@ciandt-flow/cli 2.4.0-beta.5 → 2.5.0-beta.7
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 +150 -146
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {execa}from'execa';import cu,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import oh,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as en from'crypto';import {randomUUID,createHash}from'crypto';import*as me from'fs';import me__default,{readFileSync,mkdirSync,existsSync,realpathSync,lstatSync,writeFileSync,renameSync}from'fs';import*as pe from'path';import pe__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as ve from'os';import ve__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as Ca from'readline';import {createInterface}from'readline';import k from'chalk';import Fi from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import gg from'jsonwebtoken';import Cg from'proper-lockfile';import Xg from'ink-big-text';import od from'ink-spinner';import*as Et from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp}from'fs/promises';import ey from'unzipper';import {simpleGit}from'simple-git';import Ba from'semver';import ml from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var lf=Object.defineProperty;var vi=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var cf=(e,t)=>{for(var r in t)lf(e,r,{get:t[r],enumerable:true});};function Hf(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 Gi(e){if(Hl.some(r=>r.test(e)))return true;let t=Hf(e);return !!(t&&Hl.some(r=>r.test(t)))}function Gf(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function or(e,t){let r=Gf(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&&Gi(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Hl,an=vi(()=>{"use strict";Hl=[/^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 Yh(){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 au(){return iu??=Yh(),iu}var iu,lu=vi(()=>{"use strict";});var du={};cf(du,{GitRepoAdapter:()=>wn});function uu(e,t){if(!Zh.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Zh,wn,ga=vi(()=>{"use strict";lu();an();Zh=/^[a-zA-Z0-9_.-]+$/;wn=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(Gi(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return uu(a,"owner"),uu(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 cu.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 cu.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 au();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});var vr="FLOW",W="flow-skills",Pi="flow-cli",On="internal",qr="external",Yr={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"}},vl={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Ei=new Set(["internal","external"]),Un={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"}},te="flow-claude-md-setup",Ve=5,Dt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Pl="https://flow.ciandt.com",Zr=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,Qr="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)";var El=new Set(["skill","mcp","bundle"]),S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(El),origins:new Set(Ei)},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(El)},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(Ei)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));var Mo="aes-256-gcm",df=16,Tl=16,Nn=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=en.randomBytes(df),n=en.createCipheriv(Mo,this.key,r,{authTagLength:Tl}),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:Mo}}decrypt(t){if(t.algorithm!==Mo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=en.createDecipheriv(Mo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Tl});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var pf=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,mf=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,ff=/[A-Za-z0-9+/]{40,}={0,2}/g,gf=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,hf=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,yf=/\x1b/g;function Ti(e){return e.replace(gf,"").replace(hf,"").replace(yf,"").replace(pf,"Bearer ***").replace(mf,"***").replace(ff,"***").replace(/\r\n|\r|\n/g,"\\n")}var Pr=".claude",Ro=".flow";function Cl(e,t){return ki(W,e,t)}function Ci(e){return pe.join(ve.homedir(),Pr,"plugins","marketplaces",W,"plugins","native",e)}function _o(){return pe.join(ve.homedir(),Pr,"plugins","marketplaces",W,".claude-plugin","marketplace.json")}function Do(){return pe.join(ve.homedir(),Pr,"plugins","known_marketplaces.json")}function kl(){return pe.join(ve.homedir(),Pr,"plugins","marketplaces",W)}function Al(){return pe.join(ve.homedir(),Ro,"cache","install.lock")}function $l(){return pe.join(ve.homedir(),Ro,"logs","flowsetup.log")}function ki(e,t,r){return pe.join(ve.homedir(),Pr,"plugins","cache",e,t,r)}function Er(e){let t=e==="global"?ve.homedir():process.cwd();return pe.join(t,".claude","skills")}function Bn(e){let t=e==="global"?ve.homedir():process.cwd();return pe.join(t,".claude","skills-lock.json")}function Oo(e="user"){return e==="project"?pe.join(process.cwd(),".opencode","plugins"):pe.join(ve.homedir(),".config","opencode","plugins")}function Ll(){return pe.join(ve.homedir(),Ro,"flow-catalogs.json")}function Ml(){let e=process.env.FLOW_HOME??pe.join(ve.homedir(),Ro);return pe.join(e,"config.json")}function Uo(e="user"){return e==="project"||e==="local"?pe.join(process.cwd(),Pr,"agents"):pe.join(ve.homedir(),Pr,"agents")}var wf=5*1024*1024,Sf=3,No=class{filePath;constructor(){this.filePath=$l(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
3
|
-
`;try{
|
|
4
|
-
`);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var
|
|
5
|
-
`);}};var
|
|
6
|
-
`));}function
|
|
7
|
-
`));}function C(e){process.stdout.write(
|
|
8
|
-
`));}function
|
|
9
|
-
`),process.stdout.write(` ${
|
|
10
|
-
`),process.stdout.write(` ${
|
|
2
|
+
import {execa}from'execa';import yu,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import fh,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as on from'crypto';import {randomUUID,createHash}from'crypto';import*as he from'fs';import he__default,{readFileSync,mkdirSync,existsSync,realpathSync,lstatSync,writeFileSync,renameSync}from'fs';import*as ge from'path';import ge__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as Pe from'os';import Pe__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as _a from'readline';import {createInterface}from'readline';import T from'chalk';import Ji from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Pg from'jsonwebtoken';import Ug from'proper-lockfile';import sh from'ink-big-text';import pd from'ink-spinner';import*as Ct from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import uy from'unzipper';import {simpleGit}from'simple-git';import Ga from'semver';import xl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var hf=Object.defineProperty;var Ci=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var yf=(e,t)=>{for(var r in t)hf(e,r,{get:t[r],enumerable:true});};function Qf(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 qi(e){if(Zl.some(r=>r.test(e)))return true;let t=Qf(e);return !!(t&&Zl.some(r=>r.test(t)))}function eg(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function ar(e,t){let r=eg(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&&qi(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Zl,dn=Ci(()=>{"use strict";Zl=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\./,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function ay(){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 gu(){return fu??=ay(),fu}var fu,hu=Ci(()=>{"use strict";});var Su={};yf(Su,{GitRepoAdapter:()=>bn});function wu(e,t){if(!ly.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var ly,bn,ba=Ci(()=>{"use strict";hu();dn();ly=/^[a-zA-Z0-9_.-]+$/;bn=class{id;name;source;constructor(t,r,n){this.id=t,this.name=r,this.source=n;}buildRawUrl(t,r="marketplace.json"){let n=new URL(this.source),{hostname:o,pathname:s}=n;if(qi(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return wu(a,"owner"),wu(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 yu.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 yu.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 gu();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});var rr="FLOW",X="flow-skills",ki="flow-cli",Fn="internal",Zr="external",Qr={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},bundle:{label:"Bundle",color:"green"},agent:{label:"Agent",color:"green"},hook:{label:"Hook",color:"blue"}},$l={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Ai=new Set(["internal","external"]),jn={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)",description:"available in all projects on this machine"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)",description:"shared with the team via version control"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)",description:"only on your machine, not committed"}},ne="flow-claude-md-setup",Je=5,Ut=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Ll="https://flow.ciandt.com",en=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,tn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",rn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,nn="Must be a valid email address (e.g. name@example.com)";var Ml=new Set(["skill","mcp","bundle"]),S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(Ml),origins:new Set(Ai)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal:r}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(Ml)},selectedIndex:0})),toggleOriginFilter:t=>e(r=>{let{origins:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,origins:new Set([t])},selectedIndex:0}}),selectAllOrigins:()=>e(t=>({catalogFilters:{...t.catalogFilters,origins:new Set(Ai)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));var Uo="aes-256-gcm",Sf=16,Rl=16,Kn=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=on.randomBytes(Sf),n=on.createCipheriv(Uo,this.key,r,{authTagLength:Rl}),o=Buffer.concat([n.update(t,"utf8"),n.final()]),s=n.getAuthTag();return {iv:r.toString("hex"),authTag:s.toString("hex"),ciphertext:o.toString("hex"),algorithm:Uo}}decrypt(t){if(t.algorithm!==Uo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=on.createDecipheriv(Uo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Rl});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var xf=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,If=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,bf=/[A-Za-z0-9+/]{40,}={0,2}/g,vf=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,Ef=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Pf=/\x1b/g;function $i(e){return e.replace(vf,"").replace(Ef,"").replace(Pf,"").replace(xf,"Bearer ***").replace(If,"***").replace(bf,"***").replace(/\r\n|\r|\n/g,"\\n")}var Tr=".claude",No=".flow";function _l(e,t){return Mi(X,e,t)}function Li(e){return ge.join(Pe.homedir(),Tr,"plugins","marketplaces",X,"plugins","native",e)}function Bo(){return ge.join(Pe.homedir(),Tr,"plugins","marketplaces",X,".claude-plugin","marketplace.json")}function Fo(){return ge.join(Pe.homedir(),Tr,"plugins","known_marketplaces.json")}function Dl(){return ge.join(Pe.homedir(),Tr,"plugins","marketplaces",X)}function Ol(){return ge.join(Pe.homedir(),No,"cache","install.lock")}function Ul(){return ge.join(Pe.homedir(),No,"logs","flowsetup.log")}function Mi(e,t,r){return ge.join(Pe.homedir(),Tr,"plugins","cache",e,t,r)}function Cr(e){let t=e==="global"?Pe.homedir():process.cwd();return ge.join(t,".claude","skills")}function Vn(e){let t=e==="global"?Pe.homedir():process.cwd();return ge.join(t,".claude","skills-lock.json")}function jo(e="user"){return e==="project"?ge.join(process.cwd(),".opencode","plugins"):ge.join(Pe.homedir(),".config","opencode","plugins")}function Nl(){return ge.join(Pe.homedir(),No,"flow-catalogs.json")}function Bl(){let e=process.env.FLOW_HOME??ge.join(Pe.homedir(),No);return ge.join(e,"config.json")}function Ko(e="user"){return e==="project"||e==="local"?ge.join(process.cwd(),Tr,"agents"):ge.join(Pe.homedir(),Tr,"agents")}var Tf=5*1024*1024,Cf=3,Vo=class{filePath;constructor(){this.filePath=Ul(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
3
|
+
`;try{he.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=ge.dirname(this.filePath);he.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(he.statSync(this.filePath).size>Tf){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);he.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=ge.dirname(this.filePath),r=ge.basename(this.filePath,".log"),n=he.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Cf))he.unlinkSync(ge.join(t,o));}catch{}}};var Jo=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 Ho=class{write(t){process.stdout.write(t.message+`
|
|
5
|
+
`);}};var Go=[],Ri=new Set;function _i(){return Go}function Fl(e){return Ri.add(e),()=>{Ri.delete(e);}}var Wo=class{write(t){Go.push(t),Go.length>100&&Go.shift();for(let r of Ri)r();}};var sn={debug:0,info:1,warn:2,error:3},Ar={context:"cli",transports:[],minLevel:"warn",debugModules:null};function kf(){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 De(e,t){if(e==="tui"){let r=kf();Ar={context:e,transports:[new Wo,new Vo],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Ar={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Ar={context:e,transports:[new Jo("cli")],minLevel:"debug",debugModules:null}:Ar={context:e,transports:[new Ho],minLevel:"info",debugModules:null};}function jl(){return Ar.transports}function Kl(e,t){let{debugModules:r,minLevel:n}=Ar;return Ar.context==="tui"&&r&&r!=="all"?r.has(t)?sn[e]>=sn.debug:sn[e]>=sn.warn:sn[e]>=sn[n]}var Vl=new Map;function zo(e,t,r){if(!Kl(e,t))return;let n={level:e,module:t,message:$i(r),timestamp:new Date};for(let o of jl())o.write(n);}function x(e){let t=Vl.get(e);if(t)return t;let r={debug:n=>zo("debug",e,n),info:n=>zo("info",e,n),warn:n=>zo("warn",e,n),error:n=>zo("error",e,n)};return Vl.set(e,r),r}var Di=x("encryption"),Oi="__encrypted__";function Af(e){return typeof e=="object"&&e!==null&&Oi in e&&e[Oi]===true}function Ui(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[Oi]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Di.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(Af(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Di.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Di.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Ni=promisify(execFile),Mf=promisify(exec),it=x("encryption:macos-keyvault"),an=class{static async isAvailable(){try{let{stdout:t}=await Mf("command -v security");return it.debug(`security binary found at: ${t.trim()}`),!0}catch{return it.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{it.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Ni("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return it.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return it.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{it.debug(`Storing secret: service=${t}, account=${r}`),await Ni("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),it.debug("security add-generic-password succeeded");}catch(o){let s=o;throw it.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return it.debug(`Deleting secret: service=${t}, account=${r}`),await Ni("security",["delete-generic-password","-a",r,"-s",t]),it.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return it.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};function y(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g,"")}function oe(e){process.stdout.write(T.green(` \u2713 ${y(e)}
|
|
6
|
+
`));}function E(e){process.stderr.write(T.red(` \u2717 ${y(e)}
|
|
7
|
+
`));}function C(e){process.stdout.write(T.cyan(` \u2139 ${y(e)}
|
|
8
|
+
`));}function ln(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
|
+
`),process.stdout.write(` ${T.bold(i(e))}
|
|
10
|
+
`),process.stdout.write(` ${T.dim(s)}
|
|
11
11
|
`);for(let a of r)process.stdout.write(` ${i(a)}
|
|
12
12
|
`);process.stdout.write(`
|
|
13
|
-
`);}function
|
|
14
|
-
`);}function
|
|
15
|
-
`);}function
|
|
16
|
-
`);}function
|
|
13
|
+
`);}function nr(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
14
|
+
`);}function Oe(e){process.stdout.write(JSON.stringify(e)+`
|
|
15
|
+
`);}function Ge(e){process.stderr.write(JSON.stringify(e)+`
|
|
16
|
+
`);}function J(e){return e instanceof Error?e.message:String(e)}function xt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var Bi=promisify(execFile),Fi=promisify(exec),Of=[{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"}],q=x("encryption:linux-keyvault");async function Uf(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 Nf(e){let t=_a.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var or=class e{static async isAvailable(){try{let{stdout:t}=await Fi("command -v secret-tool");q.debug(`secret-tool found at: ${t.trim()}`);}catch{return q.debug("secret-tool binary not found in PATH"),false}try{return await Bi("secret-tool",["lookup","service","__flow_connectivity_check__"]),q.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(q.debug(`Secret Service D-Bus not available: ${n}`),false):(q.debug("secret-tool is available and D-Bus service is reachable"),true)}}static async detectPackageManager(){for(let t of Of)try{return await Fi(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;q.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 q.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let r=await Nf(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return q.info(`Running: ${t.command}`),await Uf("Installing secret-tool...",()=>Fi(t.command)),e.isAvailable()}catch{return q.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,r){try{q.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Bi("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return q.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return q.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){q.debug(`Storing secret: service=${t}, account=${r}`),q.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),q.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),q.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?(q.debug("secret-tool store succeeded"),o()):(q.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=>{q.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return q.debug(`Deleting secret: service=${t}, account=${r}`),await Bi("secret-tool",["clear","service",t,"account",r]),q.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return q.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var jf=promisify(execFile),at=x("encryption:windows-keyvault"),ji=1,Kf=1,Vf=2,Jf=3;function Ki(e,t){return `${e}:${t}`}var Vi=`
|
|
17
17
|
using System;
|
|
18
18
|
using System.Runtime.InteropServices;
|
|
19
19
|
using System.Text;
|
|
@@ -49,7 +49,7 @@ public class FlowCredManager {
|
|
|
49
49
|
|
|
50
50
|
public static string Read(string target) {
|
|
51
51
|
IntPtr credPtr;
|
|
52
|
-
if (!CredRead(target, ${
|
|
52
|
+
if (!CredRead(target, ${ji}, 0, out credPtr)) return "";
|
|
53
53
|
try {
|
|
54
54
|
var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
|
|
55
55
|
if (cred.CredentialBlobSize <= 0) return "";
|
|
@@ -63,7 +63,7 @@ public class FlowCredManager {
|
|
|
63
63
|
byte[] bytes = Encoding.UTF8.GetBytes(secret);
|
|
64
64
|
IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
|
|
65
65
|
IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
|
|
66
|
-
int[] persistLevels = new int[] { ${
|
|
66
|
+
int[] persistLevels = new int[] { ${Vf}, ${Jf}, ${Kf} };
|
|
67
67
|
int lastErr = 0;
|
|
68
68
|
try {
|
|
69
69
|
foreach (int persist in persistLevels) {
|
|
@@ -71,7 +71,7 @@ public class FlowCredManager {
|
|
|
71
71
|
try {
|
|
72
72
|
Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
|
|
73
73
|
var cred = new CREDENTIAL();
|
|
74
|
-
cred.Type = ${
|
|
74
|
+
cred.Type = ${ji};
|
|
75
75
|
cred.TargetName = targetPtr;
|
|
76
76
|
cred.CredentialBlobSize = bytes.Length;
|
|
77
77
|
cred.CredentialBlob = blobPtr;
|
|
@@ -89,164 +89,167 @@ public class FlowCredManager {
|
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
public static bool Delete(string target) {
|
|
92
|
-
return CredDelete(target, ${
|
|
92
|
+
return CredDelete(target, ${ji}, 0);
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
|
-
`;function
|
|
96
|
-
${
|
|
95
|
+
`;function Hn(e){return e.replace(/'/g,"''")}function Xo(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Hf(e){return `Add-Type -TypeDefinition @'
|
|
96
|
+
${Vi}
|
|
97
97
|
'@
|
|
98
|
-
[FlowCredManager]::Read('${
|
|
99
|
-
${
|
|
98
|
+
[FlowCredManager]::Read('${Hn(e)}')`}function Gf(e,t,r){return `Add-Type -TypeDefinition @'
|
|
99
|
+
${Vi}
|
|
100
100
|
'@
|
|
101
|
-
[FlowCredManager]::Write('${
|
|
102
|
-
${
|
|
101
|
+
[FlowCredManager]::Write('${Hn(e)}', '${Hn(t)}', '${Hn(r)}')`}function Wf(e){return `Add-Type -TypeDefinition @'
|
|
102
|
+
${Vi}
|
|
103
103
|
'@
|
|
104
|
-
[FlowCredManager]::Delete('${
|
|
105
|
-
`)[0]:"unknown error";return
|
|
106
|
-
`)[0]:"unknown error";return
|
|
107
|
-
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw
|
|
108
|
-
`)[0]:"unknown error";return
|
|
104
|
+
[FlowCredManager]::Delete('${Hn(e)}')`}async function qo(e){return jf("powershell.exe",e)}var cn=class{static async isAvailable(){try{let{stdout:t}=await qo(Xo('Write-Output "ok"')),r=t.trim()==="ok";return at.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
|
|
105
|
+
`)[0]:"unknown error";return at.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=Ki(t,r);at.debug(`Looking up secret: target=${n}`);let o=Hf(n),{stdout:s}=await qo(Xo(o)),i=s.trim();return at.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
|
|
106
|
+
`)[0]:"unknown error";return at.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=Ki(t,r);at.debug(`Storing secret: target=${o}`);let s=Gf(o,n,r),{stdout:i}=await qo(Xo(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];at.debug(`CredWrite succeeded (persist=${u})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
|
|
107
|
+
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw at.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=Ki(t,r);at.debug(`Deleting secret: target=${n}`);let o=Wf(n),{stdout:s}=await qo(Xo(o)),i=s.trim()==="True";return at.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
|
|
108
|
+
`)[0]:"unknown error";return at.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var zf=32,Xf="flow-plugins-cli-fallback",Hi="flow-plugins-cli-fallback",qf={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};function Yf(){let e=`${Pe.hostname()}${Pe.userInfo().username}`;return on.scryptSync(e,Xf,zf)}function Zf(){let e=Yf(),t=new Kn(e),r=Ui(t);return new Ji({projectName:Hi,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}var Zo=null;function Yo(){return Zo||(Zo=Zf()),Zo}var Ue=class{warned=false;async getSecret(t,r){return Yo().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=qf[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
|
|
109
109
|
using a machine-derived key. For stronger security, ${o}.
|
|
110
|
-
`),this.warned=true;}Go().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Go(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return Go().path}static hasExistingData(){try{let t=new Fi({projectName:ji});return me.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Fi({projectName:ji});me.rmSync(t.path,{force:!0});}catch{}Wo=null;}};async function Ki(){if(Oe.hasExistingData())return new Oe;switch(process.platform){case "darwin":return await rn.isAvailable()?new rn:new Oe;case "linux":return await tr.isAvailable()?new tr:await tr.ensureInstalled()?new tr:new Oe;case "win32":return await on.isAvailable()?new on:new Oe;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var jl=x("config:credentials"),Ot="flow-plugins-cli",Vi="credentials",Ji="token-cache",Hi="user-info",qo=null;async function rr(){return qo||(qo=Ki()),qo}function Yo(){qo=null;}async function X(){let t=await(await rr()).getSecret(Ot,Vi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ut(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 jl.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await rr()).setSecret(Ot,Vi,JSON.stringify(e));}async function Kl(){let e=await rr();await e.deleteSecret(Ot,Vi),await e.deleteSecret(Ot,Ji),await e.deleteSecret(Ot,Hi);}async function Vl(){return (await rr()).getStoragePath()}async function Jl(e){await(await rr()).setSecret(Ot,Ji,JSON.stringify(e));}async function Zo(){let t=await(await rr()).getSecret(Ot,Ji);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Qo(e){await(await rr()).setSecret(Ot,Hi,JSON.stringify(e));}async function es(){let t=await(await rr()).getSecret(Ot,Hi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function nr(){let e=await Zo();return e?new Date(e.expiresAt)>new Date:false}function St(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/`,jl.debug(`[customUrl] Service URLs overridden to base: ${t}`);}function sn(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")}}an();var Wi=x("api:auth");function Xf(e){if(!Dt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Gl={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 qf(e){if(e instanceof HTTPError){let t=e.response.status;Wi.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&&Gl[r]?new Error(Gl[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?(Wi.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Wi.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function kr(e){let t=or("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Xf(e.tenant);let r;try{r=await cu.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await qf(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Ut(e),await Jl({accessToken:r.access_token,expiresAt:n});let o=sn(r.access_token);await Qo({sub:o.sub,name:o.name,email:o.email});}var Wl=x("lib:tokenProvider");async function xt(){if(await nr()){let n=await Zo();if(n)return n.accessToken}Wl.debug("Token expired or missing, re-authenticating...");let t=await X();if(!t)throw new Error("Not authenticated. Run: flow auth login");Oe.clearFallbackFile(),Yo(),await kr(t);let r=await Zo();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Wl.debug("Token refreshed successfully"),r.accessToken}an();var ts=x("api:metrics");function zl(){return or("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Xl(e,t,r){return cu.post(e,{json:t,headers:r})}async function Zf(e){let t=await es();if(t)return t;let r=sn(e),n={sub:r.sub,name:r.name,email:r.email};return await Qo(n),n}async function E(e,t){let r=await xt(),n=await Zf(r),o=await X();if(!Dt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Pi,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Xl(zl(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),ts.debug(`Metrics event sent: ${e}`);}catch(i){throw ts.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function ql(e,t,r){try{let n=r&&Dt.test(r)?r:"unknown",o={action:e,booster:Pi,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Xl(zl(),o,{FlowTenant:n}),ts.debug(`Anonymous metrics event sent: ${e}`);}catch(n){ts.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_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED"};var Qf={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},at={...Qf};function Yl(e){let t=Date.now();at={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Ar(e){at.currentStep=e,at.stepStart=Date.now();}function J(){return {...at}}function sr(){return at.sessionStart===0?0:Date.now()-at.sessionStart}function $r(){return at.stepStart===0?0:Date.now()-at.stepStart}function Zl(){at.tuiSessionStart=Date.now();}function Ql(){return at.tuiSessionStart===0?0:Date.now()-at.tuiSessionStart}var eg=3e3,tg=x("abandonment");async function rs(e){let{currentStep:t,sessionStart:r}=J();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:sr()};try{await Promise.race([E(v.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),eg))]);}catch(o){tg.warn(`Abandonment event failed: ${String(o)}`);}}function ec(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var rg=3e3,ng=x("session-end");async function Vn(e,t,r){let n=Ql(),s=[E(v.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(rs(e));try{await ec(Promise.all(s).then(()=>{}),rg);}catch(i){ng.warn(`Session end event failed: ${String(i)}`);}}var ag=2e3;function rc(){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),Vn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},ag);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var dg=16;function nc({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(dg)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}function oc({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[vr," \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)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}function sc(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[vr," \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 Ge=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));function Rr(){return pe__default.join(ve__default.homedir(),".claude","settings.json")}function qn(){let e=Rr();if(!me__default.existsSync(e))return {status:"missing"};let t=me__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 os(e){let t=Rr();me__default.mkdirSync(pe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,t);}function ac(e,t){let r=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...r,ANTHROPIC_AUTH_TOKEN:t}}}function Yi(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}var hg=3600,_r=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Yn(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 yg(e){return gg.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:hg})}function ss(e,t={}){let r=qn();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new _r;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?Yi(r.settings):null,s=t.jwtOverride??yg(e),i=ac(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function is(e){os(e.merged);}function lc(){let e=qn();return e.status!=="ok"?false:Yi(e.settings)!==null}function wg(){let e=Ml();if(!me__default.existsSync(e))return {};try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return {}}}var Zi=null;function Sg(){return Zi===null&&(Zi=wg()),Zi}function ir(){return !!Sg().ENABLE_EXPERIMENTAL_BETAS}function vg(){return Z.filter(e=>e.platforms[process.platform]?.status==="supported")}function uc(e){let t=vg();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var as={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=pe__default.join(ve__default.homedir(),".claude","settings.json"),r=me__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??Pl),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return [t]},onDemand:null,mode:"non-interactive"}},Pg={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},Z=ir()?[as,Pg]:[as];var kg=x("moduleState");function cs(){let e=process.env.FLOW_HOME??pe__default.join(ve__default.homedir(),".flow");return pe__default.join(e,"modules.json")}var Ag={retries:5,minTimeout:50};async function dc(e,t){me__default.mkdirSync(pe__default.dirname(e),{recursive:true});let r=await Cg.lock(e+".lock",{realpath:false,retries:Ag});try{return await t()}finally{await r();}}function pc(){let e=cs();if(!me__default.existsSync(e))return [];try{let t=JSON.parse(me__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(kg.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),me__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return me__default.rmSync(e,{force:true}),[]}}function Dr(){return pc()}function mc(e){let t=cs();me__default.mkdirSync(pe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};me__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,t);}function We(e){return Dr().find(t=>t.alias===e)??null}async function lt(e){let t=cs();await dc(t,async()=>{let r=pc(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,mc(r);});}async function Or(){let e=cs();me__default.existsSync(e)||await dc(e,async()=>{me__default.existsSync(e)||mc([]);});}var Mg=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 bt(e){let t=process.platform==="win32"?"where":"which";try{return await Mg(t,[e]),!0}catch{return false}}function Nt(){return process.platform==="win32"?"npm.cmd":"npm"}var fc=promisify(execFile),cn=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=ar(t,"npm");if(!r)return null;try{let{stdout:n}=await fc(Nt(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=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 fc(Nt(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var us=promisify(execFile),Ug=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,ds=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=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 us("brew",["tap",o.tap]),await us("brew",["trust",o.tap])),await us("brew",[r,o.formula]),{success:!0,version:await this.getVersionByFormula(o.formula)??void 0,method:"homebrew",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:s,message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}async getVersionByFormula(t){try{let{stdout:r}=await us("brew",["list","--versions",t]),n=r.trim().match(Ug);return n?n[2]:null}catch{return null}}};var un=promisify(execFile),hc=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function yc(){let e=process.env.FLOW_HOME??pe__default.join(ve__default.homedir(),".flow");return pe__default.join(e,"bin")}var ps=class{type="curl";async isAvailable(){return bt("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=pe__default.join(yc(),pe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await un(n,["--version"]),s=o.match(hc);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=pe__default.join(ve__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await un("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{me__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return me__default.chmodSync(s,448),await un("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{me__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=yc(),i=pe__default.join(s,pe__default.basename(n.binaryName)),a=false;try{if(me__default.mkdirSync(s,{recursive:!0}),a=!0,await un("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return me__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}me__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await un(i,["--version"]),c=u.match(hc);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{me__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=pe__default.join(ve__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await un("curl",["-L","--fail","-o",n,r]);let o=me__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=me__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{me__default.unlinkSync(n);}catch{}}}};var wc="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(wc=e.version);}catch{}var se=wc;var ye=x("moduleInstaller");function Pt(e){switch(e){case "npm":return new cn;case "homebrew":return new ds;case "curl":return new ps}}async function Zn(e,t,r){try{await E(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){ye.warn(`Failed to emit install failed event: ${String(n)}`);}}async function cr(e,t,r,n,o){let s=Date.now(),i=e.platforms[process.platform];if(!i)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-s};if(i.status==="experimental"){ye.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let c={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Zn(e,t,c),{success:false,error:c,durationMs:Date.now()-s}}if(i.status!=="supported"){let c={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Zn(e,t,c),{success:false,error:c,durationMs:Date.now()-s}}if(!i.strategies.some(c=>c.type===r)){let c={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await Zn(e,t,c),{success:false,error:c,durationMs:Date.now()-s}}let a=Pt(r),l=false;try{l=await a.isAvailable();}catch(c){ye.warn(`${r} availability check failed: ${String(c)}`);}if(!l){let c={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await Zn(e,t,c),{success:false,error:c,durationMs:Date.now()-s}}try{await E(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:se,trigger:t});}catch(c){ye.warn(`Failed to emit install started event: ${String(c)}`);}let u;try{u=o?.forceLatest?await a.update(e,"unknown"):await a.install(e);}catch(c){let d=c instanceof Error?c.message:String(c);ye.warn(`${r} install threw: ${d}`),u={success:false,error:{code:"INSTALL_THREW",message:d},durationMs:Date.now()-s};}if(u.success){await lt({alias:e.alias,name:e.name,installedVersion:u.version??null,installMethod:u.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await E(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:u.version??"unknown",duration_ms:u.durationMs,os:process.platform,trigger:t});}catch(m){ye.warn(`Failed to emit install completed event: ${String(m)}`);}let{pendingCmd:c,failed:d}=await Jg(e,t,n);return c?{...u,pendingInteractiveSetup:c}:d?{...u,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...u,configCheckFailed:true}:u}return await Zn(e,t,u.error??{code:"UNKNOWN",message:"unknown error"}),u}async function Jg(e,t,r){if(!e.postInstall)return {pendingCmd:null,failed:false};let n=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(n==null)return {pendingCmd:null,failed:false};let o;if(typeof n=="function"){let i=await X(),a={credentials:i?{clientId:i.clientId,clientSecret:i.clientSecret,tenant:i.tenant}:null,customUrl:r??null};try{o=n(a);}catch(l){return ye.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else o=n;if(o.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:o[0]??null,failed:false};let s=false;for(let i=0;i<o.length;i++){let a=o[i];if(a.length===0)continue;let l=spawnSync(a[0],a.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,ye.warn(`postInstall "${a.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&ye.warn(l.stderr);let u=o.slice(i+1).filter(c=>c.length>0);u.length>0&&ye.debug(`continuing with remaining postInstall steps: ${u.map(c=>c.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function ms(e,t){let r=Date.now(),n=We(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=Pt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await E(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:se,trigger:"command"});}catch(a){ye.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);ye.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await lt({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await E(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){ye.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await E(v.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){ye.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await E(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){ye.warn(`Failed to emit update failed event: ${String(a)}`);}return i}var fs=x("flowAiObsSetup");async function Qn(e){try{if(!await new cn().isAvailable().catch(()=>!1))return fs.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let n=await cr(as,"onboarding","npm",e,{forceLatest:!0});return n.success?n.postInstallFailed||n.configCheckFailed?(fs.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(fs.warn(`flow-ai-obs install failed: ${n.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(t){return fs.warn(`installFlowAiObs threw: ${String(t)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}function Sc(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 xc=x("useAuthSetup");function Ic(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),[o,s]=useState(),[i,a]=useState(null),[l,u]=useState(false),[c,d]=useState("fields"),[m,p]=useState(null),f=useRef(0),g=useRef(false),{setCredentials:h,setJustAuthenticated:w}=Ge(),I=()=>{d("fields"),p(null),t(""),r.current=null,n.current=null;},R=()=>{E(v.CLI_SESSION_STARTED,{cli_version:se,os:process.platform,node_version:process.version,duration_ms:sr(),interface:"tui"}).catch(()=>{});},B=async()=>{g.current=true;let b={...r.current,customUrl:n.current??void 0};try{await Ut(b);}catch(D){a(D instanceof Error?D.message:"Failed to persist credentials"),I(),g.current=false;return}let{clientSecret:$,...F}=b;h(F),w(true),R(),await Qn(n.current).catch(D=>xc.warn(`installFlowAiObs threw unexpectedly: ${String(D)}`)),eo({starterKit:F.starterKit});},P=async b=>{g.current=true;let $={...r.current,customUrl:n.current??void 0};try{is(b),await Ut($);}catch(ue){a(ue instanceof Error?ue.message:"Failed to persist credentials"),I(),g.current=false;return}let{clientSecret:F,...D}=$;h(D),w(true),R(),await Qn(n.current).catch(ue=>xc.warn(`installFlowAiObs threw unexpectedly: ${String(ue)}`)),eo({starterKit:D.starterKit});},A=b=>{try{return ss(r.current,{allowOverwriteMalformed:b,jwtOverride:e.trim()})}catch($){return $ instanceof _r?(d("malformedConfirm"),null):(a($ instanceof Error?$.message:"Failed to read settings.json"),d("fields"),null)}};return {jwtValue:e,jwtError:o,authError:i,isSubmitting:l,step:c,plan:m,isCommittingRef:g,setJwtValue:t,setJwtError:s,cancelToFields:I,handleSubmit:async()=>{let b=e.trim();if(!b){s("This field is required");return}let $;try{$=Yn(b);}catch(F){s(F instanceof Error?F.message:"Invalid JWT");return}s(void 0),r.current=$,d("customUrl");},handleAuthenticate:async b=>{n.current=b,b&&St(b),u(true),a(null),f.current+=1;try{await kr(r.current);let $=A(!1);$&&(p($),d("preview"));}catch($){let F=$ instanceof Error?$.message:"Authentication failed";a(F),ql(v.CLI_AUTH_FAILED,{error_code:Sc($),attempt:f.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,d("fields");}finally{u(false);}},commitAndProceed:P,skipJwtAndProceed:B,planPersistOverwrite:()=>{let b=A(true);b&&(p(b),P(b));}}}function bc(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,handleAuthenticate:d,commitAndProceed:m,skipJwtAndProceed:p,planPersistOverwrite:f}=Ic(),[g,h]=useState("confirm"),[w,I]=useState(""),R=useRef(""),[B,P]=useState(false);return useEffect(()=>{o==="customUrl"&&(h("confirm"),R.current="",I(""),P(false));},[o]),useInput((A,_)=>{if(!(n||i.current)){if(o==="preview"){_.return&&s?m(s):_.escape?p():A==="q"&&u();return}if(o==="malformedConfirm"){_.return?f():_.escape&&u();return}if(o==="customUrl"){if(g==="confirm")A==="y"||A==="Y"?h("input"):(A==="n"||A==="N"||_.return)&&d(null);else if(_.escape)R.current="",I(""),h("confirm");else if(_.return){let j=R.current.trim();j.length>0&&Zr.test(j)?(P(false),d(j)):j.length>0&&P(true);}else _.backspace||_.delete?(R.current=R.current.slice(0,-1),I(R.current)):A&&!_.ctrl&&!_.meta&&(R.current=R.current+A,I(R.current),P(false));return}_.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:[vr," \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:w}),jsx(Text,{color:"cyan",children:"\u2588"})]}),B&&jsx(Text,{color:"red",children:Qr}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="preview"&&s?jsx(oc,{plan:s}):o==="malformedConfirm"?jsx(sc,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[vr," \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(nc,{label:"JWT",value:e,onChange:A=>{a(A),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function pn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Xg,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",se]})})]})}var Tc=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],q=ir()?Tc:Tc.slice(0,3);function qg(e){return q.findIndex(t=>t.id===e)}function ta(e,t,r){let n=qg(r.activeTab);if(t.rightArrow||t.tab){let o=q[(n+1)%q.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=q[(n-1+q.length)%q.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:q[n]?.focus??"list"}]:[]}var Ac={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function $c({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:q.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${Ac[r]} (${e})`:Ac[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Ue=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Mc(){let e=S(i=>i.focus),t=Ue(i=>i.query),r=Ue(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var eh=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...Yr[e]})),th=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...vl[e]}));function Rc(){let e=S(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),eh.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"]})]}),th.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function _c({type:e}){let{label:t,color:r}=Yr[e];return jsx(Text,{color:r,children:t})}function Uc({origin:e}){return e===On?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var ys=oh.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(_c,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Uc,{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 ",wt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function mn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Fc({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(mn,{message:t});let n=Math.max(0,r-Math.floor(Ve/2)),o=Math.min(e.length,n+Ve);o===e.length&&(n=Math.max(0,o-Ve));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(ys,{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 Vc({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function Hc({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(mn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Ve/2)),u=Math.min(n.length,l+Ve);u===n.length&&(l=Math.max(0,u-Ve));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(Vc,{label:p.label,pathHint:p.pathHint},p.key):jsx(ys,{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 ph={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function mh({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Mc,{}),jsx(Rc,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:ph[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Hc,{groups:n,emptyMessage:r}):jsx(Fc,{items:e,emptyMessage:r})]})}function Gc({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(mh,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var hh={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 ws(){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:[hh[e],t?" | Ctrl+D: debug log":""]})})}function Wc({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 Ss({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(od,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function la(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Yc=20;function xs(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Yc),s="\u2588".repeat(o)+"\u2591".repeat(Yc-o),i=`${la(e)} / ${la(t)}`;return {bar:s,percent:n,label:i}}function Is({received:e,total:t}){let{bar:r,percent:n,label:o}=xs(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function bs({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ze({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}var pa=Object.entries(Un),tu=[...pa.map(([,e])=>e.actionLabel),"Cancel"],ru=Object.fromEntries(pa.map(([,e])=>[e.actionLabel,e.description]));function nu(e){let t=pa.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var Lh=x("provider.registry"),Mh=3e4,Ps=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()+Mh}),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"&&Lh.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 Rh={user:"global",project:"project",local:"local"};function Es(e){return e?Rh[e]:"global"}var Ne=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},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};an();function dt(){return cu.create({prefix:or("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await xt();e.headers.set("Authorization",`Bearer ${t}`);let r=await X();r?.tenant&&Dt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Dh=x("catalog.registry"),Ts=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);Dh.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var Vh={retries:5,minTimeout:50};async function ma(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Cg.lock(e+".lock",{realpath:false,retries:Vh});try{return await t()}finally{await r();}}var Cs=class{filePath;constructor(t){this.filePath=t??Ll();}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 ma(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 ma(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await ma(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};var Jh=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function no(e){if(!e||!Jh.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var Hh=/^[^@]+@[^@]+$/;function gn(e){return Hh.test(e)}function hn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Gh=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;function fa(e){if(!Gh.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 yn(e,t){let r=hn(e);fa(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var Wh=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,zh=/^https:\/\/[\w./:@?&=+#%-]+$/;function ks(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Wh.test(t)&&!zh.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var Xh=x("catalog.flow-api"),As=class{id="flow-api";name="Flow Marketplace";source;removable=false;constructor(){this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await dt().get("v1/plugins/catalog").json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle"}))}catch(t){if(t instanceof HTTPError){let{status:r}=t.response;throw r===401||r===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${r}`)}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${t.message}`):t}}async fetchManifest(t){no(t);try{return await dt().get(`v1/plugins/${t}/manifest`).json()}catch(r){if(r instanceof HTTPError){let{status:n}=r.response;throw n===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${n}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await dt().head("v1/plugins/catalog"),Xh.debug("ping ok"),!0}catch{return false}}};var ie=new Ts,jt=new Cs;ie.register(new As);var pu=false;async function mu(){if(pu)return;pu=true;let e=await jt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(ga(),du));for(let r of e)ie.register(new t(r.id,r.name,r.source));}var fu=2;async function pr(){return ie.fetchAll()}async function gu(){return ie.fetchAllWithErrors()}async function Sn(e){no(e);try{return await dt().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function hu(e,t){no(e);try{let r=await dt().get(`v1/plugins/${e}/archive`),n=r.headers.get("x-archive-size"),o=n?Number(n):NaN,s=Number.isFinite(o)&&o>0?o:0,i=s>0,a=r.body;if(!a)throw new Error("Failed to download plugin: response has no body");let l=a.getReader(),u=[],c=0;for(;;){let{done:d,value:m}=await l.read();if(d)break;if(c+=m.byteLength,i&&c>s*fu)throw await l.cancel(),new Error(`Download exceeded expected size: received ${c} bytes, expected at most ${s*fu}`);u.push(m),i&&t?.(c,s);}return Buffer.concat(u)}catch(r){throw r instanceof Error?r.message.includes("Download exceeded expected size")?r:new Error(`Failed to download plugin: ${r.message}`):r}}async function $s(){try{let{profiles:e}=await dt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}async function yu(e,t){let r=pe.resolve(t);await Et.mkdir(r,{recursive:true});let n=pe.join(pe.dirname(r),`${randomUUID()}.zip`);try{await Et.writeFile(n,e);let o=await ey.Open.file(n),s=pe.normalize(r+pe.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=pe.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(pe.resolve(pe.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 Et.unlink(n);}catch{}}}async function ha(e){await Et.rm(e,{recursive:true,force:true});}async function mr(){let e=Al();await Et.mkdir(pe.dirname(e),{recursive:true});try{await Et.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Cg.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function ny(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:W,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function xu(){let e=_o();if(!me__default.existsSync(e))return null;try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return null}}function oy(){let e=xu();if(e)return e;let t=ny(),r=_o();return me__default.mkdirSync(pe__default.dirname(r),{recursive:true}),ya(t),t}function ya(e){let t=_o(),r=`${t}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,t);}function sy(){let e=Do(),t={};try{me__default.existsSync(e)&&(t=JSON.parse(me__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[W])return;t[W]={source:{source:"github",repo:"cit-flow/flow-skills"},installLocation:kl(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,e);}function Iu(e,t){pt(e.name),sy();let r=Ci(e.name);me__default.mkdirSync(pe__default.dirname(r),{recursive:true});try{me__default.lstatSync(r),me__default.rmSync(r,{recursive:!0,force:!0});}catch{}me__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=oy();n.plugins.some(s=>s.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),ya(n));}function wa(e){pt(e);let t=Ci(e);try{me__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=xu();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&ya(r);}var ay=x("mcpConfigReader"),ly=500,cy=512;function uy(){return pe__default.join(ve__default.homedir(),".claude.json")}function dy(){return pe__default.join(process.cwd(),".mcp.json")}function vu(e){if(!me__default.existsSync(e))return null;try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return ay.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function oo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sa(e){if(!oo(e))return {};let t=e.mcpServers;return oo(t)?t:{}}function xa(e,t){return Object.keys(e).slice(0,ly).map(n=>({name:y(n.slice(0,cy)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Eu(){let e=[],t=uy(),r=vu(t);if(oo(r)){let a=r,l=Sa(a);e.push(...xa(l,"user"));let u=process.cwd();if(oo(a.projects)){let c=a.projects[u];if(oo(c)){let d=Sa(c);e.push(...xa(d,"local"));}}}let n=dy(),o=vu(n),s=Sa(o);e.push(...xa(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}var Xe=x("storage");async function my(e,t,r){try{await E(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:J().interfaceType});}catch(n){Xe.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function fy(e,t,r){let n=t==="enabled"?v.CLI_TOOL_ENABLED:v.CLI_TOOL_DISABLED;E(n,{tool_id:e,source:r,interface:J().interfaceType}).catch(o=>Xe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Pa(){return pe__default.join(ve__default.homedir(),".claude","plugins","installed_plugins.json")}function gy(){return pe__default.join(ve__default.homedir(),".claude","plugins")}function Ls(e){let t;try{t=me__default.realpathSync(e);}catch{t=pe__default.resolve(e);}let r=pe__default.resolve(gy()),n=pe__default.resolve(pe__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+pe__default.sep),s=t.startsWith(n+pe__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Tu(e="user"){return e==="local"?pe__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?pe__default.join(process.cwd(),".claude","settings.json"):pe__default.join(ve__default.homedir(),".claude","settings.json")}function Ye(){let e=Pa();if(!me__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Ea(){let e=Pa();try{let t=await me__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function hy(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Cu(e,t){try{me__default.mkdirSync(pe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,e);}catch(r){throw hy(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function qe(e){Cu(Pa(),e);}function so(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function yy(e,t){let r=pe__default.join(e,".claude-plugin"),n=pe__default.join(r,"plugin.json");if(me__default.existsSync(n))try{return JSON.parse(me__default.readFileSync(n,"utf-8"))}catch{return null}let o=pe__default.join(r,"marketplace.json");if(me__default.existsSync(o))try{let s=JSON.parse(me__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function Ta(e="user"){let t=Tu(e);if(!me__default.existsSync(t))return {};try{return JSON.parse(me__default.readFileSync(t,"utf-8"))}catch{return {}}}function ku(e,t="user"){Cu(Tu(t),e);}function wy(e,t){let{name:r,marketplace:n}=so(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>so(i).name===r)[0],!o)throw Xe.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Sy(e,t){let{name:r,marketplace:n}=so(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>so(i).name===r)[0],o?{key:o,name:r}:null}function Ia(e="user"){return Ta(e).enabledPlugins??{}}function ba(e,t="user"){let r=Ta(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,ku(r,t);}function io(e,t,r="user"){let n=Ta(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},ku(n,r);}function xy(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function Q(){let e=Ye(),t=Ia(),r=Ia("project"),n=Ia("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=so(u),p=c.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return xy(p).map(g=>{let h=yy(g.installPath,d),I=(o[g.scope]??t)[u];return {name:d,marketplace:m,version:g.version&&g.version!=="unknown"?g.version:void 0,installedAt:g.installedAt,installPath:g.installPath,scope:g.scope,providerId:g.providerId,type:g.type,description:h?.description,author:h?.author,status:I===false?"disabled":"enabled"}})}),i=Eu(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}async function ao(e,t){Xe.debug(`[${e}] Acquiring lock to uninstall`);let r=await mr();try{let n=Ye(),o=Sy(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);Xe.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),Ls(l.installPath);let u=pe__default.dirname(l.installPath);Ls(u),Xe.debug(`[${i}] Removing directory: ${u}`),me__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...m}=n.plugins;qe({...n,plugins:m}),ba(s,t),wa(i);}else n.plugins[s]=c,qe(n),ba(s,t);}else {Xe.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Ls(c.installPath);let d=pe__default.dirname(c.installPath);Ls(d),Xe.debug(`[${i}] Removing directory: ${d}`),me__default.rmSync(d,{recursive:!0,force:!0}),ba(s,c.scope);}wa(i);let{[s]:l,...u}=n.plugins;qe({...n,plugins:u});}await my(i,a[0].origin??"internal",a[0].type??"skill"),Xe.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function lo(e,t,r){Xe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await mr();try{let o=Ye(),{key:s,name:i}=wy(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";Xe.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),io(s,t==="enabled",l),fy(i,t,u),Xe.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var Iy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,by=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function pt(e){if(!Iy.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function vy(e){if(!by.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 fr=x("installer");function Py(e,t){let r=`${e}@${W}`,o=Ye().plugins[r];if(o&&!t)throw new Ne(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function Ey(e,t,r){r&&await ha(t);try{fr.debug(`[${t}] Extracting archive...`),await yu(e,t);}catch(n){throw await ha(t),n}}function Ty(e,t,r,n,o,s="claude-code",i){let a=Ye(),l={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],qe(a),io(e,true,n);}async function Cy(e,t,r,n,o,s){try{await E(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:J().interfaceType});}catch(i){fr.warn(`Failed to send install metrics: ${String(i)}`);}}async function ky(e,t,r,n){try{await E(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:J().interfaceType});}catch(o){fr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Ce(e,t={}){let r=Date.now(),n=null;try{fr.debug(`[${e}] Acquiring lock...`),n=await mr();let{pluginKey:o,alreadyInstalled:s}=Py(e,t.force);fr.debug(`[${e}] Fetching manifest...`);let i=await Sn(e);pt(i.name),vy(i.version),fr.debug(`[${e}] Downloading archive...`);let a=await hu(e,t.onDownloadProgress),l=t.scope??"user",u=t.type??"skill",c=Cl(i.name,i.version);await Ey(a,c,!!s&&!!t.force),Ty(o,c,i.version,l,"internal",t.providerId,u),Iu(i,c);let d=Date.now()-r;fr.debug(`[${e}] Installed successfully in ${d}ms`);let m={name:i.name,version:i.version,path:c,duration_ms:d};return t.skipMetrics||await Cy(i.name,i.version,d,Es(l),"internal",u),m}catch(o){throw await ky(e,o,"internal",t.type??"skill"),fr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var Ay=x("commands:helpers");async function ne(){let e=await X();if(!e)return T("Not authenticated. Run: flow auth login"),false;e.customUrl&&St(e.customUrl);try{await xt();}catch(t){return Ay.debug(`Token validation failed: ${String(t)}`),T("Session expired. Run: flow auth login"),false}return true}async function Tt(e){let t=Ca.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 Au(e){let t=Ca.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var In=x("claudeProxy"),La="claude ",$u="flow ",ka=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},xn=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";}},$y=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Ly=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,My={"--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}$/},Ry=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,_y=/^(flow|claude)\s+auth\s+login(\s|$)/,Lu=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Mu(e){return Lu.test(e.trim())}function Dy(e){return Lu.exec(e.trim())?.[2]??""}async function Ru(e){let t=Dy(e);fa(t);let r=Date.now();In.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw Ma(n)?new Aa:n}}function Oy(e){_u(e);let t=e.slice(La.length);if(!$y.test(t))throw new xn(e)}var Ms=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},Aa=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function _u(e){if(!e||!/^claude /.test(e))throw new ka(e)}function Uy(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!Ly.test(r))throw new xn(`Unexpected flag: ${r}`);let n=My[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new xn(`Flag ${r} requires a value`);if(!n.test(o))throw new xn(`Unsafe value for flag ${r}`);t++;}}}async function xe(e){_u(e);let t=e.slice(La.length).split(/\s+/).filter(Boolean);Uy(t);let r=Ny(t);In.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 In.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${s}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:s}}catch(o){throw Ma(o)?new Ms:o}}function Ny(e){return e.length>=3?e[2]:e.join(" ")}function Ma(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function By(e){return e.startsWith($u)?La+e.slice($u.length):e}function Fy(e){return Ry.test(e)||_y.test(e)}function jy(e){let t=0;for(;t<e.length&&Fy(e[t]);)t++;return e.slice(t)}var Ky=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Vy(e,t){return !t||e.includes("--scope")||!Ky.test(e)?e:`${e} --scope ${t}`}async function co(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=jy(r).map(i=>By(i)).map(i=>Vy(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Oy(i);In.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await xe(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await xe(o[i]),s.exitCode!==0)return s;return s}async function Rs(e,t,r){let n=hn(e),o=t?.trim();if(!o&&(o=(await Au(`Plugin "${n}" could not be installed.
|
|
111
|
-
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=ks(o),r?.(),In.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"}`);In.debug(`[${n}] Marketplace added successfully`);}catch(s){throw Ma(s)?new Ms:s}}var zy=6e4,gr=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 Ct(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:zy}}).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 gr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new gr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new gr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function kt(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm$1(e,{recursive:true,force:true});}async function Kr(e,t=["--version"]){try{return (await execa(e,t,{reject:!1})).exitCode===0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return false;throw r}}function qy(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Yy(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Zy(e){return typeof e=="object"&&e!==null&&e.source==="github"}function bn(e,t){let r=e.source;if(qy(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(Yy(r))return {cloneUrl:r.url,subPath:"."};if(Zy(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function Ze(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var At=x("claude-code.adapter");function tw(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=Do();if(!me__default.existsSync(s))return r;try{let i=JSON.parse(me__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 ju(e,t){let r=e.catalogId?ie.getAdapter(e.catalogId):void 0,n=bn(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=tw(e.catalogId,r?.source),i=t.scope??"user",a;o?a=ki(s,e.name,"external"):a=join(Er(i==="user"?"global":"project"),e.name);let l=null;try{pt(e.name),l=await Ct(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(me__default.existsSync(a)&&me__default.rmSync(a,{recursive:!0,force:!0}),me__default.mkdirSync(dirname(a),{recursive:!0}),me__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Ea(),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],qe(d),io(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return At.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await kt(l).catch(()=>{});}}async function Ra(e,t,r,n){try{await E(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:Es(n),version:"unknown",duration_ms:t,interface:J().interfaceType});}catch(o){At.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Bu(e,t,r){try{await E(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:J().interfaceType});}catch(n){At.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var rw={async install(e,t){if(e.origin===qr&&!e.installCommand&&!gn(e.name))return ju(e,t);if(e.origin===qr&&e.installCommand){let r=e.type??"skill",n=await co(e.installCommand,t.scope);return n.exitCode===0?(await Ra(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Bu(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(gn(e.name)){let r=e.type??"skill",n=yn(e.name,t.scope);At.debug(`[${e.name}] Attempting install: ${n}`);let o=await xe(n);if(o.exitCode===0)return await Ra(e.name,o.duration_ms,r,t.scope),{success:true};At.debug(`[${e.name}] First attempt failed, adding marketplace`),await Rs(e.name,t.marketplaceSource,()=>{});let s=await xe(n);return s.exitCode===0?(await Ra(e.name,s.duration_ms,r,t.scope),{success:true}):(await Bu(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 Ce(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return At.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await ao(e,t);},getInstallPath(e,t){return ""}};function Fu(e){return {async install(t,r){if(t.origin===qr&&!t.installCommand&&!gn(t.name))return ju(t,r);if(!t.installCommand)try{let o=await Ce(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return At.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}At.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await co(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=Ye(),o=`${t}@${W}`;if(n.plugins[o]){await ao(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 nw(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!me__default.existsSync(t))continue;let r=me__default.readdirSync(t).filter(n=>n.endsWith(".md")&&me__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function _a(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,_a(r)]))}function Ku(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(_a(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(_a(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Ku(s,o):r[n]=o;}return r}async function Vu(e,t,r,n){let o=await Ea(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],qe(o);}var ow={async install(e,t){let r=t.scope??"user",n=e.catalogId?ie.getAdapter(e.catalogId):void 0,o=bn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{pt(e.name),s=await Ct(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=nw(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Uo(r);me__default.mkdirSync(l,{recursive:!0});let u=Ze(e.name);if(a.length===1)me__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=Ze(basename(d,".md"));me__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await Vu(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return At.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await kt(s).catch(()=>{});}},async uninstall(e,t){let r=Uo(t),n=Ze(e);if(me__default.existsSync(r))for(let a of me__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))me__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Ye(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;qe({...s,plugins:l});}else qe({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Uo(t),`${Ze(e)}.md`)}},sw={async install(e,t){let r=t.scope??"user",n=e.catalogId?ie.getAdapter(e.catalogId):void 0,o=bn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{pt(e.name),s=await Ct(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!me__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(me__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=qn();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=Ku(m,u);return os({...d,hooks:p}),await Vu(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return At.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await kt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},_s=class{id="claude-code";name="Claude Code";async isAvailable(){return Kr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:rw,skill:Fu("skill"),mcp:Fu("mcp"),agent:ow,hook:sw}};function Ds(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 aw=new Set(["gh"]),lw=Ds(aw,"use: gh copilot mcp remove <name>"),Os=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Kr("gh",["--version"])?Kr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:lw}};var cw=new Set(["opencode"]),uw=Ds(cw,"use: opencode config remove mcp <name>");function dw(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
112
|
-
`)}function Ju(){return {async install(e,t){try{pt(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?ie.getAdapter(e.catalogId):void 0,n=bn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Ct(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Oo(t.scope??"user"),a=join(s,".opencode","plugins");if(me__default.existsSync(a)){let l=me__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/"};me__default.mkdirSync(i,{recursive:!0}),me__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);me__default.existsSync(l)&&me__default.rmSync(l,{recursive:!0,force:!0}),me__default.mkdirSync(l,{recursive:!0}),me__default.cpSync(s,l,{recursive:!0}),me__default.mkdirSync(i,{recursive:!0}),me__default.writeFileSync(join(i,`${e.name}.js`),dw(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 kt(o).catch(()=>{});}},async uninstall(e,t){pt(e);let r=Oo(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);me__default.existsSync(n)&&me__default.rmSync(n,{force:true}),me__default.existsSync(o)&&me__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Oo(t),`${e}.js`)}}}var Us=class{id="opencode";name="OpenCode";async isAvailable(){return Kr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:uw,skill:Ju(),bundle:Ju()}};var $t=new Ps;$t.register(new _s);ir()&&($t.register(new Os),$t.register(new Us));function Hu({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(()=>{$t.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(h=>{h==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(h=>{if(h==="Cancel"){a(false);return}let w=l.find(I=>I.name===h);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(h=>{let w=nu(h);w?r(w,c):s(false);},[r,c]),g=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(w=>w.name),"Cancel"];return jsx(ze,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(ze,{itemName:`${e} \u2014 Choose scope`,actions:tu,descriptions:ru,onAction:f,onClose:g},"scope"):jsx(ze,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function Wu({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,g)=>{g.upArrow?a(h=>Math.max(0,h-1)):g.downArrow?a(h=>Math.min(d.length-1,h+1)):g.return?d[i]==="Confirm Install"?n():o():g.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(f=>{let g=y(f.name??f.flowId),h=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:g}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,g)=>jsx(Box,{children:jsxs(Text,{bold:g===i,color:g===i?"cyan":void 0,children:[g===i?"\u203A ":" ",f]})},f))})]}):jsx(ze,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Fs({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function qu({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Fs({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(ze,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:h=>{h==="Uninstall"?c():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function Qu({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Fs({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(ze,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var En=x("bundle:installer"),ed=/already exists/i;async function Sw(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Mu(t)){let r=await Ru(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(ed.test(n))return;throw new Error(n)}}else {let r=await co(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(ed.test(n))return;throw new Error(n)}}}async function xw(e,t){try{await E(v.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){En.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function Iw(e,t,r){try{await E(v.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){En.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function td(e,t,r,n){try{await E(v.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){En.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function bw(e,t,r,n,o){try{await E(v.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){En.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Vs(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 xw(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let g=f.name??f.flowId,h=f.type??"unknown";if(!f.type){En.warn(`Artifact "${g}" has no type \u2014 treated as failed`),l.push({name:g,type:h,reason:"unknown artifact type"}),await td(i,g,h,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await Sw(f),u++,await Iw(i,g,h),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let I=w instanceof Error?w.message:String(w);En.error(`Failed to install artifact "${g}": ${I}`),l.push({name:g,type:h,reason:I}),await td(i,g,h,I),r?.({index:p+1,total:c,artifact:f,success:false,error:I});}}let d=Date.now()-a,m=l.length;return await bw(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}function sd({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Vs(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(od,{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(od,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ae=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:Q()})}));function id({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 ",wt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function ad({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 ${wt(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((g,h)=>{let w=h===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:g.danger?"yellow":void 0,dimColor:!w,children:g.label})]},g.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children: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 ld(e){return e.adapter.removable!==false?4:2}function cd({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 dd({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 pd({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(P=>r.has(`${P.name}@${o}`)),i=t.filter(P=>!r.has(`${P.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((P,A)=>{if(A.escape){n();return}if(A.return){d(a[l]??null);return}if(A.upArrow){u(_=>Math.max(0,_-1));return}A.downArrow&&u(_=>Math.min(a.length-1,_+1));},{isActive:c===null}),c!==null)return jsx(cd,{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(Ve/2)),p=Math.min(a.length,m+Ve);p===a.length&&(m=Math.max(0,p-Ve));let f=a.slice(m,p),g=m,h=a.length-p,w=s.length>0&&m<s.length,I=p>s.length,R=f.filter(P=>r.has(`${P.name}@${o}`)),B=f.filter(P=>!r.has(`${P.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),R.map(P=>jsx(dd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:true},P.name))]}),I&&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"]}),B.map(P=>jsx(dd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:false},P.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2193 ${h} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}ga();var Aw=/^https?:\/\/.+/;function $w(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Lw(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function hd(e){let t=S(h=>h.showNotification),r=S(h=>h.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");},[]),g=useCallback(async()=>{let h=m.current,w=d.current;if(!Aw.test(h)){c("URL must start with http:// or https://");return}c(null),o("adding");let I=randomUUID(),R=new wn(I,w,h);try{await R.fetchItems(),await jt.add({id:I,name:w,source:h}),ie.register(new wn(I,w,h)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(B){let P=$w(B)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Lw(B)?B.message:B instanceof Error?`Could not reach catalog URL: ${B.message}`:"Failed to validate catalog URL";t(P,"error"),o("add-url");}},[e,t,r]);return useInput((h,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!w.ctrl&&!w.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,w)=>{if(w.escape){o("add-name");return}if(w.return){g();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}h&&!w.ctrl&&!w.meta&&(m.current=m.current+h,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 yd(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await jt.remove(o),ie.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 Sd(){let e=S(L=>L.focus),t=S(L=>L.setFocus),r=S(L=>L.showNotification),n=ae(L=>L.installedItems),[o,s]=useState(()=>ie.listAdapters().map(L=>({adapter:L,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[f,g]=useState("main"),h=useRef(o);useEffect(()=>{h.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&g("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let L=ie.listAdapters(),N=await jt.read(),H=new Map(N.map(be=>[be.id,be]));s(L.map(be=>({adapter:be,stored:H.get(be.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let L=h.current[i-1];if(!L)return;let N=false;return p({items:[],loading:true,error:null}),L.adapter.fetchItems().then(H=>{N||p({items:H,loading:false,error:null});}).catch(H=>{N||p({items:[],loading:false,error:H instanceof Error?H.message:"Failed to load catalog"});}),()=>{N=true;}},[i]);let I=hd(w),R=useCallback(()=>{w(),a(0),u("list"),p(null),g("main");},[w]),{handleRemove:B}=yd(R),P=useCallback(async L=>{g("removing"),await B(L);},[B]),A=useCallback(async L=>{try{let N=await L.adapter.fetchItems();if(p({items:N,loading:!1,error:null}),L.stored){let H=new Date().toISOString();await jt.updateField(L.stored.id,{lastUpdated:H}),w();}r("Marketplace updated","success");}catch(N){r(N instanceof Error?N.message:"Update failed","error");}},[w,r]),_=useCallback(async L=>{if(!L.stored)return;let N=L.stored.autoUpdate!==false;await jt.updateField(L.stored.id,{autoUpdate:!N}),w();},[w]),j=useCallback(()=>g("browse"),[]),fe=useCallback(L=>{let N=o[i-1];if(!N)return;let H=N.adapter.removable!==false;[j,()=>{A(N);},...H?[()=>{_(N);},()=>{P(N.adapter.id);}]:[]][L]?.();},[o,i,j,A,_,P]),b=useCallback(()=>g("main"),[]),$=useCallback(()=>{let L=o[i-1];L&&A(L);},[o,i,A]),F=useCallback(()=>{let L=o[i-1];L&&_(L);},[o,i,_]),D=useCallback(()=>{let L=o[i-1];L&&P(L.adapter.id);},[o,i,P]);if(useInput((L,N)=>{if(N.upArrow){a(H=>Math.max(0,H-1));return}if(N.downArrow){a(H=>Math.min(o.length,H+1));return}(N.return||N.tab)&&(i===0?I.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&I.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((L,N)=>{if(N.escape||N.tab){u("list");return}if(N.upArrow){d(H=>Math.max(0,H-1));return}if(N.downArrow){let H=o[i-1],be=H?ld(H)-1:0;d(Lo=>Math.min(Lo+1,be));return}N.return&&fe(c);},{isActive:f==="main"&&I.phase==="idle"&&l==="detail"&&e==="marketplaces"}),I.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:I.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),I.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(I.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:I.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:I.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),I.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:I.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(I.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 L=o[i-1];if(!L)return jsx(Box,{});let N=L.adapter.id??"default",H=new Set(n.filter(be=>be.marketplace===L.adapter.name).map(be=>`${be.name}@${N}`));return jsx(pd,{entry:L,items:m?.items??[],installedKeys:H,onBack:b})}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 ue=o[i-1]??null,Xr=ue?n.filter(L=>L.marketplace===ue.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(id,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&ue?jsx(ad,{entry:ue,detailData:m,installedCount:Xr,focusPanel:l,actionIndex:c,onBrowse:j,onUpdate:$,onToggleAutoUpdate:F,onRemove:D}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:ue?"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 xd(e,t,r,n){if(t.upArrow)return r.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:r.selectedIndex-1}];if(t.downArrow&&r.selectedIndex<n-1)return [{type:"setSelectedIndex",index:r.selectedIndex+1}];if(t.leftArrow){let o=q.findIndex(i=>i.id===r.activeTab),s=q[(o-1+q.length)%q.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=q.findIndex(i=>i.id===r.activeTab),s=q[(o+1)%q.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=q.findIndex(i=>i.id===r.activeTab),s=q[(o+1)%q.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="a"&&r.activeTab==="updates"?[]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function Id(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function bd(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 Ow=new Set(q.filter(e=>e.focus!=="list").map(e=>e.focus));function xo(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}=Ue.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 vd({listLength:e}){let t=S(g=>g.focus),r=S(g=>g.selectedIndex),n=S(g=>g.actionMenuOpen),o=S(g=>g.setFocus),s=S(g=>g.setActionMenuOpen),i=Ue(g=>g.query),a=Ue(g=>g.setQuery),l=Ue(g=>g.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:h}=Ue.getState();h(g.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,h)=>{let{activeTab:w,selectedIndex:I,actionMenuOpen:R}=S.getState();xo(ta(g,h,{activeTab:w}));},{isActive:t==="tabs"}),useInput((g,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:w,selectedIndex:I,actionMenuOpen:R}=S.getState();xo(ta("",h,{activeTab:w}));},{isActive:Ow.has(t)}),useInput((g,h)=>{let{activeTab:w,selectedIndex:I,actionMenuOpen:R}=S.getState();xo(xd(g,h,{activeTab:w,selectedIndex:I},u.current));},{isActive:t==="list"}),useInput((g,h)=>{xo(Id(g,h));},{isActive:t==="actionMenu"}),useInput((g,h)=>{let w=bd(g,h,Ue.getState().query),I=w.queryUpdate;if(xo(w.actions),I==="reset")l(),d("");else if(I!==null){let{query:R,cursorPosition:B,setCursorPosition:P}=Ue.getState();if("backspace"in I)B>0&&(a(R.slice(0,B-1)+R.slice(B)),P(B-1));else if("append"in I)a(R.slice(0,B)+I.append+R.slice(B)),P(B+I.append.length);else if("cursorMove"in I){let A=B+I.cursorMove;A>=0&&A<=R.length&&P(A);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:w}=S.getState();g===0?h(0):w>=g&&h(g-1);},[]),f=useCallback(g=>{if(!c)return u.current=g.length,g;let h=c.toLowerCase(),w=g.filter(I=>I.name.toLowerCase().includes(h)||I.description?.toLowerCase().includes(h));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Ed(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=Ge(a=>a.justAuthenticated),o=Ge(a=>a.credentials),s=Ge(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function $e(e,t,r=false){return r?true:!Ba.valid(e)||!Ba.valid(t)?false:Ba.gt(t,e)}var Jt=x("updater");async function Uw(e,t,r,n,o,s){try{await E(v.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:J().interfaceType});}catch(i){Jt.warn(`Failed to send update metrics: ${String(i)}`);}}function Nw(e){let t=Ye(),r=`${e}@${W}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Ws(e,t={}){let r=Date.now(),n=null;try{Jt.debug(`[${e}] Acquiring lock...`),n=await mr();let o=Nw(e);if(!o)throw Jt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Jt.debug(`[${e}] Fetching manifest...`);let u=(await Sn(e)).version;if(!i||!$e(i,u,t.force))throw Jt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new dr(e,i??"unknown");Jt.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await Ce(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await Uw(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),Jt.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){Jt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await mr();let d=Ye(),m=`${e}@${W}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,qe(d),Jt.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}var zs=x("dispatcher");async function Bw(e,t,r,n,o){let s=hn(e);return zs.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Rs(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),zs.debug(`[${e}] Retrying install after marketplace add`),xe(t)}async function Td(e,t,r,n){let o=yn(e,n),s=hn(e);r?.onStatus?.(`Installing ${s}...`),zs.debug(`[${e}] Attempting install: ${o}`);let i=await xe(o);if(i.exitCode===0)return i;zs.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Bw(e,o,a,t,r)}async function Cd(e,t,r){let n=e.type??"bundle",o=await $t.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 kd(){let e=ae(i=>i.installedItems),t=ae(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Cd(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=Q().find(p=>p.name===i),u=l?.providerId??"claude-code",c=$t.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 lo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await Ws(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var qs=x("mcp");function Io(e,t){e.silent?He({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):T(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function $d(e,t){e.silent?De({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(re(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function Fw(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 Fa(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 Ld(e,t,r){if(!await ne())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Io(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}qs.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Fw(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await Tt(`Install external MCP "${s}"?
|
|
110
|
+
`),this.warned=true;}Yo().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Yo(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return Yo().path}static hasExistingData(){try{let t=new Ji({projectName:Hi});return he.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Ji({projectName:Hi});he.rmSync(t.path,{force:!0});}catch{}Zo=null;}};async function Gi(){if(Ue.hasExistingData())return new Ue;switch(process.platform){case "darwin":return await an.isAvailable()?new an:new Ue;case "linux":return await or.isAvailable()?new or:await or.ensureInstalled()?new or:new Ue;case "win32":return await cn.isAvailable()?new cn:new Ue;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var zl=x("config:credentials"),Nt="flow-plugins-cli",Wi="credentials",zi="token-cache",Xi="user-info",ts=null;async function sr(){return ts||(ts=Gi()),ts}function rs(){ts=null;}async function Y(){let t=await(await sr()).getSecret(Nt,Wi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Bt(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw zl.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await sr()).setSecret(Nt,Wi,JSON.stringify(e));}async function Xl(){let e=await sr();await e.deleteSecret(Nt,Wi),await e.deleteSecret(Nt,zi),await e.deleteSecret(Nt,Xi);}async function ql(){return (await sr()).getStoragePath()}async function Yl(e){await(await sr()).setSecret(Nt,zi,JSON.stringify(e));}async function ns(){let t=await(await sr()).getSecret(Nt,zi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function os(e){await(await sr()).setSecret(Nt,Xi,JSON.stringify(e));}async function ss(){let t=await(await sr()).getSecret(Nt,Xi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ir(){let e=await ns();return e?new Date(e.expiresAt)>new Date:false}function It(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,zl.debug(`[customUrl] Service URLs overridden to base: ${t}`);}function un(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}dn();var Yi=x("api:auth");function ng(e){if(!Ut.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Ql={INVALID_CLIENT_SECRET:"Invalid Client Secret \u2014 check the value and try again",INVALID_CLIENT_ID:"Invalid Client ID \u2014 check the value and try again",INVALID_TENANT:"Invalid Tenant \u2014 check the value and try again",TENANT_NOT_FOUND:"Tenant not found \u2014 verify the tenant identifier"};async function og(e){if(e instanceof HTTPError){let t=e.response.status;Yi.debug(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&Ql[r]?new Error(Ql[r]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Yi.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Yi.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function $r(e){let t=ar("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");ng(e.tenant);let r;try{r=await yu.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await og(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Bt(e),await Yl({accessToken:r.access_token,expiresAt:n});let o=un(r.access_token);await os({sub:o.sub,name:o.name,email:o.email});}var ec=x("lib:tokenProvider");async function bt(){if(await ir()){let n=await ns();if(n)return n.accessToken}ec.debug("Token expired or missing, re-authenticating...");let t=await Y();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ue.clearFallbackFile(),rs(),await $r(t);let r=await ns();if(!r)throw new Error("Authentication succeeded but token was not persisted");return ec.debug("Token refreshed successfully"),r.accessToken}dn();var is=x("api:metrics");function tc(){return ar("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function rc(e,t,r){return yu.post(e,{json:t,headers:r})}async function ig(e){let t=await ss();if(t)return t;let r=un(e),n={sub:r.sub,name:r.name,email:r.email};return await os(n),n}async function v(e,t){let r=await bt(),n=await ig(r),o=await Y();if(!Ut.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:ki,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await rc(tc(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),is.debug(`Metrics event sent: ${e}`);}catch(i){throw is.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function nc(e,t,r){try{let n=r&&Ut.test(r)?r:"unknown",o={action:e,booster:ki,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await rc(tc(),o,{FlowTenant:n}),is.debug(`Anonymous metrics event sent: ${e}`);}catch(n){is.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var b={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED"};var ag={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},lt={...ag};function oc(e){let t=Date.now();lt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Lr(e){lt.currentStep=e,lt.stepStart=Date.now();}function H(){return {...lt}}function lr(){return lt.sessionStart===0?0:Date.now()-lt.sessionStart}function Mr(){return lt.stepStart===0?0:Date.now()-lt.stepStart}function sc(){lt.tuiSessionStart=Date.now();}function ic(){return lt.tuiSessionStart===0?0:Date.now()-lt.tuiSessionStart}var lg=3e3,cg=x("abandonment");async function as(e){let{currentStep:t,sessionStart:r}=H();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:lr()};try{await Promise.race([v(b.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),lg))]);}catch(o){cg.warn(`Abandonment event failed: ${String(o)}`);}}function ac(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var ug=3e3,dg=x("session-end");async function Wn(e,t,r){let n=ic(),s=[v(b.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(as(e));try{await ac(Promise.all(s).then(()=>{}),ug);}catch(i){dg.warn(`Session end event failed: ${String(i)}`);}}var gg=2e3;function cc(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),Wn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},gg);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Sg=16;function uc({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,u)=>{if(u.backspace){let c=i.current.slice(0,-1);i.current=c,r(c);}else if(l&&!u.ctrl&&!u.meta&&!u.escape&&!u.return&&!u.tab&&!u.upArrow&&!u.downArrow&&!u.leftArrow&&!u.rightArrow){let c=i.current+l;i.current=c,r(c);}},{isActive:o});let a=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(Sg)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}function dc({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="n"||l==="N"){r("input");return}(l==="y"||l==="Y"||u.return)&&e(null);return}if(u.escape){a.current="",o(""),i(false),r("confirm");return}if(u.return){let c=a.current.trim();rn.test(c)?(i(false),e(c)):i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[t==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:nn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}function pc({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[rr," \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)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}function mc(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[rr," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var We=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));function Ur(){return ge__default.join(Pe__default.homedir(),".claude","settings.json")}function eo(){let e=Ur();if(!he__default.existsSync(e))return {status:"missing"};let t=he__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 cs(e){let t=Ur();he__default.mkdirSync(ge__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;he__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),he__default.renameSync(r,t);}function gc(e,t){let r=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...r,ANTHROPIC_AUTH_TOKEN:t}}}function oa(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}var Tg=3600,Nr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function to(e){let t=e.split(".");if(t.length!==3)throw new Error("Malformed JWT: invalid format");let r;try{r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed JWT: payload must be a JSON object");let n=r;if(typeof n.clientId!="string"||!n.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(n.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(n.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(n.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function Cg(e){return Pg.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Tg})}function us(e,t={}){let r=eo();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Nr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?oa(r.settings):null,s=t.jwtOverride??Cg(e),i=gc(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function ds(e){cs(e.merged);}function hc(){let e=eo();return e.status!=="ok"?false:oa(e.settings)!==null}function kg(){let e=Bl();if(!he__default.existsSync(e))return {};try{return JSON.parse(he__default.readFileSync(e,"utf-8"))}catch{return {}}}var sa=null;function Ag(){return sa===null&&(sa=kg()),sa}function cr(){return !!Ag().ENABLE_EXPERIMENTAL_BETAS}function Rg(){return ee.filter(e=>e.platforms[process.platform]?.status==="supported")}function wc(e){let t=Rg();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var ps={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=ge__default.join(Pe__default.homedir(),".claude","settings.json"),r=he__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??Ll),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"}},_g={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},ee=cr()?[ps,_g]:[ps];var Ng=x("moduleState");function fs(){let e=process.env.FLOW_HOME??ge__default.join(Pe__default.homedir(),".flow");return ge__default.join(e,"modules.json")}var Bg={retries:5,minTimeout:50};async function Sc(e,t){he__default.mkdirSync(ge__default.dirname(e),{recursive:true});let r=await Ug.lock(e+".lock",{realpath:false,retries:Bg});try{return await t()}finally{await r();}}function xc(){let e=fs();if(!he__default.existsSync(e))return [];try{let t=JSON.parse(he__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Ng.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),he__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return he__default.rmSync(e,{force:true}),[]}}function Br(){return xc()}function Ic(e){let t=fs();he__default.mkdirSync(ge__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};he__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),he__default.renameSync(r,t);}function ze(e){return Br().find(t=>t.alias===e)??null}async function ct(e){let t=fs();await Sc(t,async()=>{let r=xc(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,Ic(r);});}async function Fr(){let e=fs();he__default.existsSync(e)||await Sc(e,async()=>{he__default.existsSync(e)||Ic([]);});}var Kg=promisify(execFile);function ur(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Et(e){let t=process.platform==="win32"?"where":"which";try{return await Kg(t,[e]),!0}catch{return false}}function Ft(){return process.platform==="win32"?"npm.cmd":"npm"}var bc=promisify(execFile),mn=class{type="npm";async isAvailable(){return Et("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=ur(t,"npm");if(!r)return null;try{let{stdout:n}=await bc(Ft(),["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=ur(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 bc(Ft(),["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 gs=promisify(execFile),Wg=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,hs=class{type="homebrew";async isAvailable(){return Et("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=ur(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=ur(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 gs("brew",["tap",o.tap]),await gs("brew",["trust",o.tap])),await gs("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 gs("brew",["list","--versions",t]),n=r.trim().match(Wg);return n?n[2]:null}catch{return null}}};var fn=promisify(execFile),Ec=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Pc(){let e=process.env.FLOW_HOME??ge__default.join(Pe__default.homedir(),".flow");return ge__default.join(e,"bin")}var ys=class{type="curl";async isAvailable(){return Et("curl")}async install(t){let r=Date.now(),n=ur(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=ge__default.join(Pc(),ge__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await fn(n,["--version"]),s=o.match(Ec);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=ge__default.join(Pe__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await fn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{he__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return he__default.chmodSync(s,448),await fn("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{he__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=Pc(),i=ge__default.join(s,ge__default.basename(n.binaryName)),a=false;try{if(he__default.mkdirSync(s,{recursive:!0}),a=!0,await fn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return he__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}he__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await fn(i,["--version"]),c=u.match(Ec);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{he__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=ge__default.join(Pe__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await fn("curl",["-L","--fail","-o",n,r]);let o=he__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=he__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{he__default.unlinkSync(n);}catch{}}}};var Tc="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Tc=e.version);}catch{}var ae=Tc;var xe=x("moduleInstaller");function Tt(e){switch(e){case "npm":return new mn;case "homebrew":return new hs;case "curl":return new ys}}async function ro(e,t,r){try{await v(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){xe.warn(`Failed to emit install failed event: ${String(n)}`);}}async function pr(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){xe.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let d={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await ro(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(a.status!=="supported"){let d={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await ro(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(!a.strategies.some(d=>d.type===r)){let d={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await ro(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=Tt(r),u=false;try{u=await l.isAvailable();}catch(d){xe.warn(`${r} availability check failed: ${String(d)}`);}if(!u){let d={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await ro(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await v(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ae,trigger:t});}catch(d){xe.warn(`Failed to emit install started event: ${String(d)}`);}let c;try{c=s?.forceLatest?await l.update(e,"unknown"):await l.install(e);}catch(d){let m=d instanceof Error?d.message:String(d);xe.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await ct({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await v(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:t});}catch(p){xe.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await eh(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await ro(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function eh(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 Y(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return xe.warn(`postInstall function threw: ${String(u)}`),{pendingCmd:null,failed:false}}}else s=o;if(s.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:s[0]??null,failed:false};let i=false;for(let a=0;a<s.length;a++){let l=s[a];if(l.length===0)continue;let u=spawnSync(l[0],l.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(u.status!==0){i=true,xe.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&xe.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&xe.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function ws(e,t){let r=Date.now(),n=ze(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Tt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await v(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ae,trigger:"command"});}catch(a){xe.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);xe.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await ct({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await v(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){xe.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await v(b.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){xe.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await v(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){xe.warn(`Failed to emit update failed event: ${String(a)}`);}return i}var Ss=x("flowAiObsSetup");async function no(e,t){try{if(!await new mn().isAvailable().catch(()=>!1))return Ss.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await pr(ps,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(Ss.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Ss.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return Ss.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}function Cc(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 kc=x("useAuthSetup");function Ac(){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:I}=We(),_=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},R=()=>{v(b.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:lr(),interface:"tui"}).catch(()=>{});},P=async()=>{g.current=true;let $={...r.current,customUrl:n.current??void 0};try{await Bt($);}catch(A){l(A instanceof Error?A.message:"Failed to persist credentials"),_(),g.current=false;return}let{clientSecret:j,...Se}=$;w(Se),I(true),R(),await no(n.current,o.current).catch(A=>kc.warn(`installFlowAiObs threw unexpectedly: ${String(A)}`)),so({starterKit:Se.starterKit});},L=async $=>{g.current=true;let j={...r.current,customUrl:n.current??void 0};try{ds($),await Bt(j);}catch(O){l(O instanceof Error?O.message:"Failed to persist credentials"),_(),g.current=false;return}let{clientSecret:Se,...A}=j;w(A),I(true),R(),await no(n.current,o.current).catch(O=>kc.warn(`installFlowAiObs threw unexpectedly: ${String(O)}`)),so({starterKit:A.starterKit});},D=$=>{try{return us(r.current,{allowOverwriteMalformed:$,jwtOverride:e.trim()})}catch(j){return j instanceof Nr?(m("malformedConfirm"),null):(l(j instanceof Error?j.message:"Failed to read settings.json"),m("fields"),null)}},N=()=>{let $=D(true);$&&(f($),L($));},z=async()=>{let $=e.trim();if(!$){i("This field is required");return}let j;try{j=to($);}catch(Se){i(Se instanceof Error?Se.message:"Invalid JWT");return}i(void 0),r.current=j,m("customUrl");},k=$=>{n.current=$,m("email");},F=$=>{o.current=$,G();},G=async()=>{let $=n.current;$&&It($),c(true),l(null),h.current+=1;try{await $r(r.current);let j=D(!1);j&&(f(j),m("preview"));}catch(j){let Se=j instanceof Error?j.message:"Authentication failed";l(Se),nc(b.CLI_AUTH_FAILED,{error_code:Cc(j),attempt:h.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:g,setJwtValue:t,setJwtError:i,cancelToFields:_,handleSubmit:z,goToEmailStep:k,handleEmailConfirm:F,commitAndProceed:L,skipJwtAndProceed:P,planPersistOverwrite:N}}function $c(){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}=Ac(),[g,w]=useState("confirm"),[I,_]=useState(""),R=useRef(""),[P,L]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),R.current="",_(""),L(false));},[o]),useInput((D,N)=>{if(!(n||i.current)){if(o==="preview"){N.return&&s?p(s):N.escape?f():D==="q"&&u();return}if(o==="malformedConfirm"){N.return?h():N.escape&&u();return}if(o==="customUrl"){if(g==="confirm")D==="y"||D==="Y"?w("input"):(D==="n"||D==="N"||N.return)&&d(null);else if(N.escape)R.current="",_(""),w("confirm");else if(N.return){let z=R.current.trim();z.length>0&&en.test(z)?(L(false),d(z)):z.length>0&&L(true);}else N.backspace||N.delete?(R.current=R.current.slice(0,-1),_(R.current)):D&&!N.ctrl&&!N.meta&&(R.current=R.current+D,_(R.current),L(false));return}o!=="email"&&N.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:[rr," \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:I}),jsx(Text,{color:"cyan",children:"\u2588"})]}),P&&jsx(Text,{color:"red",children:tn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[rr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(dc,{onConfirm:m})]}):o==="preview"&&s?jsx(pc,{plan:s}):o==="malformedConfirm"?jsx(mc,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[rr," \u2014 Initial Setup"]})}),jsxs(Box,{marginBottom:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."})]}),jsx(Box,{flexDirection:"column",children:jsx(Box,{marginBottom:1,children:jsx(uc,{label:"JWT",value:e,onChange:D=>{a(D),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function hn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(sh,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ae]})})]})}var _c=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],Z=cr()?_c:_c.slice(0,3);function ih(e){return Z.findIndex(t=>t.id===e)}function la(e,t,r){let n=ih(r.activeTab);if(t.rightArrow||t.tab){let o=Z[(n+1)%Z.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=Z[(n-1+Z.length)%Z.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:Z[n]?.focus??"list"}]:[]}var Uc={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Nc({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:Z.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${Uc[r]} (${e})`:Uc[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Ne=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Fc(){let e=S(i=>i.focus),t=Ne(i=>i.query),r=Ne(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var uh=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...Qr[e]})),dh=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...$l[e]}));function jc(){let e=S(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),uh.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"]})]}),dh.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function Kc({type:e}){let{label:t,color:r}=Qr[e];return jsx(Text,{color:r,children:t})}function Hc({origin:e}){return e===Fn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Is=fh.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(Kc,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Hc,{origin:t.origin})]}),jsxs(Text,{dimColor:true,children:[t.authorName?` \xB7 ${t.authorName}`:"",t.version?` \xB7 v${t.version}`:" \xB7 n/a"]}),t.status&&jsxs(Text,{color:n,children:[" [",t.status,"]"]}),t.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),t.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",xt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function yn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function zc({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(yn,{message:t});let n=Math.max(0,r-Math.floor(Je/2)),o=Math.min(e.length,n+Je);o===e.length&&(n=Math.max(0,o-Je));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(Is,{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 Yc({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function Qc({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(yn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Je/2)),u=Math.min(n.length,l+Je);u===n.length&&(l=Math.max(0,u-Je));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Yc,{label:p.label,pathHint:p.pathHint},p.key):jsx(Is,{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 bh={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function vh({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Fc,{}),jsx(jc,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:bh[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Qc,{groups:n,emptyMessage:r}):jsx(zc,{items:e,emptyMessage:r})]})}function eu({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(vh,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var Th={tabs:"\u2190\u2192: switch tab | \u2193: navigate | Enter: select | Ctrl+C Ctrl+C: quit",list:"\u2191\u2193: navigate | Enter: select | Type: 1=All 2=Skill 3=MCP 4=Bundle | Origin: 5=All 6=Flow 7=External | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",search:"Type to filter | \u2193/Esc: exit search | Enter: confirm",actionMenu:"\u2191\u2193: navigate options | Enter: confirm | Esc: close menu",auth:"Tab: next field | Enter: confirm | Ctrl+C Ctrl+C: quit",starterKitList:"\u2191\u2193: navigate | Enter: select Starter Kit | Esc: skip",starterKitDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select",moduleSetup:"\u2191\u2193: navigate | Space: toggle | Tab: change method | Enter: confirm",marketplaces:"\u2191\u2193: navigate | a: add catalog | d: remove catalog | r: refresh | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",verify:"\u2191\u2193: navigate | Enter: confirm | Ctrl+C Ctrl+C: quit",bundleInstallProgress:"Enter/Esc: back to catalog"};function bs(){let e=S(r=>r.focus),t=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[Th[e],t?" | Ctrl+D: debug log":""]})})}function tu({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 vs({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(pd,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function ga(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var su=20;function Es(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*su),s="\u2588".repeat(o)+"\u2591".repeat(su-o),i=`${ga(e)} / ${ga(t)}`;return {bar:s,percent:n,label:i}}function Ps({received:e,total:t}){let{bar:r,percent:n,label:o}=Es(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Ts({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function Xe({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}var Sa=Object.entries(jn),cu=[...Sa.map(([,e])=>e.actionLabel),"Cancel"],uu=Object.fromEntries(Sa.map(([,e])=>[e.actionLabel,e.description]));function du(e){let t=Sa.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var jh=x("provider.registry"),Kh=3e4,ks=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()+Kh}),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"&&jh.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 Vh={user:"global",project:"project",local:"local"};function As(e){return e?Vh[e]:"global"}var Be=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},fr=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};dn();function mt(){return yu.create({prefix:ar("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await bt();e.headers.set("Authorization",`Bearer ${t}`);let r=await Y();r?.tenant&&Ut.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Hh=x("catalog.registry"),$s=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);Hh.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var Qh={retries:5,minTimeout:50};async function xa(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Ug.lock(e+".lock",{realpath:false,retries:Qh});try{return await t()}finally{await r();}}var Ls=class{filePath;constructor(t){this.filePath=t??Nl();}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 xa(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 xa(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await xa(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};var ey=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function lo(e){if(!e||!ey.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var ty=/^[^@]+@[^@]+$/;function Sn(e){return ty.test(e)}function xn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var ry=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;function Ia(e){if(!ry.test(e))throw new Error(`Invalid plugin name: "${e}". Plugin names must start with an alphanumeric character and contain only letters, digits, dots, hyphens, underscores, and slashes.`)}function In(e,t){let r=xn(e);Ia(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var ny=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,oy=/^https:\/\/[\w./:@?&=+#%-]+$/;function Ms(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!ny.test(t)&&!oy.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var sy=x("catalog.flow-api"),Rs=class{id="flow-api";name="Flow Marketplace";source;removable=false;constructor(){this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await mt().get("v1/plugins/catalog").json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle"}))}catch(t){if(t instanceof HTTPError){let{status:r}=t.response;throw r===401||r===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${r}`)}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${t.message}`):t}}async fetchManifest(t){lo(t);try{return await mt().get(`v1/plugins/${t}/manifest`).json()}catch(r){if(r instanceof HTTPError){let{status:n}=r.response;throw n===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${n}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await mt().head("v1/plugins/catalog"),sy.debug("ping ok"),!0}catch{return false}}};var le=new $s,Kt=new Ls;le.register(new Rs);var xu=false;async function Iu(){if(xu)return;xu=true;let e=await Kt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(ba(),Su));for(let r of e)le.register(new t(r.id,r.name,r.source));}var bu=2;async function gr(){return le.fetchAll()}async function vu(){return le.fetchAllWithErrors()}async function vn(e){lo(e);try{return await mt().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function Eu(e,t){lo(e);try{let r=await mt().get(`v1/plugins/${e}/archive`),n=r.headers.get("x-archive-size"),o=n?Number(n):NaN,s=Number.isFinite(o)&&o>0?o:0,i=s>0,a=r.body;if(!a)throw new Error("Failed to download plugin: response has no body");let l=a.getReader(),u=[],c=0;for(;;){let{done:d,value:m}=await l.read();if(d)break;if(c+=m.byteLength,i&&c>s*bu)throw await l.cancel(),new Error(`Download exceeded expected size: received ${c} bytes, expected at most ${s*bu}`);u.push(m),i&&t?.(c,s);}return Buffer.concat(u)}catch(r){throw r instanceof Error?r.message.includes("Download exceeded expected size")?r:new Error(`Failed to download plugin: ${r.message}`):r}}async function _s(){try{let{profiles:e}=await mt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}async function Pu(e,t){let r=ge.resolve(t);await Ct.mkdir(r,{recursive:true});let n=ge.join(ge.dirname(r),`${randomUUID()}.zip`);try{await Ct.writeFile(n,e);let o=await uy.Open.file(n),s=ge.normalize(r+ge.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=ge.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(ge.resolve(ge.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Ct.unlink(n);}catch{}}}async function va(e){await Ct.rm(e,{recursive:true,force:true});}async function hr(){let e=Ol();await Ct.mkdir(ge.dirname(e),{recursive:true});try{await Ct.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Ug.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function my(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:X,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function ku(){let e=Bo();if(!he__default.existsSync(e))return null;try{return JSON.parse(he__default.readFileSync(e,"utf-8"))}catch{return null}}function fy(){let e=ku();if(e)return e;let t=my(),r=Bo();return he__default.mkdirSync(ge__default.dirname(r),{recursive:true}),Ea(t),t}function Ea(e){let t=Bo(),r=`${t}.${randomUUID()}.tmp`;he__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),he__default.renameSync(r,t);}function gy(){let e=Fo(),t={};try{he__default.existsSync(e)&&(t=JSON.parse(he__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[X])return;t[X]={source:{source:"github",repo:"cit-flow/flow-skills"},installLocation:Dl(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;he__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),he__default.renameSync(r,e);}function Au(e,t){ft(e.name),gy();let r=Li(e.name);he__default.mkdirSync(ge__default.dirname(r),{recursive:true});try{he__default.lstatSync(r),he__default.rmSync(r,{recursive:!0,force:!0});}catch{}he__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=fy();n.plugins.some(s=>s.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Ea(n));}function Pa(e){ft(e);let t=Li(e);try{he__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=ku();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&Ea(r);}var yy=x("mcpConfigReader"),wy=500,Sy=512;function xy(){return ge__default.join(Pe__default.homedir(),".claude.json")}function Iy(){return ge__default.join(process.cwd(),".mcp.json")}function Lu(e){if(!he__default.existsSync(e))return null;try{return JSON.parse(he__default.readFileSync(e,"utf-8"))}catch{return yy.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function co(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ta(e){if(!co(e))return {};let t=e.mcpServers;return co(t)?t:{}}function Ca(e,t){return Object.keys(e).slice(0,wy).map(n=>({name:y(n.slice(0,Sy)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Ru(){let e=[],t=xy(),r=Lu(t);if(co(r)){let a=r,l=Ta(a);e.push(...Ca(l,"user"));let u=process.cwd();if(co(a.projects)){let c=a.projects[u];if(co(c)){let d=Ta(c);e.push(...Ca(d,"local"));}}}let n=Iy(),o=Lu(n),s=Ta(o);e.push(...Ca(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}var qe=x("storage");async function vy(e,t,r){try{await v(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:H().interfaceType});}catch(n){qe.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Ey(e,t,r){let n=t==="enabled"?b.CLI_TOOL_ENABLED:b.CLI_TOOL_DISABLED;v(n,{tool_id:e,source:r,interface:H().interfaceType}).catch(o=>qe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function La(){return ge__default.join(Pe__default.homedir(),".claude","plugins","installed_plugins.json")}function Py(){return ge__default.join(Pe__default.homedir(),".claude","plugins")}function Ds(e){let t;try{t=he__default.realpathSync(e);}catch{t=ge__default.resolve(e);}let r=ge__default.resolve(Py()),n=ge__default.resolve(ge__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+ge__default.sep),s=t.startsWith(n+ge__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function _u(e="user"){return e==="local"?ge__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?ge__default.join(process.cwd(),".claude","settings.json"):ge__default.join(Pe__default.homedir(),".claude","settings.json")}function Ze(){let e=La();if(!he__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(he__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Ma(){let e=La();try{let t=await he__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Ty(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Du(e,t){try{he__default.mkdirSync(ge__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;he__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),he__default.renameSync(r,e);}catch(r){throw Ty(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Ye(e){Du(La(),e);}function uo(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Cy(e,t){let r=ge__default.join(e,".claude-plugin"),n=ge__default.join(r,"plugin.json");if(he__default.existsSync(n))try{return JSON.parse(he__default.readFileSync(n,"utf-8"))}catch{return null}let o=ge__default.join(r,"marketplace.json");if(he__default.existsSync(o))try{let s=JSON.parse(he__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function Ra(e="user"){let t=_u(e);if(!he__default.existsSync(t))return {};try{return JSON.parse(he__default.readFileSync(t,"utf-8"))}catch{return {}}}function Ou(e,t="user"){Du(_u(t),e);}function ky(e,t){let{name:r,marketplace:n}=uo(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>uo(i).name===r)[0],!o)throw qe.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Ay(e,t){let{name:r,marketplace:n}=uo(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>uo(i).name===r)[0],o?{key:o,name:r}:null}function ka(e="user"){return Ra(e).enabledPlugins??{}}function Aa(e,t="user"){let r=Ra(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Ou(r,t);}function po(e,t,r="user"){let n=Ra(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Ou(n,r);}function $y(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function te(){let e=Ze(),t=ka(),r=ka("project"),n=ka("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=uo(u),p=c.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return $y(p).map(h=>{let g=Cy(h.installPath,d),I=(o[h.scope]??t)[u];return {name:d,marketplace:m,version:h.version&&h.version!=="unknown"?h.version:void 0,installedAt:h.installedAt,installPath:h.installPath,scope:h.scope,providerId:h.providerId,type:h.type,description:g?.description,author:g?.author,status:I===false?"disabled":"enabled"}})}),i=Ru(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}async function mo(e,t){qe.debug(`[${e}] Acquiring lock to uninstall`);let r=await hr();try{let n=Ze(),o=Ay(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);qe.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),Ds(l.installPath);let u=ge__default.dirname(l.installPath);Ds(u),qe.debug(`[${i}] Removing directory: ${u}`),he__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...m}=n.plugins;Ye({...n,plugins:m}),Aa(s,t),Pa(i);}else n.plugins[s]=c,Ye(n),Aa(s,t);}else {qe.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Ds(c.installPath);let d=ge__default.dirname(c.installPath);Ds(d),qe.debug(`[${i}] Removing directory: ${d}`),he__default.rmSync(d,{recursive:!0,force:!0}),Aa(s,c.scope);}Pa(i);let{[s]:l,...u}=n.plugins;Ye({...n,plugins:u});}await vy(i,a[0].origin??"internal",a[0].type??"skill"),qe.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function fo(e,t,r){qe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await hr();try{let o=Ze(),{key:s,name:i}=ky(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";qe.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),po(s,t==="enabled",l),Ey(i,t,u),qe.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var Ly=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,My=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ft(e){if(!Ly.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Ry(e){if(!My.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 yr=x("installer");function _y(e,t){let r=`${e}@${X}`,o=Ze().plugins[r];if(o&&!t)throw new Be(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function Dy(e,t,r){r&&await va(t);try{yr.debug(`[${t}] Extracting archive...`),await Pu(e,t);}catch(n){throw await va(t),n}}function Oy(e,t,r,n,o,s="claude-code",i){let a=Ze(),l={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],Ye(a),po(e,true,n);}async function Uy(e,t,r,n,o,s){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:H().interfaceType});}catch(i){yr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Ny(e,t,r,n){try{await v(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:H().interfaceType});}catch(o){yr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function ke(e,t={}){let r=Date.now(),n=null;try{yr.debug(`[${e}] Acquiring lock...`),n=await hr();let{pluginKey:o,alreadyInstalled:s}=_y(e,t.force);yr.debug(`[${e}] Fetching manifest...`);let i=await vn(e);ft(i.name),Ry(i.version),yr.debug(`[${e}] Downloading archive...`);let a=await Eu(e,t.onDownloadProgress),l=t.scope??"user",u=t.type??"skill",c=_l(i.name,i.version);await Dy(a,c,!!s&&!!t.force),Oy(o,c,i.version,l,"internal",t.providerId,u),Au(i,c);let d=Date.now()-r;yr.debug(`[${e}] Installed successfully in ${d}ms`);let m={name:i.name,version:i.version,path:c,duration_ms:d};return t.skipMetrics||await Uy(i.name,i.version,d,As(l),"internal",u),m}catch(o){throw await Ny(e,o,"internal",t.type??"skill"),yr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var By=x("commands:helpers");async function se(){let e=await Y();if(!e)return E("Not authenticated. Run: flow auth login"),false;e.customUrl&&It(e.customUrl);try{await bt();}catch(t){return By.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function kt(e){let t=_a.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 Uu(e){let t=_a.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var Pn=x("claudeProxy"),Na="claude ",Nu="flow ",Da=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},En=class extends Error{constructor(t){super(`Disallowed subcommand: "${t}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},Fy=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,jy=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Ky={"--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}$/},Vy=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Jy=/^(flow|claude)\s+auth\s+login(\s|$)/,Bu=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Fu(e){return Bu.test(e.trim())}function Hy(e){return Bu.exec(e.trim())?.[2]??""}async function ju(e){let t=Hy(e);Ia(t);let r=Date.now();Pn.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw Ba(n)?new Oa:n}}function Gy(e){Ku(e);let t=e.slice(Na.length);if(!Fy.test(t))throw new En(e)}var Os=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},Oa=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Ku(e){if(!e||!/^claude /.test(e))throw new Da(e)}function Wy(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!jy.test(r))throw new En(`Unexpected flag: ${r}`);let n=Ky[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new En(`Flag ${r} requires a value`);if(!n.test(o))throw new En(`Unsafe value for flag ${r}`);t++;}}}async function be(e){Ku(e);let t=e.slice(Na.length).split(/\s+/).filter(Boolean);Wy(t);let r=zy(t);Pn.debug(`[${r}] Executing proxy command: claude ${t.join(" ")}`);let n=Date.now();try{let o=await execa("claude",t,{reject:!1}),s=Date.now()-n;return Pn.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${s}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:s}}catch(o){throw Ba(o)?new Os:o}}function zy(e){return e.length>=3?e[2]:e.join(" ")}function Ba(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Xy(e){return e.startsWith(Nu)?Na+e.slice(Nu.length):e}function qy(e){return Vy.test(e)||Jy.test(e)}function Yy(e){let t=0;for(;t<e.length&&qy(e[t]);)t++;return e.slice(t)}var Zy=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Qy(e,t){return !t||e.includes("--scope")||!Zy.test(e)?e:`${e} --scope ${t}`}async function go(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Yy(r).map(i=>Xy(i)).map(i=>Qy(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Gy(i);Pn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await be(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await be(o[i]),s.exitCode!==0)return s;return s}async function Us(e,t,r){let n=xn(e),o=t?.trim();if(!o&&(o=(await Uu(`Plugin "${n}" could not be installed.
|
|
111
|
+
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Ms(o),r?.(),Pn.debug(`[${n}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let s=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(s.exitCode!==0)throw new Error(`Failed to add marketplace: ${s.stderr||"unknown error"}`);Pn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw Ba(s)?new Os:s}}var ow=6e4,wr=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function At(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:ow}}).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 wr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new wr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new wr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function $t(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm$1(e,{recursive:true,force:true});}async function Gr(e,t=["--version"]){try{return (await execa(e,t,{reject:!1})).exitCode===0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return false;throw r}}function iw(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function aw(e){return typeof e=="object"&&e!==null&&e.source==="url"}function lw(e){return typeof e=="object"&&e!==null&&e.source==="github"}function Tn(e,t){let r=e.source;if(iw(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(aw(r))return {cloneUrl:r.url,subPath:"."};if(lw(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function Qe(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Lt=x("claude-code.adapter");function dw(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=Fo();if(!he__default.existsSync(s))return r;try{let i=JSON.parse(he__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 Xu(e,t){let r=e.catalogId?le.getAdapter(e.catalogId):void 0,n=Tn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=e.type==="bundle"||e.type==null,s=dw(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Mi(s,e.name,"external"):a=join(Cr(i==="user"?"global":"project"),e.name);let l=null;try{ft(e.name),l=await At(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(he__default.existsSync(a)&&he__default.rmSync(a,{recursive:!0,force:!0}),he__default.mkdirSync(dirname(a),{recursive:!0}),he__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Ma(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],Ye(d),po(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Lt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await $t(l).catch(()=>{});}}async function Fa(e,t,r,n){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:As(n),version:"unknown",duration_ms:t,interface:H().interfaceType});}catch(o){Lt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Wu(e,t,r){try{await v(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:H().interfaceType});}catch(n){Lt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var pw={async install(e,t){if(e.origin===Zr&&!e.installCommand&&!Sn(e.name))return Xu(e,t);if(e.origin===Zr&&e.installCommand){let r=e.type??"skill",n=await go(e.installCommand,t.scope);return n.exitCode===0?(await Fa(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Wu(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Sn(e.name)){let r=e.type??"skill",n=In(e.name,t.scope);Lt.debug(`[${e.name}] Attempting install: ${n}`);let o=await be(n);if(o.exitCode===0)return await Fa(e.name,o.duration_ms,r,t.scope),{success:true};Lt.debug(`[${e.name}] First attempt failed, adding marketplace`),await Us(e.name,t.marketplaceSource,()=>{});let s=await be(n);return s.exitCode===0?(await Fa(e.name,s.duration_ms,r,t.scope),{success:true}):(await Wu(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await ke(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Lt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await mo(e,t);},getInstallPath(e,t){return ""}};function zu(e){return {async install(t,r){if(t.origin===Zr&&!t.installCommand&&!Sn(t.name))return Xu(t,r);if(!t.installCommand)try{let o=await ke(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Lt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Lt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await 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=Ze(),o=`${t}@${X}`;if(n.plugins[o]){await mo(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 mw(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!he__default.existsSync(t))continue;let r=he__default.readdirSync(t).filter(n=>n.endsWith(".md")&&he__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function ja(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,ja(r)]))}function qu(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(ja(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(ja(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=qu(s,o):r[n]=o;}return r}async function Yu(e,t,r,n){let o=await Ma(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],Ye(o);}var fw={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=Tn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ft(e.name),s=await At(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=mw(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Ko(r);he__default.mkdirSync(l,{recursive:!0});let u=Qe(e.name);if(a.length===1)he__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=Qe(basename(d,".md"));he__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await Yu(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Lt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await $t(s).catch(()=>{});}},async uninstall(e,t){let r=Ko(t),n=Qe(e);if(he__default.existsSync(r))for(let a of he__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))he__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Ze(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;Ye({...s,plugins:l});}else Ye({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Ko(t),`${Qe(e)}.md`)}},gw={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=Tn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ft(e.name),s=await At(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!he__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(he__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=eo();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=c.status==="ok"?c.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=qu(m,u);return cs({...d,hooks:p}),await Yu(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Lt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await $t(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},Ns=class{id="claude-code";name="Claude Code";async isAvailable(){return Gr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:pw,skill:zu("skill"),mcp:zu("mcp"),agent:fw,hook:gw}};function Bs(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 yw=new Set(["gh"]),ww=Bs(yw,"use: gh copilot mcp remove <name>"),Fs=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Gr("gh",["--version"])?Gr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:ww}};var Sw=new Set(["opencode"]),xw=Bs(Sw,"use: opencode config remove mcp <name>");function Iw(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
112
|
+
`)}function Zu(){return {async install(e,t){try{ft(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?le.getAdapter(e.catalogId):void 0,n=Tn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await At(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=jo(t.scope??"user"),a=join(s,".opencode","plugins");if(he__default.existsSync(a)){let l=he__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/"};he__default.mkdirSync(i,{recursive:!0}),he__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);he__default.existsSync(l)&&he__default.rmSync(l,{recursive:!0,force:!0}),he__default.mkdirSync(l,{recursive:!0}),he__default.cpSync(s,l,{recursive:!0}),he__default.mkdirSync(i,{recursive:!0}),he__default.writeFileSync(join(i,`${e.name}.js`),Iw(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(s){return {success:false,message:s instanceof Error?s.message:String(s)}}finally{o&&await $t(o).catch(()=>{});}},async uninstall(e,t){ft(e);let r=jo(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);he__default.existsSync(n)&&he__default.rmSync(n,{force:true}),he__default.existsSync(o)&&he__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(jo(t),`${e}.js`)}}}var js=class{id="opencode";name="OpenCode";async isAvailable(){return Gr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:xw,skill:Zu(),bundle:Zu()}};var Mt=new ks;Mt.register(new Ns);cr()&&(Mt.register(new Fs),Mt.register(new js));function Qu({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,u]=useState([]),[c,d]=useState(void 0);useEffect(()=>{Mt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(g=>{g==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(g=>{if(g==="Cancel"){a(false);return}let w=l.find(I=>I.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=du(g);w?r(w,c):s(false);},[r,c]),h=useCallback(()=>{s(false);},[]);if(i){let g=[...l.map(w=>w.name),"Cancel"];return jsx(Xe,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(Xe,{itemName:`${e} \u2014 Choose scope`,actions:cu,descriptions:uu,onAction:f,onClose:h},"scope"):jsx(Xe,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function td({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,h)=>{h.upArrow?a(g=>Math.max(0,g-1)):h.downArrow?a(g=>Math.min(d.length-1,g+1)):h.return?d[i]==="Confirm Install"?n():o():h.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(f=>{let h=y(f.name??f.flowId),g=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:h}),jsxs(Text,{dimColor:true,children:["(",g,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,h)=>jsx(Box,{children:jsxs(Text,{bold:h===i,color:h===i?"cyan":void 0,children:[h===i?"\u203A ":" ",f]})},f))})]}):jsx(Xe,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Js({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function od({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Js({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(Xe,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:g=>{g==="Uninstall"?c():g===d?i(t):g.startsWith("Update")?a?.():l();},onClose:l})}function ad({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Js({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(Xe,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var An=x("bundle:installer"),ld=/already exists/i;async function Aw(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Fu(t)){let r=await ju(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(ld.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(ld.test(n))return;throw new Error(n)}}}async function $w(e,t){try{await v(b.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){An.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function Lw(e,t,r){try{await v(b.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){An.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function cd(e,t,r,n){try{await v(b.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){An.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function Mw(e,t,r,n,o){try{await v(b.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){An.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Ws(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 $w(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let h=f.name??f.flowId,g=f.type??"unknown";if(!f.type){An.warn(`Artifact "${h}" has no type \u2014 treated as failed`),l.push({name:h,type:g,reason:"unknown artifact type"}),await cd(i,h,g,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await Aw(f),u++,await Lw(i,h,g),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let I=w instanceof Error?w.message:String(w);An.error(`Failed to install artifact "${h}": ${I}`),l.push({name:h,type:g,reason:I}),await cd(i,h,g,I),r?.({index:p+1,total:c,artifact:f,success:false,error:I});}}let d=Date.now()-a,m=l.length;return await Mw(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}function md({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Ws(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(pd,{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(pd,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ce=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:te()})}));function fd({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,u=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),u&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",xt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function gd({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${xt(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((h,g)=>{let w=g===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:h.danger?"yellow":void 0,dimColor:!w,children:h.label})]},h.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function hd(e){return e.adapter.removable!==false?4:2}function yd({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 Sd({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 xd({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(P=>r.has(`${P.name}@${o}`)),i=t.filter(P=>!r.has(`${P.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((P,L)=>{if(L.escape){n();return}if(L.return){d(a[l]??null);return}if(L.upArrow){u(D=>Math.max(0,D-1));return}L.downArrow&&u(D=>Math.min(a.length-1,D+1));},{isActive:c===null}),c!==null)return jsx(yd,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(Je/2)),p=Math.min(a.length,m+Je);p===a.length&&(m=Math.max(0,p-Je));let f=a.slice(m,p),h=m,g=a.length-p,w=s.length>0&&m<s.length,I=p>s.length,_=f.filter(P=>r.has(`${P.name}@${o}`)),R=f.filter(P=>!r.has(`${P.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2191 ${h} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),_.map(P=>jsx(Sd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:true},P.name))]}),I&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),R.map(P=>jsx(Sd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:false},P.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2193 ${g} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}ba();var Bw=/^https?:\/\/.+/;function Fw(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function jw(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Ed(e){let t=S(g=>g.showNotification),r=S(g=>g.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[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(!Bw.test(g)){c("URL must start with http:// or https://");return}c(null),o("adding");let I=randomUUID(),_=new bn(I,w,g);try{await _.fetchItems(),await Kt.add({id:I,name:w,source:g}),le.register(new bn(I,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(R){let P=Fw(R)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":jw(R)?R.message:R instanceof Error?`Could not reach catalog URL: ${R.message}`:"Failed to validate catalog URL";t(P,"error"),o("add-url");}},[e,t,r]);return useInput((g,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}g&&!w.ctrl&&!w.meta&&(d.current=d.current+g,i(d.current));},{isActive:n==="add-name"}),useInput((g,w)=>{if(w.escape){o("add-name");return}if(w.return){h();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}g&&!w.ctrl&&!w.meta&&(m.current=m.current+g,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function Pd(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Kt.remove(o),le.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function Cd(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=ce(A=>A.installedItems),[o,s]=useState(()=>le.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,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=le.listAdapters(),O=await Kt.read(),W=new Map(O.map(Ee=>[Ee.id,Ee]));s(A.map(Ee=>({adapter:Ee,stored:W.get(Ee.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=g.current[i-1];if(!A)return;let O=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(W=>{O||p({items:W,loading:false,error:null});}).catch(W=>{O||p({items:[],loading:false,error:W instanceof Error?W.message:"Failed to load catalog"});}),()=>{O=true;}},[i]);let I=Ed(w),_=useCallback(()=>{w(),a(0),u("list"),p(null),h("main");},[w]),{handleRemove:R}=Pd(_),P=useCallback(async A=>{h("removing"),await R(A);},[R]),L=useCallback(async A=>{try{let O=await A.adapter.fetchItems();if(p({items:O,loading:!1,error:null}),A.stored){let W=new Date().toISOString();await Kt.updateField(A.stored.id,{lastUpdated:W}),w();}r("Marketplace updated","success");}catch(O){r(O instanceof Error?O.message:"Update failed","error");}},[w,r]),D=useCallback(async A=>{if(!A.stored)return;let O=A.stored.autoUpdate!==false;await Kt.updateField(A.stored.id,{autoUpdate:!O}),w();},[w]),N=useCallback(()=>h("browse"),[]),z=useCallback(A=>{let O=o[i-1];if(!O)return;let W=O.adapter.removable!==false;[N,()=>{L(O);},...W?[()=>{D(O);},()=>{P(O.adapter.id);}]:[]][A]?.();},[o,i,N,L,D,P]),k=useCallback(()=>h("main"),[]),F=useCallback(()=>{let A=o[i-1];A&&L(A);},[o,i,L]),G=useCallback(()=>{let A=o[i-1];A&&D(A);},[o,i,D]),$=useCallback(()=>{let A=o[i-1];A&&P(A.adapter.id);},[o,i,P]);if(useInput((A,O)=>{if(O.upArrow){a(W=>Math.max(0,W-1));return}if(O.downArrow){a(W=>Math.min(o.length,W+1));return}(O.return||O.tab)&&(i===0?I.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&I.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,O)=>{if(O.escape||O.tab){u("list");return}if(O.upArrow){d(W=>Math.max(0,W-1));return}if(O.downArrow){let W=o[i-1],Ee=W?hd(W)-1:0;d(Oo=>Math.min(Oo+1,Ee));return}O.return&&z(c);},{isActive:f==="main"&&I.phase==="idle"&&l==="detail"&&e==="marketplaces"}),I.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:I.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),I.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(I.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:I.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:I.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),I.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:I.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(I.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 O=A.adapter.id??"default",W=new Set(n.filter(Ee=>Ee.marketplace===A.adapter.name).map(Ee=>`${Ee.name}@${O}`));return jsx(xd,{entry:A,items:m?.items??[],installedKeys:W,onBack:k})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let j=o[i-1]??null,Se=j?n.filter(A=>A.marketplace===j.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(fd,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&j?jsx(gd,{entry:j,detailData:m,installedCount:Se,focusPanel:l,actionIndex:c,onBrowse:N,onUpdate:F,onToggleAutoUpdate:G,onRemove:$}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:j?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:l==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function kd(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=Z.findIndex(i=>i.id===r.activeTab),s=Z[(o-1+Z.length)%Z.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=Z.findIndex(i=>i.id===r.activeTab),s=Z[(o+1)%Z.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=Z.findIndex(i=>i.id===r.activeTab),s=Z[(o+1)%Z.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="a"&&r.activeTab==="updates"?[]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function Ad(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function $d(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 Gw=new Set(Z.filter(e=>e.focus!=="list").map(e=>e.focus));function Po(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}=Ne.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 Ld({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=Ne(h=>h.query),a=Ne(h=>h.setQuery),l=Ne(h=>h.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:h,setCursorPosition:g}=Ne.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:I,actionMenuOpen:_}=S.getState();Po(la(h,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((h,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:I,actionMenuOpen:_}=S.getState();Po(la("",g,{activeTab:w}));},{isActive:Gw.has(t)}),useInput((h,g)=>{let{activeTab:w,selectedIndex:I,actionMenuOpen:_}=S.getState();Po(kd(h,g,{activeTab:w,selectedIndex:I},u.current));},{isActive:t==="list"}),useInput((h,g)=>{Po(Ad(h,g));},{isActive:t==="actionMenu"}),useInput((h,g)=>{let w=$d(h,g,Ne.getState().query),I=w.queryUpdate;if(Po(w.actions),I==="reset")l(),d("");else if(I!==null){let{query:_,cursorPosition:R,setCursorPosition:P}=Ne.getState();if("backspace"in I)R>0&&(a(_.slice(0,R-1)+_.slice(R)),P(R-1));else if("append"in I)a(_.slice(0,R)+I.append+_.slice(R)),P(R+I.append.length);else if("cursorMove"in I){let L=R+I.cursorMove;L>=0&&L<=_.length&&P(L);}}},{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(I=>I.name.toLowerCase().includes(g)||I.description?.toLowerCase().includes(g));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Rd(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=We(a=>a.justAuthenticated),o=We(a=>a.credentials),s=We(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function Le(e,t,r=false){return r?true:!Ga.valid(e)||!Ga.valid(t)?false:Ga.gt(t,e)}var Ht=x("updater");async function Ww(e,t,r,n,o,s){try{await v(b.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:H().interfaceType});}catch(i){Ht.warn(`Failed to send update metrics: ${String(i)}`);}}function zw(e){let t=Ze(),r=`${e}@${X}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Ys(e,t={}){let r=Date.now(),n=null;try{Ht.debug(`[${e}] Acquiring lock...`),n=await hr();let o=zw(e);if(!o)throw Ht.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Ht.debug(`[${e}] Fetching manifest...`);let u=(await vn(e)).version;if(!i||!Le(i,u,t.force))throw Ht.debug(`[${e}] Already up to date (v${i??"n/a"})`),new fr(e,i??"unknown");Ht.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await ke(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await Ww(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),Ht.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){Ht.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await hr();let d=Ze(),m=`${e}@${X}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,Ye(d),Ht.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}var Zs=x("dispatcher");async function Xw(e,t,r,n,o){let s=xn(e);return Zs.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Us(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Zs.debug(`[${e}] Retrying install after marketplace add`),be(t)}async function _d(e,t,r,n){let o=In(e,n),s=xn(e);r?.onStatus?.(`Installing ${s}...`),Zs.debug(`[${e}] Attempting install: ${o}`);let i=await be(o);if(i.exitCode===0)return i;Zs.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Xw(e,o,a,t,r)}async function Dd(e,t,r){let n=e.type??"bundle",o=await Mt.getAvailableProviders(n),s=o[0];if(!s)throw new Error(`No available provider for artifact type "${n}"`);let i=s.installers[n];if(!i)throw new Error(`Provider "${s.id}" does not support type "${n}"`);let a=t??{},l=a;return i.install(e,l)}function Od(){let e=ce(i=>i.installedItems),t=ce(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Dd(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=te().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Mt.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",m=c.installers[d];if(!m)throw new Error(`Provider "${u}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await fo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await Ys(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var ei=x("mcp");function To(e,t){e.silent?Ge({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):E(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Nd(e,t){e.silent?Oe({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(oe(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function qw(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 Wa(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 Bd(e,t,r){if(!await se())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return To(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}ei.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=qw(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await kt(`Install external MCP "${s}"?
|
|
113
113
|
This will run: ${i}
|
|
114
|
-
[y/N] `))return
|
|
114
|
+
[y/N] `))return ei.debug(`[${e}] Installation cancelled by user`),C("Operation cancelled."),0}let o=r.silent?void 0:xl({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await be(n);return o?.stop(),s.exitCode!==0?(To(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&C(`stdout: ${s.stdout}`),1):(Nd(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),To(r,{name:e,action:"add",message:J(s)}),1}}async function Fd(e,t){if(!await se())return 1;ei.debug(`[${e}] Starting MCP remove`);let r=Wa(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await kt(`Remove MCP "${o}"?
|
|
115
115
|
This will run: ${s}
|
|
116
|
-
[y/N] `))return qs.debug(`[${e}] Removal cancelled by user`),C("Operation cancelled."),0}let n=t.silent?void 0:ml({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await xe(r);return n?.stop(),o.exitCode!==0?(Io(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&C(`stdout: ${o.stdout}`),1):($d(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Io(t,{name:e,action:"remove",message:V(o)}),1}}function Rd({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(P=>P.setLoading),u=S(P=>P.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=kd(),f=async(P,A,_)=>{l(true,P),n();try{await A(),o(r.length),s(_,"success");}catch(j){let fe=j instanceof Error?j.message:"Something went wrong";i.error(`[withLoading] ${P} failed: ${fe}`),s(fe,"error");}finally{l(false);}};return {handleInstall:(P,A)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:P,...A!==void 0?{providerId:A}:{},onDownloadProgress:(_,j)=>{let fe=Date.now();(fe-a.current>100||_>=j)&&(a.current=fe,u(_,j));}}),"\u2713 Installed successfully"));},handleUninstall:P=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,P),"\u2713 Uninstalled");},handleToggleStatus:P=>{if(!e)return;let A=e.status==="enabled";f(A?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,P),A?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let P=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${P}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${P}`,"success");}catch(_){if(_ instanceof dr)s(_.message,"info");else {let j=_ instanceof Error?_.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${j}`),s(j,"error");}}finally{l(false);}})();},handleBatchUpdate:P=>{if(P.length===0)return;let A=P.length;(async()=>{l(true,`Updating ${A} plugin${A>1?"s":""}...`),n();try{let j=[];for(let $ of P)j.push(await p($.name).then(()=>({status:"fulfilled",value:void 0}),F=>({status:"rejected",reason:F})));let fe=j.filter($=>$.status==="fulfilled").length,b=j.map(($,F)=>$.status==="rejected"?P[F].name:null).filter($=>$!==null);o(r.length),b.length===0?s(`\u2713 Updated ${fe}/${A} plugin${A>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${b.join(", ")}`),s(`Updated ${fe}/${A}; failed: ${b.join(", ")}`,fe>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:P=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let A=Fa(e.name,P),_=await xe(A);if(_.exitCode!==0)throw new Error(_.stderr||"MCP removal failed");ae.getState().loadFromDisk();},"\u2713 MCP removed");}}}var bo=x("api:bundle"),$n=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},vo=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Vw=/^[a-zA-Z0-9_-]{1,128}$/;async function Dd(e,t){if(e instanceof HTTPError){let r=e.response.status;throw bo.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new $n(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new vo:new Error(`Server error (${r}) \u2014 please try again later.`)}throw bo.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Od(e){if(!Vw.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);bo.debug(`Fetching bundle by flowId "${e}"`);try{return await dt().get(`v1/use-cases/${t}`).json()}catch(r){return Dd(r,e)}}async function Ys(e){let t=encodeURIComponent(e);bo.debug(`Fetching bundle by name "${e}"`);let r;try{r=await dt().get(`v1/use-cases/by-name/${t}`).json(),bo.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Dd(n,e)}if(r.length===0)throw new $n(e);return r[0]}var Jw=x("tui:bundle-flow");function Ud({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();Jw.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Od(d):Ys(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(),ae.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var Po=["local","project","user"],Hw=new Set(["--transport","--scope","-s"]);function Nd(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(Hw.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Jr(e,t){return t?`${e}::${t}`:e}function ja(e){return e===W?On:qr}function Bd(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??On,flowId:e.flowId}}function Ka(e,t){let r=ja(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 Fd(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 Po.filter(r=>t.has(r)).map(r=>({scope:r,label:Un[r].label,pathHint:Un[r].pathHint,items:t.get(r)??[]}))}function jd(e){let t=r=>{if(!r)return 1/0;let n=Po.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Kd({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>Jr(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(h=>[Jr(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let w=f.get(Jr(h.name,h.author?.name))??g.get(h.name),I=w?.version,R=!!I&&!!h.version&&$e(h.version,I);return {...h,updateAvailable:R,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(Jr(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?Nd(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||g&&i.has(g))return false}return true}).map(f=>Bd(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>Ka(f,f.catalogItem)):a.map(f=>Ka(f,f.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(f=>{let g=f.type??"bundle";if(!n.types.has(g))return false;let h=f.origin??"internal";return n.origins.has(h)}),[l,n]),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(h=>[Jr(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(Jr(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function Va(){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 gu();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,E(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 Vd(){return {items:ae(t=>t.installedItems)}}var qw=x("catalog");function Hd(){let e=S(K=>K.bundleInstallFlow),t=S(K=>K.activeTab),r=S(K=>K.notification),n=S(K=>K.loading),o=S(K=>K.loadingMessage),s=S(K=>K.downloadProgress),i=S(K=>K.downloadTotal),a=S(K=>K.catalogError),l=S(K=>K.setCatalogError),u=S(K=>K.catalogFilters),c=Ue(K=>K.query),{catalog:d,isLoading:m,error:p,refetch:f}=Va(),{items:g}=Vd(),h=ae(K=>K.loadFromDisk),{items:w,emptyMessage:I,getSelectedCatalogItem:R,outdatedCount:B}=Kd({catalog:d,installedItems:g,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:P,closeMenu:A,selectedIndex:_,clampIndex:j,filteredItems:fe}=vd({listLength:w.length}),b=fe(w),$=useMemo(()=>t!=="installed"&&t!=="updates"?b:jd(b),[t,b]),F=useMemo(()=>t==="installed"||t==="updates"?Fd($):[],[t,$]),D=$[_]??null,ue=useMemo(()=>R(D),[R,D]),{notify:Xr}=Ed(),{handleInstall:L,handleUninstall:N,handleToggleStatus:H,handleUpdate:be,handleBatchUpdate:Lo,handleMcpConfigUninstall:tf}=Rd({selectedItem:D,selectedCatalogItem:ue,items:w,closeMenu:A,clampIndex:j,notify:Xr}),{handleBundleInstallStart:rf,handleBundleDetailConfirm:nf,handleBundleDetailBack:of,handleBundleInstallComplete:sf}=Ud({closeMenu:A,notify:Xr}),af=useCallback(()=>Lo($),[Lo,$]);return useEffect(()=>{h();},[]),useEffect(()=>{j($.length);},[$.length,j]),useEffect(()=>{p&&(qw.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(pn,{}),jsx($c,{outdatedCount:B}),t==="marketplaces"&&ir()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Sd,{})}):jsx(Gc,{filteredItems:$,groups:F,emptyMessage:I,onBatchUpdate:af}),(n||m)&&jsxs(Fragment,{children:[jsx(Ss,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(Is,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(bs,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(Wc,{message:r.message,type:r.type}),P&&D&&(t==="discover"?ue?.type==="bundle"?e?.phase==="installing"?jsx(sd,{bundle:e.bundle,onComplete:sf}):jsx(Wu,{itemName:D.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>rf(D.name,D.flowId),onConfirm:nf,onClose:e?.phase==="detail"?of:A}):jsx(Hu,{itemName:D.name,itemType:ue?.type,onInstall:L,onClose:A}):D.type==="mcp"?jsx(Qu,{itemName:D.name,itemScope:D.scope??"user",onUninstall:tf,onClose:A}):jsx(qu,{itemName:D.name,itemScope:D.scope??"user",itemStatus:D.status??"enabled",updateAvailable:D.updateAvailable??false,catalogVersion:ue?.version,onUninstall:N,onToggleStatus:K=>H(K),onUpdate:be,onClose:A})),jsx(ws,{})]})}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(ae.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));var tS=3;function Wd(){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 $s();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{ae.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 g=1;g<=tS;g++)try{await Ce(m.name,{onDownloadProgress:(h,w)=>{let I=Date.now();(I-l.current>100||h>=w)&&(l.current=I,o(m.name,h,w));}}),n(m.name,"success"),f=!0;break}catch(h){if(h instanceof Ne){n(m.name,"success"),f=true;break}p=h instanceof Error?h.message:"Unknown error";}f||(n(m.name,"failed",p),E(v.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:J().interfaceType}).catch(()=>{}));}let d=$r();Ar("summary_review"),E(v.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),ae.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var Eo={cursorDelta:0,confirm:false,back:false};function zd(e,t){return t.upArrow?{...Eo,cursorDelta:-1}:t.downArrow?{...Eo,cursorDelta:1}:t.escape?{...Eo,back:true}:t.return?{...Eo,confirm:true}:Eo}var rS={cursorDelta:0,select:false};function Xd(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:rS}var qd=oh.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 qa=5;function Yd({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(Ss,{message:"Loading Starter Kits..."});if(o)return jsx(bs,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(mn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(qa/2)),i=Math.min(t.length,s+qa);i===t.length&&(s=Math.max(0,i-qa));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(qd,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var Qd=oh.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var Qa=8;function ep(){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,E(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(Qa/2)),i=Math.min(t.length,s+Qa);i===t.length&&(s=Math.max(0,i-Qa));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(Qd,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var dS=["Retry failed","Continue anyway"];function tp({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(od,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(Is,{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 rp({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(tp,{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(tp,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:dS.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 np(){let e=M(b=>b.step),t=M(b=>b.starterKits),r=M(b=>b.selectedStarterKitIndex),n=M(b=>b.setSelectedStarterKitIndex),o=M(b=>b.selectStarterKit),s=M(b=>b.plugins),i=M(b=>b.pluginCursorIndex),a=M(b=>b.setPluginCursorIndex),l=M(b=>b.setStep),u=M(b=>b.summaryActionIndex),c=M(b=>b.setSummaryActionIndex),d=M(b=>b.failedCount),m=M(b=>b.resetForRetry),p=M(b=>b.goBackToList),f=S(b=>b.setScreen),g=S(b=>b.setFocus),h=S(b=>b.focus),w=Ge(b=>b.setJustAuthenticated),I=Ge(b=>b.justAuthenticated),{loadStarterKits:R,installSelected:B}=Wd(),P=useRef(false);useEffect(()=>{e==="starterKitList"?(g("starterKitList"),P.current||(P.current=true,Ar("bundle_selection"))):g(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,g]);let A=useCallback(async()=>{let b=M.getState().selectedStarterKit;if(b){let F=await X();F&&await Ut({...F,starterKit:b.slug});}E(v.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:$r()}).catch(()=>{});let{successCount:$}=M.getState();E(v.CLI_ONBOARDING_COMPLETED,{duration_ms:sr(),tools_installed_count:$}).catch(()=>{}),w(false),g("verify"),f("verify");},[w,g,f]),_=useCallback(()=>{m(),B();},[m,B]),j=useCallback(()=>{R();},[R]),fe=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((b,$)=>{if($.escape)rs("esc"),fe();else if($.upArrow&&r>0)n(r-1);else if($.downArrow&&r<t.length-1)n(r+1);else if($.return&&t.length>0){let F=$r();o(t[r]),Ar("kit_display"),E(v.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:F}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((b,$)=>{let F=zd(b,$);if(F.cursorDelta!==0){let D=i+F.cursorDelta;D>=0&&D<s.length&&a(D);}if(F.confirm){let D=M.getState().selectedStarterKit;D&&(async()=>(await X())?.starterKit!==D.slug&&E(v.CLI_KIT_ACCEPTED,{bundle_slug:D.slug}).catch(()=>{}))();let ue=$r();Ar("kit_confirmation"),E(v.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:ue}).catch(()=>{});let Xr=$r();Ar("tool_installation"),E(v.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Xr}).catch(()=>{}),l("installing"),B();}if(F.back){let D=M.getState().selectedStarterKit;D&&E(v.CLI_KIT_REJECTED,{bundle_slug:D.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((b,$)=>{if(d===0)return;let F=Xd(b,$);if(F.cursorDelta!==0){let D=u+F.cursorDelta;D>=0&&D<=1&&c(D);}F.select&&(u===0?_():A());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(pn,{}),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."}),!I&&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(Yd,{onRetry:j}),e==="starterKitDetail"&&jsx(ep,{}),(e==="installing"||e==="summary")&&jsx(rp,{onComplete:A,onRetry:_})]}),jsx(ws,{})]})}var ip=null;function ap(){return ip}async function si(){let t=Dr().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=Z.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await lp(n);(o||s)&&await lt({...r,installedVersion:o,installMethod:s});}}async function lp(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 Pt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function Mn(e){let t=await Promise.all(e.map(r=>fS(r)));return ip=t,t}async function fS(e){let t=op(e.versionCommand);t==="permission-denied"&&(gS(e.versionCommand[0]),t=op(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 Pt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!We(e.alias)){let{installedVersion:l,installMethod:u}=await lp(e);await lt({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function op(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 gS(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=me__default.realpathSync(r),{mode:o}=me__default.statSync(n);me__default.chmodSync(n,o|73);}catch{}}function wS(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 mp(e,t){let[r,n]=useState(()=>wS(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,g=m.upArrow||d==="[A",h=m.downArrow||d==="[B";if(g||h)g&&p>0?s(p-1):h&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let I=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),R=w.availableStrategies[(I+1)%w.availableStrategies.length];n(B=>B.map(P=>P.module.alias===w.module.alias?{...P,selectedStrategy:R}:P));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}function gp({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}=mp(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 g=f===a,h=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:g?"cyan":void 0,children:[g?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",h]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(ze,{itemName:m,actions:d,onAction:c,onClose:u})]})}var vS=/^https?:\/\/.+/;function hp({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&&vS.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 ES(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 Sp(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=ES(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 cr(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}function xp({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(od,{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 Pp({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}=Sp(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(()=>{Or().catch(()=>{}),n("list");let w=Q().some(I=>I.name===te);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,I)=>{I.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,g=a-f,h=[];return g>0&&h.push(jsxs(Text,{color:"green",children:[g," installed"]},"i")),f>0&&h.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&h.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&h.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(xp,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((w,I,R)=>(R>0&&w.push(jsx(Text,{children:" | "},`sep-${R}`)),w.push(I),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 Tp(){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(uc(p)){Or().catch(()=>{}),l("list");let g=Q().some(h=>h.name===te);u(g?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=ap();if(p){c(p);return}Mn(Z).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let f=p.some(g=>g.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(gp,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(hp,{onConfirm:m}),e==="installation"&&jsx(Pp,{confirmedItems:o,customUrl:i})]})}var DS=x("ClaudeMdSuggestion"),OS=[`Install ${te}`,"Skip for now"],US=["Retry","Skip for now"];function Ap(){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(()=>{E(v.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,E(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await Ce(te),o("installed");}catch(m){if(m instanceof Ne){o("installed");return}DS.warn(`Failed to install ${te}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?US:OS;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(pn,{}),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(kp,{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(od,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",te,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",te," 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:["/",te]})]}),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 ",te]}),jsx(kp,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function kp({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 jS=promisify(execFile),ui="@ciandt-flow/cli";async function $p(){let e=se;if(Ba.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ui};try{let t=await fetch(`https://registry.npmjs.org/${ui}/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:ui}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ui}}}async function di(e){try{return await jS(Nt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function KS(e){let t=We(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Pt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await lt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Lp(e){let t=await KS(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 Mp(e,t){let r=We(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Pt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await lt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Rp(e){let r=We(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 _p(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...Z.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([$p(),Mn(Z),Promise.all(Z.map(l=>Lp(l)))]);if(si(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await di(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=Z.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 Mp(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:Rp(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await Or(),t(l=>({...l,outcome:"done"}));}catch{await Or(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function zS({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(od,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",e.label,e.detail?` ${e.detail}...`:""]})]}):e.status==="ok"||e.status==="updated"?jsxs(Box,{children:[jsxs(Text,{color:"green",children:["\u2713 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}):e.status==="missing"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),jsx(Text,{dimColor:true,children:" \u2014 not installed"})]}):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}),e.manualCommand&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["To update manually: ",e.manualCommand]})})]})}function XS({outcome:e}){return e==="done"?jsx(Text,{color:"green",children:"All good!"}):e==="cli-updated"||e==="cli-update-failed"?jsx(Text,{color:"yellow",children:"Restart the CLI to use the new version."}):null}function Dp(){let{outcome:e,items:t}=_p(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=Q().some(i=>i.name===te);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(zS,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(XS,{outcome:e})})]})}var QS={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Op=10;function Up(){let[e,t]=useState($i());useEffect(()=>Rl(()=>{t([...$i()]);}),[]);let r=e.slice(-Op);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Op,") \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:QS[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var nx=x("app"),ox={auth:bc,starterKitSetup:np,moduleSetup:Tp,claudeMdSuggestion:Ap,verify:Dp,main:Hd};function Fp(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function eo(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function jp(){E(v.CLI_SESSION_STARTED,{cli_version:se,os:process.platform,node_version:process.version,duration_ms:sr(),interface:"tui"}).catch(()=>{});}async function Vp(){let e=await X();if(e&&lc()&&await nr()){e.customUrl&&St(e.customUrl);let{clientSecret:n,...o}=e;Ge.getState().setCredentials(o),jp(),eo(e);return}if(!e){Fp();return}try{e.customUrl&&St(e.customUrl),await xt();}catch(n){nx.debug(`Token validation failed: ${String(n)}`),Fp();return}jp();let{clientSecret:t,...r}=e;Ge.getState().setCredentials(r),eo(e);}function Jp(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=ox[r],{pendingExit:o}=rc(),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(Up,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}async function dl(e,t={}){let r=ss({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return is(r),await Ut(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var ht=x("auth");function Gp(){Oe.clearFallbackFile(),Yo();}var sx=3,Hp=3,Wp=` \u2139 The data collected during setup is used solely to improve
|
|
116
|
+
[y/N] `))return ei.debug(`[${e}] Removal cancelled by user`),C("Operation cancelled."),0}let n=t.silent?void 0:xl({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await be(r);return n?.stop(),o.exitCode!==0?(To(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&C(`stdout: ${o.stdout}`),1):(Nd(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),To(t,{name:e,action:"remove",message:J(o)}),1}}function jd({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(P=>P.setLoading),u=S(P=>P.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=Od(),f=async(P,L,D)=>{l(true,P),n();try{await L(),o(r.length),s(D,"success");}catch(N){let z=N instanceof Error?N.message:"Something went wrong";i.error(`[withLoading] ${P} failed: ${z}`),s(z,"error");}finally{l(false);}};return {handleInstall:(P,L)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:P,...L!==void 0?{providerId:L}:{},onDownloadProgress:(D,N)=>{let z=Date.now();(z-a.current>100||D>=N)&&(a.current=z,u(D,N));}}),"\u2713 Installed successfully"));},handleUninstall:P=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,P),"\u2713 Uninstalled");},handleToggleStatus:P=>{if(!e)return;let L=e.status==="enabled";f(L?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,P),L?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let P=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${P}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${P}`,"success");}catch(D){if(D instanceof fr)s(D.message,"info");else {let N=D instanceof Error?D.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${N}`),s(N,"error");}}finally{l(false);}})();},handleBatchUpdate:P=>{if(P.length===0)return;let L=P.length;(async()=>{l(true,`Updating ${L} plugin${L>1?"s":""}...`),n();try{let N=[];for(let F of P)N.push(await p(F.name).then(()=>({status:"fulfilled",value:void 0}),G=>({status:"rejected",reason:G})));let z=N.filter(F=>F.status==="fulfilled").length,k=N.map((F,G)=>F.status==="rejected"?P[G].name:null).filter(F=>F!==null);o(r.length),k.length===0?s(`\u2713 Updated ${z}/${L} plugin${L>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${z}/${L}; failed: ${k.join(", ")}`,z>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:P=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let L=Wa(e.name,P),D=await be(L);if(D.exitCode!==0)throw new Error(D.stderr||"MCP removal failed");ce.getState().loadFromDisk();},"\u2713 MCP removed");}}}var Co=x("api:bundle"),_n=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},ko=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Qw=/^[a-zA-Z0-9_-]{1,128}$/;async function Vd(e,t){if(e instanceof HTTPError){let r=e.response.status;throw Co.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new _n(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new ko:new Error(`Server error (${r}) \u2014 please try again later.`)}throw Co.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Jd(e){if(!Qw.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);Co.debug(`Fetching bundle by flowId "${e}"`);try{return await mt().get(`v1/use-cases/${t}`).json()}catch(r){return Vd(r,e)}}async function ti(e){let t=encodeURIComponent(e);Co.debug(`Fetching bundle by name "${e}"`);let r;try{r=await mt().get(`v1/use-cases/by-name/${t}`).json(),Co.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Vd(n,e)}if(r.length===0)throw new _n(e);return r[0]}var eS=x("tui:bundle-flow");function Hd({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();eS.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Jd(d):ti(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(),ce.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var Ao=["local","project","user"],tS=new Set(["--transport","--scope","-s"]);function Gd(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(tS.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function zr(e,t){return t?`${e}::${t}`:e}function za(e){return e===X?Fn:Zr}function Wd(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??Fn,flowId:e.flowId}}function Xa(e,t){let r=za(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 zd(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 Ao.filter(r=>t.has(r)).map(r=>({scope:r,label:jn[r].label,pathHint:jn[r].pathHint,items:t.get(r)??[]}))}function Xd(e){let t=r=>{if(!r)return 1/0;let n=Ao.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function qd({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>zr(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(g=>[zr(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(zr(g.name,g.author?.name))??h.get(g.name),I=w?.version,_=!!I&&!!g.version&&Le(g.version,I);return {...g,updateAvailable:_,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(zr(f.name,f.author?.name)))return false;if(f.type==="mcp"){let h=f.installCommand?Gd(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||h&&i.has(h))return false}return true}).map(f=>Wd(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>Xa(f,f.catalogItem)):a.map(f=>Xa(f,f.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(f=>{let h=f.type??"bundle";if(!n.types.has(h))return false;let g=f.origin??"internal";return n.origins.has(g)}),[l,n]),c=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let f=new Map(e.map(g=>[zr(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(zr(g.name,g.authorName))??h.get(g.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function qa(){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 vu();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,v(b.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c,u]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:c}}function Yd(){return {items:ce(t=>t.installedItems)}}var iS=x("catalog");function Qd(){let e=S(V=>V.bundleInstallFlow),t=S(V=>V.activeTab),r=S(V=>V.notification),n=S(V=>V.loading),o=S(V=>V.loadingMessage),s=S(V=>V.downloadProgress),i=S(V=>V.downloadTotal),a=S(V=>V.catalogError),l=S(V=>V.setCatalogError),u=S(V=>V.catalogFilters),c=Ne(V=>V.query),{catalog:d,isLoading:m,error:p,refetch:f}=qa(),{items:h}=Yd(),g=ce(V=>V.loadFromDisk),{items:w,emptyMessage:I,getSelectedCatalogItem:_,outdatedCount:R}=qd({catalog:d,installedItems:h,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:P,closeMenu:L,selectedIndex:D,clampIndex:N,filteredItems:z}=Ld({listLength:w.length}),k=z(w),F=useMemo(()=>t!=="installed"&&t!=="updates"?k:Xd(k),[t,k]),G=useMemo(()=>t==="installed"||t==="updates"?zd(F):[],[t,F]),$=F[D]??null,j=useMemo(()=>_($),[_,$]),{notify:Se}=Rd(),{handleInstall:A,handleUninstall:O,handleToggleStatus:W,handleUpdate:Ee,handleBatchUpdate:Oo,handleMcpConfigUninstall:uf}=jd({selectedItem:$,selectedCatalogItem:j,items:w,closeMenu:L,clampIndex:N,notify:Se}),{handleBundleInstallStart:df,handleBundleDetailConfirm:pf,handleBundleDetailBack:mf,handleBundleInstallComplete:ff}=Hd({closeMenu:L,notify:Se}),gf=useCallback(()=>Oo(F),[Oo,F]);return useEffect(()=>{g();},[]),useEffect(()=>{N(F.length);},[F.length,N]),useEffect(()=>{p&&(iS.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),l("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(hn,{}),jsx(Nc,{outdatedCount:R}),t==="marketplaces"&&cr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Cd,{})}):jsx(eu,{filteredItems:F,groups:G,emptyMessage:I,onBatchUpdate:gf}),(n||m)&&jsxs(Fragment,{children:[jsx(vs,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(Ps,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(Ts,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(tu,{message:r.message,type:r.type}),P&&$&&(t==="discover"?j?.type==="bundle"?e?.phase==="installing"?jsx(md,{bundle:e.bundle,onComplete:ff}):jsx(td,{itemName:$.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>df($.name,$.flowId),onConfirm:pf,onClose:e?.phase==="detail"?mf:L}):jsx(Qu,{itemName:$.name,itemType:j?.type,onInstall:A,onClose:L}):$.type==="mcp"?jsx(ad,{itemName:$.name,itemScope:$.scope??"user",onUninstall:uf,onClose:L}):jsx(od,{itemName:$.name,itemScope:$.scope??"user",itemStatus:$.status??"enabled",updateAvailable:$.updateAvailable??false,catalogVersion:j?.version,onUninstall:O,onToggleStatus:V=>W(V),onUpdate:Ee,onClose:L})),jsx(bs,{})]})}var M=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(ce.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));var dS=3;function tp(){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 _s();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{ce.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<=dS;h++)try{await ke(m.name,{onDownloadProgress:(g,w)=>{let I=Date.now();(I-l.current>100||g>=w)&&(l.current=I,o(m.name,g,w));}}),n(m.name,"success"),f=!0;break}catch(g){if(g instanceof Be){n(m.name,"success"),f=true;break}p=g instanceof Error?g.message:"Unknown error";}f||(n(m.name,"failed",p),v(b.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:H().interfaceType}).catch(()=>{}));}let d=Mr();Lr("summary_review"),v(b.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),ce.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var $o={cursorDelta:0,confirm:false,back:false};function rp(e,t){return t.upArrow?{...$o,cursorDelta:-1}:t.downArrow?{...$o,cursorDelta:1}:t.escape?{...$o,back:true}:t.return?{...$o,confirm:true}:$o}var pS={cursorDelta:0,select:false};function np(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:pS}var op=fh.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 nl=5;function sp({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(vs,{message:"Loading Starter Kits..."});if(o)return jsx(Ts,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(yn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(nl/2)),i=Math.min(t.length,s+nl);i===t.length&&(s=Math.max(0,i-nl));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(op,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var ap=fh.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var il=8;function lp(){let e=M(c=>c.selectedStarterKit),t=M(c=>c.plugins),r=M(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,v(b.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(c=>c.installed).length,s=Math.max(0,r-Math.floor(il/2)),i=Math.min(t.length,s+il);i===t.length&&(s=Math.max(0,i-il));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(ap,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var IS=["Retry failed","Continue anyway"];function cp({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(pd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(Ps,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function up({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(cp,{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(cp,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:IS.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 dp(){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=We(k=>k.setJustAuthenticated),I=We(k=>k.justAuthenticated),{loadStarterKits:_,installSelected:R}=tp(),P=useRef(false);useEffect(()=>{e==="starterKitList"?(h("starterKitList"),P.current||(P.current=true,Lr("bundle_selection"))):h(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,h]);let L=useCallback(async()=>{let k=M.getState().selectedStarterKit;if(k){let G=await Y();G&&await Bt({...G,starterKit:k.slug});}v(b.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Mr()}).catch(()=>{});let{successCount:F}=M.getState();v(b.CLI_ONBOARDING_COMPLETED,{duration_ms:lr(),tools_installed_count:F}).catch(()=>{}),w(false),h("verify"),f("verify");},[w,h,f]),D=useCallback(()=>{m(),R();},[m,R]),N=useCallback(()=>{_();},[_]),z=useCallback(()=>{h("verify"),f("verify");},[h,f]);return useInput((k,F)=>{if(F.escape)as("esc"),z();else if(F.upArrow&&r>0)n(r-1);else if(F.downArrow&&r<t.length-1)n(r+1);else if(F.return&&t.length>0){let G=Mr();o(t[r]),Lr("kit_display"),v(b.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:G}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((k,F)=>{let G=rp(k,F);if(G.cursorDelta!==0){let $=i+G.cursorDelta;$>=0&&$<s.length&&a($);}if(G.confirm){let $=M.getState().selectedStarterKit;$&&(async()=>(await Y())?.starterKit!==$.slug&&v(b.CLI_KIT_ACCEPTED,{bundle_slug:$.slug}).catch(()=>{}))();let j=Mr();Lr("kit_confirmation"),v(b.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:j}).catch(()=>{});let Se=Mr();Lr("tool_installation"),v(b.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Se}).catch(()=>{}),l("installing"),R();}if(G.back){let $=M.getState().selectedStarterKit;$&&v(b.CLI_KIT_REJECTED,{bundle_slug:$.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((k,F)=>{if(d===0)return;let G=np(k,F);if(G.cursorDelta!==0){let $=u+G.cursorDelta;$>=0&&$<=1&&c($);}G.select&&(u===0?D():L());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(hn,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!I&&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(sp,{onRetry:N}),e==="starterKitDetail"&&jsx(lp,{}),(e==="installing"||e==="summary")&&jsx(up,{onComplete:L,onRetry:D})]}),jsx(bs,{})]})}var fp=null;function gp(){return fp}async function ci(){let t=Br().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=ee.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await hp(n);(o||s)&&await ct({...r,installedVersion:o,installMethod:s});}}async function hp(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await Tt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function On(e){let t=await Promise.all(e.map(r=>ES(r)));return fp=t,t}async function ES(e){let t=pp(e.versionCommand);t==="permission-denied"&&(PS(e.versionCommand[0]),t=pp(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await Tt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!ze(e.alias)){let{installedVersion:l,installMethod:u}=await hp(e);await ct({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function pp(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 PS(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=he__default.realpathSync(r),{mode:o}=he__default.statSync(n);he__default.chmodSync(n,o|73);}catch{}}function kS(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 Ip(e,t){let[r,n]=useState(()=>kS(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 I=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),_=w.availableStrategies[(I+1)%w.availableStrategies.length];n(R=>R.map(P=>P.module.alias===w.module.alias?{...P,selectedStrategy:_}:P));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}function vp({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}=Ip(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let h=f===a,g=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",g," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:h?"cyan":void 0,children:[h?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",g]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(Xe,{itemName:m,actions:d,onAction:c,onClose:u})]})}var RS=/^https?:\/\/.+/;function Ep({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&&RS.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 DS(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 Cp(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=DS(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 pr(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}function kp({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(pd,{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 Mp({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}=Cp(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{Fr().catch(()=>{}),n("list");let w=te().some(I=>I.name===ne);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,I)=>{I.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(kp,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,I,_)=>(_>0&&w.push(jsx(Text,{children:" | "},`sep-${_}`)),w.push(I),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 _p(){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(wc(p)){Fr().catch(()=>{}),l("list");let h=te().some(g=>g.name===ne);u(h?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=gp();if(p){c(p);return}On(ee).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(vp,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(Ep,{onConfirm:m}),e==="installation"&&jsx(Mp,{confirmedItems:o,customUrl:i})]})}var HS=x("ClaudeMdSuggestion"),GS=[`Install ${ne}`,"Skip for now"],WS=["Retry","Skip for now"];function Up(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=M(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{v(b.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,v(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await ke(ne),o("installed");}catch(m){if(m instanceof Be){o("installed");return}HS.warn(`Failed to install ${ne}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?WS:GS;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),c()):u());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(hn,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(Op,{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(pd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ne,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ne," 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:["/",ne]})]}),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 ",ne]}),jsx(Op,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Op({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 YS=promisify(execFile),fi="@ciandt-flow/cli";async function Np(){let e=ae;if(Ga.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:fi};try{let t=await fetch(`https://registry.npmjs.org/${fi}/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:fi}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:fi}}}async function gi(e){try{return await YS(Ft(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function ZS(e){let t=ze(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Tt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await ct({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Bp(e){let t=await ZS(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 Fp(e,t){let r=ze(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Tt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await ct({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function jp(e){let r=ze(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function Kp(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...ee.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([Np(),On(ee),Promise.all(ee.map(l=>Bp(l)))]);if(ci(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await gi(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=ee.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 Fp(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:jp(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await Fr(),t(l=>({...l,outcome:"done"}));}catch{await Fr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function ox({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(pd,{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 sx({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 Vp(){let{outcome:e,items:t}=Kp(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=te().some(i=>i.name===ne);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(ox,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(sx,{outcome:e})})]})}var cx={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Jp=10;function Hp(){let[e,t]=useState(_i());useEffect(()=>Fl(()=>{t([..._i()]);}),[]);let r=e.slice(-Jp);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Jp,") \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:cx[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var mx=x("app"),fx={auth:$c,starterKitSetup:dp,moduleSetup:_p,claudeMdSuggestion:Up,verify:Vp,main:Qd};function zp(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function so(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Xp(){v(b.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:lr(),interface:"tui"}).catch(()=>{});}async function Yp(){let e=await Y();if(e&&hc()&&await ir()){e.customUrl&&It(e.customUrl);let{clientSecret:n,...o}=e;We.getState().setCredentials(o),Xp(),so(e);return}if(!e){zp();return}try{e.customUrl&&It(e.customUrl),await bt();}catch(n){mx.debug(`Token validation failed: ${String(n)}`),zp();return}Xp();let{clientSecret:t,...r}=e;We.getState().setCredentials(r),so(e);}function Zp(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=fx[r],{pendingExit:o}=cc(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let u=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!u);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(Hp,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}async function wl(e,t={}){let r=us({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return ds(r),await Bt(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var wt=x("auth");function em(){Ue.clearFallbackFile(),rs();}var gx=3,Qp=3,tm=` \u2139 The data collected during setup is used solely to improve
|
|
117
117
|
Flow's internal tools and will not be shared externally.
|
|
118
|
-
`;function
|
|
118
|
+
`;function Qt(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=c=>{if(c===""){l(),n(new Error("SIGINT"));return}if(c==="\r"||c===`
|
|
119
119
|
`){l(),process.stdout.write(`
|
|
120
|
-
`),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function
|
|
121
|
-
`+
|
|
122
|
-
`),(await
|
|
123
|
-
`));}}async function
|
|
124
|
-
`)):n?process.stdout.write(
|
|
125
|
-
`)):
|
|
120
|
+
`),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function hx(){let e=Ur();return process.stdout.write(`
|
|
121
|
+
`+T.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
|
|
122
|
+
`),(await Qt(T.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function rm(e,t,r){try{await wl(e,{jwtOverride:r});return}catch(n){if(!(n instanceof Nr))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${Ur()} and retry.`);if(!await hx())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await wl(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function yx(){if((await Qt(T.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await Qt(T.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(en.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${tn}. Try again.
|
|
123
|
+
`));}}async function wx(){let e=(await Qt(T.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await Qt(T.cyan(" ? ")+"Enter your email address: ")).trim();if(rn.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${nn}. Try again.
|
|
124
|
+
`));}}async function nm(e,t){process.stdout.write(T.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await no(e,t);return r?process.stdout.write(T.yellow(` \u26A0 npm install failed. Please contact Flow support.
|
|
125
|
+
`)):o?process.stdout.write(T.yellow(` \u26A0 Unexpected error. Please contact Flow support.
|
|
126
|
+
`)):n?process.stdout.write(T.yellow(`
|
|
126
127
|
\u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
|
|
127
|
-
`)):process.stdout.write(
|
|
128
|
-
`)),{initFailed:
|
|
129
|
-
`+
|
|
130
|
-
`),e.forEach((t,r)=>{process.stdout.write(` ${
|
|
128
|
+
`)):process.stdout.write(T.green(` done
|
|
129
|
+
`)),{initFailed:n}}async function om(){for(let e=1;e<=Qp;e++)try{return await _s()}catch{if(e===Qp)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function sm(){let e=await om();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
|
|
130
|
+
`+T.cyan(" ? ")+`Starter Kit:
|
|
131
|
+
`),e.forEach((t,r)=>{process.stdout.write(` ${T.cyan(`${r+1})`)} ${y(t.name)}
|
|
131
132
|
`);}),process.stdout.write(`
|
|
132
|
-
`);;){let t=(await
|
|
133
|
-
`));}}async function
|
|
133
|
+
`);;){let t=(await Qt(T.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write(T.yellow(` \u26A0 Invalid selection. Please try again.
|
|
134
|
+
`));}}async function im(e){if(e.plugins.length===0)return process.stdout.write(T.dim(`
|
|
134
135
|
Starter kit '${y(e.name)}' has no plugins to install.
|
|
135
136
|
`)),true;process.stdout.write(`
|
|
136
137
|
Installing ${e.plugins.length} plugins from '${y(e.name)}'...
|
|
137
|
-
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(
|
|
138
|
-
`)):(r++,process.stdout.write(
|
|
139
|
-
`)));}return r===0?process.stdout.write(
|
|
140
|
-
`)):process.stdout.write(
|
|
141
|
-
`)),r===0}async function
|
|
142
|
-
`),process.stdout.write(
|
|
143
|
-
`)),process.stdout.write(
|
|
138
|
+
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(T.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=gx;a++)try{await ke(o),t++,i=!0;break}catch(l){if(l instanceof Be){t++,i=true;break}}i?process.stdout.write(T.green(` done
|
|
139
|
+
`)):(r++,process.stdout.write(T.red(` failed
|
|
140
|
+
`)));}return r===0?process.stdout.write(T.green(` \u2713 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed successfully.
|
|
141
|
+
`)):process.stdout.write(T.yellow(` \u26A0 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
|
|
142
|
+
`)),r===0}async function am(){process.stdout.write(`
|
|
143
|
+
`),process.stdout.write(T.bold(` Personalize your Claude Code
|
|
144
|
+
`)),process.stdout.write(T.dim(` This plugin helps Claude understand your preferences and work style.
|
|
144
145
|
|
|
145
|
-
`));let e=(await
|
|
146
|
+
`));let e=(await Qt(T.cyan(" ? ")+`Install ${ne}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){v(b.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(`
|
|
146
147
|
You can always install it later from the catalog.
|
|
147
|
-
`));return}
|
|
148
|
-
`));}catch(t){if(t instanceof
|
|
149
|
-
`));else {
|
|
150
|
-
`)),process.stdout.write(
|
|
148
|
+
`));return}v(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(` Installing ${ne}...`));try{await ke(ne),process.stdout.write(T.green(` done
|
|
149
|
+
`));}catch(t){if(t instanceof Be)process.stdout.write(T.green(` already installed
|
|
150
|
+
`));else {wt.warn(`Failed to install ${ne}: ${t instanceof Error?t.message:t}`),process.stdout.write(T.red(` failed
|
|
151
|
+
`)),process.stdout.write(T.dim(` You can install it later from the catalog.
|
|
151
152
|
`));return}}process.stdout.write(`
|
|
152
153
|
`),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
|
|
153
|
-
`),process.stdout.write(
|
|
154
|
+
`),process.stdout.write(T.cyan.bold(` /${ne}
|
|
154
155
|
`)),process.stdout.write(` Claude will guide you through the rest.
|
|
155
|
-
`);}async function
|
|
156
|
-
`+
|
|
157
|
-
`),e.customUrl!==void 0&&!
|
|
158
|
-
`)),1;
|
|
159
|
-
`)),1
|
|
160
|
-
`)),1}
|
|
156
|
+
`);}async function Sx(e){if(em(),process.stdout.write(`
|
|
157
|
+
`+tm+`
|
|
158
|
+
`),e.customUrl!==void 0&&!en.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${tn}.
|
|
159
|
+
`)),1;if(e.customEmail!==void 0&&!rn.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${nn}.
|
|
160
|
+
`)),1;let t=e.jwt.trim(),r;try{r=to(t);}catch(o){let s=y(o instanceof Error?o.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${s}
|
|
161
|
+
`)),1}e.customUrl&&It(e.customUrl),wt.debug(`[${r.tenant}] Authenticating tenant via JWT`);try{await $r(r);}catch(o){let s=y(o instanceof Error?o.message:"unknown error");return wt.error(`[${r.tenant}] Authentication failed: ${s}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${s}
|
|
162
|
+
`)),1}let{initFailed:n}=await nm(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await om(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(T.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
|
|
161
163
|
`)),process.stderr.write(` Available starter kits:
|
|
162
164
|
`);for(let a of s)process.stderr.write(` - ${y(a.slug)} (${y(a.name)})
|
|
163
|
-
`);return 1}o=i;}else o=await
|
|
164
|
-
\u2713 Setup complete. Tenant: ${y(r.tenant)}. JWT written to ${
|
|
165
|
+
`);return 1}o=i;}else o=await sm();return await rm({...r,starterKit:o.slug,customUrl:e.customUrl},!1,t),await im(o),await am(),wt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(T.green(`
|
|
166
|
+
\u2713 Setup complete. Tenant: ${y(r.tenant)}. JWT written to ${Ur()}.
|
|
165
167
|
|
|
166
|
-
`)),n&&e.customUrl&&process.stdout.write(
|
|
167
|
-
`)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=y(o instanceof Error?o.message:"unknown error");return
|
|
168
|
-
`)),1}}async function
|
|
169
|
-
`),process.stdout.write(
|
|
170
|
-
`);let
|
|
171
|
-
`)),1;let
|
|
172
|
-
`)),1}let
|
|
173
|
-
`)),1}let{initFailed:
|
|
174
|
-
\u2713 Setup complete. Tenant: ${y(
|
|
175
|
-
`)),o&&
|
|
168
|
+
`)),n&&e.customUrl&&process.stdout.write(T.yellow(` \u26A0 Custom URL was not written to settings.json \u2014 flow-ai-obs authentication failed for ${y(e.customUrl)}.
|
|
169
|
+
`)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=y(o instanceof Error?o.message:"unknown error");return wt.error(`[${r.tenant}] Starter kit setup failed: ${s}`),process.stderr.write(T.red(` \u2717 Starter kit setup failed: ${s}
|
|
170
|
+
`)),1}}async function xx(e,t){em(),wt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
|
|
171
|
+
`),process.stdout.write(tm+`
|
|
172
|
+
`);let r=(await Qt(T.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return wt.error("[auth] Validation failed: JWT is required"),process.stderr.write(T.red(` \u2717 JWT is required
|
|
173
|
+
`)),1;let n;try{n=to(r);}catch(l){let u=y(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${u}
|
|
174
|
+
`)),1}let o=e??await yx(),s=t??await wx();o&&It(o),wt.debug(`[${n.tenant}] Authenticating tenant`);try{await $r(n);}catch(l){let u=y(l instanceof Error?l.message:"unknown error");return wt.error(`[${n.tenant}] Authentication failed: ${u}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${u}
|
|
175
|
+
`)),1}let{initFailed:i}=await nm(o,s),a=await sm();return await rm({...n,starterKit:a.slug,customUrl:o??void 0},!0,r),await im(a),await am(),wt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(T.green(`
|
|
176
|
+
\u2713 Setup complete. Tenant: ${y(n.tenant)}. JWT written to ${Ur()}.
|
|
177
|
+
`)),i&&o&&process.stdout.write(T.yellow(` \u26A0 Custom URL was not written to settings.json \u2014 flow-ai-obs authentication failed for ${y(o)}.
|
|
176
178
|
`)),process.stdout.write(`
|
|
177
|
-
`),0}catch(
|
|
178
|
-
`)),1}}async function
|
|
179
|
-
`)),1;
|
|
180
|
-
`),
|
|
181
|
-
`),
|
|
179
|
+
`),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=y(r instanceof Error?r.message:"unknown error");return wt.error(`[auth] Unexpected error: ${n}`),process.stderr.write(T.red(` \u2717 Unexpected error: ${n}
|
|
180
|
+
`)),1}}async function Sl(e={}){if(e.jwt)return Sx({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!en.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${tn}.
|
|
181
|
+
`)),1;if(e.customEmail!==void 0&&!rn.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${nn}.
|
|
182
|
+
`)),1;try{return await xx(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
|
|
183
|
+
`),130;throw t}}async function Ix(){try{return process.stdout.write(`
|
|
184
|
+
`),(await Qt(T.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(T.yellow(` \u26A0 Logout cancelled
|
|
182
185
|
`)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
|
|
183
|
-
`),130;throw e}}async function
|
|
184
|
-
`)),0;if(!e){let t=await
|
|
185
|
-
`)),0}catch{return process.stderr.write(
|
|
186
|
-
`)),1}}async function
|
|
187
|
-
`+
|
|
188
|
-
`)),process.stdout.write(
|
|
189
|
-
`),process.stdout.write(
|
|
190
|
-
`),process.stdout.write(
|
|
191
|
-
`),process.stdout.write(
|
|
186
|
+
`),130;throw e}}async function lm(e){if(!await Y())return process.stdout.write(T.yellow(` \u26A0 You are not authenticated
|
|
187
|
+
`)),0;if(!e){let t=await Ix();if(t!==null)return t}try{return await Xl(),process.stdout.write(T.green(` \u2713 Credentials removed successfully
|
|
188
|
+
`)),0}catch{return process.stderr.write(T.red(` \u2717 Error removing credentials
|
|
189
|
+
`)),1}}async function cm(){let e=await Y();return e?await ir()?(process.stdout.write(`
|
|
190
|
+
`+T.bold(` Authenticated
|
|
191
|
+
`)),process.stdout.write(T.dim(" Tenant: ")+y(e.tenant)+`
|
|
192
|
+
`),process.stdout.write(T.dim(" Client ID: ")+y(e.clientId)+`
|
|
193
|
+
`),process.stdout.write(T.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
|
|
194
|
+
`),process.stdout.write(T.dim(" Config: ")+y(await ql())+`
|
|
192
195
|
`),process.stdout.write(`
|
|
193
|
-
`),0):(process.stdout.write(
|
|
196
|
+
`),0):(process.stdout.write(T.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(T.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function bx(e){let t=te(),r;try{r=await gr();}catch{r=[];}let n=new Set(t.map(o=>o.name));return v(b.CLI_CATALOG_VIEWED,{interface:H().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(nr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(ln(["","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 vx(e){let t=te(),r=await gr(),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&&Le(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return v(b.CLI_CATALOG_VIEWED,{interface:H().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(C("All plugins are up to date."),0):e.json?(nr(o),0):(ln(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
|
|
194
197
|
${o.length} plugin(s) outdated.
|
|
195
|
-
`),0)}async function
|
|
198
|
+
`),0)}async function Ex(e){let t=te();if(v(b.CLI_CATALOG_VIEWED,{interface:H().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return C("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return nr(t),0;let r=[];try{r=await gr();}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=Ao.indexOf(s.scope??"user"),l=Ao.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return ln(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"bundle",l=i?.origin??za(s.marketplace);return [s.name??"",s.version??"n/a",Qr[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",xt(s.installedAt??"")]})),process.stdout.write(`
|
|
196
199
|
${t.length} plugin(s) installed.
|
|
197
|
-
`),0}async function
|
|
200
|
+
`),0}async function um(e){if(!await se())return 1;try{return e.available?await bx(e):e.outdated?await vx(e):await Ex(e)}catch(t){return E(t instanceof Error?t.message:"Failed to list plugins."),1}}var ie=x("manage");function yi(e,t){return t?te().find(r=>r.name===e&&r.scope===t):te().find(r=>r.name===e)}function Px(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,C(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=xl({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function Tx(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(In(e,r.scope));if(!await kt(`${t}Install external plugin "${i}"?
|
|
198
201
|
This will run: ${a}
|
|
199
|
-
[y/N] `))return
|
|
200
|
-
Installation summary: ${t} succeeded, ${r} failed`);}async function
|
|
201
|
-
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function
|
|
202
|
+
[y/N] `))return ie.debug(`[${e}] Installation cancelled by user`),r.silent||C(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=xl({text:`${t}Installing ${e}...`}).start());}let s=o?Px(t,o):void 0;try{let i=await _d(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Ge({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?Oe({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):oe(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=J(i);return r.silent?Ge({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function Cx(e,t,r){let n=r.silent?void 0:xl({text:`${t}Installing ${e}...`}).start();if(Sn(e))return Tx(e,t,r,n);try{let o=await ke(e,{...r,onDownloadProgress:r.silent?void 0:(s,i)=>{if(!n||i===0)return;let{bar:a,percent:l,label:u}=Es(s,i);n.text=`${t}Downloading ${e}... ${a} ${l}% (${u})`;}});return n?.stop(),r.silent?Oe({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):oe(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof Be)return r.silent?Oe({status:"already_installed",plugin:e,message:o.message}):C(`${t}${o.message}`),{name:e,success:true};let s=J(o);return r.silent?Ge({status:"error",plugin:e,message:s}):E(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function kx(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;C(`
|
|
203
|
+
Installation summary: ${t} succeeded, ${r} failed`);}async function wi(e,t={}){if(!await se())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",s=await Cx(e[n],o,t);r.push(s);}return e.length>1&&(t.silent?Oe({status:"summary",succeeded:r.filter(n=>n.success).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.error?{error:n.error}:{}}))}):kx(r)),r.some(n=>!n.success)?1:0}async function dm(e,t){if(!await se())return 1;if(ie.debug(`[${e}] Looking up installed plugin`),!t.force){let r=yi(e,t.scope);if(!r)return ie.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;let n=y(r.name),o=r.version?y(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await kt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return ie.debug(`[${e}] Uninstall cancelled by user`),C("Operation cancelled."),0}try{return ie.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await mo(e,t.scope),ie.info(`[${e}] Uninstalled successfully`),oe("Plugin removed successfully"),0}catch(r){return ie.error(`[${e}] Failed to uninstall: ${J(r)}`),E(J(r)),1}}async function pm(e,t={}){if(!await se())return 1;ie.debug(`[${e}] Looking up installed plugin`);let r=yi(e,t.scope);if(!r)return ie.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return ie.debug(`[${e}] Already enabled, skipping`),C(`${r.name} is already enabled`),0;try{return ie.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await fo(e,"enabled",t.scope),ie.info(`[${e}] Enabled successfully`),oe(`${r.name} enabled successfully`),0}catch(n){return ie.error(`[${e}] Failed to enable: ${J(n)}`),E(J(n)),1}}async function mm(e,t={}){if(!await se())return 1;ie.debug(`[${e}] Looking up installed plugin`);let r=yi(e,t.scope);if(!r)return ie.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return ie.debug(`[${e}] Already disabled, skipping`),C(`${r.name} is already disabled`),0;try{return ie.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await fo(e,"disabled",t.scope),ie.info(`[${e}] Disabled successfully`),oe(`${r.name} disabled successfully`),0}catch(n){return ie.error(`[${e}] Failed to disable: ${J(n)}`),E(J(n)),1}}async function fm(e,t,r){r.silent||C(`${t}Updating ${e}...`);try{let n=await Ys(e,r);return r.silent?Oe({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):oe(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof fr)return r.silent?Oe({status:"up_to_date",plugin:e,message:n.message}):C(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=J(n);return r.silent?Ge({status:"error",plugin:e,message:o}):E(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Ax(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;C(`
|
|
204
|
+
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function $x(e,t,r){try{let n=await vn(e);Le(t,n.version,r.force)?C(`Would update ${e}: v${t} \u2192 v${n.version}`):C(`${e} is already up to date (v${t})`);}catch(n){return E(J(n)),1}return 0}function Lx(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Mx(e,t,r){let n=t.get(e.name);return n?e.version&&Le(e.version,n,r)?(C(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(C(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(C(`Skipping ${e.name}: not found in catalog`),false)}async function Rx(e,t){try{let r=await gr(),n=Lx(r),o=0;for(let s of e)Mx(s,n,t.force)&&o++;o===0&&C("All plugins are up to date");}catch(r){return E(J(r)),1}return 0}async function _x(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await fm(e[n].name,o,t);r.push(s);}return t.silent?Oe({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}:{}}))}):Ax(r),r.some(n=>!n.success)?1:0}async function gm(e,t={}){if(!await se())return 1;if(e){let o=yi(e,t.scope);return o?t.dryRun?$x(e,o.version??"",t):(await fm(e,"",t)).success?0:1:(t.silent?Ge({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):E(`Plugin "${e}" is not installed`),1)}let n=te().filter(o=>o.marketplace===X);return n.length===0?(t.silent?Oe({status:"empty",message:"No plugins installed"}):C("No plugins installed"),0):t.dryRun?Rx(n,t):_x(n,t)}var _o=x("cli:bundle");function Dx(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 Ox(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
|
|
202
205
|
Bundle: ${y(e)} (${t.length} artifacts)
|
|
203
|
-
`);for(let o of t)process.stdout.write(`${
|
|
206
|
+
`);for(let o of t)process.stdout.write(`${Dx(o)}
|
|
204
207
|
`);process.stdout.write(`
|
|
205
208
|
${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
|
|
206
209
|
|
|
207
|
-
`);}async function
|
|
210
|
+
`);}async function hm(e){if(!e.trim())return E("Bundle name cannot be empty."),1;if(!await se())return 1;_o.debug(`Fetching bundle "${e}"`);let r;try{r=await ti(e);}catch(a){return a instanceof _n||a instanceof ko?(E(a.message),1):(E(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(_o.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),Ox(r.title,n),o.length===0)return E("No artifacts available for installation in this bundle."),1;if(!await kt(`Install ${o.length} artifact(s)? [Y/n] `))return _o.debug("Installation cancelled by user"),0;_o.debug(`Starting installation of ${o.length} artifact(s)`);let i=await Ws(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=y(u.name??u.flowId),p=y(u.type??"unknown"),f=c?"\u2713":`\u2717 (${y(d??"failed")})`;a===1&&process.stdout.write(`
|
|
208
211
|
`),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${f}
|
|
209
212
|
`),a===l&&process.stdout.write(`
|
|
210
|
-
`);}});if(
|
|
213
|
+
`);}});if(_o.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&oe(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");E(`${i.failed} failed: ${y(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>y(l.name??l.flowId)).join(", ");C(`${i.skipped} unavailable: ${a}`);}return 0}var ym=x("marketplace");function Nx(e){return `claude plugin marketplace add ${e}`}async function wm(e,t){if(!await se())return 1;let r;try{r=Ms(e);}catch(s){let i=J(s);return t.silent?Ge({status:"error",source:e,message:i}):E(i),1}ym.debug(`[marketplace] Adding marketplace source: ${r}`);let n=Nx(r);if(!t.force){let s=y(r),i=y(n);if(!await kt(`Add marketplace "${s}"?
|
|
211
214
|
This will run: ${i}
|
|
212
|
-
[y/N] `))return
|
|
213
|
-
`+
|
|
215
|
+
[y/N] `))return ym.debug("[marketplace] Operation cancelled by user"),C("Operation cancelled."),0}let o=t.silent?void 0:xl({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await be(n);return o?.stop(),s.exitCode!==0?(t.silent?Ge({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(E(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&C(`stdout: ${s.stdout}`)),1):(t.silent?Oe({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(oe(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&C(s.stdout)),0)}catch(s){o?.stop();let i=J(s);return t.silent?Ge({status:"error",source:r,message:i}):E(`Failed to add marketplace "${r}": ${i}`),1}}async function Kx(){return await Y()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Vx(){let e=Date.now();try{await gr();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 Jx(){return await ir()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Hx(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}async function Sm(){process.stdout.write(`
|
|
216
|
+
`+T.bold(` FlowSetup CLI Diagnostics
|
|
214
217
|
|
|
215
|
-
`));let e=[{name:"Credentials",fn:
|
|
218
|
+
`));let e=[{name:"Credentials",fn:Kx},{name:"Prompt Manager",fn:Vx},{name:"Valid Token",fn:Jx},{name:"Claude Code",fn:Hx}],t=true;for(let r of e){let n=await r.fn(),o="",s=T.green;n.passed?o=T.green("[OK] "):(o=T.red("[FAIL]"),s=T.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${y(n.message)}`;process.stdout.write(i+`
|
|
216
219
|
`);}return process.stdout.write(`
|
|
217
|
-
`),t?(process.stdout.write(
|
|
220
|
+
`),t?(process.stdout.write(T.green(` \u2713 All checks passed!
|
|
218
221
|
|
|
219
|
-
`)),0):(process.stdout.write(
|
|
222
|
+
`)),0):(process.stdout.write(T.red(` \u2717 Some checks failed \u2014 verify your configuration
|
|
220
223
|
|
|
221
|
-
`)),1)}
|
|
222
|
-
`),process.stdout.write(
|
|
223
|
-
`),process.stdout.write(
|
|
224
|
-
`),process.stdout.write(` ${p} ${f} ${
|
|
225
|
-
`),process.stdout.write(
|
|
224
|
+
`)),1)}dn();async function xm(e){let t=await Y(),r=ar("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Ut.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await yu.get(`${r}rate-limit/me`,{searchParams:{mode:"budget"},headers:n}).json();if(typeof o.consumed_usd!="number"||typeof o.budget_limit!="number"||typeof o.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return o}var Wx=x("commands:usage"),Si=20,Im="EMAIL",bm="MONTHLY CONSUMPTION (USD)",vm="STATUS";function zx(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*Si),n=Si-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 Em(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Xx(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 qx(e){let t=xt(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 Yx(e){try{let t=await ss();if(t?.email)return y(t.email);let r=un(e);return y(r.email??"")}catch(t){return Wx.debug(`JWT email decode failed: ${String(t)}`),""}}async function Pm(e){if(!await se())return 1;let r;try{r=await bt();}catch(g){return E(`Authentication error: ${J(g)}`),1}let n;try{n=await xm(r);}catch(g){return E(`Failed to fetch usage data: ${J(g)}`),1}if(e.json)return nr(n),0;let o=await Yx(r)||y(n.user_id),s=Em(n.consumed_usd),i=Em(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(Im.length,o.length+2),c=Math.max(bm.length,Si+2+l.length),d=` ${Im.padEnd(u)} ${bm.padEnd(c)} ${vm}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(vm.length)}`,p=`${T.cyan("\u2022")} ${o.padEnd(u-2)}`,f=`${zx(n.percentage)} ${l.padEnd(c-Si-2)}`,h=` ${T.dim("Resets")} ${qx(n.renewal_date)}`;return process.stdout.write(`
|
|
225
|
+
`),process.stdout.write(T.dim(d)+`
|
|
226
|
+
`),process.stdout.write(T.dim(m)+`
|
|
227
|
+
`),process.stdout.write(` ${p} ${f} ${Xx(n.status)}
|
|
228
|
+
`),process.stdout.write(h+`
|
|
226
229
|
`),process.stdout.write(`
|
|
227
|
-
`),0}var
|
|
228
|
-
`,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function
|
|
229
|
-
`);for(let a of o){let l=y(a.name),u=y(a.description);process.stdout.write(` ${
|
|
230
|
+
`),0}var eI=["github.com","www.github.com"],tI=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,rI=/^([^@]+)@(.+)$/;function nI(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Il(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 oI(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=Il(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Il(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function xi(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(nI(t)){let r=resolve(t);return {type:"local",url:r,localPath:r}}try{let r=new URL(t);if((r.protocol==="https:"||r.protocol==="http:")&&eI.includes(r.hostname))return oI(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(tI);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(rI);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=Il(m));}return d}}return {type:"git",url:t}}function Ii(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 Tm(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 vl=new Set(["node_modules",".git","dist","build","__pycache__"]);function Am(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function cI(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function bl(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Do(e){try{let t=await readFile(e,"utf-8"),{data:r}=Tm(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 $m(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([bl(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!vl.has(a.name)).map(a=>$m(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function Ei(e,t){let r=[],n=new Set;if(t&&!cI(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await bl(o)){let i=await Do(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 bl(u)){let c=await Do(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await $m(o);for(let a of i){let l=await Do(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function Lm(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}var Dm=1,gI={retries:5,minTimeout:50};async function Om(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Ug.lock(e+".lock",{realpath:false,retries:gI});try{return await t()}finally{await r();}}function Mm(){return {version:Dm,skills:{}}}async function Pi(e){let t=Vn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Dm?Mm():n}catch{return Mm()}}function hI(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Um(e,t){let r=Vn(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:hI(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
|
|
231
|
+
`,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function Nm(e,t,r){let n=Vn(r);await Om(n,async()=>{let o=await Pi(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Um(o,r);});}async function Bm(e,t){let r=Vn(t);await Om(r,async()=>{let n=await Pi(t);e in n.skills&&(delete n.skills[e],await Um(n,t));});}var Fm=x("skillInstaller");async function EI(e,t,r,n){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:H().interfaceType});}catch(o){Fm.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function PI(e,t){try{await v(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:H().interfaceType});}catch(r){Fm.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function TI(e,t){await cp$1(e,t,{recursive:true,dereference:false,filter:r=>{if(vl.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function CI(e,t,r){let n=Qe(e.name),o=Cr(t),s=join(o,n);if(!Am(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 TI(e.path,s);let a=Ii(r)??r.url;return await Nm(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 jm(e,t){let r=xi(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 At(r.url,r.ref),o=n;let s=await Ei(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?Lm(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await CI(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await EI(c.name,t.scope,u,p):await PI(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 $t(n).catch(()=>{});}}var MI=x("skills");async function RI(e){try{await v(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:H().interfaceType});}catch(t){MI.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function _I(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 DI(e){let t=xi(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return E("Invalid local path."),1;n=t.localPath;}else C(`Fetching skills from ${y(e)}...`),r=await At(t.url,t.ref),n=r;let o=await Ei(n,t.subpath);if(o.length===0)return C("No skills found in this source."),0;let i=Ii(t)??y(e);C(`Found ${o.length} skill(s) in ${i}:
|
|
232
|
+
`);for(let a of o){let l=y(a.name),u=y(a.description);process.stdout.write(` ${T.bold(l)} ${T.dim(u)}
|
|
230
233
|
`);}return process.stdout.write(`
|
|
231
|
-
`),0}catch(n){return n instanceof
|
|
232
|
-
`);let t=e.source;e.installed>0&&C(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&
|
|
233
|
-
`);for(let s of r){let i=n.skills[
|
|
234
|
-
`),process.stdout.write(` ${
|
|
234
|
+
`),0}catch(n){return n instanceof wr?E(n.message):E(n instanceof Error?n.message:String(n)),1}finally{r&&await $t(r).catch(()=>{});}}function OI(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);oe(`${n} installed ${T.dim(`\u2192 ${o}/`)}`);}else E(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
|
|
235
|
+
`);let t=e.source;e.installed>0&&C(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&E(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?C("No skills found in this source."):e.results.length===0&&e.discovered>0&&C(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Vm(e,t){if(t.list)return DI(e);let r=t.global?"global":"project";try{let n=await jm(e,{scope:r,skillFilter:t.skill,yes:t.yes});return OI(n),n.failed>0?1:0}catch(n){return n instanceof wr?E(n.message):E(n instanceof Error?n.message:String(n)),1}}async function Jm(e){let t=Cr(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 Do(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 Hm(e){let t=e.global?"global":"project",r=await Jm(t),n=await Pi(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[Qe(i.name)]?.source}));return nr(s),0}if(r.length===0)return C(`No skills installed (${t==="global"?"global":"project"} scope).`),0;C(`${t==="global"?"Global":"Project"} skills (${r.length}):
|
|
236
|
+
`);for(let s of r){let i=n.skills[Qe(s.name)]?.source,a=y(s.name),l=y(s.description),u=l.length>80?l.slice(0,77)+"...":l,c=i?T.dim(` (${i})`):"";process.stdout.write(` ${T.bold(a)}${c}
|
|
237
|
+
`),process.stdout.write(` ${T.dim(u)}
|
|
235
238
|
|
|
236
|
-
`);}return 0}async function
|
|
239
|
+
`);}return 0}async function Gm(e,t){let r=t.global?"global":"project";if(!e){let i=await Jm(r);if(i.length===0)return C("No skills installed."),0;C("Installed skills:");for(let a of i)process.stdout.write(` - ${y(a.name)}
|
|
237
240
|
`);return process.stdout.write(`
|
|
238
|
-
`),C("Specify a skill name to remove: flow skills remove <name>"),1}let n=
|
|
239
|
-
Import summary: 0 installed, ${o.length} failed`);for(let a of o)
|
|
240
|
-
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)
|
|
241
|
+
`),C("Specify a skill name to remove: flow skills remove <name>"),1}let n=Qe(e),o=Cr(r),s=join(o,n);try{await stat(s);}catch{return E(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await _I(`Remove skill "${y(n)}"?`))return C("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Bm(n,r),await RI(n),oe(`Skill "${y(n)}" removed.`),0}catch(i){return E(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}var Ti=x("transfer"),Pl=1;function UI(e){return e.marketplace&&e.marketplace!==X?`${e.name}@${e.marketplace}`:e.name}function NI(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&C(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),C(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Xm(e){let t=ge__default.resolve(e.output);try{let r=te(),n={version:Pl,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 he__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),oe(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=J(r);return Ti.error(`Export failed: ${n}`),E(`Failed to export plugins: ${n}`),1}}async function qm(e,t={}){if(!await se())return 1;let r;try{let a=he__default.readFileSync(ge__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return E(`Failed to read import file "${e}": ${J(a)}`),1}if(r.version!==Pl)return E(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Pl}`),1;if(!Array.isArray(r.plugins))return E('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return C("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let u=`entry[${a}]`;Ti.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(Ti.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&C(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(te().map(l=>l.name));NI(n,a);}if(t.dryRun)return C("Dry-run mode: no plugins were installed"),0;if(n.length===0){C(`
|
|
242
|
+
Import summary: 0 installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}C(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=UI(a);Ti.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await wi([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}C(`
|
|
243
|
+
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}function B(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var FI=x("moduleProxy");function jI(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=_a.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 Ym(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await v(b.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{FI.warn(`Failed to emit proxy executed event: ${String(s)}`);}),B(o);}async function Qm(e,t){let r=ee.find(o=>o.alias===e);if(!r){E(`Unknown module alias: '${e}'`),B(1);return}if(!await Et(r.binaryName)){E(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),B(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Tt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){E(`No supported installation method available for '${e}' on this platform.`),B(1);return}if(await jI("Would you like to install it now? [Y/n] ")){await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await pr(r,"inline",s);if(!a.success){E(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),B(1);return}await Ym(r,t);}else C(`To install manually, run: flow modules install ${e}`),await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),B(1);return}await Ym(r,t);}var HI=promisify(execFile);async function GI(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await HI(Ft(),["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/${ae}`,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 WI(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Le(t,r)?"outdated":"installed"}async function Tl(){let e=await Promise.all(ee.map(async t=>{let[r,n]=await Promise.all([Et(t.binaryName),GI(t)]),s=ze(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=WI(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return ln(["Name","Alias","Version","Status","Platform"],e),0}async function rf(e){let t=ee.find(i=>i.alias===e);if(!t)return E(`Unknown module alias: '${e}'`),1;let[r]=await On([t]);if(r.alreadyInstalled){let i=ze(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return C(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?E(`Module ${t.name} is not supported on ${process.platform}.${a}`):E(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=xl({text:`Installing ${t.name}...`}).start(),s;try{s=await pr(t,"on_demand",n);}finally{o.stop();}return s.success?(oe(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(E(s.error?.message??"Installation failed"),1)}async function ef(e,t){let r=xl({text:`Updating ${e.name}...`}).start(),n;try{n=await ws(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 nf(e){if(e!==null){let n=ee.find(i=>i.alias===e);if(!n)return E(`Unknown module alias: '${e}'`),1;let o=ze(n.alias);return o?.installMethod?await ef(n,o.installedVersion??"unknown")==="error"?1:0:(E(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=Br().filter(n=>n.installMethod!==null);if(t.length===0)return C("No installed modules to update."),0;let r=0;for(let n of t){let o=ee.find(i=>i.alias===n.alias);if(!o)continue;await ef(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}function of(e){let t=new Command;t.enablePositionalOptions(),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${ae}`,"-V, --version","Display the CLI version").addHelpText("after",`
|
|
241
244
|
Without arguments, opens the interactive interface (TUI).
|
|
242
245
|
Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let r=new Command("setup").description("Configure the CLI by detecting Claude Code credentials");r.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
|
|
243
246
|
Examples:
|
|
244
|
-
$ flow setup init`).action(async()=>{let c=await
|
|
247
|
+
$ flow setup init`).action(async()=>{let c=await Sl();B(c);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).addHelpText("after",`
|
|
245
248
|
Examples:
|
|
246
249
|
$ flow plugin list
|
|
247
250
|
$ flow plugin list --available
|
|
248
251
|
$ flow plugin list --outdated
|
|
249
|
-
$ flow plugin list --json`).action(async c=>{let d=await
|
|
252
|
+
$ flow plugin list --json`).action(async c=>{let d=await um(c);B(d);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
250
253
|
Examples:
|
|
251
254
|
$ flow plugin install flow-adr-writer
|
|
252
255
|
$ flow plugin install flow-adr-writer --scope project
|
|
@@ -254,11 +257,11 @@ Examples:
|
|
|
254
257
|
$ flow plugin install flow-adr-writer --force
|
|
255
258
|
$ flow plugin install flow-adr-writer --silent
|
|
256
259
|
$ flow plugin install superpowers@claude-plugins-official
|
|
257
|
-
$ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(c,d)=>{let m=c.filter(f=>f.trim());if(m.length===0){
|
|
260
|
+
$ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(c,d)=>{let m=c.filter(f=>f.trim());if(m.length===0){E("No valid plugin names provided"),B(1);return}De("cli",{verbose:d.verbose,silent:d.silent});let p=await wi(m,d);B(p);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
258
261
|
Examples:
|
|
259
262
|
$ flow plugin uninstall flow-adr-writer
|
|
260
263
|
$ flow plugin uninstall flow-adr-writer --scope project
|
|
261
|
-
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await
|
|
264
|
+
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await dm(c,d);B(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",`
|
|
262
265
|
Examples:
|
|
263
266
|
$ flow plugin update flow-adr-writer
|
|
264
267
|
$ flow plugin update flow-adr-writer --scope project
|
|
@@ -267,77 +270,78 @@ Examples:
|
|
|
267
270
|
$ flow plugin update flow-adr-writer --verbose
|
|
268
271
|
$ flow plugin update flow-adr-writer --silent
|
|
269
272
|
$ flow plugin update
|
|
270
|
-
$ flow plugin update --dry-run`).action(async(c,d)=>{
|
|
273
|
+
$ flow plugin update --dry-run`).action(async(c,d)=>{De("cli",{verbose:d.verbose,silent:d.silent});let m=await gm(c??null,d);B(m);}),n.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addOption(new Option("--scope <scope>","Scope to enable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
271
274
|
Examples:
|
|
272
275
|
$ flow plugin enable flow-adr-writer
|
|
273
|
-
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{
|
|
276
|
+
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{De("cli");let m=await pm(c,d);B(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",`
|
|
274
277
|
Examples:
|
|
275
278
|
$ flow plugin disable flow-adr-writer
|
|
276
|
-
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{
|
|
279
|
+
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{De("cli");let m=await mm(c,d);B(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
|
|
277
280
|
Examples:
|
|
278
281
|
$ flow plugin export
|
|
279
|
-
$ flow plugin export --output my-plugins.json`).action(async c=>{let d=await
|
|
282
|
+
$ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Xm(c);B(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",`
|
|
280
283
|
Examples:
|
|
281
284
|
$ flow plugin import flow-plugins.json
|
|
282
285
|
$ flow plugin import flow-plugins.json --scope user
|
|
283
286
|
$ flow plugin import flow-plugins.json --force
|
|
284
287
|
$ flow plugin import flow-plugins.json --dry-run
|
|
285
|
-
$ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await
|
|
288
|
+
$ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await qm(c,d);B(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",`
|
|
286
289
|
Examples:
|
|
287
290
|
$ flow plugin marketplace add anthropics/claude-code
|
|
288
291
|
$ flow plugin marketplace add https://github.com/owner/repo
|
|
289
292
|
$ flow plugin marketplace add anthropics/claude-code --force
|
|
290
|
-
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{
|
|
293
|
+
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{De("cli",{verbose:d.verbose,silent:d.silent});let m=await wm(c,d);B(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",`
|
|
291
294
|
Examples:
|
|
292
295
|
$ flow mcp add notion --transport http https://mcp.notion.com/mcp
|
|
293
296
|
$ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
|
|
294
297
|
$ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
|
|
295
|
-
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{
|
|
298
|
+
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{De("cli",{verbose:m.verbose,silent:m.silent});let p=await Bd(c,d,m);B(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",`
|
|
296
299
|
Examples:
|
|
297
300
|
$ flow mcp remove notion
|
|
298
301
|
$ flow mcp remove notion --scope project
|
|
299
|
-
$ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{
|
|
302
|
+
$ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{De("cli",{verbose:d.verbose,silent:d.silent});let m=await Fd(c,d);B(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",`
|
|
300
303
|
Examples:
|
|
301
304
|
$ flow auth login
|
|
302
305
|
$ flow auth login --jwt <token>
|
|
303
306
|
$ flow auth login --jwt <token> --starter-kit dev
|
|
304
|
-
$ flow auth login --
|
|
307
|
+
$ flow auth login --jwt <token> --custom-email name@example.com
|
|
308
|
+
$ flow auth login --verbose`).action(async c=>{De("cli",{verbose:c.verbose});let d=await Sl(c);B(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
|
|
305
309
|
Examples:
|
|
306
310
|
$ flow auth logout
|
|
307
|
-
$ flow auth logout --force`).action(async c=>{let d=await
|
|
311
|
+
$ flow auth logout --force`).action(async c=>{let d=await lm(c.force);B(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
|
|
308
312
|
Examples:
|
|
309
|
-
$ flow auth status`).action(async()=>{let c=await
|
|
313
|
+
$ flow auth status`).action(async()=>{let c=await cm();B(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",`
|
|
310
314
|
Examples:
|
|
311
315
|
$ flow skills add vercel-labs/agent-skills
|
|
312
316
|
$ flow skills add owner/repo -g
|
|
313
317
|
$ flow skills add owner/repo --skill pr-review commit
|
|
314
318
|
$ flow skills add ./local/skills -y
|
|
315
|
-
$ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await
|
|
319
|
+
$ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Vm(c,d);B(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
|
|
316
320
|
Examples:
|
|
317
321
|
$ flow skills list
|
|
318
322
|
$ flow skills list -g
|
|
319
|
-
$ flow skills list --json`).action(async c=>{let d=await
|
|
323
|
+
$ flow skills list --json`).action(async c=>{let d=await Hm(c);B(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",`
|
|
320
324
|
Examples:
|
|
321
325
|
$ flow skills remove pr-review
|
|
322
|
-
$ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await
|
|
326
|
+
$ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Gm(c,d);B(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",`
|
|
323
327
|
Examples:
|
|
324
328
|
$ flow bundle install "My React Kit"
|
|
325
329
|
$ flow bundle install "Squad Setup Bundle"
|
|
326
|
-
$ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{
|
|
330
|
+
$ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{De("cli",{verbose:d.verbose});let m=await hm(c);B(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
|
|
327
331
|
Examples:
|
|
328
|
-
$ flow health`).action(async()=>{let c=await
|
|
332
|
+
$ flow health`).action(async()=>{let c=await Sm();B(c);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
|
|
329
333
|
Examples:
|
|
330
334
|
$ flow usage
|
|
331
|
-
$ flow usage --json`).action(async c=>{let d=await
|
|
335
|
+
$ flow usage --json`).action(async c=>{let d=await Pm(c);B(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Tl();B(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
|
|
332
336
|
Examples:
|
|
333
|
-
$ flow modules list`).action(async()=>{let c=await
|
|
337
|
+
$ flow modules list`).action(async()=>{let c=await Tl();B(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
|
|
334
338
|
Examples:
|
|
335
339
|
$ flow modules install metrics
|
|
336
|
-
$ flow modules install dashboard`).action(async c=>{let d=await
|
|
340
|
+
$ flow modules install dashboard`).action(async c=>{let d=await rf(c);B(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",`
|
|
337
341
|
Examples:
|
|
338
342
|
$ flow modules update
|
|
339
|
-
$ flow modules update metrics`).action(async c=>{let d=await
|
|
343
|
+
$ flow modules update metrics`).action(async c=>{let d=await nf(c??null);B(d);}),t.addCommand(u);for(let c of ee)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Qm(c.alias,d);});return t.hook("preAction",()=>{ci();}),t}function qI(){return ge__default.join(Pe__default.homedir(),".claude","settings.json")}function af(){let e=qI();try{if(!he__default.existsSync(e))return !0;let r=JSON.parse(he__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}var rb=x("updateChecker"),nb=promisify(execFile),ob=1440*60*1e3,lf=3e4;function sb(){let e=process.env.FLOW_HOME??ge__default.join(Pe__default.homedir(),".flow");return ge__default.join(e,"update.lock")}async function cf(e){try{let{stdout:t}=await nb(Ft(),["view",e,"version"],{timeout:lf,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function ib(e){let t=new AbortController,r=setTimeout(()=>t.abort(),lf);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 ab(e){return e.versionCheck.type==="npm-registry"?cf(e.versionCheck.package):ib(e.versionCheck.repo)}async function lb(){let e=await cf("@ciandt-flow/cli");return e&&Le(ae,e)?(gi({currentVersion:ae,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function cb(){let e=Br().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=ee.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<ob)return;let s=await ab(r);try{await ct({...t,lastChecked:new Date().toISOString()});}catch(i){rb.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Le(t.installedVersion,s)&&ws(r,"background").catch(()=>{});}));}async function kl(){let e=af();if(e===false)return;let t=sb();he__default.mkdirSync(ge__default.dirname(t),{recursive:true});let r=null;try{r=await Ug.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await lb().catch(()=>null);n&&process.stdout.write(`
|
|
340
344
|
\u26A0 @ciandt-flow/cli v${n} installing in background.
|
|
341
345
|
Restart flow to apply the update.
|
|
342
346
|
|
|
343
|
-
`);}await
|
|
347
|
+
`);}await cb().catch(()=>{});}finally{await r().catch(()=>{});}}var db=x("cli"),Al=of(async()=>{De("tui"),oc("tui"),sc(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();Wn("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();Wn("sigterm",t,r).finally(()=>process.exit(143));}),await kl().catch(()=>{}),await Iu().catch(t=>{db.error(`Failed to init catalog registry: ${String(t)}`);}),await Yp();let{waitUntilExit:e}=render(jsx(Zp,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});Al.hook("preAction",async(e,t)=>{t!==Al&&await kl().catch(()=>{});});Al.parse();
|