@ciandt-flow/cli 1.0.6 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +187 -7
- package/dist/index.js +130 -76
- package/package.json +19 -17
package/README.md
CHANGED
|
@@ -115,28 +115,89 @@ flow plugin install <name...> [options]
|
|
|
115
115
|
| `--force` | Reinstall even if already installed |
|
|
116
116
|
| `--verbose` | Display each installation step |
|
|
117
117
|
| `--silent` | Output as JSON only |
|
|
118
|
+
| `--marketplace-source <source>` | GitHub source (owner/repo) for marketplace auto-add when installing external plugins |
|
|
119
|
+
| `--scope <scope>` | Scope to install into: `user`, `project`, or `local` |
|
|
118
120
|
|
|
119
121
|
```bash
|
|
120
122
|
flow plugin install flow-adr-writer
|
|
123
|
+
flow plugin install flow-adr-writer --scope project
|
|
121
124
|
flow plugin install flow-adr-writer flow-prd-writer
|
|
122
125
|
flow plugin install flow-adr-writer --force
|
|
126
|
+
flow plugin install superpowers@claude-plugins-official
|
|
127
|
+
flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code
|
|
123
128
|
```
|
|
124
129
|
|
|
125
|
-
#### `plugin uninstall <
|
|
130
|
+
#### `plugin uninstall <name>`
|
|
126
131
|
|
|
127
|
-
Uninstall a plugin
|
|
132
|
+
Uninstall a plugin.
|
|
128
133
|
|
|
129
134
|
```bash
|
|
130
|
-
flow plugin uninstall <
|
|
135
|
+
flow plugin uninstall <name> [options]
|
|
131
136
|
```
|
|
132
137
|
|
|
133
|
-
|
|
138
|
+
| Option | Description |
|
|
139
|
+
|---|---|
|
|
140
|
+
| `--force` | Skip interactive confirmation |
|
|
141
|
+
| `--scope <scope>` | Scope to uninstall from: `user`, `project`, or `local` |
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
flow plugin uninstall flow-adr-writer
|
|
145
|
+
flow plugin uninstall flow-adr-writer --scope project
|
|
146
|
+
flow plugin uninstall startup-pack-ai --force
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
#### `plugin enable <name>`
|
|
150
|
+
|
|
151
|
+
Enable an installed plugin.
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
flow plugin enable <name> [options]
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
| Option | Description |
|
|
158
|
+
|---|---|
|
|
159
|
+
| `--scope <scope>` | Scope to enable in: `user`, `project`, or `local` |
|
|
134
160
|
|
|
135
|
-
|
|
161
|
+
```bash
|
|
162
|
+
flow plugin enable flow-adr-writer
|
|
163
|
+
flow plugin enable flow-adr-writer --scope project
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
#### `plugin disable <name>`
|
|
167
|
+
|
|
168
|
+
Disable an installed plugin.
|
|
136
169
|
|
|
137
170
|
```bash
|
|
138
|
-
flow plugin
|
|
139
|
-
|
|
171
|
+
flow plugin disable <name> [options]
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
| Option | Description |
|
|
175
|
+
|---|---|
|
|
176
|
+
| `--scope <scope>` | Scope to disable in: `user`, `project`, or `local` |
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
flow plugin disable flow-adr-writer
|
|
180
|
+
flow plugin disable flow-adr-writer --scope project
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
#### `plugin marketplace add <source>`
|
|
184
|
+
|
|
185
|
+
Register a plugin marketplace in Claude Code.
|
|
186
|
+
|
|
187
|
+
```bash
|
|
188
|
+
flow plugin marketplace add <source> [options]
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
| Option | Description |
|
|
192
|
+
|---|---|
|
|
193
|
+
| `--force` | Skip confirmation prompt |
|
|
194
|
+
| `--verbose` | Display command output |
|
|
195
|
+
| `--silent` | Output as JSON only |
|
|
196
|
+
|
|
197
|
+
```bash
|
|
198
|
+
flow plugin marketplace add anthropics/claude-code
|
|
199
|
+
flow plugin marketplace add https://github.com/owner/repo
|
|
200
|
+
flow plugin marketplace add anthropics/claude-code --force
|
|
140
201
|
```
|
|
141
202
|
|
|
142
203
|
#### `plugin update [name]`
|
|
@@ -153,15 +214,134 @@ flow plugin update [name] [options]
|
|
|
153
214
|
| `--dry-run` | Preview what would be updated without making changes |
|
|
154
215
|
| `--verbose` | Display each update step |
|
|
155
216
|
| `--silent` | Output as JSON only |
|
|
217
|
+
| `--scope <scope>` | Scope to update in: `user`, `project`, or `local` |
|
|
156
218
|
|
|
157
219
|
```bash
|
|
158
220
|
flow plugin update flow-adr-writer
|
|
221
|
+
flow plugin update flow-adr-writer --scope project
|
|
159
222
|
flow plugin update # update all
|
|
160
223
|
flow plugin update --dry-run # preview only
|
|
161
224
|
```
|
|
162
225
|
|
|
163
226
|
---
|
|
164
227
|
|
|
228
|
+
### `mcp`
|
|
229
|
+
|
|
230
|
+
MCP server management commands.
|
|
231
|
+
|
|
232
|
+
#### `mcp add <name> [args...]`
|
|
233
|
+
|
|
234
|
+
Install an MCP server into Claude Code.
|
|
235
|
+
|
|
236
|
+
```bash
|
|
237
|
+
flow mcp add <name> [args...] --transport <http|stdio> [options]
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
| Option | Description |
|
|
241
|
+
|---|---|
|
|
242
|
+
| `--transport <type>` | Transport type: `http` or `stdio` (required) |
|
|
243
|
+
| `--scope <scope>` | Scope to install into: `user`, `project`, or `local` |
|
|
244
|
+
| `--force` | Skip confirmation prompt |
|
|
245
|
+
| `--verbose` | Display command output |
|
|
246
|
+
| `--silent` | Output as JSON only |
|
|
247
|
+
|
|
248
|
+
```bash
|
|
249
|
+
flow mcp add notion --transport http https://mcp.notion.com/mcp
|
|
250
|
+
flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
|
|
251
|
+
flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
|
|
252
|
+
flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
#### `mcp remove <name>`
|
|
256
|
+
|
|
257
|
+
Remove an MCP server from Claude Code.
|
|
258
|
+
|
|
259
|
+
```bash
|
|
260
|
+
flow mcp remove <name> [options]
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
| Option | Description |
|
|
264
|
+
|---|---|
|
|
265
|
+
| `--scope <scope>` | Scope to remove from: `user`, `project`, or `local` |
|
|
266
|
+
| `--force` | Skip confirmation prompt |
|
|
267
|
+
| `--verbose` | Display command output |
|
|
268
|
+
| `--silent` | Output as JSON only |
|
|
269
|
+
|
|
270
|
+
```bash
|
|
271
|
+
flow mcp remove notion
|
|
272
|
+
flow mcp remove notion --scope project
|
|
273
|
+
flow mcp remove playwright-mcp --force
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
### `skills`
|
|
279
|
+
|
|
280
|
+
Manage skills for Claude Code from GitHub repositories or local paths.
|
|
281
|
+
|
|
282
|
+
#### `skills add <source>`
|
|
283
|
+
|
|
284
|
+
Install skills from a GitHub repo or local path into Claude Code.
|
|
285
|
+
|
|
286
|
+
```bash
|
|
287
|
+
flow skills add <source> [options]
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
| Option | Description |
|
|
291
|
+
|---|---|
|
|
292
|
+
| `-g, --global` | Install globally (`~/.claude/skills/`) |
|
|
293
|
+
| `-s, --skill <names...>` | Install only specific skills by name |
|
|
294
|
+
| `-y, --yes` | Skip confirmation prompts |
|
|
295
|
+
| `--list` | List available skills without installing |
|
|
296
|
+
|
|
297
|
+
```bash
|
|
298
|
+
flow skills add vercel-labs/agent-skills
|
|
299
|
+
flow skills add owner/repo -g
|
|
300
|
+
flow skills add owner/repo -s my-skill
|
|
301
|
+
flow skills add owner/repo --list
|
|
302
|
+
flow skills add ./local/path
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
#### `skills list`
|
|
306
|
+
|
|
307
|
+
List installed skills.
|
|
308
|
+
|
|
309
|
+
```bash
|
|
310
|
+
flow skills list [options]
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
| Option | Description |
|
|
314
|
+
|---|---|
|
|
315
|
+
| `-g, --global` | List globally installed skills |
|
|
316
|
+
| `--json` | Output as JSON |
|
|
317
|
+
|
|
318
|
+
```bash
|
|
319
|
+
flow skills list
|
|
320
|
+
flow skills list --global
|
|
321
|
+
flow skills list --json
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
#### `skills remove [name]`
|
|
325
|
+
|
|
326
|
+
Remove an installed skill.
|
|
327
|
+
|
|
328
|
+
```bash
|
|
329
|
+
flow skills remove [name] [options]
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
| Option | Description |
|
|
333
|
+
|---|---|
|
|
334
|
+
| `-g, --global` | Remove from global scope |
|
|
335
|
+
| `-f, --force` | Skip confirmation prompt |
|
|
336
|
+
|
|
337
|
+
```bash
|
|
338
|
+
flow skills remove my-skill
|
|
339
|
+
flow skills remove my-skill --force
|
|
340
|
+
flow skills remove --global my-skill
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
---
|
|
344
|
+
|
|
165
345
|
### `health`
|
|
166
346
|
|
|
167
347
|
Run diagnostic checks.
|
package/dist/index.js
CHANGED
|
@@ -1,123 +1,177 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Box,Text,render,useWindowSize,useApp,useInput}from'ink';import
|
|
3
|
-
`);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let n=String(t.timestamp.getHours()).padStart(2,"0"),r=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${n}:${r}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var
|
|
4
|
-
`;try{
|
|
5
|
-
`);}};var
|
|
6
|
-
`)[0]:"unknown error";return
|
|
7
|
-
`)[0]:"unknown error",
|
|
2
|
+
import {Box,Text,render,useWindowSize,useApp,useInput}from'ink';import mc,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import $l,{HTTPError}from'ky';import*as mt from'crypto';import {randomUUID}from'crypto';import*as G from'fs';import G__default,{readFileSync,existsSync,realpathSync}from'fs';import*as N from'path';import N__default,{join,relative,resolve,normalize,sep,dirname,isAbsolute,basename}from'path';import*as ge from'os';import ge__default,{homedir,tmpdir}from'os';import {execFile,exec,spawn}from'child_process';import {promisify}from'util';import*as Qr from'readline';import {createInterface}from'readline';import dn from'keytar';import Ir from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import C from'chalk';import oc from'ink-big-text';import Ac from'ink-spinner';import*as Se from'fs/promises';import {stat,rm,readdir,readFile,mkdtemp,mkdir,writeFile,cp as cp$1}from'fs/promises';import Nc from'extract-zip';import Fc from'proper-lockfile';import Zr from'semver';import {execa}from'execa';import vo from'yocto-spinner';import {Command,Option}from'commander';import {simpleGit}from'simple-git';import {parse}from'yaml';var Ao="FLOW",_="flow-skills",pr="flow-cli",Ct="internal",on="external",dt={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},plugin:{label:"Plugin",color:"magenta"}},$o={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},dr=new Set(["internal","external"]),At={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)"}},Re=5,We=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var Lo=new Set(["skill","mcp","plugin"]),f=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,pendingExit:false,catalogFilters:{types:new Set(Lo),origins:new Set(dr)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,n)=>e({notification:{message:t,type:n}}),clearNotification:()=>e({notification:null}),setLoading:(t,n="")=>e({loading:t,loadingMessage:t?n:""}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(n=>{let{types:r}=n.catalogFilters;return r.size===1&&r.has(t)?{}:{catalogFilters:{...n.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(Lo)},selectedIndex:0})),toggleOriginFilter:t=>e(n=>{let{origins:r}=n.catalogFilters;return r.size===1&&r.has(t)?{}:{catalogFilters:{...n.catalogFilters,origins:new Set([t])},selectedIndex:0}}),selectAllOrigins:()=>e(t=>({catalogFilters:{...t.catalogFilters,origins:new Set(dr)},selectedIndex:0}))}));var sn="aes-256-gcm",ol=16,Ro=16,$t=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let n=mt.randomBytes(ol),r=mt.createCipheriv(sn,this.key,n,{authTagLength:Ro}),o=Buffer.concat([r.update(t,"utf8"),r.final()]),i=r.getAuthTag();return {iv:n.toString("hex"),authTag:i.toString("hex"),ciphertext:o.toString("hex"),algorithm:sn}}decrypt(t){if(t.algorithm!==sn)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let n=mt.createDecipheriv(sn,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Ro});return n.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([n.update(Buffer.from(t.ciphertext,"hex")),n.final()]).toString("utf8")}};var il=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,sl=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,al=/[A-Za-z0-9+/]{40,}={0,2}/g;function mr(e){return e.replace(il,"Bearer ***").replace(sl,"***").replace(al,"***")}var Lt=class{context;constructor(t){this.context=t;}write(t){let n=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(n+`
|
|
3
|
+
`);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let n=String(t.timestamp.getHours()).padStart(2,"0"),r=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${n}:${r}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var Rt=".claude",Mo=".flow";function _o(e,t){return N.join(ge.homedir(),Rt,"plugins","cache",_,e,t)}function fr(e){return N.join(ge.homedir(),Rt,"plugins","marketplaces",_,"plugins","native",e)}function an(){return N.join(ge.homedir(),Rt,"plugins","marketplaces",_,".claude-plugin","marketplace.json")}function Oo(){return N.join(ge.homedir(),Rt,"plugins","known_marketplaces.json")}function Do(){return N.join(ge.homedir(),Rt,"plugins","marketplaces",_)}function Bo(){return N.join(ge.homedir(),Mo,"cache","install.lock")}function No(){return N.join(ge.homedir(),Mo,"logs","flowsetup.log")}function Mt(e){let t=e==="global"?ge.homedir():process.cwd();return N.join(t,".claude","skills")}function gr(e){let t=e==="global"?ge.homedir():process.cwd();return N.join(t,".claude","skills-lock.json")}var ll=5*1024*1024,cl=3,ln=class{filePath;constructor(){this.filePath=No(),this.ensureDir(),this.rotateIfNeeded();}write(t){let n=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
4
|
+
`;try{G.appendFileSync(this.filePath,n,"utf-8");}catch{}}ensureDir(){try{let t=N.dirname(this.filePath);G.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(G.statSync(this.filePath).size>ll){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=this.filePath.replace(".log",`-${n}.log`);G.renameSync(this.filePath,r),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=N.dirname(this.filePath),n=N.basename(this.filePath,".log"),r=G.readdirSync(t).filter(o=>o.startsWith(n+"-")&&o.endsWith(".log")).sort().reverse();for(let o of r.slice(cl))G.unlinkSync(N.join(t,o));}catch{}}};var cn=class{write(t){process.stdout.write(t.message+`
|
|
5
|
+
`);}};var ft={debug:0,info:1,warn:2,error:3},Ye={context:"cli",transports:[],minLevel:"warn",debugModules:null};function ul(){let e=process.env.DEBUG;if(!e)return null;let t=e.split(",").map(r=>r.trim()).filter(Boolean);for(let r of t)if(r==="flow:*")return "all";let n=new Set;for(let r of t)r.startsWith("flow:")&&n.add(r.slice(5));return n.size>0?n:null}function re(e,t){if(e==="tui"){let n=ul();Ye={context:e,transports:[new Lt("tui"),new ln],minLevel:n?"debug":"warn",debugModules:n};}else t?.silent?Ye={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Ye={context:e,transports:[new Lt("cli")],minLevel:"debug",debugModules:null}:Ye={context:e,transports:[new cn],minLevel:"info",debugModules:null};}function Fo(){return Ye.transports}function Uo(e,t){let{debugModules:n,minLevel:r}=Ye;return Ye.context==="tui"&&n&&n!=="all"?n.has(t)?ft[e]>=ft.debug:ft[e]>=ft.warn:ft[e]>=ft[r]}var jo=new Map;function un(e,t,n){if(!Uo(e,t))return;let r={level:e,module:t,message:mr(n),timestamp:new Date};for(let o of Fo())o.write(r);}function S(e){let t=jo.get(e);if(t)return t;let n={debug:r=>un("debug",e,r),info:r=>un("info",e,r),warn:r=>un("warn",e,r),error:r=>un("error",e,r)};return jo.set(e,n),n}var yr=S("encryption"),hr="__encrypted__";function pl(e){return typeof e=="object"&&e!==null&&hr in e&&e[hr]===true}function Sr(e){return {serialize(t){let n=JSON.stringify(t),r=e.encrypt(n),o={[hr]:true,envelope:r};return JSON.stringify(o,null," ")},deserialize(t){let n;try{n=JSON.parse(t);}catch{return yr.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(pl(n))try{let r=e.decrypt(n.envelope);return JSON.parse(r)}catch(r){return yr.error(`[encryption] Decryption failed: ${r instanceof Error?r.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return yr.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),n}}}var wr=promisify(execFile),fl=promisify(exec),gt=class{static async isAvailable(){try{return await fl("command -v security"),!0}catch{return false}}async getSecret(t,n){try{let{stdout:r}=await wr("security",["find-generic-password","-w","-a",n,"-s",t]);return r.trim()||null}catch{return null}}async setSecret(t,n,r){await wr("security",["add-generic-password","-U","-a",n,"-s",t,"-w",r]);}async deleteSecret(t,n){try{return await wr("security",["delete-generic-password","-a",n,"-s",t]),!0}catch{return false}}getStoragePath(){return "macOS Keychain (security)"}};var Jo=promisify(execFile),xr=promisify(exec),Sl=[{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"}],pn=S("encryption:linux-keyvault");async function wl(e,t){let n=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r=0,o=setInterval(()=>{process.stderr.write(`\r${n[r++%n.length]} ${e}`);},80);try{return await t()}finally{clearInterval(o),process.stderr.write("\r\x1B[2K");}}function xl(e){let t=Qr.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(e,r=>{t.close(),n(r.trim().toLowerCase());});})}var Me=class e{static async isAvailable(){try{return await xr("command -v secret-tool"),!0}catch{return false}}static async detectPackageManager(){for(let t of Sl)try{return await xr(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;pn.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let t=await e.detectPackageManager();if(!t)return pn.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let n=await xl(" ? Install secret-tool? This requires sudo. (y/N) ");if(n!=="y"&&n!=="yes")return false;try{return pn.info(`Running: ${t.command}`),await wl("Installing secret-tool...",()=>xr(t.command)),e.isAvailable()}catch{return pn.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,n){try{let{stdout:r}=await Jo("secret-tool",["lookup","service",t,"account",n]);return r.trim()||null}catch{return null}}async setSecret(t,n,r){await new Promise((o,i)=>{let s=spawn("secret-tool",["store","--label",t,"service",t,"account",n]);s.stdin.end(r,"utf8"),s.on("close",c=>{c===0?o():i(new Error(`secret-tool exited with code ${c}`));}),s.on("error",i);});}async deleteSecret(t,n){try{return await Jo("secret-tool",["clear","service",t,"account",n]),!0}catch{return false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var Go=S("encryption:windows-keyvault"),yt=class{static async isAvailable(){try{return await dn.getPassword("__flow_probe__","__flow_probe__"),!0}catch{return false}}async getSecret(t,n){try{return await dn.getPassword(t,n)}catch(r){let o=r instanceof Error?r.message.split(`
|
|
6
|
+
`)[0]:"unknown error";return Go.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${n}"]: ${o}`),null}}async setSecret(t,n,r){try{await dn.setPassword(t,n,r);}catch(o){let i=o instanceof Error?o.message.split(`
|
|
7
|
+
`)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${t}", account="${n}"]: ${i}`;throw Go.error(s),new Error(s)}}async deleteSecret(t,n){try{return await dn.deletePassword(t,n)}catch{return false}}getStoragePath(){return "Windows Credential Manager (keytar)"}};var Il=32,bl="flow-plugins-cli-fallback",br="flow-plugins-cli-fallback",vl={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};function Pl(){let e=`${ge.hostname()}${ge.userInfo().username}`;return mt.scryptSync(e,bl,Il)}function El(){let e=Pl(),t=new $t(e),n=Sr(t);return new Ir({projectName:br,serialize:n.serialize,deserialize:n.deserialize})}var fn=null;function mn(){return fn||(fn=El()),fn}var W=class{warned=false;async getSecret(t,n){return mn().get(`${t}:${n}`)??null}async setSecret(t,n,r){if(!this.warned){let o=vl[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
|
|
8
8
|
using a machine-derived key. For stronger security, ${o}.
|
|
9
|
-
`),this.warned=true;}vt().set(`${t}:${n}`,r);}async deleteSecret(t,n){let r=vt(),o=`${t}:${n}`;return r.has(o)?(r.delete(o),true):false}getStoragePath(){return vt().path}static hasExistingData(){try{let t=new un({projectName:dn});return L.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new un({projectName:dn});L.rmSync(t.path,{force:!0});}catch{}St=null;}};async function pn(){if(G.hasExistingData())return new G;switch(process.platform){case "darwin":return await Le.isAvailable()?new Le:new G;case "linux":return await ye.isAvailable()?new ye:await ye.ensureInstalled()?new ye:new G;case "win32":return await Me.isAvailable()?new Me:new G;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Us=S("config:credentials"),De="flow-plugins-cli",mn="credentials",fn="token-cache",Et=null;async function Ue(){return Et||(Et=pn()),Et}function hr(){Et=null;}async function F(){let t=await(await Ue()).getSecret(De,mn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ae(e){let{clientId:t,clientSecret:n,tenant:r}=e,o=[!t?.trim()&&"clientId",!n?.trim()&&"clientSecret",!r?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw Us.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Ue()).setSecret(De,mn,JSON.stringify(e));}async function wr(){let e=await Ue();await e.deleteSecret(De,mn),await e.deleteSecret(De,fn);}async function xr(){return (await Ue()).getStoragePath()}async function br(e){await(await Ue()).setSecret(De,fn,JSON.stringify(e));}async function gn(){let t=await(await Ue()).getSecret(De,fn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Z(){let e=await gn();return e?new Date(e.expiresAt)>new Date:false}var vr=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\.0\.0\.0$/,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];function Ns(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let n=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!n)return null;let r=parseInt(n[1],16),o=parseInt(n[2],16);return `${r>>8&255}.${r&255}.${o>>8&255}.${o&255}`}function Fs(e){if(vr.some(n=>n.test(e)))return true;let t=Ns(e);return !!(t&&vr.some(n=>n.test(t)))}function Os(e,t){let n=process.env[e]??t;if(!n)throw new Error(`Missing required environment variable: ${e}`);return n}function Tt(e,t){let n=Os(e,t),r;try{r=new URL(n);}catch{throw new Error(`${e} must be a valid URL. Got: "${n}"`)}let o=process.env.NODE_ENV==="development";if(!o&&r.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${r.protocol}"`);if(r.username||r.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(!o&&Fs(r.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${r.hostname}"`);return n}var yn=S("api:auth");function Ks(e){if(!mt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Sr={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 Vs(e){if(e instanceof HTTPError){let t=e.response.status;yn.error(`HTTP error during authentication [status=${t}]`);let n="";try{let r=await e.response.text(),o=JSON.parse(r);typeof o.error=="string"&&(n=o.error);}catch{}return n&&Sr[n]?new Error(Sr[n]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(yn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(yn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function We(e){let t=Tt("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Ks(e.tenant);let n;try{n=await _s.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(o){throw await Vs(o)}let r=n.expires_at??new Date(Date.now()+(n.expires_in??3600)*1e3).toISOString();await Ae(e),await br({accessToken:n.access_token,expiresAt:r});}async function Pr(){if(await Z()){let t=await gn();if(!t)throw new Error("Flow CLI not configured. Run: flow auth login");return t.accessToken}throw new Error("Flow CLI not configured or token expired. Run: flow auth login")}var Y=["clientId","clientSecret","tenant"],qs={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function Ir(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[n,r]=useState("clientId"),[o,s]=useState({}),[i,l]=useState(null),[c,a]=useState(false),{setCredentials:d,setJustAuthenticated:h}=X(),{setFocus:E}=p();useInput((u,m)=>{if(!c){if(m.shift&&m.tab){let y=Y.indexOf(n);y>0&&r(Y[y-1]);}else if(m.tab){let y=Y.indexOf(n);y<Y.length-1&&r(Y[y+1]);}else if(m.return)if(n==="tenant")U();else {let y=Y.indexOf(n);r(Y[y+1]);}}},{isActive:true});let U=async()=>{let u={};for(let m of Y)e[m].trim()||(u[m]="This field is required");if(Object.keys(u).length>0){s(u);let m=Y.find(y=>u[y]);m&&r(m);return}a(true),l(null);try{await We({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()});let{clientSecret:m,...y}=e;d(y),h(!0),p.getState().setScreen("bundleSetup"),E("bundleList");}catch(m){l(m instanceof Error?m.message:"Authentication failed");}finally{a(false),t(m=>({...m,clientSecret:""}));}},j=u=>m=>{t(y=>({...y,[u]:m})),o[u]&&s(y=>({...y,[u]:void 0}));};return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[er," \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:Y.map(u=>jsx(Box,{marginBottom:1,children:jsx(Yn,{label:qs[u],value:e[u],onChange:j(u),masked:u==="clientSecret",isActive:n===u&&!c,error:o[u]})},u))}),c&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),i&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}var Xs=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8")),$t=Xs.version;function Ct(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Ws,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",$t]})})]})}var hn={discover:"Discover",installed:"Installed"},Qs=Object.keys(hn);function Rr(){let e=p(t=>t.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:Qs.map(t=>jsx(Box,{marginRight:1,children:t===e?jsx(Text,{bold:true,inverse:true,children:` ${hn[t]} `}):jsx(Text,{dimColor:true,children:` ${hn[t]} `})},t))})}var O=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Br(){let e=p(i=>i.focus),t=O(i=>i.query),n=O(i=>i.cursorPosition),r=e==="search",o=t.slice(0,n),s=t.slice(n);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:r?"cyan":"gray",children:"\u03C1 "}),r?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}function b(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function Fe(e){process.stdout.write(w.green(` \u2713 ${b(e)}
|
|
10
|
-
`));}function
|
|
11
|
-
`));}function
|
|
12
|
-
`));}function
|
|
13
|
-
`),process.stdout.write(` ${
|
|
14
|
-
`),process.stdout.write(` ${
|
|
15
|
-
`);for(let
|
|
9
|
+
`),this.warned=true;}mn().set(`${t}:${n}`,r);}async deleteSecret(t,n){let r=mn(),o=`${t}:${n}`;return r.has(o)?(r.delete(o),true):false}getStoragePath(){return mn().path}static hasExistingData(){try{let t=new Ir({projectName:br});return G.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Ir({projectName:br});G.rmSync(t.path,{force:!0});}catch{}fn=null;}};async function vr(){if(W.hasExistingData())return new W;switch(process.platform){case "darwin":return await gt.isAvailable()?new gt:new W;case "linux":return await Me.isAvailable()?new Me:await Me.ensureInstalled()?new Me:new W;case "win32":return await yt.isAvailable()?new yt:new W;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Tl=S("config:credentials"),Te="flow-plugins-cli",Pr="credentials",Er="token-cache",Tr="user-info",hn=null;async function _e(){return hn||(hn=vr()),hn}function Sn(){hn=null;}async function O(){let t=await(await _e()).getSecret(Te,Pr);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ze(e){let{clientId:t,clientSecret:n,tenant:r}=e,o=[!t?.trim()&&"clientId",!n?.trim()&&"clientSecret",!r?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw Tl.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await _e()).setSecret(Te,Pr,JSON.stringify(e));}async function qo(){let e=await _e();await e.deleteSecret(Te,Pr),await e.deleteSecret(Te,Er),await e.deleteSecret(Te,Tr);}async function Wo(){return (await _e()).getStoragePath()}async function Xo(e){await(await _e()).setSecret(Te,Er,JSON.stringify(e));}async function wn(){let t=await(await _e()).getSecret(Te,Er);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function xn(e){await(await _e()).setSecret(Te,Tr,JSON.stringify(e));}async function Yo(){let t=await(await _e()).getSecret(Te,Tr);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ht(){let e=await wn();return e?new Date(e.expiresAt)>new Date:false}function In(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=Buffer.from(n,"base64").toString("utf8");try{return JSON.parse(r)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Zo=[/^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\.0\.0\.0$/,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];function kl(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let n=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!n)return null;let r=parseInt(n[1],16),o=parseInt(n[2],16);return `${r>>8&255}.${r&255}.${o>>8&255}.${o&255}`}function Cl(e){if(Zo.some(n=>n.test(e)))return true;let t=kl(e);return !!(t&&Zo.some(n=>n.test(t)))}function Al(e,t){let n=process.env[e]??t;if(!n)throw new Error(`Missing required environment variable: ${e}`);return n}function St(e,t){let n=Al(e,t),r;try{r=new URL(n);}catch{throw new Error(`${e} must be a valid URL. Got: "${n}"`)}let o=process.env.NODE_ENV==="development";if(!o&&r.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${r.protocol}"`);if(r.username||r.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(!o&&Cl(r.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${r.hostname}"`);return n}var kr=S("api:auth");function Rl(e){if(!We.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Qo={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 Ml(e){if(e instanceof HTTPError){let t=e.response.status;kr.error(`HTTP error during authentication [status=${t}]`);let n="";try{let r=await e.response.text(),o=JSON.parse(r);typeof o.error=="string"&&(n=o.error);}catch{}return n&&Qo[n]?new Error(Qo[n]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(kr.debug(`Non-HTTP error during authentication: ${e.message}`),e):(kr.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Qe(e){let t=St("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Rl(e.tenant);let n;try{n=await $l.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await Ml(i)}let r=n.expires_at??new Date(Date.now()+(n.expires_in??3600)*1e3).toISOString();await Ze(e),await Xo({accessToken:n.access_token,expiresAt:r});let o=In(n.access_token);await xn({sub:o.sub,name:o.name,email:o.email});}var ei=S("lib:tokenProvider");async function Oe(){if(await ht()){let r=await wn();if(r)return r.accessToken}ei.debug("Token expired or missing, re-authenticating...");let t=await O();if(!t)throw new Error("Not authenticated. Run: flow auth login");W.clearFallbackFile(),Sn(),await Qe(t);let n=await wn();if(!n)throw new Error("Authentication succeeded but token was not persisted");return ei.debug("Token refreshed successfully"),n.accessToken}var bn=S("api:metrics");function ti(){return St("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function ni(e,t,n){return $l.post(e,{json:t,headers:n})}async function Ol(e){let t=await Yo();if(t)return t;let n=In(e),r={sub:n.sub,name:n.name,email:n.email};return await xn(r),r}async function b(e,t){let n=await Oe(),r=await Ol(n),o=await O();if(!We.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let i={action:e,booster:pr,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:r.sub,name:r.name,email:r.email}};try{await ni(ti(),i,{Authorization:`Bearer ${n}`,FlowTenant:o.tenant}),bn.debug(`Metrics event sent: ${e}`);}catch(s){throw bn.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function ri(e,t,n){try{let r=n&&We.test(n)?n:"unknown",o={action:e,booster:pr,metadata:t,success:!0,tenant:r,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await ni(ti(),o,{FlowTenant:r}),bn.debug(`Anonymous metrics event sent: ${e}`);}catch(r){bn.warn(`Failed to send anonymous metrics event "${e}": ${String(r)}`);}}var x={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_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"};var Dl={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ce={...Dl};function oi(e){let t=Date.now();ce={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function et(e){ce.currentStep=e,ce.stepStart=Date.now();}function $(){return {...ce}}function De(){return ce.sessionStart===0?0:Date.now()-ce.sessionStart}function tt(){return ce.stepStart===0?0:Date.now()-ce.stepStart}function ii(){ce.tuiSessionStart=Date.now();}function si(){return ce.tuiSessionStart===0?0:Date.now()-ce.tuiSessionStart}var Bl=3e3,Nl=S("abandonment");async function vn(e){let{currentStep:t,sessionStart:n}=$();if(n===0)return;let r={last_step:t,trigger:e,duration_ms:De()};try{await Promise.race([b(x.CLI_ONBOARDING_ABANDONED,r),new Promise((o,i)=>setTimeout(()=>i(new Error("abandonment timeout")),Bl))]);}catch(o){Nl.warn(`Abandonment event failed: ${String(o)}`);}}function ai(e,t){return Promise.race([e,new Promise(n=>setTimeout(n,t))])}var Fl=3e3,Ul=S("session-end");async function Ot(e){let{activeTab:t,screen:n}=f.getState(),r=si(),i=[b(x.CLI_TUI_SESSION_ENDED,{duration_ms:r,active_tab:t,interface:"tui"})];n!=="main"&&i.push(vn(e));try{await ai(Promise.all(i).then(()=>{}),Fl);}catch(s){Ul.warn(`Session end event failed: ${String(s)}`);}}var Hl=2e3;function ci(){let{exit:e}=useApp(),t=useRef(false),n=useRef(null),r=f(s=>s.pendingExit),o=f(s=>s.setPendingExit),i=useCallback(()=>{if(t.current){n.current&&clearTimeout(n.current),Ot("double-ctrl-c").finally(()=>e());return}t.current=true,o(true),n.current=setTimeout(()=>{t.current=false,o(false);},Hl);},[e,o]);return useInput((s,c)=>{c.ctrl&&s==="c"&&i();}),{pendingExit:r}}var ql=16;function ui({label:e,value:t,onChange:n,masked:r=false,isActive:o,error:i}){let s=useRef(t);useEffect(()=>{s.current=t;},[t]),useInput((a,l)=>{if(l.backspace){let u=s.current.slice(0,-1);s.current=u,n(u);}else if(a&&!l.ctrl&&!l.meta&&!l.escape&&!l.return&&!l.tab&&!l.upArrow&&!l.downArrow&&!l.leftArrow&&!l.rightArrow){let u=s.current+a;s.current=u,n(u);}},{isActive:o});let c=r?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(ql)}),jsx(Text,{color:o?"cyan":"gray",children:c}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}var ue=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));var Zl=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8")),Be=Zl.version;function p(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\x0e-\x1f\x7f]/g,"")}function V(e){process.stdout.write(C.green(` \u2713 ${p(e)}
|
|
10
|
+
`));}function k(e){process.stderr.write(C.red(` \u2717 ${p(e)}
|
|
11
|
+
`));}function I(e){process.stdout.write(C.cyan(` \u2139 ${p(e)}
|
|
12
|
+
`));}function Pn(e,t){let n=t.map(c=>c.map(p)),r=[e,...n],o=e.map((c,a)=>Math.max(...r.map(l=>(l[a]??"").length))),i=o.map(c=>"\u2500".repeat(c)).join(" "),s=c=>c.map((a,l)=>a.padEnd(o[l])).join(" ");process.stdout.write(`
|
|
13
|
+
`),process.stdout.write(` ${C.bold(s(e))}
|
|
14
|
+
`),process.stdout.write(` ${C.dim(i)}
|
|
15
|
+
`);for(let c of n)process.stdout.write(` ${s(c)}
|
|
16
16
|
`);process.stdout.write(`
|
|
17
|
-
`);}function
|
|
18
|
-
`);}function Lt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var Lr=ti.memo(function({item:t,isSelected:n}){let r=t.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:n?"cyan":"gray",children:n?"\u203A ":"\u25CB "}),jsx(Text,{bold:n,color:n?"cyan":"white",children:t.name}),jsxs(Text,{dimColor:true,children:[t.authorName?` \xB7 ${t.authorName}`:"",t.version?` \xB7 v${t.version}`:" \xB7 n/a"]}),t.status&&jsxs(Text,{color:r,children:[" [",t.status,"]"]}),t.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),t.installedBadge&&jsx(Text,{color:"cyan",children:" [installed]"}),t.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",Lt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Mt({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}var bn=5;function Ur({items:e,emptyMessage:t}){let n=p(c=>c.selectedIndex);if(e.length===0)return jsx(Mt,{message:t});let r=Math.max(0,n-Math.floor(bn/2)),o=Math.min(e.length,r+bn);o===e.length&&(r=Math.max(0,o-bn));let s=e.slice(r,o),i=r,l=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((c,a)=>jsx(Lr,{item:c,isSelected:r+a===n},c.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:l>0?`\u2193 ${l} more below`:" "})})]})}var si={discover:"Discover plugins",installed:"Installed plugins"};function Fr({items:e,tabId:t,emptyMessage:n}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,children:si[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),jsx(Br,{}),jsx(Ur,{items:e,emptyMessage:n})]})}function Or({filteredItems:e,emptyMessage:t}){let n=p(r=>r.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(Fr,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(Fr,{items:e,tabId:"installed",emptyMessage:t},"installed")})}var li={tabs:"\u2190\u2192: switch tab | \u2193: navigate | Enter: select | Ctrl+C Ctrl+C: quit",list:"\u2190\u2192/Tab: switch tab | \u2191\u2193: navigate | Enter: select | Type to search | Ctrl+C Ctrl+C: 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",bundleList:"\u2191\u2193: navigate | Enter: select bundle | Esc: skip",bundleDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select"};function Dt(){let e=p(t=>t.focus);return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsx(Text,{dimColor:true,children:li[e]})})}function jr({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",e]})}):null}function Ut({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(fi,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Nt({message:e,onRetry:t,onBack:n}){return useInput((r,o)=>{r==="r"&&o.ctrl&&t?t():o.escape&&n&&n();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),n&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function Ft({itemName:e,actions:t,onAction:n,onClose:r}){let o=p(l=>l.focus),[s,i]=useState(0);return useInput((l,c)=>{c.upArrow?i(a=>a>0?a-1:a):c.downArrow?i(a=>a<t.length-1?a+1:a):c.return?n(t[s]):c.escape&&r();},{isActive:o==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,c)=>jsx(Box,{children:jsxs(Text,{bold:c===s,color:c===s?"cyan":void 0,children:[c===s?"\u203A ":" ",l]})},c))})]})}function Gr({itemName:e,onInstall:t,onClose:n}){return jsx(Ft,{itemName:e,actions:["Install","Cancel"],onAction:s=>{s==="Install"?t():n();},onClose:n})}function Zr({itemName:e,itemStatus:t,updateAvailable:n,catalogVersion:r,onUninstall:o,onToggleStatus:s,onUpdate:i,onClose:l}){let[c,a]=useState(false),d=p(u=>u.focus);if(useInput((u,m)=>{m.escape||u==="n"?a(false):u==="y"&&o();},{isActive:c&&d==="actionMenu"}),c)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 h=t==="enabled"?"Disable":"Enable",E=r?`Update to v${r}`:"Update";return jsx(Ft,{itemName:e,actions:n?["Uninstall",h,E,"Cancel"]:["Uninstall",h,"Cancel"],onAction:u=>{u==="Uninstall"?a(true):u===h?s():u.startsWith("Update")?i?.():l();},onClose:l})}async function Yr(e,t){let n=le.resolve(t);await ee.mkdir(n,{recursive:true});let r=le.join(le.dirname(n),`${randomUUID()}.zip`);try{await ee.writeFile(r,e),await Pi(r,{dir:n,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let i=le.resolve(n,o.fileName);if(!i.startsWith(n+le.sep)&&i!==n)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(n);if(!o.startsWith(le.resolve(le.dirname(n))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await ee.unlink(r);}catch{}}}async function Tn(e){await ee.rm(e,{recursive:true,force:true});}async function xe(){let e=ir();await ee.mkdir(le.dirname(e),{recursive:true});try{await ee.writeFile(e,"",{flag:"wx"});}catch(n){if(n.code!=="EEXIST")throw n}return await Ii.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Ti(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:T,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function to(){let e=gt();if(!L__default.existsSync(e))return null;try{return JSON.parse(L__default.readFileSync(e,"utf-8"))}catch{return null}}function Ai(){let e=to();if(e)return e;let t=Ti(),n=gt();return L__default.mkdirSync(le__default.dirname(n),{recursive:true}),An(t),t}function An(e){let t=gt(),n=`${t}.tmp`;L__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),L__default.renameSync(n,t);}function $i(){let e=or(),t={};try{L__default.existsSync(e)&&(t=JSON.parse(L__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[T])return;t[T]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:sr(),lastUpdated:new Date().toISOString()};let n=`${e}.tmp`;L__default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8"),L__default.renameSync(n,e);}function no(e,t){$i();let n=rn(e.name);L__default.mkdirSync(le__default.dirname(n),{recursive:true});try{L__default.lstatSync(n),L__default.rmSync(n,{recursive:!0,force:!0});}catch{}L__default.symlinkSync(t,n);let r=Ai();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}),An(r));}function ro(e){let t=rn(e);try{L__default.rmSync(t,{recursive:!0,force:!0});}catch{}let n=to();if(!n)return;let r=n.plugins.length;n.plugins=n.plugins.filter(o=>o.name!==e),n.plugins.length!==r&&An(n);}var ae=S("storage");function oo(){return le__default.join(fe__default.homedir(),".claude","plugins","installed_plugins.json")}function Ci(){return le__default.join(fe__default.homedir(),".claude","plugins")}function Ri(e){let t=le__default.resolve(e),n=le__default.resolve(Ci());if(!t.startsWith(n+le__default.sep)&&t!==n)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function so(){return le__default.join(fe__default.homedir(),".claude","settings.json")}function ce(){let e=oo();if(!L__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(L__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}function ot(e){let t=oo();L__default.mkdirSync(le__default.dirname(t),{recursive:true});let n=`${t}.tmp`;L__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),L__default.renameSync(n,t);}function rt(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function ki(e){let t=le__default.join(e,".claude-plugin","plugin.json");if(!L__default.existsSync(t))return null;try{return JSON.parse(L__default.readFileSync(t,"utf-8"))}catch{return null}}function Cn(){let e=so();if(!L__default.existsSync(e))return {};try{return JSON.parse(L__default.readFileSync(e,"utf-8"))}catch{return {}}}function io(e){let t=so(),n=`${t}.tmp`;L__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),L__default.renameSync(n,t);}function Bi(){return Cn().enabledPlugins??{}}function Li(e){let t=Cn(),n=t.enabledPlugins;if(!n||!(e in n))return;let{[e]:r,...o}=n;t.enabledPlugins=o,io(t);}function Rn(e,t){let n=Cn(),r=n.enabledPlugins??{};n.enabledPlugins={...r,[e]:t},io(n);}function q(){let e=ce(),t=Bi();return Object.entries(e.plugins).map(([n,r])=>{let o=r[0],{name:s,marketplace:i}=rt(n),l=ki(o.installPath),c=t[n];return {name:s,marketplace:i,version:o.version&&o.version!=="unknown"?o.version:void 0,installedAt:o.installedAt,installPath:o.installPath,scope:o.scope,description:l?.description,author:l?.author,status:c===false?"disabled":"enabled"}})}async function _t(e){ae.debug(`[${e}] Acquiring lock to uninstall`);let t=await xe();try{let{name:n,marketplace:r}=rt(e),o=ce(),s;if(r?(s=`${n}@${r}`,o.plugins[s]||(s=void 0)):s=Object.keys(o.plugins).filter(h=>rt(h).name===n)[0],!s)throw ae.error(`[${n}] Plugin is not installed`),new Error(`Plugin '${n}' is not installed`);ae.debug(`[${n}] Resolved key: ${s}`);let i=o.plugins[s][0].installPath;Ri(i);let l=le__default.dirname(i);ae.debug(`[${n}] Removing directory: ${l}`),L__default.rmSync(l,{recursive:!0,force:!0}),ro(n);let{[s]:c,...a}=o.plugins;ot({...o,plugins:a}),Li(s),ae.debug(`[${n}] Uninstalled successfully`);}finally{await t();}}async function st(e,t){ae.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await xe();try{let{name:r}=rt(e),o=ce(),s=Object.keys(o.plugins).filter(i=>rt(i).name===r);if(s.length===0)throw ae.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);ae.debug(`[${r}] Resolved key: ${s[0]}`),Rn(s[0],t==="enabled"),ae.debug(`[${r}] Status updated to ${t}`);}finally{await n();}}var M=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:q()})}));var $=["discover","installed"];function ao(e,t,n){if(t.rightArrow||t.tab){let r=$.indexOf(n.activeTab);return [{type:"setTab",tab:$[(r+1)%$.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}if(t.leftArrow){let r=$.indexOf(n.activeTab);return [{type:"setTab",tab:$[(r-1+$.length)%$.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}return t.downArrow?[{type:"setFocus",focus:"list"}]:[]}function lo(e,t,n,r){if(t.upArrow)return n.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:n.selectedIndex-1}];if(t.downArrow&&n.selectedIndex<r-1)return [{type:"setSelectedIndex",index:n.selectedIndex+1}];if(t.leftArrow){let o=$.indexOf(n.activeTab);return [{type:"setTab",tab:$[(o-1+$.length)%$.length]},{type:"setSelectedIndex",index:0}]}if(t.rightArrow){let o=$.indexOf(n.activeTab);return [{type:"setTab",tab:$[(o+1)%$.length]},{type:"setSelectedIndex",index:0}]}if(t.tab){let o=$.indexOf(n.activeTab);return [{type:"setTab",tab:$[(o+1)%$.length]},{type:"setSelectedIndex",index:0}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function co(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function uo(e,t,n){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?n.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}function Kt(e){let{setActiveTab:t,setFocus:n,setSelectedIndex:r,setActionMenuOpen:o}=p.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")n(s.focus);else if(s.type==="setSelectedIndex")r(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:l,setCursorPosition:c,cursorPosition:a}=O.getState();i(l.slice(0,a)+s.char+l.slice(a)),c(a+s.char.length);}}function po({listLength:e}){let t=p(u=>u.focus),n=p(u=>u.selectedIndex),r=p(u=>u.actionMenuOpen),o=p(u=>u.setFocus),s=p(u=>u.setActionMenuOpen),i=O(u=>u.query),l=O(u=>u.setQuery),c=O(u=>u.resetQuery),a=useRef(e);useEffect(()=>{a.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:u,setCursorPosition:m}=O.getState();m(u.length);}},[t]);let[d,h]=useState("");useEffect(()=>{let u=setTimeout(()=>h(i),300);return ()=>clearTimeout(u)},[i]),useInput((u,m)=>{let{activeTab:y,selectedIndex:v,actionMenuOpen:I}=p.getState();Kt(ao(u,m,{activeTab:y}));},{isActive:t==="tabs"}),useInput((u,m)=>{let{activeTab:y,selectedIndex:v,actionMenuOpen:I}=p.getState();Kt(lo(u,m,{activeTab:y,selectedIndex:v},a.current));},{isActive:t==="list"}),useInput((u,m)=>{Kt(co(u,m));},{isActive:t==="actionMenu"}),useInput((u,m)=>{let y=uo(u,m,O.getState().query),v=y.queryUpdate;if(Kt(y.actions),v==="reset")c(),h("");else if(v!==null){let{query:I,cursorPosition:B,setCursorPosition:z}=O.getState();if("backspace"in v)B>0&&(l(I.slice(0,B-1)+I.slice(B)),z(B-1));else if("append"in v)l(I.slice(0,B)+v.append+I.slice(B)),z(B+v.append.length);else if("cursorMove"in v){let R=B+v.cursorMove;R>=0&&R<=I.length&&z(R);}}},{isActive:t==="search"});let E=useCallback(()=>{s(false),o("list");},[s,o]),U=useCallback(u=>{let{setSelectedIndex:m,selectedIndex:y}=p.getState();u===0?m(0):y>=u&&m(u-1);},[]),j=useCallback(u=>{if(!d)return a.current=u.length,u;let m=d.toLowerCase(),y=u.filter(v=>v.name.toLowerCase().includes(m)||v.description?.toLowerCase().includes(m));return a.current=y.length,y},[d]);return {actionMenuOpen:r,closeMenu:E,selectedIndex:n,clampIndex:U,filteredItems:j}}function fo(){let e=p(l=>l.notification),t=p(l=>l.showNotification),n=p(l=>l.clearNotification),r=X(l=>l.justAuthenticated),o=X(l=>l.credentials),s=X(l=>l.setJustAuthenticated);return useEffect(()=>{r&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[r,o]),useEffect(()=>{if(!e)return;let l=setTimeout(n,3e3);return ()=>clearTimeout(l)},[e]),{notify:(l,c)=>{t(l,c);}}}var te=class extends Error{constructor(n,r){super(`${n} v${r} is already installed. Use --force to reinstall.`);this.pluginName=n;this.version=r;this.name="AlreadyInstalledError";}},be=class extends Error{constructor(n,r){super(`${n} is already up to date (v${r})`);this.pluginName=n;this.version=r;this.name="AlreadyUpToDateError";}};function it(){return _s.create({prefix:Tt("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Pr();e.headers.set("Authorization",`Bearer ${t}`);let n=await F();n?.tenant&&mt.test(n.tenant)&&e.headers.set("FlowTenant",n.tenant);}]}})}var Fi=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function go(e){if(!e||!Fi.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function ue(){try{let{plugins:e}=await it().get("v1/plugins/catalog").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 plugin catalog"):new Error(`Failed to fetch plugin catalog: ${e.message}`):e}}async function Ke(e){go(e);try{return await it().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function yo(e){go(e);try{let t=await it().get(`v1/plugins/${e}/archive`);return Buffer.from(await t.arrayBuffer())}catch(t){throw t instanceof Error?t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to download plugin: ${t.message}`):t}}async function Vt(){try{let{profiles:e}=await it().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 bundles"):new Error(`Failed to fetch bundles: ${e.message}`):e}}var Oi=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function _i(e){if(!Oi.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}var at=S("installer");function ji(e,t){let n=`${e}@${T}`,o=ce().plugins[n];if(o&&!t)throw new te(e,o[0].version??"unknown");return {pluginKey:n,alreadyInstalled:o}}async function Ki(e,t,n){n&&await Tn(t);try{at.debug(`Extracting to ${t}...`),await Yr(e,t);}catch(r){throw await Tn(t),r}}function Vi(e,t,n){let r=ce(),o={scope:"user",installPath:t,version:n,installedAt:new Date().toISOString()};r.plugins[e]=[o],ot(r),Rn(e,true);}async function ne(e,t={}){let n=Date.now(),r=null;try{at.debug(`[${e}] Acquiring lock...`),r=await xe();let{pluginKey:o,alreadyInstalled:s}=ji(e,t.force);at.debug(`[${e}] Fetching manifest...`);let i=await Ke(e);_i(i.name),at.debug(`[${e}] Downloading archive...`);let l=await yo(e),c=rr(i.name,i.version);await Ki(l,c,!!s&&!!t.force),Vi(o,c,i.version),no(i,c);let a=Date.now()-n;return at.debug(`[${e}] Installed successfully in ${a}ms`),{name:i.name,version:i.version,path:c,duration_ms:a}}finally{r&&await r();}}function de(e,t,n=false){return n?true:!Ln.valid(e)||!Ln.valid(t)?false:Ln.gt(t,e)}var ve=S("updater");function Ji(e){let t=ce(),n=`${e}@${T}`,r=t.plugins[n];return !r||r.length===0?null:{pluginKey:n,entry:r[0]}}async function Jt(e,t={}){let n=Date.now(),r=null;try{ve.debug(`[${e}] Acquiring lock...`),r=await xe();let o=Ji(e);if(!o)throw ve.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,l=s.installPath;ve.debug(`[${e}] Fetching manifest...`);let a=(await Ke(e)).version;if(!i||!de(i,a,t.force))throw ve.debug(`[${e}] Already up to date (v${i??"n/a"})`),new be(e,i??"unknown");ve.info(`[${e}] Updating v${i} \u2192 v${a}...`),await r(),r=null;try{let d=await ne(e,{force:!0}),h=Date.now()-n;return ve.debug(`[${e}] Updated successfully in ${h}ms`),{name:d.name,previousVersion:i,newVersion:d.version,path:d.path,duration_ms:h}}catch(d){ve.warn(`[${e}] Install failed, rolling back to v${i}...`),r=await xe();let h=ce(),E=`${e}@${T}`;throw h.plugins[E]&&(h.plugins[E][0].version=i,h.plugins[E][0].installPath=l,ot(h),ve.info(`[${e}] Rollback completed, restored to v${i}`)),d}}finally{r&&await r();}}function ho(){let e=M(i=>i.installedItems),t=M(i=>i.setInstalledItems),n=useCallback(async i=>{await ne(i.name),M.getState().loadFromDisk();},[]),r=useCallback(async i=>{await _t(i),t(e.filter(l=>l.name!==i));},[e,t]),o=useCallback(async i=>{let c=e.find(a=>a.name===i)?.status==="enabled"?"disabled":"enabled";await st(i,c),t(e.map(a=>a.name===i?{...a,status:c}:a));},[e,t]),s=useCallback(async i=>{await Jt(i),M.getState().loadFromDisk();},[]);return {install:n,uninstall:r,toggle:o,update:s}}function wo({selectedItem:e,selectedCatalogItem:t,items:n,closeMenu:r,clampIndex:o,notify:s}){let i=p(m=>m.setLoading),{install:l,uninstall:c,toggle:a,update:d}=ho(),h=async(m,y,v)=>{i(true,m),r();try{await y(),o(n.length),s(v,"success");}catch(I){s(I instanceof Error?I.message:"Something went wrong","error");}finally{i(false);}};return {handleInstall:()=>{e&&t&&h(`Installing ${e.name}...`,()=>l(t),"\u2713 Installed successfully");},handleUninstall:()=>{e&&h(`Uninstalling ${e.name}...`,()=>c(e.name),"\u2713 Uninstalled");},handleToggleStatus:()=>{if(!e)return;let m=e.status==="enabled";h(m?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>a(e.name),m?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let m=t?` to v${t.version}`:"";(async()=>{i(true,`Updating ${e.name}${m}...`),r();try{await d(e.name),o(n.length),s(`\u2713 Updated ${e.name}${m}`,"success");}catch(v){v instanceof be?s(v.message,"info"):s(v instanceof Error?v.message:"Something went wrong","error");}finally{i(false);}})();}}}function xo(){let[e,t]=useState([]),[n,r]=useState(true),[o,s]=useState(null),i=useCallback(async()=>{r(true),s(null);try{let l=await ue();t(l);}catch(l){s(l instanceof Error?l:new Error(String(l))),t([]);}finally{r(false);}},[]);return useEffect(()=>{i();},[i]),{catalog:e,isLoading:n,error:o,refetch:i}}function bo(){return {items:M(t=>t.installedItems)}}var Xi=S("catalog");function Gi(e){return {name:e.name,version:e.version,description:e.description,authorName:e.author.name,updateAvailable:e.updateAvailable}}function Wi(e){return {name:e.name,version:e.version,description:e.description,authorName:e.author?.name,status:e.status,updateAvailable:e.updateAvailable,installedAt:e.installedAt}}function vo(){let e=p(x=>x.activeTab),t=p(x=>x.notification),n=p(x=>x.loading),r=p(x=>x.loadingMessage),o=p(x=>x.catalogError),s=p(x=>x.setCatalogError),i=O(x=>x.query),{catalog:l,isLoading:c,error:a,refetch:d}=xo(),{items:h}=bo(),E=M(x=>x.loadFromDisk),U=useMemo(()=>new Set(h.map(x=>`${x.name}|${x.author?.name??""}|${x.marketplace}`)),[h]),j=useMemo(()=>{let x=new Map(l.map(Ie=>[Ie.name,Ie.version]));return h.map(Ie=>{let Wn=x.get(Ie.name),rs=!!Wn&&!!Ie.version&&de(Ie.version,Wn);return {...Ie,updateAvailable:rs}})},[h,l]),u=e==="discover"?l.filter(x=>!U.has(`${x.name}|${x.author.name}|${T}`)).map(x=>Gi(x)):j.map(x=>Wi(x)),{actionMenuOpen:m,closeMenu:y,selectedIndex:v,clampIndex:I,filteredItems:B}=po({listLength:u.length}),z=B(u),R=z[v]??null,pt=useMemo(()=>R?l.find(x=>x.name===R.name)??null:null,[l,R]),Yt=e==="installed"?"No plugins installed \u2014 explore the Discover tab!":i?`No plugins found for '${i}'`:"No plugins available in the catalog",{notify:f}=fo(),{handleInstall:N,handleUninstall:Q,handleToggleStatus:se,handleUpdate:ns}=wo({selectedItem:R,selectedCatalogItem:pt,items:u,closeMenu:y,clampIndex:I,notify:f});return useEffect(()=>{E();},[]),useEffect(()=>{I(z.length);},[z.length,I]),useEffect(()=>{a&&(Xi.error(`[usePluginCatalog] ${a instanceof Error?a.message:String(a)}`),s("Failed to load catalog"));},[a]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Ct,{}),jsx(Rr,{}),jsx(Or,{filteredItems:z,emptyMessage:Yt}),(n||c)&&jsx(Ut,{message:n?r:"Loading catalog..."}),o&&!c&&e==="discover"&&jsx(Nt,{message:o,onRetry:()=>{s(null),d();},onBack:()=>s(null)}),t&&jsx(jr,{message:t.message,type:t.type}),m&&R&&e==="discover"&&jsx(Gr,{itemName:R.name,onInstall:N,onClose:y}),m&&R&&e==="installed"&&jsx(Zr,{itemName:R.name,itemStatus:R.status??"enabled",updateAvailable:R.updateAvailable??false,catalogVersion:pt?.version,onUninstall:Q,onToggleStatus:se,onUpdate:ns,onClose:y}),jsx(Dt,{})]})}var g=create((e,t)=>({bundles:[],selectedBundleIndex:0,selectedBundle:null,plugins:[],pluginCursorIndex:0,step:"bundleList",isLoadingBundles:false,bundlesError:null,successCount:0,failedCount:0,summaryActionIndex:0,setBundles:n=>e({bundles:n}),setSelectedBundleIndex:n=>e({selectedBundleIndex:n}),selectBundle:n=>{let r=new Set(M.getState().installedItems.map(o=>o.name));e({selectedBundle:n,plugins:n.plugins.map(o=>({name:o,selected:true,status:r.has(o)?"success":"pending",installed:r.has(o)})),pluginCursorIndex:0,step:"bundleDetail"});},setPluginCursorIndex:n=>e({pluginCursorIndex:n}),setStep:n=>e({step:n}),setPluginStatus:(n,r,o)=>{let s=t().plugins.map(i=>i.name===n?{...i,status:r,error:o}:i);e({plugins:s});},setIsLoadingBundles:n=>e({isLoadingBundles:n}),setBundlesError:n=>e({bundlesError:n}),setSummaryActionIndex:n=>e({summaryActionIndex:n}),computeSummary:()=>{let r=t().plugins.filter(o=>o.selected);e({successCount:r.filter(o=>o.status==="success").length,failedCount:r.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let n=t().plugins.map(r=>r.status==="failed"?{...r,status:"pending",error:void 0}:r);e({plugins:n,step:"installing"});},goBackToList:()=>e({selectedBundle:null,plugins:[],pluginCursorIndex:0,step:"bundleList"})}));var ea=3;function Po(){let e=g(c=>c.setBundles),t=g(c=>c.setIsLoadingBundles),n=g(c=>c.setBundlesError),r=g(c=>c.setPluginStatus),o=g(c=>c.setStep),s=g(c=>c.computeSummary),i=useCallback(async()=>{t(true),n(null);try{let c=await Vt();e(c);}catch(c){n(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,n,e]);useEffect(()=>{M.getState().loadFromDisk(),i();},[i]);let l=useCallback(async()=>{let c=g.getState().plugins.filter(a=>a.selected&&a.status==="pending");for(let a of c){r(a.name,"installing");let d="",h=false;for(let E=1;E<=ea;E++)try{await ne(a.name),r(a.name,"success"),h=!0;break}catch(U){if(U instanceof te){r(a.name,"success"),h=true;break}d=U instanceof Error?U.message:"Unknown error";}h||r(a.name,"failed",d);}M.getState().loadFromDisk(),s(),o("summary");},[r,s,o]);return {loadBundles:i,installSelected:l}}var lt={cursorDelta:0,confirm:false,back:false};function Io(e,t){return t.upArrow?{...lt,cursorDelta:-1}:t.downArrow?{...lt,cursorDelta:1}:t.escape?{...lt,back:true}:t.return?{...lt,confirm:true}:lt}var ta={cursorDelta:0,select:false};function Eo(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:ta}var To=ti.memo(function({bundle:t,isSelected:n}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:n?"cyan":"gray",children:n?"\u203A ":"\u25CB "}),jsx(Text,{bold:n,color:n?"cyan":"white",children:t.name}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});var _n=5;function Ao({onRetry:e}){let t=g(d=>d.bundles),n=g(d=>d.selectedBundleIndex),r=g(d=>d.isLoadingBundles),o=g(d=>d.bundlesError);if(r)return jsx(Ut,{message:"Loading bundles..."});if(o)return jsx(Nt,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Mt,{message:"No bundles available."});let s=Math.max(0,n-Math.floor(_n/2)),i=Math.min(t.length,s+_n);i===t.length&&(s=Math.max(0,i-_n));let l=t.slice(s,i),c=s,a=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a bundle to get started"})}),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",c," more above"]})}),l.map((d,h)=>jsx(To,{bundle:d,isSelected:s+h===n},d.slug)),a>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",a," more below"]})})]})}var Co=ti.memo(function({plugin:t,isCursor:n}){return jsxs(Box,{children:[jsx(Text,{color:n?"cyan":"gray",children:n?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:n,color:n?"cyan":"white",children:[" ",t.name]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var Vn=8;function Ro(){let e=g(a=>a.selectedBundle),t=g(a=>a.plugins),n=g(a=>a.pluginCursorIndex);if(!e)return jsx(Text,{dimColor:true,children:"No bundle selected."});let r=t.filter(a=>a.installed).length,o=Math.max(0,n-Math.floor(Vn/2)),s=Math.min(t.length,o+Vn);s===t.length&&(o=Math.max(0,s-Vn));let i=t.slice(o,s),l=o,c=t.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:e.name}),jsx(Text,{dimColor:true,children:e.description})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",r>0&&` \xB7 ${r} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),i.map((a,d)=>jsx(Co,{plugin:a,isCursor:o+d===n},a.name)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var la=["Retry failed","Continue anyway"];function ko({name:e,status:t,error:n}){return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(fi,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",e]})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",e]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),n&&jsxs(Text,{dimColor:true,children:[" \u2014 ",n]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",e]})})}function Bo({onComplete:e,onRetry:t}){let n=g(a=>a.plugins),r=g(a=>a.step),o=g(a=>a.successCount),s=g(a=>a.failedCount),i=g(a=>a.summaryActionIndex),l=n.filter(a=>a.selected),c=useRef(false);return useEffect(()=>{if(r==="summary"&&s===0&&!c.current){c.current=true;let a=setTimeout(e,1500);return ()=>clearTimeout(a)}},[r,s,e]),r==="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:l.map(a=>jsx(ko,{name:a.name,status:a.status,error:a.error},a.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:l.filter(a=>a.status==="failed").map(a=>jsx(ko,{name:a.name,status:a.status,error:a.error},a.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:la.map((a,d)=>jsx(Box,{children:jsxs(Text,{bold:d===i,color:d===i?"cyan":void 0,children:[d===i?"\u203A ":" ",a]})},a))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Lo(){let e=g(f=>f.step),t=g(f=>f.bundles),n=g(f=>f.selectedBundleIndex),r=g(f=>f.setSelectedBundleIndex),o=g(f=>f.selectBundle),s=g(f=>f.plugins),i=g(f=>f.pluginCursorIndex),l=g(f=>f.setPluginCursorIndex),c=g(f=>f.setStep),a=g(f=>f.summaryActionIndex),d=g(f=>f.setSummaryActionIndex),h=g(f=>f.failedCount),E=g(f=>f.resetForRetry),U=g(f=>f.goBackToList),j=p(f=>f.setScreen),u=p(f=>f.setFocus),m=p(f=>f.focus),y=X(f=>f.setJustAuthenticated),v=X(f=>f.justAuthenticated),{loadBundles:I,installSelected:B}=Po();useEffect(()=>{u(e==="bundleList"?"bundleList":e==="bundleDetail"?"bundleDetail":"installProgress");},[e,u]);let z=useCallback(async()=>{let f=g.getState().selectedBundle;if(f){let N=await F();N&&await Ae({...N,bundle:f.slug});}y(false),u("list"),j("main");},[y,u,j]),R=useCallback(()=>{E(),B();},[E,B]),pt=useCallback(()=>{I();},[I]),Yt=useCallback(()=>{u("list"),j("main");},[u,j]);return useInput((f,N)=>{N.escape?Yt():N.upArrow&&n>0?r(n-1):N.downArrow&&n<t.length-1?r(n+1):N.return&&t.length>0&&o(t[n]);},{isActive:m==="bundleList"}),useInput((f,N)=>{let Q=Io(f,N);if(Q.cursorDelta!==0){let se=i+Q.cursorDelta;se>=0&&se<s.length&&l(se);}Q.confirm&&(c("installing"),B()),Q.back&&U();},{isActive:m==="bundleDetail"}),useInput((f,N)=>{if(h===0)return;let Q=Eo(f,N);if(Q.cursorDelta!==0){let se=a+Q.cursorDelta;se>=0&&se<=1&&d(se);}Q.select&&(a===0?R():z());},{isActive:m==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Ct,{}),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."}),!v&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your bundle is not set up yet. Choose a bundle below to get your recommended starter kit."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="bundleList"&&jsx(Ao,{onRetry:pt}),e==="bundleDetail"&&jsx(Ro,{}),(e==="installing"||e==="summary")&&jsx(Bo,{onComplete:z,onRetry:R})]}),jsx(Dt,{})]})}var da={auth:Ir,bundleSetup:Lo,main:vo};async function No(){let e=await F(),t=await Z();if(!e||!t){p.getState().setScreen("auth"),p.getState().setFocus("auth");return}let{clientSecret:n,...r}=e;X.getState().setCredentials(r),!e.bundle||e.bundle.trim()===""?(p.getState().setScreen("bundleSetup"),p.getState().setFocus("bundleList")):(p.getState().setScreen("main"),p.getState().setFocus("list"));}function Fo(){let{columns:e,rows:t}=useWindowSize(),n=p(s=>s.screen),r=da[n],{pendingExit:o}=Zn();return r?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(r,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",n]})}var re=S("auth");function _o(){G.clearFallbackFile(),hr();}var pa=3,Oo=3,jo=` \u2139 The data collected during setup is used solely to improve
|
|
17
|
+
`);}function wt(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
18
|
+
`);}function X(e){process.stdout.write(JSON.stringify(e)+`
|
|
19
|
+
`);}function oe(e){process.stderr.write(JSON.stringify(e)+`
|
|
20
|
+
`);}function D(e){return e instanceof Error?e.message:String(e)}function En(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}function tc(e){if(!(e instanceof Error))return "unknown";let t=e.message.toLowerCase();return t.includes("401")||t.includes("unauthorized")?"invalid_credentials":t.includes("403")||t.includes("forbidden")?"forbidden":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("network")||t.includes("econnrefused")||t.includes("fetch")?"network_error":"unknown"}var he=["clientId","clientSecret","tenant"],nc={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function pi(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[n,r]=useState("clientId"),[o,i]=useState({}),[s,c]=useState(null),[a,l]=useState(false),u=useRef(0),{setCredentials:g,setJustAuthenticated:v}=ue(),{setFocus:d}=f();useInput((h,T)=>{if(!a){if(T.shift&&T.tab){let y=he.indexOf(n);y>0&&r(he[y-1]);}else if(T.tab){let y=he.indexOf(n);y<he.length-1&&r(he[y+1]);}else if(T.return)if(n==="tenant")E();else {let y=he.indexOf(n);r(he[y+1]);}}},{isActive:true});let E=async()=>{let h={};for(let T of he)e[T].trim()||(h[T]="This field is required");if(Object.keys(h).length>0){i(h);let T=he.find(y=>h[y]);T&&r(T);return}l(true),c(null),u.current+=1;try{await Qe({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()});let{clientSecret:T,...y}=e;g(y),v(!0),f.getState().setScreen("bundleSetup"),d("bundleList"),b(x.CLI_SESSION_STARTED,{cli_version:Be,os:process.platform,node_version:process.version,duration_ms:De(),interface:"tui"}).catch(()=>{});}catch(T){let y=T instanceof Error?T.message:"Authentication failed";c(y),ri(x.CLI_AUTH_FAILED,{error_code:tc(T),attempt:u.current},e.tenant.trim()).catch(()=>{});}finally{l(false),t(T=>({...T,clientSecret:""}));}},m=h=>T=>{t(y=>({...y,[h]:T})),o[h]&&i(y=>({...y,[h]:void 0}));};return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Ao," \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:he.map(h=>jsx(Box,{marginBottom:1,children:jsx(ui,{label:nc[h],value:e[h],onChange:m(h),masked:h==="clientSecret",isActive:n===h&&!a,error:o[h]})},h))}),a&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),s&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",p(s)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function kn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(oc,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",Be]})})]})}var $r={discover:"Discover",installed:"Installed"},ic=Object.keys($r);function hi(){let e=f(t=>t.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ic.map(t=>jsx(Box,{marginRight:1,children:t===e?jsx(Text,{bold:true,inverse:true,children:` ${$r[t]} `}):jsx(Text,{dimColor:true,children:` ${$r[t]} `})},t))})}var Y=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function wi(){let e=f(s=>s.focus),t=Y(s=>s.query),n=Y(s=>s.cursorPosition),r=e==="search",o=t.slice(0,n),i=t.slice(n);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:r?"cyan":"gray",children:"\u{1F50D} "}),r?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var cc=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...dt[e]})),uc=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...$o[e]}));function xi(){let e=f(r=>r.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("plugin"),n=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),cc.map(r=>{let o=!t&&e.types.has(r.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",r.key,"] "]}),jsxs(Text,{color:o?r.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",r.label]})]},r.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:n?"green":void 0,dimColor:!n,children:[n?"\u25C9":"\u25CB"," All"]})]}),uc.map(r=>{let o=!n&&e.origins.has(r.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",r.key,"] "]}),jsxs(Text,{color:o?r.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",r.label]})]},r.key)})]})}function Ii({type:e}){let{label:t,color:n}=dt[e];return jsx(Text,{color:n,children:t})}function Pi({origin:e}){return e===Ct?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var An=mc.memo(function({item:t,isSelected:n}){let r=t.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:n?"cyan":"gray",children:n?"\u203A ":"\u25CB "}),jsx(Text,{bold:n,color:n?"cyan":"white",children:t.name}),t.type&&jsxs(Text,{children:[" ",jsx(Ii,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Pi,{origin:t.origin})]}),jsxs(Text,{dimColor:true,children:[t.authorName?` \xB7 ${t.authorName}`:"",t.version?` \xB7 v${t.version}`:" \xB7 n/a"]}),t.status&&jsxs(Text,{color:r,children:[" [",t.status,"]"]}),t.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),t.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",En(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function It({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function ki({items:e,emptyMessage:t}){let n=f(a=>a.selectedIndex);if(e.length===0)return jsx(It,{message:t});let r=Math.max(0,n-Math.floor(Re/2)),o=Math.min(e.length,r+Re);o===e.length&&(r=Math.max(0,o-Re));let i=e.slice(r,o),s=r,c=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((a,l)=>jsx(An,{item:a,isSelected:r+l===n},a.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:c>0?`\u2193 ${c} more below`:" "})})]})}function $i({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function Ri({groups:e,emptyMessage:t}){let n=f(d=>d.selectedIndex),r=[],o=0;for(let d of e){r.push({kind:"header",label:d.label,pathHint:d.pathHint,key:`h-${d.scope}`});for(let E of d.items)r.push({kind:"item",item:E,itemIndex:o,key:`i-${d.scope}-${E.name}`}),o++;}if(o===0)return jsx(It,{message:t});let s=r.findIndex(d=>d.kind==="item"&&d.itemIndex===n),c=s>=0?s:0,a=Math.max(0,c-Math.floor(Re/2)),l=Math.min(r.length,a+Re);l===r.length&&(a=Math.max(0,l-Re));let u=r.slice(a,l),g=a,v=r.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),u.map(d=>d.kind==="header"?jsx($i,{label:d.label,pathHint:d.pathHint},d.key):jsx(An,{item:d.item,isSelected:d.itemIndex===n},d.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:v>0?`\u2193 ${v} more below`:" "})})]})}var xc={discover:"Discover",installed:"Installed"};function _i({items:e,tabId:t,emptyMessage:n,groups:r}){return jsxs(Box,{flexDirection:"column",children:[jsx(wi,{}),jsx(xi,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:xc[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),r&&r.length>0?jsx(Ri,{groups:r,emptyMessage:n}):jsx(ki,{items:e,emptyMessage:n})]})}function Oi({filteredItems:e,emptyMessage:t,groups:n}){let r=f(o=>o.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:r==="discover"?jsx(_i,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(_i,{items:e,tabId:"installed",emptyMessage:t,groups:n},"installed")})}var vc={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=Plugin | 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",bundleList:"\u2191\u2193: navigate | Enter: select bundle | Esc: skip",bundleDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select"};function $n(){let e=f(t=>t.focus);return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsx(Text,{dimColor:true,children:vc[e]})})}function Bi({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",p(e)]})}):null}function Ln({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ac,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Rn({message:e,onRetry:t,onBack:n}){return useInput((r,o)=>{r==="r"&&o.ctrl&&t?t():o.escape&&n&&n();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),n&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function at({itemName:e,actions:t,onAction:n,onClose:r}){let o=f(c=>c.focus),[i,s]=useState(0);return useInput((c,a)=>{a.upArrow?s(l=>l>0?l-1:l):a.downArrow?s(l=>l<t.length-1?l+1:l):a.return?n(t[i]):a.escape&&r();},{isActive:o==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((c,a)=>jsx(Box,{children:jsxs(Text,{bold:a===i,color:a===i?"cyan":void 0,children:[a===i?"\u203A ":" ",c]})},a))})]})}var Vi=Object.entries(At),Gi=[...Vi.map(([,e])=>e.actionLabel),"Cancel"];function zi(e){let t=Vi.find(([,n])=>n.actionLabel===e);return t?t[0]:null}function Wi({itemName:e,onInstall:t,onClose:n}){let[r,o]=useState(false),i=useCallback(l=>{let u=zi(l);u?t(u):o(false);},[t]),s=useCallback(()=>{o(false);},[]),c=useCallback(l=>{l==="Install"?o(true):n();},[n]);return r?jsx(at,{itemName:`${e} \u2014 Choose scope`,actions:Gi,onAction:i,onClose:s}):jsx(at,{itemName:e,actions:["Install","Cancel"],onAction:c,onClose:n})}function Mn({activeFocus:e,onConfirm:t}){let[n,r]=useState("idle"),o=f(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?r("idle"):i==="y"&&t();},{isActive:n==="confirming"&&o===e}),{isConfirming:n==="confirming",requestConfirm:()=>r("confirming"),cancelConfirm:()=>r("idle")}}function Zi({itemName:e,itemScope:t,itemStatus:n,updateAvailable:r,catalogVersion:o,onUninstall:i,onToggleStatus:s,onUpdate:c,onClose:a}){let{isConfirming:l,requestConfirm:u}=Mn({activeFocus:"actionMenu",onConfirm:()=>i(t)});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 g=n==="enabled"?"Disable":"Enable",v=o&&p(o),d=v?`Update to v${v}`:"Update";return jsx(at,{itemName:e,actions:r?["Uninstall",g,d,"Cancel"]:["Uninstall",g,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===g?s(t):h.startsWith("Update")?c?.():a();},onClose:a})}function ts({itemName:e,itemScope:t,onUninstall:n,onClose:r}){let{isConfirming:o,requestConfirm:i}=Mn({activeFocus:"actionMenu",onConfirm:()=>n(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(at,{itemName:e,actions:["Uninstall","Cancel"],onAction:a=>{a==="Uninstall"?i():r();},onClose:r})}async function ns(e,t){let n=N.resolve(t);await Se.mkdir(n,{recursive:true});let r=N.join(N.dirname(n),`${randomUUID()}.zip`);try{await Se.writeFile(r,e),await Nc(r,{dir:n,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let s=N.resolve(n,o.fileName);if(!s.startsWith(n+N.sep)&&s!==n)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(n);if(!o.startsWith(N.resolve(N.dirname(n))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await Se.unlink(r);}catch{}}}async function Ur(e){await Se.rm(e,{recursive:true,force:true});}async function Ue(){let e=Bo();await Se.mkdir(N.dirname(e),{recursive:true});try{await Se.writeFile(e,"",{flag:"wx"});}catch(n){if(n.code!=="EEXIST")throw n}return await Fc.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}var jc={user:"global",project:"project",local:"local"};function Dn(e){return e?jc[e]:"global"}var we=class extends Error{constructor(n,r){super(`${n} v${r} is already installed. Use --force to reinstall.`);this.pluginName=n;this.version=r;this.name="AlreadyInstalledError";}pluginName;version},je=class extends Error{constructor(n,r){super(`${n} is already up to date (v${r})`);this.pluginName=n;this.version=r;this.name="AlreadyUpToDateError";}pluginName;version};function Ht(){return $l.create({prefix:St("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Oe();e.headers.set("Authorization",`Bearer ${t}`);let n=await O();n?.tenant&&We.test(n.tenant)&&e.headers.set("FlowTenant",n.tenant);}]}})}var Jc=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function rs(e){if(!e||!Jc.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function xe(){try{let{plugins:e}=await Ht().get("v1/plugins/catalog").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 plugin catalog"):new Error(`Failed to fetch plugin catalog: ${e.message}`):e}}async function vt(e){rs(e);try{return await Ht().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function os(e){rs(e);try{let t=await Ht().get(`v1/plugins/${e}/archive`);return Buffer.from(await t.arrayBuffer())}catch(t){throw t instanceof Error?t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to download plugin: ${t.message}`):t}}async function Bn(){try{let{profiles:e}=await Ht().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 bundles"):new Error(`Failed to fetch bundles: ${e.message}`):e}}var Hc=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Vc=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function Nn(e){if(!Hc.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Gc(e){if(!Vc.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 Ke=S("installer");function zc(e,t){let n=`${e}@${_}`,o=Ce().plugins[n];if(o&&!t)throw new we(e,o[0].version??"unknown");return {pluginKey:n,alreadyInstalled:o}}async function qc(e,t,n){n&&await Ur(t);try{Ke.debug(`[${t}] Extracting archive...`),await ns(e,t);}catch(r){throw await Ur(t),r}}function Wc(e,t,n,r,o){let i=Ce(),s={scope:r,installPath:t,version:n,installedAt:new Date().toISOString(),origin:o},c=i.plugins[e]??[];i.plugins[e]=[...c.filter(a=>a.scope!==r),s],lt(i),jr(e,true,r);}async function Xc(e,t,n,r,o){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:r,version:t,duration_ms:n,interface:$().interfaceType});}catch(i){Ke.warn(`Failed to send install metrics: ${String(i)}`);}}async function Yc(e,t,n){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:n,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:$().interfaceType});}catch(r){Ke.warn(`Failed to send install-failed metrics: ${String(r)}`);}}async function Ie(e,t={}){let n=Date.now(),r=null;try{Ke.debug(`[${e}] Acquiring lock...`),r=await Ue();let{pluginKey:o,alreadyInstalled:i}=zc(e,t.force);Ke.debug(`[${e}] Fetching manifest...`);let s=await vt(e);Nn(s.name),Gc(s.version),Ke.debug(`[${e}] Downloading archive...`);let c=await os(e),a=t.scope??"user",l=_o(s.name,s.version);await qc(c,l,!!i&&!!t.force),Wc(o,l,s.version,a,"internal"),is(s,l);let u=Date.now()-n;Ke.debug(`[${e}] Installed successfully in ${u}ms`);let g={name:s.name,version:s.version,path:l,duration_ms:u};return t.skipMetrics||await Xc(s.name,s.version,u,Dn(a),"internal"),g}catch(o){throw await Yc(e,o,"internal"),Ke.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{r&&await r();}}function Zc(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:_,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function ls(){let e=an();if(!G__default.existsSync(e))return null;try{return JSON.parse(G__default.readFileSync(e,"utf-8"))}catch{return null}}function Qc(){let e=ls();if(e)return e;let t=Zc(),n=an();return G__default.mkdirSync(N__default.dirname(n),{recursive:true}),Kr(t),t}function Kr(e){let t=an(),n=`${t}.${randomUUID()}.tmp`;G__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),G__default.renameSync(n,t);}function eu(){let e=Oo(),t={};try{G__default.existsSync(e)&&(t=JSON.parse(G__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[_])return;t[_]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:Do(),lastUpdated:new Date().toISOString()};let n=`${e}.${randomUUID()}.tmp`;G__default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8"),G__default.renameSync(n,e);}function is(e,t){Nn(e.name),eu();let n=fr(e.name);G__default.mkdirSync(N__default.dirname(n),{recursive:true});try{G__default.lstatSync(n),G__default.rmSync(n,{recursive:!0,force:!0});}catch{}G__default.symlinkSync(t,n);let r=Qc();r.plugins.some(i=>i.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}),Kr(r));}function Jr(e){Nn(e);let t=fr(e);try{G__default.rmSync(t,{recursive:!0,force:!0});}catch{}let n=ls();if(!n)return;let r=n.plugins.length;n.plugins=n.plugins.filter(o=>o.name!==e),n.plugins.length!==r&&Kr(n);}var nu=S("mcpConfigReader"),ru=500,ou=512;function iu(){return N__default.join(ge__default.homedir(),".claude.json")}function su(){return N__default.join(process.cwd(),".mcp.json")}function us(e){if(!G__default.existsSync(e))return null;try{return JSON.parse(G__default.readFileSync(e,"utf-8"))}catch{return nu.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hr(e){if(!Vt(e))return {};let t=e.mcpServers;return Vt(t)?t:{}}function Vr(e,t){return Object.keys(e).slice(0,ru).map(r=>({name:p(r.slice(0,ou)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function ds(){let e=[],t=iu(),n=us(t);if(Vt(n)){let c=n,a=Hr(c);e.push(...Vr(a,"user"));let l=process.cwd();if(Vt(c.projects)){let u=c.projects[l];if(Vt(u)){let g=Hr(u);e.push(...Vr(g,"local"));}}}let r=su(),o=us(r),i=Hr(o);e.push(...Vr(i,"project"));let s=new Map;for(let c of e){let a=`${c.name}@${c.scope}`;s.has(a)||s.set(a,c);}return [...s.values()]}var se=S("storage");async function lu(e,t){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:$().interfaceType});}catch(n){se.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function cu(e,t,n){let r=t==="enabled"?x.CLI_TOOL_ENABLED:x.CLI_TOOL_DISABLED;b(r,{tool_id:e,source:n,interface:$().interfaceType}).catch(o=>se.warn(`Failed to send ${t} metrics: ${String(o)}`));}function fs(){return N__default.join(ge__default.homedir(),".claude","plugins","installed_plugins.json")}function uu(){return N__default.join(ge__default.homedir(),".claude","plugins")}function ms(e){let t=N__default.resolve(e),n=N__default.resolve(uu()),r=N__default.resolve(N__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(n+N__default.sep)||t===n,i=t.startsWith(r+N__default.sep)||t===r;if(!o&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function gs(e="user"){return e==="local"?N__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?N__default.join(process.cwd(),".claude","settings.json"):N__default.join(ge__default.homedir(),".claude","settings.json")}function Ce(){let e=fs();if(!G__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(G__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}function pu(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function ys(e,t){try{G__default.mkdirSync(N__default.dirname(e),{recursive:!0});let n=`${e}.${randomUUID()}.tmp`;G__default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8"),G__default.renameSync(n,e);}catch(n){throw pu(n)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):n}}function lt(e){ys(fs(),e);}function Gt(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function du(e,t){let n=N__default.join(e,".claude-plugin"),r=N__default.join(n,"plugin.json");if(G__default.existsSync(r))try{return JSON.parse(G__default.readFileSync(r,"utf-8"))}catch{return null}let o=N__default.join(n,"marketplace.json");if(G__default.existsSync(o))try{let i=JSON.parse(G__default.readFileSync(o,"utf-8"));return {description:i.plugins?.find(c=>c.name===t)?.description,author:i.owner}}catch{return null}return null}function Wr(e="user"){let t=gs(e);if(!G__default.existsSync(t))return {};try{return JSON.parse(G__default.readFileSync(t,"utf-8"))}catch{return {}}}function hs(e,t="user"){ys(gs(t),e);}function mu(e,t){let{name:n,marketplace:r}=Gt(e),o;if(r?(o=`${n}@${r}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Gt(s).name===n)[0],!o)throw se.error(`[${n}] Plugin is not installed`),new Error(`Plugin '${n}' is not installed`);return {key:o,name:n}}function fu(e,t){let{name:n,marketplace:r}=Gt(e),o;return r?(o=`${n}@${r}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Gt(s).name===n)[0],o?{key:o,name:n}:null}function Gr(e="user"){return Wr(e).enabledPlugins??{}}function zr(e,t="user"){let n=Wr(t),r=n.enabledPlugins;if(!r||!(e in r))return;let{[e]:o,...i}=r;n.enabledPlugins=i,hs(n,t);}function jr(e,t,n="user"){let r=Wr(n),o=r.enabledPlugins??{};r.enabledPlugins={...o,[e]:t},hs(r,n);}function gu(e){let t=new Map;for(let n of e){let r=t.get(n.scope);(!r||n.installedAt>r.installedAt)&&t.set(n.scope,n);}return [...t.values()]}function be(){let e=Ce(),t=Gr(),n=Gr("project"),r=Gr("local"),o={project:n,local:r},i=Object.entries(e.plugins).flatMap(([l,u])=>{let{name:g,marketplace:v}=Gt(l),d=u.map(m=>m.scope==="managed"?{...m,scope:"user"}:m);return gu(d).map(m=>{let h=du(m.installPath,g),y=(o[m.scope]??t)[l];return {name:g,marketplace:v,version:m.version&&m.version!=="unknown"?m.version:void 0,installedAt:m.installedAt,installPath:m.installPath,scope:m.scope,description:h?.description,author:h?.author,status:y===false?"disabled":"enabled"}})}),s=ds(),c=new Set(i.map(l=>`${l.name}@${l.scope}`)),a=s.filter(l=>!c.has(`${l.name}@${l.scope}`));return [...i,...a]}async function Fn(e,t){se.debug(`[${e}] Acquiring lock to uninstall`);let n=await Ue();try{let r=Ce(),o=fu(e,r.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:i,name:s}=o,c=r.plugins[i];if(t){let a=c.find(g=>g.scope===t);if(!a)throw new Error(`Plugin '${s}' is not installed in ${t} scope`);se.debug(`[${s}] Resolved key: ${i}, scope: ${t}`),ms(a.installPath);let l=N__default.dirname(a.installPath);se.debug(`[${s}] Removing directory: ${l}`),G__default.rmSync(l,{recursive:!0,force:!0});let u=c.filter(g=>g.scope!==t);if(u.length===0){let{[i]:g,...v}=r.plugins;lt({...r,plugins:v}),zr(i,t),Jr(s);}else r.plugins[i]=u,lt(r),zr(i,t);}else {se.debug(`[${s}] Resolved key: ${i}`);for(let u of c){ms(u.installPath);let g=N__default.dirname(u.installPath);se.debug(`[${s}] Removing directory: ${g}`),G__default.rmSync(g,{recursive:!0,force:!0}),zr(i,u.scope);}Jr(s);let{[i]:a,...l}=r.plugins;lt({...r,plugins:l});}await lu(s,c[0].origin??"internal"),se.debug(`[${s}] Uninstalled successfully`);}finally{await n();}}async function zt(e,t,n){se.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let r=await Ue();try{let o=Ce(),{key:i,name:s}=mu(e,o.plugins),c=o.plugins[i],a=n??c[0].scope,l=c[0].origin??"internal";se.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),jr(i,t==="enabled",a),cu(s,t,l),se.debug(`[${s}] Status updated to ${t}`);}finally{await r();}}var U=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:be()})}));var B=["discover","installed"];function Ss(e,t,n){if(t.rightArrow||t.tab){let r=B.indexOf(n.activeTab);return [{type:"setTab",tab:B[(r+1)%B.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}if(t.leftArrow){let r=B.indexOf(n.activeTab);return [{type:"setTab",tab:B[(r-1+B.length)%B.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}return t.downArrow?[{type:"setFocus",focus:"list"}]:[]}function ws(e,t,n,r){if(t.upArrow)return n.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:n.selectedIndex-1}];if(t.downArrow&&n.selectedIndex<r-1)return [{type:"setSelectedIndex",index:n.selectedIndex+1}];if(t.leftArrow){let o=B.indexOf(n.activeTab);return [{type:"setTab",tab:B[(o-1+B.length)%B.length]},{type:"setSelectedIndex",index:0}]}if(t.rightArrow){let o=B.indexOf(n.activeTab);return [{type:"setTab",tab:B[(o+1)%B.length]},{type:"setSelectedIndex",index:0}]}if(t.tab){let o=B.indexOf(n.activeTab);return [{type:"setTab",tab:B[(o+1)%B.length]},{type:"setSelectedIndex",index:0}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function xs(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Is(e,t,n){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?n.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}function jn(e){let{setActiveTab:t,setFocus:n,setSelectedIndex:r,setActionMenuOpen:o}=f.getState();for(let i of e)if(i.type==="setTab")t(i.tab);else if(i.type==="setFocus")n(i.focus);else if(i.type==="setSelectedIndex")r(i.index);else if(i.type==="setActionMenuOpen")o(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:c,setCursorPosition:a,cursorPosition:l}=Y.getState();s(c.slice(0,l)+i.char+c.slice(l)),a(l+i.char.length);}else i.type==="toggleTypeFilter"?f.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?f.getState().selectAllTypes():i.type==="toggleOriginFilter"?f.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&f.getState().selectAllOrigins();}function bs({listLength:e}){let t=f(m=>m.focus),n=f(m=>m.selectedIndex),r=f(m=>m.actionMenuOpen),o=f(m=>m.setFocus),i=f(m=>m.setActionMenuOpen),s=Y(m=>m.query),c=Y(m=>m.setQuery),a=Y(m=>m.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:m,setCursorPosition:h}=Y.getState();h(m.length);}},[t]);let[u,g]=useState("");useEffect(()=>{let m=setTimeout(()=>g(s),300);return ()=>clearTimeout(m)},[s]),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();jn(Ss(m,h,{activeTab:T}));},{isActive:t==="tabs"}),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();jn(ws(m,h,{activeTab:T,selectedIndex:y},l.current));},{isActive:t==="list"}),useInput((m,h)=>{jn(xs(m,h));},{isActive:t==="actionMenu"}),useInput((m,h)=>{let T=Is(m,h,Y.getState().query),y=T.queryUpdate;if(jn(T.actions),y==="reset")a(),g("");else if(y!==null){let{query:L,cursorPosition:A,setCursorPosition:J}=Y.getState();if("backspace"in y)A>0&&(c(L.slice(0,A-1)+L.slice(A)),J(A-1));else if("append"in y)c(L.slice(0,A)+y.append+L.slice(A)),J(A+y.append.length);else if("cursorMove"in y){let q=A+y.cursorMove;q>=0&&q<=L.length&&J(q);}}},{isActive:t==="search"});let v=useCallback(()=>{i(false),o("list");},[i,o]),d=useCallback(m=>{let{setSelectedIndex:h,selectedIndex:T}=f.getState();m===0?h(0):T>=m&&h(m-1);},[]),E=useCallback(m=>{if(!u)return l.current=m.length,m;let h=u.toLowerCase(),T=m.filter(y=>y.name.toLowerCase().includes(h)||y.description?.toLowerCase().includes(h));return l.current=T.length,T},[u]);return {actionMenuOpen:r,closeMenu:v,selectedIndex:n,clampIndex:d,filteredItems:E}}function Ps(){let e=f(c=>c.notification),t=f(c=>c.showNotification),n=f(c=>c.clearNotification),r=ue(c=>c.justAuthenticated),o=ue(c=>c.credentials),i=ue(c=>c.setJustAuthenticated);return useEffect(()=>{r&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),i(false));},[r,o]),useEffect(()=>{if(!e)return;let c=setTimeout(n,3e3);return ()=>clearTimeout(c)},[e]),{notify:(c,a)=>{t(c,a);}}}function Ae(e,t,n=false){return n?true:!Zr.valid(e)||!Zr.valid(t)?false:Zr.gt(t,e)}var $e=S("updater");async function wu(e,t,n,r,o){try{await b(x.CLI_TOOL_UPDATED,{tool_id:e,tool_type:"plugin",source:o,from_version:t,to_version:n,duration_ms:r,interface:$().interfaceType});}catch(i){$e.warn(`Failed to send update metrics: ${String(i)}`);}}function xu(e){let t=Ce(),n=`${e}@${_}`,r=t.plugins[n];return !r||r.length===0?null:{pluginKey:n,entry:r[0]}}async function Kn(e,t={}){let n=Date.now(),r=null;try{$e.debug(`[${e}] Acquiring lock...`),r=await Ue();let o=xu(e);if(!o)throw $e.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=o,s=i.version,c=i.installPath;$e.debug(`[${e}] Fetching manifest...`);let l=(await vt(e)).version;if(!s||!Ae(s,l,t.force))throw $e.debug(`[${e}] Already up to date (v${s??"n/a"})`),new je(e,s??"unknown");$e.info(`[${e}] Updating v${s} \u2192 v${l}...`),await r(),r=null;try{let u=await Ie(e,{force:!0,skipMetrics:!0}),g=Date.now()-n;return await wu(u.name,s,u.version,g,i.origin??"internal"),$e.debug(`[${e}] Updated successfully in ${g}ms`),{name:u.name,previousVersion:s,newVersion:u.version,path:u.path,duration_ms:g}}catch(u){$e.warn(`[${e}] Install failed, rolling back to v${s}...`),r=await Ue();let g=Ce(),v=`${e}@${_}`;throw g.plugins[v]&&(g.plugins[v][0].version=s,g.plugins[v][0].installPath=c,lt(g),$e.info(`[${e}] Rollback completed, restored to v${s}`)),u}}finally{r&&await r();}}var Iu=S("commands:helpers");async function Q(){let e=await O();if(!e)return k("Not authenticated. Run: flow auth login"),false;try{await Oe();}catch(t){return Iu.debug(`Token validation failed: ${String(t)}`),k("Session expired. Run: flow auth login"),false}return !e.bundle||e.bundle.trim()===""?(k("Bundle not set. Run: flow auth login"),false):true}async function Je(e){let t=Qr.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(p(e),r=>{t.close(),n(["y","yes"].includes(r.toLowerCase().trim()));});})}async function Es(e){let t=Qr.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(p(e),r=>{t.close(),n(r.trim());});})}var bu=/^[^@]+@[^@]+$/;function qt(e){return bu.test(e)}function Pt(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var vu=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Ts(e){if(!vu.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.`)}var Pu=/^[\w./:@?&=+#%-]+$/;function Jn(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Pu.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Wt=S("claudeProxy"),no="claude ",ks="flow ",eo=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},to=class extends Error{constructor(t){super(`Disallowed subcommand: "${t}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},Eu=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/;function Tu(e){As(e);let t=e.slice(no.length);if(!Eu.test(t))throw new to(e)}var Hn=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}};function As(e){if(!e||!/^claude /.test(e))throw new eo(e)}async function ae(e){As(e);let t=e.slice(no.length).split(/\s+/).filter(Boolean),n=ku(t);Wt.debug(`[${n}] Executing proxy command: claude ${t.join(" ")}`);let r=Date.now();try{let o=await execa("claude",t,{reject:!1}),i=Date.now()-r;return Wt.debug(`[${n}] Proxy command finished with exit code ${o.exitCode} in ${i}ms`),{name:n,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:i}}catch(o){throw $s(o)?new Hn:o}}function ku(e){return e.length>=3?e[2]:e.join(" ")}function $s(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Cu(e){return e.startsWith(ks)?no+e.slice(ks.length):e}var Au=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function $u(e,t){return !t||e.includes("--scope")||!Au.test(e)?e:`${e} --scope ${t}`}async function Ls(e,t){let n=e.split("&&").map(o=>Cu(o.trim())).filter(Boolean).map(o=>$u(o,t));if(n.length===0)throw new Error("Empty install command");for(let o of n)Tu(o);Wt.debug(`[installCommand] Executing ${n.length} command(s)`);let r=await ae(n[0]);if(r.exitCode!==0)return r;for(let o=1;o<n.length;o++)if(r=await ae(n[o]),r.exitCode!==0)return r;return r}async function Rs(e,t,n){let r=Pt(e),o=t?.trim();if(!o&&(o=(await Es(`Plugin "${r}" could not be installed.
|
|
21
|
+
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Jn(o),n?.(),Wt.debug(`[${r}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let i=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(i.exitCode!==0)throw new Error(`Failed to add marketplace: ${i.stderr||"unknown error"}`);Wt.debug(`[${r}] Marketplace added successfully`);}catch(i){throw $s(i)?new Hn:i}}var He=S("installDispatcher");async function Ms(e,t,n){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:"external",scope:Dn(n),version:"unknown",duration_ms:t,interface:$().interfaceType});}catch(r){He.warn(`Failed to send external install metrics: ${String(r)}`);}}async function _s(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:$().interfaceType});}catch(n){He.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}function ro(e,t){let n=Pt(e);Ts(n);let r=["claude","plugin","install",n];return t&&r.push("--scope",t),r.join(" ")}async function oo(e,t,n,r){let o=ro(e,r),i=Pt(e);n?.onStatus?.(`Installing ${i}...`),He.debug(`[${e}] Attempting install: ${o}`);let s=await ae(o);return s.exitCode===0?s:(He.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`),n?.onError?.(s.stderr||`Install failed with exit code ${s.exitCode}`),t?n?.onStatus?.(`Adding marketplace for ${i}...`):n?.onPause?.(),await Rs(e,t,()=>{t||n?.onResume?.(`Adding marketplace for ${i}...`);}),n?.onResume?.(`Retrying install for ${i}...`),He.debug(`[${e}] Retrying install after marketplace add`),ae(o))}async function Os(e,t){if(e.origin===on&&e.installCommand){He.debug(`[${e.name}] Routing to external installer via installCommand`);let n=await Ls(e.installCommand,t?.scope);return n.exitCode===0?await Ms(e.name,n.duration_ms,t?.scope):await _s(e.name,new Error(n.stderr||"Install failed")),n}if(qt(e.name)){He.debug(`[${e.name}] Routing to external installer via name pattern`);let n=await oo(e.name,t?.marketplaceSource,void 0,t?.scope);return n.exitCode===0?await Ms(e.name,n.duration_ms,t?.scope):await _s(e.name,new Error(n.stderr||"Install failed")),n}return He.debug(`[${e.name}] Routing to internal installer`),Ie(e.name,t)}function Ds(e){return "exitCode"in e}function Bs(){let e=U(s=>s.installedItems),t=U(s=>s.setInstalledItems),n=useCallback(async(s,c)=>{let a=await Os(s,c);if(Ds(a)&&a.exitCode!==0)throw new Error(a.stderr||"External installation failed");U.getState().loadFromDisk();},[]),r=useCallback(async(s,c)=>{await Fn(s,c),t(e.filter(a=>a.name!==s));},[e,t]),o=useCallback(async(s,c)=>{let l=e.find(u=>u.name===s)?.status==="enabled"?"disabled":"enabled";await zt(s,l,c),t(e.map(u=>u.name===s?{...u,status:l}:u));},[e,t]),i=useCallback(async s=>{await Kn(s),U.getState().loadFromDisk();},[]);return {install:n,uninstall:r,toggle:o,update:i}}var Gn=S("mcp");function Xt(e,t){e.silent?oe({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):k(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Fs(e,t){e.silent?X({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(V(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&I(t.stdout));}function Lu(e,t,n,r){let o=["claude","mcp","add","--transport",n,e];return t.length>0&&o.push(...t),r&&o.push("--scope",r),o.join(" ")}function io(e,t){let n=["claude","mcp","remove",e];return t&&n.push("--scope",t),n.join(" ")}async function Us(e,t,n){if(!await Q())return 1;if(t.length===0){let i=n.transport==="http"?"a URL":"a command";return Xt(n,{name:e,action:"add",message:`${n.transport} transport requires ${i}`}),1}Gn.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let r=Lu(e,t,n.transport,n.scope);if(!n.force){let i=p(e),s=p(r);if(!await Je(`Install external MCP "${i}"?
|
|
22
|
+
This will run: ${s}
|
|
23
|
+
[y/N] `))return Gn.debug(`[${e}] Installation cancelled by user`),I("Operation cancelled."),0}let o=n.silent?void 0:vo({text:`Adding MCP "${p(e)}"...`}).start();try{let i=await ae(r);return o?.stop(),i.exitCode!==0?(Xt(n,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!n.silent&&n.verbose&&i.stdout&&I(`stdout: ${i.stdout}`),1):(Fs(n,{name:e,actionPastTense:"added",command:r,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return o?.stop(),Xt(n,{name:e,action:"add",message:D(i)}),1}}async function js(e,t){if(!await Q())return 1;Gn.debug(`[${e}] Starting MCP remove`);let n=io(e,t.scope);if(!t.force){let o=p(e),i=p(n);if(!await Je(`Remove MCP "${o}"?
|
|
24
|
+
This will run: ${i}
|
|
25
|
+
[y/N] `))return Gn.debug(`[${e}] Removal cancelled by user`),I("Operation cancelled."),0}let r=t.silent?void 0:vo({text:`Removing MCP "${p(e)}"...`}).start();try{let o=await ae(n);return r?.stop(),o.exitCode!==0?(Xt(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&I(`stdout: ${o.stdout}`),1):(Fs(t,{name:e,actionPastTense:"removed",command:n,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return r?.stop(),Xt(t,{name:e,action:"remove",message:D(o)}),1}}function Ks({selectedItem:e,selectedCatalogItem:t,items:n,closeMenu:r,clampIndex:o,notify:i}){let s=S("pluginHandlers"),c=f(y=>y.setLoading),{install:a,uninstall:l,toggle:u,update:g}=Bs(),v=async(y,L,A)=>{c(true,y),r();try{await L(),o(n.length),i(A,"success");}catch(J){let q=J instanceof Error?J.message:"Something went wrong";s.error(`[withLoading] ${y} failed: ${q}`),i(q,"error");}finally{c(false);}};return {handleInstall:y=>{e&&t&&v(`Installing ${e.name}...`,()=>a(t,{scope:y}),"\u2713 Installed successfully");},handleUninstall:y=>{e&&v(`Uninstalling ${e.name}...`,()=>l(e.name,y),"\u2713 Uninstalled");},handleToggleStatus:y=>{if(!e)return;let L=e.status==="enabled";v(L?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,y),L?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let y=t?` to v${t.version}`:"";(async()=>{c(true,`Updating ${e.name}${y}...`),r();try{await g(e.name),o(n.length),i(`\u2713 Updated ${e.name}${y}`,"success");}catch(A){if(A instanceof je)i(A.message,"info");else {let J=A instanceof Error?A.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${J}`),i(J,"error");}}finally{c(false);}})();},handleMcpConfigUninstall:y=>{e&&v(`Removing MCP ${e.name}...`,async()=>{let L=io(e.name,y),A=await ae(L);if(A.exitCode!==0)throw new Error(A.stderr||"MCP removal failed");U.getState().loadFromDisk();},"\u2713 MCP removed");}}}var Yt=["local","project","user"],Ru=new Set(["--transport","--scope","-s"]);function Js(e){let t=e.split(/\s+/).filter(Boolean),n=t.indexOf("add");if(n===-1)return null;let r=n+1;for(;r<t.length;){let o=t[r];if(Ru.has(o))r+=2;else if(o.startsWith("-"))r+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Zt(e,t){return t?`${e}::${t}`:e}function so(e){return e===_?Ct:on}function Hs(e){return {name:p(e.name),version:e.version?p(e.version):e.version,description:e.description?p(e.description):e.description,authorName:e.author.name?p(e.author.name):e.author.name,updateAvailable:e.updateAvailable,type:e.type??"plugin",origin:e.origin??Ct}}function Vs(e,t){let n=so(e.marketplace);return {name:p(e.name),version:e.version?p(e.version):e.version,description:e.description?p(e.description):e.description,authorName:e.author?.name?p(e.author.name):e.author?.name,status:e.status,scope:e.scope,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"plugin",origin:t?.origin??n}}function Gs(e){let t=new Map;for(let n of e){if(!n.scope)continue;let r=t.get(n.scope)??[];r.push(n),t.set(n.scope,r);}return Yt.filter(n=>t.has(n)).map(n=>({scope:n,label:At[n].label,pathHint:At[n].pathHint,items:t.get(n)??[]}))}function zs(e){let t=n=>{if(!n)return 1/0;let r=Yt.indexOf(n);return r===-1?1/0:r};return [...e].sort((n,r)=>t(n.scope)-t(r.scope))}function qs({catalog:e,installedItems:t,activeTab:n,catalogFilters:r,searchQuery:o}){let i=useMemo(()=>new Set(t.map(d=>Zt(d.name,d.author?.name))),[t]),s=useMemo(()=>new Set(t.filter(d=>d.type==="mcp").map(d=>d.name.toLowerCase())),[t]),c=useMemo(()=>{let d=new Map(e.map(E=>[Zt(E.name,E.author.name),E]));return t.map(E=>{let m=d.get(Zt(E.name,E.author?.name)),h=m?.version,T=!!h&&!!E.version&&Ae(E.version,h);return {...E,updateAvailable:T,catalogItem:m}})},[t,e]),a=useMemo(()=>n==="discover"?e.filter(d=>{if(i.has(Zt(d.name,d.author.name)))return false;if(d.type==="mcp"){let E=d.installCommand?Js(d.installCommand)?.toLowerCase():null;if(s.has(d.name.toLowerCase())||E&&s.has(E))return false}return true}).map(d=>Hs(d)):c.map(d=>Vs(d,d.catalogItem)),[n,e,i,s,c]),l=useMemo(()=>a.filter(d=>{let E=d.type??"plugin";if(!r.types.has(E))return false;let m=d.origin??"internal";return r.origins.has(m)}),[a,r]),u=useMemo(()=>{let{types:d}=r;if(d.size===1){if(d.has("skill"))return "skills";if(d.has("mcp"))return "MCPs";if(d.has("plugin"))return "plugins"}return "items"},[r]),g=useMemo(()=>n==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[n,o,u]),v=useMemo(()=>d=>d?e.find(E=>E.name===d.name&&E.author.name===d.authorName)??null:null,[e]);return {items:l,emptyMessage:g,getSelectedCatalogItem:v}}function Ws(){let[e,t]=useState([]),[n,r]=useState(true),[o,i]=useState(null),s=useRef(false),c=useCallback(async()=>{r(true),i(null);try{let a=await xe();t(a),s.current||(s.current=!0,b(x.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:a.length}).catch(()=>{}));}catch(a){i(a instanceof Error?a:new Error(String(a))),t([]);}finally{r(false);}},[]);return useEffect(()=>{c();},[c]),{catalog:e,isLoading:n,error:o,refetch:c}}function Xs(){return {items:U(t=>t.installedItems)}}var Bu=S("catalog");function Ys(){let e=f(R=>R.activeTab),t=f(R=>R.notification),n=f(R=>R.loading),r=f(R=>R.loadingMessage),o=f(R=>R.catalogError),i=f(R=>R.setCatalogError),s=f(R=>R.catalogFilters),c=Y(R=>R.query),{catalog:a,isLoading:l,error:u,refetch:g}=Ws(),{items:v}=Xs(),d=U(R=>R.loadFromDisk),{items:E,emptyMessage:m,getSelectedCatalogItem:h}=qs({catalog:a,installedItems:v,activeTab:e,catalogFilters:s,searchQuery:c}),{actionMenuOpen:T,closeMenu:y,selectedIndex:L,clampIndex:A,filteredItems:J}=bs({listLength:E.length}),q=J(E),Ee=useMemo(()=>e!=="installed"?q:zs(q),[e,q]),lr=useMemo(()=>e==="installed"?Gs(Ee):[],[e,Ee]),H=Ee[L]??null,w=useMemo(()=>h(H),[h,H]),{notify:te}=Ps(),{handleInstall:K,handleUninstall:F,handleToggleStatus:cr,handleUpdate:ur,handleMcpConfigUninstall:Co}=Ks({selectedItem:H,selectedCatalogItem:w,items:E,closeMenu:y,clampIndex:A,notify:te});return useEffect(()=>{d();},[]),useEffect(()=>{A(Ee.length);},[Ee.length,A]),useEffect(()=>{u&&(Bu.error(`[catalog] ${u instanceof Error?u.message:String(u)}`),i("Failed to load catalog"));},[u]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(kn,{}),jsx(hi,{}),jsx(Oi,{filteredItems:Ee,groups:lr,emptyMessage:m}),(n||l)&&jsx(Ln,{message:n?r:"Loading catalog..."}),o&&!l&&e==="discover"&&jsx(Rn,{message:o,onRetry:()=>{i(null),g();},onBack:()=>i(null)}),t&&jsx(Bi,{message:t.message,type:t.type}),T&&H&&(e==="discover"?jsx(Wi,{itemName:H.name,onInstall:K,onClose:y}):H.type==="mcp"?jsx(ts,{itemName:H.name,itemScope:H.scope??"user",onUninstall:Co,onClose:y}):jsx(Zi,{itemName:H.name,itemScope:H.scope??"user",itemStatus:H.status??"enabled",updateAvailable:H.updateAvailable??false,catalogVersion:w?.version,onUninstall:F,onToggleStatus:R=>cr(R),onUpdate:ur,onClose:y})),jsx($n,{})]})}var P=create((e,t)=>({bundles:[],selectedBundleIndex:0,selectedBundle:null,plugins:[],pluginCursorIndex:0,step:"bundleList",isLoadingBundles:false,bundlesError:null,successCount:0,failedCount:0,summaryActionIndex:0,setBundles:n=>e({bundles:n}),setSelectedBundleIndex:n=>e({selectedBundleIndex:n}),selectBundle:n=>{let r=new Set(U.getState().installedItems.map(o=>o.name));e({selectedBundle:n,plugins:n.plugins.map(o=>({name:o,selected:true,status:r.has(o)?"success":"pending",installed:r.has(o)})),pluginCursorIndex:0,step:"bundleDetail"});},setPluginCursorIndex:n=>e({pluginCursorIndex:n}),setStep:n=>e({step:n}),setPluginStatus:(n,r,o)=>{let i=t().plugins.map(s=>s.name===n?{...s,status:r,error:o}:s);e({plugins:i});},setIsLoadingBundles:n=>e({isLoadingBundles:n}),setBundlesError:n=>e({bundlesError:n}),setSummaryActionIndex:n=>e({summaryActionIndex:n}),computeSummary:()=>{let r=t().plugins.filter(o=>o.selected);e({successCount:r.filter(o=>o.status==="success").length,failedCount:r.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let n=t().plugins.map(r=>r.status==="failed"?{...r,status:"pending",error:void 0}:r);e({plugins:n,step:"installing"});},goBackToList:()=>e({selectedBundle:null,plugins:[],pluginCursorIndex:0,step:"bundleList"})}));var ju=3;function Qs(){let e=P(a=>a.setBundles),t=P(a=>a.setIsLoadingBundles),n=P(a=>a.setBundlesError),r=P(a=>a.setPluginStatus),o=P(a=>a.setStep),i=P(a=>a.computeSummary),s=useCallback(async()=>{t(true),n(null);try{let a=await Bn();e(a);}catch(a){n(a instanceof Error?a.message:String(a));}finally{t(false);}},[t,n,e]);useEffect(()=>{U.getState().loadFromDisk(),s();},[s]);let c=useCallback(async()=>{let a=P.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of a){r(u.name,"installing");let g="",v=false;for(let d=1;d<=ju;d++)try{await Ie(u.name),r(u.name,"success"),v=!0;break}catch(E){if(E instanceof we){r(u.name,"success"),v=true;break}g=E instanceof Error?E.message:"Unknown error";}v||(r(u.name,"failed",g),b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"plugin",source:"internal",error_code:"install_failed",error_message:g,interface:$().interfaceType}).catch(()=>{}));}let l=tt();et("summary_review"),b(x.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:l}).catch(()=>{}),U.getState().loadFromDisk(),i(),o("summary");},[r,i,o]);return {loadBundles:s,installSelected:c}}var Qt={cursorDelta:0,confirm:false,back:false};function ea(e,t){return t.upArrow?{...Qt,cursorDelta:-1}:t.downArrow?{...Qt,cursorDelta:1}:t.escape?{...Qt,back:true}:t.return?{...Qt,confirm:true}:Qt}var Ku={cursorDelta:0,select:false};function ta(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:Ku}var na=mc.memo(function({bundle:t,isSelected:n}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:n?"cyan":"gray",children:n?"\u203A ":"\u25CB "}),jsx(Text,{bold:n,color:n?"cyan":"white",children:p(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:p(t.description)})})]})});var fo=5;function ra({onRetry:e}){let t=P(u=>u.bundles),n=P(u=>u.selectedBundleIndex),r=P(u=>u.isLoadingBundles),o=P(u=>u.bundlesError);if(r)return jsx(Ln,{message:"Loading bundles..."});if(o)return jsx(Rn,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(It,{message:"No bundles available."});let i=Math.max(0,n-Math.floor(fo/2)),s=Math.min(t.length,i+fo);s===t.length&&(i=Math.max(0,s-fo));let c=t.slice(i,s),a=i,l=t.length-s;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a bundle to get started"})}),a>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",a," more above"]})}),c.map((u,g)=>jsx(na,{bundle:u,isSelected:i+g===n},u.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}var ia=mc.memo(function({plugin:t,isCursor:n}){return jsxs(Box,{children:[jsx(Text,{color:n?"cyan":"gray",children:n?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:n,color:n?"cyan":"white",children:[" ",p(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var ho=8;function sa(){let e=P(u=>u.selectedBundle),t=P(u=>u.plugins),n=P(u=>u.pluginCursorIndex),r=useRef(false);if(useEffect(()=>{e&&!r.current&&(r.current=true,b(x.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No bundle selected."});let o=t.filter(u=>u.installed).length,i=Math.max(0,n-Math.floor(ho/2)),s=Math.min(t.length,i+ho);s===t.length&&(i=Math.max(0,s-ho));let c=t.slice(i,s),a=i,l=t.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:p(e.name)}),jsx(Text,{dimColor:true,children:p(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),a>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",a," more above"]})}),c.map((u,g)=>jsx(ia,{plugin:u,isCursor:i+g===n},u.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}var Yu=["Retry failed","Continue anyway"];function aa({name:e,status:t,error:n}){let r=p(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ac,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",r]})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",r]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",r]}),n&&jsxs(Text,{dimColor:true,children:[" \u2014 ",p(n)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",r]})})}function la({onComplete:e,onRetry:t}){let n=P(l=>l.plugins),r=P(l=>l.step),o=P(l=>l.successCount),i=P(l=>l.failedCount),s=P(l=>l.summaryActionIndex),c=n.filter(l=>l.selected),a=useRef(false);return useEffect(()=>{if(r==="summary"&&i===0&&!a.current){a.current=true;let l=setTimeout(e,1500);return ()=>clearTimeout(l)}},[r,i,e]),r==="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:c.map(l=>jsx(aa,{name:l.name,status:l.status,error:l.error},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:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===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:c.filter(l=>l.status==="failed").map(l=>jsx(aa,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:Yu.map((l,u)=>jsx(Box,{children:jsxs(Text,{bold:u===s,color:u===s?"cyan":void 0,children:[u===s?"\u203A ":" ",l]})},l))}),i===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function ca(){let e=P(w=>w.step),t=P(w=>w.bundles),n=P(w=>w.selectedBundleIndex),r=P(w=>w.setSelectedBundleIndex),o=P(w=>w.selectBundle),i=P(w=>w.plugins),s=P(w=>w.pluginCursorIndex),c=P(w=>w.setPluginCursorIndex),a=P(w=>w.setStep),l=P(w=>w.summaryActionIndex),u=P(w=>w.setSummaryActionIndex),g=P(w=>w.failedCount),v=P(w=>w.resetForRetry),d=P(w=>w.goBackToList),E=f(w=>w.setScreen),m=f(w=>w.setFocus),h=f(w=>w.focus),T=ue(w=>w.setJustAuthenticated),y=ue(w=>w.justAuthenticated),{loadBundles:L,installSelected:A}=Qs(),J=useRef(false);useEffect(()=>{e==="bundleList"?(m("bundleList"),J.current||(J.current=true,et("bundle_selection"))):m(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,m]);let q=useCallback(async()=>{let w=P.getState().selectedBundle;if(w){let K=await O();K&&await Ze({...K,bundle:w.slug});}b(x.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:tt()}).catch(()=>{});let{successCount:te}=P.getState();b(x.CLI_ONBOARDING_COMPLETED,{duration_ms:De(),tools_installed_count:te}).catch(()=>{}),T(false),m("list"),E("main");},[T,m,E]),Ee=useCallback(()=>{v(),A();},[v,A]),lr=useCallback(()=>{L();},[L]),H=useCallback(()=>{m("list"),E("main");},[m,E]);return useInput((w,te)=>{if(te.escape)vn("esc"),H();else if(te.upArrow&&n>0)r(n-1);else if(te.downArrow&&n<t.length-1)r(n+1);else if(te.return&&t.length>0){let K=tt();o(t[n]),et("kit_display"),b(x.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:K}).catch(()=>{});}},{isActive:h==="bundleList"}),useInput((w,te)=>{let K=ea(w,te);if(K.cursorDelta!==0){let F=s+K.cursorDelta;F>=0&&F<i.length&&c(F);}if(K.confirm){let F=P.getState().selectedBundle;F&&(async()=>(await O())?.bundle!==F.slug&&b(x.CLI_KIT_ACCEPTED,{bundle_slug:F.slug}).catch(()=>{}))();let cr=tt();et("kit_confirmation"),b(x.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:cr}).catch(()=>{});let ur=tt();et("tool_installation"),b(x.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:ur}).catch(()=>{}),a("installing"),A();}if(K.back){let F=P.getState().selectedBundle;F&&b(x.CLI_KIT_REJECTED,{bundle_slug:F.slug}).catch(()=>{}),d();}},{isActive:h==="bundleDetail"}),useInput((w,te)=>{if(g===0)return;let K=ta(w,te);if(K.cursorDelta!==0){let F=l+K.cursorDelta;F>=0&&F<=1&&u(F);}K.select&&(l===0?Ee():q());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(kn,{}),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."}),!y&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your bundle is not set up yet. Choose a bundle below to get your recommended starter kit."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="bundleList"&&jsx(ra,{onRetry:lr}),e==="bundleDetail"&&jsx(sa,{}),(e==="installing"||e==="summary")&&jsx(la,{onComplete:q,onRetry:Ee})]}),jsx($n,{})]})}var tp=S("app"),np={auth:pi,bundleSetup:ca,main:Ys};function da(){f.getState().setScreen("auth"),f.getState().setFocus("auth");}async function fa(){let e=await O();if(!e){da();return}try{await Oe();}catch(o){tp.debug(`Token validation failed: ${String(o)}`),da();return}b(x.CLI_SESSION_STARTED,{cli_version:Be,os:process.platform,node_version:process.version,duration_ms:De(),interface:"tui"}).catch(()=>{});let{clientSecret:t,...n}=e;ue.getState().setCredentials(n),!e.bundle||e.bundle.trim()===""?(f.getState().setScreen("bundleSetup"),f.getState().setFocus("bundleList")):(f.getState().setScreen("main"),f.getState().setFocus("list"));}function ga(){let{columns:e,rows:t}=useWindowSize(),n=f(i=>i.screen),r=np[n],{pendingExit:o}=ci();return r?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(r,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",n]})}var Pe=S("auth");function ha(){W.clearFallbackFile(),Sn();}var rp=3,ya=3,Sa=` \u2139 The data collected during setup is used solely to improve
|
|
19
26
|
Flow's internal tools and will not be shared externally.
|
|
20
|
-
`;function
|
|
21
|
-
`){
|
|
22
|
-
`),n(
|
|
23
|
-
`+
|
|
24
|
-
`),e.forEach((t,n)=>{process.stdout.write(` ${
|
|
27
|
+
`;function nn(e,t={}){return new Promise((n,r)=>{let{masked:o=false,defaultValue:i=""}=t;process.stdout.write(e+i);let s=i,c=u=>{if(u===""){a(),r(new Error("SIGINT"));return}if(u==="\r"||u===`
|
|
28
|
+
`){a(),process.stdout.write(`
|
|
29
|
+
`),n(s);return}if(u==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}u.startsWith("\x1B")||(s+=u,process.stdout.write(o?"*".repeat(u.length):u));};function a(){process.stdin.setRawMode(false),process.stdin.removeListener("data",c),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.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",c);})}async function wa(){for(let e=1;e<=ya;e++)try{return await Bn()}catch{if(e===ya)throw new Error("Failed to fetch bundles after 3 attempts")}return []}async function xa(){let e=await wa();if(e.length===0)throw new Error("No bundles available. Please contact your administrator.");for(process.stdout.write(`
|
|
30
|
+
`+C.cyan(" ? ")+`Bundle:
|
|
31
|
+
`),e.forEach((t,n)=>{process.stdout.write(` ${C.cyan(`${n+1})`)} ${p(t.name)}
|
|
25
32
|
`);}),process.stdout.write(`
|
|
26
|
-
`);;){let t=(await
|
|
27
|
-
`));}}async function
|
|
28
|
-
Bundle '${
|
|
33
|
+
`);;){let t=(await nn(C.cyan(" ? ")+`Select bundle (1-${e.length}): `)).trim(),n=parseInt(t,10)-1;if(!isNaN(n)&&n>=0&&n<e.length)return e[n];process.stderr.write(C.yellow(` \u26A0 Invalid selection. Please try again.
|
|
34
|
+
`));}}async function Ia(e){if(e.plugins.length===0)return process.stdout.write(C.dim(`
|
|
35
|
+
Bundle '${p(e.name)}' has no plugins to install.
|
|
29
36
|
`)),true;process.stdout.write(`
|
|
30
|
-
Installing ${e.plugins.length} plugins from '${
|
|
31
|
-
`);let t=0,n=0,r=e.plugins.length;for(let o of e.plugins){let
|
|
32
|
-
`)):(n++,process.stdout.write(
|
|
33
|
-
`)));}return n===0?process.stdout.write(
|
|
34
|
-
`)):process.stdout.write(
|
|
35
|
-
`)),n===0}async function
|
|
36
|
-
`+
|
|
37
|
-
`),
|
|
38
|
-
`)),1}try{let t;if(e.bundle){let n=await
|
|
37
|
+
Installing ${e.plugins.length} plugins from '${p(e.name)}'...
|
|
38
|
+
`);let t=0,n=0,r=e.plugins.length;for(let o of e.plugins){let i=t+n+1;process.stdout.write(C.dim(` [${i}/${r}] Installing ${p(o)}...`));let s=false;for(let c=1;c<=rp;c++)try{await Ie(o),t++,s=!0;break}catch(a){if(a instanceof we){t++,s=true;break}}s?process.stdout.write(C.green(` done
|
|
39
|
+
`)):(n++,process.stdout.write(C.red(` failed
|
|
40
|
+
`)));}return n===0?process.stdout.write(C.green(` \u2713 Bundle '${p(e.name)}' selected. ${t}/${r} plugins installed successfully.
|
|
41
|
+
`)):process.stdout.write(C.yellow(` \u26A0 Bundle '${p(e.name)}' selected. ${t}/${r} plugins installed. ${n} failed.
|
|
42
|
+
`)),n===0}async function op(e){ha(),process.stdout.write(`
|
|
43
|
+
`+Sa+`
|
|
44
|
+
`),Pe.debug(`[${e.tenant}] Authenticating tenant`);try{await Qe(e);}catch(t){let n=p(t instanceof Error?t.message:"unknown error");return Pe.error(`[${e.tenant}] Authentication failed: ${n}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${n}
|
|
45
|
+
`)),1}try{let t;if(e.bundle){let n=await wa(),r=n.find(o=>o.slug===e.bundle);if(!r){process.stderr.write(C.red(` \u2717 Bundle '${p(e.bundle)}' not found.
|
|
39
46
|
`)),process.stderr.write(` Available bundles:
|
|
40
|
-
`);for(let o of n)process.stderr.write(` - ${
|
|
41
|
-
`);return 1}t=r;}else t=await
|
|
47
|
+
`);for(let o of n)process.stderr.write(` - ${p(o.slug)} (${p(o.name)})
|
|
48
|
+
`);return 1}t=r;}else t=await xa();return await Ze({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,bundle:t.slug}),await Ia(t),Pe.info(`[${e.tenant}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${e.tenant}
|
|
42
49
|
|
|
43
|
-
`)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let n=
|
|
44
|
-
`)),1}}async function
|
|
45
|
-
`),process.stdout.write(
|
|
46
|
-
`);let e=(await
|
|
47
|
-
`)),1;
|
|
48
|
-
`)),1}let r=await
|
|
50
|
+
`)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let n=p(t instanceof Error?t.message:"unknown error");return Pe.error(`[${e.tenant}] Bundle setup failed: ${n}`),process.stderr.write(C.red(` \u2717 Bundle setup failed: ${n}
|
|
51
|
+
`)),1}}async function ip(){ha(),Pe.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
|
|
52
|
+
`),process.stdout.write(Sa+`
|
|
53
|
+
`);let e=(await nn(C.cyan(" ? ")+"Client ID: ")).trim(),t=(await nn(C.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),n=(await nn(C.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!n)return Pe.error("[auth] Validation failed: all fields are required"),process.stderr.write(C.red(` \u2717 All fields are required
|
|
54
|
+
`)),1;Pe.debug(`[${n}] Authenticating tenant`);try{await Qe({clientId:e,clientSecret:t,tenant:n});}catch(o){let i=p(o instanceof Error?o.message:"unknown error");return Pe.error(`[${n}] Authentication failed: ${i}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${i}
|
|
55
|
+
`)),1}let r=await xa();return await Ze({clientId:e,clientSecret:t,tenant:n,bundle:r.slug}),await Ia(r),Pe.info(`[${n}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${n}
|
|
49
56
|
|
|
50
|
-
`)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=
|
|
51
|
-
`)),1}}async function
|
|
52
|
-
`),130;throw t}}async function
|
|
53
|
-
`),(await
|
|
57
|
+
`)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=p(e instanceof Error?e.message:"unknown error");return Pe.error(`[auth] Unexpected error: ${t}`),process.stderr.write(C.red(` \u2717 Unexpected error: ${t}
|
|
58
|
+
`)),1}}async function bo(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return op({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,bundle:e.bundle});try{return await ip()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
|
|
59
|
+
`),130;throw t}}async function sp(){try{return process.stdout.write(`
|
|
60
|
+
`),(await nn(C.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(C.yellow(` \u26A0 Logout cancelled
|
|
54
61
|
`)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
|
|
55
|
-
`),130;throw e}}async function
|
|
56
|
-
`)),0;if(!e){let t=await
|
|
57
|
-
`)),0}catch{return process.stderr.write(
|
|
58
|
-
`)),1}}async function
|
|
59
|
-
`+
|
|
60
|
-
`)),process.stdout.write(
|
|
61
|
-
`),process.stdout.write(
|
|
62
|
-
`),process.stdout.write(
|
|
63
|
-
`),process.stdout.write(
|
|
62
|
+
`),130;throw e}}async function ba(e){if(!await O())return process.stdout.write(C.yellow(` \u26A0 You are not authenticated
|
|
63
|
+
`)),0;if(!e){let t=await sp();if(t!==null)return t}try{return await qo(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
|
|
64
|
+
`)),0}catch{return process.stderr.write(C.red(` \u2717 Error removing credentials
|
|
65
|
+
`)),1}}async function va(){let e=await O();return e?await ht()?(process.stdout.write(`
|
|
66
|
+
`+C.bold(` Authenticated
|
|
67
|
+
`)),process.stdout.write(C.dim(" Tenant: ")+p(e.tenant)+`
|
|
68
|
+
`),process.stdout.write(C.dim(" Client ID: ")+p(e.clientId)+`
|
|
69
|
+
`),process.stdout.write(C.dim(" Bundle: ")+p(e.bundle??"not set")+`
|
|
70
|
+
`),process.stdout.write(C.dim(" Config: ")+p(await Wo())+`
|
|
64
71
|
`),process.stdout.write(`
|
|
65
|
-
`),0):(process.stdout.write(
|
|
72
|
+
`),0):(process.stdout.write(C.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(C.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function ap(e){let t=be(),n;try{n=await xe();}catch{n=[];}let r=new Set(t.map(o=>o.name));return b(x.CLI_CATALOG_VIEWED,{interface:$().interfaceType,filter_type:"available",result_count:n.length}).catch(()=>{}),e.json?(wt(n.map(o=>({...o,installed:r.has(o.name)}))),0):(Pn(["","Name","Version","Category","Status"],n.map(o=>[r.has(o.name)?"*":" ",o.name??"",o.version??"n/a",o.category??"",r.has(o.name)?"installed":"available"])),0)}async function lp(e){let t=be(),n=await xe(),r=new Map(n.map(i=>[i.name,i])),o=t.map(i=>{let s=r.get(i.name);return s&&i.version&&s.version&&Ae(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return b(x.CLI_CATALOG_VIEWED,{interface:$().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(I("All plugins are up to date."),0):e.json?(wt(o),0):(Pn(["Name","Installed","Available"],o.map(i=>[i.name??"",i.version??"n/a",i.availableVersion??"n/a"])),process.stdout.write(`
|
|
66
73
|
${o.length} plugin(s) outdated.
|
|
67
|
-
`),0)}function
|
|
74
|
+
`),0)}async function cp(e){let t=be();if(b(x.CLI_CATALOG_VIEWED,{interface:$().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return I("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return wt(t),0;let n=[];try{n=await xe();}catch{n=[];}let r=new Map(n.map(i=>[i.name,i])),o=[...t].sort((i,s)=>{let c=Yt.indexOf(i.scope??"user"),a=Yt.indexOf(s.scope??"user");return (c===-1?1/0:c)-(a===-1?1/0:a)});return Pn(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(i=>{let s=r.get(i.name),c=s?.type??"plugin",a=s?.origin??so(i.marketplace);return [i.name??"",i.version??"n/a",dt[c]?.label??"Plugin",a,i.scope??"user",i.status??"enabled",En(i.installedAt??"")]})),process.stdout.write(`
|
|
68
75
|
${t.length} plugin(s) installed.
|
|
69
|
-
`),0
|
|
70
|
-
|
|
71
|
-
`);}
|
|
72
|
-
Installation summary: ${t} succeeded, ${n} failed`);}async function
|
|
73
|
-
Update summary: ${t} updated, ${n} already up to date, ${r} failed`);}async function
|
|
74
|
-
|
|
76
|
+
`),0}async function Pa(e){if(!await Q())return 1;try{return e.available?await ap(e):e.outdated?await lp(e):await cp(e)}catch(t){return k(t instanceof Error?t.message:"Failed to list plugins."),1}}var M=S("manage");function Qn(e,t){return t?be().find(n=>n.name===e&&n.scope===t):be().find(n=>n.name===e)}function up(e,t){let n=t;return {callbacks:{onStatus:o=>{n&&(n.text=`${e}${o}`);},onError:o=>{n?.stop(),n=void 0,I(`${e}${o}`);},onPause:()=>{n?.stop(),n=void 0;},onResume:o=>{n?.stop(),n=vo({text:`${e}${o}`}).start();}},stopSpinner:()=>{n?.stop(),n=void 0;}}}async function pp(e,t,n,r){let o=r;if(!n.force){o?.stop();let s=p(e),c=p(ro(e,n.scope));if(!await Je(`${t}Install external plugin "${s}"?
|
|
77
|
+
This will run: ${c}
|
|
78
|
+
[y/N] `))return M.debug(`[${e}] Installation cancelled by user`),n.silent||I(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};n.silent||(o=vo({text:`${t}Installing ${e}...`}).start());}let i=o?up(t,o):void 0;try{let s=await oo(e,n.marketplaceSource,i?.callbacks,n.scope);if(i?.stopSpinner(),s.exitCode!==0){let c=s.stderr||"Command failed";return n.silent?oe({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:!1,error:c}}return n.silent?X({status:"success",plugin:e,command:s.command,duration_ms:s.duration_ms}):V(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:s.duration_ms}}catch(s){i?.stopSpinner();let c=D(s);return n.silent?oe({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:false,error:c}}}async function dp(e,t,n){let r=n.silent?void 0:vo({text:`${t}Installing ${e}...`}).start();if(qt(e))return pp(e,t,n,r);try{let o=await Ie(e,n);return r?.stop(),n.silent?X({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):V(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(r?.stop(),o instanceof we)return n.silent?X({status:"already_installed",plugin:e,message:o.message}):I(`${t}${o.message}`),{name:e,success:true};let i=D(o);return n.silent?oe({status:"error",plugin:e,message:i}):k(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function mp(e){let t=e.filter(r=>r.success).length,n=e.filter(r=>!r.success).length;I(`
|
|
79
|
+
Installation summary: ${t} succeeded, ${n} failed`);}async function Ea(e,t={}){if(!await Q())return 1;let n=[];for(let r=0;r<e.length;r++){let o=e.length>1?`[${r+1}/${e.length}] `:"",i=await dp(e[r],o,t);n.push(i);}return e.length>1&&(t.silent?X({status:"summary",succeeded:n.filter(r=>r.success).length,failed:n.filter(r=>!r.success).length,results:n.map(r=>({plugin:r.name,success:r.success,...r.error?{error:r.error}:{}}))}):mp(n)),n.some(r=>!r.success)?1:0}async function Ta(e,t){if(!await Q())return 1;if(M.debug(`[${e}] Looking up installed plugin`),!t.force){let n=Qn(e,t.scope);if(!n)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;let r=p(n.name),o=n.version?p(n.version):void 0,i=t.scope?` (${t.scope})`:"";if(!await Je(`Remove ${r} ${o?`v${o}`:"(n/a)"}${i}? [y/N] `))return M.debug(`[${e}] Uninstall cancelled by user`),I("Operation cancelled."),0}try{return M.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Fn(e,t.scope),M.info(`[${e}] Uninstalled successfully`),V("Plugin removed successfully"),0}catch(n){return M.error(`[${e}] Failed to uninstall: ${D(n)}`),k(D(n)),1}}async function ka(e,t={}){if(!await Q())return 1;M.debug(`[${e}] Looking up installed plugin`);let n=Qn(e,t.scope);if(!n)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(n.status==="enabled")return M.debug(`[${e}] Already enabled, skipping`),I(`${n.name} is already enabled`),0;try{return M.debug(`[${e}] Enabling plugin (current status: ${n.status})`),await zt(e,"enabled",t.scope),M.info(`[${e}] Enabled successfully`),V(`${n.name} enabled successfully`),0}catch(r){return M.error(`[${e}] Failed to enable: ${D(r)}`),k(D(r)),1}}async function Ca(e,t={}){if(!await Q())return 1;M.debug(`[${e}] Looking up installed plugin`);let n=Qn(e,t.scope);if(!n)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(n.status==="disabled")return M.debug(`[${e}] Already disabled, skipping`),I(`${n.name} is already disabled`),0;try{return M.debug(`[${e}] Disabling plugin (current status: ${n.status})`),await zt(e,"disabled",t.scope),M.info(`[${e}] Disabled successfully`),V(`${n.name} disabled successfully`),0}catch(r){return M.error(`[${e}] Failed to disable: ${D(r)}`),k(D(r)),1}}async function Aa(e,t,n){n.silent||I(`${t}Updating ${e}...`);try{let r=await Kn(e,n);return n.silent?X({status:"updated",plugin:r.name,previousVersion:r.previousVersion,newVersion:r.newVersion,duration_ms:r.duration_ms}):V(`${t}${r.name} v${r.previousVersion} \u2192 v${r.newVersion}`),{name:e,success:!0}}catch(r){if(r instanceof je)return n.silent?X({status:"up_to_date",plugin:e,message:r.message}):I(`${t}${r.message}`),{name:e,success:true,skipped:true};let o=D(r);return n.silent?oe({status:"error",plugin:e,message:o}):k(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function fp(e){let t=e.filter(o=>o.success&&!o.skipped).length,n=e.filter(o=>o.skipped).length,r=e.filter(o=>!o.success).length;I(`
|
|
80
|
+
Update summary: ${t} updated, ${n} already up to date, ${r} failed`);}async function gp(e,t,n){try{let r=await vt(e);Ae(t,r.version,n.force)?I(`Would update ${e}: v${t} \u2192 v${r.version}`):I(`${e} is already up to date (v${t})`);}catch(r){return k(D(r)),1}return 0}function yp(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function hp(e,t,n){let r=t.get(e.name);return r?e.version&&Ae(e.version,r,n)?(I(`Would update ${e.name}: v${e.version} \u2192 v${r}`),true):(I(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(I(`Skipping ${e.name}: not found in catalog`),false)}async function Sp(e,t){try{let n=await xe(),r=yp(n),o=0;for(let i of e)hp(i,r,t.force)&&o++;o===0&&I("All plugins are up to date");}catch(n){return k(D(n)),1}return 0}async function wp(e,t){let n=[];for(let r=0;r<e.length;r++){let o=`[${r+1}/${e.length}] `,i=await Aa(e[r].name,o,t);n.push(i);}return t.silent?X({status:"summary",updated:n.filter(r=>r.success&&!r.skipped).length,upToDate:n.filter(r=>r.skipped).length,failed:n.filter(r=>!r.success).length,results:n.map(r=>({plugin:r.name,success:r.success,...r.skipped?{skipped:true}:{},...r.error?{error:r.error}:{}}))}):fp(n),n.some(r=>!r.success)?1:0}async function $a(e,t={}){if(!await Q())return 1;if(e){let o=Qn(e,t.scope);return o?t.dryRun?gp(e,o.version??"",t):(await Aa(e,"",t)).success?0:1:(t.silent?oe({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):k(`Plugin "${e}" is not installed`),1)}let r=be().filter(o=>o.marketplace===_);return r.length===0?(t.silent?X({status:"empty",message:"No plugins installed"}):I("No plugins installed"),0):t.dryRun?Sp(r,t):wp(r,t)}var La=S("marketplace");function Ip(e){return `claude plugin marketplace add ${e}`}async function Ra(e,t){if(!await Q())return 1;let n;try{n=Jn(e);}catch(i){let s=D(i);return t.silent?oe({status:"error",source:e,message:s}):k(s),1}La.debug(`[marketplace] Adding marketplace source: ${n}`);let r=Ip(n);if(!t.force){let i=p(n),s=p(r);if(!await Je(`Add marketplace "${i}"?
|
|
81
|
+
This will run: ${s}
|
|
82
|
+
[y/N] `))return La.debug("[marketplace] Operation cancelled by user"),I("Operation cancelled."),0}let o=t.silent?void 0:vo({text:`Adding marketplace "${p(n)}"...`}).start();try{let i=await ae(r);return o?.stop(),i.exitCode!==0?(t.silent?oe({status:"error",source:n,exitCode:i.exitCode,message:i.stderr||"Command failed"}):(k(`Failed to add marketplace "${n}": ${i.stderr||"Command failed"}`),t.verbose&&i.stdout&&I(`stdout: ${i.stdout}`)),1):(t.silent?X({status:"success",source:n,command:r,duration_ms:i.duration_ms}):(V(`Marketplace "${n}" added successfully`),t.verbose&&i.stdout&&I(i.stdout)),0)}catch(i){o?.stop();let s=D(i);return t.silent?oe({status:"error",source:n,message:s}):k(`Failed to add marketplace "${n}": ${s}`),1}}async function Ep(){return await O()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Tp(){let e=Date.now();try{await xe();let t=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${t}ms)`,latency:t}}catch(t){return t instanceof Error&&t.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${t instanceof Error?t.message:"Unknown"}`}}}async function kp(){return await ht()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Cp(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}async function Ma(){process.stdout.write(`
|
|
83
|
+
`+C.bold(` FlowSetup CLI Diagnostics
|
|
75
84
|
|
|
76
|
-
`));let e=[{name:"Credentials",fn:
|
|
85
|
+
`));let e=[{name:"Credentials",fn:Ep},{name:"Prompt Manager",fn:Tp},{name:"Valid Token",fn:kp},{name:"Claude Code",fn:Cp}],t=true;for(let n of e){let r=await n.fn(),o="",i=C.green;r.passed?o=C.green("[OK] "):(o=C.red("[FAIL]"),i=C.red,t=false);let s=` ${o} ${i(n.name.padEnd(18))} ${p(r.message)}`;process.stdout.write(s+`
|
|
77
86
|
`);}return process.stdout.write(`
|
|
78
|
-
`),t?(process.stdout.write(
|
|
87
|
+
`),t?(process.stdout.write(C.green(` \u2713 All checks passed!
|
|
79
88
|
|
|
80
|
-
`)),0):(process.stdout.write(
|
|
89
|
+
`)),0):(process.stdout.write(C.red(` \u2717 Some checks failed \u2014 verify your configuration
|
|
81
90
|
|
|
82
|
-
`)),1)}function
|
|
91
|
+
`)),1)}var Lp=["github.com","www.github.com"],Rp=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Mp=/^([^@]+)@(.+)$/;function _p(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Po(e){let t=e.replace(/\\/g,"/");t=t.replace(/^\/+/,"").replace(/\/+$/,"");let n=t.split("/").filter(Boolean);for(let r of n)if(r==="..")throw new Error(`Invalid subpath: "${e}" contains path traversal ("..").`);return n.join("/")}function Op(e){let t=e.pathname.split("/").filter(Boolean);if(t.length<2)throw new Error(`Invalid GitHub URL: expected at least owner/repo in "${e.href}"`);let n=t[0],r=t[1];r.endsWith(".git")&&(r=r.slice(0,-4));let o={type:"github",url:`https://github.com/${n}/${r}.git`};if(t.length>=3&&(t[2]==="tree"||t[2]==="blob")){if(t.length>=4&&(o.ref=t[3]),t.length>=5){let i=t.slice(4).join("/");o.subpath=Po(i);}}else if(t.length>2){let i=t.slice(2).join("/");o.subpath=Po(i);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function er(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(_p(t)){let n=resolve(t);return {type:"local",url:n,localPath:n}}try{let n=new URL(t);if((n.protocol==="https:"||n.protocol==="http:")&&Lp.includes(n.hostname))return Op(n);if(n.protocol==="https:"||n.protocol==="http:"){let r={type:"git",url:t};return n.hash&&n.hash.length>1&&(r.ref=decodeURIComponent(n.hash.slice(1)),r.url=t.replace(n.hash,"")),r}if(n.protocol==="git:"){let r={type:"git",url:t};return n.hash&&n.hash.length>1&&(r.ref=decodeURIComponent(n.hash.slice(1)),r.url=t.replace(n.hash,"")),r}}catch{}if(t.startsWith("git@")||t.includes(":")&&t.includes(".git")){let n=t,r,o=t.indexOf("#");o!==-1&&(r=t.slice(o+1),n=t.slice(0,o));let i={type:"git",url:n};return r&&(i.ref=r),i}{let n=t,r,o=n.indexOf("#");o!==-1&&(r=n.slice(o+1),n=n.slice(0,o));let i=n.match(Rp);if(i){let s=i[1],c=i[2],a=i[3],l,u=c.match(Mp);u&&(c=u[1],l=u[2]),c.endsWith(".git")&&(c=c.slice(0,-4));let g={type:"github",url:`https://github.com/${s}/${c}.git`};if(r&&(g.ref=r),l&&(g.skillFilter=l),a){let v=a.replace(/^\//,"");v&&(g.subpath=Po(v));}return g}}return {type:"git",url:t}}function tr(e){if(e.type!=="github")return null;try{let n=new URL(e.url).pathname.split("/").filter(Boolean);if(n.length<2)return null;let r=n[1];return r.endsWith(".git")&&(r=r.slice(0,-4)),`${n[0]}/${r}`}catch{return null}}var Up=6e4,ze=class extends Error{url;isTimeout;isAuthError;constructor(t,n,r=false,o=false){super(t),this.name="GitCloneError",this.url=n,this.isTimeout=r,this.isAuthError=o;}};async function nr(e,t){let n=await mkdtemp(join(tmpdir(),"flow-skills-")),r=simpleGit({timeout:{block:Up}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await r.clone(e,n,o),n}catch(i){await rm(n,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),c=s.includes("block timeout")||s.includes("timed out"),a=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw c?new ze("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):a?new ze(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new ze(`Failed to clone ${e}: ${s}`,e,false,false)}}async function rr(e){let t=normalize(resolve(e)),n=normalize(resolve(tmpdir()));if(!t.startsWith(n+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm(e,{recursive:true,force:true});}function Na(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);return t?{data:parse(t[1])??{},content:t[2]??""}:{data:{},content:e}}var To=new Set(["node_modules",".git","dist","build","__pycache__"]);function Tt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function ja(e,t){let n=normalize(resolve(e)),r=normalize(resolve(t));return r.startsWith(n+sep)||r===n}function Vp(e,t){let n=normalize(resolve(e)),r=normalize(resolve(join(e,t)));return r.startsWith(n+sep)||r===n}async function Eo(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function rn(e){try{let t=await readFile(e,"utf-8"),{data:n}=Na(t);return typeof n.name!="string"||typeof n.description!="string"?null:{name:n.name,description:n.description,path:dirname(e),rawContent:t,metadata:n.metadata}}catch{return null}}async function Ka(e,t=0,n=5){if(t>n)return [];try{let[r,o]=await Promise.all([Eo(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),i=r?[e]:[],s=await Promise.all(o.filter(c=>c.isDirectory()&&!To.has(c.name)).map(c=>Ka(join(e,c.name),t+1,n)));return [...i,...s.flat()]}catch{return []}}async function sr(e,t){let n=[],r=new Set;if(t&&!Vp(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Eo(o)){let s=await rn(join(o,"SKILL.md"));if(s)return n.push(s),r.add(s.name),n}let i=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let s of i)try{let c=await readdir(s,{withFileTypes:!0});for(let a of c){if(!a.isDirectory())continue;let l=join(s,a.name);if(await Eo(l)){let u=await rn(join(l,"SKILL.md"));u&&!r.has(u.name)&&(n.push(u),r.add(u.name));}}}catch{}if(n.length===0){let s=await Ka(o);for(let c of s){let a=await rn(join(c,"SKILL.md"));a&&!r.has(a.name)&&(n.push(a),r.add(a.name));}}return n}function Ja(e,t){let n=t.map(r=>r.toLowerCase());return e.filter(r=>{let o=r.name.toLowerCase();return n.some(i=>i===o)})}var Va=1;function Ha(){return {version:Va,skills:{}}}async function ar(e){let t=gr(e);try{let n=await readFile(t,"utf-8"),r=JSON.parse(n);return !r.version||r.version<Va?Ha():r}catch{return Ha()}}function Xp(e){let t={};for(let n of Object.keys(e).sort())t[n]=e[n];return t}async function Ga(e,t){let n=gr(t);await mkdir(dirname(n),{recursive:true});let r={version:e.version,skills:Xp(e.skills)};await writeFile(n,JSON.stringify(r,null,2)+`
|
|
92
|
+
`,"utf-8");}async function za(e,t,n){let r=await ar(n),o=new Date().toISOString(),i=r.skills[e];r.skills[e]={...t,installedAt:i?.installedAt??o,updatedAt:o},await Ga(r,n);}async function qa(e,t){let n=await ar(t);e in n.skills&&(delete n.skills[e],await Ga(n,t));}var Wa=S("skillInstaller");async function rd(e,t,n,r){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:n,duration_ms:r,interface:$().interfaceType});}catch(o){Wa.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function od(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:$().interfaceType});}catch(n){Wa.warn(`Failed to send skill install-failed metrics: ${String(n)}`);}}async function id(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:n=>!To.has(basename(n))});}async function sd(e,t,n){let r=Tt(e.name),o=Mt(t),i=join(o,r);if(!ja(o,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 id(e.path,i);let c=tr(n)??n.url;return await za(r,{source:c,sourceType:n.type,sourceUrl:n.url,ref:n.ref,skillPath:n.subpath},t),{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 Xa(e,t){let n=er(e),r;try{let o;if(n.type==="local"){if(!n.localPath||!existsSync(n.localPath))return {source:e,results:[],discovered:0,installed:0,failed:0};o=n.localPath;}else r=await nr(n.url,n.ref),o=r;let i=await sr(o,n.subpath),s=[...t.skillFilter??[]];n.skillFilter&&s.push(n.skillFilter);let c=s.length>0?Ja(i,s):i,a=[],l=n.ref??"latest";for(let u of c){let g=Date.now(),v=await sd(u,t.scope,n);a.push(v);let d=Date.now()-g;v.success?await rd(u.name,t.scope,l,d):await od(u.name,new Error(v.error??"Unknown error"));}return {source:e,results:a,discovered:i.length,installed:a.filter(u=>u.success).length,failed:a.filter(u=>!u.success).length}}finally{r&&await rr(r).catch(()=>{});}}var pd=S("skills");async function dd(e){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:$().interfaceType});}catch(t){pd.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function md(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(`${e} (y/N) `,r=>{t.close(),n(r.trim().toLowerCase()==="y");});})}async function fd(e){let t=er(e),n;try{let r;if(t.type==="local"){if(!t.localPath)return k("Invalid local path."),1;r=t.localPath;}else I(`Fetching skills from ${p(e)}...`),n=await nr(t.url,t.ref),r=n;let o=await sr(r,t.subpath);if(o.length===0)return I("No skills found in this source."),0;let s=tr(t)??p(e);I(`Found ${o.length} skill(s) in ${s}:
|
|
93
|
+
`);for(let c of o){let a=p(c.name),l=p(c.description);process.stdout.write(` ${C.bold(a)} ${C.dim(l)}
|
|
94
|
+
`);}return process.stdout.write(`
|
|
95
|
+
`),0}catch(r){return r instanceof ze?k(r.message):k(r instanceof Error?r.message:String(r)),1}finally{n&&await rr(n).catch(()=>{});}}function gd(e){for(let n of e.results){let r=p(n.skill);if(n.success){let o=relative(process.cwd(),n.path);V(`${r} installed ${C.dim(`\u2192 ${o}/`)}`);}else k(`${r}: ${p(n.error??"unknown error")}`);}process.stdout.write(`
|
|
96
|
+
`);let t=e.source;e.installed>0&&I(`Installed ${e.installed} of ${e.discovered} skill(s) from ${p(t)}`),e.failed>0&&k(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?I("No skills found in this source."):e.results.length===0&&e.discovered>0&&I(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Za(e,t){if(t.list)return fd(e);let n=t.global?"global":"project";try{let r=await Xa(e,{scope:n,skillFilter:t.skill,yes:t.yes});return gd(r),r.failed>0?1:0}catch(r){return r instanceof ze?k(r.message):k(r instanceof Error?r.message:String(r)),1}}async function Qa(e){let t=Mt(e),n=[];try{let r=await readdir(t,{withFileTypes:!0});for(let o of r){if(!o.isDirectory())continue;let i=join(t,o.name),s=join(i,"SKILL.md");try{if(!(await stat(s)).isFile())continue}catch{continue}let c=await rn(s);c?n.push({name:c.name,description:c.description,path:i}):n.push({name:o.name,description:"(no metadata)",path:i});}}catch{}return n}async function el(e){let t=e.global?"global":"project",n=await Qa(t),r=await ar(t);if(e.json){let i=n.map(s=>({name:s.name,description:s.description,path:s.path,source:r.skills[Tt(s.name)]?.source}));return wt(i),0}if(n.length===0)return I(`No skills installed (${t==="global"?"global":"project"} scope).`),0;I(`${t==="global"?"Global":"Project"} skills (${n.length}):
|
|
97
|
+
`);for(let i of n){let s=r.skills[Tt(i.name)]?.source,c=p(i.name),a=p(i.description),l=a.length>80?a.slice(0,77)+"...":a,u=s?C.dim(` (${s})`):"";process.stdout.write(` ${C.bold(c)}${u}
|
|
98
|
+
`),process.stdout.write(` ${C.dim(l)}
|
|
99
|
+
|
|
100
|
+
`);}return 0}async function tl(e,t){let n=t.global?"global":"project";if(!e){let s=await Qa(n);if(s.length===0)return I("No skills installed."),0;I("Installed skills:");for(let c of s)process.stdout.write(` - ${p(c.name)}
|
|
101
|
+
`);return process.stdout.write(`
|
|
102
|
+
`),I("Specify a skill name to remove: flow skills remove <name>"),1}let r=Tt(e),o=Mt(n),i=join(o,r);try{await stat(i);}catch{return k(`Skill "${p(e)}" is not installed.`),1}if(!t.force&&!await md(`Remove skill "${p(r)}"?`))return I("Cancelled."),0;try{return await rm(i,{recursive:!0,force:!0}),await qa(r,n),await dd(r),V(`Skill "${p(r)}" removed.`),0}catch(s){return k(`Failed to remove skill: ${s instanceof Error?s.message:String(s)}`),1}}function nl(e){let t=new Command;t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@flow/cli v${Be}`,"-V, --version","Display the CLI version").addHelpText("after",`
|
|
83
103
|
Without arguments, opens the interactive interface (TUI).
|
|
84
104
|
Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let n=new Command("setup").description("Configure the CLI by detecting Claude Code credentials");n.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
|
|
85
105
|
Examples:
|
|
86
|
-
$ flow setup init`).action(async()=>{let
|
|
106
|
+
$ flow setup init`).action(async()=>{let a=await bo();process.exit(a);}),t.addCommand(n);let r=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");r.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).addHelpText("after",`
|
|
87
107
|
Examples:
|
|
88
108
|
$ flow plugin list
|
|
89
109
|
$ flow plugin list --available
|
|
90
110
|
$ flow plugin list --outdated
|
|
91
|
-
$ flow plugin list --json`).action(async
|
|
111
|
+
$ flow plugin list --json`).action(async a=>{let l=await Pa(a);process.exit(l);}),r.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
92
112
|
Examples:
|
|
93
113
|
$ flow plugin install flow-adr-writer
|
|
114
|
+
$ flow plugin install flow-adr-writer --scope project
|
|
94
115
|
$ flow plugin install flow-adr-writer flow-prd-writer startup-pack-ai
|
|
95
116
|
$ flow plugin install flow-adr-writer --force
|
|
96
|
-
$ flow plugin install flow-adr-writer --silent
|
|
117
|
+
$ flow plugin install flow-adr-writer --silent
|
|
118
|
+
$ flow plugin install superpowers@claude-plugins-official
|
|
119
|
+
$ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(a,l)=>{let u=a.filter(v=>v.trim());if(u.length===0){k("No valid plugin names provided"),process.exit(1);return}re("cli",{verbose:l.verbose,silent:l.silent});let g=await Ea(u,l);process.exit(g);}),r.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",`
|
|
97
120
|
Examples:
|
|
98
121
|
$ flow plugin uninstall flow-adr-writer
|
|
99
|
-
$ flow plugin uninstall
|
|
122
|
+
$ flow plugin uninstall flow-adr-writer --scope project
|
|
123
|
+
$ flow plugin uninstall startup-pack-ai --force`).action(async(a,l)=>{let u=await Ta(a,l);process.exit(u);}),r.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",`
|
|
100
124
|
Examples:
|
|
101
125
|
$ flow plugin update flow-adr-writer
|
|
126
|
+
$ flow plugin update flow-adr-writer --scope project
|
|
102
127
|
$ flow plugin update flow-adr-writer --force
|
|
103
128
|
$ flow plugin update flow-adr-writer --dry-run
|
|
104
129
|
$ flow plugin update flow-adr-writer --verbose
|
|
105
130
|
$ flow plugin update flow-adr-writer --silent
|
|
106
131
|
$ flow plugin update
|
|
107
|
-
$ flow plugin update --dry-run`).action(async(
|
|
132
|
+
$ flow plugin update --dry-run`).action(async(a,l)=>{re("cli",{verbose:l.verbose,silent:l.silent});let u=await $a(a??null,l);process.exit(u);}),r.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",`
|
|
133
|
+
Examples:
|
|
134
|
+
$ flow plugin enable flow-adr-writer
|
|
135
|
+
$ flow plugin enable flow-adr-writer --scope project`).action(async(a,l)=>{re("cli");let u=await ka(a,l);process.exit(u);}),r.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",`
|
|
136
|
+
Examples:
|
|
137
|
+
$ flow plugin disable flow-adr-writer
|
|
138
|
+
$ flow plugin disable flow-adr-writer --scope project`).action(async(a,l)=>{re("cli");let u=await Ca(a,l);process.exit(u);});let o=new Command("marketplace").description("Manage plugin marketplaces");o.command("add").description("Register a plugin marketplace in Claude Code").argument("<source>","Marketplace source (owner/repo or URL)").option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
108
139
|
Examples:
|
|
109
|
-
$ flow plugin
|
|
140
|
+
$ flow plugin marketplace add anthropics/claude-code
|
|
141
|
+
$ flow plugin marketplace add https://github.com/owner/repo
|
|
142
|
+
$ flow plugin marketplace add anthropics/claude-code --force
|
|
143
|
+
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(a,l)=>{re("cli",{verbose:l.verbose,silent:l.silent});let u=await Ra(a,l);process.exit(u);}),r.addCommand(o),t.addCommand(r);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",`
|
|
110
144
|
Examples:
|
|
111
|
-
$ flow
|
|
145
|
+
$ flow mcp add notion --transport http https://mcp.notion.com/mcp
|
|
146
|
+
$ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
|
|
147
|
+
$ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
|
|
148
|
+
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(a,l,u)=>{re("cli",{verbose:u.verbose,silent:u.silent});let g=await Us(a,l,u);process.exit(g);}),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",`
|
|
149
|
+
Examples:
|
|
150
|
+
$ flow mcp remove notion
|
|
151
|
+
$ flow mcp remove notion --scope project
|
|
152
|
+
$ flow mcp remove playwright-mcp --force`).action(async(a,l)=>{re("cli",{verbose:l.verbose,silent:l.silent});let u=await js(a,l);process.exit(u);}),t.addCommand(i);let s=new Command("auth").description("Manage authentication credentials");s.command("login").description("Authenticate and save credentials locally").option("--client-id <id>","Client ID for non-interactive authentication").option("--client-secret <secret>","Client Secret for non-interactive authentication").option("--tenant <tenant>","Tenant for non-interactive authentication").option("--bundle <slug>","Bundle slug for non-interactive setup").option("--verbose","Display each step of the authentication process").addHelpText("after",`
|
|
112
153
|
Examples:
|
|
113
154
|
$ flow auth login
|
|
114
155
|
$ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
|
|
115
156
|
$ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --bundle dev
|
|
116
|
-
$ flow auth login --verbose`).action(async
|
|
157
|
+
$ flow auth login --verbose`).action(async a=>{re("cli",{verbose:a.verbose});let l=await bo(a);process.exit(l);}),s.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
|
|
117
158
|
Examples:
|
|
118
159
|
$ flow auth logout
|
|
119
|
-
$ flow auth logout --force`).action(async
|
|
160
|
+
$ flow auth logout --force`).action(async a=>{let l=await ba(a.force);process.exit(l);}),s.command("status").description("Display the current authentication status").addHelpText("after",`
|
|
161
|
+
Examples:
|
|
162
|
+
$ flow auth status`).action(async()=>{let a=await va();process.exit(a);}),t.addCommand(s);let c=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");return c.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",`
|
|
163
|
+
Examples:
|
|
164
|
+
$ flow skills add vercel-labs/agent-skills
|
|
165
|
+
$ flow skills add owner/repo -g
|
|
166
|
+
$ flow skills add owner/repo --skill pr-review commit
|
|
167
|
+
$ flow skills add ./local/skills -y
|
|
168
|
+
$ flow skills add owner/repo --list`).action(async(a,l)=>{let u=await Za(a,l);process.exit(u);}),c.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
|
|
169
|
+
Examples:
|
|
170
|
+
$ flow skills list
|
|
171
|
+
$ flow skills list -g
|
|
172
|
+
$ flow skills list --json`).action(async a=>{let l=await el(a);process.exit(l);}),c.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",`
|
|
120
173
|
Examples:
|
|
121
|
-
$ flow
|
|
174
|
+
$ flow skills remove pr-review
|
|
175
|
+
$ flow skills remove pr-review -g --force`).action(async(a,l)=>{let u=await tl(a,l);process.exit(u);}),t.addCommand(c),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
|
|
122
176
|
Examples:
|
|
123
|
-
$ flow health`).action(async()=>{let
|
|
177
|
+
$ flow health`).action(async()=>{let a=await Ma();process.exit(a);}),t}var hd=nl(async()=>{re("tui"),oi("tui"),ii(),process.on("SIGINT",()=>{Ot("sigint").finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{Ot("sigterm").finally(()=>process.exit(143));}),await fa(),render(jsx(ga,{}),{alternateScreen:true,exitOnCtrlC:false});});hd.parse();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ciandt-flow/cli",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "TUI for browsing and installing Claude Code plugins from the Flow ecosystem",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -20,9 +20,7 @@
|
|
|
20
20
|
"url": "https://github.com/CI-T-HyperX/flow-plugins-cli"
|
|
21
21
|
},
|
|
22
22
|
"scripts": {
|
|
23
|
-
"build": "npm run typecheck && tsup
|
|
24
|
-
"build:npm": "npm run typecheck && tsup",
|
|
25
|
-
"obfuscate": "javascript-obfuscator dist/index.js --output dist/index.js --options-preset medium-obfuscation --string-array true --string-array-encoding base64",
|
|
23
|
+
"build": "npm run typecheck && tsup",
|
|
26
24
|
"typecheck": "tsc --noEmit",
|
|
27
25
|
"dev": "NODE_ENV=development tsx --env-file=.env src/cli.tsx",
|
|
28
26
|
"dev:watch": "tsup --watch & sleep 2 && node --watch dist/index.js",
|
|
@@ -36,8 +34,7 @@
|
|
|
36
34
|
"prepare": "husky",
|
|
37
35
|
"changeset": "changeset",
|
|
38
36
|
"version-packages": "changeset version",
|
|
39
|
-
"release": "npm run build && changeset publish",
|
|
40
|
-
"release:npm": "npm run build:npm && changeset publish",
|
|
37
|
+
"release:npm": "npm run build && changeset publish",
|
|
41
38
|
"security-scan": "trufflehog filesystem src/ --fail --no-update",
|
|
42
39
|
"prepublishOnly": "npm run security-scan"
|
|
43
40
|
},
|
|
@@ -53,25 +50,28 @@
|
|
|
53
50
|
"email": "flow@ciandt.com"
|
|
54
51
|
},
|
|
55
52
|
"dependencies": {
|
|
56
|
-
"@tanstack/react-query": "
|
|
57
|
-
"boxen": "
|
|
53
|
+
"@tanstack/react-query": "5.100.6",
|
|
54
|
+
"boxen": "8.0.1",
|
|
58
55
|
"chalk": "5.6.2",
|
|
59
|
-
"cli-spinners": "^3.4.0",
|
|
60
56
|
"commander": "11.1.0",
|
|
61
57
|
"conf": "15.1.0",
|
|
62
|
-
"dotenv": "
|
|
58
|
+
"dotenv": "17.4.2",
|
|
59
|
+
"execa": "9.6.1",
|
|
63
60
|
"extract-zip": "2.0.1",
|
|
64
|
-
"http-status-codes": "
|
|
65
|
-
"ink": "
|
|
61
|
+
"http-status-codes": "2.3.0",
|
|
62
|
+
"ink": "7.0.1",
|
|
66
63
|
"ink-big-text": "2.0.0",
|
|
67
64
|
"ink-gradient": "4.0.0",
|
|
68
65
|
"ink-spinner": "5.0.0",
|
|
69
|
-
"keytar": "
|
|
70
|
-
"ky": "2.0.
|
|
66
|
+
"keytar": "7.9.0",
|
|
67
|
+
"ky": "2.0.2",
|
|
71
68
|
"proper-lockfile": "4.1.2",
|
|
72
69
|
"react": "19.2.5",
|
|
73
|
-
"react-dom": "
|
|
74
|
-
"semver": "
|
|
70
|
+
"react-dom": "19.2.5",
|
|
71
|
+
"semver": "7.7.4",
|
|
72
|
+
"simple-git": "3.36.0",
|
|
73
|
+
"yaml": "2.8.3",
|
|
74
|
+
"yocto-spinner": "1.1.0",
|
|
75
75
|
"zustand": "5.0.12"
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
@@ -90,7 +90,6 @@
|
|
|
90
90
|
"eslint-plugin-prettier": "^5.5.5",
|
|
91
91
|
"husky": "^9.1.7",
|
|
92
92
|
"ink-testing-library": "^4.0.0",
|
|
93
|
-
"javascript-obfuscator": "^5.4.1",
|
|
94
93
|
"prettier": "^3.8.1",
|
|
95
94
|
"tsup": "^8.0.0",
|
|
96
95
|
"tsx": "^4.7.0",
|
|
@@ -106,5 +105,8 @@
|
|
|
106
105
|
"esbuild": ">=0.25.0",
|
|
107
106
|
"picomatch": ">=4.0.4",
|
|
108
107
|
"vite": "^8.0.0"
|
|
108
|
+
},
|
|
109
|
+
"optionalDependencies": {
|
|
110
|
+
"@esbuild/darwin-arm64": "^0.28.0"
|
|
109
111
|
}
|
|
110
112
|
}
|