@betrue/openclaw-claude-code-plugin 1.0.6 → 1.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/README.md +107 -181
- package/dist/index.js +37 -35
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,131 +1,149 @@
|
|
|
1
|
-
# Claude Code
|
|
1
|
+
# OpenClaw plugin to orchestrate Claude Code
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Orchestrate Claude Code sessions as managed background processes from any OpenClaw channel.
|
|
4
4
|
|
|
5
|
-
Launch, monitor, and interact with multiple Claude Code SDK sessions directly from
|
|
5
|
+
Launch, monitor, and interact with multiple Claude Code SDK sessions directly from Telegram, Discord, or any OpenClaw-supported platform — without leaving your chat interface.
|
|
6
6
|
|
|
7
7
|
[](https://youtube.com/shorts/vbX1Y0Nx4Tc)
|
|
8
8
|
|
|
9
|
-
*
|
|
9
|
+
*Two parallel Claude Code agents building an X clone and an Instagram clone simultaneously from Telegram.*
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
-
##
|
|
14
|
-
|
|
15
|
-
- **Multi-session management** — Run up to N concurrent sessions (configurable), each with a unique ID and human-readable name
|
|
16
|
-
- **Foreground / background model** — Sessions run in the background by default; bring any session to the foreground to stream output in real time
|
|
17
|
-
- **Foreground catchup** — When foregrounding, missed background output is displayed before live streaming begins
|
|
18
|
-
- **Multi-turn conversations** — Sessions are multi-turn by default; send follow-up messages, refine instructions, or have iterative dialogues with a running agent. Set `multi_turn_disabled: true` for fire-and-forget sessions
|
|
19
|
-
- **Session resume & fork** — Resume any completed session or fork it into a new branch of conversation
|
|
20
|
-
- **Pre-launch safety checks** — Five mandatory guards (autonomy skill with 👋/🤖 notification format, heartbeat config, heartbeat interval ≥ 60m, no agent gateway restart, agentChannels mapping) ensure every agent is properly configured before spawning sessions
|
|
21
|
-
- **maxAutoResponds** — Limits consecutive agent auto-responds per session (default: 10). Resets when the user responds via slash command. Blocks `claude_respond` tool when the limit is reached
|
|
22
|
-
- **Real-time notifications** — Completion alerts, budget exhaustion warnings, long-running reminders, and live tool-use indicators
|
|
23
|
-
- **Background notifications** — In background mode, only 🔔 (Claude asks) and ↩️ (Responded) are sent directly. Completion/failure/budget notifications are suppressed — the orchestrator agent handles summaries
|
|
24
|
-
- **Event routing** — `triggerAgentEvent` and `triggerWaitingForInputEvent` use `openclaw system event --mode now` (broadcast). No `routeEventMessage` — events are broadcast and agents filter by session ownership
|
|
25
|
-
- **Waiting-for-input wake events** — `openclaw system event` fired when sessions become idle, waking the orchestrator agent
|
|
26
|
-
- **Multi-agent support** — Route notifications to the correct agent/chat via `agentChannels` workspace mapping with longest-prefix matching
|
|
27
|
-
- **Triple interface** — Every operation available as a chat command, agent tool, and gateway RPC method
|
|
28
|
-
- **Automatic cleanup** — Completed sessions garbage-collected after 1 hour; persisted IDs survive for resume
|
|
29
|
-
|
|
30
|
-
---
|
|
31
|
-
|
|
32
|
-
## Installation
|
|
13
|
+
## Quick Start
|
|
33
14
|
|
|
34
|
-
###
|
|
15
|
+
### 1. Install the plugin
|
|
35
16
|
|
|
36
17
|
```bash
|
|
37
18
|
openclaw plugins install @betrue/openclaw-claude-code-plugin
|
|
19
|
+
openclaw gateway restart
|
|
38
20
|
```
|
|
39
21
|
|
|
40
|
-
###
|
|
22
|
+
### 2. Configure notifications (minimal)
|
|
41
23
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
24
|
+
Add to `~/.openclaw/openclaw.json` under `plugins.config["openclaw-claude-code-plugin"]`:
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"fallbackChannel": "telegram|my-bot|123456789",
|
|
29
|
+
"maxSessions": 5
|
|
30
|
+
}
|
|
45
31
|
```
|
|
46
32
|
|
|
47
|
-
###
|
|
33
|
+
### 3. Launch your first session
|
|
48
34
|
|
|
49
|
-
|
|
50
|
-
git clone git@github.com:alizarion/openclaw-claude-code-plugin.git
|
|
51
|
-
openclaw plugins install --link ./openclaw-claude-code-plugin
|
|
52
|
-
```
|
|
35
|
+
Ask your agent: *"Fix the bug in auth.ts"*
|
|
53
36
|
|
|
54
|
-
|
|
37
|
+
On first launch, the plugin runs **4 safety checks** and guides you through one-time setup:
|
|
55
38
|
|
|
56
|
-
|
|
39
|
+
1. **Answer an autonomy question** — tell the agent how much freedom Claude Code gets
|
|
40
|
+
2. **Run a heartbeat config command** — paste the `jq` one-liner the agent provides
|
|
41
|
+
3. **Restart the gateway** — `openclaw gateway restart`
|
|
57
42
|
|
|
58
|
-
|
|
59
|
-
openclaw gateway restart
|
|
60
|
-
```
|
|
43
|
+
That's it. Future launches skip setup entirely.
|
|
61
44
|
|
|
62
|
-
|
|
45
|
+
> Full first-launch walkthrough: [docs/safety.md](docs/safety.md)
|
|
63
46
|
|
|
64
47
|
---
|
|
65
48
|
|
|
66
|
-
##
|
|
49
|
+
## Features
|
|
67
50
|
|
|
68
|
-
|
|
51
|
+
- **Multi-session management** — Run multiple concurrent sessions, each with a unique ID and human-readable name
|
|
52
|
+
- **Foreground / background model** — Sessions run in background by default; bring any to foreground to stream output in real time, with catchup of missed output
|
|
53
|
+
- **Real-time notifications** — Get notified on completion, failure, or when Claude asks a question
|
|
54
|
+
- **Multi-turn conversations** — Send follow-up messages, interrupt, or iterate with a running agent
|
|
55
|
+
- **Session resume & fork** — Resume any completed session or fork it into a new conversation branch
|
|
56
|
+
- **4 pre-launch safety checks** — Autonomy skill, heartbeat config, HEARTBEAT.md, and channel mapping
|
|
57
|
+
- **Multi-agent support** — Route notifications to the correct agent/chat via workspace-based channel mapping
|
|
58
|
+
- **Automatic cleanup** — Completed sessions garbage-collected after 1 hour; IDs persist for resume
|
|
69
59
|
|
|
70
|
-
|
|
60
|
+
---
|
|
71
61
|
|
|
72
|
-
|
|
62
|
+
## Tools
|
|
73
63
|
|
|
74
|
-
|
|
64
|
+
| Tool | Description |
|
|
65
|
+
|------|-------------|
|
|
66
|
+
| `claude_launch` | Start a new Claude Code session in background |
|
|
67
|
+
| `claude_respond` | Send a follow-up message to a running session |
|
|
68
|
+
| `claude_fg` | Bring a session to foreground — stream output in real time |
|
|
69
|
+
| `claude_bg` | Send a session back to background — stop streaming |
|
|
70
|
+
| `claude_kill` | Terminate a running session |
|
|
71
|
+
| `claude_output` | Read buffered output from a session |
|
|
72
|
+
| `claude_sessions` | List all sessions with status and progress |
|
|
73
|
+
| `claude_stats` | Show usage metrics (counts, durations, costs) |
|
|
75
74
|
|
|
76
|
-
|
|
75
|
+
All tools are also available as **chat commands** (`/claude`, `/claude_fg`, etc.) and most as **gateway RPC methods**.
|
|
77
76
|
|
|
78
|
-
|
|
77
|
+
> Full parameter tables and response schemas: [docs/API.md](docs/API.md)
|
|
79
78
|
|
|
80
|
-
|
|
79
|
+
---
|
|
81
80
|
|
|
82
|
-
|
|
83
|
-
{ "heartbeat": { "every": "60m", "target": "last" } }
|
|
84
|
-
```
|
|
81
|
+
## Quick Usage
|
|
85
82
|
|
|
86
|
-
|
|
83
|
+
```bash
|
|
84
|
+
# Launch a session
|
|
85
|
+
/claude Fix the authentication bug in src/auth.ts
|
|
86
|
+
/claude --name fix-auth Fix the authentication bug
|
|
87
|
+
|
|
88
|
+
# Monitor
|
|
89
|
+
/claude_sessions
|
|
90
|
+
/claude_fg fix-auth
|
|
91
|
+
/claude_bg fix-auth
|
|
87
92
|
|
|
88
|
-
|
|
93
|
+
# Interact
|
|
94
|
+
/claude_respond fix-auth Also add unit tests
|
|
95
|
+
/claude_respond --interrupt fix-auth Stop that and do this instead
|
|
89
96
|
|
|
90
|
-
|
|
97
|
+
# Lifecycle
|
|
98
|
+
/claude_kill fix-auth
|
|
99
|
+
/claude_resume fix-auth Add error handling
|
|
100
|
+
/claude_resume --fork fix-auth Try a different approach
|
|
101
|
+
/claude_stats
|
|
102
|
+
```
|
|
91
103
|
|
|
92
|
-
|
|
104
|
+
---
|
|
93
105
|
|
|
94
|
-
|
|
106
|
+
## Notifications
|
|
95
107
|
|
|
96
|
-
|
|
108
|
+
The plugin sends real-time notifications to your chat based on session lifecycle events:
|
|
97
109
|
|
|
98
|
-
|
|
110
|
+
| Emoji | Event | Description |
|
|
111
|
+
|-------|-------|-------------|
|
|
112
|
+
| ↩️ | Launched | Session started successfully |
|
|
113
|
+
| 🔔 | Claude asks | Session is waiting for user input — includes output preview |
|
|
114
|
+
| ↩️ | Responded | Follow-up message delivered to session |
|
|
115
|
+
| ✅ | Completed | Session finished successfully |
|
|
116
|
+
| ❌ | Failed | Session encountered an error |
|
|
117
|
+
| ⛔ | Killed | Session was manually terminated |
|
|
99
118
|
|
|
100
|
-
|
|
119
|
+
Foreground sessions stream full output in real time. Background sessions only send lifecycle notifications.
|
|
101
120
|
|
|
102
|
-
|
|
121
|
+
> Notification architecture and delivery model: [docs/NOTIFICATIONS.md](docs/NOTIFICATIONS.md)
|
|
103
122
|
|
|
104
123
|
---
|
|
105
124
|
|
|
106
125
|
## Configuration
|
|
107
126
|
|
|
108
|
-
|
|
127
|
+
Set values in `~/.openclaw/openclaw.json` under `plugins.config["openclaw-claude-code-plugin"]`.
|
|
128
|
+
|
|
129
|
+
### Essential parameters
|
|
109
130
|
|
|
110
131
|
| Option | Type | Default | Description |
|
|
111
|
-
|
|
112
|
-
| `
|
|
113
|
-
| `
|
|
114
|
-
| `
|
|
115
|
-
| `
|
|
116
|
-
| `
|
|
117
|
-
| `
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
| `permissionMode` | `string` | `"bypassPermissions"` | Default permission mode: `"default"`, `"plan"`, `"acceptEdits"`, `"bypassPermissions"`. |
|
|
121
|
-
| `agentChannels` | `Record<string, string>` | — | Map workdir paths to notification channels. See [Agent Channels](docs/AGENT_CHANNELS.md). |
|
|
132
|
+
|--------|------|---------|-------------|
|
|
133
|
+
| `agentChannels` | `object` | — | Map workdir paths → notification channels |
|
|
134
|
+
| `fallbackChannel` | `string` | — | Default channel when no workspace match found |
|
|
135
|
+
| `maxSessions` | `number` | `5` | Maximum concurrent sessions |
|
|
136
|
+
| `maxAutoResponds` | `number` | `10` | Max consecutive auto-responds before requiring user input |
|
|
137
|
+
| `defaultBudgetUsd` | `number` | `5` | Default budget per session (USD) |
|
|
138
|
+
| `permissionMode` | `string` | `"bypassPermissions"` | `"default"` / `"plan"` / `"acceptEdits"` / `"bypassPermissions"` |
|
|
139
|
+
|
|
140
|
+
### Example
|
|
122
141
|
|
|
123
142
|
```json
|
|
124
143
|
{
|
|
125
144
|
"maxSessions": 3,
|
|
126
145
|
"defaultBudgetUsd": 10,
|
|
127
146
|
"defaultModel": "sonnet",
|
|
128
|
-
"defaultWorkdir": "/home/user/projects",
|
|
129
147
|
"permissionMode": "bypassPermissions",
|
|
130
148
|
"fallbackChannel": "telegram|main-bot|123456789",
|
|
131
149
|
"agentChannels": {
|
|
@@ -137,154 +155,62 @@ Configuration is defined in `openclaw.plugin.json` and passed to the plugin via
|
|
|
137
155
|
|
|
138
156
|
---
|
|
139
157
|
|
|
140
|
-
## Quick Usage
|
|
141
|
-
|
|
142
|
-
### Chat Commands
|
|
143
|
-
|
|
144
|
-
```
|
|
145
|
-
/claude Fix the authentication bug in src/auth.ts
|
|
146
|
-
/claude --name fix-auth Fix the authentication bug
|
|
147
|
-
/claude_sessions
|
|
148
|
-
/claude_fg fix-auth
|
|
149
|
-
/claude_respond fix-auth Also add unit tests
|
|
150
|
-
/claude_respond --interrupt fix-auth Stop that and do this instead
|
|
151
|
-
/claude_bg fix-auth
|
|
152
|
-
/claude_kill fix-auth
|
|
153
|
-
/claude_resume fix-auth Add error handling
|
|
154
|
-
/claude_resume --fork fix-auth Try a different approach
|
|
155
|
-
/claude_resume --list
|
|
156
|
-
/claude_stats
|
|
157
|
-
```
|
|
158
|
-
|
|
159
|
-
### Agent Tools
|
|
160
|
-
|
|
161
|
-
Tools receive the calling agent's context automatically. Channel resolution is handled internally — **no `channel` parameter** is exposed on any tool. The parameter `multi_turn_disabled` (not `multi_turn`) controls single-turn mode.
|
|
162
|
-
|
|
163
|
-
```
|
|
164
|
-
claude_launch(prompt: "Fix auth bug", workdir: "/app", name: "fix-auth")
|
|
165
|
-
claude_launch(prompt: "Quick check", multi_turn_disabled: true)
|
|
166
|
-
claude_sessions(status: "running")
|
|
167
|
-
claude_output(session: "fix-auth", lines: 20)
|
|
168
|
-
claude_output(session: "fix-auth", full: true)
|
|
169
|
-
claude_fg(session: "fix-auth")
|
|
170
|
-
claude_bg(session: "fix-auth")
|
|
171
|
-
claude_respond(session: "fix-auth", message: "Also add tests")
|
|
172
|
-
claude_respond(session: "fix-auth", message: "Do this instead", interrupt: true)
|
|
173
|
-
claude_kill(session: "fix-auth")
|
|
174
|
-
claude_stats()
|
|
175
|
-
```
|
|
176
|
-
|
|
177
|
-
### Gateway RPC
|
|
178
|
-
|
|
179
|
-
```json
|
|
180
|
-
{ "method": "claude-code.launch", "params": { "prompt": "Fix auth", "workdir": "/app" } }
|
|
181
|
-
{ "method": "claude-code.sessions", "params": { "status": "running" } }
|
|
182
|
-
{ "method": "claude-code.output", "params": { "session": "fix-auth", "full": true } }
|
|
183
|
-
{ "method": "claude-code.kill", "params": { "session": "fix-auth" } }
|
|
184
|
-
{ "method": "claude-code.stats" }
|
|
185
|
-
```
|
|
186
|
-
|
|
187
|
-
For the full API reference (all parameter tables, response schemas), see [docs/API.md](docs/API.md).
|
|
188
|
-
|
|
189
|
-
---
|
|
190
|
-
|
|
191
|
-
## Multi-Agent Setup
|
|
192
|
-
|
|
193
|
-
See [docs/AGENT_CHANNELS.md](docs/AGENT_CHANNELS.md) for the complete guide. Quick summary:
|
|
194
|
-
|
|
195
|
-
Each agent needs three things configured:
|
|
196
|
-
|
|
197
|
-
1. **agentChannels mapping** — Map the agent's workspace directory to its notification channel in `openclaw.json`:
|
|
198
|
-
```json
|
|
199
|
-
{
|
|
200
|
-
"plugins": {
|
|
201
|
-
"config": {
|
|
202
|
-
"openclaw-claude-code-plugin": {
|
|
203
|
-
"agentChannels": {
|
|
204
|
-
"/home/user/agent-seo": "telegram|seo-bot|123456789",
|
|
205
|
-
"/home/user/agent-devops": "telegram|devops-bot|123456789"
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
```
|
|
212
|
-
|
|
213
|
-
2. **Heartbeat** — Enable heartbeat for each agent in `openclaw.json`:
|
|
214
|
-
```json
|
|
215
|
-
{
|
|
216
|
-
"agents": {
|
|
217
|
-
"list": [
|
|
218
|
-
{ "id": "seo-bot", "heartbeat": { "every": "60m", "target": "last" } },
|
|
219
|
-
{ "id": "devops-bot", "heartbeat": { "every": "60m", "target": "last" } }
|
|
220
|
-
]
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
```
|
|
224
|
-
|
|
225
|
-
3. **Agent files** — Each agent's workspace needs:
|
|
226
|
-
- `HEARTBEAT.md` — Instructions for checking Claude Code sessions during heartbeat cycles
|
|
227
|
-
- `skills/claude-code-autonomy/SKILL.md` — Autonomy rules for handling session interactions
|
|
228
|
-
|
|
229
|
-
---
|
|
230
|
-
|
|
231
158
|
## Skill Example
|
|
232
159
|
|
|
233
|
-
|
|
160
|
+
<details>
|
|
161
|
+
<summary>Example orchestration skill (click to expand)</summary>
|
|
234
162
|
|
|
235
|
-
|
|
163
|
+
The plugin is a **transparent transport layer** — business logic lives in **OpenClaw skills**:
|
|
236
164
|
|
|
237
165
|
```markdown
|
|
238
166
|
---
|
|
239
167
|
name: Coding Agent Orchestrator
|
|
240
|
-
description: Orchestrates Claude Code sessions with
|
|
168
|
+
description: Orchestrates Claude Code sessions with auto-response rules.
|
|
241
169
|
metadata: {"openclaw": {"requires": {"plugins": ["openclaw-claude-code-plugin"]}}}
|
|
242
170
|
---
|
|
243
171
|
|
|
244
172
|
# Coding Agent Orchestrator
|
|
245
173
|
|
|
246
|
-
You are a coding agent orchestrator. You manage Claude Code sessions via the claude-code plugin tools.
|
|
247
|
-
|
|
248
174
|
## Auto-response rules
|
|
249
175
|
|
|
250
|
-
When a Claude Code session asks a question
|
|
176
|
+
When a Claude Code session asks a question, analyze and decide:
|
|
251
177
|
|
|
252
178
|
### Auto-respond (use `claude_respond` immediately):
|
|
253
179
|
- Permission requests for file reads, writes, or bash commands -> "Yes, proceed."
|
|
254
180
|
- Confirmation prompts like "Should I continue?" -> "Yes, continue."
|
|
255
|
-
- Questions about approach when only one is reasonable -> respond with the obvious choice
|
|
256
181
|
|
|
257
182
|
### Forward to user:
|
|
258
183
|
- Architecture decisions (Redis vs PostgreSQL, REST vs GraphQL...)
|
|
259
184
|
- Destructive operations (deleting files, dropping tables...)
|
|
260
185
|
- Anything involving credentials, secrets, or production environments
|
|
261
|
-
- When in doubt -> always forward to the user
|
|
262
186
|
|
|
263
187
|
## Workflow
|
|
264
|
-
|
|
265
188
|
1. User sends a coding task -> `claude_launch(prompt, ...)`
|
|
266
189
|
2. Session runs in background. Monitor via wake events.
|
|
267
190
|
3. On wake event -> `claude_output` to read the question, then auto-respond or forward.
|
|
268
|
-
4. On
|
|
269
|
-
5. On completion -> summarize the result and notify the user.
|
|
191
|
+
4. On completion -> summarize the result and notify the user.
|
|
270
192
|
```
|
|
271
193
|
|
|
272
194
|
A comprehensive orchestration skill is available at [`skills/claude-code-orchestration/SKILL.md`](skills/claude-code-orchestration/SKILL.md).
|
|
273
195
|
|
|
196
|
+
</details>
|
|
197
|
+
|
|
274
198
|
---
|
|
275
199
|
|
|
276
200
|
## Documentation
|
|
277
201
|
|
|
278
202
|
| Document | Description |
|
|
279
|
-
|
|
280
|
-
| [docs/
|
|
281
|
-
| [docs/
|
|
282
|
-
| [docs/
|
|
283
|
-
| [docs/
|
|
203
|
+
|----------|-------------|
|
|
204
|
+
| [docs/getting-started.md](docs/getting-started.md) | Full setup guide and first-launch walkthrough |
|
|
205
|
+
| [docs/API.md](docs/API.md) | Tools, commands, and RPC methods — full parameter tables and response schemas |
|
|
206
|
+
| [docs/safety.md](docs/safety.md) | Pre-launch safety checks and troubleshooting |
|
|
207
|
+
| [docs/NOTIFICATIONS.md](docs/NOTIFICATIONS.md) | Notification architecture, delivery model, and wake mechanism |
|
|
284
208
|
| [docs/AGENT_CHANNELS.md](docs/AGENT_CHANNELS.md) | Multi-agent setup, notification routing, and workspace mapping |
|
|
209
|
+
| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Architecture overview and component breakdown |
|
|
210
|
+
| [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) | Development guide, project structure, and build instructions |
|
|
285
211
|
|
|
286
212
|
---
|
|
287
213
|
|
|
288
214
|
## License
|
|
289
215
|
|
|
290
|
-
|
|
216
|
+
MIT — see [package.json](package.json) for details.
|
package/dist/index.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
var ui=Object.create;var Jt=Object.defineProperty;var ci=Object.getOwnPropertyDescriptor;var mi=Object.getOwnPropertyNames;var li=Object.getPrototypeOf,di=Object.prototype.hasOwnProperty;var Yt=(e,t)=>{for(var n in t)Jt(e,n,{get:t[n],enumerable:!0})},Ir=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of mi(t))!di.call(e,o)&&o!==n&&Jt(e,o,{get:()=>t[o],enumerable:!(r=ci(t,o))||r.enumerable});return e};var pi=(e,t,n)=>(n=e!=null?ui(li(e)):{},Ir(t||!e||!e.__esModule?Jt(n,"default",{value:e,enumerable:!0}):n,e)),fi=e=>Ir(Jt({},"__esModule",{value:!0}),e);var nl={};Yt(nl,{register:()=>tl});module.exports=fi(nl);var ut=require("fs"),Sn=require("path"),Es=require("os");var Q={};Yt(Q,{HasPropertyKey:()=>Xt,IsArray:()=>_,IsAsyncIterator:()=>Rn,IsBigInt:()=>Pt,IsBoolean:()=>Ke,IsDate:()=>Ze,IsFunction:()=>Fn,IsIterator:()=>An,IsNull:()=>Mn,IsNumber:()=>ce,IsObject:()=>$,IsRegExp:()=>kt,IsString:()=>A,IsSymbol:()=>Un,IsUint8Array:()=>je,IsUndefined:()=>G});function Xt(e,t){return t in e}function Rn(e){return $(e)&&!_(e)&&!je(e)&&Symbol.asyncIterator in e}function _(e){return Array.isArray(e)}function Pt(e){return typeof e=="bigint"}function Ke(e){return typeof e=="boolean"}function Ze(e){return e instanceof globalThis.Date}function Fn(e){return typeof e=="function"}function An(e){return $(e)&&!_(e)&&!je(e)&&Symbol.iterator in e}function Mn(e){return e===null}function ce(e){return typeof e=="number"}function $(e){return typeof e=="object"&&e!==null}function kt(e){return e instanceof globalThis.RegExp}function A(e){return typeof e=="string"}function Un(e){return typeof e=="symbol"}function je(e){return e instanceof globalThis.Uint8Array}function G(e){return e===void 0}function gi(e){return e.map(t=>Zt(t))}function Ii(e){return new Date(e.getTime())}function hi(e){return new Uint8Array(e)}function yi(e){return new RegExp(e.source,e.flags)}function xi(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Zt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Zt(e[n]);return t}function Zt(e){return _(e)?gi(e):Ze(e)?Ii(e):je(e)?hi(e):kt(e)?yi(e):$(e)?xi(e):e}function k(e){return Zt(e)}function lt(e,t){return t===void 0?k(e):k({...t,...e})}function hr(e){return e!==null&&typeof e=="object"}function yr(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function xr(e){return e===void 0}function br(e){return typeof e=="number"}var Qt;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(a,m){return e.ExactOptionalPropertyTypes?m in a:a[m]!==void 0}e.IsExactOptionalProperty=t;function n(a){let m=hr(a);return e.AllowArrayObject?m:m&&!yr(a)}e.IsObjectLike=n;function r(a){return n(a)&&!(a instanceof Date)&&!(a instanceof Uint8Array)}e.IsRecordLike=r;function o(a){return e.AllowNaN?br(a):Number.isFinite(a)}e.IsNumberLike=o;function s(a){let m=xr(a);return e.AllowNullVoid?m||a===null:m}e.IsVoidLike=s})(Qt||(Qt={}));function bi(e){return globalThis.Object.freeze(e).map(t=>Nt(t))}function Si(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Nt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Nt(e[n]);return globalThis.Object.freeze(t)}function Nt(e){return _(e)?bi(e):Ze(e)?e:je(e)?e:kt(e)?e:$(e)?Si(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(Qt.InstanceMode){case"freeze":return Nt(n);case"clone":return k(n);default:return n}}var z=class extends Error{constructor(t){super(t)}};var B=Symbol.for("TypeBox.Transform"),Ce=Symbol.for("TypeBox.Readonly"),Y=Symbol.for("TypeBox.Optional"),Ie=Symbol.for("TypeBox.Hint"),l=Symbol.for("TypeBox.Kind");function dt(e){return $(e)&&e[Ce]==="Readonly"}function oe(e){return $(e)&&e[Y]==="Optional"}function Pn(e){return y(e,"Any")}function kn(e){return y(e,"Argument")}function Te(e){return y(e,"Array")}function Qe(e){return y(e,"AsyncIterator")}function et(e){return y(e,"BigInt")}function Ee(e){return y(e,"Boolean")}function Oe(e){return y(e,"Computed")}function $e(e){return y(e,"Constructor")}function Ci(e){return y(e,"Date")}function we(e){return y(e,"Function")}function Re(e){return y(e,"Integer")}function K(e){return y(e,"Intersect")}function tt(e){return y(e,"Iterator")}function y(e,t){return $(e)&&l in e&&e[l]===t}function en(e){return Ke(e)||ce(e)||A(e)}function me(e){return y(e,"Literal")}function le(e){return y(e,"MappedKey")}function N(e){return y(e,"MappedResult")}function De(e){return y(e,"Never")}function Ti(e){return y(e,"Not")}function Kt(e){return y(e,"Null")}function Fe(e){return y(e,"Number")}function L(e){return y(e,"Object")}function nt(e){return y(e,"Promise")}function rt(e){return y(e,"Record")}function E(e){return y(e,"Ref")}function Nn(e){return y(e,"RegExp")}function _e(e){return y(e,"String")}function jt(e){return y(e,"Symbol")}function de(e){return y(e,"TemplateLiteral")}function Oi(e){return y(e,"This")}function Be(e){return $(e)&&B in e}function pe(e){return y(e,"Tuple")}function Et(e){return y(e,"Undefined")}function x(e){return y(e,"Union")}function $i(e){return y(e,"Uint8Array")}function wi(e){return y(e,"Unknown")}function Ri(e){return y(e,"Unsafe")}function Fi(e){return y(e,"Void")}function Ai(e){return $(e)&&l in e&&A(e[l])}function fe(e){return Pn(e)||kn(e)||Te(e)||Ee(e)||et(e)||Qe(e)||Oe(e)||$e(e)||Ci(e)||we(e)||Re(e)||K(e)||tt(e)||me(e)||le(e)||N(e)||De(e)||Ti(e)||Kt(e)||Fe(e)||L(e)||nt(e)||rt(e)||E(e)||Nn(e)||_e(e)||jt(e)||de(e)||Oi(e)||pe(e)||Et(e)||x(e)||$i(e)||wi(e)||Ri(e)||Fi(e)||Ai(e)}var i={};Yt(i,{IsAny:()=>Or,IsArgument:()=>$r,IsArray:()=>wr,IsAsyncIterator:()=>Rr,IsBigInt:()=>Fr,IsBoolean:()=>Ar,IsComputed:()=>Mr,IsConstructor:()=>Ur,IsDate:()=>Pr,IsFunction:()=>kr,IsImport:()=>Ki,IsInteger:()=>Nr,IsIntersect:()=>Kr,IsIterator:()=>jr,IsKind:()=>uo,IsKindOf:()=>h,IsLiteral:()=>Gt,IsLiteralBoolean:()=>ji,IsLiteralNumber:()=>_r,IsLiteralString:()=>Er,IsLiteralValue:()=>Gr,IsMappedKey:()=>Lr,IsMappedResult:()=>Dr,IsNever:()=>Br,IsNot:()=>Vr,IsNull:()=>qr,IsNumber:()=>Wr,IsObject:()=>vr,IsOptional:()=>Ni,IsPromise:()=>zr,IsProperties:()=>tn,IsReadonly:()=>ki,IsRecord:()=>Hr,IsRecursive:()=>Ei,IsRef:()=>Jr,IsRegExp:()=>Yr,IsSchema:()=>H,IsString:()=>Xr,IsSymbol:()=>Zr,IsTemplateLiteral:()=>Qr,IsThis:()=>eo,IsTransform:()=>to,IsTuple:()=>no,IsUint8Array:()=>oo,IsUndefined:()=>ro,IsUnion:()=>_n,IsUnionLiteral:()=>_i,IsUnknown:()=>so,IsUnsafe:()=>io,IsVoid:()=>ao,TypeGuardUnknownTypeError:()=>Kn});var Kn=class extends z{},Mi=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function Sr(e){try{return new RegExp(e),!0}catch{return!1}}function jn(e){if(!A(e))return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function Cr(e){return En(e)||H(e)}function _t(e){return G(e)||Pt(e)}function M(e){return G(e)||ce(e)}function En(e){return G(e)||Ke(e)}function w(e){return G(e)||A(e)}function Ui(e){return G(e)||A(e)&&jn(e)&&Sr(e)}function Pi(e){return G(e)||A(e)&&jn(e)}function Tr(e){return G(e)||H(e)}function ki(e){return $(e)&&e[Ce]==="Readonly"}function Ni(e){return $(e)&&e[Y]==="Optional"}function Or(e){return h(e,"Any")&&w(e.$id)}function $r(e){return h(e,"Argument")&&ce(e.index)}function wr(e){return h(e,"Array")&&e.type==="array"&&w(e.$id)&&H(e.items)&&M(e.minItems)&&M(e.maxItems)&&En(e.uniqueItems)&&Tr(e.contains)&&M(e.minContains)&&M(e.maxContains)}function Rr(e){return h(e,"AsyncIterator")&&e.type==="AsyncIterator"&&w(e.$id)&&H(e.items)}function Fr(e){return h(e,"BigInt")&&e.type==="bigint"&&w(e.$id)&&_t(e.exclusiveMaximum)&&_t(e.exclusiveMinimum)&&_t(e.maximum)&&_t(e.minimum)&&_t(e.multipleOf)}function Ar(e){return h(e,"Boolean")&&e.type==="boolean"&&w(e.$id)}function Mr(e){return h(e,"Computed")&&A(e.target)&&_(e.parameters)&&e.parameters.every(t=>H(t))}function Ur(e){return h(e,"Constructor")&&e.type==="Constructor"&&w(e.$id)&&_(e.parameters)&&e.parameters.every(t=>H(t))&&H(e.returns)}function Pr(e){return h(e,"Date")&&e.type==="Date"&&w(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function kr(e){return h(e,"Function")&&e.type==="Function"&&w(e.$id)&&_(e.parameters)&&e.parameters.every(t=>H(t))&&H(e.returns)}function Ki(e){return h(e,"Import")&&Xt(e,"$defs")&&$(e.$defs)&&tn(e.$defs)&&Xt(e,"$ref")&&A(e.$ref)&&e.$ref in e.$defs}function Nr(e){return h(e,"Integer")&&e.type==="integer"&&w(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function tn(e){return $(e)&&Object.entries(e).every(([t,n])=>jn(t)&&H(n))}function Kr(e){return h(e,"Intersect")&&!(A(e.type)&&e.type!=="object")&&_(e.allOf)&&e.allOf.every(t=>H(t)&&!to(t))&&w(e.type)&&(En(e.unevaluatedProperties)||Tr(e.unevaluatedProperties))&&w(e.$id)}function jr(e){return h(e,"Iterator")&&e.type==="Iterator"&&w(e.$id)&&H(e.items)}function h(e,t){return $(e)&&l in e&&e[l]===t}function Er(e){return Gt(e)&&A(e.const)}function _r(e){return Gt(e)&&ce(e.const)}function ji(e){return Gt(e)&&Ke(e.const)}function Gt(e){return h(e,"Literal")&&w(e.$id)&&Gr(e.const)}function Gr(e){return Ke(e)||ce(e)||A(e)}function Lr(e){return h(e,"MappedKey")&&_(e.keys)&&e.keys.every(t=>ce(t)||A(t))}function Dr(e){return h(e,"MappedResult")&&tn(e.properties)}function Br(e){return h(e,"Never")&&$(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Vr(e){return h(e,"Not")&&H(e.not)}function qr(e){return h(e,"Null")&&e.type==="null"&&w(e.$id)}function Wr(e){return h(e,"Number")&&e.type==="number"&&w(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function vr(e){return h(e,"Object")&&e.type==="object"&&w(e.$id)&&tn(e.properties)&&Cr(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function zr(e){return h(e,"Promise")&&e.type==="Promise"&&w(e.$id)&&H(e.item)}function Hr(e){return h(e,"Record")&&e.type==="object"&&w(e.$id)&&Cr(e.additionalProperties)&&$(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&Sr(n[0])&&$(t.patternProperties)&&H(t.patternProperties[n[0]])})(e)}function Ei(e){return $(e)&&Ie in e&&e[Ie]==="Recursive"}function Jr(e){return h(e,"Ref")&&w(e.$id)&&A(e.$ref)}function Yr(e){return h(e,"RegExp")&&w(e.$id)&&A(e.source)&&A(e.flags)&&M(e.maxLength)&&M(e.minLength)}function Xr(e){return h(e,"String")&&e.type==="string"&&w(e.$id)&&M(e.minLength)&&M(e.maxLength)&&Ui(e.pattern)&&Pi(e.format)}function Zr(e){return h(e,"Symbol")&&e.type==="symbol"&&w(e.$id)}function Qr(e){return h(e,"TemplateLiteral")&&e.type==="string"&&A(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function eo(e){return h(e,"This")&&w(e.$id)&&A(e.$ref)}function to(e){return $(e)&&B in e}function no(e){return h(e,"Tuple")&&e.type==="array"&&w(e.$id)&&ce(e.minItems)&&ce(e.maxItems)&&e.minItems===e.maxItems&&(G(e.items)&&G(e.additionalItems)&&e.minItems===0||_(e.items)&&e.items.every(t=>H(t)))}function ro(e){return h(e,"Undefined")&&e.type==="undefined"&&w(e.$id)}function _i(e){return _n(e)&&e.anyOf.every(t=>Er(t)||_r(t))}function _n(e){return h(e,"Union")&&w(e.$id)&&$(e)&&_(e.anyOf)&&e.anyOf.every(t=>H(t))}function oo(e){return h(e,"Uint8Array")&&e.type==="Uint8Array"&&w(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function so(e){return h(e,"Unknown")&&w(e.$id)}function io(e){return h(e,"Unsafe")}function ao(e){return h(e,"Void")&&e.type==="void"&&w(e.$id)}function uo(e){return $(e)&&l in e&&A(e[l])&&!Mi.includes(e[l])}function H(e){return $(e)&&(Or(e)||$r(e)||wr(e)||Ar(e)||Fr(e)||Rr(e)||Mr(e)||Ur(e)||Pr(e)||kr(e)||Nr(e)||Kr(e)||jr(e)||Gt(e)||Lr(e)||Dr(e)||Br(e)||Vr(e)||qr(e)||Wr(e)||vr(e)||zr(e)||Hr(e)||Jr(e)||Yr(e)||Xr(e)||Zr(e)||Qr(e)||eo(e)||no(e)||ro(e)||_n(e)||oo(e)||so(e)||io(e)||ao(e)||uo(e))}var Gn="(true|false)",Lt="(0|[1-9][0-9]*)",Ln="(.*)",Gi="(?!.*)",Cl=`^${Gn}$`,Ve=`^${Lt}$`,qe=`^${Ln}$`,co=`^${Gi}$`;function mo(e,t){return e.includes(t)}function lo(e){return[...new Set(e)]}function Li(e,t){return e.filter(n=>t.includes(n))}function Di(e,t){return e.reduce((n,r)=>Li(n,r),t)}function po(e){return e.length===1?e[0]:e.length>1?Di(e.slice(1),e[0]):[]}function fo(e){let t=[];for(let n of e)t.push(...n);return t}function We(e){return u({[l]:"Any"},e)}function pt(e,t){return u({[l]:"Array",type:"array",items:e},t)}function go(e){return u({[l]:"Argument",index:e})}function ft(e,t){return u({[l]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function P(e,t,n){return u({[l]:"Computed",target:e,parameters:t},n)}function Bi(e,t){let{[t]:n,...r}=e;return r}function j(e,t){return t.reduce((n,r)=>Bi(n,r),e)}function b(e){return u({[l]:"Never",not:{}},e)}function S(e){return u({[l]:"MappedResult",properties:e})}function gt(e,t,n){return u({[l]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function Pe(e,t,n){return u({[l]:"Function",type:"Function",parameters:e,returns:t},n)}function Dt(e,t){return u({[l]:"Union",anyOf:e},t)}function Vi(e){return e.some(t=>oe(t))}function Io(e){return e.map(t=>oe(t)?qi(t):t)}function qi(e){return j(e,[Y])}function Wi(e,t){return Vi(e)?ee(Dt(Io(e),t)):Dt(Io(e),t)}function ke(e,t){return e.length===1?u(e[0],t):e.length===0?b(t):Wi(e,t)}function T(e,t){return e.length===0?b(t):e.length===1?u(e[0],t):Dt(e,t)}var nn=class extends z{};function vi(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Dn(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function Le(e,t){return Dn(e,t,"(")}function Bt(e,t){return Dn(e,t,")")}function ho(e,t){return Dn(e,t,"|")}function zi(e){if(!(Le(e,0)&&Bt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(Le(e,n)&&(t+=1),Bt(e,n)&&(t-=1),t===0&&n!==e.length-1)return!1;return!0}function Hi(e){return e.slice(1,e.length-1)}function Ji(e){let t=0;for(let n=0;n<e.length;n++)if(Le(e,n)&&(t+=1),Bt(e,n)&&(t-=1),ho(e,n)&&t===0)return!0;return!1}function Yi(e){for(let t=0;t<e.length;t++)if(Le(e,t))return!0;return!1}function Xi(e){let[t,n]=[0,0],r=[];for(let s=0;s<e.length;s++)if(Le(e,s)&&(t+=1),Bt(e,s)&&(t-=1),ho(e,s)&&t===0){let a=e.slice(n,s);a.length>0&&r.push(It(a)),n=s+1}let o=e.slice(n);return o.length>0&&r.push(It(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function Zi(e){function t(o,s){if(!Le(o,s))throw new nn("TemplateLiteralParser: Index must point to open parens");let a=0;for(let m=s;m<o.length;m++)if(Le(o,m)&&(a+=1),Bt(o,m)&&(a-=1),a===0)return[s,m];throw new nn("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,s){for(let a=s;a<o.length;a++)if(Le(o,a))return[s,a];return[s,o.length]}let r=[];for(let o=0;o<e.length;o++)if(Le(e,o)){let[s,a]=t(e,o),m=e.slice(s,a+1);r.push(It(m)),o=a}else{let[s,a]=n(e,o),m=e.slice(s,a);m.length>0&&r.push(It(m)),o=a-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function It(e){return zi(e)?It(Hi(e)):Ji(e)?Xi(e):Yi(e)?Zi(e):{type:"const",const:vi(e)}}function ht(e){return It(e.slice(1,e.length-1))}var Bn=class extends z{};function Qi(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="0"&&e.expr[1].type==="const"&&e.expr[1].const==="[1-9][0-9]*"}function ea(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="true"&&e.expr[1].type==="const"&&e.expr[1].const==="false"}function ta(e){return e.type==="const"&&e.const===".*"}function ot(e){return Qi(e)||ta(e)?!1:ea(e)?!0:e.type==="and"?e.expr.every(t=>ot(t)):e.type==="or"?e.expr.every(t=>ot(t)):e.type==="const"?!0:(()=>{throw new Bn("Unknown expression type")})()}function yo(e){let t=ht(e.pattern);return ot(t)}var Vn=class extends z{};function*xo(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let n of xo(e.slice(1)))yield`${t}${n}`}function*na(e){return yield*xo(e.expr.map(t=>[...Vt(t)]))}function*ra(e){for(let t of e.expr)yield*Vt(t)}function*oa(e){return yield e.const}function*Vt(e){return e.type==="and"?yield*na(e):e.type==="or"?yield*ra(e):e.type==="const"?yield*oa(e):(()=>{throw new Vn("Unknown expression")})()}function rn(e){let t=ht(e.pattern);return ot(t)?[...Vt(t)]:[]}function C(e,t){return u({[l]:"Literal",const:e,type:typeof e},t)}function on(e){return u({[l]:"Boolean",type:"boolean"},e)}function yt(e){return u({[l]:"BigInt",type:"bigint"},e)}function he(e){return u({[l]:"Number",type:"number"},e)}function Ae(e){return u({[l]:"String",type:"string"},e)}function*sa(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield on():t==="number"?yield he():t==="bigint"?yield yt():t==="string"?yield Ae():yield(()=>{let n=t.split("|").map(r=>C(r.trim()));return n.length===0?b():n.length===1?n[0]:ke(n)})()}function*ia(e){if(e[1]!=="{"){let t=C("$"),n=qn(e.slice(1));return yield*[t,...n]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let n=sa(e.slice(2,t)),r=qn(e.slice(t+1));return yield*[...n,...r]}yield C(e)}function*qn(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=C(e.slice(0,t)),r=ia(e.slice(t));return yield*[n,...r]}yield C(e)}function bo(e){return[...qn(e)]}var Wn=class extends z{};function aa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function So(e,t){return de(e)?e.pattern.slice(1,e.pattern.length-1):x(e)?`(${e.anyOf.map(n=>So(n,t)).join("|")})`:Fe(e)?`${t}${Lt}`:Re(e)?`${t}${Lt}`:et(e)?`${t}${Lt}`:_e(e)?`${t}${Ln}`:me(e)?`${t}${aa(e.const.toString())}`:Ee(e)?`${t}${Gn}`:(()=>{throw new Wn(`Unexpected Kind '${e[l]}'`)})()}function vn(e){return`^${e.map(t=>So(t,"")).join("")}$`}function st(e){let n=rn(e).map(r=>C(r));return ke(n)}function sn(e,t){let n=A(e)?vn(bo(e)):vn(e);return u({[l]:"TemplateLiteral",type:"string",pattern:n},t)}function ua(e){return rn(e).map(n=>n.toString())}function ca(e){let t=[];for(let n of e)t.push(...se(n));return t}function ma(e){return[e.toString()]}function se(e){return[...new Set(de(e)?ua(e):x(e)?ca(e.anyOf):me(e)?ma(e.const):Fe(e)?["[number]"]:Re(e)?["[number]"]:[])]}function la(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=ve(e,se(t[o]),n);return r}function da(e,t,n){return la(e,t.properties,n)}function Co(e,t,n){let r=da(e,t,n);return S(r)}function Oo(e,t){return e.map(n=>$o(n,t))}function pa(e){return e.filter(t=>!De(t))}function fa(e,t){return an(pa(Oo(e,t)))}function ga(e){return e.some(t=>De(t))?[]:e}function Ia(e,t){return ke(ga(Oo(e,t)))}function ha(e,t){return t in e?e[t]:t==="[number]"?ke(e):b()}function ya(e,t){return t==="[number]"?e:b()}function xa(e,t){return t in e?e[t]:b()}function $o(e,t){return K(e)?fa(e.allOf,t):x(e)?Ia(e.anyOf,t):pe(e)?ha(e.items??[],t):Te(e)?ya(e.items,t):L(e)?xa(e.properties,t):b()}function zn(e,t){return t.map(n=>$o(e,n))}function To(e,t){return ke(zn(e,t))}function ve(e,t,n){if(E(e)||E(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!fe(e)||!fe(t))throw new z(r);return P("Index",[e,t])}return N(t)?Co(e,t,n):le(t)?wo(e,t,n):u(fe(t)?To(e,se(t)):To(e,t),n)}function ba(e,t,n){return{[t]:ve(e,[t],k(n))}}function Sa(e,t,n){return t.reduce((r,o)=>({...r,...ba(e,o,n)}),{})}function Ca(e,t,n){return Sa(e,t.keys,n)}function wo(e,t,n){let r=Ca(e,t,n);return S(r)}function xt(e,t){return u({[l]:"Iterator",type:"Iterator",items:e},t)}function Ta(e){return globalThis.Object.keys(e).filter(t=>!oe(e[t]))}function Oa(e,t){let n=Ta(e),r=n.length>0?{[l]:"Object",type:"object",required:n,properties:e}:{[l]:"Object",type:"object",properties:e};return u(r,t)}var R=Oa;function un(e,t){return u({[l]:"Promise",type:"Promise",item:e},t)}function $a(e){return u(j(e,[Ce]))}function wa(e){return u({...e,[Ce]:"Readonly"})}function Ra(e,t){return t===!1?$a(e):wa(e)}function ie(e,t){let n=t??!0;return N(e)?Ro(e,n):Ra(e,n)}function Fa(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ie(e[r],t);return n}function Aa(e,t){return Fa(e.properties,t)}function Ro(e,t){let n=Aa(e,t);return S(n)}function ye(e,t){return u(e.length>0?{[l]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[l]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function Fo(e,t){return e in t?xe(e,t[e]):S(t)}function Ma(e){return{[e]:C(e)}}function Ua(e){let t={};for(let n of e)t[n]=C(n);return t}function Pa(e,t){return mo(t,e)?Ma(e):Ua(t)}function ka(e,t){let n=Pa(e,t);return Fo(e,n)}function qt(e,t){return t.map(n=>xe(e,n))}function Na(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=xe(e,t[r]);return n}function xe(e,t){let n={...t};return oe(t)?ee(xe(e,j(t,[Y]))):dt(t)?ie(xe(e,j(t,[Ce]))):N(t)?Fo(e,t.properties):le(t)?ka(e,t.keys):$e(t)?gt(qt(e,t.parameters),xe(e,t.returns),n):we(t)?Pe(qt(e,t.parameters),xe(e,t.returns),n):Qe(t)?ft(xe(e,t.items),n):tt(t)?xt(xe(e,t.items),n):K(t)?te(qt(e,t.allOf),n):x(t)?T(qt(e,t.anyOf),n):pe(t)?ye(qt(e,t.items??[]),n):L(t)?R(Na(e,t.properties),n):Te(t)?pt(xe(e,t.items),n):nt(t)?un(xe(e,t.item),n):t}function Ka(e,t){let n={};for(let r of e)n[r]=xe(r,t);return n}function Ao(e,t,n){let r=fe(e)?se(e):e,o=t({[l]:"MappedKey",keys:r}),s=Ka(r,o);return R(s,n)}function ja(e){return u(j(e,[Y]))}function Ea(e){return u({...e,[Y]:"Optional"})}function _a(e,t){return t===!1?ja(e):Ea(e)}function ee(e,t){let n=t??!0;return N(e)?Mo(e,n):_a(e,n)}function Ga(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ee(e[r],t);return n}function La(e,t){return Ga(e.properties,t)}function Mo(e,t){let n=La(e,t);return S(n)}function Wt(e,t={}){let n=e.every(o=>L(o)),r=fe(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||fe(t.unevaluatedProperties)||n?{...r,[l]:"Intersect",type:"object",allOf:e}:{...r,[l]:"Intersect",allOf:e},t)}function Da(e){return e.every(t=>oe(t))}function Ba(e){return j(e,[Y])}function Uo(e){return e.map(t=>oe(t)?Ba(t):t)}function Va(e,t){return Da(e)?ee(Wt(Uo(e),t)):Wt(Uo(e),t)}function an(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return b(t);if(e.some(n=>Be(n)))throw new Error("Cannot intersect transform types");return Va(e,t)}function te(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return b(t);if(e.some(n=>Be(n)))throw new Error("Cannot intersect transform types");return Wt(e,t)}function Ne(...e){let[t,n]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new z("Ref: $ref must be a string");return u({[l]:"Ref",$ref:t},n)}function qa(e,t){return P("Awaited",[P(e,t)])}function Wa(e){return P("Awaited",[Ne(e)])}function va(e){return te(Po(e))}function za(e){return T(Po(e))}function Ha(e){return bt(e)}function Po(e){return e.map(t=>bt(t))}function bt(e,t){return u(Oe(e)?qa(e.target,e.parameters):K(e)?va(e.allOf):x(e)?za(e.anyOf):nt(e)?Ha(e.item):E(e)?Wa(e.$ref):e,t)}function ko(e){let t=[];for(let n of e)t.push(vt(n));return t}function Ja(e){let t=ko(e);return fo(t)}function Ya(e){let t=ko(e);return po(t)}function Xa(e){return e.map((t,n)=>n.toString())}function Za(e){return["[number]"]}function Qa(e){return globalThis.Object.getOwnPropertyNames(e)}function eu(e){return tu?globalThis.Object.getOwnPropertyNames(e).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function vt(e){return K(e)?Ja(e.allOf):x(e)?Ya(e.anyOf):pe(e)?Xa(e.items??[]):Te(e)?Za(e.items):L(e)?Qa(e.properties):rt(e)?eu(e.patternProperties):[]}var tu=!1;function nu(e,t){return P("KeyOf",[P(e,t)])}function ru(e){return P("KeyOf",[Ne(e)])}function ou(e,t){let n=vt(e),r=su(n),o=ke(r);return u(o,t)}function su(e){return e.map(t=>t==="[number]"?he():C(t))}function St(e,t){return Oe(e)?nu(e.target,e.parameters):E(e)?ru(e.$ref):N(e)?No(e,t):ou(e,t)}function iu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=St(e[r],k(t));return n}function au(e,t){return iu(e.properties,t)}function No(e,t){let n=au(e,t);return S(n)}function uu(e){let t=[];for(let n of e)t.push(...vt(n));return lo(t)}function cu(e){return e.filter(t=>!De(t))}function mu(e,t){let n=[];for(let r of e)n.push(...zn(r,[t]));return cu(n)}function lu(e,t){let n={};for(let r of t)n[r]=an(mu(e,r));return n}function Ko(e,t){let n=uu(e),r=lu(e,n);return R(r,t)}function cn(e){return u({[l]:"Date",type:"Date"},e)}function mn(e){return u({[l]:"Null",type:"null"},e)}function ln(e){return u({[l]:"Symbol",type:"symbol"},e)}function dn(e){return u({[l]:"Undefined",type:"undefined"},e)}function pn(e){return u({[l]:"Uint8Array",type:"Uint8Array"},e)}function ze(e){return u({[l]:"Unknown"},e)}function du(e){return e.map(t=>Hn(t,!1))}function pu(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ie(Hn(e[n],!1));return t}function fn(e,t){return t===!0?e:ie(e)}function Hn(e,t){return Rn(e)?fn(We(),t):An(e)?fn(We(),t):_(e)?ie(ye(du(e))):je(e)?pn():Ze(e)?cn():$(e)?fn(R(pu(e)),t):Fn(e)?fn(Pe([],ze()),t):G(e)?dn():Mn(e)?mn():Un(e)?ln():Pt(e)?yt():ce(e)?C(e):Ke(e)?C(e):A(e)?C(e):R({})}function jo(e,t){return u(Hn(e,!0),t)}function Eo(e,t){return $e(e)?ye(e.parameters,t):b(t)}function _o(e,t){if(G(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(s=>isNaN(s)).map(s=>e[s]),o=[...new Set(n)].map(s=>C(s));return T(o,{...t,[Ie]:"Enum"})}var Yn=class extends z{},c;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(c||(c={}));function be(e){return e===c.False?e:c.True}function Ct(e){throw new Yn(e)}function V(e){return i.IsNever(e)||i.IsIntersect(e)||i.IsUnion(e)||i.IsUnknown(e)||i.IsAny(e)}function q(e,t){return i.IsNever(t)?Wo(e,t):i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsUnknown(t)?Jo(e,t):i.IsAny(t)?Qn(e,t):Ct("StructuralRight")}function Qn(e,t){return c.True}function fu(e,t){return i.IsIntersect(t)?gn(e,t):i.IsUnion(t)&&t.anyOf.some(n=>i.IsAny(n)||i.IsUnknown(n))?c.True:i.IsUnion(t)?c.Union:i.IsUnknown(t)||i.IsAny(t)?c.True:c.Union}function gu(e,t){return i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:i.IsNever(e)?c.True:c.False}function Iu(e,t){return i.IsObject(t)&&In(t)?c.True:V(t)?q(e,t):i.IsArray(t)?be(F(e.items,t.items)):c.False}function hu(e,t){return V(t)?q(e,t):i.IsAsyncIterator(t)?be(F(e.items,t.items)):c.False}function yu(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsBigInt(t)?c.True:c.False}function Vo(e,t){return i.IsLiteralBoolean(e)||i.IsBoolean(e)?c.True:c.False}function xu(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsBoolean(t)?c.True:c.False}function bu(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsConstructor(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>be(F(t.parameters[r],n))===c.True)?be(F(e.returns,t.returns)):c.False:c.False}function Su(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsDate(t)?c.True:c.False}function Cu(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsFunction(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>be(F(t.parameters[r],n))===c.True)?be(F(e.returns,t.returns)):c.False:c.False}function qo(e,t){return i.IsLiteral(e)&&Q.IsNumber(e.const)||i.IsNumber(e)||i.IsInteger(e)?c.True:c.False}function Tu(e,t){return i.IsInteger(t)||i.IsNumber(t)?c.True:V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):c.False}function gn(e,t){return t.allOf.every(n=>F(e,n)===c.True)?c.True:c.False}function Ou(e,t){return e.allOf.some(n=>F(n,t)===c.True)?c.True:c.False}function $u(e,t){return V(t)?q(e,t):i.IsIterator(t)?be(F(e.items,t.items)):c.False}function wu(e,t){return i.IsLiteral(t)&&t.const===e.const?c.True:V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsString(t)?Ho(e,t):i.IsNumber(t)?vo(e,t):i.IsInteger(t)?qo(e,t):i.IsBoolean(t)?Vo(e,t):c.False}function Wo(e,t){return c.False}function Ru(e,t){return c.True}function Go(e){let[t,n]=[e,0];for(;i.IsNot(t);)t=t.not,n+=1;return n%2===0?t:ze()}function Fu(e,t){return i.IsNot(e)?F(Go(e),t):i.IsNot(t)?F(e,Go(t)):Ct("Invalid fallthrough for Not")}function Au(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsNull(t)?c.True:c.False}function vo(e,t){return i.IsLiteralNumber(e)||i.IsNumber(e)||i.IsInteger(e)?c.True:c.False}function Mu(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsInteger(t)||i.IsNumber(t)?c.True:c.False}function ae(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Lo(e){return In(e)}function Do(e){return ae(e,0)||ae(e,1)&&"description"in e.properties&&i.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(i.IsString(e.properties.description.anyOf[0])&&i.IsUndefined(e.properties.description.anyOf[1])||i.IsString(e.properties.description.anyOf[1])&&i.IsUndefined(e.properties.description.anyOf[0]))}function Jn(e){return ae(e,0)}function Bo(e){return ae(e,0)}function Uu(e){return ae(e,0)}function Pu(e){return ae(e,0)}function ku(e){return In(e)}function Nu(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&be(F(e.properties.length,t))===c.True}function Ku(e){return ae(e,0)}function In(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&be(F(e.properties.length,t))===c.True}function ju(e){let t=Pe([We()],We());return ae(e,0)||ae(e,1)&&"then"in e.properties&&be(F(e.properties.then,t))===c.True}function zo(e,t){return F(e,t)===c.False||i.IsOptional(e)&&!i.IsOptional(t)?c.False:c.True}function ne(e,t){return i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:i.IsNever(e)||i.IsLiteralString(e)&&Lo(t)||i.IsLiteralNumber(e)&&Jn(t)||i.IsLiteralBoolean(e)&&Bo(t)||i.IsSymbol(e)&&Do(t)||i.IsBigInt(e)&&Uu(t)||i.IsString(e)&&Lo(t)||i.IsSymbol(e)&&Do(t)||i.IsNumber(e)&&Jn(t)||i.IsInteger(e)&&Jn(t)||i.IsBoolean(e)&&Bo(t)||i.IsUint8Array(e)&&ku(t)||i.IsDate(e)&&Pu(t)||i.IsConstructor(e)&&Ku(t)||i.IsFunction(e)&&Nu(t)?c.True:i.IsRecord(e)&&i.IsString(Xn(e))?t[Ie]==="Record"?c.True:c.False:i.IsRecord(e)&&i.IsNumber(Xn(e))&&ae(t,0)?c.True:c.False}function Eu(e,t){return V(t)?q(e,t):i.IsRecord(t)?Se(e,t):i.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!i.IsOptional(t.properties[n]))return c.False;if(i.IsOptional(t.properties[n]))return c.True;if(zo(e.properties[n],t.properties[n])===c.False)return c.False}return c.True})():c.False}function _u(e,t){return V(t)?q(e,t):i.IsObject(t)&&ju(t)?c.True:i.IsPromise(t)?be(F(e.item,t.item)):c.False}function Xn(e){return Ve in e.patternProperties?he():qe in e.patternProperties?Ae():Ct("Unknown record key pattern")}function Zn(e){return Ve in e.patternProperties?e.patternProperties[Ve]:qe in e.patternProperties?e.patternProperties[qe]:Ct("Unable to get record value schema")}function Se(e,t){let[n,r]=[Xn(t),Zn(t)];return i.IsLiteralString(e)&&i.IsNumber(n)&&be(F(e,r))===c.True?c.True:i.IsUint8Array(e)&&i.IsNumber(n)||i.IsString(e)&&i.IsNumber(n)||i.IsArray(e)&&i.IsNumber(n)?F(e,r):i.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(zo(r,e.properties[o])===c.False)return c.False;return c.True})():c.False}function Gu(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?F(Zn(e),Zn(t)):c.False}function Lu(e,t){let n=i.IsRegExp(e)?Ae():e,r=i.IsRegExp(t)?Ae():t;return F(n,r)}function Ho(e,t){return i.IsLiteral(e)&&Q.IsString(e.const)||i.IsString(e)?c.True:c.False}function Du(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsString(t)?c.True:c.False}function Bu(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsSymbol(t)?c.True:c.False}function Vu(e,t){return i.IsTemplateLiteral(e)?F(st(e),t):i.IsTemplateLiteral(t)?F(e,st(t)):Ct("Invalid fallthrough for TemplateLiteral")}function qu(e,t){return i.IsArray(t)&&e.items!==void 0&&e.items.every(n=>F(n,t.items)===c.True)}function Wu(e,t){return i.IsNever(e)?c.True:i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:c.False}function vu(e,t){return V(t)?q(e,t):i.IsObject(t)&&In(t)||i.IsArray(t)&&qu(e,t)?c.True:i.IsTuple(t)?Q.IsUndefined(e.items)&&!Q.IsUndefined(t.items)||!Q.IsUndefined(e.items)&&Q.IsUndefined(t.items)?c.False:Q.IsUndefined(e.items)&&!Q.IsUndefined(t.items)||e.items.every((n,r)=>F(n,t.items[r])===c.True)?c.True:c.False:c.False}function zu(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsUint8Array(t)?c.True:c.False}function Hu(e,t){return V(t)?q(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsVoid(t)?Xu(e,t):i.IsUndefined(t)?c.True:c.False}function er(e,t){return t.anyOf.some(n=>F(e,n)===c.True)?c.True:c.False}function Ju(e,t){return e.anyOf.every(n=>F(n,t)===c.True)?c.True:c.False}function Jo(e,t){return c.True}function Yu(e,t){return i.IsNever(t)?Wo(e,t):i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsAny(t)?Qn(e,t):i.IsString(t)?Ho(e,t):i.IsNumber(t)?vo(e,t):i.IsInteger(t)?qo(e,t):i.IsBoolean(t)?Vo(e,t):i.IsArray(t)?gu(e,t):i.IsTuple(t)?Wu(e,t):i.IsObject(t)?ne(e,t):i.IsUnknown(t)?c.True:c.False}function Xu(e,t){return i.IsUndefined(e)||i.IsUndefined(e)?c.True:c.False}function Zu(e,t){return i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsUnknown(t)?Jo(e,t):i.IsAny(t)?Qn(e,t):i.IsObject(t)?ne(e,t):i.IsVoid(t)?c.True:c.False}function F(e,t){return i.IsTemplateLiteral(e)||i.IsTemplateLiteral(t)?Vu(e,t):i.IsRegExp(e)||i.IsRegExp(t)?Lu(e,t):i.IsNot(e)||i.IsNot(t)?Fu(e,t):i.IsAny(e)?fu(e,t):i.IsArray(e)?Iu(e,t):i.IsBigInt(e)?yu(e,t):i.IsBoolean(e)?xu(e,t):i.IsAsyncIterator(e)?hu(e,t):i.IsConstructor(e)?bu(e,t):i.IsDate(e)?Su(e,t):i.IsFunction(e)?Cu(e,t):i.IsInteger(e)?Tu(e,t):i.IsIntersect(e)?Ou(e,t):i.IsIterator(e)?$u(e,t):i.IsLiteral(e)?wu(e,t):i.IsNever(e)?Ru(e,t):i.IsNull(e)?Au(e,t):i.IsNumber(e)?Mu(e,t):i.IsObject(e)?Eu(e,t):i.IsRecord(e)?Gu(e,t):i.IsString(e)?Du(e,t):i.IsSymbol(e)?Bu(e,t):i.IsTuple(e)?vu(e,t):i.IsPromise(e)?_u(e,t):i.IsUint8Array(e)?zu(e,t):i.IsUndefined(e)?Hu(e,t):i.IsUnion(e)?Ju(e,t):i.IsUnknown(e)?Yu(e,t):i.IsVoid(e)?Zu(e,t):Ct(`Unknown left type operand '${e[l]}'`)}function He(e,t){return F(e,t)}function Qu(e,t,n,r,o){let s={};for(let a of globalThis.Object.getOwnPropertyNames(e))s[a]=Tt(e[a],t,n,r,k(o));return s}function ec(e,t,n,r,o){return Qu(e.properties,t,n,r,o)}function Yo(e,t,n,r,o){let s=ec(e,t,n,r,o);return S(s)}function tc(e,t,n,r){let o=He(e,t);return o===c.Union?T([n,r]):o===c.True?n:r}function Tt(e,t,n,r,o){return N(e)?Yo(e,t,n,r,o):le(e)?u(Xo(e,t,n,r,o)):u(tc(e,t,n,r),o)}function nc(e,t,n,r,o){return{[e]:Tt(C(e),t,n,r,k(o))}}function rc(e,t,n,r,o){return e.reduce((s,a)=>({...s,...nc(a,t,n,r,o)}),{})}function oc(e,t,n,r,o){return rc(e.keys,t,n,r,o)}function Xo(e,t,n,r,o){let s=oc(e,t,n,r,o);return S(s)}function Zo(e,t){return Ot(st(e),t)}function sc(e,t){let n=e.filter(r=>He(r,t)===c.False);return n.length===1?n[0]:T(n)}function Ot(e,t,n={}){return de(e)?u(Zo(e,t),n):N(e)?u(Qo(e,t),n):u(x(e)?sc(e.anyOf,t):He(e,t)!==c.False?b():e,n)}function ic(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ot(e[r],t);return n}function ac(e,t){return ic(e.properties,t)}function Qo(e,t){let n=ac(e,t);return S(n)}function es(e,t){return $t(st(e),t)}function uc(e,t){let n=e.filter(r=>He(r,t)!==c.False);return n.length===1?n[0]:T(n)}function $t(e,t,n){return de(e)?u(es(e,t),n):N(e)?u(ts(e,t),n):u(x(e)?uc(e.anyOf,t):He(e,t)!==c.False?e:b(),n)}function cc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=$t(e[r],t);return n}function mc(e,t){return cc(e.properties,t)}function ts(e,t){let n=mc(e,t);return S(n)}function ns(e,t){return $e(e)?u(e.returns,t):b(t)}function hn(e){return ie(ee(e))}function it(e,t,n){return u({[l]:"Record",type:"object",patternProperties:{[e]:t}},n)}function tr(e,t,n){let r={};for(let o of e)r[o]=t;return R(r,{...n,[Ie]:"Record"})}function lc(e,t,n){return yo(e)?tr(se(e),t,n):it(e.pattern,t,n)}function dc(e,t,n){return tr(se(T(e)),t,n)}function pc(e,t,n){return tr([e.toString()],t,n)}function fc(e,t,n){return it(e.source,t,n)}function gc(e,t,n){let r=G(e.pattern)?qe:e.pattern;return it(r,t,n)}function Ic(e,t,n){return it(qe,t,n)}function hc(e,t,n){return it(co,t,n)}function yc(e,t,n){return R({true:t,false:t},n)}function xc(e,t,n){return it(Ve,t,n)}function bc(e,t,n){return it(Ve,t,n)}function yn(e,t,n={}){return x(e)?dc(e.anyOf,t,n):de(e)?lc(e,t,n):me(e)?pc(e.const,t,n):Ee(e)?yc(e,t,n):Re(e)?xc(e,t,n):Fe(e)?bc(e,t,n):Nn(e)?fc(e,t,n):_e(e)?gc(e,t,n):Pn(e)?Ic(e,t,n):De(e)?hc(e,t,n):b(n)}function xn(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function rs(e){let t=xn(e);return t===qe?Ae():t===Ve?he():Ae({pattern:t})}function bn(e){return e.patternProperties[xn(e)]}function Sc(e,t){return t.parameters=zt(e,t.parameters),t.returns=Me(e,t.returns),t}function Cc(e,t){return t.parameters=zt(e,t.parameters),t.returns=Me(e,t.returns),t}function Tc(e,t){return t.allOf=zt(e,t.allOf),t}function Oc(e,t){return t.anyOf=zt(e,t.anyOf),t}function $c(e,t){return G(t.items)||(t.items=zt(e,t.items)),t}function wc(e,t){return t.items=Me(e,t.items),t}function Rc(e,t){return t.items=Me(e,t.items),t}function Fc(e,t){return t.items=Me(e,t.items),t}function Ac(e,t){return t.item=Me(e,t.item),t}function Mc(e,t){let n=Nc(e,t.properties);return{...t,...R(n)}}function Uc(e,t){let n=Me(e,rs(t)),r=Me(e,bn(t)),o=yn(n,r);return{...t,...o}}function Pc(e,t){return t.index in e?e[t.index]:ze()}function kc(e,t){let n=dt(t),r=oe(t),o=Me(e,t);return n&&r?hn(o):n&&!r?ie(o):!n&&r?ee(o):o}function Nc(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:kc(e,t[r])}),{})}function zt(e,t){return t.map(n=>Me(e,n))}function Me(e,t){return $e(t)?Sc(e,t):we(t)?Cc(e,t):K(t)?Tc(e,t):x(t)?Oc(e,t):pe(t)?$c(e,t):Te(t)?wc(e,t):Qe(t)?Rc(e,t):tt(t)?Fc(e,t):nt(t)?Ac(e,t):L(t)?Mc(e,t):rt(t)?Uc(e,t):kn(t)?Pc(e,t):t}function os(e,t){return Me(t,lt(e))}function ss(e){return u({[l]:"Integer",type:"integer"},e)}function Kc(e,t,n){return{[e]:Ue(C(e),t,k(n))}}function jc(e,t,n){return e.reduce((o,s)=>({...o,...Kc(s,t,n)}),{})}function Ec(e,t,n){return jc(e.keys,t,n)}function is(e,t,n){let r=Ec(e,t,n);return S(r)}function _c(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function Gc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function Lc(e){return e.toUpperCase()}function Dc(e){return e.toLowerCase()}function Bc(e,t,n){let r=ht(e.pattern);if(!ot(r))return{...e,pattern:as(e.pattern,t)};let a=[...Vt(r)].map(g=>C(g)),m=us(a,t),p=T(m);return sn([p],n)}function as(e,t){return typeof e=="string"?t==="Uncapitalize"?_c(e):t==="Capitalize"?Gc(e):t==="Uppercase"?Lc(e):t==="Lowercase"?Dc(e):e:e.toString()}function us(e,t){return e.map(n=>Ue(n,t))}function Ue(e,t,n={}){return le(e)?is(e,t,n):de(e)?Bc(e,t,n):x(e)?T(us(e.anyOf,t),n):me(e)?C(as(e.const,t),n):u(e,n)}function cs(e,t={}){return Ue(e,"Capitalize",t)}function ms(e,t={}){return Ue(e,"Lowercase",t)}function ls(e,t={}){return Ue(e,"Uncapitalize",t)}function ds(e,t={}){return Ue(e,"Uppercase",t)}function Vc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Je(e[o],t,k(n));return r}function qc(e,t,n){return Vc(e.properties,t,n)}function ps(e,t,n){let r=qc(e,t,n);return S(r)}function Wc(e,t){return e.map(n=>nr(n,t))}function vc(e,t){return e.map(n=>nr(n,t))}function zc(e,t){let{[t]:n,...r}=e;return r}function Hc(e,t){return t.reduce((n,r)=>zc(n,r),e)}function Jc(e,t,n){let r=j(e,[B,"$id","required","properties"]),o=Hc(n,t);return R(o,r)}function Yc(e){let t=e.reduce((n,r)=>en(r)?[...n,C(r)]:n,[]);return T(t)}function nr(e,t){return K(e)?te(Wc(e.allOf,t)):x(e)?T(vc(e.anyOf,t)):L(e)?Jc(e,t,e.properties):R({})}function Je(e,t,n){let r=_(t)?Yc(t):t,o=fe(t)?se(t):t,s=E(e),a=E(t);return N(e)?ps(e,o,n):le(t)?fs(e,t,n):s&&a?P("Omit",[e,r],n):!s&&a?P("Omit",[e,r],n):s&&!a?P("Omit",[e,r],n):u({...nr(e,o),...n})}function Xc(e,t,n){return{[t]:Je(e,[t],k(n))}}function Zc(e,t,n){return t.reduce((r,o)=>({...r,...Xc(e,o,n)}),{})}function Qc(e,t,n){return Zc(e,t.keys,n)}function fs(e,t,n){let r=Qc(e,t,n);return S(r)}function em(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ye(e[o],t,k(n));return r}function tm(e,t,n){return em(e.properties,t,n)}function gs(e,t,n){let r=tm(e,t,n);return S(r)}function nm(e,t){return e.map(n=>rr(n,t))}function rm(e,t){return e.map(n=>rr(n,t))}function om(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function sm(e,t,n){let r=j(e,[B,"$id","required","properties"]),o=om(n,t);return R(o,r)}function im(e){let t=e.reduce((n,r)=>en(r)?[...n,C(r)]:n,[]);return T(t)}function rr(e,t){return K(e)?te(nm(e.allOf,t)):x(e)?T(rm(e.anyOf,t)):L(e)?sm(e,t,e.properties):R({})}function Ye(e,t,n){let r=_(t)?im(t):t,o=fe(t)?se(t):t,s=E(e),a=E(t);return N(e)?gs(e,o,n):le(t)?Is(e,t,n):s&&a?P("Pick",[e,r],n):!s&&a?P("Pick",[e,r],n):s&&!a?P("Pick",[e,r],n):u({...rr(e,o),...n})}function am(e,t,n){return{[t]:Ye(e,[t],k(n))}}function um(e,t,n){return t.reduce((r,o)=>({...r,...am(e,o,n)}),{})}function cm(e,t,n){return um(e,t.keys,n)}function Is(e,t,n){let r=cm(e,t,n);return S(r)}function mm(e,t){return P("Partial",[P(e,t)])}function lm(e){return P("Partial",[Ne(e)])}function dm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ee(e[n]);return t}function pm(e,t){let n=j(e,[B,"$id","required","properties"]),r=dm(t);return R(r,n)}function hs(e){return e.map(t=>ys(t))}function ys(e){return Oe(e)?mm(e.target,e.parameters):E(e)?lm(e.$ref):K(e)?te(hs(e.allOf)):x(e)?T(hs(e.anyOf)):L(e)?pm(e,e.properties):et(e)||Ee(e)||Re(e)||me(e)||Kt(e)||Fe(e)||_e(e)||jt(e)||Et(e)?e:R({})}function wt(e,t){return N(e)?xs(e,t):u({...ys(e),...t})}function fm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=wt(e[r],k(t));return n}function gm(e,t){return fm(e.properties,t)}function xs(e,t){let n=gm(e,t);return S(n)}function Im(e,t){return P("Required",[P(e,t)])}function hm(e){return P("Required",[Ne(e)])}function ym(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=j(e[n],[Y]);return t}function xm(e,t){let n=j(e,[B,"$id","required","properties"]),r=ym(t);return R(r,n)}function bs(e){return e.map(t=>Ss(t))}function Ss(e){return Oe(e)?Im(e.target,e.parameters):E(e)?hm(e.$ref):K(e)?te(bs(e.allOf)):x(e)?T(bs(e.anyOf)):L(e)?xm(e,e.properties):et(e)||Ee(e)||Re(e)||me(e)||Kt(e)||Fe(e)||_e(e)||jt(e)||Et(e)?e:R({})}function Rt(e,t){return N(e)?Cs(e,t):u({...Ss(e),...t})}function bm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Rt(e[r],t);return n}function Sm(e,t){return bm(e.properties,t)}function Cs(e,t){let n=Sm(e,t);return S(n)}function Cm(e,t){return t.map(n=>E(n)?or(e,n.$ref):ge(e,n))}function or(e,t){return t in e?E(e[t])?or(e,e[t].$ref):ge(e,e[t]):b()}function Tm(e){return bt(e[0])}function Om(e){return ve(e[0],e[1])}function $m(e){return St(e[0])}function wm(e){return wt(e[0])}function Rm(e){return Je(e[0],e[1])}function Fm(e){return Ye(e[0],e[1])}function Am(e){return Rt(e[0])}function Mm(e,t,n){let r=Cm(e,n);return t==="Awaited"?Tm(r):t==="Index"?Om(r):t==="KeyOf"?$m(r):t==="Partial"?wm(r):t==="Omit"?Rm(r):t==="Pick"?Fm(r):t==="Required"?Am(r):b()}function Um(e,t){return pt(ge(e,t))}function Pm(e,t){return ft(ge(e,t))}function km(e,t,n){return gt(Ht(e,t),ge(e,n))}function Nm(e,t,n){return Pe(Ht(e,t),ge(e,n))}function Km(e,t){return te(Ht(e,t))}function jm(e,t){return xt(ge(e,t))}function Em(e,t){return R(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:ge(e,t[r])}),{}))}function _m(e,t){let[n,r]=[ge(e,bn(t)),xn(t)],o=lt(t);return o.patternProperties[r]=n,o}function Gm(e,t){return E(t)?{...or(e,t.$ref),[B]:t[B]}:t}function Lm(e,t){return ye(Ht(e,t))}function Dm(e,t){return T(Ht(e,t))}function Ht(e,t){return t.map(n=>ge(e,n))}function ge(e,t){return oe(t)?u(ge(e,j(t,[Y])),t):dt(t)?u(ge(e,j(t,[Ce])),t):Be(t)?u(Gm(e,t),t):Te(t)?u(Um(e,t.items),t):Qe(t)?u(Pm(e,t.items),t):Oe(t)?u(Mm(e,t.target,t.parameters)):$e(t)?u(km(e,t.parameters,t.returns),t):we(t)?u(Nm(e,t.parameters,t.returns),t):K(t)?u(Km(e,t.allOf),t):tt(t)?u(jm(e,t.items),t):L(t)?u(Em(e,t.properties),t):rt(t)?u(_m(e,t)):pe(t)?u(Lm(e,t.items||[]),t):x(t)?u(Dm(e,t.anyOf),t):t}function Bm(e,t){return t in e?ge(e,e[t]):b()}function Ts(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:Bm(e,n)}),{})}var sr=class{constructor(t){let n=Ts(t),r=this.WithIdentifiers(n);this.$defs=r}Import(t,n){let r={...this.$defs,[t]:u(this.$defs[t],n)};return u({[l]:"Import",$defs:r,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:{...t[r],$id:r}}),{})}};function Os(e){return new sr(e)}function $s(e,t){return u({[l]:"Not",not:e},t)}function ws(e,t){return we(e)?ye(e.parameters,t):b()}var Vm=0;function Rs(e,t={}){G(t.$id)&&(t.$id=`T${Vm++}`);let n=lt(e({[l]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[Ie]:"Recursive",...n},t)}function Fs(e,t){let n=A(e)?new globalThis.RegExp(e):e;return u({[l]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},t)}function qm(e){return K(e)?e.allOf:x(e)?e.anyOf:pe(e)?e.items??[]:[]}function As(e){return qm(e)}function Ms(e,t){return we(e)?u(e.returns,t):b(t)}var ir=class{constructor(t){this.schema=t}Decode(t){return new ar(this.schema,t)}},ar=class{constructor(t,n){this.schema=t,this.decode=n}EncodeTransform(t,n){let s={Encode:a=>n[B].Encode(t(a)),Decode:a=>this.decode(n[B].Decode(a))};return{...n,[B]:s}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[B]:r}}Encode(t){return Be(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function Us(e){return new ir(e)}function Ps(e={}){return u({[l]:e[l]??"Unsafe"},e)}function ks(e){return u({[l]:"Void",type:"void"},e)}var ur={};Yt(ur,{Any:()=>We,Argument:()=>go,Array:()=>pt,AsyncIterator:()=>ft,Awaited:()=>bt,BigInt:()=>yt,Boolean:()=>on,Capitalize:()=>cs,Composite:()=>Ko,Const:()=>jo,Constructor:()=>gt,ConstructorParameters:()=>Eo,Date:()=>cn,Enum:()=>_o,Exclude:()=>Ot,Extends:()=>Tt,Extract:()=>$t,Function:()=>Pe,Index:()=>ve,InstanceType:()=>ns,Instantiate:()=>os,Integer:()=>ss,Intersect:()=>te,Iterator:()=>xt,KeyOf:()=>St,Literal:()=>C,Lowercase:()=>ms,Mapped:()=>Ao,Module:()=>Os,Never:()=>b,Not:()=>$s,Null:()=>mn,Number:()=>he,Object:()=>R,Omit:()=>Je,Optional:()=>ee,Parameters:()=>ws,Partial:()=>wt,Pick:()=>Ye,Promise:()=>un,Readonly:()=>ie,ReadonlyOptional:()=>hn,Record:()=>yn,Recursive:()=>Rs,Ref:()=>Ne,RegExp:()=>Fs,Required:()=>Rt,Rest:()=>As,ReturnType:()=>Ms,String:()=>Ae,Symbol:()=>ln,TemplateLiteral:()=>sn,Transform:()=>Us,Tuple:()=>ye,Uint8Array:()=>pn,Uncapitalize:()=>ls,Undefined:()=>dn,Union:()=>T,Unknown:()=>ze,Unsafe:()=>Ps,Uppercase:()=>ds,Void:()=>ks});var f=ur;var d=null,at=null,U={maxSessions:5,defaultBudgetUsd:5,idleTimeoutMinutes:30,maxPersistedSessions:50,maxAutoResponds:10};function Ns(e){U={maxSessions:e.maxSessions??5,defaultBudgetUsd:e.defaultBudgetUsd??5,defaultModel:e.defaultModel,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??30,maxPersistedSessions:e.maxPersistedSessions??50,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10}}function cr(e){d=e}function mr(e){at=e}function X(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channel&&e?.chatId)return`${e.channel}|${e.chatId}`;if(e?.channel&&e?.senderId)return`${e.channel}|${e.senderId}`;if(e?.id&&/^-?\d+$/.test(String(e.id)))return`telegram|${e.id}`;if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);let n=U.fallbackChannel??"unknown";return console.log(`[resolveOriginChannel] Could not resolve channel from ctx keys: ${e?Object.keys(e).join(", "):"null"}, using fallback=${n}`),n}function Wm(e){let t=e.split("|");if(t.length>=3&&t[1])return t[1]}function Ks(e){let t=v(e);if(t)return Wm(t)}function v(e){console.log(`[resolveAgentChannel] workdir=${e}, agentChannels=${JSON.stringify(U.agentChannels)}`);let t=U.agentChannels;if(!t)return;let n=s=>s.replace(/\/+$/,""),r=n(e),o=Object.entries(t).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of o)if(r===n(s)||r.startsWith(n(s)+"/"))return a}function Z(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m${r}s`:`${r}s`}var vm=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","i","me","my","we","our","you","your","it","its","he","she","to","of","in","for","on","with","at","by","from","as","into","through","about","that","this","these","those","and","or","but","if","then","so","not","no","please","just","also","very","all","some","any","each","make","write","create","build","implement","add","update"]);function js(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!vm.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var zm={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function Ft(e){let t=zm[e.status]??"\u2753",n=Z(e.duration),r=e.foregroundChannels.size>0?"foreground":"background",o=e.multiTurn?"multi-turn":"single",s=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,a=[`${t} ${e.name} [${e.id}] (${n}) \u2014 ${r}, ${o}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${s}"`];return e.claudeSessionId&&a.push(` \u{1F517} Claude ID: ${e.claudeSessionId}`),e.resumeSessionId&&a.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),a.join(`
|
|
2
|
-
`)}function
|
|
3
|
-
`)}function
|
|
4
|
-
`)}]};let I=e.agentId||
|
|
5
|
-
`)}]};if(
|
|
6
|
-
`)}]}}let
|
|
7
|
-
`)}]};if(!
|
|
8
|
-
`)}]};let ue=d.spawn({prompt:n.prompt,name:n.name,workdir:r,model:n.model||U.defaultModel,maxBudgetUsd:o,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:s,forkSession:n.fork_session,multiTurn:!n.multi_turn_disabled,permissionMode:n.permission_mode,originChannel:m}),Xe=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt
|
|
9
|
-
`)}]}}catch(s){return{content:[{type:"text",text:`Error launching session: ${s.message}`}]}}}}}function
|
|
1
|
+
var ci=Object.create;var Jt=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var li=Object.getOwnPropertyNames;var di=Object.getPrototypeOf,pi=Object.prototype.hasOwnProperty;var Yt=(e,t)=>{for(var n in t)Jt(e,n,{get:t[n],enumerable:!0})},gr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of li(t))!pi.call(e,o)&&o!==n&&Jt(e,o,{get:()=>t[o],enumerable:!(r=mi(t,o))||r.enumerable});return e};var fi=(e,t,n)=>(n=e!=null?ci(di(e)):{},gr(t||!e||!e.__esModule?Jt(n,"default",{value:e,enumerable:!0}):n,e)),gi=e=>gr(Jt({},"__esModule",{value:!0}),e);var ol={};Yt(ol,{register:()=>rl});module.exports=gi(ol);var at=require("fs"),Sn=require("path"),Es=require("os");var Z={};Yt(Z,{HasPropertyKey:()=>Xt,IsArray:()=>L,IsAsyncIterator:()=>Rn,IsBigInt:()=>Ut,IsBoolean:()=>Ke,IsDate:()=>Ze,IsFunction:()=>Fn,IsIterator:()=>An,IsNull:()=>Mn,IsNumber:()=>ce,IsObject:()=>O,IsRegExp:()=>Pt,IsString:()=>A,IsSymbol:()=>Un,IsUint8Array:()=>Ee,IsUndefined:()=>G});function Xt(e,t){return t in e}function Rn(e){return O(e)&&!L(e)&&!Ee(e)&&Symbol.asyncIterator in e}function L(e){return Array.isArray(e)}function Ut(e){return typeof e=="bigint"}function Ke(e){return typeof e=="boolean"}function Ze(e){return e instanceof globalThis.Date}function Fn(e){return typeof e=="function"}function An(e){return O(e)&&!L(e)&&!Ee(e)&&Symbol.iterator in e}function Mn(e){return e===null}function ce(e){return typeof e=="number"}function O(e){return typeof e=="object"&&e!==null}function Pt(e){return e instanceof globalThis.RegExp}function A(e){return typeof e=="string"}function Un(e){return typeof e=="symbol"}function Ee(e){return e instanceof globalThis.Uint8Array}function G(e){return e===void 0}function Ii(e){return e.map(t=>Zt(t))}function hi(e){return new Date(e.getTime())}function yi(e){return new Uint8Array(e)}function xi(e){return new RegExp(e.source,e.flags)}function bi(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Zt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Zt(e[n]);return t}function Zt(e){return L(e)?Ii(e):Ze(e)?hi(e):Ee(e)?yi(e):Pt(e)?xi(e):O(e)?bi(e):e}function k(e){return Zt(e)}function mt(e,t){return t===void 0?k(e):k({...t,...e})}function Ir(e){return e!==null&&typeof e=="object"}function hr(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function yr(e){return e===void 0}function xr(e){return typeof e=="number"}var Qt;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(a,m){return e.ExactOptionalPropertyTypes?m in a:a[m]!==void 0}e.IsExactOptionalProperty=t;function n(a){let m=Ir(a);return e.AllowArrayObject?m:m&&!hr(a)}e.IsObjectLike=n;function r(a){return n(a)&&!(a instanceof Date)&&!(a instanceof Uint8Array)}e.IsRecordLike=r;function o(a){return e.AllowNaN?xr(a):Number.isFinite(a)}e.IsNumberLike=o;function s(a){let m=yr(a);return e.AllowNullVoid?m||a===null:m}e.IsVoidLike=s})(Qt||(Qt={}));function Si(e){return globalThis.Object.freeze(e).map(t=>kt(t))}function Ti(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=kt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=kt(e[n]);return globalThis.Object.freeze(t)}function kt(e){return L(e)?Si(e):Ze(e)?e:Ee(e)?e:Pt(e)?e:O(e)?Ti(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(Qt.InstanceMode){case"freeze":return kt(n);case"clone":return k(n);default:return n}}var W=class extends Error{constructor(t){super(t)}};var V=Symbol.for("TypeBox.Transform"),Te=Symbol.for("TypeBox.Readonly"),J=Symbol.for("TypeBox.Optional"),Ie=Symbol.for("TypeBox.Hint"),l=Symbol.for("TypeBox.Kind");function lt(e){return O(e)&&e[Te]==="Readonly"}function oe(e){return O(e)&&e[J]==="Optional"}function Pn(e){return y(e,"Any")}function kn(e){return y(e,"Argument")}function Ce(e){return y(e,"Array")}function Qe(e){return y(e,"AsyncIterator")}function et(e){return y(e,"BigInt")}function je(e){return y(e,"Boolean")}function $e(e){return y(e,"Computed")}function Oe(e){return y(e,"Constructor")}function Ci(e){return y(e,"Date")}function we(e){return y(e,"Function")}function Re(e){return y(e,"Integer")}function K(e){return y(e,"Intersect")}function tt(e){return y(e,"Iterator")}function y(e,t){return O(e)&&l in e&&e[l]===t}function en(e){return Ke(e)||ce(e)||A(e)}function me(e){return y(e,"Literal")}function le(e){return y(e,"MappedKey")}function N(e){return y(e,"MappedResult")}function De(e){return y(e,"Never")}function $i(e){return y(e,"Not")}function Nt(e){return y(e,"Null")}function Fe(e){return y(e,"Number")}function D(e){return y(e,"Object")}function nt(e){return y(e,"Promise")}function rt(e){return y(e,"Record")}function _(e){return y(e,"Ref")}function Nn(e){return y(e,"RegExp")}function _e(e){return y(e,"String")}function Kt(e){return y(e,"Symbol")}function de(e){return y(e,"TemplateLiteral")}function Oi(e){return y(e,"This")}function Be(e){return O(e)&&V in e}function pe(e){return y(e,"Tuple")}function Et(e){return y(e,"Undefined")}function x(e){return y(e,"Union")}function wi(e){return y(e,"Uint8Array")}function Ri(e){return y(e,"Unknown")}function Fi(e){return y(e,"Unsafe")}function Ai(e){return y(e,"Void")}function Mi(e){return O(e)&&l in e&&A(e[l])}function fe(e){return Pn(e)||kn(e)||Ce(e)||je(e)||et(e)||Qe(e)||$e(e)||Oe(e)||Ci(e)||we(e)||Re(e)||K(e)||tt(e)||me(e)||le(e)||N(e)||De(e)||$i(e)||Nt(e)||Fe(e)||D(e)||nt(e)||rt(e)||_(e)||Nn(e)||_e(e)||Kt(e)||de(e)||Oi(e)||pe(e)||Et(e)||x(e)||wi(e)||Ri(e)||Fi(e)||Ai(e)||Mi(e)}var i={};Yt(i,{IsAny:()=>Cr,IsArgument:()=>$r,IsArray:()=>Or,IsAsyncIterator:()=>wr,IsBigInt:()=>Rr,IsBoolean:()=>Fr,IsComputed:()=>Ar,IsConstructor:()=>Mr,IsDate:()=>Ur,IsFunction:()=>Pr,IsImport:()=>Ei,IsInteger:()=>kr,IsIntersect:()=>Nr,IsIterator:()=>Kr,IsKind:()=>ao,IsKindOf:()=>h,IsLiteral:()=>_t,IsLiteralBoolean:()=>ji,IsLiteralNumber:()=>jr,IsLiteralString:()=>Er,IsLiteralValue:()=>_r,IsMappedKey:()=>Lr,IsMappedResult:()=>Gr,IsNever:()=>Dr,IsNot:()=>Br,IsNull:()=>Vr,IsNumber:()=>vr,IsObject:()=>qr,IsOptional:()=>Ki,IsPromise:()=>Wr,IsProperties:()=>tn,IsReadonly:()=>Ni,IsRecord:()=>zr,IsRecursive:()=>_i,IsRef:()=>Hr,IsRegExp:()=>Jr,IsSchema:()=>z,IsString:()=>Yr,IsSymbol:()=>Xr,IsTemplateLiteral:()=>Zr,IsThis:()=>Qr,IsTransform:()=>eo,IsTuple:()=>to,IsUint8Array:()=>ro,IsUndefined:()=>no,IsUnion:()=>_n,IsUnionLiteral:()=>Li,IsUnknown:()=>oo,IsUnsafe:()=>so,IsVoid:()=>io,TypeGuardUnknownTypeError:()=>Kn});var Kn=class extends W{},Ui=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function br(e){try{return new RegExp(e),!0}catch{return!1}}function En(e){if(!A(e))return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function Sr(e){return jn(e)||z(e)}function jt(e){return G(e)||Ut(e)}function M(e){return G(e)||ce(e)}function jn(e){return G(e)||Ke(e)}function w(e){return G(e)||A(e)}function Pi(e){return G(e)||A(e)&&En(e)&&br(e)}function ki(e){return G(e)||A(e)&&En(e)}function Tr(e){return G(e)||z(e)}function Ni(e){return O(e)&&e[Te]==="Readonly"}function Ki(e){return O(e)&&e[J]==="Optional"}function Cr(e){return h(e,"Any")&&w(e.$id)}function $r(e){return h(e,"Argument")&&ce(e.index)}function Or(e){return h(e,"Array")&&e.type==="array"&&w(e.$id)&&z(e.items)&&M(e.minItems)&&M(e.maxItems)&&jn(e.uniqueItems)&&Tr(e.contains)&&M(e.minContains)&&M(e.maxContains)}function wr(e){return h(e,"AsyncIterator")&&e.type==="AsyncIterator"&&w(e.$id)&&z(e.items)}function Rr(e){return h(e,"BigInt")&&e.type==="bigint"&&w(e.$id)&&jt(e.exclusiveMaximum)&&jt(e.exclusiveMinimum)&&jt(e.maximum)&&jt(e.minimum)&&jt(e.multipleOf)}function Fr(e){return h(e,"Boolean")&&e.type==="boolean"&&w(e.$id)}function Ar(e){return h(e,"Computed")&&A(e.target)&&L(e.parameters)&&e.parameters.every(t=>z(t))}function Mr(e){return h(e,"Constructor")&&e.type==="Constructor"&&w(e.$id)&&L(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function Ur(e){return h(e,"Date")&&e.type==="Date"&&w(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function Pr(e){return h(e,"Function")&&e.type==="Function"&&w(e.$id)&&L(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function Ei(e){return h(e,"Import")&&Xt(e,"$defs")&&O(e.$defs)&&tn(e.$defs)&&Xt(e,"$ref")&&A(e.$ref)&&e.$ref in e.$defs}function kr(e){return h(e,"Integer")&&e.type==="integer"&&w(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function tn(e){return O(e)&&Object.entries(e).every(([t,n])=>En(t)&&z(n))}function Nr(e){return h(e,"Intersect")&&!(A(e.type)&&e.type!=="object")&&L(e.allOf)&&e.allOf.every(t=>z(t)&&!eo(t))&&w(e.type)&&(jn(e.unevaluatedProperties)||Tr(e.unevaluatedProperties))&&w(e.$id)}function Kr(e){return h(e,"Iterator")&&e.type==="Iterator"&&w(e.$id)&&z(e.items)}function h(e,t){return O(e)&&l in e&&e[l]===t}function Er(e){return _t(e)&&A(e.const)}function jr(e){return _t(e)&&ce(e.const)}function ji(e){return _t(e)&&Ke(e.const)}function _t(e){return h(e,"Literal")&&w(e.$id)&&_r(e.const)}function _r(e){return Ke(e)||ce(e)||A(e)}function Lr(e){return h(e,"MappedKey")&&L(e.keys)&&e.keys.every(t=>ce(t)||A(t))}function Gr(e){return h(e,"MappedResult")&&tn(e.properties)}function Dr(e){return h(e,"Never")&&O(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Br(e){return h(e,"Not")&&z(e.not)}function Vr(e){return h(e,"Null")&&e.type==="null"&&w(e.$id)}function vr(e){return h(e,"Number")&&e.type==="number"&&w(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function qr(e){return h(e,"Object")&&e.type==="object"&&w(e.$id)&&tn(e.properties)&&Sr(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function Wr(e){return h(e,"Promise")&&e.type==="Promise"&&w(e.$id)&&z(e.item)}function zr(e){return h(e,"Record")&&e.type==="object"&&w(e.$id)&&Sr(e.additionalProperties)&&O(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&br(n[0])&&O(t.patternProperties)&&z(t.patternProperties[n[0]])})(e)}function _i(e){return O(e)&&Ie in e&&e[Ie]==="Recursive"}function Hr(e){return h(e,"Ref")&&w(e.$id)&&A(e.$ref)}function Jr(e){return h(e,"RegExp")&&w(e.$id)&&A(e.source)&&A(e.flags)&&M(e.maxLength)&&M(e.minLength)}function Yr(e){return h(e,"String")&&e.type==="string"&&w(e.$id)&&M(e.minLength)&&M(e.maxLength)&&Pi(e.pattern)&&ki(e.format)}function Xr(e){return h(e,"Symbol")&&e.type==="symbol"&&w(e.$id)}function Zr(e){return h(e,"TemplateLiteral")&&e.type==="string"&&A(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Qr(e){return h(e,"This")&&w(e.$id)&&A(e.$ref)}function eo(e){return O(e)&&V in e}function to(e){return h(e,"Tuple")&&e.type==="array"&&w(e.$id)&&ce(e.minItems)&&ce(e.maxItems)&&e.minItems===e.maxItems&&(G(e.items)&&G(e.additionalItems)&&e.minItems===0||L(e.items)&&e.items.every(t=>z(t)))}function no(e){return h(e,"Undefined")&&e.type==="undefined"&&w(e.$id)}function Li(e){return _n(e)&&e.anyOf.every(t=>Er(t)||jr(t))}function _n(e){return h(e,"Union")&&w(e.$id)&&O(e)&&L(e.anyOf)&&e.anyOf.every(t=>z(t))}function ro(e){return h(e,"Uint8Array")&&e.type==="Uint8Array"&&w(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function oo(e){return h(e,"Unknown")&&w(e.$id)}function so(e){return h(e,"Unsafe")}function io(e){return h(e,"Void")&&e.type==="void"&&w(e.$id)}function ao(e){return O(e)&&l in e&&A(e[l])&&!Ui.includes(e[l])}function z(e){return O(e)&&(Cr(e)||$r(e)||Or(e)||Fr(e)||Rr(e)||wr(e)||Ar(e)||Mr(e)||Ur(e)||Pr(e)||kr(e)||Nr(e)||Kr(e)||_t(e)||Lr(e)||Gr(e)||Dr(e)||Br(e)||Vr(e)||vr(e)||qr(e)||Wr(e)||zr(e)||Hr(e)||Jr(e)||Yr(e)||Xr(e)||Zr(e)||Qr(e)||to(e)||no(e)||_n(e)||ro(e)||oo(e)||so(e)||io(e)||ao(e))}var Ln="(true|false)",Lt="(0|[1-9][0-9]*)",Gn="(.*)",Gi="(?!.*)",$l=`^${Ln}$`,Ve=`^${Lt}$`,ve=`^${Gn}$`,uo=`^${Gi}$`;function co(e,t){return e.includes(t)}function mo(e){return[...new Set(e)]}function Di(e,t){return e.filter(n=>t.includes(n))}function Bi(e,t){return e.reduce((n,r)=>Di(n,r),t)}function lo(e){return e.length===1?e[0]:e.length>1?Bi(e.slice(1),e[0]):[]}function po(e){let t=[];for(let n of e)t.push(...n);return t}function qe(e){return u({[l]:"Any"},e)}function dt(e,t){return u({[l]:"Array",type:"array",items:e},t)}function fo(e){return u({[l]:"Argument",index:e})}function pt(e,t){return u({[l]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function P(e,t,n){return u({[l]:"Computed",target:e,parameters:t},n)}function Vi(e,t){let{[t]:n,...r}=e;return r}function E(e,t){return t.reduce((n,r)=>Vi(n,r),e)}function b(e){return u({[l]:"Never",not:{}},e)}function S(e){return u({[l]:"MappedResult",properties:e})}function ft(e,t,n){return u({[l]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function Pe(e,t,n){return u({[l]:"Function",type:"Function",parameters:e,returns:t},n)}function Gt(e,t){return u({[l]:"Union",anyOf:e},t)}function vi(e){return e.some(t=>oe(t))}function go(e){return e.map(t=>oe(t)?qi(t):t)}function qi(e){return E(e,[J])}function Wi(e,t){return vi(e)?Q(Gt(go(e),t)):Gt(go(e),t)}function ke(e,t){return e.length===1?u(e[0],t):e.length===0?b(t):Wi(e,t)}function C(e,t){return e.length===0?b(t):e.length===1?u(e[0],t):Gt(e,t)}var nn=class extends W{};function zi(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Dn(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function Ge(e,t){return Dn(e,t,"(")}function Dt(e,t){return Dn(e,t,")")}function Io(e,t){return Dn(e,t,"|")}function Hi(e){if(!(Ge(e,0)&&Dt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(Ge(e,n)&&(t+=1),Dt(e,n)&&(t-=1),t===0&&n!==e.length-1)return!1;return!0}function Ji(e){return e.slice(1,e.length-1)}function Yi(e){let t=0;for(let n=0;n<e.length;n++)if(Ge(e,n)&&(t+=1),Dt(e,n)&&(t-=1),Io(e,n)&&t===0)return!0;return!1}function Xi(e){for(let t=0;t<e.length;t++)if(Ge(e,t))return!0;return!1}function Zi(e){let[t,n]=[0,0],r=[];for(let s=0;s<e.length;s++)if(Ge(e,s)&&(t+=1),Dt(e,s)&&(t-=1),Io(e,s)&&t===0){let a=e.slice(n,s);a.length>0&&r.push(gt(a)),n=s+1}let o=e.slice(n);return o.length>0&&r.push(gt(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function Qi(e){function t(o,s){if(!Ge(o,s))throw new nn("TemplateLiteralParser: Index must point to open parens");let a=0;for(let m=s;m<o.length;m++)if(Ge(o,m)&&(a+=1),Dt(o,m)&&(a-=1),a===0)return[s,m];throw new nn("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,s){for(let a=s;a<o.length;a++)if(Ge(o,a))return[s,a];return[s,o.length]}let r=[];for(let o=0;o<e.length;o++)if(Ge(e,o)){let[s,a]=t(e,o),m=e.slice(s,a+1);r.push(gt(m)),o=a}else{let[s,a]=n(e,o),m=e.slice(s,a);m.length>0&&r.push(gt(m)),o=a-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function gt(e){return Hi(e)?gt(Ji(e)):Yi(e)?Zi(e):Xi(e)?Qi(e):{type:"const",const:zi(e)}}function It(e){return gt(e.slice(1,e.length-1))}var Bn=class extends W{};function ea(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="0"&&e.expr[1].type==="const"&&e.expr[1].const==="[1-9][0-9]*"}function ta(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="true"&&e.expr[1].type==="const"&&e.expr[1].const==="false"}function na(e){return e.type==="const"&&e.const===".*"}function ot(e){return ea(e)||na(e)?!1:ta(e)?!0:e.type==="and"?e.expr.every(t=>ot(t)):e.type==="or"?e.expr.every(t=>ot(t)):e.type==="const"?!0:(()=>{throw new Bn("Unknown expression type")})()}function ho(e){let t=It(e.pattern);return ot(t)}var Vn=class extends W{};function*yo(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let n of yo(e.slice(1)))yield`${t}${n}`}function*ra(e){return yield*yo(e.expr.map(t=>[...Bt(t)]))}function*oa(e){for(let t of e.expr)yield*Bt(t)}function*sa(e){return yield e.const}function*Bt(e){return e.type==="and"?yield*ra(e):e.type==="or"?yield*oa(e):e.type==="const"?yield*sa(e):(()=>{throw new Vn("Unknown expression")})()}function rn(e){let t=It(e.pattern);return ot(t)?[...Bt(t)]:[]}function T(e,t){return u({[l]:"Literal",const:e,type:typeof e},t)}function on(e){return u({[l]:"Boolean",type:"boolean"},e)}function ht(e){return u({[l]:"BigInt",type:"bigint"},e)}function he(e){return u({[l]:"Number",type:"number"},e)}function Ae(e){return u({[l]:"String",type:"string"},e)}function*ia(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield on():t==="number"?yield he():t==="bigint"?yield ht():t==="string"?yield Ae():yield(()=>{let n=t.split("|").map(r=>T(r.trim()));return n.length===0?b():n.length===1?n[0]:ke(n)})()}function*aa(e){if(e[1]!=="{"){let t=T("$"),n=vn(e.slice(1));return yield*[t,...n]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let n=ia(e.slice(2,t)),r=vn(e.slice(t+1));return yield*[...n,...r]}yield T(e)}function*vn(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=T(e.slice(0,t)),r=aa(e.slice(t));return yield*[n,...r]}yield T(e)}function xo(e){return[...vn(e)]}var qn=class extends W{};function ua(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bo(e,t){return de(e)?e.pattern.slice(1,e.pattern.length-1):x(e)?`(${e.anyOf.map(n=>bo(n,t)).join("|")})`:Fe(e)?`${t}${Lt}`:Re(e)?`${t}${Lt}`:et(e)?`${t}${Lt}`:_e(e)?`${t}${Gn}`:me(e)?`${t}${ua(e.const.toString())}`:je(e)?`${t}${Ln}`:(()=>{throw new qn(`Unexpected Kind '${e[l]}'`)})()}function Wn(e){return`^${e.map(t=>bo(t,"")).join("")}$`}function st(e){let n=rn(e).map(r=>T(r));return ke(n)}function sn(e,t){let n=A(e)?Wn(xo(e)):Wn(e);return u({[l]:"TemplateLiteral",type:"string",pattern:n},t)}function ca(e){return rn(e).map(n=>n.toString())}function ma(e){let t=[];for(let n of e)t.push(...se(n));return t}function la(e){return[e.toString()]}function se(e){return[...new Set(de(e)?ca(e):x(e)?ma(e.anyOf):me(e)?la(e.const):Fe(e)?["[number]"]:Re(e)?["[number]"]:[])]}function da(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=We(e,se(t[o]),n);return r}function pa(e,t,n){return da(e,t.properties,n)}function So(e,t,n){let r=pa(e,t,n);return S(r)}function Co(e,t){return e.map(n=>$o(n,t))}function fa(e){return e.filter(t=>!De(t))}function ga(e,t){return an(fa(Co(e,t)))}function Ia(e){return e.some(t=>De(t))?[]:e}function ha(e,t){return ke(Ia(Co(e,t)))}function ya(e,t){return t in e?e[t]:t==="[number]"?ke(e):b()}function xa(e,t){return t==="[number]"?e:b()}function ba(e,t){return t in e?e[t]:b()}function $o(e,t){return K(e)?ga(e.allOf,t):x(e)?ha(e.anyOf,t):pe(e)?ya(e.items??[],t):Ce(e)?xa(e.items,t):D(e)?ba(e.properties,t):b()}function zn(e,t){return t.map(n=>$o(e,n))}function To(e,t){return ke(zn(e,t))}function We(e,t,n){if(_(e)||_(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!fe(e)||!fe(t))throw new W(r);return P("Index",[e,t])}return N(t)?So(e,t,n):le(t)?Oo(e,t,n):u(fe(t)?To(e,se(t)):To(e,t),n)}function Sa(e,t,n){return{[t]:We(e,[t],k(n))}}function Ta(e,t,n){return t.reduce((r,o)=>({...r,...Sa(e,o,n)}),{})}function Ca(e,t,n){return Ta(e,t.keys,n)}function Oo(e,t,n){let r=Ca(e,t,n);return S(r)}function yt(e,t){return u({[l]:"Iterator",type:"Iterator",items:e},t)}function $a(e){return globalThis.Object.keys(e).filter(t=>!oe(e[t]))}function Oa(e,t){let n=$a(e),r=n.length>0?{[l]:"Object",type:"object",required:n,properties:e}:{[l]:"Object",type:"object",properties:e};return u(r,t)}var R=Oa;function un(e,t){return u({[l]:"Promise",type:"Promise",item:e},t)}function wa(e){return u(E(e,[Te]))}function Ra(e){return u({...e,[Te]:"Readonly"})}function Fa(e,t){return t===!1?wa(e):Ra(e)}function ie(e,t){let n=t??!0;return N(e)?wo(e,n):Fa(e,n)}function Aa(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ie(e[r],t);return n}function Ma(e,t){return Aa(e.properties,t)}function wo(e,t){let n=Ma(e,t);return S(n)}function ye(e,t){return u(e.length>0?{[l]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[l]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function Ro(e,t){return e in t?xe(e,t[e]):S(t)}function Ua(e){return{[e]:T(e)}}function Pa(e){let t={};for(let n of e)t[n]=T(n);return t}function ka(e,t){return co(t,e)?Ua(e):Pa(t)}function Na(e,t){let n=ka(e,t);return Ro(e,n)}function Vt(e,t){return t.map(n=>xe(e,n))}function Ka(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=xe(e,t[r]);return n}function xe(e,t){let n={...t};return oe(t)?Q(xe(e,E(t,[J]))):lt(t)?ie(xe(e,E(t,[Te]))):N(t)?Ro(e,t.properties):le(t)?Na(e,t.keys):Oe(t)?ft(Vt(e,t.parameters),xe(e,t.returns),n):we(t)?Pe(Vt(e,t.parameters),xe(e,t.returns),n):Qe(t)?pt(xe(e,t.items),n):tt(t)?yt(xe(e,t.items),n):K(t)?ee(Vt(e,t.allOf),n):x(t)?C(Vt(e,t.anyOf),n):pe(t)?ye(Vt(e,t.items??[]),n):D(t)?R(Ka(e,t.properties),n):Ce(t)?dt(xe(e,t.items),n):nt(t)?un(xe(e,t.item),n):t}function Ea(e,t){let n={};for(let r of e)n[r]=xe(r,t);return n}function Fo(e,t,n){let r=fe(e)?se(e):e,o=t({[l]:"MappedKey",keys:r}),s=Ea(r,o);return R(s,n)}function ja(e){return u(E(e,[J]))}function _a(e){return u({...e,[J]:"Optional"})}function La(e,t){return t===!1?ja(e):_a(e)}function Q(e,t){let n=t??!0;return N(e)?Ao(e,n):La(e,n)}function Ga(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Q(e[r],t);return n}function Da(e,t){return Ga(e.properties,t)}function Ao(e,t){let n=Da(e,t);return S(n)}function vt(e,t={}){let n=e.every(o=>D(o)),r=fe(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||fe(t.unevaluatedProperties)||n?{...r,[l]:"Intersect",type:"object",allOf:e}:{...r,[l]:"Intersect",allOf:e},t)}function Ba(e){return e.every(t=>oe(t))}function Va(e){return E(e,[J])}function Mo(e){return e.map(t=>oe(t)?Va(t):t)}function va(e,t){return Ba(e)?Q(vt(Mo(e),t)):vt(Mo(e),t)}function an(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return b(t);if(e.some(n=>Be(n)))throw new Error("Cannot intersect transform types");return va(e,t)}function ee(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return b(t);if(e.some(n=>Be(n)))throw new Error("Cannot intersect transform types");return vt(e,t)}function Ne(...e){let[t,n]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new W("Ref: $ref must be a string");return u({[l]:"Ref",$ref:t},n)}function qa(e,t){return P("Awaited",[P(e,t)])}function Wa(e){return P("Awaited",[Ne(e)])}function za(e){return ee(Uo(e))}function Ha(e){return C(Uo(e))}function Ja(e){return xt(e)}function Uo(e){return e.map(t=>xt(t))}function xt(e,t){return u($e(e)?qa(e.target,e.parameters):K(e)?za(e.allOf):x(e)?Ha(e.anyOf):nt(e)?Ja(e.item):_(e)?Wa(e.$ref):e,t)}function Po(e){let t=[];for(let n of e)t.push(qt(n));return t}function Ya(e){let t=Po(e);return po(t)}function Xa(e){let t=Po(e);return lo(t)}function Za(e){return e.map((t,n)=>n.toString())}function Qa(e){return["[number]"]}function eu(e){return globalThis.Object.getOwnPropertyNames(e)}function tu(e){return nu?globalThis.Object.getOwnPropertyNames(e).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function qt(e){return K(e)?Ya(e.allOf):x(e)?Xa(e.anyOf):pe(e)?Za(e.items??[]):Ce(e)?Qa(e.items):D(e)?eu(e.properties):rt(e)?tu(e.patternProperties):[]}var nu=!1;function ru(e,t){return P("KeyOf",[P(e,t)])}function ou(e){return P("KeyOf",[Ne(e)])}function su(e,t){let n=qt(e),r=iu(n),o=ke(r);return u(o,t)}function iu(e){return e.map(t=>t==="[number]"?he():T(t))}function bt(e,t){return $e(e)?ru(e.target,e.parameters):_(e)?ou(e.$ref):N(e)?ko(e,t):su(e,t)}function au(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=bt(e[r],k(t));return n}function uu(e,t){return au(e.properties,t)}function ko(e,t){let n=uu(e,t);return S(n)}function cu(e){let t=[];for(let n of e)t.push(...qt(n));return mo(t)}function mu(e){return e.filter(t=>!De(t))}function lu(e,t){let n=[];for(let r of e)n.push(...zn(r,[t]));return mu(n)}function du(e,t){let n={};for(let r of t)n[r]=an(lu(e,r));return n}function No(e,t){let n=cu(e),r=du(e,n);return R(r,t)}function cn(e){return u({[l]:"Date",type:"Date"},e)}function mn(e){return u({[l]:"Null",type:"null"},e)}function ln(e){return u({[l]:"Symbol",type:"symbol"},e)}function dn(e){return u({[l]:"Undefined",type:"undefined"},e)}function pn(e){return u({[l]:"Uint8Array",type:"Uint8Array"},e)}function ze(e){return u({[l]:"Unknown"},e)}function pu(e){return e.map(t=>Hn(t,!1))}function fu(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ie(Hn(e[n],!1));return t}function fn(e,t){return t===!0?e:ie(e)}function Hn(e,t){return Rn(e)?fn(qe(),t):An(e)?fn(qe(),t):L(e)?ie(ye(pu(e))):Ee(e)?pn():Ze(e)?cn():O(e)?fn(R(fu(e)),t):Fn(e)?fn(Pe([],ze()),t):G(e)?dn():Mn(e)?mn():Un(e)?ln():Ut(e)?ht():ce(e)?T(e):Ke(e)?T(e):A(e)?T(e):R({})}function Ko(e,t){return u(Hn(e,!0),t)}function Eo(e,t){return Oe(e)?ye(e.parameters,t):b(t)}function jo(e,t){if(G(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(s=>isNaN(s)).map(s=>e[s]),o=[...new Set(n)].map(s=>T(s));return C(o,{...t,[Ie]:"Enum"})}var Yn=class extends W{},c;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(c||(c={}));function be(e){return e===c.False?e:c.True}function St(e){throw new Yn(e)}function v(e){return i.IsNever(e)||i.IsIntersect(e)||i.IsUnion(e)||i.IsUnknown(e)||i.IsAny(e)}function q(e,t){return i.IsNever(t)?vo(e,t):i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsUnknown(t)?Ho(e,t):i.IsAny(t)?Qn(e,t):St("StructuralRight")}function Qn(e,t){return c.True}function gu(e,t){return i.IsIntersect(t)?gn(e,t):i.IsUnion(t)&&t.anyOf.some(n=>i.IsAny(n)||i.IsUnknown(n))?c.True:i.IsUnion(t)?c.Union:i.IsUnknown(t)||i.IsAny(t)?c.True:c.Union}function Iu(e,t){return i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:i.IsNever(e)?c.True:c.False}function hu(e,t){return i.IsObject(t)&&In(t)?c.True:v(t)?q(e,t):i.IsArray(t)?be(F(e.items,t.items)):c.False}function yu(e,t){return v(t)?q(e,t):i.IsAsyncIterator(t)?be(F(e.items,t.items)):c.False}function xu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsBigInt(t)?c.True:c.False}function Bo(e,t){return i.IsLiteralBoolean(e)||i.IsBoolean(e)?c.True:c.False}function bu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsBoolean(t)?c.True:c.False}function Su(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsConstructor(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>be(F(t.parameters[r],n))===c.True)?be(F(e.returns,t.returns)):c.False:c.False}function Tu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsDate(t)?c.True:c.False}function Cu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsFunction(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>be(F(t.parameters[r],n))===c.True)?be(F(e.returns,t.returns)):c.False:c.False}function Vo(e,t){return i.IsLiteral(e)&&Z.IsNumber(e.const)||i.IsNumber(e)||i.IsInteger(e)?c.True:c.False}function $u(e,t){return i.IsInteger(t)||i.IsNumber(t)?c.True:v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):c.False}function gn(e,t){return t.allOf.every(n=>F(e,n)===c.True)?c.True:c.False}function Ou(e,t){return e.allOf.some(n=>F(n,t)===c.True)?c.True:c.False}function wu(e,t){return v(t)?q(e,t):i.IsIterator(t)?be(F(e.items,t.items)):c.False}function Ru(e,t){return i.IsLiteral(t)&&t.const===e.const?c.True:v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsString(t)?zo(e,t):i.IsNumber(t)?qo(e,t):i.IsInteger(t)?Vo(e,t):i.IsBoolean(t)?Bo(e,t):c.False}function vo(e,t){return c.False}function Fu(e,t){return c.True}function _o(e){let[t,n]=[e,0];for(;i.IsNot(t);)t=t.not,n+=1;return n%2===0?t:ze()}function Au(e,t){return i.IsNot(e)?F(_o(e),t):i.IsNot(t)?F(e,_o(t)):St("Invalid fallthrough for Not")}function Mu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsNull(t)?c.True:c.False}function qo(e,t){return i.IsLiteralNumber(e)||i.IsNumber(e)||i.IsInteger(e)?c.True:c.False}function Uu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsInteger(t)||i.IsNumber(t)?c.True:c.False}function ae(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Lo(e){return In(e)}function Go(e){return ae(e,0)||ae(e,1)&&"description"in e.properties&&i.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(i.IsString(e.properties.description.anyOf[0])&&i.IsUndefined(e.properties.description.anyOf[1])||i.IsString(e.properties.description.anyOf[1])&&i.IsUndefined(e.properties.description.anyOf[0]))}function Jn(e){return ae(e,0)}function Do(e){return ae(e,0)}function Pu(e){return ae(e,0)}function ku(e){return ae(e,0)}function Nu(e){return In(e)}function Ku(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&be(F(e.properties.length,t))===c.True}function Eu(e){return ae(e,0)}function In(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&be(F(e.properties.length,t))===c.True}function ju(e){let t=Pe([qe()],qe());return ae(e,0)||ae(e,1)&&"then"in e.properties&&be(F(e.properties.then,t))===c.True}function Wo(e,t){return F(e,t)===c.False||i.IsOptional(e)&&!i.IsOptional(t)?c.False:c.True}function te(e,t){return i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:i.IsNever(e)||i.IsLiteralString(e)&&Lo(t)||i.IsLiteralNumber(e)&&Jn(t)||i.IsLiteralBoolean(e)&&Do(t)||i.IsSymbol(e)&&Go(t)||i.IsBigInt(e)&&Pu(t)||i.IsString(e)&&Lo(t)||i.IsSymbol(e)&&Go(t)||i.IsNumber(e)&&Jn(t)||i.IsInteger(e)&&Jn(t)||i.IsBoolean(e)&&Do(t)||i.IsUint8Array(e)&&Nu(t)||i.IsDate(e)&&ku(t)||i.IsConstructor(e)&&Eu(t)||i.IsFunction(e)&&Ku(t)?c.True:i.IsRecord(e)&&i.IsString(Xn(e))?t[Ie]==="Record"?c.True:c.False:i.IsRecord(e)&&i.IsNumber(Xn(e))&&ae(t,0)?c.True:c.False}function _u(e,t){return v(t)?q(e,t):i.IsRecord(t)?Se(e,t):i.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!i.IsOptional(t.properties[n]))return c.False;if(i.IsOptional(t.properties[n]))return c.True;if(Wo(e.properties[n],t.properties[n])===c.False)return c.False}return c.True})():c.False}function Lu(e,t){return v(t)?q(e,t):i.IsObject(t)&&ju(t)?c.True:i.IsPromise(t)?be(F(e.item,t.item)):c.False}function Xn(e){return Ve in e.patternProperties?he():ve in e.patternProperties?Ae():St("Unknown record key pattern")}function Zn(e){return Ve in e.patternProperties?e.patternProperties[Ve]:ve in e.patternProperties?e.patternProperties[ve]:St("Unable to get record value schema")}function Se(e,t){let[n,r]=[Xn(t),Zn(t)];return i.IsLiteralString(e)&&i.IsNumber(n)&&be(F(e,r))===c.True?c.True:i.IsUint8Array(e)&&i.IsNumber(n)||i.IsString(e)&&i.IsNumber(n)||i.IsArray(e)&&i.IsNumber(n)?F(e,r):i.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(Wo(r,e.properties[o])===c.False)return c.False;return c.True})():c.False}function Gu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?F(Zn(e),Zn(t)):c.False}function Du(e,t){let n=i.IsRegExp(e)?Ae():e,r=i.IsRegExp(t)?Ae():t;return F(n,r)}function zo(e,t){return i.IsLiteral(e)&&Z.IsString(e.const)||i.IsString(e)?c.True:c.False}function Bu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsString(t)?c.True:c.False}function Vu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsSymbol(t)?c.True:c.False}function vu(e,t){return i.IsTemplateLiteral(e)?F(st(e),t):i.IsTemplateLiteral(t)?F(e,st(t)):St("Invalid fallthrough for TemplateLiteral")}function qu(e,t){return i.IsArray(t)&&e.items!==void 0&&e.items.every(n=>F(n,t.items)===c.True)}function Wu(e,t){return i.IsNever(e)?c.True:i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:c.False}function zu(e,t){return v(t)?q(e,t):i.IsObject(t)&&In(t)||i.IsArray(t)&&qu(e,t)?c.True:i.IsTuple(t)?Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||!Z.IsUndefined(e.items)&&Z.IsUndefined(t.items)?c.False:Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||e.items.every((n,r)=>F(n,t.items[r])===c.True)?c.True:c.False:c.False}function Hu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsUint8Array(t)?c.True:c.False}function Ju(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsVoid(t)?Zu(e,t):i.IsUndefined(t)?c.True:c.False}function er(e,t){return t.anyOf.some(n=>F(e,n)===c.True)?c.True:c.False}function Yu(e,t){return e.anyOf.every(n=>F(n,t)===c.True)?c.True:c.False}function Ho(e,t){return c.True}function Xu(e,t){return i.IsNever(t)?vo(e,t):i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsAny(t)?Qn(e,t):i.IsString(t)?zo(e,t):i.IsNumber(t)?qo(e,t):i.IsInteger(t)?Vo(e,t):i.IsBoolean(t)?Bo(e,t):i.IsArray(t)?Iu(e,t):i.IsTuple(t)?Wu(e,t):i.IsObject(t)?te(e,t):i.IsUnknown(t)?c.True:c.False}function Zu(e,t){return i.IsUndefined(e)||i.IsUndefined(e)?c.True:c.False}function Qu(e,t){return i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsUnknown(t)?Ho(e,t):i.IsAny(t)?Qn(e,t):i.IsObject(t)?te(e,t):i.IsVoid(t)?c.True:c.False}function F(e,t){return i.IsTemplateLiteral(e)||i.IsTemplateLiteral(t)?vu(e,t):i.IsRegExp(e)||i.IsRegExp(t)?Du(e,t):i.IsNot(e)||i.IsNot(t)?Au(e,t):i.IsAny(e)?gu(e,t):i.IsArray(e)?hu(e,t):i.IsBigInt(e)?xu(e,t):i.IsBoolean(e)?bu(e,t):i.IsAsyncIterator(e)?yu(e,t):i.IsConstructor(e)?Su(e,t):i.IsDate(e)?Tu(e,t):i.IsFunction(e)?Cu(e,t):i.IsInteger(e)?$u(e,t):i.IsIntersect(e)?Ou(e,t):i.IsIterator(e)?wu(e,t):i.IsLiteral(e)?Ru(e,t):i.IsNever(e)?Fu(e,t):i.IsNull(e)?Mu(e,t):i.IsNumber(e)?Uu(e,t):i.IsObject(e)?_u(e,t):i.IsRecord(e)?Gu(e,t):i.IsString(e)?Bu(e,t):i.IsSymbol(e)?Vu(e,t):i.IsTuple(e)?zu(e,t):i.IsPromise(e)?Lu(e,t):i.IsUint8Array(e)?Hu(e,t):i.IsUndefined(e)?Ju(e,t):i.IsUnion(e)?Yu(e,t):i.IsUnknown(e)?Xu(e,t):i.IsVoid(e)?Qu(e,t):St(`Unknown left type operand '${e[l]}'`)}function He(e,t){return F(e,t)}function ec(e,t,n,r,o){let s={};for(let a of globalThis.Object.getOwnPropertyNames(e))s[a]=Tt(e[a],t,n,r,k(o));return s}function tc(e,t,n,r,o){return ec(e.properties,t,n,r,o)}function Jo(e,t,n,r,o){let s=tc(e,t,n,r,o);return S(s)}function nc(e,t,n,r){let o=He(e,t);return o===c.Union?C([n,r]):o===c.True?n:r}function Tt(e,t,n,r,o){return N(e)?Jo(e,t,n,r,o):le(e)?u(Yo(e,t,n,r,o)):u(nc(e,t,n,r),o)}function rc(e,t,n,r,o){return{[e]:Tt(T(e),t,n,r,k(o))}}function oc(e,t,n,r,o){return e.reduce((s,a)=>({...s,...rc(a,t,n,r,o)}),{})}function sc(e,t,n,r,o){return oc(e.keys,t,n,r,o)}function Yo(e,t,n,r,o){let s=sc(e,t,n,r,o);return S(s)}function Xo(e,t){return Ct(st(e),t)}function ic(e,t){let n=e.filter(r=>He(r,t)===c.False);return n.length===1?n[0]:C(n)}function Ct(e,t,n={}){return de(e)?u(Xo(e,t),n):N(e)?u(Zo(e,t),n):u(x(e)?ic(e.anyOf,t):He(e,t)!==c.False?b():e,n)}function ac(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ct(e[r],t);return n}function uc(e,t){return ac(e.properties,t)}function Zo(e,t){let n=uc(e,t);return S(n)}function Qo(e,t){return $t(st(e),t)}function cc(e,t){let n=e.filter(r=>He(r,t)!==c.False);return n.length===1?n[0]:C(n)}function $t(e,t,n){return de(e)?u(Qo(e,t),n):N(e)?u(es(e,t),n):u(x(e)?cc(e.anyOf,t):He(e,t)!==c.False?e:b(),n)}function mc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=$t(e[r],t);return n}function lc(e,t){return mc(e.properties,t)}function es(e,t){let n=lc(e,t);return S(n)}function ts(e,t){return Oe(e)?u(e.returns,t):b(t)}function hn(e){return ie(Q(e))}function it(e,t,n){return u({[l]:"Record",type:"object",patternProperties:{[e]:t}},n)}function tr(e,t,n){let r={};for(let o of e)r[o]=t;return R(r,{...n,[Ie]:"Record"})}function dc(e,t,n){return ho(e)?tr(se(e),t,n):it(e.pattern,t,n)}function pc(e,t,n){return tr(se(C(e)),t,n)}function fc(e,t,n){return tr([e.toString()],t,n)}function gc(e,t,n){return it(e.source,t,n)}function Ic(e,t,n){let r=G(e.pattern)?ve:e.pattern;return it(r,t,n)}function hc(e,t,n){return it(ve,t,n)}function yc(e,t,n){return it(uo,t,n)}function xc(e,t,n){return R({true:t,false:t},n)}function bc(e,t,n){return it(Ve,t,n)}function Sc(e,t,n){return it(Ve,t,n)}function yn(e,t,n={}){return x(e)?pc(e.anyOf,t,n):de(e)?dc(e,t,n):me(e)?fc(e.const,t,n):je(e)?xc(e,t,n):Re(e)?bc(e,t,n):Fe(e)?Sc(e,t,n):Nn(e)?gc(e,t,n):_e(e)?Ic(e,t,n):Pn(e)?hc(e,t,n):De(e)?yc(e,t,n):b(n)}function xn(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function ns(e){let t=xn(e);return t===ve?Ae():t===Ve?he():Ae({pattern:t})}function bn(e){return e.patternProperties[xn(e)]}function Tc(e,t){return t.parameters=Wt(e,t.parameters),t.returns=Me(e,t.returns),t}function Cc(e,t){return t.parameters=Wt(e,t.parameters),t.returns=Me(e,t.returns),t}function $c(e,t){return t.allOf=Wt(e,t.allOf),t}function Oc(e,t){return t.anyOf=Wt(e,t.anyOf),t}function wc(e,t){return G(t.items)||(t.items=Wt(e,t.items)),t}function Rc(e,t){return t.items=Me(e,t.items),t}function Fc(e,t){return t.items=Me(e,t.items),t}function Ac(e,t){return t.items=Me(e,t.items),t}function Mc(e,t){return t.item=Me(e,t.item),t}function Uc(e,t){let n=Kc(e,t.properties);return{...t,...R(n)}}function Pc(e,t){let n=Me(e,ns(t)),r=Me(e,bn(t)),o=yn(n,r);return{...t,...o}}function kc(e,t){return t.index in e?e[t.index]:ze()}function Nc(e,t){let n=lt(t),r=oe(t),o=Me(e,t);return n&&r?hn(o):n&&!r?ie(o):!n&&r?Q(o):o}function Kc(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:Nc(e,t[r])}),{})}function Wt(e,t){return t.map(n=>Me(e,n))}function Me(e,t){return Oe(t)?Tc(e,t):we(t)?Cc(e,t):K(t)?$c(e,t):x(t)?Oc(e,t):pe(t)?wc(e,t):Ce(t)?Rc(e,t):Qe(t)?Fc(e,t):tt(t)?Ac(e,t):nt(t)?Mc(e,t):D(t)?Uc(e,t):rt(t)?Pc(e,t):kn(t)?kc(e,t):t}function rs(e,t){return Me(t,mt(e))}function os(e){return u({[l]:"Integer",type:"integer"},e)}function Ec(e,t,n){return{[e]:Ue(T(e),t,k(n))}}function jc(e,t,n){return e.reduce((o,s)=>({...o,...Ec(s,t,n)}),{})}function _c(e,t,n){return jc(e.keys,t,n)}function ss(e,t,n){let r=_c(e,t,n);return S(r)}function Lc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function Gc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function Dc(e){return e.toUpperCase()}function Bc(e){return e.toLowerCase()}function Vc(e,t,n){let r=It(e.pattern);if(!ot(r))return{...e,pattern:is(e.pattern,t)};let a=[...Bt(r)].map(g=>T(g)),m=as(a,t),p=C(m);return sn([p],n)}function is(e,t){return typeof e=="string"?t==="Uncapitalize"?Lc(e):t==="Capitalize"?Gc(e):t==="Uppercase"?Dc(e):t==="Lowercase"?Bc(e):e:e.toString()}function as(e,t){return e.map(n=>Ue(n,t))}function Ue(e,t,n={}){return le(e)?ss(e,t,n):de(e)?Vc(e,t,n):x(e)?C(as(e.anyOf,t),n):me(e)?T(is(e.const,t),n):u(e,n)}function us(e,t={}){return Ue(e,"Capitalize",t)}function cs(e,t={}){return Ue(e,"Lowercase",t)}function ms(e,t={}){return Ue(e,"Uncapitalize",t)}function ls(e,t={}){return Ue(e,"Uppercase",t)}function vc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Je(e[o],t,k(n));return r}function qc(e,t,n){return vc(e.properties,t,n)}function ds(e,t,n){let r=qc(e,t,n);return S(r)}function Wc(e,t){return e.map(n=>nr(n,t))}function zc(e,t){return e.map(n=>nr(n,t))}function Hc(e,t){let{[t]:n,...r}=e;return r}function Jc(e,t){return t.reduce((n,r)=>Hc(n,r),e)}function Yc(e,t,n){let r=E(e,[V,"$id","required","properties"]),o=Jc(n,t);return R(o,r)}function Xc(e){let t=e.reduce((n,r)=>en(r)?[...n,T(r)]:n,[]);return C(t)}function nr(e,t){return K(e)?ee(Wc(e.allOf,t)):x(e)?C(zc(e.anyOf,t)):D(e)?Yc(e,t,e.properties):R({})}function Je(e,t,n){let r=L(t)?Xc(t):t,o=fe(t)?se(t):t,s=_(e),a=_(t);return N(e)?ds(e,o,n):le(t)?ps(e,t,n):s&&a?P("Omit",[e,r],n):!s&&a?P("Omit",[e,r],n):s&&!a?P("Omit",[e,r],n):u({...nr(e,o),...n})}function Zc(e,t,n){return{[t]:Je(e,[t],k(n))}}function Qc(e,t,n){return t.reduce((r,o)=>({...r,...Zc(e,o,n)}),{})}function em(e,t,n){return Qc(e,t.keys,n)}function ps(e,t,n){let r=em(e,t,n);return S(r)}function tm(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ye(e[o],t,k(n));return r}function nm(e,t,n){return tm(e.properties,t,n)}function fs(e,t,n){let r=nm(e,t,n);return S(r)}function rm(e,t){return e.map(n=>rr(n,t))}function om(e,t){return e.map(n=>rr(n,t))}function sm(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function im(e,t,n){let r=E(e,[V,"$id","required","properties"]),o=sm(n,t);return R(o,r)}function am(e){let t=e.reduce((n,r)=>en(r)?[...n,T(r)]:n,[]);return C(t)}function rr(e,t){return K(e)?ee(rm(e.allOf,t)):x(e)?C(om(e.anyOf,t)):D(e)?im(e,t,e.properties):R({})}function Ye(e,t,n){let r=L(t)?am(t):t,o=fe(t)?se(t):t,s=_(e),a=_(t);return N(e)?fs(e,o,n):le(t)?gs(e,t,n):s&&a?P("Pick",[e,r],n):!s&&a?P("Pick",[e,r],n):s&&!a?P("Pick",[e,r],n):u({...rr(e,o),...n})}function um(e,t,n){return{[t]:Ye(e,[t],k(n))}}function cm(e,t,n){return t.reduce((r,o)=>({...r,...um(e,o,n)}),{})}function mm(e,t,n){return cm(e,t.keys,n)}function gs(e,t,n){let r=mm(e,t,n);return S(r)}function lm(e,t){return P("Partial",[P(e,t)])}function dm(e){return P("Partial",[Ne(e)])}function pm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=Q(e[n]);return t}function fm(e,t){let n=E(e,[V,"$id","required","properties"]),r=pm(t);return R(r,n)}function Is(e){return e.map(t=>hs(t))}function hs(e){return $e(e)?lm(e.target,e.parameters):_(e)?dm(e.$ref):K(e)?ee(Is(e.allOf)):x(e)?C(Is(e.anyOf)):D(e)?fm(e,e.properties):et(e)||je(e)||Re(e)||me(e)||Nt(e)||Fe(e)||_e(e)||Kt(e)||Et(e)?e:R({})}function Ot(e,t){return N(e)?ys(e,t):u({...hs(e),...t})}function gm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ot(e[r],k(t));return n}function Im(e,t){return gm(e.properties,t)}function ys(e,t){let n=Im(e,t);return S(n)}function hm(e,t){return P("Required",[P(e,t)])}function ym(e){return P("Required",[Ne(e)])}function xm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=E(e[n],[J]);return t}function bm(e,t){let n=E(e,[V,"$id","required","properties"]),r=xm(t);return R(r,n)}function xs(e){return e.map(t=>bs(t))}function bs(e){return $e(e)?hm(e.target,e.parameters):_(e)?ym(e.$ref):K(e)?ee(xs(e.allOf)):x(e)?C(xs(e.anyOf)):D(e)?bm(e,e.properties):et(e)||je(e)||Re(e)||me(e)||Nt(e)||Fe(e)||_e(e)||Kt(e)||Et(e)?e:R({})}function wt(e,t){return N(e)?Ss(e,t):u({...bs(e),...t})}function Sm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=wt(e[r],t);return n}function Tm(e,t){return Sm(e.properties,t)}function Ss(e,t){let n=Tm(e,t);return S(n)}function Cm(e,t){return t.map(n=>_(n)?or(e,n.$ref):ge(e,n))}function or(e,t){return t in e?_(e[t])?or(e,e[t].$ref):ge(e,e[t]):b()}function $m(e){return xt(e[0])}function Om(e){return We(e[0],e[1])}function wm(e){return bt(e[0])}function Rm(e){return Ot(e[0])}function Fm(e){return Je(e[0],e[1])}function Am(e){return Ye(e[0],e[1])}function Mm(e){return wt(e[0])}function Um(e,t,n){let r=Cm(e,n);return t==="Awaited"?$m(r):t==="Index"?Om(r):t==="KeyOf"?wm(r):t==="Partial"?Rm(r):t==="Omit"?Fm(r):t==="Pick"?Am(r):t==="Required"?Mm(r):b()}function Pm(e,t){return dt(ge(e,t))}function km(e,t){return pt(ge(e,t))}function Nm(e,t,n){return ft(zt(e,t),ge(e,n))}function Km(e,t,n){return Pe(zt(e,t),ge(e,n))}function Em(e,t){return ee(zt(e,t))}function jm(e,t){return yt(ge(e,t))}function _m(e,t){return R(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:ge(e,t[r])}),{}))}function Lm(e,t){let[n,r]=[ge(e,bn(t)),xn(t)],o=mt(t);return o.patternProperties[r]=n,o}function Gm(e,t){return _(t)?{...or(e,t.$ref),[V]:t[V]}:t}function Dm(e,t){return ye(zt(e,t))}function Bm(e,t){return C(zt(e,t))}function zt(e,t){return t.map(n=>ge(e,n))}function ge(e,t){return oe(t)?u(ge(e,E(t,[J])),t):lt(t)?u(ge(e,E(t,[Te])),t):Be(t)?u(Gm(e,t),t):Ce(t)?u(Pm(e,t.items),t):Qe(t)?u(km(e,t.items),t):$e(t)?u(Um(e,t.target,t.parameters)):Oe(t)?u(Nm(e,t.parameters,t.returns),t):we(t)?u(Km(e,t.parameters,t.returns),t):K(t)?u(Em(e,t.allOf),t):tt(t)?u(jm(e,t.items),t):D(t)?u(_m(e,t.properties),t):rt(t)?u(Lm(e,t)):pe(t)?u(Dm(e,t.items||[]),t):x(t)?u(Bm(e,t.anyOf),t):t}function Vm(e,t){return t in e?ge(e,e[t]):b()}function Ts(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:Vm(e,n)}),{})}var sr=class{constructor(t){let n=Ts(t),r=this.WithIdentifiers(n);this.$defs=r}Import(t,n){let r={...this.$defs,[t]:u(this.$defs[t],n)};return u({[l]:"Import",$defs:r,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:{...t[r],$id:r}}),{})}};function Cs(e){return new sr(e)}function $s(e,t){return u({[l]:"Not",not:e},t)}function Os(e,t){return we(e)?ye(e.parameters,t):b()}var vm=0;function ws(e,t={}){G(t.$id)&&(t.$id=`T${vm++}`);let n=mt(e({[l]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[Ie]:"Recursive",...n},t)}function Rs(e,t){let n=A(e)?new globalThis.RegExp(e):e;return u({[l]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},t)}function qm(e){return K(e)?e.allOf:x(e)?e.anyOf:pe(e)?e.items??[]:[]}function Fs(e){return qm(e)}function As(e,t){return we(e)?u(e.returns,t):b(t)}var ir=class{constructor(t){this.schema=t}Decode(t){return new ar(this.schema,t)}},ar=class{constructor(t,n){this.schema=t,this.decode=n}EncodeTransform(t,n){let s={Encode:a=>n[V].Encode(t(a)),Decode:a=>this.decode(n[V].Decode(a))};return{...n,[V]:s}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[V]:r}}Encode(t){return Be(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function Ms(e){return new ir(e)}function Us(e={}){return u({[l]:e[l]??"Unsafe"},e)}function Ps(e){return u({[l]:"Void",type:"void"},e)}var ur={};Yt(ur,{Any:()=>qe,Argument:()=>fo,Array:()=>dt,AsyncIterator:()=>pt,Awaited:()=>xt,BigInt:()=>ht,Boolean:()=>on,Capitalize:()=>us,Composite:()=>No,Const:()=>Ko,Constructor:()=>ft,ConstructorParameters:()=>Eo,Date:()=>cn,Enum:()=>jo,Exclude:()=>Ct,Extends:()=>Tt,Extract:()=>$t,Function:()=>Pe,Index:()=>We,InstanceType:()=>ts,Instantiate:()=>rs,Integer:()=>os,Intersect:()=>ee,Iterator:()=>yt,KeyOf:()=>bt,Literal:()=>T,Lowercase:()=>cs,Mapped:()=>Fo,Module:()=>Cs,Never:()=>b,Not:()=>$s,Null:()=>mn,Number:()=>he,Object:()=>R,Omit:()=>Je,Optional:()=>Q,Parameters:()=>Os,Partial:()=>Ot,Pick:()=>Ye,Promise:()=>un,Readonly:()=>ie,ReadonlyOptional:()=>hn,Record:()=>yn,Recursive:()=>ws,Ref:()=>Ne,RegExp:()=>Rs,Required:()=>wt,Rest:()=>Fs,ReturnType:()=>As,String:()=>Ae,Symbol:()=>ln,TemplateLiteral:()=>sn,Transform:()=>Ms,Tuple:()=>ye,Uint8Array:()=>pn,Uncapitalize:()=>ms,Undefined:()=>dn,Union:()=>C,Unknown:()=>ze,Unsafe:()=>Us,Uppercase:()=>ls,Void:()=>Ps});var f=ur;var d=null,Wm=null,U={maxSessions:5,defaultBudgetUsd:5,idleTimeoutMinutes:30,maxPersistedSessions:50,maxAutoResponds:10};function ks(e){U={maxSessions:e.maxSessions??5,defaultBudgetUsd:e.defaultBudgetUsd??5,defaultModel:e.defaultModel,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??30,maxPersistedSessions:e.maxPersistedSessions??50,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10}}function cr(e){d=e}function mr(e){Wm=e}function re(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channel&&e?.chatId)return`${e.channel}|${e.chatId}`;if(e?.channel&&e?.senderId)return`${e.channel}|${e.senderId}`;if(e?.id&&/^-?\d+$/.test(String(e.id)))return`telegram|${e.id}`;if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);let n=U.fallbackChannel??"unknown";return console.log(`[resolveOriginChannel] Could not resolve channel from ctx keys: ${e?Object.keys(e).join(", "):"null"}, using fallback=${n}`),n}function zm(e){let t=e.split("|");if(t.length>=3&&t[1])return t[1]}function Ns(e){let t=Y(e);if(t)return zm(t)}function Y(e){console.log(`[resolveAgentChannel] workdir=${e}, agentChannels=${JSON.stringify(U.agentChannels)}`);let t=U.agentChannels;if(!t)return;let n=s=>s.replace(/\/+$/,""),r=n(e),o=Object.entries(t).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of o)if(r===n(s)||r.startsWith(n(s)+"/"))return a}function X(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m${r}s`:`${r}s`}var Hm=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","i","me","my","we","our","you","your","it","its","he","she","to","of","in","for","on","with","at","by","from","as","into","through","about","that","this","these","those","and","or","but","if","then","so","not","no","please","just","also","very","all","some","any","each","make","write","create","build","implement","add","update"]);function Ks(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!Hm.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var Jm={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function Rt(e){let t=Jm[e.status]??"\u2753",n=X(e.duration),r=e.foregroundChannels.size>0?"foreground":"background",o=e.multiTurn?"multi-turn":"single",s=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,a=[`${t} ${e.name} [${e.id}] (${n}) \u2014 ${r}, ${o}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${s}"`];return e.claudeSessionId&&a.push(` \u{1F517} Claude ID: ${e.claudeSessionId}`),e.resumeSessionId&&a.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),a.join(`
|
|
2
|
+
`)}function Ft(e){let t=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,n=d?d.list("running").length:0,{completed:r,failed:o,killed:s}=e.sessionsByStatus,a=r+o+s,m=["\u{1F4CA} Claude Code Plugin Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${n}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${s}`,"",`\u23F1\uFE0F Average duration: ${t>0?X(t):"n/a"}`];if(e.mostExpensive){let p=e.mostExpensive;m.push("","\u{1F3C6} Notable session",` ${p.name} [${p.id}]`,` \u{1F4DD} "${p.prompt}"`)}return m.join(`
|
|
3
|
+
`)}function js(e){return console.log(`[claude-launch] Factory ctx: agentId=${e.agentId}, workspaceDir=${e.workspaceDir}, messageChannel=${e.messageChannel}, agentAccountId=${e.agentAccountId}`),{name:"claude_launch",description:"Launch a Claude Code session in background to execute a development task. Sessions are multi-turn by default \u2014 they stay open for follow-up messages via claude_respond. Set multi_turn_disabled: true for fire-and-forget sessions. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:f.Object({prompt:f.String({description:"The task prompt to execute"}),name:f.Optional(f.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:f.Optional(f.String({description:"Working directory (defaults to cwd)"})),model:f.Optional(f.String({description:"Model name to use"})),max_budget_usd:f.Optional(f.Number({description:"Maximum budget in USD (default 5)"})),system_prompt:f.Optional(f.String({description:"Additional system prompt"})),allowed_tools:f.Optional(f.Array(f.String(),{description:"List of allowed tools"})),resume_session_id:f.Optional(f.String({description:"Claude session ID to resume (from a previous session's claudeSessionId). Continues the conversation from where it left off."})),fork_session:f.Optional(f.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),multi_turn_disabled:f.Optional(f.Boolean({description:"Disable multi-turn mode. By default sessions stay open for follow-up messages. Set to true for fire-and-forget sessions."})),permission_mode:f.Optional(f.Union([f.Literal("default"),f.Literal("plan"),f.Literal("acceptEdits"),f.Literal("bypassPermissions")],{description:"Permission mode for the session. Defaults to plugin config or 'bypassPermissions'."}))}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=n.workdir||e.workspaceDir||U.defaultWorkdir||process.cwd(),o=n.max_budget_usd??U.defaultBudgetUsd??5;try{let s=n.resume_session_id;if(s){let B=d.resolveClaudeSessionId(s);if(!B)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${s}" to a Claude session ID. Use claude_sessions to list available sessions.`}]};s=B}let a;if(e.messageChannel&&e.agentAccountId){let B=e.messageChannel.split("|");B.length>=2&&(a=`${B[0]}|${e.agentAccountId}|${B.slice(1).join("|")}`)}!a&&e.workspaceDir&&(a=Y(e.workspaceDir)),!a&&e.messageChannel&&e.messageChannel.includes("|")&&(a=e.messageChannel);let m=re({id:t},a||Y(r));if(m==="unknown"){let B=Y(r);B&&(m=B)}let p=e.workspaceDir||r,g=(0,Sn.join)(p,"skills","claude-code-autonomy","SKILL.md");if(!(0,at.existsSync)(g))return console.log(`[claude-launch] Autonomy skill not found at ${g} \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 no autonomy skill found.","","No autonomy skill found. You MUST ask the user what level of autonomy they want to give Claude Code sessions. Then create the skill at skills/claude-code-autonomy/ with their preferences. Only then can you launch sessions.","","Do NOT create the skill without asking the user first. Ask them how they want you to handle Claude Code interactions. For example:",'- "Respond to everything automatically except architecture choices"','- "Always ask me before responding"','- "Handle everything yourself, just notify me when done"',"","After the user responds, create the skill:","1. Create directory: skills/claude-code-autonomy/","2. Create SKILL.md with structured rules based on the user's response","3. Create autonomy.md with the user's raw preferences","4. Then re-call claude_launch to start the session.","","The skill MUST also define these notification formats that the agent uses:","","\u{1F44B} [session-name] Important question \u2014 needs your decision:",'> "question text"',"(Used when Claude asks something that requires the user's input \u2014 architecture, destructive ops, ambiguous requirements)","","\u{1F916} [session-name] finished:","Summary of what Claude did, files changed, issues found.","(Used when a session completes \u2014 the agent reads the output and summarizes)","","Note: \u{1F514} Claude asks and \u21A9\uFE0F Responded notifications are handled automatically by the plugin. The skill only needs to define rules for \u{1F44B} (when to forward vs auto-respond) and \u{1F916} (summary format)."].join(`
|
|
4
|
+
`)}]};let I=e.agentId||Ns(p);if(I&&!e.agentId&&console.warn(`[claude-launch] Using resolveAgentId fallback for agentId="${I}" \u2014 this may be an account alias, not the real agent ID`),I){let B=(0,Sn.join)((0,Es.homedir)(),".openclaw","openclaw.json"),ct=!1,pr;try{if((0,at.existsSync)(B)){let On=(0,at.readFileSync)(B,"utf-8"),fr=JSON.parse(On)?.agents?.list;if(Array.isArray(fr)){let wn=fr.find(ui=>ui.id===I);wn&&wn.heartbeat!=null&&(ct=!0,pr=wn.heartbeat.every)}}}catch(On){console.log(`[claude-launch] Failed to read openclaw config at ${B}: ${On.message}`)}if(!ct)return console.log(`[claude-launch] Heartbeat not configured for agent "${I}" \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 no heartbeat configured for this agent.","",'Claude Code sessions require heartbeat to be enabled for automatic "waiting for input" notifications.',"","You must configure the heartbeat FIRST. Here's what to do:","",`1. Edit ~/.openclaw/openclaw.json and add heartbeat config for agent "${I}":`,"",` jq '.agents.list |= map(if .id == "${I}" then . + {"heartbeat": {"every": "60m", "target": "last"}} else . end)' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"","2. Verify the config was applied:","",` cat ~/.openclaw/openclaw.json | jq '.agents.list[] | select(.id == "${I}") | .heartbeat'`,"","3. Launch a Claude Code session to restart the Gateway and wake you back:",""," claude_launch(",' prompt="STEP 1: Restart Gateway to activate heartbeat: openclaw gateway restart'," STEP 2: Wait 5 seconds",` STEP 3: Wake the agent: openclaw agent --agent ${I} --message 'Heartbeat configured, continuing task'`,' STEP 4: Continue the original task: [USER_TASK]",',' name="setup-heartbeat"'," )"].join(`
|
|
5
|
+
`)}]};if(pr==="5s")return console.log(`[claude-launch] Heartbeat interval too short (5s) for agent "${I}" \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 heartbeat interval too short (5s).","","A heartbeat interval of 5s wastes tokens unnecessarily. Targeted agent messages wake you instantly, so the heartbeat interval only affects regular polling.","","Fix the heartbeat interval to 60m:","",` jq '.agents.list |= map(if .id == "${I}" then .heartbeat.every = "60m" else . end)' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"","Then ask the user to restart the gateway. Do NOT restart the gateway yourself \u2014 only the user can do this safely. After the user confirms the restart, retry your launch."].join(`
|
|
6
|
+
`)}]}}let j=(0,Sn.join)(p,"HEARTBEAT.md"),ne=!1;try{if((0,at.existsSync)(j)){let B=(0,at.readFileSync)(j,"utf-8");/^(\s|#.*)*$/.test(B)||(ne=!0)}}catch(B){console.log(`[claude-launch] Failed to read HEARTBEAT.md at ${j}: ${B.message}`)}if(!ne)return console.log(`[claude-launch] HEARTBEAT.md missing or empty at ${j} \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 no HEARTBEAT.md file found or file is effectively empty.","","Claude Code sessions require a HEARTBEAT.md with real content as a safety-net fallback.","The plugin wakes you instantly via targeted agent messages when sessions need attention,","but the heartbeat acts as a 60m backup in case a wake message is lost.","","You must create HEARTBEAT.md FIRST. Here's what to do:","",`1. Create ${p}/HEARTBEAT.md with this content:`,"",`cat > ${p}/HEARTBEAT.md << 'EOF'`,`# Heartbeat ${I} Agent`,"","## Check Claude Code sessions (safety-net fallback)","Note: The plugin sends targeted wake messages instantly when sessions need attention.","This heartbeat is a 60m backup in case a wake message was lost.","","Si des sessions Claude Code sont en attente (waiting for input) :","1. `claude_sessions` pour lister les sessions actives","2. Si session waiting \u2192 `claude_output(session)` pour voir la question","3. Traiter ou notifier l'utilisateur","","Sinon \u2192 HEARTBEAT_OK","EOF","","2. Verify the heartbeat frequency is set to 60m:","",`cat ~/.openclaw/openclaw.json | jq '.agents.list[] | select(.id == "${I}") | .heartbeat.every'`,"",'If NOT "60m", update it:',"",`jq '.agents.list |= map(if .id == "${I}" then .heartbeat.every = "60m" else . end)' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"","3. Launch Claude Code to restart Gateway:",""," claude_launch(",' prompt="STEP 1: Restart Gateway: openclaw gateway restart'," STEP 2: Wait 5s",` STEP 3: Wake agent: openclaw agent --agent ${I} --message 'HEARTBEAT.md configured'`,' STEP 4: Continue task: [USER_TASK]",',' name="setup-heartbeat-md"'," )"].join(`
|
|
7
|
+
`)}]};if(!Y(r))return console.log(`[claude-launch] No agentChannels mapping for workdir "${r}" \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:[`ERROR: Launch blocked \u2014 no agentChannels mapping found for workspace "${r}".`,"","Claude Code sessions require the workspace directory to be mapped in the agentChannels config","so notifications can be routed to the correct agent and chat.","","You must add the workspace to agentChannels FIRST. Here's what to do:","","1. Edit ~/.openclaw/openclaw.json and add the workspace mapping under plugins.config.openclaw-claude-code-plugin.agentChannels:","",` jq '.plugins.config["openclaw-claude-code-plugin"].agentChannels["${r}"] = "channel|accountId|chatId"' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"",' Replace "channel|accountId|chatId" with the actual values, e.g.: "telegram|my-agent|123456789"',"","2. Verify the config was applied:","",` cat ~/.openclaw/openclaw.json | jq '.plugins.config["openclaw-claude-code-plugin"].agentChannels'`,"","3. Restart the Gateway to pick up the new config, then retry the launch:",""," openclaw gateway restart"].join(`
|
|
8
|
+
`)}]};let ue=d.spawn({prompt:n.prompt,name:n.name,workdir:r,model:n.model||U.defaultModel,maxBudgetUsd:o,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:s,forkSession:n.fork_session,multiTurn:!n.multi_turn_disabled,permissionMode:n.permission_mode,originChannel:m,originAgentId:e.agentId||void 0}),Xe=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,$=["Session launched successfully.",` Name: ${ue.name}`,` ID: ${ue.id}`,` Dir: ${r}`,` Model: ${ue.model??"default"}`,` Prompt: "${Xe}"`];return n.resume_session_id&&$.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),n.multi_turn_disabled?$.push(" Mode: single-turn (fire-and-forget)"):$.push(" Mode: multi-turn (use claude_respond to send follow-up messages)"),$.push(""),$.push("Use claude_sessions to check status, claude_output to see output."),{content:[{type:"text",text:$.join(`
|
|
9
|
+
`)}]}}catch(s){return{content:[{type:"text",text:`Error launching session: ${s.message}`}]}}}}}function _s(e){return{name:"claude_sessions",description:"List all Claude Code sessions with their status and progress.",parameters:f.Object({status:f.Optional(f.Union([f.Literal("all"),f.Literal("running"),f.Literal("completed"),f.Literal("failed")],{description:'Filter by status (default "all")'}))}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=n.status||"all",o=d.list(r),s=o;if(e?.workspaceDir){let m=Y(e.workspaceDir);m?(console.log(`[claude_sessions] Filtering sessions by agentChannel=${m}`),s=o.filter(p=>{let g=p.originChannel===m;return console.log(`[claude_sessions] session=${p.id} originChannel=${p.originChannel} match=${g}`),g})):console.log(`[claude_sessions] No agentChannel found for workspaceDir=${e.workspaceDir}, returning all sessions`)}return s.length===0?{content:[{type:"text",text:"No sessions found."}]}:{content:[{type:"text",text:s.map(Rt).join(`
|
|
10
10
|
|
|
11
|
-
`)}]}}}}function Ls(e){return{name:"claude_kill",description:"Terminate a running Claude Code session by name or ID.",parameters:f.Object({session:f.String({description:"Session name or ID to terminate"})}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=d.resolve(n.session);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?{content:[{type:"text",text:`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`}]}:(d.kill(r.id),{content:[{type:"text",text:`Session ${r.name} [${r.id}] has been terminated.`}]}):{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}]}}}}function
|
|
11
|
+
`)}]}}}}function Ls(e){return{name:"claude_kill",description:"Terminate a running Claude Code session by name or ID.",parameters:f.Object({session:f.String({description:"Session name or ID to terminate"})}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=d.resolve(n.session);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?{content:[{type:"text",text:`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`}]}:(d.kill(r.id),{content:[{type:"text",text:`Session ${r.name} [${r.id}] has been terminated.`}]}):{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}]}}}}function Gs(e){return{name:"claude_output",description:"Show recent output from a Claude Code session (by name or ID).",parameters:f.Object({session:f.String({description:"Session name or ID to get output from"}),lines:f.Optional(f.Number({description:"Number of recent lines to show (default 50)"})),full:f.Optional(f.Boolean({description:"Show all available output"}))}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=d.resolve(n.session);if(!r)return{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}]};let o=n.full?r.getOutput():r.getOutput(n.lines??50),s=X(r.duration),a=[`Session: ${r.name} [${r.id}] | Status: ${r.status.toUpperCase()} | Duration: ${s}`,`${"\u2500".repeat(60)}`].join(`
|
|
12
12
|
`);return o.length===0?{content:[{type:"text",text:`${a}
|
|
13
13
|
(no output yet)`}]}:{content:[{type:"text",text:`${a}
|
|
14
14
|
${o.join(`
|
|
15
|
-
`)}`}]}}}}function
|
|
15
|
+
`)}`}]}}}}function Ds(e){let t;if(e?.messageChannel&&e?.agentAccountId){let n=e.messageChannel.split("|");n.length>=2&&(t=`${n[0]}|${e.agentAccountId}|${n.slice(1).join("|")}`)}return!t&&e?.workspaceDir&&(t=Y(e.workspaceDir)),!t&&e?.messageChannel&&e.messageChannel.includes("|")&&(t=e.messageChannel),console.log(`[claude-fg] Factory context: messageChannel=${e?.messageChannel}, agentAccountId=${e?.agentAccountId}, workspaceDir=${e?.workspaceDir}, fallbackChannel=${t}`),{name:"claude_fg",description:"Bring a Claude Code session to foreground (by name or ID). Shows buffered output and streams new output.",parameters:f.Object({session:f.String({description:"Session name or ID to bring to foreground"}),lines:f.Optional(f.Number({description:"Number of recent buffered lines to show (default 30)"}))}),async execute(n,r){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let o=d.resolve(r.session);if(!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let s=re({id:n},t);if(console.log(`[claude-fg] channelId resolved: ${s}, session.workdir=${o.workdir}`),s==="unknown"){let ne=Y(o.workdir);ne&&(s=ne)}let a=o.getCatchupOutput(s);o.foregroundChannels.add(s);let m=X(o.duration),p=[`Session ${o.name} [${o.id}] now in foreground.`,`Status: ${o.status.toUpperCase()} | Duration: ${m}`,`${"\u2500".repeat(60)}`].join(`
|
|
16
16
|
`),g="";a.length>0&&(g=[`\u{1F4CB} Catchup (${a.length} missed output${a.length===1?"":"s"}):`,a.join(`
|
|
17
17
|
`),`${"\u2500".repeat(60)}`].join(`
|
|
18
18
|
`));let I=a.length>0?g:o.getOutput(r.lines??30).length>0?o.getOutput(r.lines??30).join(`
|
|
19
|
-
`):"(no output yet)",
|
|
19
|
+
`):"(no output yet)",j=o.status==="running"||o.status==="starting"?`
|
|
20
20
|
${"\u2500".repeat(60)}
|
|
21
21
|
Streaming new output... Use claude_bg to detach.`:`
|
|
22
22
|
${"\u2500".repeat(60)}
|
|
23
23
|
Session is ${o.status}. No more output expected.`;return o.markFgOutputSeen(s),{content:[{type:"text",text:`${p}
|
|
24
|
-
${I}${
|
|
25
|
-
`);
|
|
26
|
-
`)}]}}catch(a){return{content:[{type:"text",text:`Error sending message: ${a.message}`}]}}}}}function
|
|
27
|
-
`)}}catch(a){return{text:`Error: ${a.message}`}}}})}function
|
|
24
|
+
${I}${j}`}]}}}}function Bs(e){let t;if(e?.messageChannel&&e?.agentAccountId){let n=e.messageChannel.split("|");n.length>=2&&(t=`${n[0]}|${e.agentAccountId}|${n.slice(1).join("|")}`)}return!t&&e?.workspaceDir&&(t=Y(e.workspaceDir)),!t&&e?.messageChannel&&e.messageChannel.includes("|")&&(t=e.messageChannel),console.log(`[claude-bg] Factory context: messageChannel=${e?.messageChannel}, agentAccountId=${e?.agentAccountId}, workspaceDir=${e?.workspaceDir}, fallbackChannel=${t}`),{name:"claude_bg",description:"Send a Claude Code session back to background (stop streaming). If no session specified, detaches whichever session is currently in foreground.",parameters:f.Object({session:f.Optional(f.String({description:"Session name or ID to send to background. If omitted, detaches the current foreground session."}))}),async execute(n,r){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};if(r.session){let p=d.resolve(r.session);if(!p)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let g=re({id:n},t);if(console.log(`[claude-bg] channelId resolved: ${g}, session.workdir=${p.workdir}`),g==="unknown"){let I=Y(p.workdir);I&&(g=I)}return p.saveFgOutputOffset(g),p.foregroundChannels.delete(g),{content:[{type:"text",text:`Session ${p.name} [${p.id}] moved to background.`}]}}let o=re({id:n},t);if(console.log(`[claude-bg] resolvedId (no session): ${o}`),o==="unknown"){let p=d.list("all");for(let g of p){let I=Y(g.workdir);if(I&&g.foregroundChannels.has(I)){o=I;break}}}let a=d.list("all").filter(p=>p.foregroundChannels.has(o));if(a.length===0)return{content:[{type:"text",text:"No session is currently in foreground."}]};let m=[];for(let p of a)p.saveFgOutputOffset(o),p.foregroundChannels.delete(o),m.push(`${p.name} [${p.id}]`);return{content:[{type:"text",text:`Moved to background: ${m.join(", ")}`}]}}}}function Vs(e){let t;if(e?.messageChannel&&e?.agentAccountId){let n=e.messageChannel.split("|");n.length>=2&&(t=`${n[0]}|${e.agentAccountId}|${n.slice(1).join("|")}`)}return!t&&e?.workspaceDir&&(t=Y(e.workspaceDir)),!t&&e?.messageChannel&&e.messageChannel.includes("|")&&(t=e.messageChannel),{name:"claude_respond",description:"Send a follow-up message to a running Claude Code session. The session must be running. Sessions are multi-turn by default, so this works with any session unless it was launched with multi_turn_disabled: true.",parameters:f.Object({session:f.String({description:"Session name or ID to respond to"}),message:f.String({description:"The message to send to the session"}),interrupt:f.Optional(f.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:f.Optional(f.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."}))}),async execute(n,r){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let o=d.resolve(r.session);if(!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};if(o.status!=="running")return{content:[{type:"text",text:`Error: Session ${o.name} [${o.id}] is not running (status: ${o.status}). Cannot send a message to a non-running session.`}]};let s=U.maxAutoResponds??10;if(r.userInitiated)o.resetAutoRespond();else if(o.autoRespondCount>=s)return{content:[{type:"text",text:`\u26A0\uFE0F Auto-respond limit reached (${o.autoRespondCount}/${s}). Ask the user to provide the answer for session ${o.name}. Then call claude_respond with their answer and set userInitiated: true to reset the counter.`}]};try{if(r.interrupt&&await o.interrupt(),await o.sendMessage(r.message),r.userInitiated||o.incrementAutoRespond(),d){let m=[`\u21A9\uFE0F [${o.name}] Responded:`,r.message.length>200?r.message.slice(0,200)+"...":r.message].join(`
|
|
25
|
+
`);d.deliverToTelegram(o,m,"responded")}let a=r.message.length>80?r.message.slice(0,80)+"...":r.message;return{content:[{type:"text",text:[`Message sent to session ${o.name} [${o.id}].`,r.interrupt?" (interrupted current turn first)":"",` Message: "${a}"`,"","Use claude_output to see the response."].filter(Boolean).join(`
|
|
26
|
+
`)}]}}catch(a){return{content:[{type:"text",text:`Error sending message: ${a.message}`}]}}}}}function vs(e){return{name:"claude_stats",description:"Show Claude Code Plugin usage metrics: session counts by status, average duration, and notable sessions.",parameters:f.Object({}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=d.getMetrics();return{content:[{type:"text",text:Ft(r)}]}}}}function qs(e){e.registerCommand({name:"claude",description:"Launch a Claude Code session. Usage: /claude [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /claude [--name <name>] <prompt>"};let r,o=n.match(/^--name\s+(\S+)\s+/);o&&(r=o[1],n=n.slice(o[0].length).trim());let s=n;if(!s)return{text:"Usage: /claude [--name <name>] <prompt>"};try{let a=d.spawn({prompt:s,name:r,workdir:U.defaultWorkdir||process.cwd(),model:U.defaultModel,maxBudgetUsd:U.defaultBudgetUsd??5,originChannel:re(t)}),m=s.length>80?s.slice(0,80)+"...":s;return{text:["Session launched.",` Name: ${a.name}`,` ID: ${a.id}`,` Prompt: "${m}"`,` Status: ${a.status}`].join(`
|
|
27
|
+
`)}}catch(a){return{text:`Error: ${a.message}`}}}})}function Ws(e){e.registerCommand({name:"claude_sessions",description:"List all Claude Code sessions",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let t=d.list("all");return t.length===0?{text:"No sessions found."}:{text:t.map(Rt).join(`
|
|
28
28
|
|
|
29
|
-
`)}}})}function
|
|
29
|
+
`)}}})}function zs(e){e.registerCommand({name:"claude_kill",description:"Kill a Claude Code session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=t.args?.trim();if(!n)return{text:"Usage: /claude_kill <name-or-id>"};let r=d.resolve(n);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?{text:`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`}:(d.kill(r.id),{text:`Session ${r.name} [${r.id}] has been terminated.`}):{text:`Error: Session "${n}" not found.`}}})}function Hs(e){e.registerCommand({name:"claude_fg",description:"Bring a Claude Code session to foreground by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=t.args?.trim();if(!n)return{text:"Usage: /claude_fg <name-or-id>"};let r=d.resolve(n);if(!r)return{text:`Error: Session "${n}" not found.`};let o=re(t),s=r.getCatchupOutput(o);r.foregroundChannels.add(o);let a=X(r.duration),m=[`Session ${r.name} [${r.id}] now in foreground.`,`Status: ${r.status.toUpperCase()} | Duration: ${a}`,`${"\u2500".repeat(60)}`].join(`
|
|
30
30
|
`),p="";s.length>0&&(p=[`\u{1F4CB} Catchup (${s.length} missed output${s.length===1?"":"s"}):`,s.join(`
|
|
31
31
|
`),`${"\u2500".repeat(60)}`].join(`
|
|
32
32
|
`));let g=s.length>0?p:r.getOutput(30).length>0?r.getOutput(30).join(`
|
|
@@ -35,28 +35,30 @@ ${"\u2500".repeat(60)}
|
|
|
35
35
|
Streaming... Use /claude_bg to detach.`:`
|
|
36
36
|
${"\u2500".repeat(60)}
|
|
37
37
|
Session is ${r.status}.`;return r.markFgOutputSeen(o),{text:`${m}
|
|
38
|
-
${g}${I}`}}})}function
|
|
38
|
+
${g}${I}`}}})}function Js(e){e.registerCommand({name:"claude_bg",description:"Send the current foreground session back to background",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=re(t),r=t.args?.trim();if(r){let m=d.resolve(r);return m?(m.saveFgOutputOffset(n),m.foregroundChannels.delete(n),{text:`Session ${m.name} [${m.id}] moved to background.`}):{text:`Error: Session "${r}" not found.`}}let s=d.list("all").filter(m=>m.foregroundChannels.has(n));if(s.length===0)return{text:"No session is currently in foreground."};let a=[];for(let m of s)m.saveFgOutputOffset(n),m.foregroundChannels.delete(n),a.push(`${m.name} [${m.id}]`);return{text:`Moved to background: ${a.join(", ")}`}}})}function Ys(e){e.registerCommand({name:"claude_resume",description:"Resume a previous Claude Code session. Usage: /claude_resume <id-or-name> [prompt] or /claude_resume --list to see resumable sessions.",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /claude_resume <id-or-name> [prompt]
|
|
39
39
|
/claude_resume --list \u2014 list resumable sessions
|
|
40
|
-
/claude_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let
|
|
40
|
+
/claude_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let j=d.listPersistedSessions();return j.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
|
|
41
41
|
|
|
42
|
-
${
|
|
42
|
+
${j.map(H=>{let ue=H.prompt.length>60?H.prompt.slice(0,60)+"...":H.prompt,Xe=H.completedAt?`completed ${X(Date.now()-H.completedAt)} ago`:H.status;return[` ${H.name} \u2014 ${Xe}`,` Claude ID: ${H.claudeSessionId}`,` \u{1F4C1} ${H.workdir}`,` \u{1F4DD} "${ue}"`].join(`
|
|
43
43
|
`)}).join(`
|
|
44
44
|
|
|
45
45
|
`)}`}}let r=!1;n.startsWith("--fork ")&&(r=!0,n=n.slice(7).trim());let o=n.indexOf(" "),s,a;o===-1?(s=n,a="Continue where you left off."):(s=n.slice(0,o),a=n.slice(o+1).trim()||"Continue where you left off.");let m=d.resolveClaudeSessionId(s);if(!m)return{text:`Error: Could not find a Claude session ID for "${s}".
|
|
46
|
-
Use /claude_resume --list to see available sessions.`};let p=t.config??{},g=d.getPersistedSession(s),I=g?.workdir??process.cwd();try{let
|
|
47
|
-
`)}}catch(
|
|
48
|
-
/claude_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!0,o=o.slice(12).trim());let s=o.indexOf(" ");if(s===-1)return{text:"Error: Missing message. Usage: /claude_respond <id-or-name> <message>"};let a=o.slice(0,s),m=o.slice(s+1).trim();if(!m)return{text:"Error: Empty message. Usage: /claude_respond <id-or-name> <message>"};let p=d.resolve(a);if(!p)return{text:`Error: Session "${a}" not found.`};if(p.status!=="running")return{text:`Error: Session ${p.name} [${p.id}] is not running (status: ${p.status}).`};try{if(r&&await p.interrupt(),await p.sendMessage(m),p.resetAutoRespond(),
|
|
49
|
-
`);
|
|
50
|
-
`)}}catch(g){return{text:`Error: ${g.message}`}}}})}function Qs(e){e.registerCommand({name:"claude_stats",description:"Show Claude Code Plugin usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let t=d.getMetrics();return{text:At(t)}}})}function ei(e){e.registerGatewayMethod("claude-code.sessions",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.status??"all",s=d.list(r).map(a=>({id:a.id,name:a.name,status:a.status,prompt:a.prompt,workdir:a.workdir,model:a.model,costUsd:a.costUsd,startedAt:a.startedAt,completedAt:a.completedAt,durationMs:a.duration,claudeSessionId:a.claudeSessionId,foreground:a.foregroundChannels.size>0,multiTurn:a.multiTurn,display:Ft(a)}));t(!0,{sessions:s,count:s.length})}),e.registerGatewayMethod("claude-code.launch",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});if(!n?.prompt)return t(!1,{error:"Missing required parameter: prompt"});try{let r=d.spawn({prompt:n.prompt,name:n.name,workdir:n.workdir||U.defaultWorkdir||process.cwd(),model:n.model||U.defaultModel,maxBudgetUsd:n.maxBudgetUsd??n.max_budget_usd??U.defaultBudgetUsd??5,systemPrompt:n.systemPrompt??n.system_prompt,allowedTools:n.allowedTools??n.allowed_tools,resumeSessionId:n.resumeSessionId??n.resume_session_id,forkSession:n.forkSession??n.fork_session,multiTurn:!(n.multiTurnDisabled??n.multi_turn_disabled),originChannel:n.originChannel??"gateway"});t(!0,{id:r.id,name:r.name,status:r.status,workdir:r.workdir,model:r.model})}catch(r){t(!1,{error:r.message})}}),e.registerGatewayMethod("claude-code.kill",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.session??n?.id;if(!r)return t(!1,{error:"Missing required parameter: session (name or ID)"});let o=d.resolve(r);if(!o)return t(!1,{error:`Session "${r}" not found`});if(o.status==="completed"||o.status==="failed"||o.status==="killed")return t(!0,{id:o.id,name:o.name,status:o.status,message:`Session already ${o.status}`});d.kill(o.id),t(!0,{id:o.id,name:o.name,status:"killed",message:`Session ${o.name} [${o.id}] terminated`})}),e.registerGatewayMethod("claude-code.output",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.session??n?.id;if(!r)return t(!1,{error:"Missing required parameter: session (name or ID)"});let o=d.resolve(r);if(!o)return t(!1,{error:`Session "${r}" not found`});let s=n?.full?o.getOutput():o.getOutput(n?.lines??50);t(!0,{id:o.id,name:o.name,status:o.status,costUsd:o.costUsd,durationMs:o.duration,duration:Z(o.duration),lines:s,lineCount:s.length,result:o.result??null})}),e.registerGatewayMethod("claude-code.stats",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=d.getMetrics(),o={};for(let[a,m]of r.costPerDay)o[a]=m;let s=d.list("running").length;t(!0,{totalCostUsd:r.totalCostUsd,costPerDay:o,sessionsByStatus:{...r.sessionsByStatus,running:s},totalLaunched:r.totalLaunched,averageDurationMs:r.sessionsWithDuration>0?r.totalDurationMs/r.sessionsWithDuration:0,mostExpensive:r.mostExpensive,display:At(r)})})}var pr=require("child_process");var oi=require("@anthropic-ai/claude-agent-sdk");var lr=pi(require("crypto"),1);var ti="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Hm=128,ct,Mt,Jm=e=>{!ct||ct.length<e?(ct=Buffer.allocUnsafe(e*Hm),lr.default.randomFillSync(ct),Mt=0):Mt+e>ct.length&&(lr.default.randomFillSync(ct),Mt=0),Mt+=e};var ni=(e=21)=>{Jm(e|=0);let t="";for(let n=Mt-e;n<Mt;n++)t+=ti[ct[n]&63];return t};var ri=200,dr=class{queue=[];resolve=null;done=!1;push(t,n){let r={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n};this.queue.push(r),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(t=>{this.resolve=t})}}},Cn=class e{id;name;claudeSessionId;prompt;workdir;model;maxBudgetUsd;systemPrompt;allowedTools;permissionMode;resumeSessionId;forkSession;multiTurn;messageStream;queryHandle;idleTimer;safetyNetTimer;static SAFETY_NET_IDLE_MS=15e3;status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;foregroundChannels=new Set;fgOutputOffsets=new Map;originChannel;budgetExhausted=!1;waitingForInputFired=!1;autoRespondCount=0;onOutput;onToolUse;onBudgetExhausted;onComplete;onWaitingForInput;constructor(t,n){this.id=ni(8),this.name=n,this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model,this.maxBudgetUsd=t.maxBudgetUsd,this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??U.permissionMode??"bypassPermissions",this.originChannel=t.originChannel,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.startedAt=Date.now(),this.abortController=new AbortController}async start(){let t;try{let n={cwd:this.workdir,model:this.model,maxBudgetUsd:this.maxBudgetUsd,permissionMode:this.permissionMode,allowDangerouslySkipPermissions:this.permissionMode==="bypassPermissions",allowedTools:this.allowedTools,includePartialMessages:!0,abortController:this.abortController,...this.systemPrompt?{systemPrompt:this.systemPrompt}:{}};this.resumeSessionId&&(n.resume=this.resumeSessionId,this.forkSession&&(n.forkSession=!0));let r;this.multiTurn?(this.messageStream=new dr,this.messageStream.push(this.prompt,""),r=this.messageStream):r=this.prompt,t=(0,oi.query)({prompt:r,options:n}),this.queryHandle=t}catch(n){this.status="failed",this.error=n?.message??String(n),this.completedAt=Date.now();return}this.consumeMessages(t).catch(n=>{(this.status==="starting"||this.status==="running")&&(this.status="failed",this.error=n?.message??String(n),this.completedAt=Date.now())})}resetSafetyNetTimer(){this.clearSafetyNetTimer(),this.safetyNetTimer=setTimeout(()=>{this.safetyNetTimer=void 0,this.status==="running"&&this.onWaitingForInput&&!this.waitingForInputFired&&(console.log(`[Session] ${this.id} no messages for ${e.SAFETY_NET_IDLE_MS/1e3}s \u2014 firing onWaitingForInput (safety-net)`),this.waitingForInputFired=!0,this.onWaitingForInput(this))},e.SAFETY_NET_IDLE_MS)}clearSafetyNetTimer(){this.safetyNetTimer&&(clearTimeout(this.safetyNetTimer),this.safetyNetTimer=void 0)}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),!this.multiTurn)return;let t=(U.idleTimeoutMinutes??30)*60*1e3;this.idleTimer=setTimeout(()=>{this.status==="running"&&(console.log(`[Session] ${this.id} idle timeout reached (${U.idleTimeoutMinutes??30}min), auto-killing`),this.kill())},t)}async sendMessage(t){if(this.status!=="running")throw new Error(`Session is not running (status: ${this.status})`);if(this.resetIdleTimer(),this.waitingForInputFired=!1,this.multiTurn&&this.messageStream)this.messageStream.push(t,this.claudeSessionId??"");else if(this.queryHandle&&typeof this.queryHandle.streamInput=="function"){let n={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:this.claudeSessionId??""};async function*r(){yield n}await this.queryHandle.streamInput(r())}else throw new Error("Session does not support multi-turn messaging. Launch with multiTurn: true or use the SDK streamInput.")}async interrupt(){this.queryHandle&&typeof this.queryHandle.interrupt=="function"&&await this.queryHandle.interrupt()}async consumeMessages(t){for await(let n of t)if(this.resetSafetyNetTimer(),n.type==="system"&&n.subtype==="init")this.claudeSessionId=n.session_id,this.status="running",this.resetIdleTimer();else if(n.type==="assistant"){this.waitingForInputFired=!1;let r=n.message?.content??[];console.log(`[Session] ${this.id} assistant message received, blocks=${r.length}, fgChannels=${JSON.stringify([...this.foregroundChannels])}`);for(let o of r)if(o.type==="text"){let s=o.text;this.outputBuffer.push(s),this.outputBuffer.length>ri&&this.outputBuffer.splice(0,this.outputBuffer.length-ri),this.onOutput?(console.log(`[Session] ${this.id} calling onOutput, textLen=${s.length}`),this.onOutput(s)):console.log(`[Session] ${this.id} onOutput callback NOT set`)}else o.type==="tool_use"&&(this.onToolUse?(console.log(`[Session] ${this.id} calling onToolUse, tool=${o.name}`),this.onToolUse(o.name,o.input)):console.log(`[Session] ${this.id} onToolUse callback NOT set`))}else n.type==="result"&&(this.result={subtype:n.subtype,duration_ms:n.duration_ms,total_cost_usd:n.total_cost_usd,num_turns:n.num_turns,result:n.result,is_error:n.is_error,session_id:n.session_id},this.costUsd=n.total_cost_usd,this.multiTurn&&this.messageStream&&n.subtype==="success"?(console.log(`[Session] ${this.id} multi-turn end-of-turn (turn ${n.num_turns}), staying open`),this.clearSafetyNetTimer(),this.resetIdleTimer(),this.onWaitingForInput&&!this.waitingForInputFired&&(console.log(`[Session] ${this.id} calling onWaitingForInput`),this.waitingForInputFired=!0,this.onWaitingForInput(this))):(this.clearSafetyNetTimer(),this.idleTimer&&clearTimeout(this.idleTimer),this.status=n.subtype==="success"?"completed":"failed",this.completedAt=Date.now(),this.messageStream&&this.messageStream.end(),n.subtype==="error_max_budget_usd"&&(this.budgetExhausted=!0,this.onBudgetExhausted&&this.onBudgetExhausted(this)),this.onComplete?(console.log(`[Session] ${this.id} calling onComplete, status=${this.status}`),this.onComplete(this)):console.log(`[Session] ${this.id} onComplete callback NOT set`)))}kill(){this.status!=="starting"&&this.status!=="running"||(this.idleTimer&&clearTimeout(this.idleTimer),this.clearSafetyNetTimer(),this.status="killed",this.completedAt=Date.now(),this.messageStream&&this.messageStream.end(),this.abortController.abort())}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}getCatchupOutput(t){let n=this.fgOutputOffsets.get(t)??0,r=this.outputBuffer.length;return n>=r?[]:this.outputBuffer.slice(n)}markFgOutputSeen(t){this.fgOutputOffsets.set(t,this.outputBuffer.length)}saveFgOutputOffset(t){this.fgOutputOffsets.set(t,this.outputBuffer.length)}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}get duration(){return(this.completedAt??Date.now())-this.startedAt}};var Ym=3600*1e3,Xm=5e3,Tn=class{sessions=new Map;maxSessions;maxPersistedSessions;notificationRouter=null;lastWaitingEventTimestamps=new Map;persistedSessions=new Map;_metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};constructor(t=5,n=50){this.maxSessions=t,this.maxPersistedSessions=n}uniqueName(t){let n=new Set([...this.sessions.values()].map(o=>o.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}-${r}`);)r++;return`${t}-${r}`}spawn(t){if([...this.sessions.values()].filter(a=>a.status==="starting"||a.status==="running").length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Kill a session first.`);let r=t.name||js(t.prompt),o=this.uniqueName(r),s=new Cn(t,o);if(this.sessions.set(s.id,s),this._metrics.totalLaunched++,this.notificationRouter){let a=this.notificationRouter;console.log(`[SessionManager] Wiring notification callbacks for session=${s.id} (${s.name}), originChannel=${s.originChannel}`),s.onOutput=m=>{console.log(`[SessionManager] session.onOutput fired for session=${s.id}, textLen=${m.length}, fgChannels=${JSON.stringify([...s.foregroundChannels])}`),a.onAssistantText(s,m);for(let p of s.foregroundChannels)s.markFgOutputSeen(p)},s.onToolUse=(m,p)=>{console.log(`[SessionManager] session.onToolUse fired for session=${s.id}, tool=${m}`),a.onToolUse(s,m,p)},s.onBudgetExhausted=()=>{console.log(`[SessionManager] session.onBudgetExhausted fired for session=${s.id}`),a.onBudgetExhausted(s,s.originChannel)},s.onWaitingForInput=()=>{console.log(`[SessionManager] session.onWaitingForInput fired for session=${s.id}`),a.onWaitingForInput(s,s.originChannel),this.triggerWaitingForInputEvent(s)},s.onComplete=()=>{console.log(`[SessionManager] session.onComplete fired for session=${s.id}, budgetExhausted=${s.budgetExhausted}`),this.persistSession(s),s.budgetExhausted||a.onSessionComplete(s,s.originChannel),this.triggerAgentEvent(s)}}else console.warn(`[SessionManager] No NotificationRouter available when spawning session=${s.id} (${s.name})`);return s.start(),s}persistSession(t){if(this.persistedSessions.has(t.id)||this.recordSessionMetrics(t),!t.claudeSessionId)return;let r={claudeSessionId:t.claudeSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,completedAt:t.completedAt,status:t.status,costUsd:t.costUsd};this.persistedSessions.set(t.id,r),this.persistedSessions.set(t.name,r),this.persistedSessions.set(t.claudeSessionId,r),console.log(`[SessionManager] Persisted session ${t.name} [${t.id}] -> claudeSessionId=${t.claudeSessionId}`)}recordSessionMetrics(t){let n=t.costUsd??0,r=t.status;this._metrics.totalCostUsd+=n;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this._metrics.costPerDay.set(o,(this._metrics.costPerDay.get(o)??0)+n),(r==="completed"||r==="failed"||r==="killed")&&this._metrics.sessionsByStatus[r]++,t.completedAt){let s=t.completedAt-t.startedAt;this._metrics.totalDurationMs+=s,this._metrics.sessionsWithDuration++}(!this._metrics.mostExpensive||n>this._metrics.mostExpensive.costUsd)&&(this._metrics.mostExpensive={id:t.id,name:t.name,costUsd:n,prompt:t.prompt.length>80?t.prompt.slice(0,80)+"...":t.prompt})}getMetrics(){return this._metrics}triggerAgentEvent(t){let n=t.status,o=t.getOutput(5).join(`
|
|
51
|
-
`);o.
|
|
52
|
-
`);
|
|
53
|
-
`)
|
|
54
|
-
`);console.log(`[SessionManager] Triggering
|
|
55
|
-
`)
|
|
56
|
-
`);
|
|
57
|
-
|
|
58
|
-
`);this.
|
|
59
|
-
`);
|
|
46
|
+
Use /claude_resume --list to see available sessions.`};let p=t.config??{},g=d.getPersistedSession(s),I=g?.workdir??process.cwd();try{let j=d.spawn({prompt:a,workdir:I,model:g?.model??p.defaultModel,maxBudgetUsd:p.defaultBudgetUsd??5,resumeSessionId:m,forkSession:r,originChannel:re(t)}),ne=a.length>80?a.slice(0,80)+"...":a;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${j.name}`,` ID: ${j.id}`,` Resume from: ${m}`,` Dir: ${I}`,` Prompt: "${ne}"`].join(`
|
|
47
|
+
`)}}catch(j){return{text:`Error: ${j.message}`}}}})}function Xs(e){e.registerCommand({name:"claude_respond",description:"Send a follow-up message to a running Claude Code session. Usage: /claude_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /claude_respond <id-or-name> <message>
|
|
48
|
+
/claude_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!0,o=o.slice(12).trim());let s=o.indexOf(" ");if(s===-1)return{text:"Error: Missing message. Usage: /claude_respond <id-or-name> <message>"};let a=o.slice(0,s),m=o.slice(s+1).trim();if(!m)return{text:"Error: Empty message. Usage: /claude_respond <id-or-name> <message>"};let p=d.resolve(a);if(!p)return{text:`Error: Session "${a}" not found.`};if(p.status!=="running")return{text:`Error: Session ${p.name} [${p.id}] is not running (status: ${p.status}).`};try{if(r&&await p.interrupt(),await p.sendMessage(m),p.resetAutoRespond(),d){let I=[`\u21A9\uFE0F [${p.name}] Responded:`,m.length>200?m.slice(0,200)+"...":m].join(`
|
|
49
|
+
`);d.deliverToTelegram(p,I,"responded")}let g=m.length>80?m.slice(0,80)+"...":m;return{text:[`Message sent to ${p.name} [${p.id}].`,r?" (interrupted current turn)":"",` "${g}"`].filter(Boolean).join(`
|
|
50
|
+
`)}}catch(g){return{text:`Error: ${g.message}`}}}})}function Zs(e){e.registerCommand({name:"claude_stats",description:"Show Claude Code Plugin usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let t=d.getMetrics();return{text:Ft(t)}}})}function Qs(e){e.registerGatewayMethod("claude-code.sessions",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.status??"all",s=d.list(r).map(a=>({id:a.id,name:a.name,status:a.status,prompt:a.prompt,workdir:a.workdir,model:a.model,costUsd:a.costUsd,startedAt:a.startedAt,completedAt:a.completedAt,durationMs:a.duration,claudeSessionId:a.claudeSessionId,foreground:a.foregroundChannels.size>0,multiTurn:a.multiTurn,display:Rt(a)}));t(!0,{sessions:s,count:s.length})}),e.registerGatewayMethod("claude-code.launch",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});if(!n?.prompt)return t(!1,{error:"Missing required parameter: prompt"});try{let r=d.spawn({prompt:n.prompt,name:n.name,workdir:n.workdir||U.defaultWorkdir||process.cwd(),model:n.model||U.defaultModel,maxBudgetUsd:n.maxBudgetUsd??n.max_budget_usd??U.defaultBudgetUsd??5,systemPrompt:n.systemPrompt??n.system_prompt,allowedTools:n.allowedTools??n.allowed_tools,resumeSessionId:n.resumeSessionId??n.resume_session_id,forkSession:n.forkSession??n.fork_session,multiTurn:!(n.multiTurnDisabled??n.multi_turn_disabled),originChannel:n.originChannel??"gateway"});t(!0,{id:r.id,name:r.name,status:r.status,workdir:r.workdir,model:r.model})}catch(r){t(!1,{error:r.message})}}),e.registerGatewayMethod("claude-code.kill",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.session??n?.id;if(!r)return t(!1,{error:"Missing required parameter: session (name or ID)"});let o=d.resolve(r);if(!o)return t(!1,{error:`Session "${r}" not found`});if(o.status==="completed"||o.status==="failed"||o.status==="killed")return t(!0,{id:o.id,name:o.name,status:o.status,message:`Session already ${o.status}`});d.kill(o.id),t(!0,{id:o.id,name:o.name,status:"killed",message:`Session ${o.name} [${o.id}] terminated`})}),e.registerGatewayMethod("claude-code.output",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.session??n?.id;if(!r)return t(!1,{error:"Missing required parameter: session (name or ID)"});let o=d.resolve(r);if(!o)return t(!1,{error:`Session "${r}" not found`});let s=n?.full?o.getOutput():o.getOutput(n?.lines??50);t(!0,{id:o.id,name:o.name,status:o.status,costUsd:o.costUsd,durationMs:o.duration,duration:X(o.duration),lines:s,lineCount:s.length,result:o.result??null})}),e.registerGatewayMethod("claude-code.stats",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=d.getMetrics(),o={};for(let[a,m]of r.costPerDay)o[a]=m;let s=d.list("running").length;t(!0,{totalCostUsd:r.totalCostUsd,costPerDay:o,sessionsByStatus:{...r.sessionsByStatus,running:s},totalLaunched:r.totalLaunched,averageDurationMs:r.sessionsWithDuration>0?r.totalDurationMs/r.sessionsWithDuration:0,mostExpensive:r.mostExpensive,display:Ft(r)})})}var Ht=require("child_process");var ri=require("@anthropic-ai/claude-agent-sdk");var lr=fi(require("crypto"),1);var ei="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ym=128,ut,At,Xm=e=>{!ut||ut.length<e?(ut=Buffer.allocUnsafe(e*Ym),lr.default.randomFillSync(ut),At=0):At+e>ut.length&&(lr.default.randomFillSync(ut),At=0),At+=e};var ti=(e=21)=>{Xm(e|=0);let t="";for(let n=At-e;n<At;n++)t+=ei[ut[n]&63];return t};var ni=200,dr=class{queue=[];resolve=null;done=!1;push(t,n){let r={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n};this.queue.push(r),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(t=>{this.resolve=t})}}},Tn=class e{id;name;claudeSessionId;prompt;workdir;model;maxBudgetUsd;systemPrompt;allowedTools;permissionMode;resumeSessionId;forkSession;multiTurn;messageStream;queryHandle;idleTimer;safetyNetTimer;static SAFETY_NET_IDLE_MS=15e3;status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;foregroundChannels=new Set;fgOutputOffsets=new Map;originChannel;originAgentId;budgetExhausted=!1;waitingForInputFired=!1;autoRespondCount=0;onOutput;onToolUse;onBudgetExhausted;onComplete;onWaitingForInput;constructor(t,n){this.id=ti(8),this.name=n,this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model,this.maxBudgetUsd=t.maxBudgetUsd,this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??U.permissionMode??"bypassPermissions",this.originChannel=t.originChannel,this.originAgentId=t.originAgentId,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.startedAt=Date.now(),this.abortController=new AbortController}async start(){let t;try{let n={cwd:this.workdir,model:this.model,maxBudgetUsd:this.maxBudgetUsd,permissionMode:this.permissionMode,allowDangerouslySkipPermissions:this.permissionMode==="bypassPermissions",allowedTools:this.allowedTools,includePartialMessages:!0,abortController:this.abortController,...this.systemPrompt?{systemPrompt:this.systemPrompt}:{}};this.resumeSessionId&&(n.resume=this.resumeSessionId,this.forkSession&&(n.forkSession=!0));let r;this.multiTurn?(this.messageStream=new dr,this.messageStream.push(this.prompt,""),r=this.messageStream):r=this.prompt,t=(0,ri.query)({prompt:r,options:n}),this.queryHandle=t}catch(n){this.status="failed",this.error=n?.message??String(n),this.completedAt=Date.now();return}this.consumeMessages(t).catch(n=>{(this.status==="starting"||this.status==="running")&&(this.status="failed",this.error=n?.message??String(n),this.completedAt=Date.now())})}resetSafetyNetTimer(){this.clearSafetyNetTimer(),this.safetyNetTimer=setTimeout(()=>{this.safetyNetTimer=void 0,this.status==="running"&&this.onWaitingForInput&&!this.waitingForInputFired&&(console.log(`[Session] ${this.id} no messages for ${e.SAFETY_NET_IDLE_MS/1e3}s \u2014 firing onWaitingForInput (safety-net)`),this.waitingForInputFired=!0,this.onWaitingForInput(this))},e.SAFETY_NET_IDLE_MS)}clearSafetyNetTimer(){this.safetyNetTimer&&(clearTimeout(this.safetyNetTimer),this.safetyNetTimer=void 0)}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),!this.multiTurn)return;let t=(U.idleTimeoutMinutes??30)*60*1e3;this.idleTimer=setTimeout(()=>{this.status==="running"&&(console.log(`[Session] ${this.id} idle timeout reached (${U.idleTimeoutMinutes??30}min), auto-killing`),this.kill())},t)}async sendMessage(t){if(this.status!=="running")throw new Error(`Session is not running (status: ${this.status})`);if(this.resetIdleTimer(),this.waitingForInputFired=!1,this.multiTurn&&this.messageStream)this.messageStream.push(t,this.claudeSessionId??"");else if(this.queryHandle&&typeof this.queryHandle.streamInput=="function"){let n={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:this.claudeSessionId??""};async function*r(){yield n}await this.queryHandle.streamInput(r())}else throw new Error("Session does not support multi-turn messaging. Launch with multiTurn: true or use the SDK streamInput.")}async interrupt(){this.queryHandle&&typeof this.queryHandle.interrupt=="function"&&await this.queryHandle.interrupt()}async consumeMessages(t){for await(let n of t)if(this.resetSafetyNetTimer(),n.type==="system"&&n.subtype==="init")this.claudeSessionId=n.session_id,this.status="running",this.resetIdleTimer();else if(n.type==="assistant"){this.waitingForInputFired=!1;let r=n.message?.content??[];console.log(`[Session] ${this.id} assistant message received, blocks=${r.length}, fgChannels=${JSON.stringify([...this.foregroundChannels])}`);for(let o of r)if(o.type==="text"){let s=o.text;this.outputBuffer.push(s),this.outputBuffer.length>ni&&this.outputBuffer.splice(0,this.outputBuffer.length-ni),this.onOutput?(console.log(`[Session] ${this.id} calling onOutput, textLen=${s.length}`),this.onOutput(s)):console.log(`[Session] ${this.id} onOutput callback NOT set`)}else o.type==="tool_use"&&(this.onToolUse?(console.log(`[Session] ${this.id} calling onToolUse, tool=${o.name}`),this.onToolUse(o.name,o.input)):console.log(`[Session] ${this.id} onToolUse callback NOT set`))}else n.type==="result"&&(this.result={subtype:n.subtype,duration_ms:n.duration_ms,total_cost_usd:n.total_cost_usd,num_turns:n.num_turns,result:n.result,is_error:n.is_error,session_id:n.session_id},this.costUsd=n.total_cost_usd,this.multiTurn&&this.messageStream&&n.subtype==="success"?(console.log(`[Session] ${this.id} multi-turn end-of-turn (turn ${n.num_turns}), staying open`),this.clearSafetyNetTimer(),this.resetIdleTimer(),this.onWaitingForInput&&!this.waitingForInputFired&&(console.log(`[Session] ${this.id} calling onWaitingForInput`),this.waitingForInputFired=!0,this.onWaitingForInput(this))):(this.clearSafetyNetTimer(),this.idleTimer&&clearTimeout(this.idleTimer),this.status=n.subtype==="success"?"completed":"failed",this.completedAt=Date.now(),this.messageStream&&this.messageStream.end(),n.subtype==="error_max_budget_usd"&&(this.budgetExhausted=!0,this.onBudgetExhausted&&this.onBudgetExhausted(this)),this.onComplete?(console.log(`[Session] ${this.id} calling onComplete, status=${this.status}`),this.onComplete(this)):console.log(`[Session] ${this.id} onComplete callback NOT set`)))}kill(){this.status!=="starting"&&this.status!=="running"||(this.idleTimer&&clearTimeout(this.idleTimer),this.clearSafetyNetTimer(),this.status="killed",this.completedAt=Date.now(),this.messageStream&&this.messageStream.end(),this.abortController.abort())}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}getCatchupOutput(t){let n=this.fgOutputOffsets.get(t)??0,r=this.outputBuffer.length;return n>=r?[]:this.outputBuffer.slice(n)}markFgOutputSeen(t){this.fgOutputOffsets.set(t,this.outputBuffer.length)}saveFgOutputOffset(t){this.fgOutputOffsets.set(t,this.outputBuffer.length)}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}get duration(){return(this.completedAt??Date.now())-this.startedAt}};var Zm=3600*1e3,Qm=5e3,oi=3e4,si=5e3,Cn=class{sessions=new Map;maxSessions;maxPersistedSessions;notificationRouter=null;lastWaitingEventTimestamps=new Map;pendingRetryTimers=new Set;persistedSessions=new Map;_metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};constructor(t=5,n=50){this.maxSessions=t,this.maxPersistedSessions=n}uniqueName(t){let n=new Set([...this.sessions.values()].map(o=>o.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}-${r}`);)r++;return`${t}-${r}`}spawn(t){if([...this.sessions.values()].filter(m=>m.status==="starting"||m.status==="running").length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Kill a session first.`);let r=t.name||Ks(t.prompt),o=this.uniqueName(r),s=new Tn(t,o);if(this.sessions.set(s.id,s),this._metrics.totalLaunched++,this.notificationRouter){let m=this.notificationRouter;console.log(`[SessionManager] Wiring notification callbacks for session=${s.id} (${s.name}), originChannel=${s.originChannel}`),s.onOutput=p=>{console.log(`[SessionManager] session.onOutput fired for session=${s.id}, textLen=${p.length}, fgChannels=${JSON.stringify([...s.foregroundChannels])}`),m.onAssistantText(s,p);for(let g of s.foregroundChannels)s.markFgOutputSeen(g)},s.onToolUse=(p,g)=>{console.log(`[SessionManager] session.onToolUse fired for session=${s.id}, tool=${p}`),m.onToolUse(s,p,g)},s.onBudgetExhausted=()=>{console.log(`[SessionManager] session.onBudgetExhausted fired for session=${s.id}`),m.onBudgetExhausted(s)},s.onWaitingForInput=()=>{console.log(`[SessionManager] session.onWaitingForInput fired for session=${s.id}`),m.onWaitingForInput(s),this.triggerWaitingForInputEvent(s)},s.onComplete=()=>{console.log(`[SessionManager] session.onComplete fired for session=${s.id}, budgetExhausted=${s.budgetExhausted}`),this.persistSession(s),s.budgetExhausted||m.onSessionComplete(s),this.triggerAgentEvent(s)}}else console.warn(`[SessionManager] No NotificationRouter available when spawning session=${s.id} (${s.name})`);s.start();let a=s.prompt.length>80?s.prompt.slice(0,80)+"...":s.prompt;return this.deliverToTelegram(s,`\u21A9\uFE0F [${s.name}] Launched:
|
|
51
|
+
${a}`,"launched"),s}persistSession(t){if(this.persistedSessions.has(t.id)||this.recordSessionMetrics(t),!t.claudeSessionId)return;let r={claudeSessionId:t.claudeSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,completedAt:t.completedAt,status:t.status,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel};this.persistedSessions.set(t.id,r),this.persistedSessions.set(t.name,r),this.persistedSessions.set(t.claudeSessionId,r),console.log(`[SessionManager] Persisted session ${t.name} [${t.id}] -> claudeSessionId=${t.claudeSessionId}`)}recordSessionMetrics(t){let n=t.costUsd??0,r=t.status;this._metrics.totalCostUsd+=n;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this._metrics.costPerDay.set(o,(this._metrics.costPerDay.get(o)??0)+n),(r==="completed"||r==="failed"||r==="killed")&&this._metrics.sessionsByStatus[r]++,t.completedAt){let s=t.completedAt-t.startedAt;this._metrics.totalDurationMs+=s,this._metrics.sessionsWithDuration++}(!this._metrics.mostExpensive||n>this._metrics.mostExpensive.costUsd)&&(this._metrics.mostExpensive={id:t.id,name:t.name,costUsd:n,prompt:t.prompt.length>80?t.prompt.slice(0,80)+"...":t.prompt})}getMetrics(){return this._metrics}buildDeliverArgs(t){if(!t||t==="unknown"||t==="gateway")return[];let n=t.split("|");return n.length<2?[]:n.length>=3?["--deliver","--reply-channel",n[0],"--reply-account",n[1],"--reply-to",n.slice(2).join("|")]:["--deliver","--reply-channel",n[0],"--reply-to",n[1]]}wakeAgent(t,n,r,o){this.deliverToTelegram(t,r,o);let s=t.originAgentId?.trim();if(!s){console.warn(`[SessionManager] No originAgentId for ${o} session=${t.id}, falling back to system event`),this.fireSystemEventWithRetry(n,o,t.id);return}let a=this.buildDeliverArgs(t.originChannel),m=(0,Ht.spawn)("openclaw",["agent","--agent",s,"--message",n,...a],{detached:!0,stdio:"ignore"});m.unref(),console.log(`[SessionManager] Spawned detached wake for agent=${s}, ${o} session=${t.id} (pid=${m.pid}, deliver=${a.length>0})`)}deliverToTelegram(t,n,r){if(!this.notificationRouter){console.warn(`[SessionManager] Cannot deliver ${r} to Telegram for session=${t.id} (no NotificationRouter)`);return}let o=t.originChannel||"unknown";console.log(`[SessionManager] Delivering ${r} to Telegram for session=${t.id} via channel=${o}`),this.notificationRouter.emitToChannel(o,n)}fireSystemEventWithRetry(t,n,r){let o=["system","event","--text",t,"--mode","now"];(0,Ht.execFile)("openclaw",o,{timeout:oi},(s,a,m)=>{if(s){console.error(`[SessionManager] System event failed for ${n} session=${r}: ${s.message}`),m&&console.error(`[SessionManager] stderr: ${m}`),console.warn(`[SessionManager] Scheduling retry in ${si}ms for ${n} session=${r}`);let p=setTimeout(()=>{this.pendingRetryTimers.delete(p),(0,Ht.execFile)("openclaw",o,{timeout:oi},(g,I,j)=>{g?(console.error(`[SessionManager] System event retry also failed for ${n} session=${r}: ${g.message}`),j&&console.error(`[SessionManager] retry stderr: ${j}`)):console.log(`[SessionManager] System event retry succeeded for ${n} session=${r}`)})},si);this.pendingRetryTimers.add(p)}else console.log(`[SessionManager] System event sent for ${n} session=${r}`)})}triggerAgentEvent(t){let n=t.status,o=t.getOutput(5).join(`
|
|
52
|
+
`);if(o.length>500&&(o=o.slice(-500)),n==="completed"){let s=["Claude Code session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${n}`,"","Output preview:",o,"",`Use claude_output(session='${t.id}', full=true) to get the full result and transmit the analysis to the user.`].join(`
|
|
53
|
+
`),a=o.replace(/[*`_~]/g,""),m=[`\u2705 [${t.name}] Completed`,` \u{1F4C1} ${t.workdir}`,` \u{1F4B0} $${(t.costUsd??0).toFixed(4)}`];a.trim()&&m.push("",a);let p=m.join(`
|
|
54
|
+
`);console.log(`[SessionManager] Triggering agent wake for completed session=${t.id}`),this.wakeAgent(t,s,p,"completed")}else{let s=n==="killed"?"\u26D4":"\u274C",a=t.prompt.length>60?t.prompt.slice(0,60)+"...":t.prompt,m=[`${s} [${t.name}] ${n==="killed"?"Killed":"Failed"}`,` \u{1F4C1} ${t.workdir}`,` \u{1F4DD} "${a}"`,...t.error?[` \u26A0\uFE0F ${t.error}`]:[]].join(`
|
|
55
|
+
`);console.log(`[SessionManager] Delivering ${n} notification for session=${t.id}`),this.deliverToTelegram(t,m,n)}this.lastWaitingEventTimestamps.delete(t.id)}triggerWaitingForInputEvent(t){let r=t.getOutput(5).join(`
|
|
56
|
+
`);r.length>500&&(r=r.slice(-500));let o=`\u{1F514} [${t.name}] Claude asks:
|
|
57
|
+
${r.length>200?r.slice(-200):r}`,s=Date.now(),a=this.lastWaitingEventTimestamps.get(t.id);if(a&&s-a<Qm){console.log(`[SessionManager] Debounced wake for session=${t.id} (last sent ${s-a}ms ago), sending Telegram only`),this.deliverToTelegram(t,o,"waiting");return}this.lastWaitingEventTimestamps.set(t.id,s);let p=[`${t.multiTurn?"Multi-turn session":"Session"} is waiting for input.`,`Name: ${t.name} | ID: ${t.id}`,"","Last output:",r,"",`Use claude_respond(session='${t.id}', message='...') to send a reply, or claude_output(session='${t.id}') to see full context.`].join(`
|
|
58
|
+
`);this.wakeAgent(t,p,o,"waiting")}resolveClaudeSessionId(t){let n=this.resolve(t);if(n?.claudeSessionId)return n.claudeSessionId;let r=this.persistedSessions.get(t);if(r?.claudeSessionId)return r.claudeSessionId;if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return t}getPersistedSession(t){return this.persistedSessions.get(t)}listPersistedSessions(){let t=new Set,n=[];for(let r of this.persistedSessions.values())t.has(r.claudeSessionId)||(t.add(r.claudeSessionId),n.push(r));return n.sort((r,o)=>(o.completedAt??0)-(r.completedAt??0))}resolve(t){let n=this.sessions.get(t);if(n)return n;for(let r of this.sessions.values())if(r.name===t)return r}get(t){return this.sessions.get(t)}list(t){let n=[...this.sessions.values()];return t&&t!=="all"&&(n=n.filter(r=>r.status===t)),n.sort((r,o)=>o.startedAt-r.startedAt)}kill(t){let n=this.sessions.get(t);return n?(n.kill(),this.persistedSessions.has(n.id)||this.recordSessionMetrics(n),this.persistSession(n),this.notificationRouter&&this.notificationRouter.onSessionComplete(n),this.triggerAgentEvent(n),!0):!1}killAll(){for(let t of this.sessions.values())(t.status==="starting"||t.status==="running")&&this.kill(t.id);for(let t of this.pendingRetryTimers)clearTimeout(t);this.pendingRetryTimers.clear()}cleanup(){let t=Date.now();for(let[r,o]of this.sessions)o.completedAt&&(o.status==="completed"||o.status==="failed"||o.status==="killed")&&t-o.completedAt>Zm&&(this.persistSession(o),this.sessions.delete(r),this.lastWaitingEventTimestamps.delete(r));let n=this.listPersistedSessions();if(n.length>this.maxPersistedSessions){let r=n.slice(this.maxPersistedSessions);for(let o of r)for(let[s,a]of this.persistedSessions)a.claudeSessionId===o.claudeSessionId&&this.persistedSessions.delete(s);console.log(`[SessionManager] Evicted ${r.length} oldest persisted sessions (cap=${this.maxPersistedSessions})`)}}};var ii=500,el=600*1e3,$n=class{sendMessage;debounceMap=new Map;longRunningReminded=new Set;reminderInterval=null;getActiveSessions=null;constructor(t){this.sendMessage=(n,r)=>{console.log(`[NotificationRouter] sendMessage -> channel=${n}, textLen=${r.length}, preview=${r.slice(0,120)}`),t(n,r)},console.log("[NotificationRouter] Initialized")}startReminderCheck(t){this.getActiveSessions=t,this.reminderInterval=setInterval(()=>this.checkLongRunning(),6e4)}stop(){this.reminderInterval&&(clearInterval(this.reminderInterval),this.reminderInterval=null);for(let[t,n]of this.debounceMap)if(clearTimeout(n.timer),n.buffer){let[r,o]=t.split("|",2);this.sendMessage(o,n.buffer)}this.debounceMap.clear(),this.longRunningReminded.clear()}onAssistantText(t,n){if(console.log(`[NotificationRouter] onAssistantText session=${t.id} (${t.name}), fgChannels=${JSON.stringify([...t.foregroundChannels])}, textLen=${n.length}`),t.foregroundChannels.size===0){console.log("[NotificationRouter] onAssistantText SKIPPED \u2014 no foreground channels");return}for(let r of t.foregroundChannels)console.log(`[NotificationRouter] appendDebounced -> session=${t.id}, channel=${r}`),this.appendDebounced(t.id,r,n)}onToolUse(t,n,r){if(console.log(`[NotificationRouter] onToolUse session=${t.id}, tool=${n}, fgChannels=${JSON.stringify([...t.foregroundChannels])}`),t.foregroundChannels.size===0)return;let o=nl(r),s=`\u{1F527} ${n}${o?` \u2014 ${o}`:""}`;for(let a of t.foregroundChannels)this.flushDebounced(t.id,a),this.sendMessage(a,s)}onSessionComplete(t){console.log(`[NotificationRouter] onSessionComplete session=${t.id} (${t.name}), status=${t.status}, fgChannels=${JSON.stringify([...t.foregroundChannels])}`);for(let r of t.foregroundChannels)this.flushDebounced(t.id,r);let n=tl(t);for(let r of t.foregroundChannels)this.sendMessage(r,n);this.cleanupSession(t.id)}onBudgetExhausted(t){for(let o of t.foregroundChannels)this.flushDebounced(t.id,o);let n=X(t.duration),r=[`\u26D4 Session limit reached \u2014 ${t.name} [${t.id}] (${n})`,` \u{1F4C1} ${t.workdir}`].join(`
|
|
59
|
+
`);for(let o of t.foregroundChannels)this.sendMessage(o,r);this.cleanupSession(t.id)}onWaitingForInput(t){console.log(`[NotificationRouter] onWaitingForInput session=${t.id} (${t.name}), fgChannels=${JSON.stringify([...t.foregroundChannels])}`);for(let n of t.foregroundChannels)this.flushDebounced(t.id,n);for(let n of t.foregroundChannels){let r=X(t.duration),o=[`\u{1F4AC} Session ${t.name} [${t.id}] is waiting for input (${r})`," Use claude_respond to reply."].join(`
|
|
60
|
+
`);this.sendMessage(n,o)}}emitToChannel(t,n){this.sendMessage(t,n)}checkLongRunning(){if(!this.getActiveSessions)return;let t=this.getActiveSessions(),n=Date.now();for(let r of t)if((r.status==="running"||r.status==="starting")&&r.foregroundChannels.size===0&&!this.longRunningReminded.has(r.id)&&n-r.startedAt>el){this.longRunningReminded.add(r.id);let o=X(n-r.startedAt),s=[`\u23F1\uFE0F Session ${r.name} [${r.id}] running for ${o}`,` \u{1F4C1} ${r.workdir}`," Use claude_fg to check on it, or claude_kill to stop it."].join(`
|
|
61
|
+
`);r.originChannel&&this.sendMessage(r.originChannel,s)}}debounceKey(t,n){return`${t}|${n}`}appendDebounced(t,n,r){let o=this.debounceKey(t,n),s=this.debounceMap.get(o);if(s)clearTimeout(s.timer),s.buffer+=r,s.timer=setTimeout(()=>{this.flushDebounced(t,n)},ii);else{let a=setTimeout(()=>{this.flushDebounced(t,n)},ii);this.debounceMap.set(o,{buffer:r,timer:a})}}flushDebounced(t,n){let r=this.debounceKey(t,n),o=this.debounceMap.get(r);o&&(clearTimeout(o.timer),o.buffer&&(console.log(`[NotificationRouter] flushDebounced -> session=${t}, channel=${n}, bufferLen=${o.buffer.length}`),this.sendMessage(n,o.buffer)),this.debounceMap.delete(r))}cleanupSession(t){for(let n of this.debounceMap.keys())if(n.startsWith(`${t}|`)){let r=this.debounceMap.get(n);clearTimeout(r.timer),this.debounceMap.delete(n)}this.longRunningReminded.delete(t)}};function tl(e){let t=X(e.duration),n=e.prompt.length>60?e.prompt.slice(0,60)+"...":e.prompt;if(e.status==="completed")return[`\u2705 Claude Code [${e.id}] completed (${t})`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${n}"`].join(`
|
|
60
62
|
`);if(e.status==="failed"){let r=e.error?` \u26A0\uFE0F ${e.error}`:e.result?.subtype?` \u26A0\uFE0F ${e.result.subtype}`:"";return[`\u274C Claude Code [${e.id}] failed (${t})`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${n}"`,...r?[r]:[]].join(`
|
|
61
63
|
`)}return e.status==="killed"?[`\u26D4 Claude Code [${e.id}] killed (${t})`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${n}"`].join(`
|
|
62
|
-
`):`Session [${e.id}] finished with status: ${e.status}`}function
|
|
64
|
+
`):`Session [${e.id}] finished with status: ${e.status}`}function nl(e){if(!e||typeof e!="object")return"";if(e.file_path)return Mt(e.file_path,60);if(e.path)return Mt(e.path,60);if(e.command)return Mt(e.command,80);if(e.pattern)return Mt(e.pattern,60);if(e.glob)return Mt(e.glob,60);let t=Object.values(e).find(n=>typeof n=="string"&&n.length>0);return t?Mt(String(t),60):""}function Mt(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}var ai=require("child_process");function rl(e){let t=null,n=null,r=null,o=(s,a)=>{console.log(`[PLUGIN] registerTool factory called for ${s}`),console.log(`[PLUGIN] ctx keys: ${a?Object.keys(a).join(", "):"null/undefined"}`),console.log(`[PLUGIN] ctx.agentAccountId=${a?.agentAccountId}`),console.log(`[PLUGIN] ctx.messageChannel=${a?.messageChannel}`),console.log(`[PLUGIN] ctx.agentId=${a?.agentId}`),console.log(`[PLUGIN] ctx.sessionKey=${a?.sessionKey}`),console.log(`[PLUGIN] ctx.workspaceDir=${a?.workspaceDir}`),console.log(`[PLUGIN] ctx.sandboxed=${a?.sandboxed}`),console.log(`[PLUGIN] full ctx: ${JSON.stringify(a,null,2)}`)};e.registerTool(s=>(o("claude_launch",s),js(s)),{optional:!1}),e.registerTool(s=>(o("claude_sessions",s),_s(s)),{optional:!1}),e.registerTool(s=>(o("claude_kill",s),Ls(s)),{optional:!1}),e.registerTool(s=>(o("claude_output",s),Gs(s)),{optional:!1}),e.registerTool(s=>(o("claude_fg",s),Ds(s)),{optional:!1}),e.registerTool(s=>(o("claude_bg",s),Bs(s)),{optional:!1}),e.registerTool(s=>(o("claude_respond",s),Vs(s)),{optional:!1}),e.registerTool(s=>(o("claude_stats",s),vs(s)),{optional:!1}),qs(e),Ws(e),zs(e),Hs(e),Js(e),Ys(e),Xs(e),Zs(e),Qs(e),e.registerService({id:"openclaw-claude-code-plugin",start:()=>{let s=e.pluginConfig??e.getConfig?.()??{};console.log("[claude-code-plugin] Raw config from getConfig():",JSON.stringify(s)),ks(s),t=new Cn(U.maxSessions,U.maxPersistedSessions),cr(t);let a=(m,p)=>{let g="telegram",I="",j;if(U.fallbackChannel?.includes("|")){let $=U.fallbackChannel.split("|");$.length>=3&&$[0]&&$[1]?(g=$[0],j=$[1],I=$.slice(2).join("|")):$[0]&&$[1]&&(g=$[0],I=$[1])}let ne=g,H=I,ue=j;if(m==="unknown"||!m)if(I)console.log(`[claude-code] sendMessage: channelId="${m}", using fallback ${g}|${I}${j?` (account=${j})`:""}`);else{console.warn(`[claude-code] sendMessage: channelId="${m}" and no fallbackChannel configured \u2014 message will not be sent`);return}else if(m.includes("|")){let $=m.split("|");$.length>=3?(ne=$[0],ue=$[1],H=$.slice(2).join("|")):$[0]&&$[1]&&(ne=$[0],H=$[1])}else if(/^-?\d+$/.test(m))ne="telegram",H=m;else if(I)console.log(`[claude-code] sendMessage: unrecognized channelId="${m}", using fallback ${g}|${I}`);else{console.warn(`[claude-code] sendMessage: unrecognized channelId="${m}" and no fallbackChannel configured \u2014 message will not be sent`);return}console.log(`[claude-code] sendMessage -> channel=${ne}, target=${H}${ue?`, account=${ue}`:""}, textLen=${p.length}`);let Xe=["message","send","--channel",ne];ue&&Xe.push("--account",ue),Xe.push("--target",H,"-m",p),(0,ai.execFile)("openclaw",Xe,{timeout:15e3},($,B,ct)=>{$?(console.error(`[claude-code] sendMessage CLI ERROR: ${$.message}`),ct&&console.error(`[claude-code] sendMessage CLI STDERR: ${ct}`)):(console.log(`[claude-code] sendMessage CLI OK -> channel=${ne}, target=${H}${ue?`, account=${ue}`:""}`),B.trim()&&console.log(`[claude-code] sendMessage CLI STDOUT: ${B.trim()}`))})};n=new $n(a),mr(n),t.notificationRouter=n,n.startReminderCheck(()=>t?.list("running")??[]),r=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{n&&n.stop(),t&&t.killAll(),r&&clearInterval(r),r=null,t=null,n=null,cr(null),mr(null)}})}0&&(module.exports={register});
|