@betrue/openclaw-claude-code-plugin 1.0.6 → 1.0.9

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 CHANGED
@@ -1,131 +1,150 @@
1
- # Claude Code Plugin
1
+ # OpenClaw plugin to orchestrate Claude Code
2
2
 
3
- **An OpenClaw plugin that orchestrates Claude Code sessions as managed background processes.**
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 any OpenClaw channel (Telegram, Discord, etc.). Turn OpenClaw into a control plane for autonomous coding agents — launch tasks, stream output in real time, send follow-up messages, resume previous conversations, and catch up on missed output all without leaving your chat interface.
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
  [![Demo Video](https://img.youtube.com/vi/vbX1Y0Nx4Tc/maxresdefault.jpg)](https://youtube.com/shorts/vbX1Y0Nx4Tc)
8
8
 
9
- *Orchestrating two parallel Claude Code agents from Telegram — building an X clone and an Instagram clone simultaneously.*
9
+ *Two parallel Claude Code agents building an X clone and an Instagram clone simultaneously from Telegram.*
10
10
 
11
11
  ---
12
12
 
13
- ## Features
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
- ### From npm
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
- ### From source
22
+ ### 2. Configure notifications (minimal)
41
23
 
42
- ```bash
43
- git clone git@github.com:alizarion/openclaw-claude-code-plugin.git
44
- openclaw plugins install ./openclaw-claude-code-plugin
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
- ### For development (symlink)
33
+ ### 3. Launch your first session
48
34
 
49
- ```bash
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
- ### After installation
37
+ On first launch, the plugin runs **4 safety checks** and guides you through one-time setup:
55
38
 
56
- Restart the gateway to load the plugin:
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
- ```bash
59
- openclaw gateway restart
60
- ```
43
+ That's it. Future launches skip setup entirely.
61
44
 
62
- Ensure `openclaw` CLI is available in your PATH — the plugin shells out to `openclaw message send` for notifications and `openclaw system event` for agent triggers.
45
+ > Full first-launch walkthrough: [docs/safety.md](docs/safety.md)
63
46
 
64
47
  ---
65
48
 
66
- ## Pre-Launch Safety Checks
49
+ ## Features
67
50
 
68
- When an agent calls the `claude_launch` tool, five mandatory guards run before any session is spawned. If any check fails, the launch is blocked and an actionable error message is returned telling the agent exactly how to fix the issue. These checks are enforced only on the `claude_launch` tool — the gateway RPC `claude-code.launch` method and `/claude` chat command skip them.
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
- ### 1. Autonomy Skill
60
+ ---
71
61
 
72
- **Checks for:** `{agentWorkspace}/skills/claude-code-autonomy/SKILL.md`
62
+ ## Tools
73
63
 
74
- The autonomy skill defines how the agent handles Claude Code interactions (auto-respond to routine questions, forward architecture decisions to the user, etc.). The skill must include 👋/🤖 notification format guidance for user-facing messages. Without it, the agent is told to ask the user what level of autonomy they want, then create the skill directory with `SKILL.md` and `autonomy.md`.
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
- ### 2. Heartbeat Configuration
75
+ All tools are also available as **chat commands** (`/claude`, `/claude_fg`, etc.) and most as **gateway RPC methods**.
77
76
 
78
- **Checks for:** `heartbeat` field in `~/.openclaw/openclaw.json` under `agents.list[]` for the current agent (resolved from `ctx.agentId` or `resolveAgentId(workdir)` via the `agentChannels` mapping).
77
+ > Full parameter tables and response schemas: [docs/API.md](docs/API.md)
79
78
 
80
- Heartbeat enables automatic "waiting for input" notifications so the agent gets nudged when a Claude Code session needs attention. The expected config:
79
+ ---
81
80
 
82
- ```json
83
- { "heartbeat": { "every": "60m", "target": "last" } }
84
- ```
81
+ ## Quick Usage
85
82
 
86
- ### 3. Heartbeat Interval Validation
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
- **Checks for:** Heartbeat interval ≥ 60 minutes. A 5-second interval (`"every": "5s"`) is explicitly blocked.
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
- The init prompt recommends `"every": "60m"`. Short intervals cause excessive heartbeat cycles and are not suitable for production agent operation.
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
- ### 4. Gateway Restart Guard
104
+ ---
93
105
 
94
- **Checks for:** The agent must NOT attempt to restart the OpenClaw gateway itself.
106
+ ## Notifications
95
107
 
96
- If the gateway needs restarting (e.g., after config changes), the agent must ask the user to do it. This prevents agents from disrupting other running agents or services by cycling the gateway process.
108
+ The plugin sends real-time notifications to your chat based on session lifecycle events:
97
109
 
98
- ### 5. agentChannels Mapping
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
- **Checks for:** A matching entry in `pluginConfig.agentChannels` for the session's working directory, resolved via `resolveAgentChannel(workdir)`.
119
+ Foreground sessions stream full output in real time. Background sessions only send lifecycle notifications.
101
120
 
102
- The workspace must be mapped to a notification channel so session events (completion, waiting-for-input, etc.) reach the correct agent/chat. Uses longest-prefix matching with trailing slash normalisation.
121
+ > Notification architecture and delivery model: [docs/NOTIFICATIONS.md](docs/NOTIFICATIONS.md)
103
122
 
104
123
  ---
105
124
 
106
125
  ## Configuration
107
126
 
108
- Configuration is defined in `openclaw.plugin.json` and passed to the plugin via `api.getConfig()`. Set values in `~/.openclaw/openclaw.json` under `plugins.config["openclaw-claude-code-plugin"]`.
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
- | `maxSessions` | `number` | `5` | Max concurrently active sessions. |
113
- | `maxAutoResponds` | `number` | `10` | Max consecutive agent auto-responds per session. Resets on user `/claude_respond`. Blocks `claude_respond` tool when reached. |
114
- | `defaultBudgetUsd` | `number` | `5` | Default max budget per session in USD. |
115
- | `defaultModel` | `string` | | Default model (e.g. `"sonnet"`, `"opus"`). |
116
- | `defaultWorkdir` | `string` | | Default working directory. Falls back to `process.cwd()`. |
117
- | `idleTimeoutMinutes` | `number` | `30` | Idle timeout for multi-turn sessions before auto-kill. |
118
- | `maxPersistedSessions` | `number` | `50` | Max completed sessions kept for resume. |
119
- | `fallbackChannel` | `string` | — | Fallback notification channel (e.g. `"telegram\|123456789"`). |
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
+ | `skipSafetyChecks` | `boolean` | `false` | Skip ALL pre-launch safety guards (autonomy skill, heartbeat, HEARTBEAT.md, agentChannels). For dev/testing only. |
140
+
141
+ ### Example
122
142
 
123
143
  ```json
124
144
  {
125
145
  "maxSessions": 3,
126
146
  "defaultBudgetUsd": 10,
127
147
  "defaultModel": "sonnet",
128
- "defaultWorkdir": "/home/user/projects",
129
148
  "permissionMode": "bypassPermissions",
130
149
  "fallbackChannel": "telegram|main-bot|123456789",
131
150
  "agentChannels": {
@@ -137,154 +156,62 @@ Configuration is defined in `openclaw.plugin.json` and passed to the plugin via
137
156
 
138
157
  ---
139
158
 
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
159
  ## Skill Example
232
160
 
233
- Claude Code Plugin is a **transparent transport layer** — it spawns sessions and delivers notifications, but business logic lives in **OpenClaw skills**. Here's a minimal skill that orchestrates coding agent sessions:
161
+ <details>
162
+ <summary>Example orchestration skill (click to expand)</summary>
234
163
 
235
- ### `coding-agent/SKILL.md`
164
+ The plugin is a **transparent transport layer** — business logic lives in **OpenClaw skills**:
236
165
 
237
166
  ```markdown
238
167
  ---
239
168
  name: Coding Agent Orchestrator
240
- description: Orchestrates Claude Code sessions with smart auto-response rules for routine questions and user forwarding for critical decisions.
169
+ description: Orchestrates Claude Code sessions with auto-response rules.
241
170
  metadata: {"openclaw": {"requires": {"plugins": ["openclaw-claude-code-plugin"]}}}
242
171
  ---
243
172
 
244
173
  # Coding Agent Orchestrator
245
174
 
246
- You are a coding agent orchestrator. You manage Claude Code sessions via the claude-code plugin tools.
247
-
248
175
  ## Auto-response rules
249
176
 
250
- When a Claude Code session asks a question (wake event), analyze it and decide:
177
+ When a Claude Code session asks a question, analyze and decide:
251
178
 
252
179
  ### Auto-respond (use `claude_respond` immediately):
253
180
  - Permission requests for file reads, writes, or bash commands -> "Yes, proceed."
254
181
  - Confirmation prompts like "Should I continue?" -> "Yes, continue."
255
- - Questions about approach when only one is reasonable -> respond with the obvious choice
256
182
 
257
183
  ### Forward to user:
258
184
  - Architecture decisions (Redis vs PostgreSQL, REST vs GraphQL...)
259
185
  - Destructive operations (deleting files, dropping tables...)
260
186
  - Anything involving credentials, secrets, or production environments
261
- - When in doubt -> always forward to the user
262
187
 
263
188
  ## Workflow
264
-
265
189
  1. User sends a coding task -> `claude_launch(prompt, ...)`
266
190
  2. Session runs in background. Monitor via wake events.
267
191
  3. On wake event -> `claude_output` to read the question, then auto-respond or forward.
268
- 4. On user reply to a forwarded question -> `claude_respond` with their answer.
269
- 5. On completion -> summarize the result and notify the user.
192
+ 4. On completion -> summarize the result and notify the user.
270
193
  ```
271
194
 
272
195
  A comprehensive orchestration skill is available at [`skills/claude-code-orchestration/SKILL.md`](skills/claude-code-orchestration/SKILL.md).
273
196
 
197
+ </details>
198
+
274
199
  ---
275
200
 
276
201
  ## Documentation
277
202
 
278
203
  | Document | Description |
279
- |---|---|
280
- | [docs/API.md](docs/API.md) | Full API reference — tools, commands, and RPC methods with parameter tables |
281
- | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Architecture diagram and component breakdown |
282
- | [docs/NOTIFICATIONS.md](docs/NOTIFICATIONS.md) | Notification matrix, delivery details, and agent wake events |
283
- | [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) | Project structure, dependencies, design decisions, and contribution guide |
204
+ |----------|-------------|
205
+ | [docs/getting-started.md](docs/getting-started.md) | Full setup guide and first-launch walkthrough |
206
+ | [docs/API.md](docs/API.md) | Tools, commands, and RPC methods — full parameter tables and response schemas |
207
+ | [docs/safety.md](docs/safety.md) | Pre-launch safety checks and troubleshooting |
208
+ | [docs/NOTIFICATIONS.md](docs/NOTIFICATIONS.md) | Notification architecture, delivery model, and wake mechanism |
284
209
  | [docs/AGENT_CHANNELS.md](docs/AGENT_CHANNELS.md) | Multi-agent setup, notification routing, and workspace mapping |
210
+ | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Architecture overview and component breakdown |
211
+ | [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) | Development guide, project structure, and build instructions |
285
212
 
286
213
  ---
287
214
 
288
215
  ## License
289
216
 
290
- See the project repository for license information.
217
+ MIT see [package.json](package.json) for details.
package/dist/index.js CHANGED
@@ -1,62 +1,64 @@
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 At(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?Z(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 _s(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 D=d.resolveClaudeSessionId(s);if(!D)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=D}let a;if(e.messageChannel&&e.agentAccountId){let D=e.messageChannel.split("|");D.length>=2&&(a=`${D[0]}|${e.agentAccountId}|${D.slice(1).join("|")}`)}!a&&e.workspaceDir&&(a=v(e.workspaceDir)),!a&&e.messageChannel&&e.messageChannel.includes("|")&&(a=e.messageChannel);let m=X({id:t},a||v(r));if(m==="unknown"){let D=v(r);D&&(m=D)}let p=e.workspaceDir||r,g=(0,Sn.join)(p,"skills","claude-code-autonomy","SKILL.md");if(!(0,ut.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||Ks(p);if(I){let D=(0,Sn.join)((0,Es.homedir)(),".openclaw","openclaw.json"),mt=!1,fr;try{if((0,ut.existsSync)(D)){let $n=(0,ut.readFileSync)(D,"utf-8"),gr=JSON.parse($n)?.agents?.list;if(Array.isArray(gr)){let wn=gr.find(ai=>ai.id===I);wn&&wn.heartbeat!=null&&(mt=!0,fr=wn.heartbeat.every)}}}catch($n){console.log(`[claude-launch] Failed to read openclaw config at ${D}: ${$n.message}`)}if(!mt)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 system event --text 'Heartbeat configured, continuing task' --mode now",' STEP 4: Continue the original task: [USER_TASK]",',' name="setup-heartbeat"'," )"].join(`
5
- `)}]};if(fr==="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. System events use --mode now to 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 W=(0,Sn.join)(p,"HEARTBEAT.md"),re=!1;try{if((0,ut.existsSync)(W)){let D=(0,ut.readFileSync)(W,"utf-8");/^(\s|#.*)*$/.test(D)||(re=!0)}}catch(D){console.log(`[claude-launch] Failed to read HEARTBEAT.md at ${W}: ${D.message}`)}if(!re)return console.log(`[claude-launch] HEARTBEAT.md missing or empty at ${W} \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 so the agent can check for waiting sessions.","","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","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 5s for fast response:","",`cat ~/.openclaw/openclaw.json | jq '.agents.list[] | select(.id == "${I}") | .heartbeat.every'`,"",'If NOT "5s", update it:',"",`jq '.agents.list |= map(if .id == "${I}" then .heartbeat.every = "5s" 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 system event --text 'HEARTBEAT.md configured' --mode now",' STEP 4: Continue task: [USER_TASK]",',' name="setup-heartbeat-md"'," )"].join(`
7
- `)}]};if(!v(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}),Xe=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,O=["Session launched successfully.",` Name: ${ue.name}`,` ID: ${ue.id}`,` Dir: ${r}`,` Model: ${ue.model??"default"}`,` Prompt: "${Xe}"`];return n.resume_session_id&&O.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),n.multi_turn_disabled?O.push(" Mode: single-turn (fire-and-forget)"):O.push(" Mode: multi-turn (use claude_respond to send follow-up messages)"),O.push(""),O.push("Use claude_sessions to check status, claude_output to see output."),{content:[{type:"text",text:O.join(`
9
- `)}]}}catch(s){return{content:[{type:"text",text:`Error launching session: ${s.message}`}]}}}}}function Gs(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=v(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(Ft).join(`
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:()=>D,IsAsyncIterator:()=>Rn,IsBigInt:()=>Ut,IsBoolean:()=>Ke,IsDate:()=>Ze,IsFunction:()=>Fn,IsIterator:()=>An,IsNull:()=>Mn,IsNumber:()=>ue,IsObject:()=>C,IsRegExp:()=>kt,IsString:()=>A,IsSymbol:()=>Un,IsUint8Array:()=>Ee,IsUndefined:()=>B});function Xt(e,t){return t in e}function Rn(e){return C(e)&&!D(e)&&!Ee(e)&&Symbol.asyncIterator in e}function D(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 C(e)&&!D(e)&&!Ee(e)&&Symbol.iterator in e}function Mn(e){return e===null}function ue(e){return typeof e=="number"}function C(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 Ee(e){return e instanceof globalThis.Uint8Array}function B(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 D(e)?Ii(e):Ze(e)?hi(e):Ee(e)?yi(e):kt(e)?xi(e):C(e)?bi(e):e}function N(e){return Zt(e)}function mt(e,t){return t===void 0?N(e):N({...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=>Pt(t))}function Ti(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Pt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Pt(e[n]);return globalThis.Object.freeze(t)}function Pt(e){return D(e)?Si(e):Ze(e)?e:Ee(e)?e:kt(e)?e:C(e)?Ti(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(Qt.InstanceMode){case"freeze":return Pt(n);case"clone":return N(n);default:return n}}var z=class extends Error{constructor(t){super(t)}};var v=Symbol.for("TypeBox.Transform"),Se=Symbol.for("TypeBox.Readonly"),J=Symbol.for("TypeBox.Optional"),ge=Symbol.for("TypeBox.Hint"),l=Symbol.for("TypeBox.Kind");function lt(e){return C(e)&&e[Se]==="Readonly"}function oe(e){return C(e)&&e[J]==="Optional"}function kn(e){return h(e,"Any")}function Pn(e){return h(e,"Argument")}function Te(e){return h(e,"Array")}function Qe(e){return h(e,"AsyncIterator")}function et(e){return h(e,"BigInt")}function je(e){return h(e,"Boolean")}function Ce(e){return h(e,"Computed")}function $e(e){return h(e,"Constructor")}function Ci(e){return h(e,"Date")}function Oe(e){return h(e,"Function")}function we(e){return h(e,"Integer")}function _(e){return h(e,"Intersect")}function tt(e){return h(e,"Iterator")}function h(e,t){return C(e)&&l in e&&e[l]===t}function en(e){return Ke(e)||ue(e)||A(e)}function ce(e){return h(e,"Literal")}function me(e){return h(e,"MappedKey")}function K(e){return h(e,"MappedResult")}function Be(e){return h(e,"Never")}function $i(e){return h(e,"Not")}function Nt(e){return h(e,"Null")}function Re(e){return h(e,"Number")}function V(e){return h(e,"Object")}function nt(e){return h(e,"Promise")}function rt(e){return h(e,"Record")}function G(e){return h(e,"Ref")}function Nn(e){return h(e,"RegExp")}function _e(e){return h(e,"String")}function Kt(e){return h(e,"Symbol")}function le(e){return h(e,"TemplateLiteral")}function Oi(e){return h(e,"This")}function Ve(e){return C(e)&&v in e}function de(e){return h(e,"Tuple")}function Et(e){return h(e,"Undefined")}function y(e){return h(e,"Union")}function wi(e){return h(e,"Uint8Array")}function Ri(e){return h(e,"Unknown")}function Fi(e){return h(e,"Unsafe")}function Ai(e){return h(e,"Void")}function Mi(e){return C(e)&&l in e&&A(e[l])}function pe(e){return kn(e)||Pn(e)||Te(e)||je(e)||et(e)||Qe(e)||Ce(e)||$e(e)||Ci(e)||Oe(e)||we(e)||_(e)||tt(e)||ce(e)||me(e)||K(e)||Be(e)||$i(e)||Nt(e)||Re(e)||V(e)||nt(e)||rt(e)||G(e)||Nn(e)||_e(e)||Kt(e)||le(e)||Oi(e)||de(e)||Et(e)||y(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:()=>kr,IsImport:()=>Ei,IsInteger:()=>Pr,IsIntersect:()=>Nr,IsIterator:()=>Kr,IsKind:()=>ao,IsKindOf:()=>I,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:()=>H,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 z{},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)||H(e)}function jt(e){return B(e)||Ut(e)}function M(e){return B(e)||ue(e)}function jn(e){return B(e)||Ke(e)}function $(e){return B(e)||A(e)}function ki(e){return B(e)||A(e)&&En(e)&&br(e)}function Pi(e){return B(e)||A(e)&&En(e)}function Tr(e){return B(e)||H(e)}function Ni(e){return C(e)&&e[Se]==="Readonly"}function Ki(e){return C(e)&&e[J]==="Optional"}function Cr(e){return I(e,"Any")&&$(e.$id)}function $r(e){return I(e,"Argument")&&ue(e.index)}function Or(e){return I(e,"Array")&&e.type==="array"&&$(e.$id)&&H(e.items)&&M(e.minItems)&&M(e.maxItems)&&jn(e.uniqueItems)&&Tr(e.contains)&&M(e.minContains)&&M(e.maxContains)}function wr(e){return I(e,"AsyncIterator")&&e.type==="AsyncIterator"&&$(e.$id)&&H(e.items)}function Rr(e){return I(e,"BigInt")&&e.type==="bigint"&&$(e.$id)&&jt(e.exclusiveMaximum)&&jt(e.exclusiveMinimum)&&jt(e.maximum)&&jt(e.minimum)&&jt(e.multipleOf)}function Fr(e){return I(e,"Boolean")&&e.type==="boolean"&&$(e.$id)}function Ar(e){return I(e,"Computed")&&A(e.target)&&D(e.parameters)&&e.parameters.every(t=>H(t))}function Mr(e){return I(e,"Constructor")&&e.type==="Constructor"&&$(e.$id)&&D(e.parameters)&&e.parameters.every(t=>H(t))&&H(e.returns)}function Ur(e){return I(e,"Date")&&e.type==="Date"&&$(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function kr(e){return I(e,"Function")&&e.type==="Function"&&$(e.$id)&&D(e.parameters)&&e.parameters.every(t=>H(t))&&H(e.returns)}function Ei(e){return I(e,"Import")&&Xt(e,"$defs")&&C(e.$defs)&&tn(e.$defs)&&Xt(e,"$ref")&&A(e.$ref)&&e.$ref in e.$defs}function Pr(e){return I(e,"Integer")&&e.type==="integer"&&$(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function tn(e){return C(e)&&Object.entries(e).every(([t,n])=>En(t)&&H(n))}function Nr(e){return I(e,"Intersect")&&!(A(e.type)&&e.type!=="object")&&D(e.allOf)&&e.allOf.every(t=>H(t)&&!eo(t))&&$(e.type)&&(jn(e.unevaluatedProperties)||Tr(e.unevaluatedProperties))&&$(e.$id)}function Kr(e){return I(e,"Iterator")&&e.type==="Iterator"&&$(e.$id)&&H(e.items)}function I(e,t){return C(e)&&l in e&&e[l]===t}function Er(e){return _t(e)&&A(e.const)}function jr(e){return _t(e)&&ue(e.const)}function ji(e){return _t(e)&&Ke(e.const)}function _t(e){return I(e,"Literal")&&$(e.$id)&&_r(e.const)}function _r(e){return Ke(e)||ue(e)||A(e)}function Lr(e){return I(e,"MappedKey")&&D(e.keys)&&e.keys.every(t=>ue(t)||A(t))}function Gr(e){return I(e,"MappedResult")&&tn(e.properties)}function Dr(e){return I(e,"Never")&&C(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Br(e){return I(e,"Not")&&H(e.not)}function Vr(e){return I(e,"Null")&&e.type==="null"&&$(e.$id)}function vr(e){return I(e,"Number")&&e.type==="number"&&$(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function qr(e){return I(e,"Object")&&e.type==="object"&&$(e.$id)&&tn(e.properties)&&Sr(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function Wr(e){return I(e,"Promise")&&e.type==="Promise"&&$(e.$id)&&H(e.item)}function zr(e){return I(e,"Record")&&e.type==="object"&&$(e.$id)&&Sr(e.additionalProperties)&&C(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&br(n[0])&&C(t.patternProperties)&&H(t.patternProperties[n[0]])})(e)}function _i(e){return C(e)&&ge in e&&e[ge]==="Recursive"}function Hr(e){return I(e,"Ref")&&$(e.$id)&&A(e.$ref)}function Jr(e){return I(e,"RegExp")&&$(e.$id)&&A(e.source)&&A(e.flags)&&M(e.maxLength)&&M(e.minLength)}function Yr(e){return I(e,"String")&&e.type==="string"&&$(e.$id)&&M(e.minLength)&&M(e.maxLength)&&ki(e.pattern)&&Pi(e.format)}function Xr(e){return I(e,"Symbol")&&e.type==="symbol"&&$(e.$id)}function Zr(e){return I(e,"TemplateLiteral")&&e.type==="string"&&A(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Qr(e){return I(e,"This")&&$(e.$id)&&A(e.$ref)}function eo(e){return C(e)&&v in e}function to(e){return I(e,"Tuple")&&e.type==="array"&&$(e.$id)&&ue(e.minItems)&&ue(e.maxItems)&&e.minItems===e.maxItems&&(B(e.items)&&B(e.additionalItems)&&e.minItems===0||D(e.items)&&e.items.every(t=>H(t)))}function no(e){return I(e,"Undefined")&&e.type==="undefined"&&$(e.$id)}function Li(e){return _n(e)&&e.anyOf.every(t=>Er(t)||jr(t))}function _n(e){return I(e,"Union")&&$(e.$id)&&C(e)&&D(e.anyOf)&&e.anyOf.every(t=>H(t))}function ro(e){return I(e,"Uint8Array")&&e.type==="Uint8Array"&&$(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function oo(e){return I(e,"Unknown")&&$(e.$id)}function so(e){return I(e,"Unsafe")}function io(e){return I(e,"Void")&&e.type==="void"&&$(e.$id)}function ao(e){return C(e)&&l in e&&A(e[l])&&!Ui.includes(e[l])}function H(e){return C(e)&&(Cr(e)||$r(e)||Or(e)||Fr(e)||Rr(e)||wr(e)||Ar(e)||Mr(e)||Ur(e)||kr(e)||Pr(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}$`,qe=`^${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 We(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 k(e,t,n){return u({[l]:"Computed",target:e,parameters:t},n)}function Vi(e,t){let{[t]:n,...r}=e;return r}function L(e,t){return t.reduce((n,r)=>Vi(n,r),e)}function x(e){return u({[l]:"Never",not:{}},e)}function b(e){return u({[l]:"MappedResult",properties:e})}function ft(e,t,n){return u({[l]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function ke(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 L(e,[J])}function Wi(e,t){return vi(e)?Q(Gt(go(e),t)):Gt(go(e),t)}function Pe(e,t){return e.length===1?u(e[0],t):e.length===0?x(t):Wi(e,t)}function T(e,t){return e.length===0?x(t):e.length===1?u(e[0],t):Gt(e,t)}var nn=class extends z{};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 z{};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 z{};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 S(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 Ie(e){return u({[l]:"Number",type:"number"},e)}function Fe(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 Ie():t==="bigint"?yield ht():t==="string"?yield Fe():yield(()=>{let n=t.split("|").map(r=>S(r.trim()));return n.length===0?x():n.length===1?n[0]:Pe(n)})()}function*aa(e){if(e[1]!=="{"){let t=S("$"),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 S(e)}function*vn(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=S(e.slice(0,t)),r=aa(e.slice(t));return yield*[n,...r]}yield S(e)}function xo(e){return[...vn(e)]}var qn=class extends z{};function ua(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bo(e,t){return le(e)?e.pattern.slice(1,e.pattern.length-1):y(e)?`(${e.anyOf.map(n=>bo(n,t)).join("|")})`:Re(e)?`${t}${Lt}`:we(e)?`${t}${Lt}`:et(e)?`${t}${Lt}`:_e(e)?`${t}${Gn}`:ce(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=>S(r));return Pe(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(le(e)?ca(e):y(e)?ma(e.anyOf):ce(e)?la(e.const):Re(e)?["[number]"]:we(e)?["[number]"]:[])]}function da(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=ze(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 b(r)}function Co(e,t){return e.map(n=>$o(n,t))}function fa(e){return e.filter(t=>!Be(t))}function ga(e,t){return an(fa(Co(e,t)))}function Ia(e){return e.some(t=>Be(t))?[]:e}function ha(e,t){return Pe(Ia(Co(e,t)))}function ya(e,t){return t in e?e[t]:t==="[number]"?Pe(e):x()}function xa(e,t){return t==="[number]"?e:x()}function ba(e,t){return t in e?e[t]:x()}function $o(e,t){return _(e)?ga(e.allOf,t):y(e)?ha(e.anyOf,t):de(e)?ya(e.items??[],t):Te(e)?xa(e.items,t):V(e)?ba(e.properties,t):x()}function zn(e,t){return t.map(n=>$o(e,n))}function To(e,t){return Pe(zn(e,t))}function ze(e,t,n){if(G(e)||G(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!pe(e)||!pe(t))throw new z(r);return k("Index",[e,t])}return K(t)?So(e,t,n):me(t)?Oo(e,t,n):u(pe(t)?To(e,se(t)):To(e,t),n)}function Sa(e,t,n){return{[t]:ze(e,[t],N(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 b(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 O=Oa;function un(e,t){return u({[l]:"Promise",type:"Promise",item:e},t)}function wa(e){return u(L(e,[Se]))}function Ra(e){return u({...e,[Se]:"Readonly"})}function Fa(e,t){return t===!1?wa(e):Ra(e)}function ie(e,t){let n=t??!0;return K(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 b(n)}function he(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?ye(e,t[e]):b(t)}function Ua(e){return{[e]:S(e)}}function ka(e){let t={};for(let n of e)t[n]=S(n);return t}function Pa(e,t){return co(t,e)?Ua(e):ka(t)}function Na(e,t){let n=Pa(e,t);return Ro(e,n)}function Vt(e,t){return t.map(n=>ye(e,n))}function Ka(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=ye(e,t[r]);return n}function ye(e,t){let n={...t};return oe(t)?Q(ye(e,L(t,[J]))):lt(t)?ie(ye(e,L(t,[Se]))):K(t)?Ro(e,t.properties):me(t)?Na(e,t.keys):$e(t)?ft(Vt(e,t.parameters),ye(e,t.returns),n):Oe(t)?ke(Vt(e,t.parameters),ye(e,t.returns),n):Qe(t)?pt(ye(e,t.items),n):tt(t)?yt(ye(e,t.items),n):_(t)?ee(Vt(e,t.allOf),n):y(t)?T(Vt(e,t.anyOf),n):de(t)?he(Vt(e,t.items??[]),n):V(t)?O(Ka(e,t.properties),n):Te(t)?dt(ye(e,t.items),n):nt(t)?un(ye(e,t.item),n):t}function Ea(e,t){let n={};for(let r of e)n[r]=ye(r,t);return n}function Fo(e,t,n){let r=pe(e)?se(e):e,o=t({[l]:"MappedKey",keys:r}),s=Ea(r,o);return O(s,n)}function ja(e){return u(L(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 K(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 b(n)}function vt(e,t={}){let n=e.every(o=>V(o)),r=pe(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||pe(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 L(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 x(t);if(e.some(n=>Ve(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 x(t);if(e.some(n=>Ve(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 z("Ref: $ref must be a string");return u({[l]:"Ref",$ref:t},n)}function qa(e,t){return k("Awaited",[k(e,t)])}function Wa(e){return k("Awaited",[Ne(e)])}function za(e){return ee(Uo(e))}function Ha(e){return T(Uo(e))}function Ja(e){return xt(e)}function Uo(e){return e.map(t=>xt(t))}function xt(e,t){return u(Ce(e)?qa(e.target,e.parameters):_(e)?za(e.allOf):y(e)?Ha(e.anyOf):nt(e)?Ja(e.item):G(e)?Wa(e.$ref):e,t)}function ko(e){let t=[];for(let n of e)t.push(qt(n));return t}function Ya(e){let t=ko(e);return po(t)}function Xa(e){let t=ko(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 _(e)?Ya(e.allOf):y(e)?Xa(e.anyOf):de(e)?Za(e.items??[]):Te(e)?Qa(e.items):V(e)?eu(e.properties):rt(e)?tu(e.patternProperties):[]}var nu=!1;function ru(e,t){return k("KeyOf",[k(e,t)])}function ou(e){return k("KeyOf",[Ne(e)])}function su(e,t){let n=qt(e),r=iu(n),o=Pe(r);return u(o,t)}function iu(e){return e.map(t=>t==="[number]"?Ie():S(t))}function bt(e,t){return Ce(e)?ru(e.target,e.parameters):G(e)?ou(e.$ref):K(e)?Po(e,t):su(e,t)}function au(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=bt(e[r],N(t));return n}function uu(e,t){return au(e.properties,t)}function Po(e,t){let n=uu(e,t);return b(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=>!Be(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 O(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 He(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(We(),t):An(e)?fn(We(),t):D(e)?ie(he(pu(e))):Ee(e)?pn():Ze(e)?cn():C(e)?fn(O(fu(e)),t):Fn(e)?fn(ke([],He()),t):B(e)?dn():Mn(e)?mn():Un(e)?ln():Ut(e)?ht():ue(e)?S(e):Ke(e)?S(e):A(e)?S(e):O({})}function Ko(e,t){return u(Hn(e,!0),t)}function Eo(e,t){return $e(e)?he(e.parameters,t):x(t)}function jo(e,t){if(B(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=>S(s));return T(o,{...t,[ge]:"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 xe(e){return e===c.False?e:c.True}function St(e){throw new Yn(e)}function q(e){return i.IsNever(e)||i.IsIntersect(e)||i.IsUnion(e)||i.IsUnknown(e)||i.IsAny(e)}function W(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:q(t)?W(e,t):i.IsArray(t)?xe(w(e.items,t.items)):c.False}function yu(e,t){return q(t)?W(e,t):i.IsAsyncIterator(t)?xe(w(e.items,t.items)):c.False}function xu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(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 q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsBoolean(t)?c.True:c.False}function Su(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsConstructor(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>xe(w(t.parameters[r],n))===c.True)?xe(w(e.returns,t.returns)):c.False:c.False}function Tu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsDate(t)?c.True:c.False}function Cu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsFunction(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>xe(w(t.parameters[r],n))===c.True)?xe(w(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:q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):c.False}function gn(e,t){return t.allOf.every(n=>w(e,n)===c.True)?c.True:c.False}function Ou(e,t){return e.allOf.some(n=>w(n,t)===c.True)?c.True:c.False}function wu(e,t){return q(t)?W(e,t):i.IsIterator(t)?xe(w(e.items,t.items)):c.False}function Ru(e,t){return i.IsLiteral(t)&&t.const===e.const?c.True:q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(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:He()}function Au(e,t){return i.IsNot(e)?w(_o(e),t):i.IsNot(t)?w(e,_o(t)):St("Invalid fallthrough for Not")}function Mu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(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 q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(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 ku(e){return ae(e,0)}function Pu(e){return ae(e,0)}function Nu(e){return In(e)}function Ku(e){let t=Ie();return ae(e,0)||ae(e,1)&&"length"in e.properties&&xe(w(e.properties.length,t))===c.True}function Eu(e){return ae(e,0)}function In(e){let t=Ie();return ae(e,0)||ae(e,1)&&"length"in e.properties&&xe(w(e.properties.length,t))===c.True}function ju(e){let t=ke([We()],We());return ae(e,0)||ae(e,1)&&"then"in e.properties&&xe(w(e.properties.then,t))===c.True}function Wo(e,t){return w(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)&&ku(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)&&Pu(t)||i.IsConstructor(e)&&Eu(t)||i.IsFunction(e)&&Ku(t)?c.True:i.IsRecord(e)&&i.IsString(Xn(e))?t[ge]==="Record"?c.True:c.False:i.IsRecord(e)&&i.IsNumber(Xn(e))&&ae(t,0)?c.True:c.False}function _u(e,t){return q(t)?W(e,t):i.IsRecord(t)?be(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 q(t)?W(e,t):i.IsObject(t)&&ju(t)?c.True:i.IsPromise(t)?xe(w(e.item,t.item)):c.False}function Xn(e){return ve in e.patternProperties?Ie():qe in e.patternProperties?Fe():St("Unknown record key pattern")}function Zn(e){return ve in e.patternProperties?e.patternProperties[ve]:qe in e.patternProperties?e.patternProperties[qe]:St("Unable to get record value schema")}function be(e,t){let[n,r]=[Xn(t),Zn(t)];return i.IsLiteralString(e)&&i.IsNumber(n)&&xe(w(e,r))===c.True?c.True:i.IsUint8Array(e)&&i.IsNumber(n)||i.IsString(e)&&i.IsNumber(n)||i.IsArray(e)&&i.IsNumber(n)?w(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 q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?w(Zn(e),Zn(t)):c.False}function Du(e,t){let n=i.IsRegExp(e)?Fe():e,r=i.IsRegExp(t)?Fe():t;return w(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 q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsString(t)?c.True:c.False}function Vu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsSymbol(t)?c.True:c.False}function vu(e,t){return i.IsTemplateLiteral(e)?w(st(e),t):i.IsTemplateLiteral(t)?w(e,st(t)):St("Invalid fallthrough for TemplateLiteral")}function qu(e,t){return i.IsArray(t)&&e.items!==void 0&&e.items.every(n=>w(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 q(t)?W(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)=>w(n,t.items[r])===c.True)?c.True:c.False:c.False}function Hu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsUint8Array(t)?c.True:c.False}function Ju(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsVoid(t)?Zu(e,t):i.IsUndefined(t)?c.True:c.False}function er(e,t){return t.anyOf.some(n=>w(e,n)===c.True)?c.True:c.False}function Yu(e,t){return e.anyOf.every(n=>w(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 w(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 Je(e,t){return w(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,N(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 b(s)}function nc(e,t,n,r){let o=Je(e,t);return o===c.Union?T([n,r]):o===c.True?n:r}function Tt(e,t,n,r,o){return K(e)?Jo(e,t,n,r,o):me(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(S(e),t,n,r,N(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 b(s)}function Xo(e,t){return Ct(st(e),t)}function ic(e,t){let n=e.filter(r=>Je(r,t)===c.False);return n.length===1?n[0]:T(n)}function Ct(e,t,n={}){return le(e)?u(Xo(e,t),n):K(e)?u(Zo(e,t),n):u(y(e)?ic(e.anyOf,t):Je(e,t)!==c.False?x():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 b(n)}function Qo(e,t){return $t(st(e),t)}function cc(e,t){let n=e.filter(r=>Je(r,t)!==c.False);return n.length===1?n[0]:T(n)}function $t(e,t,n){return le(e)?u(Qo(e,t),n):K(e)?u(es(e,t),n):u(y(e)?cc(e.anyOf,t):Je(e,t)!==c.False?e:x(),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 b(n)}function ts(e,t){return $e(e)?u(e.returns,t):x(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 O(r,{...n,[ge]:"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(T(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=B(e.pattern)?qe:e.pattern;return it(r,t,n)}function hc(e,t,n){return it(qe,t,n)}function yc(e,t,n){return it(uo,t,n)}function xc(e,t,n){return O({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 y(e)?pc(e.anyOf,t,n):le(e)?dc(e,t,n):ce(e)?fc(e.const,t,n):je(e)?xc(e,t,n):we(e)?bc(e,t,n):Re(e)?Sc(e,t,n):Nn(e)?gc(e,t,n):_e(e)?Ic(e,t,n):kn(e)?hc(e,t,n):Be(e)?yc(e,t,n):x(n)}function xn(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function ns(e){let t=xn(e);return t===qe?Fe():t===ve?Ie():Fe({pattern:t})}function bn(e){return e.patternProperties[xn(e)]}function Tc(e,t){return t.parameters=Wt(e,t.parameters),t.returns=Ae(e,t.returns),t}function Cc(e,t){return t.parameters=Wt(e,t.parameters),t.returns=Ae(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 B(t.items)||(t.items=Wt(e,t.items)),t}function Rc(e,t){return t.items=Ae(e,t.items),t}function Fc(e,t){return t.items=Ae(e,t.items),t}function Ac(e,t){return t.items=Ae(e,t.items),t}function Mc(e,t){return t.item=Ae(e,t.item),t}function Uc(e,t){let n=Kc(e,t.properties);return{...t,...O(n)}}function kc(e,t){let n=Ae(e,ns(t)),r=Ae(e,bn(t)),o=yn(n,r);return{...t,...o}}function Pc(e,t){return t.index in e?e[t.index]:He()}function Nc(e,t){let n=lt(t),r=oe(t),o=Ae(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=>Ae(e,n))}function Ae(e,t){return $e(t)?Tc(e,t):Oe(t)?Cc(e,t):_(t)?$c(e,t):y(t)?Oc(e,t):de(t)?wc(e,t):Te(t)?Rc(e,t):Qe(t)?Fc(e,t):tt(t)?Ac(e,t):nt(t)?Mc(e,t):V(t)?Uc(e,t):rt(t)?kc(e,t):Pn(t)?Pc(e,t):t}function rs(e,t){return Ae(t,mt(e))}function os(e){return u({[l]:"Integer",type:"integer"},e)}function Ec(e,t,n){return{[e]:Me(S(e),t,N(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 b(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=>S(g)),m=as(a,t),p=T(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=>Me(n,t))}function Me(e,t,n={}){return me(e)?ss(e,t,n):le(e)?Vc(e,t,n):y(e)?T(as(e.anyOf,t),n):ce(e)?S(is(e.const,t),n):u(e,n)}function us(e,t={}){return Me(e,"Capitalize",t)}function cs(e,t={}){return Me(e,"Lowercase",t)}function ms(e,t={}){return Me(e,"Uncapitalize",t)}function ls(e,t={}){return Me(e,"Uppercase",t)}function vc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ye(e[o],t,N(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 b(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=L(e,[v,"$id","required","properties"]),o=Jc(n,t);return O(o,r)}function Xc(e){let t=e.reduce((n,r)=>en(r)?[...n,S(r)]:n,[]);return T(t)}function nr(e,t){return _(e)?ee(Wc(e.allOf,t)):y(e)?T(zc(e.anyOf,t)):V(e)?Yc(e,t,e.properties):O({})}function Ye(e,t,n){let r=D(t)?Xc(t):t,o=pe(t)?se(t):t,s=G(e),a=G(t);return K(e)?ds(e,o,n):me(t)?ps(e,t,n):s&&a?k("Omit",[e,r],n):!s&&a?k("Omit",[e,r],n):s&&!a?k("Omit",[e,r],n):u({...nr(e,o),...n})}function Zc(e,t,n){return{[t]:Ye(e,[t],N(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 b(r)}function tm(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Xe(e[o],t,N(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 b(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=L(e,[v,"$id","required","properties"]),o=sm(n,t);return O(o,r)}function am(e){let t=e.reduce((n,r)=>en(r)?[...n,S(r)]:n,[]);return T(t)}function rr(e,t){return _(e)?ee(rm(e.allOf,t)):y(e)?T(om(e.anyOf,t)):V(e)?im(e,t,e.properties):O({})}function Xe(e,t,n){let r=D(t)?am(t):t,o=pe(t)?se(t):t,s=G(e),a=G(t);return K(e)?fs(e,o,n):me(t)?gs(e,t,n):s&&a?k("Pick",[e,r],n):!s&&a?k("Pick",[e,r],n):s&&!a?k("Pick",[e,r],n):u({...rr(e,o),...n})}function um(e,t,n){return{[t]:Xe(e,[t],N(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 b(r)}function lm(e,t){return k("Partial",[k(e,t)])}function dm(e){return k("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=L(e,[v,"$id","required","properties"]),r=pm(t);return O(r,n)}function Is(e){return e.map(t=>hs(t))}function hs(e){return Ce(e)?lm(e.target,e.parameters):G(e)?dm(e.$ref):_(e)?ee(Is(e.allOf)):y(e)?T(Is(e.anyOf)):V(e)?fm(e,e.properties):et(e)||je(e)||we(e)||ce(e)||Nt(e)||Re(e)||_e(e)||Kt(e)||Et(e)?e:O({})}function Ot(e,t){return K(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],N(t));return n}function Im(e,t){return gm(e.properties,t)}function ys(e,t){let n=Im(e,t);return b(n)}function hm(e,t){return k("Required",[k(e,t)])}function ym(e){return k("Required",[Ne(e)])}function xm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=L(e[n],[J]);return t}function bm(e,t){let n=L(e,[v,"$id","required","properties"]),r=xm(t);return O(r,n)}function xs(e){return e.map(t=>bs(t))}function bs(e){return Ce(e)?hm(e.target,e.parameters):G(e)?ym(e.$ref):_(e)?ee(xs(e.allOf)):y(e)?T(xs(e.anyOf)):V(e)?bm(e,e.properties):et(e)||je(e)||we(e)||ce(e)||Nt(e)||Re(e)||_e(e)||Kt(e)||Et(e)?e:O({})}function wt(e,t){return K(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 b(n)}function Cm(e,t){return t.map(n=>G(n)?or(e,n.$ref):fe(e,n))}function or(e,t){return t in e?G(e[t])?or(e,e[t].$ref):fe(e,e[t]):x()}function $m(e){return xt(e[0])}function Om(e){return ze(e[0],e[1])}function wm(e){return bt(e[0])}function Rm(e){return Ot(e[0])}function Fm(e){return Ye(e[0],e[1])}function Am(e){return Xe(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):x()}function km(e,t){return dt(fe(e,t))}function Pm(e,t){return pt(fe(e,t))}function Nm(e,t,n){return ft(zt(e,t),fe(e,n))}function Km(e,t,n){return ke(zt(e,t),fe(e,n))}function Em(e,t){return ee(zt(e,t))}function jm(e,t){return yt(fe(e,t))}function _m(e,t){return O(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:fe(e,t[r])}),{}))}function Lm(e,t){let[n,r]=[fe(e,bn(t)),xn(t)],o=mt(t);return o.patternProperties[r]=n,o}function Gm(e,t){return G(t)?{...or(e,t.$ref),[v]:t[v]}:t}function Dm(e,t){return he(zt(e,t))}function Bm(e,t){return T(zt(e,t))}function zt(e,t){return t.map(n=>fe(e,n))}function fe(e,t){return oe(t)?u(fe(e,L(t,[J])),t):lt(t)?u(fe(e,L(t,[Se])),t):Ve(t)?u(Gm(e,t),t):Te(t)?u(km(e,t.items),t):Qe(t)?u(Pm(e,t.items),t):Ce(t)?u(Um(e,t.target,t.parameters)):$e(t)?u(Nm(e,t.parameters,t.returns),t):Oe(t)?u(Km(e,t.parameters,t.returns),t):_(t)?u(Em(e,t.allOf),t):tt(t)?u(jm(e,t.items),t):V(t)?u(_m(e,t.properties),t):rt(t)?u(Lm(e,t)):de(t)?u(Dm(e,t.items||[]),t):y(t)?u(Bm(e,t.anyOf),t):t}function Vm(e,t){return t in e?fe(e,e[t]):x()}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 Oe(e)?he(e.parameters,t):x()}var vm=0;function ws(e,t={}){B(t.$id)&&(t.$id=`T${vm++}`);let n=mt(e({[l]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[ge]:"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 _(e)?e.allOf:y(e)?e.anyOf:de(e)?e.items??[]:[]}function Fs(e){return qm(e)}function As(e,t){return Oe(e)?u(e.returns,t):x(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 Ve(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 ks(e){return u({[l]:"Void",type:"void"},e)}var ur={};Yt(ur,{Any:()=>We,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:()=>ke,Index:()=>ze,InstanceType:()=>ts,Instantiate:()=>rs,Integer:()=>os,Intersect:()=>ee,Iterator:()=>yt,KeyOf:()=>bt,Literal:()=>S,Lowercase:()=>cs,Mapped:()=>Fo,Module:()=>Cs,Never:()=>x,Not:()=>$s,Null:()=>mn,Number:()=>Ie,Object:()=>O,Omit:()=>Ye,Optional:()=>Q,Parameters:()=>Os,Partial:()=>Ot,Pick:()=>Xe,Promise:()=>un,Readonly:()=>ie,ReadonlyOptional:()=>hn,Record:()=>yn,Recursive:()=>ws,Ref:()=>Ne,RegExp:()=>Rs,Required:()=>wt,Rest:()=>Fs,ReturnType:()=>As,String:()=>Fe,Symbol:()=>ln,TemplateLiteral:()=>sn,Transform:()=>Ms,Tuple:()=>he,Uint8Array:()=>pn,Uncapitalize:()=>ms,Undefined:()=>dn,Union:()=>T,Unknown:()=>He,Unsafe:()=>Us,Uppercase:()=>ls,Void:()=>ks});var f=ur;var d=null,Wm=null,F={maxSessions:5,defaultBudgetUsd:5,idleTimeoutMinutes:30,maxPersistedSessions:50,maxAutoResponds:10};function Ps(e){F={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 ne(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=F.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(F.agentChannels)}`);let t=F.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||F.defaultWorkdir||process.cwd(),o=n.max_budget_usd??F.defaultBudgetUsd??5;try{let s=n.resume_session_id;if(s){let P=d.resolveClaudeSessionId(s);if(!P)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=P}let a;if(e.messageChannel&&e.agentAccountId){let P=e.messageChannel.split("|");P.length>=2&&(a=`${P[0]}|${e.agentAccountId}|${P.slice(1).join("|")}`)}!a&&e.workspaceDir&&(a=Y(e.workspaceDir)),!a&&e.messageChannel&&e.messageChannel.includes("|")&&(a=e.messageChannel);let m=ne({id:t},a||Y(r));if(m==="unknown"){let P=Y(r);P&&(m=P)}let p=e.workspaceDir||r;if(F.skipSafetyChecks)console.log("[claude-launch] Safety checks skipped (skipSafetyChecks=true)");else{let P=(0,Sn.join)(p,"skills","claude-code-autonomy","SKILL.md");if(!(0,at.existsSync)(P))return console.log(`[claude-launch] Autonomy skill not found at ${P} \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 R=e.agentId||Ns(p);if(R&&!e.agentId&&console.warn(`[claude-launch] Using resolveAgentId fallback for agentId="${R}" \u2014 this may be an account alias, not the real agent ID`),R){let Ue=(0,Sn.join)((0,Es.homedir)(),".openclaw","openclaw.json"),ct=!1,pr;try{if((0,at.existsSync)(Ue)){let On=(0,at.readFileSync)(Ue,"utf-8"),fr=JSON.parse(On)?.agents?.list;if(Array.isArray(fr)){let wn=fr.find(ui=>ui.id===R);wn&&wn.heartbeat!=null&&(ct=!0,pr=wn.heartbeat.every)}}}catch(On){console.log(`[claude-launch] Failed to read openclaw config at ${Ue}: ${On.message}`)}if(!ct)return console.log(`[claude-launch] Heartbeat not configured for agent "${R}" \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 "${R}":`,"",` jq '.agents.list |= map(if .id == "${R}" 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 == "${R}") | .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 ${R} --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 "${R}" \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 == "${R}" 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 re=(0,Sn.join)(p,"HEARTBEAT.md"),De=!1;try{if((0,at.existsSync)(re)){let Ue=(0,at.readFileSync)(re,"utf-8");/^(\s|#.*)*$/.test(Ue)||(De=!0)}}catch(Ue){console.log(`[claude-launch] Failed to read HEARTBEAT.md at ${re}: ${Ue.message}`)}if(!De)return console.log(`[claude-launch] HEARTBEAT.md missing or empty at ${re} \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 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[] | .heartbeat.every'","",'If NOT "60m", update it:',"",`jq '.agents.list |= map(.heartbeat.every = "60m")' ~/.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 --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 g=d.spawn({prompt:n.prompt,name:n.name,workdir:r,model:n.model||F.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}),U=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,E=["Session launched successfully.",` Name: ${g.name}`,` ID: ${g.id}`,` Dir: ${r}`,` Model: ${g.model??"default"}`,` Prompt: "${U}"`];return n.resume_session_id&&E.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),n.multi_turn_disabled?E.push(" Mode: single-turn (fire-and-forget)"):E.push(" Mode: multi-turn (use claude_respond to send follow-up messages)"),E.push(""),E.push("Use claude_sessions to check status, claude_output to see output."),{content:[{type:"text",text:E.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 Ds(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=Z(r.duration),a=[`Session: ${r.name} [${r.id}] | Status: ${r.status.toUpperCase()} | Duration: ${s}`,`${"\u2500".repeat(60)}`].join(`
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 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=v(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=X({id:n},t);if(console.log(`[claude-fg] channelId resolved: ${s}, session.workdir=${o.workdir}`),s==="unknown"){let re=v(o.workdir);re&&(s=re)}let a=o.getCatchupOutput(s);o.foregroundChannels.add(s);let m=Z(o.duration),p=[`Session ${o.name} [${o.id}] now in foreground.`,`Status: ${o.status.toUpperCase()} | Duration: ${m}`,`${"\u2500".repeat(60)}`].join(`
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=ne({id:n},t);if(console.log(`[claude-fg] channelId resolved: ${s}, session.workdir=${o.workdir}`),s==="unknown"){let P=Y(o.workdir);P&&(s=P)}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
- `));let I=a.length>0?g:o.getOutput(r.lines??30).length>0?o.getOutput(r.lines??30).join(`
19
- `):"(no output yet)",W=o.status==="running"||o.status==="starting"?`
18
+ `));let U=a.length>0?g:o.getOutput(r.lines??30).length>0?o.getOutput(r.lines??30).join(`
19
+ `):"(no output yet)",E=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}${W}`}]}}}}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=v(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=X({id:n},t);if(console.log(`[claude-bg] channelId resolved: ${g}, session.workdir=${p.workdir}`),g==="unknown"){let I=v(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=X({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=v(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 qs(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=v(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{r.interrupt&&await o.interrupt(),await o.sendMessage(r.message),r.userInitiated||o.incrementAutoRespond();let a=X({id:n},t||v(o.workdir));if(a==="unknown"){let g=v(o.workdir);g&&(a=g)}let m=a!=="unknown"?a:o.originChannel;if(at&&m){let g=[`\u21A9\uFE0F [${o.name}] Responded:`,r.message].join(`
25
- `);at.emitToChannel(m,g)}let p=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: "${p}"`,"","Use claude_output to see the response."].filter(Boolean).join(`
26
- `)}]}}catch(a){return{content:[{type:"text",text:`Error sending message: ${a.message}`}]}}}}}function Ws(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:At(r)}]}}}}function vs(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:X(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 zs(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(Ft).join(`
24
+ ${U}${E}`}]}}}}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=ne({id:n},t);if(console.log(`[claude-bg] channelId resolved: ${g}, session.workdir=${p.workdir}`),g==="unknown"){let U=Y(p.workdir);U&&(g=U)}return p.saveFgOutputOffset(g),p.foregroundChannels.delete(g),{content:[{type:"text",text:`Session ${p.name} [${p.id}] moved to background.`}]}}let o=ne({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 U=Y(g.workdir);if(U&&g.foregroundChannels.has(U)){o=U;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=F.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:F.defaultWorkdir||process.cwd(),model:F.defaultModel,maxBudgetUsd:F.defaultBudgetUsd??5,originChannel:ne(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 Hs(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 Js(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=X(t),s=r.getCatchupOutput(o);r.foregroundChannels.add(o);let a=Z(r.duration),m=[`Session ${r.name} [${r.id}] now in foreground.`,`Status: ${r.status.toUpperCase()} | Duration: ${a}`,`${"\u2500".repeat(60)}`].join(`
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=ne(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(`
33
- `):"(no output yet)",I=r.status==="running"||r.status==="starting"?`
33
+ `):"(no output yet)",U=r.status==="running"||r.status==="starting"?`
34
34
  ${"\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 Ys(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=X(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 Xs(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]
38
+ ${g}${U}`}}})}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=ne(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 W=d.listPersistedSessions();return W.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
40
+ /claude_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let E=d.listPersistedSessions();return E.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
41
41
 
42
- ${W.map(J=>{let ue=J.prompt.length>60?J.prompt.slice(0,60)+"...":J.prompt,Xe=J.completedAt?`completed ${Z(Date.now()-J.completedAt)} ago`:J.status;return[` ${J.name} \u2014 ${Xe}`,` Claude ID: ${J.claudeSessionId}`,` \u{1F4C1} ${J.workdir}`,` \u{1F4DD} "${ue}"`].join(`
42
+ ${E.map(R=>{let re=R.prompt.length>60?R.prompt.slice(0,60)+"...":R.prompt,De=R.completedAt?`completed ${X(Date.now()-R.completedAt)} ago`:R.status;return[` ${R.name} \u2014 ${De}`,` Claude ID: ${R.claudeSessionId}`,` \u{1F4C1} ${R.workdir}`,` \u{1F4DD} "${re}"`].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 W=d.spawn({prompt:a,workdir:I,model:g?.model??p.defaultModel,maxBudgetUsd:p.defaultBudgetUsd??5,resumeSessionId:m,forkSession:r,originChannel:X(t)}),re=a.length>80?a.slice(0,80)+"...":a;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${W.name}`,` ID: ${W.id}`,` Resume from: ${m}`,` Dir: ${I}`,` Prompt: "${re}"`].join(`
47
- `)}}catch(W){return{text:`Error: ${W.message}`}}}})}function Zs(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(),at&&p.originChannel){let I=[`\u21A9\uFE0F [${p.name}] Responded:`,m].join(`
49
- `);at.emitToChannel(p.originChannel,I)}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 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.length>500&&(o=o.slice(-500));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(`
52
- `);console.log(`[SessionManager] Triggering agent event for session=${t.id}`),(0,pr.execFile)("openclaw",["system","event","--text",s,"--mode","now"],a=>{a?console.error(`[SessionManager] Failed to trigger agent event for completed session=${t.id}: ${a.message}`):console.log(`[SessionManager] completion event triggered via system event for session=${t.id}`)})}triggerWaitingForInputEvent(t){let n=Date.now(),r=this.lastWaitingEventTimestamps.get(t.id);if(r&&n-r<Xm){console.log(`[SessionManager] Debounced waiting-for-input event for session=${t.id} (last sent ${n-r}ms ago)`);return}this.lastWaitingEventTimestamps.set(t.id,n);let s=t.getOutput(5).join(`
53
- `);s.length>500&&(s=s.slice(-500));let m=[`${t.multiTurn?"Multi-turn session":"Session"} is waiting for input.`,`Name: ${t.name} | ID: ${t.id}`,"","Last output:",s,"",`Use claude_respond(session='${t.id}', message='...') to send a reply, or claude_output(session='${t.id}') to see full context.`].join(`
54
- `);console.log(`[SessionManager] Triggering waiting-for-input event for session=${t.id}`),(0,pr.execFile)("openclaw",["system","event","--text",m,"--mode","now"],(p,g,I)=>{p?(console.error(`[SessionManager] Failed to trigger waiting-for-input event for session=${t.id}: ${p.message}`),I&&console.error(`[SessionManager] stderr: ${I}`)):console.log(`[SessionManager] waiting-for-input event triggered via system event for session=${t.id}`)})}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,n.originChannel),this.triggerAgentEvent(n),!0):!1}killAll(){for(let t of this.sessions.values())(t.status==="starting"||t.status==="running")&&t.kill()}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>Ym&&(this.persistSession(o),this.sessions.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 si=500,Zm=600*1e3,On=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=el(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,n){console.log(`[NotificationRouter] onSessionComplete session=${t.id} (${t.name}), status=${t.status}, originChannel=${n}, fgChannels=${JSON.stringify([...t.foregroundChannels])}`);for(let s of t.foregroundChannels)this.flushDebounced(t.id,s);let r=Qm(t),o=new Set(t.foregroundChannels);n&&t.foregroundChannels.size>0&&o.add(n);for(let s of o)this.sendMessage(s,r);this.cleanupSession(t.id)}onBudgetExhausted(t,n){for(let a of t.foregroundChannels)this.flushDebounced(t.id,a);let r=Z(t.duration),o=[`\u26D4 Session limit reached \u2014 ${t.name} [${t.id}] (${r})`,` \u{1F4C1} ${t.workdir}`].join(`
55
- `),s=new Set(t.foregroundChannels);n&&t.foregroundChannels.size>0&&s.add(n);for(let a of s)this.sendMessage(a,o);this.cleanupSession(t.id)}onWaitingForInput(t,n){console.log(`[NotificationRouter] onWaitingForInput session=${t.id} (${t.name}), originChannel=${n}, fgChannels=${JSON.stringify([...t.foregroundChannels])}`);for(let m of t.foregroundChannels)this.flushDebounced(t.id,m);let o=t.getOutput(5).join(`
56
- `);o.length>500&&(o=o.slice(-500));let s=new Set(t.foregroundChannels),a=new Set(t.foregroundChannels);n&&a.add(n);for(let m of a)if(!s.has(m)){let g=[`\u{1F514} [${t.name}] Claude asks:`,o||"(no output captured)"].join(`
57
- `);this.sendMessage(m,g)}else{let g=Z(t.duration),I=[`\u{1F4AC} Session ${t.name} [${t.id}] is waiting for input (${g})`," Use claude_respond to reply."].join(`
58
- `);this.sendMessage(m,I)}}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>Zm){this.longRunningReminded.add(r.id);let o=Z(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(`
59
- `);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)},si);else{let a=setTimeout(()=>{this.flushDebounced(t,n)},si);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 Qm(e){let t=Z(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(`
46
+ Use /claude_resume --list to see available sessions.`};let p=t.config??{},g=d.getPersistedSession(s),U=g?.workdir??process.cwd();try{let E=d.spawn({prompt:a,workdir:U,model:g?.model??p.defaultModel,maxBudgetUsd:p.defaultBudgetUsd??5,resumeSessionId:m,forkSession:r,originChannel:ne(t)}),P=a.length>80?a.slice(0,80)+"...":a;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${E.name}`,` ID: ${E.id}`,` Resume from: ${m}`,` Dir: ${U}`,` Prompt: "${P}"`].join(`
47
+ `)}}catch(E){return{text:`Error: ${E.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 U=[`\u21A9\uFE0F [${p.name}] Responded:`,m.length>200?m.slice(0,200)+"...":m].join(`
49
+ `);d.deliverToTelegram(p,U,"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||F.defaultWorkdir||process.cwd(),model:n.model||F.defaultModel,maxBudgetUsd:n.maxBudgetUsd??n.max_budget_usd??F.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??F.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=(F.idleTimeoutMinutes??30)*60*1e3;this.idleTimer=setTimeout(()=>{this.status==="running"&&(console.log(`[Session] ${this.id} idle timeout reached (${F.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,U,E)=>{g?(console.error(`[SessionManager] System event retry also failed for ${n} session=${r}: ${g.message}`),E&&console.error(`[SessionManager] retry stderr: ${E}`)):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 el(e){if(!e||typeof e!="object")return"";if(e.file_path)return Ut(e.file_path,60);if(e.path)return Ut(e.path,60);if(e.command)return Ut(e.command,80);if(e.pattern)return Ut(e.pattern,60);if(e.glob)return Ut(e.glob,60);let t=Object.values(e).find(n=>typeof n=="string"&&n.length>0);return t?Ut(String(t),60):""}function Ut(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}var ii=require("child_process");function tl(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),_s(s)),{optional:!1}),e.registerTool(s=>(o("claude_sessions",s),Gs(s)),{optional:!1}),e.registerTool(s=>(o("claude_kill",s),Ls(s)),{optional:!1}),e.registerTool(s=>(o("claude_output",s),Ds(s)),{optional:!1}),e.registerTool(s=>(o("claude_fg",s),Bs(s)),{optional:!1}),e.registerTool(s=>(o("claude_bg",s),Vs(s)),{optional:!1}),e.registerTool(s=>(o("claude_respond",s),qs(s)),{optional:!1}),e.registerTool(s=>(o("claude_stats",s),Ws(s)),{optional:!1}),vs(e),zs(e),Hs(e),Js(e),Ys(e),Xs(e),Zs(e),Qs(e),ei(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)),Ns(s),t=new Tn(U.maxSessions,U.maxPersistedSessions),cr(t);let a=(m,p)=>{let g="telegram",I="",W;if(U.fallbackChannel?.includes("|")){let O=U.fallbackChannel.split("|");O.length>=3&&O[0]&&O[1]?(g=O[0],W=O[1],I=O.slice(2).join("|")):O[0]&&O[1]&&(g=O[0],I=O[1])}let re=g,J=I,ue=W;if(m==="unknown"||!m)if(I)console.log(`[claude-code] sendMessage: channelId="${m}", using fallback ${g}|${I}${W?` (account=${W})`:""}`);else{console.warn(`[claude-code] sendMessage: channelId="${m}" and no fallbackChannel configured \u2014 message will not be sent`);return}else if(m.includes("|")){let O=m.split("|");O.length>=3?(re=O[0],ue=O[1],J=O.slice(2).join("|")):O[0]&&O[1]&&(re=O[0],J=O[1])}else if(/^-?\d+$/.test(m))re="telegram",J=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=${re}, target=${J}${ue?`, account=${ue}`:""}, textLen=${p.length}`);let Xe=["message","send","--channel",re];ue&&Xe.push("--account",ue),Xe.push("--target",J,"-m",p),(0,ii.execFile)("openclaw",Xe,{timeout:15e3},(O,D,mt)=>{O?(console.error(`[claude-code] sendMessage CLI ERROR: ${O.message}`),mt&&console.error(`[claude-code] sendMessage CLI STDERR: ${mt}`)):(console.log(`[claude-code] sendMessage CLI OK -> channel=${re}, target=${J}${ue?`, account=${ue}`:""}`),D.trim()&&console.log(`[claude-code] sendMessage CLI STDOUT: ${D.trim()}`))})};n=new On(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});
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)),Ps(s),t=new Cn(F.maxSessions,F.maxPersistedSessions),cr(t);let a=(m,p)=>{let g="telegram",U="",E;if(F.fallbackChannel?.includes("|")){let j=F.fallbackChannel.split("|");j.length>=3&&j[0]&&j[1]?(g=j[0],E=j[1],U=j.slice(2).join("|")):j[0]&&j[1]&&(g=j[0],U=j[1])}let P=g,R=U,re=E;if(m==="unknown"||!m)if(U)console.log(`[claude-code] sendMessage: channelId="${m}", using fallback ${g}|${U}${E?` (account=${E})`:""}`);else{console.warn(`[claude-code] sendMessage: channelId="${m}" and no fallbackChannel configured \u2014 message will not be sent`);return}else if(m.includes("|")){let j=m.split("|");j.length>=3?(P=j[0],re=j[1],R=j.slice(2).join("|")):j[0]&&j[1]&&(P=j[0],R=j[1])}else if(/^-?\d+$/.test(m))P="telegram",R=m;else if(U)console.log(`[claude-code] sendMessage: unrecognized channelId="${m}", using fallback ${g}|${U}`);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=${P}, target=${R}${re?`, account=${re}`:""}, textLen=${p.length}`);let De=["message","send","--channel",P];re&&De.push("--account",re),De.push("--target",R,"-m",p),(0,ai.execFile)("openclaw",De,{timeout:15e3},(j,Ue,ct)=>{j?(console.error(`[claude-code] sendMessage CLI ERROR: ${j.message}`),ct&&console.error(`[claude-code] sendMessage CLI STDERR: ${ct}`)):(console.log(`[claude-code] sendMessage CLI OK -> channel=${P}, target=${R}${re?`, account=${re}`:""}`),Ue.trim()&&console.log(`[claude-code] sendMessage CLI STDOUT: ${Ue.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});
@@ -59,6 +59,11 @@
59
59
  "type": "number",
60
60
  "default": 10,
61
61
  "description": "Maximum consecutive auto-responds (agent tool calls) per session before requiring user input via /claude-respond"
62
+ },
63
+ "skipSafetyChecks": {
64
+ "type": "boolean",
65
+ "default": false,
66
+ "description": "Skip ALL pre-launch safety guards (autonomy skill, heartbeat, HEARTBEAT.md, agentChannels). Use only for development/testing."
62
67
  }
63
68
  }
64
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@betrue/openclaw-claude-code-plugin",
3
- "version": "1.0.6",
3
+ "version": "1.0.9",
4
4
  "type": "commonjs",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {