@ciandt-flow/cli 2.13.0-beta.65 → 2.13.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 +155 -155
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as
|
|
3
|
-
`;try{le.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=ae.dirname(this.filePath);le.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(le.statSync(this.filePath).size>
|
|
4
|
-
`);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};});var
|
|
5
|
-
`);}};});function
|
|
2
|
+
import*as vn from'crypto';import {randomUUID,createHash}from'crypto';import*as $e from'os';import $e__default,{tmpdir,homedir,cpus}from'os';import*as ae from'path';import ae__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as le from'fs';import le__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 T from'chalk';import*as Ol from'readline';import {createInterface}from'readline';import ja from'conf';import zd,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import jw,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Qy from'jsonwebtoken';import dw from'proper-lockfile';import Lw from'ink-big-text';import Qp from'ink-spinner';import*as Kt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import VS from'unzipper';import {simpleGit,CheckRepoActions}from'simple-git';import zl from'semver';import ea from'yocto-spinner';import {Command,Option}from'commander';import {parse,stringify}from'yaml';var Gh=Object.defineProperty;var G=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Yc=(e,t)=>{for(var r in t)Gh(e,r,{get:t[r],enumerable:true});};var hr,Oe,fa,yr,po,wn,wr,ga,Zc,ha,Mt,fe,tt,Yt,fs,Sn,xn,bn,In,F=G(()=>{"use strict";hr="FLOW",Oe="flow-skills",fa="flow-cli",yr=[Oe,"flow-harness"],po="internal",wn="external",wr={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"},rule:{label:"Rule",color:"blue"},plugin:{label:"Plugin",color:"magenta"}},ga=new Set(Object.keys(wr)),Zc={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},ha=new Set(["internal","external"]),Mt={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"}},fe="flow-claude-md-setup",tt=5,Yt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,fs="https://flow.ciandt.com",Sn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,xn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",bn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,In="Must be a valid email address (e.g. name@example.com)";});var gs,Wh,Qc,mo,ya=G(()=>{"use strict";gs="aes-256-gcm",Wh=16,Qc=16,mo=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=vn.randomBytes(Wh),n=vn.createCipheriv(gs,this.key,r,{authTagLength:Qc}),o=Buffer.concat([n.update(t,"utf8"),n.final()]),s=n.getAuthTag();return {iv:r.toString("hex"),authTag:s.toString("hex"),ciphertext:o.toString("hex"),algorithm:gs}}decrypt(t){if(t.algorithm!==gs)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=vn.createDecipheriv(gs,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Qc});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function wa(e){return e.replace(Yh,"").replace(Zh,"").replace(Qh,"").replace(zh,"Bearer ***").replace(Xh,"***").replace(qh,"***").replace(/\r\n|\r|\n/g,"\\n")}var zh,Xh,qh,Yh,Zh,Qh,Sa=G(()=>{"use strict";zh=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Xh=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,qh=/[A-Za-z0-9+/]{40,}={0,2}/g,Yh=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,Zh=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Qh=/\x1b/g;});function ys(e){return e||Oe}function eu(e,t,r){return Ia(ys(r),e,t)}function xa(e,t){return ae.join($e.homedir(),Zt,"plugins","marketplaces",ys(t),"plugins","native",e)}function fo(e){return ae.join($e.homedir(),Zt,"plugins","marketplaces",ys(e),".claude-plugin","marketplace.json")}function Gr(){return ae.join($e.homedir(),Zt,"plugins","known_marketplaces.json")}function ba(e){return ae.join($e.homedir(),Zt,"plugins","marketplaces",ys(e))}function tu(){return ae.join($e.homedir(),hs,"cache","install.lock")}function ru(){return ae.join($e.homedir(),hs,"logs","flowsetup.log")}function Ia(e,t,r){return ae.join($e.homedir(),Zt,"plugins","cache",e,t,r)}function Jr(e){let t=e==="global"?$e.homedir():process.cwd();return ae.join(t,".claude","skills")}function go(e){let t=e==="global"?$e.homedir():process.cwd();return ae.join(t,".claude","skills-lock.json")}function ws(e="user"){return e==="project"?ae.join(process.cwd(),".opencode","plugins"):ae.join($e.homedir(),".config","opencode","plugins")}function nu(){return ae.join($e.homedir(),hs,"flow-catalogs.json")}function ou(){let e=process.env.FLOW_HOME??ae.join($e.homedir(),hs);return ae.join(e,"config.json")}function Ss(e="user"){return e==="project"||e==="local"?ae.join(process.cwd(),Zt,"agents"):ae.join($e.homedir(),Zt,"agents")}function va(e="user"){return e==="project"||e==="local"?ae.join(process.cwd(),Zt,"rules"):ae.join($e.homedir(),Zt,"rules")}var Zt,hs,We=G(()=>{"use strict";F();Zt=".claude",hs=".flow";});var ey,ty,xs,su=G(()=>{"use strict";We();ey=5*1024*1024,ty=3,xs=class{filePath;constructor(){this.filePath=ru(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
3
|
+
`;try{le.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=ae.dirname(this.filePath);le.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(le.statSync(this.filePath).size>ey){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);le.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=ae.dirname(this.filePath),r=ae.basename(this.filePath,".log"),n=le.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(ty))le.unlinkSync(ae.join(t,o));}catch{}}};});var bs,iu=G(()=>{"use strict";bs=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
|
|
4
|
+
`);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};});var Is,au=G(()=>{"use strict";Is=class{write(t){process.stdout.write(t.message+`
|
|
5
|
+
`);}};});function Pa(){return vs}function lu(e){return Ea.add(e),()=>{Ea.delete(e);}}var vs,Ea,Es,Ta=G(()=>{"use strict";vs=[],Ea=new Set;Es=class{write(t){vs.push(t),vs.length>100&&vs.shift();for(let r of Ea)r();}};});function ry(){let e=process.env.DEBUG;if(!e)return null;let t=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of t)if(n==="flow:*")return "all";let r=new Set;for(let n of t)n.startsWith("flow:")&&r.add(n.slice(5));return r.size>0?r:null}function Ue(e,t){if(e==="tui"){let r=ry();zr={context:e,transports:[new Es,new xs],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?zr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?zr={context:e,transports:[new bs("cli")],minLevel:"debug",debugModules:null}:zr={context:e,transports:[new Is],minLevel:"info",debugModules:null};}function cu(){return zr.transports}function uu(e,t){let{debugModules:r,minLevel:n}=zr;return zr.context==="tui"&&r&&r!=="all"?r.has(t)?En[e]>=En.debug:En[e]>=En.warn:En[e]>=En[n]}var En,zr,Ca=G(()=>{"use strict";su();iu();au();Ta();En={debug:0,info:1,warn:2,error:3},zr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function Ps(e,t,r){if(!uu(e,t))return;let n={level:e,module:t,message:wa(r),timestamp:new Date};for(let o of cu())o.write(n);}function x(e){let t=du.get(e);if(t)return t;let r={debug:n=>Ps("debug",e,n),info:n=>Ps("info",e,n),warn:n=>Ps("warn",e,n),error:n=>Ps("error",e,n)};return du.set(e,r),r}var du,pu=G(()=>{"use strict";Sa();Ca();du=new Map;});var $=G(()=>{"use strict";pu();Ca();Sa();});function ny(e){return typeof e=="object"&&e!==null&&Aa in e&&e[Aa]===true}function $a(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[Aa]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return ka.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(ny(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return ka.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return ka.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var ka,Aa,Ra=G(()=>{"use strict";$();ka=x("encryption"),Aa="__encrypted__";});var Ma,iy,gt,Pn,_a=G(()=>{"use strict";$();Ma=promisify(execFile),iy=promisify(exec),gt=x("encryption:macos-keyvault"),Pn=class{static async isAvailable(){try{let{stdout:t}=await iy("command -v security");return gt.debug(`security binary found at: ${t.trim()}`),!0}catch{return gt.debug("security binary not found in PATH"),!1}}async getSecret(t,r){try{gt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Ma("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return gt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return gt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{gt.debug(`Storing secret: service=${t}, account=${r}`),await Ma("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),gt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw gt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return gt.debug(`Deleting secret: service=${t}, account=${r}`),await Ma("security",["delete-generic-password","-a",r,"-s",t]),gt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return gt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function y(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g,"")}function z(e){process.stdout.write(T.green(` \u2713 ${y(e)}
|
|
6
6
|
`));}function I(e){process.stderr.write(T.red(` \u2717 ${y(e)}
|
|
7
7
|
`));}function b(e){process.stdout.write(T.cyan(` \u2139 ${y(e)}
|
|
8
|
-
`));}function
|
|
8
|
+
`));}function Sr(e,t){let r=t.map(a=>a.map(y)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(u=>(u[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,u)=>l.padEnd(o[u])).join(" ");process.stdout.write(`
|
|
9
9
|
`),process.stdout.write(` ${T.bold(i(e))}
|
|
10
10
|
`),process.stdout.write(` ${T.dim(s)}
|
|
11
11
|
`);for(let a of r)process.stdout.write(` ${i(a)}
|
|
12
12
|
`);process.stdout.write(`
|
|
13
|
-
`);}function
|
|
13
|
+
`);}function xr(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
14
14
|
`);}function ne(e){process.stdout.write(JSON.stringify(e)+`
|
|
15
|
-
`);}function
|
|
16
|
-
`);}function ee(e){return e instanceof Error?e.message:String(e)}function
|
|
17
|
-
${
|
|
15
|
+
`);}function Re(e){process.stderr.write(JSON.stringify(e)+`
|
|
16
|
+
`);}function ee(e){return e instanceof Error?e.message:String(e)}function _t(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var N=G(()=>{"use strict";});async function dy(e,t){let r=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],n=0,o=setInterval(()=>{process.stderr.write(`\r${r[n++%r.length]} ${e}`);},80);try{return await t()}finally{clearInterval(o),process.stderr.write("\r\x1B[2K");}}function py(e){let t=Ol.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var La,Da,uy,se,br,Oa=G(()=>{"use strict";$();N();La=promisify(execFile),Da=promisify(exec),uy=[{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"}],se=x("encryption:linux-keyvault");br=class e{static async isAvailable(){try{let{stdout:t}=await Da("command -v secret-tool");se.debug(`secret-tool found at: ${t.trim()}`);}catch{return se.debug("secret-tool binary not found in PATH"),!1}try{return await La("secret-tool",["lookup","service","__flow_connectivity_check__"]),se.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(se.debug(`Secret Service D-Bus not available: ${n}`),!1):(se.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let t of uy)try{return await Da(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;se.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let t=await e.detectPackageManager();if(!t)return se.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let r=await py(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return se.info(`Running: ${t.command}`),await dy("Installing secret-tool...",()=>Da(t.command)),e.isAvailable()}catch{return se.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(t,r){try{se.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await La("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return se.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return se.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){se.debug(`Storing secret: service=${t}, account=${r}`),se.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),se.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),se.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((o,s)=>{let i=spawn("secret-tool",["store","--label",t,"service",t,"account",r]),a="";i.stderr.on("data",l=>{a+=l.toString();}),i.stdin.end(n,"utf8"),i.on("close",l=>{l===0?(se.debug("secret-tool store succeeded"),o()):(se.error(`secret-tool store failed: code=${l}, stderr=${a.trim()}`),s(new Error(`secret-tool exited with code ${l}${a?`: ${a.trim()}`:""}`)));}),i.on("error",l=>{se.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return se.debug(`Deleting secret: service=${t}, account=${r}`),await La("secret-tool",["clear","service",t,"account",r]),se.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return se.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function Na(e,t){return `${e}:${t}`}function yo(e){return e.replace(/'/g,"''")}function Ts(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Sy(e){return `Add-Type -TypeDefinition @'
|
|
17
|
+
${Ba}
|
|
18
18
|
'@
|
|
19
|
-
[FlowCredManager]::Read('${
|
|
20
|
-
${
|
|
19
|
+
[FlowCredManager]::Read('${yo(e)}')`}function xy(e,t,r){return `Add-Type -TypeDefinition @'
|
|
20
|
+
${Ba}
|
|
21
21
|
'@
|
|
22
|
-
[FlowCredManager]::Write('${
|
|
23
|
-
${
|
|
22
|
+
[FlowCredManager]::Write('${yo(e)}', '${yo(t)}', '${yo(r)}')`}function by(e){return `Add-Type -TypeDefinition @'
|
|
23
|
+
${Ba}
|
|
24
24
|
'@
|
|
25
|
-
[FlowCredManager]::Delete('${
|
|
25
|
+
[FlowCredManager]::Delete('${yo(e)}')`}async function Cs(e){return gy("powershell.exe",e)}var gy,ht,Ua,hy,yy,wy,Ba,Tn,Fa=G(()=>{"use strict";$();gy=promisify(execFile),ht=x("encryption:windows-keyvault"),Ua=1,hy=1,yy=2,wy=3;Ba=`
|
|
26
26
|
using System;
|
|
27
27
|
using System.Runtime.InteropServices;
|
|
28
28
|
using System.Text;
|
|
@@ -58,7 +58,7 @@ public class FlowCredManager {
|
|
|
58
58
|
|
|
59
59
|
public static string Read(string target) {
|
|
60
60
|
IntPtr credPtr;
|
|
61
|
-
if (!CredRead(target, ${
|
|
61
|
+
if (!CredRead(target, ${Ua}, 0, out credPtr)) return "";
|
|
62
62
|
try {
|
|
63
63
|
var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
|
|
64
64
|
if (cred.CredentialBlobSize <= 0) return "";
|
|
@@ -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[] { ${yy}, ${wy}, ${hy} };
|
|
76
76
|
int lastErr = 0;
|
|
77
77
|
try {
|
|
78
78
|
foreach (int persist in persistLevels) {
|
|
@@ -80,7 +80,7 @@ public class FlowCredManager {
|
|
|
80
80
|
try {
|
|
81
81
|
Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
|
|
82
82
|
var cred = new CREDENTIAL();
|
|
83
|
-
cred.Type = ${
|
|
83
|
+
cred.Type = ${Ua};
|
|
84
84
|
cred.TargetName = targetPtr;
|
|
85
85
|
cred.CredentialBlobSize = bytes.Length;
|
|
86
86
|
cred.CredentialBlob = blobPtr;
|
|
@@ -98,177 +98,177 @@ public class FlowCredManager {
|
|
|
98
98
|
}
|
|
99
99
|
|
|
100
100
|
public static bool Delete(string target) {
|
|
101
|
-
return CredDelete(target, ${
|
|
101
|
+
return CredDelete(target, ${Ua}, 0);
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
|
-
`;
|
|
105
|
-
`)[0]:"unknown error";return
|
|
106
|
-
`)[0]:"unknown error";return
|
|
107
|
-
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw
|
|
108
|
-
`)[0]:"unknown error";return
|
|
104
|
+
`;Tn=class{static async isAvailable(){try{let{stdout:t}=await Cs(Ts('Write-Output "ok"')),r=t.trim()==="ok";return ht.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
|
|
105
|
+
`)[0]:"unknown error";return ht.debug(`PowerShell not available: ${r}`),!1}}async getSecret(t,r){try{let n=Na(t,r);ht.debug(`Looking up secret: target=${n}`);let o=Sy(n),{stdout:s}=await Cs(Ts(o)),i=s.trim();return ht.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
|
|
106
|
+
`)[0]:"unknown error";return ht.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=Na(t,r);ht.debug(`Storing secret: target=${o}`);let s=xy(o,n,r),{stdout:i}=await Cs(Ts(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];ht.debug(`CredWrite succeeded (persist=${u})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
|
|
107
|
+
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw ht.error(i),new Error(i,{cause:o})}}async deleteSecret(t,r){try{let n=Na(t,r);ht.debug(`Deleting secret: target=${n}`);let o=by(n),{stdout:s}=await Cs(Ts(o)),i=s.trim()==="True";return ht.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
|
|
108
|
+
`)[0]:"unknown error";return ht.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function Py(){let e=`${$e.hostname()}${$e.userInfo().username}`;return vn.scryptSync(e,vy,Iy)}function Ty(){let e=Py(),t=new mo(e),r=$a(t);return new ja({projectName:Ka,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function ks(){return As||(As=Ty()),As}var Iy,vy,Ka,Ey,As,ze,wo=G(()=>{"use strict";ya();Ra();Iy=32,vy="flow-plugins-cli-fallback",Ka="flow-plugins-cli-fallback",Ey={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)"};As=null;ze=class{warned=!1;async getSecret(t,r){return ks().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Ey[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
|
|
109
109
|
using a machine-derived key. For stronger security, ${o}.
|
|
110
|
-
`),this.warned=!0;}$s().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=$s(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return $s().path}static hasExistingData(){try{let t=new Ga({projectName:Ja});return le.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new Ga({projectName:Ja});le.rmSync(t.path,{force:!0});}catch{}Ms=null;}};});async function Wa(){if(ze.hasExistingData())return new ze;switch(process.platform){case "darwin":return await kn.isAvailable()?new kn:new ze;case "linux":return await Ir.isAvailable()?new Ir:await Ir.ensureInstalled()?new Ir:new ze;case "win32":return await An.isAvailable()?new An:new ze;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Iu=G(()=>{"use strict";Ua();Fa();Ha();bo();});var vu=G(()=>{"use strict";ba();Da();Iu();Ua();Fa();Ha();bo();});async function vr(){return Ds||(Ds=Wa()),Ds}function Os(){Ds=null;}async function te(){let t=await(await vr()).getSecret(er,za);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Er(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw Eu.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await vr()).setSecret(er,za,JSON.stringify(e));}async function Pu(){let e=await vr();await e.deleteSecret(er,za),await e.deleteSecret(er,Xa),await e.deleteSecret(er,qa);}async function Tu(){return (await vr()).getStoragePath()}async function Cu(e){await(await vr()).setSecret(er,Xa,JSON.stringify(e));}async function Us(){let t=await(await vr()).getSecret(er,Xa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ns(e){await(await vr()).setSecret(er,qa,JSON.stringify(e));}async function Rn(){let t=await(await vr()).getSecret(er,qa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Pr(){let e=await Us();return e?new Date(e.expiresAt)>new Date:false}function Dt(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,Eu.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Eu,er,za,Xa,qa,Ds,Ce=G(()=>{"use strict";vu();R();Eu=x("config:credentials"),er="flow-plugins-cli",za="credentials",Xa="token-cache",qa="user-info",Ds=null;});function $n(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Bs=G(()=>{"use strict";});function Ry(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;let n=parseInt(r[1],16),o=parseInt(r[2],16);return `${n>>8&255}.${n&255}.${o>>8&255}.${o&255}`}function Ya(e){if(ku.some(r=>r.test(e)))return true;let t=Ry(e);return !!(t&&ku.some(r=>r.test(t)))}function $y(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Ot(e,t){let r=$y(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&Ya(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var ku,Yr=G(()=>{"use strict";ku=[/^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 Ly(e){if(!Qt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function Dy(e){if(e instanceof HTTPError){let t=e.response.status;Za.debug(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&Au[r]?new Error(Au[r]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Za.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Za.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Zr(e){let t=Ot("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Ly(e.tenant);let r;try{r=await Qd.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Dy(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Er(e),await Cu({accessToken:r.access_token,expiresAt:n});let o=$n(r.access_token);await Ns({sub:o.sub,name:o.name,email:o.email});}var Za,Au,Fs=G(()=>{"use strict";Ce();Bs();Yr();R();F();Za=x("api:auth");Au={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 Ut(){if(await Pr()){let n=await Us();if(n)return n.accessToken}Ru.debug("Token expired or missing, re-authenticating...");let t=await te();if(!t)throw new Error("Not authenticated. Run: flow auth login");ze.clearFallbackFile(),Os(),await Zr(t);let r=await Us();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Ru.debug("Token refreshed successfully"),r.accessToken}var Ru,Mn=G(()=>{"use strict";Ce();Fs();bo();R();Ru=x("lib:tokenProvider");});function Kt(){return Qd.create({prefix:Ot("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Ut();e.headers.set("Authorization",`Bearer ${t}`);let r=await te();r?.tenant&&Qt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Oo=G(()=>{"use strict";Yr();Ce();Mn();F();});function Gd(e){if(!(e.source===void 0&&e.timeoutMs===void 0))return {...e.source!==void 0&&{searchParams:{source:e.source}},...e.timeoutMs!==void 0&&{timeout:e.timeoutMs}}}function Fn(e,t,r){let n=Kt(),o=Gd({source:t,timeoutMs:r});return o?n.get(e,o):n.get(e)}function Jd(e,t={}){let r=Kt(),n=Gd(t);return n?r.head(e,n):r.head(e)}async function jn(e){if(!(e instanceof HTTPError))return null;try{let t=await e.response.clone().json(),{message:r}=t;return Array.isArray(r)?r.filter(Boolean).join("; ")||null:typeof r=="string"&&r?r:null}catch{return null}}var xl=G(()=>{"use strict";Oo();});function Uo(e){if(!e||!$S.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Kn(e){return MS.test(e)}function Vn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Il(e){if(!_S.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 Hn(e,t){let r=Vn(e);Il(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function gi(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!LS.test(t)&&!DS.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var $S,MS,_S,LS,DS,Or=G(()=>{"use strict";$S=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;MS=/^[^@]+@[^@]+$/;_S=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;LS=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,DS=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Xd={};ru(Xd,{FlowApiAdapter:()=>Gn});var OS,Gn,vl=G(()=>{"use strict";Oo();xl();R();Or();OS=x("catalog.flow-api"),Gn=class{id;name;source;removable=!1;contentSource;constructor(t){this.contentSource=t,this.id=t?`flow-api:${t}`:"flow-api",this.name=t?`Flow Marketplace (${t})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await Fn("v1/plugins/catalog",this.contentSource).json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(t){let r=await jn(t);if(r)throw new Error(r,{cause:t});if(t instanceof HTTPError){let{status:n}=t.response;throw n===401||n===403?new Error("Authentication failed. Run: flow auth login",{cause:t}):new Error(`Failed to fetch plugin catalog: HTTP ${n}`,{cause:t})}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog",{cause:t}):new Error(`Failed to fetch plugin catalog: ${t.message}`,{cause:t}):t}}async fetchManifest(t){Uo(t);try{return await Fn(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await jn(r);if(n)throw new Error(n,{cause:r});if(r instanceof HTTPError){let{status:o}=r.response;throw o===404?new Error(`Plugin '${t}' not found in catalog`,{cause:r}):new Error(`Failed to fetch manifest: HTTP ${o}`,{cause:r})}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`,{cause:r}):r}}async ping(){try{return await Kt().head("v1/plugins/catalog"),OS.debug("ping ok"),!0}catch{return !1}}};});function NS(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:t})=>t.trim()||void 0).catch(()=>{})}function Yd(){return qd??=NS(),qd}var qd,Zd=G(()=>{"use strict";});var tp={};ru(tp,{GitRepoAdapter:()=>Jn});function ep(e,t){if(!BS.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var BS,Jn,El=G(()=>{"use strict";Zd();Yr();BS=/^[a-zA-Z0-9_.-]+$/;Jn=class{id;name;source;constructor(t,r,n){this.id=t,this.name=r,this.source=n;}buildRawUrl(t,r="marketplace.json"){let n=new URL(this.source),{hostname:o,pathname:s}=n;if(Ya(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return ep(a,"owner"),ep(l,"repo"),o==="github.com"?`https://raw.githubusercontent.com/${a}/${l}/${t}/${r}`:o==="bitbucket.org"?`https://bitbucket.org/${a}/${l}/raw/${t}/${r}`:o==="gitlab.com"||o.startsWith("git.")?`https://${o}/${a}/${l}/-/raw/${t}/${r}`:`https://${o}/${a}/${l}/raw/${t}/${r}`}async fetchItems(){return this._fetchFromBranch("main").catch(t=>{if(this._is404(t))return this._fetchFromBranch("master");throw t})}async _fetchFromBranch(t){let r=await this._buildHeaders();try{let s=this.buildRawUrl(t,".claude-plugin/marketplace.json"),{plugins:i}=await Qd.get(s,{headers:r}).json();return i.map(a=>({...a,catalogId:this.id,origin:a.origin??"external"}))}catch(s){if(this._is401or403(s))throw this._authError();if(!this._is404(s))throw s}let n=this.buildRawUrl(t),{plugins:o}=await Qd.get(n,{headers:r}).json();return o.map(s=>({...s,catalogId:this.id,origin:s.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let r=await Yd();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});F();var S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(Sa),origins:new Set(xa)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal:r}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(Sa)},selectedIndex:0})),toggleOriginFilter:t=>e(r=>{let{origins:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,origins:new Set([t])},selectedIndex:0}}),selectAllOrigins:()=>e(t=>({catalogFilters:{...t.catalogFilters,origins:new Set(xa)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ce();Mn();Bs();F();Yr();R();var js=x("api:metrics");function $u(){return Ot("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Mu(e,t,r){return Qd.post(e,{json:t,headers:r})}async function Uy(e){let t=await Rn();if(t)return t;let r=$n(e),n={sub:r.sub,name:r.name,email:r.email};return await Ns(n),n}async function P(e,t){let r=await Ut(),n=await Uy(r),o=await te();if(!Qt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:wa,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Mu($u(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),js.debug(`Metrics event sent: ${e}`);}catch(i){throw js.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function _u(e,t,r){try{let n=r&&Qt.test(r)?r:"unknown",o={action:e,booster:wa,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Mu($u(),o,{FlowTenant:n}),js.debug(`Anonymous metrics event sent: ${e}`);}catch(n){js.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var v={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_PLUGIN_PRUNE_COMPLETED:"CLI_PLUGIN_PRUNE_COMPLETED",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 Ny={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},wt={...Ny};function Lu(e){let t=Date.now();wt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Qr(e){wt.currentStep=e,wt.stepStart=Date.now();}function Q(){return {...wt}}function Tr(){return wt.sessionStart===0?0:Date.now()-wt.sessionStart}function en(){return wt.stepStart===0?0:Date.now()-wt.stepStart}function Du(){wt.tuiSessionStart=Date.now();}function Ou(){return wt.tuiSessionStart===0?0:Date.now()-wt.tuiSessionStart}R();var By=3e3,Fy=x("abandonment");async function Ks(e){let{currentStep:t,sessionStart:r}=Q();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Tr()};try{await Promise.race([P(v.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),By))]);}catch(o){Fy.warn(`Abandonment event failed: ${String(o)}`);}}function Uu(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}R();var jy=3e3,Ky=x("session-end");async function vo(e,t,r){let n=Ou(),s=[P(v.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Ks(e));try{await Uu(Promise.all(s).then(()=>{}),jy);}catch(i){Ky.warn(`Session end event failed: ${String(i)}`);}}var Jy=2e3;function Bu(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),vo("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Jy);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var qy=16;function Fu({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,u)=>{if(u.backspace){let c=i.current.slice(0,-1);i.current=c,r(c);}else if(l&&!u.ctrl&&!u.meta&&!u.escape&&!u.return&&!u.tab&&!u.upArrow&&!u.downArrow&&!u.leftArrow&&!u.rightArrow){let c=i.current+l;i.current=c,r(c);}},{isActive:o});let a=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(qy)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}F();function ju({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="n"||l==="N"){r("input");return}(l==="y"||l==="Y"||u.return)&&e(null);return}if(u.escape){a.current="",o(""),i(false),r("confirm");return}if(u.return){let c=a.current.trim();vn.test(c)?(i(false),e(c)):i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[t==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:En}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}F();function Ku({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[yr," \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"})]})]})}F();function Vu(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[yr," \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 nt=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));Fs();F();function nn(){return ae__default.join(Te__default.homedir(),".claude","settings.json")}function Gu(e){return `${(e&&e.trim().length>0?e.trim():ys).replace(/\/+$/,"")}/flow-litellm/`}function Ro(){let e=nn();if(!le__default.existsSync(e))return {status:"missing"};let t=le__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Hs(e){let t=nn();le__default.mkdirSync(ae__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;le__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,t);}function Ju(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function sl(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function Wu(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_BASE_URL;return typeof r=="string"&&r.length>0?r:null}var nw=3600,on=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function $o(e){let t=e.split(".");if(t.length!==3)throw new Error("Malformed JWT: invalid format");let r;try{r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed JWT: payload must be a JSON object");let n=r;if(typeof n.clientId!="string"||!n.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(n.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(n.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(n.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function ow(e){return rw.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:nw})}function Gs(e,t={}){let r=Ro();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new on;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?sl(r.settings):null,s=r.status==="ok"?Wu(r.settings):null,i=t.jwtOverride??ow(e),a=Gu(e.customUrl),l=Ju(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Js(e){Hs(e.merged);}function zu(){let e=Ro();return e.status!=="ok"?false:sl(e.settings)!==null}Ce();Ue();function sw(){let e=cu();if(!le__default.existsSync(e))return {};try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return {}}}var il=null;function iw(){return il===null&&(il=sw()),il}function Ar(){return !!iw().ENABLE_EXPERIMENTAL_BETAS}F();function uw(){return pe.filter(e=>e.platforms[process.platform]?.status==="supported")}function qu(e){let t=uw();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Ws={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=ae__default.join(Te__default.homedir(),".claude","settings.json"),r=le__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??ys),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return e.customEmail&&t.push("--custom-email",e.customEmail),[t]},onDemand:null,mode:"non-interactive"}},dw={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},pe=Ar()?[Ws,dw]:[Ws];Ce();R();var gw=x("moduleState");function Xs(){let e=process.env.FLOW_HOME??ae__default.join(Te__default.homedir(),".flow");return ae__default.join(e,"modules.json")}var hw={retries:5,minTimeout:50};async function Yu(e,t){le__default.mkdirSync(ae__default.dirname(e),{recursive:true});let r=await fw.lock(e+".lock",{realpath:false,retries:hw});try{return await t()}finally{await r();}}function Zu(){let e=Xs();if(!le__default.existsSync(e))return [];try{let t=JSON.parse(le__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(gw.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),le__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return le__default.rmSync(e,{force:true}),[]}}function sn(){return Zu()}function Qu(e){let t=Xs();le__default.mkdirSync(ae__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};le__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,t);}function ot(e){return sn().find(t=>t.alias===e)??null}async function St(e){let t=Xs();await Yu(t,async()=>{let r=Zu(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,Qu(r);});}async function an(){let e=Xs();le__default.existsSync(e)||await Yu(e,async()=>{le__default.existsSync(e)||Qu([]);});}var Sw=promisify(execFile);function Rr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Bt(e){let t=process.platform==="win32"?"where":"which";try{return await Sw(t,[e]),!0}catch{return false}}function tr(){return process.platform==="win32"?"npm.cmd":"npm"}var ed=promisify(execFile),Ln=class{type="npm";async isAvailable(){return Bt("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=Rr(t,"npm");if(!r)return null;try{let{stdout:n}=await ed(tr(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=Rr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await ed(tr(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var qs=promisify(execFile),Ew=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Ys=class{type="homebrew";async isAvailable(){return Bt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Rr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=Rr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await qs("brew",["tap",o.tap]),await qs("brew",["trust",o.tap])),await qs("brew",[r,o.formula]),{success:!0,version:await this.getVersionByFormula(o.formula)??void 0,method:"homebrew",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:s,message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}async getVersionByFormula(t){try{let{stdout:r}=await qs("brew",["list","--versions",t]),n=r.trim().match(Ew);return n?n[2]:null}catch{return null}}};var Dn=promisify(execFile),rd=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function nd(){let e=process.env.FLOW_HOME??ae__default.join(Te__default.homedir(),".flow");return ae__default.join(e,"bin")}var Zs=class{type="curl";async isAvailable(){return Bt("curl")}async install(t){let r=Date.now(),n=Rr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=ae__default.join(nd(),ae__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Dn(n,["--version"]),s=o.match(rd);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){if(!r)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${n.alias})`},durationMs:Date.now()-o};let s=ae__default.join(Te__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Dn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{le__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return le__default.chmodSync(s,448),await Dn("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{le__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=nd(),i=ae__default.join(s,ae__default.basename(n.binaryName)),a=false;try{if(le__default.mkdirSync(s,{recursive:!0}),a=!0,await Dn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return le__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}le__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await Dn(i,["--version"]),c=u.match(rd);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{le__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=ae__default.join(Te__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Dn("curl",["-L","--fail","-o",n,r]);let o=le__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=le__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{le__default.unlinkSync(n);}catch{}}}};R();var od="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(od=e.version);}catch{}var he=od;var Me=x("moduleInstaller");function jt(e){switch(e){case "npm":return new Ln;case "homebrew":return new Ys;case "curl":return new Zs}}async function Mo(e,t,r){try{await P(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){Me.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Mr(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){Me.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let d={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Mo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(a.status!=="supported"){let d={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Mo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(!a.strategies.some(d=>d.type===r)){let d={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await Mo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=jt(r),u=false;try{u=await l.isAvailable();}catch(d){Me.warn(`${r} availability check failed: ${String(d)}`);}if(!u){let d={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await Mo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await P(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:he,trigger:t});}catch(d){Me.warn(`Failed to emit install started event: ${String(d)}`);}let c;try{c=s?.forceLatest?await l.update(e,"unknown"):await l.install(e);}catch(d){let m=d instanceof Error?d.message:String(d);Me.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await St({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await P(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:t});}catch(p){Me.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await $w(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Mo(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function $w(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await te(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return Me.warn(`postInstall function threw: ${String(u)}`),{pendingCmd:null,failed:false}}}else s=o;if(s.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:s[0]??null,failed:false};let i=false;for(let a=0;a<s.length;a++){let l=s[a];if(l.length===0)continue;let u=spawnSync(l[0],l.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(u.status!==0){i=true,Me.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&Me.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&Me.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function Qs(e,t){let r=Date.now(),n=ot(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=jt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await P(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:he,trigger:"command"});}catch(a){Me.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);Me.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await St({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await P(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){Me.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await P(v.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Me.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await P(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){Me.warn(`Failed to emit update failed event: ${String(a)}`);}return i}R();var ei=x("flowAiObsSetup");async function ti(e,t){try{if(!await new Ln().isAvailable().catch(()=>!1))return ei.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Mr(Ws,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(ei.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(ei.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return ei.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}R();function sd(e){if(!(e instanceof Error))return "unknown";let t=e.message.toLowerCase();return t.includes("401")||t.includes("unauthorized")?"invalid_credentials":t.includes("403")||t.includes("forbidden")?"forbidden":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("network")||t.includes("econnrefused")||t.includes("fetch")?"network_error":"unknown"}var Mw=x("useAuthSetup");function id(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,f]=useState(null),h=useRef(0),g=useRef(false),{setCredentials:w,setJustAuthenticated:E}=nt(),_=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},D=()=>{P(v.CLI_SESSION_STARTED,{cli_version:he,os:process.platform,node_version:process.version,duration_ms:Tr(),interface:"tui"}).catch(()=>{});},C=async V=>{g.current=true;let Y={...r.current,customUrl:n.current??void 0};try{V&&Js(V),await Er(Y);}catch(J){l(J instanceof Error?J.message:"Failed to persist credentials"),_(),g.current=false;return}let{clientSecret:A,...j}=Y;w(j),E(true),D(),await ti(n.current,o.current).catch(J=>Mw.warn(`installFlowAiObs threw unexpectedly: ${String(J)}`)),ri({starterKit:j.starterKit});},$=async()=>C(),O=async V=>C(V),U=V=>{try{let Y={...r.current,customUrl:n.current??void 0};return Gs(Y,{allowOverwriteMalformed:V,jwtOverride:e.trim()})}catch(Y){return Y instanceof on?(m("malformedConfirm"),null):(l(Y instanceof Error?Y.message:"Failed to read settings.json"),m("fields"),null)}},oe=()=>{let V=U(true);V&&(f(V),O(V));},k=async()=>{let V=e.trim();if(!V){i("This field is required");return}let Y;try{Y=$o(V);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=Y,m("customUrl");},H=V=>{n.current=V,m("email");},re=V=>{o.current=V,K();},K=async()=>{let V=n.current;V&&Dt(V),c(true),l(null),h.current+=1;try{await Zr(r.current);let Y=U(!1);Y&&(f(Y),m("preview"));}catch(Y){let A=Y instanceof Error?Y.message:"Authentication failed";l(A),_u(v.CLI_AUTH_FAILED,{error_code:sd(Y),attempt:h.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:g,setJwtValue:t,setJwtError:i,cancelToFields:_,handleSubmit:k,goToEmailStep:H,handleEmailConfirm:re,commitAndProceed:O,skipJwtAndProceed:$,planPersistOverwrite:oe}}F();N();function ad(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:h}=id(),[g,w]=useState("confirm"),[E,_]=useState(""),D=useRef(""),[C,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),D.current="",_(""),$(false));},[o]),useInput((O,U)=>{if(!(n||i.current)){if(o==="preview"){U.return&&s?p(s):U.escape?f():O==="q"&&u();return}if(o==="malformedConfirm"){U.return?h():U.escape&&u();return}if(o==="customUrl"){if(g==="confirm")O==="y"||O==="Y"?w("input"):(O==="n"||O==="N"||U.return)&&d(null);else if(U.escape)D.current="",_(""),w("confirm");else if(U.return){let oe=D.current.trim();oe.length>0&&bn.test(oe)?($(false),d(oe)):oe.length>0&&$(true);}else U.backspace||U.delete?(D.current=D.current.slice(0,-1),_(D.current)):O&&!U.ctrl&&!U.meta&&(D.current=D.current+O,_(D.current),$(false));return}o!=="email"&&U.return&&c();}},{isActive:true}),o==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[yr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&g==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:E}),jsx(Text,{color:"cyan",children:"\u2588"})]}),C&&jsx(Text,{color:"red",children:In}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[yr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(ju,{onConfirm:m})]}):o==="preview"&&s?jsx(Ku,{plan:s}):o==="malformedConfirm"?jsx(Vu,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[yr," \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(Fu,{label:"JWT",value:e,onChange:O=>{a(O),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Un(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Uw,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",he]})})]})}var dd=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ie=Ar()?dd:dd.slice(0,3);function Nw(e){return ie.findIndex(t=>t.id===e)}function cl(e,t,r){let n=Nw(r.activeTab);if(t.rightArrow||t.tab){let o=ie[(n+1)%ie.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=ie[(n-1+ie.length)%ie.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:ie[n]?.focus??"list"}]:[]}var fd={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function gd({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ie.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${fd[r]} (${e})`:fd[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Xe=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function yd(){let e=S(i=>i.focus),t=Xe(i=>i.query),r=Xe(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}F();var wd=Object.keys(Sr).map((e,t)=>({key:t<3?String(t+2):String((t+5)%10),type:e,...Sr[e]})),Sd=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...nu[e]}));function xd(){let e=S(n=>n.catalogFilters),t=wd.every(n=>e.types.has(n.type)),r=Sd.every(n=>e.origins.has(n.origin));return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,flexWrap:"wrap",children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),wd.map(n=>{let o=!t&&e.types.has(n.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:r?"green":void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," All"]})]}),Sd.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}F();function bd({type:e}){let{label:t,color:r}=Sr[e];return jsx(Text,{color:r,children:t})}F();function Ed({origin:e}){return e===go?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}N();var oi=Hw.memo(function({item:t,isSelected:r}){let n=t.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:t.name}),t.type&&jsxs(Text,{children:[" ",jsx(bd,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Ed,{origin:t.origin})]}),jsxs(Text,{dimColor:true,children:[t.authorName?` \xB7 ${t.authorName}`:"",t.version?` \xB7 v${t.version}`:" \xB7 n/a"]}),t.status&&jsxs(Text,{color:n,children:[" [",t.status,"]"]}),t.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),t.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",Lt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Nn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}F();function Cd({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Nn,{message:t});let n=Math.max(0,r-Math.floor(tt/2)),o=Math.min(e.length,n+tt);o===e.length&&(n=Math.max(0,o-tt));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(oi,{item:l,isSelected:n+u===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function Rd({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}F();function Md({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(Nn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(tt/2)),u=Math.min(n.length,l+tt);u===n.length&&(l=Math.max(0,u-tt));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Rd,{label:p.label,pathHint:p.pathHint},p.key):jsx(oi,{item:p.item,isSelected:p.itemIndex===r},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var Zw={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Qw({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(yd,{}),jsx(xd,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Zw[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Md,{groups:n,emptyMessage:r}):jsx(Cd,{items:e,emptyMessage:r})]})}function _d({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=S(l=>l.activeTab),s=S(l=>l.focus);return useInput(l=>{l==="a"&&e.length>0&&n?.();},{isActive:o==="updates"&&s==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Qw,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var rS={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 si(){let e=S(r=>r.focus),t=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[rS[e],t?" | Ctrl+D: debug log":""]})})}N();function Ld({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function ii({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(rm$1,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Lr(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Nd=20;function ai(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Nd),s="\u2588".repeat(o)+"\u2591".repeat(Nd-o),i=`${Lr(e)} / ${Lr(t)}`;return {bar:s,percent:n,label:i}}function li({received:e,total:t}){let{bar:r,percent:n,label:o}=ai(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function ci({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function st({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}F();var Sl=Object.entries(_t),Kd=[...Sl.map(([,e])=>e.actionLabel),"Cancel"],Vd=Object.fromEntries(Sl.map(([,e])=>[e.actionLabel,e.description]));function Hd(e){let t=Sl.find(([,r])=>r.actionLabel===e);return t?t[0]:null}R();var yS=x("provider.registry"),wS=3e4,di=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+wS}),n}async getAvailableProviders(t){let r=[...this.adapters.values()].filter(o=>t in o.installers),n=await Promise.allSettled(r.map(o=>this.checkAvailability(o)));return n.forEach((o,s)=>{o.status==="rejected"&&yS.warn(`Provider "${r[s].id}" isAvailable() threw: ${String(o.reason)}`);}),r.filter((o,s)=>{let i=n[s];return i.status==="fulfilled"&&i.value===true})}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var SS={user:"global",project:"project",local:"local"};function pi(e){return e?SS[e]:"global"}var qe=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},Dr=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};Oo();xl();R();var IS=x("catalog.registry"),mi=class{adapters=new Map;register(t){this.adapters.set(t.id,t);}unregister(t){this.adapters.delete(t);}async fetchAllWithErrors(){let t=this.listAdapters(),r=await Promise.allSettled(t.map(s=>s.fetchItems())),n=[],o=[];for(let s=0;s<r.length;s++){let i=r[s],a=t[s];if(i.status==="fulfilled")n.push(...i.value);else {let l=String(i.reason);IS.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};Ue();var RS={retries:5,minTimeout:50};async function bl(e,t){mkdirSync(dirname(e),{recursive:true});let r=await fw.lock(e+".lock",{realpath:false,retries:RS});try{return await t()}finally{await r();}}var fi=class{filePath;constructor(t){this.filePath=t??lu();}async read(){try{let t=await readFile(this.filePath,"utf-8");return JSON.parse(t).catalogs??[]}catch(t){if(t.code==="ENOENT")return [];throw t}}async write(t){let r=dirname(this.filePath);await mkdir(r,{recursive:true});let n=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(n,JSON.stringify({catalogs:t},null,2),"utf-8"),await rename(n,this.filePath);}async add(t){await bl(this.filePath,async()=>{let r=await this.read();if(r.some(o=>o.id===t.id))return;let n={...t,lastUpdated:t.lastUpdated??new Date().toISOString()};await this.write([...r,n]);});}async remove(t){if(t==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await bl(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await bl(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};vl();var ye=new mi,nr=new fi,FS=["flow-harness"];function jS(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?FS:e.split(",").map(t=>t.trim()).filter(Boolean)}ye.register(new Gn);for(let e of jS())ye.register(new Gn(e));var rp=false;async function np(){if(rp)return;rp=true;let e=await nr.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(El(),tp));for(let r of e)ye.register(new t(r.id,r.name,r.source));}Or();function op(e){if(e===void 0||!Number.isFinite(e)||e<=0)return 3e4;let t=e/131072*1e3;return Math.min(6e5,Math.max(3e4,Math.ceil(t)))}R();var VS=x("api:actions"),sp=2;async function or(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(vl(),Xd));return new t(e).fetchItems()}return ye.fetchAll()}async function ip(){return ye.fetchAllWithErrors()}async function Wn(e,t){Uo(e);try{return await Fn(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await jn(r);throw n?new Error(n,{cause:r}):r instanceof Error?r.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`,{cause:r}):r.message.includes("timeout")?new Error("Download timed out after 30s",{cause:r}):new Error(`Failed to fetch plugin manifest: ${r.message}`,{cause:r}):r}}async function HS(e,t){try{let n=(await Jd(`v1/plugins/${e}/archive`,{source:t,timeoutMs:3e4})).headers.get("x-archive-size"),o=n?Number(n):NaN;return Number.isFinite(o)&&o>0?o:void 0}catch(r){VS.debug(`[${e}] Archive size probe failed, using default timeout: ${String(r)}`);return}}async function ap(e,t,r){Uo(e);try{let n=await HS(e,r),o=op(n),s=await Fn(`v1/plugins/${e}/archive`,r,o),i=s.headers.get("x-archive-size"),a=i?Number(i):NaN,l=Number.isFinite(a)&&a>0?a:0,u=l>0,c=s.body;if(!c)throw new Error("Failed to download plugin: response has no body");let d=c.getReader(),m=[],p=0;for(;;){let{done:f,value:h}=await d.read();if(f)break;if(p+=h.byteLength,u&&p>l*sp)throw await d.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${l*sp}`);m.push(h),u&&t?.(p,l);}return Buffer.concat(m)}catch(n){if(n instanceof Error&&n.message.includes("Download exceeded expected size"))throw n;let o=await jn(n);throw o?new Error(o,{cause:n}):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`,{cause:n}):n}}async function hi(){try{let{profiles:e}=await Kt().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",{cause:e}):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits",{cause:e}):new Error(`Failed to fetch starter kits: ${e.message}`,{cause:e}):e}}Ue();Ue();async function lp(e,t){let r=ae.resolve(t);await Vt.mkdir(r,{recursive:true});let n=ae.join(ae.dirname(r),`${randomUUID()}.zip`);try{await Vt.writeFile(n,e);let o=await JS.Open.file(n),s=ae.normalize(r+ae.sep);for(let i of o.files){if((i.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${i.path}" is a symbolic link and was rejected`);let l=ae.resolve(r,i.path);if(process.platform==="win32"&&l.length>=260)throw new Error(`Path too long: "${l}" (${l.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!l.startsWith(s)&&l!==r)throw new Error(`Zip Slip detected: entry "${i.path}" would escape target directory`)}await o.extract({path:r});try{let i=realpathSync(r);if(!i.startsWith(ae.resolve(ae.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Vt.unlink(n);}catch{}}}async function Pl(e){await Vt.rm(e,{recursive:true,force:true});}async function sr(){let e=iu();await Vt.mkdir(ae.dirname(e),{recursive:true});try{await Vt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await fw.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}Ue();F();R();var qS=x("marketplace-registry");function YS(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||Oe,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function up(e){let t=yo(e);if(!le__default.existsSync(t))return null;try{return JSON.parse(le__default.readFileSync(t,"utf-8"))}catch{return null}}function ZS(e){let t=up(e);if(t)return t;let r=YS(e),n=yo(e);return le__default.mkdirSync(ae__default.dirname(n),{recursive:true}),kl(r,e),r}function kl(e,t){let r=yo(t),n=`${r}.${randomUUID()}.tmp`;le__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(n,r);}function QS(e){let t=e||Oe,r=Wr(),n={};try{le__default.existsSync(r)&&(n=JSON.parse(le__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:Pa(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;le__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(o,r);}async function Tl(e,t){let r=Pa(e),n=ae__default.relative(r,yo(e));try{let o=simpleGit({baseDir:r,timeout:{block:1e4}});if((await o.status()).files.length===0)return;await o.add([n,"plugins/native/"]),await o.commit(t);}catch(o){qS.debug(`Could not commit marketplace clone changes (non-fatal): ${String(o)}`);}}async function dp(e,t,r){it(e.name),QS(r);let n=Ea(e.name,r);le__default.mkdirSync(ae__default.dirname(n),{recursive:true});try{le__default.lstatSync(n),le__default.rmSync(n,{recursive:!0,force:!0});}catch{}le__default.cpSync(t,n,{recursive:true,dereference:true});let o=ZS(r);o.plugins.some(i=>i.name===e.name)||(o.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),kl(o,r)),await Tl(r,`chore: register ${e.name}@${e.version}`);}async function pp(e,t){it(e);let r=Ea(e,t);try{le__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=up(t);if(!n){await Tl(t,`chore: unregister ${e}`);return}let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&kl(n,t),await Tl(t,`chore: unregister ${e}`);}N();R();var tx=x("mcpConfigReader"),rx=500,nx=512;function ox(){return ae__default.join(Te__default.homedir(),".claude.json")}function sx(){return ae__default.join(process.cwd(),".mcp.json")}function fp(e){if(!le__default.existsSync(e))return null;try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return tx.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function No(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Al(e){if(!No(e))return {};let t=e.mcpServers;return No(t)?t:{}}function Rl(e,t){return Object.keys(e).slice(0,rx).map(n=>({name:y(n.slice(0,nx)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function hp(){let e=[],t=ox(),r=fp(t);if(No(r)){let a=r,l=Al(a);e.push(...Rl(l,"user"));let u=process.cwd();if(No(a.projects)){let c=a.projects[u];if(No(c)){let d=Al(c);e.push(...Rl(d,"local"));}}}let n=sx(),o=fp(n),s=Al(o);e.push(...Rl(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}R();F();function Bo(e,t){let r=join(e,".gitignore");if(!existsSync(r)){writeFileSync(r,`${t}
|
|
110
|
+
`),this.warned=!0;}ks().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=ks(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return ks().path}static hasExistingData(){try{let t=new ja({projectName:Ka});return le.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new ja({projectName:Ka});le.rmSync(t.path,{force:!0});}catch{}As=null;}};});async function Va(){if(ze.hasExistingData())return new ze;switch(process.platform){case "darwin":return await Pn.isAvailable()?new Pn:new ze;case "linux":return await br.isAvailable()?new br:await br.ensureInstalled()?new br:new ze;case "win32":return await Tn.isAvailable()?new Tn:new ze;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var yu=G(()=>{"use strict";_a();Oa();Fa();wo();});var wu=G(()=>{"use strict";ya();Ra();yu();_a();Oa();Fa();wo();});async function Ir(){return Ms||(Ms=Va()),Ms}function _s(){Ms=null;}async function te(){let t=await(await Ir()).getSecret(Qt,Ha);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function vr(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw Su.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Ir()).setSecret(Qt,Ha,JSON.stringify(e));}async function xu(){let e=await Ir();await e.deleteSecret(Qt,Ha),await e.deleteSecret(Qt,Ga),await e.deleteSecret(Qt,Ja);}async function bu(){return (await Ir()).getStoragePath()}async function Iu(e){await(await Ir()).setSecret(Qt,Ga,JSON.stringify(e));}async function Ls(){let t=await(await Ir()).getSecret(Qt,Ga);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ds(e){await(await Ir()).setSecret(Qt,Ja,JSON.stringify(e));}async function Cn(){let t=await(await Ir()).getSecret(Qt,Ja);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Er(){let e=await Ls();return e?new Date(e.expiresAt)>new Date:false}function Lt(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,Su.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Su,Qt,Ha,Ga,Ja,Ms,Te=G(()=>{"use strict";wu();$();Su=x("config:credentials"),Qt="flow-plugins-cli",Ha="credentials",Ga="token-cache",Ja="user-info",Ms=null;});function kn(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Os=G(()=>{"use strict";});function Cy(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;let n=parseInt(r[1],16),o=parseInt(r[2],16);return `${n>>8&255}.${n&255}.${o>>8&255}.${o&255}`}function Wa(e){if(vu.some(r=>r.test(e)))return true;let t=Cy(e);return !!(t&&vu.some(r=>r.test(t)))}function ky(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Dt(e,t){let r=ky(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&Wa(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var vu,Xr=G(()=>{"use strict";vu=[/^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 Ry(e){if(!Yt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function My(e){if(e instanceof HTTPError){let t=e.response.status;za.debug(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&Eu[r]?new Error(Eu[r]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(za.debug(`Non-HTTP error during authentication: ${e.message}`),e):(za.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function qr(e){let t=Dt("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Ry(e.tenant);let r;try{r=await zd.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await My(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await vr(e),await Iu({accessToken:r.access_token,expiresAt:n});let o=kn(r.access_token);await Ds({sub:o.sub,name:o.name,email:o.email});}var za,Eu,Us=G(()=>{"use strict";Te();Os();Xr();$();F();za=x("api:auth");Eu={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 Ot(){if(await Er()){let n=await Ls();if(n)return n.accessToken}Pu.debug("Token expired or missing, re-authenticating...");let t=await te();if(!t)throw new Error("Not authenticated. Run: flow auth login");ze.clearFallbackFile(),_s(),await qr(t);let r=await Ls();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Pu.debug("Token refreshed successfully"),r.accessToken}var Pu,An=G(()=>{"use strict";Te();Us();wo();$();Pu=x("lib:tokenProvider");});function jt(){return zd.create({prefix:Dt("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Ot();e.headers.set("Authorization",`Bearer ${t}`);let r=await te();r?.tenant&&Yt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var _o=G(()=>{"use strict";Xr();Te();An();F();});function Fd(e){if(!(e.source===void 0&&e.timeoutMs===void 0))return {...e.source!==void 0&&{searchParams:{source:e.source}},...e.timeoutMs!==void 0&&{timeout:e.timeoutMs}}}function Un(e,t,r){let n=jt(),o=Fd({source:t,timeoutMs:r});return o?n.get(e,o):n.get(e)}function jd(e,t={}){let r=jt(),n=Fd(t);return n?r.head(e,n):r.head(e)}async function Nn(e){if(!(e instanceof HTTPError))return null;try{let t=await e.response.clone().json(),{message:r}=t;return Array.isArray(r)?r.filter(Boolean).join("; ")||null:typeof r=="string"&&r?r:null}catch{return null}}var hl=G(()=>{"use strict";_o();});function Lo(e){if(!e||!kS.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Bn(e){return AS.test(e)}function Fn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function wl(e){if(!$S.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 jn(e,t){let r=Fn(e);wl(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function pi(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!RS.test(t)&&!MS.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var kS,AS,$S,RS,MS,Dr=G(()=>{"use strict";kS=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;AS=/^[^@]+@[^@]+$/;$S=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;RS=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,MS=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Hd={};Yc(Hd,{FlowApiAdapter:()=>Kn});var _S,Kn,Sl=G(()=>{"use strict";_o();hl();$();Dr();_S=x("catalog.flow-api"),Kn=class{id;name;source;removable=!1;contentSource;constructor(t){this.contentSource=t,this.id=t?`flow-api:${t}`:"flow-api",this.name=t?`Flow Marketplace (${t})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await Un("v1/plugins/catalog",this.contentSource).json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(t){let r=await Nn(t);if(r)throw new Error(r,{cause:t});if(t instanceof HTTPError){let{status:n}=t.response;throw n===401||n===403?new Error("Authentication failed. Run: flow auth login",{cause:t}):new Error(`Failed to fetch plugin catalog: HTTP ${n}`,{cause:t})}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog",{cause:t}):new Error(`Failed to fetch plugin catalog: ${t.message}`,{cause:t}):t}}async fetchManifest(t){Lo(t);try{return await Un(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await Nn(r);if(n)throw new Error(n,{cause:r});if(r instanceof HTTPError){let{status:o}=r.response;throw o===404?new Error(`Plugin '${t}' not found in catalog`,{cause:r}):new Error(`Failed to fetch manifest: HTTP ${o}`,{cause:r})}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`,{cause:r}):r}}async ping(){try{return await jt().head("v1/plugins/catalog"),_S.debug("ping ok"),!0}catch{return !1}}};});function DS(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:t})=>t.trim()||void 0).catch(()=>{})}function Jd(){return Gd??=DS(),Gd}var Gd,Wd=G(()=>{"use strict";});var qd={};Yc(qd,{GitRepoAdapter:()=>Vn});function Xd(e,t){if(!OS.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var OS,Vn,xl=G(()=>{"use strict";Wd();Xr();OS=/^[a-zA-Z0-9_.-]+$/;Vn=class{id;name;source;constructor(t,r,n){this.id=t,this.name=r,this.source=n;}buildRawUrl(t,r="marketplace.json"){let n=new URL(this.source),{hostname:o,pathname:s}=n;if(Wa(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return Xd(a,"owner"),Xd(l,"repo"),o==="github.com"?`https://raw.githubusercontent.com/${a}/${l}/${t}/${r}`:o==="bitbucket.org"?`https://bitbucket.org/${a}/${l}/raw/${t}/${r}`:o==="gitlab.com"||o.startsWith("git.")?`https://${o}/${a}/${l}/-/raw/${t}/${r}`:`https://${o}/${a}/${l}/raw/${t}/${r}`}async fetchItems(){return this._fetchFromBranch("main").catch(t=>{if(this._is404(t))return this._fetchFromBranch("master");throw t})}async _fetchFromBranch(t){let r=await this._buildHeaders();try{let s=this.buildRawUrl(t,".claude-plugin/marketplace.json"),{plugins:i}=await zd.get(s,{headers:r}).json();return i.map(a=>({...a,catalogId:this.id,origin:a.origin??"external"}))}catch(s){if(this._is401or403(s))throw this._authError();if(!this._is404(s))throw s}let n=this.buildRawUrl(t),{plugins:o}=await zd.get(n,{headers:r}).json();return o.map(s=>({...s,catalogId:this.id,origin:s.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let r=await Jd();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});F();var S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(ga),origins:new Set(ha)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal:r}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(ga)},selectedIndex:0})),toggleOriginFilter:t=>e(r=>{let{origins:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,origins:new Set([t])},selectedIndex:0}}),selectAllOrigins:()=>e(t=>({catalogFilters:{...t.catalogFilters,origins:new Set(ha)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Te();An();Os();F();Xr();$();var Ns=x("api:metrics");function Tu(){return Dt("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Cu(e,t,r){return zd.post(e,{json:t,headers:r})}async function Ly(e){let t=await Cn();if(t)return t;let r=kn(e),n={sub:r.sub,name:r.name,email:r.email};return await Ds(n),n}async function P(e,t){let r=await Ot(),n=await Ly(r),o=await te();if(!Yt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:fa,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Cu(Tu(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Ns.debug(`Metrics event sent: ${e}`);}catch(i){throw Ns.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function ku(e,t,r){try{let n=r&&Yt.test(r)?r:"unknown",o={action:e,booster:fa,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Cu(Tu(),o,{FlowTenant:n}),Ns.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Ns.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var v={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_PLUGIN_PRUNE_COMPLETED:"CLI_PLUGIN_PRUNE_COMPLETED",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 Dy={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},yt={...Dy};function Au(e){let t=Date.now();yt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Yr(e){yt.currentStep=e,yt.stepStart=Date.now();}function Q(){return {...yt}}function Pr(){return yt.sessionStart===0?0:Date.now()-yt.sessionStart}function Zr(){return yt.stepStart===0?0:Date.now()-yt.stepStart}function $u(){yt.tuiSessionStart=Date.now();}function Ru(){return yt.tuiSessionStart===0?0:Date.now()-yt.tuiSessionStart}$();var Oy=3e3,Uy=x("abandonment");async function Bs(e){let{currentStep:t,sessionStart:r}=Q();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Pr()};try{await Promise.race([P(v.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Oy))]);}catch(o){Uy.warn(`Abandonment event failed: ${String(o)}`);}}function Mu(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}$();var Ny=3e3,By=x("session-end");async function xo(e,t,r){let n=Ru(),s=[P(v.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Bs(e));try{await Mu(Promise.all(s).then(()=>{}),Ny);}catch(i){By.warn(`Session end event failed: ${String(i)}`);}}var Vy=2e3;function Lu(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),xo("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Vy);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Wy=16;function Du({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,u)=>{if(u.backspace){let c=i.current.slice(0,-1);i.current=c,r(c);}else if(l&&!u.ctrl&&!u.meta&&!u.escape&&!u.return&&!u.tab&&!u.upArrow&&!u.downArrow&&!u.leftArrow&&!u.rightArrow){let c=i.current+l;i.current=c,r(c);}},{isActive:o});let a=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(Wy)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}F();function Ou({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="n"||l==="N"){r("input");return}(l==="y"||l==="Y"||u.return)&&e(null);return}if(u.escape){a.current="",o(""),i(false),r("confirm");return}if(u.return){let c=a.current.trim();bn.test(c)?(i(false),e(c)):i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[t==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:In}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}F();function Uu({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[hr," \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"})]})]})}F();function Nu(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[hr," \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 nt=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));Us();F();function tn(){return ae__default.join($e__default.homedir(),".claude","settings.json")}function Fu(e){return `${(e&&e.trim().length>0?e.trim():fs).replace(/\/+$/,"")}/flow-litellm/`}function Co(){let e=tn();if(!le__default.existsSync(e))return {status:"missing"};let t=le__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function js(e){let t=tn();le__default.mkdirSync(ae__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;le__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,t);}function ju(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function tl(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function Ku(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_BASE_URL;return typeof r=="string"&&r.length>0?r:null}var ew=3600,rn=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function ko(e){let t=e.split(".");if(t.length!==3)throw new Error("Malformed JWT: invalid format");let r;try{r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed JWT: payload must be a JSON object");let n=r;if(typeof n.clientId!="string"||!n.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(n.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(n.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(n.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function tw(e){return Qy.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:ew})}function Ks(e,t={}){let r=Co();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new rn;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?tl(r.settings):null,s=r.status==="ok"?Ku(r.settings):null,i=t.jwtOverride??tw(e),a=Fu(e.customUrl),l=ju(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Vs(e){js(e.merged);}function Vu(){let e=Co();return e.status!=="ok"?false:tl(e.settings)!==null}Te();We();function rw(){let e=ou();if(!le__default.existsSync(e))return {};try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return {}}}var rl=null;function nw(){return rl===null&&(rl=rw()),rl}function kr(){return !!nw().ENABLE_EXPERIMENTAL_BETAS}F();function aw(){return de.filter(e=>e.platforms[process.platform]?.status==="supported")}function Gu(e){let t=aw();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Hs={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=ae__default.join($e__default.homedir(),".claude","settings.json"),r=le__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??fs),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return e.customEmail&&t.push("--custom-email",e.customEmail),[t]},onDemand:null,mode:"non-interactive"}},lw={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},de=kr()?[Hs,lw]:[Hs];Te();$();var pw=x("moduleState");function Js(){let e=process.env.FLOW_HOME??ae__default.join($e__default.homedir(),".flow");return ae__default.join(e,"modules.json")}var mw={retries:5,minTimeout:50};async function Ju(e,t){le__default.mkdirSync(ae__default.dirname(e),{recursive:true});let r=await dw.lock(e+".lock",{realpath:false,retries:mw});try{return await t()}finally{await r();}}function Wu(){let e=Js();if(!le__default.existsSync(e))return [];try{let t=JSON.parse(le__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(pw.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),le__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return le__default.rmSync(e,{force:true}),[]}}function nn(){return Wu()}function zu(e){let t=Js();le__default.mkdirSync(ae__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};le__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,t);}function ot(e){return nn().find(t=>t.alias===e)??null}async function wt(e){let t=Js();await Ju(t,async()=>{let r=Wu(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,zu(r);});}async function on(){let e=Js();le__default.existsSync(e)||await Ju(e,async()=>{le__default.existsSync(e)||zu([]);});}var hw=promisify(execFile);function Ar(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Nt(e){let t=process.platform==="win32"?"where":"which";try{return await hw(t,[e]),!0}catch{return false}}function er(){return process.platform==="win32"?"npm.cmd":"npm"}var Xu=promisify(execFile),Rn=class{type="npm";async isAvailable(){return Nt("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=Ar(t,"npm");if(!r)return null;try{let{stdout:n}=await Xu(er(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=Ar(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await Xu(er(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var Ws=promisify(execFile),bw=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,zs=class{type="homebrew";async isAvailable(){return Nt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Ar(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=Ar(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await Ws("brew",["tap",o.tap]),await Ws("brew",["trust",o.tap])),await Ws("brew",[r,o.formula]),{success:!0,version:await this.getVersionByFormula(o.formula)??void 0,method:"homebrew",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:s,message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}async getVersionByFormula(t){try{let{stdout:r}=await Ws("brew",["list","--versions",t]),n=r.trim().match(bw);return n?n[2]:null}catch{return null}}};var Mn=promisify(execFile),Yu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Zu(){let e=process.env.FLOW_HOME??ae__default.join($e__default.homedir(),".flow");return ae__default.join(e,"bin")}var Xs=class{type="curl";async isAvailable(){return Nt("curl")}async install(t){let r=Date.now(),n=Ar(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=ae__default.join(Zu(),ae__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Mn(n,["--version"]),s=o.match(Yu);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){if(!r)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${n.alias})`},durationMs:Date.now()-o};let s=ae__default.join($e__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Mn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{le__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return le__default.chmodSync(s,448),await Mn("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{le__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=Zu(),i=ae__default.join(s,ae__default.basename(n.binaryName)),a=false;try{if(le__default.mkdirSync(s,{recursive:!0}),a=!0,await Mn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return le__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}le__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await Mn(i,["--version"]),c=u.match(Yu);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{le__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=ae__default.join($e__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Mn("curl",["-L","--fail","-o",n,r]);let o=le__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=le__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{le__default.unlinkSync(n);}catch{}}}};$();var Qu="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Qu=e.version);}catch{}var ge=Qu;var Me=x("moduleInstaller");function Ft(e){switch(e){case "npm":return new Rn;case "homebrew":return new zs;case "curl":return new Xs}}async function Ao(e,t,r){try{await P(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){Me.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Rr(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){Me.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let d={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Ao(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(a.status!=="supported"){let d={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Ao(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(!a.strategies.some(d=>d.type===r)){let d={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await Ao(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=Ft(r),u=false;try{u=await l.isAvailable();}catch(d){Me.warn(`${r} availability check failed: ${String(d)}`);}if(!u){let d={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await Ao(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await P(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ge,trigger:t});}catch(d){Me.warn(`Failed to emit install started event: ${String(d)}`);}let c;try{c=s?.forceLatest?await l.update(e,"unknown"):await l.install(e);}catch(d){let m=d instanceof Error?d.message:String(d);Me.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await wt({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await P(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:t});}catch(p){Me.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await kw(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Ao(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function kw(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await te(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return Me.warn(`postInstall function threw: ${String(u)}`),{pendingCmd:null,failed:false}}}else s=o;if(s.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:s[0]??null,failed:false};let i=false;for(let a=0;a<s.length;a++){let l=s[a];if(l.length===0)continue;let u=spawnSync(l[0],l.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(u.status!==0){i=true,Me.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&Me.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&Me.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function qs(e,t){let r=Date.now(),n=ot(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Ft(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await P(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ge,trigger:"command"});}catch(a){Me.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);Me.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await wt({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await P(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){Me.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await P(v.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Me.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await P(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){Me.warn(`Failed to emit update failed event: ${String(a)}`);}return i}$();var Ys=x("flowAiObsSetup");async function Zs(e,t){try{if(!await new Rn().isAvailable().catch(()=>!1))return Ys.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Rr(Hs,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(Ys.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Ys.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return Ys.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}$();function ed(e){if(!(e instanceof Error))return "unknown";let t=e.message.toLowerCase();return t.includes("401")||t.includes("unauthorized")?"invalid_credentials":t.includes("403")||t.includes("forbidden")?"forbidden":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("network")||t.includes("econnrefused")||t.includes("fetch")?"network_error":"unknown"}var Aw=x("useAuthSetup");function td(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,g]=useState(null),h=useRef(0),f=useRef(false),{setCredentials:w,setJustAuthenticated:E}=nt(),_=()=>{m("fields"),g(null),t(""),r.current=null,n.current=null,o.current=null;},D=()=>{P(v.CLI_SESSION_STARTED,{cli_version:ge,os:process.platform,node_version:process.version,duration_ms:Pr(),interface:"tui"}).catch(()=>{});},C=async V=>{f.current=true;let Y={...r.current,customUrl:n.current??void 0};try{V&&Vs(V),await vr(Y);}catch(J){l(J instanceof Error?J.message:"Failed to persist credentials"),_(),f.current=false;return}let{clientSecret:A,...j}=Y;w(j),E(true),D(),await Zs(n.current,o.current).catch(J=>Aw.warn(`installFlowAiObs threw unexpectedly: ${String(J)}`)),Qs({starterKit:j.starterKit});},R=async()=>C(),O=async V=>C(V),U=V=>{try{let Y={...r.current,customUrl:n.current??void 0};return Ks(Y,{allowOverwriteMalformed:V,jwtOverride:e.trim()})}catch(Y){return Y instanceof rn?(m("malformedConfirm"),null):(l(Y instanceof Error?Y.message:"Failed to read settings.json"),m("fields"),null)}},oe=()=>{let V=U(true);V&&(g(V),O(V));},k=async()=>{let V=e.trim();if(!V){i("This field is required");return}let Y;try{Y=ko(V);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=Y,m("customUrl");},H=V=>{n.current=V,m("email");},re=V=>{o.current=V,K();},K=async()=>{let V=n.current;V&&Lt(V),c(true),l(null),h.current+=1;try{await qr(r.current);let Y=U(!1);Y&&(g(Y),m("preview"));}catch(Y){let A=Y instanceof Error?Y.message:"Authentication failed";l(A),ku(v.CLI_AUTH_FAILED,{error_code:ed(Y),attempt:h.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:f,setJwtValue:t,setJwtError:i,cancelToFields:_,handleSubmit:k,goToEmailStep:H,handleEmailConfirm:re,commitAndProceed:O,skipJwtAndProceed:R,planPersistOverwrite:oe}}F();N();function rd(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:g,planPersistOverwrite:h}=td(),[f,w]=useState("confirm"),[E,_]=useState(""),D=useRef(""),[C,R]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),D.current="",_(""),R(false));},[o]),useInput((O,U)=>{if(!(n||i.current)){if(o==="preview"){U.return&&s?p(s):U.escape?g():O==="q"&&u();return}if(o==="malformedConfirm"){U.return?h():U.escape&&u();return}if(o==="customUrl"){if(f==="confirm")O==="y"||O==="Y"?w("input"):(O==="n"||O==="N"||U.return)&&d(null);else if(U.escape)D.current="",_(""),w("confirm");else if(U.return){let oe=D.current.trim();oe.length>0&&Sn.test(oe)?(R(false),d(oe)):oe.length>0&&R(true);}else U.backspace||U.delete?(D.current=D.current.slice(0,-1),_(D.current)):O&&!U.ctrl&&!U.meta&&(D.current=D.current+O,_(D.current),R(false));return}o!=="email"&&U.return&&c();}},{isActive:true}),o==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[hr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&f==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&f==="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:E}),jsx(Text,{color:"cyan",children:"\u2588"})]}),C&&jsx(Text,{color:"red",children:xn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[hr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Ou,{onConfirm:m})]}):o==="preview"&&s?jsx(Uu,{plan:s}):o==="malformedConfirm"?jsx(Nu,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[hr," \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(Du,{label:"JWT",value:e,onChange:O=>{a(O),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Ln(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Lw,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ge]})})]})}var id=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ie=kr()?id:id.slice(0,3);function Dw(e){return ie.findIndex(t=>t.id===e)}function sl(e,t,r){let n=Dw(r.activeTab);if(t.rightArrow||t.tab){let o=ie[(n+1)%ie.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=ie[(n-1+ie.length)%ie.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:ie[n]?.focus??"list"}]:[]}var cd={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function ud({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ie.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${cd[r]} (${e})`:cd[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Xe=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function pd(){let e=S(i=>i.focus),t=Xe(i=>i.query),r=Xe(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}F();var md=Object.keys(wr).map((e,t)=>({key:t<3?String(t+2):String((t+5)%10),type:e,...wr[e]})),fd=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...Zc[e]}));function gd(){let e=S(n=>n.catalogFilters),t=md.every(n=>e.types.has(n.type)),r=fd.every(n=>e.origins.has(n.origin));return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,flexWrap:"wrap",children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),md.map(n=>{let o=!t&&e.types.has(n.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:r?"green":void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," All"]})]}),fd.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}F();function hd({type:e}){let{label:t,color:r}=wr[e];return jsx(Text,{color:r,children:t})}F();function Sd({origin:e}){return e===po?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}N();var ti=jw.memo(function({item:t,isSelected:r}){let n=t.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:t.name}),t.type&&jsxs(Text,{children:[" ",jsx(hd,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Sd,{origin:t.origin})]}),jsxs(Text,{dimColor:true,children:[t.authorName?` \xB7 ${t.authorName}`:"",t.version?` \xB7 v${t.version}`:" \xB7 n/a"]}),t.status&&jsxs(Text,{color:n,children:[" [",t.status,"]"]}),t.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),t.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",_t(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Dn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}F();function Id({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Dn,{message:t});let n=Math.max(0,r-Math.floor(tt/2)),o=Math.min(e.length,n+tt);o===e.length&&(n=Math.max(0,o-tt));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(ti,{item:l,isSelected:n+u===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function Pd({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}F();function Cd({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let g of p.items)n.push({kind:"item",item:g,itemIndex:o,key:`i-${p.scope}-${g.name}-${g.marketplace??""}`}),o++;}if(o===0)return jsx(Dn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(tt/2)),u=Math.min(n.length,l+tt);u===n.length&&(l=Math.max(0,u-tt));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Pd,{label:p.label,pathHint:p.pathHint},p.key):jsx(ti,{item:p.item,isSelected:p.itemIndex===r},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var Xw={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function qw({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(pd,{}),jsx(gd,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Xw[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Cd,{groups:n,emptyMessage:r}):jsx(Id,{items:e,emptyMessage:r})]})}function kd({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=S(l=>l.activeTab),s=S(l=>l.focus);return useInput(l=>{l==="a"&&e.length>0&&n?.();},{isActive:o==="updates"&&s==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(qw,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var Qw={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 ri(){let e=S(r=>r.focus),t=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[Qw[e],t?" | Ctrl+D: debug log":""]})})}N();function Ad({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function ni({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Qp,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function _r(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var _d=20;function oi(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*_d),s="\u2588".repeat(o)+"\u2591".repeat(_d-o),i=`${_r(e)} / ${_r(t)}`;return {bar:s,percent:n,label:i}}function si({received:e,total:t}){let{bar:r,percent:n,label:o}=oi(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function ii({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function st({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}F();var gl=Object.entries(Mt),Ud=[...gl.map(([,e])=>e.actionLabel),"Cancel"],Nd=Object.fromEntries(gl.map(([,e])=>[e.actionLabel,e.description]));function Bd(e){let t=gl.find(([,r])=>r.actionLabel===e);return t?t[0]:null}$();var fS=x("provider.registry"),gS=3e4,li=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+gS}),n}async getAvailableProviders(t){let r=[...this.adapters.values()].filter(o=>t in o.installers),n=await Promise.allSettled(r.map(o=>this.checkAvailability(o)));return n.forEach((o,s)=>{o.status==="rejected"&&fS.warn(`Provider "${r[s].id}" isAvailable() threw: ${String(o.reason)}`);}),r.filter((o,s)=>{let i=n[s];return i.status==="fulfilled"&&i.value===true})}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var hS={user:"global",project:"project",local:"local"};function ci(e){return e?hS[e]:"global"}var qe=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},Lr=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};_o();hl();$();var SS=x("catalog.registry"),ui=class{adapters=new Map;register(t){this.adapters.set(t.id,t);}unregister(t){this.adapters.delete(t);}async fetchAllWithErrors(){let t=this.listAdapters(),r=await Promise.allSettled(t.map(s=>s.fetchItems())),n=[],o=[];for(let s=0;s<r.length;s++){let i=r[s],a=t[s];if(i.status==="fulfilled")n.push(...i.value);else {let l=String(i.reason);SS.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};We();var CS={retries:5,minTimeout:50};async function yl(e,t){mkdirSync(dirname(e),{recursive:true});let r=await dw.lock(e+".lock",{realpath:false,retries:CS});try{return await t()}finally{await r();}}var di=class{filePath;constructor(t){this.filePath=t??nu();}async read(){try{let t=await readFile(this.filePath,"utf-8");return JSON.parse(t).catalogs??[]}catch(t){if(t.code==="ENOENT")return [];throw t}}async write(t){let r=dirname(this.filePath);await mkdir(r,{recursive:true});let n=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(n,JSON.stringify({catalogs:t},null,2),"utf-8"),await rename(n,this.filePath);}async add(t){await yl(this.filePath,async()=>{let r=await this.read();if(r.some(o=>o.id===t.id))return;let n={...t,lastUpdated:t.lastUpdated??new Date().toISOString()};await this.write([...r,n]);});}async remove(t){if(t==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await yl(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await yl(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};Sl();var he=new ui,rr=new di,US=["flow-harness"];function NS(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?US:e.split(",").map(t=>t.trim()).filter(Boolean)}he.register(new Kn);for(let e of NS())he.register(new Kn(e));var Yd=false;async function Zd(){if(Yd)return;Yd=true;let e=await rr.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(xl(),qd));for(let r of e)he.register(new t(r.id,r.name,r.source));}Dr();function Qd(e){if(e===void 0||!Number.isFinite(e)||e<=0)return 3e4;let t=e/131072*1e3;return Math.min(6e5,Math.max(3e4,Math.ceil(t)))}$();var FS=x("api:actions"),ep=2;async function nr(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Sl(),Hd));return new t(e).fetchItems()}return he.fetchAll()}async function tp(){return he.fetchAllWithErrors()}async function Hn(e,t){Lo(e);try{return await Un(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await Nn(r);throw n?new Error(n,{cause:r}):r instanceof Error?r.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`,{cause:r}):r.message.includes("timeout")?new Error("Download timed out after 30s",{cause:r}):new Error(`Failed to fetch plugin manifest: ${r.message}`,{cause:r}):r}}async function jS(e,t){try{let n=(await jd(`v1/plugins/${e}/archive`,{source:t,timeoutMs:3e4})).headers.get("x-archive-size"),o=n?Number(n):NaN;return Number.isFinite(o)&&o>0?o:void 0}catch(r){FS.debug(`[${e}] Archive size probe failed, using default timeout: ${String(r)}`);return}}async function rp(e,t,r){Lo(e);try{let n=await jS(e,r),o=Qd(n),s=await Un(`v1/plugins/${e}/archive`,r,o),i=s.headers.get("x-archive-size"),a=i?Number(i):NaN,l=Number.isFinite(a)&&a>0?a:0,u=l>0,c=s.body;if(!c)throw new Error("Failed to download plugin: response has no body");let d=c.getReader(),m=[],p=0;for(;;){let{done:g,value:h}=await d.read();if(g)break;if(p+=h.byteLength,u&&p>l*ep)throw await d.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${l*ep}`);m.push(h),u&&t?.(p,l);}return Buffer.concat(m)}catch(n){if(n instanceof Error&&n.message.includes("Download exceeded expected size"))throw n;let o=await Nn(n);throw o?new Error(o,{cause:n}):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`,{cause:n}):n}}async function mi(){try{let{profiles:e}=await jt().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",{cause:e}):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits",{cause:e}):new Error(`Failed to fetch starter kits: ${e.message}`,{cause:e}):e}}We();We();async function np(e,t){let r=ae.resolve(t);await Kt.mkdir(r,{recursive:true});let n=ae.join(ae.dirname(r),`${randomUUID()}.zip`);try{await Kt.writeFile(n,e);let o=await VS.Open.file(n),s=ae.normalize(r+ae.sep);for(let i of o.files){if((i.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${i.path}" is a symbolic link and was rejected`);let l=ae.resolve(r,i.path);if(process.platform==="win32"&&l.length>=260)throw new Error(`Path too long: "${l}" (${l.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!l.startsWith(s)&&l!==r)throw new Error(`Zip Slip detected: entry "${i.path}" would escape target directory`)}await o.extract({path:r});try{let i=realpathSync(r);if(!i.startsWith(ae.resolve(ae.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Kt.unlink(n);}catch{}}}async function bl(e){await Kt.rm(e,{recursive:true,force:true});}async function or(){let e=tu();await Kt.mkdir(ae.dirname(e),{recursive:true});try{await Kt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await dw.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}We();F();$();var WS=x("marketplace-registry");function zS(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||Oe,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function sp(e){let t=fo(e);if(!le__default.existsSync(t))return null;try{return JSON.parse(le__default.readFileSync(t,"utf-8"))}catch{return null}}function XS(e){let t=sp(e);if(t)return t;let r=zS(e),n=fo(e);return le__default.mkdirSync(ae__default.dirname(n),{recursive:true}),El(r,e),r}function El(e,t){let r=fo(t),n=`${r}.${randomUUID()}.tmp`;le__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(n,r);}function qS(e){let t=e||Oe,r=Gr(),n={};try{le__default.existsSync(r)&&(n=JSON.parse(le__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:ba(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;le__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(o,r);}async function Il(e,t){let r=ba(e),n=ae__default.relative(r,fo(e));try{let o=simpleGit({baseDir:r,timeout:{block:1e4}});if((await o.status()).files.length===0)return;await o.add([n,"plugins/native/"]),await o.commit(t);}catch(o){WS.debug(`Could not commit marketplace clone changes (non-fatal): ${String(o)}`);}}async function ip(e,t,r){it(e.name),qS(r);let n=xa(e.name,r);le__default.mkdirSync(ae__default.dirname(n),{recursive:true});try{le__default.lstatSync(n),le__default.rmSync(n,{recursive:!0,force:!0});}catch{}le__default.cpSync(t,n,{recursive:true,dereference:true});let o=XS(r);o.plugins.some(i=>i.name===e.name)||(o.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),El(o,r)),await Il(r,`chore: register ${e.name}@${e.version}`);}async function ap(e,t){it(e);let r=xa(e,t);try{le__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=sp(t);if(!n){await Il(t,`chore: unregister ${e}`);return}let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&El(n,t),await Il(t,`chore: unregister ${e}`);}N();$();var ZS=x("mcpConfigReader"),QS=500,ex=512;function tx(){return ae__default.join($e__default.homedir(),".claude.json")}function rx(){return ae__default.join(process.cwd(),".mcp.json")}function cp(e){if(!le__default.existsSync(e))return null;try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return ZS.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Do(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pl(e){if(!Do(e))return {};let t=e.mcpServers;return Do(t)?t:{}}function Tl(e,t){return Object.keys(e).slice(0,QS).map(n=>({name:y(n.slice(0,ex)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function dp(){let e=[],t=tx(),r=cp(t);if(Do(r)){let a=r,l=Pl(a);e.push(...Tl(l,"user"));let u=process.cwd();if(Do(a.projects)){let c=a.projects[u];if(Do(c)){let d=Pl(c);e.push(...Tl(d,"local"));}}}let n=rx(),o=cp(n),s=Pl(o);e.push(...Tl(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}$();F();function Oo(e,t){let r=join(e,".gitignore");if(!existsSync(r)){writeFileSync(r,`${t}
|
|
111
111
|
`,"utf8");return}let n=readFileSync(r,"utf8");n.split(`
|
|
112
112
|
`).some(s=>s.trim()===t)||appendFileSync(r,`${n.endsWith(`
|
|
113
113
|
`)?"":`
|
|
114
114
|
`}${t}
|
|
115
|
-
`,"utf8");}var je=x("storage");async function px(e,t,r){try{await P(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Q().interfaceType});}catch(n){je.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function mx(e,t,r){let n=t==="enabled"?v.CLI_TOOL_ENABLED:v.CLI_TOOL_DISABLED;P(n,{tool_id:e,source:r,interface:Q().interfaceType}).catch(o=>je.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Ll(){return ae__default.join(Te__default.homedir(),".claude","plugins","installed_plugins.json")}function wp(){return ae__default.join(Te__default.homedir(),".claude","plugins")}function Ml(e){let t;try{t=le__default.realpathSync(e);}catch{t=ae__default.resolve(e);}let r=ae__default.resolve(wp()),n=ae__default.resolve(ae__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+ae__default.sep),s=t.startsWith(n+ae__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Sp(e="user"){return e==="local"?ae__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?ae__default.join(process.cwd(),".claude","settings.json"):ae__default.join(Te__default.homedir(),".claude","settings.json")}function Pe(){let e=Ll();if(!le__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Dl(){let e=Ll();try{let t=await le__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function fx(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function xp(e,t){try{le__default.mkdirSync(ae__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;le__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,e);}catch(r){throw fx(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`,{cause:r}):r}}function at(e){xp(Ll(),e);}function mn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function gx(e,t){let r=ae__default.join(e,".claude-plugin"),n=ae__default.join(r,"plugin.json");if(le__default.existsSync(n))try{return JSON.parse(le__default.readFileSync(n,"utf-8"))}catch{return null}let o=ae__default.join(r,"marketplace.json");if(le__default.existsSync(o))try{let s=JSON.parse(le__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function Fo(e="user"){let t=Sp(e);if(!le__default.existsSync(t))return {};try{return JSON.parse(le__default.readFileSync(t,"utf-8"))}catch{return {}}}function yi(e,t="user"){xp(Sp(t),e),t==="local"&&Bo(process.cwd(),".claude/settings.local.json");}function hx(e,t){let{name:r,marketplace:n}=mn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>mn(i).name===r)[0],!o)throw je.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function yx(e,t){let{name:r,marketplace:n}=mn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>mn(i).name===r)[0],o?{key:o,name:r}:null}function $l(e="user"){return Fo(e).enabledPlugins??{}}function yp(e,t="user"){let r=Fo(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,yi(r,t);}function jo(e,t,r="user"){let n=Fo(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},yi(n,r);}function wx(e){let t=new Map;for(let r of e){let n=r.projectPath?`${r.scope}:${r.projectPath}`:r.scope,o=t.get(n);(!o||r.installedAt>o.installedAt)&&t.set(n,r);}return [...t.values()]}function Ol(e,t,r){return t?t==="user"?e.find(n=>n.scope==="user"):e.find(n=>n.scope===t&&n.projectPath===r)??e.find(n=>n.scope===t):e.find(n=>n.projectPath===r)??e.find(n=>n.scope==="user")}function me(){let e=Pe(),t=$l(),r=$l("project"),n=$l("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=mn(u),p=c.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return wx(p).map(h=>{let g=gx(h.installPath,d),E=(o[h.scope]??t)[u];return {name:d,marketplace:m,version:h.version&&h.version!=="unknown"?h.version:void 0,installedAt:h.installedAt,installPath:h.installPath,scope:h.scope,providerId:h.providerId,type:h.type,projectPath:h.projectPath,description:g?.description,author:g?.author,status:E===false?"disabled":"enabled"}})}),i=hp(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function Sx(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Ko(e,t){je.debug(`[${e}] Acquiring lock to uninstall`);let r=await sr();try{let n=Pe(),o=yx(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s],l=t??"user",u=Ol(a,l,process.cwd());if(!u)throw new Error(t?`Plugin '${i}' is not installed in ${t} scope`:`Plugin '${i}' is not installed in user (global) scope. Pass --scope project or --scope local to remove it from this repo instead.`);je.debug(`[${i}] Resolved key: ${s}, scope: ${l}`);let c=ae__default.dirname(u.installPath),d=a.filter(p=>p!==u);if(d.some(p=>ae__default.dirname(p.installPath)===c)?je.debug(`[${i}] Directory still used by another scope, keeping: ${c}`):(Ml(u.installPath),Ml(c),je.debug(`[${i}] Removing directory: ${c}`),le__default.rmSync(c,{recursive:!0,force:!0})),d.length===0){let{[s]:p,...f}=n.plugins;at({...n,plugins:f}),yp(s,l),await pp(i,Sx(s));}else n.plugins[s]=d,at(n),yp(s,l);await px(i,u.origin??"internal",u.type??"skill"),je.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Vo(e,t,r){je.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await sr();try{let o=Pe(),{key:s,name:i}=hx(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";je.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),jo(s,t==="enabled",l),mx(i,t,u),je.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var xx=/^\d+$/;function bx(e){let t=ae__default.join(e,".in_use"),r;try{r=le__default.readdirSync(t);}catch{return false}for(let n of r){if(!xx.test(n))continue;let o=Number(n);try{return process.kill(o,0),!0}catch{}}return false}var Ix=20;function bp(e,t=0){if(t>Ix)return 0;let r=0,n;try{n=le__default.readdirSync(e,{withFileTypes:!0});}catch{return 0}for(let o of n){let s=ae__default.join(e,o.name);if(!o.isSymbolicLink()){if(o.isDirectory())r+=bp(s,t+1);else if(o.isFile())try{r+=le__default.statSync(s).size;}catch{}}}return r}function vx(e,t){let r=new Map;for(let[n,o]of Object.entries(e.plugins)){let{name:s,marketplace:i}=mn(n);if(i!==t)continue;let a=r.get(s)??new Set;for(let l of o)l.projectPath&&!le__default.existsSync(l.projectPath)||l.version&&a.add(l.version);r.set(s,a);}return r}function Ip(){let e=Pe(),t=[];for(let r of wr){let n=vx(e,r),o=ae__default.join(wp(),"cache",r),s;try{s=le__default.readdirSync(o,{withFileTypes:!0});}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=i.name,l=ae__default.join(o,a),u=n.get(a)??new Set,c;try{c=le__default.readdirSync(l,{withFileTypes:!0});}catch{continue}for(let d of c){if(!d.isDirectory())continue;let m=d.name;if(u.has(m))continue;let p=ae__default.join(l,m);bx(p)||t.push({marketplace:r,pluginName:a,version:m,path:p,sizeBytes:bp(p)});}}}return t}async function vp(e){let t=await sr(),r=[],n=[];try{for(let s of e)try{Ml(s.path),le__default.rmSync(s.path,{recursive:!0,force:!0}),r.push(s),je.debug(`[${s.pluginName}@${s.version}] Pruned ${s.path}`);}catch(i){n.push({candidate:s,error:i instanceof Error?i.message:String(i)}),je.warn(`[${s.pluginName}@${s.version}] Prune failed: ${String(i)}`);}}finally{await t();}let o=r.reduce((s,i)=>s+i.sizeBytes,0);return await P(v.CLI_PLUGIN_PRUNE_COMPLETED,{removed_count:r.length,failed_count:n.length,freed_bytes:o,interface:Q().interfaceType}).catch(s=>je.warn(`Failed to send prune metrics: ${String(s)}`)),{removed:r,failed:n,freedBytes:o}}function Ep(){let e=Pe(),t=[];for(let[r,n]of Object.entries(e.plugins)){let{name:o,marketplace:s}=mn(r);for(let i of n)i.projectPath&&!le__default.existsSync(i.projectPath)&&t.push({key:r,pluginName:o,marketplace:s,scope:i.scope,projectPath:i.projectPath});}return t}function Pp(e){if(e.length===0)return;let t=new Set(e.map(n=>`${n.key}::${n.projectPath}`)),r=Pe();for(let[n,o]of Object.entries(r.plugins)){let s=o.filter(i=>!i.projectPath||!t.has(`${n}::${i.projectPath}`));s.length===0?delete r.plugins[n]:r.plugins[n]=s;}at(r);}Ue();function Ul(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Ul(r)]))}function Ho(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];if(Array.isArray(o)&&Array.isArray(s)){let i=new Set(s.map(a=>JSON.stringify(Ul(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Ul(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Ho(s,o):r[n]=o;}return r}R();var Nl=x("bundleContent"),wi="${CLAUDE_PLUGIN_ROOT}/hooks/";function Ex(e){return e.split(wi).join("$CLAUDE_PROJECT_DIR/.claude/hooks/")}function Bl(e){return typeof e=="string"?Ex(e):Array.isArray(e)?e.map(Bl):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Bl(r)])):e}function Px(e,t){let r=ae__default.join(e,"rules");if(!le__default.existsSync(r))return 0;let n=le__default.readdirSync(r).filter(s=>s.endsWith(".md")&&le__default.lstatSync(ae__default.join(r,s)).isFile());if(n.length===0)return 0;let o=Tn(t);le__default.mkdirSync(o,{recursive:true});for(let s of n)le__default.copyFileSync(ae__default.join(r,s),ae__default.join(o,s));return n.length}function Tx(e,t){let r=ae__default.join(e,"hooks","hooks.json");if(!le__default.existsSync(r))return 0;let n;try{n=JSON.parse(le__default.readFileSync(r,"utf-8"));}catch(f){return Nl.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(f)}`),0}let o=n.hooks;if(!o||typeof o!="object"||Array.isArray(o))return 0;let s=ae__default.join(e,"hooks"),i=Ca(t),a=new Set,l=f=>{if(typeof f=="string"&&f.includes(wi)){let h=f.slice(f.indexOf(wi)+wi.length),g=/^([^"'\s]+)/.exec(h);g&&a.add(g[1]);}else Array.isArray(f)?f.forEach(l):f!==null&&typeof f=="object"&&Object.values(f).forEach(l);};l(o);let u=0;if(a.size>0){le__default.mkdirSync(i,{recursive:true});for(let f of a){let h=ae__default.join(s,f);le__default.existsSync(h)&&(le__default.copyFileSync(h,ae__default.join(i,f)),u++);}}let c=Bl(o),d=Fo(t),m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Ho(m,c);return yi({...d,hooks:p},t),u}function Si(e,t){let r=Px(e,t),n=Tx(e,t);r>0&&Nl.debug(`Copied ${r} rule file(s) to ${Tn(t)}`),n>0&&Nl.debug(`Copied ${n} hook script(s) to ${Ca(t)}`);}F();R();var Cx=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,kx=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function it(e){if(!Cx.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Ax(e){if(!kx.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 Nr=x("installer");function Rx(e,t,r){let n=`${e}@${r||Oe}`,s=Pe().plugins[n];if(s&&!t)throw new qe(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function $x(e,t,r){r&&await Pl(t);try{Nr.debug(`[${t}] Extracting archive...`),await lp(e,t);}catch(n){throw await Pl(t),n}}function Mx(e,t,r,n,o,s="claude-code",i){let a=Pe(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>!(c.scope===n&&c.projectPath===l.projectPath)),l],at(a),jo(e,true,n);}async function _x(e,t,r,n,o,s){try{await P(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:Q().interfaceType});}catch(i){Nr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Lx(e,t,r,n){try{await P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Q().interfaceType});}catch(o){Nr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Ke(e,t={}){let r=Date.now(),n=null;try{Nr.debug(`[${e}] Acquiring lock...`),n=await sr();let{pluginKey:o,alreadyInstalled:s}=Rx(e,t.force,t.source),{source:i}=t;Nr.debug(`[${e}] Fetching manifest...`);let a=await Wn(e,i);it(a.name),Ax(a.version),Nr.debug(`[${e}] Downloading archive...`);let l=await ap(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=su(a.name,a.version,t.source);await $x(l,d,!!s&&!!t.force),await Si(d,u),Mx(o,d,a.version,u,"internal",t.providerId,c),await dp(a,d,t.source);let m=Date.now()-r;Nr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await _x(a.name,a.version,m,pi(u),"internal",c),p}catch(o){throw await Lx(e,o,"internal",t.type??"skill"),Nr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}R();N();Ce();Mn();R();var Dx=x("commands:helpers");async function X(){let e=await te();if(!e)return I("Not authenticated. Run: flow auth login"),false;e.customUrl&&Dt(e.customUrl);try{await Ut();}catch(t){return Dx.debug(`Token validation failed: ${String(t)}`),I("Session expired. Run: flow auth login"),false}return true}async function q(e){let t=jl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function zn(e){let t=jl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var Ox="\x1B[A",Ux="\x1B[B";function Tp(e,t){let r=t?T.cyan("\u276F"):" ",n=t?T.cyan(e.label):e.label,o=e.description?T.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function Nx(e,t){return e.map((r,n)=>Tp(r,n===t)).join(`
|
|
116
|
-
`)}async function
|
|
117
|
-
`),process.stdout.write(
|
|
115
|
+
`,"utf8");}var Fe=x("storage");async function cx(e,t,r){try{await P(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Q().interfaceType});}catch(n){Fe.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function ux(e,t,r){let n=t==="enabled"?v.CLI_TOOL_ENABLED:v.CLI_TOOL_DISABLED;P(n,{tool_id:e,source:r,interface:Q().interfaceType}).catch(o=>Fe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function $l(){return ae__default.join($e__default.homedir(),".claude","plugins","installed_plugins.json")}function mp(){return ae__default.join($e__default.homedir(),".claude","plugins")}function kl(e){let t;try{t=le__default.realpathSync(e);}catch{t=ae__default.resolve(e);}let r=ae__default.resolve(mp()),n=ae__default.resolve(ae__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+ae__default.sep),s=t.startsWith(n+ae__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function fp(e="user"){return e==="local"?ae__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?ae__default.join(process.cwd(),".claude","settings.json"):ae__default.join($e__default.homedir(),".claude","settings.json")}function Pe(){let e=$l();if(!le__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Rl(){let e=$l();try{let t=await le__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function dx(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function gp(e,t){try{le__default.mkdirSync(ae__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;le__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,e);}catch(r){throw dx(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`,{cause:r}):r}}function at(e){gp($l(),e);}function dn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function px(e,t){let r=ae__default.join(e,".claude-plugin"),n=ae__default.join(r,"plugin.json");if(le__default.existsSync(n))try{return JSON.parse(le__default.readFileSync(n,"utf-8"))}catch{return null}let o=ae__default.join(r,"marketplace.json");if(le__default.existsSync(o))try{let s=JSON.parse(le__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function Uo(e="user"){let t=fp(e);if(!le__default.existsSync(t))return {};try{return JSON.parse(le__default.readFileSync(t,"utf-8"))}catch{return {}}}function fi(e,t="user"){gp(fp(t),e),t==="local"&&Oo(process.cwd(),".claude/settings.local.json");}function mx(e,t){let{name:r,marketplace:n}=dn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>dn(i).name===r)[0],!o)throw Fe.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function fx(e,t){let{name:r,marketplace:n}=dn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>dn(i).name===r)[0],o?{key:o,name:r}:null}function Cl(e="user"){return Uo(e).enabledPlugins??{}}function pp(e,t="user"){let r=Uo(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,fi(r,t);}function No(e,t,r="user"){let n=Uo(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},fi(n,r);}function gx(e){let t=new Map;for(let r of e){let n=r.projectPath?`${r.scope}:${r.projectPath}`:r.scope,o=t.get(n);(!o||r.installedAt>o.installedAt)&&t.set(n,r);}return [...t.values()]}function Ml(e,t,r){return t?t==="user"?e.find(n=>n.scope==="user"):e.find(n=>n.scope===t&&n.projectPath===r)??e.find(n=>n.scope===t):e.find(n=>n.projectPath===r)??e.find(n=>n.scope==="user")}function pe(){let e=Pe(),t=Cl(),r=Cl("project"),n=Cl("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=dn(u),p=c.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return gx(p).map(h=>{let f=px(h.installPath,d),E=(o[h.scope]??t)[u];return {name:d,marketplace:m,version:h.version&&h.version!=="unknown"?h.version:void 0,installedAt:h.installedAt,installPath:h.installPath,scope:h.scope,providerId:h.providerId,type:h.type,projectPath:h.projectPath,description:f?.description,author:f?.author,status:E===false?"disabled":"enabled"}})}),i=dp(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function hx(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Bo(e,t){Fe.debug(`[${e}] Acquiring lock to uninstall`);let r=await or();try{let n=Pe(),o=fx(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s],l=t??"user",u=Ml(a,l,process.cwd());if(!u)throw new Error(t?`Plugin '${i}' is not installed in ${t} scope`:`Plugin '${i}' is not installed in user (global) scope. Pass --scope project or --scope local to remove it from this repo instead.`);Fe.debug(`[${i}] Resolved key: ${s}, scope: ${l}`);let c=ae__default.dirname(u.installPath),d=a.filter(p=>p!==u);if(d.some(p=>ae__default.dirname(p.installPath)===c)?Fe.debug(`[${i}] Directory still used by another scope, keeping: ${c}`):(kl(u.installPath),kl(c),Fe.debug(`[${i}] Removing directory: ${c}`),le__default.rmSync(c,{recursive:!0,force:!0})),d.length===0){let{[s]:p,...g}=n.plugins;at({...n,plugins:g}),pp(s,l),await ap(i,hx(s));}else n.plugins[s]=d,at(n),pp(s,l);await cx(i,u.origin??"internal",u.type??"skill"),Fe.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Fo(e,t,r){Fe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await or();try{let o=Pe(),{key:s,name:i}=mx(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";Fe.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),No(s,t==="enabled",l),ux(i,t,u),Fe.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var yx=/^\d+$/;function wx(e){let t=ae__default.join(e,".in_use"),r;try{r=le__default.readdirSync(t);}catch{return false}for(let n of r){if(!yx.test(n))continue;let o=Number(n);try{return process.kill(o,0),!0}catch{}}return false}var Sx=20;function hp(e,t=0){if(t>Sx)return 0;let r=0,n;try{n=le__default.readdirSync(e,{withFileTypes:!0});}catch{return 0}for(let o of n){let s=ae__default.join(e,o.name);if(!o.isSymbolicLink()){if(o.isDirectory())r+=hp(s,t+1);else if(o.isFile())try{r+=le__default.statSync(s).size;}catch{}}}return r}function xx(e,t){let r=new Map;for(let[n,o]of Object.entries(e.plugins)){let{name:s,marketplace:i}=dn(n);if(i!==t)continue;let a=r.get(s)??new Set;for(let l of o)l.projectPath&&!le__default.existsSync(l.projectPath)||l.version&&a.add(l.version);r.set(s,a);}return r}function yp(){let e=Pe(),t=[];for(let r of yr){let n=xx(e,r),o=ae__default.join(mp(),"cache",r),s;try{s=le__default.readdirSync(o,{withFileTypes:!0});}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=i.name,l=ae__default.join(o,a),u=n.get(a)??new Set,c;try{c=le__default.readdirSync(l,{withFileTypes:!0});}catch{continue}for(let d of c){if(!d.isDirectory())continue;let m=d.name;if(u.has(m))continue;let p=ae__default.join(l,m);wx(p)||t.push({marketplace:r,pluginName:a,version:m,path:p,sizeBytes:hp(p)});}}}return t}async function wp(e){let t=await or(),r=[],n=[];try{for(let s of e)try{kl(s.path),le__default.rmSync(s.path,{recursive:!0,force:!0}),r.push(s),Fe.debug(`[${s.pluginName}@${s.version}] Pruned ${s.path}`);}catch(i){n.push({candidate:s,error:i instanceof Error?i.message:String(i)}),Fe.warn(`[${s.pluginName}@${s.version}] Prune failed: ${String(i)}`);}}finally{await t();}let o=r.reduce((s,i)=>s+i.sizeBytes,0);return await P(v.CLI_PLUGIN_PRUNE_COMPLETED,{removed_count:r.length,failed_count:n.length,freed_bytes:o,interface:Q().interfaceType}).catch(s=>Fe.warn(`Failed to send prune metrics: ${String(s)}`)),{removed:r,failed:n,freedBytes:o}}function Sp(){let e=Pe(),t=[];for(let[r,n]of Object.entries(e.plugins)){let{name:o,marketplace:s}=dn(r);for(let i of n)i.projectPath&&!le__default.existsSync(i.projectPath)&&t.push({key:r,pluginName:o,marketplace:s,scope:i.scope,projectPath:i.projectPath});}return t}function xp(e){if(e.length===0)return;let t=new Set(e.map(n=>`${n.key}::${n.projectPath}`)),r=Pe();for(let[n,o]of Object.entries(r.plugins)){let s=o.filter(i=>!i.projectPath||!t.has(`${n}::${i.projectPath}`));s.length===0?delete r.plugins[n]:r.plugins[n]=s;}at(r);}function _l(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,_l(r)]))}function jo(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];if(Array.isArray(o)&&Array.isArray(s)){let i=new Set(s.map(a=>JSON.stringify(_l(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(_l(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=jo(s,o):r[n]=o;}return r}$();var Ip=x("bundleContent"),Ix="${CLAUDE_PLUGIN_ROOT}";function vx(e,t){return t.split(Ix).join(e)}function Ll(e,t){return typeof t=="string"?vx(e,t):Array.isArray(t)?t.map(r=>Ll(e,r)):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Ll(e,n)])):t}function Ex(e,t){let r=ae__default.join(e,"hooks","hooks.json");if(!le__default.existsSync(r))return;let n;try{n=JSON.parse(le__default.readFileSync(r,"utf-8"));}catch(u){Ip.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(u)}`);return}let o=n.hooks;if(!o||typeof o!="object"||Array.isArray(o))return;let s=Ll(e,o),i=Uo(t),a=i.hooks!==null&&typeof i.hooks=="object"&&!Array.isArray(i.hooks)?i.hooks:{},l=jo(a,s);fi({...i,hooks:l},t),Ip.debug(`Registered hooks from ${r}, pointing at ${e} (scope: ${t})`);}function gi(e,t){Ex(e,t);}F();$();var Px=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Tx=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function it(e){if(!Px.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Cx(e){if(!Tx.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 Or=x("installer");function kx(e,t,r){let n=`${e}@${r||Oe}`,s=Pe().plugins[n];if(s&&!t)throw new qe(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function Ax(e,t,r){r&&await bl(t);try{Or.debug(`[${t}] Extracting archive...`),await np(e,t);}catch(n){throw await bl(t),n}}function $x(e,t,r,n,o,s="claude-code",i){let a=Pe(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>!(c.scope===n&&c.projectPath===l.projectPath)),l],at(a),No(e,true,n);}async function Rx(e,t,r,n,o,s){try{await P(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:Q().interfaceType});}catch(i){Or.warn(`Failed to send install metrics: ${String(i)}`);}}async function Mx(e,t,r,n){try{await P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Q().interfaceType});}catch(o){Or.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function je(e,t={}){let r=Date.now(),n=null;try{Or.debug(`[${e}] Acquiring lock...`),n=await or();let{pluginKey:o,alreadyInstalled:s}=kx(e,t.force,t.source),{source:i}=t;Or.debug(`[${e}] Fetching manifest...`);let a=await Hn(e,i);it(a.name),Cx(a.version),Or.debug(`[${e}] Downloading archive...`);let l=await rp(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=eu(a.name,a.version,t.source);await Ax(l,d,!!s&&!!t.force),await gi(d,u),$x(o,d,a.version,u,"internal",t.providerId,c),await ip(a,d,t.source);let m=Date.now()-r;Or.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await Rx(a.name,a.version,m,ci(u),"internal",c),p}catch(o){throw await Mx(e,o,"internal",t.type??"skill"),Or.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}$();N();Te();An();$();var _x=x("commands:helpers");async function X(){let e=await te();if(!e)return I("Not authenticated. Run: flow auth login"),false;e.customUrl&&Lt(e.customUrl);try{await Ot();}catch(t){return _x.debug(`Token validation failed: ${String(t)}`),I("Session expired. Run: flow auth login"),false}return true}async function q(e){let t=Ol.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function Gn(e){let t=Ol.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var Lx="\x1B[A",Dx="\x1B[B";function vp(e,t){let r=t?T.cyan("\u276F"):" ",n=t?T.cyan(e.label):e.label,o=e.description?T.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function Ox(e,t){return e.map((r,n)=>vp(r,n===t)).join(`
|
|
116
|
+
`)}async function Ep(e,t){if(t.length===0)throw new Error("selectPrompt requires at least one option");return new Promise((r,n)=>{let o=0;process.stdout.write(`${y(e)}
|
|
117
|
+
`),process.stdout.write(Ox(t,o));let s="",i=c=>{if(s+=c,s===""){l(),n(new Error("SIGINT"));return}if(s==="\r"||s===`
|
|
118
118
|
`){l(),process.stdout.write(`
|
|
119
|
-
`),r(t[o].value);return}if(s===
|
|
120
|
-
`);}function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",i),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",i);})}
|
|
121
|
-
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=gi(o),r?.(),qn.debug(`[${n}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let s=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(s.exitCode!==0)throw new Error(`Failed to add marketplace: ${s.stderr||"unknown error"}`);qn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw Jl(s)?new xi:s}}Or();F();Ue();R();var nb=6e4,Br=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function vt(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:nb},allowEnvironment:["GIT_TERMINAL_PROMPT","GIT_LFS_SKIP_SMUDGE"]}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(s){await rm(r,{recursive:true,force:true}).catch(()=>{});let i=s instanceof Error?s.message:String(s),a=i.includes("block timeout")||i.includes("timed out"),l=i.includes("Authentication failed")||i.includes("could not read Username")||i.includes("Permission denied")||i.includes("Repository not found");throw a?new Br("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Br(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Br(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Et(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm(e,{recursive:true,force:true});}async function fn(e,t=["--version"]){try{return (await execa(e,t,{reject:!1})).exitCode===0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return false;throw r}}function sb(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function ib(e){return typeof e=="object"&&e!==null&&e.source==="url"}function ab(e){return typeof e=="object"&&e!==null&&e.source==="github"}function gn(e,t){let r=e.source;if(sb(r)){let n=r.path?r.path.replace(/^\.\//,""):".",o=r.ref&&!/^[0-9a-f]{40}$/i.test(r.ref)?r.ref:void 0;return {cloneUrl:r.url,subPath:n||".",ref:o}}if(ib(r))return {cloneUrl:r.url,subPath:"."};if(ab(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function lt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Pt=x("claude-code.adapter");function cb(e,t){let r=e??"external";if(!t)return r;let n=t.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!n)return r;let o=n[1],s=Wr();if(!le__default.existsSync(s))return r;try{let i=JSON.parse(le__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function jp(e,t){let r=e.catalogId?ye.getAdapter(e.catalogId):void 0,n=gn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=e.type==="bundle"||e.type==null,s=cb(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Ta(s,e.name,"external"):a=join(zr(i==="user"?"global":"project"),e.name);let l=null;try{it(e.name),l=await vt(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(le__default.existsSync(a)&&le__default.rmSync(a,{recursive:!0,force:!0}),le__default.mkdirSync(dirname(a),{recursive:!0}),le__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Dl(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],at(d),jo(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Pt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Et(l).catch(()=>{});}}async function Wl(e,t,r,n){try{await P(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:pi(n),version:"unknown",duration_ms:t,interface:Q().interfaceType});}catch(o){Pt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Up(e,t,r){try{await P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Q().interfaceType});}catch(n){Pt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Np={async install(e,t){if(e.origin===xn&&!e.installCommand&&!Kn(e.name))return jp(e,t);if(e.origin===xn&&e.installCommand){let r=e.type??"skill",n=await Go(e.installCommand,t.scope);return n.exitCode===0?(await Wl(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Up(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Kn(e.name)){let r=e.type??"skill",n=Hn(e.name,t.scope);Pt.debug(`[${e.name}] Attempting install: ${n}`);let o=await _e(n);if(o.exitCode===0)return await Wl(e.name,o.duration_ms,r,t.scope),{success:true};Pt.debug(`[${e.name}] First attempt failed, adding marketplace`),await bi(e.name,t.marketplaceSource,()=>{});let s=await _e(n);return s.exitCode===0?(await Wl(e.name,s.duration_ms,r,t.scope),{success:true}):(await Up(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await Ke(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Pt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Ko(e,t);},getInstallPath(e,t){return ""}};function Bp(e){return {async install(t,r){if(t.origin===xn&&!t.installCommand&&!Kn(t.name))return jp(t,r);if(!t.installCommand)try{let o=await Ke(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Pt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Pt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Go(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=Pe(),o=`${t}@${Oe}`;if(n.plugins[o]){await Ko(t,r);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function ub(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!le__default.existsSync(t))continue;let r=le__default.readdirSync(t).filter(n=>n.endsWith(".md")&&le__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function db(e){for(let t of [join(e,".claude","rules"),join(e,"rules")]){if(!le__default.existsSync(t))continue;let r=le__default.readdirSync(t).filter(n=>n.endsWith(".md")&&le__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}async function zl(e,t,r,n){let o=await Dl(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],at(o);}var pb={async install(e,t){let r=t.scope??"user",n=e.catalogId?ye.getAdapter(e.catalogId):void 0,o=gn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await vt(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=ub(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Is(r);le__default.mkdirSync(l,{recursive:!0});let u=lt(e.name);if(a.length===1)le__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=lt(basename(d,".md"));le__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await zl(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Et(s).catch(()=>{});}},async uninstall(e,t){let r=Is(t),n=lt(e);if(le__default.existsSync(r))for(let a of le__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))le__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Pe(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;at({...s,plugins:l});}else at({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Is(t),`${lt(e)}.md`)}},mb={async install(e,t){let r=t.scope??"user",n=e.catalogId?ye.getAdapter(e.catalogId):void 0,o=gn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await vt(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=db(i);if(a.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let l=Tn(r);le__default.mkdirSync(l,{recursive:!0});for(let u of a)le__default.copyFileSync(u,join(l,basename(u)));return await zl(e.name,r,l,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Rule install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Et(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,t){return Tn(t)}},fb={async install(e,t){let r=t.scope??"user",n=e.catalogId?ye.getAdapter(e.catalogId):void 0,o=gn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await vt(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!le__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(le__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=Ro();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=c.status==="ok"?c.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Ho(m,u);return Hs({...d,hooks:p}),await zl(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Et(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},Ii=class{id="claude-code";name="Claude Code";async isAvailable(){return fn("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Np,plugin:Np,skill:Bp("skill"),mcp:Bp("mcp"),agent:pb,hook:fb,rule:mb}};function vi(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}var hb=new Set(["gh"]),yb=vi(hb,"use: gh copilot mcp remove <name>"),Ei=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await fn("gh",["--version"])?fn("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:yb}};Ue();var wb=new Set(["opencode"]),Sb=vi(wb,"use: opencode config remove mcp <name>");function xb(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(`
|
|
122
|
-
`)}function Kp(){return {async install(e,t){try{it(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?ye.getAdapter(e.catalogId):void 0,n=gn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await vt(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=bs(t.scope??"user"),a=join(s,".opencode","plugins");if(le__default.existsSync(a)){let l=le__default.readdirSync(a).filter(u=>u.endsWith(".js")||u.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};le__default.mkdirSync(i,{recursive:!0}),le__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);le__default.existsSync(l)&&le__default.rmSync(l,{recursive:!0,force:!0}),le__default.mkdirSync(l,{recursive:!0}),le__default.cpSync(s,l,{recursive:!0}),le__default.mkdirSync(i,{recursive:!0}),le__default.writeFileSync(join(i,`${e.name}.js`),xb(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(s){return {success:false,message:s instanceof Error?s.message:String(s)}}finally{o&&await Et(o).catch(()=>{});}},async uninstall(e,t){it(e);let r=bs(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);le__default.existsSync(n)&&le__default.rmSync(n,{force:true}),le__default.existsSync(o)&&le__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(bs(t),`${e}.js`)}}}var Pi=class{id="opencode";name="OpenCode";async isAvailable(){return fn("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Sb,skill:Kp(),bundle:Kp()}};var Gt=new di;Gt.register(new Ii);Ar()&&(Gt.register(new Ei),Gt.register(new Pi));function Vp({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,u]=useState([]),[c,d]=useState(void 0);useEffect(()=>{Gt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(g=>{g==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(g=>{if(g==="Cancel"){a(false);return}let w=l.find(E=>E.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=Hd(g);w?r(w,c):s(false);},[r,c]),h=useCallback(()=>{s(false);},[]);if(i){let g=[...l.map(w=>w.name),"Cancel"];return jsx(st,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(st,{itemName:`${e} \u2014 Choose scope`,actions:Kd,descriptions:Vd,onAction:f,onClose:h},"scope"):jsx(st,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}N();function Gp({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,h)=>{h.upArrow?a(g=>Math.max(0,g-1)):h.downArrow?a(g=>Math.min(d.length-1,g+1)):h.return?d[i]==="Confirm Install"?n():o():h.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(f=>{let h=y(f.name??f.flowId),g=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:h}),jsxs(Text,{dimColor:true,children:["(",g,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,h)=>jsx(Box,{children:jsxs(Text,{bold:h===i,color:h===i?"cyan":void 0,children:[h===i?"\u203A ":" ",f]})},f))})]}):jsx(st,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function ki({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}N();function zp({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=ki({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(st,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:g=>{g==="Uninstall"?c():g===d?i(t):g.startsWith("Update")?a?.():l();},onClose:l})}function Yp({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=ki({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(st,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}R();var Qn=x("bundle:installer"),Zp=/already exists/i;async function kb(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Rp(t)){let r=await $p(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Zp.test(n))return;throw new Error(n)}}else {let r=await Go(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Zp.test(n))return;throw new Error(n)}}}async function Ab(e,t){try{await P(v.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){Qn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function Rb(e,t,r){try{await P(v.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){Qn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Qp(e,t,r,n){try{await P(v.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){Qn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function $b(e,t,r,n,o){try{await P(v.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){Qn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function $i(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(p=>p.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await Ab(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let h=f.name??f.flowId,g=f.type??"unknown";if(!f.type){Qn.warn(`Artifact "${h}" has no type \u2014 treated as failed`),l.push({name:h,type:g,reason:"unknown artifact type"}),await Qp(i,h,g,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await kb(f),u++,await Rb(i,h,g),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let E=w instanceof Error?w.message:String(w);Qn.error(`Failed to install artifact "${h}": ${E}`),l.push({name:h,type:g,reason:E}),await Qp(i,h,g,E),r?.({index:p+1,total:c,artifact:f,success:false,error:E});}}let d=Date.now()-a,m=l.length;return await $b(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}N();function nm({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,$i(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",u=e.artifact.artifacts,c=u.filter(d=>d.available);s({bundleTitle:e.title,total:u.length,installed:0,skipped:u.length-c.length,failed:c.length,failures:c.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(rm$1,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(rm$1,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var xe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:me()})}));N();function om({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,u=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),u&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",Lt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}N();function sm({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${Lt(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((h,g)=>{let w=g===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:h.danger?"yellow":void 0,dimColor:!w,children:h.label})]},h.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function im(e){return e.adapter.removable!==false?4:2}F();N();function am({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function cm({item:e,isSelected:t,isInstalled:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:t?"\u203A ":" "}),jsx(Text,{color:r?"green":void 0,bold:t,children:e.name}),r&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function um({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(C=>r.has(`${C.name}@${o}`)),i=t.filter(C=>!r.has(`${C.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((C,$)=>{if($.escape){n();return}if($.return){d(a[l]??null);return}if($.upArrow){u(O=>Math.max(0,O-1));return}$.downArrow&&u(O=>Math.min(a.length-1,O+1));},{isActive:c===null}),c!==null)return jsx(am,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(tt/2)),p=Math.min(a.length,m+tt);p===a.length&&(m=Math.max(0,p-tt));let f=a.slice(m,p),h=m,g=a.length-p,w=s.length>0&&m<s.length,E=p>s.length,_=f.filter(C=>r.has(`${C.name}@${o}`)),D=f.filter(C=>!r.has(`${C.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2191 ${h} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),_.map(C=>jsx(cm,{item:C,isSelected:a.indexOf(C)===l,isInstalled:true},C.name))]}),E&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),D.map(C=>jsx(cm,{item:C,isSelected:a.indexOf(C)===l,isInstalled:false},C.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"})})]})}El();var Nb=/^https?:\/\/.+/;function Bb(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Fb(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function fm(e){let t=S(g=>g.showNotification),r=S(g=>g.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),h=useCallback(async()=>{let g=m.current,w=d.current;if(!Nb.test(g)){c("URL must start with http:// or https://");return}c(null),o("adding");let E=randomUUID(),_=new Jn(E,w,g);try{await _.fetchItems(),await nr.add({id:E,name:w,source:g}),ye.register(new Jn(E,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(D){let C=Bb(D)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Fb(D)?D.message:D instanceof Error?`Could not reach catalog URL: ${D.message}`:"Failed to validate catalog URL";t(C,"error"),o("add-url");}},[e,t,r]);return useInput((g,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}g&&!w.ctrl&&!w.meta&&(d.current=d.current+g,i(d.current));},{isActive:n==="add-name"}),useInput((g,w)=>{if(w.escape){o("add-name");return}if(w.return){h();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}g&&!w.ctrl&&!w.meta&&(m.current=m.current+g,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function gm(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await nr.remove(o),ye.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function ym(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=xe(A=>A.installedItems),[o,s]=useState(()=>ye.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[f,h]=useState("main"),g=useRef(o);useEffect(()=>{g.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&h("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let A=ye.listAdapters(),j=await nr.read(),J=new Map(j.map(De=>[De.id,De]));s(A.map(De=>({adapter:De,stored:J.get(De.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=g.current[i-1];if(!A)return;let j=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(J=>{j||p({items:J,loading:false,error:null});}).catch(J=>{j||p({items:[],loading:false,error:J instanceof Error?J.message:"Failed to load catalog"});}),()=>{j=true;}},[i]);let E=fm(w),_=useCallback(()=>{w(),a(0),u("list"),p(null),h("main");},[w]),{handleRemove:D}=gm(_),C=useCallback(async A=>{h("removing"),await D(A);},[D]),$=useCallback(async A=>{try{let j=await A.adapter.fetchItems();if(p({items:j,loading:!1,error:null}),A.stored){let J=new Date().toISOString();await nr.updateField(A.stored.id,{lastUpdated:J}),w();}r("Marketplace updated","success");}catch(j){r(j instanceof Error?j.message:"Update failed","error");}},[w,r]),O=useCallback(async A=>{if(!A.stored)return;let j=A.stored.autoUpdate!==false;await nr.updateField(A.stored.id,{autoUpdate:!j}),w();},[w]),U=useCallback(()=>h("browse"),[]),oe=useCallback(A=>{let j=o[i-1];if(!j)return;let J=j.adapter.removable!==false;[U,()=>{$(j);},...J?[()=>{O(j);},()=>{C(j.adapter.id);}]:[]][A]?.();},[o,i,U,$,O,C]),k=useCallback(()=>h("main"),[]),H=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),re=useCallback(()=>{let A=o[i-1];A&&O(A);},[o,i,O]),K=useCallback(()=>{let A=o[i-1];A&&C(A.adapter.id);},[o,i,C]);if(useInput((A,j)=>{if(j.upArrow){a(J=>Math.max(0,J-1));return}if(j.downArrow){a(J=>Math.min(o.length,J+1));return}(j.return||j.tab)&&(i===0?E.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&E.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,j)=>{if(j.escape||j.tab){u("list");return}if(j.upArrow){d(J=>Math.max(0,J-1));return}if(j.downArrow){let J=o[i-1],De=J?im(J)-1:0;d(hs=>Math.min(hs+1,De));return}j.return&&oe(c);},{isActive:f==="main"&&E.phase==="idle"&&l==="detail"&&e==="marketplaces"}),E.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:E.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),E.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(E.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:E.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:E.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),E.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:E.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(E.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(f==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(f==="browse"){let A=o[i-1];if(!A)return jsx(Box,{});let j=A.adapter.id??"default",J=new Set(n.filter(De=>De.marketplace===A.adapter.name).map(De=>`${De.name}@${j}`));return jsx(um,{entry:A,items:m?.items??[],installedKeys:J,onBack:k})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let V=o[i-1]??null,Y=V?n.filter(A=>A.marketplace===V.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(om,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&V?jsx(sm,{entry:V,detailData:m,installedCount:Y,focusPanel:l,actionIndex:c,onBrowse:U,onUpdate:H,onToggleAutoUpdate:re,onRemove:K}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:V?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:l==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function wm(e,t,r,n){if(t.upArrow)return r.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:r.selectedIndex-1}];if(t.downArrow&&r.selectedIndex<n-1)return [{type:"setSelectedIndex",index:r.selectedIndex+1}];if(t.leftArrow){let o=ie.findIndex(i=>i.id===r.activeTab),s=ie[(o-1+ie.length)%ie.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=ie.findIndex(i=>i.id===r.activeTab),s=ie[(o+1)%ie.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=ie.findIndex(i=>i.id===r.activeTab),s=ie[(o+1)%ie.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="8"?[{type:"toggleTypeFilter",catalogType:"agent"}]:e==="9"?[{type:"toggleTypeFilter",catalogType:"hook"}]:e==="0"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="a"&&r.activeTab==="updates"?[]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function Sm(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function xm(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var Gb=new Set(ie.filter(e=>e.focus!=="list").map(e=>e.focus));function ts(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:u}=Xe.getState();i(a.slice(0,u)+s.char+a.slice(u)),l(u+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function bm({listLength:e}){let t=S(h=>h.focus),r=S(h=>h.selectedIndex),n=S(h=>h.actionMenuOpen),o=S(h=>h.setFocus),s=S(h=>h.setActionMenuOpen),i=Xe(h=>h.query),a=Xe(h=>h.setQuery),l=Xe(h=>h.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:h,setCursorPosition:g}=Xe.getState();g(h.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let h=setTimeout(()=>d(i),300);return ()=>clearTimeout(h)},[i]),useInput((h,g)=>{let{activeTab:w,selectedIndex:E,actionMenuOpen:_}=S.getState();ts(cl(h,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((h,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:E,actionMenuOpen:_}=S.getState();ts(cl("",g,{activeTab:w}));},{isActive:Gb.has(t)}),useInput((h,g)=>{let{activeTab:w,selectedIndex:E,actionMenuOpen:_}=S.getState();ts(wm(h,g,{activeTab:w,selectedIndex:E},u.current));},{isActive:t==="list"}),useInput((h,g)=>{ts(Sm(h,g));},{isActive:t==="actionMenu"}),useInput((h,g)=>{let w=xm(h,g,Xe.getState().query),E=w.queryUpdate;if(ts(w.actions),E==="reset")l(),d("");else if(E!==null){let{query:_,cursorPosition:D,setCursorPosition:C}=Xe.getState();if("backspace"in E)D>0&&(a(_.slice(0,D-1)+_.slice(D)),C(D-1));else if("append"in E)a(_.slice(0,D)+E.append+_.slice(D)),C(D+E.append.length);else if("cursorMove"in E){let $=D+E.cursorMove;$>=0&&$<=_.length&&C($);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(h=>{let{setSelectedIndex:g,selectedIndex:w}=S.getState();h===0?g(0):w>=h&&g(h-1);},[]),f=useCallback(h=>{if(!c)return u.current=h.length,h;let g=c.toLowerCase(),w=h.filter(E=>E.name.toLowerCase().includes(g)||E.description?.toLowerCase().includes(g));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function vm(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=nt(a=>a.justAuthenticated),o=nt(a=>a.credentials),s=nt(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function He(e,t,r=false){return r?true:!Ql.valid(e)||!Ql.valid(t)?false:Ql.gt(t,e)}F();R();var lr=x("updater");async function Jb(e,t,r,n,o,s){try{await P(v.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:Q().interfaceType});}catch(i){lr.warn(`Failed to send update metrics: ${String(i)}`);}}function Wb(e,t){let r=Pe(),n=process.cwd();for(let o of wr){let s=`${e}@${o}`,i=r.plugins[s];if(i&&i.length>0){let a=Ol(i,t,n);if(a)return {pluginKey:s,entry:a}}}return null}async function Di(e,t={}){let r=Date.now(),n=null;try{lr.debug(`[${e}] Acquiring lock...`),n=await sr();let o=Wb(e,t.scope);if(!o)throw lr.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{pluginKey:s,entry:i}=o,a=i.version,l=i.installPath,u=s.slice(s.lastIndexOf("@")+1);lr.debug(`[${e}] Fetching manifest...`);let d=(await Wn(e,t.source??u)).version;if(!a||!He(a,d,t.force))throw l&&await Si(l,i.scope),lr.debug(`[${e}] Already up to date (v${a??"n/a"})`),new Dr(e,a??"unknown");lr.info(`[${e}] Updating v${a} \u2192 v${d}...`),await n(),n=null;try{let m=await Ke(e,{force:!0,skipMetrics:!0,source:t.source??u,scope:i.scope}),p=Date.now()-r;return await Jb(m.name,a,m.version,p,i.origin??"internal",i.type??"skill"),lr.debug(`[${e}] Updated successfully in ${p}ms`),{name:m.name,previousVersion:a,newVersion:m.version,path:m.path,duration_ms:p}}catch(m){lr.warn(`[${e}] Install failed, rolling back to v${a}...`),n=await sr();let p=Pe(),f=p.plugins[s]?.find(h=>h.scope===i.scope&&h.projectPath===i.projectPath);throw f&&(f.version=a,f.installPath=l,at(p),lr.info(`[${e}] Rollback completed, restored to v${a}`)),m}}finally{n&&await n();}}Or();R();var Oi=x("dispatcher");async function zb(e,t,r,n,o){let s=Vn(e);return Oi.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await bi(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Oi.debug(`[${e}] Retrying install after marketplace add`),_e(t)}async function Em(e,t,r,n){let o=Hn(e,n),s=Vn(e);r?.onStatus?.(`Installing ${s}...`),Oi.debug(`[${e}] Attempting install: ${o}`);let i=await _e(o);if(i.exitCode===0)return i;Oi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return zb(e,o,a,t,r)}async function Pm(e,t,r){let n=e.type??"bundle",o=await Gt.getAvailableProviders(n),s=o[0];if(!s)throw new Error(`No available provider for artifact type "${n}"`);let i=s.installers[n];if(!i)throw new Error(`Provider "${s.id}" does not support type "${n}"`);let a=t??{},l=a;return i.install(e,l)}function Tm(){let e=xe(i=>i.installedItems),t=xe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Pm(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=me().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Gt.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",m=c.installers[d];if(!m)throw new Error(`Provider "${u}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await Vo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await Di(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}N();R();var Ni=x("mcp");function rs(e,t){e.silent?$e({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):I(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function km(e,t){e.silent?ne({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(z(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&b(t.stdout));}function Xb(e,t,r,n){let o=["claude","mcp","add","--transport",r,e];return t.length>0&&o.push(...t),n&&o.push("--scope",n),o.join(" ")}function ec(e,t){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function Am(e,t,r){if(!await X())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return rs(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Ni.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Xb(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await q(`Install external MCP "${s}"?
|
|
119
|
+
`),r(t[o].value);return}if(s===Lx){o=(o-1+t.length)%t.length,a(),s="";return}if(s===Dx){o=(o+1)%t.length,a(),s="";return}s.startsWith("\x1B")&&s.length<3||(s="");};function a(){process.stdout.write(`\x1B[${t.length-1}A`);for(let c=0;c<t.length;c++)process.stdout.write(`\r\x1B[2K${vp(t[c],c===o)}`),c<t.length-1&&process.stdout.write(`
|
|
120
|
+
`);}function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",i),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",i);})}Dr();var Wn=x("claudeProxy"),Fl="claude ",Pp="flow ",Ul=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Jn=class extends Error{constructor(t){super(`Disallowed subcommand: "${t}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},Ux=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Nx=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Bx={"--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}$/},Fx=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,jx=/^(flow|claude)\s+auth\s+login(\s|$)/,Tp=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Cp(e){return Tp.test(e.trim())}function Kx(e){return Tp.exec(e.trim())?.[2]??""}async function kp(e){let t=Kx(e);wl(t);let r=Date.now();Wn.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw jl(n)?new Nl:n}}function Vx(e){Ap(e);let t=e.slice(Fl.length);if(!Ux.test(t))throw new Jn(e)}var hi=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},Nl=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Ap(e){if(!e||!/^claude /.test(e))throw new Ul(e)}function Hx(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!Nx.test(r))throw new Jn(`Unexpected flag: ${r}`);let n=Bx[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Jn(`Flag ${r} requires a value`);if(!n.test(o))throw new Jn(`Unsafe value for flag ${r}`);t++;}}}async function _e(e){Ap(e);let t=e.slice(Fl.length).split(/\s+/).filter(Boolean);Hx(t);let r=Gx(t);Wn.debug(`[${r}] Executing proxy command: claude ${t.join(" ")}`);let n=Date.now();try{let o=await execa("claude",t,{reject:!1}),s=Date.now()-n;return Wn.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${s}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:s}}catch(o){throw jl(o)?new hi:o}}function Gx(e){return e.length>=3?e[2]:e.join(" ")}function jl(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Jx(e){return e.startsWith(Pp)?Fl+e.slice(Pp.length):e}function Wx(e){return Fx.test(e)||jx.test(e)}function zx(e){let t=0;for(;t<e.length&&Wx(e[t]);)t++;return e.slice(t)}var Xx=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function qx(e,t){return !t||e.includes("--scope")||!Xx.test(e)?e:`${e} --scope ${t}`}async function Ko(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=zx(r).map(i=>Jx(i)).map(i=>qx(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Vx(i);Wn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await _e(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await _e(o[i]),s.exitCode!==0)return s;return s}async function yi(e,t,r){let n=Fn(e),o=t?.trim();if(!o&&(o=(await Gn(`Plugin "${n}" could not be installed.
|
|
121
|
+
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=pi(o),r?.(),Wn.debug(`[${n}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let s=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(s.exitCode!==0)throw new Error(`Failed to add marketplace: ${s.stderr||"unknown error"}`);Wn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw jl(s)?new hi:s}}Dr();F();We();$();var tb=6e4,Ur=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function It(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:tb},allowEnvironment:["GIT_TERMINAL_PROMPT","GIT_LFS_SKIP_SMUDGE"]}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(s){await rm$1(r,{recursive:true,force:true}).catch(()=>{});let i=s instanceof Error?s.message:String(s),a=i.includes("block timeout")||i.includes("timed out"),l=i.includes("Authentication failed")||i.includes("could not read Username")||i.includes("Permission denied")||i.includes("Repository not found");throw a?new Ur("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Ur(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Ur(`Failed to clone ${e}: ${i}`,e,false,false)}}async function vt(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm$1(e,{recursive:true,force:true});}async function pn(e,t=["--version"]){try{return (await execa(e,t,{reject:!1})).exitCode===0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return false;throw r}}function nb(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function ob(e){return typeof e=="object"&&e!==null&&e.source==="url"}function sb(e){return typeof e=="object"&&e!==null&&e.source==="github"}function mn(e,t){let r=e.source;if(nb(r)){let n=r.path?r.path.replace(/^\.\//,""):".",o=r.ref&&!/^[0-9a-f]{40}$/i.test(r.ref)?r.ref:void 0;return {cloneUrl:r.url,subPath:n||".",ref:o}}if(ob(r))return {cloneUrl:r.url,subPath:"."};if(sb(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function lt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Et=x("claude-code.adapter");function ab(e,t){let r=e??"external";if(!t)return r;let n=t.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!n)return r;let o=n[1],s=Gr();if(!le__default.existsSync(s))return r;try{let i=JSON.parse(le__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function Np(e,t){let r=e.catalogId?he.getAdapter(e.catalogId):void 0,n=mn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=e.type==="bundle"||e.type==null,s=ab(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Ia(s,e.name,"external"):a=join(Jr(i==="user"?"global":"project"),e.name);let l=null;try{it(e.name),l=await It(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(le__default.existsSync(a)&&le__default.rmSync(a,{recursive:!0,force:!0}),le__default.mkdirSync(dirname(a),{recursive:!0}),le__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Rl(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(g=>g.scope!==i),m],at(d),No(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Et.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await vt(l).catch(()=>{});}}async function Kl(e,t,r,n){try{await P(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:ci(n),version:"unknown",duration_ms:t,interface:Q().interfaceType});}catch(o){Et.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Lp(e,t,r){try{await P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Q().interfaceType});}catch(n){Et.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Dp={async install(e,t){if(e.origin===wn&&!e.installCommand&&!Bn(e.name))return Np(e,t);if(e.origin===wn&&e.installCommand){let r=e.type??"skill",n=await Ko(e.installCommand,t.scope);return n.exitCode===0?(await Kl(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Lp(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Bn(e.name)){let r=e.type??"skill",n=jn(e.name,t.scope);Et.debug(`[${e.name}] Attempting install: ${n}`);let o=await _e(n);if(o.exitCode===0)return await Kl(e.name,o.duration_ms,r,t.scope),{success:true};Et.debug(`[${e.name}] First attempt failed, adding marketplace`),await yi(e.name,t.marketplaceSource,()=>{});let s=await _e(n);return s.exitCode===0?(await Kl(e.name,s.duration_ms,r,t.scope),{success:true}):(await Lp(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await je(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Et.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Bo(e,t);},getInstallPath(e,t){return ""}};function Op(e){return {async install(t,r){if(t.origin===wn&&!t.installCommand&&!Bn(t.name))return Np(t,r);if(!t.installCommand)try{let o=await je(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Et.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Et.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Ko(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=Pe(),o=`${t}@${Oe}`;if(n.plugins[o]){await Bo(t,r);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function lb(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!le__default.existsSync(t))continue;let r=le__default.readdirSync(t).filter(n=>n.endsWith(".md")&&le__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function cb(e){for(let t of [join(e,".claude","rules"),join(e,"rules")]){if(!le__default.existsSync(t))continue;let r=le__default.readdirSync(t).filter(n=>n.endsWith(".md")&&le__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}async function Vl(e,t,r,n){let o=await Rl(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],at(o);}var ub={async install(e,t){let r=t.scope??"user",n=e.catalogId?he.getAdapter(e.catalogId):void 0,o=mn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await It(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=lb(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Ss(r);le__default.mkdirSync(l,{recursive:!0});let u=lt(e.name);if(a.length===1)le__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=lt(basename(d,".md"));le__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await Vl(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Et.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await vt(s).catch(()=>{});}},async uninstall(e,t){let r=Ss(t),n=lt(e);if(le__default.existsSync(r))for(let a of le__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))le__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Pe(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;at({...s,plugins:l});}else at({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Ss(t),`${lt(e)}.md`)}},db={async install(e,t){let r=t.scope??"user",n=e.catalogId?he.getAdapter(e.catalogId):void 0,o=mn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await It(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=cb(i);if(a.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let l=va(r);le__default.mkdirSync(l,{recursive:!0});for(let u of a)le__default.copyFileSync(u,join(l,basename(u)));return await Vl(e.name,r,l,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(i){return Et.debug(`[${e.name}] Rule install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await vt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,t){return va(t)}},pb={async install(e,t){let r=t.scope??"user",n=e.catalogId?he.getAdapter(e.catalogId):void 0,o=mn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await It(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!le__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(le__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=Co();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=c.status==="ok"?c.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=jo(m,u);return js({...d,hooks:p}),await Vl(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Et.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await vt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},wi=class{id="claude-code";name="Claude Code";async isAvailable(){return pn("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Dp,plugin:Dp,skill:Op("skill"),mcp:Op("mcp"),agent:ub,hook:pb,rule:db}};function Si(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}var fb=new Set(["gh"]),gb=Si(fb,"use: gh copilot mcp remove <name>"),xi=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await pn("gh",["--version"])?pn("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:gb}};We();var hb=new Set(["opencode"]),yb=Si(hb,"use: opencode config remove mcp <name>");function wb(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(`
|
|
122
|
+
`)}function Bp(){return {async install(e,t){try{it(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?he.getAdapter(e.catalogId):void 0,n=mn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await It(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=ws(t.scope??"user"),a=join(s,".opencode","plugins");if(le__default.existsSync(a)){let l=le__default.readdirSync(a).filter(u=>u.endsWith(".js")||u.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};le__default.mkdirSync(i,{recursive:!0}),le__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);le__default.existsSync(l)&&le__default.rmSync(l,{recursive:!0,force:!0}),le__default.mkdirSync(l,{recursive:!0}),le__default.cpSync(s,l,{recursive:!0}),le__default.mkdirSync(i,{recursive:!0}),le__default.writeFileSync(join(i,`${e.name}.js`),wb(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(s){return {success:false,message:s instanceof Error?s.message:String(s)}}finally{o&&await vt(o).catch(()=>{});}},async uninstall(e,t){it(e);let r=ws(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);le__default.existsSync(n)&&le__default.rmSync(n,{force:true}),le__default.existsSync(o)&&le__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(ws(t),`${e}.js`)}}}var bi=class{id="opencode";name="OpenCode";async isAvailable(){return pn("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:yb,skill:Bp(),bundle:Bp()}};var Vt=new li;Vt.register(new wi);kr()&&(Vt.register(new xi),Vt.register(new bi));function Fp({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,u]=useState([]),[c,d]=useState(void 0);useEffect(()=>{Vt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(f=>{f==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(f=>{if(f==="Cancel"){a(false);return}let w=l.find(E=>E.name===f);w?(d(w.id),a(false),s(true)):a(false);},[l]),g=useCallback(f=>{let w=Bd(f);w?r(w,c):s(false);},[r,c]),h=useCallback(()=>{s(false);},[]);if(i){let f=[...l.map(w=>w.name),"Cancel"];return jsx(st,{itemName:`${e} \u2014 Choose provider`,actions:f,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(st,{itemName:`${e} \u2014 Choose scope`,actions:Ud,descriptions:Nd,onAction:g,onClose:h},"scope"):jsx(st,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}N();function Kp({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(g=>g.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(g=>g.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((g,h)=>{h.upArrow?a(f=>Math.max(0,f-1)):h.downArrow?a(f=>Math.min(d.length-1,f+1)):h.return?d[i]==="Confirm Install"?n():o():h.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(g=>{g==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(g=>{let h=y(g.name??g.flowId),f=g.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:h}),jsxs(Text,{dimColor:true,children:["(",f,")"]})]},g.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((g,h)=>jsx(Box,{children:jsxs(Text,{bold:h===i,color:h===i?"cyan":void 0,children:[h===i?"\u203A ":" ",g]})},g))})]}):jsx(st,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Ei({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}N();function Gp({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Ei({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(st,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:f=>{f==="Uninstall"?c():f===d?i(t):f.startsWith("Update")?a?.():l();},onClose:l})}function zp({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Ei({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(st,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}$();var qn=x("bundle:installer"),Xp=/already exists/i;async function Tb(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Cp(t)){let r=await kp(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Xp.test(n))return;throw new Error(n)}}else {let r=await Ko(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Xp.test(n))return;throw new Error(n)}}}async function Cb(e,t){try{await P(v.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){qn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function kb(e,t,r){try{await P(v.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){qn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function qp(e,t,r,n){try{await P(v.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){qn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function Ab(e,t,r,n,o){try{await P(v.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){qn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Ci(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(p=>p.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await Cb(i,o.length);let l=[],u=0,c=o.length;for(let[p,g]of o.entries()){let h=g.name??g.flowId,f=g.type??"unknown";if(!g.type){qn.warn(`Artifact "${h}" has no type \u2014 treated as failed`),l.push({name:h,type:f,reason:"unknown artifact type"}),await qp(i,h,f,"unknown artifact type"),r?.({index:p+1,total:c,artifact:g,success:false,error:"unknown artifact type"});continue}try{await Tb(g),u++,await kb(i,h,f),r?.({index:p+1,total:c,artifact:g,success:!0});}catch(w){let E=w instanceof Error?w.message:String(w);qn.error(`Failed to install artifact "${h}": ${E}`),l.push({name:h,type:f,reason:E}),await qp(i,h,f,E),r?.({index:p+1,total:c,artifact:g,success:false,error:E});}}let d=Date.now()-a,m=l.length;return await Ab(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}N();function em({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Ci(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",u=e.artifact.artifacts,c=u.filter(d=>d.available);s({bundleTitle:e.title,total:u.length,installed:0,skipped:u.length-c.length,failed:c.length,failures:c.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Qp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Qp,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var xe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:pe()})}));N();function tm({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,u=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),u&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",_t(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}N();function rm({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",g=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${_t(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:g.map((h,f)=>{let w=f===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:h.danger?"yellow":void 0,dimColor:!w,children:h.label})]},h.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function nm(e){return e.adapter.removable!==false?4:2}F();N();function om({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function im({item:e,isSelected:t,isInstalled:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:t?"\u203A ":" "}),jsx(Text,{color:r?"green":void 0,bold:t,children:e.name}),r&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function am({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(C=>r.has(`${C.name}@${o}`)),i=t.filter(C=>!r.has(`${C.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((C,R)=>{if(R.escape){n();return}if(R.return){d(a[l]??null);return}if(R.upArrow){u(O=>Math.max(0,O-1));return}R.downArrow&&u(O=>Math.min(a.length-1,O+1));},{isActive:c===null}),c!==null)return jsx(om,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(tt/2)),p=Math.min(a.length,m+tt);p===a.length&&(m=Math.max(0,p-tt));let g=a.slice(m,p),h=m,f=a.length-p,w=s.length>0&&m<s.length,E=p>s.length,_=g.filter(C=>r.has(`${C.name}@${o}`)),D=g.filter(C=>!r.has(`${C.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2191 ${h} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),_.map(C=>jsx(im,{item:C,isSelected:a.indexOf(C)===l,isInstalled:true},C.name))]}),E&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),D.map(C=>jsx(im,{item:C,isSelected:a.indexOf(C)===l,isInstalled:false},C.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:f>0?`\u2193 ${f} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}xl();var Ob=/^https?:\/\/.+/;function Ub(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Nb(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function dm(e){let t=S(f=>f.showNotification),r=S(f=>f.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),g=useCallback(()=>{o("idle");},[]),h=useCallback(async()=>{let f=m.current,w=d.current;if(!Ob.test(f)){c("URL must start with http:// or https://");return}c(null),o("adding");let E=randomUUID(),_=new Vn(E,w,f);try{await _.fetchItems(),await rr.add({id:E,name:w,source:f}),he.register(new Vn(E,w,f)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(D){let C=Ub(D)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Nb(D)?D.message:D instanceof Error?`Could not reach catalog URL: ${D.message}`:"Failed to validate catalog URL";t(C,"error"),o("add-url");}},[e,t,r]);return useInput((f,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}f&&!w.ctrl&&!w.meta&&(d.current=d.current+f,i(d.current));},{isActive:n==="add-name"}),useInput((f,w)=>{if(w.escape){o("add-name");return}if(w.return){h();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}f&&!w.ctrl&&!w.meta&&(m.current=m.current+f,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:g}}function pm(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await rr.remove(o),he.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function fm(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=xe(A=>A.installedItems),[o,s]=useState(()=>he.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[g,h]=useState("main"),f=useRef(o);useEffect(()=>{f.current=o;},[o]),useEffect(()=>{g==="browse"&&!o[i-1]&&h("main");},[g,o,i]);let w=useCallback(()=>{(async()=>{let A=he.listAdapters(),j=await rr.read(),J=new Map(j.map(De=>[De.id,De]));s(A.map(De=>({adapter:De,stored:J.get(De.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=f.current[i-1];if(!A)return;let j=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(J=>{j||p({items:J,loading:false,error:null});}).catch(J=>{j||p({items:[],loading:false,error:J instanceof Error?J.message:"Failed to load catalog"});}),()=>{j=true;}},[i]);let E=dm(w),_=useCallback(()=>{w(),a(0),u("list"),p(null),h("main");},[w]),{handleRemove:D}=pm(_),C=useCallback(async A=>{h("removing"),await D(A);},[D]),R=useCallback(async A=>{try{let j=await A.adapter.fetchItems();if(p({items:j,loading:!1,error:null}),A.stored){let J=new Date().toISOString();await rr.updateField(A.stored.id,{lastUpdated:J}),w();}r("Marketplace updated","success");}catch(j){r(j instanceof Error?j.message:"Update failed","error");}},[w,r]),O=useCallback(async A=>{if(!A.stored)return;let j=A.stored.autoUpdate!==false;await rr.updateField(A.stored.id,{autoUpdate:!j}),w();},[w]),U=useCallback(()=>h("browse"),[]),oe=useCallback(A=>{let j=o[i-1];if(!j)return;let J=j.adapter.removable!==false;[U,()=>{R(j);},...J?[()=>{O(j);},()=>{C(j.adapter.id);}]:[]][A]?.();},[o,i,U,R,O,C]),k=useCallback(()=>h("main"),[]),H=useCallback(()=>{let A=o[i-1];A&&R(A);},[o,i,R]),re=useCallback(()=>{let A=o[i-1];A&&O(A);},[o,i,O]),K=useCallback(()=>{let A=o[i-1];A&&C(A.adapter.id);},[o,i,C]);if(useInput((A,j)=>{if(j.upArrow){a(J=>Math.max(0,J-1));return}if(j.downArrow){a(J=>Math.min(o.length,J+1));return}(j.return||j.tab)&&(i===0?E.startAdd():(u("detail"),d(0)));},{isActive:g==="main"&&E.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,j)=>{if(j.escape||j.tab){u("list");return}if(j.upArrow){d(J=>Math.max(0,J-1));return}if(j.downArrow){let J=o[i-1],De=J?nm(J)-1:0;d(ms=>Math.min(ms+1,De));return}j.return&&oe(c);},{isActive:g==="main"&&E.phase==="idle"&&l==="detail"&&e==="marketplaces"}),E.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:E.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),E.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(E.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:E.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:E.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),E.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:E.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(E.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(g==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(g==="browse"){let A=o[i-1];if(!A)return jsx(Box,{});let j=A.adapter.id??"default",J=new Set(n.filter(De=>De.marketplace===A.adapter.name).map(De=>`${De.name}@${j}`));return jsx(am,{entry:A,items:m?.items??[],installedKeys:J,onBack:k})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let V=o[i-1]??null,Y=V?n.filter(A=>A.marketplace===V.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(tm,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&V?jsx(rm,{entry:V,detailData:m,installedCount:Y,focusPanel:l,actionIndex:c,onBrowse:U,onUpdate:H,onToggleAutoUpdate:re,onRemove:K}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:V?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:l==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function gm(e,t,r,n){if(t.upArrow)return r.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:r.selectedIndex-1}];if(t.downArrow&&r.selectedIndex<n-1)return [{type:"setSelectedIndex",index:r.selectedIndex+1}];if(t.leftArrow){let o=ie.findIndex(i=>i.id===r.activeTab),s=ie[(o-1+ie.length)%ie.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=ie.findIndex(i=>i.id===r.activeTab),s=ie[(o+1)%ie.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=ie.findIndex(i=>i.id===r.activeTab),s=ie[(o+1)%ie.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="8"?[{type:"toggleTypeFilter",catalogType:"agent"}]:e==="9"?[{type:"toggleTypeFilter",catalogType:"hook"}]:e==="0"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="a"&&r.activeTab==="updates"?[]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function hm(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function ym(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var Vb=new Set(ie.filter(e=>e.focus!=="list").map(e=>e.focus));function Zo(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:u}=Xe.getState();i(a.slice(0,u)+s.char+a.slice(u)),l(u+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function wm({listLength:e}){let t=S(h=>h.focus),r=S(h=>h.selectedIndex),n=S(h=>h.actionMenuOpen),o=S(h=>h.setFocus),s=S(h=>h.setActionMenuOpen),i=Xe(h=>h.query),a=Xe(h=>h.setQuery),l=Xe(h=>h.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:h,setCursorPosition:f}=Xe.getState();f(h.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let h=setTimeout(()=>d(i),300);return ()=>clearTimeout(h)},[i]),useInput((h,f)=>{let{activeTab:w,selectedIndex:E,actionMenuOpen:_}=S.getState();Zo(sl(h,f,{activeTab:w}));},{isActive:t==="tabs"}),useInput((h,f)=>{if(!f.leftArrow&&!f.rightArrow)return;let{activeTab:w,selectedIndex:E,actionMenuOpen:_}=S.getState();Zo(sl("",f,{activeTab:w}));},{isActive:Vb.has(t)}),useInput((h,f)=>{let{activeTab:w,selectedIndex:E,actionMenuOpen:_}=S.getState();Zo(gm(h,f,{activeTab:w,selectedIndex:E},u.current));},{isActive:t==="list"}),useInput((h,f)=>{Zo(hm(h,f));},{isActive:t==="actionMenu"}),useInput((h,f)=>{let w=ym(h,f,Xe.getState().query),E=w.queryUpdate;if(Zo(w.actions),E==="reset")l(),d("");else if(E!==null){let{query:_,cursorPosition:D,setCursorPosition:C}=Xe.getState();if("backspace"in E)D>0&&(a(_.slice(0,D-1)+_.slice(D)),C(D-1));else if("append"in E)a(_.slice(0,D)+E.append+_.slice(D)),C(D+E.append.length);else if("cursorMove"in E){let R=D+E.cursorMove;R>=0&&R<=_.length&&C(R);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(h=>{let{setSelectedIndex:f,selectedIndex:w}=S.getState();h===0?f(0):w>=h&&f(h-1);},[]),g=useCallback(h=>{if(!c)return u.current=h.length,h;let f=c.toLowerCase(),w=h.filter(E=>E.name.toLowerCase().includes(f)||E.description?.toLowerCase().includes(f));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:g}}function xm(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=nt(a=>a.justAuthenticated),o=nt(a=>a.credentials),s=nt(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function Ve(e,t,r=false){return r?true:!zl.valid(e)||!zl.valid(t)?false:zl.gt(t,e)}F();$();var ar=x("updater");async function Hb(e,t,r,n,o,s){try{await P(v.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:Q().interfaceType});}catch(i){ar.warn(`Failed to send update metrics: ${String(i)}`);}}function Gb(e,t){let r=Pe(),n=process.cwd();for(let o of yr){let s=`${e}@${o}`,i=r.plugins[s];if(i&&i.length>0){let a=Ml(i,t,n);if(a)return {pluginKey:s,entry:a}}}return null}async function Ri(e,t={}){let r=Date.now(),n=null;try{ar.debug(`[${e}] Acquiring lock...`),n=await or();let o=Gb(e,t.scope);if(!o)throw ar.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{pluginKey:s,entry:i}=o,a=i.version,l=i.installPath,u=s.slice(s.lastIndexOf("@")+1);ar.debug(`[${e}] Fetching manifest...`);let d=(await Hn(e,t.source??u)).version;if(!a||!Ve(a,d,t.force))throw l&&await gi(l,i.scope),ar.debug(`[${e}] Already up to date (v${a??"n/a"})`),new Lr(e,a??"unknown");ar.info(`[${e}] Updating v${a} \u2192 v${d}...`),await n(),n=null;try{let m=await je(e,{force:!0,skipMetrics:!0,source:t.source??u,scope:i.scope}),p=Date.now()-r;return await Hb(m.name,a,m.version,p,i.origin??"internal",i.type??"skill"),ar.debug(`[${e}] Updated successfully in ${p}ms`),{name:m.name,previousVersion:a,newVersion:m.version,path:m.path,duration_ms:p}}catch(m){ar.warn(`[${e}] Install failed, rolling back to v${a}...`),n=await or();let p=Pe(),g=p.plugins[s]?.find(h=>h.scope===i.scope&&h.projectPath===i.projectPath);throw g&&(g.version=a,g.installPath=l,at(p),ar.info(`[${e}] Rollback completed, restored to v${a}`)),m}}finally{n&&await n();}}Dr();$();var Mi=x("dispatcher");async function Jb(e,t,r,n,o){let s=Fn(e);return Mi.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await yi(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Mi.debug(`[${e}] Retrying install after marketplace add`),_e(t)}async function bm(e,t,r,n){let o=jn(e,n),s=Fn(e);r?.onStatus?.(`Installing ${s}...`),Mi.debug(`[${e}] Attempting install: ${o}`);let i=await _e(o);if(i.exitCode===0)return i;Mi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Jb(e,o,a,t,r)}async function Im(e,t,r){let n=e.type??"bundle",o=await Vt.getAvailableProviders(n),s=o[0];if(!s)throw new Error(`No available provider for artifact type "${n}"`);let i=s.installers[n];if(!i)throw new Error(`Provider "${s.id}" does not support type "${n}"`);let a=t??{},l=a;return i.install(e,l)}function vm(){let e=xe(i=>i.installedItems),t=xe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Im(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=pe().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Vt.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",m=c.installers[d];if(!m)throw new Error(`Provider "${u}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await Fo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await Ri(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}N();$();var Li=x("mcp");function Qo(e,t){e.silent?Re({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):I(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Pm(e,t){e.silent?ne({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(z(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&b(t.stdout));}function Wb(e,t,r,n){let o=["claude","mcp","add","--transport",r,e];return t.length>0&&o.push(...t),n&&o.push("--scope",n),o.join(" ")}function Xl(e,t){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function Tm(e,t,r){if(!await X())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Qo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Li.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Wb(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await q(`Install external MCP "${s}"?
|
|
123
123
|
This will run: ${i}
|
|
124
|
-
[y/N] `))return
|
|
124
|
+
[y/N] `))return Li.debug(`[${e}] Installation cancelled by user`),b("Operation cancelled."),0}let o=r.silent?void 0:ea({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await _e(n);return o?.stop(),s.exitCode!==0?(Qo(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&b(`stdout: ${s.stdout}`),1):(Pm(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),Qo(r,{name:e,action:"add",message:ee(s)}),1}}async function Cm(e,t){if(!await X())return 1;Li.debug(`[${e}] Starting MCP remove`);let r=Xl(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await q(`Remove MCP "${o}"?
|
|
125
125
|
This will run: ${s}
|
|
126
|
-
[y/N] `))return Ni.debug(`[${e}] Removal cancelled by user`),b("Operation cancelled."),0}let n=t.silent?void 0:oa({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await _e(r);return n?.stop(),o.exitCode!==0?(rs(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&b(`stdout: ${o.stdout}`),1):(km(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),rs(t,{name:e,action:"remove",message:ee(o)}),1}}R();function $m({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(C=>C.setLoading),u=S(C=>C.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=Tm(),f=async(C,$,O)=>{l(true,C),n();try{await $(),o(r.length),s(O,"success");}catch(U){let oe=U instanceof Error?U.message:"Something went wrong";i.error(`[withLoading] ${C} failed: ${oe}`),s(oe,"error");}finally{l(false);}};return {handleInstall:(C,$)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:C,...$!==void 0?{providerId:$}:{},onDownloadProgress:(O,U)=>{let oe=Date.now();(oe-a.current>100||O>=U)&&(a.current=oe,u(O,U));}}),"\u2713 Installed successfully"));},handleUninstall:C=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,C),"\u2713 Uninstalled");},handleToggleStatus:C=>{if(!e)return;let $=e.status==="enabled";f($?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,C),$?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let C=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${C}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${C}`,"success");}catch(O){if(O instanceof Dr)s(O.message,"info");else {let U=O instanceof Error?O.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${U}`),s(U,"error");}}finally{l(false);}})();},handleBatchUpdate:C=>{if(C.length===0)return;let $=C.length;(async()=>{l(true,`Updating ${$} plugin${$>1?"s":""}...`),n();try{let U=[];for(let H of C)U.push(await p(H.name).then(()=>({status:"fulfilled",value:void 0}),re=>({status:"rejected",reason:re})));let oe=U.filter(H=>H.status==="fulfilled").length,k=U.map((H,re)=>H.status==="rejected"?C[re].name:null).filter(H=>H!==null);o(r.length),k.length===0?s(`\u2713 Updated ${oe}/${$} plugin${$>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${oe}/${$}; failed: ${k.join(", ")}`,oe>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:C=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let $=ec(e.name,C),O=await _e($);if(O.exitCode!==0)throw new Error(O.stderr||"MCP removal failed");xe.getState().loadFromDisk();},"\u2713 MCP removed");}}}Oo();R();var ns=x("api:bundle"),oo=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},os=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Zb=/^[a-zA-Z0-9_-]{1,128}$/;async function _m(e,t){if(e instanceof HTTPError){let r=e.response.status;throw ns.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new oo(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new os:new Error(`Server error (${r}) \u2014 please try again later.`)}throw ns.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Lm(e){if(!Zb.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);ns.debug(`Fetching bundle by flowId "${e}"`);try{return await Kt().get(`v1/use-cases/${t}`).json()}catch(r){return _m(r,e)}}async function Bi(e){let t=encodeURIComponent(e);ns.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Kt().get(`v1/use-cases/by-name/${t}`).json(),ns.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return _m(n,e)}if(r.length===0)throw new oo(e);return r[0]}R();var Qb=x("tui:bundle-flow");function Dm({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();Qb.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Lm(d):Bi(a)).then(p=>{u(false),S.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{u(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),xe.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}N();F();var ss=["local","project","user"];function tI(e){let t=Te__default.homedir();return e===t||e.startsWith(t+"/")?`~${e.slice(t.length)}`:e}function Om(e){return tI(e.projectPath??e.installPath)}var rI=new Set(["--transport","--scope","-s"]);function Um(e){let t=e.split(/\s+/).filter(Boolean),r=t.indexOf("add");if(r===-1)return null;let n=r+1;for(;n<t.length;){let o=t[n];if(rI.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function yn(e,t){return t?`${e}::${t}`:e}function tc(e){return e===Oe?go:xn}function Nm(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??go,flowId:e.flowId}}function rc(e,t){let r=tc(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function Bm(e){let t=new Map;for(let r of e){if(!r.scope)continue;let n=t.get(r.scope)??[];n.push(r),t.set(r.scope,n);}return ss.filter(r=>t.has(r)).map(r=>({scope:r,label:_t[r].label,pathHint:_t[r].pathHint,items:t.get(r)??[]}))}function Fm(e){let t=r=>{if(!r)return 1/0;let n=ss.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function jm({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>yn(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(g=>[yn(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(yn(g.name,g.author?.name))??h.get(g.name),E=w?.version,_=!!E&&!!g.version&&He(g.version,E);return {...g,updateAvailable:_,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(yn(f.name,f.author?.name)))return false;if(f.type==="mcp"){let h=f.installCommand?Um(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||h&&i.has(h))return false}return true}).map(f=>Nm(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>rc(f,f.catalogItem)):a.map(f=>rc(f,f.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(f=>{let h=f.type??"bundle";if(!n.types.has(h))return false;let g=f.origin??"internal";return n.origins.has(g)}),[l,n]),c=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let f=new Map(e.map(g=>[yn(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(yn(g.name,g.authorName))??h.get(g.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function nc(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),u=S(d=>d.catalogVersion),c=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await ip();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,P(v.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c,u]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:c}}function Km(){return {items:xe(t=>t.installedItems)}}R();var aI=x("catalog");function Hm(){let e=S(Z=>Z.bundleInstallFlow),t=S(Z=>Z.activeTab),r=S(Z=>Z.notification),n=S(Z=>Z.loading),o=S(Z=>Z.loadingMessage),s=S(Z=>Z.downloadProgress),i=S(Z=>Z.downloadTotal),a=S(Z=>Z.catalogError),l=S(Z=>Z.setCatalogError),u=S(Z=>Z.catalogFilters),c=Xe(Z=>Z.query),{catalog:d,isLoading:m,error:p,refetch:f}=nc(),{items:h}=Km(),g=xe(Z=>Z.loadFromDisk),{items:w,emptyMessage:E,getSelectedCatalogItem:_,outdatedCount:D}=jm({catalog:d,installedItems:h,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:C,closeMenu:$,selectedIndex:O,clampIndex:U,filteredItems:oe}=bm({listLength:w.length}),k=oe(w),H=useMemo(()=>t!=="installed"&&t!=="updates"?k:Fm(k),[t,k]),re=useMemo(()=>t==="installed"||t==="updates"?Bm(H):[],[t,H]),K=H[O]??null,V=useMemo(()=>_(K),[_,K]),{notify:Y}=vm(),{handleInstall:A,handleUninstall:j,handleToggleStatus:J,handleUpdate:De,handleBatchUpdate:hs,handleMcpConfigUninstall:Kh}=$m({selectedItem:K,selectedCatalogItem:V,items:w,closeMenu:$,clampIndex:U,notify:Y}),{handleBundleInstallStart:Vh,handleBundleDetailConfirm:Hh,handleBundleDetailBack:Gh,handleBundleInstallComplete:Jh}=Dm({closeMenu:$,notify:Y}),Wh=useCallback(()=>hs(H),[hs,H]);return useEffect(()=>{g();},[]),useEffect(()=>{U(H.length);},[H.length,U]),useEffect(()=>{p&&(aI.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),l("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Un,{}),jsx(gd,{outdatedCount:D}),t==="marketplaces"&&Ar()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(ym,{})}):jsx(_d,{filteredItems:H,groups:re,emptyMessage:E,onBatchUpdate:Wh}),(n||m)&&jsxs(Fragment,{children:[jsx(ii,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(li,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(ci,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(Ld,{message:r.message,type:r.type}),C&&K&&(t==="discover"?V?.type==="bundle"?e?.phase==="installing"?jsx(nm,{bundle:e.bundle,onComplete:Jh}):jsx(Gp,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>Vh(K.name,K.flowId),onConfirm:Hh,onClose:e?.phase==="detail"?Gh:$}):jsx(Vp,{itemName:K.name,itemType:V?.type,onInstall:A,onClose:$}):K.type==="mcp"?jsx(Yp,{itemName:K.name,itemScope:K.scope??"user",onUninstall:Kh,onClose:$}):jsx(zp,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:V?.version,onUninstall:j,onToggleStatus:Z=>J(Z),onUpdate:De,onClose:$})),jsx(si,{})]})}var M=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(xe.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Ce();var pI=3;function Jm(){let e=M(c=>c.setStarterKits),t=M(c=>c.setIsLoadingStarterKits),r=M(c=>c.setStarterKitsError),n=M(c=>c.setPluginStatus),o=M(c=>c.setPluginDownloadProgress),s=M(c=>c.setStep),i=M(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await hi();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{xe.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=M.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){n(m.name,"installing"),l.current=0;let p="",f=false;for(let h=1;h<=pI;h++)try{await Ke(m.name,{onDownloadProgress:(g,w)=>{let E=Date.now();(E-l.current>100||g>=w)&&(l.current=E,o(m.name,g,w));}}),n(m.name,"success"),f=!0;break}catch(g){if(g instanceof qe){n(m.name,"success"),f=true;break}p=g instanceof Error?g.message:"Unknown error";}f||(n(m.name,"failed",p),P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:Q().interfaceType}).catch(()=>{}));}let d=en();Qr("summary_review"),P(v.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),xe.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var is={cursorDelta:0,confirm:false,back:false};function Wm(e,t){return t.upArrow?{...is,cursorDelta:-1}:t.downArrow?{...is,cursorDelta:1}:t.escape?{...is,back:true}:t.return?{...is,confirm:true}:is}var mI={cursorDelta:0,select:false};function zm(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:mI}N();var Xm=Hw.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var uc=5;function qm({onRetry:e}){let t=M(c=>c.starterKits),r=M(c=>c.selectedStarterKitIndex),n=M(c=>c.isLoadingStarterKits),o=M(c=>c.starterKitsError);if(n)return jsx(ii,{message:"Loading Starter Kits..."});if(o)return jsx(ci,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Nn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(uc/2)),i=Math.min(t.length,s+uc);i===t.length&&(s=Math.max(0,i-uc));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Xm,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}N();var Zm=Hw.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});N();var mc=8;function Qm(){let e=M(c=>c.selectedStarterKit),t=M(c=>c.plugins),r=M(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,P(v.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(c=>c.installed).length,s=Math.max(0,r-Math.floor(mc/2)),i=Math.min(t.length,s+mc);i===t.length&&(s=Math.max(0,i-mc));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Zm,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}N();var II=["Retry failed","Continue anyway"];function ef({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=y(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(rm$1,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(li,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function tf({onComplete:e,onRetry:t}){let r=M(u=>u.plugins),n=M(u=>u.step),o=M(u=>u.successCount),s=M(u=>u.failedCount),i=M(u=>u.summaryActionIndex),a=r.filter(u=>u.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let u=setTimeout(e,1500);return ()=>clearTimeout(u)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(u=>jsx(ef,{name:u.name,status:u.status,error:u.error,downloadProgress:u.downloadProgress,downloadTotal:u.downloadTotal},u.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(u=>u.status==="failed").map(u=>jsx(ef,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:II.map((u,c)=>jsx(Box,{children:jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",u]})},u))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function rf(){let e=M(k=>k.step),t=M(k=>k.starterKits),r=M(k=>k.selectedStarterKitIndex),n=M(k=>k.setSelectedStarterKitIndex),o=M(k=>k.selectStarterKit),s=M(k=>k.plugins),i=M(k=>k.pluginCursorIndex),a=M(k=>k.setPluginCursorIndex),l=M(k=>k.setStep),u=M(k=>k.summaryActionIndex),c=M(k=>k.setSummaryActionIndex),d=M(k=>k.failedCount),m=M(k=>k.resetForRetry),p=M(k=>k.goBackToList),f=S(k=>k.setScreen),h=S(k=>k.setFocus),g=S(k=>k.focus),w=nt(k=>k.setJustAuthenticated),E=nt(k=>k.justAuthenticated),{loadStarterKits:_,installSelected:D}=Jm(),C=useRef(false);useEffect(()=>{e==="starterKitList"?(h("starterKitList"),C.current||(C.current=true,Qr("bundle_selection"))):h(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,h]);let $=useCallback(async()=>{let k=M.getState().selectedStarterKit;if(k){let re=await te();re&&await Er({...re,starterKit:k.slug});}P(v.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:en()}).catch(()=>{});let{successCount:H}=M.getState();P(v.CLI_ONBOARDING_COMPLETED,{duration_ms:Tr(),tools_installed_count:H}).catch(()=>{}),w(false),h("verify"),f("verify");},[w,h,f]),O=useCallback(()=>{m(),D();},[m,D]),U=useCallback(()=>{_();},[_]),oe=useCallback(()=>{h("verify"),f("verify");},[h,f]);return useInput((k,H)=>{if(H.escape)Ks("esc"),oe();else if(H.upArrow&&r>0)n(r-1);else if(H.downArrow&&r<t.length-1)n(r+1);else if(H.return&&t.length>0){let re=en();o(t[r]),Qr("kit_display"),P(v.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:re}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((k,H)=>{let re=Wm(k,H);if(re.cursorDelta!==0){let K=i+re.cursorDelta;K>=0&&K<s.length&&a(K);}if(re.confirm){let K=M.getState().selectedStarterKit;K&&(async()=>(await te())?.starterKit!==K.slug&&P(v.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let V=en();Qr("kit_confirmation"),P(v.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:V}).catch(()=>{});let Y=en();Qr("tool_installation"),P(v.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Y}).catch(()=>{}),l("installing"),D();}if(re.back){let K=M.getState().selectedStarterKit;K&&P(v.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((k,H)=>{if(d===0)return;let re=zm(k,H);if(re.cursorDelta!==0){let K=u+re.cursorDelta;K>=0&&K<=1&&c(K);}re.select&&(u===0?O():$());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Un,{}),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."}),!E&&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(qm,{onRetry:U}),e==="starterKitDetail"&&jsx(Qm,{}),(e==="installing"||e==="summary")&&jsx(tf,{onComplete:$,onRetry:O})]}),jsx(si,{})]})}F();var sf=null;function af(){return sf}async function Wi(){let t=sn().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=pe.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await lf(n);(o||s)&&await St({...r,installedVersion:o,installMethod:s});}}async function lf(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await jt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function io(e){let t=await Promise.all(e.map(r=>PI(r)));return sf=t,t}async function PI(e){let t=nf(e.versionCommand);t==="permission-denied"&&(TI(e.versionCommand[0]),t=nf(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await jt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!ot(e.alias)){let{installedVersion:l,installMethod:u}=await lf(e);await St({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function nf(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function TI(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=le__default.realpathSync(r),{mode:o}=le__default.statSync(n);le__default.chmodSync(n,o|73);}catch{}}function AI(e){return e.filter(t=>t.module.platforms[process.platform]?.status==="supported").filter(t=>!t.alreadyInstalled).map(t=>({module:t.module,alreadyInstalled:t.alreadyInstalled,checked:!t.alreadyInstalled&&(t.availableStrategies.length>0||t.module.required===true),selectedStrategy:t.availableStrategies[0]??null,availableStrategies:t.availableStrategies}))}function mf(e,t){let[r,n]=useState(()=>AI(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),u=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,h=m.upArrow||d==="[A",g=m.downArrow||d==="[B";if(h||g)h&&p>0?s(p-1):g&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let E=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),_=w.availableStrategies[(E+1)%w.availableStrategies.length];n(D=>D.map(C=>C.module.alias===w.module.alias?{...C,selectedStrategy:_}:C));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}N();function gf({probeResults:e,onConfirm:t}){let r=S(p=>p.focus),n=S(p=>p.actionMenuOpen),o=S(p=>p.setActionMenuOpen),s=S(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=mf(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let h=f===a,g=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",g," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:h?"cyan":void 0,children:[h?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",g]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(st,{itemName:m,actions:d,onAction:c,onClose:u})]})}var LI=/^https?:\/\/.+/;function hf({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||u.return){e(null);return}}if(t==="input"){if(u.escape){a.current="",o(""),r("confirm");return}if(u.return){let c=a.current.trim();c.length>0&&LI.test(c)?(i(false),e(c)):c.length>0&&i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function OI(e){let t=e.module.platforms[process.platform];return (t?.status==="supported"?t.strategies:[]).map(n=>n.type==="npm"?`npm install -g ${n.package}`:n.type==="homebrew"?`brew install ${n.formula}`:"curl (see docs)").join(" or ")}function Sf(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(f=>f.alias===d?{...f,...m}:f));},[]),a=useCallback(async()=>{for(let d of e){let m=OI(d);if(!d.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";i(d.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}i(d.module.alias,{status:"installing"});try{let p=await Mr(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}F();N();function xf({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(rm$1,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:y(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function Ef({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=Sf(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{an().catch(()=>{}),n("list");let w=me().some(E=>E.name===ge);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,c,p]),useInput((w,E)=>{E.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,h=a-f,g=[];return h>0&&g.push(jsxs(Text,{color:"green",children:[h," installed"]},"i")),f>0&&g.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&g.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&g.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(xf,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,E,_)=>(_>0&&w.push(jsx(Text,{children:" | "},`sep-${_}`)),w.push(E),w),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Tf(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),u=S(p=>p.setScreen),c=useCallback(p=>{if(qu(p)){an().catch(()=>{}),l("list");let h=me().some(g=>g.name===ge);u(h?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=af();if(p){c(p);return}io(pe).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let f=p.some(h=>h.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(gf,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(hf,{onConfirm:m}),e==="installation"&&jsx(Ef,{confirmedItems:o,customUrl:i})]})}F();R();var JI=x("ClaudeMdSuggestion"),WI=[`Install ${ge}`,"Skip for now"],zI=["Retry","Skip for now"];function Af(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=M(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{P(v.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,P(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await Ke(ge),o("installed");}catch(m){if(m instanceof qe){o("installed");return}JI.warn(`Failed to install ${ge}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?zI:WI;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),c()):u());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Un,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(kf,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(rm$1,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ge,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ge," 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:["/",ge]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",ge]}),jsx(kf,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function kf({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var ZI=promisify(execFile),Zi="@ciandt-flow/cli";async function Rf(){let e=he;if(Ql.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Zi};try{let t=await fetch(`https://registry.npmjs.org/${Zi}/latest`);if(!t.ok)throw new Error(`Registry returned ${t.status}`);let n=(await t.json()).version;return {currentVersion:e,latestVersion:n,isOutdated:n!==e,packageName:Zi}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Zi}}}async function Qi(e){try{return await ZI(tr(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function QI(e){let t=ot(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await jt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await St({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function $f(e){let t=await QI(e),r=null,n=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:n});if(!s.ok)throw new Error(`Registry returned ${s.status}`);r=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:n});if(!s.ok)throw new Error(`GitHub returned ${s.status}`);r=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=t!==null&&r!==null&&t!==r;return {moduleAlias:e.alias,currentVersion:t,latestVersion:r,isOutdated:o}}async function Mf(e,t){let r=ot(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await jt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await St({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function _f(e){let r=ot(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function Lf(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...pe.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([Rf(),io(pe),Promise.all(pe.map(l=>$f(l)))]);if(Wi(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Qi(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(u=>({...u,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(u=>({...u,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let u=pe.find(d=>d.alias===l.moduleAlias);if(!u)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let c=await Mf(u,l);c.success?r(l.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:_f(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await an(),t(l=>({...l,outcome:"done"}));}catch{await an(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}F();function sv({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(rm$1,{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 iv({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 Df(){let{outcome:e,items:t}=Lf(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=me().some(i=>i.name===ge);r(s?"main":"claudeMdSuggestion"),n("list");},1500);return ()=>clearTimeout(o)}if(e==="module-missing"){let o=setTimeout(()=>{r("moduleSetup"),n("moduleSetup");},500);return ()=>clearTimeout(o)}},[e,r,n]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:t.map(o=>jsx(sv,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(iv,{outcome:e})})]})}Ce();Mn();R();Ra();var uv={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Of=10;function Uf(){let[e,t]=useState(Aa());useEffect(()=>mu(()=>{t([...Aa()]);}),[]);let r=e.slice(-Of);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Of,") \u2014 press Ctrl+D to close"]}),r.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):r.map((n,o)=>jsxs(Text,{color:uv[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var fv=x("app"),gv={auth:ad,starterKitSetup:rf,moduleSetup:Tf,claudeMdSuggestion:Af,verify:Df,main:Hm};function Ff(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function ri(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function jf(){P(v.CLI_SESSION_STARTED,{cli_version:he,os:process.platform,node_version:process.version,duration_ms:Tr(),interface:"tui"}).catch(()=>{});}async function Vf(){let e=await te();if(e&&zu()&&await Pr()){e.customUrl&&Dt(e.customUrl);let{clientSecret:n,...o}=e;nt.getState().setCredentials(o),jf(),ri(e);return}if(!e){Ff();return}try{e.customUrl&&Dt(e.customUrl),await Ut();}catch(n){fv.debug(`Token validation failed: ${String(n)}`),Ff();return}jf();let{clientSecret:t,...r}=e;nt.getState().setCredentials(r),ri(e);}function Hf(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=gv[r],{pendingExit:o}=Bu(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let u=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!u);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(Uf,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}Ce();Fs();N();F();R();bo();Ce();async function Pc(e,t={}){let r=Gs({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Js(r),await Er(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var At=x("auth");function Jf(){ze.clearFallbackFile(),Os();}var hv=3,Gf=3,Wf=` \u2139 The data collected during setup is used solely to improve
|
|
126
|
+
[y/N] `))return Li.debug(`[${e}] Removal cancelled by user`),b("Operation cancelled."),0}let n=t.silent?void 0:ea({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await _e(r);return n?.stop(),o.exitCode!==0?(Qo(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&b(`stdout: ${o.stdout}`),1):(Pm(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Qo(t,{name:e,action:"remove",message:ee(o)}),1}}$();function km({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(C=>C.setLoading),u=S(C=>C.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=vm(),g=async(C,R,O)=>{l(true,C),n();try{await R(),o(r.length),s(O,"success");}catch(U){let oe=U instanceof Error?U.message:"Something went wrong";i.error(`[withLoading] ${C} failed: ${oe}`),s(oe,"error");}finally{l(false);}};return {handleInstall:(C,R)=>{e&&t&&(a.current=0,g(`Installing ${e.name}...`,()=>c(t,{scope:C,...R!==void 0?{providerId:R}:{},onDownloadProgress:(O,U)=>{let oe=Date.now();(oe-a.current>100||O>=U)&&(a.current=oe,u(O,U));}}),"\u2713 Installed successfully"));},handleUninstall:C=>{e&&g(`Uninstalling ${e.name}...`,()=>d(e.name,C),"\u2713 Uninstalled");},handleToggleStatus:C=>{if(!e)return;let R=e.status==="enabled";g(R?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,C),R?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let C=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${C}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${C}`,"success");}catch(O){if(O instanceof Lr)s(O.message,"info");else {let U=O instanceof Error?O.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${U}`),s(U,"error");}}finally{l(false);}})();},handleBatchUpdate:C=>{if(C.length===0)return;let R=C.length;(async()=>{l(true,`Updating ${R} plugin${R>1?"s":""}...`),n();try{let U=[];for(let H of C)U.push(await p(H.name).then(()=>({status:"fulfilled",value:void 0}),re=>({status:"rejected",reason:re})));let oe=U.filter(H=>H.status==="fulfilled").length,k=U.map((H,re)=>H.status==="rejected"?C[re].name:null).filter(H=>H!==null);o(r.length),k.length===0?s(`\u2713 Updated ${oe}/${R} plugin${R>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${oe}/${R}; failed: ${k.join(", ")}`,oe>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:C=>{e&&g(`Removing MCP ${e.name}...`,async()=>{let R=Xl(e.name,C),O=await _e(R);if(O.exitCode!==0)throw new Error(O.stderr||"MCP removal failed");xe.getState().loadFromDisk();},"\u2713 MCP removed");}}}_o();$();var es=x("api:bundle"),to=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},ts=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},qb=/^[a-zA-Z0-9_-]{1,128}$/;async function $m(e,t){if(e instanceof HTTPError){let r=e.response.status;throw es.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new to(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new ts:new Error(`Server error (${r}) \u2014 please try again later.`)}throw es.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Rm(e){if(!qb.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);es.debug(`Fetching bundle by flowId "${e}"`);try{return await jt().get(`v1/use-cases/${t}`).json()}catch(r){return $m(r,e)}}async function Di(e){let t=encodeURIComponent(e);es.debug(`Fetching bundle by name "${e}"`);let r;try{r=await jt().get(`v1/use-cases/by-name/${t}`).json(),es.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return $m(n,e)}if(r.length===0)throw new to(e);return r[0]}$();var Yb=x("tui:bundle-flow");function Mm({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();Yb.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Rm(d):Di(a)).then(p=>{u(false),S.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{u(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),xe.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}N();F();var rs=["local","project","user"];function Qb(e){let t=$e__default.homedir();return e===t||e.startsWith(t+"/")?`~${e.slice(t.length)}`:e}function _m(e){return Qb(e.projectPath??e.installPath)}var eI=new Set(["--transport","--scope","-s"]);function Lm(e){let t=e.split(/\s+/).filter(Boolean),r=t.indexOf("add");if(r===-1)return null;let n=r+1;for(;n<t.length;){let o=t[n];if(eI.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function gn(e,t){return t?`${e}::${t}`:e}function ql(e){return e===Oe?po:wn}function Dm(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??po,flowId:e.flowId}}function Yl(e,t){let r=ql(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function Om(e){let t=new Map;for(let r of e){if(!r.scope)continue;let n=t.get(r.scope)??[];n.push(r),t.set(r.scope,n);}return rs.filter(r=>t.has(r)).map(r=>({scope:r,label:Mt[r].label,pathHint:Mt[r].pathHint,items:t.get(r)??[]}))}function Um(e){let t=r=>{if(!r)return 1/0;let n=rs.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Nm({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(g=>gn(g.name,g.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(g=>g.type==="mcp").map(g=>g.name.toLowerCase())),[t]),a=useMemo(()=>{let g=new Map(e.map(f=>[gn(f.name,f.author?.name),f])),h=new Map(e.map(f=>[f.name,f]));return t.map(f=>{let w=g.get(gn(f.name,f.author?.name))??h.get(f.name),E=w?.version,_=!!E&&!!f.version&&Ve(f.version,E);return {...f,updateAvailable:_,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(g=>{if(s.has(gn(g.name,g.author?.name)))return false;if(g.type==="mcp"){let h=g.installCommand?Lm(g.installCommand)?.toLowerCase():null;if(i.has(g.name.toLowerCase())||h&&i.has(h))return false}return true}).map(g=>Dm(g)):r==="updates"?a.filter(g=>g.updateAvailable).map(g=>Yl(g,g.catalogItem)):a.map(g=>Yl(g,g.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(g=>{let h=g.type??"bundle";if(!n.types.has(h))return false;let f=g.origin??"internal";return n.origins.has(f)}),[l,n]),c=useMemo(()=>{let{types:g}=n;if(g.size===1){if(g.has("skill"))return "skills";if(g.has("mcp"))return "MCPs";if(g.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let g=new Map(e.map(f=>[gn(f.name,f.author?.name),f])),h=new Map(e.map(f=>[f.name,f]));return f=>f?g.get(gn(f.name,f.authorName))??h.get(f.name)??null:null},[e]),p=useMemo(()=>a.filter(g=>g.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function Zl(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),u=S(d=>d.catalogVersion),c=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await tp();if(t(d),m.length>0){let p=m.map(g=>g.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,P(v.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c,u]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:c}}function Bm(){return {items:xe(t=>t.installedItems)}}$();var sI=x("catalog");function jm(){let e=S(Z=>Z.bundleInstallFlow),t=S(Z=>Z.activeTab),r=S(Z=>Z.notification),n=S(Z=>Z.loading),o=S(Z=>Z.loadingMessage),s=S(Z=>Z.downloadProgress),i=S(Z=>Z.downloadTotal),a=S(Z=>Z.catalogError),l=S(Z=>Z.setCatalogError),u=S(Z=>Z.catalogFilters),c=Xe(Z=>Z.query),{catalog:d,isLoading:m,error:p,refetch:g}=Zl(),{items:h}=Bm(),f=xe(Z=>Z.loadFromDisk),{items:w,emptyMessage:E,getSelectedCatalogItem:_,outdatedCount:D}=Nm({catalog:d,installedItems:h,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:C,closeMenu:R,selectedIndex:O,clampIndex:U,filteredItems:oe}=wm({listLength:w.length}),k=oe(w),H=useMemo(()=>t!=="installed"&&t!=="updates"?k:Um(k),[t,k]),re=useMemo(()=>t==="installed"||t==="updates"?Om(H):[],[t,H]),K=H[O]??null,V=useMemo(()=>_(K),[_,K]),{notify:Y}=xm(),{handleInstall:A,handleUninstall:j,handleToggleStatus:J,handleUpdate:De,handleBatchUpdate:ms,handleMcpConfigUninstall:Bh}=km({selectedItem:K,selectedCatalogItem:V,items:w,closeMenu:R,clampIndex:U,notify:Y}),{handleBundleInstallStart:Fh,handleBundleDetailConfirm:jh,handleBundleDetailBack:Kh,handleBundleInstallComplete:Vh}=Mm({closeMenu:R,notify:Y}),Hh=useCallback(()=>ms(H),[ms,H]);return useEffect(()=>{f();},[]),useEffect(()=>{U(H.length);},[H.length,U]),useEffect(()=>{p&&(sI.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),l("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Ln,{}),jsx(ud,{outdatedCount:D}),t==="marketplaces"&&kr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(fm,{})}):jsx(kd,{filteredItems:H,groups:re,emptyMessage:E,onBatchUpdate:Hh}),(n||m)&&jsxs(Fragment,{children:[jsx(ni,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(si,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(ii,{message:a,onRetry:()=>{l(null),g();},onBack:()=>l(null)}),r&&jsx(Ad,{message:r.message,type:r.type}),C&&K&&(t==="discover"?V?.type==="bundle"?e?.phase==="installing"?jsx(em,{bundle:e.bundle,onComplete:Vh}):jsx(Kp,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>Fh(K.name,K.flowId),onConfirm:jh,onClose:e?.phase==="detail"?Kh:R}):jsx(Fp,{itemName:K.name,itemType:V?.type,onInstall:A,onClose:R}):K.type==="mcp"?jsx(zp,{itemName:K.name,itemScope:K.scope??"user",onUninstall:Bh,onClose:R}):jsx(Gp,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:V?.version,onUninstall:j,onToggleStatus:Z=>J(Z),onUpdate:De,onClose:R})),jsx(ri,{})]})}var M=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(xe.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Te();var uI=3;function Vm(){let e=M(c=>c.setStarterKits),t=M(c=>c.setIsLoadingStarterKits),r=M(c=>c.setStarterKitsError),n=M(c=>c.setPluginStatus),o=M(c=>c.setPluginDownloadProgress),s=M(c=>c.setStep),i=M(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await mi();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{xe.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=M.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){n(m.name,"installing"),l.current=0;let p="",g=false;for(let h=1;h<=uI;h++)try{await je(m.name,{onDownloadProgress:(f,w)=>{let E=Date.now();(E-l.current>100||f>=w)&&(l.current=E,o(m.name,f,w));}}),n(m.name,"success"),g=!0;break}catch(f){if(f instanceof qe){n(m.name,"success"),g=true;break}p=f instanceof Error?f.message:"Unknown error";}g||(n(m.name,"failed",p),P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:Q().interfaceType}).catch(()=>{}));}let d=Zr();Yr("summary_review"),P(v.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),xe.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var ns={cursorDelta:0,confirm:false,back:false};function Hm(e,t){return t.upArrow?{...ns,cursorDelta:-1}:t.downArrow?{...ns,cursorDelta:1}:t.escape?{...ns,back:true}:t.return?{...ns,confirm:true}:ns}var dI={cursorDelta:0,select:false};function Gm(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:dI}N();var Jm=jw.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var sc=5;function Wm({onRetry:e}){let t=M(c=>c.starterKits),r=M(c=>c.selectedStarterKitIndex),n=M(c=>c.isLoadingStarterKits),o=M(c=>c.starterKitsError);if(n)return jsx(ni,{message:"Loading Starter Kits..."});if(o)return jsx(ii,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Dn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(sc/2)),i=Math.min(t.length,s+sc);i===t.length&&(s=Math.max(0,i-sc));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Jm,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}N();var Xm=jw.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});N();var lc=8;function qm(){let e=M(c=>c.selectedStarterKit),t=M(c=>c.plugins),r=M(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,P(v.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(c=>c.installed).length,s=Math.max(0,r-Math.floor(lc/2)),i=Math.min(t.length,s+lc);i===t.length&&(s=Math.max(0,i-lc));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Xm,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}N();var xI=["Retry failed","Continue anyway"];function Ym({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=y(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Qp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(si,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function Zm({onComplete:e,onRetry:t}){let r=M(u=>u.plugins),n=M(u=>u.step),o=M(u=>u.successCount),s=M(u=>u.failedCount),i=M(u=>u.summaryActionIndex),a=r.filter(u=>u.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let u=setTimeout(e,1500);return ()=>clearTimeout(u)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(u=>jsx(Ym,{name:u.name,status:u.status,error:u.error,downloadProgress:u.downloadProgress,downloadTotal:u.downloadTotal},u.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(u=>u.status==="failed").map(u=>jsx(Ym,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:xI.map((u,c)=>jsx(Box,{children:jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",u]})},u))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Qm(){let e=M(k=>k.step),t=M(k=>k.starterKits),r=M(k=>k.selectedStarterKitIndex),n=M(k=>k.setSelectedStarterKitIndex),o=M(k=>k.selectStarterKit),s=M(k=>k.plugins),i=M(k=>k.pluginCursorIndex),a=M(k=>k.setPluginCursorIndex),l=M(k=>k.setStep),u=M(k=>k.summaryActionIndex),c=M(k=>k.setSummaryActionIndex),d=M(k=>k.failedCount),m=M(k=>k.resetForRetry),p=M(k=>k.goBackToList),g=S(k=>k.setScreen),h=S(k=>k.setFocus),f=S(k=>k.focus),w=nt(k=>k.setJustAuthenticated),E=nt(k=>k.justAuthenticated),{loadStarterKits:_,installSelected:D}=Vm(),C=useRef(false);useEffect(()=>{e==="starterKitList"?(h("starterKitList"),C.current||(C.current=true,Yr("bundle_selection"))):h(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,h]);let R=useCallback(async()=>{let k=M.getState().selectedStarterKit;if(k){let re=await te();re&&await vr({...re,starterKit:k.slug});}P(v.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Zr()}).catch(()=>{});let{successCount:H}=M.getState();P(v.CLI_ONBOARDING_COMPLETED,{duration_ms:Pr(),tools_installed_count:H}).catch(()=>{}),w(false),h("verify"),g("verify");},[w,h,g]),O=useCallback(()=>{m(),D();},[m,D]),U=useCallback(()=>{_();},[_]),oe=useCallback(()=>{h("verify"),g("verify");},[h,g]);return useInput((k,H)=>{if(H.escape)Bs("esc"),oe();else if(H.upArrow&&r>0)n(r-1);else if(H.downArrow&&r<t.length-1)n(r+1);else if(H.return&&t.length>0){let re=Zr();o(t[r]),Yr("kit_display"),P(v.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:re}).catch(()=>{});}},{isActive:f==="starterKitList"}),useInput((k,H)=>{let re=Hm(k,H);if(re.cursorDelta!==0){let K=i+re.cursorDelta;K>=0&&K<s.length&&a(K);}if(re.confirm){let K=M.getState().selectedStarterKit;K&&(async()=>(await te())?.starterKit!==K.slug&&P(v.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let V=Zr();Yr("kit_confirmation"),P(v.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:V}).catch(()=>{});let Y=Zr();Yr("tool_installation"),P(v.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Y}).catch(()=>{}),l("installing"),D();}if(re.back){let K=M.getState().selectedStarterKit;K&&P(v.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:f==="starterKitDetail"}),useInput((k,H)=>{if(d===0)return;let re=Gm(k,H);if(re.cursorDelta!==0){let K=u+re.cursorDelta;K>=0&&K<=1&&c(K);}re.select&&(u===0?O():R());},{isActive:f==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Ln,{}),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."}),!E&&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(Wm,{onRetry:U}),e==="starterKitDetail"&&jsx(qm,{}),(e==="installing"||e==="summary")&&jsx(Zm,{onComplete:R,onRetry:O})]}),jsx(ri,{})]})}F();var rf=null;function nf(){return rf}async function Vi(){let t=nn().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=de.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await of(n);(o||s)&&await wt({...r,installedVersion:o,installMethod:s});}}async function of(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await Ft(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function no(e){let t=await Promise.all(e.map(r=>vI(r)));return rf=t,t}async function vI(e){let t=ef(e.versionCommand);t==="permission-denied"&&(EI(e.versionCommand[0]),t=ef(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await Ft(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!ot(e.alias)){let{installedVersion:l,installMethod:u}=await of(e);await wt({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function ef(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function EI(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=le__default.realpathSync(r),{mode:o}=le__default.statSync(n);le__default.chmodSync(n,o|73);}catch{}}function CI(e){return e.filter(t=>t.module.platforms[process.platform]?.status==="supported").filter(t=>!t.alreadyInstalled).map(t=>({module:t.module,alreadyInstalled:t.alreadyInstalled,checked:!t.alreadyInstalled&&(t.availableStrategies.length>0||t.module.required===true),selectedStrategy:t.availableStrategies[0]??null,availableStrategies:t.availableStrategies}))}function uf(e,t){let[r,n]=useState(()=>CI(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),u=useCallback((d,m)=>{n(p=>p.map(g=>g.module.alias===d?{...g,selectedStrategy:m}:g));},[]);useInput((d,m)=>{let p=i.current,g=a.current,h=m.upArrow||d==="[A",f=m.downArrow||d==="[B";if(h||f)h&&p>0?s(p-1):f&&p<g.length-1&&s(p+1);else if(d===" "){let w=g[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=g[p];if(w&&w.availableStrategies.length>1){let E=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),_=w.availableStrategies[(E+1)%w.availableStrategies.length];n(D=>D.map(C=>C.module.alias===w.module.alias?{...C,selectedStrategy:_}:C));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}N();function pf({probeResults:e,onConfirm:t}){let r=S(p=>p.focus),n=S(p=>p.actionMenuOpen),o=S(p=>p.setActionMenuOpen),s=S(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=uf(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,g)=>{g.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,g)=>{let h=g===a,f=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",f," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:h?"cyan":void 0,children:[h?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",f]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(st,{itemName:m,actions:d,onAction:c,onClose:u})]})}var MI=/^https?:\/\/.+/;function mf({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||u.return){e(null);return}}if(t==="input"){if(u.escape){a.current="",o(""),r("confirm");return}if(u.return){let c=a.current.trim();c.length>0&&MI.test(c)?(i(false),e(c)):c.length>0&&i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function LI(e){let t=e.module.platforms[process.platform];return (t?.status==="supported"?t.strategies:[]).map(n=>n.type==="npm"?`npm install -g ${n.package}`:n.type==="homebrew"?`brew install ${n.formula}`:"curl (see docs)").join(" or ")}function hf(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(g=>g.alias===d?{...g,...m}:g));},[]),a=useCallback(async()=>{for(let d of e){let m=LI(d);if(!d.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";i(d.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}i(d.module.alias,{status:"installing"});try{let p=await Rr(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}F();N();function yf({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Qp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:y(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function bf({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=hf(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{on().catch(()=>{}),n("list");let w=pe().some(E=>E.name===fe);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,c,p]),useInput((w,E)=>{E.return&&p();},{isActive:i});let g=o.filter(w=>w.pendingSetupCommand).length,h=a-g,f=[];return h>0&&f.push(jsxs(Text,{color:"green",children:[h," installed"]},"i")),g>0&&f.push(jsxs(Text,{color:"red",children:[g," needs setup"]},"p")),l>0&&f.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&f.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(yf,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:f.reduce((w,E,_)=>(_>0&&w.push(jsx(Text,{children:" | "},`sep-${_}`)),w.push(E),w),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function vf(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),u=S(p=>p.setScreen),c=useCallback(p=>{if(Gu(p)){on().catch(()=>{}),l("list");let h=pe().some(f=>f.name===fe);u(h?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=nf();if(p){c(p);return}no(de).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let g=p.some(h=>h.module.alias==="metrics");t(g?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(pf,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(mf,{onConfirm:m}),e==="installation"&&jsx(bf,{confirmedItems:o,customUrl:i})]})}F();$();var HI=x("ClaudeMdSuggestion"),GI=[`Install ${fe}`,"Skip for now"],JI=["Retry","Skip for now"];function Tf(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=M(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{P(v.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,P(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await je(fe),o("installed");}catch(m){if(m instanceof qe){o("installed");return}HI.warn(`Failed to install ${fe}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?JI:GI;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),c()):u());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Ln,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(Pf,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Qp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",fe,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",fe," 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:["/",fe]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",fe]}),jsx(Pf,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Pf({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var qI=promisify(execFile),zi="@ciandt-flow/cli";async function Cf(){let e=ge;if(zl.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:zi};try{let t=await fetch(`https://registry.npmjs.org/${zi}/latest`);if(!t.ok)throw new Error(`Registry returned ${t.status}`);let n=(await t.json()).version;return {currentVersion:e,latestVersion:n,isOutdated:n!==e,packageName:zi}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:zi}}}async function Xi(e){try{return await qI(er(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function YI(e){let t=ot(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Ft(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await wt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function kf(e){let t=await YI(e),r=null,n=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:n});if(!s.ok)throw new Error(`Registry returned ${s.status}`);r=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:n});if(!s.ok)throw new Error(`GitHub returned ${s.status}`);r=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=t!==null&&r!==null&&t!==r;return {moduleAlias:e.alias,currentVersion:t,latestVersion:r,isOutdated:o}}async function Af(e,t){let r=ot(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Ft(r.installMethod).update(e,t.currentVersion??"");return o.success?(await wt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function $f(e){let r=ot(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function Rf(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...de.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([Cf(),no(de),Promise.all(de.map(l=>kf(l)))]);if(Vi(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Xi(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(u=>({...u,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(u=>({...u,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let u=de.find(d=>d.alias===l.moduleAlias);if(!u)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let c=await Af(u,l);c.success?r(l.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:$f(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await on(),t(l=>({...l,outcome:"done"}));}catch{await on(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}F();function nv({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Qp,{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 ov({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 Mf(){let{outcome:e,items:t}=Rf(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=pe().some(i=>i.name===fe);r(s?"main":"claudeMdSuggestion"),n("list");},1500);return ()=>clearTimeout(o)}if(e==="module-missing"){let o=setTimeout(()=>{r("moduleSetup"),n("moduleSetup");},500);return ()=>clearTimeout(o)}},[e,r,n]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:t.map(o=>jsx(nv,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(ov,{outcome:e})})]})}Te();An();$();Ta();var lv={debug:"gray",info:"cyan",warn:"yellow",error:"red"},_f=10;function Lf(){let[e,t]=useState(Pa());useEffect(()=>lu(()=>{t([...Pa()]);}),[]);let r=e.slice(-_f);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",_f,") \u2014 press Ctrl+D to close"]}),r.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):r.map((n,o)=>jsxs(Text,{color:lv[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var pv=x("app"),mv={auth:rd,starterKitSetup:Qm,moduleSetup:vf,claudeMdSuggestion:Tf,verify:Mf,main:jm};function Uf(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Qs(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Nf(){P(v.CLI_SESSION_STARTED,{cli_version:ge,os:process.platform,node_version:process.version,duration_ms:Pr(),interface:"tui"}).catch(()=>{});}async function Ff(){let e=await te();if(e&&Vu()&&await Er()){e.customUrl&&Lt(e.customUrl);let{clientSecret:n,...o}=e;nt.getState().setCredentials(o),Nf(),Qs(e);return}if(!e){Uf();return}try{e.customUrl&&Lt(e.customUrl),await Ot();}catch(n){pv.debug(`Token validation failed: ${String(n)}`),Uf();return}Nf();let{clientSecret:t,...r}=e;nt.getState().setCredentials(r),Qs(e);}function jf(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=mv[r],{pendingExit:o}=Lu(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let u=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!u);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(Lf,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}Te();Us();N();F();$();wo();Te();async function xc(e,t={}){let r=Ks({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Vs(r),await vr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var kt=x("auth");function Vf(){ze.clearFallbackFile(),_s();}var fv=3,Kf=3,Hf=` \u2139 The data collected during setup is used solely to improve
|
|
127
127
|
Flow's internal tools and will not be shared externally.
|
|
128
|
-
`;function
|
|
128
|
+
`;function zt(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=c=>{if(c===""){l(),n(new Error("SIGINT"));return}if(c==="\r"||c===`
|
|
129
129
|
`){l(),process.stdout.write(`
|
|
130
|
-
`),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function
|
|
130
|
+
`),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function gv(){let e=tn();return process.stdout.write(`
|
|
131
131
|
`+T.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
|
|
132
|
-
`),(await
|
|
133
|
-
`));}}async function
|
|
134
|
-
`));}}async function
|
|
132
|
+
`),(await zt(T.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Gf(e,t,r){try{await xc(e,{jwtOverride:r});return}catch(n){if(!(n instanceof rn))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${tn()} and retry.`,{cause:n});if(!await gv())throw new Error("Setup cancelled: settings.json must be valid JSON to continue",{cause:n});await xc(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function hv(){if((await zt(T.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await zt(T.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(Sn.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${xn}. Try again.
|
|
133
|
+
`));}}async function yv(){let e=(await zt(T.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await zt(T.cyan(" ? ")+"Enter your email address: ")).trim();if(bn.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${In}. Try again.
|
|
134
|
+
`));}}async function Jf(e,t){process.stdout.write(T.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await Zs(e,t);return r?process.stdout.write(T.yellow(` \u26A0 npm install failed. Please contact Flow support.
|
|
135
135
|
`)):o?process.stdout.write(T.yellow(` \u26A0 Unexpected error. Please contact Flow support.
|
|
136
136
|
`)):n?process.stdout.write(T.yellow(`
|
|
137
137
|
\u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
|
|
138
138
|
`)):process.stdout.write(T.green(` done
|
|
139
|
-
`)),{initFailed:n}}async function
|
|
139
|
+
`)),{initFailed:n}}async function Wf(){for(let e=1;e<=Kf;e++)try{return await mi()}catch{if(e===Kf)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function zf(){let e=await Wf();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");let t=(await zt(T.cyan(" ? ")+"Install a starter kit? (y/N): ")).trim().toLowerCase();if(t!=="y"&&t!=="yes")return null;for(process.stdout.write(`
|
|
140
140
|
`+T.cyan(" ? ")+`Starter Kit:
|
|
141
141
|
`),e.forEach((r,n)=>{process.stdout.write(` ${T.cyan(`${n+1})`)} ${y(r.name)}
|
|
142
142
|
`);}),process.stdout.write(`
|
|
143
|
-
`);;){let r=(await
|
|
144
|
-
`));}}async function
|
|
143
|
+
`);;){let r=(await zt(T.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),n=parseInt(r,10)-1;if(!isNaN(n)&&n>=0&&n<e.length)return e[n];process.stderr.write(T.yellow(` \u26A0 Invalid selection. Please try again.
|
|
144
|
+
`));}}async function Xf(e){if(e.plugins.length===0)return process.stdout.write(T.dim(`
|
|
145
145
|
Starter kit '${y(e.name)}' has no plugins to install.
|
|
146
146
|
`)),true;process.stdout.write(`
|
|
147
147
|
Installing ${e.plugins.length} plugins from '${y(e.name)}'...
|
|
148
|
-
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(T.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=
|
|
148
|
+
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(T.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=fv;a++)try{await je(o),t++,i=!0;break}catch(l){if(l instanceof qe){t++,i=true;break}}i?process.stdout.write(T.green(` done
|
|
149
149
|
`)):(r++,process.stdout.write(T.red(` failed
|
|
150
150
|
`)));}return r===0?process.stdout.write(T.green(` \u2713 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed successfully.
|
|
151
151
|
`)):process.stdout.write(T.yellow(` \u26A0 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
|
|
152
|
-
`)),r===0}async function
|
|
152
|
+
`)),r===0}async function qf(){process.stdout.write(`
|
|
153
153
|
`),process.stdout.write(T.bold(` Personalize your Claude Code
|
|
154
154
|
`)),process.stdout.write(T.dim(` This plugin helps Claude understand your preferences and work style.
|
|
155
155
|
|
|
156
|
-
`));let e=(await
|
|
156
|
+
`));let e=(await zt(T.cyan(" ? ")+`Install ${fe}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){P(v.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(`
|
|
157
157
|
You can always install it later from the catalog.
|
|
158
|
-
`));return}P(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(` Installing ${
|
|
158
|
+
`));return}P(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(` Installing ${fe}...`));try{await je(fe),process.stdout.write(T.green(` done
|
|
159
159
|
`));}catch(t){if(t instanceof qe)process.stdout.write(T.green(` already installed
|
|
160
|
-
`));else {
|
|
160
|
+
`));else {kt.warn(`Failed to install ${fe}: ${t instanceof Error?t.message:t}`),process.stdout.write(T.red(` failed
|
|
161
161
|
`)),process.stdout.write(T.dim(` You can install it later from the catalog.
|
|
162
162
|
`));return}}process.stdout.write(`
|
|
163
163
|
`),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
|
|
164
|
-
`),process.stdout.write(T.cyan.bold(` /${
|
|
164
|
+
`),process.stdout.write(T.cyan.bold(` /${fe}
|
|
165
165
|
`)),process.stdout.write(` Claude will guide you through the rest.
|
|
166
|
-
`);}async function
|
|
167
|
-
`+
|
|
168
|
-
`),e.customUrl!==void 0&&!
|
|
169
|
-
`)),1;if(e.customEmail!==void 0&&!
|
|
170
|
-
`)),1;let t=e.jwt.trim(),r;try{r
|
|
171
|
-
`)),1}e.customUrl&&
|
|
172
|
-
`)),1}let{initFailed:n}=await
|
|
166
|
+
`);}async function wv(e){if(Vf(),process.stdout.write(`
|
|
167
|
+
`+Hf+`
|
|
168
|
+
`),e.customUrl!==void 0&&!Sn.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${xn}.
|
|
169
|
+
`)),1;if(e.customEmail!==void 0&&!bn.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${In}.
|
|
170
|
+
`)),1;let t=e.jwt.trim(),r;try{r=ko(t);}catch(o){let s=y(o instanceof Error?o.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${s}
|
|
171
|
+
`)),1}e.customUrl&&Lt(e.customUrl),kt.debug(`[${r.tenant}] Authenticating tenant via JWT`);try{await qr(r);}catch(o){let s=y(o instanceof Error?o.message:"unknown error");return kt.error(`[${r.tenant}] Authentication failed: ${s}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${s}
|
|
172
|
+
`)),1}let{initFailed:n}=await Jf(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await Wf(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(T.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
|
|
173
173
|
`)),process.stderr.write(` Available starter kits:
|
|
174
174
|
`);for(let a of s)process.stderr.write(` - ${y(a.slug)} (${y(a.name)})
|
|
175
|
-
`);return 1}o=i;}else o=await
|
|
175
|
+
`);return 1}o=i;}else o=await zf();return await Gf({...r,starterKit:o?.slug,customUrl:e.customUrl},!1,t),o?await Xf(o):process.stdout.write(T.dim(`
|
|
176
176
|
Skipped starter kit installation.
|
|
177
|
-
`)),await
|
|
178
|
-
\u2713 Setup complete. Tenant: ${y(r.tenant)}. JWT written to ${
|
|
177
|
+
`)),await qf(),kt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(T.green(`
|
|
178
|
+
\u2713 Setup complete. Tenant: ${y(r.tenant)}. JWT written to ${tn()}.
|
|
179
179
|
|
|
180
180
|
`)),n&&process.stdout.write(T.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
|
|
181
|
-
`)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=y(o instanceof Error?o.message:"unknown error");return
|
|
182
|
-
`)),1}}async function
|
|
183
|
-
`),process.stdout.write(
|
|
184
|
-
`);let r=(await
|
|
185
|
-
`)),1;let n;try{n
|
|
186
|
-
`)),1}let o=e??await
|
|
187
|
-
`)),1}let{initFailed:i}=await
|
|
181
|
+
`)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=y(o instanceof Error?o.message:"unknown error");return kt.error(`[${r.tenant}] Starter kit setup failed: ${s}`),process.stderr.write(T.red(` \u2717 Starter kit setup failed: ${s}
|
|
182
|
+
`)),1}}async function Sv(e,t){Vf(),kt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
|
|
183
|
+
`),process.stdout.write(Hf+`
|
|
184
|
+
`);let r=(await zt(T.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return kt.error("[auth] Validation failed: JWT is required"),process.stderr.write(T.red(` \u2717 JWT is required
|
|
185
|
+
`)),1;let n;try{n=ko(r);}catch(l){let u=y(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${u}
|
|
186
|
+
`)),1}let o=e??await hv(),s=t??await yv();o&&Lt(o),kt.debug(`[${n.tenant}] Authenticating tenant`);try{await qr(n);}catch(l){let u=y(l instanceof Error?l.message:"unknown error");return kt.error(`[${n.tenant}] Authentication failed: ${u}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${u}
|
|
187
|
+
`)),1}let{initFailed:i}=await Jf(o,s),a=await zf();return await Gf({...n,starterKit:a?.slug,customUrl:o??void 0},!0,r),a?await Xf(a):process.stdout.write(T.dim(`
|
|
188
188
|
Skipped starter kit installation.
|
|
189
|
-
`)),await
|
|
190
|
-
\u2713 Setup complete. Tenant: ${y(n.tenant)}. JWT written to ${
|
|
189
|
+
`)),await qf(),kt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(T.green(`
|
|
190
|
+
\u2713 Setup complete. Tenant: ${y(n.tenant)}. JWT written to ${tn()}.
|
|
191
191
|
|
|
192
192
|
`)),i&&process.stdout.write(T.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
|
|
193
|
-
`)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=y(r instanceof Error?r.message:"unknown error");return
|
|
194
|
-
`)),1}}async function
|
|
195
|
-
`)),1;if(e.customEmail!==void 0&&!
|
|
196
|
-
`)),1;try{return await
|
|
197
|
-
`),130;throw t}}async function
|
|
198
|
-
`),(await
|
|
193
|
+
`)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=y(r instanceof Error?r.message:"unknown error");return kt.error(`[auth] Unexpected error: ${n}`),process.stderr.write(T.red(` \u2717 Unexpected error: ${n}
|
|
194
|
+
`)),1}}async function bc(e={}){if(e.jwt)return wv({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!Sn.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${xn}.
|
|
195
|
+
`)),1;if(e.customEmail!==void 0&&!bn.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${In}.
|
|
196
|
+
`)),1;try{return await Sv(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
|
|
197
|
+
`),130;throw t}}async function xv(){try{return process.stdout.write(`
|
|
198
|
+
`),(await zt(T.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(T.yellow(` \u26A0 Logout cancelled
|
|
199
199
|
`)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
|
|
200
|
-
`),130;throw e}}async function
|
|
201
|
-
`)),0;if(!e){let t=await
|
|
200
|
+
`),130;throw e}}async function Yf(e){if(!await te())return process.stdout.write(T.yellow(` \u26A0 You are not authenticated
|
|
201
|
+
`)),0;if(!e){let t=await xv();if(t!==null)return t}try{return await xu(),process.stdout.write(T.green(` \u2713 Credentials removed successfully
|
|
202
202
|
`)),0}catch{return process.stderr.write(T.red(` \u2717 Error removing credentials
|
|
203
|
-
`)),1}}async function
|
|
203
|
+
`)),1}}async function Zf(){let e=await te();return e?await Er()?(process.stdout.write(`
|
|
204
204
|
`+T.bold(` Authenticated
|
|
205
205
|
`)),process.stdout.write(T.dim(" Tenant: ")+y(e.tenant)+`
|
|
206
206
|
`),process.stdout.write(T.dim(" Client ID: ")+y(e.clientId)+`
|
|
207
207
|
`),process.stdout.write(T.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
|
|
208
|
-
`),process.stdout.write(T.dim(" Config: ")+y(await
|
|
208
|
+
`),process.stdout.write(T.dim(" Config: ")+y(await bu())+`
|
|
209
209
|
`),process.stdout.write(`
|
|
210
|
-
`),0):(process.stdout.write(T.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(T.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}N();F();
|
|
210
|
+
`),0):(process.stdout.write(T.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(T.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}N();F();We();F();function Qf(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Iv(e,t,r=process.env){return Qf(r.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:Qf(r.FORCE_AUTOUPDATE_PLUGINS)?{name:e,enabled:true,reason:"env-forced"}:t?.autoUpdate===false?{name:e,enabled:false,reason:"flag"}:t?.autoUpdate===true?{name:e,enabled:true,reason:"flag"}:{name:e,enabled:true,reason:"default"}}function eg(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 Yi(e=process.env){let t=Gr();if(!le__default.existsSync(t))return [];try{let r=JSON.parse(le__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>Iv(n,o,e))}catch{return []}}function tg(){let e=Gr(),t={fixed:[],skipped:[]};if(!le__default.existsSync(e))return t;let r;try{r=JSON.parse(le__default.readFileSync(e,"utf-8"));}catch{return t.skipped.push({name:"(all)",reason:"known_marketplaces.json is malformed JSON"}),t}let n=false;for(let o of yr){let s=r[o];if(!s){t.skipped.push({name:o,reason:"not registered on this machine"});continue}if("autoUpdate"in s){t.skipped.push({name:o,reason:s.autoUpdate?"already autoUpdate: true":"explicitly set to autoUpdate: false \u2014 not overridden"});continue}s.autoUpdate=true,t.fixed.push(o),n=true;}if(n){let o=`${e}.${randomUUID()}.tmp`;le__default.writeFileSync(o,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(o,e);}return t}async function vv(e){let t=pe(),r;try{r=await nr(e.source);}catch(o){if(e.source)throw o;r=[];}let n=new Set(t.map(o=>o.name));return P(v.CLI_CATALOG_VIEWED,{interface:Q().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(xr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(Sr(["","Name","Version","Category","Status"],r.map(o=>[n.has(o.name)?"*":" ",o.name??"",o.version??"n/a",o.category??"",n.has(o.name)?"installed":"available"])),0)}async function Ev(e){let t=pe(),r=await nr(e.source),n=new Map(r.map(s=>[s.name,s])),o=t.map(s=>{let i=n.get(s.name);return i&&s.version&&i.version&&Ve(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return P(v.CLI_CATALOG_VIEWED,{interface:Q().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),e.json?(xr(o),0):o.length===0?(b("All plugins are up to date."),0):(Sr(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
|
|
211
211
|
${o.length} plugin(s) outdated.
|
|
212
|
-
`),0)}async function
|
|
212
|
+
`),0)}async function Pv(e){let t=pe();if(P(v.CLI_CATALOG_VIEWED,{interface:Q().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return b("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return xr(t),0;let r;try{r=await nr(e.source);}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=new Map(Yi().map(i=>[i.name,i.enabled])),s=[...t].sort((i,a)=>{let l=rs.indexOf(i.scope??"user"),u=rs.indexOf(a.scope??"user");return (l===-1?1/0:l)-(u===-1?1/0:u)});return Sr(["Name","Version","Type","Origin","Scope","Project","Status","Auto-Update","Installed at"],s.map(i=>{let a=n.get(i.name),l=a?.type??"bundle",u=a?.origin??ql(i.marketplace),c=i.marketplace?o.get(i.marketplace):void 0,d=c===void 0?"n/a":c?"on":"off";return [i.name??"",i.version??"n/a",wr[l]?.label??"Plugin",u,i.scope??"user",_m(i),i.status??"enabled",d,_t(i.installedAt??"")]})),process.stdout.write(`
|
|
213
213
|
${t.length} plugin(s) installed.
|
|
214
|
-
`),0}async function
|
|
214
|
+
`),0}async function rg(e){if(!await X())return 1;try{return e.available?await vv(e):e.outdated?await Ev(e):await Pv(e)}catch(t){return I(t instanceof Error?t.message:"Failed to list plugins."),1}}Dr();N();F();function Zi(e){let t=Pe().plugins,r=process.cwd();for(let[n,o]of Object.entries(t))if(n===e||n.startsWith(`${e}@`)){let s=o.find(i=>i.scope==="user"||i.projectPath===r);if(s)return s}}function Xt(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function Qi(e,t,r){return b(`${e} is already installed ${Xt(r)}.`),q(` Move it to ${Mt[t].actionLabel} instead? This uninstalls it from ${Xt(r)} first. [y/N] `)}N();F();$();var Se=x("manage");function ta(e,t){return t?pe().find(r=>r.name===e&&r.scope===t):pe().find(r=>r.name===e)}function Tv(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,b(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=ea({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function Cv(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(jn(e,r.scope));if(!await q(`${t}Install external plugin "${i}"?
|
|
215
215
|
This will run: ${a}
|
|
216
|
-
[y/N] `))return Se.debug(`[${e}] Installation cancelled by user`),r.silent||b(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=
|
|
217
|
-
Installation summary: ${t} succeeded, ${r} failed`);}async function
|
|
218
|
-
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function
|
|
216
|
+
[y/N] `))return Se.debug(`[${e}] Installation cancelled by user`),r.silent||b(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=ea({text:`${t}Installing ${e}...`}).start());}let s=o?Tv(t,o):void 0;try{let i=await bm(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Re({status:"error",plugin:e,message:a}):I(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?ne({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):z(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=ee(i);return r.silent?Re({status:"error",plugin:e,message:a}):I(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function kv(e,t,r,n){if(r.force)return {proceed:true,spinner:n};let o=Zi(e);if(!o)return {proceed:true,spinner:n};n?.stop();let s=r.scope??"user";if(o.scope===s){let c=`${e} is already installed ${Xt(o)}. Use --force to reinstall.`;return r.silent?ne({status:"already_installed",plugin:e,message:c}):b(`${t}${c}`),{proceed:false}}let i=r.isInteractive??!!process.stdin.isTTY;if(r.silent||!i){let c=`Already installed ${Xt(o)}. Re-run with --force to install here too.`;return r.silent?ne({status:"already_installed",plugin:e,message:c}):b(`${t}Skipping ${e} \u2014 ${c}`),{proceed:false}}return await Qi(e,s,o)?await as(e,{force:true,scope:o.scope})!==0?(b(`${t}Could not remove ${e} from ${Xt(o)} \u2014 skipping rather than leaving it in an inconsistent state.`),{proceed:false}):{proceed:true,spinner:r.silent?void 0:ea({text:`${t}Installing ${e}...`}).start()}:(b(`${t}Skipped ${e}.`),{proceed:false})}async function Av(e,t,r){let n=r.silent?void 0:ea({text:`${t}Installing ${e}...`}).start();if(Bn(e))return Cv(e,t,r,n);let o=await kv(e,t,r,n);if(!o.proceed)return {name:e,success:true};n=o.spinner;try{let s=await je(e,{...r,onDownloadProgress:r.silent?void 0:(i,a)=>{if(!n||a===0)return;let{bar:l,percent:u,label:c}=oi(i,a);n.text=`${t}Downloading ${e}... ${l} ${u}% (${c})`;}});return n?.stop(),r.silent?ne({status:"success",plugin:e,version:s.version,duration_ms:s.duration_ms}):z(`${t}${e} v${s.version} installed successfully`),{name:e,success:!0,version:s.version,duration_ms:s.duration_ms}}catch(s){if(n?.stop(),s instanceof qe)return r.silent?ne({status:"already_installed",plugin:e,message:s.message}):b(`${t}${s.message}`),{name:e,success:true};let i=ee(s);return r.silent?Re({status:"error",plugin:e,message:i}):I(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function $v(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;b(`
|
|
217
|
+
Installation summary: ${t} succeeded, ${r} failed`);}async function Rv(e,t){let r=new Map;if(t.source){for(let n of e)r.set(n,t.source);return r}try{let n=await nr();for(let o of e){let i=n.filter(a=>a.name===o).find(a=>a.contentSource);i?.contentSource&&r.set(o,i.contentSource);}}catch{}return r}async function ao(e,t={}){if(!await X())return 1;let r=[],n=await Rv(e,t);for(let o=0;o<e.length;o++){let s=e.length>1?`[${o+1}/${e.length}] `:"",i=e[o],a=n.get(i)??t.source,l=await Av(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?ne({status:"summary",succeeded:r.filter(o=>o.success).length,failed:r.filter(o=>!o.success).length,results:r.map(o=>({plugin:o.name,success:o.success,...o.error?{error:o.error}:{}}))}):$v(r)),r.some(o=>!o.success)?1:0}async function as(e,t){if(!await X())return 1;if(Se.debug(`[${e}] Looking up installed plugin`),!t.force){let r=t.scope??"user",n=ta(e,r);if(!n)return Se.error(`[${e}] Plugin is not installed`),I(t.scope?`Plugin "${e}" is not installed in ${t.scope} scope`:`Plugin "${e}" is not installed in user (global) scope. Pass --scope project or --scope local to remove it from this repo instead.`),1;let o=y(n.name),s=n.version?y(n.version):void 0,i=` (${r})`;if(!await q(`Remove ${o} ${s?`v${s}`:"(n/a)"}${i}? [y/N] `))return Se.debug(`[${e}] Uninstall cancelled by user`),b("Operation cancelled."),0}try{return Se.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Bo(e,t.scope),Se.info(`[${e}] Uninstalled successfully`),z("Plugin removed successfully"),0}catch(r){return Se.error(`[${e}] Failed to uninstall: ${ee(r)}`),I(ee(r)),1}}async function sg(e,t={}){if(!await X())return 1;Se.debug(`[${e}] Looking up installed plugin`);let r=ta(e,t.scope);if(!r)return Se.error(`[${e}] Plugin is not installed`),I(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return Se.debug(`[${e}] Already enabled, skipping`),b(`${r.name} is already enabled`),0;try{return Se.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Fo(e,"enabled",t.scope),Se.info(`[${e}] Enabled successfully`),z(`${r.name} enabled successfully`),0}catch(n){return Se.error(`[${e}] Failed to enable: ${ee(n)}`),I(ee(n)),1}}async function ig(e,t={}){if(!await X())return 1;Se.debug(`[${e}] Looking up installed plugin`);let r=ta(e,t.scope);if(!r)return Se.error(`[${e}] Plugin is not installed`),I(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return Se.debug(`[${e}] Already disabled, skipping`),b(`${r.name} is already disabled`),0;try{return Se.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Fo(e,"disabled",t.scope),Se.info(`[${e}] Disabled successfully`),z(`${r.name} disabled successfully`),0}catch(n){return Se.error(`[${e}] Failed to disable: ${ee(n)}`),I(ee(n)),1}}async function ag(e,t,r){r.silent||b(`${t}Updating ${e}...`);try{let n=await Ri(e,r);return r.silent?ne({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):z(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Lr)return r.silent?ne({status:"up_to_date",plugin:e,message:n.message}):b(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=ee(n);return r.silent?Re({status:"error",plugin:e,message:o}):I(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Mv(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;b(`
|
|
218
|
+
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function _v(e,t,r){try{let n=await Hn(e,r.source);Ve(t,n.version,r.force)?b(`Would update ${e}: v${t} \u2192 v${n.version}`):b(`${e} is already up to date (v${t})`);}catch(n){return I(ee(n)),1}return 0}function Lv(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Dv(e,t,r){let n=t.get(e.name);return n?e.version&&Ve(e.version,n,r)?(b(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(b(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(b(`Skipping ${e.name}: not found in catalog`),false)}async function Ov(e,t){try{let r=await nr(t.source),n=Lv(r),o=0;for(let s of e)Dv(s,n,t.force)&&o++;o===0&&b("All plugins are up to date");}catch(r){return I(ee(r)),1}return 0}async function Uv(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await ag(e[n].name,o,t);r.push(s);}return t.silent?ne({status:"summary",updated:r.filter(n=>n.success&&!n.skipped).length,upToDate:r.filter(n=>n.skipped).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.skipped?{skipped:true}:{},...n.error?{error:n.error}:{}}))}):Mv(r),r.some(n=>!n.success)?1:0}async function lg(e,t={}){if(!await X())return 1;if(e){let o=ta(e,t.scope);return o?t.dryRun?_v(e,o.version??"",t):(await ag(e,"",t)).success?0:1:(t.silent?Re({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):I(`Plugin "${e}" is not installed`),1)}let n=pe().filter(o=>yr.includes(o.marketplace??""));return n.length===0?(t.silent?ne({status:"empty",message:"No plugins installed"}):b("No plugins installed"),0):t.dryRun?Ov(n,t):Uv(n,t)}function ng(e){for(let t of e)b(` ${t.pluginName}@${t.version} (${t.marketplace}) \u2014 ${_r(t.sizeBytes)}`);}function og(e){for(let t of e)b(` ${t.pluginName}@${t.marketplace} (${t.scope}) \u2014 ${t.projectPath} (no longer exists)`);}async function cg(e={}){if(!await X())return 1;let t=yp(),r=Sp();if(t.length===0&&r.length===0)return e.silent?ne({status:"empty",message:"Nothing to prune"}):b("Nothing to prune \u2014 no stale cached versions and no orphaned project entries."),0;let n=t.reduce((s,i)=>s+i.sizeBytes,0);if(e.dryRun)return e.silent?ne({status:"dry-run",candidates:t.map(s=>({plugin:s.pluginName,version:s.version,marketplace:s.marketplace,path:s.path,size_bytes:s.sizeBytes})),total_bytes:n,orphaned_entries:r.map(s=>({plugin:s.pluginName,marketplace:s.marketplace,scope:s.scope,project_path:s.projectPath}))}):(t.length>0&&(b(`Would remove ${t.length} stale version(s), freeing ${_r(n)}:`),ng(t)),r.length>0&&(b(`Would remove ${r.length} orphaned project entr${r.length===1?"y":"ies"}:`),og(r))),0;if(!e.force){if(e.silent)return Re({status:"error",message:"--silent requires --force to delete without an interactive confirmation"}),1;if(t.length>0&&(b(`Found ${t.length} stale version(s), ${_r(n)} total:`),ng(t)),r.length>0&&(b(`Found ${r.length} orphaned project entr${r.length===1?"y":"ies"}:`),og(r)),!await q(`Remove these ${t.length+r.length} item(s)? [y/N] `))return b("Operation cancelled."),0}let o=await wp(t);if(xp(r),e.silent)ne({status:"summary",removed:o.removed.length,failed:o.failed.length,freed_bytes:o.freedBytes,orphaned_entries_removed:r.length,details:o.failed.map(s=>({plugin:s.candidate.pluginName,version:s.candidate.version,error:s.error}))});else if(z(`Removed ${o.removed.length} stale version(s), freed ${_r(o.freedBytes)}`+(r.length>0?`, removed ${r.length} orphaned project entr${r.length===1?"y":"ies"}`:"")),o.failed.length>0){I(`Failed to remove ${o.failed.length} version(s):`);for(let{candidate:s,error:i}of o.failed)I(` ${s.pluginName}@${s.version}: ${i}`);}return o.failed.length>0?1:0}N();$();var ls=x("cli:bundle");function Nv(e){let t=y(e.name??e.flowId),r=y(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function Bv(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
|
|
219
219
|
Bundle: ${y(e)} (${t.length} artifacts)
|
|
220
|
-
`);for(let o of t)process.stdout.write(`${
|
|
220
|
+
`);for(let o of t)process.stdout.write(`${Nv(o)}
|
|
221
221
|
`);process.stdout.write(`
|
|
222
222
|
${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
|
|
223
223
|
|
|
224
|
-
`);}async function
|
|
225
|
-
`),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${
|
|
224
|
+
`);}async function ug(e){if(!e.trim())return I("Bundle name cannot be empty."),1;if(!await X())return 1;ls.debug(`Fetching bundle "${e}"`);let r;try{r=await Di(e);}catch(a){return a instanceof to||a instanceof ts?(I(a.message),1):(I(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(ls.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),Bv(r.title,n),o.length===0)return I("No artifacts available for installation in this bundle."),1;if(!await q(`Install ${o.length} artifact(s)? [Y/n] `))return ls.debug("Installation cancelled by user"),0;ls.debug(`Starting installation of ${o.length} artifact(s)`);let i=await Ci(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=y(u.name??u.flowId),p=y(u.type??"unknown"),g=c?"\u2713":`\u2717 (${y(d??"failed")})`;a===1&&process.stdout.write(`
|
|
225
|
+
`),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${g}
|
|
226
226
|
`),a===l&&process.stdout.write(`
|
|
227
|
-
`);}});if(
|
|
227
|
+
`);}});if(ls.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&z(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");I(`${i.failed} failed: ${y(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>y(l.name??l.flowId)).join(", ");b(`${i.skipped} unavailable: ${a}`);}return 0}Dr();N();$();var dg=x("marketplace");function jv(e){return `claude plugin marketplace add ${e}`}async function pg(e,t){if(!await X())return 1;let r;try{r=pi(e);}catch(s){let i=ee(s);return t.silent?Re({status:"error",source:e,message:i}):I(i),1}dg.debug(`[marketplace] Adding marketplace source: ${r}`);let n=jv(r);if(!t.force){let s=y(r),i=y(n);if(!await q(`Add marketplace "${s}"?
|
|
228
228
|
This will run: ${i}
|
|
229
|
-
[y/N] `))return
|
|
229
|
+
[y/N] `))return dg.debug("[marketplace] Operation cancelled by user"),b("Operation cancelled."),0}let o=t.silent?void 0:ea({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await _e(n);return o?.stop(),s.exitCode!==0?(t.silent?Re({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(I(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&b(`stdout: ${s.stdout}`)),1):(t.silent?ne({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(z(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&b(s.stdout)),0)}catch(s){o?.stop();let i=ee(s);return t.silent?Re({status:"error",source:r,message:i}):I(`Failed to add marketplace "${r}": ${i}`),1}}Te();N();async function Gv(){return await te()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Jv(){let e=Date.now();try{await nr();let t=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${t}ms)`,latency:t}}catch(t){return t instanceof Error&&t.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${t instanceof Error?t.message:"Unknown"}`}}}async function Wv(){return await Er()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function zv(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function Xv(){let e=Yi();if(e.length!==0){process.stdout.write(`
|
|
230
230
|
`+T.bold(` Marketplace Auto-Update
|
|
231
231
|
|
|
232
|
-
`));for(let t of e){let r=t.enabled?T.green("[ON] "):T.dim("[OFF]"),n=y(t.name).padEnd(20),o=y(
|
|
233
|
-
`);}}}function
|
|
232
|
+
`));for(let t of e){let r=t.enabled?T.green("[ON] "):T.dim("[OFF]"),n=y(t.name).padEnd(20),o=y(eg(t));process.stdout.write(` ${r} ${n} ${T.dim(o)}
|
|
233
|
+
`);}}}function qv(){process.stdout.write(`
|
|
234
234
|
`+T.bold(` FlowSetup CLI \u2014 Auto-Update Fix
|
|
235
235
|
|
|
236
|
-
`));let e=
|
|
236
|
+
`));let e=tg();for(let t of e.fixed)process.stdout.write(` ${T.green("[FIXED]")} ${y(t)} \u2014 autoUpdate: true set
|
|
237
237
|
`);for(let{name:t,reason:r}of e.skipped)process.stdout.write(` ${T.dim("[SKIP] ")} ${y(t)} \u2014 ${y(r)}
|
|
238
238
|
`);return process.stdout.write(`
|
|
239
239
|
`),e.fixed.length===0?process.stdout.write(T.dim(` Nothing to fix \u2014 all set.
|
|
240
240
|
|
|
241
241
|
`)):process.stdout.write(T.green(` \u2713 ${e.fixed.length} marketplace(s) updated.
|
|
242
242
|
|
|
243
|
-
`)),0}async function
|
|
243
|
+
`)),0}async function mg(e={}){if(e.fix)return qv();process.stdout.write(`
|
|
244
244
|
`+T.bold(` FlowSetup CLI Diagnostics
|
|
245
245
|
|
|
246
|
-
`));let t=[{name:"Credentials",fn:
|
|
247
|
-
`);}return
|
|
246
|
+
`));let t=[{name:"Credentials",fn:Gv},{name:"Prompt Manager",fn:Jv},{name:"Valid Token",fn:Wv},{name:"Claude Code",fn:zv}],r=true;for(let n of t){let o=await n.fn(),s,i=T.green;o.passed?s=T.green("[OK] "):(s=T.red("[FAIL]"),i=T.red,r=false);let a=` ${s} ${i(n.name.padEnd(18))} ${y(o.message)}`;process.stdout.write(a+`
|
|
247
|
+
`);}return Xv(),process.stdout.write(`
|
|
248
248
|
`),r?(process.stdout.write(T.green(` \u2713 All checks passed!
|
|
249
249
|
|
|
250
250
|
`)),0):(process.stdout.write(T.red(` \u2717 Some checks failed \u2014 verify your configuration
|
|
251
251
|
|
|
252
|
-
`)),1)}
|
|
252
|
+
`)),1)}Te();Xr();F();async function fg(e){let t=await te(),r=Dt("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Yt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await zd.get(`${r}rate-limit/me`,{searchParams:{mode:"budget"},headers:n}).json();if(typeof o.consumed_usd!="number"||typeof o.budget_limit!="number"||typeof o.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return o}An();Os();Te();N();$();var Zv=x("commands:usage"),ra=20,gg="EMAIL",hg="MONTHLY CONSUMPTION (USD)",yg="STATUS";function Qv(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*ra),n=ra-r,o=T.green;return t>=90?o=T.red:t>=70&&(o=T.yellow),o("\u2588".repeat(r))+T.dim("\u2591".repeat(n))}function wg(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function eE(e){let t=e.toLowerCase(),r=y(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?T.green(`\u2299 ${n}`):t==="warning"?T.yellow(`\u26A0 ${n}`):t==="blocked"?T.red("\u2717 Budget limit reached"):T.red(`\u2717 ${n}`)}function tE(e){let t=_t(e),r=Math.ceil((new Date(e).getTime()-Date.now())/864e5),n=r>0?` (in ${r} day${r===1?"":"s"})`:"";return `${t}${n}`}async function rE(e){try{let t=await Cn();if(t?.email)return y(t.email);let r=kn(e);return y(r.email??"")}catch(t){return Zv.debug(`JWT email decode failed: ${String(t)}`),""}}async function Sg(e){if(!await X())return 1;let r;try{r=await Ot();}catch(f){return I(`Authentication error: ${ee(f)}`),1}let n;try{n=await fg(r);}catch(f){return I(`Failed to fetch usage data: ${ee(f)}`),1}if(e.json)return xr(n),0;let o=await rE(r)||y(n.user_id),s=wg(n.consumed_usd),i=wg(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(gg.length,o.length+2),c=Math.max(hg.length,ra+2+l.length),d=` ${gg.padEnd(u)} ${hg.padEnd(c)} ${yg}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(yg.length)}`,p=`${T.cyan("\u2022")} ${o.padEnd(u-2)}`,g=`${Qv(n.percentage)} ${l.padEnd(c-ra-2)}`,h=` ${T.dim("Resets")} ${tE(n.renewal_date)}`;return process.stdout.write(`
|
|
253
253
|
`),process.stdout.write(T.dim(d)+`
|
|
254
254
|
`),process.stdout.write(T.dim(m)+`
|
|
255
|
-
`),process.stdout.write(` ${p} ${
|
|
255
|
+
`),process.stdout.write(` ${p} ${g} ${eE(n.status)}
|
|
256
256
|
`),process.stdout.write(h+`
|
|
257
257
|
`),process.stdout.write(`
|
|
258
|
-
`),0}var
|
|
259
|
-
`,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function
|
|
258
|
+
`),0}var sE=["github.com","www.github.com"],iE=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,aE=/^([^@]+)@(.+)$/;function lE(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Ic(e){let t=e.replace(/\\/g,"/");t=t.replace(/^\/+/,"").replace(/\/+$/,"");let r=t.split("/").filter(Boolean);for(let n of r)if(n==="..")throw new Error(`Invalid subpath: "${e}" contains path traversal ("..").`);return r.join("/")}function cE(e){let t=e.pathname.split("/").filter(Boolean);if(t.length<2)throw new Error(`Invalid GitHub URL: expected at least owner/repo in "${e.href}"`);let r=t[0],n=t[1];n.endsWith(".git")&&(n=n.slice(0,-4));let o={type:"github",url:`https://github.com/${r}/${n}.git`};if(t.length>=3&&(t[2]==="tree"||t[2]==="blob")){if(t.length>=4&&(o.ref=t[3]),t.length>=5){let s=t.slice(4).join("/");o.subpath=Ic(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Ic(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function na(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(lE(t)){let r=resolve(t);return {type:"local",url:r,localPath:r}}try{let r=new URL(t);if((r.protocol==="https:"||r.protocol==="http:")&&sE.includes(r.hostname))return cE(r);if(r.protocol==="https:"||r.protocol==="http:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}if(r.protocol==="git:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}}catch{}if(t.startsWith("git@")||t.includes(":")&&t.includes(".git")){let r=t,n,o=t.indexOf("#");o!==-1&&(n=t.slice(o+1),r=t.slice(0,o));let s={type:"git",url:r};return n&&(s.ref=n),s}{let r=t,n,o=r.indexOf("#");o!==-1&&(n=r.slice(o+1),r=r.slice(0,o));let s=r.match(iE);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(aE);c&&(a=c[1],u=c[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),u&&(d.skillFilter=u),l){let m=l.replace(/^\//,"");m&&(d.subpath=Ic(m));}return d}}return {type:"git",url:t}}function oa(e){if(e.type!=="github")return null;try{let r=new URL(e.url).pathname.split("/").filter(Boolean);if(r.length<2)return null;let n=r[1];return n.endsWith(".git")&&(n=n.slice(0,-4)),`${r[0]}/${n}`}catch{return null}}function xg(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);return t?{data:parse(t[1])??{},content:t[2]??""}:{data:{},content:e}}var Ec=new Set(["node_modules",".git","dist","build","__pycache__"]);function vg(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function fE(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function vc(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function cs(e){try{let t=await readFile(e,"utf-8"),{data:r}=xg(t);return typeof r.name!="string"||typeof r.description!="string"?null:{name:r.name,description:r.description,path:dirname(e),rawContent:t,metadata:r.metadata}}catch{return null}}async function Eg(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([vc(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Ec.has(a.name)).map(a=>Eg(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function aa(e,t){let r=[],n=new Set;if(t&&!fE(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await vc(o)){let i=await cs(join(o,"SKILL.md"));if(i)return r.push(i),n.add(i.name),r}let s=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let i of s)try{let a=await readdir(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let u=join(i,l.name);if(await vc(u)){let c=await cs(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await Eg(o);for(let a of i){let l=await cs(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function Pg(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}We();var Ag=1,xE={retries:5,minTimeout:50};async function $g(e,t){mkdirSync(dirname(e),{recursive:true});let r=await dw.lock(e+".lock",{realpath:false,retries:xE});try{return await t()}finally{await r();}}function Tg(){return {version:Ag,skills:{}}}async function la(e){let t=go(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Ag?Tg():n}catch{return Tg()}}function bE(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Rg(e,t){let r=go(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:bE(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
|
|
259
|
+
`,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function Mg(e,t,r){let n=go(r);await $g(n,async()=>{let o=await la(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Rg(o,r);});}async function _g(e,t){let r=go(t);await $g(r,async()=>{let n=await la(t);e in n.skills&&(delete n.skills[e],await Rg(n,t));});}We();$();var Lg=x("skillInstaller");async function AE(e,t,r,n){try{await P(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:Q().interfaceType});}catch(o){Lg.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function $E(e,t){try{await P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Q().interfaceType});}catch(r){Lg.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function RE(e,t){await cp$1(e,t,{recursive:true,dereference:false,filter:r=>{if(Ec.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function ME(e,t,r){let n=lt(e.name),o=Jr(t),s=join(o,n);if(!vg(o,s))return {skill:e.name,success:false,path:s,error:`Unsafe install path: "${s}" escapes skills directory`};try{await rm$1(s,{recursive:!0,force:!0}),await mkdir(s,{recursive:!0}),await RE(e.path,s);let a=oa(r)??r.url;return await Mg(n,{source:a,sourceType:r.type,sourceUrl:r.url,ref:r.ref,skillPath:r.subpath},t),{skill:e.name,success:!0,path:s}}catch(i){return {skill:e.name,success:false,path:s,error:i instanceof Error?i.message:String(i)}}}async function Dg(e,t){let r=na(e),n;try{let o;if(r.type==="local"){if(!r.localPath||!existsSync(r.localPath))return {source:e,results:[],discovered:0,installed:0,failed:0};o=r.localPath;}else n=await It(r.url,r.ref),o=n;let s=await aa(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?Pg(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await ME(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await AE(c.name,t.scope,u,p):await $E(c.name,new Error(m.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(c=>c.success).length,failed:l.filter(c=>!c.success).length}}finally{n&&await vt(n).catch(()=>{});}}We();N();$();var UE=x("skills");async function NE(e){try{await P(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:Q().interfaceType});}catch(t){UE.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function BE(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${y(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function FE(e){let t=na(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return I("Invalid local path."),1;n=t.localPath;}else b(`Fetching skills from ${y(e)}...`),r=await It(t.url,t.ref),n=r;let o=await aa(n,t.subpath);if(o.length===0)return b("No skills found in this source."),0;let i=oa(t)??y(e);b(`Found ${o.length} skill(s) in ${i}:
|
|
260
260
|
`);for(let a of o){let l=y(a.name),u=y(a.description);process.stdout.write(` ${T.bold(l)} ${T.dim(u)}
|
|
261
261
|
`);}return process.stdout.write(`
|
|
262
|
-
`),0}catch(n){return n instanceof
|
|
263
|
-
`);let t=e.source;e.installed>0&&b(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&I(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?b("No skills found in this source."):e.results.length===0&&e.discovered>0&&b(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function
|
|
262
|
+
`),0}catch(n){return n instanceof Ur?I(n.message):I(n instanceof Error?n.message:String(n)),1}finally{r&&await vt(r).catch(()=>{});}}function jE(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);z(`${n} installed ${T.dim(`\u2192 ${o}/`)}`);}else I(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
|
|
263
|
+
`);let t=e.source;e.installed>0&&b(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&I(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?b("No skills found in this source."):e.results.length===0&&e.discovered>0&&b(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Ug(e,t){if(t.list)return FE(e);let r=t.global?"global":"project";try{let n=await Dg(e,{scope:r,skillFilter:t.skill,yes:t.yes});return jE(n),n.failed>0?1:0}catch(n){return n instanceof Ur?I(n.message):I(n instanceof Error?n.message:String(n)),1}}async function Ng(e){let t=Jr(e),r=[];try{let n=await readdir(t,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=join(t,o.name),i=join(s,"SKILL.md");try{if(!(await stat(i)).isFile())continue}catch{continue}let a=await cs(i);a?r.push({name:a.name,description:a.description,path:s}):r.push({name:o.name,description:"(no metadata)",path:s});}}catch{}return r}async function Bg(e){let t=e.global?"global":"project",r=await Ng(t),n=await la(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[lt(i.name)]?.source}));return xr(s),0}if(r.length===0)return b(`No skills installed (${t==="global"?"global":"project"} scope).`),0;b(`${t==="global"?"Global":"Project"} skills (${r.length}):
|
|
264
264
|
`);for(let s of r){let i=n.skills[lt(s.name)]?.source,a=y(s.name),l=y(s.description),u=l.length>80?l.slice(0,77)+"...":l,c=i?T.dim(` (${i})`):"";process.stdout.write(` ${T.bold(a)}${c}
|
|
265
265
|
`),process.stdout.write(` ${T.dim(u)}
|
|
266
266
|
|
|
267
|
-
`);}return 0}async function
|
|
267
|
+
`);}return 0}async function Fg(e,t){let r=t.global?"global":"project";if(!e){let i=await Ng(r);if(i.length===0)return b("No skills installed."),0;b("Installed skills:");for(let a of i)process.stdout.write(` - ${y(a.name)}
|
|
268
268
|
`);return process.stdout.write(`
|
|
269
|
-
`),b("Specify a skill name to remove: flow skills remove <name>"),1}let n=lt(e),o=
|
|
270
|
-
Import summary: 0 installed, ${o.length} failed`);for(let a of o)I(` ${a.name}: ${a.error}`);return o.length>0?1:0}b(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=
|
|
271
|
-
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)I(` ${a.name}: ${a.error}`);return o.length>0?1:0}
|
|
269
|
+
`),b("Specify a skill name to remove: flow skills remove <name>"),1}let n=lt(e),o=Jr(r),s=join(o,n);try{await stat(s);}catch{return I(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await BE(`Remove skill "${y(n)}"?`))return b("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await _g(n,r),await NE(n),z(`Skill "${y(n)}" removed.`),0}catch(i){return I(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}N();$();F();var ca=x("transfer"),Tc=1;function KE(e){return e.marketplace&&e.marketplace!==Oe?`${e.name}@${e.marketplace}`:e.name}function VE(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&b(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),b(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Vg(e){let t=ae__default.resolve(e.output);try{let r=pe(),n={version:Tc,exportedAt:new Date().toISOString(),plugins:r.map(o=>({name:o.name,marketplace:o.marketplace,scope:o.scope,...o.type!==void 0?{type:o.type}:{}}))};return le__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),z(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=ee(r);return ca.error(`Export failed: ${n}`),I(`Failed to export plugins: ${n}`),1}}async function Hg(e,t={}){if(!await X())return 1;let r;try{let a=le__default.readFileSync(ae__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return I(`Failed to read import file "${e}": ${ee(a)}`),1}if(r.version!==Tc)return I(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Tc}`),1;if(!Array.isArray(r.plugins))return I('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return b("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let u=`entry[${a}]`;ca.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(ca.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&b(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(pe().map(l=>l.name));VE(n,a);}if(t.dryRun)return b("Dry-run mode: no plugins were installed"),0;if(n.length===0){b(`
|
|
270
|
+
Import summary: 0 installed, ${o.length} failed`);for(let a of o)I(` ${a.name}: ${a.error}`);return o.length>0?1:0}b(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=KE(a);ca.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await ao([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}b(`
|
|
271
|
+
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)I(` ${a.name}: ${a.error}`);return o.length>0?1:0}$();N();function L(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}N();$();var GE=x("moduleProxy");function JE(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Ol.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function Gg(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await P(v.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{GE.warn(`Failed to emit proxy executed event: ${String(s)}`);}),L(o);}async function Wg(e,t){let r=de.find(o=>o.alias===e);if(!r){I(`Unknown module alias: '${e}'`),L(1);return}if(!await Nt(r.binaryName)){I(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await P(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),L(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Ft(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){I(`No supported installation method available for '${e}' on this platform.`),L(1);return}if(await JE("Would you like to install it now? [Y/n] ")){await P(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await Rr(r,"inline",s);if(!a.success){I(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),L(1);return}await Gg(r,t);}else b(`To install manually, run: flow modules install ${e}`),await P(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),L(1);return}await Gg(r,t);}N();var qE=promisify(execFile);async function YE(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await qE(er(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(n).trim()||null}let t=new AbortController,r=setTimeout(()=>t.abort(),5e3);try{let n={"User-Agent":`flow-plugins-cli/${ge}`,Accept:"application/vnd.github+json"};process.env.GITHUB_TOKEN&&(n.Authorization=`Bearer ${process.env.GITHUB_TOKEN}`);let o=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t.signal,headers:n});return o.ok?(await o.json()).tag_name?.replace(/^v/,"")??null:null}finally{clearTimeout(r);}}catch{return null}}function ZE(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ve(t,r)?"outdated":"installed"}async function Cc(){let e=await Promise.all(de.map(async t=>{let[r,n]=await Promise.all([Nt(t.binaryName),YE(t)]),s=ot(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=ZE(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return Sr(["Name","Alias","Version","Status","Platform"],e),0}async function qg(e){let t=de.find(i=>i.alias===e);if(!t)return I(`Unknown module alias: '${e}'`),1;let[r]=await no([t]);if(r.alreadyInstalled){let i=ot(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return b(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?I(`Module ${t.name} is not supported on ${process.platform}.${a}`):I(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=ea({text:`Installing ${t.name}...`}).start(),s;try{s=await Rr(t,"on_demand",n);}finally{o.stop();}return s.success?(z(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(I(s.error?.message??"Installation failed"),1)}async function zg(e,t){let r=ea({text:`Updating ${e.name}...`}).start(),n;try{n=await qs(e,"command");}catch(o){return r.error(`${e.name}: ${o instanceof Error?o.message:String(o)}`),"error"}if(n.success){let o=n.version??"unknown";return o===t?(r.success(`${e.name}: already up to date (v${t})`),"up_to_date"):(r.success(`${e.name}: v${t} \u2192 v${o}`),"success")}return r.error(`${e.name}: ${n.error?.message??"Update failed"}`),"error"}async function Yg(e){if(e!==null){let n=de.find(i=>i.alias===e);if(!n)return I(`Unknown module alias: '${e}'`),1;let o=ot(n.alias);return o?.installMethod?await zg(n,o.installedVersion??"unknown")==="error"?1:0:(I(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=nn().filter(n=>n.installMethod!==null);if(t.length===0)return b("No installed modules to update."),0;let r=0;for(let n of t){let o=de.find(i=>i.alias===n.alias);if(!o)continue;await zg(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var us=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
|
|
272
272
|
title: "0-current-state \u2014 Index"
|
|
273
273
|
type: index
|
|
274
274
|
domain: platform
|
|
@@ -559,17 +559,17 @@ analyzes these files and creates the correct \`.md\` files in the numbered folde
|
|
|
559
559
|
**6. Source code never in monitored folders.**
|
|
560
560
|
If you create a folder with app or script source code, keep it out of the 5 numbered folders
|
|
561
561
|
entirely (e.g. \`prototypes/\`).
|
|
562
|
-
`},{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"}];N();var
|
|
562
|
+
`},{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"}];N();var Mc="CLAUDE.md";function tP(e){return createHash("sha256").update(e,"utf8").digest("hex")}function rP(){return {new:0,unchanged:0,divergent:0,declined:0}}async function Qg(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??sP,i=e.confirmCreate??iP,a=[],l=rP(),u=us.find(m=>m.path===Mc),c=u?existsSync(join(t,u.path)):true;if(u&&!c){let m=join(t,u.path);o?await i(u.path)?(a.push({path:u.path,status:"new"}),l.new++,r||(mkdirSync(dirname(m),{recursive:true}),writeFileSync(m,u.content,"utf8"))):b(`declined: ${Mc} not created`):e.assistant==="claude-code"&&(a.push({path:u.path,status:"new"}),l.new++,r||(mkdirSync(dirname(m),{recursive:true}),writeFileSync(m,u.content,"utf8")));}for(let m of us){if(m.path===Mc&&!c)continue;let p=join(t,m.path),g=await nP({dstPath:p,template:m,force:n,isInteractive:o,confirmOverwrite:h=>s(h)});a.push({path:m.path,status:g.status}),l[g.status]++,g.write&&!r&&(mkdirSync(dirname(p),{recursive:true}),writeFileSync(p,m.content,"utf8"));}let d=l.divergent>0||l.declined>0;return {files:a,counts:l,hasUnresolved:d}}async function nP(e){let{dstPath:t,template:r,force:n,isInteractive:o,confirmOverwrite:s}=e;return existsSync(t)?tP(readFileSync(t,"utf8"))===r.sha256?{status:"unchanged",write:false}:n?{status:"divergent",write:true}:(oP(r.path),o?await s(r.path)?{status:"divergent",write:true}:{status:"declined",write:false}:{status:"declined",write:false}):{status:"new",write:true}}function oP(e){b(`${e} differs from the Flow strategy template. Review your local changes before overwriting \u2014 run "git status" and "git diff ${e}", or open your IDE's diff/history view for this file. Once overwritten, uncommitted local changes are gone for good.`);}async function sP(e){return q(` Overwrite ${e} with the updated template? [y/N] `)}async function iP(e){return q(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}N();$();Te();Xr();$();var _c=x("lib:otelMetrics"),lP="flow-plugins-cli",cP="1.0.0",uP=5e3;function dP(){return Dt("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function pP(e,t){return typeof t=="number"?{key:e,value:{intValue:String(t)}}:typeof t=="boolean"?{key:e,value:{boolValue:t}}:{key:e,value:{stringValue:t}}}function mP(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:lP,version:cP},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>pP(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function Lc(e,t={}){try{let[r,n]=await Promise.all([Cn(),te()]),o=r?.email,s=n?.tenant;if(!o||!s){_c.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=mP(e,t);await zd.post(dP(),{json:i,timeout:uP,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),_c.debug(`OTel metric sent: ${e}`);}catch(r){_c.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var Dc=x("cli:init"),gP={new:{label:"new",color:T.green},unchanged:{label:"unchanged",color:T.dim},divergent:{label:"kept (differs from template)",color:T.yellow},declined:{label:"pending (declined)",color:T.yellow}};function hP(e){process.stdout.write(`
|
|
563
563
|
`+T.bold(` flow setup strategy
|
|
564
564
|
`)),process.stdout.write(T.dim(` Target: ${e}
|
|
565
565
|
|
|
566
566
|
`)),process.stdout.write(T.dim(` Files evaluated:
|
|
567
|
-
`));for(let t of
|
|
567
|
+
`));for(let t of us)process.stdout.write(T.dim(` \xB7 ${t.path}
|
|
568
568
|
`));process.stdout.write(`
|
|
569
|
-
`);}function
|
|
570
|
-
`));for(let m of s.files){let{label:p,color:
|
|
569
|
+
`);}function yP(e,t,r,n){P(v.CLI_STRATEGY_INIT_COMPLETED,{files_new:e.new,files_unchanged:e.unchanged,files_divergent:e.divergent,files_declined:e.declined,dry_run:t,duration_ms:n,exit_code:r}).catch(o=>{Dc.warn(`Failed to emit strategy init completed event: ${String(o)}`);}),Lc("flow_cli.strategy_init",{dry_run:t,files_new:e.new,exit_code:r}).catch(()=>{});}function wP(e,t){P(v.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:t}).catch(r=>{Dc.warn(`Failed to emit strategy init failed event: ${String(r)}`);}),Lc("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function SP(e){try{return await simpleGit(e).checkIsRepo(CheckRepoActions.IN_TREE)}catch{return false}}async function xP(e){let t=simpleGit(e);await t.init(),await t.checkoutLocalBranch("main");}async function bP(){return q(" Initialize a git repository here (git init -b main)? [y/N] ")}async function ua(e){if(Dc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`),!await X())return 1;let t=e.path??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=e.confirmInitGit??bP;if(!await SP(t)){let m=`${t} is not a git repository. Strategy docs are meant to be version-controlled.`;if(!r)return e.json?Re({error:m,exitCode:1}):I(`${m} Re-run interactively to confirm, or run "git init" first.`),1;if(b(m),!await n())return 1;await xP(t),z(`Initialized a git repository in ${t} (branch: main).`);}e.json||hP(t);let o=Date.now(),s;try{s=await Qg({targetDir:t,dryRun:e.dryRun,force:e.force,assistant:e.assistant});}catch(m){throw wP(m instanceof Error?m.message:String(m),Date.now()-o),m}let i=s.hasUnresolved?2:0;if(yP(s.counts,!!e.dryRun,i,Date.now()-o),e.json)return ne({dryRun:!!e.dryRun,counts:s.counts,files:s.files,exitCode:i}),i;let a=e.dryRun?T.dim("[dry-run] "):"";process.stdout.write(T.bold(` Result:
|
|
570
|
+
`));for(let m of s.files){let{label:p,color:g}=gP[m.status];process.stdout.write(` ${a}${g(p.padEnd(18))} ${m.path}
|
|
571
571
|
`);}process.stdout.write(`
|
|
572
|
-
`);let{new:l,unchanged:u,divergent:c,declined:d}=s.counts;return z(`${l} new, ${u} unchanged, ${c} kept (differs from template)`+(d>0?`, ${d} pending confirmation`:"")),(c>0||d>0)&&b(`Some files differ from the Flow strategy template. Review your local changes before overwriting \u2014 run "git status"/"git diff" or your IDE's diff view. Re-run with --force to overwrite them.`),i!==0&&I("flow setup strategy finished with unresolved files \u2014 see above."),i}N();F();var
|
|
572
|
+
`);let{new:l,unchanged:u,divergent:c,declined:d}=s.counts;return z(`${l} new, ${u} unchanged, ${c} kept (differs from template)`+(d>0?`, ${d} pending confirmation`:"")),(c>0||d>0)&&b(`Some files differ from the Flow strategy template. Review your local changes before overwriting \u2014 run "git status"/"git diff" or your IDE's diff view. Re-run with --force to overwrite them.`),i!==0&&I("flow setup strategy finished with unresolved files \u2014 see above."),i}N();F();var co=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var Nc="repos.yaml",EP="projects";function PP(e,t,r){if(e===void 0)return [];if(!Array.isArray(e))return r.push(`"${t}:" must be a list \u2014 ignoring the whole section.`),[];let n=[];return e.forEach((o,s)=>{if(typeof o!="object"||o===null){r.push(`${t}[${s}] is not a mapping \u2014 skipped.`);return}let i=o,a=i.name!==void 0?String(i.name):"",l=i.remote!==void 0?String(i.remote):"";if(!a||!l){let u=a||`${t}[${s}]`,c=[!a&&"name",!l&&"remote"].filter(Boolean).join(" and ");r.push(`${u}: missing required field "${c}" \u2014 skipped (did you mean "remote:" instead of "url:"?)`);return}n.push({name:a,remote:l,group:i.group!==void 0?String(i.group):void 0});}),n}function Bc(e){let t=e.match(/^https?:\/\/github\.com\/([^/]+)\/([^/.]+)(\.git)?\/?$/);return t?`git@github.com:${t[1]}/${t[2]}.git`:e}function oh(e){let t=[];return {repos:e.map(n=>{let o=Bc(n.remote);if(o===n.remote)return n;let s={...n,remote:o};return t.push({before:n,after:s}),s}),converted:t}}var TP=/^(git@[^:]+:[^/]+\/[^/]+(\.git)?|https?:\/\/[^/]+\/[^/]+\/[^/]+(\.git)?)\/?$/;function pa(e){let t=[],r=[];for(let n of e){if(!n.name.trim()){r.push({entry:n,reason:"empty name"});continue}if(!n.remote.trim()){r.push({entry:n,reason:"empty remote"});continue}if(!TP.test(n.remote.trim())){r.push({entry:n,reason:`remote does not look like a valid git URL: ${n.remote}`});continue}t.push(n);}return {valid:t,invalid:r}}function sh(e){let t=join(e,Nc);if(!existsSync(t))return null;let r=parse(readFileSync(t,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))return null;let n=[],o=r.workspace;o!==void 0&&(typeof o!="object"||o===null)&&n.push('"workspace:" must be a mapping \u2014 using the default (repos_dir).');let s=o&&typeof o=="object"?o:{};return r.repos_dir!==void 0&&n.push('"repos_dir" must be nested under "workspace:", not at the top level \u2014 using the default.'),(r.references!==void 0||s.refs_dir!==void 0)&&n.push('legacy "references:"/"refs_dir" key found \u2014 delete repos.yaml and re-run "flow setup workspace" to regenerate it clean.'),{workspace:{repos_dir:String(s.repos_dir??EP)},repos:PP(r.repos,"repos",n),warnings:n}}function ma(e,t){let r=join(e,Nc),{warnings:n,...o}=t;writeFileSync(r,stringify(o),"utf8");}function ih(e){Oo(e,Nc);}function ah(e,t){Oo(e,`${t}/`);}function lh(e,t){let r=join(e,".claudeignore"),n=existsSync(r)?readFileSync(r,"utf8"):"",o=new Set(n.split(`
|
|
573
573
|
`).map(l=>l.trim())),s=[t.repos_dir].filter(l=>!o.has(`${l}/`));if(s.length===0)return;let i=n?"":`# Paths excluded from Claude Code context.
|
|
574
574
|
`,a=s.map(l=>`# ${l}/ \u2014 repos cloned via flow setup workspace, not part of this repo's own docs.
|
|
575
575
|
${l}/`).join(`
|
|
@@ -578,30 +578,30 @@ ${l}/`).join(`
|
|
|
578
578
|
${a}
|
|
579
579
|
`,"utf8"):writeFileSync(r,`${i}
|
|
580
580
|
${a}
|
|
581
|
-
`,"utf8");}var
|
|
582
|
-
${
|
|
581
|
+
`,"utf8");}var th="## Off-Limits \u2014 Workspace Repos";function ch(e,t,r){if(!r)return "declined";let n=join(e,"CLAUDE.md");if(!existsSync(n))return "no-claude-md";let o=readFileSync(n,"utf8");if(o.includes(th))return "already-present";let s=`
|
|
582
|
+
${th}
|
|
583
583
|
|
|
584
584
|
\`${t.repos_dir}/\` contains repos cloned via \`flow setup workspace\` \u2014 not part of this repo's own documentation or code. It is excluded from Claude Code's context via \`.claudeignore\`.
|
|
585
585
|
|
|
586
586
|
> Off-limits: do not read, index, link, or reference files inside this folder in any context.
|
|
587
587
|
`;return appendFileSync(n,`${o.endsWith(`
|
|
588
588
|
`)?"":`
|
|
589
|
-
`}${s}`,"utf8"),"appended"}var
|
|
590
|
-
`);continue}let r=await
|
|
589
|
+
`}${s}`,"utf8"),"appended"}var uh="projects";function CP(e){let t=e.match(/^git@[^:]+:[^/]+\/([^/.]+)(\.git)?\/?$/);if(t)return t[1]??null;let r=e.match(/^https?:\/\/[^/]+\/[^/]+\/([^/.]+)(\.git)?\/?$/);return r?r[1]??null:null}async function dh(){for(;;){let e=await Gn(" Repo URL \u2014 SSH or HTTPS (leave empty and press ENTER to finish): ");if(!e)return null;let t=CP(e);if(!t){process.stdout.write(` Could not parse a repo name from that URL \u2014 expected an SSH (git@host:org/repo.git) or HTTPS (https://host/org/repo) GitHub URL. Try again.
|
|
590
|
+
`);continue}let r=await Gn(` Group/category for '${t}' (optional, default: general): `),n=Bc(e);return {name:t,remote:n,group:r||"general"}}}async function ph(){if(!await q("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let t=await Gn(` Folder for work repos (default: ${uh}): `),r=[];for(process.stdout.write(T.bold(`
|
|
591
591
|
Add repos (leave the URL empty to finish):
|
|
592
|
-
`));;){let n=await
|
|
592
|
+
`));;){let n=await dh();if(!n)break;r.push(n),process.stdout.write(T.green(` \u2713 added ${n.name}
|
|
593
593
|
`));}return r.length===0?null:(process.stdout.write(T.dim(`
|
|
594
594
|
${r.length} repo(s) added.
|
|
595
|
-
`)),{workspace:{repos_dir:t||
|
|
595
|
+
`)),{workspace:{repos_dir:t||uh},repos:r,warnings:[]})}async function mh(e){let{valid:t,invalid:r}=pa(e);process.stdout.write(T.bold(`
|
|
596
596
|
Current repos in repos.yaml (${e.length}):
|
|
597
597
|
`));for(let i of e){let a=r.find(u=>u.entry===i),l=a?` \u2717 (${a.reason})`:" \u2713";process.stdout.write(` - ${i.name} (${i.remote})${l}
|
|
598
598
|
`);}let n=t,o=false;if(r.length>0&&(await q(` Remove the ${r.length} invalid entr${r.length===1?"y":"ies"} listed above? [y/N] `)?o=true:n=e),await q(" Add more repos to repos.yaml? [y/N] "))for(process.stdout.write(T.bold(`
|
|
599
599
|
Add repos (leave the URL empty to finish):
|
|
600
|
-
`));;){let i=await
|
|
601
|
-
`));}return {repos:n,changed:o}}
|
|
602
|
-
`);}async function
|
|
603
|
-
`),130;throw i}let n=e.force??false,o={scope:r,silent:e.silent,isInteractive:t,force:n},s=[];try{for(let a=0;a<
|
|
604
|
-
`),130;throw i}return s.some(i=>i!==0)?1:0}var
|
|
600
|
+
`));;){let i=await dh();if(!i)break;n=[...n,i],o=true,process.stdout.write(T.green(` \u2713 added ${i.name}
|
|
601
|
+
`));}return {repos:n,changed:o}}$();var fh=x("workspace:repos"),gh=6e4;async function $P(e){try{return (await simpleGit(e).status()).current}catch{return null}}function hh(){let{HOME:e,PATH:t,USER:r,SSH_AUTH_SOCK:n}=process.env;return {HOME:e,PATH:t,USER:r,SSH_AUTH_SOCK:n,GIT_TERMINAL_PROMPT:"0"}}var yh=["GIT_TERMINAL_PROMPT"];function wh(e){return e?{progress:({progress:t})=>e(t)}:{}}async function RP(e,t){await simpleGit(e,{timeout:{block:gh},allowEnvironment:yh,...wh(t)}).env(hh()).pull(["--ff-only"]);}async function MP(e,t,r){await simpleGit({timeout:{block:gh},allowEnvironment:yh,...wh(r)}).env(hh()).clone(e,t);}async function Sh(e,t,r){let n=join(t,e.name),o=join(n,".git");if(existsSync(o)){let s=await $P(n);if(s==="main"||s==="master")try{return await RP(n,r),{name:e.name,outcome:"updated",path:n}}catch(i){return fh.warn(`[${e.name}] pull failed (branch diverged?): ${String(i)}`),{name:e.name,outcome:"skipped",path:n}}return {name:e.name,outcome:"skipped",path:n}}try{return mkdirSync(t,{recursive:!0}),await MP(e.remote,n,r),{name:e.name,outcome:"cloned",path:n}}catch(s){let i=s instanceof Error?s.message:String(s);return fh.error(`[${e.name}] clone failed: ${i}`),{name:e.name,outcome:"failed",error:i}}}function xh(e,t){return !existsSync(join(t,e.name,".git"))}function bh(e,t){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory()&&!t.has(r.name)).map(r=>r.name):[]}var DP=promisify(execFile),Ih=5e3;async function vh(){try{let{stdout:e,stderr:t}=await DP("ssh",["-T","git@github.com","-o","BatchMode=yes","-o",`ConnectTimeout=${Ih/1e3}`],{timeout:Ih+2e3});return `${e}${t}`.includes("successfully authenticated")}catch(e){return `${e.stdout??""}${e.stderr??""}`.includes("successfully authenticated")}}function Eh(e){let t=Math.max(1,cpus().length);return Math.max(1,Math.min(t,4,e))}async function Ph(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;;){let a=o++;if(a>=e.length)return;n[a]=await r(e[a],a);}}let i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},()=>s())),n}function Vc(e={}){return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true,manifestWarnings:[],sshBlocked:false,...e}}async function Ch(e={}){let t=e.targetDir??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=sh(t);if(n){if(r){let f=await mh(n.repos);f.changed?(n={...n,repos:f.repos},ma(t,n)):n={...n,repos:f.repos};}}else {if(!r)return Vc();let f=await ph();if(!f)return Vc();ma(t,f),ih(t),n=f;}let{repos:o,converted:s}=oh(n.repos);s.length>0&&(n={...n,repos:o},ma(t,n)),lh(t,n.workspace);let i=join(t,n.workspace.repos_dir),{valid:a,invalid:l}=pa(n.repos),u=[...n.warnings,...l.map(f=>`${f.entry.name||"(unnamed)"}: ${f.reason} \u2014 skipped`),...s.map(f=>`${f.before.name}: remote is HTTPS \u2014 converted to SSH (${f.after.remote}) and saved to repos.yaml`)];if(a.some(f=>xh(f,i))&&!await vh())return Vc({skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:true});let d=Eh(a.length),m=await Ph(a,d,async(f,w)=>{e.onRepoProgress?.({name:f.name,index:w,total:a.length,status:"start"});let E=await Sh(f,i,_=>{e.onRepoProgress?.({name:f.name,index:w,total:a.length,status:"start",progress:_});});return e.onRepoProgress?.({name:f.name,index:w,total:a.length,status:E.outcome,path:E.path}),E}),p=new Set(a.map(f=>f.name)),g=bh(i,p),h=0;if(e.prune&&g.length>0)for(let f of g)rmSync(join(i,f),{recursive:true,force:true}),h++;return ah(t,n.workspace.repos_dir),{repos:m,orphans:e.prune?[]:g,prunedCount:h,skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:false}}$();var NP=["local","project","user"],Ah=[{name:"cit-tools",description:"CI&T-branded content tools (deck-architect agent, ciandt-pptx, ciandt-clay-render, pptx-builder, refiner skills)"},{name:"commons-claude",description:"Claude Code machine-setup skills (setup-claude-defaults, setup-session-recap, setup-statusline) \u2014 not product tooling, personal environment config"},{name:"google-workspace",description:"Google Workspace skills (gchat-manager, gdrive-manager, gmail-manager)"}],Gc=Ah.map(e=>e.name);function BP(e){return e.filter(t=>!Gc.includes(t))}function FP(){b(`The following ${co.length} runbook bundles will be installed:`);for(let e of co)process.stdout.write(` - ${e}
|
|
602
|
+
`);}async function jP(e,t){if(t||!e)return [];let r=[];for(let{name:n,description:o}of Ah)await q(` Also install ${n}? (${o}) [y/N] `)&&r.push(n);return r}async function KP(){return Ep(" Install scope:",NP.map(e=>({value:e,label:Mt[e].actionLabel,description:Mt[e].description})))}var ps=Symbol("skip");async function kh(e,t,r){let{scope:n,silent:o,isInteractive:s,force:i}=r;if(!i){let a=Zi(e);if(a){if(a.scope===n)return o||b(`${t}${e} is already installed ${Xt(a)}. Use --force to reinstall.`),ps;if(o||!s)return o||b(`${t}Skipping ${e} \u2014 already installed ${Xt(a)}. Re-run with --force to install here too.`),ps;if(!await Qi(e,n,a))return b(`${t}Skipped ${e}.`),ps;let u=await as(e,{force:true,scope:a.scope});if(u!==0)return b(`${t}Could not remove ${e} from ${Xt(a)} \u2014 skipping rather than leaving it in an inconsistent state.`),u}}return o||b(`${t}Installing ${e}...`),ao([e],{scope:n,silent:o,force:i})}async function Jc(e={}){if(!await X())return 1;let t=e.isInteractive??!!process.stdin.isTTY;if(e.extraPlugins){let i=BP(e.extraPlugins);if(i.length>0){let a=`--extra-plugins: unknown bundle(s) ${i.join(", ")} \u2014 valid values are ${Gc.join(", ")}`;return e.silent?ne({error:a}):I(a),1}}e.silent||FP();let r=e.scope;if(!r&&!e.silent&&t)try{r=await KP();}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
|
|
603
|
+
`),130;throw i}let n=e.force??false,o={scope:r,silent:e.silent,isInteractive:t,force:n},s=[];try{for(let a=0;a<co.length;a++){let l=co[a],u=`[${a+1}/${co.length}] `,c=await kh(l,u,o);c!==ps&&s.push(c);}let i=e.extraPlugins?Gc.filter(a=>e.extraPlugins.includes(a)):await jP(t,e.silent);for(let a=0;a<i.length;a++){let l=i[a],u=`[extra ${a+1}/${i.length}] `,c=await kh(l,u,o);c!==ps&&s.push(c);}}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
|
|
604
|
+
`),130;throw i}return s.some(i=>i!==0)?1:0}var VP=x("cli:setup-workspace");function $h(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}function HP(){b("SSH key not configured for GitHub (or not added to your account)."),process.stdout.write(` Stopping before cloning \u2014 configure SSH and run this command again:
|
|
605
605
|
`),process.stdout.write(` 1. Check for an existing key: ls -la ~/.ssh/id_ed25519.pub
|
|
606
606
|
`),process.stdout.write(` 2. If none, generate one: ssh-keygen -t ed25519 -C "your_email@example.com"
|
|
607
607
|
`),process.stdout.write(` 3. Start the agent: eval "$(ssh-agent -s)"
|
|
@@ -609,23 +609,23 @@ ${oh}
|
|
|
609
609
|
`),process.stdout.write(` 5. Copy the public key: pbcopy < ~/.ssh/id_ed25519.pub (macOS)
|
|
610
610
|
`),process.stdout.write(` 6. Add it on GitHub: https://github.com/settings/ssh/new
|
|
611
611
|
`),process.stdout.write(` 7. Test the connection: ssh -T git@github.com
|
|
612
|
-
`);}var
|
|
613
|
-
`));return}let n=Math.floor(e.progress/25)*25;n>0&&
|
|
614
|
-
`)));return}
|
|
612
|
+
`);}var Hc=new Map;function GP(e){let t=`[${e.index+1}/${e.total}]`;if(e.status==="start"){if(e.progress===void 0){process.stdout.write(T.yellow(` ${t} ${e.name}...
|
|
613
|
+
`));return}let n=Math.floor(e.progress/25)*25;n>0&&Hc.get(e.name)!==n&&(Hc.set(e.name,n),process.stdout.write(T.yellow(` ${t} ${e.name}: ${n}%
|
|
614
|
+
`)));return}Hc.delete(e.name);let r=$h(e.status);if(e.status==="cloned"||e.status==="updated"){let n=e.path?` \u2192 ${e.path}`:"";process.stdout.write(T.green(` ${t} ${e.name}: ${r}${n}
|
|
615
615
|
`));}else e.status==="failed"?process.stdout.write(T.red(` ${t} ${e.name}: ${r}
|
|
616
616
|
`)):process.stdout.write(T.dim(` ${t} ${e.name}: ${r}
|
|
617
|
-
`));}function
|
|
617
|
+
`));}function JP(e){if(e.length===0)return;let t=e.map(r=>[r.outcome==="cloned"||r.outcome==="updated"?"\u2713":r.outcome==="skipped"?"\u25CB":"\u2717",r.name,$h(r.outcome),r.error??""]);Sr(["","Repo","Outcome","Detail"],t);}async function WP(e,t,r,n){if(r||!n||t.skippedNoManifest||!t.workspaceDirs)return;let{repos_dir:o}=t.workspaceDirs,s=await q(` Add an off-limits note to CLAUDE.md for '${o}/'? [y/N] `),i=ch(e,t.workspaceDirs,s);i==="appended"?b(`CLAUDE.md updated with an off-limits note for '${o}/'.`):i==="already-present"?b("CLAUDE.md already has the off-limits note \u2014 skipped."):i==="no-claude-md"&&b("No CLAUDE.md found in this repo \u2014 skipped the off-limits note.");}async function Wc(e={}){if(VP.debug(`Running flow setup workspace: ${JSON.stringify(e)}`),!await X())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=await Ch({targetDir:e.path,prune:e.prune,isInteractive:t,onRepoProgress:e.json?void 0:GP});if(e.json)return ne({repos:r.repos,orphans:r.orphans,prunedCount:r.prunedCount,skippedNoManifest:r.skippedNoManifest,manifestWarnings:r.manifestWarnings,sshBlocked:r.sshBlocked}),r.sshBlocked||r.repos.some(a=>a.outcome==="failed")?1:0;for(let a of r.manifestWarnings)b(`repos.yaml: ${a}`);if(r.sshBlocked)return HP(),1;if(r.skippedNoManifest)return b("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;JP(r.repos);let n=r.repos.filter(a=>a.outcome==="cloned").length,o=r.repos.filter(a=>a.outcome==="updated").length,s=r.repos.filter(a=>a.outcome==="skipped").length,i=r.repos.filter(a=>a.outcome==="failed").length;return z(`${n} cloned, ${o} updated, ${s} skipped`+(i>0?`, ${i} failed`:"")+(r.prunedCount>0?`, ${r.prunedCount} pruned`:"")),r.orphans.length>0&&b(`Orphan director${r.orphans.length===1?"y":"ies"} not in repos.yaml: ${r.orphans.join(", ")}. Re-run with --prune to remove.`),await WP(e.path??process.cwd(),r,e.json,t),i>0?1:0}var zP=[{key:"strategy",label:"strategy (scaffold the numbered documentation structure)",run:e=>ua({path:e})},{key:"harness",label:"harness (install the fixed set of Flow runbook bundles)",run:()=>Jc({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>Wc({path:e})}];async function XP(e){return q(` Run ${e}? [y/N] `)}async function Rh(e={}){if(!await X())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=e.confirmStep??XP,n=!!e.yes||!t;!e.yes&&!t&&b("No interactive terminal and --yes not set \u2014 running all steps without prompting.");let o=[];for(let s of zP){if(!(n||await r(s.label))){b(` \u2192 ${s.key} skipped.`);continue}o.push(await s.run(e.path));}return o.some(s=>s!==0)?1:0}var qP=">=2.9.0-beta.28 <2.10.2-beta.49";function YP(e){return zl.valid(e)?zl.satisfies(e,qP,{includePrerelease:true}):false}function _h(e=ge){return YP(e)?{blocked:true,message:`@ciandt-flow/cli@${e} is a known-affected version (FLWP-72469): it embeds internal flow-harness documentation in the published package.
|
|
618
618
|
Run: npm install -g @ciandt-flow/cli@latest
|
|
619
|
-
Then re-run this command.`}:{blocked:false}}function
|
|
620
|
-
`)}function
|
|
619
|
+
Then re-run this command.`}:{blocked:false}}function ZP(e){let t=["",T.bold("All commands:"),""];function r(n,o,s){if(n.name()==="help")return;let i=`${o} ${n.name()}`,a=" ".repeat(s),l=n.description()?T.dim(` \u2014 ${n.description()}`):"";t.push(`${a}${T.cyan(`flow${i}`)}${l}`);for(let u of n.commands)r(u,i,s+1);}for(let n of e.commands)r(n,"",1);return t.push("",T.dim("Without arguments, opens the interactive interface (TUI)."),T.dim("Use 'flow <command> --help' for details and examples on each command.")),t.join(`
|
|
620
|
+
`)}function Lh(e){let t=new Command;t.enablePositionalOptions(),t.configureHelp({styleTitle:c=>T.bold(c),styleCommandText:c=>T.cyan.bold(c),styleSubcommandText:c=>T.cyan(c),styleOptionTerm:c=>T.yellow(c),styleArgumentTerm:c=>T.green(c),styleDescriptionText:c=>T.dim(c)}),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${ge}`,"-V, --version","Display the CLI version").addHelpText("after",()=>ZP(t)).action(async()=>{await e();});let r=new Command("setup").description("Configure the CLI and provision Flow structure in the current repository");r.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
|
|
621
621
|
Examples:
|
|
622
|
-
$ flow setup init`).action(async()=>{let c=await
|
|
622
|
+
$ flow setup init`).action(async()=>{let c=await bc();L(c);}),r.command("strategy").description("Scaffold the numbered strategy documentation structure (0-current-state, 1-strategy, 2-plan, 3-delivery, 4-learn)").option("--dry-run","Preview changes without writing files or prompting",false).option("--json","Output machine-readable JSON",false).option("--force","Skip confirmation before overwriting an up-to-date file, and overwrite customized files too",false).option("--path <dir>","Target repository root (defaults to the current directory)").addOption(new Option("--assistant <name>","Also scaffold a config file for this coding assistant (e.g. CLAUDE.md). Interactive: asks for confirmation before creating it. Non-interactive: never creates it, even with this flag set.").choices(["claude-code"])).addHelpText("after",`
|
|
623
623
|
Examples:
|
|
624
624
|
$ flow setup strategy
|
|
625
625
|
$ flow setup strategy --dry-run
|
|
626
626
|
$ flow setup strategy --force
|
|
627
627
|
$ flow setup strategy --assistant claude-code
|
|
628
|
-
$ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await
|
|
628
|
+
$ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await ua({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path,assistant:c.assistant});L(d);}),r.command("harness").description("Install the fixed set of Flow runbook bundles (tech, security, product, design, ops, common, quality)").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--silent","Output in JSON only",false).option("--force","Reinstall bundles already installed elsewhere without asking for confirmation",false).option("--extra-plugins <names>","Also install these opt-in auxiliary bundles (comma-separated: cit-tools, commons-claude). The only way to install them non-interactively or with --silent \u2014 an interactive run without this flag still asks per bundle, and passing it skips that prompt entirely.").addHelpText("after",`
|
|
629
629
|
Examples:
|
|
630
630
|
$ flow setup harness
|
|
631
631
|
$ flow setup harness --scope project
|
|
@@ -641,11 +641,11 @@ here too without asking, leaving the bundle enabled in both places.
|
|
|
641
641
|
After the 7 bundles, an interactive run also asks once per opt-in extra
|
|
642
642
|
(cit-tools, commons-claude) unless --extra-plugins was passed, which installs
|
|
643
643
|
exactly the named bundles with no prompt \u2014 required in --silent or
|
|
644
|
-
non-interactive runs, since no prompt happens there either way.`).action(async c=>{let d=await
|
|
644
|
+
non-interactive runs, since no prompt happens there either way.`).action(async c=>{let d=await Jc({scope:c.scope,silent:c.silent,force:c.force,extraPlugins:c.extraPlugins?.split(",").map(m=>m.trim()).filter(Boolean)});L(d);}),r.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",`
|
|
645
645
|
Examples:
|
|
646
646
|
$ flow setup workspace
|
|
647
647
|
$ flow setup workspace --prune
|
|
648
|
-
$ flow setup workspace --json --path ./my-workspace`).action(async c=>{let d=await
|
|
648
|
+
$ flow setup workspace --json --path ./my-workspace`).action(async c=>{let d=await Wc({path:c.path,prune:c.prune,json:c.json});L(d);}),r.command("framework-strategy").description("Orchestrate strategy \u2192 harness \u2192 workspace, asking [y/N] before each step").option("--path <dir>","Target repository root (defaults to the current directory)").option("--yes","Skip every confirmation and run all 3 steps back to back",false).addHelpText("after",`
|
|
649
649
|
Examples:
|
|
650
650
|
$ flow setup framework-strategy
|
|
651
651
|
$ flow setup framework-strategy --yes
|
|
@@ -654,13 +654,13 @@ Examples:
|
|
|
654
654
|
Without --yes and with an interactive terminal, asks [y/N] before each of the
|
|
655
655
|
3 steps (strategy, harness, workspace) \u2014 declining one skips just that step
|
|
656
656
|
and moves to the next. Without an interactive terminal, runs all 3 steps
|
|
657
|
-
without prompting even if --yes wasn't passed (there is no terminal to ask in).`).action(async c=>{let d=await
|
|
657
|
+
without prompting even if --yes wasn't passed (there is no terminal to ask in).`).action(async c=>{let d=await Rh({path:c.path,yes:c.yes});L(d);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).option("--source <name>","Named content source to list from (e.g. flow-harness); defaults to the standard catalog").addHelpText("after",`
|
|
658
658
|
Examples:
|
|
659
659
|
$ flow plugin list
|
|
660
660
|
$ flow plugin list --available
|
|
661
661
|
$ flow plugin list --outdated
|
|
662
662
|
$ flow plugin list --json
|
|
663
|
-
$ flow plugin list --available --source flow-harness`).action(async c=>{let d=await
|
|
663
|
+
$ flow plugin list --available --source flow-harness`).action(async c=>{let d=await rg(c);L(d);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").option("--source <name>","Named content source to install from (e.g. flow-harness); defaults to the standard catalog").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
664
664
|
Examples:
|
|
665
665
|
$ flow plugin install flow-adr-writer
|
|
666
666
|
$ flow plugin install flow-adr-writer --scope project
|
|
@@ -674,11 +674,11 @@ Examples:
|
|
|
674
674
|
A plugin already installed elsewhere (any scope, any project) prompts to
|
|
675
675
|
move it here instead (uninstall there, install here) unless --force is
|
|
676
676
|
passed, which installs here too without asking, leaving it enabled in
|
|
677
|
-
both places.`).action(async(c,d)=>{let m=c.filter(
|
|
677
|
+
both places.`).action(async(c,d)=>{let m=c.filter(g=>g.trim());if(m.length===0){I("No valid plugin names provided"),L(1);return}Ue("cli",{verbose:d.verbose,silent:d.silent});let p=await ao(m,d);L(p);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local (default: user \u2014 project/local entries in any repo are left untouched unless named explicitly)").choices(["user","project","local"])).addHelpText("after",`
|
|
678
678
|
Examples:
|
|
679
679
|
$ flow plugin uninstall flow-adr-writer
|
|
680
680
|
$ flow plugin uninstall flow-adr-writer --scope project
|
|
681
|
-
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await
|
|
681
|
+
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await as(c,d);L(m);}),n.command("update").description("Update plugins to the latest version").argument("[name]","Name of the plugin to update (omit to update all)").option("--force","Force update even if already on latest version").option("--dry-run","Show what would be updated without making changes").option("--verbose","Display each step of the update process").option("--silent","Output in JSON only").addOption(new Option("--scope <scope>","Scope to update in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
682
682
|
Examples:
|
|
683
683
|
$ flow plugin update flow-adr-writer
|
|
684
684
|
$ flow plugin update flow-adr-writer --scope project
|
|
@@ -687,7 +687,7 @@ Examples:
|
|
|
687
687
|
$ flow plugin update flow-adr-writer --verbose
|
|
688
688
|
$ flow plugin update flow-adr-writer --silent
|
|
689
689
|
$ flow plugin update
|
|
690
|
-
$ flow plugin update --dry-run`).action(async(c,d)=>{
|
|
690
|
+
$ flow plugin update --dry-run`).action(async(c,d)=>{Ue("cli",{verbose:d.verbose,silent:d.silent});let m=await lg(c??null,d);L(m);}),n.command("prune").description("Remove cached versions of installed plugins that are no longer needed").option("--dry-run","Show what would be removed without deleting anything").option("--force","Skip interactive confirmation").option("--silent","Output in JSON only").addHelpText("after",`
|
|
691
691
|
Examples:
|
|
692
692
|
$ flow plugin prune
|
|
693
693
|
$ flow plugin prune --dry-run
|
|
@@ -706,79 +706,79 @@ version a live session still has open, even if that version is stale from
|
|
|
706
706
|
|
|
707
707
|
--silent has no terminal to prompt on, so it does NOT imply --force \u2014 a
|
|
708
708
|
non-dry-run \`--silent\` without \`--force\` returns an error instead of
|
|
709
|
-
deleting files a script didn't explicitly ask to remove.`).action(async c=>{
|
|
709
|
+
deleting files a script didn't explicitly ask to remove.`).action(async c=>{Ue("cli",{silent:c.silent});let d=await cg(c);L(d);}),n.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addOption(new Option("--scope <scope>","Scope to enable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
710
710
|
Examples:
|
|
711
711
|
$ flow plugin enable flow-adr-writer
|
|
712
|
-
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{
|
|
712
|
+
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{Ue("cli");let m=await sg(c,d);L(m);}),n.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addOption(new Option("--scope <scope>","Scope to disable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
713
713
|
Examples:
|
|
714
714
|
$ flow plugin disable flow-adr-writer
|
|
715
|
-
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{
|
|
715
|
+
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{Ue("cli");let m=await ig(c,d);L(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
|
|
716
716
|
Examples:
|
|
717
717
|
$ flow plugin export
|
|
718
|
-
$ flow plugin export --output my-plugins.json`).action(async c=>{let d=await
|
|
718
|
+
$ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Vg(c);L(d);}),n.command("import").description("Install plugins from an exported JSON file").argument("<file>","Path to the export JSON file").option("--force","Force reinstall even if already installed",false).option("--dry-run","Preview what would be installed without installing",false).option("--diff","Show which plugins are already installed vs new",false).addOption(new Option("--scope <scope>","Override scope for all plugins: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
719
719
|
Examples:
|
|
720
720
|
$ flow plugin import flow-plugins.json
|
|
721
721
|
$ flow plugin import flow-plugins.json --scope user
|
|
722
722
|
$ flow plugin import flow-plugins.json --force
|
|
723
723
|
$ flow plugin import flow-plugins.json --dry-run
|
|
724
|
-
$ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await
|
|
724
|
+
$ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await Hg(c,d);L(m);});let o=new Command("marketplace").description("Manage plugin marketplaces");o.command("add").description("Register a plugin marketplace in Claude Code").argument("<source>","Marketplace source (owner/repo or URL)").option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
725
725
|
Examples:
|
|
726
726
|
$ flow plugin marketplace add anthropics/claude-code
|
|
727
727
|
$ flow plugin marketplace add https://github.com/owner/repo
|
|
728
728
|
$ flow plugin marketplace add anthropics/claude-code --force
|
|
729
|
-
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{
|
|
729
|
+
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{Ue("cli",{verbose:d.verbose,silent:d.silent});let m=await pg(c,d);L(m);}),n.addCommand(o),t.addCommand(n);let s=new Command("mcp").description("Manage MCP servers from the Findr catalog");s.command("add").description("Install an MCP server into Claude Code").argument("<name>","Name of the MCP server to install").argument("[args...]","Arguments to pass to the MCP server (URL for http, command for stdio)").addOption(new Option("--transport <type>","Transport type: http or stdio").choices(["http","stdio"]).makeOptionMandatory()).addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
730
730
|
Examples:
|
|
731
731
|
$ flow mcp add notion --transport http https://mcp.notion.com/mcp
|
|
732
732
|
$ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
|
|
733
733
|
$ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
|
|
734
|
-
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{
|
|
734
|
+
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{Ue("cli",{verbose:m.verbose,silent:m.silent});let p=await Tm(c,d,m);L(p);}),s.command("remove").description("Remove an MCP server from Claude Code").argument("<name>","Name of the MCP server to remove").addOption(new Option("--scope <scope>","Scope to remove from: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
735
735
|
Examples:
|
|
736
736
|
$ flow mcp remove notion
|
|
737
737
|
$ flow mcp remove notion --scope project
|
|
738
|
-
$ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{
|
|
738
|
+
$ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{Ue("cli",{verbose:d.verbose,silent:d.silent});let m=await Cm(c,d);L(m);}),t.addCommand(s);let i=new Command("auth").description("Manage authentication credentials");i.command("login").description("Authenticate and save credentials locally").option("--jwt <token>","JWT token for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--custom-url <url>","Custom Flow base URL for flow-ai-obs configuration").option("--custom-email <email>","Custom email for flow-ai-obs configuration").option("--verbose","Display each step of the authentication process").addHelpText("after",`
|
|
739
739
|
Examples:
|
|
740
740
|
$ flow auth login
|
|
741
741
|
$ flow auth login --jwt <token>
|
|
742
742
|
$ flow auth login --jwt <token> --starter-kit dev
|
|
743
743
|
$ flow auth login --jwt <token> --custom-email name@example.com
|
|
744
|
-
$ flow auth login --verbose`).action(async c=>{
|
|
744
|
+
$ flow auth login --verbose`).action(async c=>{Ue("cli",{verbose:c.verbose});let d=await bc(c);L(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
|
|
745
745
|
Examples:
|
|
746
746
|
$ flow auth logout
|
|
747
|
-
$ flow auth logout --force`).action(async c=>{let d=await
|
|
747
|
+
$ flow auth logout --force`).action(async c=>{let d=await Yf(c.force);L(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
|
|
748
748
|
Examples:
|
|
749
|
-
$ flow auth status`).action(async()=>{let c=await
|
|
749
|
+
$ flow auth status`).action(async()=>{let c=await Zf();L(c);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
|
|
750
750
|
Examples:
|
|
751
751
|
$ flow skills add vercel-labs/agent-skills
|
|
752
752
|
$ flow skills add owner/repo -g
|
|
753
753
|
$ flow skills add owner/repo --skill pr-review commit
|
|
754
754
|
$ flow skills add ./local/skills -y
|
|
755
|
-
$ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await
|
|
755
|
+
$ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Ug(c,d);L(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
|
|
756
756
|
Examples:
|
|
757
757
|
$ flow skills list
|
|
758
758
|
$ flow skills list -g
|
|
759
|
-
$ flow skills list --json`).action(async c=>{let d=await
|
|
759
|
+
$ flow skills list --json`).action(async c=>{let d=await Bg(c);L(d);}),a.command("remove").description("Remove an installed skill").argument("[name]","Name of the skill to remove").option("-g, --global","Remove from global scope").option("--force","Skip confirmation").addHelpText("after",`
|
|
760
760
|
Examples:
|
|
761
761
|
$ flow skills remove pr-review
|
|
762
|
-
$ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await
|
|
762
|
+
$ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Fg(c,d);L(m);}),t.addCommand(a);let l=new Command("bundle").description("Manage Flow bundles");l.command("install").description("Install all artifacts from a Findr bundle").argument("<name>","Bundle name to install").option("--verbose","Display each step of the installation process").addHelpText("after",`
|
|
763
763
|
Examples:
|
|
764
764
|
$ flow bundle install "My React Kit"
|
|
765
765
|
$ flow bundle install "Squad Setup Bundle"
|
|
766
|
-
$ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{
|
|
766
|
+
$ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{Ue("cli",{verbose:d.verbose});let m=await ug(c);L(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").option("--fix","Retroactively set autoUpdate: true on already-registered Flow-curated marketplaces (FLWP-71702)").addHelpText("after",`
|
|
767
767
|
Examples:
|
|
768
768
|
$ flow health
|
|
769
|
-
$ flow health --fix`).action(async c=>{let d=await
|
|
769
|
+
$ flow health --fix`).action(async c=>{let d=await mg(c);L(d);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
|
|
770
770
|
Examples:
|
|
771
771
|
$ flow usage
|
|
772
|
-
$ flow usage --json`).action(async c=>{let d=await
|
|
772
|
+
$ flow usage --json`).action(async c=>{let d=await Sg(c);L(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Cc();L(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
|
|
773
773
|
Examples:
|
|
774
|
-
$ flow modules list`).action(async()=>{let c=await
|
|
774
|
+
$ flow modules list`).action(async()=>{let c=await Cc();L(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
|
|
775
775
|
Examples:
|
|
776
776
|
$ flow modules install metrics
|
|
777
|
-
$ flow modules install dashboard`).action(async c=>{let d=await
|
|
777
|
+
$ flow modules install dashboard`).action(async c=>{let d=await qg(c);L(d);}),u.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
|
|
778
778
|
Examples:
|
|
779
779
|
$ flow modules update
|
|
780
|
-
$ flow modules update metrics`).action(async c=>{let d=await
|
|
780
|
+
$ flow modules update metrics`).action(async c=>{let d=await Yg(c??null);L(d);}),t.addCommand(u);for(let c of de)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Wg(c.alias,d);});return t.hook("preAction",(c,d)=>{if(d.name()==="help")return;let{blocked:m,message:p}=_h();if(m)throw new Error(p)}),t.hook("preAction",()=>{Vi();}),t}$();function tT(){return ae__default.join($e__default.homedir(),".claude","settings.json")}function Oh(){let e=tT();try{if(!le__default.existsSync(e))return !0;let r=JSON.parse(le__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}$();var aT=x("updateChecker"),lT=promisify(execFile),cT=1440*60*1e3,Uh=3e4;function uT(){let e=process.env.FLOW_HOME??ae__default.join($e__default.homedir(),".flow");return ae__default.join(e,"update.lock")}async function Nh(e){try{let{stdout:t}=await lT(er(),["view",e,"version"],{timeout:Uh,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function dT(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Uh);try{let n=await fetch(`https://api.github.com/repos/${e}/releases/latest`,{signal:t.signal});return n.ok?(await n.json()).tag_name?.replace(/^v/,"")??null:null}catch{return null}finally{clearTimeout(r);}}async function pT(e){return e.versionCheck.type==="npm-registry"?Nh(e.versionCheck.package):dT(e.versionCheck.repo)}async function mT(){let e=await Nh("@ciandt-flow/cli");return e&&Ve(ge,e)?(Xi({currentVersion:ge,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function fT(){let e=nn().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=de.find(i=>i.alias===t.alias);if(!r||r.hasOwnUpdateCheck)return;let n=Date.now(),o=t.lastChecked?new Date(t.lastChecked).getTime():0;if(n-o<cT)return;let s=await pT(r);try{await wt({...t,lastChecked:new Date().toISOString()});}catch(i){aT.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ve(t.installedVersion,s)&&qs(r,"background").catch(()=>{});}));}async function Xc(){let e=Oh();if(e===false)return;let t=uT();le__default.mkdirSync(ae__default.dirname(t),{recursive:true});let r;try{r=await dw.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await mT().catch(()=>null);n&&process.stdout.write(`
|
|
781
781
|
\u26A0 @ciandt-flow/cli v${n} installing in background.
|
|
782
782
|
Restart flow to apply the update.
|
|
783
783
|
|
|
784
|
-
`);}await
|
|
784
|
+
`);}await fT().catch(()=>{});}finally{await r().catch(()=>{});}}N();var hT=x("cli"),qc=Lh(async()=>{Ue("tui"),Au("tui"),$u(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();xo("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();xo("sigterm",t,r).finally(()=>process.exit(143));}),await Xc().catch(()=>{}),await Zd().catch(t=>{hT.error(`Failed to init catalog registry: ${String(t)}`);}),await Ff();let{waitUntilExit:e}=render(jsx(jf,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});qc.hook("preAction",async(e,t)=>{t!==qc&&await Xc().catch(()=>{});});try{await qc.parseAsync();}catch(e){I(e instanceof Error?e.message:String(e)),L(1);}
|