@betrue/openclaw-claude-code-plugin 1.0.3 → 1.0.5

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