@ciandt-flow/cli 1.0.3 → 1.0.5-beta.21

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.
Files changed (3) hide show
  1. package/README.md +75 -240
  2. package/dist/index.js +37 -37
  3. package/package.json +7 -5
package/README.md CHANGED
@@ -2,337 +2,172 @@
2
2
 
3
3
  TUI for browsing and installing Claude Code plugins from the Flow ecosystem.
4
4
 
5
- ## Quick Start
5
+ ## Installation
6
6
 
7
7
  ```bash
8
- bun install
9
- cp .env.example .env
10
- bun run dev
8
+ npm install -g @ciandt-flow/cli
11
9
  ```
12
10
 
13
- > Copy `.env.example` to `.env` and adjust the values as needed before running the project.
14
-
15
- ## Development
11
+ ## Quick Start
16
12
 
17
13
  ```bash
18
- bun run build # Compile TypeScript
19
- bun run test # Run tests
20
- bun run lint # Lint check
21
- bun run format # Format + lint fix
22
- ```
23
-
24
- ## CLI Commands
25
-
26
- ### `setup`
27
-
28
- Setup and configuration commands.
29
-
30
- #### `setup init`
31
-
32
- Initialize Flow CLI configuration.
14
+ # Authenticate with your Flow credentials
15
+ flow auth login
33
16
 
34
- ```bash
35
- bun dev setup init
17
+ # Launch the interactive plugin browser
18
+ flow
36
19
  ```
37
20
 
38
- ---
39
-
40
- ### `plugin`
41
-
42
- Plugin management commands.
43
-
44
- #### `plugin list`
45
-
46
- List plugins.
21
+ ## Commands
47
22
 
48
- ```bash
49
- flow-plugins plugin list [options]
50
- ```
23
+ ### `flow` (no arguments)
51
24
 
52
- | Option | Description |
53
- |---|---|
54
- | `--available` | Show all plugins from catalog with install status |
55
- | `--outdated` | Show installed plugins with updates available |
56
- | `--json` | Output as JSON |
25
+ Launches the interactive TUI to browse and manage plugins.
57
26
 
58
- ```bash
59
- # list installed plugins (default)
60
- bun dev plugin list
61
-
62
- # list all plugins from catalog
63
- bun dev plugin list --available
27
+ ---
64
28
 
65
- # list plugins with updates available
66
- bun dev plugin list --outdated
29
+ ### `auth`
67
30
 
68
- # output as JSON
69
- bun dev plugin list --json
70
- bun dev plugin list --available --json
71
- ```
31
+ Authentication commands.
72
32
 
73
- #### `plugin install <name...>`
33
+ #### `auth login`
74
34
 
75
- Install one or more plugins from the Findr catalog.
35
+ Authenticate and save credentials.
76
36
 
77
37
  ```bash
78
- flow-plugins plugin install <name...> [options]
38
+ flow auth login [options]
79
39
  ```
80
40
 
81
41
  | Option | Description |
82
42
  |---|---|
83
- | `--force` | Reinstall even if the version is already installed |
84
- | `--verbose` | Display each step of the installation process |
85
- | `--silent` | Output in JSON only |
86
-
87
- ```bash
88
- # install a single plugin
89
- bun dev plugin install flow-adr-writer
90
-
91
- # install multiple plugins
92
- bun dev plugin install flow-adr-writer flow-prd-writer startup-pack-ai
93
-
94
- # force reinstall
95
- bun dev plugin install flow-adr-writer --force
96
-
97
- # silent (JSON output)
98
- bun dev plugin install flow-adr-writer --silent
99
- ```
100
-
101
- #### `plugin uninstall <id>`
43
+ | `--client-id <id>` | Client ID |
44
+ | `--client-secret <secret>` | Client Secret |
45
+ | `--tenant <tenant>` | Tenant |
102
46
 
103
- Uninstall a plugin by ID.
47
+ When called **without options**, enters interactive mode — prompts for each field in the terminal.
48
+ When called **with all three options**, runs non-interactively and saves credentials directly.
104
49
 
105
50
  ```bash
106
- bun dev plugin uninstall <id>
107
- ```
108
-
109
- #### `plugin enable <id>`
110
-
111
- Enable an installed plugin.
51
+ # interactive mode
52
+ flow auth login
112
53
 
113
- ```bash
114
- bun dev plugin enable <id>
54
+ # non-interactive mode
55
+ flow auth login --client-id <id> --client-secret <secret> --tenant <tenant>
115
56
  ```
116
57
 
117
- #### `plugin disable <id>`
58
+ #### `auth logout`
118
59
 
119
- Disable an installed plugin.
60
+ Remove saved credentials.
120
61
 
121
62
  ```bash
122
- bun dev plugin disable <id>
63
+ flow auth logout [--force]
123
64
  ```
124
65
 
125
- #### `plugin update [name]`
126
-
127
- Update plugins to the latest version. Omit the name to update all installed plugins.
128
-
129
- ```bash
130
- flow-plugins plugin update [name] [options]
131
- ```
66
+ #### `auth status`
132
67
 
133
- | Option | Description |
134
- |---|---|
135
- | `--force` | Force update even if already on latest version |
136
- | `--dry-run` | Show what would be updated without making changes |
137
- | `--verbose` | Display each step of the update process |
138
- | `--silent` | Output in JSON only |
68
+ Show current authentication status.
139
69
 
140
70
  ```bash
141
- # update a specific plugin
142
- bun dev plugin update flow-adr-writer
143
-
144
- # force update
145
- bun dev plugin update flow-adr-writer --force
146
-
147
- # dry-run (preview only)
148
- bun dev plugin update flow-adr-writer --dry-run
149
-
150
- # verbose (detailed logs)
151
- bun dev plugin update flow-adr-writer --verbose
152
-
153
- # silent (JSON output)
154
- bun dev plugin update flow-adr-writer --silent
155
-
156
- # update all plugins
157
- bun dev plugin update
158
-
159
- # dry-run all
160
- bun dev plugin update --dry-run
71
+ flow auth status
161
72
  ```
162
73
 
163
74
  ---
164
75
 
165
- ### `auth`
76
+ ### `plugin`
166
77
 
167
- Authentication commands.
78
+ Plugin management commands.
168
79
 
169
- #### `auth login`
80
+ #### `plugin list`
170
81
 
171
- Authenticate and save credentials.
82
+ List plugins.
172
83
 
173
84
  ```bash
174
- flow-plugins auth login [options]
85
+ flow plugin list [options]
175
86
  ```
176
87
 
177
88
  | Option | Description |
178
89
  |---|---|
179
- | `--client-id <id>` | Client ID |
180
- | `--client-secret <secret>` | Client Secret |
181
- | `--tenant <tenant>` | Tenant |
182
-
183
- When called **without options**, enters interactive mode — prompts for each field in the terminal. The tenant field is pre-filled if one is detected from the environment.
184
-
185
- When called **with all three options**, runs non-interactively and saves credentials directly.
90
+ | `--available` | Show all plugins from catalog with install status |
91
+ | `--outdated` | Show installed plugins with updates available |
92
+ | `--json` | Output as JSON |
186
93
 
187
94
  ```bash
188
- # interactive mode
189
- bun dev auth login
190
-
191
- # non-interactive mode
192
- bun dev auth login --client-id aa --client-secret bbb --tenant cit-dev
95
+ flow plugin list # list installed plugins
96
+ flow plugin list --available # list all plugins from catalog
97
+ flow plugin list --outdated # list plugins with updates available
98
+ flow plugin list --json # output as JSON
193
99
  ```
194
100
 
195
- #### `auth logout`
101
+ #### `plugin install <name...>`
196
102
 
197
- Remove saved credentials.
103
+ Install one or more plugins.
198
104
 
199
105
  ```bash
200
- flow-plugins auth logout [options]
106
+ flow plugin install <name...> [options]
201
107
  ```
202
108
 
203
109
  | Option | Description |
204
110
  |---|---|
205
- | `--force` | Skip confirmation prompt |
111
+ | `--force` | Reinstall even if already installed |
112
+ | `--verbose` | Display each installation step |
113
+ | `--silent` | Output as JSON only |
206
114
 
207
115
  ```bash
208
- # with confirmation prompt
209
- bun dev auth logout
210
-
211
- # skip confirmation
212
- bun dev auth logout --force
116
+ flow plugin install flow-adr-writer
117
+ flow plugin install flow-adr-writer flow-prd-writer
118
+ flow plugin install flow-adr-writer --force
213
119
  ```
214
120
 
215
- #### `auth status`
121
+ #### `plugin uninstall <id>`
216
122
 
217
- Show authentication status.
123
+ Uninstall a plugin by ID.
218
124
 
219
125
  ```bash
220
- bun dev auth status
126
+ flow plugin uninstall <id>
221
127
  ```
222
128
 
223
- ---
224
-
225
- ### `health`
129
+ #### `plugin enable <id>` / `plugin disable <id>`
226
130
 
227
- Run diagnostic checks.
131
+ Enable or disable an installed plugin.
228
132
 
229
133
  ```bash
230
- bun dev health
134
+ flow plugin enable <id>
135
+ flow plugin disable <id>
231
136
  ```
232
137
 
233
- ## Logging
234
-
235
- The CLI uses a dual-mode logger that adapts to the execution context.
236
-
237
- ### TUI mode (interactive)
238
-
239
- When running without arguments (`flow`), Ink owns stdout. All logs go to **stderr** and a **log file** at `~/.flow/logs/flowsetup.log`.
138
+ #### `plugin update [name]`
240
139
 
241
- - Default level: **warn** (only warnings and errors)
242
- - Use the `DEBUG` env var to enable debug output:
140
+ Update plugins to the latest version. Omit the name to update all installed plugins.
243
141
 
244
142
  ```bash
245
- # all modules
246
- DEBUG=flow:* bun run dev
247
-
248
- # specific module only (others stay at warn+)
249
- DEBUG=flow:installer bun run dev
143
+ flow plugin update [name] [options]
250
144
  ```
251
145
 
252
- ### CLI mode (subcommands)
253
-
254
- When running a subcommand (e.g. `flow plugin install`), the logger writes to **stdout** by default.
255
-
256
- | Flag | Behavior |
146
+ | Option | Description |
257
147
  |---|---|
258
- | _(none)_ | Plain text to stdout, **info** level and above |
259
- | `--verbose` | Timestamped output to stderr, **debug** level and above |
260
- | `--silent` | JSON to stdout (info/debug) or stderr (warn/error) |
148
+ | `--force` | Force update even if already on latest version |
149
+ | `--dry-run` | Preview what would be updated without making changes |
150
+ | `--verbose` | Display each update step |
151
+ | `--silent` | Output as JSON only |
261
152
 
262
153
  ```bash
263
- flow plugin install my-plugin --verbose
264
- flow plugin install my-plugin --silent
265
- flow plugin update my-plugin --verbose
266
- flow plugin update my-plugin --silent
154
+ flow plugin update flow-adr-writer
155
+ flow plugin update # update all
156
+ flow plugin update --dry-run # preview only
267
157
  ```
268
158
 
269
- ### Credential sanitization
270
-
271
- Every log message is automatically sanitized before being written. The following patterns are masked:
272
-
273
- - Bearer tokens
274
- - JWT tokens (`eyJ...` three-segment format)
275
- - Long base64 strings (>40 chars)
276
-
277
- ### Log file rotation
278
-
279
- The log file at `~/.flow/logs/flowsetup.log` is truncated when it exceeds **5 MB** at startup.
280
-
281
159
  ---
282
160
 
