@betrue/openclaw-claude-code-plugin 1.0.5 → 1.0.6
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 +20 -11
- package/dist/index.js +33 -32
- package/openclaw.plugin.json +5 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -17,9 +17,11 @@ Launch, monitor, and interact with multiple Claude Code SDK sessions directly fr
|
|
|
17
17
|
- **Foreground catchup** — When foregrounding, missed background output is displayed before live streaming begins
|
|
18
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
19
|
- **Session resume & fork** — Resume any completed session or fork it into a new branch of conversation
|
|
20
|
-
- **Pre-launch safety checks** —
|
|
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
|
|
21
22
|
- **Real-time notifications** — Completion alerts, budget exhaustion warnings, long-running reminders, and live tool-use indicators
|
|
22
|
-
- **Background
|
|
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
|
|
23
25
|
- **Waiting-for-input wake events** — `openclaw system event` fired when sessions become idle, waking the orchestrator agent
|
|
24
26
|
- **Multi-agent support** — Route notifications to the correct agent/chat via `agentChannels` workspace mapping with longest-prefix matching
|
|
25
27
|
- **Triple interface** — Every operation available as a chat command, agent tool, and gateway RPC method
|
|
@@ -63,13 +65,13 @@ Ensure `openclaw` CLI is available in your PATH — the plugin shells out to `op
|
|
|
63
65
|
|
|
64
66
|
## Pre-Launch Safety Checks
|
|
65
67
|
|
|
66
|
-
When an agent calls the `claude_launch` tool,
|
|
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.
|
|
67
69
|
|
|
68
70
|
### 1. Autonomy Skill
|
|
69
71
|
|
|
70
72
|
**Checks for:** `{agentWorkspace}/skills/claude-code-autonomy/SKILL.md`
|
|
71
73
|
|
|
72
|
-
The autonomy skill defines how the agent handles Claude Code interactions (auto-respond to routine questions, forward architecture decisions to the user, etc.). 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`.
|
|
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`.
|
|
73
75
|
|
|
74
76
|
### 2. Heartbeat Configuration
|
|
75
77
|
|
|
@@ -78,16 +80,22 @@ The autonomy skill defines how the agent handles Claude Code interactions (auto-
|
|
|
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
|
|
81
|
-
{ "heartbeat": { "every": "
|
|
83
|
+
{ "heartbeat": { "every": "60m", "target": "last" } }
|
|
82
84
|
```
|
|
83
85
|
|
|
84
|
-
### 3.
|
|
86
|
+
### 3. Heartbeat Interval Validation
|
|
85
87
|
|
|
86
|
-
**Checks for:**
|
|
88
|
+
**Checks for:** Heartbeat interval ≥ 60 minutes. A 5-second interval (`"every": "5s"`) is explicitly blocked.
|
|
87
89
|
|
|
88
|
-
The
|
|
90
|
+
The init prompt recommends `"every": "60m"`. Short intervals cause excessive heartbeat cycles and are not suitable for production agent operation.
|
|
89
91
|
|
|
90
|
-
### 4.
|
|
92
|
+
### 4. Gateway Restart Guard
|
|
93
|
+
|
|
94
|
+
**Checks for:** The agent must NOT attempt to restart the OpenClaw gateway itself.
|
|
95
|
+
|
|
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.
|
|
97
|
+
|
|
98
|
+
### 5. agentChannels Mapping
|
|
91
99
|
|
|
92
100
|
**Checks for:** A matching entry in `pluginConfig.agentChannels` for the session's working directory, resolved via `resolveAgentChannel(workdir)`.
|
|
93
101
|
|
|
@@ -102,6 +110,7 @@ Configuration is defined in `openclaw.plugin.json` and passed to the plugin via
|
|
|
102
110
|
| Option | Type | Default | Description |
|
|
103
111
|
|---|---|---|---|
|
|
104
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. |
|
|
105
114
|
| `defaultBudgetUsd` | `number` | `5` | Default max budget per session in USD. |
|
|
106
115
|
| `defaultModel` | `string` | — | Default model (e.g. `"sonnet"`, `"opus"`). |
|
|
107
116
|
| `defaultWorkdir` | `string` | — | Default working directory. Falls back to `process.cwd()`. |
|
|
@@ -206,8 +215,8 @@ Each agent needs three things configured:
|
|
|
206
215
|
{
|
|
207
216
|
"agents": {
|
|
208
217
|
"list": [
|
|
209
|
-
{ "id": "seo-bot", "heartbeat": { "every": "
|
|
210
|
-
{ "id": "devops-bot", "heartbeat": { "every": "
|
|
218
|
+
{ "id": "seo-bot", "heartbeat": { "every": "60m", "target": "last" } },
|
|
219
|
+
{ "id": "devops-bot", "heartbeat": { "every": "60m", "target": "last" } }
|
|
211
220
|
]
|
|
212
221
|
}
|
|
213
222
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,61 +1,62 @@
|
|
|
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})},gr=(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)):{},gr(t||!e||!e.__esModule?Jt(n,"default",{value:e,enumerable:!0}):n,e)),fi=e=>gr(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:()=>L,IsAsyncIterator:()=>Fn,IsBigInt:()=>Pt,IsBoolean:()=>Ke,IsDate:()=>Ze,IsFunction:()=>Rn,IsIterator:()=>Mn,IsNull:()=>An,IsNumber:()=>ce,IsObject:()=>$,IsRegExp:()=>kt,IsString:()=>M,IsSymbol:()=>Un,IsUint8Array:()=>Ee,IsUndefined:()=>G});function Xt(e,t){return t in e}function Fn(e){return $(e)&&!L(e)&&!Ee(e)&&Symbol.asyncIterator in e}function L(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 Rn(e){return typeof e=="function"}function Mn(e){return $(e)&&!L(e)&&!Ee(e)&&Symbol.iterator in e}function An(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 M(e){return typeof e=="string"}function Un(e){return typeof e=="symbol"}function Ee(e){return e instanceof globalThis.Uint8Array}function G(e){return e===void 0}function 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 L(e)?gi(e):Ze(e)?Ii(e):Ee(e)?hi(e):kt(e)?yi(e):$(e)?xi(e):e}function P(e){return Zt(e)}function lt(e,t){return t===void 0?P(e):P({...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 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 L(e)?bi(e):Ze(e)?e:Ee(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 P(n);default:return n}}var v=class extends Error{constructor(t){super(t)}};var V=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 je(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 Fe(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)||M(e)}function me(e){return y(e,"Literal")}function le(e){return y(e,"MappedKey")}function k(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 Re(e){return y(e,"Number")}function D(e){return y(e,"Object")}function nt(e){return y(e,"Promise")}function rt(e){return y(e,"Record")}function _(e){return y(e,"Ref")}function Nn(e){return y(e,"RegExp")}function _e(e){return y(e,"String")}function Et(e){return y(e,"Symbol")}function de(e){return y(e,"TemplateLiteral")}function Oi(e){return y(e,"This")}function Be(e){return $(e)&&V in e}function pe(e){return y(e,"Tuple")}function jt(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 Fi(e){return y(e,"Unsafe")}function Ri(e){return y(e,"Void")}function Mi(e){return $(e)&&l in e&&M(e[l])}function fe(e){return Pn(e)||kn(e)||Te(e)||je(e)||et(e)||Qe(e)||Oe(e)||$e(e)||Ci(e)||we(e)||Fe(e)||K(e)||tt(e)||me(e)||le(e)||k(e)||De(e)||Ti(e)||Kt(e)||Re(e)||D(e)||nt(e)||rt(e)||_(e)||Nn(e)||_e(e)||Et(e)||de(e)||Oi(e)||pe(e)||jt(e)||x(e)||$i(e)||wi(e)||Fi(e)||Ri(e)||Mi(e)}var i={};Yt(i,{IsAny:()=>Tr,IsArgument:()=>Or,IsArray:()=>$r,IsAsyncIterator:()=>wr,IsBigInt:()=>Fr,IsBoolean:()=>Rr,IsComputed:()=>Mr,IsConstructor:()=>Ar,IsDate:()=>Ur,IsFunction:()=>Pr,IsImport:()=>Ki,IsInteger:()=>kr,IsIntersect:()=>Nr,IsIterator:()=>Kr,IsKind:()=>ao,IsKindOf:()=>h,IsLiteral:()=>Lt,IsLiteralBoolean:()=>Ei,IsLiteralNumber:()=>jr,IsLiteralString:()=>Er,IsLiteralValue:()=>_r,IsMappedKey:()=>Lr,IsMappedResult:()=>Gr,IsNever:()=>Dr,IsNot:()=>Br,IsNull:()=>Vr,IsNumber:()=>qr,IsObject:()=>Wr,IsOptional:()=>Ni,IsPromise:()=>zr,IsProperties:()=>tn,IsReadonly:()=>ki,IsRecord:()=>vr,IsRecursive:()=>ji,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:()=>_i,IsUnknown:()=>oo,IsUnsafe:()=>so,IsVoid:()=>io,TypeGuardUnknownTypeError:()=>Kn});var Kn=class extends v{},Ai=["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(!M(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 _t(e){return G(e)||Pt(e)}function A(e){return G(e)||ce(e)}function jn(e){return G(e)||Ke(e)}function w(e){return G(e)||M(e)}function Ui(e){return G(e)||M(e)&&En(e)&&br(e)}function Pi(e){return G(e)||M(e)&&En(e)}function Cr(e){return G(e)||H(e)}function ki(e){return $(e)&&e[Ce]==="Readonly"}function Ni(e){return $(e)&&e[Y]==="Optional"}function Tr(e){return h(e,"Any")&&w(e.$id)}function Or(e){return h(e,"Argument")&&ce(e.index)}function $r(e){return h(e,"Array")&&e.type==="array"&&w(e.$id)&&H(e.items)&&A(e.minItems)&&A(e.maxItems)&&jn(e.uniqueItems)&&Cr(e.contains)&&A(e.minContains)&&A(e.maxContains)}function wr(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 Rr(e){return h(e,"Boolean")&&e.type==="boolean"&&w(e.$id)}function Mr(e){return h(e,"Computed")&&M(e.target)&&L(e.parameters)&&e.parameters.every(t=>H(t))}function Ar(e){return h(e,"Constructor")&&e.type==="Constructor"&&w(e.$id)&&L(e.parameters)&&e.parameters.every(t=>H(t))&&H(e.returns)}function Ur(e){return h(e,"Date")&&e.type==="Date"&&w(e.$id)&&A(e.exclusiveMaximumTimestamp)&&A(e.exclusiveMinimumTimestamp)&&A(e.maximumTimestamp)&&A(e.minimumTimestamp)&&A(e.multipleOfTimestamp)}function Pr(e){return h(e,"Function")&&e.type==="Function"&&w(e.$id)&&L(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")&&M(e.$ref)&&e.$ref in e.$defs}function kr(e){return h(e,"Integer")&&e.type==="integer"&&w(e.$id)&&A(e.exclusiveMaximum)&&A(e.exclusiveMinimum)&&A(e.maximum)&&A(e.minimum)&&A(e.multipleOf)}function tn(e){return $(e)&&Object.entries(e).every(([t,n])=>En(t)&&H(n))}function Nr(e){return h(e,"Intersect")&&!(M(e.type)&&e.type!=="object")&&L(e.allOf)&&e.allOf.every(t=>H(t)&&!eo(t))&&w(e.type)&&(jn(e.unevaluatedProperties)||Cr(e.unevaluatedProperties))&&w(e.$id)}function Kr(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 Lt(e)&&M(e.const)}function jr(e){return Lt(e)&&ce(e.const)}function Ei(e){return Lt(e)&&Ke(e.const)}function Lt(e){return h(e,"Literal")&&w(e.$id)&&_r(e.const)}function _r(e){return Ke(e)||ce(e)||M(e)}function Lr(e){return h(e,"MappedKey")&&L(e.keys)&&e.keys.every(t=>ce(t)||M(t))}function Gr(e){return h(e,"MappedResult")&&tn(e.properties)}function Dr(e){return h(e,"Never")&&$(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Br(e){return h(e,"Not")&&H(e.not)}function Vr(e){return h(e,"Null")&&e.type==="null"&&w(e.$id)}function qr(e){return h(e,"Number")&&e.type==="number"&&w(e.$id)&&A(e.exclusiveMaximum)&&A(e.exclusiveMinimum)&&A(e.maximum)&&A(e.minimum)&&A(e.multipleOf)}function Wr(e){return h(e,"Object")&&e.type==="object"&&w(e.$id)&&tn(e.properties)&&Sr(e.additionalProperties)&&A(e.minProperties)&&A(e.maxProperties)}function zr(e){return h(e,"Promise")&&e.type==="Promise"&&w(e.$id)&&H(e.item)}function vr(e){return h(e,"Record")&&e.type==="object"&&w(e.$id)&&Sr(e.additionalProperties)&&$(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&br(n[0])&&$(t.patternProperties)&&H(t.patternProperties[n[0]])})(e)}function ji(e){return $(e)&&Ie in e&&e[Ie]==="Recursive"}function Hr(e){return h(e,"Ref")&&w(e.$id)&&M(e.$ref)}function Jr(e){return h(e,"RegExp")&&w(e.$id)&&M(e.source)&&M(e.flags)&&A(e.maxLength)&&A(e.minLength)}function Yr(e){return h(e,"String")&&e.type==="string"&&w(e.$id)&&A(e.minLength)&&A(e.maxLength)&&Ui(e.pattern)&&Pi(e.format)}function Xr(e){return h(e,"Symbol")&&e.type==="symbol"&&w(e.$id)}function Zr(e){return h(e,"TemplateLiteral")&&e.type==="string"&&M(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Qr(e){return h(e,"This")&&w(e.$id)&&M(e.$ref)}function eo(e){return $(e)&&V in e}function to(e){return h(e,"Tuple")&&e.type==="array"&&w(e.$id)&&ce(e.minItems)&&ce(e.maxItems)&&e.minItems===e.maxItems&&(G(e.items)&&G(e.additionalItems)&&e.minItems===0||L(e.items)&&e.items.every(t=>H(t)))}function no(e){return h(e,"Undefined")&&e.type==="undefined"&&w(e.$id)}function _i(e){return _n(e)&&e.anyOf.every(t=>Er(t)||jr(t))}function _n(e){return h(e,"Union")&&w(e.$id)&&$(e)&&L(e.anyOf)&&e.anyOf.every(t=>H(t))}function ro(e){return h(e,"Uint8Array")&&e.type==="Uint8Array"&&w(e.$id)&&A(e.minByteLength)&&A(e.maxByteLength)}function oo(e){return h(e,"Unknown")&&w(e.$id)}function so(e){return h(e,"Unsafe")}function io(e){return h(e,"Void")&&e.type==="void"&&w(e.$id)}function ao(e){return $(e)&&l in e&&M(e[l])&&!Ai.includes(e[l])}function H(e){return $(e)&&(Tr(e)||Or(e)||$r(e)||Rr(e)||Fr(e)||wr(e)||Mr(e)||Ar(e)||Ur(e)||Pr(e)||kr(e)||Nr(e)||Kr(e)||Lt(e)||Lr(e)||Gr(e)||Dr(e)||Br(e)||Vr(e)||qr(e)||Wr(e)||zr(e)||vr(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)",Gt="(0|[1-9][0-9]*)",Gn="(.*)",Li="(?!.*)",Cl=`^${Ln}$`,Ve=`^${Gt}$`,qe=`^${Gn}$`,uo=`^${Li}$`;function co(e,t){return e.includes(t)}function mo(e){return[...new Set(e)]}function Gi(e,t){return e.filter(n=>t.includes(n))}function Di(e,t){return e.reduce((n,r)=>Gi(n,r),t)}function lo(e){return e.length===1?e[0]:e.length>1?Di(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 pt(e,t){return u({[l]:"Array",type:"array",items:e},t)}function fo(e){return u({[l]:"Argument",index:e})}function ft(e,t){return u({[l]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function U(e,t,n){return u({[l]:"Computed",target:e,parameters:t},n)}function Bi(e,t){let{[t]:n,...r}=e;return r}function E(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 go(e){return e.map(t=>oe(t)?qi(t):t)}function qi(e){return E(e,[Y])}function Wi(e,t){return Vi(e)?ee(Dt(go(e),t)):Dt(go(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 v{};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 Bt(e,t){return Dn(e,t,")")}function Io(e,t){return Dn(e,t,"|")}function vi(e){if(!(Ge(e,0)&&Bt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(Ge(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(Ge(e,n)&&(t+=1),Bt(e,n)&&(t-=1),Io(e,n)&&t===0)return!0;return!1}function Yi(e){for(let t=0;t<e.length;t++)if(Ge(e,t))return!0;return!1}function Xi(e){let[t,n]=[0,0],r=[];for(let s=0;s<e.length;s++)if(Ge(e,s)&&(t+=1),Bt(e,s)&&(t-=1),Io(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(!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),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(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(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 vi(e)?It(Hi(e)):Ji(e)?Xi(e):Yi(e)?Zi(e):{type:"const",const:zi(e)}}function ht(e){return It(e.slice(1,e.length-1))}var Bn=class extends v{};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 ho(e){let t=ht(e.pattern);return ot(t)}var Vn=class extends v{};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*na(e){return yield*yo(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 Me(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 Me():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 xo(e){return[...qn(e)]}var Wn=class extends v{};function aa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bo(e,t){return de(e)?e.pattern.slice(1,e.pattern.length-1):x(e)?`(${e.anyOf.map(n=>bo(n,t)).join("|")})`:Re(e)?`${t}${Gt}`:Fe(e)?`${t}${Gt}`:et(e)?`${t}${Gt}`:_e(e)?`${t}${Gn}`:me(e)?`${t}${aa(e.const.toString())}`:je(e)?`${t}${Ln}`:(()=>{throw new Wn(`Unexpected Kind '${e[l]}'`)})()}function zn(e){return`^${e.map(t=>bo(t,"")).join("")}$`}function st(e){let n=rn(e).map(r=>C(r));return ke(n)}function sn(e,t){let n=M(e)?zn(xo(e)):zn(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):Re(e)?["[number]"]:Fe(e)?["[number]"]:[])]}function la(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=ze(e,se(t[o]),n);return r}function da(e,t,n){return la(e,t.properties,n)}function So(e,t,n){let r=da(e,t,n);return S(r)}function To(e,t){return e.map(n=>Oo(n,t))}function pa(e){return e.filter(t=>!De(t))}function fa(e,t){return an(pa(To(e,t)))}function ga(e){return e.some(t=>De(t))?[]:e}function Ia(e,t){return ke(ga(To(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 Oo(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):D(e)?xa(e.properties,t):b()}function vn(e,t){return t.map(n=>Oo(e,n))}function Co(e,t){return ke(vn(e,t))}function ze(e,t,n){if(_(e)||_(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!fe(e)||!fe(t))throw new v(r);return U("Index",[e,t])}return k(t)?So(e,t,n):le(t)?$o(e,t,n):u(fe(t)?Co(e,se(t)):Co(e,t),n)}function ba(e,t,n){return{[t]:ze(e,[t],P(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 $o(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 F=Oa;function un(e,t){return u({[l]:"Promise",type:"Promise",item:e},t)}function $a(e){return u(E(e,[Ce]))}function wa(e){return u({...e,[Ce]:"Readonly"})}function Fa(e,t){return t===!1?$a(e):wa(e)}function ie(e,t){let n=t??!0;return k(e)?wo(e,n):Fa(e,n)}function Ra(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 Ra(e.properties,t)}function wo(e,t){let n=Ma(e,t);return S(n)}function ye(e,t){return u(e.length>0?{[l]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[l]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function Fo(e,t){return e in t?xe(e,t[e]):S(t)}function Aa(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 co(t,e)?Aa(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,E(t,[Y]))):dt(t)?ie(xe(e,E(t,[Ce]))):k(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):D(t)?F(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 Ro(e,t,n){let r=fe(e)?se(e):e,o=t({[l]:"MappedKey",keys:r}),s=Ka(r,o);return F(s,n)}function Ea(e){return u(E(e,[Y]))}function ja(e){return u({...e,[Y]:"Optional"})}function _a(e,t){return t===!1?Ea(e):ja(e)}function ee(e,t){let n=t??!0;return k(e)?Mo(e,n):_a(e,n)}function La(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ee(e[r],t);return n}function Ga(e,t){return La(e.properties,t)}function Mo(e,t){let n=Ga(e,t);return S(n)}function Wt(e,t={}){let n=e.every(o=>D(o)),r=fe(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||fe(t.unevaluatedProperties)||n?{...r,[l]:"Intersect",type:"object",allOf:e}:{...r,[l]:"Intersect",allOf:e},t)}function Da(e){return e.every(t=>oe(t))}function Ba(e){return E(e,[Y])}function Ao(e){return e.map(t=>oe(t)?Ba(t):t)}function Va(e,t){return Da(e)?ee(Wt(Ao(e),t)):Wt(Ao(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 v("Ref: $ref must be a string");return u({[l]:"Ref",$ref:t},n)}function qa(e,t){return U("Awaited",[U(e,t)])}function Wa(e){return U("Awaited",[Ne(e)])}function za(e){return te(Uo(e))}function va(e){return T(Uo(e))}function Ha(e){return bt(e)}function Uo(e){return e.map(t=>bt(t))}function bt(e,t){return u(Oe(e)?qa(e.target,e.parameters):K(e)?za(e.allOf):x(e)?va(e.anyOf):nt(e)?Ha(e.item):_(e)?Wa(e.$ref):e,t)}function Po(e){let t=[];for(let n of e)t.push(zt(n));return t}function Ja(e){let t=Po(e);return po(t)}function Ya(e){let t=Po(e);return lo(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 zt(e){return K(e)?Ja(e.allOf):x(e)?Ya(e.anyOf):pe(e)?Xa(e.items??[]):Te(e)?Za(e.items):D(e)?Qa(e.properties):rt(e)?eu(e.patternProperties):[]}var tu=!1;function nu(e,t){return U("KeyOf",[U(e,t)])}function ru(e){return U("KeyOf",[Ne(e)])}function ou(e,t){let n=zt(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)?ru(e.$ref):k(e)?ko(e,t):ou(e,t)}function iu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=St(e[r],P(t));return n}function au(e,t){return iu(e.properties,t)}function ko(e,t){let n=au(e,t);return S(n)}function uu(e){let t=[];for(let n of e)t.push(...zt(n));return mo(t)}function cu(e){return e.filter(t=>!De(t))}function mu(e,t){let n=[];for(let r of e)n.push(...vn(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 No(e,t){let n=uu(e),r=lu(e,n);return F(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 ve(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 Fn(e)?fn(We(),t):Mn(e)?fn(We(),t):L(e)?ie(ye(du(e))):Ee(e)?pn():Ze(e)?cn():$(e)?fn(F(pu(e)),t):Rn(e)?fn(Pe([],ve()),t):G(e)?dn():An(e)?mn():Un(e)?ln():Pt(e)?yt():ce(e)?C(e):Ke(e)?C(e):M(e)?C(e):F({})}function Ko(e,t){return u(Hn(e,!0),t)}function Eo(e,t){return $e(e)?ye(e.parameters,t):b(t)}function jo(e,t){if(G(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(s=>isNaN(s)).map(s=>e[s]),o=[...new Set(n)].map(s=>C(s));return T(o,{...t,[Ie]:"Enum"})}var Yn=class extends v{},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 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)?qo(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):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:q(t)?W(e,t):i.IsArray(t)?be(R(e.items,t.items)):c.False}function hu(e,t){return q(t)?W(e,t):i.IsAsyncIterator(t)?be(R(e.items,t.items)):c.False}function yu(e,t){return q(t)?W(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsBigInt(t)?c.True:c.False}function Bo(e,t){return i.IsLiteralBoolean(e)||i.IsBoolean(e)?c.True:c.False}function xu(e,t){return q(t)?W(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 q(t)?W(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(R(t.parameters[r],n))===c.True)?be(R(e.returns,t.returns)):c.False:c.False}function Su(e,t){return q(t)?W(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 q(t)?W(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(R(t.parameters[r],n))===c.True)?be(R(e.returns,t.returns)):c.False:c.False}function Vo(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:q(t)?W(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=>R(e,n)===c.True)?c.True:c.False}function Ou(e,t){return e.allOf.some(n=>R(n,t)===c.True)?c.True:c.False}function $u(e,t){return q(t)?W(e,t):i.IsIterator(t)?be(R(e.items,t.items)):c.False}function wu(e,t){return i.IsLiteral(t)&&t.const===e.const?c.True:q(t)?W(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsString(t)?vo(e,t):i.IsNumber(t)?Wo(e,t):i.IsInteger(t)?Vo(e,t):i.IsBoolean(t)?Bo(e,t):c.False}function qo(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:ve()}function Ru(e,t){return i.IsNot(e)?R(_o(e),t):i.IsNot(t)?R(e,_o(t)):Ct("Invalid fallthrough for Not")}function Mu(e,t){return q(t)?W(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?Se(e,t):i.IsNull(t)?c.True:c.False}function Wo(e,t){return i.IsLiteralNumber(e)||i.IsNumber(e)||i.IsInteger(e)?c.True:c.False}function Au(e,t){return q(t)?W(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 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 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(R(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(R(e.properties.length,t))===c.True}function Eu(e){let t=Pe([We()],We());return ae(e,0)||ae(e,1)&&"then"in e.properties&&be(R(e.properties.then,t))===c.True}function zo(e,t){return R(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)&&Do(t)||i.IsSymbol(e)&&Go(t)||i.IsBigInt(e)&&Uu(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)&&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 ju(e,t){return q(t)?W(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 q(t)?W(e,t):i.IsObject(t)&&Eu(t)?c.True:i.IsPromise(t)?be(R(e.item,t.item)):c.False}function Xn(e){return Ve in e.patternProperties?he():qe in e.patternProperties?Me():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(R(e,r))===c.True?c.True:i.IsUint8Array(e)&&i.IsNumber(n)||i.IsString(e)&&i.IsNumber(n)||i.IsArray(e)&&i.IsNumber(n)?R(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 Lu(e,t){return q(t)?W(e,t):i.IsObject(t)?ne(e,t):i.IsRecord(t)?R(Zn(e),Zn(t)):c.False}function Gu(e,t){let n=i.IsRegExp(e)?Me():e,r=i.IsRegExp(t)?Me():t;return R(n,r)}function vo(e,t){return i.IsLiteral(e)&&Q.IsString(e.const)||i.IsString(e)?c.True:c.False}function Du(e,t){return q(t)?W(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 q(t)?W(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)?R(st(e),t):i.IsTemplateLiteral(t)?R(e,st(t)):Ct("Invalid fallthrough for TemplateLiteral")}function qu(e,t){return i.IsArray(t)&&e.items!==void 0&&e.items.every(n=>R(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)?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)=>R(n,t.items[r])===c.True)?c.True:c.False:c.False}function vu(e,t){return q(t)?W(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 q(t)?W(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=>R(e,n)===c.True)?c.True:c.False}function Ju(e,t){return e.anyOf.every(n=>R(n,t)===c.True)?c.True:c.False}function Ho(e,t){return c.True}function Yu(e,t){return i.IsNever(t)?qo(e,t):i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsAny(t)?Qn(e,t):i.IsString(t)?vo(e,t):i.IsNumber(t)?Wo(e,t):i.IsInteger(t)?Vo(e,t):i.IsBoolean(t)?Bo(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)?Ho(e,t):i.IsAny(t)?Qn(e,t):i.IsObject(t)?ne(e,t):i.IsVoid(t)?c.True:c.False}function R(e,t){return i.IsTemplateLiteral(e)||i.IsTemplateLiteral(t)?Vu(e,t):i.IsRegExp(e)||i.IsRegExp(t)?Gu(e,t):i.IsNot(e)||i.IsNot(t)?Ru(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)?Fu(e,t):i.IsNull(e)?Mu(e,t):i.IsNumber(e)?Au(e,t):i.IsObject(e)?ju(e,t):i.IsRecord(e)?Lu(e,t):i.IsString(e)?Du(e,t):i.IsSymbol(e)?Bu(e,t):i.IsTuple(e)?zu(e,t):i.IsPromise(e)?_u(e,t):i.IsUint8Array(e)?vu(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 R(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,P(o));return s}function ec(e,t,n,r,o){return Qu(e.properties,t,n,r,o)}function Jo(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 k(e)?Jo(e,t,n,r,o):le(e)?u(Yo(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,P(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 Yo(e,t,n,r,o){let s=oc(e,t,n,r,o);return S(s)}function Xo(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(Xo(e,t),n):k(e)?u(Zo(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 Zo(e,t){let n=ac(e,t);return S(n)}function Qo(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(Qo(e,t),n):k(e)?u(es(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 es(e,t){let n=mc(e,t);return S(n)}function ts(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 F(r,{...n,[Ie]:"Record"})}function lc(e,t,n){return ho(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(uo,t,n)}function yc(e,t,n){return F({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):je(e)?yc(e,t,n):Fe(e)?xc(e,t,n):Re(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 ns(e){let t=xn(e);return t===qe?Me():t===Ve?he():Me({pattern:t})}function bn(e){return e.patternProperties[xn(e)]}function Sc(e,t){return t.parameters=vt(e,t.parameters),t.returns=Ae(e,t.returns),t}function Cc(e,t){return t.parameters=vt(e,t.parameters),t.returns=Ae(e,t.returns),t}function Tc(e,t){return t.allOf=vt(e,t.allOf),t}function Oc(e,t){return t.anyOf=vt(e,t.anyOf),t}function $c(e,t){return G(t.items)||(t.items=vt(e,t.items)),t}function wc(e,t){return t.items=Ae(e,t.items),t}function Fc(e,t){return t.items=Ae(e,t.items),t}function Rc(e,t){return t.items=Ae(e,t.items),t}function Mc(e,t){return t.item=Ae(e,t.item),t}function Ac(e,t){let n=Nc(e,t.properties);return{...t,...F(n)}}function Uc(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]:ve()}function kc(e,t){let n=dt(t),r=oe(t),o=Ae(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 vt(e,t){return t.map(n=>Ae(e,n))}function Ae(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)?Fc(e,t):tt(t)?Rc(e,t):nt(t)?Mc(e,t):D(t)?Ac(e,t):rt(t)?Uc(e,t):kn(t)?Pc(e,t):t}function rs(e,t){return Ae(t,lt(e))}function os(e){return u({[l]:"Integer",type:"integer"},e)}function Kc(e,t,n){return{[e]:Ue(C(e),t,P(n))}}function Ec(e,t,n){return e.reduce((o,s)=>({...o,...Kc(s,t,n)}),{})}function jc(e,t,n){return Ec(e.keys,t,n)}function ss(e,t,n){let r=jc(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 Lc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function Gc(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:is(e.pattern,t)};let a=[...Vt(r)].map(g=>C(g)),m=as(a,t),d=T(m);return sn([d],n)}function is(e,t){return typeof e=="string"?t==="Uncapitalize"?_c(e):t==="Capitalize"?Lc(e):t==="Uppercase"?Gc(e):t==="Lowercase"?Dc(e):e:e.toString()}function as(e,t){return e.map(n=>Ue(n,t))}function Ue(e,t,n={}){return le(e)?ss(e,t,n):de(e)?Bc(e,t,n):x(e)?T(as(e.anyOf,t),n):me(e)?C(is(e.const,t),n):u(e,n)}function us(e,t={}){return Ue(e,"Capitalize",t)}function cs(e,t={}){return Ue(e,"Lowercase",t)}function ms(e,t={}){return Ue(e,"Uncapitalize",t)}function ls(e,t={}){return Ue(e,"Uppercase",t)}function Vc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Je(e[o],t,P(n));return r}function qc(e,t,n){return Vc(e.properties,t,n)}function ds(e,t,n){let r=qc(e,t,n);return S(r)}function Wc(e,t){return e.map(n=>nr(n,t))}function zc(e,t){return e.map(n=>nr(n,t))}function vc(e,t){let{[t]:n,...r}=e;return r}function Hc(e,t){return t.reduce((n,r)=>vc(n,r),e)}function Jc(e,t,n){let r=E(e,[V,"$id","required","properties"]),o=Hc(n,t);return F(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(zc(e.anyOf,t)):D(e)?Jc(e,t,e.properties):F({})}function Je(e,t,n){let r=L(t)?Yc(t):t,o=fe(t)?se(t):t,s=_(e),a=_(t);return k(e)?ds(e,o,n):le(t)?ps(e,t,n):s&&a?U("Omit",[e,r],n):!s&&a?U("Omit",[e,r],n):s&&!a?U("Omit",[e,r],n):u({...nr(e,o),...n})}function Xc(e,t,n){return{[t]:Je(e,[t],P(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 ps(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,P(n));return r}function tm(e,t,n){return em(e.properties,t,n)}function fs(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=E(e,[V,"$id","required","properties"]),o=om(n,t);return F(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)):D(e)?sm(e,t,e.properties):F({})}function Ye(e,t,n){let r=L(t)?im(t):t,o=fe(t)?se(t):t,s=_(e),a=_(t);return k(e)?fs(e,o,n):le(t)?gs(e,t,n):s&&a?U("Pick",[e,r],n):!s&&a?U("Pick",[e,r],n):s&&!a?U("Pick",[e,r],n):u({...rr(e,o),...n})}function am(e,t,n){return{[t]:Ye(e,[t],P(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 gs(e,t,n){let r=cm(e,t,n);return S(r)}function mm(e,t){return U("Partial",[U(e,t)])}function lm(e){return U("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=E(e,[V,"$id","required","properties"]),r=dm(t);return F(r,n)}function Is(e){return e.map(t=>hs(t))}function hs(e){return Oe(e)?mm(e.target,e.parameters):_(e)?lm(e.$ref):K(e)?te(Is(e.allOf)):x(e)?T(Is(e.anyOf)):D(e)?pm(e,e.properties):et(e)||je(e)||Fe(e)||me(e)||Kt(e)||Re(e)||_e(e)||Et(e)||jt(e)?e:F({})}function wt(e,t){return k(e)?ys(e,t):u({...hs(e),...t})}function fm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=wt(e[r],P(t));return n}function gm(e,t){return fm(e.properties,t)}function ys(e,t){let n=gm(e,t);return S(n)}function Im(e,t){return U("Required",[U(e,t)])}function hm(e){return U("Required",[Ne(e)])}function ym(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=E(e[n],[Y]);return t}function xm(e,t){let n=E(e,[V,"$id","required","properties"]),r=ym(t);return F(r,n)}function xs(e){return e.map(t=>bs(t))}function bs(e){return Oe(e)?Im(e.target,e.parameters):_(e)?hm(e.$ref):K(e)?te(xs(e.allOf)):x(e)?T(xs(e.anyOf)):D(e)?xm(e,e.properties):et(e)||je(e)||Fe(e)||me(e)||Kt(e)||Re(e)||_e(e)||Et(e)||jt(e)?e:F({})}function Ft(e,t){return k(e)?Ss(e,t):u({...bs(e),...t})}function bm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ft(e[r],t);return n}function Sm(e,t){return bm(e.properties,t)}function Ss(e,t){let n=Sm(e,t);return S(n)}function Cm(e,t){return t.map(n=>_(n)?or(e,n.$ref):ge(e,n))}function or(e,t){return t in e?_(e[t])?or(e,e[t].$ref):ge(e,e[t]):b()}function Tm(e){return bt(e[0])}function Om(e){return ze(e[0],e[1])}function $m(e){return St(e[0])}function wm(e){return wt(e[0])}function Fm(e){return Je(e[0],e[1])}function Rm(e){return Ye(e[0],e[1])}function Mm(e){return Ft(e[0])}function Am(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"?Fm(r):t==="Pick"?Rm(r):t==="Required"?Mm(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 Em(e,t){return xt(ge(e,t))}function jm(e,t){return F(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 Lm(e,t){return _(t)?{...or(e,t.$ref),[V]:t[V]}:t}function Gm(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,E(t,[Y])),t):dt(t)?u(ge(e,E(t,[Ce])),t):Be(t)?u(Lm(e,t),t):Te(t)?u(Um(e,t.items),t):Qe(t)?u(Pm(e,t.items),t):Oe(t)?u(Am(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(Em(e,t.items),t):D(t)?u(jm(e,t.properties),t):rt(t)?u(_m(e,t)):pe(t)?u(Gm(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 Cs(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:Bm(e,n)}),{})}var sr=class{constructor(t){let n=Cs(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 Ts(e){return new sr(e)}function Os(e,t){return u({[l]:"Not",not:e},t)}function $s(e,t){return we(e)?ye(e.parameters,t):b()}var Vm=0;function ws(e,t={}){G(t.$id)&&(t.$id=`T${Vm++}`);let n=lt(e({[l]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[Ie]:"Recursive",...n},t)}function Fs(e,t){let n=M(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 Rs(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[V].Encode(t(a)),Decode:a=>this.decode(n[V].Decode(a))};return{...n,[V]:s}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[V]:r}}Encode(t){return Be(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function As(e){return new ir(e)}function Us(e={}){return u({[l]:e[l]??"Unsafe"},e)}function Ps(e){return u({[l]:"Void",type:"void"},e)}var ur={};Yt(ur,{Any:()=>We,Argument:()=>fo,Array:()=>pt,AsyncIterator:()=>ft,Awaited:()=>bt,BigInt:()=>yt,Boolean:()=>on,Capitalize:()=>us,Composite:()=>No,Const:()=>Ko,Constructor:()=>gt,ConstructorParameters:()=>Eo,Date:()=>cn,Enum:()=>jo,Exclude:()=>Ot,Extends:()=>Tt,Extract:()=>$t,Function:()=>Pe,Index:()=>ze,InstanceType:()=>ts,Instantiate:()=>rs,Integer:()=>os,Intersect:()=>te,Iterator:()=>xt,KeyOf:()=>St,Literal:()=>C,Lowercase:()=>cs,Mapped:()=>Ro,Module:()=>Ts,Never:()=>b,Not:()=>Os,Null:()=>mn,Number:()=>he,Object:()=>F,Omit:()=>Je,Optional:()=>ee,Parameters:()=>$s,Partial:()=>wt,Pick:()=>Ye,Promise:()=>un,Readonly:()=>ie,ReadonlyOptional:()=>hn,Record:()=>yn,Recursive:()=>ws,Ref:()=>Ne,RegExp:()=>Fs,Required:()=>Ft,Rest:()=>Rs,ReturnType:()=>Ms,String:()=>Me,Symbol:()=>ln,TemplateLiteral:()=>sn,Transform:()=>As,Tuple:()=>ye,Uint8Array:()=>pn,Uncapitalize:()=>ms,Undefined:()=>dn,Union:()=>T,Unknown:()=>ve,Unsafe:()=>Us,Uppercase:()=>ls,Void:()=>Ps});var f=ur;var p=null,at=null,N={maxSessions:5,defaultBudgetUsd:5,idleTimeoutMinutes:30,maxPersistedSessions:50};function ks(e){N={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}}function cr(e){p=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=N.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 Ns(e){let t=z(e);if(t)return Wm(t)}function z(e){console.log(`[resolveAgentChannel] workdir=${e}, agentChannels=${JSON.stringify(N.agentChannels)}`);let t=N.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 zm=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&&!zm.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var vm={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function Rt(e){let t=vm[e.status]??"\u2753",n=Z(e.duration),r=e.foregroundChannels.size>0?"foreground":"background",o=e.multiTurn?"multi-turn":"single",s=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,a=[`${t} ${e.name} [${e.id}] (${n}) \u2014 ${r}, ${o}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${s}"`];return e.claudeSessionId&&a.push(` \u{1F517} Claude ID: ${e.claudeSessionId}`),e.resumeSessionId&&a.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),a.join(`
|
|
2
|
-
`)}function
|
|
3
|
-
`)}function
|
|
4
|
-
`)}]};let I=e.agentId||
|
|
5
|
-
`)}]}
|
|
6
|
-
`)}]};if(
|
|
7
|
-
`)}]};
|
|
8
|
-
`)}]}
|
|
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(`
|
|
9
10
|
|
|
10
|
-
`)}]}}}}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(!
|
|
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
12
|
`);return o.length===0?{content:[{type:"text",text:`${a}
|
|
12
13
|
(no output yet)`}]}:{content:[{type:"text",text:`${a}
|
|
13
14
|
${o.join(`
|
|
14
|
-
`)}`}]}}}}function
|
|
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
16
|
`),g="";a.length>0&&(g=[`\u{1F4CB} Catchup (${a.length} missed output${a.length===1?"":"s"}):`,a.join(`
|
|
16
17
|
`),`${"\u2500".repeat(60)}`].join(`
|
|
17
18
|
`));let I=a.length>0?g:o.getOutput(r.lines??30).length>0?o.getOutput(r.lines??30).join(`
|
|
18
|
-
`):"(no output yet)",
|
|
19
|
+
`):"(no output yet)",W=o.status==="running"||o.status==="starting"?`
|
|
19
20
|
${"\u2500".repeat(60)}
|
|
20
21
|
Streaming new output... Use claude_bg to detach.`:`
|
|
21
22
|
${"\u2500".repeat(60)}
|
|
22
|
-
Session is ${o.status}. No more output expected.`;return o.markFgOutputSeen(s),{content:[{type:"text",text:`${
|
|
23
|
-
${I}${
|
|
24
|
-
`);at.emitToChannel(
|
|
25
|
-
`)}]}}catch(
|
|
26
|
-
`)}}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(!
|
|
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(`
|
|
27
28
|
|
|
28
|
-
`)}}})}function
|
|
29
|
-
`),
|
|
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(`
|
|
30
|
+
`),p="";s.length>0&&(p=[`\u{1F4CB} Catchup (${s.length} missed output${s.length===1?"":"s"}):`,s.join(`
|
|
30
31
|
`),`${"\u2500".repeat(60)}`].join(`
|
|
31
|
-
`));let g=s.length>0?
|
|
32
|
+
`));let g=s.length>0?p:r.getOutput(30).length>0?r.getOutput(30).join(`
|
|
32
33
|
`):"(no output yet)",I=r.status==="running"||r.status==="starting"?`
|
|
33
34
|
${"\u2500".repeat(60)}
|
|
34
35
|
Streaming... Use /claude_bg to detach.`:`
|
|
35
36
|
${"\u2500".repeat(60)}
|
|
36
37
|
Session is ${r.status}.`;return r.markFgOutputSeen(o),{text:`${m}
|
|
37
|
-
${g}${I}`}}})}function
|
|
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
39
|
/claude_resume --list \u2014 list resumable sessions
|
|
39
|
-
/claude_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let
|
|
40
|
+
/claude_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let W=d.listPersistedSessions();return W.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
|
|
40
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
43
|
`)}).join(`
|
|
43
44
|
|
|
44
|
-
`)}`}}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=
|
|
45
|
-
Use /claude_resume --list to see available sessions.`};let
|
|
46
|
-
`)}}catch(
|
|
47
|
-
/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 d
|
|
48
|
-
`);at.emitToChannel(
|
|
49
|
-
`)}}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(!p)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let t=p.getMetrics();return{text:Mt(t)}}})}function Qs(e){e.registerGatewayMethod("claude-code.sessions",({respond:t,params:n})=>{if(!p)return t(!1,{error:"SessionManager not initialized"});let r=n?.status??"all",s=p.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(!p)return t(!1,{error:"SessionManager not initialized"});if(!n?.prompt)return t(!1,{error:"Missing required parameter: prompt"});try{let r=p.spawn({prompt:n.prompt,name:n.name,workdir:n.workdir||N.defaultWorkdir||process.cwd(),model:n.model||N.defaultModel,maxBudgetUsd:n.maxBudgetUsd??n.max_budget_usd??N.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(!p)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=p.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}`});p.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(!p)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=p.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(!p)return t(!1,{error:"SessionManager not initialized"});let r=p.getMetrics(),o={};for(let[a,m]of r.costPerDay)o[a]=m;let s=p.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:Mt(r)})})}var Tn=require("child_process"),oi=require("http");var ri=require("@anthropic-ai/claude-agent-sdk");var lr=pi(require("crypto"),1);var ei="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Hm=128,ct,At,Jm=e=>{!ct||ct.length<e?(ct=Buffer.allocUnsafe(e*Hm),lr.default.randomFillSync(ct),At=0):At+e>ct.length&&(lr.default.randomFillSync(ct),At=0),At+=e};var ti=(e=21)=>{Jm(e|=0);let t="";for(let n=At-e;n<At;n++)t+=ei[ct[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})}}},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;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??N.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,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=(N.idleTimeoutMinutes??30)*60*1e3;this.idleTimer=setTimeout(()=>{this.status==="running"&&(console.log(`[Session] ${this.id} idle timeout reached (${N.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)}get duration(){return(this.completedAt??Date.now())-this.startedAt}};var Ym=3600*1e3,Xm=5e3,On=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||Ks(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 d of s.foregroundChannels)s.markFgOutputSeen(d)},s.onToolUse=(m,d)=>{console.log(`[SessionManager] session.onToolUse fired for session=${s.id}, tool=${m}`),a.onToolUse(s,m,d)},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}routeEventMessage(t,n,r){if(console.log(`[SessionManager] Triggering ${r} for session=${t.id}, originChannel=${t.originChannel}`),t.originChannel&&t.originChannel!=="unknown"){let m=t.originChannel.split("|");if(m.length<2)console.log(`[SessionManager] originChannel="${t.originChannel}" is 1-segment, falling through to system event`);else{let d;if(m.length>=3?d=["message","send","--channel",m[0],"--account",m[1],"--target",m.slice(2).join("|"),"-m",n]:m[0]&&m[1]?d=["message","send","--channel",m[0],"--target",m[1],"-m",n]:(console.log(`[SessionManager] originChannel="${t.originChannel}" has empty segment(s), falling through to system event`),d=[]),d.length>0){(0,Tn.execFile)("openclaw",d,(g,I,j)=>{g?(console.error(`[SessionManager] Failed to send ${r} via channel for session=${t.id}: ${g.message}`),j&&console.error(`[SessionManager] stderr: ${j}`)):console.log(`[SessionManager] ${r} sent via channel=${m[0]} target=${m.length>=3?m.slice(2).join("|"):m[1]} for session=${t.id}`)});return}}}let o="http://127.0.0.1:18789/hooks/wake",s=JSON.stringify({text:n,mode:"now"}),a=(0,oi.request)(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(s)}},m=>{m.statusCode===200?console.log(`[SessionManager] ${r} triggered via webhook for session=${t.id}`):console.error(`[SessionManager] Webhook returned ${m.statusCode} for session=${t.id}`)});a.on("error",m=>{console.error(`[SessionManager] Failed to trigger ${r} via webhook: ${m.message}`)}),a.write(s),a.end()}triggerAgentEvent(t){let n=t.status,o=t.getOutput(5).join(`
|
|
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(`
|
|
50
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(`
|
|
51
|
-
`);
|
|
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(`
|
|
52
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(`
|
|
53
|
-
`);(0,
|
|
54
|
-
`),s=new Set(t.foregroundChannels);n&&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(`
|
|
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(`
|
|
55
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(`
|
|
56
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(`
|
|
57
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(`
|
|
58
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(`
|
|
59
60
|
`);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(`
|
|
60
61
|
`)}return e.status==="killed"?[`\u26D4 Claude Code [${e.id}] killed (${t})`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${n}"`].join(`
|
|
61
|
-
`):`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),
|
|
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});
|
package/openclaw.plugin.json
CHANGED
|
@@ -54,6 +54,11 @@
|
|
|
54
54
|
"additionalProperties": {
|
|
55
55
|
"type": "string"
|
|
56
56
|
}
|
|
57
|
+
},
|
|
58
|
+
"maxAutoResponds": {
|
|
59
|
+
"type": "number",
|
|
60
|
+
"default": 10,
|
|
61
|
+
"description": "Maximum consecutive auto-responds (agent tool calls) per session before requiring user input via /claude-respond"
|
|
57
62
|
}
|
|
58
63
|
}
|
|
59
64
|
}
|