@ciandt-flow/cli 2.10.0-beta.40 → 2.10.0-beta.42
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 +162 -148
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as
|
|
3
|
-
`;try{ie.appendFileSync(this.filePath,o,"utf-8");}catch{}}ensureDir(){try{let a=ne.dirname(this.filePath);ie.mkdirSync(a,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(ie.statSync(this.filePath).size>
|
|
4
|
-
`);}formatTui(a){return `[flow:${a.module}] ${a.message}`}formatCli(a){let o=String(a.timestamp.getHours()).padStart(2,"0"),t=String(a.timestamp.getMinutes()).padStart(2,"0"),r=String(a.timestamp.getSeconds()).padStart(2,"0");return `[${o}:${t}:${r}] [${a.level.toUpperCase()}] ${a.message}`}};});var
|
|
5
|
-
`);}};});function
|
|
2
|
+
import*as Pt from'crypto';import {randomUUID,createHash}from'crypto';import*as Ce from'os';import Ce__default,{tmpdir,homedir}from'os';import*as ne from'path';import ne__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as ie from'fs';import ie__default,{readFileSync,mkdirSync,existsSync,writeFileSync,rmSync,appendFileSync,readdirSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import R from'chalk';import*as Bd from'readline';import {createInterface}from'readline';import Jn from'conf';import Yu,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Av,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Bb from'jsonwebtoken';import $b from'proper-lockfile';import kv from'ink-big-text';import _p from'ink-spinner';import*as Wa from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm,mkdtemp,readdir,cp}from'fs/promises';import Ey from'unzipper';import {simpleGit,CheckRepoActions}from'simple-git';import $d from'semver';import an from'yocto-spinner';import {Command,Option}from'commander';import {parse,stringify}from'yaml';var Th=Object.defineProperty;var H=(e,a,o)=>()=>{if(o)throw o[0];try{return e&&(a=e(e=0)),a}catch(t){throw o=[t],t}};var el=(e,a)=>{for(var o in a)Th(e,o,{get:a[o],enumerable:true});};var ho,ue,vn,lr,ht,bo,yn,al,kn,qa,pe,ea,Ya,pi,bt,vt,yt,kt,U=H(()=>{"use strict";ho="FLOW",ue="flow-skills",vn="flow-cli",lr="internal",ht="external",bo={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},bundle:{label:"Bundle",color:"green"},agent:{label:"Agent",color:"green"},hook:{label:"Hook",color:"blue"},rule:{label:"Rule",color:"blue"},plugin:{label:"Plugin",color:"magenta"}},yn=new Set(Object.keys(bo)),al={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},kn=new Set(["internal","external"]),qa={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"}},pe="flow-claude-md-setup",ea=5,Ya=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,pi="https://flow.ciandt.com",bt=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,vt="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",yt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,kt="Must be a valid email address (e.g. name@example.com)";});var mi,qh,ol,ur,Pn=H(()=>{"use strict";mi="aes-256-gcm",qh=16,ol=16,ur=class{key;constructor(a){if(a.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${a.length}`);this.key=a;}encrypt(a){let o=Pt.randomBytes(qh),t=Pt.createCipheriv(mi,this.key,o,{authTagLength:ol}),r=Buffer.concat([t.update(a,"utf8"),t.final()]),i=t.getAuthTag();return {iv:o.toString("hex"),authTag:i.toString("hex"),ciphertext:r.toString("hex"),algorithm:mi}}decrypt(a){if(a.algorithm!==mi)throw new Error(`Unsupported encryption algorithm: ${a.algorithm}`);let o=Pt.createDecipheriv(mi,this.key,Buffer.from(a.iv,"hex"),{authTagLength:ol});return o.setAuthTag(Buffer.from(a.authTag,"hex")),Buffer.concat([o.update(Buffer.from(a.ciphertext,"hex")),o.final()]).toString("utf8")}};});function Dn(e){return e.replace(Nh,"").replace(Gh,"").replace(Bh,"").replace(Lh,"Bearer ***").replace(Fh,"***").replace(Oh,"***").replace(/\r\n|\r|\n/g,"\\n")}var Lh,Fh,Oh,Nh,Gh,Bh,wn=H(()=>{"use strict";Lh=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Fh=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,Oh=/[A-Za-z0-9+/]{40,}={0,2}/g,Nh=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,Gh=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Bh=/\x1b/g;});function fi(e){return e||ue}function tl(e,a,o){return Cn(fi(o),e,a)}function Sn(e,a){return ne.join(Ce.homedir(),ha,"plugins","marketplaces",fi(a),"plugins","native",e)}function hi(e){return ne.join(Ce.homedir(),ha,"plugins","marketplaces",fi(e),".claude-plugin","marketplace.json")}function Ho(){return ne.join(Ce.homedir(),ha,"plugins","known_marketplaces.json")}function rl(e){return ne.join(Ce.homedir(),ha,"plugins","marketplaces",fi(e))}function il(){return ne.join(Ce.homedir(),gi,"cache","install.lock")}function sl(){return ne.join(Ce.homedir(),gi,"logs","flowsetup.log")}function Cn(e,a,o){return ne.join(Ce.homedir(),ha,"plugins","cache",e,a,o)}function Vo(e){let a=e==="global"?Ce.homedir():process.cwd();return ne.join(a,".claude","skills")}function pr(e){let a=e==="global"?Ce.homedir():process.cwd();return ne.join(a,".claude","skills-lock.json")}function bi(e="user"){return e==="project"?ne.join(process.cwd(),".opencode","plugins"):ne.join(Ce.homedir(),".config","opencode","plugins")}function nl(){return ne.join(Ce.homedir(),gi,"flow-catalogs.json")}function dl(){let e=process.env.FLOW_HOME??ne.join(Ce.homedir(),gi);return ne.join(e,"config.json")}function vi(e="user"){return e==="project"||e==="local"?ne.join(process.cwd(),ha,"agents"):ne.join(Ce.homedir(),ha,"agents")}function Dt(e="user"){return e==="project"||e==="local"?ne.join(process.cwd(),ha,"rules"):ne.join(Ce.homedir(),ha,"rules")}function Rn(e="user"){return e==="project"||e==="local"?ne.join(process.cwd(),ha,"hooks"):ne.join(Ce.homedir(),ha,"hooks")}var ha,gi,Oe=H(()=>{"use strict";U();ha=".claude",gi=".flow";});var jh,Uh,yi,cl=H(()=>{"use strict";Oe();jh=5*1024*1024,Uh=3,yi=class{filePath;constructor(){this.filePath=sl(),this.ensureDir(),this.rotateIfNeeded();}write(a){let o=`[${a.timestamp.toISOString()}] [${a.level.toUpperCase()}] [${a.module}] ${a.message}
|
|
3
|
+
`;try{ie.appendFileSync(this.filePath,o,"utf-8");}catch{}}ensureDir(){try{let a=ne.dirname(this.filePath);ie.mkdirSync(a,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(ie.statSync(this.filePath).size>jh){let o=new Date().toISOString().replace(/[:.]/g,"-"),t=this.filePath.replace(".log",`-${o}.log`);ie.renameSync(this.filePath,t),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let a=ne.dirname(this.filePath),o=ne.basename(this.filePath,".log"),t=ie.readdirSync(a).filter(r=>r.startsWith(o+"-")&&r.endsWith(".log")).sort().reverse();for(let r of t.slice(Uh))ie.unlinkSync(ne.join(a,r));}catch{}}};});var ki,ll=H(()=>{"use strict";ki=class{context;constructor(a){this.context=a;}write(a){let o=this.context==="tui"?this.formatTui(a):this.formatCli(a);process.stderr.write(o+`
|
|
4
|
+
`);}formatTui(a){return `[flow:${a.module}] ${a.message}`}formatCli(a){let o=String(a.timestamp.getHours()).padStart(2,"0"),t=String(a.timestamp.getMinutes()).padStart(2,"0"),r=String(a.timestamp.getSeconds()).padStart(2,"0");return `[${o}:${t}:${r}] [${a.level.toUpperCase()}] ${a.message}`}};});var Pi,ul=H(()=>{"use strict";Pi=class{write(a){process.stdout.write(a.message+`
|
|
5
|
+
`);}};});function xn(){return Di}function pl(e){return An.add(e),()=>{An.delete(e);}}var Di,An,wi,En=H(()=>{"use strict";Di=[],An=new Set;wi=class{write(a){Di.push(a),Di.length>100&&Di.shift();for(let o of An)o();}};});function zh(){let e=process.env.DEBUG;if(!e)return null;let a=e.split(",").map(t=>t.trim()).filter(Boolean);for(let t of a)if(t==="flow:*")return "all";let o=new Set;for(let t of a)t.startsWith("flow:")&&o.add(t.slice(5));return o.size>0?o:null}function Ve(e,a){if(e==="tui"){let o=zh();_o={context:e,transports:[new wi,new yi],minLevel:o?"debug":"warn",debugModules:o};}else a?.silent?_o={context:e,transports:[],minLevel:"error",debugModules:null}:a?.verbose?_o={context:e,transports:[new ki("cli")],minLevel:"debug",debugModules:null}:_o={context:e,transports:[new Pi],minLevel:"info",debugModules:null};}function ml(){return _o.transports}function gl(e,a){let{debugModules:o,minLevel:t}=_o;return _o.context==="tui"&&o&&o!=="all"?o.has(a)?wt[e]>=wt.debug:wt[e]>=wt.warn:wt[e]>=wt[t]}var wt,_o,In=H(()=>{"use strict";cl();ll();ul();En();wt={debug:0,info:1,warn:2,error:3},_o={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function Si(e,a,o){if(!gl(e,a))return;let t={level:e,module:a,message:Dn(o),timestamp:new Date};for(let r of ml())r.write(t);}function k(e){let a=fl.get(e);if(a)return a;let o={debug:t=>Si("debug",e,t),info:t=>Si("info",e,t),warn:t=>Si("warn",e,t),error:t=>Si("error",e,t)};return fl.set(e,o),o}var fl,hl=H(()=>{"use strict";wn();In();fl=new Map;});var I=H(()=>{"use strict";hl();In();wn();});function Wh(e){return typeof e=="object"&&e!==null&&Mn in e&&e[Mn]===true}function qn(e){return {serialize(a){let o=JSON.stringify(a),t=e.encrypt(o),r={[Mn]:true,envelope:t};return JSON.stringify(r,null," ")},deserialize(a){let o;try{o=JSON.parse(a);}catch{return Tn.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(Wh(o))try{let t=e.decrypt(o.envelope);return JSON.parse(t)}catch(t){return Tn.error(`[encryption] Decryption failed: ${t instanceof Error?t.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Tn.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),o}}}var Tn,Mn,Ln=H(()=>{"use strict";I();Tn=k("encryption"),Mn="__encrypted__";});var Fn,Vh,ba,St,On=H(()=>{"use strict";I();Fn=promisify(execFile),Vh=promisify(exec),ba=k("encryption:macos-keyvault"),St=class{static async isAvailable(){try{let{stdout:a}=await Vh("command -v security");return ba.debug(`security binary found at: ${a.trim()}`),!0}catch{return ba.debug("security binary not found in PATH"),!1}}async getSecret(a,o){try{ba.debug(`Looking up secret: service=${a}, account=${o}`);let{stdout:t}=await Fn("security",["find-generic-password","-w","-a",o,"-s",a]),r=t.trim();return ba.debug(`security find-generic-password result: ${r?"found":"empty"}`),r||null}catch(t){let r=t;return ba.debug(`security find-generic-password failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),null}}async setSecret(a,o,t){try{ba.debug(`Storing secret: service=${a}, account=${o}`),await Fn("security",["add-generic-password","-U","-a",o,"-s",a,"-w",t]),ba.debug("security add-generic-password succeeded");}catch(r){let i=r;throw ba.error(`security add-generic-password failed: code=${i.code}, stderr=${i.stderr?.trim()}, message=${i.message}`),r}}async deleteSecret(a,o){try{return ba.debug(`Deleting secret: service=${a}, account=${o}`),await Fn("security",["delete-generic-password","-a",o,"-s",a]),ba.debug("security delete-generic-password succeeded"),!0}catch(t){let r=t;return ba.debug(`security delete-generic-password failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function v(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 $(e){process.stdout.write(R.green(` \u2713 ${v(e)}
|
|
6
6
|
`));}function S(e){process.stderr.write(R.red(` \u2717 ${v(e)}
|
|
7
7
|
`));}function P(e){process.stdout.write(R.cyan(` \u2139 ${v(e)}
|
|
8
|
-
`));}function
|
|
8
|
+
`));}function vo(e,a){let o=a.map(n=>n.map(v)),t=[e,...o],r=e.map((n,d)=>Math.max(...t.map(l=>(l[d]??"").length))),i=r.map(n=>"\u2500".repeat(n)).join(" "),s=n=>n.map((d,l)=>d.padEnd(r[l])).join(" ");process.stdout.write(`
|
|
9
9
|
`),process.stdout.write(` ${R.bold(s(e))}
|
|
10
10
|
`),process.stdout.write(` ${R.dim(i)}
|
|
11
11
|
`);for(let n of o)process.stdout.write(` ${s(n)}
|
|
12
12
|
`);process.stdout.write(`
|
|
13
|
-
`);}function
|
|
14
|
-
`);}function
|
|
13
|
+
`);}function yo(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
14
|
+
`);}function me(e){process.stdout.write(JSON.stringify(e)+`
|
|
15
15
|
`);}function Ne(e){process.stderr.write(JSON.stringify(e)+`
|
|
16
|
-
`);}function
|
|
17
|
-
${
|
|
16
|
+
`);}function Y(e){return e instanceof Error?e.message:String(e)}function La(e){let a=new Date(e);return isNaN(a.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(a)}var B=H(()=>{"use strict";});async function $h(e,a){let o=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],t=0,r=setInterval(()=>{process.stderr.write(`\r${o[t++%o.length]} ${e}`);},80);try{return await a()}finally{clearInterval(r),process.stderr.write("\r\x1B[2K");}}function Yh(e){let a=Bd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(v(e),t=>{a.close(),o(t.trim().toLowerCase());});})}var Nn,Gn,Kh,te,ko,Bn=H(()=>{"use strict";I();B();Nn=promisify(execFile),Gn=promisify(exec),Kh=[{name:"apt",command:"sudo apt install -y libsecret-tools"},{name:"dnf",command:"sudo dnf install -y libsecret"},{name:"pacman",command:"sudo pacman -S --noconfirm libsecret"},{name:"apk",command:"sudo apk add libsecret-tools"},{name:"zypper",command:"sudo zypper install -y libsecret-tools"}],te=k("encryption:linux-keyvault");ko=class e{static async isAvailable(){try{let{stdout:a}=await Gn("command -v secret-tool");te.debug(`secret-tool found at: ${a.trim()}`);}catch{return te.debug("secret-tool binary not found in PATH"),!1}try{return await Nn("secret-tool",["lookup","service","__flow_connectivity_check__"]),te.debug("Secret Service D-Bus connectivity check passed"),!0}catch(a){let t=a.stderr?.trim()??"";return t.includes("org.freedesktop.secrets")?(te.debug(`Secret Service D-Bus not available: ${t}`),!1):(te.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let a of Kh)try{return await Gn(`command -v ${a.name}`),a}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;te.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let a=await e.detectPackageManager();if(!a)return te.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let o=await Yh(" ? Install secret-tool? This requires sudo. (y/N) ");if(o!=="y"&&o!=="yes")return !1;try{return te.info(`Running: ${a.command}`),await $h("Installing secret-tool...",()=>Gn(a.command)),e.isAvailable()}catch{return te.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(a,o){try{te.debug(`Looking up secret: service=${a}, account=${o}`);let{stdout:t}=await Nn("secret-tool",["lookup","service",a,"account",o]),r=t.trim();return te.debug(`secret-tool lookup result: ${r?"found":"empty"}`),r||null}catch(t){let r=t;return te.debug(`secret-tool lookup failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),null}}async setSecret(a,o,t){te.debug(`Storing secret: service=${a}, account=${o}`),te.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),te.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),te.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((r,i)=>{let s=spawn("secret-tool",["store","--label",a,"service",a,"account",o]),n="";s.stderr.on("data",d=>{n+=d.toString();}),s.stdin.end(t,"utf8"),s.on("close",d=>{d===0?(te.debug("secret-tool store succeeded"),r()):(te.error(`secret-tool store failed: code=${d}, stderr=${n.trim()}`),i(new Error(`secret-tool exited with code ${d}${n?`: ${n.trim()}`:""}`)));}),s.on("error",d=>{te.error(`secret-tool store spawn error: ${d.message}`),i(d);});});}async deleteSecret(a,o){try{return te.debug(`Deleting secret: service=${a}, account=${o}`),await Nn("secret-tool",["clear","service",a,"account",o]),te.debug("secret-tool clear succeeded"),!0}catch(t){let r=t;return te.debug(`secret-tool clear failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function Un(e,a){return `${e}:${a}`}function gr(e){return e.replace(/'/g,"''")}function Ci(e){return ["-NoProfile","-NonInteractive","-Command",e]}function ib(e){return `Add-Type -TypeDefinition @'
|
|
17
|
+
${zn}
|
|
18
18
|
'@
|
|
19
|
-
[FlowCredManager]::Read('${
|
|
20
|
-
${
|
|
19
|
+
[FlowCredManager]::Read('${gr(e)}')`}function sb(e,a,o){return `Add-Type -TypeDefinition @'
|
|
20
|
+
${zn}
|
|
21
21
|
'@
|
|
22
|
-
[FlowCredManager]::Write('${
|
|
23
|
-
${
|
|
22
|
+
[FlowCredManager]::Write('${gr(e)}', '${gr(a)}', '${gr(o)}')`}function nb(e){return `Add-Type -TypeDefinition @'
|
|
23
|
+
${zn}
|
|
24
24
|
'@
|
|
25
|
-
[FlowCredManager]::Delete('${
|
|
25
|
+
[FlowCredManager]::Delete('${gr(e)}')`}async function Ri(e){return ab("powershell.exe",e)}var ab,va,jn,ob,tb,rb,zn,Ct,Wn=H(()=>{"use strict";I();ab=promisify(execFile),va=k("encryption:windows-keyvault"),jn=1,ob=1,tb=2,rb=3;zn=`
|
|
26
26
|
using System;
|
|
27
27
|
using System.Runtime.InteropServices;
|
|
28
28
|
using System.Text;
|
|
@@ -58,7 +58,7 @@ public class FlowCredManager {
|
|
|
58
58
|
|
|
59
59
|
public static string Read(string target) {
|
|
60
60
|
IntPtr credPtr;
|
|
61
|
-
if (!CredRead(target, ${
|
|
61
|
+
if (!CredRead(target, ${jn}, 0, out credPtr)) return "";
|
|
62
62
|
try {
|
|
63
63
|
var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
|
|
64
64
|
if (cred.CredentialBlobSize <= 0) return "";
|
|
@@ -72,7 +72,7 @@ public class FlowCredManager {
|
|
|
72
72
|
byte[] bytes = Encoding.UTF8.GetBytes(secret);
|
|
73
73
|
IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
|
|
74
74
|
IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
|
|
75
|
-
int[] persistLevels = new int[] { ${
|
|
75
|
+
int[] persistLevels = new int[] { ${tb}, ${rb}, ${ob} };
|
|
76
76
|
int lastErr = 0;
|
|
77
77
|
try {
|
|
78
78
|
foreach (int persist in persistLevels) {
|
|
@@ -80,7 +80,7 @@ public class FlowCredManager {
|
|
|
80
80
|
try {
|
|
81
81
|
Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
|
|
82
82
|
var cred = new CREDENTIAL();
|
|
83
|
-
cred.Type = ${
|
|
83
|
+
cred.Type = ${jn};
|
|
84
84
|
cred.TargetName = targetPtr;
|
|
85
85
|
cred.CredentialBlobSize = bytes.Length;
|
|
86
86
|
cred.CredentialBlob = blobPtr;
|
|
@@ -98,57 +98,57 @@ public class FlowCredManager {
|
|
|
98
98
|
}
|
|
99
99
|
|
|
100
100
|
public static bool Delete(string target) {
|
|
101
|
-
return CredDelete(target, ${
|
|
101
|
+
return CredDelete(target, ${jn}, 0);
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
|
-
`;Ct=class{static async isAvailable(){try{let{stdout:a}=await
|
|
105
|
-
`)[0]:"unknown error";return va.debug(`PowerShell not available: ${o}`),!1}}async getSecret(a,o){try{let t=
|
|
106
|
-
`)[0]:"unknown error";return va.error(`Failed to read secret from Windows Credential Manager [service="${a}", account="${o}"]: ${r}`),null}}async setSecret(a,o,t){try{let r=
|
|
107
|
-
`)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${a}", account="${o}"]: ${i}`;throw va.error(s),new Error(s)}}async deleteSecret(a,o){try{let t=
|
|
108
|
-
`)[0]:"unknown error";return va.debug(`Failed to delete secret from Windows Credential Manager [service="${a}", account="${o}"]: ${r}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function
|
|
104
|
+
`;Ct=class{static async isAvailable(){try{let{stdout:a}=await Ri(Ci('Write-Output "ok"')),o=a.trim()==="ok";return va.debug(`PowerShell availability check: ${o?"available":"unexpected output"}`),o}catch(a){let o=a instanceof Error?a.message.split(`
|
|
105
|
+
`)[0]:"unknown error";return va.debug(`PowerShell not available: ${o}`),!1}}async getSecret(a,o){try{let t=Un(a,o);va.debug(`Looking up secret: target=${t}`);let r=ib(t),{stdout:i}=await Ri(Ci(r)),s=i.trim();return va.debug(`CredRead result: ${s?"found":"empty"}`),s||null}catch(t){let r=t instanceof Error?t.message.split(`
|
|
106
|
+
`)[0]:"unknown error";return va.error(`Failed to read secret from Windows Credential Manager [service="${a}", account="${o}"]: ${r}`),null}}async setSecret(a,o,t){try{let r=Un(a,o);va.debug(`Storing secret: target=${r}`);let i=sb(r,t,o),{stdout:s}=await Ri(Ci(i)),n=s.trim();if(n.startsWith("OK:")){let l=n.split(":")[1];va.debug(`CredWrite succeeded (persist=${l})`);return}let d=n.startsWith("ERR:")?n.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${d}`)}catch(r){let i=r instanceof Error?r.message.split(`
|
|
107
|
+
`)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${a}", account="${o}"]: ${i}`;throw va.error(s),new Error(s)}}async deleteSecret(a,o){try{let t=Un(a,o);va.debug(`Deleting secret: target=${t}`);let r=nb(t),{stdout:i}=await Ri(Ci(r)),s=i.trim()==="True";return va.debug(`CredDelete result: ${s}`),s}catch(t){let r=t instanceof Error?t.message.split(`
|
|
108
|
+
`)[0]:"unknown error";return va.debug(`Failed to delete secret from Windows Credential Manager [service="${a}", account="${o}"]: ${r}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function ub(){let e=`${Ce.hostname()}${Ce.userInfo().username}`;return Pt.scryptSync(e,cb,db)}function pb(){let e=ub(),a=new ur(e),o=qn(a);return new Jn({projectName:Hn,serialize:o.serialize,deserialize:o.deserialize,configFileMode:384})}function Ai(){return xi||(xi=pb()),xi}var db,cb,Hn,lb,xi,Qe,fr=H(()=>{"use strict";Pn();Ln();db=32,cb="flow-plugins-cli-fallback",Hn="flow-plugins-cli-fallback",lb={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)"};xi=null;Qe=class{warned=!1;async getSecret(a,o){return Ai().get(`${a}:${o}`)??null}async setSecret(a,o,t){if(!this.warned){let r=lb[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
|
|
109
109
|
using a machine-derived key. For stronger security, ${r}.
|
|
110
|
-
`),this.warned=!0;}Di().set(`${a}:${o}`,t);}async deleteSecret(a,o){let t=Di(),r=`${a}:${o}`;return t.has(r)?(t.delete(r),!0):!1}getStoragePath(){return Di().path}static hasExistingData(){try{let a=new Gn({projectName:Bn});return ie.existsSync(a.path)}catch{return !1}}static clearFallbackFile(){try{let a=new Gn({projectName:Bn});ie.rmSync(a.path,{force:!0});}catch{}wi=null;}};});async function jn(){if(Qe.hasExistingData())return new Qe;switch(process.platform){case "darwin":return await wt.isAvailable()?new wt:new Qe;case "linux":return await vo.isAvailable()?new vo:await vo.ensureInstalled()?new vo:new Qe;case "win32":return await Ct.isAvailable()?new Ct:new Qe;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var hl=H(()=>{"use strict";In();qn();Nn();mr();});var bl=H(()=>{"use strict";fn();xn();hl();In();qn();Nn();mr();});async function yo(){return Ri||(Ri=jn()),Ri}function Ai(){Ri=null;}async function Y(){let a=await(await yo()).getSecret(Ya,Un);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function ko(e){let{clientId:a,clientSecret:o,tenant:t}=e,r=[!a?.trim()&&"clientId",!o?.trim()&&"clientSecret",!t?.trim()&&"tenant"].filter(Boolean);if(r.length>0)throw vl.error(`missing or empty fields: ${r.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await yo()).setSecret(Ya,Un,JSON.stringify(e));}async function yl(){let e=await yo();await e.deleteSecret(Ya,Un),await e.deleteSecret(Ya,zn),await e.deleteSecret(Ya,Wn);}async function kl(){return (await yo()).getStoragePath()}async function Pl(e){await(await yo()).setSecret(Ya,zn,JSON.stringify(e));}async function xi(){let a=await(await yo()).getSecret(Ya,zn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function Ei(e){await(await yo()).setSecret(Ya,Wn,JSON.stringify(e));}async function Rt(){let a=await(await yo()).getSecret(Ya,Wn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function Po(){let e=await xi();return e?new Date(e.expiresAt)>new Date:false}function La(e){let a=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${a}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${a}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${a}/metrics-collector-api/`,vl.debug(`[customUrl] Service URLs overridden to base: ${a}`);}var vl,Ya,Un,zn,Wn,Ri,Re=H(()=>{"use strict";bl();I();vl=k("config:credentials"),Ya="flow-plugins-cli",Un="credentials",zn="token-cache",Wn="user-info",Ri=null;});function At(e){let a=e.split(".");if(a.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${a.length}`);let o=a[1].replace(/-/g,"+").replace(/_/g,"/"),t=Buffer.from(o,"base64").toString("utf8");try{return JSON.parse(t)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Ii=H(()=>{"use strict";});function rb(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let o=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!o)return null;let t=parseInt(o[1],16),r=parseInt(o[2],16);return `${t>>8&255}.${t&255}.${r>>8&255}.${r&255}`}function Jn(e){if(Dl.some(o=>o.test(e)))return true;let a=rb(e);return !!(a&&Dl.some(o=>o.test(a)))}function ib(e,a){let o=process.env[e]??a;if(!o)throw new Error(`Missing required environment variable: ${e}`);return o}function Fa(e,a){let o=ib(e,a),t;try{t=new URL(o);}catch{throw new Error(`${e} must be a valid URL. Got: "${o}"`)}let r=process.env.NODE_ENV==="development";if(!r&&t.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${t.protocol}"`);if(t.username||t.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(t.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(t.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(t.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${t.hostname}"`);if(!r&&Jn(t.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${t.hostname}"`);return o}var Dl,_o=H(()=>{"use strict";Dl=[/^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 db(e){if(!$a.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function cb(e){if(e instanceof HTTPError){let a=e.response.status;Hn.debug(`HTTP error during authentication [status=${a}]`);let o="";try{let t=await e.response.text(),r=JSON.parse(t);typeof r.error=="string"&&(o=r.error);}catch{}return o&&wl[o]?new Error(wl[o]):a===StatusCodes.UNAUTHORIZED||a===StatusCodes.FORBIDDEN||a===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):a>=StatusCodes.BAD_REQUEST&&a<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Hn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Hn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Xo(e){let a=Fa("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");db(e.tenant);let o;try{o=await Qu.post(a,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await cb(i)}let t=o.expires_at??new Date(Date.now()+(o.expires_in??3600)*1e3).toISOString();await ko(e),await Pl({accessToken:o.access_token,expiresAt:t});let r=At(o.access_token);await Ei({sub:r.sub,name:r.name,email:r.email});}var Hn,wl,Ti=H(()=>{"use strict";Re();Ii();_o();I();U();Hn=k("api:auth");wl={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 Oa(){if(await Po()){let t=await xi();if(t)return t.accessToken}Sl.debug("Token expired or missing, re-authenticating...");let a=await Y();if(!a)throw new Error("Not authenticated. Run: flow auth login");Qe.clearFallbackFile(),Ai(),await Xo(a);let o=await xi();if(!o)throw new Error("Authentication succeeded but token was not persisted");return Sl.debug("Token refreshed successfully"),o.accessToken}var Sl,xt=H(()=>{"use strict";Re();Ti();mr();I();Sl=k("lib:tokenProvider");});function Ua(){return Qu.create({prefix:Fa("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let a=await Oa();e.headers.set("Authorization",`Bearer ${a}`);let o=await Y();o?.tenant&&$a.test(o.tenant)&&e.headers.set("FlowTenant",o.tenant);}]}})}var xr=H(()=>{"use strict";_o();Re();xt();U();});function Bu(e){if(!(e.source===void 0&&e.timeoutMs===void 0))return {...e.source!==void 0&&{searchParams:{source:e.source}},...e.timeoutMs!==void 0&&{timeout:e.timeoutMs}}}function Ot(e,a,o){let t=Ua(),r=Bu({source:a,timeoutMs:o});return r?t.get(e,r):t.get(e)}function ju(e,a={}){let o=Ua(),t=Bu(a);return t?o.head(e,t):o.head(e)}async function Nt(e){if(!(e instanceof HTTPError))return null;try{let a=await e.response.clone().json(),{message:o}=a;return Array.isArray(o)?o.filter(Boolean).join("; ")||null:typeof o=="string"&&o?o:null}catch{return null}}var gd=H(()=>{"use strict";xr();});function Er(e){if(!e||!iy.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Gt(e){return sy.test(e)}function Bt(e){let a=e.indexOf("@");return a>0?e.slice(0,a):e}function hd(e){if(!ny.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 jt(e,a){let o=Bt(e);hd(o);let t=["claude","plugin","install",o];return a&&t.push("--scope",a),t.join(" ")}function ss(e){let a=e.trim();if(!a)throw new Error("No marketplace source provided.");if(!dy.test(a)&&!cy.test(a))throw new Error(`Invalid marketplace source: "${a}". Must be owner/repo or an https:// URL.`);return a}var iy,sy,ny,dy,cy,To=H(()=>{"use strict";iy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;sy=/^[^@]+@[^@]+$/;ny=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;dy=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,cy=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Wu={};Xc(Wu,{FlowApiAdapter:()=>Ut});var ly,Ut,bd=H(()=>{"use strict";xr();gd();I();To();ly=k("catalog.flow-api"),Ut=class{id;name;source;removable=!1;contentSource;constructor(a){this.contentSource=a,this.id=a?`flow-api:${a}`:"flow-api",this.name=a?`Flow Marketplace (${a})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:a}=await Ot("v1/plugins/catalog",this.contentSource).json();return a.map(o=>({...o,catalogId:this.id,origin:o.origin??"internal",type:o.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(a){let o=await Nt(a);if(o)throw new Error(o);if(a instanceof HTTPError){let{status:t}=a.response;throw t===401||t===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${t}`)}throw a instanceof Error?a.name==="TimeoutError"||a.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${a.message}`):a}}async fetchManifest(a){Er(a);try{return await Ot(`v1/plugins/${a}/manifest`,this.contentSource).json()}catch(o){let t=await Nt(o);if(t)throw new Error(t);if(o instanceof HTTPError){let{status:r}=o.response;throw r===404?new Error(`Plugin '${a}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${r}`)}throw o instanceof Error?new Error(`Failed to fetch manifest: ${o.message}`):o}}async ping(){try{return await Ua().head("v1/plugins/catalog"),ly.debug("ping ok"),!0}catch{return !1}}};});function py(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:a})=>a.trim()||void 0).catch(()=>{})}function Hu(){return Ju??=py(),Ju}var Ju,Vu=H(()=>{"use strict";});var Xu={};Xc(Xu,{GitRepoAdapter:()=>zt});function _u(e,a){if(!my.test(e))throw new Error(`Invalid ${a} in catalog source URL: "${e}"`)}var my,zt,vd=H(()=>{"use strict";Vu();_o();my=/^[a-zA-Z0-9_.-]+$/;zt=class{id;name;source;constructor(a,o,t){this.id=a,this.name=o,this.source=t;}buildRawUrl(a,o="marketplace.json"){let t=new URL(this.source),{hostname:r,pathname:i}=t;if(Jn(r))throw new Error(`Catalog source URL points to a private/loopback address: "${r}"`);let s=i.replace(/^\//,"").split("/"),[n,d]=s;return _u(n,"owner"),_u(d,"repo"),r==="github.com"?`https://raw.githubusercontent.com/${n}/${d}/${a}/${o}`:r==="bitbucket.org"?`https://bitbucket.org/${n}/${d}/raw/${a}/${o}`:r==="gitlab.com"||r.startsWith("git.")?`https://${r}/${n}/${d}/-/raw/${a}/${o}`:`https://${r}/${n}/${d}/raw/${a}/${o}`}async fetchItems(){return this._fetchFromBranch("main").catch(a=>{if(this._is404(a))return this._fetchFromBranch("master");throw a})}async _fetchFromBranch(a){let o=await this._buildHeaders();try{let i=this.buildRawUrl(a,".claude-plugin/marketplace.json"),{plugins:s}=await Qu.get(i,{headers:o}).json();return s.map(n=>({...n,catalogId:this.id,origin:n.origin??"external"}))}catch(i){if(this._is401or403(i))throw this._authError();if(!this._is404(i))throw i}let t=this.buildRawUrl(a),{plugins:r}=await Qu.get(t,{headers:o}).json();return r.map(i=>({...i,catalogId:this.id,origin:i.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let o=await Hu();return o?{Authorization:`token ${o}`}:{}}_is404(a){return a!==null&&typeof a=="object"&&"response"in a&&a.response?.status===404}_is401or403(a){return a!==null&&typeof a=="object"&&"response"in a&&[401,403].includes(a.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(a){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});U();var y=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(mn),origins:new Set(gn)},setScreen:a=>e({screen:a}),setActiveTab:a=>e({activeTab:a}),setFocus:a=>e({focus:a}),setSelectedIndex:a=>e({selectedIndex:a}),setActionMenuOpen:a=>e({actionMenuOpen:a}),showNotification:(a,o)=>e({notification:{message:a,type:o}}),clearNotification:()=>e({notification:null}),setLoading:(a,o="")=>e({loading:a,loadingMessage:a?o:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(a,o)=>e({downloadProgress:a,downloadTotal:o}),setCatalogError:a=>e({catalogError:a}),setPendingExit:a=>e({pendingExit:a}),toggleTypeFilter:a=>e(o=>{let{types:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,types:new Set([a])},selectedIndex:0}}),selectAllTypes:()=>e(a=>({catalogFilters:{...a.catalogFilters,types:new Set(mn)},selectedIndex:0})),toggleOriginFilter:a=>e(o=>{let{origins:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,origins:new Set([a])},selectedIndex:0}}),selectAllOrigins:()=>e(a=>({catalogFilters:{...a.catalogFilters,origins:new Set(gn)},selectedIndex:0})),setDebugPanelOpen:a=>e({debugPanelOpen:a}),incrementCatalogVersion:()=>e(a=>({catalogVersion:a.catalogVersion+1})),setBundleInstallFlow:a=>e({bundleInstallFlow:a})}));Re();xt();Ii();U();_o();I();var Mi=k("api:metrics");function Cl(){return Fa("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Rl(e,a,o){return Qu.post(e,{json:a,headers:o})}async function ub(e){let a=await Rt();if(a)return a;let o=At(e),t={sub:o.sub,name:o.name,email:o.email};return await Ei(t),t}async function C(e,a){let o=await Oa(),t=await ub(o),r=await Y();if(!$a.test(r.tenant))throw new Error(`Invalid tenant value: "${r.tenant}"`);let i={action:e,booster:pn,metadata:{...a},success:true,tenant:r.tenant,timestamp:new Date().toISOString(),user:{id:t.sub,name:t.name,email:t.email}};try{await Rl(Cl(),i,{Authorization:`Bearer ${o}`,FlowTenant:r.tenant}),Mi.debug(`Metrics event sent: ${e}`);}catch(s){throw Mi.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function Al(e,a,o){try{let t=o&&$a.test(o)?o:"unknown",r={action:e,booster:pn,metadata:a,success:!0,tenant:t,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Rl(Cl(),r,{FlowTenant:t}),Mi.debug(`Anonymous metrics event sent: ${e}`);}catch(t){Mi.warn(`Failed to send anonymous metrics event "${e}": ${String(t)}`);}}var w={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var pb={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ya={...pb};function xl(e){let a=Date.now();ya={sessionStart:a,stepStart:a,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Ko(e){ya.currentStep=e,ya.stepStart=Date.now();}function Z(){return {...ya}}function Do(){return ya.sessionStart===0?0:Date.now()-ya.sessionStart}function $o(){return ya.stepStart===0?0:Date.now()-ya.stepStart}function El(){ya.tuiSessionStart=Date.now();}function Il(){return ya.tuiSessionStart===0?0:Date.now()-ya.tuiSessionStart}I();var mb=3e3,gb=k("abandonment");async function qi(e){let{currentStep:a,sessionStart:o}=Z();if(o===0)return;let t={last_step:a,trigger:e,duration_ms:Do()};try{await Promise.race([C(w.CLI_ONBOARDING_ABANDONED,t),new Promise((r,i)=>setTimeout(()=>i(new Error("abandonment timeout")),mb))]);}catch(r){gb.warn(`Abandonment event failed: ${String(r)}`);}}function Tl(e,a){return Promise.race([e,new Promise(o=>setTimeout(o,a))])}I();var fb=3e3,hb=k("session-end");async function fr(e,a,o){let t=Il(),i=[C(w.CLI_TUI_SESSION_ENDED,{duration_ms:t,active_tab:a,interface:"tui"})];o!=="main"&&i.push(qi(e));try{await Tl(Promise.all(i).then(()=>{}),fb);}catch(s){hb.warn(`Session end event failed: ${String(s)}`);}}var kb=2e3;function ql(){let{exit:e}=useApp(),a=useRef(false),o=useRef(null),t=y(d=>d.pendingExit),r=y(d=>d.setPendingExit),i=y(d=>d.activeTab),s=y(d=>d.screen),n=useCallback(()=>{if(a.current){o.current&&clearTimeout(o.current),fr("double-ctrl-c",i,s).finally(()=>e());return}a.current=true,r(true),o.current=setTimeout(()=>{a.current=false,r(false);},kb);},[e,r,i,s]);return useInput((d,l)=>{l.ctrl&&d==="c"&&n();}),{pendingExit:t}}var Sb=16;function Ll({label:e,value:a,onChange:o,masked:t=false,isActive:r,error:i}){let s=useRef(a);useEffect(()=>{s.current=a;},[a]),useInput((d,l)=>{if(l.backspace){let c=s.current.slice(0,-1);s.current=c,o(c);}else if(d&&!l.ctrl&&!l.meta&&!l.escape&&!l.return&&!l.tab&&!l.upArrow&&!l.downArrow&&!l.leftArrow&&!l.rightArrow){let c=s.current+d;s.current=c,o(c);}},{isActive:r});let n=t?"\u2022".repeat(a.length):a;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u25B8 ":" "}),jsx(Text,{color:r?"white":"gray",bold:r,children:e.padEnd(Sb)}),jsx(Text,{color:r?"cyan":"gray",children:n}),r&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}U();function Fl({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="n"||d==="N"){o("input");return}(d==="y"||d==="Y"||l.return)&&e(null);return}if(l.escape){n.current="",r(""),s(false),o("confirm");return}if(l.return){let c=n.current.trim();vt.test(c)?(s(false),e(c)):s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[a==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:yt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}U();function Ol({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[fo," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}U();function Nl(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[fo," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var oa=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:a=>e({credentials:a,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:a=>e({justAuthenticated:a})}));Ti();U();function et(){return ne__default.join(Ce__default.homedir(),".claude","settings.json")}function Bl(e){return `${(e&&e.trim().length>0?e.trim():ni).replace(/\/+$/,"")}/flow-litellm/`}function Dr(){let e=et();if(!ie__default.existsSync(e))return {status:"missing"};let a=ie__default.readFileSync(e,"utf-8"),o=a.charCodeAt(0)===65279?a.slice(1):a;try{let t=JSON.parse(o);return t===null||typeof t!="object"||Array.isArray(t)?{status:"malformed",raw:a}:{status:"ok",settings:t}}catch{return {status:"malformed",raw:a}}}function Fi(e){let a=et();ie__default.mkdirSync(ne__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`;ie__default.writeFileSync(o,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,a);}function jl(e,a,o){let t=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...t,ANTHROPIC_AUTH_TOKEN:a,ANTHROPIC_BASE_URL:o}}}function Yn(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_AUTH_TOKEN;return typeof o=="string"&&o.length>0?o:null}function Ul(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.length>0?o:null}var Tb=3600,at=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function wr(e){let a=e.split(".");if(a.length!==3)throw new Error("Malformed JWT: invalid format");let o;try{o=JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Malformed JWT: payload must be a JSON object");let t=o;if(typeof t.clientId!="string"||!t.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(t.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof t.clientSecret!="string"||!t.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(t.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof t.tenant!="string"||!t.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(t.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant}}function Mb(e){return Ib.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Tb})}function Oi(e,a={}){let o=Dr();if(o.status==="malformed"&&!a.allowOverwriteMalformed)throw new at;let t=o.status==="ok"?o.settings:{},r=o.status==="ok"?Yn(o.settings):null,i=o.status==="ok"?Ul(o.settings):null,s=a.jwtOverride??Mb(e),n=Bl(e.customUrl),d=jl(t,s,n);return {jwt:s,anthropicBaseUrl:n,merged:d,previousToken:r,previousBaseUrl:i,hadExistingFile:o.status!=="missing"}}function Ni(e){Fi(e.merged);}function zl(){let e=Dr();return e.status!=="ok"?false:Yn(e.settings)!==null}Re();Oe();function qb(){let e=tl();if(!ie__default.existsSync(e))return {};try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return {}}}var Zn=null;function Lb(){return Zn===null&&(Zn=qb()),Zn}function Co(){return !!Lb().ENABLE_EXPERIMENTAL_BETAS}U();function Gb(){return de.filter(e=>e.platforms[process.platform]?.status==="supported")}function Jl(e){let a=Gb();return a.length>0&&a.every(o=>e.find(t=>t.module.alias===o.alias)?.alreadyInstalled===true)}var Gi={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=ne__default.join(Ce__default.homedir(),".claude","settings.json"),o=ie__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),r=JSON.parse(o).env;return typeof r=="object"&&r!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in r}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let a=["flow-ai-obs","init","--no-interactive"];if(a.push("--custom-url",e.customUrl??ni),e.credentials){let{clientId:o,clientSecret:t,tenant:r}=e.credentials;a.push("--client-id",o,"--client-secret",t,"--tenant",r);}return e.customEmail&&a.push("--custom-email",e.customEmail),[a]},onDemand:null,mode:"non-interactive"}},Bb={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard",tap:"FlorianBruniaux/tap"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},de=Co()?[Gi,Bb]:[Gi];Re();I();var Wb=k("moduleState");function ji(){let e=process.env.FLOW_HOME??ne__default.join(Ce__default.homedir(),".flow");return ne__default.join(e,"modules.json")}var Jb={retries:5,minTimeout:50};async function Hl(e,a){ie__default.mkdirSync(ne__default.dirname(e),{recursive:true});let o=await zb.lock(e+".lock",{realpath:false,retries:Jb});try{return await a()}finally{await o();}}function Vl(){let e=ji();if(!ie__default.existsSync(e))return [];try{let a=JSON.parse(ie__default.readFileSync(e,"utf-8"));return a.schemaVersion!==1?(Wb.warn(`modules.json has unknown schemaVersion ${a.schemaVersion}, resetting`),ie__default.rmSync(e,{force:!0}),[]):Array.isArray(a.modules)?a.modules.map(o=>({...o,name:o.name??null})):[]}catch{return ie__default.rmSync(e,{force:true}),[]}}function ot(){return Vl()}function Ql(e){let a=ji();ie__default.mkdirSync(ne__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`,t={schemaVersion:1,modules:e};ie__default.writeFileSync(o,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,a);}function ta(e){return ot().find(a=>a.alias===e)??null}async function ka(e){let a=ji();await Hl(a,async()=>{let o=Vl(),t=o.findIndex(r=>r.alias===e.alias);t===-1?o.push(e):o[t]=e,Ql(o);});}async function tt(){let e=ji();ie__default.existsSync(e)||await Hl(e,async()=>{ie__default.existsSync(e)||Ql([]);});}var Qb=promisify(execFile);function Ro(e,a){let o=e.platforms[process.platform];return !o||o.status!=="supported"?null:o.strategies.find(t=>t.type===a)??null}async function Ga(e){let a=process.platform==="win32"?"where":"which";try{return await Qb(a,[e]),!0}catch{return false}}function Za(){return process.platform==="win32"?"npm.cmd":"npm"}var _l=promisify(execFile),It=class{type="npm";async isAvailable(){return Ga("npm")}async install(a){let o=await this.getInstalledVersion(a);return o?{success:true,version:o,method:"npm",durationMs:0}:this.runNpmInstall(a,false)}async update(a,o){return this.runNpmInstall(a,true)}async getInstalledVersion(a){let o=Ro(a,"npm");if(!o)return null;try{let{stdout:t}=await _l(Za(),["list","-g",o.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(t).dependencies?.[o.package]?.version??null}catch{return null}}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(a,o){let t=Date.now(),r=Ro(a,"npm");if(!r)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-t};let i=o?`${r.package}@latest`:r.package;try{return await _l(Za(),["install","-g",i],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(a)??void 0,method:"npm",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}};var Ui=promisify(execFile),Yb=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,zi=class{type="homebrew";async isAvailable(){return Ga("brew")}async install(a){return this.runBrewCommand(a,"install")}async update(a,o){return this.runBrewCommand(a,"upgrade")}async getInstalledVersion(a){let o=Ro(a,"homebrew");return o?this.getVersionByFormula(o.formula):null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(a,o){let t=Date.now(),r=Ro(a,"homebrew");if(!r)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-t};let i=o==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return r.tap&&(await Ui("brew",["tap",r.tap]),await Ui("brew",["trust",r.tap])),await Ui("brew",[o,r.formula]),{success:!0,version:await this.getVersionByFormula(r.formula)??void 0,method:"homebrew",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:i,message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}async getVersionByFormula(a){try{let{stdout:o}=await Ui("brew",["list","--versions",a]),t=o.trim().match(Yb);return t?t[2]:null}catch{return null}}};var Tt=promisify(execFile),Kl=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function $l(){let e=process.env.FLOW_HOME??ne__default.join(Ce__default.homedir(),".flow");return ne__default.join(e,"bin")}var Wi=class{type="curl";async isAvailable(){return Ga("curl")}async install(a){let o=Date.now(),t=Ro(a,"curl");if(!t)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-o};let r=typeof t.url=="function"?t.url(process.arch):t.url;return (t.mode??"binary")==="script"?this.installScript(r,t.checksumUrl,a,o):this.installBinary(r,t.checksumUrl,a,o)}async update(a,o){return this.install(a)}async getInstalledVersion(a){let o=ne__default.join($l(),ne__default.basename(a.binaryName));for(let t of [o,a.binaryName])try{let{stdout:r}=await Tt(t,["--version"]),i=r.match(Kl);if(i)return i[1]}catch{}return null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(a,o,t,r){if(!o)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${t.alias})`},durationMs:Date.now()-r};let i=ne__default.join(Ce__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Tt("curl",["-sSL","--fail","-o",i,a]),o){let n=await this.validateChecksum(i,o);if(!n.valid){try{ie__default.unlinkSync(i);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:n.message},durationMs:Date.now()-r}}}return ie__default.chmodSync(i,448),await Tt("bash",[i]),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"curl",durationMs:Date.now()-r}}catch(s){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-r}}finally{try{ie__default.unlinkSync(i);}catch{}}}async installBinary(a,o,t,r){let i=$l(),s=ne__default.join(i,ne__default.basename(t.binaryName)),n=false;try{if(ie__default.mkdirSync(i,{recursive:!0}),n=!0,await Tt("curl",["-L","--fail","-o",s,a]),o){let l=await this.validateChecksum(s,o);if(!l.valid)return ie__default.unlinkSync(s),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:l.message},durationMs:Date.now()-r}}ie__default.chmodSync(s,493);let d=null;try{let{stdout:l}=await Tt(s,["--version"]),c=l.match(Kl);d=c?c[1]:null;}catch{}return {success:!0,version:d??void 0,method:"curl",durationMs:Date.now()-r}}catch(d){if(n)try{ie__default.unlinkSync(s);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:d instanceof Error?d.message:String(d)},durationMs:Date.now()-r}}}async validateChecksum(a,o){let t=ne__default.join(Ce__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Tt("curl",["-L","--fail","-o",t,o]);let r=ie__default.readFileSync(t,"utf-8").trim().split(/\s+/)[0],i=ie__default.readFileSync(a),s=createHash("sha256").update(i).digest("hex");return s!==r?{valid:!1,message:`SHA256 mismatch: expected ${r}, got ${s}`}:{valid:!0,message:""}}catch(r){return {valid:false,message:`Checksum validation failed: ${String(r)}`}}finally{try{ie__default.unlinkSync(t);}catch{}}}};I();var Yl="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Yl=e.version);}catch{}var ve=Yl;var Te=k("moduleInstaller");function ja(e){switch(e){case "npm":return new It;case "homebrew":return new zi;case "curl":return new Wi}}async function Sr(e,a,o){try{await C(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:o.code,error_message:o.message,trigger:a});}catch(t){Te.warn(`Failed to emit install failed event: ${String(t)}`);}}async function xo(e,a,o,t,r,i){let s=Date.now(),n=e.platforms[process.platform];if(!n)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-s};if(n.status==="experimental"){Te.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let u={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(n.status!=="supported"){let u={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(!n.strategies.some(u=>u.type===o)){let u={code:"STRATEGY_NOT_FOUND",message:`Strategy "${o}" is not configured for module "${e.alias}" on ${process.platform}`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}let d=ja(o),l=false;try{l=await d.isAvailable();}catch(u){Te.warn(`${o} availability check failed: ${String(u)}`);}if(!l){let u={code:"STRATEGY_NOT_AVAILABLE",message:`"${o}" is not installed on this system`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}try{await C(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ve,trigger:a});}catch(u){Te.warn(`Failed to emit install started event: ${String(u)}`);}let c;try{c=i?.forceLatest?await d.update(e,"unknown"):await d.install(e);}catch(u){let m=u instanceof Error?u.message:String(u);Te.warn(`${o} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-s};}if(c.success){await ka({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await C(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:a});}catch(p){Te.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:u,failed:m}=await iv(e,a,t,r);return u?{...c,pendingInteractiveSetup:u}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Sr(e,a,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function iv(e,a,o,t){if(!e.postInstall)return {pendingCmd:null,failed:false};let r=a==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(r==null)return {pendingCmd:null,failed:false};let i;if(typeof r=="function"){let n=await Y(),d={credentials:n?{clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}:null,customUrl:o??null,customEmail:t??null};try{i=r(d);}catch(l){return Te.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else i=r;if(i.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:i[0]??null,failed:false};let s=false;for(let n=0;n<i.length;n++){let d=i[n];if(d.length===0)continue;let l=spawnSync(d[0],d.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,Te.warn(`postInstall "${d.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&Te.warn(l.stderr);let c=i.slice(n+1).filter(u=>u.length>0);c.length>0&&Te.debug(`continuing with remaining postInstall steps: ${c.map(u=>u.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function Ji(e,a){let o=Date.now(),t=ta(e.alias);if(!t?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-o};let r=ja(t.installMethod),i=t.installedVersion??"unknown";if(a==="command")try{await C(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ve,trigger:"command"});}catch(n){Te.warn(`Failed to emit update started event: ${String(n)}`);}let s;try{s=await r.update(e,i);}catch(n){let d=n instanceof Error?n.message:String(n);Te.warn(`${t.installMethod} update threw: ${d}`),s={success:false,error:{code:"UPDATE_THREW",message:d},durationMs:Date.now()-o};}if(s.success)if(await ka({...t,installedVersion:s.version??t.installedVersion,lastChecked:new Date().toISOString()}),a==="command")try{await C(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:s.version??"unknown",duration_ms:s.durationMs,os:process.platform,trigger:"command"});}catch(n){Te.warn(`Failed to emit update completed event: ${String(n)}`);}else try{await C(w.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:i,to_version:s.version??"unknown",duration_ms:s.durationMs});}catch(n){Te.warn(`Failed to emit module updated event: ${String(n)}`);}else if(a==="command")try{await C(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:s.error?.code??"UNKNOWN",error_message:s.error?.message??"unknown error",trigger:"command"});}catch(n){Te.warn(`Failed to emit update failed event: ${String(n)}`);}return s}I();var Hi=k("flowAiObsSetup");async function Vi(e,a){try{if(!await new It().isAvailable().catch(()=>!1))return Hi.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let r=await xo(Gi,"onboarding","npm",e,a,{forceLatest:!0});return r.success?r.postInstallFailed||r.configCheckFailed?(Hi.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Hi.warn(`flow-ai-obs install failed: ${r.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(o){return Hi.warn(`installFlowAiObs threw: ${String(o)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}I();function Zl(e){if(!(e instanceof Error))return "unknown";let a=e.message.toLowerCase();return a.includes("401")||a.includes("unauthorized")?"invalid_credentials":a.includes("403")||a.includes("forbidden")?"forbidden":a.includes("timeout")||a.includes("timed out")?"timeout":a.includes("network")||a.includes("econnrefused")||a.includes("fetch")?"network_error":"unknown"}var sv=k("useAuthSetup");function eu(){let[e,a]=useState(""),o=useRef(null),t=useRef(null),r=useRef(null),[i,s]=useState(),[n,d]=useState(null),[l,c]=useState(false),[u,m]=useState("fields"),[p,g]=useState(null),f=useRef(0),h=useRef(false),{setCredentials:b,setJustAuthenticated:D}=oa(),q=()=>{m("fields"),g(null),a(""),o.current=null,t.current=null,r.current=null;},L=()=>{C(w.CLI_SESSION_STARTED,{cli_version:ve,os:process.platform,node_version:process.version,duration_ms:Do(),interface:"tui"}).catch(()=>{});},A=async W=>{h.current=true;let _={...o.current,customUrl:t.current??void 0};try{W&&Ni(W),await ko(_);}catch(V){d(V instanceof Error?V.message:"Failed to persist credentials"),q(),h.current=false;return}let{clientSecret:E,...B}=_;b(B),D(true),L(),await Vi(t.current,r.current).catch(V=>sv.warn(`installFlowAiObs threw unexpectedly: ${String(V)}`)),Qi({starterKit:B.starterKit});},T=async()=>A(),F=async W=>A(W),O=W=>{try{let _={...o.current,customUrl:t.current??void 0};return Oi(_,{allowOverwriteMalformed:W,jwtOverride:e.trim()})}catch(_){return _ instanceof at?(m("malformedConfirm"),null):(d(_ instanceof Error?_.message:"Failed to read settings.json"),m("fields"),null)}},oe=()=>{let W=O(true);W&&(g(W),F(W));},x=async()=>{let W=e.trim();if(!W){s("This field is required");return}let _;try{_=wr(W);}catch(E){s(E instanceof Error?E.message:"Invalid JWT");return}s(void 0),o.current=_,m("customUrl");},J=W=>{t.current=W,m("email");},ae=W=>{r.current=W,z();},z=async()=>{let W=t.current;W&&La(W),c(true),d(null),f.current+=1;try{await Xo(o.current);let _=O(!1);_&&(g(_),m("preview"));}catch(_){let E=_ instanceof Error?_.message:"Authentication failed";d(E),Al(w.CLI_AUTH_FAILED,{error_code:Zl(_),attempt:f.current},o.current.tenant).catch(()=>{}),a(""),o.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:i,authError:n,isSubmitting:l,step:u,plan:p,isCommittingRef:h,setJwtValue:a,setJwtError:s,cancelToFields:q,handleSubmit:x,goToEmailStep:J,handleEmailConfirm:ae,commitAndProceed:F,skipJwtAndProceed:T,planPersistOverwrite:oe}}U();j();function au(){let{jwtValue:e,jwtError:a,authError:o,isSubmitting:t,step:r,plan:i,isCommittingRef:s,setJwtValue:n,setJwtError:d,cancelToFields:l,handleSubmit:c,goToEmailStep:u,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:g,planPersistOverwrite:f}=eu(),[h,b]=useState("confirm"),[D,q]=useState(""),L=useRef(""),[A,T]=useState(false);return useEffect(()=>{r==="customUrl"&&(b("confirm"),L.current="",q(""),T(false));},[r]),useInput((F,O)=>{if(!(t||s.current)){if(r==="preview"){O.return&&i?p(i):O.escape?g():F==="q"&&l();return}if(r==="malformedConfirm"){O.return?f():O.escape&&l();return}if(r==="customUrl"){if(h==="confirm")F==="y"||F==="Y"?b("input"):(F==="n"||F==="N"||O.return)&&u(null);else if(O.escape)L.current="",q(""),b("confirm");else if(O.return){let oe=L.current.trim();oe.length>0&&ht.test(oe)?(T(false),u(oe)):oe.length>0&&T(true);}else O.backspace||O.delete?(L.current=L.current.slice(0,-1),q(L.current)):F&&!O.ctrl&&!O.meta&&(L.current=L.current+F,q(L.current),T(false));return}r!=="email"&&O.return&&c();}},{isActive:true}),r==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[fo," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!t&&h==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!t&&h==="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:D}),jsx(Text,{color:"cyan",children:"\u2588"})]}),A&&jsx(Text,{color:"red",children:bt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):r==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[fo," \u2014 Initial Setup"]})}),t?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Fl,{onConfirm:m})]}):r==="preview"&&i?jsx(Ol,{plan:i}):r==="malformedConfirm"?jsx(Nl,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[fo," \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(Ll,{label:"JWT",value:e,onChange:F=>{n(F),a&&d(void 0);},masked:true,isActive:!t,error:a})})}),t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),o&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",v(o)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function qt(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(uv,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ve]})})]})}var iu=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],re=Co()?iu:iu.slice(0,3);function pv(e){return re.findIndex(a=>a.id===e)}function od(e,a,o){let t=pv(o.activeTab);if(a.rightArrow||a.tab){let r=re[(t+1)%re.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}if(a.leftArrow){let r=re[(t-1+re.length)%re.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}return a.downArrow?[{type:"setFocus",focus:re[t]?.focus??"list"}]:[]}var du={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function cu({outdatedCount:e=0}){let a=y(o=>o.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:re.map(({id:o})=>{let t=o===a,r=o==="updates"&&e>0?`${du[o]} (${e})`:du[o];return jsx(Box,{marginRight:1,children:t?jsx(Text,{bold:true,inverse:true,children:` ${r} `}):jsx(Text,{dimColor:true,children:` ${r} `})},o)})})}var _e=create(e=>({query:"",cursorPosition:0,setQuery:a=>e({query:a}),setCursorPosition:a=>e({cursorPosition:a}),resetQuery:()=>e({query:"",cursorPosition:0})}));function uu(){let e=y(s=>s.focus),a=_e(s=>s.query),o=_e(s=>s.cursorPosition),t=e==="search",r=a.slice(0,o),i=a.slice(o);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:t?"cyan":"gray",children:"\u{1F50D} "}),t?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:r}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:a||"Search..."})]})}U();var pu=Object.keys(ho).map((e,a)=>({key:a<3?String(a+2):String((a+5)%10),type:e,...ho[e]})),mu=["internal","external"].map((e,a)=>({key:String(a+6),origin:e,...Kc[e]}));function gu(){let e=y(t=>t.catalogFilters),a=pu.every(t=>e.types.has(t.type)),o=mu.every(t=>e.origins.has(t.origin));return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,flexWrap:"wrap",children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:a?"green":void 0,dimColor:!a,children:[a?"\u25C9":"\u25CB"," All"]})]}),pu.map(t=>{let r=!a&&e.types.has(t.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:o?"green":void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," All"]})]}),mu.map(t=>{let r=!o&&e.origins.has(t.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)})]})}U();function fu({type:e}){let{label:a,color:o}=ho[e];return jsx(Text,{color:o,children:a})}U();function vu({origin:e}){return e===dr?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}j();var Xi=vv.memo(function({item:a,isSelected:o}){let t=a.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:a.name}),a.type&&jsxs(Text,{children:[" ",jsx(fu,{type:a.type})]}),a.origin&&jsxs(Text,{children:[" ",jsx(vu,{origin:a.origin})]}),jsxs(Text,{dimColor:true,children:[a.authorName?` \xB7 ${a.authorName}`:"",a.version?` \xB7 v${a.version}`:" \xB7 n/a"]}),a.status&&jsxs(Text,{color:t,children:[" [",a.status,"]"]}),a.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),a.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",qa(a.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:a.description})})]})});function Lt({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}U();function Pu({items:e,emptyMessage:a}){let o=y(d=>d.selectedIndex);if(e.length===0)return jsx(Lt,{message:a});let t=Math.max(0,o-Math.floor(ea/2)),r=Math.min(e.length,t+ea);r===e.length&&(t=Math.max(0,r-ea));let i=e.slice(t,r),s=t,n=e.length-r;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((d,l)=>jsx(Xi,{item:d,isSelected:t+l===o},d.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:n>0?`\u2193 ${n} more below`:" "})})]})}function Su({label:e,pathHint:a}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",a]})]})}U();function Ru({groups:e,emptyMessage:a}){let o=y(p=>p.selectedIndex),t=[],r=0;for(let p of e){t.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let g of p.items)t.push({kind:"item",item:g,itemIndex:r,key:`i-${p.scope}-${g.name}-${g.marketplace??""}`}),r++;}if(r===0)return jsx(Lt,{message:a});let s=t.findIndex(p=>p.kind==="item"&&p.itemIndex===o),n=s>=0?s:0,d=Math.max(0,n-Math.floor(ea/2)),l=Math.min(t.length,d+ea);l===t.length&&(d=Math.max(0,l-ea));let c=t.slice(d,l),u=d,m=t.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:u>0?`\u2191 ${u} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Su,{label:p.label,pathHint:p.pathHint},p.key):jsx(Xi,{item:p.item,isSelected:p.itemIndex===o},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var Rv={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Av({items:e,tabId:a,emptyMessage:o,groups:t,actionHint:r}){return jsxs(Box,{flexDirection:"column",children:[jsx(uu,{}),jsx(gu,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Rv[a]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),r&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${r}`})]}),t&&t.length>0?jsx(Ru,{groups:t,emptyMessage:o}):jsx(Pu,{items:e,emptyMessage:o})]})}function Au({filteredItems:e,emptyMessage:a,groups:o,onBatchUpdate:t}){let r=y(d=>d.activeTab),i=y(d=>d.focus);return useInput(d=>{d==="a"&&e.length>0&&t?.();},{isActive:r==="updates"&&i==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Av,{items:e,tabId:r,emptyMessage:a,groups:r!=="discover"?o:void 0,actionHint:r==="updates"?"press 'a' to update all":void 0},r)})}var Iv={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 Ki(){let e=y(o=>o.focus),a=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[Iv[e],a?" | Ctrl+D: debug log":""]})})}j();function xu({message:e,type:a}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:a==="success"?"green":a==="info"?"cyan":"red",children:[a==="success"?"\u2713":a==="info"?"(i)":"\u2717"," ",v(e)]})}):null}function $i({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Wp,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function cd(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Mu=20;function Yi(e,a){let o=a>0?Math.min(e/a,1):0,t=Math.round(o*100),r=Math.round(o*Mu),i="\u2588".repeat(r)+"\u2591".repeat(Mu-r),s=`${cd(e)} / ${cd(a)}`;return {bar:i,percent:t,label:s}}function Zi({received:e,total:a}){let{bar:o,percent:t,label:r}=Yi(e,a);return jsxs(Text,{dimColor:true,children:[o," ",t,"%"," ","(",r,")"]})}function es({message:e,onRetry:a,onBack:o}){return useInput((t,r)=>{t==="r"&&r.ctrl&&a?a():r.escape&&o&&o();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),a&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),o&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ra({itemName:e,actions:a,descriptions:o,onAction:t,onClose:r}){let i=y(d=>d.focus),[s,n]=useState(0);return useInput((d,l)=>{l.upArrow?n(c=>c>0?c-1:c):l.downArrow?n(c=>c<a.length-1?c+1:c):l.return?t(a[s]):l.escape&&r();},{isActive:i==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:a.map((d,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",d]}),o?.[d]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",o[d]]})]},l))})]})}U();var md=Object.entries(Ka),Ou=[...md.map(([,e])=>e.actionLabel),"Cancel"],Nu=Object.fromEntries(md.map(([,e])=>[e.actionLabel,e.description]));function Gu(e){let a=md.find(([,o])=>o.actionLabel===e);return a?a[0]:null}I();var Hv=k("provider.registry"),Vv=3e4,os=class{adapters=new Map;availabilityCache=new Map;register(a){this.adapters.set(a.id,a);}async checkAvailability(a){let o=this.availabilityCache.get(a.id);if(o&&Date.now()<o.expiresAt)return o.result;let t=await a.isAvailable();return this.availabilityCache.set(a.id,{result:t,expiresAt:Date.now()+Vv}),t}async getAvailableProviders(a){let o=[...this.adapters.values()].filter(r=>a in r.installers),t=await Promise.allSettled(o.map(r=>this.checkAvailability(r)));return t.forEach((r,i)=>{r.status==="rejected"&&Hv.warn(`Provider "${o[i].id}" isAvailable() threw: ${String(r.reason)}`);}),o.filter((r,i)=>{let s=t[i];return s.status==="fulfilled"&&s.value===true})}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};var Qv={user:"global",project:"project",local:"local"};function ts(e){return e?Qv[e]:"global"}var Xe=class extends Error{constructor(o,t){super(`${o} v${t} is already installed. Use --force to reinstall.`);this.pluginName=o;this.version=t;this.name="AlreadyInstalledError";}pluginName;version},Io=class extends Error{constructor(o,t){super(`${o} is already up to date (v${t})`);this.pluginName=o;this.version=t;this.name="AlreadyUpToDateError";}pluginName;version};xr();gd();I();var Kv=k("catalog.registry"),rs=class{adapters=new Map;register(a){this.adapters.set(a.id,a);}unregister(a){this.adapters.delete(a);}async fetchAllWithErrors(){let a=this.listAdapters(),o=await Promise.allSettled(a.map(i=>i.fetchItems())),t=[],r=[];for(let i=0;i<o.length;i++){let s=o[i],n=a[i];if(s.status==="fulfilled")t.push(...s.value);else {let d=String(s.reason);Kv.warn(`Catalog adapter failed: ${d}`),r.push({adapterId:n.id,adapterName:n.name,reason:d});}}return {items:t,failures:r}}async fetchAll(){let{items:a}=await this.fetchAllWithErrors();return a}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};Oe();var ry={retries:5,minTimeout:50};async function fd(e,a){mkdirSync(dirname(e),{recursive:true});let o=await zb.lock(e+".lock",{realpath:false,retries:ry});try{return await a()}finally{await o();}}var is=class{filePath;constructor(a){this.filePath=a??ol();}async read(){try{let a=await readFile(this.filePath,"utf-8");return JSON.parse(a).catalogs??[]}catch(a){if(a.code==="ENOENT")return [];throw a}}async write(a){let o=dirname(this.filePath);await mkdir(o,{recursive:true});let t=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(t,JSON.stringify({catalogs:a},null,2),"utf-8"),await rename(t,this.filePath);}async add(a){await fd(this.filePath,async()=>{let o=await this.read();if(o.some(r=>r.id===a.id))return;let t={...a,lastUpdated:a.lastUpdated??new Date().toISOString()};await this.write([...o,t]);});}async remove(a){if(a==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await fd(this.filePath,async()=>{let o=await this.read();await this.write(o.filter(t=>t.id!==a));});}async updateField(a,o){await fd(this.filePath,async()=>{let t=await this.read();t.some(r=>r.id===a)&&await this.write(t.map(r=>r.id===a?{...r,...o}:r));});}};bd();var me=new rs,ao=new is,gy=["flow-harness"];function fy(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?gy:e.split(",").map(a=>a.trim()).filter(Boolean)}me.register(new Ut);for(let e of fy())me.register(new Ut(e));var Ku=false;async function $u(){if(Ku)return;Ku=true;let e=await ao.read(),{GitRepoAdapter:a}=await Promise.resolve().then(()=>(vd(),Xu));for(let o of e)me.register(new a(o.id,o.name,o.source));}To();function Yu(e){if(e===void 0||!Number.isFinite(e)||e<=0)return 3e4;let a=e/131072*1e3;return Math.min(6e5,Math.max(3e4,Math.ceil(a)))}I();var by=k("api:actions"),Zu=2;async function oo(e){if(e){let{FlowApiAdapter:a}=await Promise.resolve().then(()=>(bd(),Wu));return new a(e).fetchItems()}return me.fetchAll()}async function ep(){return me.fetchAllWithErrors()}async function Wt(e,a){Er(e);try{return await Ot(`v1/plugins/${e}/manifest`,a).json()}catch(o){let t=await Nt(o);throw t?new Error(t):o instanceof Error?o.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):o.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${o.message}`):o}}async function vy(e,a){try{let t=(await ju(`v1/plugins/${e}/archive`,{source:a,timeoutMs:3e4})).headers.get("x-archive-size"),r=t?Number(t):NaN;return Number.isFinite(r)&&r>0?r:void 0}catch(o){by.debug(`[${e}] Archive size probe failed, using default timeout: ${String(o)}`);return}}async function ap(e,a,o){Er(e);try{let t=await vy(e,o),r=Yu(t),i=await Ot(`v1/plugins/${e}/archive`,o,r),s=i.headers.get("x-archive-size"),n=s?Number(s):NaN,d=Number.isFinite(n)&&n>0?n:0,l=d>0,c=i.body;if(!c)throw new Error("Failed to download plugin: response has no body");let u=c.getReader(),m=[],p=0;for(;;){let{done:g,value:f}=await u.read();if(g)break;if(p+=f.byteLength,l&&p>d*Zu)throw await u.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${d*Zu}`);m.push(f),l&&a?.(p,d);}return Buffer.concat(m)}catch(t){if(t instanceof Error&&t.message.includes("Download exceeded expected size"))throw t;let r=await Nt(t);throw r?new Error(r):t instanceof Error?new Error(`Failed to download plugin: ${t.message}`):t}}async function ns(){try{let{profiles:e}=await Ua().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}}Oe();Oe();async function op(e,a){let o=ne.resolve(a);await za.mkdir(o,{recursive:true});let t=ne.join(ne.dirname(o),`${randomUUID()}.zip`);try{await za.writeFile(t,e);let r=await ky.Open.file(t),i=ne.normalize(o+ne.sep);for(let s of r.files){if((s.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${s.path}" is a symbolic link and was rejected`);let d=ne.resolve(o,s.path);if(process.platform==="win32"&&d.length>=260)throw new Error(`Path too long: "${d}" (${d.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!d.startsWith(i)&&d!==o)throw new Error(`Zip Slip detected: entry "${s.path}" would escape target directory`)}await r.extract({path:o});try{let s=realpathSync(o);if(!s.startsWith(ne.resolve(ne.dirname(o))))throw new Error(`Zip Slip (post-extract): resolved path "${s}" is outside expected parent`)}catch(s){if(s.code!=="ENOENT")throw s}}finally{try{await za.unlink(t);}catch{}}}async function yd(e){await za.rm(e,{recursive:true,force:true});}async function Mo(){let e=el();await za.mkdir(ne.dirname(e),{recursive:true});try{await za.writeFile(e,"",{flag:"wx"});}catch(o){if(o.code!=="EEXIST")throw o}return await zb.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}Oe();U();function wy(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||ue,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function ip(e){let a=ui(e);if(!ie__default.existsSync(a))return null;try{return JSON.parse(ie__default.readFileSync(a,"utf-8"))}catch{return null}}function Sy(e){let a=ip(e);if(a)return a;let o=wy(e),t=ui(e);return ie__default.mkdirSync(ne__default.dirname(t),{recursive:true}),kd(o,e),o}function kd(e,a){let o=ui(a),t=`${o}.${randomUUID()}.tmp`;ie__default.writeFileSync(t,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(t,o);}function Cy(e){let a=e||ue,o=Jo(),t={};try{ie__default.existsSync(o)&&(t=JSON.parse(ie__default.readFileSync(o,"utf-8")));}catch{t={};}if(t[a])return;t[a]={source:{source:"github",repo:`cit-flow/${a}`},installLocation:Zc(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let r=`${o}.${randomUUID()}.tmp`;ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(r,o);}function sp(e,a,o){ia(e.name),Cy(o);let t=vn(e.name,o);ie__default.mkdirSync(ne__default.dirname(t),{recursive:true});try{ie__default.lstatSync(t),ie__default.rmSync(t,{recursive:!0,force:!0});}catch{}ie__default.cpSync(a,t,{recursive:true,dereference:true});let r=Sy(o);r.plugins.some(s=>s.name===e.name)||(r.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),kd(r,o));}function Pd(e,a){ia(e);let o=vn(e,a);try{ie__default.rmSync(o,{recursive:!0,force:!0});}catch{}let t=ip(a);if(!t)return;let r=t.plugins.length;t.plugins=t.plugins.filter(i=>i.name!==e),t.plugins.length!==r&&kd(t,a);}j();I();var Ay=k("mcpConfigReader"),xy=500,Ey=512;function Iy(){return ne__default.join(Ce__default.homedir(),".claude.json")}function Ty(){return ne__default.join(process.cwd(),".mcp.json")}function dp(e){if(!ie__default.existsSync(e))return null;try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return Ay.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dd(e){if(!Ir(e))return {};let a=e.mcpServers;return Ir(a)?a:{}}function wd(e,a){return Object.keys(e).slice(0,xy).map(t=>({name:v(t.slice(0,Ey)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:a,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function lp(){let e=[],a=Iy(),o=dp(a);if(Ir(o)){let n=o,d=Dd(n);e.push(...wd(d,"user"));let l=process.cwd();if(Ir(n.projects)){let c=n.projects[l];if(Ir(c)){let u=Dd(c);e.push(...wd(u,"local"));}}}let t=Ty(),r=dp(t),i=Dd(r);e.push(...wd(i,"project"));let s=new Map;for(let n of e){let d=`${n.name}@${n.scope}`;s.has(d)||s.set(d,n);}return [...s.values()]}I();var sa=k("storage");async function qy(e,a,o){try{await C(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:o,source:a,interface:Z().interfaceType});}catch(t){sa.warn(`Failed to send uninstall metrics: ${String(t)}`);}}function Ly(e,a,o){let t=a==="enabled"?w.CLI_TOOL_ENABLED:w.CLI_TOOL_DISABLED;C(t,{tool_id:e,source:o,interface:Z().interfaceType}).catch(r=>sa.warn(`Failed to send ${a} metrics: ${String(r)}`));}function Ad(){return ne__default.join(Ce__default.homedir(),".claude","plugins","installed_plugins.json")}function Fy(){return ne__default.join(Ce__default.homedir(),".claude","plugins")}function ds(e){let a;try{a=ie__default.realpathSync(e);}catch{a=ne__default.resolve(e);}let o=ne__default.resolve(Fy()),t=ne__default.resolve(ne__default.join(process.cwd(),".claude","plugins")),r=a.startsWith(o+ne__default.sep),i=a.startsWith(t+ne__default.sep);if(!r&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function pp(e="user"){return e==="local"?ne__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?ne__default.join(process.cwd(),".claude","settings.json"):ne__default.join(Ce__default.homedir(),".claude","settings.json")}function Ae(){let e=Ad();if(!ie__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function xd(){let e=Ad();try{let a=await ie__default.promises.readFile(e,"utf-8");return JSON.parse(a)}catch{return {version:2,plugins:{}}}}function Oy(e){let a=e?.code;return a==="EACCES"||a==="EPERM"}function mp(e,a){try{ie__default.mkdirSync(ne__default.dirname(e),{recursive:!0});let o=`${e}.${randomUUID()}.tmp`;ie__default.writeFileSync(o,JSON.stringify(a,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,e);}catch(o){throw Oy(o)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):o}}function na(e){mp(Ad(),e);}function Tr(e){let a=e.lastIndexOf("@");return a===-1?{name:e,marketplace:""}:{name:e.slice(0,a),marketplace:e.slice(a+1)}}function Ny(e,a){let o=ne__default.join(e,".claude-plugin"),t=ne__default.join(o,"plugin.json");if(ie__default.existsSync(t))try{return JSON.parse(ie__default.readFileSync(t,"utf-8"))}catch{return null}let r=ne__default.join(o,"marketplace.json");if(ie__default.existsSync(r))try{let i=JSON.parse(ie__default.readFileSync(r,"utf-8"));return {description:i.plugins?.find(n=>n.name===a)?.description,author:i.owner}}catch{return null}return null}function Mr(e="user"){let a=pp(e);if(!ie__default.existsSync(a))return {};try{return JSON.parse(ie__default.readFileSync(a,"utf-8"))}catch{return {}}}function cs(e,a="user"){mp(pp(a),e);}function Gy(e,a){let{name:o,marketplace:t}=Tr(e),r;if(t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>Tr(s).name===o)[0],!r)throw sa.error(`[${o}] Plugin is not installed`),new Error(`Plugin '${o}' is not installed`);return {key:r,name:o}}function By(e,a){let{name:o,marketplace:t}=Tr(e),r;return t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>Tr(s).name===o)[0],r?{key:r,name:o}:null}function Sd(e="user"){return Mr(e).enabledPlugins??{}}function Cd(e,a="user"){let o=Mr(a),t=o.enabledPlugins;if(!t||!(e in t))return;let{[e]:r,...i}=t;o.enabledPlugins=i,cs(o,a);}function qr(e,a,o="user"){let t=Mr(o),r=t.enabledPlugins??{};t.enabledPlugins={...r,[e]:a},cs(t,o);}function jy(e){let a=new Map;for(let o of e){let t=o.projectPath?`${o.scope}:${o.projectPath}`:o.scope,r=a.get(t);(!r||o.installedAt>r.installedAt)&&a.set(t,o);}return [...a.values()]}function ce(){let e=Ae(),a=Sd(),o=Sd("project"),t=Sd("local"),r={project:o,local:t},i=Object.entries(e.plugins).flatMap(([l,c])=>{let{name:u,marketplace:m}=Tr(l),p=c.map(f=>f.scope==="managed"?{...f,scope:"user"}:f);return jy(p).map(f=>{let h=Ny(f.installPath,u),D=(r[f.scope]??a)[l];return {name:u,marketplace:m,version:f.version&&f.version!=="unknown"?f.version:void 0,installedAt:f.installedAt,installPath:f.installPath,scope:f.scope,providerId:f.providerId,type:f.type,description:h?.description,author:h?.author,status:D===false?"disabled":"enabled"}})}),s=lp(),n=new Set(i.map(l=>`${l.name}@${l.scope}`)),d=s.filter(l=>!n.has(`${l.name}@${l.scope}`));return [...i,...d]}function up(e){let a=e.lastIndexOf("@");return a>0?e.slice(a+1):void 0}async function Lr(e,a){sa.debug(`[${e}] Acquiring lock to uninstall`);let o=await Mo();try{let t=Ae(),r=By(e,t.plugins);if(!r)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:i,name:s}=r,n=t.plugins[i];if(a){let d=n.find(u=>u.scope===a);if(!d)throw new Error(`Plugin '${s}' is not installed in ${a} scope`);sa.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),ds(d.installPath);let l=ne__default.dirname(d.installPath);ds(l),sa.debug(`[${s}] Removing directory: ${l}`),ie__default.rmSync(l,{recursive:!0,force:!0});let c=n.filter(u=>u.scope!==a);if(c.length===0){let{[i]:u,...m}=t.plugins;na({...t,plugins:m}),Cd(i,a),Pd(s,up(i));}else t.plugins[i]=c,na(t),Cd(i,a);}else {sa.debug(`[${s}] Resolved key: ${i}`);for(let c of n){ds(c.installPath);let u=ne__default.dirname(c.installPath);ds(u),sa.debug(`[${s}] Removing directory: ${u}`),ie__default.rmSync(u,{recursive:!0,force:!0}),Cd(i,c.scope);}Pd(s,up(i));let{[i]:d,...l}=t.plugins;na({...t,plugins:l});}await qy(s,n[0].origin??"internal",n[0].type??"skill"),sa.debug(`[${s}] Uninstalled successfully`);}finally{await o();}}async function Fr(e,a,o){sa.debug(`[${e}] Acquiring lock to set status \u2192 ${a}`);let t=await Mo();try{let r=Ae(),{key:i,name:s}=Gy(e,r.plugins),n=r.plugins[i],d=o??n[0].scope,l=n[0].origin??"internal";sa.debug(`[${s}] Resolved key: ${i}, scope: ${d}`),qr(i,a==="enabled",d),Ly(s,a,l),sa.debug(`[${s}] Status updated to ${a}`);}finally{await t();}}Oe();function Ed(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([a],[o])=>a.localeCompare(o)).map(([a,o])=>[a,Ed(o)]))}function Or(e,a){let o={...e};for(let[t,r]of Object.entries(a)){let i=o[t];if(Array.isArray(r)&&Array.isArray(i)){let s=new Set(i.map(n=>JSON.stringify(Ed(n))));o[t]=[...i,...r.filter(n=>!s.has(JSON.stringify(Ed(n))))];}else r!==null&&typeof r=="object"&&!Array.isArray(r)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?o[t]=Or(i,r):o[t]=r;}return o}I();var Id=k("bundleContent"),ls="${CLAUDE_PLUGIN_ROOT}/hooks/";function Uy(e){return e.split(ls).join("$CLAUDE_PROJECT_DIR/.claude/hooks/")}function Td(e){return typeof e=="string"?Uy(e):Array.isArray(e)?e.map(Td):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Td(o)])):e}function zy(e,a){let o=ne__default.join(e,"rules");if(!ie__default.existsSync(o))return 0;let t=ie__default.readdirSync(o).filter(i=>i.endsWith(".md")&&ie__default.lstatSync(ne__default.join(o,i)).isFile());if(t.length===0)return 0;let r=Pt(a);ie__default.mkdirSync(r,{recursive:true});for(let i of t)ie__default.copyFileSync(ne__default.join(o,i),ne__default.join(r,i));return t.length}function Wy(e,a){let o=ne__default.join(e,"hooks","hooks.json");if(!ie__default.existsSync(o))return 0;let t;try{t=JSON.parse(ie__default.readFileSync(o,"utf-8"));}catch(g){return Id.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(g)}`),0}let r=t.hooks;if(!r||typeof r!="object"||Array.isArray(r))return 0;let i=ne__default.join(e,"hooks"),s=kn(a),n=new Set,d=g=>{if(typeof g=="string"&&g.includes(ls)){let f=g.slice(g.indexOf(ls)+ls.length),h=/^([^"'\s]+)/.exec(f);h&&n.add(h[1]);}else Array.isArray(g)?g.forEach(d):g!==null&&typeof g=="object"&&Object.values(g).forEach(d);};d(r);let l=0;if(n.size>0){ie__default.mkdirSync(s,{recursive:true});for(let g of n){let f=ne__default.join(i,g);ie__default.existsSync(f)&&(ie__default.copyFileSync(f,ne__default.join(s,g)),l++);}}let c=Td(r),u=Mr(a),m=u.hooks!==null&&typeof u.hooks=="object"&&!Array.isArray(u.hooks)?u.hooks:{},p=Or(m,c);return cs({...u,hooks:p},a),l}function gp(e,a){let o=zy(e,a),t=Wy(e,a);o>0&&Id.debug(`Copied ${o} rule file(s) to ${Pt(a)}`),t>0&&Id.debug(`Copied ${t} hook script(s) to ${kn(a)}`);}U();I();var Jy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Hy=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ia(e){if(!Jy.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(!Hy.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 Lo=k("installer");function Qy(e,a,o){let t=`${e}@${o||ue}`,i=Ae().plugins[t];if(i&&!a)throw new Xe(e,i[0].version??"unknown");return {pluginKey:t,alreadyInstalled:i}}async function _y(e,a,o){o&&await yd(a);try{Lo.debug(`[${a}] Extracting archive...`),await op(e,a);}catch(t){throw await yd(a),t}}function Xy(e,a,o,t,r,i="claude-code",s){let n=Ae(),d={scope:t,...t==="user"?{}:{projectPath:process.cwd()},installPath:a,version:o,installedAt:new Date().toISOString(),origin:r,providerId:i,type:s},l=n.plugins[e]??[];n.plugins[e]=[...l.filter(c=>c.scope!==t),d],na(n),qr(e,true,t);}async function Ky(e,a,o,t,r,i){try{await C(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:i,source:r,scope:t,version:a,duration_ms:o,interface:Z().interfaceType});}catch(s){Lo.warn(`Failed to send install metrics: ${String(s)}`);}}async function $y(e,a,o,t){try{await C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:t,source:o,error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(r){Lo.warn(`Failed to send install-failed metrics: ${String(r)}`);}}async function je(e,a={}){let o=Date.now(),t=null;try{Lo.debug(`[${e}] Acquiring lock...`),t=await Mo();let{pluginKey:r,alreadyInstalled:i}=Qy(e,a.force,a.source),{source:s}=a;Lo.debug(`[${e}] Fetching manifest...`);let n=await Wt(e,s);ia(n.name),Vy(n.version),Lo.debug(`[${e}] Downloading archive...`);let d=await ap(e,a.onDownloadProgress,s),l=a.scope??"user",c=a.type??"skill",u=Yc(n.name,n.version,a.source);await _y(d,u,!!i&&!!a.force),gp(u,l),Xy(r,u,n.version,l,"internal",a.providerId,c),sp(n,u,a.source);let m=Date.now()-o;Lo.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:n.name,version:n.version,path:u,duration_ms:m};return a.skipMetrics||await Ky(n.name,n.version,m,ts(l),"internal",c),p}catch(r){throw await $y(e,r,"internal",a.type??"skill"),Lo.error(`[${e}] Installation failed: ${r instanceof Error?r.message:String(r)}`),r}finally{t&&await t();}}I();j();Re();xt();I();var Yy=k("commands:helpers");async function fe(){let e=await Y();if(!e)return S("Not authenticated. Run: flow auth login"),false;e.customUrl&&La(e.customUrl);try{await Oa();}catch(a){return Yy.debug(`Token validation failed: ${String(a)}`),S("Session expired. Run: flow auth login"),false}return true}async function ee(e){let a=qd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(v(e),t=>{a.close(),o(["y","yes"].includes(t.toLowerCase().trim()));});})}async function Fo(e){let a=qd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(v(e),t=>{a.close(),o(t.trim());});})}var Zy="\x1B[A",ek="\x1B[B";function fp(e,a){let o=a?R.cyan("\u276F"):" ",t=a?R.cyan(e.label):e.label,r=e.description?R.dim(` \u2014 ${e.description}`):"";return ` ${o} ${t}${r}`}function ak(e,a){return e.map((o,t)=>fp(o,t===a)).join(`
|
|
111
|
-
`)}async function
|
|
112
|
-
`),process.stdout.write(
|
|
110
|
+
`),this.warned=!0;}Ai().set(`${a}:${o}`,t);}async deleteSecret(a,o){let t=Ai(),r=`${a}:${o}`;return t.has(r)?(t.delete(r),!0):!1}getStoragePath(){return Ai().path}static hasExistingData(){try{let a=new Jn({projectName:Hn});return ie.existsSync(a.path)}catch{return !1}}static clearFallbackFile(){try{let a=new Jn({projectName:Hn});ie.rmSync(a.path,{force:!0});}catch{}xi=null;}};});async function Vn(){if(Qe.hasExistingData())return new Qe;switch(process.platform){case "darwin":return await St.isAvailable()?new St:new Qe;case "linux":return await ko.isAvailable()?new ko:await ko.ensureInstalled()?new ko:new Qe;case "win32":return await Ct.isAvailable()?new Ct:new Qe;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Pl=H(()=>{"use strict";On();Bn();Wn();fr();});var Dl=H(()=>{"use strict";Pn();Ln();Pl();On();Bn();Wn();fr();});async function Po(){return Ti||(Ti=Vn()),Ti}function Mi(){Ti=null;}async function Z(){let a=await(await Po()).getSecret(Za,Qn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function Do(e){let{clientId:a,clientSecret:o,tenant:t}=e,r=[!a?.trim()&&"clientId",!o?.trim()&&"clientSecret",!t?.trim()&&"tenant"].filter(Boolean);if(r.length>0)throw wl.error(`missing or empty fields: ${r.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Po()).setSecret(Za,Qn,JSON.stringify(e));}async function Sl(){let e=await Po();await e.deleteSecret(Za,Qn),await e.deleteSecret(Za,_n),await e.deleteSecret(Za,Xn);}async function Cl(){return (await Po()).getStoragePath()}async function Rl(e){await(await Po()).setSecret(Za,_n,JSON.stringify(e));}async function qi(){let a=await(await Po()).getSecret(Za,_n);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function Li(e){await(await Po()).setSecret(Za,Xn,JSON.stringify(e));}async function Rt(){let a=await(await Po()).getSecret(Za,Xn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function wo(){let e=await qi();return e?new Date(e.expiresAt)>new Date:false}function Fa(e){let a=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${a}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${a}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${a}/metrics-collector-api/`,wl.debug(`[customUrl] Service URLs overridden to base: ${a}`);}var wl,Za,Qn,_n,Xn,Ti,Re=H(()=>{"use strict";Dl();I();wl=k("config:credentials"),Za="flow-plugins-cli",Qn="credentials",_n="token-cache",Xn="user-info",Ti=null;});function At(e){let a=e.split(".");if(a.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${a.length}`);let o=a[1].replace(/-/g,"+").replace(/_/g,"/"),t=Buffer.from(o,"base64").toString("utf8");try{return JSON.parse(t)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Fi=H(()=>{"use strict";});function mb(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let o=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!o)return null;let t=parseInt(o[1],16),r=parseInt(o[2],16);return `${t>>8&255}.${t&255}.${r>>8&255}.${r&255}`}function Kn(e){if(Al.some(o=>o.test(e)))return true;let a=mb(e);return !!(a&&Al.some(o=>o.test(a)))}function gb(e,a){let o=process.env[e]??a;if(!o)throw new Error(`Missing required environment variable: ${e}`);return o}function Oa(e,a){let o=gb(e,a),t;try{t=new URL(o);}catch{throw new Error(`${e} must be a valid URL. Got: "${o}"`)}let r=process.env.NODE_ENV==="development";if(!r&&t.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${t.protocol}"`);if(t.username||t.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(t.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(t.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(t.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${t.hostname}"`);if(!r&&Kn(t.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${t.hostname}"`);return o}var Al,Xo=H(()=>{"use strict";Al=[/^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 bb(e){if(!Ya.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function vb(e){if(e instanceof HTTPError){let a=e.response.status;$n.debug(`HTTP error during authentication [status=${a}]`);let o="";try{let t=await e.response.text(),r=JSON.parse(t);typeof r.error=="string"&&(o=r.error);}catch{}return o&&xl[o]?new Error(xl[o]):a===StatusCodes.UNAUTHORIZED||a===StatusCodes.FORBIDDEN||a===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):a>=StatusCodes.BAD_REQUEST&&a<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?($n.debug(`Non-HTTP error during authentication: ${e.message}`),e):($n.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Ko(e){let a=Oa("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");bb(e.tenant);let o;try{o=await Yu.post(a,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await vb(i)}let t=o.expires_at??new Date(Date.now()+(o.expires_in??3600)*1e3).toISOString();await Do(e),await Rl({accessToken:o.access_token,expiresAt:t});let r=At(o.access_token);await Li({sub:r.sub,name:r.name,email:r.email});}var $n,xl,Oi=H(()=>{"use strict";Re();Fi();Xo();I();U();$n=k("api:auth");xl={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 Na(){if(await wo()){let t=await qi();if(t)return t.accessToken}El.debug("Token expired or missing, re-authenticating...");let a=await Z();if(!a)throw new Error("Not authenticated. Run: flow auth login");Qe.clearFallbackFile(),Mi(),await Ko(a);let o=await qi();if(!o)throw new Error("Authentication succeeded but token was not persisted");return El.debug("Token refreshed successfully"),o.accessToken}var El,xt=H(()=>{"use strict";Re();Oi();fr();I();El=k("lib:tokenProvider");});function za(){return Yu.create({prefix:Oa("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let a=await Na();e.headers.set("Authorization",`Bearer ${a}`);let o=await Z();o?.tenant&&Ya.test(o.tenant)&&e.headers.set("FlowTenant",o.tenant);}]}})}var Ir=H(()=>{"use strict";Xo();Re();xt();U();});function Ju(e){if(!(e.source===void 0&&e.timeoutMs===void 0))return {...e.source!==void 0&&{searchParams:{source:e.source}},...e.timeoutMs!==void 0&&{timeout:e.timeoutMs}}}function Ot(e,a,o){let t=za(),r=Ju({source:a,timeoutMs:o});return r?t.get(e,r):t.get(e)}function Hu(e,a={}){let o=za(),t=Ju(a);return t?o.head(e,t):o.head(e)}async function Nt(e){if(!(e instanceof HTTPError))return null;try{let a=await e.response.clone().json(),{message:o}=a;return Array.isArray(o)?o.filter(Boolean).join("; ")||null:typeof o=="string"&&o?o:null}catch{return null}}var kd=H(()=>{"use strict";Ir();});function Tr(e){if(!e||!gy.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Gt(e){return fy.test(e)}function Bt(e){let a=e.indexOf("@");return a>0?e.slice(0,a):e}function Dd(e){if(!hy.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 jt(e,a){let o=Bt(e);Dd(o);let t=["claude","plugin","install",o];return a&&t.push("--scope",a),t.join(" ")}function us(e){let a=e.trim();if(!a)throw new Error("No marketplace source provided.");if(!by.test(a)&&!vy.test(a))throw new Error(`Invalid marketplace source: "${a}". Must be owner/repo or an https:// URL.`);return a}var gy,fy,hy,by,vy,qo=H(()=>{"use strict";gy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;fy=/^[^@]+@[^@]+$/;hy=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;by=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,vy=/^https:\/\/[\w./:@?&=+#%-]+$/;});var _u={};el(_u,{FlowApiAdapter:()=>Ut});var yy,Ut,wd=H(()=>{"use strict";Ir();kd();I();qo();yy=k("catalog.flow-api"),Ut=class{id;name;source;removable=!1;contentSource;constructor(a){this.contentSource=a,this.id=a?`flow-api:${a}`:"flow-api",this.name=a?`Flow Marketplace (${a})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:a}=await Ot("v1/plugins/catalog",this.contentSource).json();return a.map(o=>({...o,catalogId:this.id,origin:o.origin??"internal",type:o.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(a){let o=await Nt(a);if(o)throw new Error(o);if(a instanceof HTTPError){let{status:t}=a.response;throw t===401||t===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${t}`)}throw a instanceof Error?a.name==="TimeoutError"||a.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${a.message}`):a}}async fetchManifest(a){Tr(a);try{return await Ot(`v1/plugins/${a}/manifest`,this.contentSource).json()}catch(o){let t=await Nt(o);if(t)throw new Error(t);if(o instanceof HTTPError){let{status:r}=o.response;throw r===404?new Error(`Plugin '${a}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${r}`)}throw o instanceof Error?new Error(`Failed to fetch manifest: ${o.message}`):o}}async ping(){try{return await za().head("v1/plugins/catalog"),yy.debug("ping ok"),!0}catch{return !1}}};});function Py(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:a})=>a.trim()||void 0).catch(()=>{})}function Ku(){return Xu??=Py(),Xu}var Xu,$u=H(()=>{"use strict";});var ep={};el(ep,{GitRepoAdapter:()=>zt});function Zu(e,a){if(!Dy.test(e))throw new Error(`Invalid ${a} in catalog source URL: "${e}"`)}var Dy,zt,Sd=H(()=>{"use strict";$u();Xo();Dy=/^[a-zA-Z0-9_.-]+$/;zt=class{id;name;source;constructor(a,o,t){this.id=a,this.name=o,this.source=t;}buildRawUrl(a,o="marketplace.json"){let t=new URL(this.source),{hostname:r,pathname:i}=t;if(Kn(r))throw new Error(`Catalog source URL points to a private/loopback address: "${r}"`);let s=i.replace(/^\//,"").split("/"),[n,d]=s;return Zu(n,"owner"),Zu(d,"repo"),r==="github.com"?`https://raw.githubusercontent.com/${n}/${d}/${a}/${o}`:r==="bitbucket.org"?`https://bitbucket.org/${n}/${d}/raw/${a}/${o}`:r==="gitlab.com"||r.startsWith("git.")?`https://${r}/${n}/${d}/-/raw/${a}/${o}`:`https://${r}/${n}/${d}/raw/${a}/${o}`}async fetchItems(){return this._fetchFromBranch("main").catch(a=>{if(this._is404(a))return this._fetchFromBranch("master");throw a})}async _fetchFromBranch(a){let o=await this._buildHeaders();try{let i=this.buildRawUrl(a,".claude-plugin/marketplace.json"),{plugins:s}=await Yu.get(i,{headers:o}).json();return s.map(n=>({...n,catalogId:this.id,origin:n.origin??"external"}))}catch(i){if(this._is401or403(i))throw this._authError();if(!this._is404(i))throw i}let t=this.buildRawUrl(a),{plugins:r}=await Yu.get(t,{headers:o}).json();return r.map(i=>({...i,catalogId:this.id,origin:i.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let o=await Ku();return o?{Authorization:`token ${o}`}:{}}_is404(a){return a!==null&&typeof a=="object"&&"response"in a&&a.response?.status===404}_is401or403(a){return a!==null&&typeof a=="object"&&"response"in a&&[401,403].includes(a.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(a){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});U();var y=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(yn),origins:new Set(kn)},setScreen:a=>e({screen:a}),setActiveTab:a=>e({activeTab:a}),setFocus:a=>e({focus:a}),setSelectedIndex:a=>e({selectedIndex:a}),setActionMenuOpen:a=>e({actionMenuOpen:a}),showNotification:(a,o)=>e({notification:{message:a,type:o}}),clearNotification:()=>e({notification:null}),setLoading:(a,o="")=>e({loading:a,loadingMessage:a?o:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(a,o)=>e({downloadProgress:a,downloadTotal:o}),setCatalogError:a=>e({catalogError:a}),setPendingExit:a=>e({pendingExit:a}),toggleTypeFilter:a=>e(o=>{let{types:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,types:new Set([a])},selectedIndex:0}}),selectAllTypes:()=>e(a=>({catalogFilters:{...a.catalogFilters,types:new Set(yn)},selectedIndex:0})),toggleOriginFilter:a=>e(o=>{let{origins:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,origins:new Set([a])},selectedIndex:0}}),selectAllOrigins:()=>e(a=>({catalogFilters:{...a.catalogFilters,origins:new Set(kn)},selectedIndex:0})),setDebugPanelOpen:a=>e({debugPanelOpen:a}),incrementCatalogVersion:()=>e(a=>({catalogVersion:a.catalogVersion+1})),setBundleInstallFlow:a=>e({bundleInstallFlow:a})}));Re();xt();Fi();U();Xo();I();var Ni=k("api:metrics");function Il(){return Oa("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Tl(e,a,o){return Yu.post(e,{json:a,headers:o})}async function kb(e){let a=await Rt();if(a)return a;let o=At(e),t={sub:o.sub,name:o.name,email:o.email};return await Li(t),t}async function C(e,a){let o=await Na(),t=await kb(o),r=await Z();if(!Ya.test(r.tenant))throw new Error(`Invalid tenant value: "${r.tenant}"`);let i={action:e,booster:vn,metadata:{...a},success:true,tenant:r.tenant,timestamp:new Date().toISOString(),user:{id:t.sub,name:t.name,email:t.email}};try{await Tl(Il(),i,{Authorization:`Bearer ${o}`,FlowTenant:r.tenant}),Ni.debug(`Metrics event sent: ${e}`);}catch(s){throw Ni.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function Ml(e,a,o){try{let t=o&&Ya.test(o)?o:"unknown",r={action:e,booster:vn,metadata:a,success:!0,tenant:t,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Tl(Il(),r,{FlowTenant:t}),Ni.debug(`Anonymous metrics event sent: ${e}`);}catch(t){Ni.warn(`Failed to send anonymous metrics event "${e}": ${String(t)}`);}}var w={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var Pb={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ya={...Pb};function ql(e){let a=Date.now();ya={sessionStart:a,stepStart:a,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function $o(e){ya.currentStep=e,ya.stepStart=Date.now();}function ee(){return {...ya}}function So(){return ya.sessionStart===0?0:Date.now()-ya.sessionStart}function Yo(){return ya.stepStart===0?0:Date.now()-ya.stepStart}function Ll(){ya.tuiSessionStart=Date.now();}function Fl(){return ya.tuiSessionStart===0?0:Date.now()-ya.tuiSessionStart}I();var Db=3e3,wb=k("abandonment");async function Gi(e){let{currentStep:a,sessionStart:o}=ee();if(o===0)return;let t={last_step:a,trigger:e,duration_ms:So()};try{await Promise.race([C(w.CLI_ONBOARDING_ABANDONED,t),new Promise((r,i)=>setTimeout(()=>i(new Error("abandonment timeout")),Db))]);}catch(r){wb.warn(`Abandonment event failed: ${String(r)}`);}}function Ol(e,a){return Promise.race([e,new Promise(o=>setTimeout(o,a))])}I();var Sb=3e3,Cb=k("session-end");async function br(e,a,o){let t=Fl(),i=[C(w.CLI_TUI_SESSION_ENDED,{duration_ms:t,active_tab:a,interface:"tui"})];o!=="main"&&i.push(Gi(e));try{await Ol(Promise.all(i).then(()=>{}),Sb);}catch(s){Cb.warn(`Session end event failed: ${String(s)}`);}}var Eb=2e3;function Gl(){let{exit:e}=useApp(),a=useRef(false),o=useRef(null),t=y(d=>d.pendingExit),r=y(d=>d.setPendingExit),i=y(d=>d.activeTab),s=y(d=>d.screen),n=useCallback(()=>{if(a.current){o.current&&clearTimeout(o.current),br("double-ctrl-c",i,s).finally(()=>e());return}a.current=true,r(true),o.current=setTimeout(()=>{a.current=false,r(false);},Eb);},[e,r,i,s]);return useInput((d,l)=>{l.ctrl&&d==="c"&&n();}),{pendingExit:t}}var qb=16;function Bl({label:e,value:a,onChange:o,masked:t=false,isActive:r,error:i}){let s=useRef(a);useEffect(()=>{s.current=a;},[a]),useInput((d,l)=>{if(l.backspace){let c=s.current.slice(0,-1);s.current=c,o(c);}else if(d&&!l.ctrl&&!l.meta&&!l.escape&&!l.return&&!l.tab&&!l.upArrow&&!l.downArrow&&!l.leftArrow&&!l.rightArrow){let c=s.current+d;s.current=c,o(c);}},{isActive:r});let n=t?"\u2022".repeat(a.length):a;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u25B8 ":" "}),jsx(Text,{color:r?"white":"gray",bold:r,children:e.padEnd(qb)}),jsx(Text,{color:r?"cyan":"gray",children:n}),r&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}U();function jl({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="n"||d==="N"){o("input");return}(d==="y"||d==="Y"||l.return)&&e(null);return}if(l.escape){n.current="",r(""),s(false),o("confirm");return}if(l.return){let c=n.current.trim();yt.test(c)?(s(false),e(c)):s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[a==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:kt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}U();function Ul({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[ho," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}U();function zl(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[ho," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var oa=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:a=>e({credentials:a,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:a=>e({justAuthenticated:a})}));Oi();U();function at(){return ne__default.join(Ce__default.homedir(),".claude","settings.json")}function Jl(e){return `${(e&&e.trim().length>0?e.trim():pi).replace(/\/+$/,"")}/flow-litellm/`}function Sr(){let e=at();if(!ie__default.existsSync(e))return {status:"missing"};let a=ie__default.readFileSync(e,"utf-8"),o=a.charCodeAt(0)===65279?a.slice(1):a;try{let t=JSON.parse(o);return t===null||typeof t!="object"||Array.isArray(t)?{status:"malformed",raw:a}:{status:"ok",settings:t}}catch{return {status:"malformed",raw:a}}}function ji(e){let a=at();ie__default.mkdirSync(ne__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`;ie__default.writeFileSync(o,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,a);}function Hl(e,a,o){let t=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...t,ANTHROPIC_AUTH_TOKEN:a,ANTHROPIC_BASE_URL:o}}}function rd(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_AUTH_TOKEN;return typeof o=="string"&&o.length>0?o:null}function Vl(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.length>0?o:null}var jb=3600,ot=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Cr(e){let a=e.split(".");if(a.length!==3)throw new Error("Malformed JWT: invalid format");let o;try{o=JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Malformed JWT: payload must be a JSON object");let t=o;if(typeof t.clientId!="string"||!t.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(t.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof t.clientSecret!="string"||!t.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(t.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof t.tenant!="string"||!t.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(t.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant}}function Ub(e){return Bb.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:jb})}function Ui(e,a={}){let o=Sr();if(o.status==="malformed"&&!a.allowOverwriteMalformed)throw new ot;let t=o.status==="ok"?o.settings:{},r=o.status==="ok"?rd(o.settings):null,i=o.status==="ok"?Vl(o.settings):null,s=a.jwtOverride??Ub(e),n=Jl(e.customUrl),d=Hl(t,s,n);return {jwt:s,anthropicBaseUrl:n,merged:d,previousToken:r,previousBaseUrl:i,hadExistingFile:o.status!=="missing"}}function zi(e){ji(e.merged);}function Ql(){let e=Sr();return e.status!=="ok"?false:rd(e.settings)!==null}Re();Oe();function zb(){let e=dl();if(!ie__default.existsSync(e))return {};try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return {}}}var id=null;function Wb(){return id===null&&(id=zb()),id}function Ao(){return !!Wb().ENABLE_EXPERIMENTAL_BETAS}U();function Qb(){return de.filter(e=>e.platforms[process.platform]?.status==="supported")}function Xl(e){let a=Qb();return a.length>0&&a.every(o=>e.find(t=>t.module.alias===o.alias)?.alreadyInstalled===true)}var Wi={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=ne__default.join(Ce__default.homedir(),".claude","settings.json"),o=ie__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),r=JSON.parse(o).env;return typeof r=="object"&&r!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in r}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let a=["flow-ai-obs","init","--no-interactive"];if(a.push("--custom-url",e.customUrl??pi),e.credentials){let{clientId:o,clientSecret:t,tenant:r}=e.credentials;a.push("--client-id",o,"--client-secret",t,"--tenant",r);}return e.customEmail&&a.push("--custom-email",e.customEmail),[a]},onDemand:null,mode:"non-interactive"}},_b={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard",tap:"FlorianBruniaux/tap"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},de=Ao()?[Wi,_b]:[Wi];Re();I();var Yb=k("moduleState");function Hi(){let e=process.env.FLOW_HOME??ne__default.join(Ce__default.homedir(),".flow");return ne__default.join(e,"modules.json")}var Zb={retries:5,minTimeout:50};async function Kl(e,a){ie__default.mkdirSync(ne__default.dirname(e),{recursive:true});let o=await $b.lock(e+".lock",{realpath:false,retries:Zb});try{return await a()}finally{await o();}}function $l(){let e=Hi();if(!ie__default.existsSync(e))return [];try{let a=JSON.parse(ie__default.readFileSync(e,"utf-8"));return a.schemaVersion!==1?(Yb.warn(`modules.json has unknown schemaVersion ${a.schemaVersion}, resetting`),ie__default.rmSync(e,{force:!0}),[]):Array.isArray(a.modules)?a.modules.map(o=>({...o,name:o.name??null})):[]}catch{return ie__default.rmSync(e,{force:true}),[]}}function tt(){return $l()}function Yl(e){let a=Hi();ie__default.mkdirSync(ne__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`,t={schemaVersion:1,modules:e};ie__default.writeFileSync(o,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,a);}function ta(e){return tt().find(a=>a.alias===e)??null}async function ka(e){let a=Hi();await Kl(a,async()=>{let o=$l(),t=o.findIndex(r=>r.alias===e.alias);t===-1?o.push(e):o[t]=e,Yl(o);});}async function rt(){let e=Hi();ie__default.existsSync(e)||await Kl(e,async()=>{ie__default.existsSync(e)||Yl([]);});}var ov=promisify(execFile);function xo(e,a){let o=e.platforms[process.platform];return !o||o.status!=="supported"?null:o.strategies.find(t=>t.type===a)??null}async function Ba(e){let a=process.platform==="win32"?"where":"which";try{return await ov(a,[e]),!0}catch{return false}}function eo(){return process.platform==="win32"?"npm.cmd":"npm"}var Zl=promisify(execFile),It=class{type="npm";async isAvailable(){return Ba("npm")}async install(a){let o=await this.getInstalledVersion(a);return o?{success:true,version:o,method:"npm",durationMs:0}:this.runNpmInstall(a,false)}async update(a,o){return this.runNpmInstall(a,true)}async getInstalledVersion(a){let o=xo(a,"npm");if(!o)return null;try{let{stdout:t}=await Zl(eo(),["list","-g",o.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(t).dependencies?.[o.package]?.version??null}catch{return null}}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(a,o){let t=Date.now(),r=xo(a,"npm");if(!r)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-t};let i=o?`${r.package}@latest`:r.package;try{return await Zl(eo(),["install","-g",i],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(a)??void 0,method:"npm",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}};var Vi=promisify(execFile),nv=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Qi=class{type="homebrew";async isAvailable(){return Ba("brew")}async install(a){return this.runBrewCommand(a,"install")}async update(a,o){return this.runBrewCommand(a,"upgrade")}async getInstalledVersion(a){let o=xo(a,"homebrew");return o?this.getVersionByFormula(o.formula):null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(a,o){let t=Date.now(),r=xo(a,"homebrew");if(!r)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-t};let i=o==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return r.tap&&(await Vi("brew",["tap",r.tap]),await Vi("brew",["trust",r.tap])),await Vi("brew",[o,r.formula]),{success:!0,version:await this.getVersionByFormula(r.formula)??void 0,method:"homebrew",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:i,message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}async getVersionByFormula(a){try{let{stdout:o}=await Vi("brew",["list","--versions",a]),t=o.trim().match(nv);return t?t[2]:null}catch{return null}}};var Tt=promisify(execFile),au=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function ou(){let e=process.env.FLOW_HOME??ne__default.join(Ce__default.homedir(),".flow");return ne__default.join(e,"bin")}var _i=class{type="curl";async isAvailable(){return Ba("curl")}async install(a){let o=Date.now(),t=xo(a,"curl");if(!t)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-o};let r=typeof t.url=="function"?t.url(process.arch):t.url;return (t.mode??"binary")==="script"?this.installScript(r,t.checksumUrl,a,o):this.installBinary(r,t.checksumUrl,a,o)}async update(a,o){return this.install(a)}async getInstalledVersion(a){let o=ne__default.join(ou(),ne__default.basename(a.binaryName));for(let t of [o,a.binaryName])try{let{stdout:r}=await Tt(t,["--version"]),i=r.match(au);if(i)return i[1]}catch{}return null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(a,o,t,r){if(!o)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${t.alias})`},durationMs:Date.now()-r};let i=ne__default.join(Ce__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Tt("curl",["-sSL","--fail","-o",i,a]),o){let n=await this.validateChecksum(i,o);if(!n.valid){try{ie__default.unlinkSync(i);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:n.message},durationMs:Date.now()-r}}}return ie__default.chmodSync(i,448),await Tt("bash",[i]),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"curl",durationMs:Date.now()-r}}catch(s){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-r}}finally{try{ie__default.unlinkSync(i);}catch{}}}async installBinary(a,o,t,r){let i=ou(),s=ne__default.join(i,ne__default.basename(t.binaryName)),n=false;try{if(ie__default.mkdirSync(i,{recursive:!0}),n=!0,await Tt("curl",["-L","--fail","-o",s,a]),o){let l=await this.validateChecksum(s,o);if(!l.valid)return ie__default.unlinkSync(s),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:l.message},durationMs:Date.now()-r}}ie__default.chmodSync(s,493);let d=null;try{let{stdout:l}=await Tt(s,["--version"]),c=l.match(au);d=c?c[1]:null;}catch{}return {success:!0,version:d??void 0,method:"curl",durationMs:Date.now()-r}}catch(d){if(n)try{ie__default.unlinkSync(s);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:d instanceof Error?d.message:String(d)},durationMs:Date.now()-r}}}async validateChecksum(a,o){let t=ne__default.join(Ce__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Tt("curl",["-L","--fail","-o",t,o]);let r=ie__default.readFileSync(t,"utf-8").trim().split(/\s+/)[0],i=ie__default.readFileSync(a),s=createHash("sha256").update(i).digest("hex");return s!==r?{valid:!1,message:`SHA256 mismatch: expected ${r}, got ${s}`}:{valid:!0,message:""}}catch(r){return {valid:false,message:`Checksum validation failed: ${String(r)}`}}finally{try{ie__default.unlinkSync(t);}catch{}}}};I();var tu="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(tu=e.version);}catch{}var ve=tu;var Te=k("moduleInstaller");function Ua(e){switch(e){case "npm":return new It;case "homebrew":return new Qi;case "curl":return new _i}}async function Rr(e,a,o){try{await C(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:o.code,error_message:o.message,trigger:a});}catch(t){Te.warn(`Failed to emit install failed event: ${String(t)}`);}}async function Io(e,a,o,t,r,i){let s=Date.now(),n=e.platforms[process.platform];if(!n)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-s};if(n.status==="experimental"){Te.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let u={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Rr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(n.status!=="supported"){let u={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Rr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(!n.strategies.some(u=>u.type===o)){let u={code:"STRATEGY_NOT_FOUND",message:`Strategy "${o}" is not configured for module "${e.alias}" on ${process.platform}`};return await Rr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}let d=Ua(o),l=false;try{l=await d.isAvailable();}catch(u){Te.warn(`${o} availability check failed: ${String(u)}`);}if(!l){let u={code:"STRATEGY_NOT_AVAILABLE",message:`"${o}" is not installed on this system`};return await Rr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}try{await C(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ve,trigger:a});}catch(u){Te.warn(`Failed to emit install started event: ${String(u)}`);}let c;try{c=i?.forceLatest?await d.update(e,"unknown"):await d.install(e);}catch(u){let m=u instanceof Error?u.message:String(u);Te.warn(`${o} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-s};}if(c.success){await ka({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await C(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:a});}catch(p){Te.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:u,failed:m}=await gv(e,a,t,r);return u?{...c,pendingInteractiveSetup:u}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Rr(e,a,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function gv(e,a,o,t){if(!e.postInstall)return {pendingCmd:null,failed:false};let r=a==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(r==null)return {pendingCmd:null,failed:false};let i;if(typeof r=="function"){let n=await Z(),d={credentials:n?{clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}:null,customUrl:o??null,customEmail:t??null};try{i=r(d);}catch(l){return Te.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else i=r;if(i.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:i[0]??null,failed:false};let s=false;for(let n=0;n<i.length;n++){let d=i[n];if(d.length===0)continue;let l=spawnSync(d[0],d.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,Te.warn(`postInstall "${d.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&Te.warn(l.stderr);let c=i.slice(n+1).filter(u=>u.length>0);c.length>0&&Te.debug(`continuing with remaining postInstall steps: ${c.map(u=>u.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function Xi(e,a){let o=Date.now(),t=ta(e.alias);if(!t?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-o};let r=Ua(t.installMethod),i=t.installedVersion??"unknown";if(a==="command")try{await C(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ve,trigger:"command"});}catch(n){Te.warn(`Failed to emit update started event: ${String(n)}`);}let s;try{s=await r.update(e,i);}catch(n){let d=n instanceof Error?n.message:String(n);Te.warn(`${t.installMethod} update threw: ${d}`),s={success:false,error:{code:"UPDATE_THREW",message:d},durationMs:Date.now()-o};}if(s.success)if(await ka({...t,installedVersion:s.version??t.installedVersion,lastChecked:new Date().toISOString()}),a==="command")try{await C(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:s.version??"unknown",duration_ms:s.durationMs,os:process.platform,trigger:"command"});}catch(n){Te.warn(`Failed to emit update completed event: ${String(n)}`);}else try{await C(w.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:i,to_version:s.version??"unknown",duration_ms:s.durationMs});}catch(n){Te.warn(`Failed to emit module updated event: ${String(n)}`);}else if(a==="command")try{await C(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:s.error?.code??"UNKNOWN",error_message:s.error?.message??"unknown error",trigger:"command"});}catch(n){Te.warn(`Failed to emit update failed event: ${String(n)}`);}return s}I();var Ki=k("flowAiObsSetup");async function $i(e,a){try{if(!await new It().isAvailable().catch(()=>!1))return Ki.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let r=await Io(Wi,"onboarding","npm",e,a,{forceLatest:!0});return r.success?r.postInstallFailed||r.configCheckFailed?(Ki.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Ki.warn(`flow-ai-obs install failed: ${r.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(o){return Ki.warn(`installFlowAiObs threw: ${String(o)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}I();function ru(e){if(!(e instanceof Error))return "unknown";let a=e.message.toLowerCase();return a.includes("401")||a.includes("unauthorized")?"invalid_credentials":a.includes("403")||a.includes("forbidden")?"forbidden":a.includes("timeout")||a.includes("timed out")?"timeout":a.includes("network")||a.includes("econnrefused")||a.includes("fetch")?"network_error":"unknown"}var fv=k("useAuthSetup");function iu(){let[e,a]=useState(""),o=useRef(null),t=useRef(null),r=useRef(null),[i,s]=useState(),[n,d]=useState(null),[l,c]=useState(false),[u,m]=useState("fields"),[p,f]=useState(null),g=useRef(0),h=useRef(false),{setCredentials:b,setJustAuthenticated:D}=oa(),q=()=>{m("fields"),f(null),a(""),o.current=null,t.current=null,r.current=null;},L=()=>{C(w.CLI_SESSION_STARTED,{cli_version:ve,os:process.platform,node_version:process.version,duration_ms:So(),interface:"tui"}).catch(()=>{});},A=async W=>{h.current=true;let X={...o.current,customUrl:t.current??void 0};try{W&&zi(W),await Do(X);}catch(V){d(V instanceof Error?V.message:"Failed to persist credentials"),q(),h.current=false;return}let{clientSecret:E,...j}=X;b(j),D(true),L(),await $i(t.current,r.current).catch(V=>fv.warn(`installFlowAiObs threw unexpectedly: ${String(V)}`)),Yi({starterKit:j.starterKit});},T=async()=>A(),F=async W=>A(W),O=W=>{try{let X={...o.current,customUrl:t.current??void 0};return Ui(X,{allowOverwriteMalformed:W,jwtOverride:e.trim()})}catch(X){return X instanceof ot?(m("malformedConfirm"),null):(d(X instanceof Error?X.message:"Failed to read settings.json"),m("fields"),null)}},oe=()=>{let W=O(true);W&&(f(W),F(W));},x=async()=>{let W=e.trim();if(!W){s("This field is required");return}let X;try{X=Cr(W);}catch(E){s(E instanceof Error?E.message:"Invalid JWT");return}s(void 0),o.current=X,m("customUrl");},J=W=>{t.current=W,m("email");},ae=W=>{r.current=W,z();},z=async()=>{let W=t.current;W&&Fa(W),c(true),d(null),g.current+=1;try{await Ko(o.current);let X=O(!1);X&&(f(X),m("preview"));}catch(X){let E=X instanceof Error?X.message:"Authentication failed";d(E),Ml(w.CLI_AUTH_FAILED,{error_code:ru(X),attempt:g.current},o.current.tenant).catch(()=>{}),a(""),o.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:i,authError:n,isSubmitting:l,step:u,plan:p,isCommittingRef:h,setJwtValue:a,setJwtError:s,cancelToFields:q,handleSubmit:x,goToEmailStep:J,handleEmailConfirm:ae,commitAndProceed:F,skipJwtAndProceed:T,planPersistOverwrite:oe}}U();B();function su(){let{jwtValue:e,jwtError:a,authError:o,isSubmitting:t,step:r,plan:i,isCommittingRef:s,setJwtValue:n,setJwtError:d,cancelToFields:l,handleSubmit:c,goToEmailStep:u,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:g}=iu(),[h,b]=useState("confirm"),[D,q]=useState(""),L=useRef(""),[A,T]=useState(false);return useEffect(()=>{r==="customUrl"&&(b("confirm"),L.current="",q(""),T(false));},[r]),useInput((F,O)=>{if(!(t||s.current)){if(r==="preview"){O.return&&i?p(i):O.escape?f():F==="q"&&l();return}if(r==="malformedConfirm"){O.return?g():O.escape&&l();return}if(r==="customUrl"){if(h==="confirm")F==="y"||F==="Y"?b("input"):(F==="n"||F==="N"||O.return)&&u(null);else if(O.escape)L.current="",q(""),b("confirm");else if(O.return){let oe=L.current.trim();oe.length>0&&bt.test(oe)?(T(false),u(oe)):oe.length>0&&T(true);}else O.backspace||O.delete?(L.current=L.current.slice(0,-1),q(L.current)):F&&!O.ctrl&&!O.meta&&(L.current=L.current+F,q(L.current),T(false));return}r!=="email"&&O.return&&c();}},{isActive:true}),r==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[ho," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!t&&h==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!t&&h==="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:D}),jsx(Text,{color:"cyan",children:"\u2588"})]}),A&&jsx(Text,{color:"red",children:vt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):r==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[ho," \u2014 Initial Setup"]})}),t?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(jl,{onConfirm:m})]}):r==="preview"&&i?jsx(Ul,{plan:i}):r==="malformedConfirm"?jsx(zl,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[ho," \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(Bl,{label:"JWT",value:e,onChange:F=>{n(F),a&&d(void 0);},masked:true,isActive:!t,error:a})})}),t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),o&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",v(o)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function qt(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(kv,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ve]})})]})}var lu=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],re=Ao()?lu:lu.slice(0,3);function Pv(e){return re.findIndex(a=>a.id===e)}function dd(e,a,o){let t=Pv(o.activeTab);if(a.rightArrow||a.tab){let r=re[(t+1)%re.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}if(a.leftArrow){let r=re[(t-1+re.length)%re.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}return a.downArrow?[{type:"setFocus",focus:re[t]?.focus??"list"}]:[]}var mu={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function gu({outdatedCount:e=0}){let a=y(o=>o.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:re.map(({id:o})=>{let t=o===a,r=o==="updates"&&e>0?`${mu[o]} (${e})`:mu[o];return jsx(Box,{marginRight:1,children:t?jsx(Text,{bold:true,inverse:true,children:` ${r} `}):jsx(Text,{dimColor:true,children:` ${r} `})},o)})})}var _e=create(e=>({query:"",cursorPosition:0,setQuery:a=>e({query:a}),setCursorPosition:a=>e({cursorPosition:a}),resetQuery:()=>e({query:"",cursorPosition:0})}));function hu(){let e=y(s=>s.focus),a=_e(s=>s.query),o=_e(s=>s.cursorPosition),t=e==="search",r=a.slice(0,o),i=a.slice(o);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:t?"cyan":"gray",children:"\u{1F50D} "}),t?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:r}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:a||"Search..."})]})}U();var bu=Object.keys(bo).map((e,a)=>({key:a<3?String(a+2):String((a+5)%10),type:e,...bo[e]})),vu=["internal","external"].map((e,a)=>({key:String(a+6),origin:e,...al[e]}));function yu(){let e=y(t=>t.catalogFilters),a=bu.every(t=>e.types.has(t.type)),o=vu.every(t=>e.origins.has(t.origin));return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,flexWrap:"wrap",children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:a?"green":void 0,dimColor:!a,children:[a?"\u25C9":"\u25CB"," All"]})]}),bu.map(t=>{let r=!a&&e.types.has(t.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:o?"green":void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," All"]})]}),vu.map(t=>{let r=!o&&e.origins.has(t.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)})]})}U();function ku({type:e}){let{label:a,color:o}=bo[e];return jsx(Text,{color:o,children:a})}U();function wu({origin:e}){return e===lr?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}B();var es=Av.memo(function({item:a,isSelected:o}){let t=a.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:a.name}),a.type&&jsxs(Text,{children:[" ",jsx(ku,{type:a.type})]}),a.origin&&jsxs(Text,{children:[" ",jsx(wu,{origin:a.origin})]}),jsxs(Text,{dimColor:true,children:[a.authorName?` \xB7 ${a.authorName}`:"",a.version?` \xB7 v${a.version}`:" \xB7 n/a"]}),a.status&&jsxs(Text,{color:t,children:[" [",a.status,"]"]}),a.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),a.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",La(a.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:a.description})})]})});function Lt({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}U();function Ru({items:e,emptyMessage:a}){let o=y(d=>d.selectedIndex);if(e.length===0)return jsx(Lt,{message:a});let t=Math.max(0,o-Math.floor(ea/2)),r=Math.min(e.length,t+ea);r===e.length&&(t=Math.max(0,r-ea));let i=e.slice(t,r),s=t,n=e.length-r;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((d,l)=>jsx(es,{item:d,isSelected:t+l===o},d.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:n>0?`\u2193 ${n} more below`:" "})})]})}function Eu({label:e,pathHint:a}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",a]})]})}U();function Tu({groups:e,emptyMessage:a}){let o=y(p=>p.selectedIndex),t=[],r=0;for(let p of e){t.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)t.push({kind:"item",item:f,itemIndex:r,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),r++;}if(r===0)return jsx(Lt,{message:a});let s=t.findIndex(p=>p.kind==="item"&&p.itemIndex===o),n=s>=0?s:0,d=Math.max(0,n-Math.floor(ea/2)),l=Math.min(t.length,d+ea);l===t.length&&(d=Math.max(0,l-ea));let c=t.slice(d,l),u=d,m=t.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:u>0?`\u2191 ${u} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Eu,{label:p.label,pathHint:p.pathHint},p.key):jsx(es,{item:p.item,isSelected:p.itemIndex===o},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var Fv={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Ov({items:e,tabId:a,emptyMessage:o,groups:t,actionHint:r}){return jsxs(Box,{flexDirection:"column",children:[jsx(hu,{}),jsx(yu,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Fv[a]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),r&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${r}`})]}),t&&t.length>0?jsx(Tu,{groups:t,emptyMessage:o}):jsx(Ru,{items:e,emptyMessage:o})]})}function Mu({filteredItems:e,emptyMessage:a,groups:o,onBatchUpdate:t}){let r=y(d=>d.activeTab),i=y(d=>d.focus);return useInput(d=>{d==="a"&&e.length>0&&t?.();},{isActive:r==="updates"&&i==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Ov,{items:e,tabId:r,emptyMessage:a,groups:r!=="discover"?o:void 0,actionHint:r==="updates"?"press 'a' to update all":void 0},r)})}var Bv={tabs:"\u2190\u2192: switch tab | \u2193: navigate | Enter: select | Ctrl+C Ctrl+C: quit",list:"\u2191\u2193: navigate | Enter: select | Type: 1=All 2=Skill 3=MCP 4=Bundle | Origin: 5=All 6=Flow 7=External | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",search:"Type to filter | \u2193/Esc: exit search | Enter: confirm",actionMenu:"\u2191\u2193: navigate options | Enter: confirm | Esc: close menu",auth:"Tab: next field | Enter: confirm | Ctrl+C Ctrl+C: quit",starterKitList:"\u2191\u2193: navigate | Enter: select Starter Kit | Esc: skip",starterKitDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select",moduleSetup:"\u2191\u2193: navigate | Space: toggle | Tab: change method | Enter: confirm",marketplaces:"\u2191\u2193: navigate | a: add catalog | d: remove catalog | r: refresh | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",verify:"\u2191\u2193: navigate | Enter: confirm | Ctrl+C Ctrl+C: quit",bundleInstallProgress:"Enter/Esc: back to catalog"};function as(){let e=y(o=>o.focus),a=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[Bv[e],a?" | Ctrl+D: debug log":""]})})}B();function qu({message:e,type:a}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:a==="success"?"green":a==="info"?"cyan":"red",children:[a==="success"?"\u2713":a==="info"?"(i)":"\u2717"," ",v(e)]})}):null}function os({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(_p,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function fd(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Nu=20;function ts(e,a){let o=a>0?Math.min(e/a,1):0,t=Math.round(o*100),r=Math.round(o*Nu),i="\u2588".repeat(r)+"\u2591".repeat(Nu-r),s=`${fd(e)} / ${fd(a)}`;return {bar:i,percent:t,label:s}}function rs({received:e,total:a}){let{bar:o,percent:t,label:r}=ts(e,a);return jsxs(Text,{dimColor:true,children:[o," ",t,"%"," ","(",r,")"]})}function is({message:e,onRetry:a,onBack:o}){return useInput((t,r)=>{t==="r"&&r.ctrl&&a?a():r.escape&&o&&o();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),a&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),o&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ra({itemName:e,actions:a,descriptions:o,onAction:t,onClose:r}){let i=y(d=>d.focus),[s,n]=useState(0);return useInput((d,l)=>{l.upArrow?n(c=>c>0?c-1:c):l.downArrow?n(c=>c<a.length-1?c+1:c):l.return?t(a[s]):l.escape&&r();},{isActive:i==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:a.map((d,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",d]}),o?.[d]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",o[d]]})]},l))})]})}U();var yd=Object.entries(qa),Uu=[...yd.map(([,e])=>e.actionLabel),"Cancel"],zu=Object.fromEntries(yd.map(([,e])=>[e.actionLabel,e.description]));function Wu(e){let a=yd.find(([,o])=>o.actionLabel===e);return a?a[0]:null}I();var ey=k("provider.registry"),ay=3e4,ns=class{adapters=new Map;availabilityCache=new Map;register(a){this.adapters.set(a.id,a);}async checkAvailability(a){let o=this.availabilityCache.get(a.id);if(o&&Date.now()<o.expiresAt)return o.result;let t=await a.isAvailable();return this.availabilityCache.set(a.id,{result:t,expiresAt:Date.now()+ay}),t}async getAvailableProviders(a){let o=[...this.adapters.values()].filter(r=>a in r.installers),t=await Promise.allSettled(o.map(r=>this.checkAvailability(r)));return t.forEach((r,i)=>{r.status==="rejected"&&ey.warn(`Provider "${o[i].id}" isAvailable() threw: ${String(r.reason)}`);}),o.filter((r,i)=>{let s=t[i];return s.status==="fulfilled"&&s.value===true})}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};var oy={user:"global",project:"project",local:"local"};function ds(e){return e?oy[e]:"global"}var Xe=class extends Error{constructor(o,t){super(`${o} v${t} is already installed. Use --force to reinstall.`);this.pluginName=o;this.version=t;this.name="AlreadyInstalledError";}pluginName;version},Mo=class extends Error{constructor(o,t){super(`${o} is already up to date (v${t})`);this.pluginName=o;this.version=t;this.name="AlreadyUpToDateError";}pluginName;version};Ir();kd();I();var iy=k("catalog.registry"),cs=class{adapters=new Map;register(a){this.adapters.set(a.id,a);}unregister(a){this.adapters.delete(a);}async fetchAllWithErrors(){let a=this.listAdapters(),o=await Promise.allSettled(a.map(i=>i.fetchItems())),t=[],r=[];for(let i=0;i<o.length;i++){let s=o[i],n=a[i];if(s.status==="fulfilled")t.push(...s.value);else {let d=String(s.reason);iy.warn(`Catalog adapter failed: ${d}`),r.push({adapterId:n.id,adapterName:n.name,reason:d});}}return {items:t,failures:r}}async fetchAll(){let{items:a}=await this.fetchAllWithErrors();return a}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};Oe();var my={retries:5,minTimeout:50};async function Pd(e,a){mkdirSync(dirname(e),{recursive:true});let o=await $b.lock(e+".lock",{realpath:false,retries:my});try{return await a()}finally{await o();}}var ls=class{filePath;constructor(a){this.filePath=a??nl();}async read(){try{let a=await readFile(this.filePath,"utf-8");return JSON.parse(a).catalogs??[]}catch(a){if(a.code==="ENOENT")return [];throw a}}async write(a){let o=dirname(this.filePath);await mkdir(o,{recursive:true});let t=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(t,JSON.stringify({catalogs:a},null,2),"utf-8"),await rename(t,this.filePath);}async add(a){await Pd(this.filePath,async()=>{let o=await this.read();if(o.some(r=>r.id===a.id))return;let t={...a,lastUpdated:a.lastUpdated??new Date().toISOString()};await this.write([...o,t]);});}async remove(a){if(a==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await Pd(this.filePath,async()=>{let o=await this.read();await this.write(o.filter(t=>t.id!==a));});}async updateField(a,o){await Pd(this.filePath,async()=>{let t=await this.read();t.some(r=>r.id===a)&&await this.write(t.map(r=>r.id===a?{...r,...o}:r));});}};wd();var ge=new cs,oo=new ls,wy=["flow-harness"];function Sy(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?wy:e.split(",").map(a=>a.trim()).filter(Boolean)}ge.register(new Ut);for(let e of Sy())ge.register(new Ut(e));var ap=false;async function op(){if(ap)return;ap=true;let e=await oo.read(),{GitRepoAdapter:a}=await Promise.resolve().then(()=>(Sd(),ep));for(let o of e)ge.register(new a(o.id,o.name,o.source));}qo();function tp(e){if(e===void 0||!Number.isFinite(e)||e<=0)return 3e4;let a=e/131072*1e3;return Math.min(6e5,Math.max(3e4,Math.ceil(a)))}I();var Ry=k("api:actions"),rp=2;async function to(e){if(e){let{FlowApiAdapter:a}=await Promise.resolve().then(()=>(wd(),_u));return new a(e).fetchItems()}return ge.fetchAll()}async function ip(){return ge.fetchAllWithErrors()}async function Wt(e,a){Tr(e);try{return await Ot(`v1/plugins/${e}/manifest`,a).json()}catch(o){let t=await Nt(o);throw t?new Error(t):o instanceof Error?o.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):o.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${o.message}`):o}}async function Ay(e,a){try{let t=(await Hu(`v1/plugins/${e}/archive`,{source:a,timeoutMs:3e4})).headers.get("x-archive-size"),r=t?Number(t):NaN;return Number.isFinite(r)&&r>0?r:void 0}catch(o){Ry.debug(`[${e}] Archive size probe failed, using default timeout: ${String(o)}`);return}}async function sp(e,a,o){Tr(e);try{let t=await Ay(e,o),r=tp(t),i=await Ot(`v1/plugins/${e}/archive`,o,r),s=i.headers.get("x-archive-size"),n=s?Number(s):NaN,d=Number.isFinite(n)&&n>0?n:0,l=d>0,c=i.body;if(!c)throw new Error("Failed to download plugin: response has no body");let u=c.getReader(),m=[],p=0;for(;;){let{done:f,value:g}=await u.read();if(f)break;if(p+=g.byteLength,l&&p>d*rp)throw await u.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${d*rp}`);m.push(g),l&&a?.(p,d);}return Buffer.concat(m)}catch(t){if(t instanceof Error&&t.message.includes("Download exceeded expected size"))throw t;let r=await Nt(t);throw r?new Error(r):t instanceof Error?new Error(`Failed to download plugin: ${t.message}`):t}}async function ps(){try{let{profiles:e}=await za().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}}Oe();Oe();async function np(e,a){let o=ne.resolve(a);await Wa.mkdir(o,{recursive:true});let t=ne.join(ne.dirname(o),`${randomUUID()}.zip`);try{await Wa.writeFile(t,e);let r=await Ey.Open.file(t),i=ne.normalize(o+ne.sep);for(let s of r.files){if((s.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${s.path}" is a symbolic link and was rejected`);let d=ne.resolve(o,s.path);if(process.platform==="win32"&&d.length>=260)throw new Error(`Path too long: "${d}" (${d.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!d.startsWith(i)&&d!==o)throw new Error(`Zip Slip detected: entry "${s.path}" would escape target directory`)}await r.extract({path:o});try{let s=realpathSync(o);if(!s.startsWith(ne.resolve(ne.dirname(o))))throw new Error(`Zip Slip (post-extract): resolved path "${s}" is outside expected parent`)}catch(s){if(s.code!=="ENOENT")throw s}}finally{try{await Wa.unlink(t);}catch{}}}async function Cd(e){await Wa.rm(e,{recursive:true,force:true});}async function Lo(){let e=il();await Wa.mkdir(ne.dirname(e),{recursive:true});try{await Wa.writeFile(e,"",{flag:"wx"});}catch(o){if(o.code!=="EEXIST")throw o}return await $b.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}Oe();U();function My(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||ue,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function lp(e){let a=hi(e);if(!ie__default.existsSync(a))return null;try{return JSON.parse(ie__default.readFileSync(a,"utf-8"))}catch{return null}}function qy(e){let a=lp(e);if(a)return a;let o=My(e),t=hi(e);return ie__default.mkdirSync(ne__default.dirname(t),{recursive:true}),Rd(o,e),o}function Rd(e,a){let o=hi(a),t=`${o}.${randomUUID()}.tmp`;ie__default.writeFileSync(t,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(t,o);}function Ly(e){let a=e||ue,o=Ho(),t={};try{ie__default.existsSync(o)&&(t=JSON.parse(ie__default.readFileSync(o,"utf-8")));}catch{t={};}if(t[a])return;t[a]={source:{source:"github",repo:`cit-flow/${a}`},installLocation:rl(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let r=`${o}.${randomUUID()}.tmp`;ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(r,o);}function up(e,a,o){ia(e.name),Ly(o);let t=Sn(e.name,o);ie__default.mkdirSync(ne__default.dirname(t),{recursive:true});try{ie__default.lstatSync(t),ie__default.rmSync(t,{recursive:!0,force:!0});}catch{}ie__default.cpSync(a,t,{recursive:true,dereference:true});let r=qy(o);r.plugins.some(s=>s.name===e.name)||(r.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Rd(r,o));}function Ad(e,a){ia(e);let o=Sn(e,a);try{ie__default.rmSync(o,{recursive:!0,force:!0});}catch{}let t=lp(a);if(!t)return;let r=t.plugins.length;t.plugins=t.plugins.filter(i=>i.name!==e),t.plugins.length!==r&&Rd(t,a);}B();I();var Oy=k("mcpConfigReader"),Ny=500,Gy=512;function By(){return ne__default.join(Ce__default.homedir(),".claude.json")}function jy(){return ne__default.join(process.cwd(),".mcp.json")}function mp(e){if(!ie__default.existsSync(e))return null;try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return Oy.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Mr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xd(e){if(!Mr(e))return {};let a=e.mcpServers;return Mr(a)?a:{}}function Ed(e,a){return Object.keys(e).slice(0,Ny).map(t=>({name:v(t.slice(0,Gy)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:a,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function fp(){let e=[],a=By(),o=mp(a);if(Mr(o)){let n=o,d=xd(n);e.push(...Ed(d,"user"));let l=process.cwd();if(Mr(n.projects)){let c=n.projects[l];if(Mr(c)){let u=xd(c);e.push(...Ed(u,"local"));}}}let t=jy(),r=mp(t),i=xd(r);e.push(...Ed(i,"project"));let s=new Map;for(let n of e){let d=`${n.name}@${n.scope}`;s.has(d)||s.set(d,n);}return [...s.values()]}I();var sa=k("storage");async function zy(e,a,o){try{await C(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:o,source:a,interface:ee().interfaceType});}catch(t){sa.warn(`Failed to send uninstall metrics: ${String(t)}`);}}function Wy(e,a,o){let t=a==="enabled"?w.CLI_TOOL_ENABLED:w.CLI_TOOL_DISABLED;C(t,{tool_id:e,source:o,interface:ee().interfaceType}).catch(r=>sa.warn(`Failed to send ${a} metrics: ${String(r)}`));}function qd(){return ne__default.join(Ce__default.homedir(),".claude","plugins","installed_plugins.json")}function Jy(){return ne__default.join(Ce__default.homedir(),".claude","plugins")}function ms(e){let a;try{a=ie__default.realpathSync(e);}catch{a=ne__default.resolve(e);}let o=ne__default.resolve(Jy()),t=ne__default.resolve(ne__default.join(process.cwd(),".claude","plugins")),r=a.startsWith(o+ne__default.sep),i=a.startsWith(t+ne__default.sep);if(!r&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function bp(e="user"){return e==="local"?ne__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?ne__default.join(process.cwd(),".claude","settings.json"):ne__default.join(Ce__default.homedir(),".claude","settings.json")}function Ae(){let e=qd();if(!ie__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Ld(){let e=qd();try{let a=await ie__default.promises.readFile(e,"utf-8");return JSON.parse(a)}catch{return {version:2,plugins:{}}}}function Hy(e){let a=e?.code;return a==="EACCES"||a==="EPERM"}function vp(e,a){try{ie__default.mkdirSync(ne__default.dirname(e),{recursive:!0});let o=`${e}.${randomUUID()}.tmp`;ie__default.writeFileSync(o,JSON.stringify(a,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,e);}catch(o){throw Hy(o)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):o}}function na(e){vp(qd(),e);}function qr(e){let a=e.lastIndexOf("@");return a===-1?{name:e,marketplace:""}:{name:e.slice(0,a),marketplace:e.slice(a+1)}}function Vy(e,a){let o=ne__default.join(e,".claude-plugin"),t=ne__default.join(o,"plugin.json");if(ie__default.existsSync(t))try{return JSON.parse(ie__default.readFileSync(t,"utf-8"))}catch{return null}let r=ne__default.join(o,"marketplace.json");if(ie__default.existsSync(r))try{let i=JSON.parse(ie__default.readFileSync(r,"utf-8"));return {description:i.plugins?.find(n=>n.name===a)?.description,author:i.owner}}catch{return null}return null}function Lr(e="user"){let a=bp(e);if(!ie__default.existsSync(a))return {};try{return JSON.parse(ie__default.readFileSync(a,"utf-8"))}catch{return {}}}function gs(e,a="user"){vp(bp(a),e);}function Qy(e,a){let{name:o,marketplace:t}=qr(e),r;if(t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>qr(s).name===o)[0],!r)throw sa.error(`[${o}] Plugin is not installed`),new Error(`Plugin '${o}' is not installed`);return {key:r,name:o}}function _y(e,a){let{name:o,marketplace:t}=qr(e),r;return t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>qr(s).name===o)[0],r?{key:r,name:o}:null}function Id(e="user"){return Lr(e).enabledPlugins??{}}function Td(e,a="user"){let o=Lr(a),t=o.enabledPlugins;if(!t||!(e in t))return;let{[e]:r,...i}=t;o.enabledPlugins=i,gs(o,a);}function Fr(e,a,o="user"){let t=Lr(o),r=t.enabledPlugins??{};t.enabledPlugins={...r,[e]:a},gs(t,o);}function Xy(e){let a=new Map;for(let o of e){let t=o.projectPath?`${o.scope}:${o.projectPath}`:o.scope,r=a.get(t);(!r||o.installedAt>r.installedAt)&&a.set(t,o);}return [...a.values()]}function ce(){let e=Ae(),a=Id(),o=Id("project"),t=Id("local"),r={project:o,local:t},i=Object.entries(e.plugins).flatMap(([l,c])=>{let{name:u,marketplace:m}=qr(l),p=c.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return Xy(p).map(g=>{let h=Vy(g.installPath,u),D=(r[g.scope]??a)[l];return {name:u,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:D===false?"disabled":"enabled"}})}),s=fp(),n=new Set(i.map(l=>`${l.name}@${l.scope}`)),d=s.filter(l=>!n.has(`${l.name}@${l.scope}`));return [...i,...d]}function hp(e){let a=e.lastIndexOf("@");return a>0?e.slice(a+1):void 0}async function Or(e,a){sa.debug(`[${e}] Acquiring lock to uninstall`);let o=await Lo();try{let t=Ae(),r=_y(e,t.plugins);if(!r)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:i,name:s}=r,n=t.plugins[i];if(a){let d=n.find(u=>u.scope===a);if(!d)throw new Error(`Plugin '${s}' is not installed in ${a} scope`);sa.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),ms(d.installPath);let l=ne__default.dirname(d.installPath);ms(l),sa.debug(`[${s}] Removing directory: ${l}`),ie__default.rmSync(l,{recursive:!0,force:!0});let c=n.filter(u=>u.scope!==a);if(c.length===0){let{[i]:u,...m}=t.plugins;na({...t,plugins:m}),Td(i,a),Ad(s,hp(i));}else t.plugins[i]=c,na(t),Td(i,a);}else {sa.debug(`[${s}] Resolved key: ${i}`);for(let c of n){ms(c.installPath);let u=ne__default.dirname(c.installPath);ms(u),sa.debug(`[${s}] Removing directory: ${u}`),ie__default.rmSync(u,{recursive:!0,force:!0}),Td(i,c.scope);}Ad(s,hp(i));let{[i]:d,...l}=t.plugins;na({...t,plugins:l});}await zy(s,n[0].origin??"internal",n[0].type??"skill"),sa.debug(`[${s}] Uninstalled successfully`);}finally{await o();}}async function Nr(e,a,o){sa.debug(`[${e}] Acquiring lock to set status \u2192 ${a}`);let t=await Lo();try{let r=Ae(),{key:i,name:s}=Qy(e,r.plugins),n=r.plugins[i],d=o??n[0].scope,l=n[0].origin??"internal";sa.debug(`[${s}] Resolved key: ${i}, scope: ${d}`),Fr(i,a==="enabled",d),Wy(s,a,l),sa.debug(`[${s}] Status updated to ${a}`);}finally{await t();}}Oe();function Fd(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([a],[o])=>a.localeCompare(o)).map(([a,o])=>[a,Fd(o)]))}function Gr(e,a){let o={...e};for(let[t,r]of Object.entries(a)){let i=o[t];if(Array.isArray(r)&&Array.isArray(i)){let s=new Set(i.map(n=>JSON.stringify(Fd(n))));o[t]=[...i,...r.filter(n=>!s.has(JSON.stringify(Fd(n))))];}else r!==null&&typeof r=="object"&&!Array.isArray(r)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?o[t]=Gr(i,r):o[t]=r;}return o}I();var Od=k("bundleContent"),fs="${CLAUDE_PLUGIN_ROOT}/hooks/";function Ky(e){return e.split(fs).join("$CLAUDE_PROJECT_DIR/.claude/hooks/")}function Nd(e){return typeof e=="string"?Ky(e):Array.isArray(e)?e.map(Nd):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Nd(o)])):e}function $y(e,a){let o=ne__default.join(e,"rules");if(!ie__default.existsSync(o))return 0;let t=ie__default.readdirSync(o).filter(i=>i.endsWith(".md")&&ie__default.lstatSync(ne__default.join(o,i)).isFile());if(t.length===0)return 0;let r=Dt(a);ie__default.mkdirSync(r,{recursive:true});for(let i of t)ie__default.copyFileSync(ne__default.join(o,i),ne__default.join(r,i));return t.length}function Yy(e,a){let o=ne__default.join(e,"hooks","hooks.json");if(!ie__default.existsSync(o))return 0;let t;try{t=JSON.parse(ie__default.readFileSync(o,"utf-8"));}catch(f){return Od.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(f)}`),0}let r=t.hooks;if(!r||typeof r!="object"||Array.isArray(r))return 0;let i=ne__default.join(e,"hooks"),s=Rn(a),n=new Set,d=f=>{if(typeof f=="string"&&f.includes(fs)){let g=f.slice(f.indexOf(fs)+fs.length),h=/^([^"'\s]+)/.exec(g);h&&n.add(h[1]);}else Array.isArray(f)?f.forEach(d):f!==null&&typeof f=="object"&&Object.values(f).forEach(d);};d(r);let l=0;if(n.size>0){ie__default.mkdirSync(s,{recursive:true});for(let f of n){let g=ne__default.join(i,f);ie__default.existsSync(g)&&(ie__default.copyFileSync(g,ne__default.join(s,f)),l++);}}let c=Nd(r),u=Lr(a),m=u.hooks!==null&&typeof u.hooks=="object"&&!Array.isArray(u.hooks)?u.hooks:{},p=Gr(m,c);return gs({...u,hooks:p},a),l}function yp(e,a){let o=$y(e,a),t=Yy(e,a);o>0&&Od.debug(`Copied ${o} rule file(s) to ${Dt(a)}`),t>0&&Od.debug(`Copied ${t} hook script(s) to ${Rn(a)}`);}U();I();var Zy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,ek=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ia(e){if(!Zy.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function ak(e){if(!ek.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 Oo=k("installer");function ok(e,a,o){let t=`${e}@${o||ue}`,i=Ae().plugins[t];if(i&&!a)throw new Xe(e,i[0].version??"unknown");return {pluginKey:t,alreadyInstalled:i}}async function tk(e,a,o){o&&await Cd(a);try{Oo.debug(`[${a}] Extracting archive...`),await np(e,a);}catch(t){throw await Cd(a),t}}function rk(e,a,o,t,r,i="claude-code",s){let n=Ae(),d={scope:t,...t==="user"?{}:{projectPath:process.cwd()},installPath:a,version:o,installedAt:new Date().toISOString(),origin:r,providerId:i,type:s},l=n.plugins[e]??[];n.plugins[e]=[...l.filter(c=>c.scope!==t),d],na(n),Fr(e,true,t);}async function ik(e,a,o,t,r,i){try{await C(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:i,source:r,scope:t,version:a,duration_ms:o,interface:ee().interfaceType});}catch(s){Oo.warn(`Failed to send install metrics: ${String(s)}`);}}async function sk(e,a,o,t){try{await C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:t,source:o,error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:ee().interfaceType});}catch(r){Oo.warn(`Failed to send install-failed metrics: ${String(r)}`);}}async function je(e,a={}){let o=Date.now(),t=null;try{Oo.debug(`[${e}] Acquiring lock...`),t=await Lo();let{pluginKey:r,alreadyInstalled:i}=ok(e,a.force,a.source),{source:s}=a;Oo.debug(`[${e}] Fetching manifest...`);let n=await Wt(e,s);ia(n.name),ak(n.version),Oo.debug(`[${e}] Downloading archive...`);let d=await sp(e,a.onDownloadProgress,s),l=a.scope??"user",c=a.type??"skill",u=tl(n.name,n.version,a.source);await tk(d,u,!!i&&!!a.force),yp(u,l),rk(r,u,n.version,l,"internal",a.providerId,c),up(n,u,a.source);let m=Date.now()-o;Oo.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:n.name,version:n.version,path:u,duration_ms:m};return a.skipMetrics||await ik(n.name,n.version,m,ds(l),"internal",c),p}catch(r){throw await sk(e,r,"internal",a.type??"skill"),Oo.error(`[${e}] Installation failed: ${r instanceof Error?r.message:String(r)}`),r}finally{t&&await t();}}I();B();Re();xt();I();var nk=k("commands:helpers");async function he(){let e=await Z();if(!e)return S("Not authenticated. Run: flow auth login"),false;e.customUrl&&Fa(e.customUrl);try{await Na();}catch(a){return nk.debug(`Token validation failed: ${String(a)}`),S("Session expired. Run: flow auth login"),false}return true}async function _(e){let a=Bd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(v(e),t=>{a.close(),o(["y","yes"].includes(t.toLowerCase().trim()));});})}async function Jt(e){let a=Bd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(v(e),t=>{a.close(),o(t.trim());});})}var dk="\x1B[A",ck="\x1B[B";function kp(e,a){let o=a?R.cyan("\u276F"):" ",t=a?R.cyan(e.label):e.label,r=e.description?R.dim(` \u2014 ${e.description}`):"";return ` ${o} ${t}${r}`}function lk(e,a){return e.map((o,t)=>kp(o,t===a)).join(`
|
|
111
|
+
`)}async function hs(e,a){if(a.length===0)throw new Error("selectPrompt requires at least one option");return new Promise((o,t)=>{let r=0;process.stdout.write(`${v(e)}
|
|
112
|
+
`),process.stdout.write(lk(a,r));let i="",s=c=>{if(i+=c,i===""){d(),t(new Error("SIGINT"));return}if(i==="\r"||i===`
|
|
113
113
|
`){d(),process.stdout.write(`
|
|
114
|
-
`),o(a[r].value);return}if(i===
|
|
115
|
-
`);}function d(){process.stdin.setRawMode(false),process.stdin.removeListener("data",s),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",s);})}
|
|
116
|
-
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!r))throw new Error("No marketplace source provided. Cannot retry install.");r=ss(r),o?.(),Ht.debug(`[${t}] Adding marketplace via: claude plugin marketplace add ${r}`);try{let i=await execa("claude",["plugin","marketplace","add",r],{reject:!1});if(i.exitCode!==0)throw new Error(`Failed to add marketplace: ${i.stderr||"unknown error"}`);Ht.debug(`[${t}] Marketplace added successfully`);}catch(i){throw Gd(i)?new ps:i}}To();U();Oe();I();var kk=6e4,Oo=class extends Error{url;isTimeout;isAuthError;constructor(a,o,t=false,r=false){super(a),this.name="GitCloneError",this.url=o,this.isTimeout=t,this.isAuthError=r;}};async function Sa(e,a){let o=await mkdtemp(join(tmpdir(),"flow-skills-")),t=simpleGit({timeout:{block:kk}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),r=a?["--depth","1","--branch",a]:["--depth","1"];try{return await t.clone(e,o,r),o}catch(i){await rm$1(o,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),n=s.includes("block timeout")||s.includes("timed out"),d=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw n?new Oo("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):d?new Oo(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Oo(`Failed to clone ${e}: ${s}`,e,false,false)}}async function Ca(e){let a=normalize(resolve(e)),o=normalize(resolve(tmpdir()));if(!a.startsWith(o+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm$1(e,{recursive:true,force:true});}async function ct(e,a=["--version"]){try{return (await execa(e,a,{reject:!1})).exitCode===0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return false;throw o}}function Dk(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function wk(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Sk(e){return typeof e=="object"&&e!==null&&e.source==="github"}function lt(e,a){let o=e.source;if(Dk(o)){let t=o.path?o.path.replace(/^\.\//,""):".",r=o.ref&&!/^[0-9a-f]{40}$/i.test(o.ref)?o.ref:void 0;return {cloneUrl:o.url,subPath:t||".",ref:r}}if(wk(o))return {cloneUrl:o.url,subPath:"."};if(Sk(o))return {cloneUrl:`https://github.com/${o.repo}`,subPath:"."};if(typeof o=="string"){if(o.startsWith("https://")||o.startsWith("git@"))return {cloneUrl:o,subPath:"."};if((o.startsWith("./")||o===".")&&a){let t=o==="."?".":o.replace(/^\.\//,"")||".";return {cloneUrl:a,subPath:t}}}return null}function da(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Ra=k("claude-code.adapter");function Rk(e,a){let o=e??"external";if(!a)return o;let t=a.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!t)return o;let r=t[1],i=Jo();if(!ie__default.existsSync(i))return o;try{let s=JSON.parse(ie__default.readFileSync(i,"utf-8"));for(let[n,d]of Object.entries(s))if(d.source?.repo===r)return n}catch{}return o}async function xp(e,a){let o=e.catalogId?me.getAdapter(e.catalogId):void 0,t=lt(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=e.type==="bundle"||e.type==null,i=Rk(e.catalogId,o?.source),s=a.scope??"user",n;r?n=yn(i,e.name,"external"):n=join(Ho(s==="user"?"global":"project"),e.name);let d=null;try{ia(e.name),d=await Sa(t.cloneUrl,t.ref);let l=t.subPath==="."?d:join(d,t.subPath);if(ie__default.existsSync(n)&&ie__default.rmSync(n,{recursive:!0,force:!0}),ie__default.mkdirSync(dirname(n),{recursive:!0}),ie__default.cpSync(l,n,{recursive:!0}),r){let c=`${e.name}@${i}`,u=await xd(),m={scope:s,installPath:n,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=u.plugins[c]??[];u.plugins[c]=[...p.filter(g=>g.scope!==s),m],na(u),qr(c,!0,s);}return {success:!0,message:`Installed ${e.name} from ${t.cloneUrl}`}}catch(l){return Ra.debug(`[${e.name}] External catalog install failed: ${String(l)}`),{success:false,message:l instanceof Error?l.message:String(l)}}finally{d&&await Ca(d).catch(()=>{});}}async function Bd(e,a,o,t){try{await C(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:o,source:"external",scope:ts(t),version:"unknown",duration_ms:a,interface:Z().interfaceType});}catch(r){Ra.warn(`Failed to send external install metrics: ${String(r)}`);}}async function Cp(e,a,o){try{await C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:o,source:"external",error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(t){Ra.warn(`Failed to send external install-failed metrics: ${String(t)}`);}}var Ak={async install(e,a){if(e.origin===ft&&!e.installCommand&&!Gt(e.name))return xp(e,a);if(e.origin===ft&&e.installCommand){let o=e.type??"skill",t=await Nr(e.installCommand,a.scope);return t.exitCode===0?(await Bd(e.name,t.duration_ms,o,a.scope),{success:true,message:`Installed ${e.name}`}):(await Cp(e.name,new Error(t.stderr||"Install failed"),o),{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`})}if(Gt(e.name)){let o=e.type??"skill",t=jt(e.name,a.scope);Ra.debug(`[${e.name}] Attempting install: ${t}`);let r=await qe(t);if(r.exitCode===0)return await Bd(e.name,r.duration_ms,o,a.scope),{success:true};Ra.debug(`[${e.name}] First attempt failed, adding marketplace`),await ms(e.name,a.marketplaceSource,()=>{});let i=await qe(t);return i.exitCode===0?(await Bd(e.name,i.duration_ms,o,a.scope),{success:true}):(await Cp(e.name,new Error(i.stderr||"Install failed"),o),{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`})}try{let o=await je(e.name,{...a,type:e.type});return {success:!0,message:`Installed ${e.name}@${o.version}`}}catch(o){return Ra.debug(`[${e.name}] Plugin install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}},async uninstall(e,a){await Lr(e,a);},getInstallPath(e,a){return ""}};function Rp(e){return {async install(a,o){if(a.origin===ft&&!a.installCommand&&!Gt(a.name))return xp(a,o);if(!a.installCommand)try{let r=await je(a.name,{...o,type:e});return {success:!0,message:`Installed ${a.name}@${r.version}`}}catch(r){return Ra.debug(`[${a.name}] ${e} install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}Ra.debug(`[${a.name}] Executing install command: ${a.installCommand}`);let t=await Nr(a.installCommand,o.scope);return t.exitCode===0?{success:true}:{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`}},async uninstall(a,o){let t=Ae(),r=`${a}@${ue}`;if(t.plugins[r]){await Lr(a,o);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${a}`)},getInstallPath(a,o){return ""}}}function xk(e){for(let a of [join(e,".claude","agents"),join(e,"agents")]){if(!ie__default.existsSync(a))continue;let o=ie__default.readdirSync(a).filter(t=>t.endsWith(".md")&&ie__default.lstatSync(join(a,t)).isFile());if(o.length>0)return o.map(t=>join(a,t))}return []}function Ek(e){for(let a of [join(e,".claude","rules"),join(e,"rules")]){if(!ie__default.existsSync(a))continue;let o=ie__default.readdirSync(a).filter(t=>t.endsWith(".md")&&ie__default.lstatSync(join(a,t)).isFile());if(o.length>0)return o.map(t=>join(a,t))}return []}async function jd(e,a,o,t){let r=await xd(),i=`${e}@claude-code`,s={scope:a,installPath:o,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:t},n=r.plugins[i]??[];r.plugins[i]=[...n.filter(d=>d.scope!==a),s],na(r);}var Ik={async install(e,a){let o=a.scope??"user",t=e.catalogId?me.getAdapter(e.catalogId):void 0,r=lt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{ia(e.name),i=await Sa(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=xk(s);if(n.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let d=mi(o);ie__default.mkdirSync(d,{recursive:!0});let l=da(e.name);if(n.length===1)ie__default.copyFileSync(n[0],join(d,`${l}.md`));else for(let u of n){let m=da(basename(u,".md"));ie__default.copyFileSync(u,join(d,`${l}--${m}.md`));}let c=n.length===1?join(d,`${l}.md`):d;return await jd(e.name,o,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(s){return Ra.debug(`[${e.name}] Agent install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ca(i).catch(()=>{});}},async uninstall(e,a){let o=mi(a),t=da(e);if(ie__default.existsSync(o))for(let n of ie__default.readdirSync(o).filter(d=>d===`${t}.md`||d.startsWith(`${t}--`)&&d.endsWith(".md")))ie__default.rmSync(join(o,n),{force:true});let r=`${e}@claude-code`,i=Ae(),s=(i.plugins[r]??[]).filter(n=>n.scope!==a);if(s.length===0){let{[r]:n,...d}=i.plugins;na({...i,plugins:d});}else na({...i,plugins:{...i.plugins,[r]:s}});},getInstallPath(e,a){return join(mi(a),`${da(e)}.md`)}},Tk={async install(e,a){let o=a.scope??"user",t=e.catalogId?me.getAdapter(e.catalogId):void 0,r=lt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{ia(e.name),i=await Sa(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=Ek(s);if(n.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let d=Pt(o);ie__default.mkdirSync(d,{recursive:!0});for(let l of n)ie__default.copyFileSync(l,join(d,basename(l)));return await jd(e.name,o,d,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(s){return Ra.debug(`[${e.name}] Rule install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ca(i).catch(()=>{});}},async uninstall(e,a){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,a){return Pt(a)}},Mk={async install(e,a){let o=a.scope??"user",t=e.catalogId?me.getAdapter(e.catalogId):void 0,r=lt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{ia(e.name),i=await Sa(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=join(s,"settings.json");if(!ie__default.existsSync(n))return {success:!1,message:`No settings.json found in "${e.name}"`};let d;try{d=JSON.parse(ie__default.readFileSync(n,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let l=d.hooks;if(!l||typeof l!="object"||Array.isArray(l))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=Dr();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let u=c.status==="ok"?c.settings:{},m=u.hooks!==null&&typeof u.hooks=="object"&&!Array.isArray(u.hooks)?u.hooks:{},p=Or(m,l);return Fi({...u,hooks:p}),await jd(e.name,o,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(s){return Ra.debug(`[${e.name}] Hook install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ca(i).catch(()=>{});}},async uninstall(e,a){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,a){return ""}},gs=class{id="claude-code";name="Claude Code";async isAvailable(){return ct("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Ak,skill:Rp("skill"),mcp:Rp("mcp"),agent:Ik,hook:Mk,rule:Tk}};function fs(e,a){return {async install(o,t){if(!o.installCommand)return {success:false,message:"No install command provided"};let[r,...i]=o.installCommand.split(/\s+/).filter(Boolean);if(!r||!e.has(r))return {success:false,message:`Disallowed command: "${r??""}"`};let s=await execa(r,i,{reject:false});return s.exitCode===0?{success:true}:{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`}},async uninstall(o,t){throw new Error(`MCP uninstall not supported \u2014 ${a.replace("<name>",o)}`)},getInstallPath(o,t){return ""}}}var Lk=new Set(["gh"]),Fk=fs(Lk,"use: gh copilot mcp remove <name>"),hs=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await ct("gh",["--version"])?ct("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:Fk}};Oe();var Ok=new Set(["opencode"]),Nk=fs(Ok,"use: opencode config remove mcp <name>");function Gk(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
117
|
-
`)}function Ep(){return {async install(e,a){try{ia(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let o=e.catalogId?me.getAdapter(e.catalogId):void 0,t=lt(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=null;try{r=await Sa(t.cloneUrl,t.ref);let i=t.subPath==="."?r:join(r,t.subPath),s=pi(a.scope??"user"),n=join(i,".opencode","plugins");if(ie__default.existsSync(n)){let d=ie__default.readdirSync(n).filter(l=>l.endsWith(".js")||l.endsWith(".mjs"));if(d.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};ie__default.mkdirSync(s,{recursive:!0}),ie__default.copyFileSync(join(n,d[0]),join(s,`${e.name}.js`));}else {let d=join(s,`${e.name}-content`);ie__default.existsSync(d)&&ie__default.rmSync(d,{recursive:!0,force:!0}),ie__default.mkdirSync(d,{recursive:!0}),ie__default.cpSync(i,d,{recursive:!0}),ie__default.mkdirSync(s,{recursive:!0}),ie__default.writeFileSync(join(s,`${e.name}.js`),Gk(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(i){return {success:false,message:i instanceof Error?i.message:String(i)}}finally{r&&await Ca(r).catch(()=>{});}},async uninstall(e,a){ia(e);let o=pi(a),t=join(o,`${e}.js`),r=join(o,`${e}-content`);ie__default.existsSync(t)&&ie__default.rmSync(t,{force:true}),ie__default.existsSync(r)&&ie__default.rmSync(r,{recursive:true,force:true});},getInstallPath(e,a){return join(pi(a),`${e}.js`)}}}var bs=class{id="opencode";name="OpenCode";async isAvailable(){return ct("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Nk,skill:Ep(),bundle:Ep()}};var Ja=new os;Ja.register(new gs);Co()&&(Ja.register(new hs),Ja.register(new bs));function Ip({itemName:e,itemType:a,onInstall:o,onClose:t}){let[r,i]=useState(false),[s,n]=useState(false),[d,l]=useState([]),[c,u]=useState(void 0);useEffect(()=>{Ja.getAvailableProviders(a??"bundle").then(l).catch(()=>{});},[a]);let m=useCallback(h=>{h==="Install"?d.length>1?n(true):i(true):t();},[t,d.length]),p=useCallback(h=>{if(h==="Cancel"){n(false);return}let b=d.find(D=>D.name===h);b?(u(b.id),n(false),i(true)):n(false);},[d]),g=useCallback(h=>{let b=Gu(h);b?o(b,c):i(false);},[o,c]),f=useCallback(()=>{i(false);},[]);if(s){let h=[...d.map(b=>b.name),"Cancel"];return jsx(ra,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>n(false)},"provider")}return r?jsx(ra,{itemName:`${e} \u2014 Choose scope`,actions:Ou,descriptions:Nu,onAction:g,onClose:f},"scope"):jsx(ra,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:t},"main")}j();function Mp({itemName:e,bundle:a,onInstall:o,onConfirm:t,onClose:r}){let i=y(g=>g.focus),[s,n]=useState(0),l=(a?.artifact.artifacts??[]).filter(g=>g.available),c=a!==void 0&&l.length===0,u=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{n(0);},[a]);let m=useCallback((g,f)=>{f.upArrow?n(h=>Math.max(0,h-1)):f.downArrow?n(h=>Math.min(u.length-1,h+1)):f.return?u[s]==="Confirm Install"?t():r():f.escape&&r();},[u,s,t,r]);useInput(m,{isActive:i==="actionMenu"&&a!==void 0});let p=useCallback(g=>{g==="Install Bundle"?o():r();},[o,r]);return a?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:a.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[l.length," artifact",l.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:l.map(g=>{let f=v(g.name??g.flowId),h=g.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:f}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},g.flowId)})}),jsx(Box,{flexDirection:"column",children:u.map((g,f)=>jsx(Box,{children:jsxs(Text,{bold:f===s,color:f===s?"cyan":void 0,children:[f===s?"\u203A ":" ",g]})},g))})]}):jsx(ra,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:r})}function ks({activeFocus:e,onConfirm:a}){let[o,t]=useState("idle"),r=y(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?t("idle"):i==="y"&&a();},{isActive:o==="confirming"&&r===e}),{isConfirming:o==="confirming",requestConfirm:()=>t("confirming"),cancelConfirm:()=>t("idle")}}j();function Fp({itemName:e,itemScope:a,itemStatus:o,updateAvailable:t,catalogVersion:r,onUninstall:i,onToggleStatus:s,onUpdate:n,onClose:d}){let{isConfirming:l,requestConfirm:c}=ks({activeFocus:"actionMenu",onConfirm:()=>i(a)});if(l)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let u=o==="enabled"?"Disable":"Enable",m=r&&v(r),p=m?`Update to v${m}`:"Update";return jsx(ra,{itemName:e,actions:t?["Uninstall",u,p,"Cancel"]:["Uninstall",u,"Cancel"],onAction:h=>{h==="Uninstall"?c():h===u?s(a):h.startsWith("Update")?n?.():d();},onClose:d})}function Gp({itemName:e,itemScope:a,onUninstall:o,onClose:t}){let{isConfirming:r,requestConfirm:i}=ks({activeFocus:"actionMenu",onConfirm:()=>o(a)});return r?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(ra,{itemName:e,actions:["Uninstall","Cancel"],onAction:d=>{d==="Uninstall"?i():t();},onClose:t})}I();var _t=k("bundle:installer"),Bp=/already exists/i;async function Vk(e){if(!e.installCommand)throw new Error("Missing install command");let a=e.installCommand;if(vp(a)){let o=await yp(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(Bp.test(t))return;throw new Error(t)}}else {let o=await Nr(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(Bp.test(t))return;throw new Error(t)}}}async function Qk(e,a){try{await C(w.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:a});}catch(o){_t.warn(`Failed to emit bundle install started event: ${String(o)}`);}}async function _k(e,a,o){try{await C(w.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:a,artifact_type:o});}catch(t){_t.warn(`Failed to emit bundle install plugin success event: ${String(t)}`);}}async function jp(e,a,o,t){try{await C(w.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:a,artifact_type:o,error_message:t});}catch(r){_t.warn(`Failed to emit bundle install plugin failed event: ${String(r)}`);}}async function Xk(e,a,o,t,r){try{await C(w.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:a,failed_count:o,unavailable_count:t,duration_ms:r});}catch(i){_t.warn(`Failed to emit bundle install completed event: ${String(i)}`);}}async function ws(e,a={}){let{onProgress:o}=a,t=e.artifact.artifacts,r=t.filter(p=>p.available),i=t.length-r.length,s=e.artifact.name,n=Date.now();await Qk(s,r.length);let d=[],l=0,c=r.length;for(let[p,g]of r.entries()){let f=g.name??g.flowId,h=g.type??"unknown";if(!g.type){_t.warn(`Artifact "${f}" has no type \u2014 treated as failed`),d.push({name:f,type:h,reason:"unknown artifact type"}),await jp(s,f,h,"unknown artifact type"),o?.({index:p+1,total:c,artifact:g,success:false,error:"unknown artifact type"});continue}try{await Vk(g),l++,await _k(s,f,h),o?.({index:p+1,total:c,artifact:g,success:!0});}catch(b){let D=b instanceof Error?b.message:String(b);_t.error(`Failed to install artifact "${f}": ${D}`),d.push({name:f,type:h,reason:D}),await jp(s,f,h,D),o?.({index:p+1,total:c,artifact:g,success:false,error:D});}}let u=Date.now()-n,m=d.length;return await Xk(s,l,m,i,u),{bundleTitle:e.title,total:t.length,installed:l,skipped:i,failed:m,failures:d}}j();function Jp({bundle:e,onComplete:a}){let[o,t]=useState(null),[r,i]=useState(null),s=useRef(false);return useEffect(()=>{s.current||(s.current=true,ws(e,{onProgress:t}).then(i).catch(n=>{let d=n instanceof Error?n.message:"Installation failed",l=e.artifact.artifacts,c=l.filter(u=>u.available);i({bundleTitle:e.title,total:l.length,installed:0,skipped:l.length-c.length,failed:c.length,failures:c.map(u=>({name:u.name??u.flowId,type:u.type??"unknown",reason:d}))});}));},[e]),useEffect(()=>{r&&a(r);},[r,a]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",o.index,"/",o.total,"] Installing"," ",v(o.artifact.name??o.artifact.flowId)," (",o.artifact.type??"unknown",")"]})]}),!o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Wp,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ye=create(e=>({installedItems:[],setInstalledItems:a=>e({installedItems:a}),loadFromDisk:()=>e({installedItems:ce()})}));j();function Hp({entries:e,selectedIndex:a,focusPanel:o}){let t=o==="list",r=a===0&&t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:r,dimColor:!t,children:"+ Add Marketplace"})]}),e.map((i,s)=>{let n=s+1,d=a===n&&t,l=i.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:d?"\u203A ":" "}),jsx(Text,{bold:d,dimColor:!t,children:i.adapter.name}),l&&i.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),i.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",qa(i.stored.lastUpdated)]})})]},i.adapter.id)})]})}j();function Vp({entry:e,detailData:a,installedCount:o,focusPanel:t,actionIndex:r,onBrowse:i,onUpdate:s,onToggleAutoUpdate:n,onRemove:d}){let{adapter:l,stored:c}=e,u=l.removable!==false,m=c?.autoUpdate!==false,p=t==="detail",g=[{label:`Browse plugins${a&&!a.loading?` (${a.items.length})`:""}`,handler:i},{label:"Update marketplace",handler:s},...u?[{label:"Toggle auto-update",handler:n},{label:"Remove marketplace",handler:d,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:a?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):a?.error?jsx(Text,{color:"red",children:a.error}):jsxs(Text,{dimColor:true,children:[a?`${a.items.length} available`:"\u2014 available",o>0?` \xB7 ${o} installed`:"",c?.lastUpdated?` \xB7 Updated ${qa(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:g.map((f,h)=>{let b=h===r;return jsxs(Box,{children:[jsx(Text,{color:b?"cyan":void 0,children:b?"\u203A ":" "}),jsx(Text,{bold:b,color:f.danger?"yellow":void 0,dimColor:!b,children:f.label})]},f.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function Qp(e){return e.adapter.removable!==false?4:2}U();j();function _p({item:e,adapterName:a,isInstalled:o,onBack:t,onInstall:r,onUninstall:i}){let s=[...o&&i?[{label:"Uninstall",handler:()=>i(e),danger:true}]:!o&&r?[{label:"Install",handler:()=>r(e)}]:[],{label:"Back",handler:t}],[n,d]=useState(0);return useInput((l,c)=>{if(c.escape){t();return}if(c.upArrow){d(u=>Math.max(0,u-1));return}if(c.downArrow){d(u=>Math.min(s.length-1,u+1));return}c.return&&s[n].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",a," \u203A Browse plugins \u203A ",v(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:v(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",v(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",v(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:v(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 ",v(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",v(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",v(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:s.map((l,c)=>jsxs(Box,{children:[jsx(Text,{color:c===n?"cyan":void 0,children:c===n?"\u203A ":" "}),jsx(Text,{bold:c===n,color:l.danger?"yellow":void 0,dimColor:c!==n,children:l.label})]},l.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Kp({item:e,isSelected:a,isInstalled:o}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:a?"\u203A ":" "}),jsx(Text,{color:o?"green":void 0,bold:a,children:e.name}),o&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function $p({entry:e,items:a,installedKeys:o,onBack:t}){let r=e.adapter.id??"default",i=a.filter(A=>o.has(`${A.name}@${r}`)),s=a.filter(A=>!o.has(`${A.name}@${r}`)),n=[...i,...s],[d,l]=useState(0),[c,u]=useState(null);if(useInput((A,T)=>{if(T.escape){t();return}if(T.return){u(n[d]??null);return}if(T.upArrow){l(F=>Math.max(0,F-1));return}T.downArrow&&l(F=>Math.min(n.length-1,F+1));},{isActive:c===null}),c!==null)return jsx(_p,{item:c,adapterName:e.adapter.name,isInstalled:o.has(`${c.name}@${r}`),onBack:()=>u(null)});if(a.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,d-Math.floor(ea/2)),p=Math.min(n.length,m+ea);p===n.length&&(m=Math.max(0,p-ea));let g=n.slice(m,p),f=m,h=n.length-p,b=i.length>0&&m<i.length,D=p>i.length,q=g.filter(A=>o.has(`${A.name}@${r}`)),L=g.filter(A=>!o.has(`${A.name}@${r}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:f>0?`\u2191 ${f} more above`:" "})}),b&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),q.map(A=>jsx(Kp,{item:A,isSelected:n.indexOf(A)===d,isInstalled:true},A.name))]}),D&&jsxs(Box,{flexDirection:"column",marginTop:b?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),L.map(A=>jsx(Kp,{item:A,isSelected:n.indexOf(A)===d,isInstalled:false},A.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"})})]})}vd();var oP=/^https?:\/\/.+/;function tP(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function rP(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function am(e){let a=y(h=>h.showNotification),o=y(h=>h.incrementCatalogVersion),[t,r]=useState("idle"),[i,s]=useState(""),[n,d]=useState(""),[l,c]=useState(null),u=useRef(""),m=useRef("");useEffect(()=>{u.current=i;},[i]),useEffect(()=>{m.current=n;},[n]);let p=useCallback(()=>{u.current="",m.current="",s(""),d(""),c(null),r("add-name");},[]),g=useCallback(()=>{r("idle");},[]),f=useCallback(async()=>{let h=m.current,b=u.current;if(!oP.test(h)){c("URL must start with http:// or https://");return}c(null),r("adding");let D=randomUUID(),q=new zt(D,b,h);try{await q.fetchItems(),await ao.add({id:D,name:b,source:h}),me.register(new zt(D,b,h)),o(),e(),a(`Catalog "${b}" added`,"success"),s(""),d(""),u.current="",m.current="",r("idle");}catch(L){let A=tP(L)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":rP(L)?L.message:L instanceof Error?`Could not reach catalog URL: ${L.message}`:"Failed to validate catalog URL";a(A,"error"),r("add-url");}},[e,a,o]);return useInput((h,b)=>{if(b.escape){r("idle");return}if(b.return){u.current.trim().length>0&&r("add-url");return}if(b.backspace||b.delete){u.current=u.current.slice(0,-1),s(u.current);return}h&&!b.ctrl&&!b.meta&&(u.current=u.current+h,s(u.current));},{isActive:t==="add-name"}),useInput((h,b)=>{if(b.escape){r("add-name");return}if(b.return){f();return}if(b.backspace||b.delete){m.current=m.current.slice(0,-1),d(m.current),c(null);return}h&&!b.ctrl&&!b.meta&&(m.current=m.current+h,d(m.current),c(null));},{isActive:t==="add-url"}),{phase:t,inputName:i,inputUrl:n,urlError:l,setInputName:s,setInputUrl:d,startAdd:p,cancelAdd:g}}function om(e){let a=y(r=>r.showNotification),o=y(r=>r.incrementCatalogVersion);return {handleRemove:useCallback(async r=>{try{await ao.remove(r),me.unregister(r),o(),e(),a("Catalog removed","success");}catch(i){a(i instanceof Error?i.message:"Failed to remove catalog","error");}},[e,a,o])}}function rm(){let e=y(E=>E.focus),a=y(E=>E.setFocus),o=y(E=>E.showNotification),t=ye(E=>E.installedItems),[r,i]=useState(()=>me.listAdapters().map(E=>({adapter:E,stored:null}))),[s,n]=useState(0),[d,l]=useState("list"),[c,u]=useState(0),[m,p]=useState(null),[g,f]=useState("main"),h=useRef(r);useEffect(()=>{h.current=r;},[r]),useEffect(()=>{g==="browse"&&!r[s-1]&&f("main");},[g,r,s]);let b=useCallback(()=>{(async()=>{let E=me.listAdapters(),B=await ao.read(),V=new Map(B.map(Fe=>[Fe.id,Fe]));i(E.map(Fe=>({adapter:Fe,stored:V.get(Fe.id)??null})));})();},[]);useEffect(()=>{a("marketplaces"),b();},[a,b]),useEffect(()=>{if(s===0){p(null);return}let E=h.current[s-1];if(!E)return;let B=false;return p({items:[],loading:true,error:null}),E.adapter.fetchItems().then(V=>{B||p({items:V,loading:false,error:null});}).catch(V=>{B||p({items:[],loading:false,error:V instanceof Error?V.message:"Failed to load catalog"});}),()=>{B=true;}},[s]);let D=am(b),q=useCallback(()=>{b(),n(0),l("list"),p(null),f("main");},[b]),{handleRemove:L}=om(q),A=useCallback(async E=>{f("removing"),await L(E);},[L]),T=useCallback(async E=>{try{let B=await E.adapter.fetchItems();if(p({items:B,loading:!1,error:null}),E.stored){let V=new Date().toISOString();await ao.updateField(E.stored.id,{lastUpdated:V}),b();}o("Marketplace updated","success");}catch(B){o(B instanceof Error?B.message:"Update failed","error");}},[b,o]),F=useCallback(async E=>{if(!E.stored)return;let B=E.stored.autoUpdate!==false;await ao.updateField(E.stored.id,{autoUpdate:!B}),b();},[b]),O=useCallback(()=>f("browse"),[]),oe=useCallback(E=>{let B=r[s-1];if(!B)return;let V=B.adapter.removable!==false;[O,()=>{T(B);},...V?[()=>{F(B);},()=>{A(B.adapter.id);}]:[]][E]?.();},[r,s,O,T,F,A]),x=useCallback(()=>f("main"),[]),J=useCallback(()=>{let E=r[s-1];E&&T(E);},[r,s,T]),ae=useCallback(()=>{let E=r[s-1];E&&F(E);},[r,s,F]),z=useCallback(()=>{let E=r[s-1];E&&A(E.adapter.id);},[r,s,A]);if(useInput((E,B)=>{if(B.upArrow){n(V=>Math.max(0,V-1));return}if(B.downArrow){n(V=>Math.min(r.length,V+1));return}(B.return||B.tab)&&(s===0?D.startAdd():(l("detail"),u(0)));},{isActive:g==="main"&&D.phase==="idle"&&d==="list"&&e==="marketplaces"}),useInput((E,B)=>{if(B.escape||B.tab){l("list");return}if(B.upArrow){u(V=>Math.max(0,V-1));return}if(B.downArrow){let V=r[s-1],Fe=V?Qp(V)-1:0;u(si=>Math.min(si+1,Fe));return}B.return&&oe(c);},{isActive:g==="main"&&D.phase==="idle"&&d==="detail"&&e==="marketplaces"}),D.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:D.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),D.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(D.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:D.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:D.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),D.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:D.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(D.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(g==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(g==="browse"){let E=r[s-1];if(!E)return jsx(Box,{});let B=E.adapter.id??"default",V=new Set(t.filter(Fe=>Fe.marketplace===E.adapter.name).map(Fe=>`${Fe.name}@${B}`));return jsx($p,{entry:E,items:m?.items??[],installedKeys:V,onBack:x})}if(r.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let W=r[s-1]??null,_=W?t.filter(E=>E.marketplace===W.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Hp,{entries:r,selectedIndex:s,focusPanel:d})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:d==="detail"&&W?jsx(Vp,{entry:W,detailData:m,installedCount:_,focusPanel:d,actionIndex:c,onBrowse:O,onUpdate:J,onToggleAutoUpdate:ae,onRemove:z}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:W?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:d==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function im(e,a,o,t){if(a.upArrow)return o.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:o.selectedIndex-1}];if(a.downArrow&&o.selectedIndex<t-1)return [{type:"setSelectedIndex",index:o.selectedIndex+1}];if(a.leftArrow){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r-1+re.length)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.rightArrow){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r+1)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.tab){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r+1)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}return a.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="8"?[{type:"toggleTypeFilter",catalogType:"agent"}]:e==="9"?[{type:"toggleTypeFilter",catalogType:"hook"}]:e==="0"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="a"&&o.activeTab==="updates"?[]:e&&e!==" "&&!a.ctrl&&!a.meta&&!a.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function sm(e,a){return a.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function nm(e,a,o){return a.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:a.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:a.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:a.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.backspace?o.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!a.ctrl&&!a.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var cP=new Set(re.filter(e=>e.focus!=="list").map(e=>e.focus));function Qr(e){let{setActiveTab:a,setFocus:o,setSelectedIndex:t,setActionMenuOpen:r}=y.getState();for(let i of e)if(i.type==="setTab")a(i.tab);else if(i.type==="setFocus")o(i.focus);else if(i.type==="setSelectedIndex")t(i.index);else if(i.type==="setActionMenuOpen")r(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:n,setCursorPosition:d,cursorPosition:l}=_e.getState();s(n.slice(0,l)+i.char+n.slice(l)),d(l+i.char.length);}else i.type==="toggleTypeFilter"?y.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?y.getState().selectAllTypes():i.type==="toggleOriginFilter"?y.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&y.getState().selectAllOrigins();}function dm({listLength:e}){let a=y(f=>f.focus),o=y(f=>f.selectedIndex),t=y(f=>f.actionMenuOpen),r=y(f=>f.setFocus),i=y(f=>f.setActionMenuOpen),s=_e(f=>f.query),n=_e(f=>f.setQuery),d=_e(f=>f.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(a==="search"){let{query:f,setCursorPosition:h}=_e.getState();h(f.length);}},[a]);let[c,u]=useState("");useEffect(()=>{let f=setTimeout(()=>u(s),300);return ()=>clearTimeout(f)},[s]),useInput((f,h)=>{let{activeTab:b,selectedIndex:D,actionMenuOpen:q}=y.getState();Qr(od(f,h,{activeTab:b}));},{isActive:a==="tabs"}),useInput((f,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:b,selectedIndex:D,actionMenuOpen:q}=y.getState();Qr(od("",h,{activeTab:b}));},{isActive:cP.has(a)}),useInput((f,h)=>{let{activeTab:b,selectedIndex:D,actionMenuOpen:q}=y.getState();Qr(im(f,h,{activeTab:b,selectedIndex:D},l.current));},{isActive:a==="list"}),useInput((f,h)=>{Qr(sm(f,h));},{isActive:a==="actionMenu"}),useInput((f,h)=>{let b=nm(f,h,_e.getState().query),D=b.queryUpdate;if(Qr(b.actions),D==="reset")d(),u("");else if(D!==null){let{query:q,cursorPosition:L,setCursorPosition:A}=_e.getState();if("backspace"in D)L>0&&(n(q.slice(0,L-1)+q.slice(L)),A(L-1));else if("append"in D)n(q.slice(0,L)+D.append+q.slice(L)),A(L+D.append.length);else if("cursorMove"in D){let T=L+D.cursorMove;T>=0&&T<=q.length&&A(T);}}},{isActive:a==="search"});let m=useCallback(()=>{i(false),r("list");},[i,r]),p=useCallback(f=>{let{setSelectedIndex:h,selectedIndex:b}=y.getState();f===0?h(0):b>=f&&h(f-1);},[]),g=useCallback(f=>{if(!c)return l.current=f.length,f;let h=c.toLowerCase(),b=f.filter(D=>D.name.toLowerCase().includes(h)||D.description?.toLowerCase().includes(h));return l.current=b.length,b},[c]);return {actionMenuOpen:t,closeMenu:m,selectedIndex:o,clampIndex:p,filteredItems:g}}function lm(){let e=y(n=>n.notification),a=y(n=>n.showNotification),o=y(n=>n.clearNotification),t=oa(n=>n.justAuthenticated),r=oa(n=>n.credentials),i=oa(n=>n.setJustAuthenticated);return useEffect(()=>{t&&r&&(a(`Authenticated. Tenant: ${r.tenant}`,"success"),i(false));},[t,r]),useEffect(()=>{if(!e)return;let n=setTimeout(o,3e3);return ()=>clearTimeout(n)},[e]),{notify:(n,d)=>{a(n,d);}}}function ze(e,a,o=false){return o?true:!Hd.valid(e)||!Hd.valid(a)?false:Hd.gt(a,e)}U();I();var io=k("updater");async function lP(e,a,o,t,r,i){try{await C(w.CLI_TOOL_UPDATED,{tool_id:e,tool_type:i,source:r,from_version:a,to_version:o,duration_ms:t,interface:Z().interfaceType});}catch(s){io.warn(`Failed to send update metrics: ${String(s)}`);}}function uP(e){let a=Ae(),o=`${e}@${ue}`,t=a.plugins[o];return !t||t.length===0?null:{pluginKey:o,entry:t[0]}}async function As(e,a={}){let o=Date.now(),t=null;try{io.debug(`[${e}] Acquiring lock...`),t=await Mo();let r=uP(e);if(!r)throw io.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=r,s=i.version,n=i.installPath;io.debug(`[${e}] Fetching manifest...`);let l=(await Wt(e,a.source)).version;if(!s||!ze(s,l,a.force))throw io.debug(`[${e}] Already up to date (v${s??"n/a"})`),new Io(e,s??"unknown");io.info(`[${e}] Updating v${s} \u2192 v${l}...`),await t(),t=null;try{let c=await je(e,{force:!0,skipMetrics:!0,source:a.source}),u=Date.now()-o;return await lP(c.name,s,c.version,u,i.origin??"internal",i.type??"skill"),io.debug(`[${e}] Updated successfully in ${u}ms`),{name:c.name,previousVersion:s,newVersion:c.version,path:c.path,duration_ms:u}}catch(c){io.warn(`[${e}] Install failed, rolling back to v${s}...`),t=await Mo();let u=Ae(),m=`${e}@${ue}`;throw u.plugins[m]&&(u.plugins[m][0].version=s,u.plugins[m][0].installPath=n,na(u),io.info(`[${e}] Rollback completed, restored to v${s}`)),c}}finally{t&&await t();}}To();I();var xs=k("dispatcher");async function pP(e,a,o,t,r){let i=Bt(e);return xs.debug(`[${e}] Install failed (exit code), attempting marketplace add`),r?.onError?.(o),t?r?.onStatus?.(`Adding marketplace for ${i}...`):r?.onPause?.(),await ms(e,t,()=>{}),r?.onResume?.(`Retrying install for ${i}...`),xs.debug(`[${e}] Retrying install after marketplace add`),qe(a)}async function um(e,a,o,t){let r=jt(e,t),i=Bt(e);o?.onStatus?.(`Installing ${i}...`),xs.debug(`[${e}] Attempting install: ${r}`);let s=await qe(r);if(s.exitCode===0)return s;xs.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`);let n=s.stderr||`Install failed with exit code ${s.exitCode}`;return pP(e,r,n,a,o)}async function pm(e,a,o){let t=e.type??"bundle",r=await Ja.getAvailableProviders(t),i=r[0];if(!i)throw new Error(`No available provider for artifact type "${t}"`);let s=i.installers[t];if(!s)throw new Error(`Provider "${i.id}" does not support type "${t}"`);let n=a??{},d=n;return s.install(e,d)}function mm(){let e=ye(s=>s.installedItems),a=ye(s=>s.loadFromDisk),o=useCallback(async(s,n)=>{let d=await pm(s,n);if(!d.success)throw new Error(d.message||"Installation failed");a();},[a]),t=useCallback(async(s,n)=>{let d=ce().find(p=>p.name===s),l=d?.providerId??"claude-code",c=Ja.getAdapter(l);if(!c)throw new Error(`Provider "${l}" not found`);let u=d?.type??"bundle",m=c.installers[u];if(!m)throw new Error(`Provider "${l}" does not support type "${u}"`);await m.uninstall(s,n??"user"),a();},[a]),r=useCallback(async(s,n)=>{let l=e.find(c=>c.name===s)?.status==="enabled"?"disabled":"enabled";await Fr(s,l,n),a();},[e,a]),i=useCallback(async s=>{await As(s),a();},[a]);return {install:o,uninstall:t,toggle:r,update:i}}j();I();var Is=k("mcp");function _r(e,a){e.silent?Ne({status:"error",mcp:a.name,...a.exitCode!==void 0&&{exitCode:a.exitCode},message:a.message}):S(`Failed to ${a.action} MCP "${a.name}": ${a.message}`);}function fm(e,a){e.silent?be({status:"success",mcp:a.name,command:a.command,duration_ms:a.durationMs}):(K(`MCP "${a.name}" ${a.actionPastTense} successfully`),e.verbose&&a.stdout&&P(a.stdout));}function mP(e,a,o,t){let r=["claude","mcp","add","--transport",o,e];return a.length>0&&r.push(...a),t&&r.push("--scope",t),r.join(" ")}function Vd(e,a){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let o=["claude","mcp","remove",e];return a&&o.push("--scope",a),o.join(" ")}async function hm(e,a,o){if(!await fe())return 1;if(a.length===0){let i=o.transport==="http"?"a URL":"a command";return _r(o,{name:e,action:"add",message:`${o.transport} transport requires ${i}`}),1}Is.debug(`[${e}] Starting MCP add with args: ${a.join(" ")}`);let t=mP(e,a,o.transport,o.scope);if(!o.force){let i=v(e),s=v(t);if(!await ee(`Install external MCP "${i}"?
|
|
114
|
+
`),o(a[r].value);return}if(i===dk){r=(r-1+a.length)%a.length,n(),i="";return}if(i===ck){r=(r+1)%a.length,n(),i="";return}i.startsWith("\x1B")&&i.length<3||(i="");};function n(){process.stdout.write(`\x1B[${a.length-1}A`);for(let c=0;c<a.length;c++)process.stdout.write(`\r\x1B[2K${kp(a[c],c===r)}`),c<a.length-1&&process.stdout.write(`
|
|
115
|
+
`);}function d(){process.stdin.setRawMode(false),process.stdin.removeListener("data",s),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",s);})}qo();var Vt=k("claudeProxy"),Wd="claude ",Pp="flow ",jd=class extends Error{constructor(a){super(`Invalid install command: "${a}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Ht=class extends Error{constructor(a){super(`Disallowed subcommand: "${a}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},uk=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,pk=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,mk={"--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}$/},gk=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,fk=/^(flow|claude)\s+auth\s+login(\s|$)/,Dp=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function wp(e){return Dp.test(e.trim())}function hk(e){return Dp.exec(e.trim())?.[2]??""}async function Sp(e){let a=hk(e);Dd(a);let o=Date.now();Vt.debug(`[${a}] Executing: flow plugin install ${a}`);try{let t=await execa("flow",["plugin","install",a],{reject:!1});return {name:a,command:`flow plugin install ${a}`,exitCode:t.exitCode??1,stdout:t.stdout,stderr:t.stderr,duration_ms:Date.now()-o}}catch(t){throw Jd(t)?new Ud:t}}function bk(e){Cp(e);let a=e.slice(Wd.length);if(!uk.test(a))throw new Ht(e)}var bs=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},Ud=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Cp(e){if(!e||!/^claude /.test(e))throw new jd(e)}function vk(e){for(let a=0;a<e.length;a++){let o=e[a];if(o==="--")return;if(!o.startsWith("-"))continue;if(!pk.test(o))throw new Ht(`Unexpected flag: ${o}`);let t=mk[o];if(t!==void 0){let r=e[a+1];if(r===void 0||r.startsWith("-"))throw new Ht(`Flag ${o} requires a value`);if(!t.test(r))throw new Ht(`Unsafe value for flag ${o}`);a++;}}}async function qe(e){Cp(e);let a=e.slice(Wd.length).split(/\s+/).filter(Boolean);vk(a);let o=yk(a);Vt.debug(`[${o}] Executing proxy command: claude ${a.join(" ")}`);let t=Date.now();try{let r=await execa("claude",a,{reject:!1}),i=Date.now()-t;return Vt.debug(`[${o}] Proxy command finished with exit code ${r.exitCode} in ${i}ms`),{name:o,command:e,exitCode:r.exitCode??1,stdout:r.stdout,stderr:r.stderr,duration_ms:i}}catch(r){throw Jd(r)?new bs:r}}function yk(e){return e.length>=3?e[2]:e.join(" ")}function Jd(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function kk(e){return e.startsWith(Pp)?Wd+e.slice(Pp.length):e}function Pk(e){return gk.test(e)||fk.test(e)}function Dk(e){let a=0;for(;a<e.length&&Pk(e[a]);)a++;return e.slice(a)}var wk=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Sk(e,a){return !a||e.includes("--scope")||!wk.test(e)?e:`${e} --scope ${a}`}async function Br(e,a){let o=e.split("&&").map(s=>s.trim()).filter(Boolean),r=Dk(o).map(s=>kk(s)).map(s=>Sk(s,a));if(r.length===0)throw new Error("Empty install command");for(let s of r)bk(s);Vt.debug(`[installCommand] Executing ${r.length} command(s)`);let i=await qe(r[0]);if(i.exitCode!==0)return i;for(let s=1;s<r.length;s++)if(i=await qe(r[s]),i.exitCode!==0)return i;return i}async function vs(e,a,o){let t=Bt(e),r=a?.trim();if(!r&&(r=(await Jt(`Plugin "${t}" could not be installed.
|
|
116
|
+
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!r))throw new Error("No marketplace source provided. Cannot retry install.");r=us(r),o?.(),Vt.debug(`[${t}] Adding marketplace via: claude plugin marketplace add ${r}`);try{let i=await execa("claude",["plugin","marketplace","add",r],{reject:!1});if(i.exitCode!==0)throw new Error(`Failed to add marketplace: ${i.stderr||"unknown error"}`);Vt.debug(`[${t}] Marketplace added successfully`);}catch(i){throw Jd(i)?new bs:i}}qo();U();Oe();I();var Ek=6e4,No=class extends Error{url;isTimeout;isAuthError;constructor(a,o,t=false,r=false){super(a),this.name="GitCloneError",this.url=o,this.isTimeout=t,this.isAuthError=r;}};async function Sa(e,a){let o=await mkdtemp(join(tmpdir(),"flow-skills-")),t=simpleGit({timeout:{block:Ek}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),r=a?["--depth","1","--branch",a]:["--depth","1"];try{return await t.clone(e,o,r),o}catch(i){await rm(o,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),n=s.includes("block timeout")||s.includes("timed out"),d=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw n?new No("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):d?new No(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new No(`Failed to clone ${e}: ${s}`,e,false,false)}}async function Ca(e){let a=normalize(resolve(e)),o=normalize(resolve(tmpdir()));if(!a.startsWith(o+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm(e,{recursive:true,force:true});}async function lt(e,a=["--version"]){try{return (await execa(e,a,{reject:!1})).exitCode===0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return false;throw o}}function Tk(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Mk(e){return typeof e=="object"&&e!==null&&e.source==="url"}function qk(e){return typeof e=="object"&&e!==null&&e.source==="github"}function ut(e,a){let o=e.source;if(Tk(o)){let t=o.path?o.path.replace(/^\.\//,""):".",r=o.ref&&!/^[0-9a-f]{40}$/i.test(o.ref)?o.ref:void 0;return {cloneUrl:o.url,subPath:t||".",ref:r}}if(Mk(o))return {cloneUrl:o.url,subPath:"."};if(qk(o))return {cloneUrl:`https://github.com/${o.repo}`,subPath:"."};if(typeof o=="string"){if(o.startsWith("https://")||o.startsWith("git@"))return {cloneUrl:o,subPath:"."};if((o.startsWith("./")||o===".")&&a){let t=o==="."?".":o.replace(/^\.\//,"")||".";return {cloneUrl:a,subPath:t}}}return null}function da(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Ra=k("claude-code.adapter");function Fk(e,a){let o=e??"external";if(!a)return o;let t=a.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!t)return o;let r=t[1],i=Ho();if(!ie__default.existsSync(i))return o;try{let s=JSON.parse(ie__default.readFileSync(i,"utf-8"));for(let[n,d]of Object.entries(s))if(d.source?.repo===r)return n}catch{}return o}async function qp(e,a){let o=e.catalogId?ge.getAdapter(e.catalogId):void 0,t=ut(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=e.type==="bundle"||e.type==null,i=Fk(e.catalogId,o?.source),s=a.scope??"user",n;r?n=Cn(i,e.name,"external"):n=join(Vo(s==="user"?"global":"project"),e.name);let d=null;try{ia(e.name),d=await Sa(t.cloneUrl,t.ref);let l=t.subPath==="."?d:join(d,t.subPath);if(ie__default.existsSync(n)&&ie__default.rmSync(n,{recursive:!0,force:!0}),ie__default.mkdirSync(dirname(n),{recursive:!0}),ie__default.cpSync(l,n,{recursive:!0}),r){let c=`${e.name}@${i}`,u=await Ld(),m={scope:s,installPath:n,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=u.plugins[c]??[];u.plugins[c]=[...p.filter(f=>f.scope!==s),m],na(u),Fr(c,!0,s);}return {success:!0,message:`Installed ${e.name} from ${t.cloneUrl}`}}catch(l){return Ra.debug(`[${e.name}] External catalog install failed: ${String(l)}`),{success:false,message:l instanceof Error?l.message:String(l)}}finally{d&&await Ca(d).catch(()=>{});}}async function Hd(e,a,o,t){try{await C(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:o,source:"external",scope:ds(t),version:"unknown",duration_ms:a,interface:ee().interfaceType});}catch(r){Ra.warn(`Failed to send external install metrics: ${String(r)}`);}}async function Ip(e,a,o){try{await C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:o,source:"external",error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:ee().interfaceType});}catch(t){Ra.warn(`Failed to send external install-failed metrics: ${String(t)}`);}}var Ok={async install(e,a){if(e.origin===ht&&!e.installCommand&&!Gt(e.name))return qp(e,a);if(e.origin===ht&&e.installCommand){let o=e.type??"skill",t=await Br(e.installCommand,a.scope);return t.exitCode===0?(await Hd(e.name,t.duration_ms,o,a.scope),{success:true,message:`Installed ${e.name}`}):(await Ip(e.name,new Error(t.stderr||"Install failed"),o),{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`})}if(Gt(e.name)){let o=e.type??"skill",t=jt(e.name,a.scope);Ra.debug(`[${e.name}] Attempting install: ${t}`);let r=await qe(t);if(r.exitCode===0)return await Hd(e.name,r.duration_ms,o,a.scope),{success:true};Ra.debug(`[${e.name}] First attempt failed, adding marketplace`),await vs(e.name,a.marketplaceSource,()=>{});let i=await qe(t);return i.exitCode===0?(await Hd(e.name,i.duration_ms,o,a.scope),{success:true}):(await Ip(e.name,new Error(i.stderr||"Install failed"),o),{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`})}try{let o=await je(e.name,{...a,type:e.type});return {success:!0,message:`Installed ${e.name}@${o.version}`}}catch(o){return Ra.debug(`[${e.name}] Plugin install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}},async uninstall(e,a){await Or(e,a);},getInstallPath(e,a){return ""}};function Tp(e){return {async install(a,o){if(a.origin===ht&&!a.installCommand&&!Gt(a.name))return qp(a,o);if(!a.installCommand)try{let r=await je(a.name,{...o,type:e});return {success:!0,message:`Installed ${a.name}@${r.version}`}}catch(r){return Ra.debug(`[${a.name}] ${e} install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}Ra.debug(`[${a.name}] Executing install command: ${a.installCommand}`);let t=await Br(a.installCommand,o.scope);return t.exitCode===0?{success:true}:{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`}},async uninstall(a,o){let t=Ae(),r=`${a}@${ue}`;if(t.plugins[r]){await Or(a,o);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${a}`)},getInstallPath(a,o){return ""}}}function Nk(e){for(let a of [join(e,".claude","agents"),join(e,"agents")]){if(!ie__default.existsSync(a))continue;let o=ie__default.readdirSync(a).filter(t=>t.endsWith(".md")&&ie__default.lstatSync(join(a,t)).isFile());if(o.length>0)return o.map(t=>join(a,t))}return []}function Gk(e){for(let a of [join(e,".claude","rules"),join(e,"rules")]){if(!ie__default.existsSync(a))continue;let o=ie__default.readdirSync(a).filter(t=>t.endsWith(".md")&&ie__default.lstatSync(join(a,t)).isFile());if(o.length>0)return o.map(t=>join(a,t))}return []}async function Vd(e,a,o,t){let r=await Ld(),i=`${e}@claude-code`,s={scope:a,installPath:o,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:t},n=r.plugins[i]??[];r.plugins[i]=[...n.filter(d=>d.scope!==a),s],na(r);}var Bk={async install(e,a){let o=a.scope??"user",t=e.catalogId?ge.getAdapter(e.catalogId):void 0,r=ut(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{ia(e.name),i=await Sa(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=Nk(s);if(n.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let d=vi(o);ie__default.mkdirSync(d,{recursive:!0});let l=da(e.name);if(n.length===1)ie__default.copyFileSync(n[0],join(d,`${l}.md`));else for(let u of n){let m=da(basename(u,".md"));ie__default.copyFileSync(u,join(d,`${l}--${m}.md`));}let c=n.length===1?join(d,`${l}.md`):d;return await Vd(e.name,o,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(s){return Ra.debug(`[${e.name}] Agent install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ca(i).catch(()=>{});}},async uninstall(e,a){let o=vi(a),t=da(e);if(ie__default.existsSync(o))for(let n of ie__default.readdirSync(o).filter(d=>d===`${t}.md`||d.startsWith(`${t}--`)&&d.endsWith(".md")))ie__default.rmSync(join(o,n),{force:true});let r=`${e}@claude-code`,i=Ae(),s=(i.plugins[r]??[]).filter(n=>n.scope!==a);if(s.length===0){let{[r]:n,...d}=i.plugins;na({...i,plugins:d});}else na({...i,plugins:{...i.plugins,[r]:s}});},getInstallPath(e,a){return join(vi(a),`${da(e)}.md`)}},jk={async install(e,a){let o=a.scope??"user",t=e.catalogId?ge.getAdapter(e.catalogId):void 0,r=ut(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{ia(e.name),i=await Sa(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=Gk(s);if(n.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let d=Dt(o);ie__default.mkdirSync(d,{recursive:!0});for(let l of n)ie__default.copyFileSync(l,join(d,basename(l)));return await Vd(e.name,o,d,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(s){return Ra.debug(`[${e.name}] Rule install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ca(i).catch(()=>{});}},async uninstall(e,a){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,a){return Dt(a)}},Uk={async install(e,a){let o=a.scope??"user",t=e.catalogId?ge.getAdapter(e.catalogId):void 0,r=ut(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{ia(e.name),i=await Sa(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=join(s,"settings.json");if(!ie__default.existsSync(n))return {success:!1,message:`No settings.json found in "${e.name}"`};let d;try{d=JSON.parse(ie__default.readFileSync(n,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let l=d.hooks;if(!l||typeof l!="object"||Array.isArray(l))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=Sr();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let u=c.status==="ok"?c.settings:{},m=u.hooks!==null&&typeof u.hooks=="object"&&!Array.isArray(u.hooks)?u.hooks:{},p=Gr(m,l);return ji({...u,hooks:p}),await Vd(e.name,o,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(s){return Ra.debug(`[${e.name}] Hook install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ca(i).catch(()=>{});}},async uninstall(e,a){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,a){return ""}},ys=class{id="claude-code";name="Claude Code";async isAvailable(){return lt("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Ok,skill:Tp("skill"),mcp:Tp("mcp"),agent:Bk,hook:Uk,rule:jk}};function ks(e,a){return {async install(o,t){if(!o.installCommand)return {success:false,message:"No install command provided"};let[r,...i]=o.installCommand.split(/\s+/).filter(Boolean);if(!r||!e.has(r))return {success:false,message:`Disallowed command: "${r??""}"`};let s=await execa(r,i,{reject:false});return s.exitCode===0?{success:true}:{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`}},async uninstall(o,t){throw new Error(`MCP uninstall not supported \u2014 ${a.replace("<name>",o)}`)},getInstallPath(o,t){return ""}}}var Wk=new Set(["gh"]),Jk=ks(Wk,"use: gh copilot mcp remove <name>"),Ps=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await lt("gh",["--version"])?lt("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:Jk}};Oe();var Hk=new Set(["opencode"]),Vk=ks(Hk,"use: opencode config remove mcp <name>");function Qk(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
117
|
+
`)}function Lp(){return {async install(e,a){try{ia(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let o=e.catalogId?ge.getAdapter(e.catalogId):void 0,t=ut(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=null;try{r=await Sa(t.cloneUrl,t.ref);let i=t.subPath==="."?r:join(r,t.subPath),s=bi(a.scope??"user"),n=join(i,".opencode","plugins");if(ie__default.existsSync(n)){let d=ie__default.readdirSync(n).filter(l=>l.endsWith(".js")||l.endsWith(".mjs"));if(d.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};ie__default.mkdirSync(s,{recursive:!0}),ie__default.copyFileSync(join(n,d[0]),join(s,`${e.name}.js`));}else {let d=join(s,`${e.name}-content`);ie__default.existsSync(d)&&ie__default.rmSync(d,{recursive:!0,force:!0}),ie__default.mkdirSync(d,{recursive:!0}),ie__default.cpSync(i,d,{recursive:!0}),ie__default.mkdirSync(s,{recursive:!0}),ie__default.writeFileSync(join(s,`${e.name}.js`),Qk(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(i){return {success:false,message:i instanceof Error?i.message:String(i)}}finally{r&&await Ca(r).catch(()=>{});}},async uninstall(e,a){ia(e);let o=bi(a),t=join(o,`${e}.js`),r=join(o,`${e}-content`);ie__default.existsSync(t)&&ie__default.rmSync(t,{force:true}),ie__default.existsSync(r)&&ie__default.rmSync(r,{recursive:true,force:true});},getInstallPath(e,a){return join(bi(a),`${e}.js`)}}}var Ds=class{id="opencode";name="OpenCode";async isAvailable(){return lt("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Vk,skill:Lp(),bundle:Lp()}};var Ha=new ns;Ha.register(new ys);Ao()&&(Ha.register(new Ps),Ha.register(new Ds));function Fp({itemName:e,itemType:a,onInstall:o,onClose:t}){let[r,i]=useState(false),[s,n]=useState(false),[d,l]=useState([]),[c,u]=useState(void 0);useEffect(()=>{Ha.getAvailableProviders(a??"bundle").then(l).catch(()=>{});},[a]);let m=useCallback(h=>{h==="Install"?d.length>1?n(true):i(true):t();},[t,d.length]),p=useCallback(h=>{if(h==="Cancel"){n(false);return}let b=d.find(D=>D.name===h);b?(u(b.id),n(false),i(true)):n(false);},[d]),f=useCallback(h=>{let b=Wu(h);b?o(b,c):i(false);},[o,c]),g=useCallback(()=>{i(false);},[]);if(s){let h=[...d.map(b=>b.name),"Cancel"];return jsx(ra,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>n(false)},"provider")}return r?jsx(ra,{itemName:`${e} \u2014 Choose scope`,actions:Uu,descriptions:zu,onAction:f,onClose:g},"scope"):jsx(ra,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:t},"main")}B();function Np({itemName:e,bundle:a,onInstall:o,onConfirm:t,onClose:r}){let i=y(f=>f.focus),[s,n]=useState(0),l=(a?.artifact.artifacts??[]).filter(f=>f.available),c=a!==void 0&&l.length===0,u=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{n(0);},[a]);let m=useCallback((f,g)=>{g.upArrow?n(h=>Math.max(0,h-1)):g.downArrow?n(h=>Math.min(u.length-1,h+1)):g.return?u[s]==="Confirm Install"?t():r():g.escape&&r();},[u,s,t,r]);useInput(m,{isActive:i==="actionMenu"&&a!==void 0});let p=useCallback(f=>{f==="Install Bundle"?o():r();},[o,r]);return a?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:a.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[l.length," artifact",l.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:l.map(f=>{let g=v(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:u.map((f,g)=>jsx(Box,{children:jsxs(Text,{bold:g===s,color:g===s?"cyan":void 0,children:[g===s?"\u203A ":" ",f]})},f))})]}):jsx(ra,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:r})}function Cs({activeFocus:e,onConfirm:a}){let[o,t]=useState("idle"),r=y(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?t("idle"):i==="y"&&a();},{isActive:o==="confirming"&&r===e}),{isConfirming:o==="confirming",requestConfirm:()=>t("confirming"),cancelConfirm:()=>t("idle")}}B();function jp({itemName:e,itemScope:a,itemStatus:o,updateAvailable:t,catalogVersion:r,onUninstall:i,onToggleStatus:s,onUpdate:n,onClose:d}){let{isConfirming:l,requestConfirm:c}=Cs({activeFocus:"actionMenu",onConfirm:()=>i(a)});if(l)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let u=o==="enabled"?"Disable":"Enable",m=r&&v(r),p=m?`Update to v${m}`:"Update";return jsx(ra,{itemName:e,actions:t?["Uninstall",u,p,"Cancel"]:["Uninstall",u,"Cancel"],onAction:h=>{h==="Uninstall"?c():h===u?s(a):h.startsWith("Update")?n?.():d();},onClose:d})}function Wp({itemName:e,itemScope:a,onUninstall:o,onClose:t}){let{isConfirming:r,requestConfirm:i}=Cs({activeFocus:"actionMenu",onConfirm:()=>o(a)});return r?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(ra,{itemName:e,actions:["Uninstall","Cancel"],onAction:d=>{d==="Uninstall"?i():t();},onClose:t})}I();var Xt=k("bundle:installer"),Jp=/already exists/i;async function aP(e){if(!e.installCommand)throw new Error("Missing install command");let a=e.installCommand;if(wp(a)){let o=await Sp(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(Jp.test(t))return;throw new Error(t)}}else {let o=await Br(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(Jp.test(t))return;throw new Error(t)}}}async function oP(e,a){try{await C(w.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:a});}catch(o){Xt.warn(`Failed to emit bundle install started event: ${String(o)}`);}}async function tP(e,a,o){try{await C(w.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:a,artifact_type:o});}catch(t){Xt.warn(`Failed to emit bundle install plugin success event: ${String(t)}`);}}async function Hp(e,a,o,t){try{await C(w.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:a,artifact_type:o,error_message:t});}catch(r){Xt.warn(`Failed to emit bundle install plugin failed event: ${String(r)}`);}}async function rP(e,a,o,t,r){try{await C(w.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:a,failed_count:o,unavailable_count:t,duration_ms:r});}catch(i){Xt.warn(`Failed to emit bundle install completed event: ${String(i)}`);}}async function xs(e,a={}){let{onProgress:o}=a,t=e.artifact.artifacts,r=t.filter(p=>p.available),i=t.length-r.length,s=e.artifact.name,n=Date.now();await oP(s,r.length);let d=[],l=0,c=r.length;for(let[p,f]of r.entries()){let g=f.name??f.flowId,h=f.type??"unknown";if(!f.type){Xt.warn(`Artifact "${g}" has no type \u2014 treated as failed`),d.push({name:g,type:h,reason:"unknown artifact type"}),await Hp(s,g,h,"unknown artifact type"),o?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await aP(f),l++,await tP(s,g,h),o?.({index:p+1,total:c,artifact:f,success:!0});}catch(b){let D=b instanceof Error?b.message:String(b);Xt.error(`Failed to install artifact "${g}": ${D}`),d.push({name:g,type:h,reason:D}),await Hp(s,g,h,D),o?.({index:p+1,total:c,artifact:f,success:false,error:D});}}let u=Date.now()-n,m=d.length;return await rP(s,l,m,i,u),{bundleTitle:e.title,total:t.length,installed:l,skipped:i,failed:m,failures:d}}B();function Xp({bundle:e,onComplete:a}){let[o,t]=useState(null),[r,i]=useState(null),s=useRef(false);return useEffect(()=>{s.current||(s.current=true,xs(e,{onProgress:t}).then(i).catch(n=>{let d=n instanceof Error?n.message:"Installation failed",l=e.artifact.artifacts,c=l.filter(u=>u.available);i({bundleTitle:e.title,total:l.length,installed:0,skipped:l.length-c.length,failed:c.length,failures:c.map(u=>({name:u.name??u.flowId,type:u.type??"unknown",reason:d}))});}));},[e]),useEffect(()=>{r&&a(r);},[r,a]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(_p,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",o.index,"/",o.total,"] Installing"," ",v(o.artifact.name??o.artifact.flowId)," (",o.artifact.type??"unknown",")"]})]}),!o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(_p,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ye=create(e=>({installedItems:[],setInstalledItems:a=>e({installedItems:a}),loadFromDisk:()=>e({installedItems:ce()})}));B();function Kp({entries:e,selectedIndex:a,focusPanel:o}){let t=o==="list",r=a===0&&t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:r,dimColor:!t,children:"+ Add Marketplace"})]}),e.map((i,s)=>{let n=s+1,d=a===n&&t,l=i.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:d?"\u203A ":" "}),jsx(Text,{bold:d,dimColor:!t,children:i.adapter.name}),l&&i.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),i.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",La(i.stored.lastUpdated)]})})]},i.adapter.id)})]})}B();function $p({entry:e,detailData:a,installedCount:o,focusPanel:t,actionIndex:r,onBrowse:i,onUpdate:s,onToggleAutoUpdate:n,onRemove:d}){let{adapter:l,stored:c}=e,u=l.removable!==false,m=c?.autoUpdate!==false,p=t==="detail",f=[{label:`Browse plugins${a&&!a.loading?` (${a.items.length})`:""}`,handler:i},{label:"Update marketplace",handler:s},...u?[{label:"Toggle auto-update",handler:n},{label:"Remove marketplace",handler:d,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:a?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):a?.error?jsx(Text,{color:"red",children:a.error}):jsxs(Text,{dimColor:true,children:[a?`${a.items.length} available`:"\u2014 available",o>0?` \xB7 ${o} installed`:"",c?.lastUpdated?` \xB7 Updated ${La(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 b=h===r;return jsxs(Box,{children:[jsx(Text,{color:b?"cyan":void 0,children:b?"\u203A ":" "}),jsx(Text,{bold:b,color:g.danger?"yellow":void 0,dimColor:!b,children:g.label})]},g.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function Yp(e){return e.adapter.removable!==false?4:2}U();B();function Zp({item:e,adapterName:a,isInstalled:o,onBack:t,onInstall:r,onUninstall:i}){let s=[...o&&i?[{label:"Uninstall",handler:()=>i(e),danger:true}]:!o&&r?[{label:"Install",handler:()=>r(e)}]:[],{label:"Back",handler:t}],[n,d]=useState(0);return useInput((l,c)=>{if(c.escape){t();return}if(c.upArrow){d(u=>Math.max(0,u-1));return}if(c.downArrow){d(u=>Math.min(s.length-1,u+1));return}c.return&&s[n].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",a," \u203A Browse plugins \u203A ",v(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:v(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",v(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",v(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:v(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 ",v(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",v(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",v(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:s.map((l,c)=>jsxs(Box,{children:[jsx(Text,{color:c===n?"cyan":void 0,children:c===n?"\u203A ":" "}),jsx(Text,{bold:c===n,color:l.danger?"yellow":void 0,dimColor:c!==n,children:l.label})]},l.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function am({item:e,isSelected:a,isInstalled:o}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:a?"\u203A ":" "}),jsx(Text,{color:o?"green":void 0,bold:a,children:e.name}),o&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function om({entry:e,items:a,installedKeys:o,onBack:t}){let r=e.adapter.id??"default",i=a.filter(A=>o.has(`${A.name}@${r}`)),s=a.filter(A=>!o.has(`${A.name}@${r}`)),n=[...i,...s],[d,l]=useState(0),[c,u]=useState(null);if(useInput((A,T)=>{if(T.escape){t();return}if(T.return){u(n[d]??null);return}if(T.upArrow){l(F=>Math.max(0,F-1));return}T.downArrow&&l(F=>Math.min(n.length-1,F+1));},{isActive:c===null}),c!==null)return jsx(Zp,{item:c,adapterName:e.adapter.name,isInstalled:o.has(`${c.name}@${r}`),onBack:()=>u(null)});if(a.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,d-Math.floor(ea/2)),p=Math.min(n.length,m+ea);p===n.length&&(m=Math.max(0,p-ea));let f=n.slice(m,p),g=m,h=n.length-p,b=i.length>0&&m<i.length,D=p>i.length,q=f.filter(A=>o.has(`${A.name}@${r}`)),L=f.filter(A=>!o.has(`${A.name}@${r}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),b&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),q.map(A=>jsx(am,{item:A,isSelected:n.indexOf(A)===d,isInstalled:true},A.name))]}),D&&jsxs(Box,{flexDirection:"column",marginTop:b?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),L.map(A=>jsx(am,{item:A,isSelected:n.indexOf(A)===d,isInstalled:false},A.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"})})]})}Sd();var uP=/^https?:\/\/.+/;function pP(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function mP(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function sm(e){let a=y(h=>h.showNotification),o=y(h=>h.incrementCatalogVersion),[t,r]=useState("idle"),[i,s]=useState(""),[n,d]=useState(""),[l,c]=useState(null),u=useRef(""),m=useRef("");useEffect(()=>{u.current=i;},[i]),useEffect(()=>{m.current=n;},[n]);let p=useCallback(()=>{u.current="",m.current="",s(""),d(""),c(null),r("add-name");},[]),f=useCallback(()=>{r("idle");},[]),g=useCallback(async()=>{let h=m.current,b=u.current;if(!uP.test(h)){c("URL must start with http:// or https://");return}c(null),r("adding");let D=randomUUID(),q=new zt(D,b,h);try{await q.fetchItems(),await oo.add({id:D,name:b,source:h}),ge.register(new zt(D,b,h)),o(),e(),a(`Catalog "${b}" added`,"success"),s(""),d(""),u.current="",m.current="",r("idle");}catch(L){let A=pP(L)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":mP(L)?L.message:L instanceof Error?`Could not reach catalog URL: ${L.message}`:"Failed to validate catalog URL";a(A,"error"),r("add-url");}},[e,a,o]);return useInput((h,b)=>{if(b.escape){r("idle");return}if(b.return){u.current.trim().length>0&&r("add-url");return}if(b.backspace||b.delete){u.current=u.current.slice(0,-1),s(u.current);return}h&&!b.ctrl&&!b.meta&&(u.current=u.current+h,s(u.current));},{isActive:t==="add-name"}),useInput((h,b)=>{if(b.escape){r("add-name");return}if(b.return){g();return}if(b.backspace||b.delete){m.current=m.current.slice(0,-1),d(m.current),c(null);return}h&&!b.ctrl&&!b.meta&&(m.current=m.current+h,d(m.current),c(null));},{isActive:t==="add-url"}),{phase:t,inputName:i,inputUrl:n,urlError:l,setInputName:s,setInputUrl:d,startAdd:p,cancelAdd:f}}function nm(e){let a=y(r=>r.showNotification),o=y(r=>r.incrementCatalogVersion);return {handleRemove:useCallback(async r=>{try{await oo.remove(r),ge.unregister(r),o(),e(),a("Catalog removed","success");}catch(i){a(i instanceof Error?i.message:"Failed to remove catalog","error");}},[e,a,o])}}function cm(){let e=y(E=>E.focus),a=y(E=>E.setFocus),o=y(E=>E.showNotification),t=ye(E=>E.installedItems),[r,i]=useState(()=>ge.listAdapters().map(E=>({adapter:E,stored:null}))),[s,n]=useState(0),[d,l]=useState("list"),[c,u]=useState(0),[m,p]=useState(null),[f,g]=useState("main"),h=useRef(r);useEffect(()=>{h.current=r;},[r]),useEffect(()=>{f==="browse"&&!r[s-1]&&g("main");},[f,r,s]);let b=useCallback(()=>{(async()=>{let E=ge.listAdapters(),j=await oo.read(),V=new Map(j.map(Fe=>[Fe.id,Fe]));i(E.map(Fe=>({adapter:Fe,stored:V.get(Fe.id)??null})));})();},[]);useEffect(()=>{a("marketplaces"),b();},[a,b]),useEffect(()=>{if(s===0){p(null);return}let E=h.current[s-1];if(!E)return;let j=false;return p({items:[],loading:true,error:null}),E.adapter.fetchItems().then(V=>{j||p({items:V,loading:false,error:null});}).catch(V=>{j||p({items:[],loading:false,error:V instanceof Error?V.message:"Failed to load catalog"});}),()=>{j=true;}},[s]);let D=sm(b),q=useCallback(()=>{b(),n(0),l("list"),p(null),g("main");},[b]),{handleRemove:L}=nm(q),A=useCallback(async E=>{g("removing"),await L(E);},[L]),T=useCallback(async E=>{try{let j=await E.adapter.fetchItems();if(p({items:j,loading:!1,error:null}),E.stored){let V=new Date().toISOString();await oo.updateField(E.stored.id,{lastUpdated:V}),b();}o("Marketplace updated","success");}catch(j){o(j instanceof Error?j.message:"Update failed","error");}},[b,o]),F=useCallback(async E=>{if(!E.stored)return;let j=E.stored.autoUpdate!==false;await oo.updateField(E.stored.id,{autoUpdate:!j}),b();},[b]),O=useCallback(()=>g("browse"),[]),oe=useCallback(E=>{let j=r[s-1];if(!j)return;let V=j.adapter.removable!==false;[O,()=>{T(j);},...V?[()=>{F(j);},()=>{A(j.adapter.id);}]:[]][E]?.();},[r,s,O,T,F,A]),x=useCallback(()=>g("main"),[]),J=useCallback(()=>{let E=r[s-1];E&&T(E);},[r,s,T]),ae=useCallback(()=>{let E=r[s-1];E&&F(E);},[r,s,F]),z=useCallback(()=>{let E=r[s-1];E&&A(E.adapter.id);},[r,s,A]);if(useInput((E,j)=>{if(j.upArrow){n(V=>Math.max(0,V-1));return}if(j.downArrow){n(V=>Math.min(r.length,V+1));return}(j.return||j.tab)&&(s===0?D.startAdd():(l("detail"),u(0)));},{isActive:f==="main"&&D.phase==="idle"&&d==="list"&&e==="marketplaces"}),useInput((E,j)=>{if(j.escape||j.tab){l("list");return}if(j.upArrow){u(V=>Math.max(0,V-1));return}if(j.downArrow){let V=r[s-1],Fe=V?Yp(V)-1:0;u(ui=>Math.min(ui+1,Fe));return}j.return&&oe(c);},{isActive:f==="main"&&D.phase==="idle"&&d==="detail"&&e==="marketplaces"}),D.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:D.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),D.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(D.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:D.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:D.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),D.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:D.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(D.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 E=r[s-1];if(!E)return jsx(Box,{});let j=E.adapter.id??"default",V=new Set(t.filter(Fe=>Fe.marketplace===E.adapter.name).map(Fe=>`${Fe.name}@${j}`));return jsx(om,{entry:E,items:m?.items??[],installedKeys:V,onBack:x})}if(r.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let W=r[s-1]??null,X=W?t.filter(E=>E.marketplace===W.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Kp,{entries:r,selectedIndex:s,focusPanel:d})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:d==="detail"&&W?jsx($p,{entry:W,detailData:m,installedCount:X,focusPanel:d,actionIndex:c,onBrowse:O,onUpdate:J,onToggleAutoUpdate:ae,onRemove:z}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:W?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:d==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function lm(e,a,o,t){if(a.upArrow)return o.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:o.selectedIndex-1}];if(a.downArrow&&o.selectedIndex<t-1)return [{type:"setSelectedIndex",index:o.selectedIndex+1}];if(a.leftArrow){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r-1+re.length)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.rightArrow){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r+1)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.tab){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r+1)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}return a.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="8"?[{type:"toggleTypeFilter",catalogType:"agent"}]:e==="9"?[{type:"toggleTypeFilter",catalogType:"hook"}]:e==="0"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="a"&&o.activeTab==="updates"?[]:e&&e!==" "&&!a.ctrl&&!a.meta&&!a.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function um(e,a){return a.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function pm(e,a,o){return a.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:a.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:a.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:a.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.backspace?o.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!a.ctrl&&!a.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var vP=new Set(re.filter(e=>e.focus!=="list").map(e=>e.focus));function Xr(e){let{setActiveTab:a,setFocus:o,setSelectedIndex:t,setActionMenuOpen:r}=y.getState();for(let i of e)if(i.type==="setTab")a(i.tab);else if(i.type==="setFocus")o(i.focus);else if(i.type==="setSelectedIndex")t(i.index);else if(i.type==="setActionMenuOpen")r(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:n,setCursorPosition:d,cursorPosition:l}=_e.getState();s(n.slice(0,l)+i.char+n.slice(l)),d(l+i.char.length);}else i.type==="toggleTypeFilter"?y.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?y.getState().selectAllTypes():i.type==="toggleOriginFilter"?y.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&y.getState().selectAllOrigins();}function mm({listLength:e}){let a=y(g=>g.focus),o=y(g=>g.selectedIndex),t=y(g=>g.actionMenuOpen),r=y(g=>g.setFocus),i=y(g=>g.setActionMenuOpen),s=_e(g=>g.query),n=_e(g=>g.setQuery),d=_e(g=>g.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(a==="search"){let{query:g,setCursorPosition:h}=_e.getState();h(g.length);}},[a]);let[c,u]=useState("");useEffect(()=>{let g=setTimeout(()=>u(s),300);return ()=>clearTimeout(g)},[s]),useInput((g,h)=>{let{activeTab:b,selectedIndex:D,actionMenuOpen:q}=y.getState();Xr(dd(g,h,{activeTab:b}));},{isActive:a==="tabs"}),useInput((g,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:b,selectedIndex:D,actionMenuOpen:q}=y.getState();Xr(dd("",h,{activeTab:b}));},{isActive:vP.has(a)}),useInput((g,h)=>{let{activeTab:b,selectedIndex:D,actionMenuOpen:q}=y.getState();Xr(lm(g,h,{activeTab:b,selectedIndex:D},l.current));},{isActive:a==="list"}),useInput((g,h)=>{Xr(um(g,h));},{isActive:a==="actionMenu"}),useInput((g,h)=>{let b=pm(g,h,_e.getState().query),D=b.queryUpdate;if(Xr(b.actions),D==="reset")d(),u("");else if(D!==null){let{query:q,cursorPosition:L,setCursorPosition:A}=_e.getState();if("backspace"in D)L>0&&(n(q.slice(0,L-1)+q.slice(L)),A(L-1));else if("append"in D)n(q.slice(0,L)+D.append+q.slice(L)),A(L+D.append.length);else if("cursorMove"in D){let T=L+D.cursorMove;T>=0&&T<=q.length&&A(T);}}},{isActive:a==="search"});let m=useCallback(()=>{i(false),r("list");},[i,r]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:b}=y.getState();g===0?h(0):b>=g&&h(g-1);},[]),f=useCallback(g=>{if(!c)return l.current=g.length,g;let h=c.toLowerCase(),b=g.filter(D=>D.name.toLowerCase().includes(h)||D.description?.toLowerCase().includes(h));return l.current=b.length,b},[c]);return {actionMenuOpen:t,closeMenu:m,selectedIndex:o,clampIndex:p,filteredItems:f}}function fm(){let e=y(n=>n.notification),a=y(n=>n.showNotification),o=y(n=>n.clearNotification),t=oa(n=>n.justAuthenticated),r=oa(n=>n.credentials),i=oa(n=>n.setJustAuthenticated);return useEffect(()=>{t&&r&&(a(`Authenticated. Tenant: ${r.tenant}`,"success"),i(false));},[t,r]),useEffect(()=>{if(!e)return;let n=setTimeout(o,3e3);return ()=>clearTimeout(n)},[e]),{notify:(n,d)=>{a(n,d);}}}function ze(e,a,o=false){return o?true:!$d.valid(e)||!$d.valid(a)?false:$d.gt(a,e)}U();I();var so=k("updater");async function yP(e,a,o,t,r,i){try{await C(w.CLI_TOOL_UPDATED,{tool_id:e,tool_type:i,source:r,from_version:a,to_version:o,duration_ms:t,interface:ee().interfaceType});}catch(s){so.warn(`Failed to send update metrics: ${String(s)}`);}}function kP(e){let a=Ae(),o=`${e}@${ue}`,t=a.plugins[o];return !t||t.length===0?null:{pluginKey:o,entry:t[0]}}async function Ms(e,a={}){let o=Date.now(),t=null;try{so.debug(`[${e}] Acquiring lock...`),t=await Lo();let r=kP(e);if(!r)throw so.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=r,s=i.version,n=i.installPath;so.debug(`[${e}] Fetching manifest...`);let l=(await Wt(e,a.source)).version;if(!s||!ze(s,l,a.force))throw so.debug(`[${e}] Already up to date (v${s??"n/a"})`),new Mo(e,s??"unknown");so.info(`[${e}] Updating v${s} \u2192 v${l}...`),await t(),t=null;try{let c=await je(e,{force:!0,skipMetrics:!0,source:a.source}),u=Date.now()-o;return await yP(c.name,s,c.version,u,i.origin??"internal",i.type??"skill"),so.debug(`[${e}] Updated successfully in ${u}ms`),{name:c.name,previousVersion:s,newVersion:c.version,path:c.path,duration_ms:u}}catch(c){so.warn(`[${e}] Install failed, rolling back to v${s}...`),t=await Lo();let u=Ae(),m=`${e}@${ue}`;throw u.plugins[m]&&(u.plugins[m][0].version=s,u.plugins[m][0].installPath=n,na(u),so.info(`[${e}] Rollback completed, restored to v${s}`)),c}}finally{t&&await t();}}qo();I();var qs=k("dispatcher");async function PP(e,a,o,t,r){let i=Bt(e);return qs.debug(`[${e}] Install failed (exit code), attempting marketplace add`),r?.onError?.(o),t?r?.onStatus?.(`Adding marketplace for ${i}...`):r?.onPause?.(),await vs(e,t,()=>{}),r?.onResume?.(`Retrying install for ${i}...`),qs.debug(`[${e}] Retrying install after marketplace add`),qe(a)}async function hm(e,a,o,t){let r=jt(e,t),i=Bt(e);o?.onStatus?.(`Installing ${i}...`),qs.debug(`[${e}] Attempting install: ${r}`);let s=await qe(r);if(s.exitCode===0)return s;qs.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`);let n=s.stderr||`Install failed with exit code ${s.exitCode}`;return PP(e,r,n,a,o)}async function bm(e,a,o){let t=e.type??"bundle",r=await Ha.getAvailableProviders(t),i=r[0];if(!i)throw new Error(`No available provider for artifact type "${t}"`);let s=i.installers[t];if(!s)throw new Error(`Provider "${i.id}" does not support type "${t}"`);let n=a??{},d=n;return s.install(e,d)}function vm(){let e=ye(s=>s.installedItems),a=ye(s=>s.loadFromDisk),o=useCallback(async(s,n)=>{let d=await bm(s,n);if(!d.success)throw new Error(d.message||"Installation failed");a();},[a]),t=useCallback(async(s,n)=>{let d=ce().find(p=>p.name===s),l=d?.providerId??"claude-code",c=Ha.getAdapter(l);if(!c)throw new Error(`Provider "${l}" not found`);let u=d?.type??"bundle",m=c.installers[u];if(!m)throw new Error(`Provider "${l}" does not support type "${u}"`);await m.uninstall(s,n??"user"),a();},[a]),r=useCallback(async(s,n)=>{let l=e.find(c=>c.name===s)?.status==="enabled"?"disabled":"enabled";await Nr(s,l,n),a();},[e,a]),i=useCallback(async s=>{await Ms(s),a();},[a]);return {install:o,uninstall:t,toggle:r,update:i}}B();I();var Fs=k("mcp");function Kr(e,a){e.silent?Ne({status:"error",mcp:a.name,...a.exitCode!==void 0&&{exitCode:a.exitCode},message:a.message}):S(`Failed to ${a.action} MCP "${a.name}": ${a.message}`);}function km(e,a){e.silent?me({status:"success",mcp:a.name,command:a.command,duration_ms:a.durationMs}):($(`MCP "${a.name}" ${a.actionPastTense} successfully`),e.verbose&&a.stdout&&P(a.stdout));}function DP(e,a,o,t){let r=["claude","mcp","add","--transport",o,e];return a.length>0&&r.push(...a),t&&r.push("--scope",t),r.join(" ")}function Yd(e,a){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let o=["claude","mcp","remove",e];return a&&o.push("--scope",a),o.join(" ")}async function Pm(e,a,o){if(!await he())return 1;if(a.length===0){let i=o.transport==="http"?"a URL":"a command";return Kr(o,{name:e,action:"add",message:`${o.transport} transport requires ${i}`}),1}Fs.debug(`[${e}] Starting MCP add with args: ${a.join(" ")}`);let t=DP(e,a,o.transport,o.scope);if(!o.force){let i=v(e),s=v(t);if(!await _(`Install external MCP "${i}"?
|
|
118
118
|
This will run: ${s}
|
|
119
|
-
[y/N] `))return
|
|
119
|
+
[y/N] `))return Fs.debug(`[${e}] Installation cancelled by user`),P("Operation cancelled."),0}let r=o.silent?void 0:an({text:`Adding MCP "${v(e)}"...`}).start();try{let i=await qe(t);return r?.stop(),i.exitCode!==0?(Kr(o,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!o.silent&&o.verbose&&i.stdout&&P(`stdout: ${i.stdout}`),1):(km(o,{name:e,actionPastTense:"added",command:t,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return r?.stop(),Kr(o,{name:e,action:"add",message:Y(i)}),1}}async function Dm(e,a){if(!await he())return 1;Fs.debug(`[${e}] Starting MCP remove`);let o=Yd(e,a.scope);if(!a.force){let r=v(e),i=v(o);if(!await _(`Remove MCP "${r}"?
|
|
120
120
|
This will run: ${i}
|
|
121
|
-
[y/N] `))return Is.debug(`[${e}] Removal cancelled by user`),P("Operation cancelled."),0}let t=a.silent?void 0:yc({text:`Removing MCP "${v(e)}"...`}).start();try{let r=await qe(o);return t?.stop(),r.exitCode!==0?(_r(a,{name:e,action:"remove",message:r.stderr||"Command failed",exitCode:r.exitCode}),!a.silent&&a.verbose&&r.stdout&&P(`stdout: ${r.stdout}`),1):(fm(a,{name:e,actionPastTense:"removed",command:o,durationMs:r.duration_ms,stdout:r.stdout}),0)}catch(r){return t?.stop(),_r(a,{name:e,action:"remove",message:$(r)}),1}}I();function vm({selectedItem:e,selectedCatalogItem:a,items:o,closeMenu:t,clampIndex:r,notify:i}){let s=k("pluginHandlers"),n=useRef(0),d=y(A=>A.setLoading),l=y(A=>A.setDownloadProgress),{install:c,uninstall:u,toggle:m,update:p}=mm(),g=async(A,T,F)=>{d(true,A),t();try{await T(),r(o.length),i(F,"success");}catch(O){let oe=O instanceof Error?O.message:"Something went wrong";s.error(`[withLoading] ${A} failed: ${oe}`),i(oe,"error");}finally{d(false);}};return {handleInstall:(A,T)=>{e&&a&&(n.current=0,g(`Installing ${e.name}...`,()=>c(a,{scope:A,...T!==void 0?{providerId:T}:{},onDownloadProgress:(F,O)=>{let oe=Date.now();(oe-n.current>100||F>=O)&&(n.current=oe,l(F,O));}}),"\u2713 Installed successfully"));},handleUninstall:A=>{e&&g(`Uninstalling ${e.name}...`,()=>u(e.name,A),"\u2713 Uninstalled");},handleToggleStatus:A=>{if(!e)return;let T=e.status==="enabled";g(T?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,A),T?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let A=a?` to v${a.version}`:"";(async()=>{d(true,`Updating ${e.name}${A}...`),t();try{await p(e.name),r(o.length),i(`\u2713 Updated ${e.name}${A}`,"success");}catch(F){if(F instanceof Io)i(F.message,"info");else {let O=F instanceof Error?F.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${O}`),i(O,"error");}}finally{d(false);}})();},handleBatchUpdate:A=>{if(A.length===0)return;let T=A.length;(async()=>{d(true,`Updating ${T} plugin${T>1?"s":""}...`),t();try{let O=[];for(let J of A)O.push(await p(J.name).then(()=>({status:"fulfilled",value:void 0}),ae=>({status:"rejected",reason:ae})));let oe=O.filter(J=>J.status==="fulfilled").length,x=O.map((J,ae)=>J.status==="rejected"?A[ae].name:null).filter(J=>J!==null);r(o.length),x.length===0?i(`\u2713 Updated ${oe}/${T} plugin${T>1?"s":""}`,"success"):(s.error(`[handleBatchUpdate] failed: ${x.join(", ")}`),i(`Updated ${oe}/${T}; failed: ${x.join(", ")}`,oe>0?"info":"error"));}finally{d(false);}})();},handleMcpConfigUninstall:A=>{e&&g(`Removing MCP ${e.name}...`,async()=>{let T=Vd(e.name,A),F=await qe(T);if(F.exitCode!==0)throw new Error(F.stderr||"MCP removal failed");ye.getState().loadFromDisk();},"\u2713 MCP removed");}}}xr();I();var Xr=k("api:bundle"),Zt=class extends Error{constructor(a){super(`Bundle '${a}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Kr=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},hP=/^[a-zA-Z0-9_-]{1,128}$/;async function km(e,a){if(e instanceof HTTPError){let o=e.response.status;throw Xr.error(`HTTP error fetching bundle '${a}' [status=${o}]`),o===StatusCodes.NOT_FOUND?new Zt(a):o===StatusCodes.INTERNAL_SERVER_ERROR?new Kr:new Error(`Server error (${o}) \u2014 please try again later.`)}throw Xr.error(`Unexpected error fetching bundle '${a}': ${e instanceof Error?e.message:String(e)}`),e}async function Pm(e){if(!hP.test(e))throw new Error("Invalid bundle identifier format.");let a=encodeURIComponent(e);Xr.debug(`Fetching bundle by flowId "${e}"`);try{return await Ua().get(`v1/use-cases/${a}`).json()}catch(o){return km(o,e)}}async function Ts(e){let a=encodeURIComponent(e);Xr.debug(`Fetching bundle by name "${e}"`);let o;try{o=await Ua().get(`v1/use-cases/by-name/${a}`).json(),Xr.debug(`API returned ${o.length} result(s) for "${e}"`);}catch(t){return km(t,e)}if(o.length===0)throw new Zt(e);return o[0]}I();var bP=k("tui:bundle-flow");function Dm({closeMenu:e,notify:a}){let o=y(n=>n.bundleInstallFlow);return {handleBundleInstallStart:(n,d)=>{let{setLoading:l,setBundleInstallFlow:c}=y.getState(),u=d?.trim();bP.debug(`Starting bundle install: itemName="${n}" flowId="${u??"none"}"`),l(true,"Loading bundle..."),(u?Pm(u):Ts(n)).then(p=>{l(false),y.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{l(false),a(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!o||o.phase!=="detail")return;let{setBundleInstallFlow:n,setFocus:d}=y.getState();n({phase:"installing",bundle:o.bundle}),d("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:n}=y.getState();n(null),e();},handleBundleInstallComplete:n=>{y.getState().setBundleInstallFlow(null),e(),ye.getState().loadFromDisk(),a(`\u2713 Installed ${n.installed} of ${n.total} artifacts`,"success");}}}j();U();var $r=["local","project","user"],vP=new Set(["--transport","--scope","-s"]);function wm(e){let a=e.split(/\s+/).filter(Boolean),o=a.indexOf("add");if(o===-1)return null;let t=o+1;for(;t<a.length;){let r=a[t];if(vP.has(r))t+=2;else if(r.startsWith("-"))t+=1;else return r.replace(/^["']|["']$/g,"")}return null}function pt(e,a){return a?`${e}::${a}`:e}function Qd(e){return e===ue?dr:ft}function Sm(e){return {name:v(e.name),version:e.version?v(e.version):e.version,description:e.description?v(e.description):e.description,authorName:e.author?.name?v(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??dr,flowId:e.flowId}}function _d(e,a){let o=Qd(e.marketplace);return {name:v(e.name),version:e.version?v(e.version):e.version,description:e.description?v(e.description):e.description,authorName:e.author?.name?v(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:a?.type??e.type??"bundle",origin:a?.origin??o}}function Cm(e){let a=new Map;for(let o of e){if(!o.scope)continue;let t=a.get(o.scope)??[];t.push(o),a.set(o.scope,t);}return $r.filter(o=>a.has(o)).map(o=>({scope:o,label:Ka[o].label,pathHint:Ka[o].pathHint,items:a.get(o)??[]}))}function Rm(e){let a=o=>{if(!o)return 1/0;let t=$r.indexOf(o);return t===-1?1/0:t};return [...e].sort((o,t)=>a(o.scope)-a(t.scope))}function Am({catalog:e,installedItems:a,activeTab:o,catalogFilters:t,searchQuery:r}){let i=useMemo(()=>new Set(a.map(g=>pt(g.name,g.author?.name))),[a]),s=useMemo(()=>new Set(a.filter(g=>g.type==="mcp").map(g=>g.name.toLowerCase())),[a]),n=useMemo(()=>{let g=new Map(e.map(h=>[pt(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return a.map(h=>{let b=g.get(pt(h.name,h.author?.name))??f.get(h.name),D=b?.version,q=!!D&&!!h.version&&ze(h.version,D);return {...h,updateAvailable:q,catalogItem:b}})},[a,e]),d=useMemo(()=>o==="discover"?e.filter(g=>{if(i.has(pt(g.name,g.author?.name)))return false;if(g.type==="mcp"){let f=g.installCommand?wm(g.installCommand)?.toLowerCase():null;if(s.has(g.name.toLowerCase())||f&&s.has(f))return false}return true}).map(g=>Sm(g)):o==="updates"?n.filter(g=>g.updateAvailable).map(g=>_d(g,g.catalogItem)):n.map(g=>_d(g,g.catalogItem)),[o,e,i,s,n]),l=useMemo(()=>d.filter(g=>{let f=g.type??"bundle";if(!t.types.has(f))return false;let h=g.origin??"internal";return t.origins.has(h)}),[d,t]),c=useMemo(()=>{let{types:g}=t;if(g.size===1){if(g.has("skill"))return "skills";if(g.has("mcp"))return "MCPs";if(g.has("bundle"))return "bundles"}return "items"},[t]),u=useMemo(()=>o==="installed"?r?`No ${c} found for '${r}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:o==="updates"?r?`No ${c} found for '${r}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":r?`No ${c} found for '${r}'`:`No ${c} available in the catalog`,[o,r,c]),m=useMemo(()=>{let g=new Map(e.map(h=>[pt(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return h=>h?g.get(pt(h.name,h.authorName))??f.get(h.name)??null:null},[e]),p=useMemo(()=>n.filter(g=>g.updateAvailable).length,[n]);return {items:l,emptyMessage:u,getSelectedCatalogItem:m,outdatedCount:p}}function Xd(){let[e,a]=useState([]),[o,t]=useState(true),[r,i]=useState(null),[s,n]=useState(null),d=useRef(false),l=y(u=>u.catalogVersion),c=useCallback(async()=>{t(true),i(null),n(null);try{let{items:u,failures:m}=await ep();if(a(u),m.length>0){let p=m.map(g=>g.adapterName).join(", ");n(`Some catalogs failed to load: ${p}`);}d.current||(d.current=!0,C(w.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:u.length}).catch(()=>{}));}catch(u){i(u instanceof Error?u:new Error(String(u))),a([]);}finally{t(false);}},[]);return useEffect(()=>{c();},[c,l]),{catalog:e,isLoading:o,error:r,partialError:s,refetch:c}}function xm(){return {items:ye(a=>a.installedItems)}}I();var wP=k("catalog");function Im(){let e=y(X=>X.bundleInstallFlow),a=y(X=>X.activeTab),o=y(X=>X.notification),t=y(X=>X.loading),r=y(X=>X.loadingMessage),i=y(X=>X.downloadProgress),s=y(X=>X.downloadTotal),n=y(X=>X.catalogError),d=y(X=>X.setCatalogError),l=y(X=>X.catalogFilters),c=_e(X=>X.query),{catalog:u,isLoading:m,error:p,refetch:g}=Xd(),{items:f}=xm(),h=ye(X=>X.loadFromDisk),{items:b,emptyMessage:D,getSelectedCatalogItem:q,outdatedCount:L}=Am({catalog:u,installedItems:f,activeTab:a,catalogFilters:l,searchQuery:c}),{actionMenuOpen:A,closeMenu:T,selectedIndex:F,clampIndex:O,filteredItems:oe}=dm({listLength:b.length}),x=oe(b),J=useMemo(()=>a!=="installed"&&a!=="updates"?x:Rm(x),[a,x]),ae=useMemo(()=>a==="installed"||a==="updates"?Cm(J):[],[a,J]),z=J[F]??null,W=useMemo(()=>q(z),[q,z]),{notify:_}=lm(),{handleInstall:E,handleUninstall:B,handleToggleStatus:V,handleUpdate:Fe,handleBatchUpdate:si,handleMcpConfigUninstall:hh}=vm({selectedItem:z,selectedCatalogItem:W,items:b,closeMenu:T,clampIndex:O,notify:_}),{handleBundleInstallStart:bh,handleBundleDetailConfirm:vh,handleBundleDetailBack:yh,handleBundleInstallComplete:kh}=Dm({closeMenu:T,notify:_}),Ph=useCallback(()=>si(J),[si,J]);return useEffect(()=>{h();},[]),useEffect(()=>{O(J.length);},[J.length,O]),useEffect(()=>{p&&(wP.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),d("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),jsx(cu,{outdatedCount:L}),a==="marketplaces"&&Co()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(rm,{})}):jsx(Au,{filteredItems:J,groups:ae,emptyMessage:D,onBatchUpdate:Ph}),(t||m)&&jsxs(Fragment,{children:[jsx($i,{message:t?r:"Loading catalog..."}),t&&s>0&&i>0&&jsx(Box,{paddingLeft:2,children:jsx(Zi,{received:i,total:s})})]}),n&&!m&&a==="discover"&&jsx(es,{message:n,onRetry:()=>{d(null),g();},onBack:()=>d(null)}),o&&jsx(xu,{message:o.message,type:o.type}),A&&z&&(a==="discover"?W?.type==="bundle"?e?.phase==="installing"?jsx(Jp,{bundle:e.bundle,onComplete:kh}):jsx(Mp,{itemName:z.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>bh(z.name,z.flowId),onConfirm:vh,onClose:e?.phase==="detail"?yh:T}):jsx(Ip,{itemName:z.name,itemType:W?.type,onInstall:E,onClose:T}):z.type==="mcp"?jsx(Gp,{itemName:z.name,itemScope:z.scope??"user",onUninstall:hh,onClose:T}):jsx(Fp,{itemName:z.name,itemScope:z.scope??"user",itemStatus:z.status??"enabled",updateAvailable:z.updateAvailable??false,catalogVersion:W?.version,onUninstall:B,onToggleStatus:X=>V(X),onUpdate:Fe,onClose:T})),jsx(Ki,{})]})}var M=create((e,a)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:o=>e({starterKits:o}),setSelectedStarterKitIndex:o=>e({selectedStarterKitIndex:o}),selectStarterKit:o=>{let t=new Set(ye.getState().installedItems.map(r=>r.name));e({selectedStarterKit:o,plugins:o.plugins.map(r=>({name:r,selected:true,status:t.has(r)?"success":"pending",installed:t.has(r)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:o=>e({pluginCursorIndex:o}),setStep:o=>e({step:o}),setPluginStatus:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,status:t,error:r}:s);e({plugins:i});},setPluginDownloadProgress:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,downloadProgress:t,downloadTotal:r}:s);e({plugins:i});},setIsLoadingStarterKits:o=>e({isLoadingStarterKits:o}),setStarterKitsError:o=>e({starterKitsError:o}),setSummaryActionIndex:o=>e({summaryActionIndex:o}),computeSummary:()=>{let t=a().plugins.filter(r=>r.selected);e({successCount:t.filter(r=>r.status==="success").length,failedCount:t.filter(r=>r.status==="failed").length});},resetForRetry:()=>{let o=a().plugins.map(t=>t.status==="failed"?{...t,status:"pending",error:void 0}:t);e({plugins:o,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Re();var xP=3;function Mm(){let e=M(c=>c.setStarterKits),a=M(c=>c.setIsLoadingStarterKits),o=M(c=>c.setStarterKitsError),t=M(c=>c.setPluginStatus),r=M(c=>c.setPluginDownloadProgress),i=M(c=>c.setStep),s=M(c=>c.computeSummary),n=useCallback(async()=>{a(true),o(null);try{let c=await ns();e(c);}catch(c){o(c instanceof Error?c.message:String(c));}finally{a(false);}},[a,o,e]);useEffect(()=>{ye.getState().loadFromDisk(),n();},[n]);let d=useRef(0),l=useCallback(async()=>{let c=M.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){t(m.name,"installing"),d.current=0;let p="",g=false;for(let f=1;f<=xP;f++)try{await je(m.name,{onDownloadProgress:(h,b)=>{let D=Date.now();(D-d.current>100||h>=b)&&(d.current=D,r(m.name,h,b));}}),t(m.name,"success"),g=!0;break}catch(h){if(h instanceof Xe){t(m.name,"success"),g=true;break}p=h instanceof Error?h.message:"Unknown error";}g||(t(m.name,"failed",p),C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:Z().interfaceType}).catch(()=>{}));}let u=$o();Ko("summary_review"),C(w.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:u}).catch(()=>{}),ye.getState().loadFromDisk(),s(),i("summary");},[t,r,s,i]);return {loadStarterKits:n,installSelected:l}}var Yr={cursorDelta:0,confirm:false,back:false};function qm(e,a){return a.upArrow?{...Yr,cursorDelta:-1}:a.downArrow?{...Yr,cursorDelta:1}:a.escape?{...Yr,back:true}:a.return?{...Yr,confirm:true}:Yr}var EP={cursorDelta:0,select:false};function Lm(e,a){return a.upArrow?{cursorDelta:-1,select:false}:a.downArrow?{cursorDelta:1,select:false}:a.return?{cursorDelta:0,select:true}:EP}j();var Fm=vv.memo(function({starterKit:a,isSelected:o}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:v(a.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",a.plugins.length," ",a.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:v(a.description)})})]})});var oc=5;function Om({onRetry:e}){let a=M(c=>c.starterKits),o=M(c=>c.selectedStarterKitIndex),t=M(c=>c.isLoadingStarterKits),r=M(c=>c.starterKitsError);if(t)return jsx($i,{message:"Loading Starter Kits..."});if(r)return jsx(es,{message:r,onRetry:e,onBack:e});if(a.length===0)return jsx(Lt,{message:"No Starter Kits available."});let i=Math.max(0,o-Math.floor(oc/2)),s=Math.min(a.length,i+oc);s===a.length&&(i=Math.max(0,s-oc));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(Fm,{starterKit:c,isSelected:i+u===o},c.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var Gm=vv.memo(function({plugin:a,isCursor:o}){return jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:o,color:o?"cyan":"white",children:[" ",v(a.name)]}),a.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});j();var ic=8;function Bm(){let e=M(c=>c.selectedStarterKit),a=M(c=>c.plugins),o=M(c=>c.pluginCursorIndex),t=useRef(false);if(useEffect(()=>{e&&!t.current&&(t.current=true,C(w.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:a.length}).catch(()=>{}));},[e,a.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let r=a.filter(c=>c.installed).length,i=Math.max(0,o-Math.floor(ic/2)),s=Math.min(a.length,i+ic);s===a.length&&(i=Math.max(0,s-ic));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:v(e.name)}),jsx(Text,{dimColor:true,children:v(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[a.length," plugins to install",r>0&&` \xB7 ${r} already installed`]})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(Gm,{plugin:c,isCursor:i+u===o},c.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var GP=["Retry failed","Continue anyway"];function jm({name:e,status:a,error:o,downloadProgress:t,downloadTotal:r}){let i=v(e);return a==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",i]})]}),r!==void 0&&r>0&&t!==void 0&&t>0&&jsx(Box,{paddingLeft:2,children:jsx(Zi,{received:t,total:r})})]}):a==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",i]})}):a==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",i]}),o&&jsxs(Text,{dimColor:true,children:[" \u2014 ",v(o)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",i]})})}function Um({onComplete:e,onRetry:a}){let o=M(l=>l.plugins),t=M(l=>l.step),r=M(l=>l.successCount),i=M(l=>l.failedCount),s=M(l=>l.summaryActionIndex),n=o.filter(l=>l.selected),d=useRef(false);return useEffect(()=>{if(t==="summary"&&i===0&&!d.current){d.current=true;let l=setTimeout(e,1500);return ()=>clearTimeout(l)}},[t,i,e]),t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:n.map(l=>jsx(jm,{name:l.name,status:l.status,error:l.error,downloadProgress:l.downloadProgress,downloadTotal:l.downloadTotal},l.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[r>0&&jsxs(Text,{color:"green",children:["\u2713 ",r," ",r===1?"plugin":"plugins"," installed successfully"]}),i>0&&jsxs(Text,{color:"red",children:["\u2717 ",i," ",i===1?"plugin":"plugins"," failed"]})]}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:n.filter(l=>l.status==="failed").map(l=>jsx(jm,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:GP.map((l,c)=>jsx(Box,{children:jsxs(Text,{bold:c===s,color:c===s?"cyan":void 0,children:[c===s?"\u203A ":" ",l]})},l))}),i===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function zm(){let e=M(x=>x.step),a=M(x=>x.starterKits),o=M(x=>x.selectedStarterKitIndex),t=M(x=>x.setSelectedStarterKitIndex),r=M(x=>x.selectStarterKit),i=M(x=>x.plugins),s=M(x=>x.pluginCursorIndex),n=M(x=>x.setPluginCursorIndex),d=M(x=>x.setStep),l=M(x=>x.summaryActionIndex),c=M(x=>x.setSummaryActionIndex),u=M(x=>x.failedCount),m=M(x=>x.resetForRetry),p=M(x=>x.goBackToList),g=y(x=>x.setScreen),f=y(x=>x.setFocus),h=y(x=>x.focus),b=oa(x=>x.setJustAuthenticated),D=oa(x=>x.justAuthenticated),{loadStarterKits:q,installSelected:L}=Mm(),A=useRef(false);useEffect(()=>{e==="starterKitList"?(f("starterKitList"),A.current||(A.current=true,Ko("bundle_selection"))):f(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,f]);let T=useCallback(async()=>{let x=M.getState().selectedStarterKit;if(x){let ae=await Y();ae&&await ko({...ae,starterKit:x.slug});}C(w.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:$o()}).catch(()=>{});let{successCount:J}=M.getState();C(w.CLI_ONBOARDING_COMPLETED,{duration_ms:Do(),tools_installed_count:J}).catch(()=>{}),b(false),f("verify"),g("verify");},[b,f,g]),F=useCallback(()=>{m(),L();},[m,L]),O=useCallback(()=>{q();},[q]),oe=useCallback(()=>{f("verify"),g("verify");},[f,g]);return useInput((x,J)=>{if(J.escape)qi("esc"),oe();else if(J.upArrow&&o>0)t(o-1);else if(J.downArrow&&o<a.length-1)t(o+1);else if(J.return&&a.length>0){let ae=$o();r(a[o]),Ko("kit_display"),C(w.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:ae}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((x,J)=>{let ae=qm(x,J);if(ae.cursorDelta!==0){let z=s+ae.cursorDelta;z>=0&&z<i.length&&n(z);}if(ae.confirm){let z=M.getState().selectedStarterKit;z&&(async()=>(await Y())?.starterKit!==z.slug&&C(w.CLI_KIT_ACCEPTED,{bundle_slug:z.slug}).catch(()=>{}))();let W=$o();Ko("kit_confirmation"),C(w.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:W}).catch(()=>{});let _=$o();Ko("tool_installation"),C(w.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:_}).catch(()=>{}),d("installing"),L();}if(ae.back){let z=M.getState().selectedStarterKit;z&&C(w.CLI_KIT_REJECTED,{bundle_slug:z.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((x,J)=>{if(u===0)return;let ae=Lm(x,J);if(ae.cursorDelta!==0){let z=l+ae.cursorDelta;z>=0&&z<=1&&c(z);}ae.select&&(l===0?F():T());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),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."}),!D&&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(Om,{onRetry:O}),e==="starterKitDetail"&&jsx(Bm,{}),(e==="installing"||e==="summary")&&jsx(Um,{onComplete:T,onRetry:F})]}),jsx(Ki,{})]})}U();var Hm=null;function Vm(){return Hm}async function Bs(){let a=ot().filter(o=>o.installedVersion===null&&o.installMethod===null);for(let o of a){let t=de.find(s=>s.alias===o.alias);if(!t)continue;let{installedVersion:r,installMethod:i}=await Qm(t);(r||i)&&await ka({...o,installedVersion:r,installMethod:i});}}async function Qm(e){let a=e.platforms[process.platform];if(a?.status!=="supported")return {installedVersion:null,installMethod:null};for(let o of a.strategies)if(o.type!=="curl")try{let r=await ja(o.type).getInstalledVersion(e);if(r)return {installedVersion:r,installMethod:o.type}}catch{}return {installedVersion:null,installMethod:null}}async function ar(e){let a=await Promise.all(e.map(o=>UP(o)));return Hm=a,a}async function UP(e){let a=Wm(e.versionCommand);a==="permission-denied"&&(zP(e.versionCommand[0]),a=Wm(e.versionCommand));let t=a==="installed"&&(!e.configCheck||e.configCheck()),r=e.platforms[process.platform],i=r?.status==="supported"?r.strategies:[],n=(await Promise.all(i.map(async d=>{try{return await ja(d.type).isAvailable()?d.type:null}catch{return null}}))).filter(d=>d!==null);if(t&&!ta(e.alias)){let{installedVersion:d,installMethod:l}=await Qm(e);await ka({alias:e.alias,name:e.name,installedVersion:d,installMethod:l,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:t,availableStrategies:n}}function Wm(e){if(e.length===0)return "not-found";try{let a=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return a.status===0?"installed":a.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function zP(e){if(process.platform!=="win32")try{let a=spawnSync("which",[e],{stdio:"pipe"});if(a.status!==0)return;let o=a.stdout.toString().trim(),t=ie__default.realpathSync(o),{mode:r}=ie__default.statSync(t);ie__default.chmodSync(t,r|73);}catch{}}function HP(e){return e.filter(a=>a.module.platforms[process.platform]?.status==="supported").filter(a=>!a.alreadyInstalled).map(a=>({module:a.module,alreadyInstalled:a.alreadyInstalled,checked:!a.alreadyInstalled&&(a.availableStrategies.length>0||a.module.required===true),selectedStrategy:a.availableStrategies[0]??null,availableStrategies:a.availableStrategies}))}function Ym(e,a){let[o,t]=useState(()=>HP(e)),[r,i]=useState(0),s=useRef(r);useEffect(()=>{s.current=r;},[r]);let n=useRef(o);useEffect(()=>{n.current=o;},[o]);let d=useCallback(u=>{t(m=>m.map(p=>p.module.alias!==u||p.module.required?p:{...p,checked:!p.checked}));},[]),l=useCallback((u,m)=>{t(p=>p.map(g=>g.module.alias===u?{...g,selectedStrategy:m}:g));},[]);useInput((u,m)=>{let p=s.current,g=n.current,f=m.upArrow||u==="[A",h=m.downArrow||u==="[B";if(f||h)f&&p>0?i(p-1):h&&p<g.length-1&&i(p+1);else if(u===" "){let b=g[p];b&&!b.module.required&&d(b.module.alias);}else if(m.tab){let b=g[p];if(b&&b.availableStrategies.length>1){let D=b.availableStrategies.indexOf(b.selectedStrategy??b.availableStrategies[0]),q=b.availableStrategies[(D+1)%b.availableStrategies.length];t(L=>L.map(A=>A.module.alias===b.module.alias?{...A,selectedStrategy:q}:A));}}},{isActive:a});let c=useMemo(()=>o.filter(u=>u.checked),[o]);return {items:o,focusedIndex:r,toggle:d,setStrategy:l,confirmedItems:c}}j();function eg({probeResults:e,onConfirm:a}){let o=y(p=>p.focus),t=y(p=>p.actionMenuOpen),r=y(p=>p.setActionMenuOpen),i=y(p=>p.setFocus),{items:s,focusedIndex:n,confirmedItems:d}=Ym(e,o==="moduleSetup"),l=useCallback(()=>{r(false),i("moduleSetup");},[r,i]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&a(d),l();},[d,a,l]);useInput((p,g)=>{g.return&&(r(true),i("actionMenu"));},{isActive:o==="moduleSetup"});let u=d.length>0?["Install","Cancel"]:["Skip","Cancel"],m=d.length>0?`Install ${d.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:s.map((p,g)=>{let f=g===n,h=v(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:f?"cyan":void 0,children:[f?"\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:v(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),t&&jsx(ra,{itemName:m,actions:u,onAction:c,onClose:l})]})}var KP=/^https?:\/\/.+/;function ag({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="y"||d==="Y"){o("input");return}if(d==="n"||d==="N"||l.return){e(null);return}}if(a==="input"){if(l.escape){n.current="",r(""),o("confirm");return}if(l.return){let c=n.current.trim();c.length>0&&KP.test(c)?(s(false),e(c)):c.length>0&&s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[a==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function YP(e){let a=e.module.platforms[process.platform];return (a?.status==="supported"?a.strategies:[]).map(t=>t.type==="npm"?`npm install -g ${t.package}`:t.type==="homebrew"?`brew install ${t.formula}`:"curl (see docs)").join(" or ")}function rg(e,a){let[o,t]=useState(()=>e.map(u=>({alias:u.module.alias,name:u.module.name,status:"pending"}))),[r,i]=useState(false),s=useCallback((u,m)=>{t(p=>p.map(g=>g.alias===u?{...g,...m}:g));},[]),n=useCallback(async()=>{for(let u of e){let m=YP(u);if(!u.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";s(u.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}s(u.module.alias,{status:"installing"});try{let p=await xo(u.module,"onboarding",u.selectedStrategy,a);p.success?s(u.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):s(u.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){s(u.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}i(true);},[e,s,a]),d=useMemo(()=>o.filter(u=>u.status==="installed").length,[o]),l=useMemo(()=>o.filter(u=>u.status==="failed").length,[o]),c=useMemo(()=>o.filter(u=>u.status==="skipped").length,[o]);return {modules:o,install:n,isComplete:r,installedCount:d,failedCount:l,skippedCount:c}}U();j();function ig({module:e}){let a=v(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",a," \u2014 Installing..."]})]});if(e.status==="installed"){let o=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:o?"red":"green",children:[o?"\u2717":"\u2713"," ",a]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:v(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",a]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",v(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",v(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",a," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",a]})})}function cg({confirmedItems:e,customUrl:a}){let o=y(b=>b.setScreen),t=y(b=>b.setFocus),{modules:r,install:i,isComplete:s,installedCount:n,failedCount:d,skippedCount:l}=rg(e,a),c=r.some(b=>b.pendingSetupCommand),u=useRef(false),m=useRef(false);useEffect(()=>{u.current||(u.current=true,i());},[i]);let p=useCallback(()=>{tt().catch(()=>{}),t("list");let b=ce().some(D=>D.name===pe);o(b?"main":"claudeMdSuggestion");},[t,o]);useEffect(()=>{if(s&&d===0&&!c&&!m.current){m.current=true;let b=setTimeout(p,1500);return ()=>clearTimeout(b)}},[s,d,c,p]),useInput((b,D)=>{D.return&&p();},{isActive:s});let g=r.filter(b=>b.pendingSetupCommand).length,f=n-g,h=[];return f>0&&h.push(jsxs(Text,{color:"green",children:[f," installed"]},"i")),g>0&&h.push(jsxs(Text,{color:"red",children:[g," needs setup"]},"p")),d>0&&h.push(jsxs(Text,{color:"red",children:[d," failed"]},"f")),l>0&&h.push(jsxs(Text,{dimColor:true,children:[l," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:s?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:r.map(b=>jsx(ig,{module:b},b.alias))}),s&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((b,D,q)=>(q>0&&b.push(jsx(Text,{children:" | "},`sep-${q}`)),b.push(D),b),[])}),jsx(Box,{paddingX:1,children:d>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function ug(){let[e,a]=useState("loading"),[o,t]=useState([]),[r,i]=useState([]),[s,n]=useState(null),d=y(p=>p.setFocus),l=y(p=>p.setScreen),c=useCallback(p=>{if(Jl(p)){tt().catch(()=>{}),d("list");let f=ce().some(h=>h.name===pe);l(f?"main":"claudeMdSuggestion");}else t(p),a("selection");},[d,l]);useEffect(()=>{let p=Vm();if(p){c(p);return}ar(de).then(c).catch(()=>{t([]),a("selection");});},[c]);let u=useCallback(p=>{i(p);let g=p.some(f=>f.module.alias==="metrics");a(g?"customUrl":"installation");},[]),m=useCallback(p=>{n(p),a("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(eg,{probeResults:o,onConfirm:u}),e==="customUrl"&&jsx(ag,{onConfirm:m}),e==="installation"&&jsx(cg,{confirmedItems:r,customUrl:s})]})}U();I();var dD=k("ClaudeMdSuggestion"),cD=[`Install ${pe}`,"Skip for now"],lD=["Retry","Skip for now"];function gg(){let e=y(m=>m.setScreen),a=y(m=>m.setFocus),o=M(m=>m.successCount),[t,r]=useState("prompt"),[i,s]=useState(0),n=useRef(0),d=useCallback(()=>{a("list"),e("main");},[a,e]),l=useCallback(()=>{C(w.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),d();},[d]),c=useCallback(async()=>{n.current+=1,C(w.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:n.current}).catch(()=>{}),r("installing");try{await je(pe),r("installed");}catch(m){if(m instanceof Xe){r("installed");return}dD.warn(`Failed to install ${pe}: ${m instanceof Error?m.message:m}`),r("error");}},[]),u=t==="error"?lD:cD;return useInput((m,p)=>{if(p.escape){t==="prompt"||t==="error"?l():t==="installed"&&d();return}if(t==="prompt"||t==="error"){p.upArrow&&i>0?s(i-1):p.downArrow&&i<u.length-1?s(i+1):p.return&&(i===0?(s(0),c()):l());return}t==="installed"&&p.return&&d();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:o>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),t==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(mg,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),t==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",pe,"..."]})]}),t==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",pe," 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:["/",pe]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),t==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",pe]}),jsx(mg,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function mg({options:e,cursorIndex:a}){return jsx(Box,{flexDirection:"column",children:e.map((o,t)=>jsxs(Text,{bold:t===a,color:t===a?"cyan":void 0,children:[t===a?"\u203A ":" ",o]},o))})}var gD=promisify(execFile),Js="@ciandt-flow/cli";async function fg(){let e=ve;if(Hd.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Js};try{let a=await fetch(`https://registry.npmjs.org/${Js}/latest`);if(!a.ok)throw new Error(`Registry returned ${a.status}`);let t=(await a.json()).version;return {currentVersion:e,latestVersion:t,isOutdated:t!==e,packageName:Js}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Js}}}async function Hs(e){try{return await gD(Za(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(a){return {success:false,error:String(a)}}}async function fD(e){let a=ta(e.alias);if(!a?.installMethod)return a?.installedVersion??null;try{let t=await ja(a.installMethod).getInstalledVersion(e);return t&&t!==a.installedVersion&&await ka({...a,installedVersion:t,lastChecked:new Date().toISOString()}),t??a.installedVersion}catch{return a.installedVersion}}async function hg(e){let a=await fD(e),o=null,t=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let i=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:t});if(!i.ok)throw new Error(`Registry returned ${i.status}`);o=(await i.json()).version;}else if(e.versionCheck.type==="github-releases"){let i=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t});if(!i.ok)throw new Error(`GitHub returned ${i.status}`);o=(await i.json()).tag_name.replace(/^v/,"");}}catch{}let r=a!==null&&o!==null&&a!==o;return {moduleAlias:e.alias,currentVersion:a,latestVersion:o,isOutdated:r}}async function bg(e,a){let o=ta(e.alias);if(!o?.installMethod)return {success:false,error:"Unknown install method"};let r=await ja(o.installMethod).update(e,a.currentVersion??"");return r.success?(await ka({...o,installedVersion:r.version??o.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:r.version}):{success:false,error:r.error?.message}}function vg(e){let o=ta(e.alias)?.installMethod,t=e.platforms[process.platform];if(t?.status==="supported"){if(o==="npm"){let r=t.strategies.find(i=>i.type==="npm");if(r?.type==="npm")return `npm install -g ${r.package}`}if(o==="homebrew"){let r=t.strategies.find(i=>i.type==="homebrew");if(r?.type==="homebrew")return `brew upgrade ${r.formula}`}}}function yg(){let[e,a]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...de.map(t=>({id:t.alias,label:t.name,status:"pending"}))]}),o=useCallback((t,r)=>{a(i=>({...i,items:i.items.map(s=>s.id===t?{...s,...r}:s)}));},[]);return useEffect(()=>{async function t(){try{let[r,i,s]=await Promise.all([fg(),ar(de),Promise.all(de.map(d=>hg(d)))]);if(Bs(),r.isOutdated){o("cli",{status:"updating",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),(await Hs(r)).success?(o("cli",{status:"updated",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),a(l=>({...l,outcome:"cli-updated"}))):(o("cli",{status:"error",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`,manualCommand:`npm install -g ${r.packageName}`}),a(l=>({...l,outcome:"cli-update-failed"})));return}o("cli",{status:"ok",detail:`v${r.currentVersion}`});let n=i.some(d=>!d.alreadyInstalled);for(let d of i)d.alreadyInstalled||o(d.module.alias,{status:"missing"});if(n){a(d=>({...d,outcome:"module-missing"}));return}for(let d of s){let l=de.find(u=>u.alias===d.moduleAlias);if(!l)continue;if(!d.isOutdated){o(d.moduleAlias,{status:"ok",detail:d.currentVersion?`v${d.currentVersion}`:void 0});continue}o(d.moduleAlias,{status:"updating",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`});let c=await bg(l,d);c.success?o(d.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):o(d.moduleAlias,{status:"error",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`,manualCommand:vg(l)});}a(d=>({...d,items:d.items.map(l=>l.status==="pending"?{...l,status:"ok"}:l)})),await tt(),a(d=>({...d,outcome:"done"}));}catch{await tt(),a(r=>({...r,outcome:"done"}));}}t();},[o]),e}U();function PD({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",e.label,e.detail?` ${e.detail}...`:""]})]}):e.status==="ok"||e.status==="updated"?jsxs(Box,{children:[jsxs(Text,{color:"green",children:["\u2713 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}):e.status==="missing"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),jsx(Text,{dimColor:true,children:" \u2014 not installed"})]}):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}),e.manualCommand&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["To update manually: ",e.manualCommand]})})]})}function DD({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 kg(){let{outcome:e,items:a}=yg(),o=y(r=>r.setScreen),t=y(r=>r.setFocus);return useEffect(()=>{if(e==="done"){let r=setTimeout(()=>{let i=ce().some(s=>s.name===pe);o(i?"main":"claudeMdSuggestion"),t("list");},1500);return ()=>clearTimeout(r)}if(e==="module-missing"){let r=setTimeout(()=>{o("moduleSetup"),t("moduleSetup");},500);return ()=>clearTimeout(r)}},[e,o,t]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:a.map(r=>jsx(PD,{item:r},r.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(DD,{outcome:e})})]})}Re();xt();I();wn();var RD={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Pg=10;function Dg(){let[e,a]=useState(Dn());useEffect(()=>nl(()=>{a([...Dn()]);}),[]);let o=e.slice(-Pg);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Pg,") \u2014 press Ctrl+D to close"]}),o.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):o.map((t,r)=>jsxs(Text,{color:RD[t.level],children:["[",t.level.toUpperCase(),"] [",t.module,"] ",t.message]},r))]})}var ID=k("app"),TD={auth:au,starterKitSetup:zm,moduleSetup:ug,claudeMdSuggestion:gg,verify:kg,main:Im};function Cg(){let{setScreen:e,setFocus:a}=y.getState();e("auth"),a("auth");}function Qi(e){let{setScreen:a,setFocus:o}=y.getState();!e.starterKit||e.starterKit.trim()===""?(a("starterKitSetup"),o("starterKitList")):(a("verify"),o("verify"));}function Rg(){C(w.CLI_SESSION_STARTED,{cli_version:ve,os:process.platform,node_version:process.version,duration_ms:Do(),interface:"tui"}).catch(()=>{});}async function xg(){let e=await Y();if(e&&zl()&&await Po()){e.customUrl&&La(e.customUrl);let{clientSecret:t,...r}=e;oa.getState().setCredentials(r),Rg(),Qi(e);return}if(!e){Cg();return}try{e.customUrl&&La(e.customUrl),await Oa();}catch(t){ID.debug(`Token validation failed: ${String(t)}`),Cg();return}Rg();let{clientSecret:a,...o}=e;oa.getState().setCredentials(o),Qi(e);}function Eg(){let{columns:e,rows:a}=useWindowSize(),o=y(n=>n.screen),t=TD[o],{pendingExit:r}=ql(),i=y(n=>n.debugPanelOpen),s=!!process.env.DEBUG;return useInput((n,d)=>{if(s&&d.ctrl&&n==="d"){let l=y.getState().debugPanelOpen;y.getState().setDebugPanelOpen(!l);}}),t?jsxs(Box,{flexDirection:"column",width:e,height:a,children:[jsx(t,{}),s&&i&&jsx(Dg,{}),r&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",o]})}Re();Ti();j();U();I();mr();Re();async function bc(e,a={}){let o=Oi({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},a);return Ni(o),await ko(e),{jwt:o.jwt,anthropicBaseUrl:o.anthropicBaseUrl,previousToken:o.previousToken,previousBaseUrl:o.previousBaseUrl,hadExistingFile:o.hadExistingFile}}var Ia=k("auth");function Tg(){Qe.clearFallbackFile(),Ai();}var MD=3,Ig=3,Mg=` \u2139 The data collected during setup is used solely to improve
|
|
121
|
+
[y/N] `))return Fs.debug(`[${e}] Removal cancelled by user`),P("Operation cancelled."),0}let t=a.silent?void 0:an({text:`Removing MCP "${v(e)}"...`}).start();try{let r=await qe(o);return t?.stop(),r.exitCode!==0?(Kr(a,{name:e,action:"remove",message:r.stderr||"Command failed",exitCode:r.exitCode}),!a.silent&&a.verbose&&r.stdout&&P(`stdout: ${r.stdout}`),1):(km(a,{name:e,actionPastTense:"removed",command:o,durationMs:r.duration_ms,stdout:r.stdout}),0)}catch(r){return t?.stop(),Kr(a,{name:e,action:"remove",message:Y(r)}),1}}I();function wm({selectedItem:e,selectedCatalogItem:a,items:o,closeMenu:t,clampIndex:r,notify:i}){let s=k("pluginHandlers"),n=useRef(0),d=y(A=>A.setLoading),l=y(A=>A.setDownloadProgress),{install:c,uninstall:u,toggle:m,update:p}=vm(),f=async(A,T,F)=>{d(true,A),t();try{await T(),r(o.length),i(F,"success");}catch(O){let oe=O instanceof Error?O.message:"Something went wrong";s.error(`[withLoading] ${A} failed: ${oe}`),i(oe,"error");}finally{d(false);}};return {handleInstall:(A,T)=>{e&&a&&(n.current=0,f(`Installing ${e.name}...`,()=>c(a,{scope:A,...T!==void 0?{providerId:T}:{},onDownloadProgress:(F,O)=>{let oe=Date.now();(oe-n.current>100||F>=O)&&(n.current=oe,l(F,O));}}),"\u2713 Installed successfully"));},handleUninstall:A=>{e&&f(`Uninstalling ${e.name}...`,()=>u(e.name,A),"\u2713 Uninstalled");},handleToggleStatus:A=>{if(!e)return;let T=e.status==="enabled";f(T?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,A),T?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let A=a?` to v${a.version}`:"";(async()=>{d(true,`Updating ${e.name}${A}...`),t();try{await p(e.name),r(o.length),i(`\u2713 Updated ${e.name}${A}`,"success");}catch(F){if(F instanceof Mo)i(F.message,"info");else {let O=F instanceof Error?F.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${O}`),i(O,"error");}}finally{d(false);}})();},handleBatchUpdate:A=>{if(A.length===0)return;let T=A.length;(async()=>{d(true,`Updating ${T} plugin${T>1?"s":""}...`),t();try{let O=[];for(let J of A)O.push(await p(J.name).then(()=>({status:"fulfilled",value:void 0}),ae=>({status:"rejected",reason:ae})));let oe=O.filter(J=>J.status==="fulfilled").length,x=O.map((J,ae)=>J.status==="rejected"?A[ae].name:null).filter(J=>J!==null);r(o.length),x.length===0?i(`\u2713 Updated ${oe}/${T} plugin${T>1?"s":""}`,"success"):(s.error(`[handleBatchUpdate] failed: ${x.join(", ")}`),i(`Updated ${oe}/${T}; failed: ${x.join(", ")}`,oe>0?"info":"error"));}finally{d(false);}})();},handleMcpConfigUninstall:A=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let T=Yd(e.name,A),F=await qe(T);if(F.exitCode!==0)throw new Error(F.stderr||"MCP removal failed");ye.getState().loadFromDisk();},"\u2713 MCP removed");}}}Ir();I();var $r=k("api:bundle"),er=class extends Error{constructor(a){super(`Bundle '${a}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Yr=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},CP=/^[a-zA-Z0-9_-]{1,128}$/;async function Cm(e,a){if(e instanceof HTTPError){let o=e.response.status;throw $r.error(`HTTP error fetching bundle '${a}' [status=${o}]`),o===StatusCodes.NOT_FOUND?new er(a):o===StatusCodes.INTERNAL_SERVER_ERROR?new Yr:new Error(`Server error (${o}) \u2014 please try again later.`)}throw $r.error(`Unexpected error fetching bundle '${a}': ${e instanceof Error?e.message:String(e)}`),e}async function Rm(e){if(!CP.test(e))throw new Error("Invalid bundle identifier format.");let a=encodeURIComponent(e);$r.debug(`Fetching bundle by flowId "${e}"`);try{return await za().get(`v1/use-cases/${a}`).json()}catch(o){return Cm(o,e)}}async function Os(e){let a=encodeURIComponent(e);$r.debug(`Fetching bundle by name "${e}"`);let o;try{o=await za().get(`v1/use-cases/by-name/${a}`).json(),$r.debug(`API returned ${o.length} result(s) for "${e}"`);}catch(t){return Cm(t,e)}if(o.length===0)throw new er(e);return o[0]}I();var RP=k("tui:bundle-flow");function Am({closeMenu:e,notify:a}){let o=y(n=>n.bundleInstallFlow);return {handleBundleInstallStart:(n,d)=>{let{setLoading:l,setBundleInstallFlow:c}=y.getState(),u=d?.trim();RP.debug(`Starting bundle install: itemName="${n}" flowId="${u??"none"}"`),l(true,"Loading bundle..."),(u?Rm(u):Os(n)).then(p=>{l(false),y.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{l(false),a(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!o||o.phase!=="detail")return;let{setBundleInstallFlow:n,setFocus:d}=y.getState();n({phase:"installing",bundle:o.bundle}),d("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:n}=y.getState();n(null),e();},handleBundleInstallComplete:n=>{y.getState().setBundleInstallFlow(null),e(),ye.getState().loadFromDisk(),a(`\u2713 Installed ${n.installed} of ${n.total} artifacts`,"success");}}}B();U();var Zr=["local","project","user"],AP=new Set(["--transport","--scope","-s"]);function xm(e){let a=e.split(/\s+/).filter(Boolean),o=a.indexOf("add");if(o===-1)return null;let t=o+1;for(;t<a.length;){let r=a[t];if(AP.has(r))t+=2;else if(r.startsWith("-"))t+=1;else return r.replace(/^["']|["']$/g,"")}return null}function mt(e,a){return a?`${e}::${a}`:e}function Zd(e){return e===ue?lr:ht}function Em(e){return {name:v(e.name),version:e.version?v(e.version):e.version,description:e.description?v(e.description):e.description,authorName:e.author?.name?v(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??lr,flowId:e.flowId}}function ec(e,a){let o=Zd(e.marketplace);return {name:v(e.name),version:e.version?v(e.version):e.version,description:e.description?v(e.description):e.description,authorName:e.author?.name?v(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:a?.type??e.type??"bundle",origin:a?.origin??o}}function Im(e){let a=new Map;for(let o of e){if(!o.scope)continue;let t=a.get(o.scope)??[];t.push(o),a.set(o.scope,t);}return Zr.filter(o=>a.has(o)).map(o=>({scope:o,label:qa[o].label,pathHint:qa[o].pathHint,items:a.get(o)??[]}))}function Tm(e){let a=o=>{if(!o)return 1/0;let t=Zr.indexOf(o);return t===-1?1/0:t};return [...e].sort((o,t)=>a(o.scope)-a(t.scope))}function Mm({catalog:e,installedItems:a,activeTab:o,catalogFilters:t,searchQuery:r}){let i=useMemo(()=>new Set(a.map(f=>mt(f.name,f.author?.name))),[a]),s=useMemo(()=>new Set(a.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[a]),n=useMemo(()=>{let f=new Map(e.map(h=>[mt(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return a.map(h=>{let b=f.get(mt(h.name,h.author?.name))??g.get(h.name),D=b?.version,q=!!D&&!!h.version&&ze(h.version,D);return {...h,updateAvailable:q,catalogItem:b}})},[a,e]),d=useMemo(()=>o==="discover"?e.filter(f=>{if(i.has(mt(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?xm(f.installCommand)?.toLowerCase():null;if(s.has(f.name.toLowerCase())||g&&s.has(g))return false}return true}).map(f=>Em(f)):o==="updates"?n.filter(f=>f.updateAvailable).map(f=>ec(f,f.catalogItem)):n.map(f=>ec(f,f.catalogItem)),[o,e,i,s,n]),l=useMemo(()=>d.filter(f=>{let g=f.type??"bundle";if(!t.types.has(g))return false;let h=f.origin??"internal";return t.origins.has(h)}),[d,t]),c=useMemo(()=>{let{types:f}=t;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[t]),u=useMemo(()=>o==="installed"?r?`No ${c} found for '${r}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:o==="updates"?r?`No ${c} found for '${r}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":r?`No ${c} found for '${r}'`:`No ${c} available in the catalog`,[o,r,c]),m=useMemo(()=>{let f=new Map(e.map(h=>[mt(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(mt(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>n.filter(f=>f.updateAvailable).length,[n]);return {items:l,emptyMessage:u,getSelectedCatalogItem:m,outdatedCount:p}}function ac(){let[e,a]=useState([]),[o,t]=useState(true),[r,i]=useState(null),[s,n]=useState(null),d=useRef(false),l=y(u=>u.catalogVersion),c=useCallback(async()=>{t(true),i(null),n(null);try{let{items:u,failures:m}=await ip();if(a(u),m.length>0){let p=m.map(f=>f.adapterName).join(", ");n(`Some catalogs failed to load: ${p}`);}d.current||(d.current=!0,C(w.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:u.length}).catch(()=>{}));}catch(u){i(u instanceof Error?u:new Error(String(u))),a([]);}finally{t(false);}},[]);return useEffect(()=>{c();},[c,l]),{catalog:e,isLoading:o,error:r,partialError:s,refetch:c}}function qm(){return {items:ye(a=>a.installedItems)}}I();var MP=k("catalog");function Fm(){let e=y(K=>K.bundleInstallFlow),a=y(K=>K.activeTab),o=y(K=>K.notification),t=y(K=>K.loading),r=y(K=>K.loadingMessage),i=y(K=>K.downloadProgress),s=y(K=>K.downloadTotal),n=y(K=>K.catalogError),d=y(K=>K.setCatalogError),l=y(K=>K.catalogFilters),c=_e(K=>K.query),{catalog:u,isLoading:m,error:p,refetch:f}=ac(),{items:g}=qm(),h=ye(K=>K.loadFromDisk),{items:b,emptyMessage:D,getSelectedCatalogItem:q,outdatedCount:L}=Mm({catalog:u,installedItems:g,activeTab:a,catalogFilters:l,searchQuery:c}),{actionMenuOpen:A,closeMenu:T,selectedIndex:F,clampIndex:O,filteredItems:oe}=mm({listLength:b.length}),x=oe(b),J=useMemo(()=>a!=="installed"&&a!=="updates"?x:Tm(x),[a,x]),ae=useMemo(()=>a==="installed"||a==="updates"?Im(J):[],[a,J]),z=J[F]??null,W=useMemo(()=>q(z),[q,z]),{notify:X}=fm(),{handleInstall:E,handleUninstall:j,handleToggleStatus:V,handleUpdate:Fe,handleBatchUpdate:ui,handleMcpConfigUninstall:Ch}=wm({selectedItem:z,selectedCatalogItem:W,items:b,closeMenu:T,clampIndex:O,notify:X}),{handleBundleInstallStart:Rh,handleBundleDetailConfirm:Ah,handleBundleDetailBack:xh,handleBundleInstallComplete:Eh}=Am({closeMenu:T,notify:X}),Ih=useCallback(()=>ui(J),[ui,J]);return useEffect(()=>{h();},[]),useEffect(()=>{O(J.length);},[J.length,O]),useEffect(()=>{p&&(MP.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),d("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),jsx(gu,{outdatedCount:L}),a==="marketplaces"&&Ao()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(cm,{})}):jsx(Mu,{filteredItems:J,groups:ae,emptyMessage:D,onBatchUpdate:Ih}),(t||m)&&jsxs(Fragment,{children:[jsx(os,{message:t?r:"Loading catalog..."}),t&&s>0&&i>0&&jsx(Box,{paddingLeft:2,children:jsx(rs,{received:i,total:s})})]}),n&&!m&&a==="discover"&&jsx(is,{message:n,onRetry:()=>{d(null),f();},onBack:()=>d(null)}),o&&jsx(qu,{message:o.message,type:o.type}),A&&z&&(a==="discover"?W?.type==="bundle"?e?.phase==="installing"?jsx(Xp,{bundle:e.bundle,onComplete:Eh}):jsx(Np,{itemName:z.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>Rh(z.name,z.flowId),onConfirm:Ah,onClose:e?.phase==="detail"?xh:T}):jsx(Fp,{itemName:z.name,itemType:W?.type,onInstall:E,onClose:T}):z.type==="mcp"?jsx(Wp,{itemName:z.name,itemScope:z.scope??"user",onUninstall:Ch,onClose:T}):jsx(jp,{itemName:z.name,itemScope:z.scope??"user",itemStatus:z.status??"enabled",updateAvailable:z.updateAvailable??false,catalogVersion:W?.version,onUninstall:j,onToggleStatus:K=>V(K),onUpdate:Fe,onClose:T})),jsx(as,{})]})}var M=create((e,a)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:o=>e({starterKits:o}),setSelectedStarterKitIndex:o=>e({selectedStarterKitIndex:o}),selectStarterKit:o=>{let t=new Set(ye.getState().installedItems.map(r=>r.name));e({selectedStarterKit:o,plugins:o.plugins.map(r=>({name:r,selected:true,status:t.has(r)?"success":"pending",installed:t.has(r)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:o=>e({pluginCursorIndex:o}),setStep:o=>e({step:o}),setPluginStatus:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,status:t,error:r}:s);e({plugins:i});},setPluginDownloadProgress:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,downloadProgress:t,downloadTotal:r}:s);e({plugins:i});},setIsLoadingStarterKits:o=>e({isLoadingStarterKits:o}),setStarterKitsError:o=>e({starterKitsError:o}),setSummaryActionIndex:o=>e({summaryActionIndex:o}),computeSummary:()=>{let t=a().plugins.filter(r=>r.selected);e({successCount:t.filter(r=>r.status==="success").length,failedCount:t.filter(r=>r.status==="failed").length});},resetForRetry:()=>{let o=a().plugins.map(t=>t.status==="failed"?{...t,status:"pending",error:void 0}:t);e({plugins:o,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Re();var NP=3;function Nm(){let e=M(c=>c.setStarterKits),a=M(c=>c.setIsLoadingStarterKits),o=M(c=>c.setStarterKitsError),t=M(c=>c.setPluginStatus),r=M(c=>c.setPluginDownloadProgress),i=M(c=>c.setStep),s=M(c=>c.computeSummary),n=useCallback(async()=>{a(true),o(null);try{let c=await ps();e(c);}catch(c){o(c instanceof Error?c.message:String(c));}finally{a(false);}},[a,o,e]);useEffect(()=>{ye.getState().loadFromDisk(),n();},[n]);let d=useRef(0),l=useCallback(async()=>{let c=M.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){t(m.name,"installing"),d.current=0;let p="",f=false;for(let g=1;g<=NP;g++)try{await je(m.name,{onDownloadProgress:(h,b)=>{let D=Date.now();(D-d.current>100||h>=b)&&(d.current=D,r(m.name,h,b));}}),t(m.name,"success"),f=!0;break}catch(h){if(h instanceof Xe){t(m.name,"success"),f=true;break}p=h instanceof Error?h.message:"Unknown error";}f||(t(m.name,"failed",p),C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:ee().interfaceType}).catch(()=>{}));}let u=Yo();$o("summary_review"),C(w.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:u}).catch(()=>{}),ye.getState().loadFromDisk(),s(),i("summary");},[t,r,s,i]);return {loadStarterKits:n,installSelected:l}}var ei={cursorDelta:0,confirm:false,back:false};function Gm(e,a){return a.upArrow?{...ei,cursorDelta:-1}:a.downArrow?{...ei,cursorDelta:1}:a.escape?{...ei,back:true}:a.return?{...ei,confirm:true}:ei}var GP={cursorDelta:0,select:false};function Bm(e,a){return a.upArrow?{cursorDelta:-1,select:false}:a.downArrow?{cursorDelta:1,select:false}:a.return?{cursorDelta:0,select:true}:GP}B();var jm=Av.memo(function({starterKit:a,isSelected:o}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:v(a.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",a.plugins.length," ",a.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:v(a.description)})})]})});var dc=5;function Um({onRetry:e}){let a=M(c=>c.starterKits),o=M(c=>c.selectedStarterKitIndex),t=M(c=>c.isLoadingStarterKits),r=M(c=>c.starterKitsError);if(t)return jsx(os,{message:"Loading Starter Kits..."});if(r)return jsx(is,{message:r,onRetry:e,onBack:e});if(a.length===0)return jsx(Lt,{message:"No Starter Kits available."});let i=Math.max(0,o-Math.floor(dc/2)),s=Math.min(a.length,i+dc);s===a.length&&(i=Math.max(0,s-dc));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(jm,{starterKit:c,isSelected:i+u===o},c.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}B();var Wm=Av.memo(function({plugin:a,isCursor:o}){return jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:o,color:o?"cyan":"white",children:[" ",v(a.name)]}),a.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});B();var uc=8;function Jm(){let e=M(c=>c.selectedStarterKit),a=M(c=>c.plugins),o=M(c=>c.pluginCursorIndex),t=useRef(false);if(useEffect(()=>{e&&!t.current&&(t.current=true,C(w.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:a.length}).catch(()=>{}));},[e,a.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let r=a.filter(c=>c.installed).length,i=Math.max(0,o-Math.floor(uc/2)),s=Math.min(a.length,i+uc);s===a.length&&(i=Math.max(0,s-uc));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:v(e.name)}),jsx(Text,{dimColor:true,children:v(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[a.length," plugins to install",r>0&&` \xB7 ${r} already installed`]})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(Wm,{plugin:c,isCursor:i+u===o},c.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}B();var QP=["Retry failed","Continue anyway"];function Hm({name:e,status:a,error:o,downloadProgress:t,downloadTotal:r}){let i=v(e);return a==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(_p,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",i]})]}),r!==void 0&&r>0&&t!==void 0&&t>0&&jsx(Box,{paddingLeft:2,children:jsx(rs,{received:t,total:r})})]}):a==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",i]})}):a==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",i]}),o&&jsxs(Text,{dimColor:true,children:[" \u2014 ",v(o)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",i]})})}function Vm({onComplete:e,onRetry:a}){let o=M(l=>l.plugins),t=M(l=>l.step),r=M(l=>l.successCount),i=M(l=>l.failedCount),s=M(l=>l.summaryActionIndex),n=o.filter(l=>l.selected),d=useRef(false);return useEffect(()=>{if(t==="summary"&&i===0&&!d.current){d.current=true;let l=setTimeout(e,1500);return ()=>clearTimeout(l)}},[t,i,e]),t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:n.map(l=>jsx(Hm,{name:l.name,status:l.status,error:l.error,downloadProgress:l.downloadProgress,downloadTotal:l.downloadTotal},l.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[r>0&&jsxs(Text,{color:"green",children:["\u2713 ",r," ",r===1?"plugin":"plugins"," installed successfully"]}),i>0&&jsxs(Text,{color:"red",children:["\u2717 ",i," ",i===1?"plugin":"plugins"," failed"]})]}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:n.filter(l=>l.status==="failed").map(l=>jsx(Hm,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:QP.map((l,c)=>jsx(Box,{children:jsxs(Text,{bold:c===s,color:c===s?"cyan":void 0,children:[c===s?"\u203A ":" ",l]})},l))}),i===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Qm(){let e=M(x=>x.step),a=M(x=>x.starterKits),o=M(x=>x.selectedStarterKitIndex),t=M(x=>x.setSelectedStarterKitIndex),r=M(x=>x.selectStarterKit),i=M(x=>x.plugins),s=M(x=>x.pluginCursorIndex),n=M(x=>x.setPluginCursorIndex),d=M(x=>x.setStep),l=M(x=>x.summaryActionIndex),c=M(x=>x.setSummaryActionIndex),u=M(x=>x.failedCount),m=M(x=>x.resetForRetry),p=M(x=>x.goBackToList),f=y(x=>x.setScreen),g=y(x=>x.setFocus),h=y(x=>x.focus),b=oa(x=>x.setJustAuthenticated),D=oa(x=>x.justAuthenticated),{loadStarterKits:q,installSelected:L}=Nm(),A=useRef(false);useEffect(()=>{e==="starterKitList"?(g("starterKitList"),A.current||(A.current=true,$o("bundle_selection"))):g(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,g]);let T=useCallback(async()=>{let x=M.getState().selectedStarterKit;if(x){let ae=await Z();ae&&await Do({...ae,starterKit:x.slug});}C(w.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Yo()}).catch(()=>{});let{successCount:J}=M.getState();C(w.CLI_ONBOARDING_COMPLETED,{duration_ms:So(),tools_installed_count:J}).catch(()=>{}),b(false),g("verify"),f("verify");},[b,g,f]),F=useCallback(()=>{m(),L();},[m,L]),O=useCallback(()=>{q();},[q]),oe=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((x,J)=>{if(J.escape)Gi("esc"),oe();else if(J.upArrow&&o>0)t(o-1);else if(J.downArrow&&o<a.length-1)t(o+1);else if(J.return&&a.length>0){let ae=Yo();r(a[o]),$o("kit_display"),C(w.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:ae}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((x,J)=>{let ae=Gm(x,J);if(ae.cursorDelta!==0){let z=s+ae.cursorDelta;z>=0&&z<i.length&&n(z);}if(ae.confirm){let z=M.getState().selectedStarterKit;z&&(async()=>(await Z())?.starterKit!==z.slug&&C(w.CLI_KIT_ACCEPTED,{bundle_slug:z.slug}).catch(()=>{}))();let W=Yo();$o("kit_confirmation"),C(w.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:W}).catch(()=>{});let X=Yo();$o("tool_installation"),C(w.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:X}).catch(()=>{}),d("installing"),L();}if(ae.back){let z=M.getState().selectedStarterKit;z&&C(w.CLI_KIT_REJECTED,{bundle_slug:z.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((x,J)=>{if(u===0)return;let ae=Bm(x,J);if(ae.cursorDelta!==0){let z=l+ae.cursorDelta;z>=0&&z<=1&&c(z);}ae.select&&(l===0?F():T());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),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."}),!D&&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(Um,{onRetry:O}),e==="starterKitDetail"&&jsx(Jm,{}),(e==="installing"||e==="summary")&&jsx(Vm,{onComplete:T,onRetry:F})]}),jsx(as,{})]})}U();var Km=null;function $m(){return Km}async function Js(){let a=tt().filter(o=>o.installedVersion===null&&o.installMethod===null);for(let o of a){let t=de.find(s=>s.alias===o.alias);if(!t)continue;let{installedVersion:r,installMethod:i}=await Ym(t);(r||i)&&await ka({...o,installedVersion:r,installMethod:i});}}async function Ym(e){let a=e.platforms[process.platform];if(a?.status!=="supported")return {installedVersion:null,installMethod:null};for(let o of a.strategies)if(o.type!=="curl")try{let r=await Ua(o.type).getInstalledVersion(e);if(r)return {installedVersion:r,installMethod:o.type}}catch{}return {installedVersion:null,installMethod:null}}async function or(e){let a=await Promise.all(e.map(o=>KP(o)));return Km=a,a}async function KP(e){let a=_m(e.versionCommand);a==="permission-denied"&&($P(e.versionCommand[0]),a=_m(e.versionCommand));let t=a==="installed"&&(!e.configCheck||e.configCheck()),r=e.platforms[process.platform],i=r?.status==="supported"?r.strategies:[],n=(await Promise.all(i.map(async d=>{try{return await Ua(d.type).isAvailable()?d.type:null}catch{return null}}))).filter(d=>d!==null);if(t&&!ta(e.alias)){let{installedVersion:d,installMethod:l}=await Ym(e);await ka({alias:e.alias,name:e.name,installedVersion:d,installMethod:l,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:t,availableStrategies:n}}function _m(e){if(e.length===0)return "not-found";try{let a=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return a.status===0?"installed":a.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function $P(e){if(process.platform!=="win32")try{let a=spawnSync("which",[e],{stdio:"pipe"});if(a.status!==0)return;let o=a.stdout.toString().trim(),t=ie__default.realpathSync(o),{mode:r}=ie__default.statSync(t);ie__default.chmodSync(t,r|73);}catch{}}function eD(e){return e.filter(a=>a.module.platforms[process.platform]?.status==="supported").filter(a=>!a.alreadyInstalled).map(a=>({module:a.module,alreadyInstalled:a.alreadyInstalled,checked:!a.alreadyInstalled&&(a.availableStrategies.length>0||a.module.required===true),selectedStrategy:a.availableStrategies[0]??null,availableStrategies:a.availableStrategies}))}function tg(e,a){let[o,t]=useState(()=>eD(e)),[r,i]=useState(0),s=useRef(r);useEffect(()=>{s.current=r;},[r]);let n=useRef(o);useEffect(()=>{n.current=o;},[o]);let d=useCallback(u=>{t(m=>m.map(p=>p.module.alias!==u||p.module.required?p:{...p,checked:!p.checked}));},[]),l=useCallback((u,m)=>{t(p=>p.map(f=>f.module.alias===u?{...f,selectedStrategy:m}:f));},[]);useInput((u,m)=>{let p=s.current,f=n.current,g=m.upArrow||u==="[A",h=m.downArrow||u==="[B";if(g||h)g&&p>0?i(p-1):h&&p<f.length-1&&i(p+1);else if(u===" "){let b=f[p];b&&!b.module.required&&d(b.module.alias);}else if(m.tab){let b=f[p];if(b&&b.availableStrategies.length>1){let D=b.availableStrategies.indexOf(b.selectedStrategy??b.availableStrategies[0]),q=b.availableStrategies[(D+1)%b.availableStrategies.length];t(L=>L.map(A=>A.module.alias===b.module.alias?{...A,selectedStrategy:q}:A));}}},{isActive:a});let c=useMemo(()=>o.filter(u=>u.checked),[o]);return {items:o,focusedIndex:r,toggle:d,setStrategy:l,confirmedItems:c}}B();function ig({probeResults:e,onConfirm:a}){let o=y(p=>p.focus),t=y(p=>p.actionMenuOpen),r=y(p=>p.setActionMenuOpen),i=y(p=>p.setFocus),{items:s,focusedIndex:n,confirmedItems:d}=tg(e,o==="moduleSetup"),l=useCallback(()=>{r(false),i("moduleSetup");},[r,i]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&a(d),l();},[d,a,l]);useInput((p,f)=>{f.return&&(r(true),i("actionMenu"));},{isActive:o==="moduleSetup"});let u=d.length>0?["Install","Cancel"]:["Skip","Cancel"],m=d.length>0?`Install ${d.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:s.map((p,f)=>{let g=f===n,h=v(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:v(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),t&&jsx(ra,{itemName:m,actions:u,onAction:c,onClose:l})]})}var iD=/^https?:\/\/.+/;function sg({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="y"||d==="Y"){o("input");return}if(d==="n"||d==="N"||l.return){e(null);return}}if(a==="input"){if(l.escape){n.current="",r(""),o("confirm");return}if(l.return){let c=n.current.trim();c.length>0&&iD.test(c)?(s(false),e(c)):c.length>0&&s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[a==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function nD(e){let a=e.module.platforms[process.platform];return (a?.status==="supported"?a.strategies:[]).map(t=>t.type==="npm"?`npm install -g ${t.package}`:t.type==="homebrew"?`brew install ${t.formula}`:"curl (see docs)").join(" or ")}function cg(e,a){let[o,t]=useState(()=>e.map(u=>({alias:u.module.alias,name:u.module.name,status:"pending"}))),[r,i]=useState(false),s=useCallback((u,m)=>{t(p=>p.map(f=>f.alias===u?{...f,...m}:f));},[]),n=useCallback(async()=>{for(let u of e){let m=nD(u);if(!u.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";s(u.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}s(u.module.alias,{status:"installing"});try{let p=await Io(u.module,"onboarding",u.selectedStrategy,a);p.success?s(u.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):s(u.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){s(u.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}i(true);},[e,s,a]),d=useMemo(()=>o.filter(u=>u.status==="installed").length,[o]),l=useMemo(()=>o.filter(u=>u.status==="failed").length,[o]),c=useMemo(()=>o.filter(u=>u.status==="skipped").length,[o]);return {modules:o,install:n,isComplete:r,installedCount:d,failedCount:l,skippedCount:c}}U();B();function lg({module:e}){let a=v(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(_p,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",a," \u2014 Installing..."]})]});if(e.status==="installed"){let o=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:o?"red":"green",children:[o?"\u2717":"\u2713"," ",a]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:v(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",a]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",v(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",v(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",a," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",a]})})}function gg({confirmedItems:e,customUrl:a}){let o=y(b=>b.setScreen),t=y(b=>b.setFocus),{modules:r,install:i,isComplete:s,installedCount:n,failedCount:d,skippedCount:l}=cg(e,a),c=r.some(b=>b.pendingSetupCommand),u=useRef(false),m=useRef(false);useEffect(()=>{u.current||(u.current=true,i());},[i]);let p=useCallback(()=>{rt().catch(()=>{}),t("list");let b=ce().some(D=>D.name===pe);o(b?"main":"claudeMdSuggestion");},[t,o]);useEffect(()=>{if(s&&d===0&&!c&&!m.current){m.current=true;let b=setTimeout(p,1500);return ()=>clearTimeout(b)}},[s,d,c,p]),useInput((b,D)=>{D.return&&p();},{isActive:s});let f=r.filter(b=>b.pendingSetupCommand).length,g=n-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")),d>0&&h.push(jsxs(Text,{color:"red",children:[d," failed"]},"f")),l>0&&h.push(jsxs(Text,{dimColor:true,children:[l," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:s?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:r.map(b=>jsx(lg,{module:b},b.alias))}),s&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((b,D,q)=>(q>0&&b.push(jsx(Text,{children:" | "},`sep-${q}`)),b.push(D),b),[])}),jsx(Box,{paddingX:1,children:d>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function hg(){let[e,a]=useState("loading"),[o,t]=useState([]),[r,i]=useState([]),[s,n]=useState(null),d=y(p=>p.setFocus),l=y(p=>p.setScreen),c=useCallback(p=>{if(Xl(p)){rt().catch(()=>{}),d("list");let g=ce().some(h=>h.name===pe);l(g?"main":"claudeMdSuggestion");}else t(p),a("selection");},[d,l]);useEffect(()=>{let p=$m();if(p){c(p);return}or(de).then(c).catch(()=>{t([]),a("selection");});},[c]);let u=useCallback(p=>{i(p);let f=p.some(g=>g.module.alias==="metrics");a(f?"customUrl":"installation");},[]),m=useCallback(p=>{n(p),a("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(ig,{probeResults:o,onConfirm:u}),e==="customUrl"&&jsx(sg,{onConfirm:m}),e==="installation"&&jsx(gg,{confirmedItems:r,customUrl:s})]})}U();I();var bD=k("ClaudeMdSuggestion"),vD=[`Install ${pe}`,"Skip for now"],yD=["Retry","Skip for now"];function yg(){let e=y(m=>m.setScreen),a=y(m=>m.setFocus),o=M(m=>m.successCount),[t,r]=useState("prompt"),[i,s]=useState(0),n=useRef(0),d=useCallback(()=>{a("list"),e("main");},[a,e]),l=useCallback(()=>{C(w.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),d();},[d]),c=useCallback(async()=>{n.current+=1,C(w.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:n.current}).catch(()=>{}),r("installing");try{await je(pe),r("installed");}catch(m){if(m instanceof Xe){r("installed");return}bD.warn(`Failed to install ${pe}: ${m instanceof Error?m.message:m}`),r("error");}},[]),u=t==="error"?yD:vD;return useInput((m,p)=>{if(p.escape){t==="prompt"||t==="error"?l():t==="installed"&&d();return}if(t==="prompt"||t==="error"){p.upArrow&&i>0?s(i-1):p.downArrow&&i<u.length-1?s(i+1):p.return&&(i===0?(s(0),c()):l());return}t==="installed"&&p.return&&d();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:o>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),t==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(vg,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),t==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(_p,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",pe,"..."]})]}),t==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",pe," 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:["/",pe]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),t==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",pe]}),jsx(vg,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function vg({options:e,cursorIndex:a}){return jsx(Box,{flexDirection:"column",children:e.map((o,t)=>jsxs(Text,{bold:t===a,color:t===a?"cyan":void 0,children:[t===a?"\u203A ":" ",o]},o))})}var wD=promisify(execFile),Xs="@ciandt-flow/cli";async function kg(){let e=ve;if($d.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Xs};try{let a=await fetch(`https://registry.npmjs.org/${Xs}/latest`);if(!a.ok)throw new Error(`Registry returned ${a.status}`);let t=(await a.json()).version;return {currentVersion:e,latestVersion:t,isOutdated:t!==e,packageName:Xs}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Xs}}}async function Ks(e){try{return await wD(eo(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(a){return {success:false,error:String(a)}}}async function SD(e){let a=ta(e.alias);if(!a?.installMethod)return a?.installedVersion??null;try{let t=await Ua(a.installMethod).getInstalledVersion(e);return t&&t!==a.installedVersion&&await ka({...a,installedVersion:t,lastChecked:new Date().toISOString()}),t??a.installedVersion}catch{return a.installedVersion}}async function Pg(e){let a=await SD(e),o=null,t=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let i=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:t});if(!i.ok)throw new Error(`Registry returned ${i.status}`);o=(await i.json()).version;}else if(e.versionCheck.type==="github-releases"){let i=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t});if(!i.ok)throw new Error(`GitHub returned ${i.status}`);o=(await i.json()).tag_name.replace(/^v/,"");}}catch{}let r=a!==null&&o!==null&&a!==o;return {moduleAlias:e.alias,currentVersion:a,latestVersion:o,isOutdated:r}}async function Dg(e,a){let o=ta(e.alias);if(!o?.installMethod)return {success:false,error:"Unknown install method"};let r=await Ua(o.installMethod).update(e,a.currentVersion??"");return r.success?(await ka({...o,installedVersion:r.version??o.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:r.version}):{success:false,error:r.error?.message}}function wg(e){let o=ta(e.alias)?.installMethod,t=e.platforms[process.platform];if(t?.status==="supported"){if(o==="npm"){let r=t.strategies.find(i=>i.type==="npm");if(r?.type==="npm")return `npm install -g ${r.package}`}if(o==="homebrew"){let r=t.strategies.find(i=>i.type==="homebrew");if(r?.type==="homebrew")return `brew upgrade ${r.formula}`}}}function Sg(){let[e,a]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...de.map(t=>({id:t.alias,label:t.name,status:"pending"}))]}),o=useCallback((t,r)=>{a(i=>({...i,items:i.items.map(s=>s.id===t?{...s,...r}:s)}));},[]);return useEffect(()=>{async function t(){try{let[r,i,s]=await Promise.all([kg(),or(de),Promise.all(de.map(d=>Pg(d)))]);if(Js(),r.isOutdated){o("cli",{status:"updating",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),(await Ks(r)).success?(o("cli",{status:"updated",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),a(l=>({...l,outcome:"cli-updated"}))):(o("cli",{status:"error",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`,manualCommand:`npm install -g ${r.packageName}`}),a(l=>({...l,outcome:"cli-update-failed"})));return}o("cli",{status:"ok",detail:`v${r.currentVersion}`});let n=i.some(d=>!d.alreadyInstalled);for(let d of i)d.alreadyInstalled||o(d.module.alias,{status:"missing"});if(n){a(d=>({...d,outcome:"module-missing"}));return}for(let d of s){let l=de.find(u=>u.alias===d.moduleAlias);if(!l)continue;if(!d.isOutdated){o(d.moduleAlias,{status:"ok",detail:d.currentVersion?`v${d.currentVersion}`:void 0});continue}o(d.moduleAlias,{status:"updating",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`});let c=await Dg(l,d);c.success?o(d.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):o(d.moduleAlias,{status:"error",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`,manualCommand:wg(l)});}a(d=>({...d,items:d.items.map(l=>l.status==="pending"?{...l,status:"ok"}:l)})),await rt(),a(d=>({...d,outcome:"done"}));}catch{await rt(),a(r=>({...r,outcome:"done"}));}}t();},[o]),e}U();function ID({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(_p,{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 TD({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 Cg(){let{outcome:e,items:a}=Sg(),o=y(r=>r.setScreen),t=y(r=>r.setFocus);return useEffect(()=>{if(e==="done"){let r=setTimeout(()=>{let i=ce().some(s=>s.name===pe);o(i?"main":"claudeMdSuggestion"),t("list");},1500);return ()=>clearTimeout(r)}if(e==="module-missing"){let r=setTimeout(()=>{o("moduleSetup"),t("moduleSetup");},500);return ()=>clearTimeout(r)}},[e,o,t]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:a.map(r=>jsx(ID,{item:r},r.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(TD,{outcome:e})})]})}Re();xt();I();En();var FD={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Rg=10;function Ag(){let[e,a]=useState(xn());useEffect(()=>pl(()=>{a([...xn()]);}),[]);let o=e.slice(-Rg);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Rg,") \u2014 press Ctrl+D to close"]}),o.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):o.map((t,r)=>jsxs(Text,{color:FD[t.level],children:["[",t.level.toUpperCase(),"] [",t.module,"] ",t.message]},r))]})}var BD=k("app"),jD={auth:su,starterKitSetup:Qm,moduleSetup:hg,claudeMdSuggestion:yg,verify:Cg,main:Fm};function Ig(){let{setScreen:e,setFocus:a}=y.getState();e("auth"),a("auth");}function Yi(e){let{setScreen:a,setFocus:o}=y.getState();!e.starterKit||e.starterKit.trim()===""?(a("starterKitSetup"),o("starterKitList")):(a("verify"),o("verify"));}function Tg(){C(w.CLI_SESSION_STARTED,{cli_version:ve,os:process.platform,node_version:process.version,duration_ms:So(),interface:"tui"}).catch(()=>{});}async function qg(){let e=await Z();if(e&&Ql()&&await wo()){e.customUrl&&Fa(e.customUrl);let{clientSecret:t,...r}=e;oa.getState().setCredentials(r),Tg(),Yi(e);return}if(!e){Ig();return}try{e.customUrl&&Fa(e.customUrl),await Na();}catch(t){BD.debug(`Token validation failed: ${String(t)}`),Ig();return}Tg();let{clientSecret:a,...o}=e;oa.getState().setCredentials(o),Yi(e);}function Lg(){let{columns:e,rows:a}=useWindowSize(),o=y(n=>n.screen),t=jD[o],{pendingExit:r}=Gl(),i=y(n=>n.debugPanelOpen),s=!!process.env.DEBUG;return useInput((n,d)=>{if(s&&d.ctrl&&n==="d"){let l=y.getState().debugPanelOpen;y.getState().setDebugPanelOpen(!l);}}),t?jsxs(Box,{flexDirection:"column",width:e,height:a,children:[jsx(t,{}),s&&i&&jsx(Ag,{}),r&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",o]})}Re();Oi();B();U();I();fr();Re();async function wc(e,a={}){let o=Ui({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},a);return zi(o),await Do(e),{jwt:o.jwt,anthropicBaseUrl:o.anthropicBaseUrl,previousToken:o.previousToken,previousBaseUrl:o.previousBaseUrl,hadExistingFile:o.hadExistingFile}}var Ia=k("auth");function Og(){Qe.clearFallbackFile(),Mi();}var UD=3,Fg=3,Ng=` \u2139 The data collected during setup is used solely to improve
|
|
122
122
|
Flow's internal tools and will not be shared externally.
|
|
123
|
-
`;function
|
|
123
|
+
`;function Ka(e,a={}){return new Promise((o,t)=>{let{masked:r=false,defaultValue:i=""}=a;process.stdout.write(e+i);let s=i,n=c=>{if(c===""){d(),t(new Error("SIGINT"));return}if(c==="\r"||c===`
|
|
124
124
|
`){d(),process.stdout.write(`
|
|
125
|
-
`),o(s);return}if(c==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(s+=c,process.stdout.write(r?"*".repeat(c.length):c));};function d(){process.stdin.setRawMode(false),process.stdin.removeListener("data",n),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",n);})}async function
|
|
125
|
+
`),o(s);return}if(c==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(s+=c,process.stdout.write(r?"*".repeat(c.length):c));};function d(){process.stdin.setRawMode(false),process.stdin.removeListener("data",n),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",n);})}async function zD(){let e=at();return process.stdout.write(`
|
|
126
126
|
`+R.yellow(" \u26A0 ")+`${v(e)} contains invalid JSON.
|
|
127
|
-
`),(await
|
|
128
|
-
`));}}async function
|
|
129
|
-
`));}}async function
|
|
127
|
+
`),(await Ka(R.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Gg(e,a,o){try{await wc(e,{jwtOverride:o});return}catch(t){if(!(t instanceof ot))throw t;if(!a)throw new Error(`${t.message}. Fix or remove ${at()} and retry.`);if(!await zD())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await wc(e,{allowOverwriteMalformed:true,jwtOverride:o});}}async function WD(){if((await Ka(R.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let a=(await Ka(R.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(bt.test(a))return a;process.stderr.write(R.yellow(` \u26A0 ${vt}. Try again.
|
|
128
|
+
`));}}async function JD(){let e=(await Ka(R.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let a=(await Ka(R.cyan(" ? ")+"Enter your email address: ")).trim();if(yt.test(a))return a;process.stderr.write(R.yellow(` \u26A0 ${kt}. Try again.
|
|
129
|
+
`));}}async function Bg(e,a){process.stdout.write(R.dim(" Installing flow-ai-obs..."));let{npmFailed:o,initFailed:t,unexpectedError:r}=await $i(e,a);return o?process.stdout.write(R.yellow(` \u26A0 npm install failed. Please contact Flow support.
|
|
130
130
|
`)):r?process.stdout.write(R.yellow(` \u26A0 Unexpected error. Please contact Flow support.
|
|
131
131
|
`)):t?process.stdout.write(R.yellow(`
|
|
132
132
|
\u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
|
|
133
133
|
`)):process.stdout.write(R.green(` done
|
|
134
|
-
`)),{initFailed:t}}async function
|
|
134
|
+
`)),{initFailed:t}}async function jg(){for(let e=1;e<=Fg;e++)try{return await ps()}catch{if(e===Fg)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Ug(){let e=await jg();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");let a=(await Ka(R.cyan(" ? ")+"Install a starter kit? (y/N): ")).trim().toLowerCase();if(a!=="y"&&a!=="yes")return null;for(process.stdout.write(`
|
|
135
135
|
`+R.cyan(" ? ")+`Starter Kit:
|
|
136
136
|
`),e.forEach((o,t)=>{process.stdout.write(` ${R.cyan(`${t+1})`)} ${v(o.name)}
|
|
137
137
|
`);}),process.stdout.write(`
|
|
138
|
-
`);;){let o=(await
|
|
139
|
-
`));}}async function
|
|
138
|
+
`);;){let o=(await Ka(R.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),t=parseInt(o,10)-1;if(!isNaN(t)&&t>=0&&t<e.length)return e[t];process.stderr.write(R.yellow(` \u26A0 Invalid selection. Please try again.
|
|
139
|
+
`));}}async function zg(e){if(e.plugins.length===0)return process.stdout.write(R.dim(`
|
|
140
140
|
Starter kit '${v(e.name)}' has no plugins to install.
|
|
141
141
|
`)),true;process.stdout.write(`
|
|
142
142
|
Installing ${e.plugins.length} plugins from '${v(e.name)}'...
|
|
143
|
-
`);let a=0,o=0,t=e.plugins.length;for(let r of e.plugins){let i=a+o+1;process.stdout.write(R.dim(` [${i}/${t}] Installing ${v(r)}...`));let s=false;for(let n=1;n<=
|
|
143
|
+
`);let a=0,o=0,t=e.plugins.length;for(let r of e.plugins){let i=a+o+1;process.stdout.write(R.dim(` [${i}/${t}] Installing ${v(r)}...`));let s=false;for(let n=1;n<=UD;n++)try{await je(r),a++,s=!0;break}catch(d){if(d instanceof Xe){a++,s=true;break}}s?process.stdout.write(R.green(` done
|
|
144
144
|
`)):(o++,process.stdout.write(R.red(` failed
|
|
145
145
|
`)));}return o===0?process.stdout.write(R.green(` \u2713 Starter kit '${v(e.name)}' selected. ${a}/${t} plugins installed successfully.
|
|
146
146
|
`)):process.stdout.write(R.yellow(` \u26A0 Starter kit '${v(e.name)}' selected. ${a}/${t} plugins installed. ${o} failed.
|
|
147
|
-
`)),o===0}async function
|
|
147
|
+
`)),o===0}async function Wg(){process.stdout.write(`
|
|
148
148
|
`),process.stdout.write(R.bold(` Personalize your Claude Code
|
|
149
149
|
`)),process.stdout.write(R.dim(` This plugin helps Claude understand your preferences and work style.
|
|
150
150
|
|
|
151
|
-
`));let e=(await
|
|
151
|
+
`));let e=(await Ka(R.cyan(" ? ")+`Install ${pe}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){C(w.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(R.dim(`
|
|
152
152
|
You can always install it later from the catalog.
|
|
153
153
|
`));return}C(w.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(R.dim(` Installing ${pe}...`));try{await je(pe),process.stdout.write(R.green(` done
|
|
154
154
|
`));}catch(a){if(a instanceof Xe)process.stdout.write(R.green(` already installed
|
|
@@ -158,112 +158,112 @@ This will run: ${i}
|
|
|
158
158
|
`),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
|
|
159
159
|
`),process.stdout.write(R.cyan.bold(` /${pe}
|
|
160
160
|
`)),process.stdout.write(` Claude will guide you through the rest.
|
|
161
|
-
`);}async function
|
|
162
|
-
`+
|
|
163
|
-
`),e.customUrl!==void 0&&!
|
|
164
|
-
`)),1;if(e.customEmail!==void 0&&!
|
|
165
|
-
`)),1;let a=e.jwt.trim(),o;try{o=
|
|
166
|
-
`)),1}e.customUrl&&
|
|
167
|
-
`)),1}let{initFailed:t}=await
|
|
161
|
+
`);}async function HD(e){if(Og(),process.stdout.write(`
|
|
162
|
+
`+Ng+`
|
|
163
|
+
`),e.customUrl!==void 0&&!bt.test(e.customUrl))return process.stderr.write(R.red(` \u2717 ${vt}.
|
|
164
|
+
`)),1;if(e.customEmail!==void 0&&!yt.test(e.customEmail))return process.stderr.write(R.red(` \u2717 ${kt}.
|
|
165
|
+
`)),1;let a=e.jwt.trim(),o;try{o=Cr(a);}catch(r){let i=v(r instanceof Error?r.message:"Invalid JWT");return process.stderr.write(R.red(` \u2717 ${i}
|
|
166
|
+
`)),1}e.customUrl&&Fa(e.customUrl),Ia.debug(`[${o.tenant}] Authenticating tenant via JWT`);try{await Ko(o);}catch(r){let i=v(r instanceof Error?r.message:"unknown error");return Ia.error(`[${o.tenant}] Authentication failed: ${i}`),process.stderr.write(R.red(` \u2717 Authentication failed: ${i}
|
|
167
|
+
`)),1}let{initFailed:t}=await Bg(e.customUrl??null,e.customEmail??null);try{let r;if(e.starterKit){let i=await jg(),s=i.find(n=>n.slug===e.starterKit);if(!s){process.stderr.write(R.red(` \u2717 Starter kit '${v(e.starterKit)}' not found.
|
|
168
168
|
`)),process.stderr.write(` Available starter kits:
|
|
169
169
|
`);for(let n of i)process.stderr.write(` - ${v(n.slug)} (${v(n.name)})
|
|
170
|
-
`);return 1}r=s;}else r=await
|
|
170
|
+
`);return 1}r=s;}else r=await Ug();return await Gg({...o,starterKit:r?.slug,customUrl:e.customUrl},!1,a),r?await zg(r):process.stdout.write(R.dim(`
|
|
171
171
|
Skipped starter kit installation.
|
|
172
|
-
`)),await
|
|
173
|
-
\u2713 Setup complete. Tenant: ${v(o.tenant)}. JWT written to ${
|
|
172
|
+
`)),await Wg(),Ia.info(`[${o.tenant}] Authentication successful`),process.stdout.write(R.green(`
|
|
173
|
+
\u2713 Setup complete. Tenant: ${v(o.tenant)}. JWT written to ${at()}.
|
|
174
174
|
|
|
175
175
|
`)),t&&process.stdout.write(R.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
|
|
176
176
|
`)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let i=v(r instanceof Error?r.message:"unknown error");return Ia.error(`[${o.tenant}] Starter kit setup failed: ${i}`),process.stderr.write(R.red(` \u2717 Starter kit setup failed: ${i}
|
|
177
|
-
`)),1}}async function
|
|
178
|
-
`),process.stdout.write(
|
|
179
|
-
`);let o=(await
|
|
180
|
-
`)),1;let t;try{t=
|
|
181
|
-
`)),1}let r=e??await
|
|
182
|
-
`)),1}let{initFailed:s}=await
|
|
177
|
+
`)),1}}async function VD(e,a){Og(),Ia.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
|
|
178
|
+
`),process.stdout.write(Ng+`
|
|
179
|
+
`);let o=(await Ka(R.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!o)return Ia.error("[auth] Validation failed: JWT is required"),process.stderr.write(R.red(` \u2717 JWT is required
|
|
180
|
+
`)),1;let t;try{t=Cr(o);}catch(d){let l=v(d instanceof Error?d.message:"Invalid JWT");return process.stderr.write(R.red(` \u2717 ${l}
|
|
181
|
+
`)),1}let r=e??await WD(),i=a??await JD();r&&Fa(r),Ia.debug(`[${t.tenant}] Authenticating tenant`);try{await Ko(t);}catch(d){let l=v(d instanceof Error?d.message:"unknown error");return Ia.error(`[${t.tenant}] Authentication failed: ${l}`),process.stderr.write(R.red(` \u2717 Authentication failed: ${l}
|
|
182
|
+
`)),1}let{initFailed:s}=await Bg(r,i),n=await Ug();return await Gg({...t,starterKit:n?.slug,customUrl:r??void 0},!0,o),n?await zg(n):process.stdout.write(R.dim(`
|
|
183
183
|
Skipped starter kit installation.
|
|
184
|
-
`)),await
|
|
185
|
-
\u2713 Setup complete. Tenant: ${v(t.tenant)}. JWT written to ${
|
|
184
|
+
`)),await Wg(),Ia.info(`[${t.tenant}] Authentication successful`),process.stdout.write(R.green(`
|
|
185
|
+
\u2713 Setup complete. Tenant: ${v(t.tenant)}. JWT written to ${at()}.
|
|
186
186
|
|
|
187
187
|
`)),s&&process.stdout.write(R.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
|
|
188
188
|
`)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let t=v(o instanceof Error?o.message:"unknown error");return Ia.error(`[auth] Unexpected error: ${t}`),process.stderr.write(R.red(` \u2717 Unexpected error: ${t}
|
|
189
|
-
`)),1}}async function
|
|
190
|
-
`)),1;if(e.customEmail!==void 0&&!
|
|
191
|
-
`)),1;try{return await
|
|
192
|
-
`),130;throw a}}async function
|
|
193
|
-
`),(await
|
|
189
|
+
`)),1}}async function Sc(e={}){if(e.jwt)return HD({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!bt.test(e.customUrl))return process.stderr.write(R.red(` \u2717 ${vt}.
|
|
190
|
+
`)),1;if(e.customEmail!==void 0&&!yt.test(e.customEmail))return process.stderr.write(R.red(` \u2717 ${kt}.
|
|
191
|
+
`)),1;try{return await VD(e.customUrl,e.customEmail)}catch(a){if(a instanceof Error&&a.message==="SIGINT")return process.stdout.write(`
|
|
192
|
+
`),130;throw a}}async function QD(){try{return process.stdout.write(`
|
|
193
|
+
`),(await Ka(R.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(R.yellow(` \u26A0 Logout cancelled
|
|
194
194
|
`)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
|
|
195
|
-
`),130;throw e}}async function
|
|
196
|
-
`)),0;if(!e){let a=await
|
|
195
|
+
`),130;throw e}}async function Jg(e){if(!await Z())return process.stdout.write(R.yellow(` \u26A0 You are not authenticated
|
|
196
|
+
`)),0;if(!e){let a=await QD();if(a!==null)return a}try{return await Sl(),process.stdout.write(R.green(` \u2713 Credentials removed successfully
|
|
197
197
|
`)),0}catch{return process.stderr.write(R.red(` \u2717 Error removing credentials
|
|
198
|
-
`)),1}}async function
|
|
198
|
+
`)),1}}async function Hg(){let e=await Z();return e?await wo()?(process.stdout.write(`
|
|
199
199
|
`+R.bold(` Authenticated
|
|
200
200
|
`)),process.stdout.write(R.dim(" Tenant: ")+v(e.tenant)+`
|
|
201
201
|
`),process.stdout.write(R.dim(" Client ID: ")+v(e.clientId)+`
|
|
202
202
|
`),process.stdout.write(R.dim(" Starter Kit: ")+v(e.starterKit??"not set")+`
|
|
203
|
-
`),process.stdout.write(R.dim(" Config: ")+v(await
|
|
203
|
+
`),process.stdout.write(R.dim(" Config: ")+v(await Cl())+`
|
|
204
204
|
`),process.stdout.write(`
|
|
205
|
-
`),0):(process.stdout.write(R.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(R.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}
|
|
205
|
+
`),0):(process.stdout.write(R.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(R.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}B();U();Oe();U();var XD=[ue,"flow-harness"];function Vg(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function KD(e,a,o=process.env){return Vg(o.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:Vg(o.FORCE_AUTOUPDATE_PLUGINS)?{name:e,enabled:true,reason:"env-forced"}:a?.autoUpdate===false?{name:e,enabled:false,reason:"flag"}:a?.autoUpdate===true?{name:e,enabled:true,reason:"flag"}:{name:e,enabled:true,reason:"default"}}function Qg(e){switch(e.reason){case "env-disabled":return "DISABLE_AUTOUPDATER is set";case "env-forced":return "FORCE_AUTOUPDATE_PLUGINS is set";case "flag":return e.enabled?"autoUpdate: true":"autoUpdate: false";case "default":return "default (no explicit flag)"}}function Ys(e=process.env){let a=Ho();if(!ie__default.existsSync(a))return [];try{let o=JSON.parse(ie__default.readFileSync(a,"utf-8"));return Object.entries(o).map(([t,r])=>KD(t,r,e))}catch{return []}}function _g(){let e=Ho(),a={fixed:[],skipped:[]};if(!ie__default.existsSync(e))return a;let o;try{o=JSON.parse(ie__default.readFileSync(e,"utf-8"));}catch{return a.skipped.push({name:"(all)",reason:"known_marketplaces.json is malformed JSON"}),a}let t=false;for(let r of XD){let i=o[r];if(!i){a.skipped.push({name:r,reason:"not registered on this machine"});continue}if("autoUpdate"in i){a.skipped.push({name:r,reason:i.autoUpdate?"already autoUpdate: true":"explicitly set to autoUpdate: false \u2014 not overridden"});continue}i.autoUpdate=true,a.fixed.push(r),t=true;}if(t){let r=`${e}.${randomUUID()}.tmp`;ie__default.writeFileSync(r,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(r,e);}return a}async function $D(e){let a=ce(),o;try{o=await to(e.source);}catch(r){if(e.source)throw r;o=[];}let t=new Set(a.map(r=>r.name));return C(w.CLI_CATALOG_VIEWED,{interface:ee().interfaceType,filter_type:"available",result_count:o.length}).catch(()=>{}),e.json?(yo(o.map(r=>({...r,installed:t.has(r.name)}))),0):(vo(["","Name","Version","Category","Status"],o.map(r=>[t.has(r.name)?"*":" ",r.name??"",r.version??"n/a",r.category??"",t.has(r.name)?"installed":"available"])),0)}async function YD(e){let a=ce(),o=await to(e.source),t=new Map(o.map(i=>[i.name,i])),r=a.map(i=>{let s=t.get(i.name);return s&&i.version&&s.version&&ze(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return C(w.CLI_CATALOG_VIEWED,{interface:ee().interfaceType,filter_type:"outdated",result_count:r.length}).catch(()=>{}),e.json?(yo(r),0):r.length===0?(P("All plugins are up to date."),0):(vo(["Name","Installed","Available"],r.map(i=>[i.name??"",i.version??"n/a",i.availableVersion??"n/a"])),process.stdout.write(`
|
|
206
206
|
${r.length} plugin(s) outdated.
|
|
207
|
-
`),0)}async function
|
|
207
|
+
`),0)}async function ZD(e){let a=ce();if(C(w.CLI_CATALOG_VIEWED,{interface:ee().interfaceType,filter_type:"all",result_count:a.length}).catch(()=>{}),a.length===0)return P("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return yo(a),0;let o=[];try{o=await to(e.source);}catch{o=[];}let t=new Map(o.map(s=>[s.name,s])),r=new Map(Ys().map(s=>[s.name,s.enabled])),i=[...a].sort((s,n)=>{let d=Zr.indexOf(s.scope??"user"),l=Zr.indexOf(n.scope??"user");return (d===-1?1/0:d)-(l===-1?1/0:l)});return vo(["Name","Version","Type","Origin","Scope","Status","Auto-Update","Installed at"],i.map(s=>{let n=t.get(s.name),d=n?.type??"bundle",l=n?.origin??Zd(s.marketplace),c=s.marketplace?r.get(s.marketplace):void 0,u=c===void 0?"n/a":c?"on":"off";return [s.name??"",s.version??"n/a",bo[d]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",u,La(s.installedAt??"")]})),process.stdout.write(`
|
|
208
208
|
${a.length} plugin(s) installed.
|
|
209
|
-
`),0}async function
|
|
209
|
+
`),0}async function Xg(e){if(!await he())return 1;try{return e.available?await $D(e):e.outdated?await YD(e):await ZD(e)}catch(a){return S(a instanceof Error?a.message:"Failed to list plugins."),1}}qo();B();U();function Zs(e){let a=Ae().plugins,o=process.cwd();for(let[t,r]of Object.entries(a))if(t===e||t.startsWith(`${e}@`)){let i=r.find(s=>s.scope==="user"||s.projectPath===o);if(i)return i}}function $a(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function en(e,a,o){return P(`${e} is already installed ${$a(o)}.`),_(` Move it to ${qa[a].actionLabel} instead? This uninstalls it from ${$a(o)} first. [y/N] `)}B();U();I();var be=k("manage");function on(e,a){return a?ce().find(o=>o.name===e&&o.scope===a):ce().find(o=>o.name===e)}function ew(e,a){let o=a;return {callbacks:{onStatus:r=>{o&&(o.text=`${e}${r}`);},onError:r=>{o?.stop(),o=void 0,P(`${e}${r}`);},onPause:()=>{o?.stop(),o=void 0;},onResume:r=>{o?.stop(),o=an({text:`${e}${r}`}).start();}},stopSpinner:()=>{o?.stop(),o=void 0;}}}async function aw(e,a,o,t){let r=t;if(!o.force){r?.stop();let s=v(e),n=v(jt(e,o.scope));if(!await _(`${a}Install external plugin "${s}"?
|
|
210
210
|
This will run: ${n}
|
|
211
|
-
[y/N] `))return
|
|
212
|
-
Installation summary: ${a} succeeded, ${o} failed`);}async function
|
|
213
|
-
Update summary: ${a} updated, ${o} already up to date, ${t} failed`);}async function
|
|
211
|
+
[y/N] `))return be.debug(`[${e}] Installation cancelled by user`),o.silent||P(`${a}Skipped ${e} (cancelled).`),{name:e,success:true};o.silent||(r=an({text:`${a}Installing ${e}...`}).start());}let i=r?ew(a,r):void 0;try{let s=await hm(e,o.marketplaceSource,i?.callbacks,o.scope);if(i?.stopSpinner(),s.exitCode!==0){let n=s.stderr||"Command failed";return o.silent?Ne({status:"error",plugin:e,message:n}):S(`${a}Failed to install "${e}": ${n}`),{name:e,success:!1,error:n}}return o.silent?me({status:"success",plugin:e,command:s.command,duration_ms:s.duration_ms}):$(`${a}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:s.duration_ms}}catch(s){i?.stopSpinner();let n=Y(s);return o.silent?Ne({status:"error",plugin:e,message:n}):S(`${a}Failed to install "${e}": ${n}`),{name:e,success:false,error:n}}}async function ow(e,a,o,t){if(o.force)return {proceed:true,spinner:t};let r=Zs(e);if(!r)return {proceed:true,spinner:t};t?.stop();let i=o.scope??"user";if(r.scope===i){let c=`${e} is already installed ${$a(r)}. Use --force to reinstall.`;return o.silent?me({status:"already_installed",plugin:e,message:c}):P(`${a}${c}`),{proceed:false}}let s=o.isInteractive??!!process.stdin.isTTY;if(o.silent||!s){let c=`Already installed ${$a(r)}. Re-run with --force to install here too.`;return o.silent?me({status:"already_installed",plugin:e,message:c}):P(`${a}Skipping ${e} \u2014 ${c}`),{proceed:false}}return await en(e,i,r)?await ri(e,{force:true,scope:r.scope})!==0?(P(`${a}Could not remove ${e} from ${$a(r)} \u2014 skipping rather than leaving it in an inconsistent state.`),{proceed:false}):{proceed:true,spinner:o.silent?void 0:an({text:`${a}Installing ${e}...`}).start()}:(P(`${a}Skipped ${e}.`),{proceed:false})}async function tw(e,a,o){let t=o.silent?void 0:an({text:`${a}Installing ${e}...`}).start();if(Gt(e))return aw(e,a,o,t);let r=await ow(e,a,o,t);if(!r.proceed)return {name:e,success:true};t=r.spinner;try{let i=await je(e,{...o,onDownloadProgress:o.silent?void 0:(s,n)=>{if(!t||n===0)return;let{bar:d,percent:l,label:c}=ts(s,n);t.text=`${a}Downloading ${e}... ${d} ${l}% (${c})`;}});return t?.stop(),o.silent?me({status:"success",plugin:e,version:i.version,duration_ms:i.duration_ms}):$(`${a}${e} v${i.version} installed successfully`),{name:e,success:!0,version:i.version,duration_ms:i.duration_ms}}catch(i){if(t?.stop(),i instanceof Xe)return o.silent?me({status:"already_installed",plugin:e,message:i.message}):P(`${a}${i.message}`),{name:e,success:true};let s=Y(i);return o.silent?Ne({status:"error",plugin:e,message:s}):S(`${a}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function rw(e){let a=e.filter(t=>t.success).length,o=e.filter(t=>!t.success).length;P(`
|
|
212
|
+
Installation summary: ${a} succeeded, ${o} failed`);}async function iw(e,a){let o=new Map;if(a.source){for(let t of e)o.set(t,a.source);return o}try{let t=await to();for(let r of e){let s=t.filter(n=>n.name===r).find(n=>n.contentSource);s?.contentSource&&o.set(r,s.contentSource);}}catch{}return o}async function sr(e,a={}){if(!await he())return 1;let o=[],t=await iw(e,a);for(let r=0;r<e.length;r++){let i=e.length>1?`[${r+1}/${e.length}] `:"",s=e[r],n=t.get(s)??a.source,d=await tw(s,i,{...a,source:n});o.push(d);}return e.length>1&&(a.silent?me({status:"summary",succeeded:o.filter(r=>r.success).length,failed:o.filter(r=>!r.success).length,results:o.map(r=>({plugin:r.name,success:r.success,...r.error?{error:r.error}:{}}))}):rw(o)),o.some(r=>!r.success)?1:0}async function ri(e,a){if(!await he())return 1;if(be.debug(`[${e}] Looking up installed plugin`),!a.force){let o=on(e,a.scope);if(!o)return be.error(`[${e}] Plugin is not installed`),S(`Plugin "${e}" is not installed`),1;let t=v(o.name),r=o.version?v(o.version):void 0,i=a.scope?` (${a.scope})`:"";if(!await _(`Remove ${t} ${r?`v${r}`:"(n/a)"}${i}? [y/N] `))return be.debug(`[${e}] Uninstall cancelled by user`),P("Operation cancelled."),0}try{return be.debug(`[${e}] Uninstalling plugin${a.scope?` (scope: ${a.scope})`:""}`),await Or(e,a.scope),be.info(`[${e}] Uninstalled successfully`),$("Plugin removed successfully"),0}catch(o){return be.error(`[${e}] Failed to uninstall: ${Y(o)}`),S(Y(o)),1}}async function Kg(e,a={}){if(!await he())return 1;be.debug(`[${e}] Looking up installed plugin`);let o=on(e,a.scope);if(!o)return be.error(`[${e}] Plugin is not installed`),S(`Plugin "${e}" is not installed`),1;if(o.status==="enabled")return be.debug(`[${e}] Already enabled, skipping`),P(`${o.name} is already enabled`),0;try{return be.debug(`[${e}] Enabling plugin (current status: ${o.status})`),await Nr(e,"enabled",a.scope),be.info(`[${e}] Enabled successfully`),$(`${o.name} enabled successfully`),0}catch(t){return be.error(`[${e}] Failed to enable: ${Y(t)}`),S(Y(t)),1}}async function $g(e,a={}){if(!await he())return 1;be.debug(`[${e}] Looking up installed plugin`);let o=on(e,a.scope);if(!o)return be.error(`[${e}] Plugin is not installed`),S(`Plugin "${e}" is not installed`),1;if(o.status==="disabled")return be.debug(`[${e}] Already disabled, skipping`),P(`${o.name} is already disabled`),0;try{return be.debug(`[${e}] Disabling plugin (current status: ${o.status})`),await Nr(e,"disabled",a.scope),be.info(`[${e}] Disabled successfully`),$(`${o.name} disabled successfully`),0}catch(t){return be.error(`[${e}] Failed to disable: ${Y(t)}`),S(Y(t)),1}}async function Yg(e,a,o){o.silent||P(`${a}Updating ${e}...`);try{let t=await Ms(e,o);return o.silent?me({status:"updated",plugin:t.name,previousVersion:t.previousVersion,newVersion:t.newVersion,duration_ms:t.duration_ms}):$(`${a}${t.name} v${t.previousVersion} \u2192 v${t.newVersion}`),{name:e,success:!0}}catch(t){if(t instanceof Mo)return o.silent?me({status:"up_to_date",plugin:e,message:t.message}):P(`${a}${t.message}`),{name:e,success:true,skipped:true};let r=Y(t);return o.silent?Ne({status:"error",plugin:e,message:r}):S(`${a}Failed to update ${e}: ${r}`),{name:e,success:false,error:r}}}function sw(e){let a=e.filter(r=>r.success&&!r.skipped).length,o=e.filter(r=>r.skipped).length,t=e.filter(r=>!r.success).length;P(`
|
|
213
|
+
Update summary: ${a} updated, ${o} already up to date, ${t} failed`);}async function nw(e,a,o){try{let t=await Wt(e,o.source);ze(a,t.version,o.force)?P(`Would update ${e}: v${a} \u2192 v${t.version}`):P(`${e} is already up to date (v${a})`);}catch(t){return S(Y(t)),1}return 0}function dw(e){return new Map(e.filter(a=>!!a.version).map(a=>[a.name,a.version]))}function cw(e,a,o){let t=a.get(e.name);return t?e.version&&ze(e.version,t,o)?(P(`Would update ${e.name}: v${e.version} \u2192 v${t}`),true):(P(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(P(`Skipping ${e.name}: not found in catalog`),false)}async function lw(e,a){try{let o=await to(a.source),t=dw(o),r=0;for(let i of e)cw(i,t,a.force)&&r++;r===0&&P("All plugins are up to date");}catch(o){return S(Y(o)),1}return 0}async function uw(e,a){let o=[];for(let t=0;t<e.length;t++){let r=`[${t+1}/${e.length}] `,i=await Yg(e[t].name,r,a);o.push(i);}return a.silent?me({status:"summary",updated:o.filter(t=>t.success&&!t.skipped).length,upToDate:o.filter(t=>t.skipped).length,failed:o.filter(t=>!t.success).length,results:o.map(t=>({plugin:t.name,success:t.success,...t.skipped?{skipped:true}:{},...t.error?{error:t.error}:{}}))}):sw(o),o.some(t=>!t.success)?1:0}async function Zg(e,a={}){if(!await he())return 1;if(e){let r=on(e,a.scope);return r?a.dryRun?nw(e,r.version??"",a):(await Yg(e,"",a)).success?0:1:(a.silent?Ne({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):S(`Plugin "${e}" is not installed`),1)}let t=ce().filter(r=>r.marketplace===ue);return t.length===0?(a.silent?me({status:"empty",message:"No plugins installed"}):P("No plugins installed"),0):a.dryRun?lw(t,a):uw(t,a)}B();I();var ii=k("cli:bundle");function pw(e){let a=v(e.name??e.flowId),o=v(e.type??"unknown");return e.available?` \u2713 ${a} (${o})`:` \u2717 ${a} (${o}) \u2014 unavailable`}function mw(e,a){let o=a.filter(r=>r.available).length,t=a.length-o;process.stdout.write(`
|
|
214
214
|
Bundle: ${v(e)} (${a.length} artifacts)
|
|
215
|
-
`);for(let r of a)process.stdout.write(`${
|
|
215
|
+
`);for(let r of a)process.stdout.write(`${pw(r)}
|
|
216
216
|
`);process.stdout.write(`
|
|
217
217
|
${o} available for installation`),t>0&&process.stdout.write(` | ${t} unavailable`),process.stdout.write(`
|
|
218
218
|
|
|
219
|
-
`);}async function
|
|
220
|
-
`),process.stdout.write(`[${n}/${d}] Installing ${m} (${p})... ${
|
|
219
|
+
`);}async function ef(e){if(!e.trim())return S("Bundle name cannot be empty."),1;if(!await he())return 1;ii.debug(`Fetching bundle "${e}"`);let o;try{o=await Os(e);}catch(n){return n instanceof er||n instanceof Yr?(S(n.message),1):(S(`Failed to fetch bundle: ${n instanceof Error?n.message:String(n)}`),1)}let t=o.artifact.artifacts,r=t.filter(n=>n.available);if(ii.debug(`Bundle "${o.title}" \u2014 ${t.length} artifact(s), ${r.length} available`),mw(o.title,t),r.length===0)return S("No artifacts available for installation in this bundle."),1;if(!await _(`Install ${r.length} artifact(s)? [Y/n] `))return ii.debug("Installation cancelled by user"),0;ii.debug(`Starting installation of ${r.length} artifact(s)`);let s=await xs(o,{onProgress:({index:n,total:d,artifact:l,success:c,error:u})=>{let m=v(l.name??l.flowId),p=v(l.type??"unknown"),f=c?"\u2713":`\u2717 (${v(u??"failed")})`;n===1&&process.stdout.write(`
|
|
220
|
+
`),process.stdout.write(`[${n}/${d}] Installing ${m} (${p})... ${f}
|
|
221
221
|
`),n===d&&process.stdout.write(`
|
|
222
|
-
`);}});if(
|
|
222
|
+
`);}});if(ii.debug(`Installation complete \u2014 ${s.installed} installed, ${s.failed} failed, ${s.skipped} skipped`),s.installed>0&&$(`${s.installed} installed successfully`),s.failed>0){let n=s.failures.map(d=>d.name).join(", ");S(`${s.failed} failed: ${v(n)}`);}if(s.skipped>0){let n=t.filter(d=>!d.available).map(d=>v(d.name??d.flowId)).join(", ");P(`${s.skipped} unavailable: ${n}`);}return 0}qo();B();I();var af=k("marketplace");function fw(e){return `claude plugin marketplace add ${e}`}async function of(e,a){if(!await he())return 1;let o;try{o=us(e);}catch(i){let s=Y(i);return a.silent?Ne({status:"error",source:e,message:s}):S(s),1}af.debug(`[marketplace] Adding marketplace source: ${o}`);let t=fw(o);if(!a.force){let i=v(o),s=v(t);if(!await _(`Add marketplace "${i}"?
|
|
223
223
|
This will run: ${s}
|
|
224
|
-
[y/N] `))return
|
|
224
|
+
[y/N] `))return af.debug("[marketplace] Operation cancelled by user"),P("Operation cancelled."),0}let r=a.silent?void 0:an({text:`Adding marketplace "${v(o)}"...`}).start();try{let i=await qe(t);return r?.stop(),i.exitCode!==0?(a.silent?Ne({status:"error",source:o,exitCode:i.exitCode,message:i.stderr||"Command failed"}):(S(`Failed to add marketplace "${o}": ${i.stderr||"Command failed"}`),a.verbose&&i.stdout&&P(`stdout: ${i.stdout}`)),1):(a.silent?me({status:"success",source:o,command:t,duration_ms:i.duration_ms}):($(`Marketplace "${o}" added successfully`),a.verbose&&i.stdout&&P(i.stdout)),0)}catch(i){r?.stop();let s=Y(i);return a.silent?Ne({status:"error",source:o,message:s}):S(`Failed to add marketplace "${o}": ${s}`),1}}Re();B();async function yw(){return await Z()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function kw(){let e=Date.now();try{await to();let a=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${a}ms)`,latency:a}}catch(a){return a instanceof Error&&a.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${a instanceof Error?a.message:"Unknown"}`}}}async function Pw(){return await wo()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Dw(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function ww(){let e=Ys();if(e.length!==0){process.stdout.write(`
|
|
225
225
|
`+R.bold(` Marketplace Auto-Update
|
|
226
226
|
|
|
227
|
-
`));for(let a of e){let o=a.enabled?R.green("[ON] "):R.dim("[OFF]"),t=v(a.name).padEnd(20),r=v(
|
|
228
|
-
`);}}}function
|
|
227
|
+
`));for(let a of e){let o=a.enabled?R.green("[ON] "):R.dim("[OFF]"),t=v(a.name).padEnd(20),r=v(Qg(a));process.stdout.write(` ${o} ${t} ${R.dim(r)}
|
|
228
|
+
`);}}}function Sw(){process.stdout.write(`
|
|
229
229
|
`+R.bold(` FlowSetup CLI \u2014 Auto-Update Fix
|
|
230
230
|
|
|
231
|
-
`));let e=
|
|
231
|
+
`));let e=_g();for(let a of e.fixed)process.stdout.write(` ${R.green("[FIXED]")} ${v(a)} \u2014 autoUpdate: true set
|
|
232
232
|
`);for(let{name:a,reason:o}of e.skipped)process.stdout.write(` ${R.dim("[SKIP] ")} ${v(a)} \u2014 ${v(o)}
|
|
233
233
|
`);return process.stdout.write(`
|
|
234
234
|
`),e.fixed.length===0?process.stdout.write(R.dim(` Nothing to fix \u2014 all set.
|
|
235
235
|
|
|
236
236
|
`)):process.stdout.write(R.green(` \u2713 ${e.fixed.length} marketplace(s) updated.
|
|
237
237
|
|
|
238
|
-
`)),0}async function
|
|
238
|
+
`)),0}async function tf(e={}){if(e.fix)return Sw();process.stdout.write(`
|
|
239
239
|
`+R.bold(` FlowSetup CLI Diagnostics
|
|
240
240
|
|
|
241
|
-
`));let a=[{name:"Credentials",fn:
|
|
242
|
-
`);}return
|
|
241
|
+
`));let a=[{name:"Credentials",fn:yw},{name:"Prompt Manager",fn:kw},{name:"Valid Token",fn:Pw},{name:"Claude Code",fn:Dw}],o=true;for(let t of a){let r=await t.fn(),i="",s=R.green;r.passed?i=R.green("[OK] "):(i=R.red("[FAIL]"),s=R.red,o=false);let n=` ${i} ${s(t.name.padEnd(18))} ${v(r.message)}`;process.stdout.write(n+`
|
|
242
|
+
`);}return ww(),process.stdout.write(`
|
|
243
243
|
`),o?(process.stdout.write(R.green(` \u2713 All checks passed!
|
|
244
244
|
|
|
245
245
|
`)),0):(process.stdout.write(R.red(` \u2717 Some checks failed \u2014 verify your configuration
|
|
246
246
|
|
|
247
|
-
`)),1)}Re();
|
|
247
|
+
`)),1)}Re();Xo();U();async function rf(e){let a=await Z(),o=Oa("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),t={Authorization:`Bearer ${e}`,accept:"application/json"};if(a?.tenant){if(!Ya.test(a.tenant))throw new Error(`Invalid tenant value: "${a.tenant}"`);t.FlowTenant=a.tenant;}let r=await Yu.get(`${o}rate-limit/me`,{searchParams:{mode:"budget"},headers:t}).json();if(typeof r.consumed_usd!="number"||typeof r.budget_limit!="number"||typeof r.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return r}xt();Fi();Re();B();I();var Rw=k("commands:usage"),tn=20,sf="EMAIL",nf="MONTHLY CONSUMPTION (USD)",df="STATUS";function Aw(e){let a=Math.min(100,Math.max(0,e)),o=Math.round(a/100*tn),t=tn-o,r=R.green;return a>=90?r=R.red:a>=70&&(r=R.yellow),r("\u2588".repeat(o))+R.dim("\u2591".repeat(t))}function cf(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function xw(e){let a=e.toLowerCase(),o=v(e),t=o.charAt(0).toUpperCase()+o.slice(1).toLowerCase();return a==="ok"||a==="unblocked"?R.green(`\u2299 ${t}`):a==="warning"?R.yellow(`\u26A0 ${t}`):a==="blocked"?R.red("\u2717 Budget limit reached"):R.red(`\u2717 ${t}`)}function Ew(e){let a=La(e),o=Math.ceil((new Date(e).getTime()-Date.now())/864e5),t=o>0?` (in ${o} day${o===1?"":"s"})`:"";return `${a}${t}`}async function Iw(e){try{let a=await Rt();if(a?.email)return v(a.email);let o=At(e);return v(o.email??"")}catch(a){return Rw.debug(`JWT email decode failed: ${String(a)}`),""}}async function lf(e){if(!await he())return 1;let o;try{o=await Na();}catch(h){return S(`Authentication error: ${Y(h)}`),1}let t;try{t=await rf(o);}catch(h){return S(`Failed to fetch usage data: ${Y(h)}`),1}if(e.json)return yo(t),0;let r=await Iw(o)||v(t.user_id),i=cf(t.consumed_usd),s=cf(t.budget_limit),n=`${t.percentage.toFixed(1)}%`,d=`${i} / ${s} (${n})`,l=Math.max(sf.length,r.length+2),c=Math.max(nf.length,tn+2+d.length),u=` ${sf.padEnd(l)} ${nf.padEnd(c)} ${df}`,m=` ${"\u2500".repeat(l)} ${"\u2500".repeat(c)} ${"\u2500".repeat(df.length)}`,p=`${R.cyan("\u2022")} ${r.padEnd(l-2)}`,f=`${Aw(t.percentage)} ${d.padEnd(c-tn-2)}`,g=` ${R.dim("Resets")} ${Ew(t.renewal_date)}`;return process.stdout.write(`
|
|
248
248
|
`),process.stdout.write(R.dim(u)+`
|
|
249
249
|
`),process.stdout.write(R.dim(m)+`
|
|
250
|
-
`),process.stdout.write(` ${p} ${
|
|
251
|
-
`),process.stdout.write(
|
|
250
|
+
`),process.stdout.write(` ${p} ${f} ${xw(t.status)}
|
|
251
|
+
`),process.stdout.write(g+`
|
|
252
252
|
`),process.stdout.write(`
|
|
253
|
-
`),0}var
|
|
254
|
-
`,{encoding:"utf-8",mode:384}),renameSync(r,o);}async function
|
|
253
|
+
`),0}var qw=["github.com","www.github.com"],Lw=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Fw=/^([^@]+)@(.+)$/;function Ow(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Cc(e){let a=e.replace(/\\/g,"/");a=a.replace(/^\/+/,"").replace(/\/+$/,"");let o=a.split("/").filter(Boolean);for(let t of o)if(t==="..")throw new Error(`Invalid subpath: "${e}" contains path traversal ("..").`);return o.join("/")}function Nw(e){let a=e.pathname.split("/").filter(Boolean);if(a.length<2)throw new Error(`Invalid GitHub URL: expected at least owner/repo in "${e.href}"`);let o=a[0],t=a[1];t.endsWith(".git")&&(t=t.slice(0,-4));let r={type:"github",url:`https://github.com/${o}/${t}.git`};if(a.length>=3&&(a[2]==="tree"||a[2]==="blob")){if(a.length>=4&&(r.ref=a[3]),a.length>=5){let i=a.slice(4).join("/");r.subpath=Cc(i);}}else if(a.length>2){let i=a.slice(2).join("/");r.subpath=Cc(i);}return e.hash&&e.hash.length>1&&(r.ref=decodeURIComponent(e.hash.slice(1))),r}function rn(e){let a=e.trim();if(!a)throw new Error("Skill source cannot be empty.");if(Ow(a)){let o=resolve(a);return {type:"local",url:o,localPath:o}}try{let o=new URL(a);if((o.protocol==="https:"||o.protocol==="http:")&&qw.includes(o.hostname))return Nw(o);if(o.protocol==="https:"||o.protocol==="http:"){let t={type:"git",url:a};return o.hash&&o.hash.length>1&&(t.ref=decodeURIComponent(o.hash.slice(1)),t.url=a.replace(o.hash,"")),t}if(o.protocol==="git:"){let t={type:"git",url:a};return o.hash&&o.hash.length>1&&(t.ref=decodeURIComponent(o.hash.slice(1)),t.url=a.replace(o.hash,"")),t}}catch{}if(a.startsWith("git@")||a.includes(":")&&a.includes(".git")){let o=a,t,r=a.indexOf("#");r!==-1&&(t=a.slice(r+1),o=a.slice(0,r));let i={type:"git",url:o};return t&&(i.ref=t),i}{let o=a,t,r=o.indexOf("#");r!==-1&&(t=o.slice(r+1),o=o.slice(0,r));let i=o.match(Lw);if(i){let s=i[1],n=i[2],d=i[3],l,c=n.match(Fw);c&&(n=c[1],l=c[2]),n.endsWith(".git")&&(n=n.slice(0,-4));let u={type:"github",url:`https://github.com/${s}/${n}.git`};if(t&&(u.ref=t),l&&(u.skillFilter=l),d){let m=d.replace(/^\//,"");m&&(u.subpath=Cc(m));}return u}}return {type:"git",url:a}}function sn(e){if(e.type!=="github")return null;try{let o=new URL(e.url).pathname.split("/").filter(Boolean);if(o.length<2)return null;let t=o[1];return t.endsWith(".git")&&(t=t.slice(0,-4)),`${o[0]}/${t}`}catch{return null}}function uf(e){let a=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);return a?{data:parse(a[1])??{},content:a[2]??""}:{data:{},content:e}}var Ac=new Set(["node_modules",".git","dist","build","__pycache__"]);function gf(e,a){let o=normalize(resolve(e)),t=normalize(resolve(a));return t.startsWith(o+sep)||t===o}function zw(e,a){let o=normalize(resolve(e)),t=normalize(resolve(join(e,a)));return t.startsWith(o+sep)||t===o}async function Rc(e){try{let a=join(e,"SKILL.md");return (await stat(a)).isFile()}catch{return false}}async function si(e){try{let a=await readFile(e,"utf-8"),{data:o}=uf(a);return typeof o.name!="string"||typeof o.description!="string"?null:{name:o.name,description:o.description,path:dirname(e),rawContent:a,metadata:o.metadata}}catch{return null}}async function ff(e,a=0,o=5){if(a>o)return [];try{let[t,r]=await Promise.all([Rc(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),i=t?[e]:[],s=await Promise.all(r.filter(n=>n.isDirectory()&&!Ac.has(n.name)).map(n=>ff(join(e,n.name),a+1,o)));return [...i,...s.flat()]}catch{return []}}async function cn(e,a){let o=[],t=new Set;if(a&&!zw(e,a))throw new Error(`Invalid subpath: "${a}" resolves outside the repository directory.`);let r=a?join(e,a):e;if(await Rc(r)){let s=await si(join(r,"SKILL.md"));if(s)return o.push(s),t.add(s.name),o}let i=[r,join(r,"skills"),join(r,".claude/skills"),join(r,".agents/skills")];for(let s of i)try{let n=await readdir(s,{withFileTypes:!0});for(let d of n){if(!d.isDirectory())continue;let l=join(s,d.name);if(await Rc(l)){let c=await si(join(l,"SKILL.md"));c&&!t.has(c.name)&&(o.push(c),t.add(c.name));}}}catch{}if(o.length===0){let s=await ff(r);for(let n of s){let d=await si(join(n,"SKILL.md"));d&&!t.has(d.name)&&(o.push(d),t.add(d.name));}}return o}function hf(e,a){let o=a.map(t=>t.toLowerCase());return e.filter(t=>{let r=t.name.toLowerCase();return o.some(i=>i===r)})}Oe();var kf=1,_w={retries:5,minTimeout:50};async function Pf(e,a){mkdirSync(dirname(e),{recursive:true});let o=await $b.lock(e+".lock",{realpath:false,retries:_w});try{return await a()}finally{await o();}}function bf(){return {version:kf,skills:{}}}async function ln(e){let a=pr(e);try{let o=await readFile(a,"utf-8"),t=JSON.parse(o);return !t.version||t.version<kf?bf():t}catch{return bf()}}function Xw(e){let a={};for(let o of Object.keys(e).sort())a[o]=e[o];return a}async function Df(e,a){let o=pr(a);mkdirSync(dirname(o),{recursive:true});let t={version:e.version,skills:Xw(e.skills)},r=`${o}.${randomUUID()}.tmp`;writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
254
|
+
`,{encoding:"utf-8",mode:384}),renameSync(r,o);}async function wf(e,a,o){let t=pr(o);await Pf(t,async()=>{let r=await ln(o),i=new Date().toISOString(),s=r.skills[e];r.skills[e]={...a,installedAt:s?.installedAt??i,updatedAt:i},await Df(r,o);});}async function Sf(e,a){let o=pr(a);await Pf(o,async()=>{let t=await ln(a);e in t.skills&&(delete t.skills[e],await Df(t,a));});}Oe();I();var Cf=k("skillInstaller");async function tS(e,a,o,t){try{await C(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:a,version:o,duration_ms:t,interface:ee().interfaceType});}catch(r){Cf.warn(`Failed to send skill install metrics: ${String(r)}`);}}async function rS(e,a){try{await C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:ee().interfaceType});}catch(o){Cf.warn(`Failed to send skill install-failed metrics: ${String(o)}`);}}async function iS(e,a){await cp(e,a,{recursive:true,dereference:false,filter:o=>{if(Ac.has(basename(o)))return false;try{return !lstatSync(o).isSymbolicLink()}catch{return false}}});}async function sS(e,a,o){let t=da(e.name),r=Vo(a),i=join(r,t);if(!gf(r,i))return {skill:e.name,success:false,path:i,error:`Unsafe install path: "${i}" escapes skills directory`};try{await rm(i,{recursive:!0,force:!0}),await mkdir(i,{recursive:!0}),await iS(e.path,i);let n=sn(o)??o.url;return await wf(t,{source:n,sourceType:o.type,sourceUrl:o.url,ref:o.ref,skillPath:o.subpath},a),{skill:e.name,success:!0,path:i}}catch(s){return {skill:e.name,success:false,path:i,error:s instanceof Error?s.message:String(s)}}}async function Rf(e,a){let o=rn(e),t;try{let r;if(o.type==="local"){if(!o.localPath||!existsSync(o.localPath))return {source:e,results:[],discovered:0,installed:0,failed:0};r=o.localPath;}else t=await Sa(o.url,o.ref),r=t;let i=await cn(r,o.subpath),s=[...a.skillFilter??[]];o.skillFilter&&s.push(o.skillFilter);let n=s.length>0?hf(i,s):i,d=[],l=o.ref??"latest";for(let c of n){let u=Date.now(),m=await sS(c,a.scope,o);d.push(m);let p=Date.now()-u;m.success?await tS(c.name,a.scope,l,p):await rS(c.name,new Error(m.error??"Unknown error"));}return {source:e,results:d,discovered:i.length,installed:d.filter(c=>c.success).length,failed:d.filter(c=>!c.success).length}}finally{t&&await Ca(t).catch(()=>{});}}Oe();B();I();var uS=k("skills");async function pS(e){try{await C(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:ee().interfaceType});}catch(a){uS.warn(`Failed to send skill uninstall metrics: ${String(a)}`);}}async function mS(e){let a=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(`${v(e)} (y/N) `,t=>{a.close(),o(t.trim().toLowerCase()==="y");});})}async function gS(e){let a=rn(e),o;try{let t;if(a.type==="local"){if(!a.localPath)return S("Invalid local path."),1;t=a.localPath;}else P(`Fetching skills from ${v(e)}...`),o=await Sa(a.url,a.ref),t=o;let r=await cn(t,a.subpath);if(r.length===0)return P("No skills found in this source."),0;let s=sn(a)??v(e);P(`Found ${r.length} skill(s) in ${s}:
|
|
255
255
|
`);for(let n of r){let d=v(n.name),l=v(n.description);process.stdout.write(` ${R.bold(d)} ${R.dim(l)}
|
|
256
256
|
`);}return process.stdout.write(`
|
|
257
|
-
`),0}catch(t){return t instanceof
|
|
258
|
-
`);let a=e.source;e.installed>0&&P(`Installed ${e.installed} of ${e.discovered} skill(s) from ${v(a)}`),e.failed>0&&S(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?P("No skills found in this source."):e.results.length===0&&e.discovered>0&&P(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function
|
|
257
|
+
`),0}catch(t){return t instanceof No?S(t.message):S(t instanceof Error?t.message:String(t)),1}finally{o&&await Ca(o).catch(()=>{});}}function fS(e){for(let o of e.results){let t=v(o.skill);if(o.success){let r=relative(process.cwd(),o.path);$(`${t} installed ${R.dim(`\u2192 ${r}/`)}`);}else S(`${t}: ${v(o.error??"unknown error")}`);}process.stdout.write(`
|
|
258
|
+
`);let a=e.source;e.installed>0&&P(`Installed ${e.installed} of ${e.discovered} skill(s) from ${v(a)}`),e.failed>0&&S(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?P("No skills found in this source."):e.results.length===0&&e.discovered>0&&P(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function xf(e,a){if(a.list)return gS(e);let o=a.global?"global":"project";try{let t=await Rf(e,{scope:o,skillFilter:a.skill,yes:a.yes});return fS(t),t.failed>0?1:0}catch(t){return t instanceof No?S(t.message):S(t instanceof Error?t.message:String(t)),1}}async function Ef(e){let a=Vo(e),o=[];try{let t=await readdir(a,{withFileTypes:!0});for(let r of t){if(!r.isDirectory())continue;let i=join(a,r.name),s=join(i,"SKILL.md");try{if(!(await stat(s)).isFile())continue}catch{continue}let n=await si(s);n?o.push({name:n.name,description:n.description,path:i}):o.push({name:r.name,description:"(no metadata)",path:i});}}catch{}return o}async function If(e){let a=e.global?"global":"project",o=await Ef(a),t=await ln(a);if(e.json){let i=o.map(s=>({name:s.name,description:s.description,path:s.path,source:t.skills[da(s.name)]?.source}));return yo(i),0}if(o.length===0)return P(`No skills installed (${a==="global"?"global":"project"} scope).`),0;P(`${a==="global"?"Global":"Project"} skills (${o.length}):
|
|
259
259
|
`);for(let i of o){let s=t.skills[da(i.name)]?.source,n=v(i.name),d=v(i.description),l=d.length>80?d.slice(0,77)+"...":d,c=s?R.dim(` (${s})`):"";process.stdout.write(` ${R.bold(n)}${c}
|
|
260
260
|
`),process.stdout.write(` ${R.dim(l)}
|
|
261
261
|
|
|
262
|
-
`);}return 0}async function
|
|
262
|
+
`);}return 0}async function Tf(e,a){let o=a.global?"global":"project";if(!e){let s=await Ef(o);if(s.length===0)return P("No skills installed."),0;P("Installed skills:");for(let n of s)process.stdout.write(` - ${v(n.name)}
|
|
263
263
|
`);return process.stdout.write(`
|
|
264
|
-
`),P("Specify a skill name to remove: flow skills remove <name>"),1}let t=da(e),r=
|
|
265
|
-
Import summary: 0 installed, ${r.length} failed`);for(let n of r)S(` ${n.name}: ${n.error}`);return r.length>0?1:0}P(`Importing ${t.length} plugin(s)...`);let s=0;for(let n of t){let d=a.scope??n.scope??"user",l=
|
|
266
|
-
Import summary: ${s} installed, ${r.length} failed`);for(let n of r)S(` ${n.name}: ${n.error}`);return r.length>0?1:0}I();
|
|
264
|
+
`),P("Specify a skill name to remove: flow skills remove <name>"),1}let t=da(e),r=Vo(o),i=join(r,t);try{await stat(i);}catch{return S(`Skill "${v(e)}" is not installed.`),1}if(!a.force&&!await mS(`Remove skill "${v(t)}"?`))return P("Cancelled."),0;try{return await rm(i,{recursive:!0,force:!0}),await Sf(t,o),await pS(t),$(`Skill "${v(t)}" removed.`),0}catch(s){return S(`Failed to remove skill: ${s instanceof Error?s.message:String(s)}`),1}}B();I();U();var un=k("transfer"),Ec=1;function hS(e){return e.marketplace&&e.marketplace!==ue?`${e.name}@${e.marketplace}`:e.name}function bS(e,a){let o=e.filter(r=>a.has(r.name)),t=e.filter(r=>!a.has(r.name));o.length>0&&P(`Already installed (${o.length}): ${o.map(r=>r.name).join(", ")}`),P(`To install (${t.length}): ${t.length>0?t.map(r=>r.name).join(", "):"none"}`);}function Lf(e){let a=ne__default.resolve(e.output);try{let o=ce(),t={version:Ec,exportedAt:new Date().toISOString(),plugins:o.map(r=>({name:r.name,marketplace:r.marketplace,scope:r.scope,...r.type!==void 0?{type:r.type}:{}}))};return ie__default.writeFileSync(a,JSON.stringify(t,null,2),"utf-8"),$(`Exported ${o.length} plugin(s) to ${a}`),0}catch(o){let t=Y(o);return un.error(`Export failed: ${t}`),S(`Failed to export plugins: ${t}`),1}}async function Ff(e,a={}){if(!await he())return 1;let o;try{let n=ie__default.readFileSync(ne__default.resolve(e),"utf-8");o=JSON.parse(n);}catch(n){return S(`Failed to read import file "${e}": ${Y(n)}`),1}if(o.version!==Ec)return S(`Unsupported export format version ${o.version??"(none)"} \u2014 expected ${Ec}`),1;if(!Array.isArray(o.plugins))return S('Invalid export file format: missing or invalid "plugins" array'),1;if(o.plugins.length===0)return P("No plugins to import"),0;let t=[],r=[],i=0;for(let[n,d]of o.plugins.entries())if(!d?.name||typeof d.name!="string"){let l=`entry[${n}]`;un.warn(`Skipping ${l}: missing or invalid name`),r.push({name:l,error:"missing or invalid name"});}else d.type==="mcp"?(un.debug(`[${d.name}] Skipping MCP entry`),i++):t.push(d);if(i>0&&P(`Skipping ${i} MCP(s) \u2014 use 'flow mcp add' to install them manually`),a.diff||a.dryRun){let n=new Set(ce().map(d=>d.name));bS(t,n);}if(a.dryRun)return P("Dry-run mode: no plugins were installed"),0;if(t.length===0){P(`
|
|
265
|
+
Import summary: 0 installed, ${r.length} failed`);for(let n of r)S(` ${n.name}: ${n.error}`);return r.length>0?1:0}P(`Importing ${t.length} plugin(s)...`);let s=0;for(let n of t){let d=a.scope??n.scope??"user",l=hS(n);un.debug(`[${n.name}] Installing as "${l}" in scope "${d}"`),await sr([l],{scope:d,force:a.force})===0?s++:r.push({name:n.name,error:"installation failed"});}P(`
|
|
266
|
+
Import summary: ${s} installed, ${r.length} failed`);for(let n of r)S(` ${n.name}: ${n.error}`);return r.length>0?1:0}I();B();function G(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}B();I();var yS=k("moduleProxy");function kS(e){if(!process.stdin.isTTY)return Promise.resolve(false);let a=Bd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(v(e),t=>{a.close(),o(!["n","no"].includes(t.toLowerCase().trim()));});})}async function Of(e,a){let o=Date.now(),r=spawnSync(e.binaryName,a,{stdio:"inherit",env:process.env}).status??1;await C(w.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:r,duration_ms:Date.now()-o,subcommand:a[0]??null}).catch(i=>{yS.warn(`Failed to emit proxy executed event: ${String(i)}`);}),G(r);}async function Gf(e,a){let o=de.find(r=>r.alias===e);if(!o){S(`Unknown module alias: '${e}'`),G(1);return}if(!await Ba(o.binaryName)){S(`Module '${e}' (${o.binaryName}) is not installed.`);let r=o.platforms[process.platform];if(!r||r.status!=="supported"){await C(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),G(1);return}let i=(await Promise.all(r.strategies.map(async n=>{try{return await Ua(n.type).isAvailable()?n.type:null}catch{return null}}))).find(n=>n!==null)??null;if(!i){S(`No supported installation method available for '${e}' on this platform.`),G(1);return}if(await kS("Would you like to install it now? [Y/n] ")){await C(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let n=await Io(o,"inline",i);if(!n.success){S(`Failed to install '${e}': ${n.error?.message??"unknown error"}`),G(1);return}await Of(o,a);}else P(`To install manually, run: flow modules install ${e}`),await C(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),G(1);return}await Of(o,a);}B();var SS=promisify(execFile);async function CS(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:t}=await SS(eo(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(t).trim()||null}let a=new AbortController,o=setTimeout(()=>a.abort(),5e3);try{let t={"User-Agent":`flow-plugins-cli/${ve}`,Accept:"application/vnd.github+json"};process.env.GITHUB_TOKEN&&(t.Authorization=`Bearer ${process.env.GITHUB_TOKEN}`);let r=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:a.signal,headers:t});return r.ok?(await r.json()).tag_name?.replace(/^v/,"")??null:null}finally{clearTimeout(o);}}catch{return null}}function RS(e,a,o,t){return t?.status==="experimental"?"experimental":!t||t.status!=="supported"||!e?"not_installed":a&&o&&ze(a,o)?"outdated":"installed"}async function Ic(){let e=await Promise.all(de.map(async a=>{let[o,t]=await Promise.all([Ba(a.binaryName),CS(a)]),i=ta(a.alias)?.installedVersion??null,s=a.platforms[process.platform],n=RS(o,i,t,s),d=i??"\u2014";return [a.name,a.alias,d,n,process.platform]}));return vo(["Name","Alias","Version","Status","Platform"],e),0}async function Uf(e){let a=de.find(s=>s.alias===e);if(!a)return S(`Unknown module alias: '${e}'`),1;let[o]=await or([a]);if(o.alreadyInstalled){let s=ta(a.alias),n=s?.installedVersion?` (v${s.installedVersion})`:"";return P(`Module ${a.name} already installed${n}. Use: flow modules update ${e}`),0}if(o.availableStrategies.length===0){let s=a.platforms[process.platform],n=a.docs?` See: ${a.docs}`:"";return !s||s.status!=="supported"?S(`Module ${a.name} is not supported on ${process.platform}.${n}`):S(`No installation method available for ${a.name} on ${process.platform}.${n}`),1}let t=o.availableStrategies[0],r=an({text:`Installing ${a.name}...`}).start(),i;try{i=await Io(a,"on_demand",t);}finally{r.stop();}return i.success?($(`${a.name} v${i.version??"unknown"} installed`),i.pendingInteractiveSetup&&spawnSync(i.pendingInteractiveSetup[0],i.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(S(i.error?.message??"Installation failed"),1)}async function Bf(e,a){let o=an({text:`Updating ${e.name}...`}).start(),t;try{t=await Xi(e,"command");}catch(r){return o.error(`${e.name}: ${r instanceof Error?r.message:String(r)}`),"error"}if(t.success){let r=t.version??"unknown";return r===a?(o.success(`${e.name}: already up to date (v${a})`),"up_to_date"):(o.success(`${e.name}: v${a} \u2192 v${r}`),"success")}return o.error(`${e.name}: ${t.error?.message??"Update failed"}`),"error"}async function zf(e){if(e!==null){let t=de.find(s=>s.alias===e);if(!t)return S(`Unknown module alias: '${e}'`),1;let r=ta(t.alias);return r?.installMethod?await Bf(t,r.installedVersion??"unknown")==="error"?1:0:(S(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let a=tt().filter(t=>t.installMethod!==null);if(a.length===0)return P("No installed modules to update."),0;let o=0;for(let t of a){let r=de.find(s=>s.alias===t.alias);if(!r)continue;await Bf(r,t.installedVersion??"unknown")==="error"&&(o=1);}return o}var ni=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
|
|
267
267
|
title: "0-current-state \u2014 Index"
|
|
268
268
|
type: index
|
|
269
269
|
domain: platform
|
|
@@ -554,7 +554,7 @@ analyzes these files and creates the correct \`.md\` files in the numbered folde
|
|
|
554
554
|
**6. Source code never in monitored folders.**
|
|
555
555
|
If you create a folder with app or script source code, keep it out of the 5 numbered folders
|
|
556
556
|
entirely (e.g. \`prototypes/\`).
|
|
557
|
-
`},{path:"docs/README.md",sha256:"da3c8e019b808bd66cc794d8350bd204d75ba0387eb1545f7223eb9049a911c8",content:"# docs/ \u2014 Raw Input\n\nDrop raw files here \u2014 PDFs, images, standalone Markdowns, tool exports (Jira, Miro, Confluence),\nlegacy documentation. Nothing in this folder is curated content: it exists to be analyzed and\nsynthesized into `0-current-state/`, `1-strategy/`, `2-plan/`, `3-delivery/` or `4-learn/`.\n\nSee `STRUCTURE.md` at the repo root for the full folder guide.\n"}];
|
|
557
|
+
`},{path:"docs/README.md",sha256:"da3c8e019b808bd66cc794d8350bd204d75ba0387eb1545f7223eb9049a911c8",content:"# docs/ \u2014 Raw Input\n\nDrop raw files here \u2014 PDFs, images, standalone Markdowns, tool exports (Jira, Miro, Confluence),\nlegacy documentation. Nothing in this folder is curated content: it exists to be analyzed and\nsynthesized into `0-current-state/`, `1-strategy/`, `2-plan/`, `3-delivery/` or `4-learn/`.\n\nSee `STRUCTURE.md` at the repo root for the full folder guide.\n"}];B();var Fc="CLAUDE.md";function ES(e){return createHash("sha256").update(e,"utf8").digest("hex")}function Oc(){return {new:0,unchanged:0,divergent:0,declined:0}}async function Jf(e={}){let a=e.targetDir??process.cwd(),o=e.dryRun??false,t=e.force??false,r=e.isInteractive??!!process.stdin.isTTY,i=e.confirmOverwrite??Gc,s=e.confirmCreate??TS,n=[],d=Oc(),l=ni.find(m=>m.path===Fc),c=l?existsSync(join(a,l.path)):true;if(l&&!c){let m=join(a,l.path);r?await s(l.path)?(n.push({path:l.path,status:"new"}),d.new++,o||(mkdirSync(dirname(m),{recursive:true}),writeFileSync(m,l.content,"utf8"))):P(`declined: ${Fc} not created`):e.assistant==="claude-code"&&(n.push({path:l.path,status:"new"}),d.new++,o||(mkdirSync(dirname(m),{recursive:true}),writeFileSync(m,l.content,"utf8")));}for(let m of ni){if(m.path===Fc&&!c)continue;let p=join(a,m.path),f=await Nc({dstPath:p,template:m,force:t,isInteractive:r,confirmOverwrite:g=>i(g)});n.push({path:m.path,status:f.status}),d[f.status]++,f.write&&!o&&(mkdirSync(dirname(p),{recursive:true}),writeFileSync(p,m.content,"utf8"));}let u=d.divergent>0||d.declined>0;return {files:n,counts:d,hasUnresolved:u}}async function Nc(e){let{dstPath:a,template:o,force:t,isInteractive:r,confirmOverwrite:i}=e;return existsSync(a)?ES(readFileSync(a,"utf8"))===o.sha256?{status:"unchanged",write:false}:t?{status:"divergent",write:true}:(IS(o.path),r?await i(o.path)?{status:"divergent",write:true}:{status:"declined",write:false}:{status:"declined",write:false}):{status:"new",write:true}}function IS(e){P(`${e} differs from the Flow strategy template. Review your local changes before overwriting \u2014 run "git status" and "git diff ${e}", or open your IDE's diff/history view for this file. Once overwritten, uncommitted local changes are gone for good.`);}async function Gc(e){return _(` Overwrite ${e} with the updated template? [y/N] `)}async function TS(e){return _(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}var Hf=[{path:"docs/catalog/TEMPLATES/agents/_TEMPLATE-LEVEL-0.md",sha256:"5f6d1ef6336d69c9fa53ec3167e4f0eb8ec212e21e771356e357e397946f3638",content:`---
|
|
558
558
|
id: <slug-do-card>
|
|
559
559
|
kind: agent | skill
|
|
560
560
|
level: 0
|
|
@@ -30830,7 +30830,7 @@ flowchart TD
|
|
|
30830
30830
|
style A fill:#0369a1,color:#fff,stroke:none
|
|
30831
30831
|
style H fill:#059669,color:#fff,stroke:none
|
|
30832
30832
|
\`\`\`
|
|
30833
|
-
`}],
|
|
30833
|
+
`}],pn={"cit-tools":[{path:"docs/playbooks/cit-tools.en.md",sha256:"e05497be5766955d50b040efb0eeb031a3b1bddfe0c9ed16f78c91fa1a17dcda",content:`---
|
|
30834
30834
|
title: "cit-tools \u2014 CI&T-Branded Design Tooling"
|
|
30835
30835
|
type: runbook
|
|
30836
30836
|
domain: toolchain
|
|
@@ -84775,26 +84775,31 @@ updated: "2026-09-23"
|
|
|
84775
84775
|
flow plugin marketplace add cit-flow/flow-harness
|
|
84776
84776
|
flow plugin install runbook-tech-common
|
|
84777
84777
|
\`\`\`
|
|
84778
|
-
`}]};function
|
|
84778
|
+
`}]};function OS(e){let a=new Set,o=[];for(let t of e){let r=pn[t];if(r)for(let i of r)a.has(i.path)||(a.add(i.path),o.push(i));}return o}function NS(e){return e.endsWith(".en.md")||e.endsWith(".es.md")?e.slice(0,-6)+".md":e}function GS(e){return e.endsWith(".en.md")?"en":e.endsWith(".es.md")?"es":"pt"}function BS(e,a){if(a==="all")return e;let o=new Map,t=[];for(let i of e){if(!i.path.endsWith(".md")){t.push(i);continue}let s=NS(i.path),n=GS(i.path),d=o.get(s);d||(d=new Map,o.set(s,d)),d.set(n,i);}let r=[];for(let[i,s]of o){let n=s.get(a)??s.get("pt")??s.get("en")??s.get("es");r.push({...n,path:i});}return [...t,...r]}async function Vf(e){let a=e.targetDir??process.cwd(),o=e.dryRun??false,t=e.force??false,r=e.isInteractive??!!process.stdin.isTTY,i=e.confirmOverwrite??Gc,s=e.docsLang??"all",n=e.installedBundles.length===0,d=n?[]:OS(e.installedBundles),l=BS([...Hf,...d],s),c=[],u=Oc();for(let p of l){let f=join(a,p.path),g=await Nc({dstPath:f,template:p,force:t,isInteractive:r,confirmOverwrite:h=>i(h)});c.push({path:p.path,status:g.status}),u[g.status]++,g.write&&!o&&(mkdirSync(dirname(f),{recursive:true}),writeFileSync(f,p.content,"utf8"));}let m=u.divergent>0||u.declined>0;return {files:c,counts:u,hasUnresolved:m,skippedPlaybooks:n}}function Qf(){let e=Ae().plugins,a=process.cwd(),o=new Set(Object.keys(pn)),t=new Set;for(let[r,i]of Object.entries(e)){let s=r.split("@")[0];if(!s||!o.has(s))continue;i.some(d=>d.scope==="user"||d.projectPath===a)&&t.add(s);}return [...t].sort()}B();I();Re();Xo();I();var Bc=k("lib:otelMetrics"),US="flow-plugins-cli",zS="1.0.0",WS=5e3;function JS(){return Oa("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function HS(e,a){return typeof a=="number"?{key:e,value:{intValue:String(a)}}:typeof a=="boolean"?{key:e,value:{boolValue:a}}:{key:e,value:{stringValue:a}}}function VS(e,a){let o=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:US,version:zS},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:o,timeUnixNano:o,attributes:Object.entries(a).map(([t,r])=>HS(t,r))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function jc(e,a={}){try{let[o,t]=await Promise.all([Rt(),Z()]),r=o?.email,i=t?.tenant;if(!r||!i){Bc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let s=VS(e,a);await Yu.post(JS(),{json:s,timeout:WS,headers:{"Content-Type":"application/json","x-flow-user":r,flowtenant:i}}),Bc.debug(`OTel metric sent: ${e}`);}catch(o){Bc.warn(`Failed to send OTel metric "${e}": ${String(o)}`);}}var Uc=k("cli:init"),XS={new:{label:"new",color:R.green},unchanged:{label:"unchanged",color:R.dim},divergent:{label:"kept (differs from template)",color:R.yellow},declined:{label:"pending (declined)",color:R.yellow}};function KS(e){process.stdout.write(`
|
|
84779
84779
|
`+R.bold(` flow setup strategy
|
|
84780
84780
|
`)),process.stdout.write(R.dim(` Target: ${e}
|
|
84781
84781
|
|
|
84782
84782
|
`)),process.stdout.write(R.dim(` Files evaluated:
|
|
84783
|
-
`));for(let a of
|
|
84783
|
+
`));for(let a of ni)process.stdout.write(R.dim(` \xB7 ${a.path}
|
|
84784
84784
|
`));process.stdout.write(`
|
|
84785
|
-
`);}function
|
|
84785
|
+
`);}function $S(e,a,o,t){C(w.CLI_STRATEGY_INIT_COMPLETED,{files_new:e.new,files_unchanged:e.unchanged,files_divergent:e.divergent,files_declined:e.declined,dry_run:a,duration_ms:t,exit_code:o}).catch(r=>{Uc.warn(`Failed to emit strategy init completed event: ${String(r)}`);}),jc("flow_cli.strategy_init",{dry_run:a,files_new:e.new,exit_code:o}).catch(()=>{});}function _f(e,a){C(w.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:a}).catch(o=>{Uc.warn(`Failed to emit strategy init failed event: ${String(o)}`);}),jc("flow_cli.strategy_init_failed",{duration_ms:a}).catch(()=>{});}async function YS(e){try{return await simpleGit(e).checkIsRepo(CheckRepoActions.IN_TREE)}catch{return false}}async function ZS(){return _(" Continue anyway? [y/N] ")}async function eC(){return P(`docs/catalog/ is the skill/agent/command catalog (~2.6MB); docs/playbooks/ is the
|
|
84786
84786
|
runbook + sub-runbook docs for your installed bundles, in every language they ship
|
|
84787
84787
|
in (.md/.en.md/.es.md). This is the same content flow-playbooks-app renders \u2014 skip
|
|
84788
|
-
it if you don't run that app.`),
|
|
84789
|
-
`));for(let b of i.files){let{label:D,color:q}=
|
|
84788
|
+
it if you don't run that app.`),_(" Also scaffold docs/catalog and docs/playbooks content? [y/N] ")}async function aC(){return hs(" Which language?",[{value:"all",label:"All variants",description:"every .md/.en.md/.es.md kept as-is"},{value:"pt",label:"pt (default)",description:"the base, unsuffixed .md files only"},{value:"en",label:"en",description:".en.md only"},{value:"es",label:"es",description:".es.md only"}])}async function mn(e){Uc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`);let a=e.path??process.cwd(),o=e.isInteractive??!!process.stdin.isTTY,t=e.confirmContinueWithoutGit??ZS;if(!await YS(a)){let b=`${a} is not a git repository. Strategy docs are meant to be version-controlled \u2014 consider running "git init" first.`;if(!o)return e.json?Ne({error:b,exitCode:1}):S(`${b} Re-run interactively to confirm, or run "git init" first.`),1;if(P(b),!await t())return 1}e.json||KS(a);let r=Date.now(),i;try{i=await Jf({targetDir:a,dryRun:e.dryRun,force:e.force,assistant:e.assistant});}catch(b){throw _f(b instanceof Error?b.message:String(b),Date.now()-r),b}let s,n=e.confirmDocsContent??eC,d=e.selectDocsLang??aC,l=!!e.docsContent,c=e.docsLang??"all";if(!l&&o&&(l=await n(),l&&(c=await d())),l){let b=Qf();try{s=await Vf({targetDir:a,dryRun:e.dryRun,force:e.force,installedBundles:b,docsLang:c});}catch(D){throw _f(D instanceof Error?D.message:String(D),Date.now()-r),D}}let u=i.hasUnresolved||s?.hasUnresolved?2:0;if($S(i.counts,!!e.dryRun,u,Date.now()-r),e.json)return me({dryRun:!!e.dryRun,counts:i.counts,files:i.files,docsContent:s?{counts:s.counts,files:s.files,skippedPlaybooks:s.skippedPlaybooks}:void 0,exitCode:u}),u;let m=e.dryRun?R.dim("[dry-run] "):"";process.stdout.write(R.bold(` Result:
|
|
84789
|
+
`));for(let b of i.files){let{label:D,color:q}=XS[b.status];process.stdout.write(` ${m}${q(D.padEnd(18))} ${b.path}
|
|
84790
84790
|
`);}process.stdout.write(`
|
|
84791
|
-
`);let{new:p,unchanged:
|
|
84791
|
+
`);let{new:p,unchanged:f,divergent:g,declined:h}=i.counts;if($(`${p} new, ${f} unchanged, ${g} kept (differs from template)`+(h>0?`, ${h} pending confirmation`:"")),(g>0||h>0)&&P(`Some files differ from the Flow strategy template. Review your local changes before overwriting \u2014 run "git status"/"git diff" or your IDE's diff view. Re-run with --force to overwrite them.`),s){process.stdout.write(`
|
|
84792
84792
|
`+R.bold(` docs/catalog + docs/playbooks:
|
|
84793
|
-
`)),s.skippedPlaybooks&&P('No bundles installed (run "flow setup harness" first) \u2014 docs/playbooks/ was skipped; docs/catalog/ was still scaffolded.');let b=s.counts
|
|
84793
|
+
`)),s.skippedPlaybooks&&P('No bundles installed (run "flow setup harness" first) \u2014 docs/playbooks/ was skipped; docs/catalog/ was still scaffolded.');let b=s.counts;$(`${b.new} new, ${b.unchanged} unchanged, ${b.divergent} kept (differs from template)`+(b.declined>0?`, ${b.declined} pending confirmation`:"")),(b.divergent>0||b.declined>0)&&P("Some docs-content files were kept as-is or pending confirmation. Re-run with --force to resolve.");}return u!==0&&S("flow setup strategy finished with unresolved files \u2014 see above."),u}B();U();var dr=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var zc="repos.yaml",rC="projects";function iC(e,a,o){if(e===void 0)return [];if(!Array.isArray(e))return o.push(`"${a}:" must be a list \u2014 ignoring the whole section.`),[];let t=[];return e.forEach((r,i)=>{if(typeof r!="object"||r===null){o.push(`${a}[${i}] is not a mapping \u2014 skipped.`);return}let s=r,n=s.name!==void 0?String(s.name):"",d=s.remote!==void 0?String(s.remote):"";if(!n||!d){let l=n||`${a}[${i}]`,c=[!n&&"name",!d&&"remote"].filter(Boolean).join(" and ");o.push(`${l}: missing required field "${c}" \u2014 skipped (did you mean "remote:" instead of "url:"?)`);return}t.push({name:n,remote:d,group:s.group!==void 0?String(s.group):void 0});}),t}function Wc(e){let a=e.match(/^https?:\/\/github\.com\/([^/]+)\/([^/.]+)(\.git)?\/?$/);return a?`git@github.com:${a[1]}/${a[2]}.git`:e}function Kf(e){let a=[];return {repos:e.map(t=>{let r=Wc(t.remote);if(r===t.remote)return t;let i={...t,remote:r};return a.push({before:t,after:i}),i}),converted:a}}var sC=/^(git@[^:]+:[^/]+\/[^/]+(\.git)?|https?:\/\/[^/]+\/[^/]+\/[^/]+(\.git)?)\/?$/;function hn(e){let a=[],o=[];for(let t of e){if(!t.name.trim()){o.push({entry:t,reason:"empty name"});continue}if(!t.remote.trim()){o.push({entry:t,reason:"empty remote"});continue}if(!sC.test(t.remote.trim())){o.push({entry:t,reason:`remote does not look like a valid git URL: ${t.remote}`});continue}a.push(t);}return {valid:a,invalid:o}}function $f(e){let a=join(e,zc);if(!existsSync(a))return null;let o=parse(readFileSync(a,"utf8"));if(!o||typeof o!="object"||Array.isArray(o))return null;let t=[],r=o.workspace;r!==void 0&&(typeof r!="object"||r===null)&&t.push('"workspace:" must be a mapping \u2014 using the default (repos_dir).');let i=r&&typeof r=="object"?r:{};return o.repos_dir!==void 0&&t.push('"repos_dir" must be nested under "workspace:", not at the top level \u2014 using the default.'),(o.references!==void 0||i.refs_dir!==void 0)&&t.push('legacy "references:"/"refs_dir" key found \u2014 delete repos.yaml and re-run "flow setup workspace" to regenerate it clean.'),{workspace:{repos_dir:String(i.repos_dir??rC)},repos:iC(o.repos,"repos",t),warnings:t}}function bn(e,a){let o=join(e,zc),{warnings:t,...r}=a;writeFileSync(o,stringify(r),"utf8");}function Yf(e){let a=join(e,".gitignore"),o=zc;if(!existsSync(a)){writeFileSync(a,`${o}
|
|
84794
84794
|
`,"utf8");return}readFileSync(a,"utf8").split(`
|
|
84795
84795
|
`).some(i=>i.trim()===o)||appendFileSync(a,`${o}
|
|
84796
|
-
`,"utf8");}function
|
|
84797
|
-
|
|
84796
|
+
`,"utf8");}function Zf(e,a){let o=join(e,".gitignore"),t=`${a}/`;if(!existsSync(o)){writeFileSync(o,`${t}
|
|
84797
|
+
`,"utf8");return}let r=readFileSync(o,"utf8");r.split(`
|
|
84798
|
+
`).some(s=>s.trim()===t)||appendFileSync(o,`${r.endsWith(`
|
|
84799
|
+
`)?"":`
|
|
84800
|
+
`}${t}
|
|
84801
|
+
`,"utf8");}function eh(e,a){let o=join(e,".claudeignore"),t=existsSync(o)?readFileSync(o,"utf8"):"",r=new Set(t.split(`
|
|
84802
|
+
`).map(d=>d.trim())),i=[a.repos_dir].filter(d=>!r.has(`${d}/`));if(i.length===0)return;let s=t?"":`# Paths excluded from Claude Code context.
|
|
84798
84803
|
`,n=i.map(d=>`# ${d}/ \u2014 repos cloned via flow setup workspace, not part of this repo's own docs.
|
|
84799
84804
|
${d}/`).join(`
|
|
84800
84805
|
|
|
@@ -84802,18 +84807,21 @@ ${d}/`).join(`
|
|
|
84802
84807
|
${n}
|
|
84803
84808
|
`,"utf8"):writeFileSync(o,`${s}
|
|
84804
84809
|
${n}
|
|
84805
|
-
`,"utf8");}var
|
|
84806
|
-
${
|
|
84810
|
+
`,"utf8");}var Xf="## Off-Limits \u2014 Workspace Repos";function ah(e,a,o){if(!o)return "declined";let t=join(e,"CLAUDE.md");if(!existsSync(t))return "no-claude-md";let r=readFileSync(t,"utf8");if(r.includes(Xf))return "already-present";let i=`
|
|
84811
|
+
${Xf}
|
|
84807
84812
|
|
|
84808
|
-
\`${a.repos_dir}/\`
|
|
84813
|
+
\`${a.repos_dir}/\` contains repos cloned via \`flow setup workspace\` \u2014 not part of this repo's own documentation or code. It is excluded from Claude Code's context via \`.claudeignore\`.
|
|
84809
84814
|
|
|
84810
|
-
> Off-limits: do not read, index, link, or reference files inside
|
|
84815
|
+
> Off-limits: do not read, index, link, or reference files inside this folder in any context.
|
|
84811
84816
|
`;return appendFileSync(t,`${r.endsWith(`
|
|
84812
84817
|
`)?"":`
|
|
84813
|
-
`}${i}`,"utf8"),"appended"}var
|
|
84814
|
-
`)
|
|
84815
|
-
`)
|
|
84816
|
-
`),
|
|
84818
|
+
`}${i}`,"utf8"),"appended"}var oh="projects";function nC(e){let a=e.match(/^git@[^:]+:[^/]+\/([^/.]+)(\.git)?\/?$/);if(a)return a[1]??null;let o=e.match(/^https?:\/\/[^/]+\/[^/]+\/([^/.]+)(\.git)?\/?$/);return o?o[1]??null:null}async function th(){let e=await Jt(" Repo URL \u2014 SSH or HTTPS (ENTER to finish): ");if(!e)return null;let a=nC(e);if(!a)return process.stdout.write(` Could not parse a repo name from that URL \u2014 skipped.
|
|
84819
|
+
`),null;let o=await Jt(` Group/category for '${a}' (optional, default: general): `),t=Wc(e);return {name:a,remote:t,group:o||"general"}}async function rh(){if(!await _("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let a=await Jt(` Folder for work repos (default: ${oh}): `),o=[];for(;;){let t=await th();if(!t)break;o.push(t);}return o.length===0?null:{workspace:{repos_dir:a||oh},repos:o,warnings:[]}}async function ih(e){let{valid:a,invalid:o}=hn(e);process.stdout.write(` Current repos in repos.yaml (${e.length}):
|
|
84820
|
+
`);for(let s of e){let n=o.find(l=>l.entry===s),d=n?` \u2717 (${n.reason})`:" \u2713";process.stdout.write(` - ${s.name} (${s.remote})${d}
|
|
84821
|
+
`);}let t=a,r=false;if(o.length>0&&(await _(` Remove the ${o.length} invalid entr${o.length===1?"y":"ies"} listed above? [y/N] `)?r=true:t=e),await _(" Add more repos to repos.yaml? [y/N] "))for(;;){let s=await th();if(!s)break;t=[...t,s],r=true;}return {repos:t,changed:r}}I();var sh=k("workspace:repos"),nh=6e4;async function lC(e){try{return (await simpleGit(e).status()).current}catch{return null}}function dh(){let{HOME:e,PATH:a,USER:o,SSH_AUTH_SOCK:t}=process.env;return {HOME:e,PATH:a,USER:o,SSH_AUTH_SOCK:t,GIT_TERMINAL_PROMPT:"0"}}async function uC(e){await simpleGit(e,{timeout:{block:nh}}).env(dh()).pull(["--ff-only"]);}async function pC(e,a){await simpleGit({timeout:{block:nh}}).env(dh()).clone(e,a);}async function ch(e,a){let o=join(a,e.name),t=join(o,".git");if(existsSync(t)){let r=await lC(o);if(r==="main"||r==="master")try{return await uC(o),{name:e.name,outcome:"updated"}}catch(i){return sh.warn(`[${e.name}] pull failed (branch diverged?): ${String(i)}`),{name:e.name,outcome:"skipped"}}return {name:e.name,outcome:"skipped"}}try{return mkdirSync(a,{recursive:!0}),await pC(e.remote,o),{name:e.name,outcome:"cloned"}}catch(r){let i=r instanceof Error?r.message:String(r);return sh.error(`[${e.name}] clone failed: ${i}`),{name:e.name,outcome:"failed",error:i}}}function lh(e,a){return !existsSync(join(a,e.name,".git"))}function uh(e,a){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(o=>o.isDirectory()&&!a.has(o.name)).map(o=>o.name):[]}var fC=promisify(execFile),ph=5e3;async function mh(){try{let{stdout:e,stderr:a}=await fC("ssh",["-T","git@github.com","-o","BatchMode=yes","-o",`ConnectTimeout=${ph/1e3}`],{timeout:ph+2e3});return `${e}${a}`.includes("successfully authenticated")}catch(e){return `${e.stdout??""}${e.stderr??""}`.includes("successfully authenticated")}}function Qc(e={}){return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true,manifestWarnings:[],sshBlocked:false,...e}}async function fh(e={}){let a=e.targetDir??process.cwd(),o=e.isInteractive??!!process.stdin.isTTY,t=$f(a);if(t){if(o){let g=await ih(t.repos);g.changed?(t={...t,repos:g.repos},bn(a,t)):t={...t,repos:g.repos};}}else {if(!o)return Qc();let g=await rh();if(!g)return Qc();bn(a,g),Yf(a),t=g;}let{repos:r,converted:i}=Kf(t.repos);i.length>0&&(t={...t,repos:r},bn(a,t)),eh(a,t.workspace);let s=join(a,t.workspace.repos_dir),{valid:n,invalid:d}=hn(t.repos),l=[...t.warnings,...d.map(g=>`${g.entry.name||"(unnamed)"}: ${g.reason} \u2014 skipped`),...i.map(g=>`${g.before.name}: remote is HTTPS \u2014 converted to SSH (${g.after.remote}) and saved to repos.yaml`)];if(n.some(g=>lh(g,s))&&!await mh())return Qc({skippedNoManifest:false,manifestWarnings:l,workspaceDirs:t.workspace,sshBlocked:true});let u=[];for(let g=0;g<n.length;g++){let h=n[g];e.onRepoProgress?.({name:h.name,index:g,total:n.length,status:"start"});let b=await ch(h,s);u.push(b),e.onRepoProgress?.({name:h.name,index:g,total:n.length,status:b.outcome});}let m=new Set(n.map(g=>g.name)),p=uh(s,m),f=0;if(e.prune&&p.length>0)for(let g of p)rmSync(join(s,g),{recursive:true,force:true}),f++;return Zf(a,t.workspace.repos_dir),{repos:u,orphans:e.prune?[]:p,prunedCount:f,skippedNoManifest:false,manifestWarnings:l,workspaceDirs:t.workspace,sshBlocked:false}}I();var bC=["local","project","user"],bh=[{name:"cit-tools",description:"CI&T-branded content tools (deck-architect agent, ciandt-pptx, ciandt-clay-render, pptx-builder, refiner skills)"},{name:"commons-claude",description:"Claude Code machine-setup skills (setup-claude-defaults, setup-session-recap, setup-statusline) \u2014 not product tooling, personal environment config"}],_c=bh.map(e=>e.name);function vC(e){return e.filter(a=>!_c.includes(a))}function yC(){P(`The following ${dr.length} runbook bundles will be installed:`);for(let e of dr)process.stdout.write(` - ${e}
|
|
84822
|
+
`);}async function kC(e,a){if(a||!e)return [];let o=[];for(let{name:t,description:r}of bh)await _(` Also install ${t}? (${r}) [y/N] `)&&o.push(t);return o}async function PC(){return hs(" Install scope:",bC.map(e=>({value:e,label:qa[e].actionLabel,description:qa[e].description})))}var li=Symbol("skip");async function hh(e,a,o){let{scope:t,silent:r,isInteractive:i,force:s}=o;if(!s){let n=Zs(e);if(n){if(n.scope===t)return r||P(`${a}${e} is already installed ${$a(n)}. Use --force to reinstall.`),li;if(r||!i)return r||P(`${a}Skipping ${e} \u2014 already installed ${$a(n)}. Re-run with --force to install here too.`),li;if(!await en(e,t,n))return P(`${a}Skipped ${e}.`),li;let l=await ri(e,{force:true,scope:n.scope});if(l!==0)return P(`${a}Could not remove ${e} from ${$a(n)} \u2014 skipping rather than leaving it in an inconsistent state.`),l}}return r||P(`${a}Installing ${e}...`),sr([e],{scope:t,silent:r,force:s})}async function Xc(e={}){let a=e.isInteractive??!!process.stdin.isTTY;if(e.extraPlugins){let s=vC(e.extraPlugins);if(s.length>0){let n=`--extra-plugins: unknown bundle(s) ${s.join(", ")} \u2014 valid values are ${_c.join(", ")}`;return e.silent?me({error:n}):S(n),1}}e.silent||yC();let o=e.scope;if(!o&&!e.silent&&a)try{o=await PC();}catch(s){if(s instanceof Error&&s.message==="SIGINT")return process.stdout.write(`
|
|
84823
|
+
`),130;throw s}let t=e.force??false,r={scope:o,silent:e.silent,isInteractive:a,force:t},i=[];try{for(let n=0;n<dr.length;n++){let d=dr[n],l=`[${n+1}/${dr.length}] `,c=await hh(d,l,r);c!==li&&i.push(c);}let s=e.extraPlugins?_c.filter(n=>e.extraPlugins.includes(n)):await kC(a,e.silent);for(let n=0;n<s.length;n++){let d=s[n],l=`[extra ${n+1}/${s.length}] `,c=await hh(d,l,r);c!==li&&i.push(c);}}catch(s){if(s instanceof Error&&s.message==="SIGINT")return process.stdout.write(`
|
|
84824
|
+
`),130;throw s}return i.some(s=>s!==0)?1:0}var DC=k("cli:setup-workspace");function vh(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}function wC(){P("SSH key not configured for GitHub (or not added to your account)."),process.stdout.write(` Stopping before cloning \u2014 configure SSH and run this command again:
|
|
84817
84825
|
`),process.stdout.write(` 1. Check for an existing key: ls -la ~/.ssh/id_ed25519.pub
|
|
84818
84826
|
`),process.stdout.write(` 2. If none, generate one: ssh-keygen -t ed25519 -C "your_email@example.com"
|
|
84819
84827
|
`),process.stdout.write(` 3. Start the agent: eval "$(ssh-agent -s)"
|
|
@@ -84821,12 +84829,13 @@ ${Hf}
|
|
|
84821
84829
|
`),process.stdout.write(` 5. Copy the public key: pbcopy < ~/.ssh/id_ed25519.pub (macOS)
|
|
84822
84830
|
`),process.stdout.write(` 6. Add it on GitHub: https://github.com/settings/ssh/new
|
|
84823
84831
|
`),process.stdout.write(` 7. Test the connection: ssh -T git@github.com
|
|
84824
|
-
`)
|
|
84825
|
-
`);
|
|
84832
|
+
`);}function SC(e){let a=`[${e.index+1}/${e.total}]`;if(e.status==="start"){process.stdout.write(` ${a} ${e.name}...
|
|
84833
|
+
`);return}process.stdout.write(` ${a} ${e.name}: ${vh(e.status)}
|
|
84834
|
+
`);}function CC(e){if(e.length===0)return;let a=e.map(o=>[o.outcome==="cloned"||o.outcome==="updated"?"\u2713":o.outcome==="skipped"?"\u25CB":"\u2717",o.name,vh(o.outcome),o.error??""]);vo(["","Repo","Outcome","Detail"],a);}async function RC(e,a,o,t){if(o||!t||a.skippedNoManifest||!a.workspaceDirs)return;let{repos_dir:r}=a.workspaceDirs,i=await _(` Add an off-limits note to CLAUDE.md for '${r}/'? [y/N] `),s=ah(e,a.workspaceDirs,i);s==="appended"?P(`CLAUDE.md updated with an off-limits note for '${r}/'.`):s==="already-present"?P("CLAUDE.md already has the off-limits note \u2014 skipped."):s==="no-claude-md"&&P("No CLAUDE.md found in this repo \u2014 skipped the off-limits note.");}async function Kc(e={}){DC.debug(`Running flow setup workspace: ${JSON.stringify(e)}`);let a=e.isInteractive??!!process.stdin.isTTY,o=await fh({targetDir:e.path,prune:e.prune,isInteractive:a,onRepoProgress:e.json?void 0:SC});if(e.json)return me({repos:o.repos,orphans:o.orphans,prunedCount:o.prunedCount,skippedNoManifest:o.skippedNoManifest,manifestWarnings:o.manifestWarnings,sshBlocked:o.sshBlocked}),o.sshBlocked||o.repos.some(n=>n.outcome==="failed")?1:0;for(let n of o.manifestWarnings)P(`repos.yaml: ${n}`);if(o.sshBlocked)return wC(),1;if(o.skippedNoManifest)return P("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;CC(o.repos);let t=o.repos.filter(n=>n.outcome==="cloned").length,r=o.repos.filter(n=>n.outcome==="updated").length,i=o.repos.filter(n=>n.outcome==="skipped").length,s=o.repos.filter(n=>n.outcome==="failed").length;return $(`${t} cloned, ${r} updated, ${i} skipped`+(s>0?`, ${s} failed`:"")+(o.prunedCount>0?`, ${o.prunedCount} pruned`:"")),o.orphans.length>0&&P(`Orphan director${o.orphans.length===1?"y":"ies"} not in repos.yaml: ${o.orphans.join(", ")}. Re-run with --prune to remove.`),await RC(e.path??process.cwd(),o,e.json,a),s>0?1:0}var AC=[{key:"strategy",label:"strategy (scaffold the numbered documentation structure)",run:e=>mn({path:e})},{key:"harness",label:"harness (install the fixed set of Flow runbook bundles)",run:()=>Xc({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>Kc({path:e})}];async function xC(e){return _(` Run ${e}? [y/N] `)}async function yh(e={}){let a=e.isInteractive??!!process.stdin.isTTY,o=e.confirmStep??xC,t=!!e.yes||!a;!e.yes&&!a&&P("No interactive terminal and --yes not set \u2014 running all steps without prompting.");let r=[];for(let i of AC){if(!(t||await o(i.label))){P(` \u2192 ${i.key} skipped.`);continue}r.push(await i.run(e.path));}return r.some(i=>i!==0)?1:0}function kh(e){let a=new Command;a.enablePositionalOptions(),a.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${ve}`,"-V, --version","Display the CLI version").addHelpText("after",`
|
|
84826
84835
|
Without arguments, opens the interactive interface (TUI).
|
|
84827
84836
|
Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let o=new Command("setup").description("Configure the CLI and provision Flow structure in the current repository");o.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
|
|
84828
84837
|
Examples:
|
|
84829
|
-
$ flow setup init`).action(async()=>{let c=await
|
|
84838
|
+
$ flow setup init`).action(async()=>{let c=await Sc();G(c);}),o.command("strategy").description("Scaffold the numbered strategy documentation structure (0-current-state, 1-strategy, 2-plan, 3-delivery, 4-learn)").option("--dry-run","Preview changes without writing files or prompting",false).option("--json","Output machine-readable JSON",false).option("--force","Skip confirmation before overwriting an up-to-date file, and overwrite customized files too",false).option("--path <dir>","Target repository root (defaults to the current directory)").addOption(new Option("--assistant <name>","Also scaffold a config file for this coding assistant (e.g. CLAUDE.md). Interactive: asks for confirmation before creating it. Non-interactive: never creates it, even with this flag set.").choices(["claude-code"])).option("--docs-content","Also scaffold docs/catalog (skill/agent/command catalog) and docs/playbooks (runbook docs for your installed bundles). Interactive: asks for confirmation. Non-interactive: never scaffolds it, even with this flag set.",false).addOption(new Option("--docs-lang <lang>","With --docs-content: which language variant to write (default: all \u2014 every .md/.en.md/.es.md kept). Interactive: asked right after you confirm docs-content, no flag needed. A doc missing the chosen language falls back to whatever variant it does have.").choices(["all","pt","en","es"])).addHelpText("after",`
|
|
84830
84839
|
Examples:
|
|
84831
84840
|
$ flow setup strategy
|
|
84832
84841
|
$ flow setup strategy --dry-run
|
|
@@ -84834,7 +84843,7 @@ Examples:
|
|
|
84834
84843
|
$ flow setup strategy --assistant claude-code
|
|
84835
84844
|
$ flow setup strategy --docs-content
|
|
84836
84845
|
$ flow setup strategy --docs-content --docs-lang en
|
|
84837
|
-
$ flow setup strategy --json --path ./my-repo`).action(async c=>{let u=await
|
|
84846
|
+
$ flow setup strategy --json --path ./my-repo`).action(async c=>{let u=await mn({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path,assistant:c.assistant,docsContent:c.docsContent,docsLang:c.docsLang});G(u);}),o.command("harness").description("Install the fixed set of Flow runbook bundles (tech, security, product, design, ops, common, quality)").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--silent","Output in JSON only",false).option("--force","Reinstall bundles already installed elsewhere without asking for confirmation",false).option("--extra-plugins <names>","Also install these opt-in auxiliary bundles (comma-separated: cit-tools, commons-claude). The only way to install them non-interactively or with --silent \u2014 an interactive run without this flag still asks per bundle, and passing it skips that prompt entirely.").addHelpText("after",`
|
|
84838
84847
|
Examples:
|
|
84839
84848
|
$ flow setup harness
|
|
84840
84849
|
$ flow setup harness --scope project
|
|
@@ -84850,11 +84859,11 @@ here too without asking, leaving the bundle enabled in both places.
|
|
|
84850
84859
|
After the 7 bundles, an interactive run also asks once per opt-in extra
|
|
84851
84860
|
(cit-tools, commons-claude) unless --extra-plugins was passed, which installs
|
|
84852
84861
|
exactly the named bundles with no prompt \u2014 required in --silent or
|
|
84853
|
-
non-interactive runs, since no prompt happens there either way.`).action(async c=>{let u=await
|
|
84862
|
+
non-interactive runs, since no prompt happens there either way.`).action(async c=>{let u=await Xc({scope:c.scope,silent:c.silent,force:c.force,extraPlugins:c.extraPlugins?.split(",").map(m=>m.trim()).filter(Boolean)});G(u);}),o.command("workspace").description("Clone / update repos declared in repos.yaml (wizard on first run)").option("--path <dir>","Target repository root (defaults to the current directory)").option("--prune","Remove local directories no longer declared in repos.yaml",false).option("--json","Output machine-readable JSON",false).addHelpText("after",`
|
|
84854
84863
|
Examples:
|
|
84855
84864
|
$ flow setup workspace
|
|
84856
84865
|
$ flow setup workspace --prune
|
|
84857
|
-
$ flow setup workspace --json --path ./my-workspace`).action(async c=>{let u=await
|
|
84866
|
+
$ flow setup workspace --json --path ./my-workspace`).action(async c=>{let u=await Kc({path:c.path,prune:c.prune,json:c.json});G(u);}),o.command("framework-strategy").description("Orchestrate strategy \u2192 harness \u2192 workspace, asking [y/N] before each step").option("--path <dir>","Target repository root (defaults to the current directory)").option("--yes","Skip every confirmation and run all 3 steps back to back",false).addHelpText("after",`
|
|
84858
84867
|
Examples:
|
|
84859
84868
|
$ flow setup framework-strategy
|
|
84860
84869
|
$ flow setup framework-strategy --yes
|
|
@@ -84863,13 +84872,13 @@ Examples:
|
|
|
84863
84872
|
Without --yes and with an interactive terminal, asks [y/N] before each of the
|
|
84864
84873
|
3 steps (strategy, harness, workspace) \u2014 declining one skips just that step
|
|
84865
84874
|
and moves to the next. Without an interactive terminal, runs all 3 steps
|
|
84866
|
-
without prompting even if --yes wasn't passed (there is no terminal to ask in).`).action(async c=>{let u=await
|
|
84875
|
+
without prompting even if --yes wasn't passed (there is no terminal to ask in).`).action(async c=>{let u=await yh({path:c.path,yes:c.yes});G(u);}),a.addCommand(o);let t=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");t.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).option("--source <name>","Named content source to list from (e.g. flow-harness); defaults to the standard catalog").addHelpText("after",`
|
|
84867
84876
|
Examples:
|
|
84868
84877
|
$ flow plugin list
|
|
84869
84878
|
$ flow plugin list --available
|
|
84870
84879
|
$ flow plugin list --outdated
|
|
84871
84880
|
$ flow plugin list --json
|
|
84872
|
-
$ flow plugin list --available --source flow-harness`).action(async c=>{let u=await
|
|
84881
|
+
$ flow plugin list --available --source flow-harness`).action(async c=>{let u=await Xg(c);G(u);}),t.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").option("--source <name>","Named content source to install from (e.g. flow-harness); defaults to the standard catalog").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
84873
84882
|
Examples:
|
|
84874
84883
|
$ flow plugin install flow-adr-writer
|
|
84875
84884
|
$ flow plugin install flow-adr-writer --scope project
|
|
@@ -84878,11 +84887,16 @@ Examples:
|
|
|
84878
84887
|
$ flow plugin install flow-adr-writer --silent
|
|
84879
84888
|
$ flow plugin install superpowers@claude-plugins-official
|
|
84880
84889
|
$ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code
|
|
84881
|
-
$ flow plugin install runbook-design --source flow-harness
|
|
84890
|
+
$ flow plugin install runbook-design --source flow-harness
|
|
84891
|
+
|
|
84892
|
+
A plugin already installed elsewhere (any scope, any project) prompts to
|
|
84893
|
+
move it here instead (uninstall there, install here) unless --force is
|
|
84894
|
+
passed, which installs here too without asking, leaving it enabled in
|
|
84895
|
+
both places.`).action(async(c,u)=>{let m=c.filter(f=>f.trim());if(m.length===0){S("No valid plugin names provided"),G(1);return}Ve("cli",{verbose:u.verbose,silent:u.silent});let p=await sr(m,u);G(p);}),t.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",`
|
|
84882
84896
|
Examples:
|
|
84883
84897
|
$ flow plugin uninstall flow-adr-writer
|
|
84884
84898
|
$ flow plugin uninstall flow-adr-writer --scope project
|
|
84885
|
-
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,u)=>{let m=await
|
|
84899
|
+
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,u)=>{let m=await ri(c,u);G(m);}),t.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",`
|
|
84886
84900
|
Examples:
|
|
84887
84901
|
$ flow plugin update flow-adr-writer
|
|
84888
84902
|
$ flow plugin update flow-adr-writer --scope project
|
|
@@ -84891,79 +84905,79 @@ Examples:
|
|
|
84891
84905
|
$ flow plugin update flow-adr-writer --verbose
|
|
84892
84906
|
$ flow plugin update flow-adr-writer --silent
|
|
84893
84907
|
$ flow plugin update
|
|
84894
|
-
$ flow plugin update --dry-run`).action(async(c,u)=>{Ve("cli",{verbose:u.verbose,silent:u.silent});let m=await
|
|
84908
|
+
$ flow plugin update --dry-run`).action(async(c,u)=>{Ve("cli",{verbose:u.verbose,silent:u.silent});let m=await Zg(c??null,u);G(m);}),t.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",`
|
|
84895
84909
|
Examples:
|
|
84896
84910
|
$ flow plugin enable flow-adr-writer
|
|
84897
|
-
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,u)=>{Ve("cli");let m=await
|
|
84911
|
+
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,u)=>{Ve("cli");let m=await Kg(c,u);G(m);}),t.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",`
|
|
84898
84912
|
Examples:
|
|
84899
84913
|
$ flow plugin disable flow-adr-writer
|
|
84900
|
-
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,u)=>{Ve("cli");let m=await
|
|
84914
|
+
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,u)=>{Ve("cli");let m=await $g(c,u);G(m);}),t.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
|
|
84901
84915
|
Examples:
|
|
84902
84916
|
$ flow plugin export
|
|
84903
|
-
$ flow plugin export --output my-plugins.json`).action(async c=>{let u=await
|
|
84917
|
+
$ flow plugin export --output my-plugins.json`).action(async c=>{let u=await Lf(c);G(u);}),t.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",`
|
|
84904
84918
|
Examples:
|
|
84905
84919
|
$ flow plugin import flow-plugins.json
|
|
84906
84920
|
$ flow plugin import flow-plugins.json --scope user
|
|
84907
84921
|
$ flow plugin import flow-plugins.json --force
|
|
84908
84922
|
$ flow plugin import flow-plugins.json --dry-run
|
|
84909
|
-
$ flow plugin import flow-plugins.json --diff`).action(async(c,u)=>{let m=await
|
|
84923
|
+
$ flow plugin import flow-plugins.json --diff`).action(async(c,u)=>{let m=await Ff(c,u);G(m);});let r=new Command("marketplace").description("Manage plugin marketplaces");r.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",`
|
|
84910
84924
|
Examples:
|
|
84911
84925
|
$ flow plugin marketplace add anthropics/claude-code
|
|
84912
84926
|
$ flow plugin marketplace add https://github.com/owner/repo
|
|
84913
84927
|
$ flow plugin marketplace add anthropics/claude-code --force
|
|
84914
|
-
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,u)=>{Ve("cli",{verbose:u.verbose,silent:u.silent});let m=await
|
|
84928
|
+
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,u)=>{Ve("cli",{verbose:u.verbose,silent:u.silent});let m=await of(c,u);G(m);}),t.addCommand(r),a.addCommand(t);let i=new Command("mcp").description("Manage MCP servers from the Findr catalog");i.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",`
|
|
84915
84929
|
Examples:
|
|
84916
84930
|
$ flow mcp add notion --transport http https://mcp.notion.com/mcp
|
|
84917
84931
|
$ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
|
|
84918
84932
|
$ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
|
|
84919
|
-
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,u,m)=>{Ve("cli",{verbose:m.verbose,silent:m.silent});let p=await
|
|
84933
|
+
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,u,m)=>{Ve("cli",{verbose:m.verbose,silent:m.silent});let p=await Pm(c,u,m);G(p);}),i.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",`
|
|
84920
84934
|
Examples:
|
|
84921
84935
|
$ flow mcp remove notion
|
|
84922
84936
|
$ flow mcp remove notion --scope project
|
|
84923
|
-
$ flow mcp remove playwright-mcp --force`).action(async(c,u)=>{Ve("cli",{verbose:u.verbose,silent:u.silent});let m=await
|
|
84937
|
+
$ flow mcp remove playwright-mcp --force`).action(async(c,u)=>{Ve("cli",{verbose:u.verbose,silent:u.silent});let m=await Dm(c,u);G(m);}),a.addCommand(i);let s=new Command("auth").description("Manage authentication credentials");s.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",`
|
|
84924
84938
|
Examples:
|
|
84925
84939
|
$ flow auth login
|
|
84926
84940
|
$ flow auth login --jwt <token>
|
|
84927
84941
|
$ flow auth login --jwt <token> --starter-kit dev
|
|
84928
84942
|
$ flow auth login --jwt <token> --custom-email name@example.com
|
|
84929
|
-
$ flow auth login --verbose`).action(async c=>{Ve("cli",{verbose:c.verbose});let u=await
|
|
84943
|
+
$ flow auth login --verbose`).action(async c=>{Ve("cli",{verbose:c.verbose});let u=await Sc(c);G(u);}),s.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
|
|
84930
84944
|
Examples:
|
|
84931
84945
|
$ flow auth logout
|
|
84932
|
-
$ flow auth logout --force`).action(async c=>{let u=await
|
|
84946
|
+
$ flow auth logout --force`).action(async c=>{let u=await Jg(c.force);G(u);}),s.command("status").description("Display the current authentication status").addHelpText("after",`
|
|
84933
84947
|
Examples:
|
|
84934
|
-
$ flow auth status`).action(async()=>{let c=await
|
|
84948
|
+
$ flow auth status`).action(async()=>{let c=await Hg();G(c);}),a.addCommand(s);let n=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");n.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",`
|
|
84935
84949
|
Examples:
|
|
84936
84950
|
$ flow skills add vercel-labs/agent-skills
|
|
84937
84951
|
$ flow skills add owner/repo -g
|
|
84938
84952
|
$ flow skills add owner/repo --skill pr-review commit
|
|
84939
84953
|
$ flow skills add ./local/skills -y
|
|
84940
|
-
$ flow skills add owner/repo --list`).action(async(c,u)=>{let m=await
|
|
84954
|
+
$ flow skills add owner/repo --list`).action(async(c,u)=>{let m=await xf(c,u);G(m);}),n.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
|
|
84941
84955
|
Examples:
|
|
84942
84956
|
$ flow skills list
|
|
84943
84957
|
$ flow skills list -g
|
|
84944
|
-
$ flow skills list --json`).action(async c=>{let u=await
|
|
84958
|
+
$ flow skills list --json`).action(async c=>{let u=await If(c);G(u);}),n.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",`
|
|
84945
84959
|
Examples:
|
|
84946
84960
|
$ flow skills remove pr-review
|
|
84947
|
-
$ flow skills remove pr-review -g --force`).action(async(c,u)=>{let m=await
|
|
84961
|
+
$ flow skills remove pr-review -g --force`).action(async(c,u)=>{let m=await Tf(c,u);G(m);}),a.addCommand(n);let d=new Command("bundle").description("Manage Flow bundles");d.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",`
|
|
84948
84962
|
Examples:
|
|
84949
84963
|
$ flow bundle install "My React Kit"
|
|
84950
84964
|
$ flow bundle install "Squad Setup Bundle"
|
|
84951
|
-
$ flow bundle install "My React Kit" --verbose`).action(async(c,u)=>{Ve("cli",{verbose:u.verbose});let m=await
|
|
84965
|
+
$ flow bundle install "My React Kit" --verbose`).action(async(c,u)=>{Ve("cli",{verbose:u.verbose});let m=await ef(c);G(m);}),a.addCommand(d),a.command("health").description("Check the CLI configuration and connectivity").option("--fix","Retroactively set autoUpdate: true on already-registered Flow-curated marketplaces (FLWP-71702)").addHelpText("after",`
|
|
84952
84966
|
Examples:
|
|
84953
84967
|
$ flow health
|
|
84954
|
-
$ flow health --fix`).action(async c=>{let u=await
|
|
84968
|
+
$ flow health --fix`).action(async c=>{let u=await tf(c);G(u);}),a.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
|
|
84955
84969
|
Examples:
|
|
84956
84970
|
$ flow usage
|
|
84957
|
-
$ flow usage --json`).action(async c=>{let u=await
|
|
84971
|
+
$ flow usage --json`).action(async c=>{let u=await lf(c);G(u);});let l=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");l.action(async()=>{let c=await Ic();G(c);}),l.command("list").description("List available and installed modules").addHelpText("after",`
|
|
84958
84972
|
Examples:
|
|
84959
|
-
$ flow modules list`).action(async()=>{let c=await
|
|
84973
|
+
$ flow modules list`).action(async()=>{let c=await Ic();G(c);}),l.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
|
|
84960
84974
|
Examples:
|
|
84961
84975
|
$ flow modules install metrics
|
|
84962
|
-
$ flow modules install dashboard`).action(async c=>{let u=await
|
|
84976
|
+
$ flow modules install dashboard`).action(async c=>{let u=await Uf(c);G(u);}),l.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
|
|
84963
84977
|
Examples:
|
|
84964
84978
|
$ flow modules update
|
|
84965
|
-
$ flow modules update metrics`).action(async c=>{let u=await
|
|
84979
|
+
$ flow modules update metrics`).action(async c=>{let u=await zf(c??null);G(u);}),a.addCommand(l);for(let c of de)a.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async u=>{await Gf(c.alias,u);});return a.hook("preAction",()=>{Js();}),a}I();function TC(){return ne__default.join(Ce__default.homedir(),".claude","settings.json")}function Dh(){let e=TC();try{if(!ie__default.existsSync(e))return !0;let o=JSON.parse(ie__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return o===!1?!1:o==="modules-only"?"modules-only":!0}catch{return true}}I();var NC=k("updateChecker"),GC=promisify(execFile),BC=1440*60*1e3,wh=3e4;function jC(){let e=process.env.FLOW_HOME??ne__default.join(Ce__default.homedir(),".flow");return ne__default.join(e,"update.lock")}async function Sh(e){try{let{stdout:a}=await GC(eo(),["view",e,"version"],{timeout:wh,shell:process.platform==="win32"});return String(a).trim()||null}catch{return null}}async function UC(e){let a=new AbortController,o=setTimeout(()=>a.abort(),wh);try{let t=await fetch(`https://api.github.com/repos/${e}/releases/latest`,{signal:a.signal});return t.ok?(await t.json()).tag_name?.replace(/^v/,"")??null:null}catch{return null}finally{clearTimeout(o);}}async function zC(e){return e.versionCheck.type==="npm-registry"?Sh(e.versionCheck.package):UC(e.versionCheck.repo)}async function WC(){let e=await Sh("@ciandt-flow/cli");return e&&ze(ve,e)?(Ks({currentVersion:ve,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function JC(){let e=tt().filter(a=>a.installMethod!==null);await Promise.all(e.map(async a=>{let o=de.find(s=>s.alias===a.alias);if(!o||o.hasOwnUpdateCheck)return;let t=Date.now(),r=a.lastChecked?new Date(a.lastChecked).getTime():0;if(t-r<BC)return;let i=await zC(o);try{await ka({...a,lastChecked:new Date().toISOString()});}catch(s){NC.warn(`Failed to update lastChecked for ${a.alias}: ${String(s)}`);}i&&a.installedVersion&&ze(a.installedVersion,i)&&Xi(o,"background").catch(()=>{});}));}async function Yc(){let e=Dh();if(e===false)return;let a=jC();ie__default.mkdirSync(ne__default.dirname(a),{recursive:true});let o=null;try{o=await $b.lock(a,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let t=await WC().catch(()=>null);t&&process.stdout.write(`
|
|
84966
84980
|
\u26A0 @ciandt-flow/cli v${t} installing in background.
|
|
84967
84981
|
Restart flow to apply the update.
|
|
84968
84982
|
|
|
84969
|
-
`);}await
|
|
84983
|
+
`);}await JC().catch(()=>{});}finally{await o().catch(()=>{});}}var VC=k("cli"),Zc=kh(async()=>{Ve("tui"),ql("tui"),Ll(),process.on("SIGINT",()=>{let{activeTab:a,screen:o}=y.getState();br("sigint",a,o).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:a,screen:o}=y.getState();br("sigterm",a,o).finally(()=>process.exit(143));}),await Yc().catch(()=>{}),await op().catch(a=>{VC.error(`Failed to init catalog registry: ${String(a)}`);}),await qg();let{waitUntilExit:e}=render(jsx(Lg,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});Zc.hook("preAction",async(e,a)=>{a!==Zc&&await Yc().catch(()=>{});});Zc.parse();
|