283
- ## Versioning & Releases
284
-
285
- This project uses [Changesets](https://github.com/changesets/changesets) for version management and automated releases.
286
-
287
- ### How it works
288
-
289
- 1. Developers add a **changeset** describing their changes before opening a PR
290
- 2. On merge to `main`, a GitHub Action detects pending changesets and opens a **"Version Packages"** PR
291
- 3. That PR bumps the version in `package.json`, updates `CHANGELOG.md`, and removes consumed changesets
292
- 4. Merging the Version Packages PR triggers an automated **npm publish** with provenance
293
-
294
- The version is read at runtime from `package.json` — there is no hardcoded version constant to keep in sync.
295
-
296
- ### Adding a changeset
297
-
298
- After making your changes and before opening a PR, run:
299
-
300
- ```bash
301
- bunx changeset
302
- ```
303
-
304
- You'll be prompted to:
305
- - Select the semver bump type (`patch`, `minor`, or `major`)
306
- - Write a summary of the change (this goes into the CHANGELOG)
307
-
308
- This creates a markdown file in `.changeset/`. Commit it with your PR.
309
-
310
- > **When to use each bump type:**
311
- > - `patch` — bug fixes, docs, internal refactors
312
- > - `minor` — new features, non-breaking additions
313
- > - `major` — breaking changes
161
+ ### `health`
314
162
 
315
- ### Release scripts
163
+ Run diagnostic checks.
316
164
 
317
165
  ```bash
318
- bun run changeset # Add a new changeset
319
- bun run version-packages # Apply pending changesets (bump version + CHANGELOG)
320
- bun run release # Build + publish to npm
166
+ flow health
321
167
  ```
322
168
 
323
- These are used by CI — you typically only need `bunx changeset` locally.
324
-
325
- ### CI/CD
326
-
327
- | Workflow | Trigger | What it does |
328
- |---|---|---|
329
- | `ci.yml` | Pull requests to `main` | Runs lint, test, and build |
330
- | `release.yml` | Push to `main` | Runs CI checks, then creates a Version Packages PR or publishes to npm |
331
-
332
- The release workflow requires two secrets configured in the repository:
333
- - `GITHUB_TOKEN` — provided automatically by GitHub Actions
334
- - `NPM_TOKEN` — npm access token with publish permissions
169
+ ---
335
170
 
336
171
  ## License
337
172
 
338
- MIT
173
+ Copyright (c) CI&T Inc. All rights reserved. See LICENSE.md for details.
package/dist/index.js CHANGED
@@ -1,75 +1,75 @@
1
1
  #!/usr/bin/env node
2
- import {Box,Text,render,useInput}from'ink';import ao,{useMemo,useEffect,useState,useCallback,useRef}from'react';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {create}from'zustand';import Jr,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import Lr from'conf';import*as E from'fs';import E__default,{readFileSync,existsSync,chmodSync,realpathSync}from'fs';import*as q from'path';import q__default,{join}from'path';import*as Q from'os';import Q__default,{homedir}from'os';import eo from'ink-big-text';import to from'ink-gradient';import x from'chalk';import bo from'ink-spinner';import*as N from'fs/promises';import ko from'extract-zip';import Ro from'proper-lockfile';import {randomUUID}from'crypto';import Ct from'semver';import {Command}from'commander';var kr=16;function Bt({label:e,value:t,onChange:n,masked:r=false,isActive:o,error:i}){let s=useRef(t);useEffect(()=>{s.current=t;},[t]),useInput((u,c)=>{if(c.backspace||c.delete){let m=s.current.slice(0,-1);s.current=m,n(m);}else if(u&&!c.ctrl&&!c.meta&&!c.escape&&!c.return&&!c.tab&&!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow){let m=s.current+u;s.current=m,n(m);}},{isActive:o});let a=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(kr)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}var j=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 p=create(e=>({activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,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})}));var Oe="FLOW",b="flow-skills";var Z=new Lr({projectName:Oe});function jt(){try{chmodSync(Z.path,384);}catch{}}function C(){let e=Z.get("credentials");if(!e)return null;try{return JSON.parse(e)}catch{return null}}function _t(e){Z.set("credentials",JSON.stringify(e)),jt();}function Kt(){Z.delete("credentials"),Z.delete("tokenCache");}function Jt(){return Z.path}function qt(e){Z.set("tokenCache",{accessToken:e.accessToken,expiresAt:e.expiresAt}),jt();}function lt(){let e=Z.get("tokenCache");return e?{accessToken:e.accessToken,expiresAt:e.expiresAt}:null}function D(){let e=lt();return e?new Date(e.expiresAt)>new Date:false}var Ur=[/^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 Dr(e){return Ur.some(t=>t.test(e))}function Or(e,t){let n=process.env[e]??t;if(!n)throw new Error(`Missing required environment variable: ${e}`);return n}function Fe(e,t){let n=Or(e,t),r;try{r=new URL(n);}catch{throw new Error(`${e} must be a valid URL. Got: "${n}"`)}if(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(Dr(r.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${r.hostname}"`);return n}var Fr=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Nr=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,Br=/[A-Za-z0-9+/]{40,}={0,2}/g;function ct(e){return e.replace(Fr,"Bearer ***").replace(Nr,"***").replace(Br,"***")}var Pe=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 Ie=".claude",Ht=".flow";function Vt(e,t){return q.join(Q.homedir(),Ie,"plugins","cache",b,e,t)}function ut(e){return q.join(Q.homedir(),Ie,"plugins","marketplaces",b,"plugins","native",e)}function Ne(){return q.join(Q.homedir(),Ie,"plugins","marketplaces",b,".claude-plugin","marketplace.json")}function zt(){return q.join(Q.homedir(),Ie,"plugins","known_marketplaces.json")}function Gt(){return q.join(Q.homedir(),Ie,"plugins","marketplaces",b)}function Xt(){return q.join(Q.homedir(),Ht,"cache","install.lock")}function Wt(){return q.join(Q.homedir(),Ht,"logs","flowsetup.log")}var jr=5*1024*1024,_r=3,Be=class{filePath;constructor(){this.filePath=Wt(),this.ensureDir(),this.rotateIfNeeded();}write(t){let n=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
4
- `;try{E.appendFileSync(this.filePath,n,"utf-8");}catch{}}ensureDir(){try{let t=q.dirname(this.filePath);E.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(E.statSync(this.filePath).size>jr){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=this.filePath.replace(".log",`-${n}.log`);E.renameSync(this.filePath,r),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=q.dirname(this.filePath),n=q.basename(this.filePath,".log"),r=E.readdirSync(t).filter(o=>o.startsWith(n+"-")&&o.endsWith(".log")).sort().reverse();for(let o of r.slice(_r))E.unlinkSync(q.join(t,o));}catch{}}};var je=class{write(t){process.stdout.write(t.message+`
5
- `);}};var fe={debug:0,info:1,warn:2,error:3},le={context:"cli",transports:[],minLevel:"warn",debugModules:null};function Kr(){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 _(e,t){if(e==="tui"){let n=Kr();le={context:e,transports:[new Pe("tui"),new Be],minLevel:n?"debug":"warn",debugModules:n};}else t?.silent?le={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?le={context:e,transports:[new Pe("cli")],minLevel:"debug",debugModules:null}:le={context:e,transports:[new je],minLevel:"info",debugModules:null};}function Zt(){return le.transports}function Qt(e,t){let{debugModules:n,minLevel:r}=le;return le.context==="tui"&&n&&n!=="all"?n.has(t)?fe[e]>=fe.debug:fe[e]>=fe.warn:fe[e]>=fe[r]}var Yt=new Map;function _e(e,t,n){if(!Qt(e,t))return;let r={level:e,module:t,message:ct(n),timestamp:new Date};for(let o of Zt())o.write(r);}function S(e){let t=Yt.get(e);if(t)return t;let n={debug:r=>_e("debug",e,r),info:r=>_e("info",e,r),warn:r=>_e("warn",e,r),error:r=>_e("error",e,r)};return Yt.set(e,n),n}var dt=S("api:auth"),Hr=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function Vr(e){if(!Hr.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var en={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 zr(e){if(e instanceof HTTPError){let t=e.response.status;dt.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&&en[n]?new Error(en[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?(dt.debug(`Non-HTTP error during authentication: ${e.message}`),e):(dt.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Ee(e){let t=Fe("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Vr(e.tenant);let n;try{n=await Jr.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(o){throw await zr(o)}let r=n.expires_at??new Date(Date.now()+(n.expires_in??3600)*1e3).toISOString();_t(e),qt({accessToken:n.access_token,expiresAt:r});}async function tn(){if(D()){let e=lt();if(!e)throw new Error("Flow CLI not configured. Run: flow-cli auth login");return e.accessToken}throw new Error("Flow CLI not configured or token expired. Run: flow-cli auth login")}var O=["clientId","clientSecret","tenant"],Xr={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function nn(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[n,r]=useState("clientId"),[o,i]=useState({}),[s,a]=useState(null),[u,c]=useState(false),{setCredentials:m,setJustAuthenticated:h}=j(),{setFocus:T}=p();useInput((l,d)=>{if(!u){if(d.shift&&d.tab){let f=O.indexOf(n);f>0&&r(O[f-1]);}else if(d.tab){let f=O.indexOf(n);f<O.length-1&&r(O[f+1]);}else if(d.return)if(n==="tenant")ie();else {let f=O.indexOf(n);r(O[f+1]);}}},{isActive:true});let ie=async()=>{let l={};for(let d of O)e[d].trim()||(l[d]="This field is required");if(Object.keys(l).length>0){i(l);let d=O.find(f=>l[f]);d&&r(d);return}c(true),a(null);try{await Ee({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()});let{clientSecret:d,...f}=e;m(f),h(!0),T("list");}catch(d){a(d instanceof Error?d.message:"Authentication failed");}finally{c(false),t(d=>({...d,clientSecret:""}));}},se=l=>d=>{t(f=>({...f,[l]:d})),o[l]&&i(f=>({...f,[l]:void 0}));};return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Oe," \u2014 Initial Setup"]})}),jsx(Box,{flexDirection:"column",children:O.map(l=>jsx(Box,{marginBottom:1,children:jsx(Bt,{label:Xr[l],value:e[l],onChange:se(l),masked:l==="clientSecret",isActive:n===l&&!u,error:o[l]})},l))}),u&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),s&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}var Qr=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8")),Je=Qr.version;function sn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(to,{name:"morning",children:jsx(eo,{text:"FLOW",font:"block"})}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",Je]})})]})}var gt={discover:"Discover",installed:"Installed"},no=Object.keys(gt);function ln(){let e=p(t=>t.activeTab);return jsxs(Box,{paddingX:1,paddingBottom:1,children:[no.map(t=>jsx(Box,{marginRight:2,children:t===e?jsx(Text,{bold:true,underline:true,color:"cyan",children:gt[t]}):jsx(Text,{dimColor:true,children:gt[t]})},t)),jsx(Text,{dimColor:true,children:"(Tab to cycle)"})]})}var F=create(e=>({query:"",setQuery:t=>e({query:t}),resetQuery:()=>e({query:""})}));function un(){let e=p(r=>r.focus),t=F(r=>r.query),n=e==="search";return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u03C1 "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}function I(e){return 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 me(e){process.stdout.write(x.green(` \u2713 ${I(e)}
2
+ import {Box,Text,render,useInput}from'ink';import ao,{useMemo,useEffect,useState,useCallback,useRef}from'react';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {create}from'zustand';import qr,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import Mr from'conf';import*as E from'fs';import E__default,{readFileSync,existsSync,chmodSync,realpathSync}from'fs';import*as q from'path';import q__default,{join}from'path';import*as Q from'os';import Q__default,{homedir}from'os';import eo from'ink-big-text';import to from'ink-gradient';import x from'chalk';import bo from'ink-spinner';import*as N from'fs/promises';import ko from'extract-zip';import Ro from'proper-lockfile';import {randomUUID}from'crypto';import Lt from'semver';import {Command}from'commander';var Rr=16;function jt({label:e,value:t,onChange:n,masked:r=false,isActive:o,error:i}){let s=useRef(t);useEffect(()=>{s.current=t;},[t]),useInput((u,c)=>{if(c.backspace||c.delete){let m=s.current.slice(0,-1);s.current=m,n(m);}else if(u&&!c.ctrl&&!c.meta&&!c.escape&&!c.return&&!c.tab&&!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow){let m=s.current+u;s.current=m,n(m);}},{isActive:o});let a=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(Rr)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}var j=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 p=create(e=>({activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,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})}));var Oe="FLOW",b="flow-skills",Fe=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var Z=new Mr({projectName:Oe});function _t(){try{chmodSync(Z.path,384);}catch{}}function C(){let e=Z.get("credentials");if(!e)return null;try{return JSON.parse(e)}catch{return null}}function Kt(e){Z.set("credentials",JSON.stringify(e)),_t();}function Jt(){Z.delete("credentials"),Z.delete("tokenCache");}function qt(){return Z.path}function Ht(e){Z.set("tokenCache",{accessToken:e.accessToken,expiresAt:e.expiresAt}),_t();}function ct(){let e=Z.get("tokenCache");return e?{accessToken:e.accessToken,expiresAt:e.expiresAt}:null}function D(){let e=ct();return e?new Date(e.expiresAt)>new Date:false}var Dr=[/^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 Or(e){return Dr.some(t=>t.test(e))}function Fr(e,t){let n=process.env[e]??t;if(!n)throw new Error(`Missing required environment variable: ${e}`);return n}function Ne(e,t){let n=Fr(e,t),r;try{r=new URL(n);}catch{throw new Error(`${e} must be a valid URL. Got: "${n}"`)}if(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(Or(r.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${r.hostname}"`);return n}var Nr=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Br=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,jr=/[A-Za-z0-9+/]{40,}={0,2}/g;function ut(e){return e.replace(Nr,"Bearer ***").replace(Br,"***").replace(jr,"***")}var Pe=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 Ie=".claude",Vt=".flow";function zt(e,t){return q.join(Q.homedir(),Ie,"plugins","cache",b,e,t)}function dt(e){return q.join(Q.homedir(),Ie,"plugins","marketplaces",b,"plugins","native",e)}function Be(){return q.join(Q.homedir(),Ie,"plugins","marketplaces",b,".claude-plugin","marketplace.json")}function Gt(){return q.join(Q.homedir(),Ie,"plugins","known_marketplaces.json")}function Xt(){return q.join(Q.homedir(),Ie,"plugins","marketplaces",b)}function Wt(){return q.join(Q.homedir(),Vt,"cache","install.lock")}function Zt(){return q.join(Q.homedir(),Vt,"logs","flowsetup.log")}var _r=5*1024*1024,Kr=3,je=class{filePath;constructor(){this.filePath=Zt(),this.ensureDir(),this.rotateIfNeeded();}write(t){let n=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
4
+ `;try{E.appendFileSync(this.filePath,n,"utf-8");}catch{}}ensureDir(){try{let t=q.dirname(this.filePath);E.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(E.statSync(this.filePath).size>_r){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=this.filePath.replace(".log",`-${n}.log`);E.renameSync(this.filePath,r),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=q.dirname(this.filePath),n=q.basename(this.filePath,".log"),r=E.readdirSync(t).filter(o=>o.startsWith(n+"-")&&o.endsWith(".log")).sort().reverse();for(let o of r.slice(Kr))E.unlinkSync(q.join(t,o));}catch{}}};var _e=class{write(t){process.stdout.write(t.message+`
5
+ `);}};var fe={debug:0,info:1,warn:2,error:3},le={context:"cli",transports:[],minLevel:"warn",debugModules:null};function Jr(){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 _(e,t){if(e==="tui"){let n=Jr();le={context:e,transports:[new Pe("tui"),new je],minLevel:n?"debug":"warn",debugModules:n};}else t?.silent?le={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?le={context:e,transports:[new Pe("cli")],minLevel:"debug",debugModules:null}:le={context:e,transports:[new _e],minLevel:"info",debugModules:null};}function Qt(){return le.transports}function Yt(e,t){let{debugModules:n,minLevel:r}=le;return le.context==="tui"&&n&&n!=="all"?n.has(t)?fe[e]>=fe.debug:fe[e]>=fe.warn:fe[e]>=fe[r]}var en=new Map;function Ke(e,t,n){if(!Yt(e,t))return;let r={level:e,module:t,message:ut(n),timestamp:new Date};for(let o of Qt())o.write(r);}function S(e){let t=en.get(e);if(t)return t;let n={debug:r=>Ke("debug",e,r),info:r=>Ke("info",e,r),warn:r=>Ke("warn",e,r),error:r=>Ke("error",e,r)};return en.set(e,n),n}var pt=S("api:auth");function Vr(e){if(!Fe.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var tn={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 zr(e){if(e instanceof HTTPError){let t=e.response.status;pt.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&&tn[n]?new Error(tn[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?(pt.debug(`Non-HTTP error during authentication: ${e.message}`),e):(pt.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Ee(e){let t=Ne("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Vr(e.tenant);let n;try{n=await qr.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(o){throw await zr(o)}let r=n.expires_at??new Date(Date.now()+(n.expires_in??3600)*1e3).toISOString();Kt(e),Ht({accessToken:n.access_token,expiresAt:r});}async function nn(){if(D()){let e=ct();if(!e)throw new Error("Flow CLI not configured. Run: flow-cli auth login");return e.accessToken}throw new Error("Flow CLI not configured or token expired. Run: flow-cli auth login")}var O=["clientId","clientSecret","tenant"],Xr={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function rn(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[n,r]=useState("clientId"),[o,i]=useState({}),[s,a]=useState(null),[u,c]=useState(false),{setCredentials:m,setJustAuthenticated:h}=j(),{setFocus:T}=p();useInput((l,d)=>{if(!u){if(d.shift&&d.tab){let f=O.indexOf(n);f>0&&r(O[f-1]);}else if(d.tab){let f=O.indexOf(n);f<O.length-1&&r(O[f+1]);}else if(d.return)if(n==="tenant")ie();else {let f=O.indexOf(n);r(O[f+1]);}}},{isActive:true});let ie=async()=>{let l={};for(let d of O)e[d].trim()||(l[d]="This field is required");if(Object.keys(l).length>0){i(l);let d=O.find(f=>l[f]);d&&r(d);return}c(true),a(null);try{await Ee({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()});let{clientSecret:d,...f}=e;m(f),h(!0),T("list");}catch(d){a(d instanceof Error?d.message:"Authentication failed");}finally{c(false),t(d=>({...d,clientSecret:""}));}},se=l=>d=>{t(f=>({...f,[l]:d})),o[l]&&i(f=>({...f,[l]:void 0}));};return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Oe," \u2014 Initial Setup"]})}),jsx(Box,{flexDirection:"column",children:O.map(l=>jsx(Box,{marginBottom:1,children:jsx(jt,{label:Xr[l],value:e[l],onChange:se(l),masked:l==="clientSecret",isActive:n===l&&!u,error:o[l]})},l))}),u&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),s&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}var Qr=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8")),qe=Qr.version;function an(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(to,{name:"morning",children:jsx(eo,{text:"FLOW",font:"block"})}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",qe]})})]})}var ht={discover:"Discover",installed:"Installed"},no=Object.keys(ht);function cn(){let e=p(t=>t.activeTab);return jsxs(Box,{paddingX:1,paddingBottom:1,children:[no.map(t=>jsx(Box,{marginRight:2,children:t===e?jsx(Text,{bold:true,underline:true,color:"cyan",children:ht[t]}):jsx(Text,{dimColor:true,children:ht[t]})},t)),jsx(Text,{dimColor:true,children:"(Tab to cycle)"})]})}var F=create(e=>({query:"",setQuery:t=>e({query:t}),resetQuery:()=>e({query:""})}));function dn(){let e=p(r=>r.focus),t=F(r=>r.query),n=e==="search";return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u03C1 "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}function I(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 me(e){process.stdout.write(x.green(` \u2713 ${I(e)}
6
6
  `));}function P(e){process.stderr.write(x.red(` \u2717 ${I(e)}
7
7
  `));}function w(e){process.stdout.write(x.cyan(` \u2139 ${I(e)}
8
- `));}function ze(e,t){let n=t.map(a=>a.map(I)),r=[e,...n],o=e.map((a,u)=>Math.max(...r.map(c=>(c[u]??"").length))),i=o.map(a=>"\u2500".repeat(a)).join(" "),s=a=>a.map((u,c)=>u.padEnd(o[c])).join(" ");process.stdout.write(`
8
+ `));}function Ge(e,t){let n=t.map(a=>a.map(I)),r=[e,...n],o=e.map((a,u)=>Math.max(...r.map(c=>(c[u]??"").length))),i=o.map(a=>"\u2500".repeat(a)).join(" "),s=a=>a.map((u,c)=>u.padEnd(o[c])).join(" ");process.stdout.write(`
9
9
  `),process.stdout.write(` ${x.bold(s(e))}
10
10
  `),process.stdout.write(` ${x.dim(i)}
11
11
  `);for(let a of n)process.stdout.write(` ${s(a)}
12
12
  `);process.stdout.write(`
13
- `);}function Ge(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
- `);}function Xe(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var dn=ao.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}`:""," \xB7 v",t.version]}),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 ",Xe(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function fn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}var wt=5;function gn({items:e,emptyMessage:t}){let n=p(u=>u.selectedIndex);if(e.length===0)return jsx(fn,{message:t});let r=Math.max(0,n-Math.floor(wt/2)),o=Math.min(e.length,r+wt);o===e.length&&(r=Math.max(0,o-wt));let i=e.slice(r,o),s=r,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[s>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",s," more above"]})}),i.map((u,c)=>jsx(dn,{item:u,isSelected:r+c===n},u.name)),a>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",a," more below"]})})]})}var uo={discover:"Discover plugins",installed:"Installed plugins"};function yn({items:e,tabId:t,emptyMessage:n}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,children:uo[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),jsx(un,{}),jsx(gn,{items:e,emptyMessage:n})]})}function wn({filteredItems:e,emptyMessage:t}){let n=p(r=>r.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(yn,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(yn,{items:e,tabId:"installed",emptyMessage:t},"installed")})}var mo={tabs:"Tab: switch tab | \u2191\u2193: navigate | Enter: select | /: search | q: quit",list:"Tab: switch tab | \u2191\u2193: navigate | Enter: select | /: search | q: quit",search:"Type to filter | Esc: cancel search | Enter: confirm",actionMenu:"\u2191\u2193: navigate options | Enter: confirm | Esc: close menu",auth:"Tab: next field | Enter: confirm | Ctrl+C: quit"};function bn(){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:mo[e]})})}function vn({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 En({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(bo,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function $n({message:e,onRetry:t,onBack:n}){return useInput((r,o)=>{r==="r"&&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 r to retry"}),n&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function Ze({itemName:e,actions:t,onAction:n,onClose:r}){let o=p(a=>a.focus),[i,s]=useState(0);return useInput((a,u)=>{u.upArrow?s(c=>c>0?c-1:c):u.downArrow?s(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&r();},{isActive:o==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((a,u)=>jsx(Box,{children:jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",a]})},u))})]})}function Cn({itemName:e,onInstall:t,onClose:n}){return jsx(Ze,{itemName:e,actions:["Install","Cancel"],onAction:i=>{i==="Install"?t():n();},onClose:n})}function Un({itemName:e,itemStatus:t,updateAvailable:n,catalogVersion:r,onUninstall:o,onToggleStatus:i,onUpdate:s,onClose:a}){let[u,c]=useState(false),m=p(l=>l.focus);if(useInput((l,d)=>{d.escape||l==="n"?c(false):l==="y"&&o();},{isActive:u&&m==="actionMenu"}),u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,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",T=r?`Update to v${r}`:"Update";return jsx(Ze,{itemName:e,actions:n?["Uninstall",h,T,"Cancel"]:["Uninstall",h,"Cancel"],onAction:l=>{l==="Uninstall"?c(true):l===h?i():l.startsWith("Update")?s?.():a();},onClose:a})}async function Dn(e,t){let n=q.resolve(t);await N.mkdir(n,{recursive:true});let r=q.join(q.dirname(n),`${randomUUID()}.zip`);try{await N.writeFile(r,e),await ko(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=q.resolve(n,o.fileName);if(!s.startsWith(n+q.sep)&&s!==n)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(n);if(!o.startsWith(q.resolve(q.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 N.unlink(r);}catch{}}}async function Et(e){await N.rm(e,{recursive:true,force:true});}async function te(){let e=Xt();await N.mkdir(q.dirname(e),{recursive:true});try{await N.writeFile(e,"",{flag:"wx"});}catch(n){if(n.code!=="EEXIST")throw n}return await Ro.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Lo(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:b,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Fn(){let e=Ne();if(!E__default.existsSync(e))return null;try{return JSON.parse(E__default.readFileSync(e,"utf-8"))}catch{return null}}function Mo(){let e=Fn();if(e)return e;let t=Lo(),n=Ne();return E__default.mkdirSync(q__default.dirname(n),{recursive:true}),Tt(t),t}function Tt(e){let t=Ne(),n=`${t}.tmp`;E__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),E__default.renameSync(n,t);}function Uo(){let e=zt(),t={};try{E__default.existsSync(e)&&(t=JSON.parse(E__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[b])return;t[b]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:Gt(),lastUpdated:new Date().toISOString()};let n=`${e}.tmp`;E__default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8"),E__default.renameSync(n,e);}function Nn(e,t){Uo();let n=ut(e.name);E__default.mkdirSync(q__default.dirname(n),{recursive:true});try{E__default.lstatSync(n),E__default.rmSync(n,{recursive:!0,force:!0});}catch{}E__default.symlinkSync(t,n);let r=Mo();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}),Tt(r));}function Bn(e){let t=ut(e);try{E__default.rmSync(t,{recursive:!0,force:!0});}catch{}let n=Fn();if(!n)return;let r=n.plugins.length;n.plugins=n.plugins.filter(o=>o.name!==e),n.plugins.length!==r&&Tt(n);}var J=S("storage");function jn(){return q__default.join(Q__default.homedir(),".claude","plugins","installed_plugins.json")}function Do(){return q__default.join(Q__default.homedir(),".claude","plugins")}function Oo(e){let t=q__default.resolve(e),n=q__default.resolve(Do());if(!t.startsWith(n+q__default.sep)&&t!==n)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function _n(){return q__default.join(Q__default.homedir(),".claude","settings.json")}function H(){let e=jn();if(!E__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(E__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}function Ce(e){let t=jn();E__default.mkdirSync(q__default.dirname(t),{recursive:true});let n=`${t}.tmp`;E__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),E__default.renameSync(n,t);}function Re(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Fo(e){let t=q__default.join(e,".claude-plugin","plugin.json");if(!E__default.existsSync(t))return null;try{return JSON.parse(E__default.readFileSync(t,"utf-8"))}catch{return null}}function $t(){let e=_n();if(!E__default.existsSync(e))return {};try{return JSON.parse(E__default.readFileSync(e,"utf-8"))}catch{return {}}}function Kn(e){let t=_n(),n=`${t}.tmp`;E__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),E__default.renameSync(n,t);}function No(){return $t().enabledPlugins??{}}function Bo(e){let t=$t(),n=t.enabledPlugins;if(!n||!(e in n))return;let{[e]:r,...o}=n;t.enabledPlugins=o,Kn(t);}function kt(e,t){let n=$t(),r=n.enabledPlugins??{};n.enabledPlugins={...r,[e]:t},Kn(n);}function R(){let e=H(),t=No();return Object.entries(e.plugins).map(([n,r])=>{let o=r[0],{name:i,marketplace:s}=Re(n),a=Fo(o.installPath),u=t[n];return {name:i,marketplace:s,version:o.version,installedAt:o.installedAt,installPath:o.installPath,scope:o.scope,description:a?.description,author:a?.author,status:u===false?"disabled":"enabled"}})}async function Ye(e){J.debug(`[${e}] Acquiring lock to uninstall`);let t=await te();try{let{name:n,marketplace:r}=Re(e),o=H(),i;if(r?(i=`${n}@${r}`,o.plugins[i]||(i=void 0)):i=Object.keys(o.plugins).filter(h=>Re(h).name===n)[0],!i)throw J.error(`[${n}] Plugin is not installed`),new Error(`Plugin '${n}' is not installed`);J.debug(`[${n}] Resolved key: ${i}`);let s=o.plugins[i][0].installPath;Oo(s);let a=q__default.dirname(s);J.debug(`[${n}] Removing directory: ${a}`),E__default.rmSync(a,{recursive:!0,force:!0}),Bn(n);let{[i]:u,...c}=o.plugins;Ce({...o,plugins:c}),Bo(i),J.debug(`[${n}] Uninstalled successfully`);}finally{await t();}}async function Le(e,t){J.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await te();try{let{name:r}=Re(e),o=H(),i=Object.keys(o.plugins).filter(s=>Re(s).name===r);if(i.length===0)throw J.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);J.debug(`[${r}] Resolved key: ${i[0]}`),kt(i[0],t==="enabled"),J.debug(`[${r}] Status updated to ${t}`);}finally{await n();}}var V=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:R()})}));var L=["discover","installed"];function Jn(e,t,n){if(t.rightArrow||t.tab){let r=L.indexOf(n.activeTab);return [{type:"setTab",tab:L[(r+1)%L.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}if(t.leftArrow){let r=L.indexOf(n.activeTab);return [{type:"setTab",tab:L[(r-1+L.length)%L.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}return t.downArrow?[{type:"setFocus",focus:"list"}]:[]}function qn(e,t,n,r){if(t.upArrow&&n.selectedIndex>0)return [{type:"setSelectedIndex",index:n.selectedIndex-1}];if(t.downArrow&&n.selectedIndex<r-1)return [{type:"setSelectedIndex",index:n.selectedIndex+1}];if(t.tab){let o=L.indexOf(n.activeTab);return [{type:"setTab",tab:L[(o+1)%L.length]},{type:"setSelectedIndex",index:0}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:[]}function Hn(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Vn(e,t){return t.escape?{actions:[{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.return?{actions:[{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace||t.delete?{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}function et(e){let{setActiveTab:t,setFocus:n,setSelectedIndex:r,setActionMenuOpen:o}=p.getState();for(let i of e)i.type==="setTab"?t(i.tab):i.type==="setFocus"?n(i.focus):i.type==="setSelectedIndex"?r(i.index):i.type==="setActionMenuOpen"&&o(i.open);}function Gn({listLength:e}){let t=p(l=>l.focus),n=p(l=>l.selectedIndex),r=p(l=>l.actionMenuOpen),o=p(l=>l.setFocus),i=p(l=>l.setActionMenuOpen),s=F(l=>l.query),a=F(l=>l.setQuery),u=F(l=>l.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]);let[m,h]=useState("");useEffect(()=>{let l=setTimeout(()=>h(s),300);return ()=>clearTimeout(l)},[s]),useInput((l,d)=>{l==="q"&&process.exit(0);},{isActive:t!=="search"&&t!=="auth"}),useInput((l,d)=>{let{activeTab:f,selectedIndex:y,actionMenuOpen:M}=p.getState();et(Jn(l,d,{activeTab:f}));},{isActive:t==="tabs"}),useInput((l,d)=>{let{activeTab:f,selectedIndex:y,actionMenuOpen:M}=p.getState();et(qn(l,d,{activeTab:f,selectedIndex:y},c.current));},{isActive:t==="list"}),useInput((l,d)=>{et(Hn(l,d));},{isActive:t==="actionMenu"}),useInput((l,d)=>{let f=Vn(l,d),y=f.queryUpdate;et(f.actions),y==="reset"?(u(),h("")):y!==null&&("backspace"in y?a(F.getState().query.slice(0,-1)):a(F.getState().query+y.append));},{isActive:t==="search"});let T=useCallback(()=>{i(false),o("list");},[i,o]),ie=useCallback(l=>{let{setSelectedIndex:d,selectedIndex:f}=p.getState();l===0?d(0):f>=l&&d(l-1);},[]),se=useCallback(l=>{if(!m)return c.current=l.length,l;let d=m.toLowerCase(),f=l.filter(y=>y.name.toLowerCase().includes(d)||y.description?.toLowerCase().includes(d));return c.current=f.length,f},[m]);return {actionMenuOpen:r,closeMenu:T,selectedIndex:n,clampIndex:ie,filteredItems:se}}function Wn(){let e=p(a=>a.notification),t=p(a=>a.showNotification),n=p(a=>a.clearNotification),r=j(a=>a.justAuthenticated),o=j(a=>a.credentials),i=j(a=>a.setJustAuthenticated);return useEffect(()=>{r&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),i(false));},[r,o]),useEffect(()=>{if(!e)return;let a=setTimeout(n,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,u)=>{t(a,u);}}}var ye=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";}},ne=class extends Error{constructor(n,r){super(`${n} is already up to date (v${r})`);this.pluginName=n;this.version=r;this.name="AlreadyUpToDateError";}};var qo=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function tt(){return Jr.create({prefixUrl:Fe("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async e=>{let t=await tn();e.headers.set("Authorization",`Bearer ${t}`);let n=C();n?.tenant&&qo.test(n.tenant)&&e.headers.set("FlowTenant",n.tenant);}]}})}var Ho=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function Zn(e){if(!e||!Ho.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function z(){try{let{plugins:e}=await tt().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-cli 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 we(e){Zn(e);try{return await tt().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 Qn(e){Zn(e);try{let t=await tt().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}}var Vo=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function zo(e){if(!Vo.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Ue=S("installer");function Go(e,t){let n=`${e}@${b}`,o=H().plugins[n];if(o&&!t)throw new ye(e,o[0].version);return {pluginKey:n,alreadyInstalled:o}}async function Xo(e,t,n){n&&await Et(t);try{Ue.debug(`Extracting to ${t}...`),await Dn(e,t);}catch(r){throw await Et(t),r}}function Wo(e,t,n){let r=H(),o={scope:"user",installPath:t,version:n,installedAt:new Date().toISOString()};r.plugins[e]=[o],Ce(r),kt(e,true);}async function xe(e,t={}){let n=Date.now(),r=null;try{Ue.debug(`[${e}] Acquiring lock...`),r=await te();let{pluginKey:o,alreadyInstalled:i}=Go(e,t.force);Ue.debug(`[${e}] Fetching manifest...`);let s=await we(e);zo(s.name),Ue.debug(`[${e}] Downloading archive...`);let a=await Qn(e),u=Vt(s.name,s.version);await Xo(a,u,!!i&&!!t.force),Wo(o,u,s.version),Nn(s,u);let c=Date.now()-n;return Ue.debug(`[${e}] Installed successfully in ${c}ms`),{name:s.name,version:s.version,path:u,duration_ms:c}}finally{r&&await r();}}function G(e,t,n=false){return n?true:!Ct.valid(e)||!Ct.valid(t)?false:Ct.gt(t,e)}var re=S("updater");function Zo(e){let t=H(),n=`${e}@${b}`,r=t.plugins[n];return !r||r.length===0?null:{pluginKey:n,entry:r[0]}}async function nt(e,t={}){let n=Date.now(),r=null;try{re.debug(`[${e}] Acquiring lock...`),r=await te();let o=Zo(e);if(!o)throw re.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=o,s=i.version,a=i.installPath;re.debug(`[${e}] Fetching manifest...`);let c=(await we(e)).version;if(!G(s,c,t.force))throw re.debug(`[${e}] Already up to date (v${s})`),new ne(e,s);re.info(`[${e}] Updating v${s} \u2192 v${c}...`),await r(),r=null;try{let m=await xe(e,{force:!0}),h=Date.now()-n;return re.debug(`[${e}] Updated successfully in ${h}ms`),{name:m.name,previousVersion:s,newVersion:m.version,path:m.path,duration_ms:h}}catch(m){re.warn(`[${e}] Install failed, rolling back to v${s}...`),r=await te();let h=H(),T=`${e}@${b}`;throw h.plugins[T]&&(h.plugins[T][0].version=s,h.plugins[T][0].installPath=a,Ce(h),re.info(`[${e}] Rollback completed, restored to v${s}`)),m}}finally{r&&await r();}}function Yn(){let e=V(s=>s.installedItems),t=V(s=>s.setInstalledItems),n=useCallback(async s=>{await xe(s.name),V.getState().loadFromDisk();},[]),r=useCallback(async s=>{await Ye(s),t(e.filter(a=>a.name!==s));},[e,t]),o=useCallback(async s=>{let u=e.find(c=>c.name===s)?.status==="enabled"?"disabled":"enabled";await Le(s,u),t(e.map(c=>c.name===s?{...c,status:u}:c));},[e,t]),i=useCallback(async s=>{await nt(s),V.getState().loadFromDisk();},[]);return {install:n,uninstall:r,toggle:o,update:i}}function er({selectedItem:e,selectedCatalogItem:t,items:n,closeMenu:r,clampIndex:o,notify:i}){let s=p(d=>d.setLoading),{install:a,uninstall:u,toggle:c,update:m}=Yn(),h=async(d,f,y)=>{s(true,d),r();try{await f(),o(n.length),i(y,"success");}catch(M){i(M instanceof Error?M.message:"Something went wrong","error");}finally{s(false);}};return {handleInstall:()=>{e&&t&&h(`Installing ${e.name}...`,()=>a(t),"\u2713 Installed successfully");},handleUninstall:()=>{e&&h(`Uninstalling ${e.name}...`,()=>u(e.name),"\u2713 Uninstalled");},handleToggleStatus:()=>{if(!e)return;let d=e.status==="enabled";h(d?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>c(e.name),d?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let d=t?` to v${t.version}`:"";(async()=>{s(true,`Updating ${e.name}${d}...`),r();try{await m(e.name),o(n.length),i(`\u2713 Updated ${e.name}${d}`,"success");}catch(y){y instanceof ne?i(y.message,"info"):i(y instanceof Error?y.message:"Something went wrong","error");}finally{s(false);}})();}}}function tr(){let[e,t]=useState([]),[n,r]=useState(true),[o,i]=useState(null),s=useCallback(async()=>{r(true),i(null);try{let a=await z();t(a);}catch(a){i(a instanceof Error?a:new Error(String(a))),t([]);}finally{r(false);}},[]);return useEffect(()=>{s();},[s]),{catalog:e,isLoading:n,error:o,refetch:s}}function nr(){return {items:V(t=>t.installedItems)}}var ti=S("catalog");function ni(e){return {name:e.name,version:e.version,description:e.description,authorName:e.author.name,updateAvailable:e.updateAvailable}}function ri(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 rr(){let e=p(g=>g.activeTab),t=p(g=>g.notification),n=p(g=>g.loading),r=p(g=>g.loadingMessage),o=p(g=>g.catalogError),i=p(g=>g.setCatalogError),s=F(g=>g.query),{catalog:a,isLoading:u,error:c,refetch:m}=tr(),{items:h}=nr(),T=V(g=>g.loadFromDisk),ie=useMemo(()=>new Set(h.map(g=>`${g.name}|${g.author?.name??""}|${g.marketplace}`)),[h]),se=useMemo(()=>{let g=new Map(a.map(pe=>[pe.name,pe.version]));return h.map(pe=>{let Nt=g.get(pe.name),Er=!!Nt&&G(pe.version,Nt);return {...pe,updateAvailable:Er}})},[h,a]),l=e==="discover"?a.filter(g=>!ie.has(`${g.name}|${g.author.name}|${b}`)).map(g=>ni(g)):se.map(g=>ri(g)),{actionMenuOpen:d,closeMenu:f,selectedIndex:y,clampIndex:M,filteredItems:wr}=Gn({listLength:l.length}),De=wr(l),U=De[y]??null,Ft=useMemo(()=>U?a.find(g=>g.name===U.name)??null:null,[a,U]),xr=e==="installed"?"No plugins installed \u2014 explore the Discover tab!":s?`No plugins found for '${s}'`:"No plugins available in the catalog",{notify:br}=Wn(),{handleInstall:vr,handleUninstall:Pr,handleToggleStatus:Ir,handleUpdate:Sr}=er({selectedItem:U,selectedCatalogItem:Ft,items:l,closeMenu:f,clampIndex:M,notify:br});return useEffect(()=>{T();},[]),useEffect(()=>{M(De.length);},[De.length,M]),useEffect(()=>{c&&(ti.error(`[usePluginCatalog] ${c instanceof Error?c.message:String(c)}`),i("Failed to load catalog"));},[c]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(sn,{}),jsx(ln,{}),jsx(wn,{filteredItems:De,emptyMessage:xr}),(n||u)&&jsx(En,{message:n?r:"Loading catalog..."}),o&&!u&&e==="discover"&&jsx($n,{message:o,onRetry:()=>{i(null),m();},onBack:()=>i(null)}),t&&jsx(vn,{message:t.message,type:t.type}),d&&U&&e==="discover"&&jsx(Cn,{itemName:U.name,onInstall:vr,onClose:f}),d&&U&&e==="installed"&&jsx(Un,{itemName:U.name,itemStatus:U.status??"enabled",updateAvailable:U.updateAvailable??false,catalogVersion:Ft?.version,onUninstall:Pr,onToggleStatus:Ir,onUpdate:Sr,onClose:f}),jsx(bn,{})]})}var or=C();if(or&&D()){let{clientSecret:e,...t}=or;j.getState().setCredentials(t),p.getState().setFocus("list");}else p.getState().setFocus("auth");function sr(){return j(t=>t.isAuthenticated)?jsx(rr,{}):jsx(nn,{})}var W=S("auth");function ot(e,t={}){return new Promise((n,r)=>{let{masked:o=false,defaultValue:i=""}=t;process.stdout.write(e+i);let s=i,a=m=>{if(m===""){u(),r(new Error("SIGINT"));return}if(m==="\r"||m===`
13
+ `);}function Xe(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
+ `);}function We(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var pn=ao.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}`:""," \xB7 v",t.version]}),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 ",We(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function mn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}var xt=5;function hn({items:e,emptyMessage:t}){let n=p(u=>u.selectedIndex);if(e.length===0)return jsx(mn,{message:t});let r=Math.max(0,n-Math.floor(xt/2)),o=Math.min(e.length,r+xt);o===e.length&&(r=Math.max(0,o-xt));let i=e.slice(r,o),s=r,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[s>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",s," more above"]})}),i.map((u,c)=>jsx(pn,{item:u,isSelected:r+c===n},u.name)),a>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",a," more below"]})})]})}var uo={discover:"Discover plugins",installed:"Installed plugins"};function wn({items:e,tabId:t,emptyMessage:n}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,children:uo[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),jsx(dn,{}),jsx(hn,{items:e,emptyMessage:n})]})}function xn({filteredItems:e,emptyMessage:t}){let n=p(r=>r.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(wn,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(wn,{items:e,tabId:"installed",emptyMessage:t},"installed")})}var mo={tabs:"Tab: switch tab | \u2191\u2193: navigate | Enter: select | /: search | q: quit",list:"Tab: switch tab | \u2191\u2193: navigate | Enter: select | /: search | q: quit",search:"Type to filter | Esc: cancel search | Enter: confirm",actionMenu:"\u2191\u2193: navigate options | Enter: confirm | Esc: close menu",auth:"Tab: next field | Enter: confirm | Ctrl+C: quit"};function vn(){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:mo[e]})})}function Pn({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 Tn({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(bo,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function kn({message:e,onRetry:t,onBack:n}){return useInput((r,o)=>{r==="r"&&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 r to retry"}),n&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function Qe({itemName:e,actions:t,onAction:n,onClose:r}){let o=p(a=>a.focus),[i,s]=useState(0);return useInput((a,u)=>{u.upArrow?s(c=>c>0?c-1:c):u.downArrow?s(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&r();},{isActive:o==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((a,u)=>jsx(Box,{children:jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",a]})},u))})]})}function Ln({itemName:e,onInstall:t,onClose:n}){return jsx(Qe,{itemName:e,actions:["Install","Cancel"],onAction:i=>{i==="Install"?t():n();},onClose:n})}function Dn({itemName:e,itemStatus:t,updateAvailable:n,catalogVersion:r,onUninstall:o,onToggleStatus:i,onUpdate:s,onClose:a}){let[u,c]=useState(false),m=p(l=>l.focus);if(useInput((l,d)=>{d.escape||l==="n"?c(false):l==="y"&&o();},{isActive:u&&m==="actionMenu"}),u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,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",T=r?`Update to v${r}`:"Update";return jsx(Qe,{itemName:e,actions:n?["Uninstall",h,T,"Cancel"]:["Uninstall",h,"Cancel"],onAction:l=>{l==="Uninstall"?c(true):l===h?i():l.startsWith("Update")?s?.():a();},onClose:a})}async function On(e,t){let n=q.resolve(t);await N.mkdir(n,{recursive:true});let r=q.join(q.dirname(n),`${randomUUID()}.zip`);try{await N.writeFile(r,e),await ko(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=q.resolve(n,o.fileName);if(!s.startsWith(n+q.sep)&&s!==n)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(n);if(!o.startsWith(q.resolve(q.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 N.unlink(r);}catch{}}}async function Tt(e){await N.rm(e,{recursive:true,force:true});}async function te(){let e=Wt();await N.mkdir(q.dirname(e),{recursive:true});try{await N.writeFile(e,"",{flag:"wx"});}catch(n){if(n.code!=="EEXIST")throw n}return await Ro.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Lo(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:b,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Nn(){let e=Be();if(!E__default.existsSync(e))return null;try{return JSON.parse(E__default.readFileSync(e,"utf-8"))}catch{return null}}function Mo(){let e=Nn();if(e)return e;let t=Lo(),n=Be();return E__default.mkdirSync(q__default.dirname(n),{recursive:true}),At(t),t}function At(e){let t=Be(),n=`${t}.tmp`;E__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),E__default.renameSync(n,t);}function Uo(){let e=Gt(),t={};try{E__default.existsSync(e)&&(t=JSON.parse(E__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[b])return;t[b]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:Xt(),lastUpdated:new Date().toISOString()};let n=`${e}.tmp`;E__default.writeFileSync(n,JSON.stringify(t,null,2),"utf-8"),E__default.renameSync(n,e);}function Bn(e,t){Uo();let n=dt(e.name);E__default.mkdirSync(q__default.dirname(n),{recursive:true});try{E__default.lstatSync(n),E__default.rmSync(n,{recursive:!0,force:!0});}catch{}E__default.symlinkSync(t,n);let r=Mo();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}),At(r));}function jn(e){let t=dt(e);try{E__default.rmSync(t,{recursive:!0,force:!0});}catch{}let n=Nn();if(!n)return;let r=n.plugins.length;n.plugins=n.plugins.filter(o=>o.name!==e),n.plugins.length!==r&&At(n);}var J=S("storage");function _n(){return q__default.join(Q__default.homedir(),".claude","plugins","installed_plugins.json")}function Do(){return q__default.join(Q__default.homedir(),".claude","plugins")}function Oo(e){let t=q__default.resolve(e),n=q__default.resolve(Do());if(!t.startsWith(n+q__default.sep)&&t!==n)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Kn(){return q__default.join(Q__default.homedir(),".claude","settings.json")}function H(){let e=_n();if(!E__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(E__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}function Ce(e){let t=_n();E__default.mkdirSync(q__default.dirname(t),{recursive:true});let n=`${t}.tmp`;E__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),E__default.renameSync(n,t);}function Re(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Fo(e){let t=q__default.join(e,".claude-plugin","plugin.json");if(!E__default.existsSync(t))return null;try{return JSON.parse(E__default.readFileSync(t,"utf-8"))}catch{return null}}function kt(){let e=Kn();if(!E__default.existsSync(e))return {};try{return JSON.parse(E__default.readFileSync(e,"utf-8"))}catch{return {}}}function Jn(e){let t=Kn(),n=`${t}.tmp`;E__default.writeFileSync(n,JSON.stringify(e,null,2),"utf-8"),E__default.renameSync(n,t);}function No(){return kt().enabledPlugins??{}}function Bo(e){let t=kt(),n=t.enabledPlugins;if(!n||!(e in n))return;let{[e]:r,...o}=n;t.enabledPlugins=o,Jn(t);}function Rt(e,t){let n=kt(),r=n.enabledPlugins??{};n.enabledPlugins={...r,[e]:t},Jn(n);}function R(){let e=H(),t=No();return Object.entries(e.plugins).map(([n,r])=>{let o=r[0],{name:i,marketplace:s}=Re(n),a=Fo(o.installPath),u=t[n];return {name:i,marketplace:s,version:o.version,installedAt:o.installedAt,installPath:o.installPath,scope:o.scope,description:a?.description,author:a?.author,status:u===false?"disabled":"enabled"}})}async function et(e){J.debug(`[${e}] Acquiring lock to uninstall`);let t=await te();try{let{name:n,marketplace:r}=Re(e),o=H(),i;if(r?(i=`${n}@${r}`,o.plugins[i]||(i=void 0)):i=Object.keys(o.plugins).filter(h=>Re(h).name===n)[0],!i)throw J.error(`[${n}] Plugin is not installed`),new Error(`Plugin '${n}' is not installed`);J.debug(`[${n}] Resolved key: ${i}`);let s=o.plugins[i][0].installPath;Oo(s);let a=q__default.dirname(s);J.debug(`[${n}] Removing directory: ${a}`),E__default.rmSync(a,{recursive:!0,force:!0}),jn(n);let{[i]:u,...c}=o.plugins;Ce({...o,plugins:c}),Bo(i),J.debug(`[${n}] Uninstalled successfully`);}finally{await t();}}async function Le(e,t){J.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await te();try{let{name:r}=Re(e),o=H(),i=Object.keys(o.plugins).filter(s=>Re(s).name===r);if(i.length===0)throw J.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);J.debug(`[${r}] Resolved key: ${i[0]}`),Rt(i[0],t==="enabled"),J.debug(`[${r}] Status updated to ${t}`);}finally{await n();}}var V=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:R()})}));var L=["discover","installed"];function qn(e,t,n){if(t.rightArrow||t.tab){let r=L.indexOf(n.activeTab);return [{type:"setTab",tab:L[(r+1)%L.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}if(t.leftArrow){let r=L.indexOf(n.activeTab);return [{type:"setTab",tab:L[(r-1+L.length)%L.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}return t.downArrow?[{type:"setFocus",focus:"list"}]:[]}function Hn(e,t,n,r){if(t.upArrow&&n.selectedIndex>0)return [{type:"setSelectedIndex",index:n.selectedIndex-1}];if(t.downArrow&&n.selectedIndex<r-1)return [{type:"setSelectedIndex",index:n.selectedIndex+1}];if(t.tab){let o=L.indexOf(n.activeTab);return [{type:"setTab",tab:L[(o+1)%L.length]},{type:"setSelectedIndex",index:0}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:[]}function Vn(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function zn(e,t){return t.escape?{actions:[{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.return?{actions:[{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace||t.delete?{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}function tt(e){let{setActiveTab:t,setFocus:n,setSelectedIndex:r,setActionMenuOpen:o}=p.getState();for(let i of e)i.type==="setTab"?t(i.tab):i.type==="setFocus"?n(i.focus):i.type==="setSelectedIndex"?r(i.index):i.type==="setActionMenuOpen"&&o(i.open);}function Xn({listLength:e}){let t=p(l=>l.focus),n=p(l=>l.selectedIndex),r=p(l=>l.actionMenuOpen),o=p(l=>l.setFocus),i=p(l=>l.setActionMenuOpen),s=F(l=>l.query),a=F(l=>l.setQuery),u=F(l=>l.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]);let[m,h]=useState("");useEffect(()=>{let l=setTimeout(()=>h(s),300);return ()=>clearTimeout(l)},[s]),useInput((l,d)=>{l==="q"&&process.exit(0);},{isActive:t!=="search"&&t!=="auth"}),useInput((l,d)=>{let{activeTab:f,selectedIndex:y,actionMenuOpen:M}=p.getState();tt(qn(l,d,{activeTab:f}));},{isActive:t==="tabs"}),useInput((l,d)=>{let{activeTab:f,selectedIndex:y,actionMenuOpen:M}=p.getState();tt(Hn(l,d,{activeTab:f,selectedIndex:y},c.current));},{isActive:t==="list"}),useInput((l,d)=>{tt(Vn(l,d));},{isActive:t==="actionMenu"}),useInput((l,d)=>{let f=zn(l,d),y=f.queryUpdate;tt(f.actions),y==="reset"?(u(),h("")):y!==null&&("backspace"in y?a(F.getState().query.slice(0,-1)):a(F.getState().query+y.append));},{isActive:t==="search"});let T=useCallback(()=>{i(false),o("list");},[i,o]),ie=useCallback(l=>{let{setSelectedIndex:d,selectedIndex:f}=p.getState();l===0?d(0):f>=l&&d(l-1);},[]),se=useCallback(l=>{if(!m)return c.current=l.length,l;let d=m.toLowerCase(),f=l.filter(y=>y.name.toLowerCase().includes(d)||y.description?.toLowerCase().includes(d));return c.current=f.length,f},[m]);return {actionMenuOpen:r,closeMenu:T,selectedIndex:n,clampIndex:ie,filteredItems:se}}function Zn(){let e=p(a=>a.notification),t=p(a=>a.showNotification),n=p(a=>a.clearNotification),r=j(a=>a.justAuthenticated),o=j(a=>a.credentials),i=j(a=>a.setJustAuthenticated);return useEffect(()=>{r&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),i(false));},[r,o]),useEffect(()=>{if(!e)return;let a=setTimeout(n,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,u)=>{t(a,u);}}}var ye=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},ne=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 nt(){return qr.create({prefixUrl:Ne("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async e=>{let t=await nn();e.headers.set("Authorization",`Bearer ${t}`);let n=C();n?.tenant&&Fe.test(n.tenant)&&e.headers.set("FlowTenant",n.tenant);}]}})}var qo=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function Qn(e){if(!e||!qo.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function z(){try{let{plugins:e}=await nt().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-cli 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 we(e){Qn(e);try{return await nt().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 Yn(e){Qn(e);try{let t=await nt().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}}var Ho=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function Vo(e){if(!Ho.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Ue=S("installer");function zo(e,t){let n=`${e}@${b}`,o=H().plugins[n];if(o&&!t)throw new ye(e,o[0].version);return {pluginKey:n,alreadyInstalled:o}}async function Go(e,t,n){n&&await Tt(t);try{Ue.debug(`Extracting to ${t}...`),await On(e,t);}catch(r){throw await Tt(t),r}}function Xo(e,t,n){let r=H(),o={scope:"user",installPath:t,version:n,installedAt:new Date().toISOString()};r.plugins[e]=[o],Ce(r),Rt(e,true);}async function xe(e,t={}){let n=Date.now(),r=null;try{Ue.debug(`[${e}] Acquiring lock...`),r=await te();let{pluginKey:o,alreadyInstalled:i}=zo(e,t.force);Ue.debug(`[${e}] Fetching manifest...`);let s=await we(e);Vo(s.name),Ue.debug(`[${e}] Downloading archive...`);let a=await Yn(e),u=zt(s.name,s.version);await Go(a,u,!!i&&!!t.force),Xo(o,u,s.version),Bn(s,u);let c=Date.now()-n;return Ue.debug(`[${e}] Installed successfully in ${c}ms`),{name:s.name,version:s.version,path:u,duration_ms:c}}finally{r&&await r();}}function G(e,t,n=false){return n?true:!Lt.valid(e)||!Lt.valid(t)?false:Lt.gt(t,e)}var re=S("updater");function Wo(e){let t=H(),n=`${e}@${b}`,r=t.plugins[n];return !r||r.length===0?null:{pluginKey:n,entry:r[0]}}async function rt(e,t={}){let n=Date.now(),r=null;try{re.debug(`[${e}] Acquiring lock...`),r=await te();let o=Wo(e);if(!o)throw re.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=o,s=i.version,a=i.installPath;re.debug(`[${e}] Fetching manifest...`);let c=(await we(e)).version;if(!G(s,c,t.force))throw re.debug(`[${e}] Already up to date (v${s})`),new ne(e,s);re.info(`[${e}] Updating v${s} \u2192 v${c}...`),await r(),r=null;try{let m=await xe(e,{force:!0}),h=Date.now()-n;return re.debug(`[${e}] Updated successfully in ${h}ms`),{name:m.name,previousVersion:s,newVersion:m.version,path:m.path,duration_ms:h}}catch(m){re.warn(`[${e}] Install failed, rolling back to v${s}...`),r=await te();let h=H(),T=`${e}@${b}`;throw h.plugins[T]&&(h.plugins[T][0].version=s,h.plugins[T][0].installPath=a,Ce(h),re.info(`[${e}] Rollback completed, restored to v${s}`)),m}}finally{r&&await r();}}function er(){let e=V(s=>s.installedItems),t=V(s=>s.setInstalledItems),n=useCallback(async s=>{await xe(s.name),V.getState().loadFromDisk();},[]),r=useCallback(async s=>{await et(s),t(e.filter(a=>a.name!==s));},[e,t]),o=useCallback(async s=>{let u=e.find(c=>c.name===s)?.status==="enabled"?"disabled":"enabled";await Le(s,u),t(e.map(c=>c.name===s?{...c,status:u}:c));},[e,t]),i=useCallback(async s=>{await rt(s),V.getState().loadFromDisk();},[]);return {install:n,uninstall:r,toggle:o,update:i}}function tr({selectedItem:e,selectedCatalogItem:t,items:n,closeMenu:r,clampIndex:o,notify:i}){let s=p(d=>d.setLoading),{install:a,uninstall:u,toggle:c,update:m}=er(),h=async(d,f,y)=>{s(true,d),r();try{await f(),o(n.length),i(y,"success");}catch(M){i(M instanceof Error?M.message:"Something went wrong","error");}finally{s(false);}};return {handleInstall:()=>{e&&t&&h(`Installing ${e.name}...`,()=>a(t),"\u2713 Installed successfully");},handleUninstall:()=>{e&&h(`Uninstalling ${e.name}...`,()=>u(e.name),"\u2713 Uninstalled");},handleToggleStatus:()=>{if(!e)return;let d=e.status==="enabled";h(d?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>c(e.name),d?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let d=t?` to v${t.version}`:"";(async()=>{s(true,`Updating ${e.name}${d}...`),r();try{await m(e.name),o(n.length),i(`\u2713 Updated ${e.name}${d}`,"success");}catch(y){y instanceof ne?i(y.message,"info"):i(y instanceof Error?y.message:"Something went wrong","error");}finally{s(false);}})();}}}function nr(){let[e,t]=useState([]),[n,r]=useState(true),[o,i]=useState(null),s=useCallback(async()=>{r(true),i(null);try{let a=await z();t(a);}catch(a){i(a instanceof Error?a:new Error(String(a))),t([]);}finally{r(false);}},[]);return useEffect(()=>{s();},[s]),{catalog:e,isLoading:n,error:o,refetch:s}}function rr(){return {items:V(t=>t.installedItems)}}var ei=S("catalog");function ti(e){return {name:e.name,version:e.version,description:e.description,authorName:e.author.name,updateAvailable:e.updateAvailable}}function ni(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 or(){let e=p(g=>g.activeTab),t=p(g=>g.notification),n=p(g=>g.loading),r=p(g=>g.loadingMessage),o=p(g=>g.catalogError),i=p(g=>g.setCatalogError),s=F(g=>g.query),{catalog:a,isLoading:u,error:c,refetch:m}=nr(),{items:h}=rr(),T=V(g=>g.loadFromDisk),ie=useMemo(()=>new Set(h.map(g=>`${g.name}|${g.author?.name??""}|${g.marketplace}`)),[h]),se=useMemo(()=>{let g=new Map(a.map(pe=>[pe.name,pe.version]));return h.map(pe=>{let Bt=g.get(pe.name),Tr=!!Bt&&G(pe.version,Bt);return {...pe,updateAvailable:Tr}})},[h,a]),l=e==="discover"?a.filter(g=>!ie.has(`${g.name}|${g.author.name}|${b}`)).map(g=>ti(g)):se.map(g=>ni(g)),{actionMenuOpen:d,closeMenu:f,selectedIndex:y,clampIndex:M,filteredItems:xr}=Xn({listLength:l.length}),De=xr(l),U=De[y]??null,Nt=useMemo(()=>U?a.find(g=>g.name===U.name)??null:null,[a,U]),br=e==="installed"?"No plugins installed \u2014 explore the Discover tab!":s?`No plugins found for '${s}'`:"No plugins available in the catalog",{notify:vr}=Zn(),{handleInstall:Pr,handleUninstall:Ir,handleToggleStatus:Sr,handleUpdate:Er}=tr({selectedItem:U,selectedCatalogItem:Nt,items:l,closeMenu:f,clampIndex:M,notify:vr});return useEffect(()=>{T();},[]),useEffect(()=>{M(De.length);},[De.length,M]),useEffect(()=>{c&&(ei.error(`[usePluginCatalog] ${c instanceof Error?c.message:String(c)}`),i("Failed to load catalog"));},[c]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(an,{}),jsx(cn,{}),jsx(xn,{filteredItems:De,emptyMessage:br}),(n||u)&&jsx(Tn,{message:n?r:"Loading catalog..."}),o&&!u&&e==="discover"&&jsx(kn,{message:o,onRetry:()=>{i(null),m();},onBack:()=>i(null)}),t&&jsx(Pn,{message:t.message,type:t.type}),d&&U&&e==="discover"&&jsx(Ln,{itemName:U.name,onInstall:Pr,onClose:f}),d&&U&&e==="installed"&&jsx(Dn,{itemName:U.name,itemStatus:U.status??"enabled",updateAvailable:U.updateAvailable??false,catalogVersion:Nt?.version,onUninstall:Ir,onToggleStatus:Sr,onUpdate:Er,onClose:f}),jsx(vn,{})]})}var ir=C();if(ir&&D()){let{clientSecret:e,...t}=ir;j.getState().setCredentials(t),p.getState().setFocus("list");}else p.getState().setFocus("auth");function ar(){return j(t=>t.isAuthenticated)?jsx(or,{}):jsx(rn,{})}var W=S("auth");function it(e,t={}){return new Promise((n,r)=>{let{masked:o=false,defaultValue:i=""}=t;process.stdout.write(e+i);let s=i,a=m=>{if(m===""){u(),r(new Error("SIGINT"));return}if(m==="\r"||m===`
15
15
  `){u(),process.stdout.write(`
16
- `),n(s);return}if(m==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}m.startsWith("\x1B")||(s+=m,process.stdout.write(o?"*".repeat(m.length):m));};function u(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",c),process.removeListener("unhandledRejection",c);}function c(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",c),process.on("unhandledRejection",c),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function ii(e){W.debug(`Authenticating tenant: ${e.tenant}`);try{return await Ee(e),W.info(`Authentication successful for tenant: ${e.tenant}`),process.stdout.write(x.green(` \u2713 Setup complete. Tenant: ${e.tenant}
16
+ `),n(s);return}if(m==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}m.startsWith("\x1B")||(s+=m,process.stdout.write(o?"*".repeat(m.length):m));};function u(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",c),process.removeListener("unhandledRejection",c);}function c(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",c),process.on("unhandledRejection",c),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function oi(e){W.debug(`Authenticating tenant: ${e.tenant}`);try{return await Ee(e),W.info(`Authentication successful for tenant: ${e.tenant}`),process.stdout.write(x.green(` \u2713 Setup complete. Tenant: ${e.tenant}
17
17
 
18
18
  `)),0}catch(t){let n=I(t instanceof Error?t.message:"unknown error");return W.error(`Authentication failed: ${n}`),process.stderr.write(x.red(` \u2717 Authentication failed: ${n}
19
- `)),1}}async function si(){W.debug("Starting interactive authentication");try{process.stdout.write(`
20
- `);let e=(await ot(x.cyan(" ? ")+"Client ID: ")).trim(),t=(await ot(x.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),n=(await ot(x.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!n)return W.error("Validation failed: all fields are required"),process.stderr.write(x.red(` \u2717 All fields are required
19
+ `)),1}}async function ii(){W.debug("Starting interactive authentication");try{process.stdout.write(`
20
+ `);let e=(await it(x.cyan(" ? ")+"Client ID: ")).trim(),t=(await it(x.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),n=(await it(x.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!n)return W.error("Validation failed: all fields are required"),process.stderr.write(x.red(` \u2717 All fields are required
21
21
  `)),1;W.debug(`Authenticating tenant: ${n}`);try{await Ee({clientId:e,clientSecret:t,tenant:n});}catch(r){let o=I(r instanceof Error?r.message:"unknown error");return W.error(`Authentication failed: ${o}`),process.stderr.write(x.red(` \u2717 Authentication failed: ${o}
22
22
  `)),1}return W.info(`Authentication successful for tenant: ${n}`),process.stdout.write(x.green(` \u2713 Setup complete. Tenant: ${n}
23
23
 
24
24
  `)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=I(e instanceof Error?e.message:"unknown error");return W.error(`Unexpected error: ${t}`),process.stderr.write(x.red(` \u2717 Unexpected error: ${t}
25
- `)),1}}async function Dt(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return ii({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant});try{return await si()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
26
- `),130;throw t}}async function ai(){try{return process.stdout.write(`
27
- `),(await ot(x.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(x.yellow(` \u26A0 Logout cancelled
25
+ `)),1}}async function Ot(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return oi({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant});try{return await ii()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
26
+ `),130;throw t}}async function si(){try{return process.stdout.write(`
27
+ `),(await it(x.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(x.yellow(` \u26A0 Logout cancelled
28
28
  `)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
29
- `),130;throw e}}async function ar(e){if(!C())return process.stdout.write(x.yellow(` \u26A0 You are not authenticated
30
- `)),0;if(!e){let t=await ai();if(t!==null)return t}try{return Kt(),process.stdout.write(x.green(` \u2713 Credentials removed successfully
29
+ `),130;throw e}}async function lr(e){if(!C())return process.stdout.write(x.yellow(` \u26A0 You are not authenticated
30
+ `)),0;if(!e){let t=await si();if(t!==null)return t}try{return Jt(),process.stdout.write(x.green(` \u2713 Credentials removed successfully
31
31
  `)),0}catch{return process.stderr.write(x.red(` \u2717 Error removing credentials
32
- `)),1}}async function lr(){let e=C();return e?D()?(process.stdout.write(`
32
+ `)),1}}async function cr(){let e=C();return e?D()?(process.stdout.write(`
33
33
  `+x.bold(` Authenticated
34
34
  `)),process.stdout.write(x.dim(" Tenant: ")+I(e.tenant)+`
35
35
  `),process.stdout.write(x.dim(" Client ID: ")+I(e.clientId)+`
36
- `),process.stdout.write(x.dim(" Config: ")+I(Jt())+`
36
+ `),process.stdout.write(x.dim(" Config: ")+I(qt())+`
37
37
  `),process.stdout.write(`
38
- `),0):(process.stdout.write(x.yellow(" \u26A0 Session expired. Run `flow-cli auth login` to re-authenticate.\n")),0):(process.stdout.write(x.yellow(" \u26A0 Not authenticated. Run `flow-cli auth login` to set up.\n")),0)}function oe(){return C()?D()?true:(P("Session expired. Run: flow-cli auth login"),false):(P("Not authenticated. Run: flow-cli auth login"),false)}async function li(e){let t=R(),n;try{n=await z();}catch{n=[];}let r=new Set(t.map(o=>o.name));return e.json?(Ge(n.map(o=>({...o,installed:r.has(o.name)}))),0):(ze(["","Name","Version","Category","Status"],n.map(o=>[r.has(o.name)?"*":" ",o.name,o.version,o.category,r.has(o.name)?"installed":"available"])),0)}async function ci(e){let t=R(),n=await z(),r=new Map(n.map(i=>[i.name,i])),o=t.map(i=>{let s=r.get(i.name);return s&&G(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return o.length===0?(w("All plugins are up to date."),0):e.json?(Ge(o),0):(ze(["Name","Installed","Available"],o.map(i=>[i.name,i.version,i.availableVersion])),process.stdout.write(`
38
+ `),0):(process.stdout.write(x.yellow(" \u26A0 Session expired. Run `flow-cli auth login` to re-authenticate.\n")),0):(process.stdout.write(x.yellow(" \u26A0 Not authenticated. Run `flow-cli auth login` to set up.\n")),0)}function oe(){return C()?D()?true:(P("Session expired. Run: flow-cli auth login"),false):(P("Not authenticated. Run: flow-cli auth login"),false)}async function ai(e){let t=R(),n;try{n=await z();}catch{n=[];}let r=new Set(t.map(o=>o.name));return e.json?(Xe(n.map(o=>({...o,installed:r.has(o.name)}))),0):(Ge(["","Name","Version","Category","Status"],n.map(o=>[r.has(o.name)?"*":" ",o.name??"",o.version??"",o.category??"",r.has(o.name)?"installed":"available"])),0)}async function li(e){let t=R(),n=await z(),r=new Map(n.map(i=>[i.name,i])),o=t.map(i=>{let s=r.get(i.name);return s&&G(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return o.length===0?(w("All plugins are up to date."),0):e.json?(Xe(o),0):(Ge(["Name","Installed","Available"],o.map(i=>[i.name??"",i.version??"",i.availableVersion??""])),process.stdout.write(`
39
39
  ${o.length} plugin(s) outdated.
40
- `),0)}function ui(e){let t=R();return t.length===0?(w("No plugins installed. Use `flow plugin install <name>` to install one."),0):e.json?(Ge(t),0):(ze(["Name","Version","Installed at"],t.map(n=>[n.name,n.version,Xe(n.installedAt)])),process.stdout.write(`
40
+ `),0)}function ci(e){let t=R();return t.length===0?(w("No plugins installed. Use `flow plugin install <name>` to install one."),0):e.json?(Xe(t),0):(Ge(["Name","Version","Installed at"],t.map(n=>[n.name??"",n.version??"",We(n.installedAt??"")])),process.stdout.write(`
41
41
  ${t.length} plugin(s) installed.
42
- `),0)}async function cr(e){if(!oe())return 1;try{return e.available?await li(e):e.outdated?await ci(e):ui(e)}catch(t){return P(t instanceof Error?t.message:"Failed to list plugins."),1}}var v=S("manage");function ue(e){process.stdout.write(JSON.stringify(e)+`
43
- `);}function Ot(e){process.stderr.write(JSON.stringify(e)+`
44
- `);}function B(e){return e instanceof Error?e.message:String(e)}async function di(e,t,n){n.silent||w(`${t}Installing ${e}...`);try{let r=await xe(e,n);return n.silent?ue({status:"success",plugin:r.name,version:r.version,duration_ms:r.duration_ms}):me(`${t}${r.name} v${r.version} installed successfully`),{name:e,success:!0,version:r.version,duration_ms:r.duration_ms}}catch(r){if(r instanceof ye)return n.silent?ue({status:"already_installed",plugin:e,message:r.message}):w(`${t}${r.message}`),{name:e,success:true};let o=B(r);return n.silent?Ot({status:"error",plugin:e,message:o}):P(`${t}Failed to install ${e}: ${o}`),{name:e,success:false,error:o}}}function pi(e){let t=e.filter(r=>r.success).length,n=e.filter(r=>!r.success).length;w(`
45
- Installation summary: ${t} succeeded, ${n} failed`);}async function ur(e,t={}){if(!oe())return 1;let n=[];for(let r=0;r<e.length;r++){let o=e.length>1?`[${r+1}/${e.length}] `:"",i=await di(e[r],o,t);n.push(i);}return e.length>1&&(t.silent?ue({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}:{}}))}):pi(n)),n.some(r=>!r.success)?1:0}async function dr(e,t){if(!oe())return 1;if(v.debug(`[${e}] Looking up installed plugin`),!t.force){let n=R().find(s=>s.name===e);if(!n)return v.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;let r=I(n.name),o=I(n.version);if(!await fi(`Remove ${r} v${o}? [y/N] `))return v.debug(`[${e}] Uninstall cancelled by user`),w("Operation cancelled."),0}try{return v.debug(`[${e}] Uninstalling plugin`),await Ye(e),v.info(`[${e}] Uninstalled successfully`),me("Plugin removed successfully"),0}catch(n){return v.error(`[${e}] Failed to uninstall: ${B(n)}`),P(B(n)),1}}async function fi(e){let n=(await import('readline')).default.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{n.question(e,o=>{n.close(),r(o.toLowerCase()==="y");});})}async function pr(e){if(!oe())return 1;v.debug(`[${e}] Looking up installed plugin`);let t=R().find(n=>n.name===e);if(!t)return v.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(t.status==="enabled")return v.debug(`[${e}] Already enabled, skipping`),w(`${t.name} is already enabled`),0;try{return v.debug(`[${e}] Enabling plugin (current status: ${t.status})`),await Le(e,"enabled"),v.info(`[${e}] Enabled successfully`),me(`${t.name} enabled successfully`),0}catch(n){return v.error(`[${e}] Failed to enable: ${B(n)}`),P(B(n)),1}}async function fr(e){if(!oe())return 1;v.debug(`[${e}] Looking up installed plugin`);let t=R().find(n=>n.name===e);if(!t)return v.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(t.status==="disabled")return v.debug(`[${e}] Already disabled, skipping`),w(`${t.name} is already disabled`),0;try{return v.debug(`[${e}] Disabling plugin (current status: ${t.status})`),await Le(e,"disabled"),v.info(`[${e}] Disabled successfully`),me(`${t.name} disabled successfully`),0}catch(n){return v.error(`[${e}] Failed to disable: ${B(n)}`),P(B(n)),1}}async function mr(e,t,n){n.silent||w(`${t}Updating ${e}...`);try{let r=await nt(e,n);return n.silent?ue({status:"updated",plugin:r.name,previousVersion:r.previousVersion,newVersion:r.newVersion,duration_ms:r.duration_ms}):me(`${t}${r.name} v${r.previousVersion} \u2192 v${r.newVersion}`),{name:e,success:!0}}catch(r){if(r instanceof ne)return n.silent?ue({status:"up_to_date",plugin:e,message:r.message}):w(`${t}${r.message}`),{name:e,success:true,skipped:true};let o=B(r);return n.silent?Ot({status:"error",plugin:e,message:o}):P(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function mi(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;w(`
46
- Update summary: ${t} updated, ${n} already up to date, ${r} failed`);}async function gi(e,t,n){try{let r=await we(e);G(t,r.version,n.force)?w(`Would update ${e}: v${t} \u2192 v${r.version}`):w(`${e} is already up to date (v${t})`);}catch(r){return P(B(r)),1}return 0}function hi(e){return new Map(e.map(t=>[t.name,t.version]))}function yi(e,t,n){let r=t.get(e.name);return r?G(e.version,r,n)?(w(`Would update ${e.name}: v${e.version} \u2192 v${r}`),true):(w(`${e.name} is already up to date (v${e.version})`),false):(w(`Skipping ${e.name}: not found in catalog`),false)}async function wi(e,t){try{let n=await z(),r=hi(n),o=0;for(let i of e)yi(i,r,t.force)&&o++;o===0&&w("All plugins are up to date");}catch(n){return P(B(n)),1}return 0}async function xi(e,t){let n=[];for(let r=0;r<e.length;r++){let o=`[${r+1}/${e.length}] `,i=await mr(e[r].name,o,t);n.push(i);}return t.silent?ue({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}:{}}))}):mi(n),n.some(r=>!r.success)?1:0}async function gr(e,t={}){if(!oe())return 1;if(e){let o=R().find(s=>s.name===e);return o?t.dryRun?gi(e,o.version,t):(await mr(e,"",t)).success?0:1:(t.silent?Ot({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):P(`Plugin "${e}" is not installed`),1)}let r=R().filter(o=>o.marketplace===b);return r.length===0?(t.silent?ue({status:"empty",message:"No plugins installed"}):w("No plugins installed"),0):t.dryRun?wi(r,t):xi(r,t)}function Ii(){return C()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow-cli auth login`"}}async function Si(){let e=Date.now();try{await z();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"}`}}}function Ei(){return D()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow-cli auth login` to re-authenticate"}}function Ti(){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 hr(){process.stdout.write(`
42
+ `),0)}async function ur(e){if(!oe())return 1;try{return e.available?await ai(e):e.outdated?await li(e):ci(e)}catch(t){return P(t instanceof Error?t.message:"Failed to list plugins."),1}}var v=S("manage");function ue(e){process.stdout.write(JSON.stringify(e)+`
43
+ `);}function Ft(e){process.stderr.write(JSON.stringify(e)+`
44
+ `);}function B(e){return e instanceof Error?e.message:String(e)}async function ui(e,t,n){n.silent||w(`${t}Installing ${e}...`);try{let r=await xe(e,n);return n.silent?ue({status:"success",plugin:r.name,version:r.version,duration_ms:r.duration_ms}):me(`${t}${r.name} v${r.version} installed successfully`),{name:e,success:!0,version:r.version,duration_ms:r.duration_ms}}catch(r){if(r instanceof ye)return n.silent?ue({status:"already_installed",plugin:e,message:r.message}):w(`${t}${r.message}`),{name:e,success:true};let o=B(r);return n.silent?Ft({status:"error",plugin:e,message:o}):P(`${t}Failed to install ${e}: ${o}`),{name:e,success:false,error:o}}}function di(e){let t=e.filter(r=>r.success).length,n=e.filter(r=>!r.success).length;w(`
45
+ Installation summary: ${t} succeeded, ${n} failed`);}async function dr(e,t={}){if(!oe())return 1;let n=[];for(let r=0;r<e.length;r++){let o=e.length>1?`[${r+1}/${e.length}] `:"",i=await ui(e[r],o,t);n.push(i);}return e.length>1&&(t.silent?ue({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}:{}}))}):di(n)),n.some(r=>!r.success)?1:0}async function pr(e,t){if(!oe())return 1;if(v.debug(`[${e}] Looking up installed plugin`),!t.force){let n=R().find(s=>s.name===e);if(!n)return v.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;let r=I(n.name),o=I(n.version);if(!await pi(`Remove ${r} v${o}? [y/N] `))return v.debug(`[${e}] Uninstall cancelled by user`),w("Operation cancelled."),0}try{return v.debug(`[${e}] Uninstalling plugin`),await et(e),v.info(`[${e}] Uninstalled successfully`),me("Plugin removed successfully"),0}catch(n){return v.error(`[${e}] Failed to uninstall: ${B(n)}`),P(B(n)),1}}async function pi(e){let n=(await import('readline')).default.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{n.question(e,o=>{n.close(),r(o.toLowerCase()==="y");});})}async function fr(e){if(!oe())return 1;v.debug(`[${e}] Looking up installed plugin`);let t=R().find(n=>n.name===e);if(!t)return v.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(t.status==="enabled")return v.debug(`[${e}] Already enabled, skipping`),w(`${t.name} is already enabled`),0;try{return v.debug(`[${e}] Enabling plugin (current status: ${t.status})`),await Le(e,"enabled"),v.info(`[${e}] Enabled successfully`),me(`${t.name} enabled successfully`),0}catch(n){return v.error(`[${e}] Failed to enable: ${B(n)}`),P(B(n)),1}}async function mr(e){if(!oe())return 1;v.debug(`[${e}] Looking up installed plugin`);let t=R().find(n=>n.name===e);if(!t)return v.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(t.status==="disabled")return v.debug(`[${e}] Already disabled, skipping`),w(`${t.name} is already disabled`),0;try{return v.debug(`[${e}] Disabling plugin (current status: ${t.status})`),await Le(e,"disabled"),v.info(`[${e}] Disabled successfully`),me(`${t.name} disabled successfully`),0}catch(n){return v.error(`[${e}] Failed to disable: ${B(n)}`),P(B(n)),1}}async function gr(e,t,n){n.silent||w(`${t}Updating ${e}...`);try{let r=await rt(e,n);return n.silent?ue({status:"updated",plugin:r.name,previousVersion:r.previousVersion,newVersion:r.newVersion,duration_ms:r.duration_ms}):me(`${t}${r.name} v${r.previousVersion} \u2192 v${r.newVersion}`),{name:e,success:!0}}catch(r){if(r instanceof ne)return n.silent?ue({status:"up_to_date",plugin:e,message:r.message}):w(`${t}${r.message}`),{name:e,success:true,skipped:true};let o=B(r);return n.silent?Ft({status:"error",plugin:e,message:o}):P(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function fi(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;w(`
46
+ Update summary: ${t} updated, ${n} already up to date, ${r} failed`);}async function mi(e,t,n){try{let r=await we(e);G(t,r.version,n.force)?w(`Would update ${e}: v${t} \u2192 v${r.version}`):w(`${e} is already up to date (v${t})`);}catch(r){return P(B(r)),1}return 0}function gi(e){return new Map(e.map(t=>[t.name,t.version]))}function hi(e,t,n){let r=t.get(e.name);return r?G(e.version,r,n)?(w(`Would update ${e.name}: v${e.version} \u2192 v${r}`),true):(w(`${e.name} is already up to date (v${e.version})`),false):(w(`Skipping ${e.name}: not found in catalog`),false)}async function yi(e,t){try{let n=await z(),r=gi(n),o=0;for(let i of e)hi(i,r,t.force)&&o++;o===0&&w("All plugins are up to date");}catch(n){return P(B(n)),1}return 0}async function wi(e,t){let n=[];for(let r=0;r<e.length;r++){let o=`[${r+1}/${e.length}] `,i=await gr(e[r].name,o,t);n.push(i);}return t.silent?ue({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}:{}}))}):fi(n),n.some(r=>!r.success)?1:0}async function hr(e,t={}){if(!oe())return 1;if(e){let o=R().find(s=>s.name===e);return o?t.dryRun?mi(e,o.version,t):(await gr(e,"",t)).success?0:1:(t.silent?Ft({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):P(`Plugin "${e}" is not installed`),1)}let r=R().filter(o=>o.marketplace===b);return r.length===0?(t.silent?ue({status:"empty",message:"No plugins installed"}):w("No plugins installed"),0):t.dryRun?yi(r,t):wi(r,t)}function Pi(){return C()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow-cli auth login`"}}async function Ii(){let e=Date.now();try{await z();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"}`}}}function Si(){return D()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow-cli auth login` to re-authenticate"}}function Ei(){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 yr(){process.stdout.write(`
47
47
  `+x.bold(` FlowSetup CLI Diagnostics
48
48
 
49
- `));let e=[{name:"Credentials",fn:Ii},{name:"Prompt Manager",fn:Si},{name:"Valid Token",fn:Ei},{name:"Claude Code",fn:Ti}],t=true;for(let n of e){let r=await n.fn(),o="",i=x.green;r.passed?o=x.green("[OK] "):(o=x.red("[FAIL]"),i=x.red,t=false);let s=` ${o} ${i(n.name.padEnd(18))} ${I(r.message)}`;process.stdout.write(s+`
49
+ `));let e=[{name:"Credentials",fn:Pi},{name:"Prompt Manager",fn:Ii},{name:"Valid Token",fn:Si},{name:"Claude Code",fn:Ei}],t=true;for(let n of e){let r=await n.fn(),o="",i=x.green;r.passed?o=x.green("[OK] "):(o=x.red("[FAIL]"),i=x.red,t=false);let s=` ${o} ${i(n.name.padEnd(18))} ${I(r.message)}`;process.stdout.write(s+`
50
50
  `);}return process.stdout.write(`
51
51
  `),t?(process.stdout.write(x.green(` \u2713 All checks passed!
52
52
 
53
53
  `)),0):(process.stdout.write(x.red(` \u2717 Some checks failed \u2014 verify your configuration
54
54
 
55
- `)),1)}function yr(e){let t=new Command;t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@flow/cli v${Je}`,"-V, --version","Display the CLI version").addHelpText("after",`
55
+ `)),1)}function wr(e){let t=new Command;t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@flow/cli v${qe}`,"-V, --version","Display the CLI version").addHelpText("after",`
56
56
  Without arguments, opens the interactive interface (TUI).
57
57
  Use 'flow <command> --help' for details on each command.`).action(()=>{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",`
58
58
  Examples:
59
- $ flow setup init`).action(async()=>{let i=await Dt();process.exit(i);}),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",`
59
+ $ flow setup init`).action(async()=>{let i=await Ot();process.exit(i);}),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",`
60
60
  Examples:
61
61
  $ flow plugin list
62
62
  $ flow plugin list --available
63
63
  $ flow plugin list --outdated
64
- $ flow plugin list --json`).action(async i=>{let s=await cr(i);process.exit(s);}),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").addHelpText("after",`
64
+ $ flow plugin list --json`).action(async i=>{let s=await ur(i);process.exit(s);}),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").addHelpText("after",`
65
65
  Examples:
66
66
  $ flow plugin install flow-adr-writer
67
67
  $ flow plugin install flow-adr-writer flow-prd-writer startup-pack-ai
68
68
  $ flow plugin install flow-adr-writer --force
69
- $ flow plugin install flow-adr-writer --silent`).action(async(i,s)=>{_("cli",{verbose:s.verbose,silent:s.silent});let a=await ur(i,s);process.exit(a);}),r.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addHelpText("after",`
69
+ $ flow plugin install flow-adr-writer --silent`).action(async(i,s)=>{_("cli",{verbose:s.verbose,silent:s.silent});let a=await dr(i,s);process.exit(a);}),r.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addHelpText("after",`
70
70
  Examples:
71
71
  $ flow plugin uninstall flow-adr-writer
72
- $ flow plugin uninstall startup-pack-ai --force`).action(async(i,s)=>{let a=await dr(i,s);process.exit(a);}),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").addHelpText("after",`
72
+ $ flow plugin uninstall startup-pack-ai --force`).action(async(i,s)=>{let a=await pr(i,s);process.exit(a);}),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").addHelpText("after",`
73
73
  Examples:
74
74
  $ flow plugin update flow-adr-writer
75
75
  $ flow plugin update flow-adr-writer --force
@@ -77,19 +77,19 @@ Examples:
77
77
  $ flow plugin update flow-adr-writer --verbose
78
78
  $ flow plugin update flow-adr-writer --silent
79
79
  $ flow plugin update
80
- $ flow plugin update --dry-run`).action(async(i,s)=>{_("cli",{verbose:s.verbose,silent:s.silent});let a=await gr(i??null,s);process.exit(a);}),r.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addHelpText("after",`
80
+ $ flow plugin update --dry-run`).action(async(i,s)=>{_("cli",{verbose:s.verbose,silent:s.silent});let a=await hr(i??null,s);process.exit(a);}),r.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addHelpText("after",`
81
81
  Examples:
82
- $ flow plugin enable flow-adr-writer`).action(async i=>{_("cli");let s=await pr(i);process.exit(s);}),r.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addHelpText("after",`
82
+ $ flow plugin enable flow-adr-writer`).action(async i=>{_("cli");let s=await fr(i);process.exit(s);}),r.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addHelpText("after",`
83
83
  Examples:
84
- $ flow plugin disable flow-adr-writer`).action(async i=>{_("cli");let s=await fr(i);process.exit(s);}),t.addCommand(r);let o=new Command("auth").description("Manage authentication credentials");return o.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("--verbose","Display each step of the authentication process").addHelpText("after",`
84
+ $ flow plugin disable flow-adr-writer`).action(async i=>{_("cli");let s=await mr(i);process.exit(s);}),t.addCommand(r);let o=new Command("auth").description("Manage authentication credentials");return o.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("--verbose","Display each step of the authentication process").addHelpText("after",`
85
85
  Examples:
86
86
  $ flow auth login
87
87
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
88
- $ flow auth login --verbose`).action(async i=>{_("cli",{verbose:i.verbose});let s=await Dt(i);process.exit(s);}),o.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
88
+ $ flow auth login --verbose`).action(async i=>{_("cli",{verbose:i.verbose});let s=await Ot(i);process.exit(s);}),o.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
89
89
  Examples:
