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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -136,6 +136,7 @@ Set values in `~/.openclaw/openclaw.json` under `plugins.config["openclaw-claude
136
136
  | `maxAutoResponds` | `number` | `10` | Max consecutive auto-responds before requiring user input |
137
137
  | `defaultBudgetUsd` | `number` | `5` | Default budget per session (USD) |
138
138
  | `permissionMode` | `string` | `"bypassPermissions"` | `"default"` / `"plan"` / `"acceptEdits"` / `"bypassPermissions"` |
139
+ | `skipSafetyChecks` | `boolean` | `false` | Skip ALL pre-launch safety guards (autonomy skill, heartbeat, HEARTBEAT.md, agentChannels). For dev/testing only. |
139
140
 
140
141
  ### Example
141
142
 
package/dist/index.js CHANGED
@@ -1,54 +1,54 @@
1
- var ci=Object.create;var Jt=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var li=Object.getOwnPropertyNames;var di=Object.getPrototypeOf,pi=Object.prototype.hasOwnProperty;var Yt=(e,t)=>{for(var n in t)Jt(e,n,{get:t[n],enumerable:!0})},gr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of li(t))!pi.call(e,o)&&o!==n&&Jt(e,o,{get:()=>t[o],enumerable:!(r=mi(t,o))||r.enumerable});return e};var fi=(e,t,n)=>(n=e!=null?ci(di(e)):{},gr(t||!e||!e.__esModule?Jt(n,"default",{value:e,enumerable:!0}):n,e)),gi=e=>gr(Jt({},"__esModule",{value:!0}),e);var ol={};Yt(ol,{register:()=>rl});module.exports=gi(ol);var at=require("fs"),Sn=require("path"),Es=require("os");var Z={};Yt(Z,{HasPropertyKey:()=>Xt,IsArray:()=>L,IsAsyncIterator:()=>Rn,IsBigInt:()=>Ut,IsBoolean:()=>Ke,IsDate:()=>Ze,IsFunction:()=>Fn,IsIterator:()=>An,IsNull:()=>Mn,IsNumber:()=>ce,IsObject:()=>O,IsRegExp:()=>Pt,IsString:()=>A,IsSymbol:()=>Un,IsUint8Array:()=>Ee,IsUndefined:()=>G});function Xt(e,t){return t in e}function Rn(e){return O(e)&&!L(e)&&!Ee(e)&&Symbol.asyncIterator in e}function L(e){return Array.isArray(e)}function Ut(e){return typeof e=="bigint"}function Ke(e){return typeof e=="boolean"}function Ze(e){return e instanceof globalThis.Date}function Fn(e){return typeof e=="function"}function An(e){return O(e)&&!L(e)&&!Ee(e)&&Symbol.iterator in e}function Mn(e){return e===null}function ce(e){return typeof e=="number"}function O(e){return typeof e=="object"&&e!==null}function Pt(e){return e instanceof globalThis.RegExp}function A(e){return typeof e=="string"}function Un(e){return typeof e=="symbol"}function Ee(e){return e instanceof globalThis.Uint8Array}function G(e){return e===void 0}function Ii(e){return e.map(t=>Zt(t))}function hi(e){return new Date(e.getTime())}function yi(e){return new Uint8Array(e)}function xi(e){return new RegExp(e.source,e.flags)}function bi(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Zt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Zt(e[n]);return t}function Zt(e){return L(e)?Ii(e):Ze(e)?hi(e):Ee(e)?yi(e):Pt(e)?xi(e):O(e)?bi(e):e}function k(e){return Zt(e)}function mt(e,t){return t===void 0?k(e):k({...t,...e})}function Ir(e){return e!==null&&typeof e=="object"}function hr(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function yr(e){return e===void 0}function xr(e){return typeof e=="number"}var Qt;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(a,m){return e.ExactOptionalPropertyTypes?m in a:a[m]!==void 0}e.IsExactOptionalProperty=t;function n(a){let m=Ir(a);return e.AllowArrayObject?m:m&&!hr(a)}e.IsObjectLike=n;function r(a){return n(a)&&!(a instanceof Date)&&!(a instanceof Uint8Array)}e.IsRecordLike=r;function o(a){return e.AllowNaN?xr(a):Number.isFinite(a)}e.IsNumberLike=o;function s(a){let m=yr(a);return e.AllowNullVoid?m||a===null:m}e.IsVoidLike=s})(Qt||(Qt={}));function Si(e){return globalThis.Object.freeze(e).map(t=>kt(t))}function Ti(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=kt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=kt(e[n]);return globalThis.Object.freeze(t)}function kt(e){return L(e)?Si(e):Ze(e)?e:Ee(e)?e:Pt(e)?e:O(e)?Ti(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(Qt.InstanceMode){case"freeze":return kt(n);case"clone":return k(n);default:return n}}var W=class extends Error{constructor(t){super(t)}};var V=Symbol.for("TypeBox.Transform"),Te=Symbol.for("TypeBox.Readonly"),J=Symbol.for("TypeBox.Optional"),Ie=Symbol.for("TypeBox.Hint"),l=Symbol.for("TypeBox.Kind");function lt(e){return O(e)&&e[Te]==="Readonly"}function oe(e){return O(e)&&e[J]==="Optional"}function Pn(e){return y(e,"Any")}function kn(e){return y(e,"Argument")}function Ce(e){return y(e,"Array")}function Qe(e){return y(e,"AsyncIterator")}function et(e){return y(e,"BigInt")}function je(e){return y(e,"Boolean")}function $e(e){return y(e,"Computed")}function Oe(e){return y(e,"Constructor")}function Ci(e){return y(e,"Date")}function we(e){return y(e,"Function")}function Re(e){return y(e,"Integer")}function K(e){return y(e,"Intersect")}function tt(e){return y(e,"Iterator")}function y(e,t){return O(e)&&l in e&&e[l]===t}function en(e){return Ke(e)||ce(e)||A(e)}function me(e){return y(e,"Literal")}function le(e){return y(e,"MappedKey")}function N(e){return y(e,"MappedResult")}function De(e){return y(e,"Never")}function $i(e){return y(e,"Not")}function Nt(e){return y(e,"Null")}function Fe(e){return y(e,"Number")}function D(e){return y(e,"Object")}function nt(e){return y(e,"Promise")}function rt(e){return y(e,"Record")}function _(e){return y(e,"Ref")}function Nn(e){return y(e,"RegExp")}function _e(e){return y(e,"String")}function Kt(e){return y(e,"Symbol")}function de(e){return y(e,"TemplateLiteral")}function Oi(e){return y(e,"This")}function Be(e){return O(e)&&V in e}function pe(e){return y(e,"Tuple")}function Et(e){return y(e,"Undefined")}function x(e){return y(e,"Union")}function wi(e){return y(e,"Uint8Array")}function Ri(e){return y(e,"Unknown")}function Fi(e){return y(e,"Unsafe")}function Ai(e){return y(e,"Void")}function Mi(e){return O(e)&&l in e&&A(e[l])}function fe(e){return Pn(e)||kn(e)||Ce(e)||je(e)||et(e)||Qe(e)||$e(e)||Oe(e)||Ci(e)||we(e)||Re(e)||K(e)||tt(e)||me(e)||le(e)||N(e)||De(e)||$i(e)||Nt(e)||Fe(e)||D(e)||nt(e)||rt(e)||_(e)||Nn(e)||_e(e)||Kt(e)||de(e)||Oi(e)||pe(e)||Et(e)||x(e)||wi(e)||Ri(e)||Fi(e)||Ai(e)||Mi(e)}var i={};Yt(i,{IsAny:()=>Cr,IsArgument:()=>$r,IsArray:()=>Or,IsAsyncIterator:()=>wr,IsBigInt:()=>Rr,IsBoolean:()=>Fr,IsComputed:()=>Ar,IsConstructor:()=>Mr,IsDate:()=>Ur,IsFunction:()=>Pr,IsImport:()=>Ei,IsInteger:()=>kr,IsIntersect:()=>Nr,IsIterator:()=>Kr,IsKind:()=>ao,IsKindOf:()=>h,IsLiteral:()=>_t,IsLiteralBoolean:()=>ji,IsLiteralNumber:()=>jr,IsLiteralString:()=>Er,IsLiteralValue:()=>_r,IsMappedKey:()=>Lr,IsMappedResult:()=>Gr,IsNever:()=>Dr,IsNot:()=>Br,IsNull:()=>Vr,IsNumber:()=>vr,IsObject:()=>qr,IsOptional:()=>Ki,IsPromise:()=>Wr,IsProperties:()=>tn,IsReadonly:()=>Ni,IsRecord:()=>zr,IsRecursive:()=>_i,IsRef:()=>Hr,IsRegExp:()=>Jr,IsSchema:()=>z,IsString:()=>Yr,IsSymbol:()=>Xr,IsTemplateLiteral:()=>Zr,IsThis:()=>Qr,IsTransform:()=>eo,IsTuple:()=>to,IsUint8Array:()=>ro,IsUndefined:()=>no,IsUnion:()=>_n,IsUnionLiteral:()=>Li,IsUnknown:()=>oo,IsUnsafe:()=>so,IsVoid:()=>io,TypeGuardUnknownTypeError:()=>Kn});var Kn=class extends W{},Ui=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function br(e){try{return new RegExp(e),!0}catch{return!1}}function En(e){if(!A(e))return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function Sr(e){return jn(e)||z(e)}function jt(e){return G(e)||Ut(e)}function M(e){return G(e)||ce(e)}function jn(e){return G(e)||Ke(e)}function w(e){return G(e)||A(e)}function Pi(e){return G(e)||A(e)&&En(e)&&br(e)}function ki(e){return G(e)||A(e)&&En(e)}function Tr(e){return G(e)||z(e)}function Ni(e){return O(e)&&e[Te]==="Readonly"}function Ki(e){return O(e)&&e[J]==="Optional"}function Cr(e){return h(e,"Any")&&w(e.$id)}function $r(e){return h(e,"Argument")&&ce(e.index)}function Or(e){return h(e,"Array")&&e.type==="array"&&w(e.$id)&&z(e.items)&&M(e.minItems)&&M(e.maxItems)&&jn(e.uniqueItems)&&Tr(e.contains)&&M(e.minContains)&&M(e.maxContains)}function wr(e){return h(e,"AsyncIterator")&&e.type==="AsyncIterator"&&w(e.$id)&&z(e.items)}function Rr(e){return h(e,"BigInt")&&e.type==="bigint"&&w(e.$id)&&jt(e.exclusiveMaximum)&&jt(e.exclusiveMinimum)&&jt(e.maximum)&&jt(e.minimum)&&jt(e.multipleOf)}function Fr(e){return h(e,"Boolean")&&e.type==="boolean"&&w(e.$id)}function Ar(e){return h(e,"Computed")&&A(e.target)&&L(e.parameters)&&e.parameters.every(t=>z(t))}function Mr(e){return h(e,"Constructor")&&e.type==="Constructor"&&w(e.$id)&&L(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function Ur(e){return h(e,"Date")&&e.type==="Date"&&w(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function Pr(e){return h(e,"Function")&&e.type==="Function"&&w(e.$id)&&L(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function Ei(e){return h(e,"Import")&&Xt(e,"$defs")&&O(e.$defs)&&tn(e.$defs)&&Xt(e,"$ref")&&A(e.$ref)&&e.$ref in e.$defs}function kr(e){return h(e,"Integer")&&e.type==="integer"&&w(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function tn(e){return O(e)&&Object.entries(e).every(([t,n])=>En(t)&&z(n))}function Nr(e){return h(e,"Intersect")&&!(A(e.type)&&e.type!=="object")&&L(e.allOf)&&e.allOf.every(t=>z(t)&&!eo(t))&&w(e.type)&&(jn(e.unevaluatedProperties)||Tr(e.unevaluatedProperties))&&w(e.$id)}function Kr(e){return h(e,"Iterator")&&e.type==="Iterator"&&w(e.$id)&&z(e.items)}function h(e,t){return O(e)&&l in e&&e[l]===t}function Er(e){return _t(e)&&A(e.const)}function jr(e){return _t(e)&&ce(e.const)}function ji(e){return _t(e)&&Ke(e.const)}function _t(e){return h(e,"Literal")&&w(e.$id)&&_r(e.const)}function _r(e){return Ke(e)||ce(e)||A(e)}function Lr(e){return h(e,"MappedKey")&&L(e.keys)&&e.keys.every(t=>ce(t)||A(t))}function Gr(e){return h(e,"MappedResult")&&tn(e.properties)}function Dr(e){return h(e,"Never")&&O(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Br(e){return h(e,"Not")&&z(e.not)}function Vr(e){return h(e,"Null")&&e.type==="null"&&w(e.$id)}function vr(e){return h(e,"Number")&&e.type==="number"&&w(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function qr(e){return h(e,"Object")&&e.type==="object"&&w(e.$id)&&tn(e.properties)&&Sr(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function Wr(e){return h(e,"Promise")&&e.type==="Promise"&&w(e.$id)&&z(e.item)}function zr(e){return h(e,"Record")&&e.type==="object"&&w(e.$id)&&Sr(e.additionalProperties)&&O(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&br(n[0])&&O(t.patternProperties)&&z(t.patternProperties[n[0]])})(e)}function _i(e){return O(e)&&Ie in e&&e[Ie]==="Recursive"}function Hr(e){return h(e,"Ref")&&w(e.$id)&&A(e.$ref)}function Jr(e){return h(e,"RegExp")&&w(e.$id)&&A(e.source)&&A(e.flags)&&M(e.maxLength)&&M(e.minLength)}function Yr(e){return h(e,"String")&&e.type==="string"&&w(e.$id)&&M(e.minLength)&&M(e.maxLength)&&Pi(e.pattern)&&ki(e.format)}function Xr(e){return h(e,"Symbol")&&e.type==="symbol"&&w(e.$id)}function Zr(e){return h(e,"TemplateLiteral")&&e.type==="string"&&A(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Qr(e){return h(e,"This")&&w(e.$id)&&A(e.$ref)}function eo(e){return O(e)&&V in e}function to(e){return h(e,"Tuple")&&e.type==="array"&&w(e.$id)&&ce(e.minItems)&&ce(e.maxItems)&&e.minItems===e.maxItems&&(G(e.items)&&G(e.additionalItems)&&e.minItems===0||L(e.items)&&e.items.every(t=>z(t)))}function no(e){return h(e,"Undefined")&&e.type==="undefined"&&w(e.$id)}function Li(e){return _n(e)&&e.anyOf.every(t=>Er(t)||jr(t))}function _n(e){return h(e,"Union")&&w(e.$id)&&O(e)&&L(e.anyOf)&&e.anyOf.every(t=>z(t))}function ro(e){return h(e,"Uint8Array")&&e.type==="Uint8Array"&&w(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function oo(e){return h(e,"Unknown")&&w(e.$id)}function so(e){return h(e,"Unsafe")}function io(e){return h(e,"Void")&&e.type==="void"&&w(e.$id)}function ao(e){return O(e)&&l in e&&A(e[l])&&!Ui.includes(e[l])}function z(e){return O(e)&&(Cr(e)||$r(e)||Or(e)||Fr(e)||Rr(e)||wr(e)||Ar(e)||Mr(e)||Ur(e)||Pr(e)||kr(e)||Nr(e)||Kr(e)||_t(e)||Lr(e)||Gr(e)||Dr(e)||Br(e)||Vr(e)||vr(e)||qr(e)||Wr(e)||zr(e)||Hr(e)||Jr(e)||Yr(e)||Xr(e)||Zr(e)||Qr(e)||to(e)||no(e)||_n(e)||ro(e)||oo(e)||so(e)||io(e)||ao(e))}var Ln="(true|false)",Lt="(0|[1-9][0-9]*)",Gn="(.*)",Gi="(?!.*)",$l=`^${Ln}$`,Ve=`^${Lt}$`,ve=`^${Gn}$`,uo=`^${Gi}$`;function co(e,t){return e.includes(t)}function mo(e){return[...new Set(e)]}function Di(e,t){return e.filter(n=>t.includes(n))}function Bi(e,t){return e.reduce((n,r)=>Di(n,r),t)}function lo(e){return e.length===1?e[0]:e.length>1?Bi(e.slice(1),e[0]):[]}function po(e){let t=[];for(let n of e)t.push(...n);return t}function qe(e){return u({[l]:"Any"},e)}function dt(e,t){return u({[l]:"Array",type:"array",items:e},t)}function fo(e){return u({[l]:"Argument",index:e})}function pt(e,t){return u({[l]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function P(e,t,n){return u({[l]:"Computed",target:e,parameters:t},n)}function Vi(e,t){let{[t]:n,...r}=e;return r}function E(e,t){return t.reduce((n,r)=>Vi(n,r),e)}function b(e){return u({[l]:"Never",not:{}},e)}function S(e){return u({[l]:"MappedResult",properties:e})}function ft(e,t,n){return u({[l]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function Pe(e,t,n){return u({[l]:"Function",type:"Function",parameters:e,returns:t},n)}function Gt(e,t){return u({[l]:"Union",anyOf:e},t)}function vi(e){return e.some(t=>oe(t))}function go(e){return e.map(t=>oe(t)?qi(t):t)}function qi(e){return E(e,[J])}function Wi(e,t){return vi(e)?Q(Gt(go(e),t)):Gt(go(e),t)}function ke(e,t){return e.length===1?u(e[0],t):e.length===0?b(t):Wi(e,t)}function C(e,t){return e.length===0?b(t):e.length===1?u(e[0],t):Gt(e,t)}var nn=class extends W{};function zi(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Dn(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function Ge(e,t){return Dn(e,t,"(")}function Dt(e,t){return Dn(e,t,")")}function Io(e,t){return Dn(e,t,"|")}function Hi(e){if(!(Ge(e,0)&&Dt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(Ge(e,n)&&(t+=1),Dt(e,n)&&(t-=1),t===0&&n!==e.length-1)return!1;return!0}function Ji(e){return e.slice(1,e.length-1)}function Yi(e){let t=0;for(let n=0;n<e.length;n++)if(Ge(e,n)&&(t+=1),Dt(e,n)&&(t-=1),Io(e,n)&&t===0)return!0;return!1}function Xi(e){for(let t=0;t<e.length;t++)if(Ge(e,t))return!0;return!1}function Zi(e){let[t,n]=[0,0],r=[];for(let s=0;s<e.length;s++)if(Ge(e,s)&&(t+=1),Dt(e,s)&&(t-=1),Io(e,s)&&t===0){let a=e.slice(n,s);a.length>0&&r.push(gt(a)),n=s+1}let o=e.slice(n);return o.length>0&&r.push(gt(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function Qi(e){function t(o,s){if(!Ge(o,s))throw new nn("TemplateLiteralParser: Index must point to open parens");let a=0;for(let m=s;m<o.length;m++)if(Ge(o,m)&&(a+=1),Dt(o,m)&&(a-=1),a===0)return[s,m];throw new nn("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,s){for(let a=s;a<o.length;a++)if(Ge(o,a))return[s,a];return[s,o.length]}let r=[];for(let o=0;o<e.length;o++)if(Ge(e,o)){let[s,a]=t(e,o),m=e.slice(s,a+1);r.push(gt(m)),o=a}else{let[s,a]=n(e,o),m=e.slice(s,a);m.length>0&&r.push(gt(m)),o=a-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function gt(e){return Hi(e)?gt(Ji(e)):Yi(e)?Zi(e):Xi(e)?Qi(e):{type:"const",const:zi(e)}}function It(e){return gt(e.slice(1,e.length-1))}var Bn=class extends W{};function ea(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="0"&&e.expr[1].type==="const"&&e.expr[1].const==="[1-9][0-9]*"}function ta(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="true"&&e.expr[1].type==="const"&&e.expr[1].const==="false"}function na(e){return e.type==="const"&&e.const===".*"}function ot(e){return ea(e)||na(e)?!1:ta(e)?!0:e.type==="and"?e.expr.every(t=>ot(t)):e.type==="or"?e.expr.every(t=>ot(t)):e.type==="const"?!0:(()=>{throw new Bn("Unknown expression type")})()}function ho(e){let t=It(e.pattern);return ot(t)}var Vn=class extends W{};function*yo(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let n of yo(e.slice(1)))yield`${t}${n}`}function*ra(e){return yield*yo(e.expr.map(t=>[...Bt(t)]))}function*oa(e){for(let t of e.expr)yield*Bt(t)}function*sa(e){return yield e.const}function*Bt(e){return e.type==="and"?yield*ra(e):e.type==="or"?yield*oa(e):e.type==="const"?yield*sa(e):(()=>{throw new Vn("Unknown expression")})()}function rn(e){let t=It(e.pattern);return ot(t)?[...Bt(t)]:[]}function T(e,t){return u({[l]:"Literal",const:e,type:typeof e},t)}function on(e){return u({[l]:"Boolean",type:"boolean"},e)}function ht(e){return u({[l]:"BigInt",type:"bigint"},e)}function he(e){return u({[l]:"Number",type:"number"},e)}function Ae(e){return u({[l]:"String",type:"string"},e)}function*ia(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield on():t==="number"?yield he():t==="bigint"?yield ht():t==="string"?yield Ae():yield(()=>{let n=t.split("|").map(r=>T(r.trim()));return n.length===0?b():n.length===1?n[0]:ke(n)})()}function*aa(e){if(e[1]!=="{"){let t=T("$"),n=vn(e.slice(1));return yield*[t,...n]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let n=ia(e.slice(2,t)),r=vn(e.slice(t+1));return yield*[...n,...r]}yield T(e)}function*vn(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=T(e.slice(0,t)),r=aa(e.slice(t));return yield*[n,...r]}yield T(e)}function xo(e){return[...vn(e)]}var qn=class extends W{};function ua(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bo(e,t){return de(e)?e.pattern.slice(1,e.pattern.length-1):x(e)?`(${e.anyOf.map(n=>bo(n,t)).join("|")})`:Fe(e)?`${t}${Lt}`:Re(e)?`${t}${Lt}`:et(e)?`${t}${Lt}`:_e(e)?`${t}${Gn}`:me(e)?`${t}${ua(e.const.toString())}`:je(e)?`${t}${Ln}`:(()=>{throw new qn(`Unexpected Kind '${e[l]}'`)})()}function Wn(e){return`^${e.map(t=>bo(t,"")).join("")}$`}function st(e){let n=rn(e).map(r=>T(r));return ke(n)}function sn(e,t){let n=A(e)?Wn(xo(e)):Wn(e);return u({[l]:"TemplateLiteral",type:"string",pattern:n},t)}function ca(e){return rn(e).map(n=>n.toString())}function ma(e){let t=[];for(let n of e)t.push(...se(n));return t}function la(e){return[e.toString()]}function se(e){return[...new Set(de(e)?ca(e):x(e)?ma(e.anyOf):me(e)?la(e.const):Fe(e)?["[number]"]:Re(e)?["[number]"]:[])]}function da(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=We(e,se(t[o]),n);return r}function pa(e,t,n){return da(e,t.properties,n)}function So(e,t,n){let r=pa(e,t,n);return S(r)}function Co(e,t){return e.map(n=>$o(n,t))}function fa(e){return e.filter(t=>!De(t))}function ga(e,t){return an(fa(Co(e,t)))}function Ia(e){return e.some(t=>De(t))?[]:e}function ha(e,t){return ke(Ia(Co(e,t)))}function ya(e,t){return t in e?e[t]:t==="[number]"?ke(e):b()}function xa(e,t){return t==="[number]"?e:b()}function ba(e,t){return t in e?e[t]:b()}function $o(e,t){return K(e)?ga(e.allOf,t):x(e)?ha(e.anyOf,t):pe(e)?ya(e.items??[],t):Ce(e)?xa(e.items,t):D(e)?ba(e.properties,t):b()}function zn(e,t){return t.map(n=>$o(e,n))}function To(e,t){return ke(zn(e,t))}function We(e,t,n){if(_(e)||_(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!fe(e)||!fe(t))throw new W(r);return P("Index",[e,t])}return N(t)?So(e,t,n):le(t)?Oo(e,t,n):u(fe(t)?To(e,se(t)):To(e,t),n)}function Sa(e,t,n){return{[t]:We(e,[t],k(n))}}function Ta(e,t,n){return t.reduce((r,o)=>({...r,...Sa(e,o,n)}),{})}function Ca(e,t,n){return Ta(e,t.keys,n)}function Oo(e,t,n){let r=Ca(e,t,n);return S(r)}function yt(e,t){return u({[l]:"Iterator",type:"Iterator",items:e},t)}function $a(e){return globalThis.Object.keys(e).filter(t=>!oe(e[t]))}function Oa(e,t){let n=$a(e),r=n.length>0?{[l]:"Object",type:"object",required:n,properties:e}:{[l]:"Object",type:"object",properties:e};return u(r,t)}var R=Oa;function un(e,t){return u({[l]:"Promise",type:"Promise",item:e},t)}function wa(e){return u(E(e,[Te]))}function Ra(e){return u({...e,[Te]:"Readonly"})}function Fa(e,t){return t===!1?wa(e):Ra(e)}function ie(e,t){let n=t??!0;return N(e)?wo(e,n):Fa(e,n)}function Aa(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ie(e[r],t);return n}function Ma(e,t){return Aa(e.properties,t)}function wo(e,t){let n=Ma(e,t);return S(n)}function ye(e,t){return u(e.length>0?{[l]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[l]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function Ro(e,t){return e in t?xe(e,t[e]):S(t)}function Ua(e){return{[e]:T(e)}}function Pa(e){let t={};for(let n of e)t[n]=T(n);return t}function ka(e,t){return co(t,e)?Ua(e):Pa(t)}function Na(e,t){let n=ka(e,t);return Ro(e,n)}function Vt(e,t){return t.map(n=>xe(e,n))}function Ka(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=xe(e,t[r]);return n}function xe(e,t){let n={...t};return oe(t)?Q(xe(e,E(t,[J]))):lt(t)?ie(xe(e,E(t,[Te]))):N(t)?Ro(e,t.properties):le(t)?Na(e,t.keys):Oe(t)?ft(Vt(e,t.parameters),xe(e,t.returns),n):we(t)?Pe(Vt(e,t.parameters),xe(e,t.returns),n):Qe(t)?pt(xe(e,t.items),n):tt(t)?yt(xe(e,t.items),n):K(t)?ee(Vt(e,t.allOf),n):x(t)?C(Vt(e,t.anyOf),n):pe(t)?ye(Vt(e,t.items??[]),n):D(t)?R(Ka(e,t.properties),n):Ce(t)?dt(xe(e,t.items),n):nt(t)?un(xe(e,t.item),n):t}function Ea(e,t){let n={};for(let r of e)n[r]=xe(r,t);return n}function Fo(e,t,n){let r=fe(e)?se(e):e,o=t({[l]:"MappedKey",keys:r}),s=Ea(r,o);return R(s,n)}function ja(e){return u(E(e,[J]))}function _a(e){return u({...e,[J]:"Optional"})}function La(e,t){return t===!1?ja(e):_a(e)}function Q(e,t){let n=t??!0;return N(e)?Ao(e,n):La(e,n)}function Ga(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Q(e[r],t);return n}function Da(e,t){return Ga(e.properties,t)}function Ao(e,t){let n=Da(e,t);return S(n)}function vt(e,t={}){let n=e.every(o=>D(o)),r=fe(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||fe(t.unevaluatedProperties)||n?{...r,[l]:"Intersect",type:"object",allOf:e}:{...r,[l]:"Intersect",allOf:e},t)}function Ba(e){return e.every(t=>oe(t))}function Va(e){return E(e,[J])}function Mo(e){return e.map(t=>oe(t)?Va(t):t)}function va(e,t){return Ba(e)?Q(vt(Mo(e),t)):vt(Mo(e),t)}function an(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return b(t);if(e.some(n=>Be(n)))throw new Error("Cannot intersect transform types");return va(e,t)}function ee(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return b(t);if(e.some(n=>Be(n)))throw new Error("Cannot intersect transform types");return vt(e,t)}function Ne(...e){let[t,n]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new W("Ref: $ref must be a string");return u({[l]:"Ref",$ref:t},n)}function qa(e,t){return P("Awaited",[P(e,t)])}function Wa(e){return P("Awaited",[Ne(e)])}function za(e){return ee(Uo(e))}function Ha(e){return C(Uo(e))}function Ja(e){return xt(e)}function Uo(e){return e.map(t=>xt(t))}function xt(e,t){return u($e(e)?qa(e.target,e.parameters):K(e)?za(e.allOf):x(e)?Ha(e.anyOf):nt(e)?Ja(e.item):_(e)?Wa(e.$ref):e,t)}function Po(e){let t=[];for(let n of e)t.push(qt(n));return t}function Ya(e){let t=Po(e);return po(t)}function Xa(e){let t=Po(e);return lo(t)}function Za(e){return e.map((t,n)=>n.toString())}function Qa(e){return["[number]"]}function eu(e){return globalThis.Object.getOwnPropertyNames(e)}function tu(e){return nu?globalThis.Object.getOwnPropertyNames(e).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function qt(e){return K(e)?Ya(e.allOf):x(e)?Xa(e.anyOf):pe(e)?Za(e.items??[]):Ce(e)?Qa(e.items):D(e)?eu(e.properties):rt(e)?tu(e.patternProperties):[]}var nu=!1;function ru(e,t){return P("KeyOf",[P(e,t)])}function ou(e){return P("KeyOf",[Ne(e)])}function su(e,t){let n=qt(e),r=iu(n),o=ke(r);return u(o,t)}function iu(e){return e.map(t=>t==="[number]"?he():T(t))}function bt(e,t){return $e(e)?ru(e.target,e.parameters):_(e)?ou(e.$ref):N(e)?ko(e,t):su(e,t)}function au(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=bt(e[r],k(t));return n}function uu(e,t){return au(e.properties,t)}function ko(e,t){let n=uu(e,t);return S(n)}function cu(e){let t=[];for(let n of e)t.push(...qt(n));return mo(t)}function mu(e){return e.filter(t=>!De(t))}function lu(e,t){let n=[];for(let r of e)n.push(...zn(r,[t]));return mu(n)}function du(e,t){let n={};for(let r of t)n[r]=an(lu(e,r));return n}function No(e,t){let n=cu(e),r=du(e,n);return R(r,t)}function cn(e){return u({[l]:"Date",type:"Date"},e)}function mn(e){return u({[l]:"Null",type:"null"},e)}function ln(e){return u({[l]:"Symbol",type:"symbol"},e)}function dn(e){return u({[l]:"Undefined",type:"undefined"},e)}function pn(e){return u({[l]:"Uint8Array",type:"Uint8Array"},e)}function ze(e){return u({[l]:"Unknown"},e)}function pu(e){return e.map(t=>Hn(t,!1))}function fu(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ie(Hn(e[n],!1));return t}function fn(e,t){return t===!0?e:ie(e)}function Hn(e,t){return Rn(e)?fn(qe(),t):An(e)?fn(qe(),t):L(e)?ie(ye(pu(e))):Ee(e)?pn():Ze(e)?cn():O(e)?fn(R(fu(e)),t):Fn(e)?fn(Pe([],ze()),t):G(e)?dn():Mn(e)?mn():Un(e)?ln():Ut(e)?ht():ce(e)?T(e):Ke(e)?T(e):A(e)?T(e):R({})}function Ko(e,t){return u(Hn(e,!0),t)}function Eo(e,t){return Oe(e)?ye(e.parameters,t):b(t)}function jo(e,t){if(G(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(s=>isNaN(s)).map(s=>e[s]),o=[...new Set(n)].map(s=>T(s));return C(o,{...t,[Ie]:"Enum"})}var Yn=class extends W{},c;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(c||(c={}));function be(e){return e===c.False?e:c.True}function St(e){throw new Yn(e)}function v(e){return i.IsNever(e)||i.IsIntersect(e)||i.IsUnion(e)||i.IsUnknown(e)||i.IsAny(e)}function q(e,t){return i.IsNever(t)?vo(e,t):i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsUnknown(t)?Ho(e,t):i.IsAny(t)?Qn(e,t):St("StructuralRight")}function Qn(e,t){return c.True}function gu(e,t){return i.IsIntersect(t)?gn(e,t):i.IsUnion(t)&&t.anyOf.some(n=>i.IsAny(n)||i.IsUnknown(n))?c.True:i.IsUnion(t)?c.Union:i.IsUnknown(t)||i.IsAny(t)?c.True:c.Union}function Iu(e,t){return i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:i.IsNever(e)?c.True:c.False}function hu(e,t){return i.IsObject(t)&&In(t)?c.True:v(t)?q(e,t):i.IsArray(t)?be(F(e.items,t.items)):c.False}function yu(e,t){return v(t)?q(e,t):i.IsAsyncIterator(t)?be(F(e.items,t.items)):c.False}function xu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsBigInt(t)?c.True:c.False}function Bo(e,t){return i.IsLiteralBoolean(e)||i.IsBoolean(e)?c.True:c.False}function bu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsBoolean(t)?c.True:c.False}function Su(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsConstructor(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>be(F(t.parameters[r],n))===c.True)?be(F(e.returns,t.returns)):c.False:c.False}function Tu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsDate(t)?c.True:c.False}function Cu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsFunction(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>be(F(t.parameters[r],n))===c.True)?be(F(e.returns,t.returns)):c.False:c.False}function Vo(e,t){return i.IsLiteral(e)&&Z.IsNumber(e.const)||i.IsNumber(e)||i.IsInteger(e)?c.True:c.False}function $u(e,t){return i.IsInteger(t)||i.IsNumber(t)?c.True:v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):c.False}function gn(e,t){return t.allOf.every(n=>F(e,n)===c.True)?c.True:c.False}function Ou(e,t){return e.allOf.some(n=>F(n,t)===c.True)?c.True:c.False}function wu(e,t){return v(t)?q(e,t):i.IsIterator(t)?be(F(e.items,t.items)):c.False}function Ru(e,t){return i.IsLiteral(t)&&t.const===e.const?c.True:v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsString(t)?zo(e,t):i.IsNumber(t)?qo(e,t):i.IsInteger(t)?Vo(e,t):i.IsBoolean(t)?Bo(e,t):c.False}function vo(e,t){return c.False}function Fu(e,t){return c.True}function _o(e){let[t,n]=[e,0];for(;i.IsNot(t);)t=t.not,n+=1;return n%2===0?t:ze()}function Au(e,t){return i.IsNot(e)?F(_o(e),t):i.IsNot(t)?F(e,_o(t)):St("Invalid fallthrough for Not")}function Mu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsNull(t)?c.True:c.False}function qo(e,t){return i.IsLiteralNumber(e)||i.IsNumber(e)||i.IsInteger(e)?c.True:c.False}function Uu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsInteger(t)||i.IsNumber(t)?c.True:c.False}function ae(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Lo(e){return In(e)}function Go(e){return ae(e,0)||ae(e,1)&&"description"in e.properties&&i.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(i.IsString(e.properties.description.anyOf[0])&&i.IsUndefined(e.properties.description.anyOf[1])||i.IsString(e.properties.description.anyOf[1])&&i.IsUndefined(e.properties.description.anyOf[0]))}function Jn(e){return ae(e,0)}function Do(e){return ae(e,0)}function Pu(e){return ae(e,0)}function ku(e){return ae(e,0)}function Nu(e){return In(e)}function Ku(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&be(F(e.properties.length,t))===c.True}function Eu(e){return ae(e,0)}function In(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&be(F(e.properties.length,t))===c.True}function ju(e){let t=Pe([qe()],qe());return ae(e,0)||ae(e,1)&&"then"in e.properties&&be(F(e.properties.then,t))===c.True}function Wo(e,t){return F(e,t)===c.False||i.IsOptional(e)&&!i.IsOptional(t)?c.False:c.True}function te(e,t){return i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:i.IsNever(e)||i.IsLiteralString(e)&&Lo(t)||i.IsLiteralNumber(e)&&Jn(t)||i.IsLiteralBoolean(e)&&Do(t)||i.IsSymbol(e)&&Go(t)||i.IsBigInt(e)&&Pu(t)||i.IsString(e)&&Lo(t)||i.IsSymbol(e)&&Go(t)||i.IsNumber(e)&&Jn(t)||i.IsInteger(e)&&Jn(t)||i.IsBoolean(e)&&Do(t)||i.IsUint8Array(e)&&Nu(t)||i.IsDate(e)&&ku(t)||i.IsConstructor(e)&&Eu(t)||i.IsFunction(e)&&Ku(t)?c.True:i.IsRecord(e)&&i.IsString(Xn(e))?t[Ie]==="Record"?c.True:c.False:i.IsRecord(e)&&i.IsNumber(Xn(e))&&ae(t,0)?c.True:c.False}function _u(e,t){return v(t)?q(e,t):i.IsRecord(t)?Se(e,t):i.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!i.IsOptional(t.properties[n]))return c.False;if(i.IsOptional(t.properties[n]))return c.True;if(Wo(e.properties[n],t.properties[n])===c.False)return c.False}return c.True})():c.False}function Lu(e,t){return v(t)?q(e,t):i.IsObject(t)&&ju(t)?c.True:i.IsPromise(t)?be(F(e.item,t.item)):c.False}function Xn(e){return Ve in e.patternProperties?he():ve in e.patternProperties?Ae():St("Unknown record key pattern")}function Zn(e){return Ve in e.patternProperties?e.patternProperties[Ve]:ve in e.patternProperties?e.patternProperties[ve]:St("Unable to get record value schema")}function Se(e,t){let[n,r]=[Xn(t),Zn(t)];return i.IsLiteralString(e)&&i.IsNumber(n)&&be(F(e,r))===c.True?c.True:i.IsUint8Array(e)&&i.IsNumber(n)||i.IsString(e)&&i.IsNumber(n)||i.IsArray(e)&&i.IsNumber(n)?F(e,r):i.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(Wo(r,e.properties[o])===c.False)return c.False;return c.True})():c.False}function Gu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?F(Zn(e),Zn(t)):c.False}function Du(e,t){let n=i.IsRegExp(e)?Ae():e,r=i.IsRegExp(t)?Ae():t;return F(n,r)}function zo(e,t){return i.IsLiteral(e)&&Z.IsString(e.const)||i.IsString(e)?c.True:c.False}function Bu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsString(t)?c.True:c.False}function Vu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsSymbol(t)?c.True:c.False}function vu(e,t){return i.IsTemplateLiteral(e)?F(st(e),t):i.IsTemplateLiteral(t)?F(e,st(t)):St("Invalid fallthrough for TemplateLiteral")}function qu(e,t){return i.IsArray(t)&&e.items!==void 0&&e.items.every(n=>F(n,t.items)===c.True)}function Wu(e,t){return i.IsNever(e)?c.True:i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:c.False}function zu(e,t){return v(t)?q(e,t):i.IsObject(t)&&In(t)||i.IsArray(t)&&qu(e,t)?c.True:i.IsTuple(t)?Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||!Z.IsUndefined(e.items)&&Z.IsUndefined(t.items)?c.False:Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||e.items.every((n,r)=>F(n,t.items[r])===c.True)?c.True:c.False:c.False}function Hu(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsUint8Array(t)?c.True:c.False}function Ju(e,t){return v(t)?q(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?Se(e,t):i.IsVoid(t)?Zu(e,t):i.IsUndefined(t)?c.True:c.False}function er(e,t){return t.anyOf.some(n=>F(e,n)===c.True)?c.True:c.False}function Yu(e,t){return e.anyOf.every(n=>F(n,t)===c.True)?c.True:c.False}function Ho(e,t){return c.True}function Xu(e,t){return i.IsNever(t)?vo(e,t):i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsAny(t)?Qn(e,t):i.IsString(t)?zo(e,t):i.IsNumber(t)?qo(e,t):i.IsInteger(t)?Vo(e,t):i.IsBoolean(t)?Bo(e,t):i.IsArray(t)?Iu(e,t):i.IsTuple(t)?Wu(e,t):i.IsObject(t)?te(e,t):i.IsUnknown(t)?c.True:c.False}function Zu(e,t){return i.IsUndefined(e)||i.IsUndefined(e)?c.True:c.False}function Qu(e,t){return i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsUnknown(t)?Ho(e,t):i.IsAny(t)?Qn(e,t):i.IsObject(t)?te(e,t):i.IsVoid(t)?c.True:c.False}function F(e,t){return i.IsTemplateLiteral(e)||i.IsTemplateLiteral(t)?vu(e,t):i.IsRegExp(e)||i.IsRegExp(t)?Du(e,t):i.IsNot(e)||i.IsNot(t)?Au(e,t):i.IsAny(e)?gu(e,t):i.IsArray(e)?hu(e,t):i.IsBigInt(e)?xu(e,t):i.IsBoolean(e)?bu(e,t):i.IsAsyncIterator(e)?yu(e,t):i.IsConstructor(e)?Su(e,t):i.IsDate(e)?Tu(e,t):i.IsFunction(e)?Cu(e,t):i.IsInteger(e)?$u(e,t):i.IsIntersect(e)?Ou(e,t):i.IsIterator(e)?wu(e,t):i.IsLiteral(e)?Ru(e,t):i.IsNever(e)?Fu(e,t):i.IsNull(e)?Mu(e,t):i.IsNumber(e)?Uu(e,t):i.IsObject(e)?_u(e,t):i.IsRecord(e)?Gu(e,t):i.IsString(e)?Bu(e,t):i.IsSymbol(e)?Vu(e,t):i.IsTuple(e)?zu(e,t):i.IsPromise(e)?Lu(e,t):i.IsUint8Array(e)?Hu(e,t):i.IsUndefined(e)?Ju(e,t):i.IsUnion(e)?Yu(e,t):i.IsUnknown(e)?Xu(e,t):i.IsVoid(e)?Qu(e,t):St(`Unknown left type operand '${e[l]}'`)}function He(e,t){return F(e,t)}function ec(e,t,n,r,o){let s={};for(let a of globalThis.Object.getOwnPropertyNames(e))s[a]=Tt(e[a],t,n,r,k(o));return s}function tc(e,t,n,r,o){return ec(e.properties,t,n,r,o)}function Jo(e,t,n,r,o){let s=tc(e,t,n,r,o);return S(s)}function nc(e,t,n,r){let o=He(e,t);return o===c.Union?C([n,r]):o===c.True?n:r}function Tt(e,t,n,r,o){return N(e)?Jo(e,t,n,r,o):le(e)?u(Yo(e,t,n,r,o)):u(nc(e,t,n,r),o)}function rc(e,t,n,r,o){return{[e]:Tt(T(e),t,n,r,k(o))}}function oc(e,t,n,r,o){return e.reduce((s,a)=>({...s,...rc(a,t,n,r,o)}),{})}function sc(e,t,n,r,o){return oc(e.keys,t,n,r,o)}function Yo(e,t,n,r,o){let s=sc(e,t,n,r,o);return S(s)}function Xo(e,t){return Ct(st(e),t)}function ic(e,t){let n=e.filter(r=>He(r,t)===c.False);return n.length===1?n[0]:C(n)}function Ct(e,t,n={}){return de(e)?u(Xo(e,t),n):N(e)?u(Zo(e,t),n):u(x(e)?ic(e.anyOf,t):He(e,t)!==c.False?b():e,n)}function ac(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ct(e[r],t);return n}function uc(e,t){return ac(e.properties,t)}function Zo(e,t){let n=uc(e,t);return S(n)}function Qo(e,t){return $t(st(e),t)}function cc(e,t){let n=e.filter(r=>He(r,t)!==c.False);return n.length===1?n[0]:C(n)}function $t(e,t,n){return de(e)?u(Qo(e,t),n):N(e)?u(es(e,t),n):u(x(e)?cc(e.anyOf,t):He(e,t)!==c.False?e:b(),n)}function mc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=$t(e[r],t);return n}function lc(e,t){return mc(e.properties,t)}function es(e,t){let n=lc(e,t);return S(n)}function ts(e,t){return Oe(e)?u(e.returns,t):b(t)}function hn(e){return ie(Q(e))}function it(e,t,n){return u({[l]:"Record",type:"object",patternProperties:{[e]:t}},n)}function tr(e,t,n){let r={};for(let o of e)r[o]=t;return R(r,{...n,[Ie]:"Record"})}function dc(e,t,n){return ho(e)?tr(se(e),t,n):it(e.pattern,t,n)}function pc(e,t,n){return tr(se(C(e)),t,n)}function fc(e,t,n){return tr([e.toString()],t,n)}function gc(e,t,n){return it(e.source,t,n)}function Ic(e,t,n){let r=G(e.pattern)?ve:e.pattern;return it(r,t,n)}function hc(e,t,n){return it(ve,t,n)}function yc(e,t,n){return it(uo,t,n)}function xc(e,t,n){return R({true:t,false:t},n)}function bc(e,t,n){return it(Ve,t,n)}function Sc(e,t,n){return it(Ve,t,n)}function yn(e,t,n={}){return x(e)?pc(e.anyOf,t,n):de(e)?dc(e,t,n):me(e)?fc(e.const,t,n):je(e)?xc(e,t,n):Re(e)?bc(e,t,n):Fe(e)?Sc(e,t,n):Nn(e)?gc(e,t,n):_e(e)?Ic(e,t,n):Pn(e)?hc(e,t,n):De(e)?yc(e,t,n):b(n)}function xn(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function ns(e){let t=xn(e);return t===ve?Ae():t===Ve?he():Ae({pattern:t})}function bn(e){return e.patternProperties[xn(e)]}function Tc(e,t){return t.parameters=Wt(e,t.parameters),t.returns=Me(e,t.returns),t}function Cc(e,t){return t.parameters=Wt(e,t.parameters),t.returns=Me(e,t.returns),t}function $c(e,t){return t.allOf=Wt(e,t.allOf),t}function Oc(e,t){return t.anyOf=Wt(e,t.anyOf),t}function wc(e,t){return G(t.items)||(t.items=Wt(e,t.items)),t}function Rc(e,t){return t.items=Me(e,t.items),t}function Fc(e,t){return t.items=Me(e,t.items),t}function Ac(e,t){return t.items=Me(e,t.items),t}function Mc(e,t){return t.item=Me(e,t.item),t}function Uc(e,t){let n=Kc(e,t.properties);return{...t,...R(n)}}function Pc(e,t){let n=Me(e,ns(t)),r=Me(e,bn(t)),o=yn(n,r);return{...t,...o}}function kc(e,t){return t.index in e?e[t.index]:ze()}function Nc(e,t){let n=lt(t),r=oe(t),o=Me(e,t);return n&&r?hn(o):n&&!r?ie(o):!n&&r?Q(o):o}function Kc(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:Nc(e,t[r])}),{})}function Wt(e,t){return t.map(n=>Me(e,n))}function Me(e,t){return Oe(t)?Tc(e,t):we(t)?Cc(e,t):K(t)?$c(e,t):x(t)?Oc(e,t):pe(t)?wc(e,t):Ce(t)?Rc(e,t):Qe(t)?Fc(e,t):tt(t)?Ac(e,t):nt(t)?Mc(e,t):D(t)?Uc(e,t):rt(t)?Pc(e,t):kn(t)?kc(e,t):t}function rs(e,t){return Me(t,mt(e))}function os(e){return u({[l]:"Integer",type:"integer"},e)}function Ec(e,t,n){return{[e]:Ue(T(e),t,k(n))}}function jc(e,t,n){return e.reduce((o,s)=>({...o,...Ec(s,t,n)}),{})}function _c(e,t,n){return jc(e.keys,t,n)}function ss(e,t,n){let r=_c(e,t,n);return S(r)}function Lc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function Gc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function Dc(e){return e.toUpperCase()}function Bc(e){return e.toLowerCase()}function Vc(e,t,n){let r=It(e.pattern);if(!ot(r))return{...e,pattern:is(e.pattern,t)};let a=[...Bt(r)].map(g=>T(g)),m=as(a,t),p=C(m);return sn([p],n)}function is(e,t){return typeof e=="string"?t==="Uncapitalize"?Lc(e):t==="Capitalize"?Gc(e):t==="Uppercase"?Dc(e):t==="Lowercase"?Bc(e):e:e.toString()}function as(e,t){return e.map(n=>Ue(n,t))}function Ue(e,t,n={}){return le(e)?ss(e,t,n):de(e)?Vc(e,t,n):x(e)?C(as(e.anyOf,t),n):me(e)?T(is(e.const,t),n):u(e,n)}function us(e,t={}){return Ue(e,"Capitalize",t)}function cs(e,t={}){return Ue(e,"Lowercase",t)}function ms(e,t={}){return Ue(e,"Uncapitalize",t)}function ls(e,t={}){return Ue(e,"Uppercase",t)}function vc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Je(e[o],t,k(n));return r}function qc(e,t,n){return vc(e.properties,t,n)}function ds(e,t,n){let r=qc(e,t,n);return S(r)}function Wc(e,t){return e.map(n=>nr(n,t))}function zc(e,t){return e.map(n=>nr(n,t))}function Hc(e,t){let{[t]:n,...r}=e;return r}function Jc(e,t){return t.reduce((n,r)=>Hc(n,r),e)}function Yc(e,t,n){let r=E(e,[V,"$id","required","properties"]),o=Jc(n,t);return R(o,r)}function Xc(e){let t=e.reduce((n,r)=>en(r)?[...n,T(r)]:n,[]);return C(t)}function nr(e,t){return K(e)?ee(Wc(e.allOf,t)):x(e)?C(zc(e.anyOf,t)):D(e)?Yc(e,t,e.properties):R({})}function Je(e,t,n){let r=L(t)?Xc(t):t,o=fe(t)?se(t):t,s=_(e),a=_(t);return N(e)?ds(e,o,n):le(t)?ps(e,t,n):s&&a?P("Omit",[e,r],n):!s&&a?P("Omit",[e,r],n):s&&!a?P("Omit",[e,r],n):u({...nr(e,o),...n})}function Zc(e,t,n){return{[t]:Je(e,[t],k(n))}}function Qc(e,t,n){return t.reduce((r,o)=>({...r,...Zc(e,o,n)}),{})}function em(e,t,n){return Qc(e,t.keys,n)}function ps(e,t,n){let r=em(e,t,n);return S(r)}function tm(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ye(e[o],t,k(n));return r}function nm(e,t,n){return tm(e.properties,t,n)}function fs(e,t,n){let r=nm(e,t,n);return S(r)}function rm(e,t){return e.map(n=>rr(n,t))}function om(e,t){return e.map(n=>rr(n,t))}function sm(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function im(e,t,n){let r=E(e,[V,"$id","required","properties"]),o=sm(n,t);return R(o,r)}function am(e){let t=e.reduce((n,r)=>en(r)?[...n,T(r)]:n,[]);return C(t)}function rr(e,t){return K(e)?ee(rm(e.allOf,t)):x(e)?C(om(e.anyOf,t)):D(e)?im(e,t,e.properties):R({})}function Ye(e,t,n){let r=L(t)?am(t):t,o=fe(t)?se(t):t,s=_(e),a=_(t);return N(e)?fs(e,o,n):le(t)?gs(e,t,n):s&&a?P("Pick",[e,r],n):!s&&a?P("Pick",[e,r],n):s&&!a?P("Pick",[e,r],n):u({...rr(e,o),...n})}function um(e,t,n){return{[t]:Ye(e,[t],k(n))}}function cm(e,t,n){return t.reduce((r,o)=>({...r,...um(e,o,n)}),{})}function mm(e,t,n){return cm(e,t.keys,n)}function gs(e,t,n){let r=mm(e,t,n);return S(r)}function lm(e,t){return P("Partial",[P(e,t)])}function dm(e){return P("Partial",[Ne(e)])}function pm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=Q(e[n]);return t}function fm(e,t){let n=E(e,[V,"$id","required","properties"]),r=pm(t);return R(r,n)}function Is(e){return e.map(t=>hs(t))}function hs(e){return $e(e)?lm(e.target,e.parameters):_(e)?dm(e.$ref):K(e)?ee(Is(e.allOf)):x(e)?C(Is(e.anyOf)):D(e)?fm(e,e.properties):et(e)||je(e)||Re(e)||me(e)||Nt(e)||Fe(e)||_e(e)||Kt(e)||Et(e)?e:R({})}function Ot(e,t){return N(e)?ys(e,t):u({...hs(e),...t})}function gm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ot(e[r],k(t));return n}function Im(e,t){return gm(e.properties,t)}function ys(e,t){let n=Im(e,t);return S(n)}function hm(e,t){return P("Required",[P(e,t)])}function ym(e){return P("Required",[Ne(e)])}function xm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=E(e[n],[J]);return t}function bm(e,t){let n=E(e,[V,"$id","required","properties"]),r=xm(t);return R(r,n)}function xs(e){return e.map(t=>bs(t))}function bs(e){return $e(e)?hm(e.target,e.parameters):_(e)?ym(e.$ref):K(e)?ee(xs(e.allOf)):x(e)?C(xs(e.anyOf)):D(e)?bm(e,e.properties):et(e)||je(e)||Re(e)||me(e)||Nt(e)||Fe(e)||_e(e)||Kt(e)||Et(e)?e:R({})}function wt(e,t){return N(e)?Ss(e,t):u({...bs(e),...t})}function Sm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=wt(e[r],t);return n}function Tm(e,t){return Sm(e.properties,t)}function Ss(e,t){let n=Tm(e,t);return S(n)}function Cm(e,t){return t.map(n=>_(n)?or(e,n.$ref):ge(e,n))}function or(e,t){return t in e?_(e[t])?or(e,e[t].$ref):ge(e,e[t]):b()}function $m(e){return xt(e[0])}function Om(e){return We(e[0],e[1])}function wm(e){return bt(e[0])}function Rm(e){return Ot(e[0])}function Fm(e){return Je(e[0],e[1])}function Am(e){return Ye(e[0],e[1])}function Mm(e){return wt(e[0])}function Um(e,t,n){let r=Cm(e,n);return t==="Awaited"?$m(r):t==="Index"?Om(r):t==="KeyOf"?wm(r):t==="Partial"?Rm(r):t==="Omit"?Fm(r):t==="Pick"?Am(r):t==="Required"?Mm(r):b()}function Pm(e,t){return dt(ge(e,t))}function km(e,t){return pt(ge(e,t))}function Nm(e,t,n){return ft(zt(e,t),ge(e,n))}function Km(e,t,n){return Pe(zt(e,t),ge(e,n))}function Em(e,t){return ee(zt(e,t))}function jm(e,t){return yt(ge(e,t))}function _m(e,t){return R(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:ge(e,t[r])}),{}))}function Lm(e,t){let[n,r]=[ge(e,bn(t)),xn(t)],o=mt(t);return o.patternProperties[r]=n,o}function Gm(e,t){return _(t)?{...or(e,t.$ref),[V]:t[V]}:t}function Dm(e,t){return ye(zt(e,t))}function Bm(e,t){return C(zt(e,t))}function zt(e,t){return t.map(n=>ge(e,n))}function ge(e,t){return oe(t)?u(ge(e,E(t,[J])),t):lt(t)?u(ge(e,E(t,[Te])),t):Be(t)?u(Gm(e,t),t):Ce(t)?u(Pm(e,t.items),t):Qe(t)?u(km(e,t.items),t):$e(t)?u(Um(e,t.target,t.parameters)):Oe(t)?u(Nm(e,t.parameters,t.returns),t):we(t)?u(Km(e,t.parameters,t.returns),t):K(t)?u(Em(e,t.allOf),t):tt(t)?u(jm(e,t.items),t):D(t)?u(_m(e,t.properties),t):rt(t)?u(Lm(e,t)):pe(t)?u(Dm(e,t.items||[]),t):x(t)?u(Bm(e,t.anyOf),t):t}function Vm(e,t){return t in e?ge(e,e[t]):b()}function Ts(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:Vm(e,n)}),{})}var sr=class{constructor(t){let n=Ts(t),r=this.WithIdentifiers(n);this.$defs=r}Import(t,n){let r={...this.$defs,[t]:u(this.$defs[t],n)};return u({[l]:"Import",$defs:r,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:{...t[r],$id:r}}),{})}};function Cs(e){return new sr(e)}function $s(e,t){return u({[l]:"Not",not:e},t)}function Os(e,t){return we(e)?ye(e.parameters,t):b()}var vm=0;function ws(e,t={}){G(t.$id)&&(t.$id=`T${vm++}`);let n=mt(e({[l]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[Ie]:"Recursive",...n},t)}function Rs(e,t){let n=A(e)?new globalThis.RegExp(e):e;return u({[l]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},t)}function qm(e){return K(e)?e.allOf:x(e)?e.anyOf:pe(e)?e.items??[]:[]}function Fs(e){return qm(e)}function As(e,t){return we(e)?u(e.returns,t):b(t)}var ir=class{constructor(t){this.schema=t}Decode(t){return new ar(this.schema,t)}},ar=class{constructor(t,n){this.schema=t,this.decode=n}EncodeTransform(t,n){let s={Encode:a=>n[V].Encode(t(a)),Decode:a=>this.decode(n[V].Decode(a))};return{...n,[V]:s}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[V]:r}}Encode(t){return Be(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function Ms(e){return new ir(e)}function Us(e={}){return u({[l]:e[l]??"Unsafe"},e)}function Ps(e){return u({[l]:"Void",type:"void"},e)}var ur={};Yt(ur,{Any:()=>qe,Argument:()=>fo,Array:()=>dt,AsyncIterator:()=>pt,Awaited:()=>xt,BigInt:()=>ht,Boolean:()=>on,Capitalize:()=>us,Composite:()=>No,Const:()=>Ko,Constructor:()=>ft,ConstructorParameters:()=>Eo,Date:()=>cn,Enum:()=>jo,Exclude:()=>Ct,Extends:()=>Tt,Extract:()=>$t,Function:()=>Pe,Index:()=>We,InstanceType:()=>ts,Instantiate:()=>rs,Integer:()=>os,Intersect:()=>ee,Iterator:()=>yt,KeyOf:()=>bt,Literal:()=>T,Lowercase:()=>cs,Mapped:()=>Fo,Module:()=>Cs,Never:()=>b,Not:()=>$s,Null:()=>mn,Number:()=>he,Object:()=>R,Omit:()=>Je,Optional:()=>Q,Parameters:()=>Os,Partial:()=>Ot,Pick:()=>Ye,Promise:()=>un,Readonly:()=>ie,ReadonlyOptional:()=>hn,Record:()=>yn,Recursive:()=>ws,Ref:()=>Ne,RegExp:()=>Rs,Required:()=>wt,Rest:()=>Fs,ReturnType:()=>As,String:()=>Ae,Symbol:()=>ln,TemplateLiteral:()=>sn,Transform:()=>Ms,Tuple:()=>ye,Uint8Array:()=>pn,Uncapitalize:()=>ms,Undefined:()=>dn,Union:()=>C,Unknown:()=>ze,Unsafe:()=>Us,Uppercase:()=>ls,Void:()=>Ps});var f=ur;var d=null,Wm=null,U={maxSessions:5,defaultBudgetUsd:5,idleTimeoutMinutes:30,maxPersistedSessions:50,maxAutoResponds:10};function ks(e){U={maxSessions:e.maxSessions??5,defaultBudgetUsd:e.defaultBudgetUsd??5,defaultModel:e.defaultModel,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??30,maxPersistedSessions:e.maxPersistedSessions??50,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10}}function cr(e){d=e}function mr(e){Wm=e}function re(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channel&&e?.chatId)return`${e.channel}|${e.chatId}`;if(e?.channel&&e?.senderId)return`${e.channel}|${e.senderId}`;if(e?.id&&/^-?\d+$/.test(String(e.id)))return`telegram|${e.id}`;if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);let n=U.fallbackChannel??"unknown";return console.log(`[resolveOriginChannel] Could not resolve channel from ctx keys: ${e?Object.keys(e).join(", "):"null"}, using fallback=${n}`),n}function zm(e){let t=e.split("|");if(t.length>=3&&t[1])return t[1]}function Ns(e){let t=Y(e);if(t)return zm(t)}function Y(e){console.log(`[resolveAgentChannel] workdir=${e}, agentChannels=${JSON.stringify(U.agentChannels)}`);let t=U.agentChannels;if(!t)return;let n=s=>s.replace(/\/+$/,""),r=n(e),o=Object.entries(t).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of o)if(r===n(s)||r.startsWith(n(s)+"/"))return a}function X(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m${r}s`:`${r}s`}var Hm=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","i","me","my","we","our","you","your","it","its","he","she","to","of","in","for","on","with","at","by","from","as","into","through","about","that","this","these","those","and","or","but","if","then","so","not","no","please","just","also","very","all","some","any","each","make","write","create","build","implement","add","update"]);function Ks(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!Hm.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var Jm={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function Rt(e){let t=Jm[e.status]??"\u2753",n=X(e.duration),r=e.foregroundChannels.size>0?"foreground":"background",o=e.multiTurn?"multi-turn":"single",s=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,a=[`${t} ${e.name} [${e.id}] (${n}) \u2014 ${r}, ${o}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${s}"`];return e.claudeSessionId&&a.push(` \u{1F517} Claude ID: ${e.claudeSessionId}`),e.resumeSessionId&&a.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),a.join(`
1
+ var ci=Object.create;var Jt=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var li=Object.getOwnPropertyNames;var di=Object.getPrototypeOf,pi=Object.prototype.hasOwnProperty;var Yt=(e,t)=>{for(var n in t)Jt(e,n,{get:t[n],enumerable:!0})},gr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of li(t))!pi.call(e,o)&&o!==n&&Jt(e,o,{get:()=>t[o],enumerable:!(r=mi(t,o))||r.enumerable});return e};var fi=(e,t,n)=>(n=e!=null?ci(di(e)):{},gr(t||!e||!e.__esModule?Jt(n,"default",{value:e,enumerable:!0}):n,e)),gi=e=>gr(Jt({},"__esModule",{value:!0}),e);var ol={};Yt(ol,{register:()=>rl});module.exports=gi(ol);var at=require("fs"),Sn=require("path"),Es=require("os");var Z={};Yt(Z,{HasPropertyKey:()=>Xt,IsArray:()=>D,IsAsyncIterator:()=>Rn,IsBigInt:()=>Ut,IsBoolean:()=>Ke,IsDate:()=>Ze,IsFunction:()=>Fn,IsIterator:()=>An,IsNull:()=>Mn,IsNumber:()=>ue,IsObject:()=>C,IsRegExp:()=>kt,IsString:()=>A,IsSymbol:()=>Un,IsUint8Array:()=>Ee,IsUndefined:()=>B});function Xt(e,t){return t in e}function Rn(e){return C(e)&&!D(e)&&!Ee(e)&&Symbol.asyncIterator in e}function D(e){return Array.isArray(e)}function Ut(e){return typeof e=="bigint"}function Ke(e){return typeof e=="boolean"}function Ze(e){return e instanceof globalThis.Date}function Fn(e){return typeof e=="function"}function An(e){return C(e)&&!D(e)&&!Ee(e)&&Symbol.iterator in e}function Mn(e){return e===null}function ue(e){return typeof e=="number"}function C(e){return typeof e=="object"&&e!==null}function kt(e){return e instanceof globalThis.RegExp}function A(e){return typeof e=="string"}function Un(e){return typeof e=="symbol"}function Ee(e){return e instanceof globalThis.Uint8Array}function B(e){return e===void 0}function Ii(e){return e.map(t=>Zt(t))}function hi(e){return new Date(e.getTime())}function yi(e){return new Uint8Array(e)}function xi(e){return new RegExp(e.source,e.flags)}function bi(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Zt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Zt(e[n]);return t}function Zt(e){return D(e)?Ii(e):Ze(e)?hi(e):Ee(e)?yi(e):kt(e)?xi(e):C(e)?bi(e):e}function N(e){return Zt(e)}function mt(e,t){return t===void 0?N(e):N({...t,...e})}function Ir(e){return e!==null&&typeof e=="object"}function hr(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function yr(e){return e===void 0}function xr(e){return typeof e=="number"}var Qt;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(a,m){return e.ExactOptionalPropertyTypes?m in a:a[m]!==void 0}e.IsExactOptionalProperty=t;function n(a){let m=Ir(a);return e.AllowArrayObject?m:m&&!hr(a)}e.IsObjectLike=n;function r(a){return n(a)&&!(a instanceof Date)&&!(a instanceof Uint8Array)}e.IsRecordLike=r;function o(a){return e.AllowNaN?xr(a):Number.isFinite(a)}e.IsNumberLike=o;function s(a){let m=yr(a);return e.AllowNullVoid?m||a===null:m}e.IsVoidLike=s})(Qt||(Qt={}));function Si(e){return globalThis.Object.freeze(e).map(t=>Pt(t))}function Ti(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Pt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Pt(e[n]);return globalThis.Object.freeze(t)}function Pt(e){return D(e)?Si(e):Ze(e)?e:Ee(e)?e:kt(e)?e:C(e)?Ti(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(Qt.InstanceMode){case"freeze":return Pt(n);case"clone":return N(n);default:return n}}var z=class extends Error{constructor(t){super(t)}};var v=Symbol.for("TypeBox.Transform"),Se=Symbol.for("TypeBox.Readonly"),J=Symbol.for("TypeBox.Optional"),ge=Symbol.for("TypeBox.Hint"),l=Symbol.for("TypeBox.Kind");function lt(e){return C(e)&&e[Se]==="Readonly"}function oe(e){return C(e)&&e[J]==="Optional"}function kn(e){return h(e,"Any")}function Pn(e){return h(e,"Argument")}function Te(e){return h(e,"Array")}function Qe(e){return h(e,"AsyncIterator")}function et(e){return h(e,"BigInt")}function je(e){return h(e,"Boolean")}function Ce(e){return h(e,"Computed")}function $e(e){return h(e,"Constructor")}function Ci(e){return h(e,"Date")}function Oe(e){return h(e,"Function")}function we(e){return h(e,"Integer")}function _(e){return h(e,"Intersect")}function tt(e){return h(e,"Iterator")}function h(e,t){return C(e)&&l in e&&e[l]===t}function en(e){return Ke(e)||ue(e)||A(e)}function ce(e){return h(e,"Literal")}function me(e){return h(e,"MappedKey")}function K(e){return h(e,"MappedResult")}function Be(e){return h(e,"Never")}function $i(e){return h(e,"Not")}function Nt(e){return h(e,"Null")}function Re(e){return h(e,"Number")}function V(e){return h(e,"Object")}function nt(e){return h(e,"Promise")}function rt(e){return h(e,"Record")}function G(e){return h(e,"Ref")}function Nn(e){return h(e,"RegExp")}function _e(e){return h(e,"String")}function Kt(e){return h(e,"Symbol")}function le(e){return h(e,"TemplateLiteral")}function Oi(e){return h(e,"This")}function Ve(e){return C(e)&&v in e}function de(e){return h(e,"Tuple")}function Et(e){return h(e,"Undefined")}function y(e){return h(e,"Union")}function wi(e){return h(e,"Uint8Array")}function Ri(e){return h(e,"Unknown")}function Fi(e){return h(e,"Unsafe")}function Ai(e){return h(e,"Void")}function Mi(e){return C(e)&&l in e&&A(e[l])}function pe(e){return kn(e)||Pn(e)||Te(e)||je(e)||et(e)||Qe(e)||Ce(e)||$e(e)||Ci(e)||Oe(e)||we(e)||_(e)||tt(e)||ce(e)||me(e)||K(e)||Be(e)||$i(e)||Nt(e)||Re(e)||V(e)||nt(e)||rt(e)||G(e)||Nn(e)||_e(e)||Kt(e)||le(e)||Oi(e)||de(e)||Et(e)||y(e)||wi(e)||Ri(e)||Fi(e)||Ai(e)||Mi(e)}var i={};Yt(i,{IsAny:()=>Cr,IsArgument:()=>$r,IsArray:()=>Or,IsAsyncIterator:()=>wr,IsBigInt:()=>Rr,IsBoolean:()=>Fr,IsComputed:()=>Ar,IsConstructor:()=>Mr,IsDate:()=>Ur,IsFunction:()=>kr,IsImport:()=>Ei,IsInteger:()=>Pr,IsIntersect:()=>Nr,IsIterator:()=>Kr,IsKind:()=>ao,IsKindOf:()=>I,IsLiteral:()=>_t,IsLiteralBoolean:()=>ji,IsLiteralNumber:()=>jr,IsLiteralString:()=>Er,IsLiteralValue:()=>_r,IsMappedKey:()=>Lr,IsMappedResult:()=>Gr,IsNever:()=>Dr,IsNot:()=>Br,IsNull:()=>Vr,IsNumber:()=>vr,IsObject:()=>qr,IsOptional:()=>Ki,IsPromise:()=>Wr,IsProperties:()=>tn,IsReadonly:()=>Ni,IsRecord:()=>zr,IsRecursive:()=>_i,IsRef:()=>Hr,IsRegExp:()=>Jr,IsSchema:()=>H,IsString:()=>Yr,IsSymbol:()=>Xr,IsTemplateLiteral:()=>Zr,IsThis:()=>Qr,IsTransform:()=>eo,IsTuple:()=>to,IsUint8Array:()=>ro,IsUndefined:()=>no,IsUnion:()=>_n,IsUnionLiteral:()=>Li,IsUnknown:()=>oo,IsUnsafe:()=>so,IsVoid:()=>io,TypeGuardUnknownTypeError:()=>Kn});var Kn=class extends z{},Ui=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function br(e){try{return new RegExp(e),!0}catch{return!1}}function En(e){if(!A(e))return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function Sr(e){return jn(e)||H(e)}function jt(e){return B(e)||Ut(e)}function M(e){return B(e)||ue(e)}function jn(e){return B(e)||Ke(e)}function $(e){return B(e)||A(e)}function ki(e){return B(e)||A(e)&&En(e)&&br(e)}function Pi(e){return B(e)||A(e)&&En(e)}function Tr(e){return B(e)||H(e)}function Ni(e){return C(e)&&e[Se]==="Readonly"}function Ki(e){return C(e)&&e[J]==="Optional"}function Cr(e){return I(e,"Any")&&$(e.$id)}function $r(e){return I(e,"Argument")&&ue(e.index)}function Or(e){return I(e,"Array")&&e.type==="array"&&$(e.$id)&&H(e.items)&&M(e.minItems)&&M(e.maxItems)&&jn(e.uniqueItems)&&Tr(e.contains)&&M(e.minContains)&&M(e.maxContains)}function wr(e){return I(e,"AsyncIterator")&&e.type==="AsyncIterator"&&$(e.$id)&&H(e.items)}function Rr(e){return I(e,"BigInt")&&e.type==="bigint"&&$(e.$id)&&jt(e.exclusiveMaximum)&&jt(e.exclusiveMinimum)&&jt(e.maximum)&&jt(e.minimum)&&jt(e.multipleOf)}function Fr(e){return I(e,"Boolean")&&e.type==="boolean"&&$(e.$id)}function Ar(e){return I(e,"Computed")&&A(e.target)&&D(e.parameters)&&e.parameters.every(t=>H(t))}function Mr(e){return I(e,"Constructor")&&e.type==="Constructor"&&$(e.$id)&&D(e.parameters)&&e.parameters.every(t=>H(t))&&H(e.returns)}function Ur(e){return I(e,"Date")&&e.type==="Date"&&$(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function kr(e){return I(e,"Function")&&e.type==="Function"&&$(e.$id)&&D(e.parameters)&&e.parameters.every(t=>H(t))&&H(e.returns)}function Ei(e){return I(e,"Import")&&Xt(e,"$defs")&&C(e.$defs)&&tn(e.$defs)&&Xt(e,"$ref")&&A(e.$ref)&&e.$ref in e.$defs}function Pr(e){return I(e,"Integer")&&e.type==="integer"&&$(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function tn(e){return C(e)&&Object.entries(e).every(([t,n])=>En(t)&&H(n))}function Nr(e){return I(e,"Intersect")&&!(A(e.type)&&e.type!=="object")&&D(e.allOf)&&e.allOf.every(t=>H(t)&&!eo(t))&&$(e.type)&&(jn(e.unevaluatedProperties)||Tr(e.unevaluatedProperties))&&$(e.$id)}function Kr(e){return I(e,"Iterator")&&e.type==="Iterator"&&$(e.$id)&&H(e.items)}function I(e,t){return C(e)&&l in e&&e[l]===t}function Er(e){return _t(e)&&A(e.const)}function jr(e){return _t(e)&&ue(e.const)}function ji(e){return _t(e)&&Ke(e.const)}function _t(e){return I(e,"Literal")&&$(e.$id)&&_r(e.const)}function _r(e){return Ke(e)||ue(e)||A(e)}function Lr(e){return I(e,"MappedKey")&&D(e.keys)&&e.keys.every(t=>ue(t)||A(t))}function Gr(e){return I(e,"MappedResult")&&tn(e.properties)}function Dr(e){return I(e,"Never")&&C(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Br(e){return I(e,"Not")&&H(e.not)}function Vr(e){return I(e,"Null")&&e.type==="null"&&$(e.$id)}function vr(e){return I(e,"Number")&&e.type==="number"&&$(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function qr(e){return I(e,"Object")&&e.type==="object"&&$(e.$id)&&tn(e.properties)&&Sr(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function Wr(e){return I(e,"Promise")&&e.type==="Promise"&&$(e.$id)&&H(e.item)}function zr(e){return I(e,"Record")&&e.type==="object"&&$(e.$id)&&Sr(e.additionalProperties)&&C(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&br(n[0])&&C(t.patternProperties)&&H(t.patternProperties[n[0]])})(e)}function _i(e){return C(e)&&ge in e&&e[ge]==="Recursive"}function Hr(e){return I(e,"Ref")&&$(e.$id)&&A(e.$ref)}function Jr(e){return I(e,"RegExp")&&$(e.$id)&&A(e.source)&&A(e.flags)&&M(e.maxLength)&&M(e.minLength)}function Yr(e){return I(e,"String")&&e.type==="string"&&$(e.$id)&&M(e.minLength)&&M(e.maxLength)&&ki(e.pattern)&&Pi(e.format)}function Xr(e){return I(e,"Symbol")&&e.type==="symbol"&&$(e.$id)}function Zr(e){return I(e,"TemplateLiteral")&&e.type==="string"&&A(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Qr(e){return I(e,"This")&&$(e.$id)&&A(e.$ref)}function eo(e){return C(e)&&v in e}function to(e){return I(e,"Tuple")&&e.type==="array"&&$(e.$id)&&ue(e.minItems)&&ue(e.maxItems)&&e.minItems===e.maxItems&&(B(e.items)&&B(e.additionalItems)&&e.minItems===0||D(e.items)&&e.items.every(t=>H(t)))}function no(e){return I(e,"Undefined")&&e.type==="undefined"&&$(e.$id)}function Li(e){return _n(e)&&e.anyOf.every(t=>Er(t)||jr(t))}function _n(e){return I(e,"Union")&&$(e.$id)&&C(e)&&D(e.anyOf)&&e.anyOf.every(t=>H(t))}function ro(e){return I(e,"Uint8Array")&&e.type==="Uint8Array"&&$(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function oo(e){return I(e,"Unknown")&&$(e.$id)}function so(e){return I(e,"Unsafe")}function io(e){return I(e,"Void")&&e.type==="void"&&$(e.$id)}function ao(e){return C(e)&&l in e&&A(e[l])&&!Ui.includes(e[l])}function H(e){return C(e)&&(Cr(e)||$r(e)||Or(e)||Fr(e)||Rr(e)||wr(e)||Ar(e)||Mr(e)||Ur(e)||kr(e)||Pr(e)||Nr(e)||Kr(e)||_t(e)||Lr(e)||Gr(e)||Dr(e)||Br(e)||Vr(e)||vr(e)||qr(e)||Wr(e)||zr(e)||Hr(e)||Jr(e)||Yr(e)||Xr(e)||Zr(e)||Qr(e)||to(e)||no(e)||_n(e)||ro(e)||oo(e)||so(e)||io(e)||ao(e))}var Ln="(true|false)",Lt="(0|[1-9][0-9]*)",Gn="(.*)",Gi="(?!.*)",$l=`^${Ln}$`,ve=`^${Lt}$`,qe=`^${Gn}$`,uo=`^${Gi}$`;function co(e,t){return e.includes(t)}function mo(e){return[...new Set(e)]}function Di(e,t){return e.filter(n=>t.includes(n))}function Bi(e,t){return e.reduce((n,r)=>Di(n,r),t)}function lo(e){return e.length===1?e[0]:e.length>1?Bi(e.slice(1),e[0]):[]}function po(e){let t=[];for(let n of e)t.push(...n);return t}function We(e){return u({[l]:"Any"},e)}function dt(e,t){return u({[l]:"Array",type:"array",items:e},t)}function fo(e){return u({[l]:"Argument",index:e})}function pt(e,t){return u({[l]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function k(e,t,n){return u({[l]:"Computed",target:e,parameters:t},n)}function Vi(e,t){let{[t]:n,...r}=e;return r}function L(e,t){return t.reduce((n,r)=>Vi(n,r),e)}function x(e){return u({[l]:"Never",not:{}},e)}function b(e){return u({[l]:"MappedResult",properties:e})}function ft(e,t,n){return u({[l]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function ke(e,t,n){return u({[l]:"Function",type:"Function",parameters:e,returns:t},n)}function Gt(e,t){return u({[l]:"Union",anyOf:e},t)}function vi(e){return e.some(t=>oe(t))}function go(e){return e.map(t=>oe(t)?qi(t):t)}function qi(e){return L(e,[J])}function Wi(e,t){return vi(e)?Q(Gt(go(e),t)):Gt(go(e),t)}function Pe(e,t){return e.length===1?u(e[0],t):e.length===0?x(t):Wi(e,t)}function T(e,t){return e.length===0?x(t):e.length===1?u(e[0],t):Gt(e,t)}var nn=class extends z{};function zi(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Dn(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function Ge(e,t){return Dn(e,t,"(")}function Dt(e,t){return Dn(e,t,")")}function Io(e,t){return Dn(e,t,"|")}function Hi(e){if(!(Ge(e,0)&&Dt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(Ge(e,n)&&(t+=1),Dt(e,n)&&(t-=1),t===0&&n!==e.length-1)return!1;return!0}function Ji(e){return e.slice(1,e.length-1)}function Yi(e){let t=0;for(let n=0;n<e.length;n++)if(Ge(e,n)&&(t+=1),Dt(e,n)&&(t-=1),Io(e,n)&&t===0)return!0;return!1}function Xi(e){for(let t=0;t<e.length;t++)if(Ge(e,t))return!0;return!1}function Zi(e){let[t,n]=[0,0],r=[];for(let s=0;s<e.length;s++)if(Ge(e,s)&&(t+=1),Dt(e,s)&&(t-=1),Io(e,s)&&t===0){let a=e.slice(n,s);a.length>0&&r.push(gt(a)),n=s+1}let o=e.slice(n);return o.length>0&&r.push(gt(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function Qi(e){function t(o,s){if(!Ge(o,s))throw new nn("TemplateLiteralParser: Index must point to open parens");let a=0;for(let m=s;m<o.length;m++)if(Ge(o,m)&&(a+=1),Dt(o,m)&&(a-=1),a===0)return[s,m];throw new nn("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,s){for(let a=s;a<o.length;a++)if(Ge(o,a))return[s,a];return[s,o.length]}let r=[];for(let o=0;o<e.length;o++)if(Ge(e,o)){let[s,a]=t(e,o),m=e.slice(s,a+1);r.push(gt(m)),o=a}else{let[s,a]=n(e,o),m=e.slice(s,a);m.length>0&&r.push(gt(m)),o=a-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function gt(e){return Hi(e)?gt(Ji(e)):Yi(e)?Zi(e):Xi(e)?Qi(e):{type:"const",const:zi(e)}}function It(e){return gt(e.slice(1,e.length-1))}var Bn=class extends z{};function ea(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="0"&&e.expr[1].type==="const"&&e.expr[1].const==="[1-9][0-9]*"}function ta(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="true"&&e.expr[1].type==="const"&&e.expr[1].const==="false"}function na(e){return e.type==="const"&&e.const===".*"}function ot(e){return ea(e)||na(e)?!1:ta(e)?!0:e.type==="and"?e.expr.every(t=>ot(t)):e.type==="or"?e.expr.every(t=>ot(t)):e.type==="const"?!0:(()=>{throw new Bn("Unknown expression type")})()}function ho(e){let t=It(e.pattern);return ot(t)}var Vn=class extends z{};function*yo(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let n of yo(e.slice(1)))yield`${t}${n}`}function*ra(e){return yield*yo(e.expr.map(t=>[...Bt(t)]))}function*oa(e){for(let t of e.expr)yield*Bt(t)}function*sa(e){return yield e.const}function*Bt(e){return e.type==="and"?yield*ra(e):e.type==="or"?yield*oa(e):e.type==="const"?yield*sa(e):(()=>{throw new Vn("Unknown expression")})()}function rn(e){let t=It(e.pattern);return ot(t)?[...Bt(t)]:[]}function S(e,t){return u({[l]:"Literal",const:e,type:typeof e},t)}function on(e){return u({[l]:"Boolean",type:"boolean"},e)}function ht(e){return u({[l]:"BigInt",type:"bigint"},e)}function Ie(e){return u({[l]:"Number",type:"number"},e)}function Fe(e){return u({[l]:"String",type:"string"},e)}function*ia(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield on():t==="number"?yield Ie():t==="bigint"?yield ht():t==="string"?yield Fe():yield(()=>{let n=t.split("|").map(r=>S(r.trim()));return n.length===0?x():n.length===1?n[0]:Pe(n)})()}function*aa(e){if(e[1]!=="{"){let t=S("$"),n=vn(e.slice(1));return yield*[t,...n]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let n=ia(e.slice(2,t)),r=vn(e.slice(t+1));return yield*[...n,...r]}yield S(e)}function*vn(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=S(e.slice(0,t)),r=aa(e.slice(t));return yield*[n,...r]}yield S(e)}function xo(e){return[...vn(e)]}var qn=class extends z{};function ua(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bo(e,t){return le(e)?e.pattern.slice(1,e.pattern.length-1):y(e)?`(${e.anyOf.map(n=>bo(n,t)).join("|")})`:Re(e)?`${t}${Lt}`:we(e)?`${t}${Lt}`:et(e)?`${t}${Lt}`:_e(e)?`${t}${Gn}`:ce(e)?`${t}${ua(e.const.toString())}`:je(e)?`${t}${Ln}`:(()=>{throw new qn(`Unexpected Kind '${e[l]}'`)})()}function Wn(e){return`^${e.map(t=>bo(t,"")).join("")}$`}function st(e){let n=rn(e).map(r=>S(r));return Pe(n)}function sn(e,t){let n=A(e)?Wn(xo(e)):Wn(e);return u({[l]:"TemplateLiteral",type:"string",pattern:n},t)}function ca(e){return rn(e).map(n=>n.toString())}function ma(e){let t=[];for(let n of e)t.push(...se(n));return t}function la(e){return[e.toString()]}function se(e){return[...new Set(le(e)?ca(e):y(e)?ma(e.anyOf):ce(e)?la(e.const):Re(e)?["[number]"]:we(e)?["[number]"]:[])]}function da(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=ze(e,se(t[o]),n);return r}function pa(e,t,n){return da(e,t.properties,n)}function So(e,t,n){let r=pa(e,t,n);return b(r)}function Co(e,t){return e.map(n=>$o(n,t))}function fa(e){return e.filter(t=>!Be(t))}function ga(e,t){return an(fa(Co(e,t)))}function Ia(e){return e.some(t=>Be(t))?[]:e}function ha(e,t){return Pe(Ia(Co(e,t)))}function ya(e,t){return t in e?e[t]:t==="[number]"?Pe(e):x()}function xa(e,t){return t==="[number]"?e:x()}function ba(e,t){return t in e?e[t]:x()}function $o(e,t){return _(e)?ga(e.allOf,t):y(e)?ha(e.anyOf,t):de(e)?ya(e.items??[],t):Te(e)?xa(e.items,t):V(e)?ba(e.properties,t):x()}function zn(e,t){return t.map(n=>$o(e,n))}function To(e,t){return Pe(zn(e,t))}function ze(e,t,n){if(G(e)||G(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!pe(e)||!pe(t))throw new z(r);return k("Index",[e,t])}return K(t)?So(e,t,n):me(t)?Oo(e,t,n):u(pe(t)?To(e,se(t)):To(e,t),n)}function Sa(e,t,n){return{[t]:ze(e,[t],N(n))}}function Ta(e,t,n){return t.reduce((r,o)=>({...r,...Sa(e,o,n)}),{})}function Ca(e,t,n){return Ta(e,t.keys,n)}function Oo(e,t,n){let r=Ca(e,t,n);return b(r)}function yt(e,t){return u({[l]:"Iterator",type:"Iterator",items:e},t)}function $a(e){return globalThis.Object.keys(e).filter(t=>!oe(e[t]))}function Oa(e,t){let n=$a(e),r=n.length>0?{[l]:"Object",type:"object",required:n,properties:e}:{[l]:"Object",type:"object",properties:e};return u(r,t)}var O=Oa;function un(e,t){return u({[l]:"Promise",type:"Promise",item:e},t)}function wa(e){return u(L(e,[Se]))}function Ra(e){return u({...e,[Se]:"Readonly"})}function Fa(e,t){return t===!1?wa(e):Ra(e)}function ie(e,t){let n=t??!0;return K(e)?wo(e,n):Fa(e,n)}function Aa(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ie(e[r],t);return n}function Ma(e,t){return Aa(e.properties,t)}function wo(e,t){let n=Ma(e,t);return b(n)}function he(e,t){return u(e.length>0?{[l]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[l]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function Ro(e,t){return e in t?ye(e,t[e]):b(t)}function Ua(e){return{[e]:S(e)}}function ka(e){let t={};for(let n of e)t[n]=S(n);return t}function Pa(e,t){return co(t,e)?Ua(e):ka(t)}function Na(e,t){let n=Pa(e,t);return Ro(e,n)}function Vt(e,t){return t.map(n=>ye(e,n))}function Ka(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=ye(e,t[r]);return n}function ye(e,t){let n={...t};return oe(t)?Q(ye(e,L(t,[J]))):lt(t)?ie(ye(e,L(t,[Se]))):K(t)?Ro(e,t.properties):me(t)?Na(e,t.keys):$e(t)?ft(Vt(e,t.parameters),ye(e,t.returns),n):Oe(t)?ke(Vt(e,t.parameters),ye(e,t.returns),n):Qe(t)?pt(ye(e,t.items),n):tt(t)?yt(ye(e,t.items),n):_(t)?ee(Vt(e,t.allOf),n):y(t)?T(Vt(e,t.anyOf),n):de(t)?he(Vt(e,t.items??[]),n):V(t)?O(Ka(e,t.properties),n):Te(t)?dt(ye(e,t.items),n):nt(t)?un(ye(e,t.item),n):t}function Ea(e,t){let n={};for(let r of e)n[r]=ye(r,t);return n}function Fo(e,t,n){let r=pe(e)?se(e):e,o=t({[l]:"MappedKey",keys:r}),s=Ea(r,o);return O(s,n)}function ja(e){return u(L(e,[J]))}function _a(e){return u({...e,[J]:"Optional"})}function La(e,t){return t===!1?ja(e):_a(e)}function Q(e,t){let n=t??!0;return K(e)?Ao(e,n):La(e,n)}function Ga(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Q(e[r],t);return n}function Da(e,t){return Ga(e.properties,t)}function Ao(e,t){let n=Da(e,t);return b(n)}function vt(e,t={}){let n=e.every(o=>V(o)),r=pe(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||pe(t.unevaluatedProperties)||n?{...r,[l]:"Intersect",type:"object",allOf:e}:{...r,[l]:"Intersect",allOf:e},t)}function Ba(e){return e.every(t=>oe(t))}function Va(e){return L(e,[J])}function Mo(e){return e.map(t=>oe(t)?Va(t):t)}function va(e,t){return Ba(e)?Q(vt(Mo(e),t)):vt(Mo(e),t)}function an(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>Ve(n)))throw new Error("Cannot intersect transform types");return va(e,t)}function ee(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>Ve(n)))throw new Error("Cannot intersect transform types");return vt(e,t)}function Ne(...e){let[t,n]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new z("Ref: $ref must be a string");return u({[l]:"Ref",$ref:t},n)}function qa(e,t){return k("Awaited",[k(e,t)])}function Wa(e){return k("Awaited",[Ne(e)])}function za(e){return ee(Uo(e))}function Ha(e){return T(Uo(e))}function Ja(e){return xt(e)}function Uo(e){return e.map(t=>xt(t))}function xt(e,t){return u(Ce(e)?qa(e.target,e.parameters):_(e)?za(e.allOf):y(e)?Ha(e.anyOf):nt(e)?Ja(e.item):G(e)?Wa(e.$ref):e,t)}function ko(e){let t=[];for(let n of e)t.push(qt(n));return t}function Ya(e){let t=ko(e);return po(t)}function Xa(e){let t=ko(e);return lo(t)}function Za(e){return e.map((t,n)=>n.toString())}function Qa(e){return["[number]"]}function eu(e){return globalThis.Object.getOwnPropertyNames(e)}function tu(e){return nu?globalThis.Object.getOwnPropertyNames(e).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function qt(e){return _(e)?Ya(e.allOf):y(e)?Xa(e.anyOf):de(e)?Za(e.items??[]):Te(e)?Qa(e.items):V(e)?eu(e.properties):rt(e)?tu(e.patternProperties):[]}var nu=!1;function ru(e,t){return k("KeyOf",[k(e,t)])}function ou(e){return k("KeyOf",[Ne(e)])}function su(e,t){let n=qt(e),r=iu(n),o=Pe(r);return u(o,t)}function iu(e){return e.map(t=>t==="[number]"?Ie():S(t))}function bt(e,t){return Ce(e)?ru(e.target,e.parameters):G(e)?ou(e.$ref):K(e)?Po(e,t):su(e,t)}function au(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=bt(e[r],N(t));return n}function uu(e,t){return au(e.properties,t)}function Po(e,t){let n=uu(e,t);return b(n)}function cu(e){let t=[];for(let n of e)t.push(...qt(n));return mo(t)}function mu(e){return e.filter(t=>!Be(t))}function lu(e,t){let n=[];for(let r of e)n.push(...zn(r,[t]));return mu(n)}function du(e,t){let n={};for(let r of t)n[r]=an(lu(e,r));return n}function No(e,t){let n=cu(e),r=du(e,n);return O(r,t)}function cn(e){return u({[l]:"Date",type:"Date"},e)}function mn(e){return u({[l]:"Null",type:"null"},e)}function ln(e){return u({[l]:"Symbol",type:"symbol"},e)}function dn(e){return u({[l]:"Undefined",type:"undefined"},e)}function pn(e){return u({[l]:"Uint8Array",type:"Uint8Array"},e)}function He(e){return u({[l]:"Unknown"},e)}function pu(e){return e.map(t=>Hn(t,!1))}function fu(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ie(Hn(e[n],!1));return t}function fn(e,t){return t===!0?e:ie(e)}function Hn(e,t){return Rn(e)?fn(We(),t):An(e)?fn(We(),t):D(e)?ie(he(pu(e))):Ee(e)?pn():Ze(e)?cn():C(e)?fn(O(fu(e)),t):Fn(e)?fn(ke([],He()),t):B(e)?dn():Mn(e)?mn():Un(e)?ln():Ut(e)?ht():ue(e)?S(e):Ke(e)?S(e):A(e)?S(e):O({})}function Ko(e,t){return u(Hn(e,!0),t)}function Eo(e,t){return $e(e)?he(e.parameters,t):x(t)}function jo(e,t){if(B(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(s=>isNaN(s)).map(s=>e[s]),o=[...new Set(n)].map(s=>S(s));return T(o,{...t,[ge]:"Enum"})}var Yn=class extends z{},c;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(c||(c={}));function xe(e){return e===c.False?e:c.True}function St(e){throw new Yn(e)}function q(e){return i.IsNever(e)||i.IsIntersect(e)||i.IsUnion(e)||i.IsUnknown(e)||i.IsAny(e)}function W(e,t){return i.IsNever(t)?vo(e,t):i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsUnknown(t)?Ho(e,t):i.IsAny(t)?Qn(e,t):St("StructuralRight")}function Qn(e,t){return c.True}function gu(e,t){return i.IsIntersect(t)?gn(e,t):i.IsUnion(t)&&t.anyOf.some(n=>i.IsAny(n)||i.IsUnknown(n))?c.True:i.IsUnion(t)?c.Union:i.IsUnknown(t)||i.IsAny(t)?c.True:c.Union}function Iu(e,t){return i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:i.IsNever(e)?c.True:c.False}function hu(e,t){return i.IsObject(t)&&In(t)?c.True:q(t)?W(e,t):i.IsArray(t)?xe(w(e.items,t.items)):c.False}function yu(e,t){return q(t)?W(e,t):i.IsAsyncIterator(t)?xe(w(e.items,t.items)):c.False}function xu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsBigInt(t)?c.True:c.False}function Bo(e,t){return i.IsLiteralBoolean(e)||i.IsBoolean(e)?c.True:c.False}function bu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsBoolean(t)?c.True:c.False}function Su(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsConstructor(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>xe(w(t.parameters[r],n))===c.True)?xe(w(e.returns,t.returns)):c.False:c.False}function Tu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsDate(t)?c.True:c.False}function Cu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsFunction(t)?e.parameters.length>t.parameters.length?c.False:e.parameters.every((n,r)=>xe(w(t.parameters[r],n))===c.True)?xe(w(e.returns,t.returns)):c.False:c.False}function Vo(e,t){return i.IsLiteral(e)&&Z.IsNumber(e.const)||i.IsNumber(e)||i.IsInteger(e)?c.True:c.False}function $u(e,t){return i.IsInteger(t)||i.IsNumber(t)?c.True:q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):c.False}function gn(e,t){return t.allOf.every(n=>w(e,n)===c.True)?c.True:c.False}function Ou(e,t){return e.allOf.some(n=>w(n,t)===c.True)?c.True:c.False}function wu(e,t){return q(t)?W(e,t):i.IsIterator(t)?xe(w(e.items,t.items)):c.False}function Ru(e,t){return i.IsLiteral(t)&&t.const===e.const?c.True:q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsString(t)?zo(e,t):i.IsNumber(t)?qo(e,t):i.IsInteger(t)?Vo(e,t):i.IsBoolean(t)?Bo(e,t):c.False}function vo(e,t){return c.False}function Fu(e,t){return c.True}function _o(e){let[t,n]=[e,0];for(;i.IsNot(t);)t=t.not,n+=1;return n%2===0?t:He()}function Au(e,t){return i.IsNot(e)?w(_o(e),t):i.IsNot(t)?w(e,_o(t)):St("Invalid fallthrough for Not")}function Mu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsNull(t)?c.True:c.False}function qo(e,t){return i.IsLiteralNumber(e)||i.IsNumber(e)||i.IsInteger(e)?c.True:c.False}function Uu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsInteger(t)||i.IsNumber(t)?c.True:c.False}function ae(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Lo(e){return In(e)}function Go(e){return ae(e,0)||ae(e,1)&&"description"in e.properties&&i.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(i.IsString(e.properties.description.anyOf[0])&&i.IsUndefined(e.properties.description.anyOf[1])||i.IsString(e.properties.description.anyOf[1])&&i.IsUndefined(e.properties.description.anyOf[0]))}function Jn(e){return ae(e,0)}function Do(e){return ae(e,0)}function ku(e){return ae(e,0)}function Pu(e){return ae(e,0)}function Nu(e){return In(e)}function Ku(e){let t=Ie();return ae(e,0)||ae(e,1)&&"length"in e.properties&&xe(w(e.properties.length,t))===c.True}function Eu(e){return ae(e,0)}function In(e){let t=Ie();return ae(e,0)||ae(e,1)&&"length"in e.properties&&xe(w(e.properties.length,t))===c.True}function ju(e){let t=ke([We()],We());return ae(e,0)||ae(e,1)&&"then"in e.properties&&xe(w(e.properties.then,t))===c.True}function Wo(e,t){return w(e,t)===c.False||i.IsOptional(e)&&!i.IsOptional(t)?c.False:c.True}function te(e,t){return i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:i.IsNever(e)||i.IsLiteralString(e)&&Lo(t)||i.IsLiteralNumber(e)&&Jn(t)||i.IsLiteralBoolean(e)&&Do(t)||i.IsSymbol(e)&&Go(t)||i.IsBigInt(e)&&ku(t)||i.IsString(e)&&Lo(t)||i.IsSymbol(e)&&Go(t)||i.IsNumber(e)&&Jn(t)||i.IsInteger(e)&&Jn(t)||i.IsBoolean(e)&&Do(t)||i.IsUint8Array(e)&&Nu(t)||i.IsDate(e)&&Pu(t)||i.IsConstructor(e)&&Eu(t)||i.IsFunction(e)&&Ku(t)?c.True:i.IsRecord(e)&&i.IsString(Xn(e))?t[ge]==="Record"?c.True:c.False:i.IsRecord(e)&&i.IsNumber(Xn(e))&&ae(t,0)?c.True:c.False}function _u(e,t){return q(t)?W(e,t):i.IsRecord(t)?be(e,t):i.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!i.IsOptional(t.properties[n]))return c.False;if(i.IsOptional(t.properties[n]))return c.True;if(Wo(e.properties[n],t.properties[n])===c.False)return c.False}return c.True})():c.False}function Lu(e,t){return q(t)?W(e,t):i.IsObject(t)&&ju(t)?c.True:i.IsPromise(t)?xe(w(e.item,t.item)):c.False}function Xn(e){return ve in e.patternProperties?Ie():qe in e.patternProperties?Fe():St("Unknown record key pattern")}function Zn(e){return ve in e.patternProperties?e.patternProperties[ve]:qe in e.patternProperties?e.patternProperties[qe]:St("Unable to get record value schema")}function be(e,t){let[n,r]=[Xn(t),Zn(t)];return i.IsLiteralString(e)&&i.IsNumber(n)&&xe(w(e,r))===c.True?c.True:i.IsUint8Array(e)&&i.IsNumber(n)||i.IsString(e)&&i.IsNumber(n)||i.IsArray(e)&&i.IsNumber(n)?w(e,r):i.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(Wo(r,e.properties[o])===c.False)return c.False;return c.True})():c.False}function Gu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?w(Zn(e),Zn(t)):c.False}function Du(e,t){let n=i.IsRegExp(e)?Fe():e,r=i.IsRegExp(t)?Fe():t;return w(n,r)}function zo(e,t){return i.IsLiteral(e)&&Z.IsString(e.const)||i.IsString(e)?c.True:c.False}function Bu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsString(t)?c.True:c.False}function Vu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsSymbol(t)?c.True:c.False}function vu(e,t){return i.IsTemplateLiteral(e)?w(st(e),t):i.IsTemplateLiteral(t)?w(e,st(t)):St("Invalid fallthrough for TemplateLiteral")}function qu(e,t){return i.IsArray(t)&&e.items!==void 0&&e.items.every(n=>w(n,t.items)===c.True)}function Wu(e,t){return i.IsNever(e)?c.True:i.IsUnknown(e)?c.False:i.IsAny(e)?c.Union:c.False}function zu(e,t){return q(t)?W(e,t):i.IsObject(t)&&In(t)||i.IsArray(t)&&qu(e,t)?c.True:i.IsTuple(t)?Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||!Z.IsUndefined(e.items)&&Z.IsUndefined(t.items)?c.False:Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||e.items.every((n,r)=>w(n,t.items[r])===c.True)?c.True:c.False:c.False}function Hu(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsUint8Array(t)?c.True:c.False}function Ju(e,t){return q(t)?W(e,t):i.IsObject(t)?te(e,t):i.IsRecord(t)?be(e,t):i.IsVoid(t)?Zu(e,t):i.IsUndefined(t)?c.True:c.False}function er(e,t){return t.anyOf.some(n=>w(e,n)===c.True)?c.True:c.False}function Yu(e,t){return e.anyOf.every(n=>w(n,t)===c.True)?c.True:c.False}function Ho(e,t){return c.True}function Xu(e,t){return i.IsNever(t)?vo(e,t):i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsAny(t)?Qn(e,t):i.IsString(t)?zo(e,t):i.IsNumber(t)?qo(e,t):i.IsInteger(t)?Vo(e,t):i.IsBoolean(t)?Bo(e,t):i.IsArray(t)?Iu(e,t):i.IsTuple(t)?Wu(e,t):i.IsObject(t)?te(e,t):i.IsUnknown(t)?c.True:c.False}function Zu(e,t){return i.IsUndefined(e)||i.IsUndefined(e)?c.True:c.False}function Qu(e,t){return i.IsIntersect(t)?gn(e,t):i.IsUnion(t)?er(e,t):i.IsUnknown(t)?Ho(e,t):i.IsAny(t)?Qn(e,t):i.IsObject(t)?te(e,t):i.IsVoid(t)?c.True:c.False}function w(e,t){return i.IsTemplateLiteral(e)||i.IsTemplateLiteral(t)?vu(e,t):i.IsRegExp(e)||i.IsRegExp(t)?Du(e,t):i.IsNot(e)||i.IsNot(t)?Au(e,t):i.IsAny(e)?gu(e,t):i.IsArray(e)?hu(e,t):i.IsBigInt(e)?xu(e,t):i.IsBoolean(e)?bu(e,t):i.IsAsyncIterator(e)?yu(e,t):i.IsConstructor(e)?Su(e,t):i.IsDate(e)?Tu(e,t):i.IsFunction(e)?Cu(e,t):i.IsInteger(e)?$u(e,t):i.IsIntersect(e)?Ou(e,t):i.IsIterator(e)?wu(e,t):i.IsLiteral(e)?Ru(e,t):i.IsNever(e)?Fu(e,t):i.IsNull(e)?Mu(e,t):i.IsNumber(e)?Uu(e,t):i.IsObject(e)?_u(e,t):i.IsRecord(e)?Gu(e,t):i.IsString(e)?Bu(e,t):i.IsSymbol(e)?Vu(e,t):i.IsTuple(e)?zu(e,t):i.IsPromise(e)?Lu(e,t):i.IsUint8Array(e)?Hu(e,t):i.IsUndefined(e)?Ju(e,t):i.IsUnion(e)?Yu(e,t):i.IsUnknown(e)?Xu(e,t):i.IsVoid(e)?Qu(e,t):St(`Unknown left type operand '${e[l]}'`)}function Je(e,t){return w(e,t)}function ec(e,t,n,r,o){let s={};for(let a of globalThis.Object.getOwnPropertyNames(e))s[a]=Tt(e[a],t,n,r,N(o));return s}function tc(e,t,n,r,o){return ec(e.properties,t,n,r,o)}function Jo(e,t,n,r,o){let s=tc(e,t,n,r,o);return b(s)}function nc(e,t,n,r){let o=Je(e,t);return o===c.Union?T([n,r]):o===c.True?n:r}function Tt(e,t,n,r,o){return K(e)?Jo(e,t,n,r,o):me(e)?u(Yo(e,t,n,r,o)):u(nc(e,t,n,r),o)}function rc(e,t,n,r,o){return{[e]:Tt(S(e),t,n,r,N(o))}}function oc(e,t,n,r,o){return e.reduce((s,a)=>({...s,...rc(a,t,n,r,o)}),{})}function sc(e,t,n,r,o){return oc(e.keys,t,n,r,o)}function Yo(e,t,n,r,o){let s=sc(e,t,n,r,o);return b(s)}function Xo(e,t){return Ct(st(e),t)}function ic(e,t){let n=e.filter(r=>Je(r,t)===c.False);return n.length===1?n[0]:T(n)}function Ct(e,t,n={}){return le(e)?u(Xo(e,t),n):K(e)?u(Zo(e,t),n):u(y(e)?ic(e.anyOf,t):Je(e,t)!==c.False?x():e,n)}function ac(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ct(e[r],t);return n}function uc(e,t){return ac(e.properties,t)}function Zo(e,t){let n=uc(e,t);return b(n)}function Qo(e,t){return $t(st(e),t)}function cc(e,t){let n=e.filter(r=>Je(r,t)!==c.False);return n.length===1?n[0]:T(n)}function $t(e,t,n){return le(e)?u(Qo(e,t),n):K(e)?u(es(e,t),n):u(y(e)?cc(e.anyOf,t):Je(e,t)!==c.False?e:x(),n)}function mc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=$t(e[r],t);return n}function lc(e,t){return mc(e.properties,t)}function es(e,t){let n=lc(e,t);return b(n)}function ts(e,t){return $e(e)?u(e.returns,t):x(t)}function hn(e){return ie(Q(e))}function it(e,t,n){return u({[l]:"Record",type:"object",patternProperties:{[e]:t}},n)}function tr(e,t,n){let r={};for(let o of e)r[o]=t;return O(r,{...n,[ge]:"Record"})}function dc(e,t,n){return ho(e)?tr(se(e),t,n):it(e.pattern,t,n)}function pc(e,t,n){return tr(se(T(e)),t,n)}function fc(e,t,n){return tr([e.toString()],t,n)}function gc(e,t,n){return it(e.source,t,n)}function Ic(e,t,n){let r=B(e.pattern)?qe:e.pattern;return it(r,t,n)}function hc(e,t,n){return it(qe,t,n)}function yc(e,t,n){return it(uo,t,n)}function xc(e,t,n){return O({true:t,false:t},n)}function bc(e,t,n){return it(ve,t,n)}function Sc(e,t,n){return it(ve,t,n)}function yn(e,t,n={}){return y(e)?pc(e.anyOf,t,n):le(e)?dc(e,t,n):ce(e)?fc(e.const,t,n):je(e)?xc(e,t,n):we(e)?bc(e,t,n):Re(e)?Sc(e,t,n):Nn(e)?gc(e,t,n):_e(e)?Ic(e,t,n):kn(e)?hc(e,t,n):Be(e)?yc(e,t,n):x(n)}function xn(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function ns(e){let t=xn(e);return t===qe?Fe():t===ve?Ie():Fe({pattern:t})}function bn(e){return e.patternProperties[xn(e)]}function Tc(e,t){return t.parameters=Wt(e,t.parameters),t.returns=Ae(e,t.returns),t}function Cc(e,t){return t.parameters=Wt(e,t.parameters),t.returns=Ae(e,t.returns),t}function $c(e,t){return t.allOf=Wt(e,t.allOf),t}function Oc(e,t){return t.anyOf=Wt(e,t.anyOf),t}function wc(e,t){return B(t.items)||(t.items=Wt(e,t.items)),t}function Rc(e,t){return t.items=Ae(e,t.items),t}function Fc(e,t){return t.items=Ae(e,t.items),t}function Ac(e,t){return t.items=Ae(e,t.items),t}function Mc(e,t){return t.item=Ae(e,t.item),t}function Uc(e,t){let n=Kc(e,t.properties);return{...t,...O(n)}}function kc(e,t){let n=Ae(e,ns(t)),r=Ae(e,bn(t)),o=yn(n,r);return{...t,...o}}function Pc(e,t){return t.index in e?e[t.index]:He()}function Nc(e,t){let n=lt(t),r=oe(t),o=Ae(e,t);return n&&r?hn(o):n&&!r?ie(o):!n&&r?Q(o):o}function Kc(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:Nc(e,t[r])}),{})}function Wt(e,t){return t.map(n=>Ae(e,n))}function Ae(e,t){return $e(t)?Tc(e,t):Oe(t)?Cc(e,t):_(t)?$c(e,t):y(t)?Oc(e,t):de(t)?wc(e,t):Te(t)?Rc(e,t):Qe(t)?Fc(e,t):tt(t)?Ac(e,t):nt(t)?Mc(e,t):V(t)?Uc(e,t):rt(t)?kc(e,t):Pn(t)?Pc(e,t):t}function rs(e,t){return Ae(t,mt(e))}function os(e){return u({[l]:"Integer",type:"integer"},e)}function Ec(e,t,n){return{[e]:Me(S(e),t,N(n))}}function jc(e,t,n){return e.reduce((o,s)=>({...o,...Ec(s,t,n)}),{})}function _c(e,t,n){return jc(e.keys,t,n)}function ss(e,t,n){let r=_c(e,t,n);return b(r)}function Lc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function Gc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function Dc(e){return e.toUpperCase()}function Bc(e){return e.toLowerCase()}function Vc(e,t,n){let r=It(e.pattern);if(!ot(r))return{...e,pattern:is(e.pattern,t)};let a=[...Bt(r)].map(g=>S(g)),m=as(a,t),p=T(m);return sn([p],n)}function is(e,t){return typeof e=="string"?t==="Uncapitalize"?Lc(e):t==="Capitalize"?Gc(e):t==="Uppercase"?Dc(e):t==="Lowercase"?Bc(e):e:e.toString()}function as(e,t){return e.map(n=>Me(n,t))}function Me(e,t,n={}){return me(e)?ss(e,t,n):le(e)?Vc(e,t,n):y(e)?T(as(e.anyOf,t),n):ce(e)?S(is(e.const,t),n):u(e,n)}function us(e,t={}){return Me(e,"Capitalize",t)}function cs(e,t={}){return Me(e,"Lowercase",t)}function ms(e,t={}){return Me(e,"Uncapitalize",t)}function ls(e,t={}){return Me(e,"Uppercase",t)}function vc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ye(e[o],t,N(n));return r}function qc(e,t,n){return vc(e.properties,t,n)}function ds(e,t,n){let r=qc(e,t,n);return b(r)}function Wc(e,t){return e.map(n=>nr(n,t))}function zc(e,t){return e.map(n=>nr(n,t))}function Hc(e,t){let{[t]:n,...r}=e;return r}function Jc(e,t){return t.reduce((n,r)=>Hc(n,r),e)}function Yc(e,t,n){let r=L(e,[v,"$id","required","properties"]),o=Jc(n,t);return O(o,r)}function Xc(e){let t=e.reduce((n,r)=>en(r)?[...n,S(r)]:n,[]);return T(t)}function nr(e,t){return _(e)?ee(Wc(e.allOf,t)):y(e)?T(zc(e.anyOf,t)):V(e)?Yc(e,t,e.properties):O({})}function Ye(e,t,n){let r=D(t)?Xc(t):t,o=pe(t)?se(t):t,s=G(e),a=G(t);return K(e)?ds(e,o,n):me(t)?ps(e,t,n):s&&a?k("Omit",[e,r],n):!s&&a?k("Omit",[e,r],n):s&&!a?k("Omit",[e,r],n):u({...nr(e,o),...n})}function Zc(e,t,n){return{[t]:Ye(e,[t],N(n))}}function Qc(e,t,n){return t.reduce((r,o)=>({...r,...Zc(e,o,n)}),{})}function em(e,t,n){return Qc(e,t.keys,n)}function ps(e,t,n){let r=em(e,t,n);return b(r)}function tm(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Xe(e[o],t,N(n));return r}function nm(e,t,n){return tm(e.properties,t,n)}function fs(e,t,n){let r=nm(e,t,n);return b(r)}function rm(e,t){return e.map(n=>rr(n,t))}function om(e,t){return e.map(n=>rr(n,t))}function sm(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function im(e,t,n){let r=L(e,[v,"$id","required","properties"]),o=sm(n,t);return O(o,r)}function am(e){let t=e.reduce((n,r)=>en(r)?[...n,S(r)]:n,[]);return T(t)}function rr(e,t){return _(e)?ee(rm(e.allOf,t)):y(e)?T(om(e.anyOf,t)):V(e)?im(e,t,e.properties):O({})}function Xe(e,t,n){let r=D(t)?am(t):t,o=pe(t)?se(t):t,s=G(e),a=G(t);return K(e)?fs(e,o,n):me(t)?gs(e,t,n):s&&a?k("Pick",[e,r],n):!s&&a?k("Pick",[e,r],n):s&&!a?k("Pick",[e,r],n):u({...rr(e,o),...n})}function um(e,t,n){return{[t]:Xe(e,[t],N(n))}}function cm(e,t,n){return t.reduce((r,o)=>({...r,...um(e,o,n)}),{})}function mm(e,t,n){return cm(e,t.keys,n)}function gs(e,t,n){let r=mm(e,t,n);return b(r)}function lm(e,t){return k("Partial",[k(e,t)])}function dm(e){return k("Partial",[Ne(e)])}function pm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=Q(e[n]);return t}function fm(e,t){let n=L(e,[v,"$id","required","properties"]),r=pm(t);return O(r,n)}function Is(e){return e.map(t=>hs(t))}function hs(e){return Ce(e)?lm(e.target,e.parameters):G(e)?dm(e.$ref):_(e)?ee(Is(e.allOf)):y(e)?T(Is(e.anyOf)):V(e)?fm(e,e.properties):et(e)||je(e)||we(e)||ce(e)||Nt(e)||Re(e)||_e(e)||Kt(e)||Et(e)?e:O({})}function Ot(e,t){return K(e)?ys(e,t):u({...hs(e),...t})}function gm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ot(e[r],N(t));return n}function Im(e,t){return gm(e.properties,t)}function ys(e,t){let n=Im(e,t);return b(n)}function hm(e,t){return k("Required",[k(e,t)])}function ym(e){return k("Required",[Ne(e)])}function xm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=L(e[n],[J]);return t}function bm(e,t){let n=L(e,[v,"$id","required","properties"]),r=xm(t);return O(r,n)}function xs(e){return e.map(t=>bs(t))}function bs(e){return Ce(e)?hm(e.target,e.parameters):G(e)?ym(e.$ref):_(e)?ee(xs(e.allOf)):y(e)?T(xs(e.anyOf)):V(e)?bm(e,e.properties):et(e)||je(e)||we(e)||ce(e)||Nt(e)||Re(e)||_e(e)||Kt(e)||Et(e)?e:O({})}function wt(e,t){return K(e)?Ss(e,t):u({...bs(e),...t})}function Sm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=wt(e[r],t);return n}function Tm(e,t){return Sm(e.properties,t)}function Ss(e,t){let n=Tm(e,t);return b(n)}function Cm(e,t){return t.map(n=>G(n)?or(e,n.$ref):fe(e,n))}function or(e,t){return t in e?G(e[t])?or(e,e[t].$ref):fe(e,e[t]):x()}function $m(e){return xt(e[0])}function Om(e){return ze(e[0],e[1])}function wm(e){return bt(e[0])}function Rm(e){return Ot(e[0])}function Fm(e){return Ye(e[0],e[1])}function Am(e){return Xe(e[0],e[1])}function Mm(e){return wt(e[0])}function Um(e,t,n){let r=Cm(e,n);return t==="Awaited"?$m(r):t==="Index"?Om(r):t==="KeyOf"?wm(r):t==="Partial"?Rm(r):t==="Omit"?Fm(r):t==="Pick"?Am(r):t==="Required"?Mm(r):x()}function km(e,t){return dt(fe(e,t))}function Pm(e,t){return pt(fe(e,t))}function Nm(e,t,n){return ft(zt(e,t),fe(e,n))}function Km(e,t,n){return ke(zt(e,t),fe(e,n))}function Em(e,t){return ee(zt(e,t))}function jm(e,t){return yt(fe(e,t))}function _m(e,t){return O(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:fe(e,t[r])}),{}))}function Lm(e,t){let[n,r]=[fe(e,bn(t)),xn(t)],o=mt(t);return o.patternProperties[r]=n,o}function Gm(e,t){return G(t)?{...or(e,t.$ref),[v]:t[v]}:t}function Dm(e,t){return he(zt(e,t))}function Bm(e,t){return T(zt(e,t))}function zt(e,t){return t.map(n=>fe(e,n))}function fe(e,t){return oe(t)?u(fe(e,L(t,[J])),t):lt(t)?u(fe(e,L(t,[Se])),t):Ve(t)?u(Gm(e,t),t):Te(t)?u(km(e,t.items),t):Qe(t)?u(Pm(e,t.items),t):Ce(t)?u(Um(e,t.target,t.parameters)):$e(t)?u(Nm(e,t.parameters,t.returns),t):Oe(t)?u(Km(e,t.parameters,t.returns),t):_(t)?u(Em(e,t.allOf),t):tt(t)?u(jm(e,t.items),t):V(t)?u(_m(e,t.properties),t):rt(t)?u(Lm(e,t)):de(t)?u(Dm(e,t.items||[]),t):y(t)?u(Bm(e,t.anyOf),t):t}function Vm(e,t){return t in e?fe(e,e[t]):x()}function Ts(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:Vm(e,n)}),{})}var sr=class{constructor(t){let n=Ts(t),r=this.WithIdentifiers(n);this.$defs=r}Import(t,n){let r={...this.$defs,[t]:u(this.$defs[t],n)};return u({[l]:"Import",$defs:r,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:{...t[r],$id:r}}),{})}};function Cs(e){return new sr(e)}function $s(e,t){return u({[l]:"Not",not:e},t)}function Os(e,t){return Oe(e)?he(e.parameters,t):x()}var vm=0;function ws(e,t={}){B(t.$id)&&(t.$id=`T${vm++}`);let n=mt(e({[l]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[ge]:"Recursive",...n},t)}function Rs(e,t){let n=A(e)?new globalThis.RegExp(e):e;return u({[l]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},t)}function qm(e){return _(e)?e.allOf:y(e)?e.anyOf:de(e)?e.items??[]:[]}function Fs(e){return qm(e)}function As(e,t){return Oe(e)?u(e.returns,t):x(t)}var ir=class{constructor(t){this.schema=t}Decode(t){return new ar(this.schema,t)}},ar=class{constructor(t,n){this.schema=t,this.decode=n}EncodeTransform(t,n){let s={Encode:a=>n[v].Encode(t(a)),Decode:a=>this.decode(n[v].Decode(a))};return{...n,[v]:s}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[v]:r}}Encode(t){return Ve(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function Ms(e){return new ir(e)}function Us(e={}){return u({[l]:e[l]??"Unsafe"},e)}function ks(e){return u({[l]:"Void",type:"void"},e)}var ur={};Yt(ur,{Any:()=>We,Argument:()=>fo,Array:()=>dt,AsyncIterator:()=>pt,Awaited:()=>xt,BigInt:()=>ht,Boolean:()=>on,Capitalize:()=>us,Composite:()=>No,Const:()=>Ko,Constructor:()=>ft,ConstructorParameters:()=>Eo,Date:()=>cn,Enum:()=>jo,Exclude:()=>Ct,Extends:()=>Tt,Extract:()=>$t,Function:()=>ke,Index:()=>ze,InstanceType:()=>ts,Instantiate:()=>rs,Integer:()=>os,Intersect:()=>ee,Iterator:()=>yt,KeyOf:()=>bt,Literal:()=>S,Lowercase:()=>cs,Mapped:()=>Fo,Module:()=>Cs,Never:()=>x,Not:()=>$s,Null:()=>mn,Number:()=>Ie,Object:()=>O,Omit:()=>Ye,Optional:()=>Q,Parameters:()=>Os,Partial:()=>Ot,Pick:()=>Xe,Promise:()=>un,Readonly:()=>ie,ReadonlyOptional:()=>hn,Record:()=>yn,Recursive:()=>ws,Ref:()=>Ne,RegExp:()=>Rs,Required:()=>wt,Rest:()=>Fs,ReturnType:()=>As,String:()=>Fe,Symbol:()=>ln,TemplateLiteral:()=>sn,Transform:()=>Ms,Tuple:()=>he,Uint8Array:()=>pn,Uncapitalize:()=>ms,Undefined:()=>dn,Union:()=>T,Unknown:()=>He,Unsafe:()=>Us,Uppercase:()=>ls,Void:()=>ks});var f=ur;var d=null,Wm=null,F={maxSessions:5,defaultBudgetUsd:5,idleTimeoutMinutes:30,maxPersistedSessions:50,maxAutoResponds:10};function Ps(e){F={maxSessions:e.maxSessions??5,defaultBudgetUsd:e.defaultBudgetUsd??5,defaultModel:e.defaultModel,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??30,maxPersistedSessions:e.maxPersistedSessions??50,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10}}function cr(e){d=e}function mr(e){Wm=e}function ne(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channel&&e?.chatId)return`${e.channel}|${e.chatId}`;if(e?.channel&&e?.senderId)return`${e.channel}|${e.senderId}`;if(e?.id&&/^-?\d+$/.test(String(e.id)))return`telegram|${e.id}`;if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);let n=F.fallbackChannel??"unknown";return console.log(`[resolveOriginChannel] Could not resolve channel from ctx keys: ${e?Object.keys(e).join(", "):"null"}, using fallback=${n}`),n}function zm(e){let t=e.split("|");if(t.length>=3&&t[1])return t[1]}function Ns(e){let t=Y(e);if(t)return zm(t)}function Y(e){console.log(`[resolveAgentChannel] workdir=${e}, agentChannels=${JSON.stringify(F.agentChannels)}`);let t=F.agentChannels;if(!t)return;let n=s=>s.replace(/\/+$/,""),r=n(e),o=Object.entries(t).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of o)if(r===n(s)||r.startsWith(n(s)+"/"))return a}function X(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m${r}s`:`${r}s`}var Hm=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","i","me","my","we","our","you","your","it","its","he","she","to","of","in","for","on","with","at","by","from","as","into","through","about","that","this","these","those","and","or","but","if","then","so","not","no","please","just","also","very","all","some","any","each","make","write","create","build","implement","add","update"]);function Ks(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!Hm.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var Jm={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function Rt(e){let t=Jm[e.status]??"\u2753",n=X(e.duration),r=e.foregroundChannels.size>0?"foreground":"background",o=e.multiTurn?"multi-turn":"single",s=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,a=[`${t} ${e.name} [${e.id}] (${n}) \u2014 ${r}, ${o}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${s}"`];return e.claudeSessionId&&a.push(` \u{1F517} Claude ID: ${e.claudeSessionId}`),e.resumeSessionId&&a.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),a.join(`
2
2
  `)}function Ft(e){let t=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,n=d?d.list("running").length:0,{completed:r,failed:o,killed:s}=e.sessionsByStatus,a=r+o+s,m=["\u{1F4CA} Claude Code Plugin Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${n}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${s}`,"",`\u23F1\uFE0F Average duration: ${t>0?X(t):"n/a"}`];if(e.mostExpensive){let p=e.mostExpensive;m.push("","\u{1F3C6} Notable session",` ${p.name} [${p.id}]`,` \u{1F4DD} "${p.prompt}"`)}return m.join(`
3
- `)}function js(e){return console.log(`[claude-launch] Factory ctx: agentId=${e.agentId}, workspaceDir=${e.workspaceDir}, messageChannel=${e.messageChannel}, agentAccountId=${e.agentAccountId}`),{name:"claude_launch",description:"Launch a Claude Code session in background to execute a development task. Sessions are multi-turn by default \u2014 they stay open for follow-up messages via claude_respond. Set multi_turn_disabled: true for fire-and-forget sessions. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:f.Object({prompt:f.String({description:"The task prompt to execute"}),name:f.Optional(f.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:f.Optional(f.String({description:"Working directory (defaults to cwd)"})),model:f.Optional(f.String({description:"Model name to use"})),max_budget_usd:f.Optional(f.Number({description:"Maximum budget in USD (default 5)"})),system_prompt:f.Optional(f.String({description:"Additional system prompt"})),allowed_tools:f.Optional(f.Array(f.String(),{description:"List of allowed tools"})),resume_session_id:f.Optional(f.String({description:"Claude session ID to resume (from a previous session's claudeSessionId). Continues the conversation from where it left off."})),fork_session:f.Optional(f.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),multi_turn_disabled:f.Optional(f.Boolean({description:"Disable multi-turn mode. By default sessions stay open for follow-up messages. Set to true for fire-and-forget sessions."})),permission_mode:f.Optional(f.Union([f.Literal("default"),f.Literal("plan"),f.Literal("acceptEdits"),f.Literal("bypassPermissions")],{description:"Permission mode for the session. Defaults to plugin config or 'bypassPermissions'."}))}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=n.workdir||e.workspaceDir||U.defaultWorkdir||process.cwd(),o=n.max_budget_usd??U.defaultBudgetUsd??5;try{let s=n.resume_session_id;if(s){let B=d.resolveClaudeSessionId(s);if(!B)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${s}" to a Claude session ID. Use claude_sessions to list available sessions.`}]};s=B}let a;if(e.messageChannel&&e.agentAccountId){let B=e.messageChannel.split("|");B.length>=2&&(a=`${B[0]}|${e.agentAccountId}|${B.slice(1).join("|")}`)}!a&&e.workspaceDir&&(a=Y(e.workspaceDir)),!a&&e.messageChannel&&e.messageChannel.includes("|")&&(a=e.messageChannel);let m=re({id:t},a||Y(r));if(m==="unknown"){let B=Y(r);B&&(m=B)}let p=e.workspaceDir||r,g=(0,Sn.join)(p,"skills","claude-code-autonomy","SKILL.md");if(!(0,at.existsSync)(g))return console.log(`[claude-launch] Autonomy skill not found at ${g} \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 no autonomy skill found.","","No autonomy skill found. You MUST ask the user what level of autonomy they want to give Claude Code sessions. Then create the skill at skills/claude-code-autonomy/ with their preferences. Only then can you launch sessions.","","Do NOT create the skill without asking the user first. Ask them how they want you to handle Claude Code interactions. For example:",'- "Respond to everything automatically except architecture choices"','- "Always ask me before responding"','- "Handle everything yourself, just notify me when done"',"","After the user responds, create the skill:","1. Create directory: skills/claude-code-autonomy/","2. Create SKILL.md with structured rules based on the user's response","3. Create autonomy.md with the user's raw preferences","4. Then re-call claude_launch to start the session.","","The skill MUST also define these notification formats that the agent uses:","","\u{1F44B} [session-name] Important question \u2014 needs your decision:",'> "question text"',"(Used when Claude asks something that requires the user's input \u2014 architecture, destructive ops, ambiguous requirements)","","\u{1F916} [session-name] finished:","Summary of what Claude did, files changed, issues found.","(Used when a session completes \u2014 the agent reads the output and summarizes)","","Note: \u{1F514} Claude asks and \u21A9\uFE0F Responded notifications are handled automatically by the plugin. The skill only needs to define rules for \u{1F44B} (when to forward vs auto-respond) and \u{1F916} (summary format)."].join(`
4
- `)}]};let I=e.agentId||Ns(p);if(I&&!e.agentId&&console.warn(`[claude-launch] Using resolveAgentId fallback for agentId="${I}" \u2014 this may be an account alias, not the real agent ID`),I){let B=(0,Sn.join)((0,Es.homedir)(),".openclaw","openclaw.json"),ct=!1,pr;try{if((0,at.existsSync)(B)){let On=(0,at.readFileSync)(B,"utf-8"),fr=JSON.parse(On)?.agents?.list;if(Array.isArray(fr)){let wn=fr.find(ui=>ui.id===I);wn&&wn.heartbeat!=null&&(ct=!0,pr=wn.heartbeat.every)}}}catch(On){console.log(`[claude-launch] Failed to read openclaw config at ${B}: ${On.message}`)}if(!ct)return console.log(`[claude-launch] Heartbeat not configured for agent "${I}" \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 no heartbeat configured for this agent.","",'Claude Code sessions require heartbeat to be enabled for automatic "waiting for input" notifications.',"","You must configure the heartbeat FIRST. Here's what to do:","",`1. Edit ~/.openclaw/openclaw.json and add heartbeat config for agent "${I}":`,"",` jq '.agents.list |= map(if .id == "${I}" then . + {"heartbeat": {"every": "60m", "target": "last"}} else . end)' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"","2. Verify the config was applied:","",` cat ~/.openclaw/openclaw.json | jq '.agents.list[] | select(.id == "${I}") | .heartbeat'`,"","3. Launch a Claude Code session to restart the Gateway and wake you back:",""," claude_launch(",' prompt="STEP 1: Restart Gateway to activate heartbeat: openclaw gateway restart'," STEP 2: Wait 5 seconds",` STEP 3: Wake the agent: openclaw agent --agent ${I} --message 'Heartbeat configured, continuing task'`,' STEP 4: Continue the original task: [USER_TASK]",',' name="setup-heartbeat"'," )"].join(`
5
- `)}]};if(pr==="5s")return console.log(`[claude-launch] Heartbeat interval too short (5s) for agent "${I}" \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 heartbeat interval too short (5s).","","A heartbeat interval of 5s wastes tokens unnecessarily. Targeted agent messages wake you instantly, so the heartbeat interval only affects regular polling.","","Fix the heartbeat interval to 60m:","",` jq '.agents.list |= map(if .id == "${I}" then .heartbeat.every = "60m" else . end)' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"","Then ask the user to restart the gateway. Do NOT restart the gateway yourself \u2014 only the user can do this safely. After the user confirms the restart, retry your launch."].join(`
6
- `)}]}}let j=(0,Sn.join)(p,"HEARTBEAT.md"),ne=!1;try{if((0,at.existsSync)(j)){let B=(0,at.readFileSync)(j,"utf-8");/^(\s|#.*)*$/.test(B)||(ne=!0)}}catch(B){console.log(`[claude-launch] Failed to read HEARTBEAT.md at ${j}: ${B.message}`)}if(!ne)return console.log(`[claude-launch] HEARTBEAT.md missing or empty at ${j} \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 no HEARTBEAT.md file found or file is effectively empty.","","Claude Code sessions require a HEARTBEAT.md with real content as a safety-net fallback.","The plugin wakes you instantly via targeted agent messages when sessions need attention,","but the heartbeat acts as a 60m backup in case a wake message is lost.","","You must create HEARTBEAT.md FIRST. Here's what to do:","",`1. Create ${p}/HEARTBEAT.md with this content:`,"",`cat > ${p}/HEARTBEAT.md << 'EOF'`,`# Heartbeat ${I} Agent`,"","## Check Claude Code sessions (safety-net fallback)","Note: The plugin sends targeted wake messages instantly when sessions need attention.","This heartbeat is a 60m backup in case a wake message was lost.","","Si des sessions Claude Code sont en attente (waiting for input) :","1. `claude_sessions` pour lister les sessions actives","2. Si session waiting \u2192 `claude_output(session)` pour voir la question","3. Traiter ou notifier l'utilisateur","","Sinon \u2192 HEARTBEAT_OK","EOF","","2. Verify the heartbeat frequency is set to 60m:","",`cat ~/.openclaw/openclaw.json | jq '.agents.list[] | select(.id == "${I}") | .heartbeat.every'`,"",'If NOT "60m", update it:',"",`jq '.agents.list |= map(if .id == "${I}" then .heartbeat.every = "60m" else . end)' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"","3. Launch Claude Code to restart Gateway:",""," claude_launch(",' prompt="STEP 1: Restart Gateway: openclaw gateway restart'," STEP 2: Wait 5s",` STEP 3: Wake agent: openclaw agent --agent ${I} --message 'HEARTBEAT.md configured'`,' STEP 4: Continue task: [USER_TASK]",',' name="setup-heartbeat-md"'," )"].join(`
3
+ `)}function js(e){return console.log(`[claude-launch] Factory ctx: agentId=${e.agentId}, workspaceDir=${e.workspaceDir}, messageChannel=${e.messageChannel}, agentAccountId=${e.agentAccountId}`),{name:"claude_launch",description:"Launch a Claude Code session in background to execute a development task. Sessions are multi-turn by default \u2014 they stay open for follow-up messages via claude_respond. Set multi_turn_disabled: true for fire-and-forget sessions. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:f.Object({prompt:f.String({description:"The task prompt to execute"}),name:f.Optional(f.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:f.Optional(f.String({description:"Working directory (defaults to cwd)"})),model:f.Optional(f.String({description:"Model name to use"})),max_budget_usd:f.Optional(f.Number({description:"Maximum budget in USD (default 5)"})),system_prompt:f.Optional(f.String({description:"Additional system prompt"})),allowed_tools:f.Optional(f.Array(f.String(),{description:"List of allowed tools"})),resume_session_id:f.Optional(f.String({description:"Claude session ID to resume (from a previous session's claudeSessionId). Continues the conversation from where it left off."})),fork_session:f.Optional(f.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),multi_turn_disabled:f.Optional(f.Boolean({description:"Disable multi-turn mode. By default sessions stay open for follow-up messages. Set to true for fire-and-forget sessions."})),permission_mode:f.Optional(f.Union([f.Literal("default"),f.Literal("plan"),f.Literal("acceptEdits"),f.Literal("bypassPermissions")],{description:"Permission mode for the session. Defaults to plugin config or 'bypassPermissions'."}))}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=n.workdir||e.workspaceDir||F.defaultWorkdir||process.cwd(),o=n.max_budget_usd??F.defaultBudgetUsd??5;try{let s=n.resume_session_id;if(s){let P=d.resolveClaudeSessionId(s);if(!P)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${s}" to a Claude session ID. Use claude_sessions to list available sessions.`}]};s=P}let a;if(e.messageChannel&&e.agentAccountId){let P=e.messageChannel.split("|");P.length>=2&&(a=`${P[0]}|${e.agentAccountId}|${P.slice(1).join("|")}`)}!a&&e.workspaceDir&&(a=Y(e.workspaceDir)),!a&&e.messageChannel&&e.messageChannel.includes("|")&&(a=e.messageChannel);let m=ne({id:t},a||Y(r));if(m==="unknown"){let P=Y(r);P&&(m=P)}let p=e.workspaceDir||r;if(F.skipSafetyChecks)console.log("[claude-launch] Safety checks skipped (skipSafetyChecks=true)");else{let P=(0,Sn.join)(p,"skills","claude-code-autonomy","SKILL.md");if(!(0,at.existsSync)(P))return console.log(`[claude-launch] Autonomy skill not found at ${P} \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 no autonomy skill found.","","No autonomy skill found. You MUST ask the user what level of autonomy they want to give Claude Code sessions. Then create the skill at skills/claude-code-autonomy/ with their preferences. Only then can you launch sessions.","","Do NOT create the skill without asking the user first. Ask them how they want you to handle Claude Code interactions. For example:",'- "Respond to everything automatically except architecture choices"','- "Always ask me before responding"','- "Handle everything yourself, just notify me when done"',"","After the user responds, create the skill:","1. Create directory: skills/claude-code-autonomy/","2. Create SKILL.md with structured rules based on the user's response","3. Create autonomy.md with the user's raw preferences","4. Then re-call claude_launch to start the session.","","The skill MUST also define these notification formats that the agent uses:","","\u{1F44B} [session-name] Important question \u2014 needs your decision:",'> "question text"',"(Used when Claude asks something that requires the user's input \u2014 architecture, destructive ops, ambiguous requirements)","","\u{1F916} [session-name] finished:","Summary of what Claude did, files changed, issues found.","(Used when a session completes \u2014 the agent reads the output and summarizes)","","Note: \u{1F514} Claude asks and \u21A9\uFE0F Responded notifications are handled automatically by the plugin. The skill only needs to define rules for \u{1F44B} (when to forward vs auto-respond) and \u{1F916} (summary format)."].join(`
4
+ `)}]};let R=e.agentId||Ns(p);if(R&&!e.agentId&&console.warn(`[claude-launch] Using resolveAgentId fallback for agentId="${R}" \u2014 this may be an account alias, not the real agent ID`),R){let Ue=(0,Sn.join)((0,Es.homedir)(),".openclaw","openclaw.json"),ct=!1,pr;try{if((0,at.existsSync)(Ue)){let On=(0,at.readFileSync)(Ue,"utf-8"),fr=JSON.parse(On)?.agents?.list;if(Array.isArray(fr)){let wn=fr.find(ui=>ui.id===R);wn&&wn.heartbeat!=null&&(ct=!0,pr=wn.heartbeat.every)}}}catch(On){console.log(`[claude-launch] Failed to read openclaw config at ${Ue}: ${On.message}`)}if(!ct)return console.log(`[claude-launch] Heartbeat not configured for agent "${R}" \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 no heartbeat configured for this agent.","",'Claude Code sessions require heartbeat to be enabled for automatic "waiting for input" notifications.',"","You must configure the heartbeat FIRST. Here's what to do:","",`1. Edit ~/.openclaw/openclaw.json and add heartbeat config for agent "${R}":`,"",` jq '.agents.list |= map(if .id == "${R}" then . + {"heartbeat": {"every": "60m", "target": "last"}} else . end)' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"","2. Verify the config was applied:","",` cat ~/.openclaw/openclaw.json | jq '.agents.list[] | select(.id == "${R}") | .heartbeat'`,"","3. Launch a Claude Code session to restart the Gateway and wake you back:",""," claude_launch(",' prompt="STEP 1: Restart Gateway to activate heartbeat: openclaw gateway restart'," STEP 2: Wait 5 seconds",` STEP 3: Wake the agent: openclaw agent --agent ${R} --message 'Heartbeat configured, continuing task'`,' STEP 4: Continue the original task: [USER_TASK]",',' name="setup-heartbeat"'," )"].join(`
5
+ `)}]};if(pr==="5s")return console.log(`[claude-launch] Heartbeat interval too short (5s) for agent "${R}" \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 heartbeat interval too short (5s).","","A heartbeat interval of 5s wastes tokens unnecessarily. Targeted agent messages wake you instantly, so the heartbeat interval only affects regular polling.","","Fix the heartbeat interval to 60m:","",` jq '.agents.list |= map(if .id == "${R}" then .heartbeat.every = "60m" else . end)' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"","Then ask the user to restart the gateway. Do NOT restart the gateway yourself \u2014 only the user can do this safely. After the user confirms the restart, retry your launch."].join(`
6
+ `)}]}}let re=(0,Sn.join)(p,"HEARTBEAT.md"),De=!1;try{if((0,at.existsSync)(re)){let Ue=(0,at.readFileSync)(re,"utf-8");/^(\s|#.*)*$/.test(Ue)||(De=!0)}}catch(Ue){console.log(`[claude-launch] Failed to read HEARTBEAT.md at ${re}: ${Ue.message}`)}if(!De)return console.log(`[claude-launch] HEARTBEAT.md missing or empty at ${re} \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:["ERROR: Launch blocked \u2014 no HEARTBEAT.md file found or file is effectively empty.","","Claude Code sessions require a HEARTBEAT.md with real content as a safety-net fallback.","The plugin wakes you instantly via targeted agent messages when sessions need attention,","but the heartbeat acts as a 60m backup in case a wake message is lost.","","You must create HEARTBEAT.md FIRST. Here's what to do:","",`1. Create ${p}/HEARTBEAT.md with this content:`,"",`cat > ${p}/HEARTBEAT.md << 'EOF'`,"# Heartbeat Agent","","## Check Claude Code sessions (safety-net fallback)","Note: The plugin sends targeted wake messages instantly when sessions need attention.","This heartbeat is a 60m backup in case a wake message was lost.","","Si des sessions Claude Code sont en attente (waiting for input) :","1. `claude_sessions` pour lister les sessions actives","2. Si session waiting \u2192 `claude_output(session)` pour voir la question","3. Traiter ou notifier l'utilisateur","","Sinon \u2192 HEARTBEAT_OK","EOF","","2. Verify the heartbeat frequency is set to 60m:","","cat ~/.openclaw/openclaw.json | jq '.agents.list[] | .heartbeat.every'","",'If NOT "60m", update it:',"",`jq '.agents.list |= map(.heartbeat.every = "60m")' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"","3. Launch Claude Code to restart Gateway:",""," claude_launch(",' prompt="STEP 1: Restart Gateway: openclaw gateway restart'," STEP 2: Wait 5s"," STEP 3: Wake agent: openclaw agent --message 'HEARTBEAT.md configured'",' STEP 4: Continue task: [USER_TASK]",',' name="setup-heartbeat-md"'," )"].join(`
7
7
  `)}]};if(!Y(r))return console.log(`[claude-launch] No agentChannels mapping for workdir "${r}" \u2014 blocking launch`),{isError:!0,content:[{type:"text",text:[`ERROR: Launch blocked \u2014 no agentChannels mapping found for workspace "${r}".`,"","Claude Code sessions require the workspace directory to be mapped in the agentChannels config","so notifications can be routed to the correct agent and chat.","","You must add the workspace to agentChannels FIRST. Here's what to do:","","1. Edit ~/.openclaw/openclaw.json and add the workspace mapping under plugins.config.openclaw-claude-code-plugin.agentChannels:","",` jq '.plugins.config["openclaw-claude-code-plugin"].agentChannels["${r}"] = "channel|accountId|chatId"' ~/.openclaw/openclaw.json > /tmp/openclaw-updated.json && mv /tmp/openclaw-updated.json ~/.openclaw/openclaw.json`,"",' Replace "channel|accountId|chatId" with the actual values, e.g.: "telegram|my-agent|123456789"',"","2. Verify the config was applied:","",` cat ~/.openclaw/openclaw.json | jq '.plugins.config["openclaw-claude-code-plugin"].agentChannels'`,"","3. Restart the Gateway to pick up the new config, then retry the launch:",""," openclaw gateway restart"].join(`
8
- `)}]};let ue=d.spawn({prompt:n.prompt,name:n.name,workdir:r,model:n.model||U.defaultModel,maxBudgetUsd:o,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:s,forkSession:n.fork_session,multiTurn:!n.multi_turn_disabled,permissionMode:n.permission_mode,originChannel:m,originAgentId:e.agentId||void 0}),Xe=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,$=["Session launched successfully.",` Name: ${ue.name}`,` ID: ${ue.id}`,` Dir: ${r}`,` Model: ${ue.model??"default"}`,` Prompt: "${Xe}"`];return n.resume_session_id&&$.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),n.multi_turn_disabled?$.push(" Mode: single-turn (fire-and-forget)"):$.push(" Mode: multi-turn (use claude_respond to send follow-up messages)"),$.push(""),$.push("Use claude_sessions to check status, claude_output to see output."),{content:[{type:"text",text:$.join(`
8
+ `)}]}}let g=d.spawn({prompt:n.prompt,name:n.name,workdir:r,model:n.model||F.defaultModel,maxBudgetUsd:o,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:s,forkSession:n.fork_session,multiTurn:!n.multi_turn_disabled,permissionMode:n.permission_mode,originChannel:m,originAgentId:e.agentId||void 0}),U=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,E=["Session launched successfully.",` Name: ${g.name}`,` ID: ${g.id}`,` Dir: ${r}`,` Model: ${g.model??"default"}`,` Prompt: "${U}"`];return n.resume_session_id&&E.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),n.multi_turn_disabled?E.push(" Mode: single-turn (fire-and-forget)"):E.push(" Mode: multi-turn (use claude_respond to send follow-up messages)"),E.push(""),E.push("Use claude_sessions to check status, claude_output to see output."),{content:[{type:"text",text:E.join(`
9
9
  `)}]}}catch(s){return{content:[{type:"text",text:`Error launching session: ${s.message}`}]}}}}}function _s(e){return{name:"claude_sessions",description:"List all Claude Code sessions with their status and progress.",parameters:f.Object({status:f.Optional(f.Union([f.Literal("all"),f.Literal("running"),f.Literal("completed"),f.Literal("failed")],{description:'Filter by status (default "all")'}))}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=n.status||"all",o=d.list(r),s=o;if(e?.workspaceDir){let m=Y(e.workspaceDir);m?(console.log(`[claude_sessions] Filtering sessions by agentChannel=${m}`),s=o.filter(p=>{let g=p.originChannel===m;return console.log(`[claude_sessions] session=${p.id} originChannel=${p.originChannel} match=${g}`),g})):console.log(`[claude_sessions] No agentChannel found for workspaceDir=${e.workspaceDir}, returning all sessions`)}return s.length===0?{content:[{type:"text",text:"No sessions found."}]}:{content:[{type:"text",text:s.map(Rt).join(`
10
10
 
11
11
  `)}]}}}}function Ls(e){return{name:"claude_kill",description:"Terminate a running Claude Code session by name or ID.",parameters:f.Object({session:f.String({description:"Session name or ID to terminate"})}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=d.resolve(n.session);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?{content:[{type:"text",text:`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`}]}:(d.kill(r.id),{content:[{type:"text",text:`Session ${r.name} [${r.id}] has been terminated.`}]}):{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}]}}}}function Gs(e){return{name:"claude_output",description:"Show recent output from a Claude Code session (by name or ID).",parameters:f.Object({session:f.String({description:"Session name or ID to get output from"}),lines:f.Optional(f.Number({description:"Number of recent lines to show (default 50)"})),full:f.Optional(f.Boolean({description:"Show all available output"}))}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=d.resolve(n.session);if(!r)return{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}]};let o=n.full?r.getOutput():r.getOutput(n.lines??50),s=X(r.duration),a=[`Session: ${r.name} [${r.id}] | Status: ${r.status.toUpperCase()} | Duration: ${s}`,`${"\u2500".repeat(60)}`].join(`
12
12
  `);return o.length===0?{content:[{type:"text",text:`${a}
13
13
  (no output yet)`}]}:{content:[{type:"text",text:`${a}
14
14
  ${o.join(`
15
- `)}`}]}}}}function Ds(e){let t;if(e?.messageChannel&&e?.agentAccountId){let n=e.messageChannel.split("|");n.length>=2&&(t=`${n[0]}|${e.agentAccountId}|${n.slice(1).join("|")}`)}return!t&&e?.workspaceDir&&(t=Y(e.workspaceDir)),!t&&e?.messageChannel&&e.messageChannel.includes("|")&&(t=e.messageChannel),console.log(`[claude-fg] Factory context: messageChannel=${e?.messageChannel}, agentAccountId=${e?.agentAccountId}, workspaceDir=${e?.workspaceDir}, fallbackChannel=${t}`),{name:"claude_fg",description:"Bring a Claude Code session to foreground (by name or ID). Shows buffered output and streams new output.",parameters:f.Object({session:f.String({description:"Session name or ID to bring to foreground"}),lines:f.Optional(f.Number({description:"Number of recent buffered lines to show (default 30)"}))}),async execute(n,r){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let o=d.resolve(r.session);if(!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let s=re({id:n},t);if(console.log(`[claude-fg] channelId resolved: ${s}, session.workdir=${o.workdir}`),s==="unknown"){let ne=Y(o.workdir);ne&&(s=ne)}let a=o.getCatchupOutput(s);o.foregroundChannels.add(s);let m=X(o.duration),p=[`Session ${o.name} [${o.id}] now in foreground.`,`Status: ${o.status.toUpperCase()} | Duration: ${m}`,`${"\u2500".repeat(60)}`].join(`
15
+ `)}`}]}}}}function Ds(e){let t;if(e?.messageChannel&&e?.agentAccountId){let n=e.messageChannel.split("|");n.length>=2&&(t=`${n[0]}|${e.agentAccountId}|${n.slice(1).join("|")}`)}return!t&&e?.workspaceDir&&(t=Y(e.workspaceDir)),!t&&e?.messageChannel&&e.messageChannel.includes("|")&&(t=e.messageChannel),console.log(`[claude-fg] Factory context: messageChannel=${e?.messageChannel}, agentAccountId=${e?.agentAccountId}, workspaceDir=${e?.workspaceDir}, fallbackChannel=${t}`),{name:"claude_fg",description:"Bring a Claude Code session to foreground (by name or ID). Shows buffered output and streams new output.",parameters:f.Object({session:f.String({description:"Session name or ID to bring to foreground"}),lines:f.Optional(f.Number({description:"Number of recent buffered lines to show (default 30)"}))}),async execute(n,r){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let o=d.resolve(r.session);if(!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let s=ne({id:n},t);if(console.log(`[claude-fg] channelId resolved: ${s}, session.workdir=${o.workdir}`),s==="unknown"){let P=Y(o.workdir);P&&(s=P)}let a=o.getCatchupOutput(s);o.foregroundChannels.add(s);let m=X(o.duration),p=[`Session ${o.name} [${o.id}] now in foreground.`,`Status: ${o.status.toUpperCase()} | Duration: ${m}`,`${"\u2500".repeat(60)}`].join(`
16
16
  `),g="";a.length>0&&(g=[`\u{1F4CB} Catchup (${a.length} missed output${a.length===1?"":"s"}):`,a.join(`
17
17
  `),`${"\u2500".repeat(60)}`].join(`
18
- `));let I=a.length>0?g:o.getOutput(r.lines??30).length>0?o.getOutput(r.lines??30).join(`
19
- `):"(no output yet)",j=o.status==="running"||o.status==="starting"?`
18
+ `));let U=a.length>0?g:o.getOutput(r.lines??30).length>0?o.getOutput(r.lines??30).join(`
19
+ `):"(no output yet)",E=o.status==="running"||o.status==="starting"?`
20
20
  ${"\u2500".repeat(60)}
21
21
  Streaming new output... Use claude_bg to detach.`:`
22
22
  ${"\u2500".repeat(60)}
23
23
  Session is ${o.status}. No more output expected.`;return o.markFgOutputSeen(s),{content:[{type:"text",text:`${p}
24
- ${I}${j}`}]}}}}function Bs(e){let t;if(e?.messageChannel&&e?.agentAccountId){let n=e.messageChannel.split("|");n.length>=2&&(t=`${n[0]}|${e.agentAccountId}|${n.slice(1).join("|")}`)}return!t&&e?.workspaceDir&&(t=Y(e.workspaceDir)),!t&&e?.messageChannel&&e.messageChannel.includes("|")&&(t=e.messageChannel),console.log(`[claude-bg] Factory context: messageChannel=${e?.messageChannel}, agentAccountId=${e?.agentAccountId}, workspaceDir=${e?.workspaceDir}, fallbackChannel=${t}`),{name:"claude_bg",description:"Send a Claude Code session back to background (stop streaming). If no session specified, detaches whichever session is currently in foreground.",parameters:f.Object({session:f.Optional(f.String({description:"Session name or ID to send to background. If omitted, detaches the current foreground session."}))}),async execute(n,r){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};if(r.session){let p=d.resolve(r.session);if(!p)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let g=re({id:n},t);if(console.log(`[claude-bg] channelId resolved: ${g}, session.workdir=${p.workdir}`),g==="unknown"){let I=Y(p.workdir);I&&(g=I)}return p.saveFgOutputOffset(g),p.foregroundChannels.delete(g),{content:[{type:"text",text:`Session ${p.name} [${p.id}] moved to background.`}]}}let o=re({id:n},t);if(console.log(`[claude-bg] resolvedId (no session): ${o}`),o==="unknown"){let p=d.list("all");for(let g of p){let I=Y(g.workdir);if(I&&g.foregroundChannels.has(I)){o=I;break}}}let a=d.list("all").filter(p=>p.foregroundChannels.has(o));if(a.length===0)return{content:[{type:"text",text:"No session is currently in foreground."}]};let m=[];for(let p of a)p.saveFgOutputOffset(o),p.foregroundChannels.delete(o),m.push(`${p.name} [${p.id}]`);return{content:[{type:"text",text:`Moved to background: ${m.join(", ")}`}]}}}}function Vs(e){let t;if(e?.messageChannel&&e?.agentAccountId){let n=e.messageChannel.split("|");n.length>=2&&(t=`${n[0]}|${e.agentAccountId}|${n.slice(1).join("|")}`)}return!t&&e?.workspaceDir&&(t=Y(e.workspaceDir)),!t&&e?.messageChannel&&e.messageChannel.includes("|")&&(t=e.messageChannel),{name:"claude_respond",description:"Send a follow-up message to a running Claude Code session. The session must be running. Sessions are multi-turn by default, so this works with any session unless it was launched with multi_turn_disabled: true.",parameters:f.Object({session:f.String({description:"Session name or ID to respond to"}),message:f.String({description:"The message to send to the session"}),interrupt:f.Optional(f.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:f.Optional(f.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."}))}),async execute(n,r){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let o=d.resolve(r.session);if(!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};if(o.status!=="running")return{content:[{type:"text",text:`Error: Session ${o.name} [${o.id}] is not running (status: ${o.status}). Cannot send a message to a non-running session.`}]};let s=U.maxAutoResponds??10;if(r.userInitiated)o.resetAutoRespond();else if(o.autoRespondCount>=s)return{content:[{type:"text",text:`\u26A0\uFE0F Auto-respond limit reached (${o.autoRespondCount}/${s}). Ask the user to provide the answer for session ${o.name}. Then call claude_respond with their answer and set userInitiated: true to reset the counter.`}]};try{if(r.interrupt&&await o.interrupt(),await o.sendMessage(r.message),r.userInitiated||o.incrementAutoRespond(),d){let m=[`\u21A9\uFE0F [${o.name}] Responded:`,r.message.length>200?r.message.slice(0,200)+"...":r.message].join(`
24
+ ${U}${E}`}]}}}}function Bs(e){let t;if(e?.messageChannel&&e?.agentAccountId){let n=e.messageChannel.split("|");n.length>=2&&(t=`${n[0]}|${e.agentAccountId}|${n.slice(1).join("|")}`)}return!t&&e?.workspaceDir&&(t=Y(e.workspaceDir)),!t&&e?.messageChannel&&e.messageChannel.includes("|")&&(t=e.messageChannel),console.log(`[claude-bg] Factory context: messageChannel=${e?.messageChannel}, agentAccountId=${e?.agentAccountId}, workspaceDir=${e?.workspaceDir}, fallbackChannel=${t}`),{name:"claude_bg",description:"Send a Claude Code session back to background (stop streaming). If no session specified, detaches whichever session is currently in foreground.",parameters:f.Object({session:f.Optional(f.String({description:"Session name or ID to send to background. If omitted, detaches the current foreground session."}))}),async execute(n,r){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};if(r.session){let p=d.resolve(r.session);if(!p)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let g=ne({id:n},t);if(console.log(`[claude-bg] channelId resolved: ${g}, session.workdir=${p.workdir}`),g==="unknown"){let U=Y(p.workdir);U&&(g=U)}return p.saveFgOutputOffset(g),p.foregroundChannels.delete(g),{content:[{type:"text",text:`Session ${p.name} [${p.id}] moved to background.`}]}}let o=ne({id:n},t);if(console.log(`[claude-bg] resolvedId (no session): ${o}`),o==="unknown"){let p=d.list("all");for(let g of p){let U=Y(g.workdir);if(U&&g.foregroundChannels.has(U)){o=U;break}}}let a=d.list("all").filter(p=>p.foregroundChannels.has(o));if(a.length===0)return{content:[{type:"text",text:"No session is currently in foreground."}]};let m=[];for(let p of a)p.saveFgOutputOffset(o),p.foregroundChannels.delete(o),m.push(`${p.name} [${p.id}]`);return{content:[{type:"text",text:`Moved to background: ${m.join(", ")}`}]}}}}function Vs(e){let t;if(e?.messageChannel&&e?.agentAccountId){let n=e.messageChannel.split("|");n.length>=2&&(t=`${n[0]}|${e.agentAccountId}|${n.slice(1).join("|")}`)}return!t&&e?.workspaceDir&&(t=Y(e.workspaceDir)),!t&&e?.messageChannel&&e.messageChannel.includes("|")&&(t=e.messageChannel),{name:"claude_respond",description:"Send a follow-up message to a running Claude Code session. The session must be running. Sessions are multi-turn by default, so this works with any session unless it was launched with multi_turn_disabled: true.",parameters:f.Object({session:f.String({description:"Session name or ID to respond to"}),message:f.String({description:"The message to send to the session"}),interrupt:f.Optional(f.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:f.Optional(f.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."}))}),async execute(n,r){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let o=d.resolve(r.session);if(!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};if(o.status!=="running")return{content:[{type:"text",text:`Error: Session ${o.name} [${o.id}] is not running (status: ${o.status}). Cannot send a message to a non-running session.`}]};let s=F.maxAutoResponds??10;if(r.userInitiated)o.resetAutoRespond();else if(o.autoRespondCount>=s)return{content:[{type:"text",text:`\u26A0\uFE0F Auto-respond limit reached (${o.autoRespondCount}/${s}). Ask the user to provide the answer for session ${o.name}. Then call claude_respond with their answer and set userInitiated: true to reset the counter.`}]};try{if(r.interrupt&&await o.interrupt(),await o.sendMessage(r.message),r.userInitiated||o.incrementAutoRespond(),d){let m=[`\u21A9\uFE0F [${o.name}] Responded:`,r.message.length>200?r.message.slice(0,200)+"...":r.message].join(`
25
25
  `);d.deliverToTelegram(o,m,"responded")}let a=r.message.length>80?r.message.slice(0,80)+"...":r.message;return{content:[{type:"text",text:[`Message sent to session ${o.name} [${o.id}].`,r.interrupt?" (interrupted current turn first)":"",` Message: "${a}"`,"","Use claude_output to see the response."].filter(Boolean).join(`
26
- `)}]}}catch(a){return{content:[{type:"text",text:`Error sending message: ${a.message}`}]}}}}}function vs(e){return{name:"claude_stats",description:"Show Claude Code Plugin usage metrics: session counts by status, average duration, and notable sessions.",parameters:f.Object({}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=d.getMetrics();return{content:[{type:"text",text:Ft(r)}]}}}}function qs(e){e.registerCommand({name:"claude",description:"Launch a Claude Code session. Usage: /claude [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /claude [--name <name>] <prompt>"};let r,o=n.match(/^--name\s+(\S+)\s+/);o&&(r=o[1],n=n.slice(o[0].length).trim());let s=n;if(!s)return{text:"Usage: /claude [--name <name>] <prompt>"};try{let a=d.spawn({prompt:s,name:r,workdir:U.defaultWorkdir||process.cwd(),model:U.defaultModel,maxBudgetUsd:U.defaultBudgetUsd??5,originChannel:re(t)}),m=s.length>80?s.slice(0,80)+"...":s;return{text:["Session launched.",` Name: ${a.name}`,` ID: ${a.id}`,` Prompt: "${m}"`,` Status: ${a.status}`].join(`
26
+ `)}]}}catch(a){return{content:[{type:"text",text:`Error sending message: ${a.message}`}]}}}}}function vs(e){return{name:"claude_stats",description:"Show Claude Code Plugin usage metrics: session counts by status, average duration, and notable sessions.",parameters:f.Object({}),async execute(t,n){if(!d)return{content:[{type:"text",text:"Error: SessionManager not initialized. The claude-code service must be running."}]};let r=d.getMetrics();return{content:[{type:"text",text:Ft(r)}]}}}}function qs(e){e.registerCommand({name:"claude",description:"Launch a Claude Code session. Usage: /claude [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /claude [--name <name>] <prompt>"};let r,o=n.match(/^--name\s+(\S+)\s+/);o&&(r=o[1],n=n.slice(o[0].length).trim());let s=n;if(!s)return{text:"Usage: /claude [--name <name>] <prompt>"};try{let a=d.spawn({prompt:s,name:r,workdir:F.defaultWorkdir||process.cwd(),model:F.defaultModel,maxBudgetUsd:F.defaultBudgetUsd??5,originChannel:ne(t)}),m=s.length>80?s.slice(0,80)+"...":s;return{text:["Session launched.",` Name: ${a.name}`,` ID: ${a.id}`,` Prompt: "${m}"`,` Status: ${a.status}`].join(`
27
27
  `)}}catch(a){return{text:`Error: ${a.message}`}}}})}function Ws(e){e.registerCommand({name:"claude_sessions",description:"List all Claude Code sessions",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let t=d.list("all");return t.length===0?{text:"No sessions found."}:{text:t.map(Rt).join(`
28
28
 
29
- `)}}})}function zs(e){e.registerCommand({name:"claude_kill",description:"Kill a Claude Code session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=t.args?.trim();if(!n)return{text:"Usage: /claude_kill <name-or-id>"};let r=d.resolve(n);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?{text:`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`}:(d.kill(r.id),{text:`Session ${r.name} [${r.id}] has been terminated.`}):{text:`Error: Session "${n}" not found.`}}})}function Hs(e){e.registerCommand({name:"claude_fg",description:"Bring a Claude Code session to foreground by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=t.args?.trim();if(!n)return{text:"Usage: /claude_fg <name-or-id>"};let r=d.resolve(n);if(!r)return{text:`Error: Session "${n}" not found.`};let o=re(t),s=r.getCatchupOutput(o);r.foregroundChannels.add(o);let a=X(r.duration),m=[`Session ${r.name} [${r.id}] now in foreground.`,`Status: ${r.status.toUpperCase()} | Duration: ${a}`,`${"\u2500".repeat(60)}`].join(`
29
+ `)}}})}function zs(e){e.registerCommand({name:"claude_kill",description:"Kill a Claude Code session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=t.args?.trim();if(!n)return{text:"Usage: /claude_kill <name-or-id>"};let r=d.resolve(n);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?{text:`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`}:(d.kill(r.id),{text:`Session ${r.name} [${r.id}] has been terminated.`}):{text:`Error: Session "${n}" not found.`}}})}function Hs(e){e.registerCommand({name:"claude_fg",description:"Bring a Claude Code session to foreground by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=t.args?.trim();if(!n)return{text:"Usage: /claude_fg <name-or-id>"};let r=d.resolve(n);if(!r)return{text:`Error: Session "${n}" not found.`};let o=ne(t),s=r.getCatchupOutput(o);r.foregroundChannels.add(o);let a=X(r.duration),m=[`Session ${r.name} [${r.id}] now in foreground.`,`Status: ${r.status.toUpperCase()} | Duration: ${a}`,`${"\u2500".repeat(60)}`].join(`
30
30
  `),p="";s.length>0&&(p=[`\u{1F4CB} Catchup (${s.length} missed output${s.length===1?"":"s"}):`,s.join(`
31
31
  `),`${"\u2500".repeat(60)}`].join(`
32
32
  `));let g=s.length>0?p:r.getOutput(30).length>0?r.getOutput(30).join(`
33
- `):"(no output yet)",I=r.status==="running"||r.status==="starting"?`
33
+ `):"(no output yet)",U=r.status==="running"||r.status==="starting"?`
34
34
  ${"\u2500".repeat(60)}
35
35
  Streaming... Use /claude_bg to detach.`:`
36
36
  ${"\u2500".repeat(60)}
37
37
  Session is ${r.status}.`;return r.markFgOutputSeen(o),{text:`${m}
38
- ${g}${I}`}}})}function Js(e){e.registerCommand({name:"claude_bg",description:"Send the current foreground session back to background",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=re(t),r=t.args?.trim();if(r){let m=d.resolve(r);return m?(m.saveFgOutputOffset(n),m.foregroundChannels.delete(n),{text:`Session ${m.name} [${m.id}] moved to background.`}):{text:`Error: Session "${r}" not found.`}}let s=d.list("all").filter(m=>m.foregroundChannels.has(n));if(s.length===0)return{text:"No session is currently in foreground."};let a=[];for(let m of s)m.saveFgOutputOffset(n),m.foregroundChannels.delete(n),a.push(`${m.name} [${m.id}]`);return{text:`Moved to background: ${a.join(", ")}`}}})}function Ys(e){e.registerCommand({name:"claude_resume",description:"Resume a previous Claude Code session. Usage: /claude_resume <id-or-name> [prompt] or /claude_resume --list to see resumable sessions.",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /claude_resume <id-or-name> [prompt]
38
+ ${g}${U}`}}})}function Js(e){e.registerCommand({name:"claude_bg",description:"Send the current foreground session back to background",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=ne(t),r=t.args?.trim();if(r){let m=d.resolve(r);return m?(m.saveFgOutputOffset(n),m.foregroundChannels.delete(n),{text:`Session ${m.name} [${m.id}] moved to background.`}):{text:`Error: Session "${r}" not found.`}}let s=d.list("all").filter(m=>m.foregroundChannels.has(n));if(s.length===0)return{text:"No session is currently in foreground."};let a=[];for(let m of s)m.saveFgOutputOffset(n),m.foregroundChannels.delete(n),a.push(`${m.name} [${m.id}]`);return{text:`Moved to background: ${a.join(", ")}`}}})}function Ys(e){e.registerCommand({name:"claude_resume",description:"Resume a previous Claude Code session. Usage: /claude_resume <id-or-name> [prompt] or /claude_resume --list to see resumable sessions.",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /claude_resume <id-or-name> [prompt]
39
39
  /claude_resume --list \u2014 list resumable sessions
40
- /claude_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let j=d.listPersistedSessions();return j.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
40
+ /claude_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let E=d.listPersistedSessions();return E.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
41
41
 
42
- ${j.map(H=>{let ue=H.prompt.length>60?H.prompt.slice(0,60)+"...":H.prompt,Xe=H.completedAt?`completed ${X(Date.now()-H.completedAt)} ago`:H.status;return[` ${H.name} \u2014 ${Xe}`,` Claude ID: ${H.claudeSessionId}`,` \u{1F4C1} ${H.workdir}`,` \u{1F4DD} "${ue}"`].join(`
42
+ ${E.map(R=>{let re=R.prompt.length>60?R.prompt.slice(0,60)+"...":R.prompt,De=R.completedAt?`completed ${X(Date.now()-R.completedAt)} ago`:R.status;return[` ${R.name} \u2014 ${De}`,` Claude ID: ${R.claudeSessionId}`,` \u{1F4C1} ${R.workdir}`,` \u{1F4DD} "${re}"`].join(`
43
43
  `)}).join(`
44
44
 
45
45
  `)}`}}let r=!1;n.startsWith("--fork ")&&(r=!0,n=n.slice(7).trim());let o=n.indexOf(" "),s,a;o===-1?(s=n,a="Continue where you left off."):(s=n.slice(0,o),a=n.slice(o+1).trim()||"Continue where you left off.");let m=d.resolveClaudeSessionId(s);if(!m)return{text:`Error: Could not find a Claude session ID for "${s}".
46
- Use /claude_resume --list to see available sessions.`};let p=t.config??{},g=d.getPersistedSession(s),I=g?.workdir??process.cwd();try{let j=d.spawn({prompt:a,workdir:I,model:g?.model??p.defaultModel,maxBudgetUsd:p.defaultBudgetUsd??5,resumeSessionId:m,forkSession:r,originChannel:re(t)}),ne=a.length>80?a.slice(0,80)+"...":a;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${j.name}`,` ID: ${j.id}`,` Resume from: ${m}`,` Dir: ${I}`,` Prompt: "${ne}"`].join(`
47
- `)}}catch(j){return{text:`Error: ${j.message}`}}}})}function Xs(e){e.registerCommand({name:"claude_respond",description:"Send a follow-up message to a running Claude Code session. Usage: /claude_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /claude_respond <id-or-name> <message>
48
- /claude_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!0,o=o.slice(12).trim());let s=o.indexOf(" ");if(s===-1)return{text:"Error: Missing message. Usage: /claude_respond <id-or-name> <message>"};let a=o.slice(0,s),m=o.slice(s+1).trim();if(!m)return{text:"Error: Empty message. Usage: /claude_respond <id-or-name> <message>"};let p=d.resolve(a);if(!p)return{text:`Error: Session "${a}" not found.`};if(p.status!=="running")return{text:`Error: Session ${p.name} [${p.id}] is not running (status: ${p.status}).`};try{if(r&&await p.interrupt(),await p.sendMessage(m),p.resetAutoRespond(),d){let I=[`\u21A9\uFE0F [${p.name}] Responded:`,m.length>200?m.slice(0,200)+"...":m].join(`
49
- `);d.deliverToTelegram(p,I,"responded")}let g=m.length>80?m.slice(0,80)+"...":m;return{text:[`Message sent to ${p.name} [${p.id}].`,r?" (interrupted current turn)":"",` "${g}"`].filter(Boolean).join(`
50
- `)}}catch(g){return{text:`Error: ${g.message}`}}}})}function Zs(e){e.registerCommand({name:"claude_stats",description:"Show Claude Code Plugin usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let t=d.getMetrics();return{text:Ft(t)}}})}function Qs(e){e.registerGatewayMethod("claude-code.sessions",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.status??"all",s=d.list(r).map(a=>({id:a.id,name:a.name,status:a.status,prompt:a.prompt,workdir:a.workdir,model:a.model,costUsd:a.costUsd,startedAt:a.startedAt,completedAt:a.completedAt,durationMs:a.duration,claudeSessionId:a.claudeSessionId,foreground:a.foregroundChannels.size>0,multiTurn:a.multiTurn,display:Rt(a)}));t(!0,{sessions:s,count:s.length})}),e.registerGatewayMethod("claude-code.launch",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});if(!n?.prompt)return t(!1,{error:"Missing required parameter: prompt"});try{let r=d.spawn({prompt:n.prompt,name:n.name,workdir:n.workdir||U.defaultWorkdir||process.cwd(),model:n.model||U.defaultModel,maxBudgetUsd:n.maxBudgetUsd??n.max_budget_usd??U.defaultBudgetUsd??5,systemPrompt:n.systemPrompt??n.system_prompt,allowedTools:n.allowedTools??n.allowed_tools,resumeSessionId:n.resumeSessionId??n.resume_session_id,forkSession:n.forkSession??n.fork_session,multiTurn:!(n.multiTurnDisabled??n.multi_turn_disabled),originChannel:n.originChannel??"gateway"});t(!0,{id:r.id,name:r.name,status:r.status,workdir:r.workdir,model:r.model})}catch(r){t(!1,{error:r.message})}}),e.registerGatewayMethod("claude-code.kill",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.session??n?.id;if(!r)return t(!1,{error:"Missing required parameter: session (name or ID)"});let o=d.resolve(r);if(!o)return t(!1,{error:`Session "${r}" not found`});if(o.status==="completed"||o.status==="failed"||o.status==="killed")return t(!0,{id:o.id,name:o.name,status:o.status,message:`Session already ${o.status}`});d.kill(o.id),t(!0,{id:o.id,name:o.name,status:"killed",message:`Session ${o.name} [${o.id}] terminated`})}),e.registerGatewayMethod("claude-code.output",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.session??n?.id;if(!r)return t(!1,{error:"Missing required parameter: session (name or ID)"});let o=d.resolve(r);if(!o)return t(!1,{error:`Session "${r}" not found`});let s=n?.full?o.getOutput():o.getOutput(n?.lines??50);t(!0,{id:o.id,name:o.name,status:o.status,costUsd:o.costUsd,durationMs:o.duration,duration:X(o.duration),lines:s,lineCount:s.length,result:o.result??null})}),e.registerGatewayMethod("claude-code.stats",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=d.getMetrics(),o={};for(let[a,m]of r.costPerDay)o[a]=m;let s=d.list("running").length;t(!0,{totalCostUsd:r.totalCostUsd,costPerDay:o,sessionsByStatus:{...r.sessionsByStatus,running:s},totalLaunched:r.totalLaunched,averageDurationMs:r.sessionsWithDuration>0?r.totalDurationMs/r.sessionsWithDuration:0,mostExpensive:r.mostExpensive,display:Ft(r)})})}var Ht=require("child_process");var ri=require("@anthropic-ai/claude-agent-sdk");var lr=fi(require("crypto"),1);var ei="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ym=128,ut,At,Xm=e=>{!ut||ut.length<e?(ut=Buffer.allocUnsafe(e*Ym),lr.default.randomFillSync(ut),At=0):At+e>ut.length&&(lr.default.randomFillSync(ut),At=0),At+=e};var ti=(e=21)=>{Xm(e|=0);let t="";for(let n=At-e;n<At;n++)t+=ei[ut[n]&63];return t};var ni=200,dr=class{queue=[];resolve=null;done=!1;push(t,n){let r={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n};this.queue.push(r),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(t=>{this.resolve=t})}}},Tn=class e{id;name;claudeSessionId;prompt;workdir;model;maxBudgetUsd;systemPrompt;allowedTools;permissionMode;resumeSessionId;forkSession;multiTurn;messageStream;queryHandle;idleTimer;safetyNetTimer;static SAFETY_NET_IDLE_MS=15e3;status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;foregroundChannels=new Set;fgOutputOffsets=new Map;originChannel;originAgentId;budgetExhausted=!1;waitingForInputFired=!1;autoRespondCount=0;onOutput;onToolUse;onBudgetExhausted;onComplete;onWaitingForInput;constructor(t,n){this.id=ti(8),this.name=n,this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model,this.maxBudgetUsd=t.maxBudgetUsd,this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??U.permissionMode??"bypassPermissions",this.originChannel=t.originChannel,this.originAgentId=t.originAgentId,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.startedAt=Date.now(),this.abortController=new AbortController}async start(){let t;try{let n={cwd:this.workdir,model:this.model,maxBudgetUsd:this.maxBudgetUsd,permissionMode:this.permissionMode,allowDangerouslySkipPermissions:this.permissionMode==="bypassPermissions",allowedTools:this.allowedTools,includePartialMessages:!0,abortController:this.abortController,...this.systemPrompt?{systemPrompt:this.systemPrompt}:{}};this.resumeSessionId&&(n.resume=this.resumeSessionId,this.forkSession&&(n.forkSession=!0));let r;this.multiTurn?(this.messageStream=new dr,this.messageStream.push(this.prompt,""),r=this.messageStream):r=this.prompt,t=(0,ri.query)({prompt:r,options:n}),this.queryHandle=t}catch(n){this.status="failed",this.error=n?.message??String(n),this.completedAt=Date.now();return}this.consumeMessages(t).catch(n=>{(this.status==="starting"||this.status==="running")&&(this.status="failed",this.error=n?.message??String(n),this.completedAt=Date.now())})}resetSafetyNetTimer(){this.clearSafetyNetTimer(),this.safetyNetTimer=setTimeout(()=>{this.safetyNetTimer=void 0,this.status==="running"&&this.onWaitingForInput&&!this.waitingForInputFired&&(console.log(`[Session] ${this.id} no messages for ${e.SAFETY_NET_IDLE_MS/1e3}s \u2014 firing onWaitingForInput (safety-net)`),this.waitingForInputFired=!0,this.onWaitingForInput(this))},e.SAFETY_NET_IDLE_MS)}clearSafetyNetTimer(){this.safetyNetTimer&&(clearTimeout(this.safetyNetTimer),this.safetyNetTimer=void 0)}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),!this.multiTurn)return;let t=(U.idleTimeoutMinutes??30)*60*1e3;this.idleTimer=setTimeout(()=>{this.status==="running"&&(console.log(`[Session] ${this.id} idle timeout reached (${U.idleTimeoutMinutes??30}min), auto-killing`),this.kill())},t)}async sendMessage(t){if(this.status!=="running")throw new Error(`Session is not running (status: ${this.status})`);if(this.resetIdleTimer(),this.waitingForInputFired=!1,this.multiTurn&&this.messageStream)this.messageStream.push(t,this.claudeSessionId??"");else if(this.queryHandle&&typeof this.queryHandle.streamInput=="function"){let n={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:this.claudeSessionId??""};async function*r(){yield n}await this.queryHandle.streamInput(r())}else throw new Error("Session does not support multi-turn messaging. Launch with multiTurn: true or use the SDK streamInput.")}async interrupt(){this.queryHandle&&typeof this.queryHandle.interrupt=="function"&&await this.queryHandle.interrupt()}async consumeMessages(t){for await(let n of t)if(this.resetSafetyNetTimer(),n.type==="system"&&n.subtype==="init")this.claudeSessionId=n.session_id,this.status="running",this.resetIdleTimer();else if(n.type==="assistant"){this.waitingForInputFired=!1;let r=n.message?.content??[];console.log(`[Session] ${this.id} assistant message received, blocks=${r.length}, fgChannels=${JSON.stringify([...this.foregroundChannels])}`);for(let o of r)if(o.type==="text"){let s=o.text;this.outputBuffer.push(s),this.outputBuffer.length>ni&&this.outputBuffer.splice(0,this.outputBuffer.length-ni),this.onOutput?(console.log(`[Session] ${this.id} calling onOutput, textLen=${s.length}`),this.onOutput(s)):console.log(`[Session] ${this.id} onOutput callback NOT set`)}else o.type==="tool_use"&&(this.onToolUse?(console.log(`[Session] ${this.id} calling onToolUse, tool=${o.name}`),this.onToolUse(o.name,o.input)):console.log(`[Session] ${this.id} onToolUse callback NOT set`))}else n.type==="result"&&(this.result={subtype:n.subtype,duration_ms:n.duration_ms,total_cost_usd:n.total_cost_usd,num_turns:n.num_turns,result:n.result,is_error:n.is_error,session_id:n.session_id},this.costUsd=n.total_cost_usd,this.multiTurn&&this.messageStream&&n.subtype==="success"?(console.log(`[Session] ${this.id} multi-turn end-of-turn (turn ${n.num_turns}), staying open`),this.clearSafetyNetTimer(),this.resetIdleTimer(),this.onWaitingForInput&&!this.waitingForInputFired&&(console.log(`[Session] ${this.id} calling onWaitingForInput`),this.waitingForInputFired=!0,this.onWaitingForInput(this))):(this.clearSafetyNetTimer(),this.idleTimer&&clearTimeout(this.idleTimer),this.status=n.subtype==="success"?"completed":"failed",this.completedAt=Date.now(),this.messageStream&&this.messageStream.end(),n.subtype==="error_max_budget_usd"&&(this.budgetExhausted=!0,this.onBudgetExhausted&&this.onBudgetExhausted(this)),this.onComplete?(console.log(`[Session] ${this.id} calling onComplete, status=${this.status}`),this.onComplete(this)):console.log(`[Session] ${this.id} onComplete callback NOT set`)))}kill(){this.status!=="starting"&&this.status!=="running"||(this.idleTimer&&clearTimeout(this.idleTimer),this.clearSafetyNetTimer(),this.status="killed",this.completedAt=Date.now(),this.messageStream&&this.messageStream.end(),this.abortController.abort())}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}getCatchupOutput(t){let n=this.fgOutputOffsets.get(t)??0,r=this.outputBuffer.length;return n>=r?[]:this.outputBuffer.slice(n)}markFgOutputSeen(t){this.fgOutputOffsets.set(t,this.outputBuffer.length)}saveFgOutputOffset(t){this.fgOutputOffsets.set(t,this.outputBuffer.length)}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}get duration(){return(this.completedAt??Date.now())-this.startedAt}};var Zm=3600*1e3,Qm=5e3,oi=3e4,si=5e3,Cn=class{sessions=new Map;maxSessions;maxPersistedSessions;notificationRouter=null;lastWaitingEventTimestamps=new Map;pendingRetryTimers=new Set;persistedSessions=new Map;_metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};constructor(t=5,n=50){this.maxSessions=t,this.maxPersistedSessions=n}uniqueName(t){let n=new Set([...this.sessions.values()].map(o=>o.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}-${r}`);)r++;return`${t}-${r}`}spawn(t){if([...this.sessions.values()].filter(m=>m.status==="starting"||m.status==="running").length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Kill a session first.`);let r=t.name||Ks(t.prompt),o=this.uniqueName(r),s=new Tn(t,o);if(this.sessions.set(s.id,s),this._metrics.totalLaunched++,this.notificationRouter){let m=this.notificationRouter;console.log(`[SessionManager] Wiring notification callbacks for session=${s.id} (${s.name}), originChannel=${s.originChannel}`),s.onOutput=p=>{console.log(`[SessionManager] session.onOutput fired for session=${s.id}, textLen=${p.length}, fgChannels=${JSON.stringify([...s.foregroundChannels])}`),m.onAssistantText(s,p);for(let g of s.foregroundChannels)s.markFgOutputSeen(g)},s.onToolUse=(p,g)=>{console.log(`[SessionManager] session.onToolUse fired for session=${s.id}, tool=${p}`),m.onToolUse(s,p,g)},s.onBudgetExhausted=()=>{console.log(`[SessionManager] session.onBudgetExhausted fired for session=${s.id}`),m.onBudgetExhausted(s)},s.onWaitingForInput=()=>{console.log(`[SessionManager] session.onWaitingForInput fired for session=${s.id}`),m.onWaitingForInput(s),this.triggerWaitingForInputEvent(s)},s.onComplete=()=>{console.log(`[SessionManager] session.onComplete fired for session=${s.id}, budgetExhausted=${s.budgetExhausted}`),this.persistSession(s),s.budgetExhausted||m.onSessionComplete(s),this.triggerAgentEvent(s)}}else console.warn(`[SessionManager] No NotificationRouter available when spawning session=${s.id} (${s.name})`);s.start();let a=s.prompt.length>80?s.prompt.slice(0,80)+"...":s.prompt;return this.deliverToTelegram(s,`\u21A9\uFE0F [${s.name}] Launched:
51
- ${a}`,"launched"),s}persistSession(t){if(this.persistedSessions.has(t.id)||this.recordSessionMetrics(t),!t.claudeSessionId)return;let r={claudeSessionId:t.claudeSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,completedAt:t.completedAt,status:t.status,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel};this.persistedSessions.set(t.id,r),this.persistedSessions.set(t.name,r),this.persistedSessions.set(t.claudeSessionId,r),console.log(`[SessionManager] Persisted session ${t.name} [${t.id}] -> claudeSessionId=${t.claudeSessionId}`)}recordSessionMetrics(t){let n=t.costUsd??0,r=t.status;this._metrics.totalCostUsd+=n;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this._metrics.costPerDay.set(o,(this._metrics.costPerDay.get(o)??0)+n),(r==="completed"||r==="failed"||r==="killed")&&this._metrics.sessionsByStatus[r]++,t.completedAt){let s=t.completedAt-t.startedAt;this._metrics.totalDurationMs+=s,this._metrics.sessionsWithDuration++}(!this._metrics.mostExpensive||n>this._metrics.mostExpensive.costUsd)&&(this._metrics.mostExpensive={id:t.id,name:t.name,costUsd:n,prompt:t.prompt.length>80?t.prompt.slice(0,80)+"...":t.prompt})}getMetrics(){return this._metrics}buildDeliverArgs(t){if(!t||t==="unknown"||t==="gateway")return[];let n=t.split("|");return n.length<2?[]:n.length>=3?["--deliver","--reply-channel",n[0],"--reply-account",n[1],"--reply-to",n.slice(2).join("|")]:["--deliver","--reply-channel",n[0],"--reply-to",n[1]]}wakeAgent(t,n,r,o){this.deliverToTelegram(t,r,o);let s=t.originAgentId?.trim();if(!s){console.warn(`[SessionManager] No originAgentId for ${o} session=${t.id}, falling back to system event`),this.fireSystemEventWithRetry(n,o,t.id);return}let a=this.buildDeliverArgs(t.originChannel),m=(0,Ht.spawn)("openclaw",["agent","--agent",s,"--message",n,...a],{detached:!0,stdio:"ignore"});m.unref(),console.log(`[SessionManager] Spawned detached wake for agent=${s}, ${o} session=${t.id} (pid=${m.pid}, deliver=${a.length>0})`)}deliverToTelegram(t,n,r){if(!this.notificationRouter){console.warn(`[SessionManager] Cannot deliver ${r} to Telegram for session=${t.id} (no NotificationRouter)`);return}let o=t.originChannel||"unknown";console.log(`[SessionManager] Delivering ${r} to Telegram for session=${t.id} via channel=${o}`),this.notificationRouter.emitToChannel(o,n)}fireSystemEventWithRetry(t,n,r){let o=["system","event","--text",t,"--mode","now"];(0,Ht.execFile)("openclaw",o,{timeout:oi},(s,a,m)=>{if(s){console.error(`[SessionManager] System event failed for ${n} session=${r}: ${s.message}`),m&&console.error(`[SessionManager] stderr: ${m}`),console.warn(`[SessionManager] Scheduling retry in ${si}ms for ${n} session=${r}`);let p=setTimeout(()=>{this.pendingRetryTimers.delete(p),(0,Ht.execFile)("openclaw",o,{timeout:oi},(g,I,j)=>{g?(console.error(`[SessionManager] System event retry also failed for ${n} session=${r}: ${g.message}`),j&&console.error(`[SessionManager] retry stderr: ${j}`)):console.log(`[SessionManager] System event retry succeeded for ${n} session=${r}`)})},si);this.pendingRetryTimers.add(p)}else console.log(`[SessionManager] System event sent for ${n} session=${r}`)})}triggerAgentEvent(t){let n=t.status,o=t.getOutput(5).join(`
46
+ Use /claude_resume --list to see available sessions.`};let p=t.config??{},g=d.getPersistedSession(s),U=g?.workdir??process.cwd();try{let E=d.spawn({prompt:a,workdir:U,model:g?.model??p.defaultModel,maxBudgetUsd:p.defaultBudgetUsd??5,resumeSessionId:m,forkSession:r,originChannel:ne(t)}),P=a.length>80?a.slice(0,80)+"...":a;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${E.name}`,` ID: ${E.id}`,` Resume from: ${m}`,` Dir: ${U}`,` Prompt: "${P}"`].join(`
47
+ `)}}catch(E){return{text:`Error: ${E.message}`}}}})}function Xs(e){e.registerCommand({name:"claude_respond",description:"Send a follow-up message to a running Claude Code session. Usage: /claude_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /claude_respond <id-or-name> <message>
48
+ /claude_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!0,o=o.slice(12).trim());let s=o.indexOf(" ");if(s===-1)return{text:"Error: Missing message. Usage: /claude_respond <id-or-name> <message>"};let a=o.slice(0,s),m=o.slice(s+1).trim();if(!m)return{text:"Error: Empty message. Usage: /claude_respond <id-or-name> <message>"};let p=d.resolve(a);if(!p)return{text:`Error: Session "${a}" not found.`};if(p.status!=="running")return{text:`Error: Session ${p.name} [${p.id}] is not running (status: ${p.status}).`};try{if(r&&await p.interrupt(),await p.sendMessage(m),p.resetAutoRespond(),d){let U=[`\u21A9\uFE0F [${p.name}] Responded:`,m.length>200?m.slice(0,200)+"...":m].join(`
49
+ `);d.deliverToTelegram(p,U,"responded")}let g=m.length>80?m.slice(0,80)+"...":m;return{text:[`Message sent to ${p.name} [${p.id}].`,r?" (interrupted current turn)":"",` "${g}"`].filter(Boolean).join(`
50
+ `)}}catch(g){return{text:`Error: ${g.message}`}}}})}function Zs(e){e.registerCommand({name:"claude_stats",description:"Show Claude Code Plugin usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!d)return{text:"Error: SessionManager not initialized. The claude-code service must be running."};let t=d.getMetrics();return{text:Ft(t)}}})}function Qs(e){e.registerGatewayMethod("claude-code.sessions",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.status??"all",s=d.list(r).map(a=>({id:a.id,name:a.name,status:a.status,prompt:a.prompt,workdir:a.workdir,model:a.model,costUsd:a.costUsd,startedAt:a.startedAt,completedAt:a.completedAt,durationMs:a.duration,claudeSessionId:a.claudeSessionId,foreground:a.foregroundChannels.size>0,multiTurn:a.multiTurn,display:Rt(a)}));t(!0,{sessions:s,count:s.length})}),e.registerGatewayMethod("claude-code.launch",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});if(!n?.prompt)return t(!1,{error:"Missing required parameter: prompt"});try{let r=d.spawn({prompt:n.prompt,name:n.name,workdir:n.workdir||F.defaultWorkdir||process.cwd(),model:n.model||F.defaultModel,maxBudgetUsd:n.maxBudgetUsd??n.max_budget_usd??F.defaultBudgetUsd??5,systemPrompt:n.systemPrompt??n.system_prompt,allowedTools:n.allowedTools??n.allowed_tools,resumeSessionId:n.resumeSessionId??n.resume_session_id,forkSession:n.forkSession??n.fork_session,multiTurn:!(n.multiTurnDisabled??n.multi_turn_disabled),originChannel:n.originChannel??"gateway"});t(!0,{id:r.id,name:r.name,status:r.status,workdir:r.workdir,model:r.model})}catch(r){t(!1,{error:r.message})}}),e.registerGatewayMethod("claude-code.kill",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.session??n?.id;if(!r)return t(!1,{error:"Missing required parameter: session (name or ID)"});let o=d.resolve(r);if(!o)return t(!1,{error:`Session "${r}" not found`});if(o.status==="completed"||o.status==="failed"||o.status==="killed")return t(!0,{id:o.id,name:o.name,status:o.status,message:`Session already ${o.status}`});d.kill(o.id),t(!0,{id:o.id,name:o.name,status:"killed",message:`Session ${o.name} [${o.id}] terminated`})}),e.registerGatewayMethod("claude-code.output",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=n?.session??n?.id;if(!r)return t(!1,{error:"Missing required parameter: session (name or ID)"});let o=d.resolve(r);if(!o)return t(!1,{error:`Session "${r}" not found`});let s=n?.full?o.getOutput():o.getOutput(n?.lines??50);t(!0,{id:o.id,name:o.name,status:o.status,costUsd:o.costUsd,durationMs:o.duration,duration:X(o.duration),lines:s,lineCount:s.length,result:o.result??null})}),e.registerGatewayMethod("claude-code.stats",({respond:t,params:n})=>{if(!d)return t(!1,{error:"SessionManager not initialized"});let r=d.getMetrics(),o={};for(let[a,m]of r.costPerDay)o[a]=m;let s=d.list("running").length;t(!0,{totalCostUsd:r.totalCostUsd,costPerDay:o,sessionsByStatus:{...r.sessionsByStatus,running:s},totalLaunched:r.totalLaunched,averageDurationMs:r.sessionsWithDuration>0?r.totalDurationMs/r.sessionsWithDuration:0,mostExpensive:r.mostExpensive,display:Ft(r)})})}var Ht=require("child_process");var ri=require("@anthropic-ai/claude-agent-sdk");var lr=fi(require("crypto"),1);var ei="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ym=128,ut,At,Xm=e=>{!ut||ut.length<e?(ut=Buffer.allocUnsafe(e*Ym),lr.default.randomFillSync(ut),At=0):At+e>ut.length&&(lr.default.randomFillSync(ut),At=0),At+=e};var ti=(e=21)=>{Xm(e|=0);let t="";for(let n=At-e;n<At;n++)t+=ei[ut[n]&63];return t};var ni=200,dr=class{queue=[];resolve=null;done=!1;push(t,n){let r={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n};this.queue.push(r),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(t=>{this.resolve=t})}}},Tn=class e{id;name;claudeSessionId;prompt;workdir;model;maxBudgetUsd;systemPrompt;allowedTools;permissionMode;resumeSessionId;forkSession;multiTurn;messageStream;queryHandle;idleTimer;safetyNetTimer;static SAFETY_NET_IDLE_MS=15e3;status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;foregroundChannels=new Set;fgOutputOffsets=new Map;originChannel;originAgentId;budgetExhausted=!1;waitingForInputFired=!1;autoRespondCount=0;onOutput;onToolUse;onBudgetExhausted;onComplete;onWaitingForInput;constructor(t,n){this.id=ti(8),this.name=n,this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model,this.maxBudgetUsd=t.maxBudgetUsd,this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??F.permissionMode??"bypassPermissions",this.originChannel=t.originChannel,this.originAgentId=t.originAgentId,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.startedAt=Date.now(),this.abortController=new AbortController}async start(){let t;try{let n={cwd:this.workdir,model:this.model,maxBudgetUsd:this.maxBudgetUsd,permissionMode:this.permissionMode,allowDangerouslySkipPermissions:this.permissionMode==="bypassPermissions",allowedTools:this.allowedTools,includePartialMessages:!0,abortController:this.abortController,...this.systemPrompt?{systemPrompt:this.systemPrompt}:{}};this.resumeSessionId&&(n.resume=this.resumeSessionId,this.forkSession&&(n.forkSession=!0));let r;this.multiTurn?(this.messageStream=new dr,this.messageStream.push(this.prompt,""),r=this.messageStream):r=this.prompt,t=(0,ri.query)({prompt:r,options:n}),this.queryHandle=t}catch(n){this.status="failed",this.error=n?.message??String(n),this.completedAt=Date.now();return}this.consumeMessages(t).catch(n=>{(this.status==="starting"||this.status==="running")&&(this.status="failed",this.error=n?.message??String(n),this.completedAt=Date.now())})}resetSafetyNetTimer(){this.clearSafetyNetTimer(),this.safetyNetTimer=setTimeout(()=>{this.safetyNetTimer=void 0,this.status==="running"&&this.onWaitingForInput&&!this.waitingForInputFired&&(console.log(`[Session] ${this.id} no messages for ${e.SAFETY_NET_IDLE_MS/1e3}s \u2014 firing onWaitingForInput (safety-net)`),this.waitingForInputFired=!0,this.onWaitingForInput(this))},e.SAFETY_NET_IDLE_MS)}clearSafetyNetTimer(){this.safetyNetTimer&&(clearTimeout(this.safetyNetTimer),this.safetyNetTimer=void 0)}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),!this.multiTurn)return;let t=(F.idleTimeoutMinutes??30)*60*1e3;this.idleTimer=setTimeout(()=>{this.status==="running"&&(console.log(`[Session] ${this.id} idle timeout reached (${F.idleTimeoutMinutes??30}min), auto-killing`),this.kill())},t)}async sendMessage(t){if(this.status!=="running")throw new Error(`Session is not running (status: ${this.status})`);if(this.resetIdleTimer(),this.waitingForInputFired=!1,this.multiTurn&&this.messageStream)this.messageStream.push(t,this.claudeSessionId??"");else if(this.queryHandle&&typeof this.queryHandle.streamInput=="function"){let n={type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:this.claudeSessionId??""};async function*r(){yield n}await this.queryHandle.streamInput(r())}else throw new Error("Session does not support multi-turn messaging. Launch with multiTurn: true or use the SDK streamInput.")}async interrupt(){this.queryHandle&&typeof this.queryHandle.interrupt=="function"&&await this.queryHandle.interrupt()}async consumeMessages(t){for await(let n of t)if(this.resetSafetyNetTimer(),n.type==="system"&&n.subtype==="init")this.claudeSessionId=n.session_id,this.status="running",this.resetIdleTimer();else if(n.type==="assistant"){this.waitingForInputFired=!1;let r=n.message?.content??[];console.log(`[Session] ${this.id} assistant message received, blocks=${r.length}, fgChannels=${JSON.stringify([...this.foregroundChannels])}`);for(let o of r)if(o.type==="text"){let s=o.text;this.outputBuffer.push(s),this.outputBuffer.length>ni&&this.outputBuffer.splice(0,this.outputBuffer.length-ni),this.onOutput?(console.log(`[Session] ${this.id} calling onOutput, textLen=${s.length}`),this.onOutput(s)):console.log(`[Session] ${this.id} onOutput callback NOT set`)}else o.type==="tool_use"&&(this.onToolUse?(console.log(`[Session] ${this.id} calling onToolUse, tool=${o.name}`),this.onToolUse(o.name,o.input)):console.log(`[Session] ${this.id} onToolUse callback NOT set`))}else n.type==="result"&&(this.result={subtype:n.subtype,duration_ms:n.duration_ms,total_cost_usd:n.total_cost_usd,num_turns:n.num_turns,result:n.result,is_error:n.is_error,session_id:n.session_id},this.costUsd=n.total_cost_usd,this.multiTurn&&this.messageStream&&n.subtype==="success"?(console.log(`[Session] ${this.id} multi-turn end-of-turn (turn ${n.num_turns}), staying open`),this.clearSafetyNetTimer(),this.resetIdleTimer(),this.onWaitingForInput&&!this.waitingForInputFired&&(console.log(`[Session] ${this.id} calling onWaitingForInput`),this.waitingForInputFired=!0,this.onWaitingForInput(this))):(this.clearSafetyNetTimer(),this.idleTimer&&clearTimeout(this.idleTimer),this.status=n.subtype==="success"?"completed":"failed",this.completedAt=Date.now(),this.messageStream&&this.messageStream.end(),n.subtype==="error_max_budget_usd"&&(this.budgetExhausted=!0,this.onBudgetExhausted&&this.onBudgetExhausted(this)),this.onComplete?(console.log(`[Session] ${this.id} calling onComplete, status=${this.status}`),this.onComplete(this)):console.log(`[Session] ${this.id} onComplete callback NOT set`)))}kill(){this.status!=="starting"&&this.status!=="running"||(this.idleTimer&&clearTimeout(this.idleTimer),this.clearSafetyNetTimer(),this.status="killed",this.completedAt=Date.now(),this.messageStream&&this.messageStream.end(),this.abortController.abort())}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}getCatchupOutput(t){let n=this.fgOutputOffsets.get(t)??0,r=this.outputBuffer.length;return n>=r?[]:this.outputBuffer.slice(n)}markFgOutputSeen(t){this.fgOutputOffsets.set(t,this.outputBuffer.length)}saveFgOutputOffset(t){this.fgOutputOffsets.set(t,this.outputBuffer.length)}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}get duration(){return(this.completedAt??Date.now())-this.startedAt}};var Zm=3600*1e3,Qm=5e3,oi=3e4,si=5e3,Cn=class{sessions=new Map;maxSessions;maxPersistedSessions;notificationRouter=null;lastWaitingEventTimestamps=new Map;pendingRetryTimers=new Set;persistedSessions=new Map;_metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};constructor(t=5,n=50){this.maxSessions=t,this.maxPersistedSessions=n}uniqueName(t){let n=new Set([...this.sessions.values()].map(o=>o.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}-${r}`);)r++;return`${t}-${r}`}spawn(t){if([...this.sessions.values()].filter(m=>m.status==="starting"||m.status==="running").length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Kill a session first.`);let r=t.name||Ks(t.prompt),o=this.uniqueName(r),s=new Tn(t,o);if(this.sessions.set(s.id,s),this._metrics.totalLaunched++,this.notificationRouter){let m=this.notificationRouter;console.log(`[SessionManager] Wiring notification callbacks for session=${s.id} (${s.name}), originChannel=${s.originChannel}`),s.onOutput=p=>{console.log(`[SessionManager] session.onOutput fired for session=${s.id}, textLen=${p.length}, fgChannels=${JSON.stringify([...s.foregroundChannels])}`),m.onAssistantText(s,p);for(let g of s.foregroundChannels)s.markFgOutputSeen(g)},s.onToolUse=(p,g)=>{console.log(`[SessionManager] session.onToolUse fired for session=${s.id}, tool=${p}`),m.onToolUse(s,p,g)},s.onBudgetExhausted=()=>{console.log(`[SessionManager] session.onBudgetExhausted fired for session=${s.id}`),m.onBudgetExhausted(s)},s.onWaitingForInput=()=>{console.log(`[SessionManager] session.onWaitingForInput fired for session=${s.id}`),m.onWaitingForInput(s),this.triggerWaitingForInputEvent(s)},s.onComplete=()=>{console.log(`[SessionManager] session.onComplete fired for session=${s.id}, budgetExhausted=${s.budgetExhausted}`),this.persistSession(s),s.budgetExhausted||m.onSessionComplete(s),this.triggerAgentEvent(s)}}else console.warn(`[SessionManager] No NotificationRouter available when spawning session=${s.id} (${s.name})`);s.start();let a=s.prompt.length>80?s.prompt.slice(0,80)+"...":s.prompt;return this.deliverToTelegram(s,`\u21A9\uFE0F [${s.name}] Launched:
51
+ ${a}`,"launched"),s}persistSession(t){if(this.persistedSessions.has(t.id)||this.recordSessionMetrics(t),!t.claudeSessionId)return;let r={claudeSessionId:t.claudeSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,completedAt:t.completedAt,status:t.status,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel};this.persistedSessions.set(t.id,r),this.persistedSessions.set(t.name,r),this.persistedSessions.set(t.claudeSessionId,r),console.log(`[SessionManager] Persisted session ${t.name} [${t.id}] -> claudeSessionId=${t.claudeSessionId}`)}recordSessionMetrics(t){let n=t.costUsd??0,r=t.status;this._metrics.totalCostUsd+=n;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this._metrics.costPerDay.set(o,(this._metrics.costPerDay.get(o)??0)+n),(r==="completed"||r==="failed"||r==="killed")&&this._metrics.sessionsByStatus[r]++,t.completedAt){let s=t.completedAt-t.startedAt;this._metrics.totalDurationMs+=s,this._metrics.sessionsWithDuration++}(!this._metrics.mostExpensive||n>this._metrics.mostExpensive.costUsd)&&(this._metrics.mostExpensive={id:t.id,name:t.name,costUsd:n,prompt:t.prompt.length>80?t.prompt.slice(0,80)+"...":t.prompt})}getMetrics(){return this._metrics}buildDeliverArgs(t){if(!t||t==="unknown"||t==="gateway")return[];let n=t.split("|");return n.length<2?[]:n.length>=3?["--deliver","--reply-channel",n[0],"--reply-account",n[1],"--reply-to",n.slice(2).join("|")]:["--deliver","--reply-channel",n[0],"--reply-to",n[1]]}wakeAgent(t,n,r,o){this.deliverToTelegram(t,r,o);let s=t.originAgentId?.trim();if(!s){console.warn(`[SessionManager] No originAgentId for ${o} session=${t.id}, falling back to system event`),this.fireSystemEventWithRetry(n,o,t.id);return}let a=this.buildDeliverArgs(t.originChannel),m=(0,Ht.spawn)("openclaw",["agent","--agent",s,"--message",n,...a],{detached:!0,stdio:"ignore"});m.unref(),console.log(`[SessionManager] Spawned detached wake for agent=${s}, ${o} session=${t.id} (pid=${m.pid}, deliver=${a.length>0})`)}deliverToTelegram(t,n,r){if(!this.notificationRouter){console.warn(`[SessionManager] Cannot deliver ${r} to Telegram for session=${t.id} (no NotificationRouter)`);return}let o=t.originChannel||"unknown";console.log(`[SessionManager] Delivering ${r} to Telegram for session=${t.id} via channel=${o}`),this.notificationRouter.emitToChannel(o,n)}fireSystemEventWithRetry(t,n,r){let o=["system","event","--text",t,"--mode","now"];(0,Ht.execFile)("openclaw",o,{timeout:oi},(s,a,m)=>{if(s){console.error(`[SessionManager] System event failed for ${n} session=${r}: ${s.message}`),m&&console.error(`[SessionManager] stderr: ${m}`),console.warn(`[SessionManager] Scheduling retry in ${si}ms for ${n} session=${r}`);let p=setTimeout(()=>{this.pendingRetryTimers.delete(p),(0,Ht.execFile)("openclaw",o,{timeout:oi},(g,U,E)=>{g?(console.error(`[SessionManager] System event retry also failed for ${n} session=${r}: ${g.message}`),E&&console.error(`[SessionManager] retry stderr: ${E}`)):console.log(`[SessionManager] System event retry succeeded for ${n} session=${r}`)})},si);this.pendingRetryTimers.add(p)}else console.log(`[SessionManager] System event sent for ${n} session=${r}`)})}triggerAgentEvent(t){let n=t.status,o=t.getOutput(5).join(`
52
52
  `);if(o.length>500&&(o=o.slice(-500)),n==="completed"){let s=["Claude Code session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${n}`,"","Output preview:",o,"",`Use claude_output(session='${t.id}', full=true) to get the full result and transmit the analysis to the user.`].join(`
53
53
  `),a=o.replace(/[*`_~]/g,""),m=[`\u2705 [${t.name}] Completed`,` \u{1F4C1} ${t.workdir}`,` \u{1F4B0} $${(t.costUsd??0).toFixed(4)}`];a.trim()&&m.push("",a);let p=m.join(`
54
54
  `);console.log(`[SessionManager] Triggering agent wake for completed session=${t.id}`),this.wakeAgent(t,s,p,"completed")}else{let s=n==="killed"?"\u26D4":"\u274C",a=t.prompt.length>60?t.prompt.slice(0,60)+"...":t.prompt,m=[`${s} [${t.name}] ${n==="killed"?"Killed":"Failed"}`,` \u{1F4C1} ${t.workdir}`,` \u{1F4DD} "${a}"`,...t.error?[` \u26A0\uFE0F ${t.error}`]:[]].join(`
@@ -61,4 +61,4 @@ ${r.length>200?r.slice(-200):r}`,s=Date.now(),a=this.lastWaitingEventTimestamps.
61
61
  `);r.originChannel&&this.sendMessage(r.originChannel,s)}}debounceKey(t,n){return`${t}|${n}`}appendDebounced(t,n,r){let o=this.debounceKey(t,n),s=this.debounceMap.get(o);if(s)clearTimeout(s.timer),s.buffer+=r,s.timer=setTimeout(()=>{this.flushDebounced(t,n)},ii);else{let a=setTimeout(()=>{this.flushDebounced(t,n)},ii);this.debounceMap.set(o,{buffer:r,timer:a})}}flushDebounced(t,n){let r=this.debounceKey(t,n),o=this.debounceMap.get(r);o&&(clearTimeout(o.timer),o.buffer&&(console.log(`[NotificationRouter] flushDebounced -> session=${t}, channel=${n}, bufferLen=${o.buffer.length}`),this.sendMessage(n,o.buffer)),this.debounceMap.delete(r))}cleanupSession(t){for(let n of this.debounceMap.keys())if(n.startsWith(`${t}|`)){let r=this.debounceMap.get(n);clearTimeout(r.timer),this.debounceMap.delete(n)}this.longRunningReminded.delete(t)}};function tl(e){let t=X(e.duration),n=e.prompt.length>60?e.prompt.slice(0,60)+"...":e.prompt;if(e.status==="completed")return[`\u2705 Claude Code [${e.id}] completed (${t})`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${n}"`].join(`
62
62
  `);if(e.status==="failed"){let r=e.error?` \u26A0\uFE0F ${e.error}`:e.result?.subtype?` \u26A0\uFE0F ${e.result.subtype}`:"";return[`\u274C Claude Code [${e.id}] failed (${t})`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${n}"`,...r?[r]:[]].join(`
63
63
  `)}return e.status==="killed"?[`\u26D4 Claude Code [${e.id}] killed (${t})`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${n}"`].join(`
64
- `):`Session [${e.id}] finished with status: ${e.status}`}function nl(e){if(!e||typeof e!="object")return"";if(e.file_path)return Mt(e.file_path,60);if(e.path)return Mt(e.path,60);if(e.command)return Mt(e.command,80);if(e.pattern)return Mt(e.pattern,60);if(e.glob)return Mt(e.glob,60);let t=Object.values(e).find(n=>typeof n=="string"&&n.length>0);return t?Mt(String(t),60):""}function Mt(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}var ai=require("child_process");function rl(e){let t=null,n=null,r=null,o=(s,a)=>{console.log(`[PLUGIN] registerTool factory called for ${s}`),console.log(`[PLUGIN] ctx keys: ${a?Object.keys(a).join(", "):"null/undefined"}`),console.log(`[PLUGIN] ctx.agentAccountId=${a?.agentAccountId}`),console.log(`[PLUGIN] ctx.messageChannel=${a?.messageChannel}`),console.log(`[PLUGIN] ctx.agentId=${a?.agentId}`),console.log(`[PLUGIN] ctx.sessionKey=${a?.sessionKey}`),console.log(`[PLUGIN] ctx.workspaceDir=${a?.workspaceDir}`),console.log(`[PLUGIN] ctx.sandboxed=${a?.sandboxed}`),console.log(`[PLUGIN] full ctx: ${JSON.stringify(a,null,2)}`)};e.registerTool(s=>(o("claude_launch",s),js(s)),{optional:!1}),e.registerTool(s=>(o("claude_sessions",s),_s(s)),{optional:!1}),e.registerTool(s=>(o("claude_kill",s),Ls(s)),{optional:!1}),e.registerTool(s=>(o("claude_output",s),Gs(s)),{optional:!1}),e.registerTool(s=>(o("claude_fg",s),Ds(s)),{optional:!1}),e.registerTool(s=>(o("claude_bg",s),Bs(s)),{optional:!1}),e.registerTool(s=>(o("claude_respond",s),Vs(s)),{optional:!1}),e.registerTool(s=>(o("claude_stats",s),vs(s)),{optional:!1}),qs(e),Ws(e),zs(e),Hs(e),Js(e),Ys(e),Xs(e),Zs(e),Qs(e),e.registerService({id:"openclaw-claude-code-plugin",start:()=>{let s=e.pluginConfig??e.getConfig?.()??{};console.log("[claude-code-plugin] Raw config from getConfig():",JSON.stringify(s)),ks(s),t=new Cn(U.maxSessions,U.maxPersistedSessions),cr(t);let a=(m,p)=>{let g="telegram",I="",j;if(U.fallbackChannel?.includes("|")){let $=U.fallbackChannel.split("|");$.length>=3&&$[0]&&$[1]?(g=$[0],j=$[1],I=$.slice(2).join("|")):$[0]&&$[1]&&(g=$[0],I=$[1])}let ne=g,H=I,ue=j;if(m==="unknown"||!m)if(I)console.log(`[claude-code] sendMessage: channelId="${m}", using fallback ${g}|${I}${j?` (account=${j})`:""}`);else{console.warn(`[claude-code] sendMessage: channelId="${m}" and no fallbackChannel configured \u2014 message will not be sent`);return}else if(m.includes("|")){let $=m.split("|");$.length>=3?(ne=$[0],ue=$[1],H=$.slice(2).join("|")):$[0]&&$[1]&&(ne=$[0],H=$[1])}else if(/^-?\d+$/.test(m))ne="telegram",H=m;else if(I)console.log(`[claude-code] sendMessage: unrecognized channelId="${m}", using fallback ${g}|${I}`);else{console.warn(`[claude-code] sendMessage: unrecognized channelId="${m}" and no fallbackChannel configured \u2014 message will not be sent`);return}console.log(`[claude-code] sendMessage -> channel=${ne}, target=${H}${ue?`, account=${ue}`:""}, textLen=${p.length}`);let Xe=["message","send","--channel",ne];ue&&Xe.push("--account",ue),Xe.push("--target",H,"-m",p),(0,ai.execFile)("openclaw",Xe,{timeout:15e3},($,B,ct)=>{$?(console.error(`[claude-code] sendMessage CLI ERROR: ${$.message}`),ct&&console.error(`[claude-code] sendMessage CLI STDERR: ${ct}`)):(console.log(`[claude-code] sendMessage CLI OK -> channel=${ne}, target=${H}${ue?`, account=${ue}`:""}`),B.trim()&&console.log(`[claude-code] sendMessage CLI STDOUT: ${B.trim()}`))})};n=new $n(a),mr(n),t.notificationRouter=n,n.startReminderCheck(()=>t?.list("running")??[]),r=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{n&&n.stop(),t&&t.killAll(),r&&clearInterval(r),r=null,t=null,n=null,cr(null),mr(null)}})}0&&(module.exports={register});
64
+ `):`Session [${e.id}] finished with status: ${e.status}`}function nl(e){if(!e||typeof e!="object")return"";if(e.file_path)return Mt(e.file_path,60);if(e.path)return Mt(e.path,60);if(e.command)return Mt(e.command,80);if(e.pattern)return Mt(e.pattern,60);if(e.glob)return Mt(e.glob,60);let t=Object.values(e).find(n=>typeof n=="string"&&n.length>0);return t?Mt(String(t),60):""}function Mt(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}var ai=require("child_process");function rl(e){let t=null,n=null,r=null,o=(s,a)=>{console.log(`[PLUGIN] registerTool factory called for ${s}`),console.log(`[PLUGIN] ctx keys: ${a?Object.keys(a).join(", "):"null/undefined"}`),console.log(`[PLUGIN] ctx.agentAccountId=${a?.agentAccountId}`),console.log(`[PLUGIN] ctx.messageChannel=${a?.messageChannel}`),console.log(`[PLUGIN] ctx.agentId=${a?.agentId}`),console.log(`[PLUGIN] ctx.sessionKey=${a?.sessionKey}`),console.log(`[PLUGIN] ctx.workspaceDir=${a?.workspaceDir}`),console.log(`[PLUGIN] ctx.sandboxed=${a?.sandboxed}`),console.log(`[PLUGIN] full ctx: ${JSON.stringify(a,null,2)}`)};e.registerTool(s=>(o("claude_launch",s),js(s)),{optional:!1}),e.registerTool(s=>(o("claude_sessions",s),_s(s)),{optional:!1}),e.registerTool(s=>(o("claude_kill",s),Ls(s)),{optional:!1}),e.registerTool(s=>(o("claude_output",s),Gs(s)),{optional:!1}),e.registerTool(s=>(o("claude_fg",s),Ds(s)),{optional:!1}),e.registerTool(s=>(o("claude_bg",s),Bs(s)),{optional:!1}),e.registerTool(s=>(o("claude_respond",s),Vs(s)),{optional:!1}),e.registerTool(s=>(o("claude_stats",s),vs(s)),{optional:!1}),qs(e),Ws(e),zs(e),Hs(e),Js(e),Ys(e),Xs(e),Zs(e),Qs(e),e.registerService({id:"openclaw-claude-code-plugin",start:()=>{let s=e.pluginConfig??e.getConfig?.()??{};console.log("[claude-code-plugin] Raw config from getConfig():",JSON.stringify(s)),Ps(s),t=new Cn(F.maxSessions,F.maxPersistedSessions),cr(t);let a=(m,p)=>{let g="telegram",U="",E;if(F.fallbackChannel?.includes("|")){let j=F.fallbackChannel.split("|");j.length>=3&&j[0]&&j[1]?(g=j[0],E=j[1],U=j.slice(2).join("|")):j[0]&&j[1]&&(g=j[0],U=j[1])}let P=g,R=U,re=E;if(m==="unknown"||!m)if(U)console.log(`[claude-code] sendMessage: channelId="${m}", using fallback ${g}|${U}${E?` (account=${E})`:""}`);else{console.warn(`[claude-code] sendMessage: channelId="${m}" and no fallbackChannel configured \u2014 message will not be sent`);return}else if(m.includes("|")){let j=m.split("|");j.length>=3?(P=j[0],re=j[1],R=j.slice(2).join("|")):j[0]&&j[1]&&(P=j[0],R=j[1])}else if(/^-?\d+$/.test(m))P="telegram",R=m;else if(U)console.log(`[claude-code] sendMessage: unrecognized channelId="${m}", using fallback ${g}|${U}`);else{console.warn(`[claude-code] sendMessage: unrecognized channelId="${m}" and no fallbackChannel configured \u2014 message will not be sent`);return}console.log(`[claude-code] sendMessage -> channel=${P}, target=${R}${re?`, account=${re}`:""}, textLen=${p.length}`);let De=["message","send","--channel",P];re&&De.push("--account",re),De.push("--target",R,"-m",p),(0,ai.execFile)("openclaw",De,{timeout:15e3},(j,Ue,ct)=>{j?(console.error(`[claude-code] sendMessage CLI ERROR: ${j.message}`),ct&&console.error(`[claude-code] sendMessage CLI STDERR: ${ct}`)):(console.log(`[claude-code] sendMessage CLI OK -> channel=${P}, target=${R}${re?`, account=${re}`:""}`),Ue.trim()&&console.log(`[claude-code] sendMessage CLI STDOUT: ${Ue.trim()}`))})};n=new $n(a),mr(n),t.notificationRouter=n,n.startReminderCheck(()=>t?.list("running")??[]),r=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{n&&n.stop(),t&&t.killAll(),r&&clearInterval(r),r=null,t=null,n=null,cr(null),mr(null)}})}0&&(module.exports={register});
@@ -59,6 +59,11 @@
59
59
  "type": "number",
60
60
  "default": 10,
61
61
  "description": "Maximum consecutive auto-responds (agent tool calls) per session before requiring user input via /claude-respond"
62
+ },
63
+ "skipSafetyChecks": {
64
+ "type": "boolean",
65
+ "default": false,
66
+ "description": "Skip ALL pre-launch safety guards (autonomy skill, heartbeat, HEARTBEAT.md, agentChannels). Use only for development/testing."
62
67
  }
63
68
  }
64
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@betrue/openclaw-claude-code-plugin",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "type": "commonjs",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {