@segosolutions/auto-task 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +270 -0
- package/dist/index.cjs +60 -0
- package/package.json +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Sego Solutions
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
# @segosolutions/auto-task
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@segosolutions/auto-task)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
|
|
6
|
+
Background task monitor for [Sego PM](https://sego.pm) - automatically processes high-confidence tasks using Claude.
|
|
7
|
+
|
|
8
|
+
## Prerequisites
|
|
9
|
+
|
|
10
|
+
Before installing, ensure you have:
|
|
11
|
+
|
|
12
|
+
1. **Node.js 18+** - [Download here](https://nodejs.org/)
|
|
13
|
+
2. **Claude Code CLI** - Install and authenticate:
|
|
14
|
+
```bash
|
|
15
|
+
npm install -g @anthropic-ai/claude-code
|
|
16
|
+
claude auth login
|
|
17
|
+
```
|
|
18
|
+
3. **Sego PM API Key** - Generate from [Developer Settings](https://sego.pm/developer/api-keys)
|
|
19
|
+
|
|
20
|
+
## Quick Start
|
|
21
|
+
|
|
22
|
+
Get up and running in under 5 minutes:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
# 1. Install globally
|
|
26
|
+
npm install -g @segosolutions/auto-task
|
|
27
|
+
|
|
28
|
+
# 2. Run the interactive setup
|
|
29
|
+
sego-auto-task init
|
|
30
|
+
|
|
31
|
+
# 3. Start monitoring (from your project directory)
|
|
32
|
+
sego-auto-task
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
That's it! The monitor will now process eligible tasks automatically.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
### Global Install (Recommended)
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm install -g @segosolutions/auto-task
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Project Install
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
npm install --save-dev @sego/auto-task
|
|
49
|
+
npx sego-auto-task --help
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Usage
|
|
53
|
+
|
|
54
|
+
### Basic Usage
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
# Start monitoring with default settings (connects to https://sego.pm)
|
|
58
|
+
sego-auto-task
|
|
59
|
+
|
|
60
|
+
# Use environment variables
|
|
61
|
+
export SEGO_API_KEY=sk_live_...
|
|
62
|
+
sego-auto-task
|
|
63
|
+
|
|
64
|
+
# Or pass directly
|
|
65
|
+
sego-auto-task --api-key=sk_live_...
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Development Mode
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
# Connect to local Sego PM instance
|
|
72
|
+
sego-auto-task --api-url=http://localhost:3000
|
|
73
|
+
|
|
74
|
+
# Test without processing tasks
|
|
75
|
+
sego-auto-task --dry-run
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Project-Specific Monitoring
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
# Only monitor tasks for a specific project
|
|
82
|
+
sego-auto-task --project-id=cmiursa7x0001qptpaehaq7hg
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## CLI Options
|
|
86
|
+
|
|
87
|
+
| Option | Description | Default |
|
|
88
|
+
|--------|-------------|---------|
|
|
89
|
+
| `--api-key <key>` | Sego PM API key | `SEGO_API_KEY` env |
|
|
90
|
+
| `--api-url <url>` | Sego PM API URL | `https://sego.pm` |
|
|
91
|
+
| `--project-id <id>` | Only process tasks for this project | All projects |
|
|
92
|
+
| `--poll <seconds>` | Poll interval for checking tasks | `30` |
|
|
93
|
+
| `--timeout <minutes>` | Task processing timeout | `10` |
|
|
94
|
+
| `--client-request-timeout <minutes>` | Client request analysis timeout | `2` |
|
|
95
|
+
| `--no-sse` | Disable SSE mode | SSE enabled |
|
|
96
|
+
| `--dry-run` | Poll but don't process tasks | `false` |
|
|
97
|
+
| `--working-dir <path>` | Working directory for Claude | Current directory |
|
|
98
|
+
| `--no-update-check` | Disable update check on startup | Check enabled |
|
|
99
|
+
| `-V, --version` | Show version number | |
|
|
100
|
+
| `-h, --help` | Show help | |
|
|
101
|
+
|
|
102
|
+
## Environment Variables
|
|
103
|
+
|
|
104
|
+
Create a `.env` file in your working directory or export these variables:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
# Required
|
|
108
|
+
SEGO_API_KEY=sk_live_... # Your Sego PM API key
|
|
109
|
+
|
|
110
|
+
# Optional
|
|
111
|
+
SEGO_API_URL=https://sego.pm # API URL (default: https://sego.pm)
|
|
112
|
+
SEGO_PROJECT_ID=... # Filter to specific project
|
|
113
|
+
SEGO_WORKING_DIR=/path/to/project # Working directory for Claude
|
|
114
|
+
|
|
115
|
+
# Advanced
|
|
116
|
+
AUTO_TASK_POLL_INTERVAL_MS=30000 # Poll interval in milliseconds
|
|
117
|
+
AUTO_TASK_TIMEOUT_MS=600000 # Task timeout in milliseconds
|
|
118
|
+
AUTO_TASK_SSE_ENABLED=true # Enable/disable SSE mode
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## How It Works
|
|
122
|
+
|
|
123
|
+
The monitor runs in hybrid mode:
|
|
124
|
+
|
|
125
|
+
### SSE Mode (Real-time)
|
|
126
|
+
- Listens for client request events via Server-Sent Events
|
|
127
|
+
- Processes new requests immediately as they arrive
|
|
128
|
+
- Uses local Claude to analyze and shape tasks
|
|
129
|
+
|
|
130
|
+
### Polling Mode (Batch)
|
|
131
|
+
- Checks every 30 seconds (configurable) for eligible tasks
|
|
132
|
+
- Processes tasks where:
|
|
133
|
+
- Project has auto-task enabled
|
|
134
|
+
- Task is in `BACKLOG` status
|
|
135
|
+
- Task's AI confidence >= project threshold
|
|
136
|
+
|
|
137
|
+
### Processing Flow
|
|
138
|
+
|
|
139
|
+
1. **Detect** - New task or client request is found
|
|
140
|
+
2. **Claim** - Task status updated to `IN_PROGRESS`
|
|
141
|
+
3. **Execute** - Claude processes the task with full context
|
|
142
|
+
4. **Complete** - Task moves to `IN_REVIEW` with output attached
|
|
143
|
+
|
|
144
|
+
## Project Configuration
|
|
145
|
+
|
|
146
|
+
Enable auto-task processing for your project:
|
|
147
|
+
|
|
148
|
+
1. Go to your project settings in Sego PM
|
|
149
|
+
2. Enable "Auto-Task Processing"
|
|
150
|
+
3. Set your confidence threshold (recommended: 0.85)
|
|
151
|
+
|
|
152
|
+
Or via API:
|
|
153
|
+
```bash
|
|
154
|
+
curl -X PATCH https://sego.pm/api/mcp/projects/{projectId}/auto-task \
|
|
155
|
+
-H "Authorization: Bearer sk_live_..." \
|
|
156
|
+
-H "Content-Type: application/json" \
|
|
157
|
+
-d '{"enabled": true, "confidenceThreshold": 0.85}'
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## Troubleshooting
|
|
161
|
+
|
|
162
|
+
### "Claude CLI is not available"
|
|
163
|
+
|
|
164
|
+
Ensure Claude Code is installed and authenticated:
|
|
165
|
+
```bash
|
|
166
|
+
npm install -g @anthropic-ai/claude-code
|
|
167
|
+
claude auth login
|
|
168
|
+
claude --version
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### "API key is required"
|
|
172
|
+
|
|
173
|
+
Set your API key via environment variable or CLI flag:
|
|
174
|
+
```bash
|
|
175
|
+
export SEGO_API_KEY=sk_live_...
|
|
176
|
+
# or
|
|
177
|
+
sego-auto-task --api-key=sk_live_...
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### Connection Issues
|
|
181
|
+
|
|
182
|
+
1. Verify your API key is valid
|
|
183
|
+
2. Check if you can reach the API:
|
|
184
|
+
```bash
|
|
185
|
+
curl -H "Authorization: Bearer sk_live_..." https://sego.pm/api/mcp/tasks
|
|
186
|
+
```
|
|
187
|
+
3. For local development, ensure `--api-url` points to your local server
|
|
188
|
+
|
|
189
|
+
### Tasks Not Being Processed
|
|
190
|
+
|
|
191
|
+
1. Verify auto-task is enabled for the project
|
|
192
|
+
2. Check task AI confidence meets the threshold
|
|
193
|
+
3. Ensure task is in `BACKLOG` status
|
|
194
|
+
4. Run with `--dry-run` to see what would be processed
|
|
195
|
+
|
|
196
|
+
## Running as a Service
|
|
197
|
+
|
|
198
|
+
### Using PM2
|
|
199
|
+
|
|
200
|
+
```bash
|
|
201
|
+
npm install -g pm2
|
|
202
|
+
|
|
203
|
+
# Start the monitor
|
|
204
|
+
pm2 start sego-auto-task --name "sego-monitor" -- --api-key=sk_live_...
|
|
205
|
+
|
|
206
|
+
# View logs
|
|
207
|
+
pm2 logs sego-monitor
|
|
208
|
+
|
|
209
|
+
# Auto-start on boot
|
|
210
|
+
pm2 save
|
|
211
|
+
pm2 startup
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### Using systemd (Linux)
|
|
215
|
+
|
|
216
|
+
Create `/etc/systemd/system/sego-auto-task.service`:
|
|
217
|
+
|
|
218
|
+
```ini
|
|
219
|
+
[Unit]
|
|
220
|
+
Description=Sego Auto-Task Monitor
|
|
221
|
+
After=network.target
|
|
222
|
+
|
|
223
|
+
[Service]
|
|
224
|
+
Type=simple
|
|
225
|
+
User=your-user
|
|
226
|
+
WorkingDirectory=/path/to/your/project
|
|
227
|
+
Environment=SEGO_API_KEY=sk_live_...
|
|
228
|
+
ExecStart=/usr/bin/sego-auto-task
|
|
229
|
+
Restart=always
|
|
230
|
+
RestartSec=10
|
|
231
|
+
|
|
232
|
+
[Install]
|
|
233
|
+
WantedBy=multi-user.target
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Then:
|
|
237
|
+
```bash
|
|
238
|
+
sudo systemctl enable sego-auto-task
|
|
239
|
+
sudo systemctl start sego-auto-task
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
## Development
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
# Clone the repository
|
|
246
|
+
git clone https://github.com/sego-solutions/sego-pm.git
|
|
247
|
+
cd sego-pm/auto-task-monitor
|
|
248
|
+
|
|
249
|
+
# Install dependencies
|
|
250
|
+
pnpm install
|
|
251
|
+
|
|
252
|
+
# Run in development mode
|
|
253
|
+
pnpm dev -- --api-key=sk_dev_...
|
|
254
|
+
|
|
255
|
+
# Type check
|
|
256
|
+
pnpm typecheck
|
|
257
|
+
|
|
258
|
+
# Build for production
|
|
259
|
+
pnpm build
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
## License
|
|
263
|
+
|
|
264
|
+
MIT - see [LICENSE](./LICENSE)
|
|
265
|
+
|
|
266
|
+
## Links
|
|
267
|
+
|
|
268
|
+
- [Sego PM](https://sego.pm) - AI-Assisted Project Management
|
|
269
|
+
- [Documentation](https://sego.pm/docs)
|
|
270
|
+
- [GitHub Issues](https://github.com/sego-solutions/sego-pm/issues)
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";var St=Object.create;var je=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var $t=Object.getOwnPropertyNames;var Pt=Object.getPrototypeOf,xt=Object.prototype.hasOwnProperty;var $=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Nt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $t(e))!xt.call(i,s)&&s!==t&&je(i,s,{get:()=>e[s],enumerable:!(n=It(e,s))||n.enumerable});return i};var de=(i,e,t)=>(t=i!=null?St(Pt(i)):{},Nt(e||!i||!i.__esModule?je(t,"default",{value:i,enumerable:!0}):t,i));var L=$(me=>{var ee=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},pe=class extends ee{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};me.CommanderError=ee;me.InvalidArgumentError=pe});var te=$(fe=>{var{InvalidArgumentError:Mt}=L(),ge=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Mt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Dt(i){let e=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+e+">":"["+e+"]"}fe.Argument=ge;fe.humanReadableArgName=Dt});var Ce=$(Re=>{var{humanReadableArgName:jt}=te(),ve=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,o)=>s.name().localeCompare(o.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),o=n.long&&e._findOption(n.long);!s&&!o?t.push(n):n.long&&!o?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(o=>!o.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>jt(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth||80,o=2,r=2;function a(m,v){if(v){let p=`${m.padEnd(n+r)}${v}`;return t.wrap(p,s-o,n+r)}return m}function l(m){return m.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(o))}let u=[`Usage: ${t.commandUsage(e)}`,""],c=t.commandDescription(e);c.length>0&&(u=u.concat([t.wrap(c,s,0),""]));let h=t.visibleArguments(e).map(m=>a(t.argumentTerm(m),t.argumentDescription(m)));h.length>0&&(u=u.concat(["Arguments:",l(h),""]));let d=t.visibleOptions(e).map(m=>a(t.optionTerm(m),t.optionDescription(m)));if(d.length>0&&(u=u.concat(["Options:",l(d),""])),this.showGlobalOptions){let m=t.visibleGlobalOptions(e).map(v=>a(t.optionTerm(v),t.optionDescription(v)));m.length>0&&(u=u.concat(["Global Options:",l(m),""]))}let f=t.visibleCommands(e).map(m=>a(t.subcommandTerm(m),t.subcommandDescription(m)));return f.length>0&&(u=u.concat(["Commands:",l(f),""])),u.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let o=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",r=new RegExp(`[\\n][${o}]+`);if(e.match(r))return e;let a=t-n;if(a<s)return e;let l=e.slice(0,n),u=e.slice(n).replace(`\r
|
|
5
|
+
`,`
|
|
6
|
+
`),c=" ".repeat(n),d="\\s\u200B",f=new RegExp(`
|
|
7
|
+
|.{1,${a-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),m=u.match(f)||[];return l+m.map((v,p)=>v===`
|
|
8
|
+
`?"":(p>0?c:"")+v.trimEnd()).join(`
|
|
9
|
+
`)}};Re.Help=ve});var Ee=$(be=>{var{InvalidArgumentError:Rt}=L(),ye=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Ht(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Rt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Vt(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},_e=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,o=s!==void 0?s:!1;return t.negate===(o===e)}};function Vt(i){return i.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ht(i){let e,t,n=i.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}be.Option=ye;be.DualOptions=_e});var He=$(Ve=>{function qt(i,e){if(Math.abs(i.length-e.length)>3)return Math.max(i.length,e.length);let t=[];for(let n=0;n<=i.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=i.length;s++){let o=1;i[s-1]===e[n-1]?o=0:o=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+o),s>1&&n>1&&i[s-1]===e[n-2]&&i[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[i.length][e.length]}function Ut(i,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=i.startsWith("--");t&&(i=i.slice(2),e=e.map(r=>r.slice(2)));let n=[],s=3,o=.4;return e.forEach(r=>{if(r.length<=1)return;let a=qt(i,r),l=Math.max(i.length,r.length);(l-a)/l>o&&(a<s?(s=a,n=[r]):a===s&&n.push(r))}),n.sort((r,a)=>r.localeCompare(a)),t&&(n=n.map(r=>`--${r}`)),n.length>1?`
|
|
10
|
+
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}Ve.suggestSimilar=Ut});var Be=$(Le=>{var Ft=require("node:events").EventEmitter,Oe=require("node:child_process"),x=require("node:path"),ke=require("node:fs"),y=require("node:process"),{Argument:Lt,humanReadableArgName:Bt}=te(),{CommanderError:we}=L(),{Help:Kt}=Ce(),{Option:qe,DualOptions:Gt}=Ee(),{suggestSimilar:Ue}=He(),Ae=class i extends Ft{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>y.stdout.write(t),writeErr:t=>y.stderr.write(t),getOutHelpWidth:()=>y.stdout.isTTY?y.stdout.columns:void 0,getErrHelpWidth:()=>y.stderr.isTTY?y.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,o=n;typeof s=="object"&&s!==null&&(o=s,s=null),o=o||{};let[,r,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(r);return s&&(l.description(s),l._executableHandler=!0),o.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(o.noHelp||o.hidden),l._executableFile=o.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),s?this:l}createCommand(e){return new i(e)}createHelp(){return Object.assign(new Kt,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Lt(e,t)}argument(e,t,n,s){let o=this.createArgument(e,t);return typeof n=="function"?o.default(s).argParser(n):o.default(n),this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",r=this.createCommand(n);return r.helpOption(!1),s&&r.arguments(s),o&&r.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=r,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new we(e,t,n)),y.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,o=n.slice(0,s);return this._storeOptionsAsProperties?o[s]=this:o[s]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new qe(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let r=`${s} ${o.message}`;this.error(r,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(o,r,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let l=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,l,r):o!==null&&e.variadic&&(o=e._concatValue(o,l)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,a)};return this.on("option:"+t,o=>{let r=`error: option '${e.flags}' argument '${o}' is invalid.`;s(o,r,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let r=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;s(o,r,"env")}),this}_optionEx(e,t,n,s,o){if(typeof t=="object"&&t instanceof qe)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(t,n);if(r.makeOptionMandatory(!!e.mandatory),typeof s=="function")r.default(o).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,u)=>{let c=a.exec(l);return c?c[0]:u},r.default(o).argParser(s)}else r.default(s);return this.addOption(r)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){y.versions?.electron&&(t.from="electron");let s=y.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=y.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":y.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function o(c,h){let d=x.resolve(c,h);if(ke.existsSync(d))return d;if(s.includes(x.extname(h)))return;let f=s.find(m=>ke.existsSync(`${d}${m}`));if(f)return`${d}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=ke.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=x.resolve(x.dirname(c),a)}if(a){let c=o(a,r);if(!c&&!e._executableFile&&this._scriptPath){let h=x.basename(this._scriptPath,x.extname(this._scriptPath));h!==this._name&&(c=o(a,`${h}-${e._name}`))}r=c||r}n=s.includes(x.extname(r));let l;y.platform!=="win32"?n?(t.unshift(r),t=Fe(y.execArgv).concat(t),l=Oe.spawn(y.argv[0],t,{stdio:"inherit"})):l=Oe.spawn(r,t,{stdio:"inherit"}):(t.unshift(r),t=Fe(y.execArgv).concat(t),l=Oe.spawn(y.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{y.on(h,()=>{l.killed===!1&&l.exitCode===null&&l.kill(h)})});let u=this._exitCallback;l.on("close",c=>{c=c??1,u?u(new we(c,"commander.executeSubCommandAsync","(close)")):y.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT"){let h=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",d=`'${r}' does not exist
|
|
15
|
+
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
+
- ${h}`;throw new Error(d)}else if(c.code==="EACCES")throw new Error(`'${r}' not executable`);if(!u)y.exit(1);else{let h=new we(1,"commander.executeSubCommandAsync","(error)");h.nestedError=c,u(h)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let o;return o=this._chainOrCallSubCommandHook(o,s,"preSubcommand"),o=this._chainOrCall(o,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),o}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,o)=>{let r=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;r=this._callParseArg(n,s,o,a)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let o=n.defaultValue;n.variadic?s<this.args.length?(o=this.args.slice(s),n.parseArg&&(o=o.reduce((r,a)=>e(n,a,r),n.defaultValue))):o===void 0&&(o=[]):s<this.args.length&&(o=this.args[s],n.parseArg&&(o=e(n,o,n.defaultValue))),t[s]=o}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(r=>{s.push({hookedCommand:o,callback:r})})}),t==="postAction"&&s.reverse(),s.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{s=this._chainOrCall(s,()=>o(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(o,e,t)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent&&this.parent.listenerCount(o))s(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(o=>n.conflictsWith.includes(o.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,o=e.slice();function r(l){return l.length>1&&l[0]==="-"}let a=null;for(;o.length;){let l=o.shift();if(l==="--"){s===n&&s.push(l),s.push(...o);break}if(a&&!r(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,r(l)){let u=this._findOption(l);if(u){if(u.required){let c=o.shift();c===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,c)}else if(u.optional){let c=null;o.length>0&&!r(o[0])&&(c=o.shift()),this.emit(`option:${u.name()}`,c)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),o.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),c=this._findOption(l.slice(0,u));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,l.slice(u+1));continue}}if(r(l)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(l),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){s.push(l),o.length>0&&s.push(...o);break}s.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,o=n.code||"commander.error";this._exit(s,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in y.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,y.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Gt(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=r=>{let a=r.attributeName(),l=this.getOptionValue(a),u=this.options.find(h=>h.negate&&a===h.attributeName()),c=this.options.find(h=>!h.negate&&a===h.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:c||r},s=r=>{let a=n(r),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],o=this;do{let r=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);s=s.concat(r),o=o.parent}while(o&&!o._enablePositionalOptions);t=Ue(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(o=>{s.push(o.name()),o.alias()&&s.push(o.alias())}),t=Ue(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Bt(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=x.basename(e,x.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=y.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,o=>{let r;typeof t=="function"?r=t({error:o.error,command:o.command}):r=t,r&&o.write(`${r}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Fe(i){return i.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?s=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],s=o[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}Le.Command=Ae});var Ye=$(I=>{var{Argument:Ke}=te(),{Command:Te}=Be(),{CommanderError:Wt,InvalidArgumentError:Ge}=L(),{Help:Yt}=Ce(),{Option:We}=Ee();I.program=new Te;I.createCommand=i=>new Te(i);I.createOption=(i,e)=>new We(i,e);I.createArgument=(i,e)=>new Ke(i,e);I.Command=Te;I.Option=We;I.Argument=Ke;I.Help=Yt;I.CommanderError=Wt;I.InvalidArgumentError=Ge;I.InvalidOptionArgumentError=Ge});var Qe=$((ts,Jt)=>{Jt.exports={name:"dotenv",version:"17.2.3",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var nt=$((ns,N)=>{var Se=require("fs"),ne=require("path"),Qt=require("os"),zt=require("crypto"),Xt=Qe(),Ie=Xt.version,ze=["\u{1F510} encrypt with Dotenvx: https://dotenvx.com","\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit","\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild","\u{1F4E1} add observability to secrets: https://dotenvx.com/ops","\u{1F465} sync secrets across teammates & machines: https://dotenvx.com/ops","\u{1F5C2}\uFE0F backup and recover secrets: https://dotenvx.com/ops","\u2705 audit secrets and track compliance: https://dotenvx.com/ops","\u{1F504} add secrets lifecycle management: https://dotenvx.com/ops","\u{1F511} add access controls to secrets: https://dotenvx.com/ops","\u{1F6E0}\uFE0F run anywhere with `dotenvx run -- yourcommand`","\u2699\uFE0F specify custom .env file path with { path: '/custom/path/.env' }","\u2699\uFE0F enable debug logging with { debug: true }","\u2699\uFE0F override existing env vars with { override: true }","\u2699\uFE0F suppress all logs with { quiet: true }","\u2699\uFE0F write to custom object with { processEnv: myObject }","\u2699\uFE0F load multiple .env files with { path: ['.env.local', '.env'] }"];function Zt(){return ze[Math.floor(Math.random()*ze.length)]}function F(i){return typeof i=="string"?!["false","0","no","off",""].includes(i.toLowerCase()):!!i}function en(){return process.stdout.isTTY}function tn(i){return en()?`\x1B[2m${i}\x1B[0m`:i}var nn=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function sn(i){let e={},t=i.toString();t=t.replace(/\r\n?/mg,`
|
|
24
|
+
`);let n;for(;(n=nn.exec(t))!=null;){let s=n[1],o=n[2]||"";o=o.trim();let r=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),r==='"'&&(o=o.replace(/\\n/g,`
|
|
25
|
+
`),o=o.replace(/\\r/g,"\r")),e[s]=o}return e}function on(i){i=i||{};let e=tt(i);i.path=e;let t=O.configDotenv(i);if(!t.parsed){let r=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw r.code="MISSING_DATA",r}let n=et(i).split(","),s=n.length,o;for(let r=0;r<s;r++)try{let a=n[r].trim(),l=an(t,a);o=O.decrypt(l.ciphertext,l.key);break}catch(a){if(r+1>=s)throw a}return O.parse(o)}function rn(i){console.error(`[dotenv@${Ie}][WARN] ${i}`)}function K(i){console.log(`[dotenv@${Ie}][DEBUG] ${i}`)}function Ze(i){console.log(`[dotenv@${Ie}] ${i}`)}function et(i){return i&&i.DOTENV_KEY&&i.DOTENV_KEY.length>0?i.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function an(i,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let n=t.password;if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let s=t.searchParams.get("environment");if(!s){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let o=`DOTENV_VAULT_${s.toUpperCase()}`,r=i.parsed[o];if(!r){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${o} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:r,key:n}}function tt(i){let e=null;if(i&&i.path&&i.path.length>0)if(Array.isArray(i.path))for(let t of i.path)Se.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=i.path.endsWith(".vault")?i.path:`${i.path}.vault`;else e=ne.resolve(process.cwd(),".env.vault");return Se.existsSync(e)?e:null}function Xe(i){return i[0]==="~"?ne.join(Qt.homedir(),i.slice(1)):i}function ln(i){let e=F(process.env.DOTENV_CONFIG_DEBUG||i&&i.debug),t=F(process.env.DOTENV_CONFIG_QUIET||i&&i.quiet);(e||!t)&&Ze("Loading env from encrypted .env.vault");let n=O._parseVault(i),s=process.env;return i&&i.processEnv!=null&&(s=i.processEnv),O.populate(s,n,i),{parsed:n}}function cn(i){let e=ne.resolve(process.cwd(),".env"),t="utf8",n=process.env;i&&i.processEnv!=null&&(n=i.processEnv);let s=F(n.DOTENV_CONFIG_DEBUG||i&&i.debug),o=F(n.DOTENV_CONFIG_QUIET||i&&i.quiet);i&&i.encoding?t=i.encoding:s&&K("No encoding is specified. UTF-8 is used by default");let r=[e];if(i&&i.path)if(!Array.isArray(i.path))r=[Xe(i.path)];else{r=[];for(let c of i.path)r.push(Xe(c))}let a,l={};for(let c of r)try{let h=O.parse(Se.readFileSync(c,{encoding:t}));O.populate(l,h,i)}catch(h){s&&K(`Failed to load ${c} ${h.message}`),a=h}let u=O.populate(n,l,i);if(s=F(n.DOTENV_CONFIG_DEBUG||s),o=F(n.DOTENV_CONFIG_QUIET||o),s||!o){let c=Object.keys(u).length,h=[];for(let d of r)try{let f=ne.relative(process.cwd(),d);h.push(f)}catch(f){s&&K(`Failed to load ${d} ${f.message}`),a=f}Ze(`injecting env (${c}) from ${h.join(",")} ${tn(`-- tip: ${Zt()}`)}`)}return a?{parsed:l,error:a}:{parsed:l}}function un(i){if(et(i).length===0)return O.configDotenv(i);let e=tt(i);return e?O._configVault(i):(rn(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),O.configDotenv(i))}function hn(i,e){let t=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(i,"base64"),s=n.subarray(0,12),o=n.subarray(-16);n=n.subarray(12,-16);try{let r=zt.createDecipheriv("aes-256-gcm",t,s);return r.setAuthTag(o),`${r.update(n)}${r.final()}`}catch(r){let a=r instanceof RangeError,l=r.message==="Invalid key length",u=r.message==="Unsupported state or unable to authenticate data";if(a||l){let c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(u){let c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw r}}function dn(i,e,t={}){let n=!!(t&&t.debug),s=!!(t&&t.override),o={};if(typeof e!="object"){let r=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw r.code="OBJECT_REQUIRED",r}for(let r of Object.keys(e))Object.prototype.hasOwnProperty.call(i,r)?(s===!0&&(i[r]=e[r],o[r]=e[r]),n&&K(s===!0?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):(i[r]=e[r],o[r]=e[r]);return o}var O={configDotenv:cn,_configVault:ln,_parseVault:on,config:un,decrypt:hn,parse:sn,populate:dn};N.exports.configDotenv=O.configDotenv;N.exports._configVault=O._configVault;N.exports._parseVault=O._parseVault;N.exports.config=O.config;N.exports.decrypt=O.decrypt;N.exports.parse=O.parse;N.exports.populate=O.populate;N.exports=O});var pt=$((as,dt)=>{var lt=require("url").parse,vn=require("events"),Cn=require("https"),yn=require("http"),_n=require("util"),bn=["pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","secureProtocol","servername","checkServerIdentity"],ht=[239,187,191],En=58,On=32,ct=10,kn=13,ut=1024*256,wn=/^(cookie|authorization)$/i;function An(i){return ht.every(function(e,t){return i[t]===e})}function _(i,e){var t=_.CONNECTING,n=e&&e.headers,s=!1;Object.defineProperty(this,"readyState",{get:function(){return t}}),Object.defineProperty(this,"url",{get:function(){return i}});var o=this;o.reconnectInterval=1e3,o.connectionInProgress=!1;function r(p){t!==_.CLOSED&&(t=_.CONNECTING,m("error",new Y("error",{message:p})),d&&(i=d,d=null,s=!1),setTimeout(function(){t!==_.CONNECTING||o.connectionInProgress||(o.connectionInProgress=!0,f())},o.reconnectInterval))}var a,l="";n&&n["Last-Event-ID"]&&(l=n["Last-Event-ID"],delete n["Last-Event-ID"]);var u=!1,c="",h="",d=null;function f(){var p=lt(i),C=p.protocol==="https:";if(p.headers={"Cache-Control":"no-cache",Accept:"text/event-stream"},l&&(p.headers["Last-Event-ID"]=l),n){var T=s?Sn(n):n;for(var b in T){var w=T[b];w&&(p.headers[b]=w)}}p.rejectUnauthorized=!(e&&!e.rejectUnauthorized),e&&e.createConnection!==void 0&&(p.createConnection=e.createConnection);var R=e&&e.proxy;if(R){var A=lt(e.proxy);C=A.protocol==="https:",p.protocol=C?"https:":"http:",p.path=i,p.headers.Host=p.host,p.hostname=A.hostname,p.host=A.host,p.port=A.port}if(e&&e.https){for(var j in e.https)if(bn.indexOf(j)!==-1){var J=e.https[j];J!==void 0&&(p[j]=J)}}e&&e.withCredentials!==void 0&&(p.withCredentials=e.withCredentials),a=(C?Cn:yn).request(p,function(g){if(o.connectionInProgress=!1,g.statusCode===500||g.statusCode===502||g.statusCode===503||g.statusCode===504){m("error",new Y("error",{status:g.statusCode,message:g.statusMessage})),r();return}if(g.statusCode===301||g.statusCode===302||g.statusCode===307){var V=g.headers.location;if(!V){m("error",new Y("error",{status:g.statusCode,message:g.statusMessage}));return}var At=new URL(i).origin,Tt=new URL(V).origin;s=At!==Tt,g.statusCode===307&&(d=i),i=V,process.nextTick(f);return}if(g.statusCode!==200)return m("error",new Y("error",{status:g.statusCode,message:g.statusMessage})),o.close();t=_.OPEN,g.on("close",function(){g.removeAllListeners("close"),g.removeAllListeners("end"),r()}),g.on("end",function(){g.removeAllListeners("close"),g.removeAllListeners("end"),r()}),m("open",new Y("open"));var E,ce,ue=0,he=-1,Q=0,P=0;g.on("data",function(H){E?(H.length>E.length-P&&(Q=E.length*2+H.length,Q>ut&&(Q=E.length+H.length+ut),ce=Buffer.alloc(Q),E.copy(ce,0,0,P),E=ce),H.copy(E,P),P+=H.length):(E=H,An(E)&&(E=E.slice(ht.length)),P=E.length);for(var S=0,z=P;S<z;){u&&(E[S]===ct&&++S,u=!1);for(var q=-1,X=he,Z,U=ue;q<0&&U<z;++U)Z=E[U],Z===En?X<0&&(X=U-S):Z===kn?(u=!0,q=U-S):Z===ct&&(q=U-S);if(q<0){ue=z-S,he=X;break}else ue=0,he=-1;v(E,S,X,q),S+=q+1}S===z?(E=void 0,P=0):S>0&&(E=E.slice(S,P),P=E.length)})}),a.on("error",function(g){o.connectionInProgress=!1,r(g.message)}),a.setNoDelay&&a.setNoDelay(!0),a.end()}f();function m(){o.listeners(arguments[0]).length>0&&o.emit.apply(o,arguments)}this._close=function(){t!==_.CLOSED&&(t=_.CLOSED,a.abort&&a.abort(),a.xhr&&a.xhr.abort&&a.xhr.abort())};function v(p,C,T,b){if(b===0){if(c.length>0){var w=h||"message";m(w,new Tn(w,{data:c.slice(0,-1),lastEventId:l,origin:new URL(i).origin})),c=""}h=void 0}else if(T>0){var R=T<0,A=0,j=p.slice(C,C+(R?b:T)).toString();R?A=b:p[C+T+1]!==On?A=T+1:A=T+2,C+=A;var J=b-A,g=p.slice(C,C+J).toString();if(j==="data")c+=g+`
|
|
26
|
+
`;else if(j==="event")h=g;else if(j==="id")l=g;else if(j==="retry"){var V=parseInt(g,10);Number.isNaN(V)||(o.reconnectInterval=V)}}}}dt.exports=_;_n.inherits(_,vn.EventEmitter);_.prototype.constructor=_;["open","error","message"].forEach(function(i){Object.defineProperty(_.prototype,"on"+i,{get:function(){var t=this.listeners(i)[0];return t?t._listener?t._listener:t:void 0},set:function(t){this.removeAllListeners(i),this.addEventListener(i,t)}})});Object.defineProperty(_,"CONNECTING",{enumerable:!0,value:0});Object.defineProperty(_,"OPEN",{enumerable:!0,value:1});Object.defineProperty(_,"CLOSED",{enumerable:!0,value:2});_.prototype.CONNECTING=0;_.prototype.OPEN=1;_.prototype.CLOSED=2;_.prototype.close=function(){this._close()};_.prototype.addEventListener=function(e,t){typeof t=="function"&&(t._listener=t,this.on(e,t))};_.prototype.dispatchEvent=function(e){if(!e.type)throw new Error("UNSPECIFIED_EVENT_TYPE_ERR");this.emit(e.type,e.detail)};_.prototype.removeEventListener=function(e,t){typeof t=="function"&&(t._listener=void 0,this.removeListener(e,t))};function Y(i,e){if(Object.defineProperty(this,"type",{writable:!1,value:i,enumerable:!0}),e)for(var t in e)e.hasOwnProperty(t)&&Object.defineProperty(this,t,{writable:!1,value:e[t],enumerable:!0})}function Tn(i,e){Object.defineProperty(this,"type",{writable:!1,value:i,enumerable:!0});for(var t in e)e.hasOwnProperty(t)&&Object.defineProperty(this,t,{writable:!1,value:e[t],enumerable:!0})}function Sn(i){var e={};for(var t in i)wn.test(t)||(e[t]=i[t]);return e}});var Je=de(Ye(),1),{program:B,createCommand:Bn,createArgument:Kn,createOption:Gn,CommanderError:Wn,InvalidArgumentError:Yn,InvalidOptionArgumentError:Jn,Command:Qn,Argument:zn,Option:Xn,Help:Zn}=Je.default;var Ot=de(nt(),1),De=require("path"),kt=require("fs");function st(i){let e=i.apiKey||process.env.SEGO_API_KEY,t=i.apiUrl||process.env.SEGO_API_URL||"https://sego.pm",n=i.pollIntervalMs||(process.env.AUTO_TASK_POLL_INTERVAL_MS?parseInt(process.env.AUTO_TASK_POLL_INTERVAL_MS,10):3e4),s=i.timeoutMs||(process.env.AUTO_TASK_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_TIMEOUT_MS,10):6e5),o=i.clientRequestTimeoutMs||(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS,10):3e5);if(!e)throw new Error("API key is required. Set SEGO_API_KEY environment variable or use --api-key flag.");let r=i.projectId||process.env.SEGO_PROJECT_ID,a=i.sseEnabled??process.env.AUTO_TASK_SSE_ENABLED!=="false",l=i.workingDirectory||process.env.SEGO_WORKING_DIR;return{apiKey:e,apiUrl:t,pollIntervalMs:n,timeoutMs:s,dryRun:i.dryRun??!1,projectId:r,sseEnabled:a,clientRequestTimeoutMs:o,workingDirectory:l}}var se=class{baseUrl;apiKey;projectId;constructor(e,t,n){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t,this.projectId=n}async request(e,t={}){let n=`${this.baseUrl}${e}`,s=await fetch(n,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...t.headers}});if(!s.ok){let o=await s.text(),r;try{let a=JSON.parse(o);r=a.error||a.message||o}catch{r=o}throw new Error(`API error (${s.status}): ${r}`)}return s.json()}async getEligibleTask(){let e=this.projectId?`/api/mcp/tasks/auto-task/eligible?projectId=${this.projectId}`:"/api/mcp/tasks/auto-task/eligible";return(await this.request(e)).task}async startTask(e){return this.request("/api/mcp/tasks/auto-task/start",{method:"POST",body:JSON.stringify({taskId:e})})}async completeTask(e,t,n){return this.request("/api/mcp/tasks/auto-task/complete",{method:"POST",body:JSON.stringify({runId:e,status:t,comment:n?.comment,errorMessage:n?.errorMessage})})}async sendAlert(e,t,n){return this.request("/api/notifications/auto-task-alert",{method:"POST",body:JSON.stringify({runId:e,alertType:t,errorDetails:n})})}async validateAuth(){try{return await this.request("/api/mcp/auth/validate",{method:"POST"}),!0}catch{return!1}}getClientRequestMonitorUrl(){if(!this.projectId)throw new Error("Project ID is required for client request monitoring");return`${this.baseUrl}/api/projects/${this.projectId}/client-requests/monitor`}getApiKey(){return this.apiKey}getProjectId(){return this.projectId}async submitAnalysis(e,t,n,s){return this.request(`/api/client-requests/${e}/analysis`,{method:"POST",body:JSON.stringify({monitorId:t,analysis:n,processingTimeMs:s})})}async reportAnalysisFailure(e,t,n){return this.request(`/api/client-requests/${e}/analysis`,{method:"PUT",body:JSON.stringify({monitorId:t,error:n})})}async claimTask(e,t){if(!this.projectId)throw new Error("Project ID is required for claiming tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/claim`,{method:"POST",body:JSON.stringify({monitorId:t})})}async completeBacklogTask(e,t,n){if(!this.projectId)throw new Error("Project ID is required for completing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/complete`,{method:"POST",body:JSON.stringify({monitorId:t,result:n})})}async failBacklogTask(e,t,n,s=!0){if(!this.projectId)throw new Error("Project ID is required for failing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/fail`,{method:"POST",body:JSON.stringify({monitorId:t,error:n,returnToBacklog:s})})}};var G=require("child_process"),M=require("fs"),W=require("os"),ie=require("path");function oe(){let i=[(0,ie.join)((0,W.homedir)(),".claude","local","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let e of i)if((0,M.existsSync)(e))return e;return"claude"}var k=null;function pn(i){let e=[`# Task: ${i.title}`,"",`**Project:** ${i.project.name}`,`**Priority:** ${i.priority}`,`**Type:** ${i.type}`,"","## Description",i.description,""];return i.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),i.acceptanceCriteria.forEach((t,n)=>{e.push(`${n+1}. ${t}`)}),e.push("")),i.technicalNotes&&(e.push("## Technical Notes"),e.push(i.technicalNotes),e.push("")),i.project.knowledgeBase&&(e.push("## Project Context"),e.push(i.project.knowledgeBase),e.push("")),e.push("---"),e.push(""),e.push('Please work on this task. When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
|
|
27
|
+
`)}async function it(i,e){let t=pn(i);return k||(k=oe()),new Promise(n=>{let s="",o="",r=!1,a=!1,l=(0,G.spawn)(k,["--print","--dangerously-skip-permissions","--mcp-config",'{"mcpServers":{}}'],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:process.cwd()}});l.stdin?.write(t),l.stdin?.end();let u=setTimeout(()=>{r=!0,a=!0,l.kill("SIGTERM"),setTimeout(()=>{l.killed||l.kill("SIGKILL")},5e3)},e);l.stdout?.on("data",c=>{s+=c.toString()}),l.stderr?.on("data",c=>{o+=c.toString()}),l.on("close",c=>{if(clearTimeout(u),r){n({success:!1,output:s,error:"Process timed out",timedOut:!0});return}let h=s.includes("TASK_COMPLETE")&&!s.includes("TASK_BLOCKED");if(c!==0&&!a){n({success:!1,output:s,error:o||`Process exited with code ${c}`,timedOut:!1});return}let d=s.match(/TASK_BLOCKED:\s*(.+)/i);if(d){n({success:!1,output:s,error:`Task blocked: ${d[1]}`,timedOut:!1});return}n({success:h,output:s,error:h?void 0:"Task did not complete successfully",timedOut:!1})}),l.on("error",c=>{clearTimeout(u),n({success:!1,output:s,error:`Failed to spawn claude: ${c.message}`,timedOut:!1})})})}async function ot(){return k=oe(),k&&k!=="claude"&&(0,M.existsSync)(k)?(console.log(`Found Claude CLI at: ${k}`),!0):new Promise(i=>{let e=(0,G.spawn)(k,["--version"],{stdio:["pipe","pipe","pipe"]});e.on("close",t=>{i(t===0)}),e.on("error",()=>{i(!1)}),setTimeout(()=>{e.kill(),i(!1)},5e3)})}function mn(i){let e=["# Client Request Analysis","","You are an expert software architect and project manager. A client has submitted a request for their project.","Your job is to analyze this request and break it down into actionable development tasks.","","## Client Request","",i.description,"","## Project Context","",`**Project Name:** ${i.projectContext.projectName}`];return i.projectContext.projectDescription&&e.push(`**Description:** ${i.projectContext.projectDescription}`),i.projectContext.techStack&&i.projectContext.techStack.length>0&&e.push(`**Tech Stack:** ${i.projectContext.techStack.join(", ")}`),i.projectContext.existingFeatures&&i.projectContext.existingFeatures.length>0&&(e.push(""),e.push("**Existing Features/Tasks:**"),i.projectContext.existingFeatures.forEach(t=>{e.push(`- ${t}`)})),e.push(""),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Analyze this client request and produce a structured JSON response. You have access to the full codebase, so:"),e.push("1. Explore the codebase to understand the existing architecture and patterns"),e.push("2. Identify the specific files and components that would need to be modified"),e.push("3. Break down the request into 2-6 specific, actionable tasks"),e.push("4. Provide accurate time estimates based on the actual complexity you observe in the code"),e.push(""),e.push("Output your analysis as a JSON object with this structure:"),e.push("```json"),e.push("{"),e.push(' "summary": "Brief summary of what the client wants",'),e.push(' "reasoning": "Your analysis of how to approach this",'),e.push(' "suggestedTasks": ['),e.push(" {"),e.push(' "title": "Task title",'),e.push(' "description": "Detailed description",'),e.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),e.push(' "estimatedHours": 4,'),e.push(' "priority": "MEDIUM",'),e.push(' "type": "FEATURE",'),e.push(' "technicalNotes": "Implementation details",'),e.push(' "questionsForClient": [],'),e.push(' "aiConfidence": 0.85'),e.push(" }"),e.push(" ],"),e.push(' "questionsForClient": ["Any clarifying questions"],'),e.push(' "estimatedTotalHours": 12,'),e.push(' "aiConfidence": 0.85'),e.push("}"),e.push("```"),e.push(""),e.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),e.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),e.push("aiConfidence should be between 0 and 1"),e.push(""),e.push("IMPORTANT: Output ONLY the JSON object, no additional text before or after."),e.join(`
|
|
28
|
+
`)}function gn(i){let e=i.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1].trim())}catch{}let t=i.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function rt(i,e,t={}){let n=mn(i),s=t.verbose??!0;return s&&(console.log("[Claude] Starting analysis..."),console.log("[Claude] Prompt length:",n.length,"characters")),k||(k=oe()),new Promise(o=>{let r="",a="",l=!1,u=!1;s&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let c=(0,ie.join)((0,W.tmpdir)(),`claude-prompt-${Date.now()}.txt`);(0,M.writeFileSync)(c,n,"utf-8");let h=`cat "${c}" | ${k} --print --dangerously-skip-permissions`;s&&(console.log("[Claude] Working directory:",process.cwd()),console.log("[Claude] Temp file:",c),console.log("[Claude] Running via shell..."));let d=(0,G.spawn)("sh",["-c",h],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:process.cwd()},cwd:process.cwd()});s&&console.log("[Claude] Shell process started with PID:",d.pid),d.stdin?.end();let f=()=>{try{(0,M.unlinkSync)(c),s&&console.log("[Claude] Temp file cleaned up")}catch{}},m=setTimeout(()=>{l=!0,u=!0,console.log("[Claude] Timeout reached, killing process..."),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},5e3)},e);d.stdout?.on("data",v=>{let p=v.toString();r+=p,s&&process.stdout.write(p)}),d.stderr?.on("data",v=>{let p=v.toString();a+=p,s&&process.stderr.write(`[Claude stderr] ${p}`)}),d.on("close",(v,p)=>{clearTimeout(m),f(),s&&(console.log(""),console.log(`[Claude] Process exited with code ${v}, signal ${p}`),console.log(`[Claude] Output length: ${r.length} characters`),console.log(`[Claude] Error output length: ${a.length} characters`),a&&console.log(`[Claude] Stderr: ${a.substring(0,500)}`));let C=gn(r);if(C&&C.summary&&Array.isArray(C.suggestedTasks)){s&&l&&console.log("[Claude] Timeout was triggered but we got valid output - treating as success"),o({success:!0,analysis:C,output:r,timedOut:!1});return}if(l){o({success:!1,output:r,error:"Process timed out without producing valid output",timedOut:!0});return}if(v!==0&&!u){o({success:!1,output:r,error:a||`Process exited with code ${v}`,timedOut:!1});return}if(!C){o({success:!1,output:r,error:"Failed to parse analysis JSON from output",timedOut:!1});return}if(!C.summary||!Array.isArray(C.suggestedTasks)){o({success:!1,output:r,error:"Invalid analysis structure - missing required fields",timedOut:!1});return}o({success:!0,analysis:C,output:r,timedOut:!1})}),d.on("error",v=>{clearTimeout(m),console.error("[Claude] Spawn error:",v),o({success:!1,output:r,error:`Failed to spawn claude: ${v.message}`,timedOut:!1})}),d.on("spawn",()=>{s&&console.log("[Claude] Process spawned successfully")})})}function fn(i){let e=[`# Task: ${i.title}`,"",`**Project:** ${i.projectContext.projectName}`,`**Priority:** ${i.priority}`,`**Type:** ${i.type}`,`**Estimated Hours:** ${i.estimatedHours||"N/A"}`,"","## Description",i.description||"No description provided.",""];if(i.acceptanceCriteria&&i.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),i.acceptanceCriteria.forEach((t,n)=>{e.push(`${n+1}. ${t}`)}),e.push("")),i.technicalNotes&&(e.push("## Technical Notes"),e.push(i.technicalNotes),e.push("")),i.projectContext.projectDescription&&(e.push("## Project Description"),e.push(i.projectContext.projectDescription),e.push("")),i.projectContext.knowledgeBase){e.push("## Project Knowledge Base");let t=i.projectContext.knowledgeBase;t.length>1e4?e.push(t.substring(0,1e4)+`
|
|
29
|
+
|
|
30
|
+
[... truncated ...]`):e.push(t),e.push("")}return e.push("---"),e.push(""),e.push("Please work on this task. Implement the required changes according to the acceptance criteria."),e.push(""),e.push('When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
|
|
31
|
+
`)}async function at(i,e,t={}){let n=fn(i),s=t.verbose??!0,o=t.workingDirectory||process.cwd();return s&&(console.log("[Claude] Starting backlog task processing..."),console.log("[Claude] Prompt length:",n.length,"characters"),console.log("[Claude] Working directory:",o)),k||(k=oe()),s&&console.log("[Claude] Claude path:",k),new Promise(r=>{let a="",l="",u=!1,c=!1;s&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let h=(0,ie.join)((0,W.tmpdir)(),`claude-task-${Date.now()}.txt`);(0,M.writeFileSync)(h,n,"utf-8");let d=`cat "${h}" | ${k} --print --dangerously-skip-permissions`;s&&(console.log("[Claude] Temp file:",h),console.log("[Claude] Running via shell..."));let f=(0,G.spawn)("sh",["-c",d],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:o},cwd:o});s&&console.log("[Claude] Shell process started with PID:",f.pid);let m=0,v=setInterval(()=>{if(s&&!u){let b=Math.floor((Date.now()-p)/1e3);a.length===m&&console.log(`[Claude] Still running... ${b}s elapsed, ${a.length} bytes output, waiting for response...`),m=a.length}},3e4),p=Date.now();f.stdin?.end();let C=()=>{try{(0,M.unlinkSync)(h),s&&console.log("[Claude] Temp file cleaned up")}catch{}},T=setTimeout(()=>{u=!0,c=!0,clearInterval(v),console.log("[Claude] Timeout reached, killing process..."),console.log(`[Claude] Output collected: ${a.length} characters`),a.length>0&&console.log(`[Claude] Last 500 chars of output: ${a.slice(-500)}`),l.length>0&&console.log(`[Claude] Stderr: ${l.substring(0,500)}`),f.kill("SIGTERM"),setTimeout(()=>{f.killed||f.kill("SIGKILL")},5e3)},e);f.stdout?.on("data",b=>{let w=b.toString();a+=w,s&&process.stdout.write(w)}),f.stderr?.on("data",b=>{let w=b.toString();l+=w,s&&process.stderr.write(`[Claude stderr] ${w}`)}),f.on("close",(b,w)=>{clearTimeout(T),clearInterval(v),C(),s&&(console.log(""),console.log(`[Claude] Process exited with code ${b}, signal ${w}`),console.log(`[Claude] Output length: ${a.length} characters`),l&&console.log(`[Claude] Stderr: ${l.substring(0,1e3)}`));let R=a.includes("TASK_COMPLETE"),A=a.match(/TASK_BLOCKED:\s*(.+)/);if(u&&!R){r({success:!1,output:a,error:"Process timed out",timedOut:!0});return}if(A){r({success:!1,output:a,error:`Task blocked: ${A[1]}`,timedOut:!1});return}if(b!==0&&!c){r({success:!1,output:a,error:l||`Process exited with code ${b}`,timedOut:!1});return}r({success:!0,output:a,timedOut:!1})}),f.on("error",b=>{clearTimeout(T),clearInterval(v),C(),console.error("[Claude] Spawn error:",b),r({success:!1,output:a,error:`Failed to spawn claude: ${b.message}`,timedOut:!1})}),f.on("spawn",()=>{s&&console.log("[Claude] Process spawned successfully")})})}var $e=de(pt(),1),re=class{eventSource=null;url;apiKey;monitorId;reconnectAttempts=0;maxReconnectAttempts;reconnectDelayMs;reconnectTimer=null;isConnecting=!1;isStopped=!1;onClientRequestHandler=null;onTaskAvailableHandler=null;onConnectedHandler=null;onErrorHandler=null;onDisconnectedHandler=null;constructor(e,t,n,s={}){this.url=e,this.apiKey=t,this.monitorId=n,this.maxReconnectAttempts=s.maxReconnectAttempts??10,this.reconnectDelayMs=s.reconnectDelayMs??5e3}connect(){if(this.isConnecting||this.eventSource){console.log("[SSE] Already connected or connecting");return}this.isStopped=!1,this.isConnecting=!0;let e=`${this.url}?monitorId=${encodeURIComponent(this.monitorId)}`;console.log(`[SSE] Connecting to ${e}`),this.eventSource=new $e.default(e,{headers:{Authorization:`Bearer ${this.apiKey}`}}),this.eventSource.onopen=()=>{console.log("[SSE] Connection opened"),this.isConnecting=!1,this.reconnectAttempts=0},this.eventSource.addEventListener("connected",t=>{try{let n=JSON.parse(t.data);console.log(`[SSE] Connected to project: ${n.projectName}`),this.onConnectedHandler&&this.onConnectedHandler(n)}catch(n){console.error("[SSE] Error parsing connected event:",n)}}),this.eventSource.addEventListener("client_request_created",t=>{try{let n=JSON.parse(t.data);console.log(`[SSE] Received client request: ${n.requestId}`),this.onClientRequestHandler&&this.onClientRequestHandler(n.data)}catch(n){console.error("[SSE] Error parsing client_request_created event:",n)}}),this.eventSource.addEventListener("task_available",t=>{try{let n=JSON.parse(t.data);console.log(`[SSE] Received task available: ${n.taskId} - ${n.data.title}`),this.onTaskAvailableHandler&&this.onTaskAvailableHandler(n.data)}catch(n){console.error("[SSE] Error parsing task_available event:",n)}}),this.eventSource.onerror=t=>{console.error("[SSE] Connection error:",t),this.isConnecting=!1,this.onErrorHandler&&this.onErrorHandler(new Error("SSE connection error")),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.onDisconnectedHandler&&this.onDisconnectedHandler(),this.scheduleReconnect()}}scheduleReconnect(){if(this.isStopped){console.log("[SSE] Reconnection cancelled - client stopped");return}if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error(`[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached`),this.onErrorHandler&&this.onErrorHandler(new Error("Max reconnection attempts reached"));return}this.reconnectAttempts++;let e=Math.min(this.reconnectDelayMs*Math.pow(2,this.reconnectAttempts-1),6e4);console.log(`[SSE] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimer=setTimeout(()=>{this.connect()},e)}disconnect(){console.log("[SSE] Disconnecting"),this.isStopped=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.onDisconnectedHandler&&this.onDisconnectedHandler()}isConnected(){return this.eventSource?.readyState===$e.default.OPEN}onClientRequest(e){this.onClientRequestHandler=e}onTaskAvailable(e){this.onTaskAvailableHandler=e}onConnected(e){this.onConnectedHandler=e}onError(e){this.onErrorHandler=e}onDisconnected(e){this.onDisconnectedHandler=e}};var mt=require("crypto"),ae=class{client;config;isProcessing=!1;isProcessingClientRequest=!1;isProcessingBacklogTask=!1;isRunning=!1;pollTimeout=null;sseClient=null;monitorId;backlogTaskQueue=[];constructor(e){this.config=e,this.client=new se(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${(0,mt.randomBytes)(8).toString("hex")}`}async start(){if(this.isRunning){console.log("[Monitor] Already running");return}if(console.log("[Monitor] Starting auto-task monitor..."),console.log(`[Monitor] Monitor ID: ${this.monitorId}`),console.log(`[Monitor] API URL: ${this.config.apiUrl}`),console.log(`[Monitor] Project ID: ${this.config.projectId||"all projects"}`),console.log(`[Monitor] Poll interval: ${this.config.pollIntervalMs}ms`),console.log(`[Monitor] Task timeout: ${this.config.timeoutMs}ms`),console.log(`[Monitor] SSE enabled: ${this.config.sseEnabled}`),console.log(`[Monitor] Dry run: ${this.config.dryRun}`),console.log(`[Monitor] Working directory: ${this.config.workingDirectory||process.cwd()}`),!await this.client.validateAuth())throw new Error("API key validation failed");console.log("[Monitor] API key validated successfully"),this.isRunning=!0,this.config.sseEnabled&&this.config.projectId?this.startSSE():this.config.sseEnabled&&!this.config.projectId&&console.log("[Monitor] SSE disabled - project ID required for client request monitoring"),await this.poll()}startSSE(){try{let e=this.client.getClientRequestMonitorUrl();console.log(`[Monitor] Connecting to SSE: ${e}`),this.sseClient=new re(e,this.client.getApiKey(),this.monitorId,{maxReconnectAttempts:10,reconnectDelayMs:5e3}),this.sseClient.onConnected(t=>{console.log(`[Monitor] SSE connected to project: ${t.projectName}`),console.log(`[Monitor] Active subscribers: ${t.subscriberCount}`),t.backlogTaskCount!==void 0&&console.log(`[Monitor] Backlog tasks available: ${t.backlogTaskCount}`)}),this.sseClient.onClientRequest(async t=>{await this.processClientRequest(t)}),this.sseClient.onTaskAvailable(async t=>{await this.handleTaskAvailable(t)}),this.sseClient.onError(t=>{console.error("[Monitor] SSE error:",t.message)}),this.sseClient.onDisconnected(()=>{console.log("[Monitor] SSE disconnected")}),this.sseClient.connect()}catch(e){console.error("[Monitor] Failed to start SSE:",e)}}async processClientRequest(e){if(this.isProcessingClientRequest){console.log("[Monitor] Already processing a client request, skipping");return}if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing client request: ${e.id}`),console.log(`[Monitor] Project: ${e.projectContext.projectName}`),console.log(`[Monitor] Description: ${e.description.substring(0,200)}${e.description.length>200?"...":""}`),console.log(`[Monitor] Timeout: ${this.config.clientRequestTimeoutMs}ms`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping client request processing");return}this.isProcessingClientRequest=!0;let t=Date.now();try{console.log("[Monitor] Running Claude for client request analysis..."),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let n=await rt(e,this.config.clientRequestTimeoutMs,{verbose:!0});console.log("-".repeat(60));let s=Date.now()-t;if(n.timedOut){console.log("[Monitor] Claude timed out for client request"),await this.client.reportAnalysisFailure(e.id,this.monitorId,"Analysis timed out");return}if(!n.success||!n.analysis){console.log(`[Monitor] Claude analysis failed: ${n.error}`),await this.client.reportAnalysisFailure(e.id,this.monitorId,n.error||"Unknown error");return}console.log("[Monitor] Submitting analysis...");let o=await this.client.submitAnalysis(e.id,this.monitorId,n.analysis,s);console.log(`[Monitor] Analysis submitted successfully - ${o.tasksCount} tasks suggested (${s}ms)`)}catch(n){console.error("[Monitor] Error processing client request:",n);try{await this.client.reportAnalysisFailure(e.id,this.monitorId,n instanceof Error?n.message:"Unknown error")}catch(s){console.error("[Monitor] Failed to report analysis failure:",s)}}finally{this.isProcessingClientRequest=!1}}async handleTaskAvailable(e){console.log(`[Monitor] Task available: ${e.id} - ${e.title}`),this.backlogTaskQueue.some(t=>t.id===e.id)||(this.backlogTaskQueue.push(e),console.log(`[Monitor] Added to queue (${this.backlogTaskQueue.length} tasks in queue)`)),await this.processNextBacklogTask()}async processNextBacklogTask(){if(this.isProcessingBacklogTask){console.log("[Monitor] Already processing a backlog task");return}if(this.backlogTaskQueue.length===0){console.log("[Monitor] No backlog tasks in queue");return}let e=this.backlogTaskQueue.shift();if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing backlog task: ${e.id}`),console.log(`[Monitor] Title: ${e.title}`),console.log(`[Monitor] Type: ${e.type} | Priority: ${e.priority}`),console.log(`[Monitor] Estimated hours: ${e.estimatedHours||"N/A"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping backlog task processing"),this.backlogTaskQueue.length>0&&await this.processNextBacklogTask();return}this.isProcessingBacklogTask=!0;let t=Date.now();try{console.log("[Monitor] Claiming task..."),await this.client.claimTask(e.id,this.monitorId),console.log("[Monitor] Task claimed successfully"),console.log("[Monitor] Running Claude for backlog task..."),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let n=await at(e,this.config.timeoutMs,{verbose:!0,workingDirectory:this.config.workingDirectory});console.log("-".repeat(60));let s=Date.now()-t;if(n.timedOut){console.log("[Monitor] Claude timed out for backlog task"),await this.client.failBacklogTask(e.id,this.monitorId,"Task processing timed out",!0);return}if(!n.success){console.log(`[Monitor] Claude failed: ${n.error}`),await this.client.failBacklogTask(e.id,this.monitorId,n.error||"Unknown error",!0);return}console.log("[Monitor] Completing task..."),await this.client.completeBacklogTask(e.id,this.monitorId,{summary:n.output?.substring(0,1e3)||"Task completed by auto-monitor"}),console.log(`[Monitor] Task ${e.id} completed successfully (${s}ms)`)}catch(n){console.error("[Monitor] Error processing backlog task:",n);try{await this.client.failBacklogTask(e.id,this.monitorId,n instanceof Error?n.message:"Unknown error",!0)}catch(s){console.error("[Monitor] Failed to report task failure:",s)}}finally{this.isProcessingBacklogTask=!1,this.backlogTaskQueue.length>0&&(console.log(`[Monitor] ${this.backlogTaskQueue.length} more tasks in queue, processing next...`),await this.processNextBacklogTask())}}stop(){console.log("[Monitor] Stopping..."),this.isRunning=!1,this.pollTimeout&&(clearTimeout(this.pollTimeout),this.pollTimeout=null),this.sseClient&&(this.sseClient.disconnect(),this.sseClient=null)}async poll(){if(this.isRunning){try{this.isProcessing||await this.checkForTask()}catch(e){console.error("[Monitor] Poll error:",e)}this.isRunning&&(this.pollTimeout=setTimeout(()=>this.poll(),this.config.pollIntervalMs))}}async checkForTask(){console.log("[Monitor] Checking for eligible tasks...");let e=await this.client.getEligibleTask();if(!e){console.log("[Monitor] No eligible tasks found");return}if(console.log(`[Monitor] Found eligible task: ${e.title} (confidence: ${e.aiConfidence})`),this.config.dryRun){console.log("[Monitor] Dry run - skipping task processing");return}await this.processTask(e)}async processTask(e){this.isProcessing=!0;try{console.log(`[Monitor] Starting task: ${e.id}`);let t=await this.client.startTask(e.id);console.log(`[Monitor] Task started, run ID: ${t.runId}`),console.log("[Monitor] Invoking Claude...");let n=await it(e,this.config.timeoutMs);if(n.timedOut){console.log("[Monitor] Claude timed out"),await this.handleFailure(t.runId,e,"TIMEOUT",n.output,"Task processing timed out");return}if(!n.success){console.log(`[Monitor] Claude failed: ${n.error}`),await this.handleFailure(t.runId,e,"FAILED",n.output,n.error);return}console.log("[Monitor] Claude completed successfully"),await this.handleSuccess(t.runId,e,n.output)}catch(t){console.error("[Monitor] Error processing task:",t)}finally{this.isProcessing=!1}}async handleSuccess(e,t,n){let o=n.length>5e3?`${n.substring(0,5e3)}...
|
|
32
|
+
|
|
33
|
+
[Output truncated]`:n;await this.client.completeTask(e,"COMPLETED",{comment:`## Auto-Task Completed
|
|
34
|
+
|
|
35
|
+
${o}`}),console.log(`[Monitor] Task ${t.id} completed and moved to IN_REVIEW`)}async handleFailure(e,t,n,s,o){let a=s.length>3e3?`${s.substring(0,3e3)}...
|
|
36
|
+
|
|
37
|
+
[Output truncated]`:s,l=[`## Auto-Task ${n==="TIMEOUT"?"Timed Out":"Failed"}`,"",o?`**Error:** ${o}`:"","","### Output","```",a,"```"].filter(Boolean).join(`
|
|
38
|
+
`);await this.client.completeTask(e,n,{comment:l,errorMessage:o}),console.log(`[Monitor] Task ${t.id} marked as ${n}, sending alert...`);try{let u=await this.client.sendAlert(e,n,o);console.log(`[Monitor] Alert sent to ${u.emailsSent} recipients`)}catch(u){console.error("[Monitor] Failed to send alert:",u)}}};var gt=require("readline"),le=require("fs"),ft=require("path");function In(){let i=(0,gt.createInterface)({input:process.stdin,output:process.stdout});return{ask:e=>new Promise(t=>{i.question(e,n=>{t(n.trim())})}),close:()=>i.close()}}async function $n(i,e){try{return(await fetch(`${i}/api/mcp/auth/validate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}})).ok}catch{return!1}}function Pn(i){let e=`# Sego Auto-Task Monitor Configuration
|
|
39
|
+
# Generated by sego-auto-task init
|
|
40
|
+
|
|
41
|
+
# Required: Your Sego PM API key
|
|
42
|
+
SEGO_API_KEY=${i.apiKey}
|
|
43
|
+
|
|
44
|
+
# API URL (default: https://sego.pm)
|
|
45
|
+
SEGO_API_URL=${i.apiUrl}
|
|
46
|
+
`;return i.projectId&&(e+=`
|
|
47
|
+
# Filter to specific project
|
|
48
|
+
SEGO_PROJECT_ID=${i.projectId}
|
|
49
|
+
`),e}async function vt(i={}){console.log(""),console.log("=".repeat(50)),console.log(" Sego Auto-Task Monitor Setup Wizard"),console.log("=".repeat(50)),console.log("");let e=In();try{console.log("Step 1: API Key"),console.log("Get your API key from: https://sego.pm/developer/api-keys"),console.log("");let t=await e.ask("Enter your Sego PM API key: ");t||(console.error(`
|
|
50
|
+
Error: API key is required.`),process.exit(1)),console.log(""),console.log("Step 2: API URL");let s=await e.ask("Enter API URL (press Enter for https://sego.pm): ")||"https://sego.pm";console.log(""),console.log("Validating API key..."),await $n(s,t)||(console.error(`
|
|
51
|
+
Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${s}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!"),console.log(""),console.log("Step 3: Project ID (Optional)"),console.log("You can filter to a specific project, or monitor all projects.");let r=await e.ask("Enter Project ID (press Enter to skip): "),a={apiKey:t,apiUrl:s,projectId:r||void 0};console.log(""),console.log("Step 4: Save Configuration");let l=(0,ft.resolve)(process.cwd(),".env");if((0,le.existsSync)(l)&&(console.log(`Warning: .env file already exists at ${l}`),(await e.ask("Overwrite? (y/N): ")).toLowerCase()!=="y")){console.log(""),console.log("Configuration not saved. You can set these environment variables manually:"),console.log(""),console.log(`export SEGO_API_KEY="${a.apiKey}"`),console.log(`export SEGO_API_URL="${a.apiUrl}"`),a.projectId&&console.log(`export SEGO_PROJECT_ID="${a.projectId}"`),console.log(""),e.close();return}let c=Pn(a);(0,le.writeFileSync)(l,c),console.log(""),console.log("=".repeat(50)),console.log(" Setup Complete!"),console.log("=".repeat(50)),console.log(""),console.log(`Configuration saved to: ${l}`),console.log(""),console.log("Next steps:"),console.log(" 1. Make sure Claude Code CLI is installed and authenticated:"),console.log(" npm install -g @anthropic-ai/claude-code"),console.log(" claude auth login"),console.log(""),console.log(" 2. Start the monitor:"),console.log(" sego-auto-task"),console.log(""),console.log(" 3. Or run in dry-run mode to test:"),console.log(" sego-auto-task --dry-run"),console.log("")}finally{e.close()}}var D=require("fs"),yt=require("os"),Ne=require("path"),_t="@segosolutions/auto-task",Pe=(0,Ne.join)((0,yt.homedir)(),".sego-auto-task"),xe=(0,Ne.join)(Pe,"version-check.json"),xn=24*60*60*1e3;function Ct(i,e){let t=i.replace(/^v/,"").split(".").map(Number),n=e.replace(/^v/,"").split(".").map(Number);for(let s=0;s<Math.max(t.length,n.length);s++){let o=t[s]||0,r=n[s]||0;if(o<r)return-1;if(o>r)return 1}return 0}function Nn(){try{if(!(0,D.existsSync)(xe))return null;let i=JSON.parse((0,D.readFileSync)(xe,"utf-8"));return Date.now()-i.checkedAt<xn?i:null}catch{return null}}function Mn(i){try{(0,D.existsSync)(Pe)||(0,D.mkdirSync)(Pe,{recursive:!0});let e={latestVersion:i,checkedAt:Date.now()};(0,D.writeFileSync)(xe,JSON.stringify(e,null,2))}catch{}}async function Dn(){try{let i=new AbortController,e=setTimeout(()=>i.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(_t)}/latest`,{signal:i.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function bt(i){let e=Nn();if(e)return{currentVersion:i,latestVersion:e.latestVersion,updateAvailable:Ct(i,e.latestVersion)<0};let t=await Dn();return t&&Mn(t),{currentVersion:i,latestVersion:t,updateAvailable:t?Ct(i,t)<0:!1}}function Et(i){!i.updateAvailable||!i.latestVersion||(console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m Update available!\x1B[0m"),console.log(` Current version: \x1B[90m${i.currentVersion}\x1B[0m`),console.log(` Latest version: \x1B[32m${i.latestVersion}\x1B[0m`),console.log(""),console.log(" Run to update:"),console.log(` \x1B[36m npm update -g ${_t}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var wt="1.0.0",Me=null;B.name("sego-auto-task").description(`Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude.
|
|
52
|
+
|
|
53
|
+
Runs in hybrid mode:
|
|
54
|
+
- SSE: Listens for client request events and processes them with local Claude
|
|
55
|
+
- Polling: Checks for eligible auto-tasks to execute
|
|
56
|
+
|
|
57
|
+
Environment variables are loaded from .env in the working directory.
|
|
58
|
+
|
|
59
|
+
Use "sego-auto-task init" to run the interactive setup wizard.`).version(wt);B.command("init").description("Interactive setup wizard to configure your API key and settings").option("-y, --yes","Accept defaults without prompting").action(async i=>{await vt({yes:i.yes})});B.option("--api-key <key>","Sego PM API key (or set SEGO_API_KEY env)").option("--api-url <url>","Sego PM API URL (default: https://sego.pm)").option("--project-id <id>","Only process tasks for this project (or set SEGO_PROJECT_ID env). Required for SSE mode.").option("--poll <seconds>","Poll interval in seconds (default: 30)","30").option("--timeout <minutes>","Task timeout in minutes (default: 10)","10").option("--client-request-timeout <minutes>","Client request analysis timeout in minutes (default: 2)","2").option("--no-sse","Disable SSE mode for client request processing").option("--dry-run","Poll but do not process tasks",!1).option("--working-dir <path>","Working directory for Claude and .env loading (or set SEGO_WORKING_DIR env)").option("--no-update-check","Disable update check on startup").action(async i=>{try{i.updateCheck!==!1&&(Me=bt(wt).then(Et).catch(()=>{}));let e=i.workingDir||process.env.SEGO_WORKING_DIR||process.cwd(),t=(0,De.resolve)(e),n=(0,De.resolve)(t,".env");(0,kt.existsSync)(n)?(console.log(`Loading environment from: ${n}`),Ot.default.config({path:n})):console.log(`No .env file found in: ${t}`),console.log("Checking for Claude CLI..."),await ot()||(console.error("Error: Claude CLI is not available. Please install Claude Code first."),console.error(" npm install -g @anthropic-ai/claude-code"),process.exit(1)),console.log("Claude CLI is available");let o=st({apiKey:i.apiKey,apiUrl:i.apiUrl,projectId:i.projectId,pollIntervalMs:parseInt(i.poll,10)*1e3,timeoutMs:parseInt(i.timeout,10)*60*1e3,clientRequestTimeoutMs:parseInt(i.clientRequestTimeout,10)*60*1e3,sseEnabled:i.sse!==!1,dryRun:i.dryRun,workingDirectory:t}),a=o.apiUrl.includes("sego.pm")||o.apiUrl.includes("vercel")?"PRODUCTION":"DEVELOPMENT";console.log(""),console.log("=".repeat(60)),console.log("Sego Auto-Task Monitor - Environment Configuration"),console.log("=".repeat(60)),console.log(`Environment: ${a}`),console.log(`API URL: ${o.apiUrl}`),console.log(`SSE Mode: ${o.sseEnabled?"enabled":"disabled"}`),console.log(`Project Filter: ${o.projectId||"all projects"}`),console.log(`Poll Interval: ${o.pollIntervalMs/1e3}s`),console.log(`Task Timeout: ${o.timeoutMs/6e4}min`),console.log(`Dry Run: ${o.dryRun?"yes":"no"}`),console.log(`Working Dir: ${o.workingDirectory}`),console.log("=".repeat(60)),console.log(""),Me&&await Me;let l=new ae(o),u=()=>{console.log(`
|
|
60
|
+
Received shutdown signal`),l.stop(),process.exit(0)};process.on("SIGINT",u),process.on("SIGTERM",u),await l.start()}catch(e){console.error("Error:",e instanceof Error?e.message:e),process.exit(1)}});B.parse();
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@segosolutions/auto-task",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.cjs",
|
|
7
|
+
"bin": {
|
|
8
|
+
"sego-auto-task": "dist/index.cjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/sego-solutions/sego-pm.git",
|
|
18
|
+
"directory": "auto-task-monitor"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://sego.pm",
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/sego-solutions/sego-pm/issues"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"sego",
|
|
26
|
+
"task-automation",
|
|
27
|
+
"claude",
|
|
28
|
+
"ai",
|
|
29
|
+
"project-management",
|
|
30
|
+
"automation"
|
|
31
|
+
],
|
|
32
|
+
"author": "Sego Solutions <hello@segosolutions.com>",
|
|
33
|
+
"license": "MIT",
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=18.0.0"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"commander": "^12.1.0",
|
|
42
|
+
"dotenv": "^17.2.3",
|
|
43
|
+
"eventsource": "^2.0.2"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@types/eventsource": "^1.1.15",
|
|
47
|
+
"@types/node": "^20.10.0",
|
|
48
|
+
"esbuild": "^0.24.0",
|
|
49
|
+
"tsx": "^4.19.0",
|
|
50
|
+
"typescript": "^5.3.0"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"dev": "tsx watch src/index.ts",
|
|
54
|
+
"build": "tsx build.ts",
|
|
55
|
+
"start": "node dist/index.cjs",
|
|
56
|
+
"typecheck": "tsc --noEmit"
|
|
57
|
+
}
|
|
58
|
+
}
|