90
90
  $ flow auth logout
91
- $ flow auth logout --force`).action(async i=>{let s=await ar(i.force);process.exit(s);}),o.command("status").description("Display the current authentication status").addHelpText("after",`
91
+ $ flow auth logout --force`).action(async i=>{let s=await lr(i.force);process.exit(s);}),o.command("status").description("Display the current authentication status").addHelpText("after",`
92
92
  Examples:
93
- $ flow auth status`).action(async()=>{let i=await lr();process.exit(i);}),t.addCommand(o),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
93
+ $ flow auth status`).action(async()=>{let i=await cr();process.exit(i);}),t.addCommand(o),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
94
94
  Examples:
95
- $ flow health`).action(async()=>{let i=await hr();process.exit(i);}),t}var $i=yr(()=>{_("tui"),render(jsx(sr,{}));});$i.parse();
95
+ $ flow health`).action(async()=>{let i=await yr();process.exit(i);}),t}var Ai=wr(()=>{_("tui"),render(jsx(ar,{}));});Ai.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ciandt-flow/cli",
3
- "version": "1.0.3",
3
+ "version": "1.0.5-beta.21",
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",
@@ -38,8 +38,7 @@
38
38
  "version-packages": "changeset version",
39
39
  "release": "npm run build && changeset publish",
40
40
  "release:npm": "npm run build:npm && changeset publish",
41
- "security-scan": "trufflehog filesystem src/ --fail --no-update",
42
- "prepublishOnly": "npm run security-scan"
41
+ "security-scan": "trufflehog filesystem src/ --fail --no-update"
43
42
  },
44
43
  "keywords": [
45
44
  "cli",
@@ -48,7 +47,10 @@
48
47
  "claude",
49
48
  "tui"
50
49
  ],
51
- "author": "queryCLient",
50
+ "author": {
51
+ "name": "CI&T Flow Team",
52
+ "email": "flow@ciandt.com"
53
+ },
52
54
  "dependencies": {
53
55
  "@tanstack/react-query": "^5.90.21",
54
56
  "boxen": "^8.0.1",
@@ -103,4 +105,4 @@
103
105
  "esbuild": ">=0.25.0",
104
106
  "picomatch": ">=4.0.4"
105
107
  }
106
- }
108
+ }