@agiflowai/agent-cli 0.0.6 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +236 -27
- package/dist/AgentHttpService-MFVF-74l.js +6 -0
- package/dist/AgentHttpService-MFVF-74l.js.map +1 -0
- package/dist/claudePostToolUse.js +5 -5
- package/dist/cli-2Wesya-Z.js +129 -0
- package/dist/cli-2Wesya-Z.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/networkLog.js +411 -16
- package/dist/networkLog.js.map +1 -1
- package/dist/package.json +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/dist/AgentHttpService-CYYuD3Wj.js +0 -6
- package/dist/AgentHttpService-CYYuD3Wj.js.map +0 -1
- package/dist/cli-DiglQoZ5.js +0 -129
- package/dist/cli-DiglQoZ5.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.0.7
|
|
4
|
+
Add:
|
|
5
|
+
- Add `router` command to enable switching provider to openai chatgpt sub.
|
|
6
|
+
Update:
|
|
7
|
+
- Launch `claude` command independently which can be dynamically switch model between gpt and claude.
|
|
8
|
+
|
|
3
9
|
## 0.0.6
|
|
4
10
|
- Launch Claude code npm package instead of native binary.
|
|
5
11
|
|
package/README.md
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
# Agiflow Agent CLI
|
|
2
2
|
|
|
3
|
+
[](https://github.com/AgiFlow/aicode-toolkit)
|
|
4
|
+
[](https://www.npmjs.com/package/@agiflowai/agent-cli)
|
|
5
|
+
[](./LICENSE)
|
|
6
|
+
|
|
3
7
|
@agiflowai/agent-cli - Command-line interface for connecting and managing AI agents (Claude Code, Gemini) with Agiflow remotely.
|
|
4
8
|
|
|
9
|
+
**Note**: for `agent-cli claude` and `agent-cli router` you don't need to authenticate with Agiflow server.
|
|
10
|
+
|
|
11
|
+
**🔗 Related Project**: Check out the [AgiFlow AI Code Toolkit](https://github.com/AgiFlow/aicode-toolkit) - an open-source collection of AI development tools and utilities.
|
|
12
|
+
|
|
5
13
|
## Quick Start
|
|
6
14
|
|
|
7
15
|
### Installation
|
|
@@ -18,18 +26,18 @@ npm install @agiflowai/agent-cli
|
|
|
18
26
|
|
|
19
27
|
The CLI provides three main commands:
|
|
20
28
|
|
|
21
|
-
#### 1. `
|
|
29
|
+
#### 1. `agent-cli connect` - Connect Daemon
|
|
22
30
|
Connect your local machine to the Agiflow platform to receive remote commands.
|
|
23
31
|
|
|
24
32
|
```bash
|
|
25
33
|
# Basic connection
|
|
26
|
-
|
|
34
|
+
agent-cli connect
|
|
27
35
|
|
|
28
36
|
# With custom server URL
|
|
29
|
-
|
|
37
|
+
agent-cli connect --server-url wss://your-server.com
|
|
30
38
|
|
|
31
39
|
# With verbose logging
|
|
32
|
-
|
|
40
|
+
agent-cli connect --verbose
|
|
33
41
|
```
|
|
34
42
|
|
|
35
43
|
**Options:**
|
|
@@ -39,19 +47,30 @@ agiflow connect --verbose
|
|
|
39
47
|
- `--reconnect-interval <ms>` - Reconnection interval in milliseconds (default: 5000)
|
|
40
48
|
- `--unique-instance` - Create unique daemon instance
|
|
41
49
|
|
|
42
|
-
#### 2. `
|
|
50
|
+
#### 2. `agent-cli claude` - Launch Claude Agent
|
|
43
51
|
Launch a Claude Code agent with full functionality.
|
|
44
52
|
|
|
45
53
|
```bash
|
|
46
54
|
# Basic Claude agent launch (requires session ID)
|
|
47
|
-
|
|
55
|
+
agent-cli claude --agent-session-id your-session-id
|
|
56
|
+
|
|
57
|
+
# With custom alias for easy identification
|
|
58
|
+
agent-cli claude \
|
|
59
|
+
--agent-session-id your-session-id \
|
|
60
|
+
--alias "my-dev-session"
|
|
48
61
|
|
|
49
62
|
# With custom configuration
|
|
50
|
-
|
|
63
|
+
agent-cli claude \
|
|
51
64
|
--agent-session-id your-session-id \
|
|
52
65
|
--server-url wss://your-server.com \
|
|
53
66
|
--working-directory /path/to/project \
|
|
54
67
|
--verbose
|
|
68
|
+
|
|
69
|
+
# With LLM routing to GPT-5
|
|
70
|
+
agent-cli claude \
|
|
71
|
+
--llm-provider chatgpt \
|
|
72
|
+
--llm-model gpt-5 \
|
|
73
|
+
--alias "gpt5-experiment"
|
|
55
74
|
```
|
|
56
75
|
|
|
57
76
|
**Options:**
|
|
@@ -65,41 +84,198 @@ agiflow claude \
|
|
|
65
84
|
- `-c, --agent-config <json>` - Agent configuration as JSON string
|
|
66
85
|
- `--args <args...>` - Additional arguments to pass to Claude
|
|
67
86
|
- `-v, --verbose` - Enable verbose logging
|
|
87
|
+
- `--alias <alias>` - Custom session alias for easy identification
|
|
68
88
|
|
|
69
|
-
|
|
70
|
-
|
|
89
|
+
**LLM Routing Options:**
|
|
90
|
+
- `--llm-provider <provider>` - LLM provider to route requests to (e.g., `chatgpt`, `openai`)
|
|
91
|
+
- `--llm-model <model>` - LLM model to use (e.g., `gpt-5`, `gpt-5-codex`)
|
|
92
|
+
|
|
93
|
+
**Note:** LLM routing configuration is saved to `~/.agiflow/sessions.json` and can be changed later using the `agent-cli router` command without restarting the agent.
|
|
94
|
+
|
|
95
|
+
##### Running Claude with ChatGPT/OpenAI
|
|
96
|
+
|
|
97
|
+
You can route Claude Code requests to ChatGPT/OpenAI using the LLM routing feature. This allows you to use GPT models while keeping the Claude Code interface.
|
|
98
|
+
|
|
99
|
+
**Prerequisites:**
|
|
100
|
+
|
|
101
|
+
1. **Authenticate with Codex CLI** (required for ChatGPT access):
|
|
102
|
+
```bash
|
|
103
|
+
# Install Codex CLI
|
|
104
|
+
npm install -g @openai/codex
|
|
105
|
+
|
|
106
|
+
# Authenticate (opens browser for OAuth login)
|
|
107
|
+
codex auth login
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
This stores your ChatGPT credentials in `~/.codex/auth.json`
|
|
111
|
+
|
|
112
|
+
**Usage Examples:**
|
|
71
113
|
|
|
72
114
|
```bash
|
|
73
|
-
#
|
|
74
|
-
|
|
115
|
+
# Start with default Claude (no routing)
|
|
116
|
+
agent-cli claude --alias "claude-session"
|
|
117
|
+
|
|
118
|
+
# Start with GPT-5 routing
|
|
119
|
+
agent-cli claude \
|
|
120
|
+
--alias "gpt5-session" \
|
|
121
|
+
--llm-provider chatgpt \
|
|
122
|
+
--llm-model gpt-5
|
|
123
|
+
|
|
124
|
+
# Start with GPT-5 Codex
|
|
125
|
+
agent-cli claude \
|
|
126
|
+
--alias "codex-session" \
|
|
127
|
+
--llm-provider chatgpt \
|
|
128
|
+
--llm-model gpt-5-codex
|
|
129
|
+
```
|
|
75
130
|
|
|
76
|
-
|
|
77
|
-
agiflow logout --remove-all
|
|
131
|
+
**How It Works:**
|
|
78
132
|
|
|
79
|
-
|
|
80
|
-
|
|
133
|
+
When routing is enabled:
|
|
134
|
+
1. Claude Code requests are intercepted before reaching Anthropic's API
|
|
135
|
+
2. Requests are transformed from Claude Messages API format → ChatGPT Responses API format
|
|
136
|
+
3. The request is sent to ChatGPT with proper authentication (via Codex CLI)
|
|
137
|
+
4. ChatGPT's streaming response is transformed back to Claude's format
|
|
138
|
+
5. Claude Code receives responses as if they came from Anthropic
|
|
139
|
+
|
|
140
|
+
**Supported Models:**
|
|
141
|
+
|
|
142
|
+
- `gpt-5` - GPT-5 with reasoning (supports reasoning effort levels)
|
|
143
|
+
- `gpt-5-codex` - GPT-5 optimized for coding tasks
|
|
144
|
+
- More models may be added in the future
|
|
145
|
+
|
|
146
|
+
**Dynamic Model Switching:**
|
|
147
|
+
|
|
148
|
+
You can change the LLM routing configuration for an active session without restarting using the `agent-cli router` command (see below).
|
|
149
|
+
|
|
150
|
+
#### 3. `agent-cli router` - Manage LLM Routing
|
|
151
|
+
|
|
152
|
+
Manage LLM routing configuration for active Claude sessions. This allows you to switch between different LLM models without restarting your agent.
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
# Configure routing for a session (interactive)
|
|
156
|
+
agent-cli router
|
|
157
|
+
|
|
158
|
+
# Clear all session routing configurations
|
|
159
|
+
agent-cli router --clear
|
|
160
|
+
|
|
161
|
+
# With verbose logging
|
|
162
|
+
agent-cli router --verbose
|
|
81
163
|
```
|
|
82
164
|
|
|
83
165
|
**Options:**
|
|
84
166
|
- `-v, --verbose` - Enable verbose logging
|
|
85
|
-
- `--
|
|
167
|
+
- `--clear` - Clear all session routing configurations
|
|
86
168
|
|
|
87
|
-
|
|
169
|
+
**Interactive Workflow:**
|
|
88
170
|
|
|
89
|
-
|
|
171
|
+
1. **Select a session** - The command shows all active sessions with their current routing:
|
|
172
|
+
```
|
|
173
|
+
? Select a session to configure routing:
|
|
174
|
+
❯ my-dev-session [chatgpt/gpt-5 (high)]
|
|
175
|
+
gpt5-experiment [chatgpt/gpt-5-codex (medium)]
|
|
176
|
+
claude-session [default]
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
2. **Select routing configuration** - Choose from available options:
|
|
180
|
+
```
|
|
181
|
+
? Select LLM routing configuration:
|
|
182
|
+
❯ Default (Claude)
|
|
183
|
+
GPT-5 (Reasoning: High)
|
|
184
|
+
GPT-5 (Reasoning: Medium)
|
|
185
|
+
GPT-5 (Reasoning: Low)
|
|
186
|
+
GPT-5 (Reasoning: Minimal)
|
|
187
|
+
GPT-5 Codex (Reasoning: High)
|
|
188
|
+
GPT-5 Codex (Reasoning: Medium)
|
|
189
|
+
GPT-5 Codex (Reasoning: Low)
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
3. **Configuration saved** - The routing configuration is updated in `~/.agiflow/sessions.json`
|
|
193
|
+
|
|
194
|
+
**Available Routing Options:**
|
|
195
|
+
|
|
196
|
+
- **Default (Claude)** - Remove routing, use native Claude
|
|
197
|
+
- **GPT-5 (Reasoning: High)** - GPT-5 with maximum reasoning effort (best for complex problems)
|
|
198
|
+
- **GPT-5 (Reasoning: Medium)** - GPT-5 with balanced reasoning (default)
|
|
199
|
+
- **GPT-5 (Reasoning: Low)** - GPT-5 with minimal reasoning (faster responses)
|
|
200
|
+
- **GPT-5 (Reasoning: Minimal)** - GPT-5 with no reasoning (fastest)
|
|
201
|
+
- **GPT-5 Codex** - GPT-5 optimized for coding with reasoning levels
|
|
202
|
+
|
|
203
|
+
**Reasoning Effort Levels:**
|
|
204
|
+
|
|
205
|
+
The reasoning effort parameter controls how much computational reasoning the model uses:
|
|
206
|
+
- **High** - Maximum reasoning, best for complex problems, slowest
|
|
207
|
+
- **Medium** - Balanced reasoning, good for most tasks
|
|
208
|
+
- **Low** - Light reasoning, faster responses
|
|
209
|
+
- **Minimal** - No extra reasoning, fastest responses
|
|
210
|
+
|
|
211
|
+
**Session Settings Location:**
|
|
212
|
+
|
|
213
|
+
All session routing configurations are stored in `~/.agiflow/sessions.json`:
|
|
214
|
+
|
|
215
|
+
```json
|
|
216
|
+
{
|
|
217
|
+
"session-id-1": {
|
|
218
|
+
"provider": "chatgpt",
|
|
219
|
+
"model": "gpt-5",
|
|
220
|
+
"reasoningEffort": "high",
|
|
221
|
+
"alias": "my-dev-session"
|
|
222
|
+
},
|
|
223
|
+
"session-id-2": {
|
|
224
|
+
"provider": "chatgpt",
|
|
225
|
+
"model": "gpt-5-codex",
|
|
226
|
+
"reasoningEffort": "medium",
|
|
227
|
+
"alias": "gpt5-experiment"
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
**Example Workflow:**
|
|
90
233
|
|
|
91
234
|
```bash
|
|
92
|
-
#
|
|
93
|
-
|
|
235
|
+
# 1. Start Claude with default routing
|
|
236
|
+
agent-cli claude --alias "dev-session"
|
|
237
|
+
|
|
238
|
+
# 2. Switch to GPT-5 with high reasoning (while agent is running)
|
|
239
|
+
agent-cli router
|
|
240
|
+
# Select "dev-session" → "GPT-5 (Reasoning: High)"
|
|
241
|
+
|
|
242
|
+
# 3. Switch to GPT-5 Codex with medium reasoning
|
|
243
|
+
agent-cli router
|
|
244
|
+
# Select "dev-session" → "GPT-5 Codex (Reasoning: Medium)"
|
|
245
|
+
|
|
246
|
+
# 4. Switch back to default Claude
|
|
247
|
+
agent-cli router
|
|
248
|
+
# Select "dev-session" → "Default (Claude)"
|
|
249
|
+
|
|
250
|
+
# 5. Clear all routing configurations
|
|
251
|
+
agent-cli router --clear
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
**Tips:**
|
|
255
|
+
|
|
256
|
+
- Use `--alias` when launching Claude to give your sessions meaningful names
|
|
257
|
+
- Session routing is dynamic - changes take effect immediately without restart
|
|
258
|
+
- Clear routing with `agent-cli router --clear` to reset all sessions to default Claude
|
|
259
|
+
- Reasoning effort only applies to GPT models (not Claude)
|
|
260
|
+
|
|
261
|
+
#### 4. `agent-cli logout` - Clean Up Credentials
|
|
262
|
+
Log out and clean up stored credentials.
|
|
263
|
+
|
|
264
|
+
```bash
|
|
265
|
+
# Remove credential files only
|
|
266
|
+
agent-cli logout
|
|
94
267
|
|
|
95
|
-
#
|
|
96
|
-
|
|
97
|
-
AGENT_ORGANIZATION_ID=your-org-id
|
|
268
|
+
# Remove entire .agiflow directory
|
|
269
|
+
agent-cli logout --remove-all
|
|
98
270
|
|
|
99
|
-
#
|
|
100
|
-
|
|
271
|
+
# With verbose output
|
|
272
|
+
agent-cli logout --verbose
|
|
101
273
|
```
|
|
102
274
|
|
|
275
|
+
**Options:**
|
|
276
|
+
- `-v, --verbose` - Enable verbose logging
|
|
277
|
+
- `--remove-all` - Remove entire .agiflow directory (default: remove only credential files)
|
|
278
|
+
|
|
103
279
|
### Authentication Flow
|
|
104
280
|
|
|
105
281
|
1. **Connect Command**: Uses device code authentication flow
|
|
@@ -131,20 +307,53 @@ VITE_INJECT_AGIFLOW_APP_ENDPOINT=wss://your-server.com
|
|
|
131
307
|
```
|
|
132
308
|
Error: Authentication failed
|
|
133
309
|
```
|
|
134
|
-
Solution: Run `
|
|
310
|
+
Solution: Run `agent-cli connect` first or provide valid API credentials
|
|
135
311
|
|
|
136
312
|
4. **Connection Issues**
|
|
137
313
|
- Check network connectivity
|
|
138
314
|
- Verify server URL is accessible
|
|
139
315
|
- Use `--verbose` flag for detailed logging
|
|
140
316
|
|
|
317
|
+
**LLM Routing Issues:**
|
|
318
|
+
|
|
319
|
+
1. **Codex Auth Not Found**
|
|
320
|
+
```
|
|
321
|
+
Warning: Failed to read Codex auth
|
|
322
|
+
```
|
|
323
|
+
Solutions:
|
|
324
|
+
- Install Codex CLI: `npm install -g @openai/codex`
|
|
325
|
+
- Authenticate: `codex auth login`
|
|
326
|
+
- Verify `~/.codex/auth.json` exists
|
|
327
|
+
|
|
328
|
+
2. **ChatGPT Token Expired**
|
|
329
|
+
```
|
|
330
|
+
Error: 401 Unauthorized
|
|
331
|
+
```
|
|
332
|
+
Solution: Re-authenticate with Codex: `codex auth login`
|
|
333
|
+
|
|
334
|
+
3. **Routing Not Working**
|
|
335
|
+
- Verify routing is configured via `agent-cli router` command
|
|
336
|
+
- Use `--verbose` to see routing status
|
|
337
|
+
- Check that Codex credentials are valid (`codex auth login`)
|
|
338
|
+
- Ensure network can reach ChatGPT API
|
|
339
|
+
|
|
340
|
+
4. **Session Not Found in Router**
|
|
341
|
+
If your session doesn't appear in `agent-cli router`:
|
|
342
|
+
- Restart Claude agent with `--alias` to give it a meaningful name
|
|
343
|
+
- Check `~/.agiflow/sessions.json` to see saved sessions
|
|
344
|
+
- Use `agent-cli router --clear` to reset all configurations
|
|
345
|
+
|
|
141
346
|
### Global Options
|
|
142
347
|
|
|
143
348
|
All commands support these global options:
|
|
144
349
|
- `-v, --verbose` - Enable verbose logging
|
|
145
350
|
- `--debug` - Enable debug mode
|
|
146
351
|
|
|
147
|
-
Use `
|
|
352
|
+
Use `agent-cli --help` or `agent-cli <command> --help` for detailed command information.
|
|
353
|
+
|
|
354
|
+
## Related Projects
|
|
355
|
+
|
|
356
|
+
🔗 **[AgiFlow AI Code Toolkit](https://github.com/AgiFlow/aicode-toolkit)** - An open-source collection of AI development tools and utilities for building with AI coding assistants.
|
|
148
357
|
|
|
149
358
|
## License
|
|
150
359
|
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";const As=require("node:fs"),Os=require("node:os"),Is=require("node:path"),le=require("path"),ce=require("fs-extra"),Tt=require("os");require("node:crypto");require("@inquirer/prompts");function $t(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const at=$t(As),Ns=$t(Os),xt=$t(Is);function os(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}const kt=10,Ut=(r=0)=>e=>`\x1B[${e+r}m`,qt=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,Yt=(r=0)=>(e,t,s)=>`\x1B[${38+r};2;${e};${t};${s}m`,C={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(C.modifier);const Rs=Object.keys(C.color),Cs=Object.keys(C.bgColor);[...Rs,...Cs];function js(){const r=new Map;for(const[e,t]of Object.entries(C)){for(const[s,n]of Object.entries(t))C[s]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},t[s]=C[s],r.set(n[0],n[1]);Object.defineProperty(C,e,{value:t,enumerable:!1})}return Object.defineProperty(C,"codes",{value:r,enumerable:!1}),C.color.close="\x1B[39m",C.bgColor.close="\x1B[49m",C.color.ansi=Ut(),C.color.ansi256=qt(),C.color.ansi16m=Yt(),C.bgColor.ansi=Ut(kt),C.bgColor.ansi256=qt(kt),C.bgColor.ansi16m=Yt(kt),Object.defineProperties(C,{rgbToAnsi256:{value(e,t,s){return e===t&&t===s?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(s/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[s]=t;s.length===3&&(s=[...s].map(a=>a+a).join(""));const n=Number.parseInt(s,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:e=>C.rgbToAnsi256(...C.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,s,n;if(e>=232)t=((e-232)*10+8)/255,s=t,n=t;else{e-=16;const o=e%36;t=Math.floor(e/36)/5,s=Math.floor(o/6)/5,n=o%6/5}const a=Math.max(t,s,n)*2;if(a===0)return 30;let i=30+(Math.round(n)<<2|Math.round(s)<<1|Math.round(t));return a===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,s)=>C.ansi256ToAnsi(C.rgbToAnsi256(e,t,s)),enumerable:!1},hexToAnsi:{value:e=>C.ansi256ToAnsi(C.hexToAnsi256(e)),enumerable:!1}}),C}const Q=js(),Ht=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),Kt=Ht!==0&&{level:Ht},Ls={stdout:Kt,stderr:Kt};function $s(r,e,t){let s=r.indexOf(e);if(s===-1)return r;const n=e.length;let a=0,i="";do i+=r.slice(a,s)+e+t,a=s+n,s=r.indexOf(e,a);while(s!==-1);return i+=r.slice(a),i}function zs(r,e,t,s){let n=0,a="";do{const i=r[s-1]==="\r";a+=r.slice(n,i?s-1:s)+e+(i?`\r
|
|
2
|
+
`:`
|
|
3
|
+
`)+t,n=s+1,s=r.indexOf(`
|
|
4
|
+
`,n)}while(s!==-1);return a+=r.slice(n),a}const{stdout:Wt,stderr:Jt}=Ls,Ot=Symbol("GENERATOR"),Ae=Symbol("STYLER"),$e=Symbol("IS_EMPTY"),Xt=["ansi","ansi","ansi256","ansi16m"],Oe=Object.create(null),Ms=(r,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const t=Wt?Wt.level:0;r.level=e.level===void 0?t:e.level},Ds=r=>{const e=(...t)=>t.join(" ");return Ms(e,r),Object.setPrototypeOf(e,Ke.prototype),e};function Ke(r){return Ds(r)}Object.setPrototypeOf(Ke.prototype,Function.prototype);for(const[r,e]of Object.entries(Q))Oe[r]={get(){const t=lt(this,Nt(e.open,e.close,this[Ae]),this[$e]);return Object.defineProperty(this,r,{value:t}),t}};Oe.visible={get(){const r=lt(this,this[Ae],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const It=(r,e,t,...s)=>r==="rgb"?e==="ansi16m"?Q[t].ansi16m(...s):e==="ansi256"?Q[t].ansi256(Q.rgbToAnsi256(...s)):Q[t].ansi(Q.rgbToAnsi(...s)):r==="hex"?It("rgb",e,t,...Q.hexToRgb(...s)):Q[t][r](...s),Fs=["rgb","hex","ansi256"];for(const r of Fs){Oe[r]={get(){const{level:t}=this;return function(...s){const n=Nt(It(r,Xt[t],"color",...s),Q.color.close,this[Ae]);return lt(this,n,this[$e])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);Oe[e]={get(){const{level:t}=this;return function(...s){const n=Nt(It(r,Xt[t],"bgColor",...s),Q.bgColor.close,this[Ae]);return lt(this,n,this[$e])}}}}const Gs=Object.defineProperties(()=>{},{...Oe,level:{enumerable:!0,get(){return this[Ot].level},set(r){this[Ot].level=r}}}),Nt=(r,e,t)=>{let s,n;return t===void 0?(s=r,n=e):(s=t.openAll+r,n=e+t.closeAll),{open:r,close:e,openAll:s,closeAll:n,parent:t}},lt=(r,e,t)=>{const s=(...n)=>Ps(s,n.length===1?""+n[0]:n.join(" "));return Object.setPrototypeOf(s,Gs),s[Ot]=r,s[Ae]=e,s[$e]=t,s},Ps=(r,e)=>{if(r.level<=0||!e)return r[$e]?"":e;let t=r[Ae];if(t===void 0)return e;const{openAll:s,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=$s(e,t.close,t.open),t=t.parent;const a=e.indexOf(`
|
|
5
|
+
`);return a!==-1&&(e=zs(e,n,s,a)),s+e+n};Object.defineProperties(Ke.prototype,Oe);const z=Ke();Ke({level:Jt?Jt.level:0});var x;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},r.getValidEnumValues=n=>{const a=r.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(const i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(x||(x={}));var Rt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Rt||(Rt={}));const h=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=r=>{switch(typeof r){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(r)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(r)?h.array:r===null?h.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?h.promise:typeof Map<"u"&&r instanceof Map?h.map:typeof Set<"u"&&r instanceof Set?h.set:typeof Date<"u"&&r instanceof Date?h.date:h.object;default:return h.unknown}},l=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Vs=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class q extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let o=s,d=0;for(;d<i.path.length;){const u=i.path[d];d===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(i))):o[u]=o[u]||{_errors:[]},o=o[u],d++}}};return n(this),s}static assert(e){if(!(e instanceof q))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const n of this.issues)if(n.path.length>0){const a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}q.create=r=>new q(r);const Ie=(r,e)=>{let t;switch(r.code){case l.invalid_type:r.received===h.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case l.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case l.invalid_union:t="Invalid input";break;case l.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case l.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case l.invalid_arguments:t="Invalid function arguments";break;case l.invalid_return_type:t="Invalid function return type";break;case l.invalid_date:t="Invalid date";break;case l.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case l.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case l.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case l.custom:t="Invalid input";break;case l.invalid_intersection_types:t="Intersection results could not be merged";break;case l.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case l.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}};let cs=Ie;function Zs(r){cs=r}function ut(){return cs}const dt=r=>{const{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const d=s.filter(u=>!!u).slice().reverse();for(const u of d)o=u(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},Bs=[];function f(r,e){const t=ut(),s=dt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ie?void 0:Ie].filter(n=>!!n)});r.common.issues.push(s)}class V{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const n of t){if(n.status==="aborted")return _;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const n of t){const a=await n.key,i=await n.value;s.push({key:a,value:i})}return V.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return _;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value)}return{status:e.value,value:s}}}const _=Object.freeze({status:"aborted"}),ke=r=>({status:"dirty",value:r}),B=r=>({status:"valid",value:r}),Ct=r=>r.status==="aborted",jt=r=>r.status==="dirty",_e=r=>r.status==="valid",ze=r=>typeof Promise<"u"&&r instanceof Promise;var m;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));class se{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Qt=(r,e)=>{if(_e(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new q(r.common.issues);return this._error=t,this._error}}};function w(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{const{message:d}=r;return i.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:d??s??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:d??t??o.defaultError}},description:n}}class E{get description(){return this._def.description}_getType(e){return ie(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new V,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ze(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},n=this._parseSync({data:e,path:s.path,parent:s});return Qt(s,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return _e(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>_e(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(ze(n)?n:Promise.resolve(n));return Qt(s,a)}refine(e,t){const s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:l.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(d=>d?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new X({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ee.create(this,this._def)}nullable(){return he.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return J.create(this)}promise(){return Re.create(this,this._def)}or(e){return Ge.create([this,e],this._def)}and(e){return Pe.create(this,e,this._def)}transform(e){return new X({...w(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new qe({...w(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new zt({typeName:v.ZodBranded,type:this,...w(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ye({...w(this._def),innerType:this,catchValue:t,typeName:v.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return We.create(this,e)}readonly(){return He.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Us=/^c[^\s-]{8,}$/i,qs=/^[0-9a-z]+$/,Ys=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Hs=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ks=/^[a-z0-9_-]{21}$/i,Ws=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Js=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Xs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Qs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let St;const er=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,tr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,sr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,rr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ar=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ls="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ir=new RegExp(`^${ls}$`);function us(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function or(r){return new RegExp(`^${us(r)}$`)}function ds(r){let e=`${ls}T${us(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function cr(r,e){return!!((e==="v4"||!e)&&er.test(r)||(e==="v6"||!e)&&sr.test(r))}function lr(r,e){if(!Ws.test(r))return!1;try{const[t]=r.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function ur(r,e){return!!((e==="v4"||!e)&&tr.test(r)||(e==="v6"||!e)&&rr.test(r))}class W extends E{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:h.string,received:a.parsedType}),_}const s=new V;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?f(n,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&f(n,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if(a.kind==="email")Xs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"email",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")St||(St=new RegExp(Qs,"u")),St.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"emoji",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")Hs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"uuid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")Ks.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"nanoid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")Us.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")qs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid2",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")Ys.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ulid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),f(n,{validation:"url",code:l.invalid_string,message:a.message}),s.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"regex",code:l.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?ds(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?ir.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?or(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?Js.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?cr(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ip",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?lr(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"jwt",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?ur(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cidr",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?nr.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?ar.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64url",code:l.invalid_string,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:l.invalid_string,...m.errToObj(s)})}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new W({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new W({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new W({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}W.create=r=>new W({checks:[],typeName:v.ZodString,coerce:r?.coerce??!1,...w(r)});function dr(r,e){const t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=Number.parseInt(r.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}class ue extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:h.number,received:a.parsedType}),_}let s;const n=new V;for(const a of this._def.checks)a.kind==="int"?x.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?dr(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.not_finite,message:a.message}),n.dirty()):x.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,s,n){return new ue({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ue.create=r=>new ue({checks:[],typeName:v.ZodNumber,coerce:r?.coerce||!1,...w(r)});class de extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==h.bigint)return this._getInvalidInput(e);let s;const n=new V;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):x.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:h.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,s,n){return new de({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}de.create=r=>new de({checks:[],typeName:v.ZodBigInt,coerce:r?.coerce??!1,...w(r)});class Me extends E{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.boolean,received:s.parsedType}),_}return B(e.data)}}Me.create=r=>new Me({typeName:v.ZodBoolean,coerce:r?.coerce||!1,...w(r)});class ve extends E{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:h.date,received:a.parsedType}),_}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_date}),_}const s=new V;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):x.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ve({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ve.create=r=>new ve({checks:[],coerce:r?.coerce||!1,typeName:v.ZodDate,...w(r)});class ft extends E{_parse(e){if(this._getType(e)!==h.symbol){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.symbol,received:s.parsedType}),_}return B(e.data)}}ft.create=r=>new ft({typeName:v.ZodSymbol,...w(r)});class De extends E{_parse(e){if(this._getType(e)!==h.undefined){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.undefined,received:s.parsedType}),_}return B(e.data)}}De.create=r=>new De({typeName:v.ZodUndefined,...w(r)});class Fe extends E{_parse(e){if(this._getType(e)!==h.null){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.null,received:s.parsedType}),_}return B(e.data)}}Fe.create=r=>new Fe({typeName:v.ZodNull,...w(r)});class Ne extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return B(e.data)}}Ne.create=r=>new Ne({typeName:v.ZodAny,...w(r)});class ye extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return B(e.data)}}ye.create=r=>new ye({typeName:v.ZodUnknown,...w(r)});class oe extends E{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:h.never,received:t.parsedType}),_}}oe.create=r=>new oe({typeName:v.ZodNever,...w(r)});class ht extends E{_parse(e){if(this._getType(e)!==h.undefined){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.void,received:s.parsedType}),_}return B(e.data)}}ht.create=r=>new ht({typeName:v.ZodVoid,...w(r)});class J extends E{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==h.array)return f(t,{code:l.invalid_type,expected:h.array,received:t.parsedType}),_;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(f(t,{code:i?l.too_big:l.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(f(t,{code:l.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(f(t,{code:l.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new se(t,i,t.path,o)))).then(i=>V.mergeArray(s,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new se(t,i,t.path,o)));return V.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new J({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new J({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new J({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}}J.create=(r,e)=>new J({type:r,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...w(e)});function xe(r){if(r instanceof L){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=ee.create(xe(s))}return new L({...r._def,shape:()=>e})}else return r instanceof J?new J({...r._def,type:xe(r.element)}):r instanceof ee?ee.create(xe(r.unwrap())):r instanceof he?he.create(xe(r.unwrap())):r instanceof re?re.create(r.items.map(e=>xe(e))):r}class L extends E{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){const u=this._getOrReturnCtx(e);return f(u,{code:l.invalid_type,expected:h.object,received:u.parsedType}),_}const{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof oe&&this._def.unknownKeys==="strip"))for(const u in n.data)i.includes(u)||o.push(u);const d=[];for(const u of i){const g=a[u],T=n.data[u];d.push({key:{status:"valid",value:u},value:g._parse(new se(n,T,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof oe){const u=this._def.unknownKeys;if(u==="passthrough")for(const g of o)d.push({key:{status:"valid",value:g},value:{status:"valid",value:n.data[g]}});else if(u==="strict")o.length>0&&(f(n,{code:l.unrecognized_keys,keys:o}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const g of o){const T=n.data[g];d.push({key:{status:"valid",value:g},value:u._parse(new se(n,T,n.path,g)),alwaysSet:g in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const u=[];for(const g of d){const T=await g.key,j=await g.value;u.push({key:T,value:j,alwaysSet:g.alwaysSet})}return u}).then(u=>V.mergeObjectSync(s,u)):V.mergeObjectSync(s,d)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new L({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const n=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new L({...this._def,unknownKeys:"strip"})}passthrough(){return new L({...this._def,unknownKeys:"passthrough"})}extend(e){return new L({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new L({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new L({...this._def,catchall:e})}pick(e){const t={};for(const s of x.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new L({...this._def,shape:()=>t})}omit(e){const t={};for(const s of x.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new L({...this._def,shape:()=>t})}deepPartial(){return xe(this)}partial(e){const t={};for(const s of x.objectKeys(this.shape)){const n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}return new L({...this._def,shape:()=>t})}required(e){const t={};for(const s of x.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof ee;)a=a._def.innerType;t[s]=a}return new L({...this._def,shape:()=>t})}keyof(){return fs(x.objectKeys(this.shape))}}L.create=(r,e)=>new L({shape:()=>r,unknownKeys:"strip",catchall:oe.create(),typeName:v.ZodObject,...w(e)});L.strictCreate=(r,e)=>new L({shape:()=>r,unknownKeys:"strict",catchall:oe.create(),typeName:v.ZodObject,...w(e)});L.lazycreate=(r,e)=>new L({shape:r,unknownKeys:"strip",catchall:oe.create(),typeName:v.ZodObject,...w(e)});class Ge extends E{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new q(o.ctx.common.issues));return f(t,{code:l.invalid_union,unionErrors:i}),_}if(t.common.async)return Promise.all(s.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const d of s){const u={...t,common:{...t.common,issues:[]},parent:null},g=d._parseSync({data:t.data,path:t.path,parent:u});if(g.status==="valid")return g;g.status==="dirty"&&!a&&(a={result:g,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(d=>new q(d));return f(t,{code:l.invalid_union,unionErrors:o}),_}}get options(){return this._def.options}}Ge.create=(r,e)=>new Ge({options:r,typeName:v.ZodUnion,...w(e)});const ae=r=>r instanceof Ze?ae(r.schema):r instanceof X?ae(r.innerType()):r instanceof Be?[r.value]:r instanceof fe?r.options:r instanceof Ue?x.objectValues(r.enum):r instanceof qe?ae(r._def.innerType):r instanceof De?[void 0]:r instanceof Fe?[null]:r instanceof ee?[void 0,...ae(r.unwrap())]:r instanceof he?[null,...ae(r.unwrap())]:r instanceof zt||r instanceof He?ae(r.unwrap()):r instanceof Ye?ae(r._def.innerType):[];class gt extends E{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.object)return f(t,{code:l.invalid_type,expected:h.object,received:t.parsedType}),_;const s=this.discriminator,n=t.data[s],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),_)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const n=new Map;for(const a of t){const i=ae(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a)}}return new gt({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...w(s)})}}function Lt(r,e){const t=ie(r),s=ie(e);if(r===e)return{valid:!0,data:r};if(t===h.object&&s===h.object){const n=x.objectKeys(e),a=x.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(const o of a){const d=Lt(r[o],e[o]);if(!d.valid)return{valid:!1};i[o]=d.data}return{valid:!0,data:i}}else if(t===h.array&&s===h.array){if(r.length!==e.length)return{valid:!1};const n=[];for(let a=0;a<r.length;a++){const i=r[a],o=e[a],d=Lt(i,o);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return t===h.date&&s===h.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class Pe extends E{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(Ct(a)||Ct(i))return _;const o=Lt(a.value,i.value);return o.valid?((jt(a)||jt(i))&&t.dirty(),{status:t.value,value:o.data}):(f(s,{code:l.invalid_intersection_types}),_)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Pe.create=(r,e,t)=>new Pe({left:r,right:e,typeName:v.ZodIntersection,...w(t)});class re extends E{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.array)return f(s,{code:l.invalid_type,expected:h.array,received:s.parsedType}),_;if(s.data.length<this._def.items.length)return f(s,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_;!this._def.rest&&s.data.length>this._def.items.length&&(f(s,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map((i,o)=>{const d=this._def.items[o]||this._def.rest;return d?d._parse(new se(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>V.mergeArray(t,i)):V.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new re({...this._def,rest:e})}}re.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new re({items:r,typeName:v.ZodTuple,rest:null,...w(e)})};class Ve extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.object)return f(s,{code:l.invalid_type,expected:h.object,received:s.parsedType}),_;const n=[],a=this._def.keyType,i=this._def.valueType;for(const o in s.data)n.push({key:a._parse(new se(s,o,s.path,o)),value:i._parse(new se(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?V.mergeObjectAsync(t,n):V.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof E?new Ve({keyType:e,valueType:t,typeName:v.ZodRecord,...w(s)}):new Ve({keyType:W.create(),valueType:e,typeName:v.ZodRecord,...w(t)})}}class pt extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.map)return f(s,{code:l.invalid_type,expected:h.map,received:s.parsedType}),_;const n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([o,d],u)=>({key:n._parse(new se(s,o,s.path,[u,"key"])),value:a._parse(new se(s,d,s.path,[u,"value"]))}));if(s.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const d of i){const u=await d.key,g=await d.value;if(u.status==="aborted"||g.status==="aborted")return _;(u.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(u.value,g.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const d of i){const u=d.key,g=d.value;if(u.status==="aborted"||g.status==="aborted")return _;(u.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(u.value,g.value)}return{status:t.value,value:o}}}}pt.create=(r,e,t)=>new pt({valueType:e,keyType:r,typeName:v.ZodMap,...w(t)});class be extends E{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.set)return f(s,{code:l.invalid_type,expected:h.set,received:s.parsedType}),_;const n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(f(s,{code:l.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(f(s,{code:l.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(d){const u=new Set;for(const g of d){if(g.status==="aborted")return _;g.status==="dirty"&&t.dirty(),u.add(g.value)}return{status:t.value,value:u}}const o=[...s.data.values()].map((d,u)=>a._parse(new se(s,d,s.path,u)));return s.common.async?Promise.all(o).then(d=>i(d)):i(o)}min(e,t){return new be({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new be({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}be.create=(r,e)=>new be({valueType:r,minSize:null,maxSize:null,typeName:v.ZodSet,...w(e)});class Se extends E{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.function)return f(t,{code:l.invalid_type,expected:h.function,received:t.parsedType}),_;function s(o,d){return dt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ut(),Ie].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:d}})}function n(o,d){return dt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ut(),Ie].filter(u=>!!u),issueData:{code:l.invalid_return_type,returnTypeError:d}})}const a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Re){const o=this;return B(async function(...d){const u=new q([]),g=await o._def.args.parseAsync(d,a).catch(S=>{throw u.addIssue(s(d,S)),u}),T=await Reflect.apply(i,this,g);return await o._def.returns._def.type.parseAsync(T,a).catch(S=>{throw u.addIssue(n(T,S)),u})})}else{const o=this;return B(function(...d){const u=o._def.args.safeParse(d,a);if(!u.success)throw new q([s(d,u.error)]);const g=Reflect.apply(i,this,u.data),T=o._def.returns.safeParse(g,a);if(!T.success)throw new q([n(g,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Se({...this._def,args:re.create(e).rest(ye.create())})}returns(e){return new Se({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new Se({args:e||re.create([]).rest(ye.create()),returns:t||ye.create(),typeName:v.ZodFunction,...w(s)})}}class Ze extends E{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ze.create=(r,e)=>new Ze({getter:r,typeName:v.ZodLazy,...w(e)});class Be extends E{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:l.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}}Be.create=(r,e)=>new Be({value:r,typeName:v.ZodLiteral,...w(e)});function fs(r,e){return new fe({values:r,typeName:v.ZodEnum,...w(e)})}class fe extends E{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return f(t,{expected:x.joinValues(s),received:t.parsedType,code:l.invalid_type}),_}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return f(t,{received:t.data,code:l.invalid_enum_value,options:s}),_}return B(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return fe.create(e,{...this._def,...t})}exclude(e,t=this._def){return fe.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}fe.create=fs;class Ue extends E{_parse(e){const t=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==h.string&&s.parsedType!==h.number){const n=x.objectValues(t);return f(s,{expected:x.joinValues(n),received:s.parsedType,code:l.invalid_type}),_}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=x.objectValues(t);return f(s,{received:s.data,code:l.invalid_enum_value,options:n}),_}return B(e.data)}get enum(){return this._def.values}}Ue.create=(r,e)=>new Ue({values:r,typeName:v.ZodNativeEnum,...w(e)});class Re extends E{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return f(t,{code:l.invalid_type,expected:h.promise,received:t.parsedType}),_;const s=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return B(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Re.create=(r,e)=>new Re({type:r,typeName:v.ZodPromise,...w(e)});class X extends E{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{f(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return _;const d=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return d.status==="aborted"?_:d.status==="dirty"||t.value==="dirty"?ke(d.value):d});{if(t.value==="aborted")return _;const o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?_:o.status==="dirty"||t.value==="dirty"?ke(o.value):o}}if(n.type==="refinement"){const i=o=>{const d=n.refinement(o,a);if(s.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!_e(i))return _;const o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>_e(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):_);x.assertNever(n)}}X.create=(r,e,t)=>new X({schema:r,typeName:v.ZodEffects,effect:e,...w(t)});X.createWithPreprocess=(r,e,t)=>new X({schema:e,effect:{type:"preprocess",transform:r},typeName:v.ZodEffects,...w(t)});class ee extends E{_parse(e){return this._getType(e)===h.undefined?B(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ee.create=(r,e)=>new ee({innerType:r,typeName:v.ZodOptional,...w(e)});class he extends E{_parse(e){return this._getType(e)===h.null?B(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}he.create=(r,e)=>new he({innerType:r,typeName:v.ZodNullable,...w(e)});class qe extends E{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===h.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}qe.create=(r,e)=>new qe({innerType:r,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});class Ye extends E{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return ze(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new q(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new q(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ye.create=(r,e)=>new Ye({innerType:r,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});class mt extends E{_parse(e){if(this._getType(e)!==h.nan){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.nan,received:s.parsedType}),_}return{status:"valid",value:e.data}}}mt.create=r=>new mt({typeName:v.ZodNaN,...w(r)});const fr=Symbol("zod_brand");class zt extends E{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class We extends E{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?_:a.status==="dirty"?(t.dirty(),ke(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?_:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new We({in:e,out:t,typeName:v.ZodPipeline})}}class He extends E{_parse(e){const t=this._def.innerType._parse(e),s=n=>(_e(n)&&(n.value=Object.freeze(n.value)),n);return ze(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}}He.create=(r,e)=>new He({innerType:r,typeName:v.ZodReadonly,...w(e)});function es(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function hs(r,e={},t){return r?Ne.create().superRefine((s,n)=>{const a=r(s);if(a instanceof Promise)return a.then(i=>{if(!i){const o=es(e,s),d=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:d})}});if(!a){const i=es(e,s),o=i.fatal??t??!0;n.addIssue({code:"custom",...i,fatal:o})}}):Ne.create()}const hr={object:L.lazycreate};var v;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(v||(v={}));const pr=(r,e={message:`Input not instance of ${r.name}`})=>hs(t=>t instanceof r,e),I=W.create,te=ue.create,mr=mt.create,gr=de.create,Je=Me.create,yr=ve.create,_r=ft.create,vr=De.create,ps=Fe.create,pe=Ne.create,yt=ye.create,br=oe.create,wr=ht.create,we=J.create,N=L.create,Er=L.strictCreate,Ee=Ge.create,Tr=gt.create,xr=Pe.create,kr=re.create,Xe=Ve.create,Sr=pt.create,Ar=be.create,Or=Se.create,ms=Ze.create,Z=Be.create,_t=fe.create,Ir=Ue.create,Nr=Re.create,ts=X.create,Rr=ee.create,Cr=he.create,jr=X.createWithPreprocess,Lr=We.create,$r=()=>I().optional(),zr=()=>te().optional(),Mr=()=>Je().optional(),ct={string:r=>W.create({...r,coerce:!0}),number:r=>ue.create({...r,coerce:!0}),boolean:r=>Me.create({...r,coerce:!0}),bigint:r=>de.create({...r,coerce:!0}),date:r=>ve.create({...r,coerce:!0})},Dr=_,F=Object.freeze(Object.defineProperty({__proto__:null,BRAND:fr,DIRTY:ke,EMPTY_PATH:Bs,INVALID:_,NEVER:Dr,OK:B,ParseStatus:V,Schema:E,ZodAny:Ne,ZodArray:J,ZodBigInt:de,ZodBoolean:Me,ZodBranded:zt,ZodCatch:Ye,ZodDate:ve,ZodDefault:qe,ZodDiscriminatedUnion:gt,ZodEffects:X,ZodEnum:fe,ZodError:q,get ZodFirstPartyTypeKind(){return v},ZodFunction:Se,ZodIntersection:Pe,ZodIssueCode:l,ZodLazy:Ze,ZodLiteral:Be,ZodMap:pt,ZodNaN:mt,ZodNativeEnum:Ue,ZodNever:oe,ZodNull:Fe,ZodNullable:he,ZodNumber:ue,ZodObject:L,ZodOptional:ee,ZodParsedType:h,ZodPipeline:We,ZodPromise:Re,ZodReadonly:He,ZodRecord:Ve,ZodSchema:E,ZodSet:be,ZodString:W,ZodSymbol:ft,ZodTransformer:X,ZodTuple:re,ZodType:E,ZodUndefined:De,ZodUnion:Ge,ZodUnknown:ye,ZodVoid:ht,addIssueToContext:f,any:pe,array:we,bigint:gr,boolean:Je,coerce:ct,custom:hs,date:yr,datetimeRegex:ds,defaultErrorMap:Ie,discriminatedUnion:Tr,effect:ts,enum:_t,function:Or,getErrorMap:ut,getParsedType:ie,instanceof:pr,intersection:xr,isAborted:Ct,isAsync:ze,isDirty:jt,isValid:_e,late:hr,lazy:ms,literal:Z,makeIssue:dt,map:Sr,nan:mr,nativeEnum:Ir,never:br,null:ps,nullable:Cr,number:te,object:N,get objectUtil(){return Rt},oboolean:Mr,onumber:zr,optional:Rr,ostring:$r,pipeline:Lr,preprocess:jr,promise:Nr,quotelessJson:Vs,record:Xe,set:Ar,setErrorMap:Zs,strictObject:Er,string:I,symbol:_r,transformer:ts,tuple:kr,undefined:vr,union:Ee,unknown:yt,get util(){return x},void:wr},Symbol.toStringTag,{value:"Module"})),Fr={AGENT_SERVER_URL:"AGENT_SERVER_URL",AGENT_API_KEY:"AGENT_API_KEY",AGENT_ORGANIZATION_ID:"AGENT_ORGANIZATION_ID",AGENT_SESSION_ID:"AGENT_SESSION_ID",AGENT_TYPE:"AGENT_TYPE",AGENT_CONTAINER_MODE:"AGENT_CONTAINER_MODE",AGENT_DEVICE_GUID:"AGENT_DEVICE_GUID",CONTEXT_DATA:"CONTEXT_DATA",NODE_ENV:"NODE_ENV",DEBUG:"DEBUG",VERBOSE:"VERBOSE",LOG_LEVEL:"LOG_LEVEL",AGI_NETLOG_ENABLE:"AGI_NETLOG_ENABLE",AGI_NETLOG_DEBUG:"AGI_NETLOG_DEBUG",AGI_NETLOG_MAX_BODY:"AGI_NETLOG_MAX_BODY",AGI_NETLOG_FILE:"AGI_NETLOG_FILE",AGI_NETLOG_REMOTE_ENABLE:"AGI_NETLOG_REMOTE_ENABLE",AGI_NETLOG_REMOTE_FILE:"AGI_NETLOG_REMOTE_FILE",HOSTNAME:"HOSTNAME",VITE_SAVE_RAW:"VITE_SAVE_RAW"},ge=()=>F.preprocess(r=>{if(typeof r=="boolean")return r;if(typeof r=="number")return r===1;if(typeof r=="string"){const e=r.trim().toLowerCase();if(["1","true","yes","y","on"].includes(e))return!0;if(["0","false","no","n","off"].includes(e))return!1}},F.boolean()),Gr=()=>F.preprocess(r=>{if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){const e=Number(r);if(Number.isFinite(e))return e}},F.number()),gs=F.object({NODE_ENV:F.enum(["development","production","test"]).default("production"),AGENT_CONTAINER_MODE:ge().default(!1),AGENT_API_KEY:F.string().optional(),AGENT_ORGANIZATION_ID:F.string().optional(),AGENT_SESSION_ID:F.string().optional(),AGENT_SERVER_URL:F.string().optional(),AGENT_TYPE:F.string().optional(),AGENT_DEVICE_GUID:F.string().optional(),CONTEXT_DATA:F.string().optional(),AGI_NETLOG_ENABLE:ge().default(!0),AGI_NETLOG_DEBUG:ge().optional(),AGI_NETLOG_FILE:F.string().optional(),AGI_NETLOG_MAX_BODY:Gr().optional(),AGI_NETLOG_REMOTE_ENABLE:ge().default(!0),AGI_NETLOG_REMOTE_FILE:F.string().optional(),DEBUG:ge().default(!1),VERBOSE:ge().default(!1),LOG_LEVEL:F.string().optional(),HOSTNAME:F.string().optional(),VITE_SAVE_RAW:ge().default(!1)});function it(r=!1){return r?"https://agiflow.io":"https://agiflow.io"}let R=gs.parse(process.env);class vt{static refresh(){R=gs.parse(process.env)}static get isContainerMode(){return!!R.AGENT_CONTAINER_MODE}static get apiKey(){return R.AGENT_API_KEY||process.env.AGENT_API_KEY}static get organizationId(){return R.AGENT_ORGANIZATION_ID||process.env.AGENT_ORGANIZATION_ID}static get sessionId(){return R.AGENT_SESSION_ID||process.env.AGENT_SESSION_ID}static get serverUrl(){return R.AGENT_SERVER_URL||process.env.AGENT_SERVER_URL||it(this.isContainerMode)}static get isNetlogEnabled(){return!!R.AGI_NETLOG_ENABLE}static get isNetlogDebug(){return!!R.AGI_NETLOG_DEBUG}static get isNetlogRemoteEnabled(){return!!R.AGI_NETLOG_REMOTE_ENABLE}static get isDebugMode(){return R.DEBUG}static get isVerbose(){return R.VERBOSE}static get logLevel(){return R.LOG_LEVEL??(R.DEBUG?"debug":"info")}static get nodeEnv(){return R.NODE_ENV}static get homeDir(){return process.env.HOME||process.env.USERPROFILE}static get isMacOS(){return process.platform==="darwin"}static get hostname(){return R.HOSTNAME}static get netlogMaxBody(){return R.AGI_NETLOG_MAX_BODY}static get netlogFile(){return R.AGI_NETLOG_FILE}static get netlogRemoteFile(){return R.AGI_NETLOG_REMOTE_FILE}static get agentType(){return R.AGENT_TYPE||process.env.AGENT_TYPE}static get deviceGuid(){return R.AGENT_DEVICE_GUID}static get isSaveRawEnabled(){return!!R.VITE_SAVE_RAW}static get contextData(){return R.CONTEXT_DATA||process.env.CONTEXT_DATA}static serializeEnv(){const e={...process.env};for(const[t,s]of Object.entries(R))s!==void 0&&(typeof s=="string"?e[t]=s:typeof s=="number"?e[t]=String(s):typeof s=="boolean"?e[t]=s?"true":"false":e[t]=String(s));return e}static toChildProcess(){const e=this.serializeEnv();return e.AGENT_SERVER_URL||(e.AGENT_SERVER_URL=it(this.isContainerMode)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static toDocker(){const e=this.serializeEnv();return e.AGENT_CONTAINER_MODE="true",e.AGENT_SERVER_URL||(e.AGENT_SERVER_URL=it(!0)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static toPty(){const e=this.serializeEnv();return e.AGENT_SERVER_URL||(e.AGENT_SERVER_URL=it(this.isContainerMode)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static getEnvs(){return R}}const ss=ms(()=>Ee([ps(),I(),te(),Je(),we(ss),Xe(ss)])),rs=N({toolCallId:I(),toolName:I(),args:pe()}),Pr=N({toolCallId:I(),toolName:I(),args:pe(),result:pe()}),Vr=Ee([rs.extend({state:Z("partial-call"),step:te().optional()}),rs.extend({state:Z("call"),step:te().optional()}),Pr.extend({state:Z("result"),step:te().optional()})]),Zr=N({type:I(),content:I()}),Br=N({type:Z("text"),text:I()}),Ur=N({type:Z("reasoning"),reasoning:I(),details:we(Ee([N({type:Z("text"),text:I(),signature:I().optional()}),N({type:Z("redacted"),data:I()})])).optional()}),qr=N({name:Z("select"),props:N({options:we(N({label:I(),value:Ee([I(),te()]),selected:Je().optional()}))})}),Yr=N({name:Z("placeholder"),props:N({})}),Hr=Ee([qr,Yr]),Kr=N({completed:Je(),component:Hr}),Wr=N({type:Z("tool-invocation"),toolInvocation:Vr,input:Kr.optional(),jsx:I({description:"UI rendering"}).optional()}),Jr=N({type:Z("source"),source:Zr}),Xr=N({type:Z("file"),mimeType:I(),data:I()}),Qr=N({type:Z("error"),text:I(),error:pe().optional()}),en=N({type:Z("step-start")}),ys=Ee([Br,Ur,Wr,Jr,Xr,Qr,en]),Mt=_t(["input","output","error","system"]),_s=N({messageType:Mt,parts:we(ys),metadata:Xe(I(),yt()).optional(),raw:pe().optional()});N({id:I(),sessionId:I(),agentTypeId:I(),messageType:Mt,contentSize:te().nullable(),timestamp:ct.date(),metadata:I().nullable(),raw:pe().nullable().optional(),createdAt:ct.date(),updatedAt:ct.date()});const tn=N({messageType:_t(["output"]).default("output"),metadata:Xe(I(),yt()).optional()});N({id:I(),messageId:I()});const sn=N({parts:we(ys).optional(),metadata:Xe(I(),yt()).optional(),raw:pe().optional()});N({messages:we(_s)});function rn(r){return[vs(r)]}function ns(r){let e=r.parts;if(!e&&r.content&&(e=rn(r.content)),!e)throw new Error("Either content or parts is required for message creation");return{messageType:r.messageType,parts:e,metadata:r.metadata,raw:r.raw}}function vs(r){return{type:"text",text:r}}function nn(r){return{name:"select",props:{options:r}}}function an(r,e){return{completed:r,component:e}}function on(r,e,t){return{type:"tool-invocation",toolInvocation:r,input:e,jsx:t}}class M{static AGIFLOW_DIR=le.join(Tt.homedir(),".agiflow");static async ensureDir(e){await ce.ensureDir(e)}static async exists(e){try{return await ce.access(e),!0}catch{return!1}}static async readJson(e){const t=await ce.readFile(e,"utf-8");return JSON.parse(t)}static async writeJson(e,t,s){await ce.ensureDir(le.dirname(e));const n=JSON.stringify(t,null,s?.spaces??2);await ce.writeFile(e,n,"utf-8")}static async copy(e,t){await ce.copy(e,t)}static async remove(e){await ce.remove(e)}static getCurrentDirectory(){return process.cwd()}static resolvePath(...e){return le.resolve(process.cwd(),...e)}static async getFiles(e,t){const s=await ce.readdir(e);return t?s.filter(n=>t.test(n)):s}static getAbsolutePath(e){return e?e.startsWith("~/")?le.join(Tt.homedir(),e.slice(2)):e==="~"?Tt.homedir():le.isAbsolute(e)?e:le.resolve(process.cwd(),e):process.cwd()}}var Le={exports:{}},At,as;function cn(){if(as)return At;as=1;function r(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}At=e;function e(t,s,n){var a=n&&n.stringify||r,i=1;if(typeof t=="object"&&t!==null){var o=s.length+i;if(o===1)return t;var d=new Array(o);d[0]=a(t);for(var u=1;u<o;u++)d[u]=a(s[u]);return d.join(" ")}if(typeof t!="string")return t;var g=s.length;if(g===0)return t;for(var T="",j=1-i,S=-1,H=t&&t.length||0,A=0;A<H;){if(t.charCodeAt(A)===37&&A+1<H){switch(S=S>-1?S:0,t.charCodeAt(A+1)){case 100:case 102:if(j>=g||s[j]==null)break;S<A&&(T+=t.slice(S,A)),T+=Number(s[j]),S=A+2,A++;break;case 105:if(j>=g||s[j]==null)break;S<A&&(T+=t.slice(S,A)),T+=Math.floor(Number(s[j])),S=A+2,A++;break;case 79:case 111:case 106:if(j>=g||s[j]===void 0)break;S<A&&(T+=t.slice(S,A));var Qe=typeof s[j];if(Qe==="string"){T+="'"+s[j]+"'",S=A+2,A++;break}if(Qe==="function"){T+=s[j].name||"<anonymous>",S=A+2,A++;break}T+=a(s[j]),S=A+2,A++;break;case 115:if(j>=g)break;S<A&&(T+=t.slice(S,A)),T+=String(s[j]),S=A+2,A++;break;case 37:S<A&&(T+=t.slice(S,A)),T+="%",S=A+2,A++,j--;break}++j}++A}return S===-1?t:(S<H&&(T+=t.slice(S)),T)}return At}var is;function ln(){if(is)return Le.exports;is=1;const r=cn();Le.exports=g;const e=Ss().console||{},t={mapHttpRequest:et,mapHttpResponse:et,wrapRequestSerializer:Et,wrapResponseSerializer:Et,wrapErrorSerializer:Et,req:et,res:et,err:Dt,errWithCause:Dt};function s(c,p){return c==="silent"?1/0:p.levels.values[c]}const n=Symbol("pino.logFuncs"),a=Symbol("pino.hierarchy"),i={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function o(c,p){const b={logger:p,parent:c[a]};p[a]=b}function d(c,p,b){const k={};p.forEach(O=>{k[O]=b[O]?b[O]:e[O]||e[i[O]||"log"]||Te}),c[n]=k}function u(c,p){return Array.isArray(c)?c.filter(function(k){return k!=="!stdSerializers.err"}):c===!0?Object.keys(p):!1}function g(c){c=c||{},c.browser=c.browser||{};const p=c.browser.transmit;if(p&&typeof p.send!="function")throw Error("pino: transmit option must have a send function");const b=c.browser.write||e;c.browser.write&&(c.browser.asObject=!0);const k=c.serializers||{},O=u(c.browser.serialize,k);let P=c.browser.serialize;Array.isArray(c.browser.serialize)&&c.browser.serialize.indexOf("!stdSerializers.err")>-1&&(P=!1);const Y=Object.keys(c.customLevels||{}),$=["error","fatal","warn","info","debug","trace"].concat(Y);typeof b=="function"&&$.forEach(function(K){b[K]=b}),(c.enabled===!1||c.browser.disabled)&&(c.level="silent");const U=c.level||"info",y=Object.create(b);y.log||(y.log=Te),d(y,$,b),o({},y),Object.defineProperty(y,"levelVal",{get:tt}),Object.defineProperty(y,"level",{get:me,set:st});const G={transmit:p,serialize:O,asObject:c.browser.asObject,formatters:c.browser.formatters,levels:$,timestamp:Ts(c),messageKey:c.messageKey||"msg",onChild:c.onChild||Te};y.levels=T(c),y.level=U,y.setMaxListeners=y.getMaxListeners=y.emit=y.addListener=y.on=y.prependListener=y.once=y.prependOnceListener=y.removeListener=y.removeAllListeners=y.listeners=y.listenerCount=y.eventNames=y.write=y.flush=Te,y.serializers=k,y._serialize=O,y._stdErrSerialize=P,y.child=function(...K){return Pt.call(this,G,...K)},p&&(y._logEvent=wt());function tt(){return s(this.level,this)}function me(){return this._level}function st(K){if(K!=="silent"&&!this.levels.values[K])throw Error("unknown level "+K);this._level=K,H(this,G,y,"error"),H(this,G,y,"fatal"),H(this,G,y,"warn"),H(this,G,y,"info"),H(this,G,y,"debug"),H(this,G,y,"trace"),Y.forEach(ne=>{H(this,G,y,ne)})}function Pt(K,ne,Ce){if(!ne)throw new Error("missing bindings for child Pino");Ce=Ce||{},O&&ne.serializers&&(Ce.serializers=ne.serializers);const Vt=Ce.serializers;if(O&&Vt){var rt=Object.assign({},k,Vt),Zt=c.browser.serialize===!0?Object.keys(rt):O;delete ne.serializers,bt([ne],Zt,rt,this._stdErrSerialize)}function Bt(nt){this._childLevel=(nt._childLevel|0)+1,this.bindings=ne,rt&&(this.serializers=rt,this._serialize=Zt),p&&(this._logEvent=wt([].concat(nt._logEvent.bindings,ne)))}Bt.prototype=this;const je=new Bt(this);return o(this,je),je.child=function(...nt){return Pt.call(this,K,...nt)},je.level=Ce.level||this.level,K.onChild(je),je}return y}function T(c){const p=c.customLevels||{},b=Object.assign({},g.levels.values,p),k=Object.assign({},g.levels.labels,j(p));return{values:b,labels:k}}function j(c){const p={};return Object.keys(c).forEach(function(b){p[c[b]]=b}),p}g.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},g.stdSerializers=t,g.stdTimeFunctions=Object.assign({},{nullTime:Ft,epochTime:Gt,unixTime:xs,isoTime:ks});function S(c){const p=[];c.bindings&&p.push(c.bindings);let b=c[a];for(;b.parent;)b=b.parent,b.logger.bindings&&p.push(b.logger.bindings);return p.reverse()}function H(c,p,b,k){if(Object.defineProperty(c,k,{value:s(c.level,b)>s(k,b)?Te:b[n][k],writable:!0,enumerable:!0,configurable:!0}),c[k]===Te){if(!p.transmit)return;const P=p.transmit.level||c.level,Y=s(P,b);if(s(k,b)<Y)return}c[k]=Qe(c,p,b,k);const O=S(c);O.length!==0&&(c[k]=A(O,c[k]))}function A(c,p){return function(){return p.apply(this,[...c,...arguments])}}function Qe(c,p,b,k){return function(O){return function(){const Y=p.timestamp(),$=new Array(arguments.length),U=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var y=0;y<$.length;y++)$[y]=arguments[y];var G=!1;if(p.serialize&&(bt($,this._serialize,this.serializers,this._stdErrSerialize),G=!0),p.asObject||p.formatters?O.call(U,ws(this,k,$,Y,p)):O.apply(U,$),p.transmit){const tt=p.transmit.level||c._level,me=s(tt,b),st=s(k,b);if(st<me)return;Es(this,{ts:Y,methodLevel:k,methodValue:st,transmitValue:b.levels.values[p.transmit.level||c._level],send:p.transmit.send,val:s(c._level,b)},$,G)}}}(c[n][k])}function ws(c,p,b,k,O){const{level:P,log:Y=me=>me}=O.formatters||{},$=b.slice();let U=$[0];const y={};if(k&&(y.time=k),P){const me=P(p,c.levels.values[p]);Object.assign(y,me)}else y.level=c.levels.values[p];let G=(c._childLevel|0)+1;if(G<1&&(G=1),U!==null&&typeof U=="object"){for(;G--&&typeof $[0]=="object";)Object.assign(y,$.shift());U=$.length?r($.shift(),$):void 0}else typeof U=="string"&&(U=r($.shift(),$));return U!==void 0&&(y[O.messageKey]=U),Y(y)}function bt(c,p,b,k){for(const O in c)if(k&&c[O]instanceof Error)c[O]=g.stdSerializers.err(c[O]);else if(typeof c[O]=="object"&&!Array.isArray(c[O])&&p)for(const P in c[O])p.indexOf(P)>-1&&P in b&&(c[O][P]=b[P](c[O][P]))}function Es(c,p,b,k=!1){const O=p.send,P=p.ts,Y=p.methodLevel,$=p.methodValue,U=p.val,y=c._logEvent.bindings;k||bt(b,c._serialize||Object.keys(c.serializers),c.serializers,c._stdErrSerialize===void 0?!0:c._stdErrSerialize),c._logEvent.ts=P,c._logEvent.messages=b.filter(function(G){return y.indexOf(G)===-1}),c._logEvent.level.label=Y,c._logEvent.level.value=$,O(Y,c._logEvent,U),c._logEvent=wt(y)}function wt(c){return{ts:0,messages:[],bindings:c||[],level:{label:"",value:0}}}function Dt(c){const p={type:c.constructor.name,msg:c.message,stack:c.stack};for(const b in c)p[b]===void 0&&(p[b]=c[b]);return p}function Ts(c){return typeof c.timestamp=="function"?c.timestamp:c.timestamp===!1?Ft:Gt}function et(){return{}}function Et(c){return c}function Te(){}function Ft(){return!1}function Gt(){return Date.now()}function xs(){return Math.round(Date.now()/1e3)}function ks(){return new Date(Date.now()).toISOString()}function Ss(){function c(p){return typeof p<"u"&&p}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return c(self)||c(window)||c(this)||{}}}return Le.exports.default=g,Le.exports.pino=g,Le.exports}var un=ln();const ot=os(un);class D{pino;useTerminalFormat;static instance;constructor(e={}){this.useTerminalFormat=e.useTerminalFormat??!0;const t=e.debug?"debug":e.verbose?"trace":"info";e.silent?this.pino=ot({level:"silent"}):e.logFile||e.logDir?this.pino=this.createMultiTransportLogger(t,e):this.useTerminalFormat&&process.stdout.isTTY?this.pino=ot({level:t,transport:{target:"pino-pretty",options:{colorize:!0,ignore:"pid,hostname",translateTime:"HH:MM:ss",messageFormat:"{msg}"}}}):this.pino=ot({level:t})}createMultiTransportLogger(e,t){let s;if(t.logFile)s=t.logFile;else if(t.logDir){at.existsSync(t.logDir)||at.mkdirSync(t.logDir,{recursive:!0});const a=new Date().toISOString().split("T")[0];s=xt.join(t.logDir,`app-${a}.log`)}else{const a=xt.join(Ns.tmpdir(),"agiflow-agents","logs",`session-${process.pid}`);at.existsSync(a)||at.mkdirSync(a,{recursive:!0});const i=new Date().toISOString().split("T")[0];s=xt.join(a,`app-${i}.log`)}const n=[];return this.useTerminalFormat&&process.stdout.isTTY?n.push({level:e,target:"pino-pretty",options:{destination:1,colorize:!0,ignore:"pid,hostname",translateTime:"HH:MM:ss",messageFormat:"{msg}"}}):n.push({level:e,target:"pino/file",options:{destination:1}}),t.maxFileSize||t.maxFiles?n.push({level:e,target:"pino-roll",options:{file:s,frequency:"daily",size:t.maxFileSize||"10m",limit:{count:t.maxFiles||7},symlink:!0,mkdir:!0}}):n.push({level:e,target:"pino/file",options:{destination:s,mkdir:!0}}),ot({level:e,transport:{targets:n}})}static getInstance(){return D.instance||(D.instance=new D),D.instance}static configure(e){D.instance=new D(e)}getLogFilePath(){const e=this.pino.transports;if(e&&Array.isArray(e)){const t=e.find(s=>s.target==="pino/file"||s.target==="pino-roll");if(t&&t.options)return t.options.destination||t.options.file}}info(e,...t){this.useTerminalFormat&&process.stdout.isTTY?console.log(z.blue("ℹ"),e,...t):this.pino.info(e,...t)}static info(e,...t){D.getInstance().info(e,...t)}success(e,...t){this.useTerminalFormat&&process.stdout.isTTY?console.log(z.green("✓"),e,...t):this.pino.info({type:"success"},e,...t)}static success(e,...t){D.getInstance().success(e,...t)}warn(e,...t){this.useTerminalFormat&&process.stdout.isTTY?console.warn(z.yellow("⚠"),e,...t):this.pino.warn(e,...t)}static warn(e,...t){D.getInstance().warn(e,...t)}error(e,t,s){let n,a;t instanceof Error?(n=t,a=s):a=t,this.useTerminalFormat&&process.stdout.isTTY?console.error(z.red("✗"),e,n||""):n?this.pino.error(n,e):this.pino.error(e),a?.exit!==void 0&&process.exit(a.exit)}static error(e,t){D.getInstance().error(e,void 0,t)}debug(e,...t){this.useTerminalFormat&&process.stdout.isTTY?(vt.isDebugMode||this.pino.level==="debug"||this.pino.level==="trace")&&console.log(z.gray("🔍"),z.gray(e),...t):this.pino.debug(e,...t)}static debug(e,...t){D.getInstance().debug(e,...t)}trace(e,...t){this.useTerminalFormat&&process.stdout.isTTY?this.pino.level==="trace"&&console.log(z.gray("..."),z.gray(e),...t):this.pino.trace(e,...t)}title(e){this.useTerminalFormat&&process.stdout.isTTY?(console.log(),console.log(z.bold.cyan(e)),console.log(z.cyan("=".repeat(e.length)))):this.pino.info({type:"title"},e)}static title(e){D.getInstance().title(e)}code(e){this.useTerminalFormat&&process.stdout.isTTY?(console.log(),console.log(z.gray(" "+e)),console.log()):this.pino.info({type:"code",code:e},"Code example")}static code(e){D.getInstance().code(e)}newLine(){this.useTerminalFormat&&process.stdout.isTTY&&console.log()}static newLine(){D.getInstance().newLine()}terminal(e,t,...s){if(!process.stdout.isTTY){this.pino[e==="success"||e==="title"||e==="code"?"info":e](t,...s);return}switch(e){case"info":console.log(z.blue("ℹ"),t,...s);break;case"success":console.log(z.green("✓"),t,...s);break;case"warn":console.warn(z.yellow("⚠"),t,...s);break;case"error":console.error(z.red("✗"),t,...s);break;case"debug":console.log(z.gray("🔍"),z.gray(t),...s);break;case"title":console.log(),console.log(z.bold.cyan(t)),console.log(z.cyan("=".repeat(t.length)));break;case"code":console.log(),console.log(z.gray(" "+t)),console.log();break}}getPino(){return this.pino}child(e){const t=new D({useTerminalFormat:this.useTerminalFormat});return t.pino=this.pino.child(e),t}}class dn{static SESSIONS_FILE=le.join(M.AGIFLOW_DIR,"sessions.json");static async getSessionSettings(e){try{return await M.exists(this.SESSIONS_FILE)&&(await M.readJson(this.SESSIONS_FILE))[e]||null}catch(t){return console.error("[SessionSettings] Failed to read session settings:",t),null}}static async setSessionSettings(e,t){try{let s={};await M.exists(this.SESSIONS_FILE)&&(s=await M.readJson(this.SESSIONS_FILE)),s[e]=t,await M.writeJson(this.SESSIONS_FILE,s,{spaces:2})}catch(s){throw console.error("[SessionSettings] Failed to write session settings:",s),s}}static async removeSessionSettings(e){try{if(!await M.exists(this.SESSIONS_FILE))return;const s=await M.readJson(this.SESSIONS_FILE);delete s[e],await M.writeJson(this.SESSIONS_FILE,s,{spaces:2})}catch(t){throw console.error("[SessionSettings] Failed to remove session settings:",t),t}}static async getAllSessions(){try{return await M.exists(this.SESSIONS_FILE)?await M.readJson(this.SESSIONS_FILE):{}}catch(e){return console.error("[SessionSettings] Failed to read all session settings:",e),{}}}static async clearAllSessions(){try{await M.writeJson(this.SESSIONS_FILE,{},{spaces:2})}catch(e){throw console.error("[SessionSettings] Failed to clear session settings:",e),e}}}class bs{filePath;cache=null;dirty=!1;constructor(e){this.filePath=e||le.join(M.AGIFLOW_DIR,"credentials.json")}async load(){if(this.cache)return this.cache;try{if(!await M.exists(this.filePath))return null;const t=await M.readJson(this.filePath);return this.cache=t,t}catch{return null}}async flush(){!this.dirty||!this.cache||(await M.ensureDir(M.AGIFLOW_DIR),await M.writeJson(this.filePath,this.cache),this.dirty=!1)}async setApiKey(e){this.cache={apiKey:e.apiKey,organizationId:e.organizationId,deviceId:e.deviceId||this.cache?.deviceId,expiresAt:e.expiresAt},this.dirty=!0,await this.flush()}async setDeviceId(e){const t=await this.load()||{apiKey:"",organizationId:""};t.deviceId=e,this.cache=t,this.dirty=!0,await this.flush()}async getApiKey(){return(await this.load())?.apiKey||null}async getAgentCreds(){const e=await this.load();if(!e)throw new Error("Cred not set");return{apiKey:e.apiKey,organizationId:e.organizationId,deviceId:e.deviceId}}async getOrganizationId(){return(await this.load())?.organizationId||null}async getDeviceId(){return(await this.load())?.deviceId||null}async isExpired(e=300*1e3){const t=await this.load();return t?.expiresAt?Date.now()>=t.expiresAt-e:!1}async clear(){this.cache=null,this.dirty=!1;try{await M.exists(this.filePath)&&await M.remove(this.filePath)}catch{}}async buildAuthHeaders(){const e=await this.load();return e?.apiKey?{"x-api-key":e.apiKey}:{}}async buildDeviceAuthHeaders(e){const t=await this.load();if(!t?.apiKey)return{};const s={"x-api-key":t.apiKey};return e&&(s["x-device-guid"]=e),t.deviceId&&(s["x-device-id"]=t.deviceId),t.organizationId&&(s["x-organization-id"]=t.organizationId),s}async buildAgentAuthHeaders(e){let t=e;if(t||(t=await this.getApiKey()||void 0),t||(t=vt.apiKey),!t)return{};const s={"x-api-key":t,"Content-Type":"application/json"},n=await this.getOrganizationId();n&&(s["x-organization-id"]=n);const a=await this.getDeviceId();return a&&(s["x-device-id"]=a),s}}N({limit:te().min(1).max(100).optional(),offset:te().min(0).optional(),messageType:Mt.optional(),sort:I().optional(),order:_t(["asc","desc"]).optional()});class fn{options;authService;credentials;logger;constructor(e){this.options=e,this.authService=e.authService,this.credentials=e.credentials??new bs,this.logger=e.logger??new D({verbose:!1})}async getAuthHeaders(){let e=await this.credentials.getApiKey(),t=await this.credentials.getOrganizationId();if((!e||!t)&&this.authService){const n=await this.authService.getValidApiKey();e=n.api_key,t=n.organization_id,await this.credentials.setApiKey({apiKey:e,organizationId:t,expiresAt:n.expires_at})}if(!e&&this.options.apiKey&&(e=this.options.apiKey),!t&&this.options.organizationId&&(t=this.options.organizationId),e&&t)return this.options.organizationId=t,{"Content-Type":"application/json","x-api-key":e};const s=this.options.authToken;if(!s)throw new Error("Authentication token is required for agent message operations");if(!this.options.organizationId)throw new Error("Organization ID is required for agent message operations");return{"Content-Type":"application/json",Authorization:`Bearer ${s}`}}async makeAuthenticatedRequest(e,t,s=!0){const n=await fetch(e,t);if(n.status===401&&s&&this.authService){const a=await n.text();if(a.includes("Invalid API key")){this.logger.info("= API key expired or invalid, clearing tokens and retrying authentication..."),await this.authService.clearTokens();try{await this.credentials.clear()}catch{}this.logger.info("= Retrying authentication...");const i=await this.getAuthHeaders(),o={...t,headers:{...t.headers,...i}};return await this.makeAuthenticatedRequest(e,o,!1)}if(a.includes("Invalid or expired session")){const i=vt.isContainerMode;if(this.logger.error("🚫 Session validation failed:",new Error(`Session validation failed for ${e}. Docker mode: ${i}, Method: ${t.method||"GET"}, Timestamp: ${new Date().toISOString()}`)),i)return this.logger.warn("🐳 Docker session timing issue detected, waiting and retrying..."),await new Promise(o=>setTimeout(o,2e3)),await this.makeAuthenticatedRequest(e,t,!1)}}return n.status===429&&this.logger.warn("= Rate limit exceeded, keeping credentials but not retrying"),n}async sendMessage(e){const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s)throw new Error("Organization ID is required for sending agent messages");const n=ns(e);try{_s.parse(n)}catch(a){throw new Error(`Invalid message payload: ${a instanceof Error?a.message:a}`)}try{const a=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/agent-sessions/${e.sessionId}/messages`,{method:"POST",headers:t,body:JSON.stringify(n)});if(!a.ok){const o=await a.text();throw new Error(`Failed to send agent message: ${a.status} ${o}`)}return await a.json()}catch(a){throw new Error(`Failed to send agent message: ${a instanceof Error?a.message:a}`)}}async sendMessageBatch(e,t){const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)throw new Error("Organization ID is required for sending agent messages");const a=(t||[]).map(i=>ns(i));try{const i=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${n}/agent-sessions/${e}/messages/batch`,{method:"POST",headers:s,body:JSON.stringify({messages:a})});if(!i.ok){const d=await i.text();throw new Error(`Failed to send agent message batch: ${i.status} ${d}`)}return await i.json()}catch(i){throw new Error(`Failed to send agent message batch: ${i instanceof Error?i.message:i}`)}}async getSessionMessages(e,t){const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)throw new Error("Organization ID is required for fetching agent messages");const a=new URLSearchParams;t?.limit&&a.append("limit",t.limit.toString()),t?.offset&&a.append("offset",t.offset.toString()),t?.messageType&&a.append("messageType",t.messageType),t?.sort&&a.append("sort",t.sort),t?.order&&a.append("order",t.order);const i=`${this.options.apiUrl}/api/v1/organizations/${n}/agent-sessions/${e}/messages?${a.toString()}`;try{const o=await this.makeAuthenticatedRequest(i,{method:"GET",headers:s});if(!o.ok){const u=await o.text();throw new Error(`Failed to fetch session messages: ${o.status} ${u}`)}return await o.json()}catch(o){throw new Error(`Failed to fetch session messages: ${o instanceof Error?o.message:o}`)}}async uploadMessageContent(e,t,s,n){const a=await this.getAuthHeaders(),i=this.options.organizationId;if(!i)throw new Error("Organization ID is required for uploading message content");const o=typeof s=="string"?Buffer.from(s,"utf-8"):s,d=o.length;try{const u=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${i}/agent-sessions/${e}/messages/presign`,{method:"POST",headers:a,body:JSON.stringify({messageType:t,contentSize:d})});if(!u.ok){const S=await u.text();throw new Error(`Failed to get presigned URL: ${u.status} ${S}`)}const{uploadUrl:g}=await u.json(),T=await fetch(g,{method:"PUT",body:o,headers:{"Content-Type":"application/octet-stream","Content-Length":d.toString()}});if(!T.ok)throw new Error(`Failed to upload content to R2: ${T.status}`);const j={sessionId:e,messageType:t,contentSize:d,metadata:n};return await this.sendMessage(j)}catch(u){throw new Error(`Failed to upload message content: ${u instanceof Error?u.message:u}`)}}async startMessage(e,t){const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)throw new Error("Organization ID is required for starting agent messages");try{tn.parse(t)}catch(a){throw new Error(`Invalid start message payload: ${a instanceof Error?a.message:a}`)}try{const a=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${n}/agent-sessions/${e}/messages/start`,{method:"POST",headers:s,body:JSON.stringify(t)});if(!a.ok){const o=await a.text();throw new Error(`Failed to start agent message: ${a.status} ${o}`)}return await a.json()}catch(a){throw new Error(`Failed to start agent message: ${a instanceof Error?a.message:a}`)}}async updateMessage(e,t,s){const n=await this.getAuthHeaders(),a=this.options.organizationId;if(!a)throw new Error("Organization ID is required for updating agent messages");try{sn.parse(s)}catch(o){throw this.logger.error("=❌ Update message validation failed",new Error(`Update message validation failed: ${o instanceof Error?o.message:o}`)),new Error(`Invalid update message payload: ${o instanceof Error?o.message:o}`)}const i=JSON.stringify(s);try{const o=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${a}/agent-sessions/${e}/messages/${t}`,{method:"PATCH",headers:n,body:i});if(!o.ok){const u=await o.text();throw new Error(`Failed to update agent message: ${o.status} ${u}`)}return await o.json()}catch(o){throw new Error(`Failed to update agent message: ${o instanceof Error?o.message:o}`)}}async deleteSessionMessages(e){const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s)throw new Error("Organization ID is required for deleting session messages");this.logger.info(`=� Deleting all messages for session ${e}...`);try{const n=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/agent-sessions/${e}/messages`,{method:"DELETE",headers:t},!1);if(!n.ok){const i=await n.text().catch(()=>"Unknown error");return this.logger.warn(`� Failed to delete session messages: ${n.status} ${i}`),0}const{deletedCount:a}=await n.json();return this.logger.success(` Deleted ${a} messages for session ${e}`),a}catch(n){return this.logger.warn("� Failed to delete session messages:",n),0}}async getAgentSession(e){const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s)throw new Error("Organization ID is required for fetching agent session");try{const n=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/agent-sessions/${e}`,{method:"GET",headers:t});if(!n.ok){const i=await n.text();throw new Error(`Failed to fetch agent session: ${n.status} ${i}`)}return await n.json()}catch(n){throw new Error(`Failed to fetch agent session: ${n instanceof Error?n.message:n}`)}}async createTaskComment(e,t,s,n){try{const a=await this.getAuthHeaders(),i=this.options.organizationId;if(!i)return this.logger.warn("Organization ID is required for creating task comment"),null;const o=t&&t.length>1e4?t.substring(0,1e4):t,d=await this.getAgentSession(e);if(!d)return this.logger.warn("Agent session not found for task comment creation"),null;if(!d.taskId)return this.logger.debug("Agent session has no associated task - skipping comment creation"),null;const u=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${i}/tasks/${d.taskId}/comments`,{method:"POST",headers:a,body:JSON.stringify({content:o,assigneeId:s,info:n})});if(!u.ok){const T=await u.text();return this.logger.warn(`Failed to create task comment: ${u.status} ${T}`),null}const g=await u.json();return this.logger.debug("Task comment created successfully"),g}catch(a){return this.logger.warn(`Failed to create task comment: ${a instanceof Error?a.message:a}`),null}}async updateTaskDevInfo(e,t){try{const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)return this.logger.warn("Organization ID is required for updating task devInfo"),null;const a=await this.getAgentSession(e);if(!a)return this.logger.warn("Agent session not found for task devInfo update"),null;if(!a.taskId)return this.logger.debug("Agent session has no associated task - skipping devInfo update"),null;const i=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${n}/tasks/${a.taskId}`,{method:"PATCH",headers:s,body:JSON.stringify({devInfo:t})});if(!i.ok){const d=await i.text();return this.logger.warn(`Failed to update task devInfo: ${i.status} ${d}`),null}const o=await i.json();return this.logger.debug("Task devInfo updated successfully"),o}catch(s){return this.logger.warn(`Failed to update task devInfo: ${s instanceof Error?s.message:s}`),null}}}exports.AgentHttpService=fn;exports.CredentialsService=bs;exports.ENV_KEYS=Fr;exports.FileSystemUtils=M;exports.Logger=D;exports.SessionSettingsManager=dn;exports.SubEnvManager=vt;exports.chalk=z;exports.createSelectComponent=nn;exports.createTextPart=vs;exports.createToolInvocationInput=an;exports.createToolInvocationPart=on;exports.getDefaultExportFromCjs=os;exports.z=F;
|
|
6
|
+
//# sourceMappingURL=AgentHttpService-MFVF-74l.js.map
|