openclaw-code-agent 2.3.1 → 3.0.0

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,66 +1,123 @@
1
- var Ta=Object.defineProperty;var ir=(e,t)=>{for(var n in t)Ta(e,n,{get:t[n],enumerable:!0})};import{existsSync as tp}from"fs";var Z={};ir(Z,{HasPropertyKey:()=>cn,IsArray:()=>K,IsAsyncIterator:()=>ar,IsBigInt:()=>jt,IsBoolean:()=>Le,IsDate:()=>it,IsFunction:()=>ur,IsIterator:()=>dr,IsNull:()=>cr,IsNumber:()=>ue,IsObject:()=>A,IsRegExp:()=>Gt,IsString:()=>C,IsSymbol:()=>mr,IsUint8Array:()=>Ke,IsUndefined:()=>D});function cn(e,t){return t in e}function ar(e){return A(e)&&!K(e)&&!Ke(e)&&Symbol.asyncIterator in e}function K(e){return Array.isArray(e)}function jt(e){return typeof e=="bigint"}function Le(e){return typeof e=="boolean"}function it(e){return e instanceof globalThis.Date}function ur(e){return typeof e=="function"}function dr(e){return A(e)&&!K(e)&&!Ke(e)&&Symbol.iterator in e}function cr(e){return e===null}function ue(e){return typeof e=="number"}function A(e){return typeof e=="object"&&e!==null}function Gt(e){return e instanceof globalThis.RegExp}function C(e){return typeof e=="string"}function mr(e){return typeof e=="symbol"}function Ke(e){return e instanceof globalThis.Uint8Array}function D(e){return e===void 0}function ba(e){return e.map(t=>mn(t))}function wa(e){return new Date(e.getTime())}function Aa(e){return new Uint8Array(e)}function Pa(e){return new RegExp(e.source,e.flags)}function Ra(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=mn(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=mn(e[n]);return t}function mn(e){return K(e)?ba(e):it(e)?wa(e):Ke(e)?Aa(e):Gt(e)?Pa(e):A(e)?Ra(e):e}function $(e){return mn(e)}function xt(e,t){return t===void 0?$(e):$({...t,...e})}function oo(e){return e!==null&&typeof e=="object"}function so(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function io(e){return e===void 0}function ao(e){return typeof e=="number"}var pn;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(s,c){return e.ExactOptionalPropertyTypes?c in s:s[c]!==void 0}e.IsExactOptionalProperty=t;function n(s){let c=oo(s);return e.AllowArrayObject?c:c&&!so(s)}e.IsObjectLike=n;function r(s){return n(s)&&!(s instanceof Date)&&!(s instanceof Uint8Array)}e.IsRecordLike=r;function o(s){return e.AllowNaN?ao(s):Number.isFinite(s)}e.IsNumberLike=o;function i(s){let c=io(s);return e.AllowNullVoid?c||s===null:c}e.IsVoidLike=i})(pn||(pn={}));function Oa(e){return globalThis.Object.freeze(e).map(t=>Vt(t))}function Ca(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Vt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Vt(e[n]);return globalThis.Object.freeze(t)}function Vt(e){return K(e)?Oa(e):it(e)?e:Ke(e)?e:Gt(e)?e:A(e)?Ca(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(pn.InstanceMode){case"freeze":return Vt(n);case"clone":return $(n);default:return n}}var q=class extends Error{constructor(t){super(t)}};var V=Symbol.for("TypeBox.Transform"),we=Symbol.for("TypeBox.Readonly"),J=Symbol.for("TypeBox.Optional"),Ie=Symbol.for("TypeBox.Hint"),m=Symbol.for("TypeBox.Kind");function St(e){return A(e)&&e[we]==="Readonly"}function oe(e){return A(e)&&e[J]==="Optional"}function pr(e){return h(e,"Any")}function lr(e){return h(e,"Argument")}function Ae(e){return h(e,"Array")}function at(e){return h(e,"AsyncIterator")}function ut(e){return h(e,"BigInt")}function De(e){return h(e,"Boolean")}function Pe(e){return h(e,"Computed")}function Re(e){return h(e,"Constructor")}function Ma(e){return h(e,"Date")}function Oe(e){return h(e,"Function")}function Ce(e){return h(e,"Integer")}function U(e){return h(e,"Intersect")}function dt(e){return h(e,"Iterator")}function h(e,t){return A(e)&&m in e&&e[m]===t}function ln(e){return Le(e)||ue(e)||C(e)}function de(e){return h(e,"Literal")}function ce(e){return h(e,"MappedKey")}function v(e){return h(e,"MappedResult")}function Be(e){return h(e,"Never")}function Ea(e){return h(e,"Not")}function Ht(e){return h(e,"Null")}function Me(e){return h(e,"Number")}function j(e){return h(e,"Object")}function ct(e){return h(e,"Promise")}function mt(e){return h(e,"Record")}function L(e){return h(e,"Ref")}function fr(e){return h(e,"RegExp")}function je(e){return h(e,"String")}function Bt(e){return h(e,"Symbol")}function me(e){return h(e,"TemplateLiteral")}function Fa(e){return h(e,"This")}function We(e){return A(e)&&V in e}function pe(e){return h(e,"Tuple")}function Wt(e){return h(e,"Undefined")}function y(e){return h(e,"Union")}function ka(e){return h(e,"Uint8Array")}function $a(e){return h(e,"Unknown")}function va(e){return h(e,"Unsafe")}function Na(e){return h(e,"Void")}function Ua(e){return A(e)&&m in e&&C(e[m])}function le(e){return pr(e)||lr(e)||Ae(e)||De(e)||ut(e)||at(e)||Pe(e)||Re(e)||Ma(e)||Oe(e)||Ce(e)||U(e)||dt(e)||de(e)||ce(e)||v(e)||Be(e)||Ea(e)||Ht(e)||Me(e)||j(e)||ct(e)||mt(e)||L(e)||fr(e)||je(e)||Bt(e)||me(e)||Fa(e)||pe(e)||Wt(e)||y(e)||ka(e)||$a(e)||va(e)||Na(e)||Ua(e)}var a={};ir(a,{IsAny:()=>po,IsArgument:()=>lo,IsArray:()=>fo,IsAsyncIterator:()=>go,IsBigInt:()=>Io,IsBoolean:()=>ho,IsComputed:()=>yo,IsConstructor:()=>xo,IsDate:()=>So,IsFunction:()=>To,IsImport:()=>Ga,IsInteger:()=>bo,IsIntersect:()=>wo,IsIterator:()=>Ao,IsKind:()=>Jo,IsKindOf:()=>I,IsLiteral:()=>zt,IsLiteralBoolean:()=>Va,IsLiteralNumber:()=>Ro,IsLiteralString:()=>Po,IsLiteralValue:()=>Oo,IsMappedKey:()=>Co,IsMappedResult:()=>Mo,IsNever:()=>Eo,IsNot:()=>Fo,IsNull:()=>ko,IsNumber:()=>$o,IsObject:()=>vo,IsOptional:()=>ja,IsPromise:()=>No,IsProperties:()=>fn,IsReadonly:()=>Da,IsRecord:()=>Uo,IsRecursive:()=>Ha,IsRef:()=>_o,IsRegExp:()=>Lo,IsSchema:()=>z,IsString:()=>Ko,IsSymbol:()=>Do,IsTemplateLiteral:()=>jo,IsThis:()=>Go,IsTransform:()=>Vo,IsTuple:()=>Ho,IsUint8Array:()=>Wo,IsUndefined:()=>Bo,IsUnion:()=>yr,IsUnionLiteral:()=>Ba,IsUnknown:()=>qo,IsUnsafe:()=>zo,IsVoid:()=>Yo,TypeGuardUnknownTypeError:()=>gr});var gr=class extends q{},_a=["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 uo(e){try{return new RegExp(e),!0}catch{return!1}}function Ir(e){if(!C(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 co(e){return hr(e)||z(e)}function qt(e){return D(e)||jt(e)}function M(e){return D(e)||ue(e)}function hr(e){return D(e)||Le(e)}function P(e){return D(e)||C(e)}function La(e){return D(e)||C(e)&&Ir(e)&&uo(e)}function Ka(e){return D(e)||C(e)&&Ir(e)}function mo(e){return D(e)||z(e)}function Da(e){return A(e)&&e[we]==="Readonly"}function ja(e){return A(e)&&e[J]==="Optional"}function po(e){return I(e,"Any")&&P(e.$id)}function lo(e){return I(e,"Argument")&&ue(e.index)}function fo(e){return I(e,"Array")&&e.type==="array"&&P(e.$id)&&z(e.items)&&M(e.minItems)&&M(e.maxItems)&&hr(e.uniqueItems)&&mo(e.contains)&&M(e.minContains)&&M(e.maxContains)}function go(e){return I(e,"AsyncIterator")&&e.type==="AsyncIterator"&&P(e.$id)&&z(e.items)}function Io(e){return I(e,"BigInt")&&e.type==="bigint"&&P(e.$id)&&qt(e.exclusiveMaximum)&&qt(e.exclusiveMinimum)&&qt(e.maximum)&&qt(e.minimum)&&qt(e.multipleOf)}function ho(e){return I(e,"Boolean")&&e.type==="boolean"&&P(e.$id)}function yo(e){return I(e,"Computed")&&C(e.target)&&K(e.parameters)&&e.parameters.every(t=>z(t))}function xo(e){return I(e,"Constructor")&&e.type==="Constructor"&&P(e.$id)&&K(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function So(e){return I(e,"Date")&&e.type==="Date"&&P(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function To(e){return I(e,"Function")&&e.type==="Function"&&P(e.$id)&&K(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function Ga(e){return I(e,"Import")&&cn(e,"$defs")&&A(e.$defs)&&fn(e.$defs)&&cn(e,"$ref")&&C(e.$ref)&&e.$ref in e.$defs}function bo(e){return I(e,"Integer")&&e.type==="integer"&&P(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function fn(e){return A(e)&&Object.entries(e).every(([t,n])=>Ir(t)&&z(n))}function wo(e){return I(e,"Intersect")&&!(C(e.type)&&e.type!=="object")&&K(e.allOf)&&e.allOf.every(t=>z(t)&&!Vo(t))&&P(e.type)&&(hr(e.unevaluatedProperties)||mo(e.unevaluatedProperties))&&P(e.$id)}function Ao(e){return I(e,"Iterator")&&e.type==="Iterator"&&P(e.$id)&&z(e.items)}function I(e,t){return A(e)&&m in e&&e[m]===t}function Po(e){return zt(e)&&C(e.const)}function Ro(e){return zt(e)&&ue(e.const)}function Va(e){return zt(e)&&Le(e.const)}function zt(e){return I(e,"Literal")&&P(e.$id)&&Oo(e.const)}function Oo(e){return Le(e)||ue(e)||C(e)}function Co(e){return I(e,"MappedKey")&&K(e.keys)&&e.keys.every(t=>ue(t)||C(t))}function Mo(e){return I(e,"MappedResult")&&fn(e.properties)}function Eo(e){return I(e,"Never")&&A(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Fo(e){return I(e,"Not")&&z(e.not)}function ko(e){return I(e,"Null")&&e.type==="null"&&P(e.$id)}function $o(e){return I(e,"Number")&&e.type==="number"&&P(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function vo(e){return I(e,"Object")&&e.type==="object"&&P(e.$id)&&fn(e.properties)&&co(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function No(e){return I(e,"Promise")&&e.type==="Promise"&&P(e.$id)&&z(e.item)}function Uo(e){return I(e,"Record")&&e.type==="object"&&P(e.$id)&&co(e.additionalProperties)&&A(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&uo(n[0])&&A(t.patternProperties)&&z(t.patternProperties[n[0]])})(e)}function Ha(e){return A(e)&&Ie in e&&e[Ie]==="Recursive"}function _o(e){return I(e,"Ref")&&P(e.$id)&&C(e.$ref)}function Lo(e){return I(e,"RegExp")&&P(e.$id)&&C(e.source)&&C(e.flags)&&M(e.maxLength)&&M(e.minLength)}function Ko(e){return I(e,"String")&&e.type==="string"&&P(e.$id)&&M(e.minLength)&&M(e.maxLength)&&La(e.pattern)&&Ka(e.format)}function Do(e){return I(e,"Symbol")&&e.type==="symbol"&&P(e.$id)}function jo(e){return I(e,"TemplateLiteral")&&e.type==="string"&&C(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Go(e){return I(e,"This")&&P(e.$id)&&C(e.$ref)}function Vo(e){return A(e)&&V in e}function Ho(e){return I(e,"Tuple")&&e.type==="array"&&P(e.$id)&&ue(e.minItems)&&ue(e.maxItems)&&e.minItems===e.maxItems&&(D(e.items)&&D(e.additionalItems)&&e.minItems===0||K(e.items)&&e.items.every(t=>z(t)))}function Bo(e){return I(e,"Undefined")&&e.type==="undefined"&&P(e.$id)}function Ba(e){return yr(e)&&e.anyOf.every(t=>Po(t)||Ro(t))}function yr(e){return I(e,"Union")&&P(e.$id)&&A(e)&&K(e.anyOf)&&e.anyOf.every(t=>z(t))}function Wo(e){return I(e,"Uint8Array")&&e.type==="Uint8Array"&&P(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function qo(e){return I(e,"Unknown")&&P(e.$id)}function zo(e){return I(e,"Unsafe")}function Yo(e){return I(e,"Void")&&e.type==="void"&&P(e.$id)}function Jo(e){return A(e)&&m in e&&C(e[m])&&!_a.includes(e[m])}function z(e){return A(e)&&(po(e)||lo(e)||fo(e)||ho(e)||Io(e)||go(e)||yo(e)||xo(e)||So(e)||To(e)||bo(e)||wo(e)||Ao(e)||zt(e)||Co(e)||Mo(e)||Eo(e)||Fo(e)||ko(e)||$o(e)||vo(e)||No(e)||Uo(e)||_o(e)||Lo(e)||Ko(e)||Do(e)||jo(e)||Go(e)||Ho(e)||Bo(e)||yr(e)||Wo(e)||qo(e)||zo(e)||Yo(e)||Jo(e))}var xr="(true|false)",Yt="(0|[1-9][0-9]*)",Sr="(.*)",Wa="(?!.*)",Af=`^${xr}$`,qe=`^${Yt}$`,ze=`^${Sr}$`,Xo=`^${Wa}$`;function Qo(e,t){return e.includes(t)}function Zo(e){return[...new Set(e)]}function qa(e,t){return e.filter(n=>t.includes(n))}function za(e,t){return e.reduce((n,r)=>qa(n,r),t)}function es(e){return e.length===1?e[0]:e.length>1?za(e.slice(1),e[0]):[]}function ts(e){let t=[];for(let n of e)t.push(...n);return t}function Ye(e){return u({[m]:"Any"},e)}function Tt(e,t){return u({[m]:"Array",type:"array",items:e},t)}function ns(e){return u({[m]:"Argument",index:e})}function bt(e,t){return u({[m]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function E(e,t,n){return u({[m]:"Computed",target:e,parameters:t},n)}function Ya(e,t){let{[t]:n,...r}=e;return r}function _(e,t){return t.reduce((n,r)=>Ya(n,r),e)}function x(e){return u({[m]:"Never",not:{}},e)}function S(e){return u({[m]:"MappedResult",properties:e})}function wt(e,t,n){return u({[m]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function ve(e,t,n){return u({[m]:"Function",type:"Function",parameters:e,returns:t},n)}function Jt(e,t){return u({[m]:"Union",anyOf:e},t)}function Ja(e){return e.some(t=>oe(t))}function rs(e){return e.map(t=>oe(t)?Xa(t):t)}function Xa(e){return _(e,[J])}function Qa(e,t){return Ja(e)?ee(Jt(rs(e),t)):Jt(rs(e),t)}function Ne(e,t){return e.length===1?u(e[0],t):e.length===0?x(t):Qa(e,t)}function w(e,t){return e.length===0?x(t):e.length===1?u(e[0],t):Jt(e,t)}var gn=class extends q{};function Za(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Tr(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function Ve(e,t){return Tr(e,t,"(")}function Xt(e,t){return Tr(e,t,")")}function os(e,t){return Tr(e,t,"|")}function eu(e){if(!(Ve(e,0)&&Xt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(Ve(e,n)&&(t+=1),Xt(e,n)&&(t-=1),t===0&&n!==e.length-1)return!1;return!0}function tu(e){return e.slice(1,e.length-1)}function nu(e){let t=0;for(let n=0;n<e.length;n++)if(Ve(e,n)&&(t+=1),Xt(e,n)&&(t-=1),os(e,n)&&t===0)return!0;return!1}function ru(e){for(let t=0;t<e.length;t++)if(Ve(e,t))return!0;return!1}function ou(e){let[t,n]=[0,0],r=[];for(let i=0;i<e.length;i++)if(Ve(e,i)&&(t+=1),Xt(e,i)&&(t-=1),os(e,i)&&t===0){let s=e.slice(n,i);s.length>0&&r.push(At(s)),n=i+1}let o=e.slice(n);return o.length>0&&r.push(At(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function su(e){function t(o,i){if(!Ve(o,i))throw new gn("TemplateLiteralParser: Index must point to open parens");let s=0;for(let c=i;c<o.length;c++)if(Ve(o,c)&&(s+=1),Xt(o,c)&&(s-=1),s===0)return[i,c];throw new gn("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,i){for(let s=i;s<o.length;s++)if(Ve(o,s))return[i,s];return[i,o.length]}let r=[];for(let o=0;o<e.length;o++)if(Ve(e,o)){let[i,s]=t(e,o),c=e.slice(i,s+1);r.push(At(c)),o=s}else{let[i,s]=n(e,o),c=e.slice(i,s);c.length>0&&r.push(At(c)),o=s-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function At(e){return eu(e)?At(tu(e)):nu(e)?ou(e):ru(e)?su(e):{type:"const",const:Za(e)}}function Pt(e){return At(e.slice(1,e.length-1))}var br=class extends q{};function iu(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 au(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 uu(e){return e.type==="const"&&e.const===".*"}function pt(e){return iu(e)||uu(e)?!1:au(e)?!0:e.type==="and"?e.expr.every(t=>pt(t)):e.type==="or"?e.expr.every(t=>pt(t)):e.type==="const"?!0:(()=>{throw new br("Unknown expression type")})()}function ss(e){let t=Pt(e.pattern);return pt(t)}var wr=class extends q{};function*is(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let n of is(e.slice(1)))yield`${t}${n}`}function*du(e){return yield*is(e.expr.map(t=>[...Qt(t)]))}function*cu(e){for(let t of e.expr)yield*Qt(t)}function*mu(e){return yield e.const}function*Qt(e){return e.type==="and"?yield*du(e):e.type==="or"?yield*cu(e):e.type==="const"?yield*mu(e):(()=>{throw new wr("Unknown expression")})()}function In(e){let t=Pt(e.pattern);return pt(t)?[...Qt(t)]:[]}function T(e,t){return u({[m]:"Literal",const:e,type:typeof e},t)}function hn(e){return u({[m]:"Boolean",type:"boolean"},e)}function Rt(e){return u({[m]:"BigInt",type:"bigint"},e)}function he(e){return u({[m]:"Number",type:"number"},e)}function Ee(e){return u({[m]:"String",type:"string"},e)}function*pu(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield hn():t==="number"?yield he():t==="bigint"?yield Rt():t==="string"?yield Ee():yield(()=>{let n=t.split("|").map(r=>T(r.trim()));return n.length===0?x():n.length===1?n[0]:Ne(n)})()}function*lu(e){if(e[1]!=="{"){let t=T("$"),n=Ar(e.slice(1));return yield*[t,...n]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let n=pu(e.slice(2,t)),r=Ar(e.slice(t+1));return yield*[...n,...r]}yield T(e)}function*Ar(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=T(e.slice(0,t)),r=lu(e.slice(t));return yield*[n,...r]}yield T(e)}function as(e){return[...Ar(e)]}var Pr=class extends q{};function fu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function us(e,t){return me(e)?e.pattern.slice(1,e.pattern.length-1):y(e)?`(${e.anyOf.map(n=>us(n,t)).join("|")})`:Me(e)?`${t}${Yt}`:Ce(e)?`${t}${Yt}`:ut(e)?`${t}${Yt}`:je(e)?`${t}${Sr}`:de(e)?`${t}${fu(e.const.toString())}`:De(e)?`${t}${xr}`:(()=>{throw new Pr(`Unexpected Kind '${e[m]}'`)})()}function Rr(e){return`^${e.map(t=>us(t,"")).join("")}$`}function lt(e){let n=In(e).map(r=>T(r));return Ne(n)}function yn(e,t){let n=C(e)?Rr(as(e)):Rr(e);return u({[m]:"TemplateLiteral",type:"string",pattern:n},t)}function gu(e){return In(e).map(n=>n.toString())}function Iu(e){let t=[];for(let n of e)t.push(...se(n));return t}function hu(e){return[e.toString()]}function se(e){return[...new Set(me(e)?gu(e):y(e)?Iu(e.anyOf):de(e)?hu(e.const):Me(e)?["[number]"]:Ce(e)?["[number]"]:[])]}function yu(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=Je(e,se(t[o]),n);return r}function xu(e,t,n){return yu(e,t.properties,n)}function ds(e,t,n){let r=xu(e,t,n);return S(r)}function ms(e,t){return e.map(n=>ps(n,t))}function Su(e){return e.filter(t=>!Be(t))}function Tu(e,t){return xn(Su(ms(e,t)))}function bu(e){return e.some(t=>Be(t))?[]:e}function wu(e,t){return Ne(bu(ms(e,t)))}function Au(e,t){return t in e?e[t]:t==="[number]"?Ne(e):x()}function Pu(e,t){return t==="[number]"?e:x()}function Ru(e,t){return t in e?e[t]:x()}function ps(e,t){return U(e)?Tu(e.allOf,t):y(e)?wu(e.anyOf,t):pe(e)?Au(e.items??[],t):Ae(e)?Pu(e.items,t):j(e)?Ru(e.properties,t):x()}function Or(e,t){return t.map(n=>ps(e,n))}function cs(e,t){return Ne(Or(e,t))}function Je(e,t,n){if(L(e)||L(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!le(e)||!le(t))throw new q(r);return E("Index",[e,t])}return v(t)?ds(e,t,n):ce(t)?ls(e,t,n):u(le(t)?cs(e,se(t)):cs(e,t),n)}function Ou(e,t,n){return{[t]:Je(e,[t],$(n))}}function Cu(e,t,n){return t.reduce((r,o)=>({...r,...Ou(e,o,n)}),{})}function Mu(e,t,n){return Cu(e,t.keys,n)}function ls(e,t,n){let r=Mu(e,t,n);return S(r)}function Ot(e,t){return u({[m]:"Iterator",type:"Iterator",items:e},t)}function Eu(e){return globalThis.Object.keys(e).filter(t=>!oe(e[t]))}function Fu(e,t){let n=Eu(e),r=n.length>0?{[m]:"Object",type:"object",required:n,properties:e}:{[m]:"Object",type:"object",properties:e};return u(r,t)}var R=Fu;function Sn(e,t){return u({[m]:"Promise",type:"Promise",item:e},t)}function ku(e){return u(_(e,[we]))}function $u(e){return u({...e,[we]:"Readonly"})}function vu(e,t){return t===!1?ku(e):$u(e)}function ie(e,t){let n=t??!0;return v(e)?fs(e,n):vu(e,n)}function Nu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ie(e[r],t);return n}function Uu(e,t){return Nu(e.properties,t)}function fs(e,t){let n=Uu(e,t);return S(n)}function ye(e,t){return u(e.length>0?{[m]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[m]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function gs(e,t){return e in t?xe(e,t[e]):S(t)}function _u(e){return{[e]:T(e)}}function Lu(e){let t={};for(let n of e)t[n]=T(n);return t}function Ku(e,t){return Qo(t,e)?_u(e):Lu(t)}function Du(e,t){let n=Ku(e,t);return gs(e,n)}function Zt(e,t){return t.map(n=>xe(e,n))}function ju(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,_(t,[J]))):St(t)?ie(xe(e,_(t,[we]))):v(t)?gs(e,t.properties):ce(t)?Du(e,t.keys):Re(t)?wt(Zt(e,t.parameters),xe(e,t.returns),n):Oe(t)?ve(Zt(e,t.parameters),xe(e,t.returns),n):at(t)?bt(xe(e,t.items),n):dt(t)?Ot(xe(e,t.items),n):U(t)?te(Zt(e,t.allOf),n):y(t)?w(Zt(e,t.anyOf),n):pe(t)?ye(Zt(e,t.items??[]),n):j(t)?R(ju(e,t.properties),n):Ae(t)?Tt(xe(e,t.items),n):ct(t)?Sn(xe(e,t.item),n):t}function Gu(e,t){let n={};for(let r of e)n[r]=xe(r,t);return n}function Is(e,t,n){let r=le(e)?se(e):e,o=t({[m]:"MappedKey",keys:r}),i=Gu(r,o);return R(i,n)}function Vu(e){return u(_(e,[J]))}function Hu(e){return u({...e,[J]:"Optional"})}function Bu(e,t){return t===!1?Vu(e):Hu(e)}function ee(e,t){let n=t??!0;return v(e)?hs(e,n):Bu(e,n)}function Wu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ee(e[r],t);return n}function qu(e,t){return Wu(e.properties,t)}function hs(e,t){let n=qu(e,t);return S(n)}function en(e,t={}){let n=e.every(o=>j(o)),r=le(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||le(t.unevaluatedProperties)||n?{...r,[m]:"Intersect",type:"object",allOf:e}:{...r,[m]:"Intersect",allOf:e},t)}function zu(e){return e.every(t=>oe(t))}function Yu(e){return _(e,[J])}function ys(e){return e.map(t=>oe(t)?Yu(t):t)}function Ju(e,t){return zu(e)?ee(en(ys(e),t)):en(ys(e),t)}function xn(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>We(n)))throw new Error("Cannot intersect transform types");return Ju(e,t)}function te(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>We(n)))throw new Error("Cannot intersect transform types");return en(e,t)}function Ue(...e){let[t,n]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new q("Ref: $ref must be a string");return u({[m]:"Ref",$ref:t},n)}function Xu(e,t){return E("Awaited",[E(e,t)])}function Qu(e){return E("Awaited",[Ue(e)])}function Zu(e){return te(xs(e))}function ed(e){return w(xs(e))}function td(e){return Ct(e)}function xs(e){return e.map(t=>Ct(t))}function Ct(e,t){return u(Pe(e)?Xu(e.target,e.parameters):U(e)?Zu(e.allOf):y(e)?ed(e.anyOf):ct(e)?td(e.item):L(e)?Qu(e.$ref):e,t)}function Ss(e){let t=[];for(let n of e)t.push(tn(n));return t}function nd(e){let t=Ss(e);return ts(t)}function rd(e){let t=Ss(e);return es(t)}function od(e){return e.map((t,n)=>n.toString())}function sd(e){return["[number]"]}function id(e){return globalThis.Object.getOwnPropertyNames(e)}function ad(e){return ud?globalThis.Object.getOwnPropertyNames(e).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function tn(e){return U(e)?nd(e.allOf):y(e)?rd(e.anyOf):pe(e)?od(e.items??[]):Ae(e)?sd(e.items):j(e)?id(e.properties):mt(e)?ad(e.patternProperties):[]}var ud=!1;function dd(e,t){return E("KeyOf",[E(e,t)])}function cd(e){return E("KeyOf",[Ue(e)])}function md(e,t){let n=tn(e),r=pd(n),o=Ne(r);return u(o,t)}function pd(e){return e.map(t=>t==="[number]"?he():T(t))}function Mt(e,t){return Pe(e)?dd(e.target,e.parameters):L(e)?cd(e.$ref):v(e)?Ts(e,t):md(e,t)}function ld(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Mt(e[r],$(t));return n}function fd(e,t){return ld(e.properties,t)}function Ts(e,t){let n=fd(e,t);return S(n)}function gd(e){let t=[];for(let n of e)t.push(...tn(n));return Zo(t)}function Id(e){return e.filter(t=>!Be(t))}function hd(e,t){let n=[];for(let r of e)n.push(...Or(r,[t]));return Id(n)}function yd(e,t){let n={};for(let r of t)n[r]=xn(hd(e,r));return n}function bs(e,t){let n=gd(e),r=yd(e,n);return R(r,t)}function Tn(e){return u({[m]:"Date",type:"Date"},e)}function bn(e){return u({[m]:"Null",type:"null"},e)}function wn(e){return u({[m]:"Symbol",type:"symbol"},e)}function An(e){return u({[m]:"Undefined",type:"undefined"},e)}function Pn(e){return u({[m]:"Uint8Array",type:"Uint8Array"},e)}function Xe(e){return u({[m]:"Unknown"},e)}function xd(e){return e.map(t=>Cr(t,!1))}function Sd(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ie(Cr(e[n],!1));return t}function Rn(e,t){return t===!0?e:ie(e)}function Cr(e,t){return ar(e)?Rn(Ye(),t):dr(e)?Rn(Ye(),t):K(e)?ie(ye(xd(e))):Ke(e)?Pn():it(e)?Tn():A(e)?Rn(R(Sd(e)),t):ur(e)?Rn(ve([],Xe()),t):D(e)?An():cr(e)?bn():mr(e)?wn():jt(e)?Rt():ue(e)?T(e):Le(e)?T(e):C(e)?T(e):R({})}function ws(e,t){return u(Cr(e,!0),t)}function As(e,t){return Re(e)?ye(e.parameters,t):x(t)}function Ps(e,t){if(D(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(i=>isNaN(i)).map(i=>e[i]),o=[...new Set(n)].map(i=>T(i));return w(o,{...t,[Ie]:"Enum"})}var Er=class extends q{},d;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(d||(d={}));function Se(e){return e===d.False?e:d.True}function Et(e){throw new Er(e)}function H(e){return a.IsNever(e)||a.IsIntersect(e)||a.IsUnion(e)||a.IsUnknown(e)||a.IsAny(e)}function B(e,t){return a.IsNever(t)?ks(e,t):a.IsIntersect(t)?On(e,t):a.IsUnion(t)?vr(e,t):a.IsUnknown(t)?Us(e,t):a.IsAny(t)?$r(e,t):Et("StructuralRight")}function $r(e,t){return d.True}function Td(e,t){return a.IsIntersect(t)?On(e,t):a.IsUnion(t)&&t.anyOf.some(n=>a.IsAny(n)||a.IsUnknown(n))?d.True:a.IsUnion(t)?d.Union:a.IsUnknown(t)||a.IsAny(t)?d.True:d.Union}function bd(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)?d.True:d.False}function wd(e,t){return a.IsObject(t)&&Cn(t)?d.True:H(t)?B(e,t):a.IsArray(t)?Se(O(e.items,t.items)):d.False}function Ad(e,t){return H(t)?B(e,t):a.IsAsyncIterator(t)?Se(O(e.items,t.items)):d.False}function Pd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsBigInt(t)?d.True:d.False}function Es(e,t){return a.IsLiteralBoolean(e)||a.IsBoolean(e)?d.True:d.False}function Rd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsBoolean(t)?d.True:d.False}function Od(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsConstructor(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>Se(O(t.parameters[r],n))===d.True)?Se(O(e.returns,t.returns)):d.False:d.False}function Cd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsDate(t)?d.True:d.False}function Md(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsFunction(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>Se(O(t.parameters[r],n))===d.True)?Se(O(e.returns,t.returns)):d.False:d.False}function Fs(e,t){return a.IsLiteral(e)&&Z.IsNumber(e.const)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function Ed(e,t){return a.IsInteger(t)||a.IsNumber(t)?d.True:H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):d.False}function On(e,t){return t.allOf.every(n=>O(e,n)===d.True)?d.True:d.False}function Fd(e,t){return e.allOf.some(n=>O(n,t)===d.True)?d.True:d.False}function kd(e,t){return H(t)?B(e,t):a.IsIterator(t)?Se(O(e.items,t.items)):d.False}function $d(e,t){return a.IsLiteral(t)&&t.const===e.const?d.True:H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsString(t)?Ns(e,t):a.IsNumber(t)?$s(e,t):a.IsInteger(t)?Fs(e,t):a.IsBoolean(t)?Es(e,t):d.False}function ks(e,t){return d.False}function vd(e,t){return d.True}function Rs(e){let[t,n]=[e,0];for(;a.IsNot(t);)t=t.not,n+=1;return n%2===0?t:Xe()}function Nd(e,t){return a.IsNot(e)?O(Rs(e),t):a.IsNot(t)?O(e,Rs(t)):Et("Invalid fallthrough for Not")}function Ud(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsNull(t)?d.True:d.False}function $s(e,t){return a.IsLiteralNumber(e)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function _d(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsInteger(t)||a.IsNumber(t)?d.True:d.False}function ae(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Os(e){return Cn(e)}function Cs(e){return ae(e,0)||ae(e,1)&&"description"in e.properties&&a.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(a.IsString(e.properties.description.anyOf[0])&&a.IsUndefined(e.properties.description.anyOf[1])||a.IsString(e.properties.description.anyOf[1])&&a.IsUndefined(e.properties.description.anyOf[0]))}function Mr(e){return ae(e,0)}function Ms(e){return ae(e,0)}function Ld(e){return ae(e,0)}function Kd(e){return ae(e,0)}function Dd(e){return Cn(e)}function jd(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&Se(O(e.properties.length,t))===d.True}function Gd(e){return ae(e,0)}function Cn(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&Se(O(e.properties.length,t))===d.True}function Vd(e){let t=ve([Ye()],Ye());return ae(e,0)||ae(e,1)&&"then"in e.properties&&Se(O(e.properties.then,t))===d.True}function vs(e,t){return O(e,t)===d.False||a.IsOptional(e)&&!a.IsOptional(t)?d.False:d.True}function ne(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)||a.IsLiteralString(e)&&Os(t)||a.IsLiteralNumber(e)&&Mr(t)||a.IsLiteralBoolean(e)&&Ms(t)||a.IsSymbol(e)&&Cs(t)||a.IsBigInt(e)&&Ld(t)||a.IsString(e)&&Os(t)||a.IsSymbol(e)&&Cs(t)||a.IsNumber(e)&&Mr(t)||a.IsInteger(e)&&Mr(t)||a.IsBoolean(e)&&Ms(t)||a.IsUint8Array(e)&&Dd(t)||a.IsDate(e)&&Kd(t)||a.IsConstructor(e)&&Gd(t)||a.IsFunction(e)&&jd(t)?d.True:a.IsRecord(e)&&a.IsString(Fr(e))?t[Ie]==="Record"?d.True:d.False:a.IsRecord(e)&&a.IsNumber(Fr(e))&&ae(t,0)?d.True:d.False}function Hd(e,t){return H(t)?B(e,t):a.IsRecord(t)?Te(e,t):a.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!a.IsOptional(t.properties[n]))return d.False;if(a.IsOptional(t.properties[n]))return d.True;if(vs(e.properties[n],t.properties[n])===d.False)return d.False}return d.True})():d.False}function Bd(e,t){return H(t)?B(e,t):a.IsObject(t)&&Vd(t)?d.True:a.IsPromise(t)?Se(O(e.item,t.item)):d.False}function Fr(e){return qe in e.patternProperties?he():ze in e.patternProperties?Ee():Et("Unknown record key pattern")}function kr(e){return qe in e.patternProperties?e.patternProperties[qe]:ze in e.patternProperties?e.patternProperties[ze]:Et("Unable to get record value schema")}function Te(e,t){let[n,r]=[Fr(t),kr(t)];return a.IsLiteralString(e)&&a.IsNumber(n)&&Se(O(e,r))===d.True?d.True:a.IsUint8Array(e)&&a.IsNumber(n)||a.IsString(e)&&a.IsNumber(n)||a.IsArray(e)&&a.IsNumber(n)?O(e,r):a.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(vs(r,e.properties[o])===d.False)return d.False;return d.True})():d.False}function Wd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?O(kr(e),kr(t)):d.False}function qd(e,t){let n=a.IsRegExp(e)?Ee():e,r=a.IsRegExp(t)?Ee():t;return O(n,r)}function Ns(e,t){return a.IsLiteral(e)&&Z.IsString(e.const)||a.IsString(e)?d.True:d.False}function zd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsString(t)?d.True:d.False}function Yd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsSymbol(t)?d.True:d.False}function Jd(e,t){return a.IsTemplateLiteral(e)?O(lt(e),t):a.IsTemplateLiteral(t)?O(e,lt(t)):Et("Invalid fallthrough for TemplateLiteral")}function Xd(e,t){return a.IsArray(t)&&e.items!==void 0&&e.items.every(n=>O(n,t.items)===d.True)}function Qd(e,t){return a.IsNever(e)?d.True:a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:d.False}function Zd(e,t){return H(t)?B(e,t):a.IsObject(t)&&Cn(t)||a.IsArray(t)&&Xd(e,t)?d.True:a.IsTuple(t)?Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||!Z.IsUndefined(e.items)&&Z.IsUndefined(t.items)?d.False:Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||e.items.every((n,r)=>O(n,t.items[r])===d.True)?d.True:d.False:d.False}function ec(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsUint8Array(t)?d.True:d.False}function tc(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsVoid(t)?oc(e,t):a.IsUndefined(t)?d.True:d.False}function vr(e,t){return t.anyOf.some(n=>O(e,n)===d.True)?d.True:d.False}function nc(e,t){return e.anyOf.every(n=>O(n,t)===d.True)?d.True:d.False}function Us(e,t){return d.True}function rc(e,t){return a.IsNever(t)?ks(e,t):a.IsIntersect(t)?On(e,t):a.IsUnion(t)?vr(e,t):a.IsAny(t)?$r(e,t):a.IsString(t)?Ns(e,t):a.IsNumber(t)?$s(e,t):a.IsInteger(t)?Fs(e,t):a.IsBoolean(t)?Es(e,t):a.IsArray(t)?bd(e,t):a.IsTuple(t)?Qd(e,t):a.IsObject(t)?ne(e,t):a.IsUnknown(t)?d.True:d.False}function oc(e,t){return a.IsUndefined(e)||a.IsUndefined(e)?d.True:d.False}function sc(e,t){return a.IsIntersect(t)?On(e,t):a.IsUnion(t)?vr(e,t):a.IsUnknown(t)?Us(e,t):a.IsAny(t)?$r(e,t):a.IsObject(t)?ne(e,t):a.IsVoid(t)?d.True:d.False}function O(e,t){return a.IsTemplateLiteral(e)||a.IsTemplateLiteral(t)?Jd(e,t):a.IsRegExp(e)||a.IsRegExp(t)?qd(e,t):a.IsNot(e)||a.IsNot(t)?Nd(e,t):a.IsAny(e)?Td(e,t):a.IsArray(e)?wd(e,t):a.IsBigInt(e)?Pd(e,t):a.IsBoolean(e)?Rd(e,t):a.IsAsyncIterator(e)?Ad(e,t):a.IsConstructor(e)?Od(e,t):a.IsDate(e)?Cd(e,t):a.IsFunction(e)?Md(e,t):a.IsInteger(e)?Ed(e,t):a.IsIntersect(e)?Fd(e,t):a.IsIterator(e)?kd(e,t):a.IsLiteral(e)?$d(e,t):a.IsNever(e)?vd(e,t):a.IsNull(e)?Ud(e,t):a.IsNumber(e)?_d(e,t):a.IsObject(e)?Hd(e,t):a.IsRecord(e)?Wd(e,t):a.IsString(e)?zd(e,t):a.IsSymbol(e)?Yd(e,t):a.IsTuple(e)?Zd(e,t):a.IsPromise(e)?Bd(e,t):a.IsUint8Array(e)?ec(e,t):a.IsUndefined(e)?tc(e,t):a.IsUnion(e)?nc(e,t):a.IsUnknown(e)?rc(e,t):a.IsVoid(e)?sc(e,t):Et(`Unknown left type operand '${e[m]}'`)}function Qe(e,t){return O(e,t)}function ic(e,t,n,r,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(e))i[s]=Ft(e[s],t,n,r,$(o));return i}function ac(e,t,n,r,o){return ic(e.properties,t,n,r,o)}function _s(e,t,n,r,o){let i=ac(e,t,n,r,o);return S(i)}function uc(e,t,n,r){let o=Qe(e,t);return o===d.Union?w([n,r]):o===d.True?n:r}function Ft(e,t,n,r,o){return v(e)?_s(e,t,n,r,o):ce(e)?u(Ls(e,t,n,r,o)):u(uc(e,t,n,r),o)}function dc(e,t,n,r,o){return{[e]:Ft(T(e),t,n,r,$(o))}}function cc(e,t,n,r,o){return e.reduce((i,s)=>({...i,...dc(s,t,n,r,o)}),{})}function mc(e,t,n,r,o){return cc(e.keys,t,n,r,o)}function Ls(e,t,n,r,o){let i=mc(e,t,n,r,o);return S(i)}function Ks(e,t){return kt(lt(e),t)}function pc(e,t){let n=e.filter(r=>Qe(r,t)===d.False);return n.length===1?n[0]:w(n)}function kt(e,t,n={}){return me(e)?u(Ks(e,t),n):v(e)?u(Ds(e,t),n):u(y(e)?pc(e.anyOf,t):Qe(e,t)!==d.False?x():e,n)}function lc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=kt(e[r],t);return n}function fc(e,t){return lc(e.properties,t)}function Ds(e,t){let n=fc(e,t);return S(n)}function js(e,t){return $t(lt(e),t)}function gc(e,t){let n=e.filter(r=>Qe(r,t)!==d.False);return n.length===1?n[0]:w(n)}function $t(e,t,n){return me(e)?u(js(e,t),n):v(e)?u(Gs(e,t),n):u(y(e)?gc(e.anyOf,t):Qe(e,t)!==d.False?e:x(),n)}function Ic(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=$t(e[r],t);return n}function hc(e,t){return Ic(e.properties,t)}function Gs(e,t){let n=hc(e,t);return S(n)}function Vs(e,t){return Re(e)?u(e.returns,t):x(t)}function Mn(e){return ie(ee(e))}function ft(e,t,n){return u({[m]:"Record",type:"object",patternProperties:{[e]:t}},n)}function Nr(e,t,n){let r={};for(let o of e)r[o]=t;return R(r,{...n,[Ie]:"Record"})}function yc(e,t,n){return ss(e)?Nr(se(e),t,n):ft(e.pattern,t,n)}function xc(e,t,n){return Nr(se(w(e)),t,n)}function Sc(e,t,n){return Nr([e.toString()],t,n)}function Tc(e,t,n){return ft(e.source,t,n)}function bc(e,t,n){let r=D(e.pattern)?ze:e.pattern;return ft(r,t,n)}function wc(e,t,n){return ft(ze,t,n)}function Ac(e,t,n){return ft(Xo,t,n)}function Pc(e,t,n){return R({true:t,false:t},n)}function Rc(e,t,n){return ft(qe,t,n)}function Oc(e,t,n){return ft(qe,t,n)}function En(e,t,n={}){return y(e)?xc(e.anyOf,t,n):me(e)?yc(e,t,n):de(e)?Sc(e.const,t,n):De(e)?Pc(e,t,n):Ce(e)?Rc(e,t,n):Me(e)?Oc(e,t,n):fr(e)?Tc(e,t,n):je(e)?bc(e,t,n):pr(e)?wc(e,t,n):Be(e)?Ac(e,t,n):x(n)}function Fn(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function Hs(e){let t=Fn(e);return t===ze?Ee():t===qe?he():Ee({pattern:t})}function kn(e){return e.patternProperties[Fn(e)]}function Cc(e,t){return t.parameters=nn(e,t.parameters),t.returns=Fe(e,t.returns),t}function Mc(e,t){return t.parameters=nn(e,t.parameters),t.returns=Fe(e,t.returns),t}function Ec(e,t){return t.allOf=nn(e,t.allOf),t}function Fc(e,t){return t.anyOf=nn(e,t.anyOf),t}function kc(e,t){return D(t.items)||(t.items=nn(e,t.items)),t}function $c(e,t){return t.items=Fe(e,t.items),t}function vc(e,t){return t.items=Fe(e,t.items),t}function Nc(e,t){return t.items=Fe(e,t.items),t}function Uc(e,t){return t.item=Fe(e,t.item),t}function _c(e,t){let n=jc(e,t.properties);return{...t,...R(n)}}function Lc(e,t){let n=Fe(e,Hs(t)),r=Fe(e,kn(t)),o=En(n,r);return{...t,...o}}function Kc(e,t){return t.index in e?e[t.index]:Xe()}function Dc(e,t){let n=St(t),r=oe(t),o=Fe(e,t);return n&&r?Mn(o):n&&!r?ie(o):!n&&r?ee(o):o}function jc(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:Dc(e,t[r])}),{})}function nn(e,t){return t.map(n=>Fe(e,n))}function Fe(e,t){return Re(t)?Cc(e,t):Oe(t)?Mc(e,t):U(t)?Ec(e,t):y(t)?Fc(e,t):pe(t)?kc(e,t):Ae(t)?$c(e,t):at(t)?vc(e,t):dt(t)?Nc(e,t):ct(t)?Uc(e,t):j(t)?_c(e,t):mt(t)?Lc(e,t):lr(t)?Kc(e,t):t}function Bs(e,t){return Fe(t,xt(e))}function Ws(e){return u({[m]:"Integer",type:"integer"},e)}function Gc(e,t,n){return{[e]:ke(T(e),t,$(n))}}function Vc(e,t,n){return e.reduce((o,i)=>({...o,...Gc(i,t,n)}),{})}function Hc(e,t,n){return Vc(e.keys,t,n)}function qs(e,t,n){let r=Hc(e,t,n);return S(r)}function Bc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function Wc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function qc(e){return e.toUpperCase()}function zc(e){return e.toLowerCase()}function Yc(e,t,n){let r=Pt(e.pattern);if(!pt(r))return{...e,pattern:zs(e.pattern,t)};let s=[...Qt(r)].map(f=>T(f)),c=Ys(s,t),p=w(c);return yn([p],n)}function zs(e,t){return typeof e=="string"?t==="Uncapitalize"?Bc(e):t==="Capitalize"?Wc(e):t==="Uppercase"?qc(e):t==="Lowercase"?zc(e):e:e.toString()}function Ys(e,t){return e.map(n=>ke(n,t))}function ke(e,t,n={}){return ce(e)?qs(e,t,n):me(e)?Yc(e,t,n):y(e)?w(Ys(e.anyOf,t),n):de(e)?T(zs(e.const,t),n):u(e,n)}function Js(e,t={}){return ke(e,"Capitalize",t)}function Xs(e,t={}){return ke(e,"Lowercase",t)}function Qs(e,t={}){return ke(e,"Uncapitalize",t)}function Zs(e,t={}){return ke(e,"Uppercase",t)}function Jc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ze(e[o],t,$(n));return r}function Xc(e,t,n){return Jc(e.properties,t,n)}function ei(e,t,n){let r=Xc(e,t,n);return S(r)}function Qc(e,t){return e.map(n=>Ur(n,t))}function Zc(e,t){return e.map(n=>Ur(n,t))}function em(e,t){let{[t]:n,...r}=e;return r}function tm(e,t){return t.reduce((n,r)=>em(n,r),e)}function nm(e,t,n){let r=_(e,[V,"$id","required","properties"]),o=tm(n,t);return R(o,r)}function rm(e){let t=e.reduce((n,r)=>ln(r)?[...n,T(r)]:n,[]);return w(t)}function Ur(e,t){return U(e)?te(Qc(e.allOf,t)):y(e)?w(Zc(e.anyOf,t)):j(e)?nm(e,t,e.properties):R({})}function Ze(e,t,n){let r=K(t)?rm(t):t,o=le(t)?se(t):t,i=L(e),s=L(t);return v(e)?ei(e,o,n):ce(t)?ti(e,t,n):i&&s?E("Omit",[e,r],n):!i&&s?E("Omit",[e,r],n):i&&!s?E("Omit",[e,r],n):u({...Ur(e,o),...n})}function om(e,t,n){return{[t]:Ze(e,[t],$(n))}}function sm(e,t,n){return t.reduce((r,o)=>({...r,...om(e,o,n)}),{})}function im(e,t,n){return sm(e,t.keys,n)}function ti(e,t,n){let r=im(e,t,n);return S(r)}function am(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=et(e[o],t,$(n));return r}function um(e,t,n){return am(e.properties,t,n)}function ni(e,t,n){let r=um(e,t,n);return S(r)}function dm(e,t){return e.map(n=>_r(n,t))}function cm(e,t){return e.map(n=>_r(n,t))}function mm(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function pm(e,t,n){let r=_(e,[V,"$id","required","properties"]),o=mm(n,t);return R(o,r)}function lm(e){let t=e.reduce((n,r)=>ln(r)?[...n,T(r)]:n,[]);return w(t)}function _r(e,t){return U(e)?te(dm(e.allOf,t)):y(e)?w(cm(e.anyOf,t)):j(e)?pm(e,t,e.properties):R({})}function et(e,t,n){let r=K(t)?lm(t):t,o=le(t)?se(t):t,i=L(e),s=L(t);return v(e)?ni(e,o,n):ce(t)?ri(e,t,n):i&&s?E("Pick",[e,r],n):!i&&s?E("Pick",[e,r],n):i&&!s?E("Pick",[e,r],n):u({..._r(e,o),...n})}function fm(e,t,n){return{[t]:et(e,[t],$(n))}}function gm(e,t,n){return t.reduce((r,o)=>({...r,...fm(e,o,n)}),{})}function Im(e,t,n){return gm(e,t.keys,n)}function ri(e,t,n){let r=Im(e,t,n);return S(r)}function hm(e,t){return E("Partial",[E(e,t)])}function ym(e){return E("Partial",[Ue(e)])}function xm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ee(e[n]);return t}function Sm(e,t){let n=_(e,[V,"$id","required","properties"]),r=xm(t);return R(r,n)}function oi(e){return e.map(t=>si(t))}function si(e){return Pe(e)?hm(e.target,e.parameters):L(e)?ym(e.$ref):U(e)?te(oi(e.allOf)):y(e)?w(oi(e.anyOf)):j(e)?Sm(e,e.properties):ut(e)||De(e)||Ce(e)||de(e)||Ht(e)||Me(e)||je(e)||Bt(e)||Wt(e)?e:R({})}function vt(e,t){return v(e)?ii(e,t):u({...si(e),...t})}function Tm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=vt(e[r],$(t));return n}function bm(e,t){return Tm(e.properties,t)}function ii(e,t){let n=bm(e,t);return S(n)}function wm(e,t){return E("Required",[E(e,t)])}function Am(e){return E("Required",[Ue(e)])}function Pm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=_(e[n],[J]);return t}function Rm(e,t){let n=_(e,[V,"$id","required","properties"]),r=Pm(t);return R(r,n)}function ai(e){return e.map(t=>ui(t))}function ui(e){return Pe(e)?wm(e.target,e.parameters):L(e)?Am(e.$ref):U(e)?te(ai(e.allOf)):y(e)?w(ai(e.anyOf)):j(e)?Rm(e,e.properties):ut(e)||De(e)||Ce(e)||de(e)||Ht(e)||Me(e)||je(e)||Bt(e)||Wt(e)?e:R({})}function Nt(e,t){return v(e)?di(e,t):u({...ui(e),...t})}function Om(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Nt(e[r],t);return n}function Cm(e,t){return Om(e.properties,t)}function di(e,t){let n=Cm(e,t);return S(n)}function Mm(e,t){return t.map(n=>L(n)?Lr(e,n.$ref):fe(e,n))}function Lr(e,t){return t in e?L(e[t])?Lr(e,e[t].$ref):fe(e,e[t]):x()}function Em(e){return Ct(e[0])}function Fm(e){return Je(e[0],e[1])}function km(e){return Mt(e[0])}function $m(e){return vt(e[0])}function vm(e){return Ze(e[0],e[1])}function Nm(e){return et(e[0],e[1])}function Um(e){return Nt(e[0])}function _m(e,t,n){let r=Mm(e,n);return t==="Awaited"?Em(r):t==="Index"?Fm(r):t==="KeyOf"?km(r):t==="Partial"?$m(r):t==="Omit"?vm(r):t==="Pick"?Nm(r):t==="Required"?Um(r):x()}function Lm(e,t){return Tt(fe(e,t))}function Km(e,t){return bt(fe(e,t))}function Dm(e,t,n){return wt(rn(e,t),fe(e,n))}function jm(e,t,n){return ve(rn(e,t),fe(e,n))}function Gm(e,t){return te(rn(e,t))}function Vm(e,t){return Ot(fe(e,t))}function Hm(e,t){return R(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:fe(e,t[r])}),{}))}function Bm(e,t){let[n,r]=[fe(e,kn(t)),Fn(t)],o=xt(t);return o.patternProperties[r]=n,o}function Wm(e,t){return L(t)?{...Lr(e,t.$ref),[V]:t[V]}:t}function qm(e,t){return ye(rn(e,t))}function zm(e,t){return w(rn(e,t))}function rn(e,t){return t.map(n=>fe(e,n))}function fe(e,t){return oe(t)?u(fe(e,_(t,[J])),t):St(t)?u(fe(e,_(t,[we])),t):We(t)?u(Wm(e,t),t):Ae(t)?u(Lm(e,t.items),t):at(t)?u(Km(e,t.items),t):Pe(t)?u(_m(e,t.target,t.parameters)):Re(t)?u(Dm(e,t.parameters,t.returns),t):Oe(t)?u(jm(e,t.parameters,t.returns),t):U(t)?u(Gm(e,t.allOf),t):dt(t)?u(Vm(e,t.items),t):j(t)?u(Hm(e,t.properties),t):mt(t)?u(Bm(e,t)):pe(t)?u(qm(e,t.items||[]),t):y(t)?u(zm(e,t.anyOf),t):t}function Ym(e,t){return t in e?fe(e,e[t]):x()}function ci(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:Ym(e,n)}),{})}var Kr=class{constructor(t){let n=ci(t),r=this.WithIdentifiers(n);this.$defs=r}Import(t,n){let r={...this.$defs,[t]:u(this.$defs[t],n)};return u({[m]:"Import",$defs:r,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:{...t[r],$id:r}}),{})}};function mi(e){return new Kr(e)}function pi(e,t){return u({[m]:"Not",not:e},t)}function li(e,t){return Oe(e)?ye(e.parameters,t):x()}var Jm=0;function fi(e,t={}){D(t.$id)&&(t.$id=`T${Jm++}`);let n=xt(e({[m]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[Ie]:"Recursive",...n},t)}function gi(e,t){let n=C(e)?new globalThis.RegExp(e):e;return u({[m]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},t)}function Xm(e){return U(e)?e.allOf:y(e)?e.anyOf:pe(e)?e.items??[]:[]}function Ii(e){return Xm(e)}function hi(e,t){return Oe(e)?u(e.returns,t):x(t)}var Dr=class{constructor(t){this.schema=t}Decode(t){return new jr(this.schema,t)}},jr=class{constructor(t,n){this.schema=t,this.decode=n}EncodeTransform(t,n){let i={Encode:s=>n[V].Encode(t(s)),Decode:s=>this.decode(n[V].Decode(s))};return{...n,[V]:i}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[V]:r}}Encode(t){return We(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function yi(e){return new Dr(e)}function xi(e={}){return u({[m]:e[m]??"Unsafe"},e)}function Si(e){return u({[m]:"Void",type:"void"},e)}var Gr={};ir(Gr,{Any:()=>Ye,Argument:()=>ns,Array:()=>Tt,AsyncIterator:()=>bt,Awaited:()=>Ct,BigInt:()=>Rt,Boolean:()=>hn,Capitalize:()=>Js,Composite:()=>bs,Const:()=>ws,Constructor:()=>wt,ConstructorParameters:()=>As,Date:()=>Tn,Enum:()=>Ps,Exclude:()=>kt,Extends:()=>Ft,Extract:()=>$t,Function:()=>ve,Index:()=>Je,InstanceType:()=>Vs,Instantiate:()=>Bs,Integer:()=>Ws,Intersect:()=>te,Iterator:()=>Ot,KeyOf:()=>Mt,Literal:()=>T,Lowercase:()=>Xs,Mapped:()=>Is,Module:()=>mi,Never:()=>x,Not:()=>pi,Null:()=>bn,Number:()=>he,Object:()=>R,Omit:()=>Ze,Optional:()=>ee,Parameters:()=>li,Partial:()=>vt,Pick:()=>et,Promise:()=>Sn,Readonly:()=>ie,ReadonlyOptional:()=>Mn,Record:()=>En,Recursive:()=>fi,Ref:()=>Ue,RegExp:()=>gi,Required:()=>Nt,Rest:()=>Ii,ReturnType:()=>hi,String:()=>Ee,Symbol:()=>wn,TemplateLiteral:()=>yn,Transform:()=>yi,Tuple:()=>ye,Uint8Array:()=>Pn,Uncapitalize:()=>Qs,Undefined:()=>An,Union:()=>w,Unknown:()=>Xe,Unsafe:()=>xi,Uppercase:()=>Zs,Void:()=>Si});var l=Gr;var g=null;function Vr(e){g=e}import{readFileSync as Qm}from"fs";import{homedir as Zm}from"os";import{join as ep}from"path";var on,Ti="claude-code",$n={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium",approvalPolicy:"on-request"}};function bi(){if(on!==void 0)return on;try{let e=Qm(ep(Zm(),".claude.json"),"utf-8");on=JSON.parse(e).mcpServers??{}}catch{on={}}return on}var F={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",codexApprovalPolicy:"on-request",harnesses:{"claude-code":{...$n["claude-code"]},codex:{...$n.codex}}};function wi(e){let t=e.defaultHarness??Ti,n={};for(let[r,o]of Object.entries($n))n[r]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[r,o]of Object.entries(e.harnesses??{})){let s={...n[r]??{},...o};o.allowedModels!==void 0?s.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(s.allowedModels=void 0),n[r]=s}if(e.defaultModel!==void 0){let r=n[t]??{};n[t]={...r,defaultModel:e.harnesses?.[t]?.defaultModel??e.defaultModel,allowedModels:e.harnesses?.[t]?.allowedModels!==void 0?r.allowedModels:e.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${t}.defaultModel instead.`)}if(e.model!==void 0){let r=n.codex??{};n.codex={...r,defaultModel:e.harnesses?.codex?.defaultModel??e.model,allowedModels:e.harnesses?.codex?.allowedModels!==void 0?r.allowedModels:e.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(e.reasoningEffort!==void 0){let r=n.codex??{};n.codex={...r,reasoningEffort:e.harnesses?.codex?.reasoningEffort??e.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(e.codexApprovalPolicy!==void 0){let r=n.codex??{};n.codex={...r,approvalPolicy:e.harnesses?.codex?.approvalPolicy??e.codexApprovalPolicy},console.warn("[openclaw-code-agent] config.codexApprovalPolicy is deprecated; use harnesses.codex.approvalPolicy instead.")}if(e.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[r,o]of Object.entries(n))e.harnesses?.[r]?.allowedModels===void 0&&(n[r]={...o,allowedModels:void 0})}F={maxSessions:e.maxSessions??20,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??15,sessionGcAgeMinutes:e.sessionGcAgeMinutes??1440,maxPersistedSessions:e.maxPersistedSessions??1e4,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10,permissionMode:e.permissionMode??"plan",codexApprovalPolicy:e.codexApprovalPolicy??"on-request",planApproval:e.planApproval??"delegate",defaultHarness:t,harnesses:n,allowedModels:e.allowedModels}}function tt(){return F.defaultHarness??Ti}function Hr(e){let t=$n[e],n=F.harnesses[e];return{...t,...n,allowedModels:n?.allowedModels??t?.allowedModels}}function nt(e){return Hr(e).defaultModel}function Ai(e){return F.harnesses[e]?.allowedModels??F.allowedModels}function Ut(e){return Hr(e).reasoningEffort}function gt(e){return Hr(e).approvalPolicy}function Pi(e){if(e.messageChannel){let t=e.messageChannel.split("|");if(t.length>=3)return e.messageChannel;if(e.agentAccountId&&t.length>=2)return`${t[0]}|${e.agentAccountId}|${t.slice(1).join("|")}`;if(t.length===1&&e.chatId)return`${t[0]}|${e.chatId}`;if(t.length===1&&e.senderId)return`${t[0]}|${e.senderId}`}if(e.workspaceDir){let t=sn(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function _t(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);if(e?.messageChannel){let n=String(e.messageChannel);if(n.includes("|"))return n;if(e.chatId)return`${n}|${e.chatId}`;if(e.senderId)return`${n}|${e.senderId}`}return e?.channel&&e?.chatId?`${e.channel}|${e.chatId}`:e?.channel&&e?.senderId?`${e.channel}|${e.senderId}`:e?.id&&/^-?\d+$/.test(String(e.id))?`telegram|${e.id}`:F.fallbackChannel??"unknown"}function Lt(e){return e?.messageThreadId??void 0}function sn(e){let t=F.agentChannels;if(!t)return;let n=i=>i.replace(/\/+$/,""),r=n(e),o=Object.entries(t).sort((i,s)=>s[0].length-i[0].length);for(let[i,s]of o)if(r===n(i)||r.startsWith(n(i)+"/"))return s}function Ri(e){if(!e)return;let t=e.match(/:topic:(\d+)$/);return t?parseInt(t[1],10):void 0}function Kt(e){let{requestedResumeSessionId:t,activeSession:n,persistedSession:r}=e;return t?n?{resumeSessionId:t,clearedPersistedCodexResume:!1}:r?.harness==="codex"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:t,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}function np(e){return e instanceof Error?e.message:String(e)}function rp(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function op(e,t){if(!t||t.length===0)return!0;if(!e)return!1;let n=e.toLowerCase();return t.some(r=>n.includes(r.toLowerCase()))}function Oi(e){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn by default \u2014 they stay open for follow-up messages via agent_respond. Set multi_turn_disabled: true for fire-and-forget sessions. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:l.Object({prompt:l.String({description:"The task prompt to execute"}),name:l.Optional(l.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:l.Optional(l.String({description:"Working directory (defaults to cwd)"})),model:l.Optional(l.String({description:"Model name to use"})),system_prompt:l.Optional(l.String({description:"Additional system prompt"})),allowed_tools:l.Optional(l.Array(l.String(),{description:"List of allowed tools"})),resume_session_id:l.Optional(l.String({description:"Session ID to resume (from a previous session's harnessSessionId). Continues the conversation from where it left off."})),fork_session:l.Optional(l.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),multi_turn_disabled:l.Optional(l.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:l.Optional(l.Union([l.Literal("default"),l.Literal("plan"),l.Literal("acceptEdits"),l.Literal("bypassPermissions")],{description:"Permission mode for the session. This is the plugin's orchestration mode, not the Codex SDK approval policy. Defaults to plugin config (plan by default)."})),harness:l.Optional(l.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!rp(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};n.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${n.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${e.agentId}" will be used for origin routing instead.`);let r=n.workdir||e.workspaceDir||F.defaultWorkdir||process.cwd();if(!tp(r))return{content:[{type:"text",text:`Error: Working directory does not exist: ${r}`}]};try{let o=n.harness??tt(),i=nt(o),s=n.model??i,c=n.model!==void 0;if(!s)return{content:[{type:"text",text:`Error: No default model configured for harness "${o}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${o}.defaultModel or pass model explicitly.`}]};let p=Ai(o);if(p&&p.length>0&&!op(s,p))return{content:[{type:"text",text:c?`Error: Model "${s}" is not allowed. Permitted models: ${p.join(", ")}`:`Error: Default model "${s||"undefined"}" is not in allowedModels (${p.join(", ")}). Update your plugin config to set a compatible defaultModel.`}]};let f=n.resume_session_id,b=f?g.resolve(f):void 0,k=f?g.getPersistedSession(f):void 0;if(f){let yt=g.resolveHarnessSessionId(f);if(!yt)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${f}" to a session ID. Use agent_sessions to list available sessions.`}]};f=yt}let{resumeSessionId:X,clearedPersistedCodexResume:ge}=Kt({requestedResumeSessionId:f,activeSession:b?{harnessSessionId:b.harnessSessionId}:void 0,persistedSession:k?{harness:k.harness}:void 0}),Y=Pi(e),W=_t(e,Y||sn(r)),Q=e.sessionKey||void 0;!Q&&e.agentId&&console.warn(`[agent_launch] ctx.sessionKey is not populated. ctx fields: agentId=${e.agentId}, messageChannel=${e.messageChannel}, agentAccountId=${e.agentAccountId}, workspaceDir=${e.workspaceDir}`);let N=g.spawn({prompt:n.prompt,name:n.name,workdir:r,model:s,reasoningEffort:Ut(o),systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:X,forkSession:X?n.fork_session:!1,multiTurn:!n.multi_turn_disabled,permissionMode:n.permission_mode,codexApprovalPolicy:o==="codex"?gt(o)??F.codexApprovalPolicy:void 0,originChannel:W,originThreadId:Ri(Q)??Lt(e),originAgentId:e.agentId||void 0,originSessionKey:Q,harness:o}),He=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,be=["Session launched successfully.",` Name: ${N.name}`,` ID: ${N.id}`,` Dir: ${r}`,` Model: ${N.model??"default"}`,` Prompt: "${He}"`];return o==="codex"&&be.push(` Codex approval policy: ${N.codexApprovalPolicy??gt(o)??F.codexApprovalPolicy}`),n.resume_session_id&&(be.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),ge&&be.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),be.push(n.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),be.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:be.join(`
2
- `)}]}}catch(o){let i=np(o),s=i.includes("Max sessions")?"":`
3
-
4
- Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${i}${s}`}]}}}}}import{existsSync as ap,readFileSync as up}from"fs";function _e(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 sp=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 Ci(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!sp.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var ip={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function Mi(e){let t=ip[e.status]??"\u2753",n=_e(e.duration),r=e.multiTurn?"multi-turn":"single",o=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,i=e.costUsd>0?` | $${e.costUsd.toFixed(2)}`:"",s=[`${t} ${e.name} [${e.id}] (${n}${i}) \u2014 ${r}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];return e.phase!==e.status&&s.push(` \u2699\uFE0F Phase: ${e.phase}`),e.harness&&s.push(` \u{1F9F0} Harness: ${e.harness}`),e.harnessSessionId&&s.push(` \u{1F517} Session ID: ${e.harnessSessionId}`),e.resumeSessionId&&s.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),s.join(`
5
- `)}function vn(e,t){let n=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:r,failed:o,killed:i}=e.sessionsByStatus,s=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${n>0?_e(n):"n/a"}`];if(e.mostExpensive){let c=e.mostExpensive;s.push("","\u{1F3C6} Notable session",` ${c.name} [${c.id}]`,` \u{1F4DD} "${c.prompt}"`)}return s.join(`
6
- `)}function rt(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function Ei(e,t){let n=e.split(`
7
- `),r=[],o=0;for(let i=n.length-1;i>=0;i--){let s=n[i].length+(r.length>0?1:0);if(o+s>t&&r.length>0)break;r.unshift(n[i]),o+=s}return r.join(`
8
- `)}var dp=50,cp=1,mp=new Set(["starting","running","completed","failed","killed"]),pp=5,lp=1440*60*1e3;function fp(e){let t=Number(e);return!Number.isFinite(t)||t<cp?dp:Math.floor(t)}function gp(e){return typeof e=="string"&&mp.has(e)}function Ip(e){let t=_e(e.duration),n=` | Cost: $${e.costUsd.toFixed(4)}`,r=e.status==="running"?` | Phase: ${e.phase}`:"";return[`Session: ${e.name} [${e.id}] | Status: ${e.status.toUpperCase()}${r}${n} | Duration: ${t}`,`${"\u2500".repeat(60)}`].join(`
9
- `)}function hp(e){return[`Session: ${e.name||e.harnessSessionId} | Status: ${e.status.toUpperCase()} | Cost: $${e.costUsd.toFixed(4)}`,`(retrieved from ${e.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`,`${"\u2500".repeat(60)}`].join(`
10
- `)}function yp(e){let t=[];return e.error&&t.push(`Error: ${e.error}`),e.result?.result&&t.push(`Result: ${e.result.result}`),e.result&&t.push(`Result status: ${e.result.subtype}`),t.length>0?`
1
+ var nu=Object.defineProperty;var En=(e,t)=>{for(var r in t)nu(e,r,{get:t[r],enumerable:!0})};import{readdirSync as cg,statSync as dg,rmSync as lg}from"fs";import{execFileSync as pg}from"child_process";import{join as Za}from"path";import{existsSync as Up}from"fs";var ie={};En(ie,{HasPropertyKey:()=>Tr,IsArray:()=>Q,IsAsyncIterator:()=>vn,IsBigInt:()=>nr,IsBoolean:()=>ze,IsDate:()=>It,IsFunction:()=>_n,IsIterator:()=>Fn,IsNull:()=>Nn,IsNumber:()=>he,IsObject:()=>U,IsRegExp:()=>or,IsString:()=>j,IsSymbol:()=>Un,IsUint8Array:()=>Qe,IsUndefined:()=>Y});function Tr(e,t){return t in e}function vn(e){return U(e)&&!Q(e)&&!Qe(e)&&Symbol.asyncIterator in e}function Q(e){return Array.isArray(e)}function nr(e){return typeof e=="bigint"}function ze(e){return typeof e=="boolean"}function It(e){return e instanceof globalThis.Date}function _n(e){return typeof e=="function"}function Fn(e){return U(e)&&!Q(e)&&!Qe(e)&&Symbol.iterator in e}function Nn(e){return e===null}function he(e){return typeof e=="number"}function U(e){return typeof e=="object"&&e!==null}function or(e){return e instanceof globalThis.RegExp}function j(e){return typeof e=="string"}function Un(e){return typeof e=="symbol"}function Qe(e){return e instanceof globalThis.Uint8Array}function Y(e){return e===void 0}function ou(e){return e.map(t=>Ar(t))}function su(e){return new Date(e.getTime())}function iu(e){return new Uint8Array(e)}function au(e){return new RegExp(e.source,e.flags)}function uu(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=Ar(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=Ar(e[r]);return t}function Ar(e){return Q(e)?ou(e):It(e)?su(e):Qe(e)?iu(e):or(e)?au(e):U(e)?uu(e):e}function G(e){return Ar(e)}function vt(e,t){return t===void 0?G(e):G({...t,...e})}function Eo(e){return e!==null&&typeof e=="object"}function vo(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function _o(e){return e===void 0}function Fo(e){return typeof e=="number"}var $r;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(i,a){return e.ExactOptionalPropertyTypes?a in i:i[a]!==void 0}e.IsExactOptionalProperty=t;function r(i){let a=Eo(i);return e.AllowArrayObject?a:a&&!vo(i)}e.IsObjectLike=r;function n(i){return r(i)&&!(i instanceof Date)&&!(i instanceof Uint8Array)}e.IsRecordLike=n;function o(i){return e.AllowNaN?Fo(i):Number.isFinite(i)}e.IsNumberLike=o;function s(i){let a=_o(i);return e.AllowNullVoid?a||i===null:a}e.IsVoidLike=s})($r||($r={}));function cu(e){return globalThis.Object.freeze(e).map(t=>sr(t))}function du(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=sr(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=sr(e[r]);return globalThis.Object.freeze(t)}function sr(e){return Q(e)?cu(e):It(e)?e:Qe(e)?e:or(e)?e:U(e)?du(e):e}function l(e,t){let r=t!==void 0?{...t,...e}:e;switch($r.InstanceMode){case"freeze":return sr(r);case"clone":return G(r);default:return r}}var re=class extends Error{constructor(t){super(t)}};var Z=Symbol.for("TypeBox.Transform"),Me=Symbol.for("TypeBox.Readonly"),oe=Symbol.for("TypeBox.Optional"),Pe=Symbol.for("TypeBox.Hint"),h=Symbol.for("TypeBox.Kind");function _t(e){return U(e)&&e[Me]==="Readonly"}function pe(e){return U(e)&&e[oe]==="Optional"}function Dn(e){return C(e,"Any")}function Ln(e){return C(e,"Argument")}function Oe(e){return C(e,"Array")}function wt(e){return C(e,"AsyncIterator")}function St(e){return C(e,"BigInt")}function Ye(e){return C(e,"Boolean")}function Ee(e){return C(e,"Computed")}function ve(e){return C(e,"Constructor")}function lu(e){return C(e,"Date")}function _e(e){return C(e,"Function")}function Fe(e){return C(e,"Integer")}function V(e){return C(e,"Intersect")}function xt(e){return C(e,"Iterator")}function C(e,t){return U(e)&&h in e&&e[h]===t}function Rr(e){return ze(e)||he(e)||j(e)}function ye(e){return C(e,"Literal")}function Ie(e){return C(e,"MappedKey")}function H(e){return C(e,"MappedResult")}function rt(e){return C(e,"Never")}function pu(e){return C(e,"Not")}function ir(e){return C(e,"Null")}function Ne(e){return C(e,"Number")}function J(e){return C(e,"Object")}function bt(e){return C(e,"Promise")}function kt(e){return C(e,"Record")}function z(e){return C(e,"Ref")}function Kn(e){return C(e,"RegExp")}function Je(e){return C(e,"String")}function ar(e){return C(e,"Symbol")}function we(e){return C(e,"TemplateLiteral")}function mu(e){return C(e,"This")}function nt(e){return U(e)&&Z in e}function Se(e){return C(e,"Tuple")}function ur(e){return C(e,"Undefined")}function M(e){return C(e,"Union")}function fu(e){return C(e,"Uint8Array")}function gu(e){return C(e,"Unknown")}function hu(e){return C(e,"Unsafe")}function yu(e){return C(e,"Void")}function Iu(e){return U(e)&&h in e&&j(e[h])}function xe(e){return Dn(e)||Ln(e)||Oe(e)||Ye(e)||St(e)||wt(e)||Ee(e)||ve(e)||lu(e)||_e(e)||Fe(e)||V(e)||xt(e)||ye(e)||Ie(e)||H(e)||rt(e)||pu(e)||ir(e)||Ne(e)||J(e)||bt(e)||kt(e)||z(e)||Kn(e)||Je(e)||ar(e)||we(e)||mu(e)||Se(e)||ur(e)||M(e)||fu(e)||gu(e)||hu(e)||yu(e)||Iu(e)}var u={};En(u,{IsAny:()=>Lo,IsArgument:()=>Ko,IsArray:()=>jo,IsAsyncIterator:()=>Bo,IsBigInt:()=>Wo,IsBoolean:()=>Go,IsComputed:()=>Ho,IsConstructor:()=>Vo,IsDate:()=>qo,IsFunction:()=>zo,IsImport:()=>Pu,IsInteger:()=>Qo,IsIntersect:()=>Yo,IsIterator:()=>Jo,IsKind:()=>ks,IsKindOf:()=>R,IsLiteral:()=>dr,IsLiteralBoolean:()=>Tu,IsLiteralNumber:()=>Zo,IsLiteralString:()=>Xo,IsLiteralValue:()=>es,IsMappedKey:()=>ts,IsMappedResult:()=>rs,IsNever:()=>ns,IsNot:()=>os,IsNull:()=>ss,IsNumber:()=>is,IsObject:()=>as,IsOptional:()=>ku,IsPromise:()=>us,IsProperties:()=>Cr,IsReadonly:()=>bu,IsRecord:()=>cs,IsRecursive:()=>Au,IsRef:()=>ds,IsRegExp:()=>ls,IsSchema:()=>ne,IsString:()=>ps,IsSymbol:()=>ms,IsTemplateLiteral:()=>fs,IsThis:()=>gs,IsTransform:()=>hs,IsTuple:()=>ys,IsUint8Array:()=>ws,IsUndefined:()=>Is,IsUnion:()=>Gn,IsUnionLiteral:()=>$u,IsUnknown:()=>Ss,IsUnsafe:()=>xs,IsVoid:()=>bs,TypeGuardUnknownTypeError:()=>jn});var jn=class extends re{},wu=["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 No(e){try{return new RegExp(e),!0}catch{return!1}}function Bn(e){if(!j(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 Uo(e){return Wn(e)||ne(e)}function cr(e){return Y(e)||nr(e)}function B(e){return Y(e)||he(e)}function Wn(e){return Y(e)||ze(e)}function D(e){return Y(e)||j(e)}function Su(e){return Y(e)||j(e)&&Bn(e)&&No(e)}function xu(e){return Y(e)||j(e)&&Bn(e)}function Do(e){return Y(e)||ne(e)}function bu(e){return U(e)&&e[Me]==="Readonly"}function ku(e){return U(e)&&e[oe]==="Optional"}function Lo(e){return R(e,"Any")&&D(e.$id)}function Ko(e){return R(e,"Argument")&&he(e.index)}function jo(e){return R(e,"Array")&&e.type==="array"&&D(e.$id)&&ne(e.items)&&B(e.minItems)&&B(e.maxItems)&&Wn(e.uniqueItems)&&Do(e.contains)&&B(e.minContains)&&B(e.maxContains)}function Bo(e){return R(e,"AsyncIterator")&&e.type==="AsyncIterator"&&D(e.$id)&&ne(e.items)}function Wo(e){return R(e,"BigInt")&&e.type==="bigint"&&D(e.$id)&&cr(e.exclusiveMaximum)&&cr(e.exclusiveMinimum)&&cr(e.maximum)&&cr(e.minimum)&&cr(e.multipleOf)}function Go(e){return R(e,"Boolean")&&e.type==="boolean"&&D(e.$id)}function Ho(e){return R(e,"Computed")&&j(e.target)&&Q(e.parameters)&&e.parameters.every(t=>ne(t))}function Vo(e){return R(e,"Constructor")&&e.type==="Constructor"&&D(e.$id)&&Q(e.parameters)&&e.parameters.every(t=>ne(t))&&ne(e.returns)}function qo(e){return R(e,"Date")&&e.type==="Date"&&D(e.$id)&&B(e.exclusiveMaximumTimestamp)&&B(e.exclusiveMinimumTimestamp)&&B(e.maximumTimestamp)&&B(e.minimumTimestamp)&&B(e.multipleOfTimestamp)}function zo(e){return R(e,"Function")&&e.type==="Function"&&D(e.$id)&&Q(e.parameters)&&e.parameters.every(t=>ne(t))&&ne(e.returns)}function Pu(e){return R(e,"Import")&&Tr(e,"$defs")&&U(e.$defs)&&Cr(e.$defs)&&Tr(e,"$ref")&&j(e.$ref)&&e.$ref in e.$defs}function Qo(e){return R(e,"Integer")&&e.type==="integer"&&D(e.$id)&&B(e.exclusiveMaximum)&&B(e.exclusiveMinimum)&&B(e.maximum)&&B(e.minimum)&&B(e.multipleOf)}function Cr(e){return U(e)&&Object.entries(e).every(([t,r])=>Bn(t)&&ne(r))}function Yo(e){return R(e,"Intersect")&&!(j(e.type)&&e.type!=="object")&&Q(e.allOf)&&e.allOf.every(t=>ne(t)&&!hs(t))&&D(e.type)&&(Wn(e.unevaluatedProperties)||Do(e.unevaluatedProperties))&&D(e.$id)}function Jo(e){return R(e,"Iterator")&&e.type==="Iterator"&&D(e.$id)&&ne(e.items)}function R(e,t){return U(e)&&h in e&&e[h]===t}function Xo(e){return dr(e)&&j(e.const)}function Zo(e){return dr(e)&&he(e.const)}function Tu(e){return dr(e)&&ze(e.const)}function dr(e){return R(e,"Literal")&&D(e.$id)&&es(e.const)}function es(e){return ze(e)||he(e)||j(e)}function ts(e){return R(e,"MappedKey")&&Q(e.keys)&&e.keys.every(t=>he(t)||j(t))}function rs(e){return R(e,"MappedResult")&&Cr(e.properties)}function ns(e){return R(e,"Never")&&U(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function os(e){return R(e,"Not")&&ne(e.not)}function ss(e){return R(e,"Null")&&e.type==="null"&&D(e.$id)}function is(e){return R(e,"Number")&&e.type==="number"&&D(e.$id)&&B(e.exclusiveMaximum)&&B(e.exclusiveMinimum)&&B(e.maximum)&&B(e.minimum)&&B(e.multipleOf)}function as(e){return R(e,"Object")&&e.type==="object"&&D(e.$id)&&Cr(e.properties)&&Uo(e.additionalProperties)&&B(e.minProperties)&&B(e.maxProperties)}function us(e){return R(e,"Promise")&&e.type==="Promise"&&D(e.$id)&&ne(e.item)}function cs(e){return R(e,"Record")&&e.type==="object"&&D(e.$id)&&Uo(e.additionalProperties)&&U(e.patternProperties)&&(t=>{let r=Object.getOwnPropertyNames(t.patternProperties);return r.length===1&&No(r[0])&&U(t.patternProperties)&&ne(t.patternProperties[r[0]])})(e)}function Au(e){return U(e)&&Pe in e&&e[Pe]==="Recursive"}function ds(e){return R(e,"Ref")&&D(e.$id)&&j(e.$ref)}function ls(e){return R(e,"RegExp")&&D(e.$id)&&j(e.source)&&j(e.flags)&&B(e.maxLength)&&B(e.minLength)}function ps(e){return R(e,"String")&&e.type==="string"&&D(e.$id)&&B(e.minLength)&&B(e.maxLength)&&Su(e.pattern)&&xu(e.format)}function ms(e){return R(e,"Symbol")&&e.type==="symbol"&&D(e.$id)}function fs(e){return R(e,"TemplateLiteral")&&e.type==="string"&&j(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function gs(e){return R(e,"This")&&D(e.$id)&&j(e.$ref)}function hs(e){return U(e)&&Z in e}function ys(e){return R(e,"Tuple")&&e.type==="array"&&D(e.$id)&&he(e.minItems)&&he(e.maxItems)&&e.minItems===e.maxItems&&(Y(e.items)&&Y(e.additionalItems)&&e.minItems===0||Q(e.items)&&e.items.every(t=>ne(t)))}function Is(e){return R(e,"Undefined")&&e.type==="undefined"&&D(e.$id)}function $u(e){return Gn(e)&&e.anyOf.every(t=>Xo(t)||Zo(t))}function Gn(e){return R(e,"Union")&&D(e.$id)&&U(e)&&Q(e.anyOf)&&e.anyOf.every(t=>ne(t))}function ws(e){return R(e,"Uint8Array")&&e.type==="Uint8Array"&&D(e.$id)&&B(e.minByteLength)&&B(e.maxByteLength)}function Ss(e){return R(e,"Unknown")&&D(e.$id)}function xs(e){return R(e,"Unsafe")}function bs(e){return R(e,"Void")&&e.type==="void"&&D(e.$id)}function ks(e){return U(e)&&h in e&&j(e[h])&&!wu.includes(e[h])}function ne(e){return U(e)&&(Lo(e)||Ko(e)||jo(e)||Go(e)||Wo(e)||Bo(e)||Ho(e)||Vo(e)||qo(e)||zo(e)||Qo(e)||Yo(e)||Jo(e)||dr(e)||ts(e)||rs(e)||ns(e)||os(e)||ss(e)||is(e)||as(e)||us(e)||cs(e)||ds(e)||ls(e)||ps(e)||ms(e)||fs(e)||gs(e)||ys(e)||Is(e)||Gn(e)||ws(e)||Ss(e)||xs(e)||bs(e)||ks(e))}var Hn="(true|false)",lr="(0|[1-9][0-9]*)",Vn="(.*)",Ru="(?!.*)",Eg=`^${Hn}$`,ot=`^${lr}$`,st=`^${Vn}$`,Ps=`^${Ru}$`;function Ts(e,t){return e.includes(t)}function As(e){return[...new Set(e)]}function Cu(e,t){return e.filter(r=>t.includes(r))}function Mu(e,t){return e.reduce((r,n)=>Cu(r,n),t)}function $s(e){return e.length===1?e[0]:e.length>1?Mu(e.slice(1),e[0]):[]}function Rs(e){let t=[];for(let r of e)t.push(...r);return t}function it(e){return l({[h]:"Any"},e)}function Ft(e,t){return l({[h]:"Array",type:"array",items:e},t)}function Cs(e){return l({[h]:"Argument",index:e})}function Nt(e,t){return l({[h]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function W(e,t,r){return l({[h]:"Computed",target:e,parameters:t},r)}function Ou(e,t){let{[t]:r,...n}=e;return n}function q(e,t){return t.reduce((r,n)=>Ou(r,n),e)}function O(e){return l({[h]:"Never",not:{}},e)}function v(e){return l({[h]:"MappedResult",properties:e})}function Ut(e,t,r){return l({[h]:"Constructor",type:"Constructor",parameters:e,returns:t},r)}function Ge(e,t,r){return l({[h]:"Function",type:"Function",parameters:e,returns:t},r)}function pr(e,t){return l({[h]:"Union",anyOf:e},t)}function Eu(e){return e.some(t=>pe(t))}function Ms(e){return e.map(t=>pe(t)?vu(t):t)}function vu(e){return q(e,[oe])}function _u(e,t){return Eu(e)?ae(pr(Ms(e),t)):pr(Ms(e),t)}function He(e,t){return e.length===1?l(e[0],t):e.length===0?O(t):_u(e,t)}function F(e,t){return e.length===0?O(t):e.length===1?l(e[0],t):pr(e,t)}var Mr=class extends re{};function Fu(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function qn(e,t,r){return e[t]===r&&e.charCodeAt(t-1)!==92}function Ze(e,t){return qn(e,t,"(")}function mr(e,t){return qn(e,t,")")}function Os(e,t){return qn(e,t,"|")}function Nu(e){if(!(Ze(e,0)&&mr(e,e.length-1)))return!1;let t=0;for(let r=0;r<e.length;r++)if(Ze(e,r)&&(t+=1),mr(e,r)&&(t-=1),t===0&&r!==e.length-1)return!1;return!0}function Uu(e){return e.slice(1,e.length-1)}function Du(e){let t=0;for(let r=0;r<e.length;r++)if(Ze(e,r)&&(t+=1),mr(e,r)&&(t-=1),Os(e,r)&&t===0)return!0;return!1}function Lu(e){for(let t=0;t<e.length;t++)if(Ze(e,t))return!0;return!1}function Ku(e){let[t,r]=[0,0],n=[];for(let s=0;s<e.length;s++)if(Ze(e,s)&&(t+=1),mr(e,s)&&(t-=1),Os(e,s)&&t===0){let i=e.slice(r,s);i.length>0&&n.push(Dt(i)),r=s+1}let o=e.slice(r);return o.length>0&&n.push(Dt(o)),n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"or",expr:n}}function ju(e){function t(o,s){if(!Ze(o,s))throw new Mr("TemplateLiteralParser: Index must point to open parens");let i=0;for(let a=s;a<o.length;a++)if(Ze(o,a)&&(i+=1),mr(o,a)&&(i-=1),i===0)return[s,a];throw new Mr("TemplateLiteralParser: Unclosed group parens in expression")}function r(o,s){for(let i=s;i<o.length;i++)if(Ze(o,i))return[s,i];return[s,o.length]}let n=[];for(let o=0;o<e.length;o++)if(Ze(e,o)){let[s,i]=t(e,o),a=e.slice(s,i+1);n.push(Dt(a)),o=i}else{let[s,i]=r(e,o),a=e.slice(s,i);a.length>0&&n.push(Dt(a)),o=i-1}return n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"and",expr:n}}function Dt(e){return Nu(e)?Dt(Uu(e)):Du(e)?Ku(e):Lu(e)?ju(e):{type:"const",const:Fu(e)}}function Lt(e){return Dt(e.slice(1,e.length-1))}var zn=class extends re{};function Bu(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 Wu(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 Gu(e){return e.type==="const"&&e.const===".*"}function Pt(e){return Bu(e)||Gu(e)?!1:Wu(e)?!0:e.type==="and"?e.expr.every(t=>Pt(t)):e.type==="or"?e.expr.every(t=>Pt(t)):e.type==="const"?!0:(()=>{throw new zn("Unknown expression type")})()}function Es(e){let t=Lt(e.pattern);return Pt(t)}var Qn=class extends re{};function*vs(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let r of vs(e.slice(1)))yield`${t}${r}`}function*Hu(e){return yield*vs(e.expr.map(t=>[...fr(t)]))}function*Vu(e){for(let t of e.expr)yield*fr(t)}function*qu(e){return yield e.const}function*fr(e){return e.type==="and"?yield*Hu(e):e.type==="or"?yield*Vu(e):e.type==="const"?yield*qu(e):(()=>{throw new Qn("Unknown expression")})()}function Or(e){let t=Lt(e.pattern);return Pt(t)?[...fr(t)]:[]}function _(e,t){return l({[h]:"Literal",const:e,type:typeof e},t)}function Er(e){return l({[h]:"Boolean",type:"boolean"},e)}function Kt(e){return l({[h]:"BigInt",type:"bigint"},e)}function Te(e){return l({[h]:"Number",type:"number"},e)}function Ue(e){return l({[h]:"String",type:"string"},e)}function*zu(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield Er():t==="number"?yield Te():t==="bigint"?yield Kt():t==="string"?yield Ue():yield(()=>{let r=t.split("|").map(n=>_(n.trim()));return r.length===0?O():r.length===1?r[0]:He(r)})()}function*Qu(e){if(e[1]!=="{"){let t=_("$"),r=Yn(e.slice(1));return yield*[t,...r]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let r=zu(e.slice(2,t)),n=Yn(e.slice(t+1));return yield*[...r,...n]}yield _(e)}function*Yn(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let r=_(e.slice(0,t)),n=Qu(e.slice(t));return yield*[r,...n]}yield _(e)}function _s(e){return[...Yn(e)]}var Jn=class extends re{};function Yu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fs(e,t){return we(e)?e.pattern.slice(1,e.pattern.length-1):M(e)?`(${e.anyOf.map(r=>Fs(r,t)).join("|")})`:Ne(e)?`${t}${lr}`:Fe(e)?`${t}${lr}`:St(e)?`${t}${lr}`:Je(e)?`${t}${Vn}`:ye(e)?`${t}${Yu(e.const.toString())}`:Ye(e)?`${t}${Hn}`:(()=>{throw new Jn(`Unexpected Kind '${e[h]}'`)})()}function Xn(e){return`^${e.map(t=>Fs(t,"")).join("")}$`}function Tt(e){let r=Or(e).map(n=>_(n));return He(r)}function vr(e,t){let r=j(e)?Xn(_s(e)):Xn(e);return l({[h]:"TemplateLiteral",type:"string",pattern:r},t)}function Ju(e){return Or(e).map(r=>r.toString())}function Xu(e){let t=[];for(let r of e)t.push(...me(r));return t}function Zu(e){return[e.toString()]}function me(e){return[...new Set(we(e)?Ju(e):M(e)?Xu(e.anyOf):ye(e)?Zu(e.const):Ne(e)?["[number]"]:Fe(e)?["[number]"]:[])]}function ec(e,t,r){let n={};for(let o of Object.getOwnPropertyNames(t))n[o]=at(e,me(t[o]),r);return n}function tc(e,t,r){return ec(e,t.properties,r)}function Ns(e,t,r){let n=tc(e,t,r);return v(n)}function Ds(e,t){return e.map(r=>Ls(r,t))}function rc(e){return e.filter(t=>!rt(t))}function nc(e,t){return _r(rc(Ds(e,t)))}function oc(e){return e.some(t=>rt(t))?[]:e}function sc(e,t){return He(oc(Ds(e,t)))}function ic(e,t){return t in e?e[t]:t==="[number]"?He(e):O()}function ac(e,t){return t==="[number]"?e:O()}function uc(e,t){return t in e?e[t]:O()}function Ls(e,t){return V(e)?nc(e.allOf,t):M(e)?sc(e.anyOf,t):Se(e)?ic(e.items??[],t):Oe(e)?ac(e.items,t):J(e)?uc(e.properties,t):O()}function Zn(e,t){return t.map(r=>Ls(e,r))}function Us(e,t){return He(Zn(e,t))}function at(e,t,r){if(z(e)||z(t)){let n="Index types using Ref parameters require both Type and Key to be of TSchema";if(!xe(e)||!xe(t))throw new re(n);return W("Index",[e,t])}return H(t)?Ns(e,t,r):Ie(t)?Ks(e,t,r):l(xe(t)?Us(e,me(t)):Us(e,t),r)}function cc(e,t,r){return{[t]:at(e,[t],G(r))}}function dc(e,t,r){return t.reduce((n,o)=>({...n,...cc(e,o,r)}),{})}function lc(e,t,r){return dc(e,t.keys,r)}function Ks(e,t,r){let n=lc(e,t,r);return v(n)}function jt(e,t){return l({[h]:"Iterator",type:"Iterator",items:e},t)}function pc(e){return globalThis.Object.keys(e).filter(t=>!pe(e[t]))}function mc(e,t){let r=pc(e),n=r.length>0?{[h]:"Object",type:"object",required:r,properties:e}:{[h]:"Object",type:"object",properties:e};return l(n,t)}var L=mc;function Fr(e,t){return l({[h]:"Promise",type:"Promise",item:e},t)}function fc(e){return l(q(e,[Me]))}function gc(e){return l({...e,[Me]:"Readonly"})}function hc(e,t){return t===!1?fc(e):gc(e)}function fe(e,t){let r=t??!0;return H(e)?js(e,r):hc(e,r)}function yc(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=fe(e[n],t);return r}function Ic(e,t){return yc(e.properties,t)}function js(e,t){let r=Ic(e,t);return v(r)}function Ae(e,t){return l(e.length>0?{[h]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[h]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function Bs(e,t){return e in t?$e(e,t[e]):v(t)}function wc(e){return{[e]:_(e)}}function Sc(e){let t={};for(let r of e)t[r]=_(r);return t}function xc(e,t){return Ts(t,e)?wc(e):Sc(t)}function bc(e,t){let r=xc(e,t);return Bs(e,r)}function gr(e,t){return t.map(r=>$e(e,r))}function kc(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=$e(e,t[n]);return r}function $e(e,t){let r={...t};return pe(t)?ae($e(e,q(t,[oe]))):_t(t)?fe($e(e,q(t,[Me]))):H(t)?Bs(e,t.properties):Ie(t)?bc(e,t.keys):ve(t)?Ut(gr(e,t.parameters),$e(e,t.returns),r):_e(t)?Ge(gr(e,t.parameters),$e(e,t.returns),r):wt(t)?Nt($e(e,t.items),r):xt(t)?jt($e(e,t.items),r):V(t)?ue(gr(e,t.allOf),r):M(t)?F(gr(e,t.anyOf),r):Se(t)?Ae(gr(e,t.items??[]),r):J(t)?L(kc(e,t.properties),r):Oe(t)?Ft($e(e,t.items),r):bt(t)?Fr($e(e,t.item),r):t}function Pc(e,t){let r={};for(let n of e)r[n]=$e(n,t);return r}function Ws(e,t,r){let n=xe(e)?me(e):e,o=t({[h]:"MappedKey",keys:n}),s=Pc(n,o);return L(s,r)}function Tc(e){return l(q(e,[oe]))}function Ac(e){return l({...e,[oe]:"Optional"})}function $c(e,t){return t===!1?Tc(e):Ac(e)}function ae(e,t){let r=t??!0;return H(e)?Gs(e,r):$c(e,r)}function Rc(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=ae(e[n],t);return r}function Cc(e,t){return Rc(e.properties,t)}function Gs(e,t){let r=Cc(e,t);return v(r)}function hr(e,t={}){let r=e.every(o=>J(o)),n=xe(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return l(t.unevaluatedProperties===!1||xe(t.unevaluatedProperties)||r?{...n,[h]:"Intersect",type:"object",allOf:e}:{...n,[h]:"Intersect",allOf:e},t)}function Mc(e){return e.every(t=>pe(t))}function Oc(e){return q(e,[oe])}function Hs(e){return e.map(t=>pe(t)?Oc(t):t)}function Ec(e,t){return Mc(e)?ae(hr(Hs(e),t)):hr(Hs(e),t)}function _r(e,t={}){if(e.length===1)return l(e[0],t);if(e.length===0)return O(t);if(e.some(r=>nt(r)))throw new Error("Cannot intersect transform types");return Ec(e,t)}function ue(e,t){if(e.length===1)return l(e[0],t);if(e.length===0)return O(t);if(e.some(r=>nt(r)))throw new Error("Cannot intersect transform types");return hr(e,t)}function Ve(...e){let[t,r]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new re("Ref: $ref must be a string");return l({[h]:"Ref",$ref:t},r)}function vc(e,t){return W("Awaited",[W(e,t)])}function _c(e){return W("Awaited",[Ve(e)])}function Fc(e){return ue(Vs(e))}function Nc(e){return F(Vs(e))}function Uc(e){return Bt(e)}function Vs(e){return e.map(t=>Bt(t))}function Bt(e,t){return l(Ee(e)?vc(e.target,e.parameters):V(e)?Fc(e.allOf):M(e)?Nc(e.anyOf):bt(e)?Uc(e.item):z(e)?_c(e.$ref):e,t)}function qs(e){let t=[];for(let r of e)t.push(yr(r));return t}function Dc(e){let t=qs(e);return Rs(t)}function Lc(e){let t=qs(e);return $s(t)}function Kc(e){return e.map((t,r)=>r.toString())}function jc(e){return["[number]"]}function Bc(e){return globalThis.Object.getOwnPropertyNames(e)}function Wc(e){return Gc?globalThis.Object.getOwnPropertyNames(e).map(r=>r[0]==="^"&&r[r.length-1]==="$"?r.slice(1,r.length-1):r):[]}function yr(e){return V(e)?Dc(e.allOf):M(e)?Lc(e.anyOf):Se(e)?Kc(e.items??[]):Oe(e)?jc(e.items):J(e)?Bc(e.properties):kt(e)?Wc(e.patternProperties):[]}var Gc=!1;function Hc(e,t){return W("KeyOf",[W(e,t)])}function Vc(e){return W("KeyOf",[Ve(e)])}function qc(e,t){let r=yr(e),n=zc(r),o=He(n);return l(o,t)}function zc(e){return e.map(t=>t==="[number]"?Te():_(t))}function Wt(e,t){return Ee(e)?Hc(e.target,e.parameters):z(e)?Vc(e.$ref):H(e)?zs(e,t):qc(e,t)}function Qc(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Wt(e[n],G(t));return r}function Yc(e,t){return Qc(e.properties,t)}function zs(e,t){let r=Yc(e,t);return v(r)}function Jc(e){let t=[];for(let r of e)t.push(...yr(r));return As(t)}function Xc(e){return e.filter(t=>!rt(t))}function Zc(e,t){let r=[];for(let n of e)r.push(...Zn(n,[t]));return Xc(r)}function ed(e,t){let r={};for(let n of t)r[n]=_r(Zc(e,n));return r}function Qs(e,t){let r=Jc(e),n=ed(e,r);return L(n,t)}function Nr(e){return l({[h]:"Date",type:"Date"},e)}function Ur(e){return l({[h]:"Null",type:"null"},e)}function Dr(e){return l({[h]:"Symbol",type:"symbol"},e)}function Lr(e){return l({[h]:"Undefined",type:"undefined"},e)}function Kr(e){return l({[h]:"Uint8Array",type:"Uint8Array"},e)}function ut(e){return l({[h]:"Unknown"},e)}function td(e){return e.map(t=>eo(t,!1))}function rd(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=fe(eo(e[r],!1));return t}function jr(e,t){return t===!0?e:fe(e)}function eo(e,t){return vn(e)?jr(it(),t):Fn(e)?jr(it(),t):Q(e)?fe(Ae(td(e))):Qe(e)?Kr():It(e)?Nr():U(e)?jr(L(rd(e)),t):_n(e)?jr(Ge([],ut()),t):Y(e)?Lr():Nn(e)?Ur():Un(e)?Dr():nr(e)?Kt():he(e)?_(e):ze(e)?_(e):j(e)?_(e):L({})}function Ys(e,t){return l(eo(e,!0),t)}function Js(e,t){return ve(e)?Ae(e.parameters,t):O(t)}function Xs(e,t){if(Y(e))throw new Error("Enum undefined or empty");let r=globalThis.Object.getOwnPropertyNames(e).filter(s=>isNaN(s)).map(s=>e[s]),o=[...new Set(r)].map(s=>_(s));return F(o,{...t,[Pe]:"Enum"})}var ro=class extends re{},p;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(p||(p={}));function Re(e){return e===p.False?e:p.True}function Gt(e){throw new ro(e)}function ee(e){return u.IsNever(e)||u.IsIntersect(e)||u.IsUnion(e)||u.IsUnknown(e)||u.IsAny(e)}function te(e,t){return u.IsNever(t)?si(e,t):u.IsIntersect(t)?Br(e,t):u.IsUnion(t)?io(e,t):u.IsUnknown(t)?ci(e,t):u.IsAny(t)?so(e,t):Gt("StructuralRight")}function so(e,t){return p.True}function nd(e,t){return u.IsIntersect(t)?Br(e,t):u.IsUnion(t)&&t.anyOf.some(r=>u.IsAny(r)||u.IsUnknown(r))?p.True:u.IsUnion(t)?p.Union:u.IsUnknown(t)||u.IsAny(t)?p.True:p.Union}function od(e,t){return u.IsUnknown(e)?p.False:u.IsAny(e)?p.Union:u.IsNever(e)?p.True:p.False}function sd(e,t){return u.IsObject(t)&&Wr(t)?p.True:ee(t)?te(e,t):u.IsArray(t)?Re(K(e.items,t.items)):p.False}function id(e,t){return ee(t)?te(e,t):u.IsAsyncIterator(t)?Re(K(e.items,t.items)):p.False}function ad(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsBigInt(t)?p.True:p.False}function ni(e,t){return u.IsLiteralBoolean(e)||u.IsBoolean(e)?p.True:p.False}function ud(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsBoolean(t)?p.True:p.False}function cd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsConstructor(t)?e.parameters.length>t.parameters.length?p.False:e.parameters.every((r,n)=>Re(K(t.parameters[n],r))===p.True)?Re(K(e.returns,t.returns)):p.False:p.False}function dd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsDate(t)?p.True:p.False}function ld(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsFunction(t)?e.parameters.length>t.parameters.length?p.False:e.parameters.every((r,n)=>Re(K(t.parameters[n],r))===p.True)?Re(K(e.returns,t.returns)):p.False:p.False}function oi(e,t){return u.IsLiteral(e)&&ie.IsNumber(e.const)||u.IsNumber(e)||u.IsInteger(e)?p.True:p.False}function pd(e,t){return u.IsInteger(t)||u.IsNumber(t)?p.True:ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):p.False}function Br(e,t){return t.allOf.every(r=>K(e,r)===p.True)?p.True:p.False}function md(e,t){return e.allOf.some(r=>K(r,t)===p.True)?p.True:p.False}function fd(e,t){return ee(t)?te(e,t):u.IsIterator(t)?Re(K(e.items,t.items)):p.False}function gd(e,t){return u.IsLiteral(t)&&t.const===e.const?p.True:ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsString(t)?ui(e,t):u.IsNumber(t)?ii(e,t):u.IsInteger(t)?oi(e,t):u.IsBoolean(t)?ni(e,t):p.False}function si(e,t){return p.False}function hd(e,t){return p.True}function Zs(e){let[t,r]=[e,0];for(;u.IsNot(t);)t=t.not,r+=1;return r%2===0?t:ut()}function yd(e,t){return u.IsNot(e)?K(Zs(e),t):u.IsNot(t)?K(e,Zs(t)):Gt("Invalid fallthrough for Not")}function Id(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsNull(t)?p.True:p.False}function ii(e,t){return u.IsLiteralNumber(e)||u.IsNumber(e)||u.IsInteger(e)?p.True:p.False}function wd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsInteger(t)||u.IsNumber(t)?p.True:p.False}function ge(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function ei(e){return Wr(e)}function ti(e){return ge(e,0)||ge(e,1)&&"description"in e.properties&&u.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(u.IsString(e.properties.description.anyOf[0])&&u.IsUndefined(e.properties.description.anyOf[1])||u.IsString(e.properties.description.anyOf[1])&&u.IsUndefined(e.properties.description.anyOf[0]))}function to(e){return ge(e,0)}function ri(e){return ge(e,0)}function Sd(e){return ge(e,0)}function xd(e){return ge(e,0)}function bd(e){return Wr(e)}function kd(e){let t=Te();return ge(e,0)||ge(e,1)&&"length"in e.properties&&Re(K(e.properties.length,t))===p.True}function Pd(e){return ge(e,0)}function Wr(e){let t=Te();return ge(e,0)||ge(e,1)&&"length"in e.properties&&Re(K(e.properties.length,t))===p.True}function Td(e){let t=Ge([it()],it());return ge(e,0)||ge(e,1)&&"then"in e.properties&&Re(K(e.properties.then,t))===p.True}function ai(e,t){return K(e,t)===p.False||u.IsOptional(e)&&!u.IsOptional(t)?p.False:p.True}function ce(e,t){return u.IsUnknown(e)?p.False:u.IsAny(e)?p.Union:u.IsNever(e)||u.IsLiteralString(e)&&ei(t)||u.IsLiteralNumber(e)&&to(t)||u.IsLiteralBoolean(e)&&ri(t)||u.IsSymbol(e)&&ti(t)||u.IsBigInt(e)&&Sd(t)||u.IsString(e)&&ei(t)||u.IsSymbol(e)&&ti(t)||u.IsNumber(e)&&to(t)||u.IsInteger(e)&&to(t)||u.IsBoolean(e)&&ri(t)||u.IsUint8Array(e)&&bd(t)||u.IsDate(e)&&xd(t)||u.IsConstructor(e)&&Pd(t)||u.IsFunction(e)&&kd(t)?p.True:u.IsRecord(e)&&u.IsString(no(e))?t[Pe]==="Record"?p.True:p.False:u.IsRecord(e)&&u.IsNumber(no(e))&&ge(t,0)?p.True:p.False}function Ad(e,t){return ee(t)?te(e,t):u.IsRecord(t)?Ce(e,t):u.IsObject(t)?(()=>{for(let r of Object.getOwnPropertyNames(t.properties)){if(!(r in e.properties)&&!u.IsOptional(t.properties[r]))return p.False;if(u.IsOptional(t.properties[r]))return p.True;if(ai(e.properties[r],t.properties[r])===p.False)return p.False}return p.True})():p.False}function $d(e,t){return ee(t)?te(e,t):u.IsObject(t)&&Td(t)?p.True:u.IsPromise(t)?Re(K(e.item,t.item)):p.False}function no(e){return ot in e.patternProperties?Te():st in e.patternProperties?Ue():Gt("Unknown record key pattern")}function oo(e){return ot in e.patternProperties?e.patternProperties[ot]:st in e.patternProperties?e.patternProperties[st]:Gt("Unable to get record value schema")}function Ce(e,t){let[r,n]=[no(t),oo(t)];return u.IsLiteralString(e)&&u.IsNumber(r)&&Re(K(e,n))===p.True?p.True:u.IsUint8Array(e)&&u.IsNumber(r)||u.IsString(e)&&u.IsNumber(r)||u.IsArray(e)&&u.IsNumber(r)?K(e,n):u.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(ai(n,e.properties[o])===p.False)return p.False;return p.True})():p.False}function Rd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?K(oo(e),oo(t)):p.False}function Cd(e,t){let r=u.IsRegExp(e)?Ue():e,n=u.IsRegExp(t)?Ue():t;return K(r,n)}function ui(e,t){return u.IsLiteral(e)&&ie.IsString(e.const)||u.IsString(e)?p.True:p.False}function Md(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsString(t)?p.True:p.False}function Od(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsSymbol(t)?p.True:p.False}function Ed(e,t){return u.IsTemplateLiteral(e)?K(Tt(e),t):u.IsTemplateLiteral(t)?K(e,Tt(t)):Gt("Invalid fallthrough for TemplateLiteral")}function vd(e,t){return u.IsArray(t)&&e.items!==void 0&&e.items.every(r=>K(r,t.items)===p.True)}function _d(e,t){return u.IsNever(e)?p.True:u.IsUnknown(e)?p.False:u.IsAny(e)?p.Union:p.False}function Fd(e,t){return ee(t)?te(e,t):u.IsObject(t)&&Wr(t)||u.IsArray(t)&&vd(e,t)?p.True:u.IsTuple(t)?ie.IsUndefined(e.items)&&!ie.IsUndefined(t.items)||!ie.IsUndefined(e.items)&&ie.IsUndefined(t.items)?p.False:ie.IsUndefined(e.items)&&!ie.IsUndefined(t.items)||e.items.every((r,n)=>K(r,t.items[n])===p.True)?p.True:p.False:p.False}function Nd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsUint8Array(t)?p.True:p.False}function Ud(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsVoid(t)?Kd(e,t):u.IsUndefined(t)?p.True:p.False}function io(e,t){return t.anyOf.some(r=>K(e,r)===p.True)?p.True:p.False}function Dd(e,t){return e.anyOf.every(r=>K(r,t)===p.True)?p.True:p.False}function ci(e,t){return p.True}function Ld(e,t){return u.IsNever(t)?si(e,t):u.IsIntersect(t)?Br(e,t):u.IsUnion(t)?io(e,t):u.IsAny(t)?so(e,t):u.IsString(t)?ui(e,t):u.IsNumber(t)?ii(e,t):u.IsInteger(t)?oi(e,t):u.IsBoolean(t)?ni(e,t):u.IsArray(t)?od(e,t):u.IsTuple(t)?_d(e,t):u.IsObject(t)?ce(e,t):u.IsUnknown(t)?p.True:p.False}function Kd(e,t){return u.IsUndefined(e)||u.IsUndefined(e)?p.True:p.False}function jd(e,t){return u.IsIntersect(t)?Br(e,t):u.IsUnion(t)?io(e,t):u.IsUnknown(t)?ci(e,t):u.IsAny(t)?so(e,t):u.IsObject(t)?ce(e,t):u.IsVoid(t)?p.True:p.False}function K(e,t){return u.IsTemplateLiteral(e)||u.IsTemplateLiteral(t)?Ed(e,t):u.IsRegExp(e)||u.IsRegExp(t)?Cd(e,t):u.IsNot(e)||u.IsNot(t)?yd(e,t):u.IsAny(e)?nd(e,t):u.IsArray(e)?sd(e,t):u.IsBigInt(e)?ad(e,t):u.IsBoolean(e)?ud(e,t):u.IsAsyncIterator(e)?id(e,t):u.IsConstructor(e)?cd(e,t):u.IsDate(e)?dd(e,t):u.IsFunction(e)?ld(e,t):u.IsInteger(e)?pd(e,t):u.IsIntersect(e)?md(e,t):u.IsIterator(e)?fd(e,t):u.IsLiteral(e)?gd(e,t):u.IsNever(e)?hd(e,t):u.IsNull(e)?Id(e,t):u.IsNumber(e)?wd(e,t):u.IsObject(e)?Ad(e,t):u.IsRecord(e)?Rd(e,t):u.IsString(e)?Md(e,t):u.IsSymbol(e)?Od(e,t):u.IsTuple(e)?Fd(e,t):u.IsPromise(e)?$d(e,t):u.IsUint8Array(e)?Nd(e,t):u.IsUndefined(e)?Ud(e,t):u.IsUnion(e)?Dd(e,t):u.IsUnknown(e)?Ld(e,t):u.IsVoid(e)?jd(e,t):Gt(`Unknown left type operand '${e[h]}'`)}function ct(e,t){return K(e,t)}function Bd(e,t,r,n,o){let s={};for(let i of globalThis.Object.getOwnPropertyNames(e))s[i]=Ht(e[i],t,r,n,G(o));return s}function Wd(e,t,r,n,o){return Bd(e.properties,t,r,n,o)}function di(e,t,r,n,o){let s=Wd(e,t,r,n,o);return v(s)}function Gd(e,t,r,n){let o=ct(e,t);return o===p.Union?F([r,n]):o===p.True?r:n}function Ht(e,t,r,n,o){return H(e)?di(e,t,r,n,o):Ie(e)?l(li(e,t,r,n,o)):l(Gd(e,t,r,n),o)}function Hd(e,t,r,n,o){return{[e]:Ht(_(e),t,r,n,G(o))}}function Vd(e,t,r,n,o){return e.reduce((s,i)=>({...s,...Hd(i,t,r,n,o)}),{})}function qd(e,t,r,n,o){return Vd(e.keys,t,r,n,o)}function li(e,t,r,n,o){let s=qd(e,t,r,n,o);return v(s)}function pi(e,t){return Vt(Tt(e),t)}function zd(e,t){let r=e.filter(n=>ct(n,t)===p.False);return r.length===1?r[0]:F(r)}function Vt(e,t,r={}){return we(e)?l(pi(e,t),r):H(e)?l(mi(e,t),r):l(M(e)?zd(e.anyOf,t):ct(e,t)!==p.False?O():e,r)}function Qd(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Vt(e[n],t);return r}function Yd(e,t){return Qd(e.properties,t)}function mi(e,t){let r=Yd(e,t);return v(r)}function fi(e,t){return qt(Tt(e),t)}function Jd(e,t){let r=e.filter(n=>ct(n,t)!==p.False);return r.length===1?r[0]:F(r)}function qt(e,t,r){return we(e)?l(fi(e,t),r):H(e)?l(gi(e,t),r):l(M(e)?Jd(e.anyOf,t):ct(e,t)!==p.False?e:O(),r)}function Xd(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=qt(e[n],t);return r}function Zd(e,t){return Xd(e.properties,t)}function gi(e,t){let r=Zd(e,t);return v(r)}function hi(e,t){return ve(e)?l(e.returns,t):O(t)}function Gr(e){return fe(ae(e))}function At(e,t,r){return l({[h]:"Record",type:"object",patternProperties:{[e]:t}},r)}function ao(e,t,r){let n={};for(let o of e)n[o]=t;return L(n,{...r,[Pe]:"Record"})}function el(e,t,r){return Es(e)?ao(me(e),t,r):At(e.pattern,t,r)}function tl(e,t,r){return ao(me(F(e)),t,r)}function rl(e,t,r){return ao([e.toString()],t,r)}function nl(e,t,r){return At(e.source,t,r)}function ol(e,t,r){let n=Y(e.pattern)?st:e.pattern;return At(n,t,r)}function sl(e,t,r){return At(st,t,r)}function il(e,t,r){return At(Ps,t,r)}function al(e,t,r){return L({true:t,false:t},r)}function ul(e,t,r){return At(ot,t,r)}function cl(e,t,r){return At(ot,t,r)}function Hr(e,t,r={}){return M(e)?tl(e.anyOf,t,r):we(e)?el(e,t,r):ye(e)?rl(e.const,t,r):Ye(e)?al(e,t,r):Fe(e)?ul(e,t,r):Ne(e)?cl(e,t,r):Kn(e)?nl(e,t,r):Je(e)?ol(e,t,r):Dn(e)?sl(e,t,r):rt(e)?il(e,t,r):O(r)}function Vr(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function yi(e){let t=Vr(e);return t===st?Ue():t===ot?Te():Ue({pattern:t})}function qr(e){return e.patternProperties[Vr(e)]}function dl(e,t){return t.parameters=Ir(e,t.parameters),t.returns=De(e,t.returns),t}function ll(e,t){return t.parameters=Ir(e,t.parameters),t.returns=De(e,t.returns),t}function pl(e,t){return t.allOf=Ir(e,t.allOf),t}function ml(e,t){return t.anyOf=Ir(e,t.anyOf),t}function fl(e,t){return Y(t.items)||(t.items=Ir(e,t.items)),t}function gl(e,t){return t.items=De(e,t.items),t}function hl(e,t){return t.items=De(e,t.items),t}function yl(e,t){return t.items=De(e,t.items),t}function Il(e,t){return t.item=De(e,t.item),t}function wl(e,t){let r=kl(e,t.properties);return{...t,...L(r)}}function Sl(e,t){let r=De(e,yi(t)),n=De(e,qr(t)),o=Hr(r,n);return{...t,...o}}function xl(e,t){return t.index in e?e[t.index]:ut()}function bl(e,t){let r=_t(t),n=pe(t),o=De(e,t);return r&&n?Gr(o):r&&!n?fe(o):!r&&n?ae(o):o}function kl(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:bl(e,t[n])}),{})}function Ir(e,t){return t.map(r=>De(e,r))}function De(e,t){return ve(t)?dl(e,t):_e(t)?ll(e,t):V(t)?pl(e,t):M(t)?ml(e,t):Se(t)?fl(e,t):Oe(t)?gl(e,t):wt(t)?hl(e,t):xt(t)?yl(e,t):bt(t)?Il(e,t):J(t)?wl(e,t):kt(t)?Sl(e,t):Ln(t)?xl(e,t):t}function Ii(e,t){return De(t,vt(e))}function wi(e){return l({[h]:"Integer",type:"integer"},e)}function Pl(e,t,r){return{[e]:Le(_(e),t,G(r))}}function Tl(e,t,r){return e.reduce((o,s)=>({...o,...Pl(s,t,r)}),{})}function Al(e,t,r){return Tl(e.keys,t,r)}function Si(e,t,r){let n=Al(e,t,r);return v(n)}function $l(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),r].join("")}function Rl(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),r].join("")}function Cl(e){return e.toUpperCase()}function Ml(e){return e.toLowerCase()}function Ol(e,t,r){let n=Lt(e.pattern);if(!Pt(n))return{...e,pattern:xi(e.pattern,t)};let i=[...fr(n)].map(m=>_(m)),a=bi(i,t),d=F(a);return vr([d],r)}function xi(e,t){return typeof e=="string"?t==="Uncapitalize"?$l(e):t==="Capitalize"?Rl(e):t==="Uppercase"?Cl(e):t==="Lowercase"?Ml(e):e:e.toString()}function bi(e,t){return e.map(r=>Le(r,t))}function Le(e,t,r={}){return Ie(e)?Si(e,t,r):we(e)?Ol(e,t,r):M(e)?F(bi(e.anyOf,t),r):ye(e)?_(xi(e.const,t),r):l(e,r)}function ki(e,t={}){return Le(e,"Capitalize",t)}function Pi(e,t={}){return Le(e,"Lowercase",t)}function Ti(e,t={}){return Le(e,"Uncapitalize",t)}function Ai(e,t={}){return Le(e,"Uppercase",t)}function El(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=dt(e[o],t,G(r));return n}function vl(e,t,r){return El(e.properties,t,r)}function $i(e,t,r){let n=vl(e,t,r);return v(n)}function _l(e,t){return e.map(r=>uo(r,t))}function Fl(e,t){return e.map(r=>uo(r,t))}function Nl(e,t){let{[t]:r,...n}=e;return n}function Ul(e,t){return t.reduce((r,n)=>Nl(r,n),e)}function Dl(e,t,r){let n=q(e,[Z,"$id","required","properties"]),o=Ul(r,t);return L(o,n)}function Ll(e){let t=e.reduce((r,n)=>Rr(n)?[...r,_(n)]:r,[]);return F(t)}function uo(e,t){return V(e)?ue(_l(e.allOf,t)):M(e)?F(Fl(e.anyOf,t)):J(e)?Dl(e,t,e.properties):L({})}function dt(e,t,r){let n=Q(t)?Ll(t):t,o=xe(t)?me(t):t,s=z(e),i=z(t);return H(e)?$i(e,o,r):Ie(t)?Ri(e,t,r):s&&i?W("Omit",[e,n],r):!s&&i?W("Omit",[e,n],r):s&&!i?W("Omit",[e,n],r):l({...uo(e,o),...r})}function Kl(e,t,r){return{[t]:dt(e,[t],G(r))}}function jl(e,t,r){return t.reduce((n,o)=>({...n,...Kl(e,o,r)}),{})}function Bl(e,t,r){return jl(e,t.keys,r)}function Ri(e,t,r){let n=Bl(e,t,r);return v(n)}function Wl(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=lt(e[o],t,G(r));return n}function Gl(e,t,r){return Wl(e.properties,t,r)}function Ci(e,t,r){let n=Gl(e,t,r);return v(n)}function Hl(e,t){return e.map(r=>co(r,t))}function Vl(e,t){return e.map(r=>co(r,t))}function ql(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function zl(e,t,r){let n=q(e,[Z,"$id","required","properties"]),o=ql(r,t);return L(o,n)}function Ql(e){let t=e.reduce((r,n)=>Rr(n)?[...r,_(n)]:r,[]);return F(t)}function co(e,t){return V(e)?ue(Hl(e.allOf,t)):M(e)?F(Vl(e.anyOf,t)):J(e)?zl(e,t,e.properties):L({})}function lt(e,t,r){let n=Q(t)?Ql(t):t,o=xe(t)?me(t):t,s=z(e),i=z(t);return H(e)?Ci(e,o,r):Ie(t)?Mi(e,t,r):s&&i?W("Pick",[e,n],r):!s&&i?W("Pick",[e,n],r):s&&!i?W("Pick",[e,n],r):l({...co(e,o),...r})}function Yl(e,t,r){return{[t]:lt(e,[t],G(r))}}function Jl(e,t,r){return t.reduce((n,o)=>({...n,...Yl(e,o,r)}),{})}function Xl(e,t,r){return Jl(e,t.keys,r)}function Mi(e,t,r){let n=Xl(e,t,r);return v(n)}function Zl(e,t){return W("Partial",[W(e,t)])}function ep(e){return W("Partial",[Ve(e)])}function tp(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=ae(e[r]);return t}function rp(e,t){let r=q(e,[Z,"$id","required","properties"]),n=tp(t);return L(n,r)}function Oi(e){return e.map(t=>Ei(t))}function Ei(e){return Ee(e)?Zl(e.target,e.parameters):z(e)?ep(e.$ref):V(e)?ue(Oi(e.allOf)):M(e)?F(Oi(e.anyOf)):J(e)?rp(e,e.properties):St(e)||Ye(e)||Fe(e)||ye(e)||ir(e)||Ne(e)||Je(e)||ar(e)||ur(e)?e:L({})}function zt(e,t){return H(e)?vi(e,t):l({...Ei(e),...t})}function np(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=zt(e[n],G(t));return r}function op(e,t){return np(e.properties,t)}function vi(e,t){let r=op(e,t);return v(r)}function sp(e,t){return W("Required",[W(e,t)])}function ip(e){return W("Required",[Ve(e)])}function ap(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=q(e[r],[oe]);return t}function up(e,t){let r=q(e,[Z,"$id","required","properties"]),n=ap(t);return L(n,r)}function _i(e){return e.map(t=>Fi(t))}function Fi(e){return Ee(e)?sp(e.target,e.parameters):z(e)?ip(e.$ref):V(e)?ue(_i(e.allOf)):M(e)?F(_i(e.anyOf)):J(e)?up(e,e.properties):St(e)||Ye(e)||Fe(e)||ye(e)||ir(e)||Ne(e)||Je(e)||ar(e)||ur(e)?e:L({})}function Qt(e,t){return H(e)?Ni(e,t):l({...Fi(e),...t})}function cp(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Qt(e[n],t);return r}function dp(e,t){return cp(e.properties,t)}function Ni(e,t){let r=dp(e,t);return v(r)}function lp(e,t){return t.map(r=>z(r)?lo(e,r.$ref):be(e,r))}function lo(e,t){return t in e?z(e[t])?lo(e,e[t].$ref):be(e,e[t]):O()}function pp(e){return Bt(e[0])}function mp(e){return at(e[0],e[1])}function fp(e){return Wt(e[0])}function gp(e){return zt(e[0])}function hp(e){return dt(e[0],e[1])}function yp(e){return lt(e[0],e[1])}function Ip(e){return Qt(e[0])}function wp(e,t,r){let n=lp(e,r);return t==="Awaited"?pp(n):t==="Index"?mp(n):t==="KeyOf"?fp(n):t==="Partial"?gp(n):t==="Omit"?hp(n):t==="Pick"?yp(n):t==="Required"?Ip(n):O()}function Sp(e,t){return Ft(be(e,t))}function xp(e,t){return Nt(be(e,t))}function bp(e,t,r){return Ut(wr(e,t),be(e,r))}function kp(e,t,r){return Ge(wr(e,t),be(e,r))}function Pp(e,t){return ue(wr(e,t))}function Tp(e,t){return jt(be(e,t))}function Ap(e,t){return L(globalThis.Object.keys(t).reduce((r,n)=>({...r,[n]:be(e,t[n])}),{}))}function $p(e,t){let[r,n]=[be(e,qr(t)),Vr(t)],o=vt(t);return o.patternProperties[n]=r,o}function Rp(e,t){return z(t)?{...lo(e,t.$ref),[Z]:t[Z]}:t}function Cp(e,t){return Ae(wr(e,t))}function Mp(e,t){return F(wr(e,t))}function wr(e,t){return t.map(r=>be(e,r))}function be(e,t){return pe(t)?l(be(e,q(t,[oe])),t):_t(t)?l(be(e,q(t,[Me])),t):nt(t)?l(Rp(e,t),t):Oe(t)?l(Sp(e,t.items),t):wt(t)?l(xp(e,t.items),t):Ee(t)?l(wp(e,t.target,t.parameters)):ve(t)?l(bp(e,t.parameters,t.returns),t):_e(t)?l(kp(e,t.parameters,t.returns),t):V(t)?l(Pp(e,t.allOf),t):xt(t)?l(Tp(e,t.items),t):J(t)?l(Ap(e,t.properties),t):kt(t)?l($p(e,t)):Se(t)?l(Cp(e,t.items||[]),t):M(t)?l(Mp(e,t.anyOf),t):t}function Op(e,t){return t in e?be(e,e[t]):O()}function Ui(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,r)=>({...t,[r]:Op(e,r)}),{})}var po=class{constructor(t){let r=Ui(t),n=this.WithIdentifiers(r);this.$defs=n}Import(t,r){let n={...this.$defs,[t]:l(this.$defs[t],r)};return l({[h]:"Import",$defs:n,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:{...t[n],$id:n}}),{})}};function Di(e){return new po(e)}function Li(e,t){return l({[h]:"Not",not:e},t)}function Ki(e,t){return _e(e)?Ae(e.parameters,t):O()}var Ep=0;function ji(e,t={}){Y(t.$id)&&(t.$id=`T${Ep++}`);let r=vt(e({[h]:"This",$ref:`${t.$id}`}));return r.$id=t.$id,l({[Pe]:"Recursive",...r},t)}function Bi(e,t){let r=j(e)?new globalThis.RegExp(e):e;return l({[h]:"RegExp",type:"RegExp",source:r.source,flags:r.flags},t)}function vp(e){return V(e)?e.allOf:M(e)?e.anyOf:Se(e)?e.items??[]:[]}function Wi(e){return vp(e)}function Gi(e,t){return _e(e)?l(e.returns,t):O(t)}var mo=class{constructor(t){this.schema=t}Decode(t){return new fo(this.schema,t)}},fo=class{constructor(t,r){this.schema=t,this.decode=r}EncodeTransform(t,r){let s={Encode:i=>r[Z].Encode(t(i)),Decode:i=>this.decode(r[Z].Decode(i))};return{...r,[Z]:s}}EncodeSchema(t,r){let n={Decode:this.decode,Encode:t};return{...r,[Z]:n}}Encode(t){return nt(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function Hi(e){return new mo(e)}function Vi(e={}){return l({[h]:e[h]??"Unsafe"},e)}function qi(e){return l({[h]:"Void",type:"void"},e)}var go={};En(go,{Any:()=>it,Argument:()=>Cs,Array:()=>Ft,AsyncIterator:()=>Nt,Awaited:()=>Bt,BigInt:()=>Kt,Boolean:()=>Er,Capitalize:()=>ki,Composite:()=>Qs,Const:()=>Ys,Constructor:()=>Ut,ConstructorParameters:()=>Js,Date:()=>Nr,Enum:()=>Xs,Exclude:()=>Vt,Extends:()=>Ht,Extract:()=>qt,Function:()=>Ge,Index:()=>at,InstanceType:()=>hi,Instantiate:()=>Ii,Integer:()=>wi,Intersect:()=>ue,Iterator:()=>jt,KeyOf:()=>Wt,Literal:()=>_,Lowercase:()=>Pi,Mapped:()=>Ws,Module:()=>Di,Never:()=>O,Not:()=>Li,Null:()=>Ur,Number:()=>Te,Object:()=>L,Omit:()=>dt,Optional:()=>ae,Parameters:()=>Ki,Partial:()=>zt,Pick:()=>lt,Promise:()=>Fr,Readonly:()=>fe,ReadonlyOptional:()=>Gr,Record:()=>Hr,Recursive:()=>ji,Ref:()=>Ve,RegExp:()=>Bi,Required:()=>Qt,Rest:()=>Wi,ReturnType:()=>Gi,String:()=>Ue,Symbol:()=>Dr,TemplateLiteral:()=>vr,Transform:()=>Hi,Tuple:()=>Ae,Uint8Array:()=>Kr,Uncapitalize:()=>Ti,Undefined:()=>Lr,Union:()=>F,Unknown:()=>ut,Unsafe:()=>Vi,Uppercase:()=>Ai,Void:()=>qi});var g=go;var I=null;function ho(e){I=e}import{readFileSync as _p}from"fs";import{homedir as Fp}from"os";import{join as Np}from"path";var Sr,zi="claude-code",zr={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium",approvalPolicy:"on-request"}};function Qi(){if(Sr!==void 0)return Sr;try{let e=_p(Np(Fp(),".claude.json"),"utf-8");Sr=JSON.parse(e).mcpServers??{}}catch{Sr={}}return Sr}var N={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"ask",codexApprovalPolicy:"on-request",harnesses:{"claude-code":{...zr["claude-code"]},codex:{...zr.codex}}};function Yi(e){let t=e.defaultHarness??zi,r={};for(let[n,o]of Object.entries(zr))r[n]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[n,o]of Object.entries(e.harnesses??{})){let i={...r[n]??{},...o};o.allowedModels!==void 0?i.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(i.allowedModels=void 0),r[n]=i}if(e.defaultModel!==void 0){let n=r[t]??{};r[t]={...n,defaultModel:e.harnesses?.[t]?.defaultModel??e.defaultModel,allowedModels:e.harnesses?.[t]?.allowedModels!==void 0?n.allowedModels:e.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${t}.defaultModel instead.`)}if(e.model!==void 0){let n=r.codex??{};r.codex={...n,defaultModel:e.harnesses?.codex?.defaultModel??e.model,allowedModels:e.harnesses?.codex?.allowedModels!==void 0?n.allowedModels:e.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(e.reasoningEffort!==void 0){let n=r.codex??{};r.codex={...n,reasoningEffort:e.harnesses?.codex?.reasoningEffort??e.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(e.codexApprovalPolicy!==void 0){let n=r.codex??{};r.codex={...n,approvalPolicy:e.harnesses?.codex?.approvalPolicy??e.codexApprovalPolicy},console.warn("[openclaw-code-agent] config.codexApprovalPolicy is deprecated; use harnesses.codex.approvalPolicy instead.")}if(e.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[n,o]of Object.entries(r))e.harnesses?.[n]?.allowedModels===void 0&&(r[n]={...o,allowedModels:void 0})}N={maxSessions:e.maxSessions??20,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??15,sessionGcAgeMinutes:e.sessionGcAgeMinutes??1440,maxPersistedSessions:e.maxPersistedSessions??1e4,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10,permissionMode:e.permissionMode??"plan",codexApprovalPolicy:e.codexApprovalPolicy??"on-request",planApproval:e.planApproval??"ask",defaultHarness:t,harnesses:r,allowedModels:e.allowedModels,defaultWorktreeStrategy:e.defaultWorktreeStrategy??"ask",worktreeDir:e.worktreeDir}}function pt(){return N.defaultHarness??zi}function yo(e){let t=zr[e],r=N.harnesses[e];return{...t,...r,allowedModels:r?.allowedModels??t?.allowedModels}}function mt(e){return yo(e).defaultModel}function Ji(e){return N.harnesses[e]?.allowedModels??N.allowedModels}function Yt(e){return yo(e).reasoningEffort}function $t(e){return yo(e).approvalPolicy}function Xi(e){if(e.messageChannel){let t=e.messageChannel.split("|");if(t.length>=3)return e.messageChannel;if(e.agentAccountId&&t.length>=2)return`${t[0]}|${e.agentAccountId}|${t.slice(1).join("|")}`;if(t.length===1&&e.chatId)return`${t[0]}|${e.chatId}`;if(t.length===1&&e.senderId)return`${t[0]}|${e.senderId}`}if(e.workspaceDir){let t=xr(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function Jt(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);if(e?.messageChannel){let r=String(e.messageChannel);if(r.includes("|"))return r;if(e.chatId)return`${r}|${e.chatId}`;if(e.senderId)return`${r}|${e.senderId}`}return e?.channel&&e?.chatId?`${e.channel}|${e.chatId}`:e?.channel&&e?.senderId?`${e.channel}|${e.senderId}`:e?.id&&/^-?\d+$/.test(String(e.id))?`telegram|${e.id}`:N.fallbackChannel??"unknown"}function Xt(e){return e?.messageThreadId??void 0}function xr(e){let t=N.agentChannels;if(!t)return;let r=s=>s.replace(/\/+$/,""),n=r(e),o=Object.entries(t).sort((s,i)=>i[0].length-s[0].length);for(let[s,i]of o)if(n===r(s)||n.startsWith(r(s)+"/"))return i}function Zi(e){if(!e)return;let t=e.match(/:topic:(\d+)$/);return t?parseInt(t[1],10):void 0}function Zt(e){let{requestedResumeSessionId:t,activeSession:r,persistedSession:n}=e;return t?r?{resumeSessionId:t,clearedPersistedCodexResume:!1}:n?.harness==="codex"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:t,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}function Dp(e){return e instanceof Error?e.message:String(e)}function Lp(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function Kp(e,t){if(!t||t.length===0)return!0;if(!e)return!1;let r=e.toLowerCase();return t.some(n=>r.includes(n.toLowerCase()))}function ea(e){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn by default \u2014 they stay open for follow-up messages via agent_respond. Set multi_turn_disabled: true for fire-and-forget sessions. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:g.Object({prompt:g.String({description:"The task prompt to execute"}),name:g.Optional(g.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:g.Optional(g.String({description:"Working directory (defaults to cwd)"})),model:g.Optional(g.String({description:"Model name to use"})),system_prompt:g.Optional(g.String({description:"Additional system prompt"})),allowed_tools:g.Optional(g.Array(g.String(),{description:"List of allowed tools"})),resume_session_id:g.Optional(g.String({description:"Session ID to resume (from a previous session's harnessSessionId). Continues the conversation from where it left off."})),fork_session:g.Optional(g.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),multi_turn_disabled:g.Optional(g.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:g.Optional(g.Union([g.Literal("default"),g.Literal("plan"),g.Literal("bypassPermissions")],{description:"Permission mode: 'default' (standard prompts), 'plan' (present plan first, wait for approval), 'bypassPermissions' (fully autonomous execution). Defaults to plugin config ('plan' by default)."})),harness:g.Optional(g.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."})),worktree_strategy:g.Optional(g.Union([g.Literal("off"),g.Literal("manual"),g.Literal("ask"),g.Literal("auto-merge"),g.Literal("auto-pr")],{description:"Worktree strategy: 'off' (no worktree), 'manual' (create worktree but no auto merge-back), 'ask' (prompt user with options), 'auto-merge' (merge automatically), 'auto-pr' (create PR automatically). Defaults to 'off'. Only respected when `defaultWorktreeStrategy` is set to `delegate` or is unset. Otherwise the admin-configured default is used regardless."})),worktree_base_branch:g.Optional(g.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),output_mode:g.Optional(g.Literal("deliverable",{description:"Output mode: 'deliverable' sends a \u{1F4C4} Deliverable ready notification instead of \u2705 Completed when the session finishes."}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Lp(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};r.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${r.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${e.agentId}" will be used for origin routing instead.`);let n=r.workdir||e.workspaceDir||N.defaultWorkdir||process.cwd();if(!Up(n))return{content:[{type:"text",text:`Error: Working directory does not exist: ${n}`}]};try{let o=r.harness??pt(),s=mt(o),i=r.model??s,a=r.model!==void 0;if(!i)return{content:[{type:"text",text:`Error: No default model configured for harness "${o}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${o}.defaultModel or pass model explicitly.`}]};let d=Ji(o);if(d&&d.length>0&&!Kp(i,d))return{content:[{type:"text",text:a?`Error: Model "${i}" is not allowed. Permitted models: ${d.join(", ")}`:`Error: Default model "${i||"undefined"}" is not in allowedModels (${d.join(", ")}). Update your plugin config to set a compatible defaultModel.`}]};let m=r.resume_session_id,y=m?I.resolve(m):void 0,f=m?I.getPersistedSession(m):void 0;if(m){let P=I.resolveHarnessSessionId(m);if(!P)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${m}" to a session ID. Use agent_sessions to list available sessions.`}]};m=P}let{resumeSessionId:c,clearedPersistedCodexResume:w}=Zt({requestedResumeSessionId:m,activeSession:y?{harnessSessionId:y.harnessSessionId}:void 0,persistedSession:f?{harness:f.harness}:void 0}),S=Xi(e),k=Jt(e,S||xr(n)),x=e.sessionKey||void 0;!x&&e.agentId&&console.warn(`[agent_launch] ctx.sessionKey is not populated. ctx fields: agentId=${e.agentId}, messageChannel=${e.messageChannel}, agentAccountId=${e.agentAccountId}, workspaceDir=${e.workspaceDir}`);let T=I.spawn({prompt:r.prompt,name:r.name,workdir:n,model:i,reasoningEffort:Yt(o),systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,resumeSessionId:c,resumeWorktreeFrom:m,forkSession:c?r.fork_session:!1,multiTurn:!r.multi_turn_disabled,permissionMode:r.permission_mode,codexApprovalPolicy:o==="codex"?$t(o)??N.codexApprovalPolicy:void 0,originChannel:k,originThreadId:Zi(x)??Xt(e),originAgentId:e.agentId||void 0,originSessionKey:x,harness:o,worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,outputMode:r.output_mode}),b=r.prompt.length>80?r.prompt.slice(0,80)+"...":r.prompt,E=["Session launched successfully.",` Name: ${T.name}`,` ID: ${T.id}`,` Dir: ${n}`,` Model: ${T.model??"default"}`,` Prompt: "${b}"`];return o==="codex"&&E.push(` Codex approval policy: ${T.codexApprovalPolicy??$t(o)??N.codexApprovalPolicy}`),r.resume_session_id&&(E.push(` Resume: ${r.resume_session_id}${r.fork_session?" (forked)":""}`),w&&E.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),E.push(r.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),E.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:E.join(`
2
+ `)}]}}catch(o){let s=Dp(o),i=s.includes("Max sessions")?"":`
3
+
4
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${s}${i}`}]}}}}}import{existsSync as sa,readFileSync as ia}from"fs";function qe(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 jp=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 ra(e){let r=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!jp.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var ta={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",deliverable:"\u{1F4C4}",failed:"\u274C",killed:"\u26D4","awaiting-plan-approval":"\u{1F4CB}"};function na(e){let t=ta[e.phase]??ta[e.status]??"\u2753",r=qe(e.duration),n=e.multiTurn?"multi-turn":"single",o=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,s=e.costUsd>0?` | $${e.costUsd.toFixed(2)}`:"",i=[`${t} ${e.name} [${e.id}] (${r}${s}) \u2014 ${n}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];if(e.worktreePath&&e.worktreeBranch){let a=` \u{1F33F} Worktree: ${e.worktreeBranch}`;e.worktreeMerged?a+=" [merged \u2713]":e.worktreePrUrl?a+=` [PR: ${e.worktreePrUrl}]`:a+=" [not merged]",i.push(a)}return e.phase!==e.status&&i.push(` \u2699\uFE0F Phase: ${e.phase}`),e.harness&&i.push(` \u{1F9F0} Harness: ${e.harness}`),e.harnessSessionId&&i.push(` \u{1F517} Session ID: ${e.harnessSessionId}`),e.resumeSessionId&&i.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),i.join(`
5
+ `)}function Qr(e,t){let r=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:n,failed:o,killed:s}=e.sessionsByStatus,i=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${n}`,` Failed: ${o}`,` Killed: ${s}`,"",`\u23F1\uFE0F Average duration: ${r>0?qe(r):"n/a"}`];if(e.mostExpensive){let a=e.mostExpensive;i.push("","\u{1F3C6} Notable session",` ${a.name} [${a.id}]`,` \u{1F4DD} "${a.prompt}"`)}return i.join(`
6
+ `)}function Rt(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function oa(e,t){let r=e.split(`
7
+ `),n=[],o=0;for(let s=r.length-1;s>=0;s--){let i=r[s].length+(n.length>0?1:0);if(o+i>t&&n.length>0)break;n.unshift(r[s]),o+=i}return n.join(`
8
+ `)}var Bp=50,Wp=1,Gp=new Set(["starting","running","completed","failed","killed"]),Hp=5,Vp=1440*60*1e3;function qp(e){let t=Number(e);return!Number.isFinite(t)||t<Wp?Bp:Math.floor(t)}function zp(e){return typeof e=="string"&&Gp.has(e)}function Qp(e){let t=qe(e.duration),r=` | Cost: $${e.costUsd.toFixed(4)}`,n=e.status==="running"?` | Phase: ${e.phase}`:"";return[`Session: ${e.name} [${e.id}] | Status: ${e.status.toUpperCase()}${n}${r} | Duration: ${t}`,`${"\u2500".repeat(60)}`].join(`
9
+ `)}function Yp(e){return[`Session: ${e.name||e.harnessSessionId} | Status: ${e.status.toUpperCase()} | Cost: $${e.costUsd.toFixed(4)}`,`(retrieved from ${e.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`,`${"\u2500".repeat(60)}`].join(`
10
+ `)}function Jp(e){let t=[];return e.error&&t.push(`Error: ${e.error}`),e.result?.result&&t.push(`Result: ${e.result.result}`),e.result&&t.push(`Result status: ${e.result.subtype}`),t.length>0?`
11
11
  (no output yet)
12
12
  ${t.join(`
13
13
  `)}`:`
14
- (no output yet)`}function Nn(e,t,n={}){let r=fp(n.lines),o=e.resolve(t);if(!o){let c=e.getPersistedSession(t);if(c?.outputPath&&ap(c.outputPath))try{let p=up(c.outputPath,"utf-8"),f=p;!n.full&&p&&(f=p.split(`
15
- `).slice(-r).join(`
16
- `));let b=hp(c);return f?`${b}
17
- ${f}`:`${b}
18
- (output file was empty)`}catch(p){let f=p instanceof Error?p.message:String(p);return`Error: Session "${t}" was cleaned up (expired) and output file could not be read: ${f}`}return`Error: Session "${t}" not found.`}let i=n.full?o.getOutput():o.getOutput(r),s=Ip(o);return i.length===0?`${s}${yp(o)}`:`${s}
19
- ${i.join(`
20
- `)}`}function Un(e,t="all",n,r={}){let o=e.listPersistedSessions()??[],s=xp(e.list("all"),o);if(t!=="all"&&(s=s.filter(c=>c.status===t)),n&&(s=s.filter(c=>c.originChannel===n)),r.full){let c=Date.now()-lp;s=s.filter(p=>(p.startedAt??0)>=c)}else s=s.slice(0,pp);return s.length===0?"No sessions found.":s.map(c=>Mi(c)).join(`
21
-
22
- `)}function xp(e,t){let n=new Map;for(let r of t){if(!gp(r.status))continue;let o=r.completedAt??Date.now(),i=r.createdAt??o,s=r.sessionId??`persisted:${r.harnessSessionId}`;n.set(s,{id:r.sessionId??r.harnessSessionId,name:r.name||r.harnessSessionId,status:r.status,startedAt:r.createdAt??0,completedAt:r.completedAt,duration:Math.max(0,o-i),prompt:r.prompt??"",workdir:r.workdir??"(unknown)",costUsd:r.costUsd??0,multiTurn:!0,phase:r.status,harness:r.harness,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId})}for(let r of e)n.set(r.id,{id:r.id,name:r.name,status:r.status,startedAt:r.startedAt,completedAt:r.completedAt,duration:r.duration,prompt:r.prompt,workdir:r.workdir,costUsd:r.costUsd,multiTurn:r.multiTurn,phase:r.phase,harness:r.harnessName,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId});return[...n.values()].sort((r,o)=>(o.startedAt??0)-(r.startedAt??0))}function Sp(e){if(!e||typeof e!="object")return"all";let t=e.status;switch(t){case"running":case"completed":case"failed":case"killed":case"all":return t;default:return"all"}}function Fi(e){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:l.Object({status:l.Optional(l.Union([l.Literal("all"),l.Literal("running"),l.Literal("completed"),l.Literal("failed"),l.Literal("killed")],{description:'Filter by status (default "all")'})),full:l.Optional(l.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=Sp(n),o=e?.workspaceDir?sn(e.workspaceDir):void 0,i=!!(n&&typeof n=="object"&&n.full===!0);return{content:[{type:"text",text:Un(g,r,o,{full:i})}]}}}}function _n(e,t,n){let r=e.resolve(t);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`:n==="completed"?(r.complete(),`Session ${r.name} [${r.id}] marked as completed.`):(e.kill(r.id),`Session ${r.name} [${r.id}] has been terminated.`):`Error: Session "${t}" not found.`}function Tp(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session!="string"?!1:t.reason===void 0?!0:t.reason==="completed"||t.reason==="killed"}function ki(e){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:l.Object({session:l.String({description:"Session name or ID to terminate"}),reason:l.Optional(l.Union([l.Literal("completed"),l.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(t,n){return g?Tp(n)?{content:[{type:"text",text:_n(g,n.session,n.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}function bp(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function $i(e){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:l.Object({session:l.String({description:"Session name or ID to get output from"}),lines:l.Optional(l.Number({description:"Number of recent lines to show (default 50)"})),full:l.Optional(l.Boolean({description:"Show all available output"}))}),async execute(t,n){return g?bp(n)?{content:[{type:"text",text:Nn(g,n.session,{full:n.full,lines:n.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}var wp=new Set(["killed","completed","failed"]),Ap=new Set(["startup-timeout"]),Pp=10,Rp=100,Op=/\b(change|swap|replace|remove|add|update|instead|don't|revise|modify)\b/i;function an(e){return e instanceof Error?e.message:String(e)}function vi(e){return"id"in e?e.id:e.sessionId??e.harnessSessionId}function Cp(e){return e.status==="killed"&&e.completedAt==null}function Mp(e,t){return wp.has(e.status)&&!!e.harnessSessionId&&(e.status==="failed"||e.status==="completed"&&e.killReason==="done"||e.status==="killed"&&(!Ap.has(e.killReason??"")||t&&Cp(e)))}function Ep(e,t){if(!(t.trim().length<Rp&&!Op.test(t)))return{text:["Cannot approve and revise in the same call.","Your message appears to contain revision feedback. Send it first WITHOUT approve=true:",` agent_respond(session='${e}', message='<your feedback>')`,"The agent will revise the plan. Then approve the revised plan."].join(`
23
- `),isError:!0}}async function Fp(e,t,n,r={}){if(Mp(t,r.allowRecoveredRunningStub===!0))try{let o="harnessName"in t?t:void 0,i="harnessName"in t?void 0:t,{resumeSessionId:s}=Kt({requestedResumeSessionId:t.harnessSessionId,activeSession:o?{harnessSessionId:o.harnessSessionId}:void 0,persistedSession:i?{harness:i.harness}:void 0}),c={prompt:n,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:s,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,harness:"harnessName"in t?t.harnessName:t.harness},p=await e.spawnAndAwaitRunning(c,{notifyLaunch:!1});return e.notifySession(p,`\u25B6\uFE0F [${p.name}] Auto-resumed`),{text:`Auto-resumed session ${p.name} [${p.id}]. Use agent_output to see the response.`}}catch(o){return{text:`Error auto-resuming session ${t.name} [${vi(t)}]: ${an(o)}`,isError:!0}}}function kp(e,t,n){let r=t.lobsterResumeToken;if(!r)return;t.lobsterResumeToken=void 0;let o=t.pendingPlanApproval||t.currentPermissionMode==="acceptEdits"||t.currentPermissionMode==="default";if(n.approve&&o)return e.resumeLobsterApproval(r,!0).catch(i=>{console.error(`[Respond] Lobster resume failed, falling back to direct mode switch: ${an(i)}`),t.switchPermissionMode("bypassPermissions"),t.sendMessage(n.message).catch(s=>{console.error(`[Respond] Fallback sendMessage also failed: ${an(s)}`)})}),{text:`Plan approved. Lobster workflow resuming for session ${t.name} [${t.id}].`};e.resumeLobsterApproval(r,!1).catch(i=>{console.error(`[Respond] Lobster cancel failed (non-critical): ${an(i)}`)})}async function Ln(e,t){let n=e.resolve(t.session),r=n?void 0:e.getPersistedSession(t.session);if(!n&&!r)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let i=await Fp(e,n??r,t.message,{allowRecoveredRunningStub:!n});if(i)return i;if(!n)return{text:`Error: Session ${r.name} [${vi(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return{text:`Error: Session ${n.name} [${n.id}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};let s=F.maxAutoResponds??Pp;if(t.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=s)return{text:`\u26A0\uFE0F Auto-respond limit reached (${n.autoRespondCount}/${s}). Ask the user to provide the answer for session ${n.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};let c=kp(e,n,t);if(c)return c;try{let p=!1;t.interrupt&&(p=await n.interrupt());let f="";if(t.approve&&n.pendingPlanApproval){let k=Ep(n.name,t.message);if(k)return k;n.switchPermissionMode("bypassPermissions")}else t.approve&&(n.currentPermissionMode==="acceptEdits"||n.currentPermissionMode==="default")?n.switchPermissionMode("bypassPermissions"):t.approve&&n.currentPermissionMode==="bypassPermissions"?f=`
24
- \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:t.approve?f=`
25
- \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:n.pendingPlanApproval&&(f=`
26
- \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`);await n.sendMessage(t.message),p&&e.notifySession(n,`\u21AA\uFE0F [${n.name}] Redirected`,"redirected"),t.userInitiated||n.incrementAutoRespond();let b=rt(t.message,80);return{text:[`Message sent to session ${n.name} [${n.id}].`,p?" (redirected active turn first)":t.interrupt?" (no active turn to interrupt)":"",` Message: "${b}"`,f,"Use agent_output to see the response."].filter(Boolean).join(`
27
- `)}}catch(p){return{text:`Error sending message to session ${n.name} [${n.id}]: ${an(p)}`,isError:!0}}}function $p(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function Ni(e){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent 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:l.Object({session:l.String({description:"Session name or ID to respond to"}),message:l.String({description:"The message to send to the session"}),interrupt:l.Optional(l.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:l.Optional(l.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:l.Optional(l.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode (after ExitPlanMode / set_permission_mode), or (2) escalate an acceptEdits or default mode session to skip all remaining permission prompts. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!$p(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let r=await Ln(g,n);return{isError:r.isError??!1,content:[{type:"text",text:r.text}]}}}}function Ui(e){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:l.Object({}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=g.getMetrics(),o=g.list("running").length;return{content:[{type:"text",text:vn(r,o)}]}}}}function vp(e){return e instanceof Error?e.message:String(e)}function _i(e){e.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent [--name <name>] <prompt>"};let r,o=n.match(/^--name\s+(\S+)\s+/);o&&(r=o[1],n=n.slice(o[0].length).trim());let i=n;if(!i)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let s=tt(),c=nt(s);if(!c)return{text:`Error: No default model configured for harness "${s}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${s}.defaultModel or pass model explicitly via agent_launch.`};let p=g.spawn({prompt:i,name:r,workdir:F.defaultWorkdir||process.cwd(),model:c,reasoningEffort:Ut(s),codexApprovalPolicy:s==="codex"?gt(s)??F.codexApprovalPolicy:void 0,originChannel:_t(t),originThreadId:Lt(t),harness:s}),f=i.length>80?i.slice(0,80)+"...":i;return{text:["Session launched.",` Name: ${p.name}`,` ID: ${p.id}`,` Prompt: "${f}"`,` Status: ${p.status}`].join(`
28
- `)}}catch(s){let c=vp(s),p=c.includes("Max sessions")?"":`
29
-
30
- Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${c}${p}`}}}})}function Li(e){e.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").split(/\s+/).includes("--full");return{text:Un(g,"all",void 0,{full:n})}}})}function Ki(e){e.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=t.args?.trim();return n?{text:_n(g,n,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}function Np(e){return e instanceof Error?e.message:String(e)}function Di(e){e.registerCommand({name:"agent_resume",description:"Resume a previous coding agent session. Usage: /agent_resume <id-or-name> [prompt] or /agent_resume --list to see resumable sessions.",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /agent_resume <id-or-name> [prompt]
14
+ (no output yet)`}function Yr(e,t,r={}){let n=qp(r.lines),o=e.resolve(t);if(!o){let d=e.getPersistedSession(t);if(d?.outputPath&&sa(d.outputPath))try{let m=ia(d.outputPath,"utf-8"),y=m;!r.full&&m&&(y=m.split(`
15
+ `).slice(-n).join(`
16
+ `));let f=Yp(d);return y?`${f}
17
+ ${y}`:`${f}
18
+ (output file was empty)`}catch(m){let y=m instanceof Error?m.message:String(m);return`Error: Session "${t}" was cleaned up (expired) and output file could not be read: ${y}`}return`Error: Session "${t}" not found.`}let s=r.full?o.getOutput():o.getOutput(n),i=Qp(o),a=s.length===0?`${i}${Jp(o)}`:`${i}
19
+ ${s.join(`
20
+ `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(sa(o.planFilePath)){let d=ia(o.planFilePath,"utf-8"),m="\u2500".repeat(60);return`${a}
21
+ ${m}
22
+ Plan file: ${o.planFilePath}
23
+ ${m}
24
+ ${d}`}}catch{}return a}function Jr(e,t="all",r,n={}){let o=e.listPersistedSessions()??[],i=Xp(e.list("all"),o);if(t!=="all"&&(i=i.filter(a=>a.status===t)),r&&(i=i.filter(a=>a.originChannel===r)),n.full){let a=Date.now()-Vp;i=i.filter(d=>(d.startedAt??0)>=a)}else i=i.slice(0,Hp);return i.length===0?"No sessions found.":i.map(a=>na(a)).join(`
25
+
26
+ `)}function Xp(e,t){let r=new Map;for(let n of t){if(!zp(n.status))continue;let o=n.completedAt??Date.now(),s=n.createdAt??o,i=n.sessionId??`persisted:${n.harnessSessionId}`;r.set(i,{id:n.sessionId??n.harnessSessionId,name:n.name||n.harnessSessionId,status:n.status,startedAt:n.createdAt??0,completedAt:n.completedAt,duration:Math.max(0,o-s),prompt:n.prompt??"",workdir:n.workdir??"(unknown)",costUsd:n.costUsd??0,multiTurn:!0,phase:n.status,harness:n.harness,harnessSessionId:n.harnessSessionId,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeMerged:n.worktreeMerged,worktreeMergedAt:n.worktreeMergedAt,worktreePrUrl:n.worktreePrUrl})}for(let n of e){let o;if(n.worktreePath&&n.originalWorkdir){let s=n.worktreePath.match(/openclaw-worktree-(.+)$/);s&&(o=`agent/${s[1]}`)}r.set(n.id,{id:n.id,name:n.name,status:n.status,startedAt:n.startedAt,completedAt:n.completedAt,duration:n.duration,prompt:n.prompt,workdir:n.originalWorkdir??n.workdir,costUsd:n.costUsd,multiTurn:n.multiTurn,phase:n.phase,harness:n.harnessName,harnessSessionId:n.harnessSessionId,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:o,worktreeStrategy:n.worktreeStrategy,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0})}return[...r.values()].sort((n,o)=>(o.startedAt??0)-(n.startedAt??0))}function Zp(e){if(!e||typeof e!="object")return"all";let t=e.status;switch(t){case"running":case"completed":case"failed":case"killed":case"all":return t;default:return"all"}}function aa(e){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:g.Object({status:g.Optional(g.Union([g.Literal("all"),g.Literal("running"),g.Literal("completed"),g.Literal("failed"),g.Literal("killed")],{description:'Filter by status (default "all")'})),full:g.Optional(g.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=Zp(r),o=e?.workspaceDir?xr(e.workspaceDir):void 0,s=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:Jr(I,n,o,{full:s})}]}}}}function Xr(e,t,r){let n=e.resolve(t);return n?n.status==="completed"||n.status==="failed"||n.status==="killed"?`Session ${n.name} [${n.id}] is already ${n.status}. No action needed.`:r==="completed"?(n.complete(),`Session ${n.name} [${n.id}] marked as completed.`):(e.kill(n.id),`Session ${n.name} [${n.id}] has been terminated.`):`Error: Session "${t}" not found.`}function em(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session!="string"?!1:t.reason===void 0?!0:t.reason==="completed"||t.reason==="killed"}function ua(e){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:g.Object({session:g.String({description:"Session name or ID to terminate"}),reason:g.Optional(g.Union([g.Literal("completed"),g.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(t,r){return I?em(r)?{content:[{type:"text",text:Xr(I,r.session,r.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}function tm(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function Zr(e){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:g.Object({session:g.String({description:"Session name or ID to get output from"}),lines:g.Optional(g.Number({description:"Number of recent lines to show (default 50)"})),full:g.Optional(g.Boolean({description:"Show all available output"}))}),async execute(t,r){return I?tm(r)?{content:[{type:"text",text:Yr(I,r.session,{full:r.full,lines:r.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}var rm=new Set(["killed","completed","failed"]),nm=new Set(["startup-timeout"]),om=10,sm=100,im=/\b(change|swap|replace|remove|add|update|instead|don't|revise|modify)\b/i;function Io(e){return e instanceof Error?e.message:String(e)}function wo(e){return"id"in e?e.id:e.sessionId??e.harnessSessionId}function am(e){return e.status==="killed"&&e.completedAt==null}function um(e,t){return rm.has(e.status)&&!!e.harnessSessionId&&(e.status==="failed"||e.status==="completed"&&e.killReason==="done"||e.status==="killed"&&(!nm.has(e.killReason??"")||t&&am(e)))}function cm(e){return e.killReason==="shutdown"&&!e.harnessSessionId}async function dm(e,t,r){try{let n={prompt:t.prompt,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,worktreeStrategy:t.worktreeStrategy,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,harness:"harnessName"in t?t.harnessName:t.harness},o=await e.spawnAndAwaitRunning(n,{notifyLaunch:!1});return e.notifySession(o,`\u25B6\uFE0F [${o.name}] Relaunched fresh`),{text:`Session ${t.name} was relaunched fresh \u2014 it was killed during startup before the harness initialized. New session: ${o.name} [${o.id}].`}}catch(n){return{text:`Error relaunching session ${t.name} [${wo(t)}]: ${Io(n)}`,isError:!0}}}function ca(e,t){if(!(t.trim().length<sm&&!im.test(t)))return{text:["Cannot approve and revise in the same call.","Your message appears to contain revision feedback. Send it first WITHOUT approve=true:",` agent_respond(session='${e}', message='<your feedback>')`,"The agent will revise the plan. Then approve the revised plan."].join(`
27
+ `),isError:!0}}var lm=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
28
+
29
+ `;async function pm(e,t,r,n={}){if(!um(t,n.allowRecoveredRunningStub===!0))return;let o=!!(n.approve&&t.currentPermissionMode==="plan");if(o){let s=ca(t.name,r);if(s)return s}try{let s="harnessName"in t?t:void 0,i="harnessName"in t?void 0:t,{resumeSessionId:a}=Zt({requestedResumeSessionId:t.harnessSessionId,activeSession:s?{harnessSessionId:s.harnessSessionId}:void 0,persistedSession:i?{harness:i.harness}:void 0}),d={prompt:o?lm+r:r,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:a,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:o?"bypassPermissions":t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,harness:"harnessName"in t?t.harnessName:t.harness},m=await e.spawnAndAwaitRunning(d,{notifyLaunch:!1});return o?e.notifySession(m,`\u{1F44D} [${m.name}] Plan approved (resumed)`,"plan-approved"):e.notifySession(m,`\u25B6\uFE0F [${m.name}] Auto-resumed`),{text:`Auto-resumed session ${m.name} [${m.id}]. Use agent_output to see the response.`}}catch(s){return{text:`Error auto-resuming session ${t.name} [${wo(t)}]: ${Io(s)}`,isError:!0}}}async function ft(e,t){let r=e.resolve(t.session),n=r?void 0:e.getPersistedSession(t.session);if(!r&&!n)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let o=r??n;if(cm(o))return dm(e,o,t.message);let s=await pm(e,o,t.message,{allowRecoveredRunningStub:!r,approve:t.approve});if(s)return s;if(!r)return{text:`Error: Session ${n.name} [${wo(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return{text:`Error: Session ${r.name} [${r.id}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};let i=N.maxAutoResponds??om;if(t.userInitiated)r.resetAutoRespond();else if(r.autoRespondCount>=i)return{text:`\u26A0\uFE0F Auto-respond limit reached (${r.autoRespondCount}/${i}). Ask the user to provide the answer for session ${r.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{let a=!1;t.interrupt&&(a=await r.interrupt());let d=!!(t.approve&&r.pendingPlanApproval),m="";if(t.approve&&r.pendingPlanApproval){let f=ca(r.name,t.message);if(f)return f;r.switchPermissionMode("bypassPermissions")}else t.approve&&r.currentPermissionMode==="default"?r.switchPermissionMode("bypassPermissions"):t.approve&&r.currentPermissionMode==="bypassPermissions"?m=`
30
+ \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:t.approve?m=`
31
+ \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:r.pendingPlanApproval&&(m=`
32
+ \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`);if(await r.sendMessage(t.message),d)e.notifySession(r,`\u{1F44D} [${r.name}] Plan approved`,"plan-approved");else{let f=Rt(t.message,100);e.notifySession(r,`\u21AA\uFE0F [${r.name}] "${f}"`,"agent-respond")}t.userInitiated||r.incrementAutoRespond();let y=Rt(t.message,80);return{text:[`Message sent to session ${r.name} [${r.id}].`,a?" (redirected active turn first)":t.interrupt?" (no active turn to interrupt)":"",` Message: "${y}"`,m,"Use agent_output to see the response."].filter(Boolean).join(`
33
+ `)}}catch(a){return{text:`Error sending message to session ${r.name} [${r.id}]: ${Io(a)}`,isError:!0}}}function mm(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function da(e){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent 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:g.Object({session:g.String({description:"Session name or ID to respond to"}),message:g.String({description:"The message to send to the session"}),interrupt:g.Optional(g.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:g.Optional(g.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:g.Optional(g.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode (after ExitPlanMode), or (2) escalate a default mode session to skip all remaining permission prompts. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!mm(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let n=await ft(I,r);return{isError:n.isError??!1,content:[{type:"text",text:n.text}]}}}}function la(e){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:g.Object({}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=I.getMetrics(),o=I.list("running").length;return{content:[{type:"text",text:Qr(n,o)}]}}}}import{existsSync as un}from"fs";import{resolve as bm,dirname as km}from"path";import{execFileSync as $}from"child_process";import{existsSync as fm,mkdirSync as pa,rmSync as fa,statfsSync as gm}from"fs";import{tmpdir as hm}from"os";import{join as ym}from"path";var en,tn;function Im(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function wm(e){try{return $("git",["rev-parse","--show-toplevel"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function ga(e){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(e){let t=wm(e);if(t)return ym(t,".worktrees")}return hm()}function Sm(){if(en!==void 0)return en;try{return $("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),en=!0,!0}catch{return en=!1,!1}}function et(){if(tn!==void 0)return tn;try{return $("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),tn=!0,!0}catch{return tn=!1,!1}}function ha(e){if(!Sm())return!1;try{return $("git",["rev-parse","--git-dir"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function ya(){try{let e=ga(),t=gm(e),r=t.bavail*t.bsize,n=100*1024*1024;return r>=n}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function xm(e,t){try{return $("git",["-C",e,"rev-parse","--verify",t],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function So(e,t){let r=Im(t),n=ga(e);pa(n,{recursive:!0});let o,s,i=10;for(let d=0;d<i;d++){let m=d===0?"":`-${Math.random().toString(16).slice(2,6)}`,y=`${n}/openclaw-worktree-${r}${m}`,f=`agent/${r}${m}`;try{pa(y,{recursive:!1}),o=y,s=f;break}catch(c){if(c&&typeof c=="object"&&"code"in c&&c.code==="EEXIST")continue;throw c}}if(!o||!s)throw new Error(`Failed to create unique worktree directory after ${i} attempts`);let a=xm(e,s);try{a?$("git",["-C",e,"worktree","add",o,s],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):$("git",["-C",e,"worktree","add","-b",s,o],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(d){try{fa(o,{recursive:!0,force:!0})}catch{}throw d}return o}function br(e,t){try{return $("git",["-C",e,"worktree","remove","--force",t],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){console.warn(`[worktree] git worktree remove failed for ${t}: ${r instanceof Error?r.message:String(r)}`);try{return fa(t,{recursive:!0,force:!0}),console.info(`[worktree] Fallback rmSync succeeded for ${t}`),!0}catch(n){return console.error(`[worktree] Both git worktree remove and rmSync failed for ${t}: ${n instanceof Error?n.message:String(n)}`),!1}}}function rn(e){try{$("git",["-C",e,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}function Ke(e){let t=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(t)return t;try{let n=$("git",["-C",e,"rev-parse","--abbrev-ref","origin/HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().replace(/^origin\//,"");if(n)return n}catch{}try{return $("git",["-C",e,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return $("git",["-C",e,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{}return"main"}function se(e){try{let r=$("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r==="HEAD"){console.warn(`[worktree] Worktree ${e} is in detached HEAD state \u2014 cannot determine branch name`);return}return r||void 0}catch{return}}function nn(e,t,r){try{let n=$("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(n.trim(),10)>0}catch{return!1}}function Ct(e,t,r){try{let n=$("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(n.trim(),10),i=$("git",["-C",e,"diff","--shortstat",`${r}...${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,m=0,y=i.match(/(\d+)\s+files?\s+changed/);y&&(a=parseInt(y[1],10));let f=i.match(/(\d+)\s+insertions?\(/);f&&(d=parseInt(f[1],10));let c=i.match(/(\d+)\s+deletions?\(/);c&&(m=parseInt(c[1],10));let S=$("git",["-C",e,"log",`${r}..${t}`,"--format=%h|%s|%an","-n","5"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
34
+ `).filter(Boolean).map(k=>{let[x,T,b]=k.split("|");return{hash:x||"",message:T||"",author:b||""}});return{commits:o,filesChanged:a,insertions:d,deletions:m,commitMessages:S}}catch(n){console.warn(`[worktree] Failed to get diff summary: ${n instanceof Error?n.message:String(n)}`);return}}function gt(e,t,r="origin"){try{return $("git",["-C",e,"push",r,t],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to push branch ${t}: ${n instanceof Error?n.message:String(n)}`),!1}}function ma(e){try{return $("git",["-C",e,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
35
+ `).some(r=>r.length>0&&!r.startsWith("??")&&!r.startsWith("!!"))}catch{return!1}}function on(e,t,r,n="merge",o){let s=!1,i,a=d=>{if(s)try{$("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(n==="squash"){if($("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ma(e)){let m;try{m=$("git",["-C",e,"stash","push","-m",`pre-merge stash before ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(y){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${y instanceof Error?y.message:String(y)}. Commit or stash changes manually, then retry.`}}if(!m.includes("No local changes to save")){s=!0;try{i=$("git",["-C",e,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}$("git",["-C",e,"merge","--squash",t],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),$("git",["-C",e,"commit","-m",`Squash merge ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let d=!1;if(s)try{$("git",["-C",e,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{d=!0}return{success:!0,stashed:s||void 0,stashRef:i,stashPopConflict:d||void 0}}else{let d=o&&fm(o),m=d?o:e;if(d||$("git",["-C",e,"checkout",t],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ma(e)){let f;try{f=$("git",["-C",e,"stash","push","-m",`pre-merge stash before ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(c){try{$("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${c instanceof Error?c.message:String(c)}. Commit or stash changes manually, then retry.`}}if(!f.includes("No local changes to save")){s=!0;try{i=$("git",["-C",e,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{$("git",["-C",m,"rebase",r],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{$("git",["-C",m,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{$("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(e),{success:!1,rebaseConflict:!0,stashed:s||void 0,stashRef:i,error:[`Rebase of ${t} onto ${r} hit conflicts.`,"To resolve manually:",` cd ${m}`,` git rebase ${r}`," # resolve conflicts in each file, then:"," git add <file>"," git rebase --continue"," # repeat until rebase finishes, then re-run agent_merge."].join(`
36
+ `)}}$("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),$("git",["-C",e,"merge","--ff-only",t],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let y=!1;if(s)try{$("git",["-C",e,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{y=!0}return{success:!0,fastForward:!0,stashed:s||void 0,stashRef:i,stashPopConflict:y||void 0}}}catch(d){try{$("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(e),{success:!1,error:d instanceof Error?d.message:String(d),stashed:s||void 0,stashRef:i}}}function sn(e,t,r,n,o){if(!et())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s=["pr","create","--base",r,"--head",t];return n&&o?s.push("--title",n,"--body",o):s.push("--fill-verbose"),{success:!0,prUrl:$("gh",s,{cwd:e,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}function Mt(e,t){try{return $("git",["-C",e,"branch","-D",t],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){return console.warn(`[worktree] Failed to delete branch ${t}: ${r instanceof Error?r.message:String(r)}`),!1}}function er(e,t){if(!et())return{exists:!1,state:"none"};try{let n=$("gh",["pr","list","--head",t,"--state","all","--json","url,number,title,state","--jq",".[0]"],{cwd:e,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!n)return{exists:!1,state:"none"};let o=JSON.parse(n),s,i=o.state.toLowerCase();return i==="open"?s="open":i==="merged"?s="merged":i==="closed"?s="closed":s="none",{exists:!0,state:s,url:o.url,number:o.number,title:o.title}}catch(r){return console.warn(`[worktree] Failed to sync PR status for ${t}: ${r instanceof Error?r.message:String(r)}`),{exists:!1,state:"none"}}}function an(e,t,r){if(!et())return!1;try{return $("gh",["pr","comment",String(t),"--body",r],{cwd:e,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to comment on PR #${t}: ${n instanceof Error?n.message:String(n)}`),!1}}function Pm(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function cn(e){return{name:"agent_merge",description:"Merge a worktree branch back to the base branch. Resolves session (active or persisted), gets worktree path, and performs the merge. On conflict, spawns a Claude Code conflict-resolver session.",parameters:g.Object({session:g.String({description:"Session name or ID to merge"}),base_branch:g.Optional(g.String({description:"Base branch to merge into (default: main)"})),strategy:g.Optional(g.Union([g.Literal("merge"),g.Literal("squash")],{description:"Merge strategy: 'merge' (default, fast-forward if possible; merge commit if branches have diverged) or 'squash' (squashes all commits into one)"})),push:g.Optional(g.Boolean({description:"Push the base branch after successful merge (default: false)"})),delete_branch:g.Optional(g.Boolean({description:"Delete the worktree branch after successful merge (default: true)"}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Pm(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=I.resolve(r.session),o=I.getPersistedSession(r.session);if(!n&&!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let s=n?.worktreePath??o?.worktreePath,i=n?.originalWorkdir??o?.workdir;if(!s||!i)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}]};let d=se(s)??o?.worktreeBranch;if(!d)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree at ${s}. The worktree may have been removed and no persisted branch name is available.`}]};un(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${i})`);let m=i;if(!un(i)){let k=bm(km(s),"..");if(un(k))console.warn(`[agent_merge] originalWorkdir "${i}" does not exist \u2014 falling back to derived repo root "${k}" (worktree path: ${s}).`),m=k;else return{content:[{type:"text",text:`Error: originalWorkdir "${i}" does not exist and could not derive repo root from worktree path "${s}".`}]}}let y=r.base_branch??Ke(m),f=r.strategy??"merge",c=r.push===!0,w=r.delete_branch!==!1;if(o?.worktreeMerged)return{content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" is already merged.`}]};let S={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]};return await I.enqueueMerge(m,async()=>{let k=I.getPersistedSession(r.session);if(k?.worktreeMerged){S={content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" was already merged while waiting in queue.`}]};return}let x=on(m,d,y,f,s);if(x.success){if(c&&!gt(m,y)){S={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${y} locally, but failed to push ${y}`}]};return}w&&Mt(m,d),un(s)&&(br(m,s),rn(m)),k&&I.updatePersistedSession(k.harnessSessionId,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0});let P=`\u2705 ${x.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${y}.${c?" Pushed.":""}${w?" Branch and worktree cleaned up.":""}`;x.stashPopConflict?P+=`
37
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${x.stashRef??"stash@{0}"}\` in ${m} to review stashed changes.`:x.stashed&&(P+=`
38
+ (Pre-existing changes on ${y} were auto-stashed and restored.)`),S={content:[{type:"text",text:P}]}}else if(x.rebaseConflict)S={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
39
+
40
+ ${x.error}`}]};else if(x.conflictFiles&&x.conflictFiles.length>0){let T=["Resolve merge conflicts in the following files and commit the resolution:","",...x.conflictFiles.map(b=>`- ${b}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${d}"`].join(`
41
+ `);try{let b=I.spawn({prompt:T,workdir:m,name:`${r.session}-conflict-resolver`,harness:"claude-code",permissionMode:"bypassPermissions",multiTurn:!0});S={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${x.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${b.name}`}]}}catch(b){S={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${b instanceof Error?b.message:String(b)}`}]}}}else S={content:[{type:"text",text:x.dirtyError?`\u274C Merge blocked: ${x.error}`:`\u274C Merge failed: ${x.error??"unknown error"}`}]}}),S}}}import{existsSync as Tm}from"fs";function Am(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function kr(e){return{name:"agent_pr",description:"Create or update a GitHub PR for a worktree branch. Handles full PR lifecycle: creates new PRs, updates existing open PRs with comments, and handles merged/closed PRs. Pushes the branch, syncs PR state, and persists metadata.",parameters:g.Object({session:g.String({description:"Session name or ID to create/update PR for"}),title:g.Optional(g.String({description:"PR title (default: auto-generated from session name)"})),body:g.Optional(g.String({description:"PR body (default: auto-generated from commit summary)"})),base_branch:g.Optional(g.String({description:"Base branch for the PR (default: detected from repo)"})),force_new:g.Optional(g.Boolean({description:"Force creation of a new PR even if one exists (default: false)"}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Am(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}]};if(!et())return{content:[{type:"text",text:"Error: GitHub CLI (gh) is not available. Install it and authenticate to create PRs."}]};let n=I.resolve(r.session),o=I.getPersistedSession(r.session);if(!n&&!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let s=n?.worktreePath??o?.worktreePath,i=n?.originalWorkdir??o?.workdir,a=n?.name??o?.name??r.session;if(!s||!i)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}]};let d=se(s),m=`agent/${a}`,y=d??o?.worktreeBranch??m;if(!y)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree ${s}. The worktree may have been removed and no persisted branch name is available.`}]};Tm(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${y}" via originalWorkdir (${i})`);let f=r.base_branch??Ke(i);if(!gt(i,y))return{content:[{type:"text",text:`\u274C Failed to push ${y} \u2014 cannot create/update PR`}]};let c=er(i,y);if(r.force_new&&c.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${y} (${c.state}).
42
+
43
+ Existing PR: ${c.url}
44
+
45
+ To create a new PR, you must first close/merge the existing PR manually or use a different branch.`}]};if(c.exists&&c.state==="open"){let w=Ct(i,y,f);if(w&&w.commits>0){let S=w.commitMessages.slice(0,5).map(b=>`\u2022 ${b.hash} ${b.message} (${b.author})`).join(`
46
+ `),k=w.commits>5?`
47
+ ...and ${w.commits-5} more commits`:"",x=["\u{1F504} **New commits pushed**","",`${w.commits} new commits (+${w.insertions} / -${w.deletions})`,"","### Latest commits:",S+k,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
48
+ `);return an(i,c.number,x)?(o&&I.updatePersistedSession(o.harnessSessionId,{worktreePrUrl:c.url,worktreePrNumber:c.number}),{content:[{type:"text",text:`\u2705 PR updated with new commits: ${c.url}
49
+
50
+ \u{1F4DD} Added comment detailing ${w.commits} new commits (+${w.insertions} / -${w.deletions})`}]}):{content:[{type:"text",text:`\u26A0\uFE0F Pushed to ${c.url} but failed to add comment.
51
+
52
+ ${w.commits} new commits (+${w.insertions} / -${w.deletions})`}]}}else return o&&I.updatePersistedSession(o.harnessSessionId,{worktreePrUrl:c.url,worktreePrNumber:c.number}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${c.url}
53
+
54
+ No new commits to push.`}]}}else{if(c.exists&&c.state==="merged")return o&&I.updatePersistedSession(o.harnessSessionId,{worktreePrUrl:c.url,worktreePrNumber:c.number}),{content:[{type:"text",text:`\u2705 PR was already merged: ${c.url}
55
+
56
+ The worktree branch ${y} can be cleaned up with agent_merge(delete_branch=true).`}]};if(c.exists&&c.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${c.url}
57
+
58
+ What would you like to do?
59
+
60
+ 1. Reopen the closed PR manually on GitHub, then call agent_pr() again to update it
61
+ 2. Close and delete the branch with agent_merge(delete_branch=true), then start a new session/worktree
62
+ 3. Manually delete the closed PR on GitHub, then call agent_pr(force_new=true) to create a fresh PR
63
+
64
+ (This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}]};{let w=r.title??`[openclaw-code-agent] ${a}`,S=r.body;if(!S){let x=Ct(i,y,f);if(x){let T=x.commitMessages.slice(0,5).map(E=>`\u2022 ${E.hash} ${E.message} (${E.author})`).join(`
65
+ `),b=x.commits>5?`
66
+ ...and ${x.commits-5} more`:"";S=[`Automated changes from OpenClaw Code Agent session: ${a}`,"","## Summary",`${x.commits} commits, ${x.filesChanged} files changed (+${x.insertions} / -${x.deletions})`,"","## Commits",T+b,"","---","\u{1F916} Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
67
+ `)}else S=`Automated changes from OpenClaw Code Agent session: ${a}`}let k=sn(i,y,f,w,S);if(k.success&&k.prUrl){let x=er(i,y);return o&&I.updatePersistedSession(o.harnessSessionId,{worktreePrUrl:k.prUrl,worktreePrNumber:x.number,pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0}),{content:[{type:"text",text:`\u{1F500} PR created: ${k.prUrl}`}]}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${k.error??"unknown error"}`}]}}}}}}import{execFileSync as tr}from"child_process";import{existsSync as $m}from"fs";function Rm(e){return!(!e||typeof e!="object")}function Cm(e){try{return tr("git",["-C",e,"branch","--list","agent/*"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
68
+ `).map(r=>r.replace(/^\*?\s+/,"").trim()).filter(Boolean)}catch{return[]}}function Mm(e,t,r){try{let n=tr("git",["-C",e,"merge-base",t,r],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=tr("git",["-C",e,"rev-parse",t],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return n===o}catch{return!1}}function Om(e,t,r){try{let n=tr("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(n.trim(),10)||0}catch{return 0}}function Em(e,t){if(I){for(let r of I.listPersistedSessions())if(r.worktreeBranch===t&&r.worktreePrUrl&&r.worktreeMerged!==!0)return{number:r.worktreePrNumber??0,url:r.worktreePrUrl}}if(et())try{let r=tr("gh",["pr","list","--head",t,"--state","open","--json","number,url"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"],cwd:e}),n=JSON.parse(r.trim());if(Array.isArray(n)&&n.length>0)return{number:n[0].number,url:n[0].url}}catch{}return null}function Ia(e){return{name:"agent_worktree_cleanup",description:"Clean up agent/* branches. Three categories are always protected from deletion: (1) branches with active running/starting sessions, (2) branches with unmerged commits ahead of the base branch, (3) branches with open GitHub PRs. Only fully merged branches with no active session or open PR are eligible for deletion. Use skip_session_check (alias: force) to bypass the active-session check only \u2014 useful when a session crashed and left a stale branch. Use session to dismiss a pending worktree decision without merging.",parameters:g.Object({workdir:g.Optional(g.String({description:"Working directory (defaults to cwd)"})),base_branch:g.Optional(g.String({description:"Base branch to check merge status against (default: main)"})),skip_session_check:g.Optional(g.Boolean({description:"Skip the check for running sessions (use only when a session crashed and left a stale branch). Does NOT override unmerged commit or open PR protection. (default: false)"})),force:g.Optional(g.Boolean({description:"Deprecated alias for skip_session_check. See skip_session_check for details."})),dry_run:g.Optional(g.Boolean({description:"Show what would be deleted without actually deleting (default: false)"})),session:g.Optional(g.String({description:"Session name or ID to dismiss/clear pending worktree decision for (optional)"}))}),async execute(t,r){if(!Rm(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, skip_session_check?, force?, dry_run?, session? }."}]};let n=r.session;if(n&&I){let b=I.getPersistedSession(n);b&&I.updatePersistedSession(b.harnessSessionId,{pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0})}let o=r.workdir||process.cwd(),s=r.base_branch??Ke(o),i=r.skip_session_check===!0||r.force===!0,a=r.dry_run===!0;if(!$m(o))return{content:[{type:"text",text:`Error: Working directory does not exist: ${o}`}]};try{tr("git",["-C",o,"rev-parse","--git-dir"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{return{content:[{type:"text",text:`Error: ${o} is not a git repository`}]}}let d=Cm(o);if(d.length===0)return{content:[{type:"text",text:"No agent/* branches found."}]};let m=new Set,y=new Map;if(I){for(let b of I.list())if(b.status==="starting"||b.status==="running"){let E=b.worktreeBranch??(b.worktreePath?se(b.worktreePath):void 0);E&&(m.add(E),y.set(E,`${b.name} is ${b.status}`))}}let f=[],c=[],w=[],S=[];for(let b of d){if(!i&&m.has(b)){let E=y.get(b)??"unknown";w.push(`${b} (session: ${E})`);continue}if(Mm(o,b,s))f.push(b);else{let E=Em(o,b);if(E)S.push({branch:b,prNumber:E.number,prUrl:E.url});else{let P=Om(o,b,s);c.push({branch:b,commitsAhead:P})}}}let k=(b,E)=>{let P=["agent/* branch status:"],A=a?"WOULD DELETE":"DELETED",de=(a?f:b).join(", ")||"(none)",ke=E.length>0?`; ${E.length} failed: ${E.join(", ")}`:"";P.push(` ${A} (${a?f.length:b.length}): ${de}${ke}`);let ht=c.length>0?c.map(({branch:tt,commitsAhead:We})=>We>0?`${tt} [${We} commit${We!==1?"s":""} ahead]`:tt).join(", "):"(none)";P.push(` KEPT \u2013 unmerged (${c.length}): ${ht}`);let Et=w.length>0?w.join(", "):"(none)";P.push(` KEPT \u2013 active session (${w.length}): ${Et}`);let Tn=S.length>0?S.map(({branch:tt,prNumber:We,prUrl:eu})=>We>0?`${tt} [PR #${We}]`:`${tt} [open PR]`).join(", "):"(none)";return P.push(` KEPT \u2013 open PR (${S.length}): ${Tn}`),P.join(`
69
+ `)};if(a)return{content:[{type:"text",text:k([],[])}]};let x=[],T=[];for(let b of f)Mt(o,b)?x.push(b):T.push(b);return{content:[{type:"text",text:k(x,T)}]}}}}import{existsSync as vm}from"fs";function _m(e){return!0}function wa(e){return{name:"agent_worktree_status",description:"Show worktree status for coding agent sessions. If session parameter is provided, shows status for that session only. Otherwise, shows all sessions with worktrees. Displays branch name, repository, strategy, commits ahead, merge status, and PR URLs.",parameters:g.Object({session:g.Optional(g.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!_m(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let n=r.session,o=[],s=I.list("all").filter(c=>c.worktreePath),i=I.listPersistedSessions().filter(c=>c.worktreePath),a=new Map;for(let c of i){if(!c.worktreePath)continue;let w=c.sessionId??c.harnessSessionId;a.set(w,{id:w,name:c.name,worktreePath:c.worktreePath,worktreeBranch:c.worktreeBranch,worktreeStrategy:c.worktreeStrategy,workdir:c.workdir,worktreeMerged:c.worktreeMerged,worktreeMergedAt:c.worktreeMergedAt,worktreePrUrl:c.worktreePrUrl})}for(let c of s)c.worktreePath&&a.set(c.id,{id:c.id,name:c.name,worktreePath:c.worktreePath,worktreeBranch:se(c.worktreePath),worktreeStrategy:c.worktreeStrategy,workdir:c.originalWorkdir??c.workdir,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0});let d=Array.from(a.values());if(n&&(d=d.filter(c=>c.id===n||c.name===n),d.length===0))return{content:[{type:"text",text:`Error: Session "${n}" not found or has no worktree.`}]};if(d.length===0)return{content:[{type:"text",text:"No sessions with worktrees found."}]};let y=I.listPersistedSessions().filter(c=>c.pendingWorktreeDecisionSince&&!c.worktreeMerged&&!c.worktreePrUrl),f=n?y.filter(c=>c.harnessSessionId===n||c.name===n||c.sessionId===n):y;if(f.length>0){o.push(`\u23F3 Pending decisions (${f.length}):`),o.push("");for(let c of f){let w=new Date(c.pendingWorktreeDecisionSince),S=Date.now()-w.getTime(),k=Math.floor(S/(3600*1e3)),x=Math.floor(k/24),T=k%24,b=Math.floor(S%(3600*1e3)/6e4),E=x>0?`${x}d ${T}h`:k>0?`${k}h ${b}m`:`${b}m`,P=Ke(c.workdir);o.push(`\u2022 ${c.name.padEnd(14)} ${(c.worktreeBranch??"?").padEnd(30)} \u2192 ${P.padEnd(10)} pending ${E}`)}if(o.push(""),f.length===1){let c=f[0];o.push(`Use agent_merge(session="${c.name}") or agent_pr(session="${c.name}") to resolve.`)}else o.push('Use agent_merge(session="<name>") or agent_pr(session="<name>") to resolve.');o.push(""),o.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),o.push("All worktrees:"),o.push("")}for(let c of d){let w=c.worktreeBranch??se(c.worktreePath);if(!w){o.push(`Session: ${c.name} [${c.id}]`),o.push(` Worktree: ${c.worktreePath}`),o.push(" Status: Cannot determine branch (detached HEAD or worktree removed)"),o.push("");continue}let S=Ke(c.workdir),k=vm(c.workdir);if(o.push(`Session: ${c.name} [${c.id}]`),o.push(` Branch: ${w} \u2192 ${S}`),o.push(` Repo: ${c.workdir}`),c.worktreeStrategy&&o.push(` Strategy: ${c.worktreeStrategy}`),k)try{if(nn(c.workdir,w,S)){let T=Ct(c.workdir,w,S);T?o.push(` Commits: ${T.commits} ahead of ${S} (+${T.insertions} / -${T.deletions})`):o.push(` Commits: ahead of ${S}`)}else o.push(` Commits: even with ${S}`)}catch{o.push(" Commits: (unable to check)")}else o.push(" Commits: (repo no longer exists)");if(c.worktreeMerged){let x=c.worktreeMergedAt?new Date(c.worktreeMergedAt).toLocaleString():"unknown";o.push(` Merged: Yes (${x})`)}else c.worktreePrUrl?o.push(` PR: ${c.worktreePrUrl}`):o.push(" Merged: No");o.push("")}return{content:[{type:"text",text:o.join(`
70
+ `).trim()}]}}}}var Fm="code-agent";function Nm(e){let t=e.indexOf(":");if(t===-1)return null;let r=e.slice(0,t).trim(),n=e.slice(t+1).trim();return!r||!n?null:{action:r,sessionId:n}}function dn(e){if(e&&typeof e=="object"&&"content"in e&&Array.isArray(e.content)){let t=e.content[0];return typeof t?.text=="string"?t.text:"(done)"}return"(done)"}function Sa(){return{channel:"telegram",namespace:Fm,handler:async e=>{if(!e.auth.isAuthorizedSender)return await e.respond.reply({text:"\u26D4 Unauthorized."}),{handled:!0};let t=Nm(e.callback.payload);if(!t)return await e.respond.reply({text:`\u26A0\uFE0F Unrecognized callback payload: "${e.callback.payload}". Expected "action:session-id".`}),{handled:!0};let{action:r,sessionId:n}=t;if(!I)return await e.respond.reply({text:"\u26A0\uFE0F Code agent service not running."}),{handled:!0};switch(await e.respond.clearButtons(),r){case"merge":case"merge-locally":{{let s=I.resolve(n),i=I.getPersistedSession(n),a=s?.harnessSessionId??i?.harnessSessionId;a&&I.updatePersistedSession(a,{pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0})}let o=await cn().execute("callback",{session:n});await e.respond.reply({text:dn(o)});break}case"pr":case"open-pr":{let o=await kr().execute("callback",{session:n});await e.respond.reply({text:dn(o)});break}case"new-pr":{let o=await kr().execute("callback",{session:n,force_new:!0});await e.respond.reply({text:dn(o)});break}case"approve":{let o=await ft(I,{session:n,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});await e.respond.reply({text:o.isError?`\u26A0\uFE0F ${o.text}`:`\u{1F44D} ${o.text}`});break}case"reject":{let o=await ft(I,{session:n,message:"Plan rejected. Please stop.",userInitiated:!0});await e.respond.reply({text:o.isError?`\u26A0\uFE0F ${o.text}`:`\u274C ${o.text}`});break}case"revise":{let o=I.resolve(n),s=I.getPersistedSession(n),i=o?.name??s?.name??n;await e.respond.reply({text:`\u270F\uFE0F Type your revision feedback for [${i}] and I'll forward it to the agent.`});break}case"reply":{let o=I.resolve(n),s=I.getPersistedSession(n),i=o?.name??s?.name??n;await e.respond.reply({text:`\u{1F4AC} Type your reply for [${i}] and I'll forward it to the agent.`});break}case"retry":{let o=await ft(I,{session:n,message:"Retry.",userInitiated:!0});await e.respond.reply({text:o.isError?`\u26A0\uFE0F ${o.text}`:`\u{1F504} ${o.text}`});break}case"view-output":{let o=await Zr().execute("callback",{session:n,lines:50});await e.respond.reply({text:dn(o)});break}case"question-answer":{let o=n.lastIndexOf(":");if(o===-1){await e.respond.reply({text:`\u26A0\uFE0F Malformed question-answer payload: "${n}"`});break}let s=n.slice(0,o),i=parseInt(n.slice(o+1),10);if(isNaN(i)){await e.respond.reply({text:"\u26A0\uFE0F Invalid option index in question-answer payload."});break}I.resolveAskUserQuestion(s,i),await e.respond.reply({text:"\u2705 Answer submitted."});break}default:{await e.respond.reply({text:`\u26A0\uFE0F Unknown callback action: "${r}". Supported: merge, pr, open-pr, new-pr, approve, reject, revise, reply, retry, view-output, question-answer.`});break}}return{handled:!0}}}}function Um(e){return e instanceof Error?e.message:String(e)}function xa(e){e.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:"Usage: /agent [--name <name>] <prompt>"};let n,o=r.match(/^--name\s+(\S+)\s+/);o&&(n=o[1],r=r.slice(o[0].length).trim());let s=r;if(!s)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=pt(),a=mt(i);if(!a)return{text:`Error: No default model configured for harness "${i}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${i}.defaultModel or pass model explicitly via agent_launch.`};let d=I.spawn({prompt:s,name:n,workdir:N.defaultWorkdir||process.cwd(),model:a,reasoningEffort:Yt(i),codexApprovalPolicy:i==="codex"?$t(i)??N.codexApprovalPolicy:void 0,originChannel:Jt(t),originThreadId:Xt(t),harness:i}),m=s.length>80?s.slice(0,80)+"...":s;return{text:["Session launched.",` Name: ${d.name}`,` ID: ${d.id}`,` Prompt: "${m}"`,` Status: ${d.status}`].join(`
71
+ `)}}catch(i){let a=Um(i),d=a.includes("Max sessions")?"":`
72
+
73
+ Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${d}`}}}})}function ba(e){e.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").split(/\s+/).includes("--full");return{text:Jr(I,"all",void 0,{full:r})}}})}function ka(e){e.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=t.args?.trim();return r?{text:Xr(I,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}function Dm(e){return e instanceof Error?e.message:String(e)}function Pa(e){e.registerCommand({name:"agent_resume",description:"Resume a previous coding agent session. Usage: /agent_resume <id-or-name> [prompt] or /agent_resume --list to see resumable sessions.",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:`Usage: /agent_resume <id-or-name> [prompt]
31
74
  /agent_resume --list \u2014 list resumable sessions
32
- /agent_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let W=g.listPersistedSessions();return W.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
75
+ /agent_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(r==="--list"){let k=I.listPersistedSessions();return k.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
33
76
 
34
- ${W.map(N=>{let He=N.prompt.length>60?N.prompt.slice(0,60)+"...":N.prompt,be=N.completedAt?`completed ${_e(Date.now()-N.completedAt)} ago`:N.status;return[` ${N.name} \u2014 ${be}`,` Session ID: ${N.harnessSessionId}`,` \u{1F4C1} ${N.workdir}`,` \u{1F4DD} "${He}"`].join(`
77
+ ${k.map(T=>{let b=T.prompt.length>60?T.prompt.slice(0,60)+"...":T.prompt,E=T.completedAt?`completed ${qe(Date.now()-T.completedAt)} ago`:T.status;return[` ${T.name} \u2014 ${E}`,` Session ID: ${T.harnessSessionId}`,` \u{1F4C1} ${T.workdir}`,` \u{1F4DD} "${b}"`].join(`
35
78
  `)}).join(`
36
79
 
37
- `)}`}}let r=!1;n.startsWith("--fork ")&&(r=!0,n=n.slice(7).trim());let o=n.indexOf(" "),i,s;o===-1?(i=n,s="Continue where you left off."):(i=n.slice(0,o),s=n.slice(o+1).trim()||"Continue where you left off.");let c=g.resolveHarnessSessionId(i);if(!c)return{text:`Error: Could not find a session ID for "${i}".
38
- Use /agent_resume --list to see available sessions.`};let p=g.resolve(i),f=g.getPersistedSession(i),{resumeSessionId:b,clearedPersistedCodexResume:k}=Kt({requestedResumeSessionId:c,activeSession:p?{harnessSessionId:p.harnessSessionId}:void 0,persistedSession:f?{harness:f.harness}:void 0}),X=f?.workdir??process.cwd(),ge=f?.harness??tt(),Y=f?.model??nt(ge);try{if(!Y)return{text:`Error: No default model configured for harness "${ge}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${ge}.defaultModel or pass model explicitly when launching a fresh session.`};let W=g.spawn({prompt:s,workdir:X,name:f?.name,model:Y,codexApprovalPolicy:p?.codexApprovalPolicy??f?.codexApprovalPolicy,resumeSessionId:b,forkSession:b?r:!1,originChannel:_t(t),originThreadId:Lt(t)??f?.originThreadId,originAgentId:t?.agentId??f?.originAgentId,originSessionKey:t?.sessionKey??f?.originSessionKey,harness:ge}),Q=s.length>80?s.slice(0,80)+"...":s;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${W.name}`,` ID: ${W.id}`,b?` Resume from: ${c}`:" Resume from: fresh thread",` Dir: ${X}`,` Prompt: "${Q}"`,k?" Note: cleared persisted Codex thread state after restart to avoid org-mismatch resume failures.":""].join(`
39
- `)}}catch(W){let Q=Np(W),N=Q.includes("Max sessions")?"":`
40
-
41
- Use /agent_sessions to see active sessions or /agent_resume --list to see resumable sessions.`;return{text:`Error resuming session: ${Q}${N}`}}}})}function ji(e){e.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /agent_respond <id-or-name> <message>
42
- /agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!0,o=o.slice(12).trim());let i=o.indexOf(" ");if(i===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let s=o.slice(0,i),c=o.slice(i+1).trim();return c?{text:(await Ln(g,{session:s,message:c,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}function Gi(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=g.getMetrics(),n=g.list("running").length;return{text:vn(t,n)}}})}var Up=50;function Vi(e){e.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=n.split(/\s+/),o="",i=!1,s=Up;for(let p=0;p<r.length;p++)if(r[p]==="--full")i=!0;else if(r[p]==="--lines"&&p+1<r.length){let f=parseInt(r[p+1],10);!isNaN(f)&&f>0&&(s=f),p++}else o||(o=r[p]);return o?{text:Nn(g,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}import{execFile as fa}from"child_process";import{existsSync as Xl}from"fs";import{fileURLToPath as ga}from"url";import{dirname as Ql,join as Yr}from"path";import{EventEmitter as wl}from"events";import Bi from"crypto";var Hi="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var _p=128,It,Dt,Lp=e=>{!It||It.length<e?(It=Buffer.allocUnsafe(e*_p),Bi.randomFillSync(It),Dt=0):Dt+e>It.length&&(Bi.randomFillSync(It),Dt=0),Dt+=e};var Wi=(e=21)=>{Lp(e|=0);let t="";for(let n=Dt-e;n<Dt;n++)t+=Hi[It[n]&63];return t};import{query as Kp}from"@anthropic-ai/claude-agent-sdk";var Kn=class{name="claude-code";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=["AskUserQuestion"];planApprovalToolNames=["ExitPlanMode","set_permission_mode"];launch(t){let n={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers};t.resumeSessionId&&(n.resume=t.resumeSessionId,n.forkSession=t.forkSession??!1);let r=Kp({prompt:t.prompt,options:n});return{messages:this.adaptMessages(r),async setPermissionMode(o){typeof r.setPermissionMode=="function"&&await r.setPermissionMode(o)},async streamInput(o){typeof r.streamInput=="function"&&await r.streamInput(o)},async interrupt(){typeof r.interrupt=="function"&&await r.interrupt()}}}buildUserMessage(t,n){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n}}async*adaptMessages(t){for await(let n of t){let r=n;if(r.type==="system"&&r.subtype==="init")yield{type:"init",session_id:r.session_id??""};else if(r.type==="system"&&r.subtype==="status"&&r.permissionMode)yield{type:"permission_mode_change",mode:r.permissionMode};else if(r.type==="assistant")for(let o of r.message?.content??[])o.type==="text"?yield{type:"text",text:o.text}:o.type==="tool_use"&&(yield{type:"tool_use",name:o.name,input:o.input});else r.type==="result"&&(yield{type:"result",data:{success:r.subtype==="success",duration_ms:r.duration_ms??0,total_cost_usd:r.total_cost_usd??0,num_turns:r.num_turns??0,result:r.result,session_id:r.session_id??""}})}}};import{parse as ul,resolve as dl}from"path";import{Codex as ta}from"@openai/codex-sdk";import{randomUUID as Dp}from"node:crypto";import{lstat as jp,mkdir as Br,readFile as Yi,readlink as Gp,realpath as Vp,rename as Hp,rm as Dn,symlink as Bp,writeFile as Ji}from"node:fs/promises";import{homedir as Wp,tmpdir as Xi}from"node:os";import{dirname as qp,join as $e,resolve as zp}from"node:path";var Yp=50,Jp=3e4,Xp=$e(Xi(),"openclaw-codex-auth.lock");function Qp(e,t){let n={};for(let[r,o]of Object.entries(e))typeof o=="string"&&(n[r]=o);return n.HOME=t,n}function Zp(e){return new Promise(t=>setTimeout(t,e))}async function Qi(e){try{return await jp(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function qi(e,t){if(await Qi(t)){if(await Gp(t)===e)return;await Dn(t,{recursive:!0,force:!0})}await Bp(e,t)}function el(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return null;let n=Number(t);if(Number.isFinite(n))return n;let r=Date.parse(t);if(Number.isFinite(r))return r}return null}async function zi(e){let t;try{t=await Yi(e,"utf8")}catch(n){return n.code==="ENOENT",null}try{let n=JSON.parse(t);if(!n||typeof n!="object")return null;let r=el(n.last_refresh);return r===null?null:{lastRefresh:r,raw:t}}catch{return null}}async function Zi(e,t){await Br(qp(e),{recursive:!0});let n=`${e}.tmp`;await Ji(n,t,"utf8"),await Hp(n,e)}async function tl(e,t){try{let n=await Yi(e,"utf8");await Zi(t,n)}catch(n){if(n.code!=="ENOENT")throw n;await Dn(t,{force:!0})}}async function nl(e,t){let n=await zi(e);if(!n)return;let r=await zi(t);r&&n.lastRefresh<=r.lastRefresh||await Zi(t,n.raw)}async function rl(e,t,n){let r=Date.now()+t;for(;;)try{await Br(e);break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()>=r)throw new Error(`Timed out waiting for Codex auth lock at ${e}`);await Zp(n)}try{await Ji($e(e,"holder.json"),JSON.stringify({pid:process.pid,acquired_at:new Date().toISOString()}),"utf8")}catch{}let o=!1;return async()=>{o||(o=!0,await Dn(e,{recursive:!0,force:!0}))}}async function ea(e=process.env,t={}){let n=e.HOME??Wp(),r=await Vp(n).catch(()=>zp(n)),o=$e(r,".codex"),i=$e(o,"auth.json"),s=$e(o,"sessions"),c=$e(o,"config.toml"),p=await Qi(c)?c:void 0,f=t.tempRootDir??Xi(),b=$e(f,`openclaw-codex-auth-${Dp()}`),k=$e(b,".codex"),X=$e(k,"auth.json"),ge=t.lockDir??Xp,Y=t.lockTimeoutMs??Jp,W=t.lockRetryMs??Yp;return await Br(k,{recursive:!0}),await qi(s,$e(k,"sessions")),p&&await qi(p,$e(k,"config.toml")),{tempHome:b,tempCodexDir:k,canonicalHome:r,canonicalCodexDir:o,canonicalAuthPath:i,canonicalSessionsPath:s,canonicalConfigPath:p,env:Qp(e,b),async prepareForTurn(){let Q=await rl(ge,Y,W);try{await tl(i,X)}catch(He){throw await Q(),He}let N=!1;return async()=>{if(!N){N=!0;try{await nl(X,i)}finally{await Q()}}}},async cleanup(){await Dn(b,{recursive:!0,force:!0})}}}var ol=["proceed","continue","implement","apply","run","merge","deploy","commit"],sl=["shall i proceed","do you want me to","would you like me to","please confirm","should i continue","can i proceed","should i proceed","should i go ahead","want me to continue","approve and i'll","confirm and i'll"],il=["why this failed was","why did this fail","what failed","what happened","how can i help","is this clear","any questions","anything else","let me know","would you like a summary"];function al(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function jn(e){let t=al(e);if(!t||il.some(r=>t.includes(r)))return!1;let n=ol.some(r=>t.includes(r));return sl.some(r=>t.includes(r))?n||t.includes("confirm"):t.endsWith("?")?n:!1}var na=1e4,ra="codex:waiting-for-user",cl=1.1/1e6,ml=.275/1e6,pl=4.4/1e6,ll="OPENCLAW_CODEX_HEARTBEAT_MS",fl="OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS",gl="OPENCLAW_CODEX_AUTH_STRATEGY";function Il(e){if(!e)return 0;let t=e.cached_input_tokens??0,n=Math.max(0,(e.input_tokens??0)-t),r=e.output_tokens??0;return n*cl+t*ml+r*pl}function oa(e,t={}){return{success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,session_id:e,...t}}function hl(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return String(e);let t=e;return typeof t.message?.content=="string"?t.message.content:typeof t.text=="string"?t.text:String(e)}function yl(e){return["[SYSTEM: First turn only. Do not implement yet.]","Start by producing a concise implementation plan only.","Then end your response with an explicit question asking whether you should proceed with implementation.","",e].join(`
43
- `)}function sa(e){return e instanceof Error?e.message:String(e)}function xl(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Sl(e){return ul(dl(e)).root||"/"}function Tl(e){let n=[Sl(e)];return n.push(...xl(process.env[fl])),[...new Set(n)]}function bl(e,t){let r=(t??e.permissionMode)==="bypassPermissions"?Tl(e.cwd):void 0;return{model:e.model,modelReasoningEffort:e.reasoningEffort,workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:e.codexApprovalPolicy??"on-request",skipGitRepoCheck:!0,additionalDirectories:r}}var Gn=class{constructor(t={}){this.deps=t}name="codex";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=[ra];planApprovalToolNames=[];activityHeartbeatMs(){let t=Number.parseInt(process.env[ll]??String(na),10);return!Number.isFinite(t)||t<=0?na:t}createCodexClient(t){return this.deps.createCodex?.({env:t})??(t?new ta({env:t}):new ta)}launch(t){let r=process.env[gl]==="legacy"?void 0:this.deps.createAuthWorkspace?.(process.env)??ea(process.env),o=t.permissionMode==="plan",i=t.permissionMode==="plan"?"default":t.permissionMode,s=t.resumeSessionId,c=0,p=0,f=this.activityHeartbeatMs(),b,k,X=!1,ge=!0,Y,W=!1,Q=[],N=null,He=!1,be=!1;function yt(){N&&(N(),N=null)}function ot(G){Q.push(G),yt()}function Xr(){He=!0,yt()}function Ia(G){!G||be||(be=!0,ot({type:"init",session_id:G}))}async function*ha(){for(;;){for(;Q.length>0;)yield Q.shift();if(He)return;await new Promise(G=>{N=G})}}let un=()=>bl(t,i),ya=G=>(b||(b=this.createCodexClient(G)),k||(ge&&t.resumeSessionId?k=b.resumeThread(t.resumeSessionId,un()):s?k=b.resumeThread(s,un()):k=b.startThread(un())),X&&s&&(k=b.resumeThread(s,un()),X=!1),k),Qr=async G=>{let er=Date.now();p+=1;let Zr="",tr=!1,eo=!1,nr,rr,to=!1,xa=ge&&o?yl(G):G,dn=st=>{tr||(tr=!0,ot({type:"result",data:oa(s??"",{duration_ms:Date.now()-er,total_cost_usd:c,num_turns:p,...st,session_id:s??""})}))},or=async()=>{!rr||to||(to=!0,await rr())};try{let st=r?await r:void 0;st&&(rr=await st.prepareForTurn());let sr=ya(st?.env),no=sr.id??s??void 0;no&&(s=no),Y=new AbortController,t.abortController?.signal.aborted&&Y.abort(t.abortController.signal.reason),nr=setInterval(()=>{ot({type:"activity"})},f);let Sa=await sr.runStreamed(xa,{signal:Y.signal});for await(let re of Sa.events)if(await or(),re.type==="thread.started"&&(s=re.thread_id),Ia(s??sr.id??void 0),re.type!=="thread.started"){if(re.type==="item.completed"){(re.item.type==="agent_message"||re.item.type==="reasoning")&&(Zr+=`${re.item.text}
44
- `,ot({type:"text",text:re.item.text}));continue}if(re.type==="error"){Y?.signal.aborted&&W||ot({type:"text",text:`[codex:error] ${re.message}`});continue}if(re.type==="turn.failed"){if(Y?.signal.aborted&&W){W=!1,eo=!0,X=!0;break}dn({success:!1,result:re.error.message,session_id:s??""});continue}if(re.type==="turn.completed"){c+=Il(re.usage);let ro=Zr.slice(-500);jn(ro)&&ot({type:"tool_use",name:ra,input:{text:ro}}),dn({success:!0,session_id:s??""})}}if(await or(),eo)return;tr||dn({success:!1,result:"Codex turn ended without terminal event",session_id:s??""})}catch(st){if(await or(),Y?.signal.aborted&&W){W=!1,X=!0;return}dn({success:!1,result:sa(st),session_id:s??""})}finally{nr&&clearInterval(nr),Y=void 0,ge=!1}},Zn=()=>{Y?.abort(t.abortController?.signal.reason??"interrupted")};return t.abortController?.signal&&t.abortController.signal.addEventListener("abort",Zn),(async()=>{try{let G=t.prompt;if(typeof G=="string"){await Qr(G);return}for await(let er of G)if(t.abortController?.signal.aborted||(await Qr(hl(er)),t.abortController?.signal.aborted))break}finally{if(t.abortController?.signal.removeEventListener("abort",Zn),r)try{await(await r).cleanup()}catch{}Xr()}})().catch(G=>{ot({type:"result",data:oa(s??"",{success:!1,result:sa(G),total_cost_usd:c,num_turns:p,session_id:s??""})}),t.abortController?.signal.removeEventListener("abort",Zn),Xr()}),{messages:ha(),async setPermissionMode(G){i=G,X=!0},async interrupt(){Y&&(W=!0,Y.abort("interrupted"))}}}buildUserMessage(t,n){return{type:"user",text:t,session_id:n}}};var Wr=new Map;function ia(e){Wr.set(e.name,e)}function qr(e){let t=Wr.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...Wr.keys()].join(", ")}`);return t}function aa(){return qr(tt())}ia(new Kn);ia(new Gn);var ua=200,Al=120*1e3;function Vn(e){return e instanceof Error?e.message:String(e)}var Pl={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},zr=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(t){this.queue.push(t),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})}}},Hn=class extends wl{id;name;harnessSessionId;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;multiTurn;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;pendingPlanApproval=!1;lobsterResumeToken;killReason="unknown";waitingForInputFired=!1;lastTurnHadQuestion=!1;planModeApproved=!1;turnInProgress=!0;autoRespondCount=0;timers=new Map;constructor(t,n){super(),this.id=Wi(8),this.name=n,this.harness=t.harness?qr(t.harness):aa(),this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??nt(this.harness.name),this.reasoningEffort=t.reasoningEffort??Ut(this.harness.name),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??F.permissionMode,this.codexApprovalPolicy=this.harness.name==="codex"?t.codexApprovalPolicy??gt(this.harness.name)??F.codexApprovalPolicy:void 0,this.currentPermissionMode=this.harness.name==="codex"&&this.permissionMode==="plan"?"default":this.permissionMode,this.originChannel=t.originChannel,this.originThreadId=t.originThreadId,this.originAgentId=t.originAgentId,this.originSessionKey=t.originSessionKey,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.startedAt=Date.now(),this.abortController=new AbortController}get status(){return this._status}get harnessName(){return this.harness.name}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this._status!=="running"?this._status:this.harness.name==="codex"?"implementing":this.pendingPlanApproval?"awaiting-plan-approval":this.currentPermissionMode==="plan"?"planning":"implementing"}transition(t){if(!Pl[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let n=this._status;this._status=t,this.emit("statusChange",this,t,n)}setTimer(t,n,r){this.clearTimer(t),this.timers.set(t,setTimeout(r,n))}clearTimer(t){let n=this.timers.get(t);n&&(clearTimeout(n),this.timers.delete(t))}clearAllTimers(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}async start(){try{let t;this.multiTurn?(this.messageStream=new zr,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let n=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,abortController:this.abortController,mcpServers:bi()});this.harnessHandle=n,this.setTimer("startup",Al,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let n=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:n});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let n=t instanceof Error?t.message:String(t),r=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${n}`,r),this.isActive&&this.transitionToTerminal("failed",{error:n})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.waitingForInputFired=!1,this.turnInProgress=!0;let n=t;if(this.pendingModeSwitch){let r=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(r),this.currentPermissionMode=r,this.pendingModeSwitch=void 0,i=!0,o=!0}catch(s){throw console.error(`[Session ${this.id}] setPermissionMode(${r}) FAILED: ${Vn(s)}`),this.pendingPlanApproval=!0,new Error(`Failed to switch permission mode to ${r}: ${Vn(s)}`)}else this.pendingModeSwitch=void 0,i=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);i&&(this.pendingPlanApproval=!1,r!=="plan"&&(this.planModeApproved=!0)),o&&(n=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
80
+ `)}`}}let n=!1;r.startsWith("--fork ")&&(n=!0,r=r.slice(7).trim());let o=r.indexOf(" "),s,i;o===-1?(s=r,i="Continue where you left off."):(s=r.slice(0,o),i=r.slice(o+1).trim()||"Continue where you left off.");let a=I.resolveHarnessSessionId(s);if(!a)return{text:`Error: Could not find a session ID for "${s}".
81
+ Use /agent_resume --list to see available sessions.`};let d=I.resolve(s),m=I.getPersistedSession(s),{resumeSessionId:y,clearedPersistedCodexResume:f}=Zt({requestedResumeSessionId:a,activeSession:d?{harnessSessionId:d.harnessSessionId}:void 0,persistedSession:m?{harness:m.harness}:void 0}),c=m?.workdir??process.cwd(),w=m?.harness??pt(),S=m?.model??mt(w);try{if(!S)return{text:`Error: No default model configured for harness "${w}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${w}.defaultModel or pass model explicitly when launching a fresh session.`};let k=I.spawn({prompt:i,workdir:c,name:m?.name,model:S,codexApprovalPolicy:d?.codexApprovalPolicy??m?.codexApprovalPolicy,resumeSessionId:y,forkSession:y?n:!1,originChannel:Jt(t),originThreadId:Xt(t)??m?.originThreadId,originAgentId:t?.agentId??m?.originAgentId,originSessionKey:t?.sessionKey??m?.originSessionKey,harness:w}),x=i.length>80?i.slice(0,80)+"...":i;return{text:[`Session resumed${n?" (forked)":""}.`,` Name: ${k.name}`,` ID: ${k.id}`,y?` Resume from: ${a}`:" Resume from: fresh thread",` Dir: ${c}`,` Prompt: "${x}"`,f?" Note: cleared persisted Codex thread state after restart to avoid org-mismatch resume failures.":""].join(`
82
+ `)}}catch(k){let x=Dm(k),T=x.includes("Max sessions")?"":`
45
83
 
46
- ${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved){let r=this.harness.planApprovalToolNames;if(n=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below,${r.length>0?` then call ${r.join(" or ")} again to re-submit for approval.`:" then re-submit your revised plan for approval."} Do NOT start implementing yet.]
84
+ Use /agent_sessions to see active sessions or /agent_resume --list to see resumable sessions.`;return{text:`Error resuming session: ${x}${T}`}}}})}function Ta(e){e.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:`Usage: /agent_respond <id-or-name> <message>
85
+ /agent_respond --interrupt <id-or-name> <message>`};let n=!1,o=r;o.startsWith("--interrupt ")&&(n=!0,o=o.slice(12).trim());let s=o.indexOf(" ");if(s===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let i=o.slice(0,s),a=o.slice(s+1).trim();return a?{text:(await ft(I,{session:i,message:a,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}function Aa(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=I.getMetrics(),r=I.list("running").length;return{text:Qr(t,r)}}})}var Lm=50;function $a(e){e.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let n=r.split(/\s+/),o="",s=!1,i=Lm;for(let d=0;d<n.length;d++)if(n[d]==="--full")s=!0;else if(n[d]==="--lines"&&d+1<n.length){let m=parseInt(n[d+1],10);!isNaN(m)&&m>0&&(i=m),d++}else o||(o=n[d]);return o?{text:Yr(I,o,{full:s,lines:i})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}import{existsSync as ag}from"fs";import{EventEmitter as Cf}from"events";import{appendFileSync as Mf}from"fs";import{tmpdir as Of}from"os";import{join as Ef}from"path";import{webcrypto as Ca}from"node:crypto";var Ra="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Km=128,Ot,rr;function jm(e){!Ot||Ot.length<e?(Ot=Buffer.allocUnsafe(e*Km),Ca.getRandomValues(Ot),rr=0):rr+e>Ot.length&&(Ca.getRandomValues(Ot),rr=0),rr+=e}function Ma(e=21){jm(e|=0);let t="";for(let r=rr-e;r<rr;r++)t+=Ra[Ot[r]&63];return t}import{query as Bm}from"@anthropic-ai/claude-agent-sdk";import{dirname as Oa,join as Ea}from"path";import{fileURLToPath as Wm}from"url";import{createRequire as Gm}from"module";var ln=class{name="claude-code";supportedPermissionModes=["default","plan","bypassPermissions"];questionToolNames=["AskUserQuestion"];planApprovalToolNames=["ExitPlanMode","set_permission_mode"];launch(t){let r=t.canUseTool,n={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,pathToClaudeCodeExecutable:(()=>{try{let i=Gm(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return Ea(Oa(i),"cli.js")}catch{let s=Oa(Wm(import.meta.url));return Ea(s,"..","node_modules","@anthropic-ai","claude-agent-sdk","cli.js")}})(),allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers,...r?{canUseTool:async(s,i)=>s==="AskUserQuestion"?r(s,i):{behavior:"allow"}}:{}};t.resumeSessionId&&(n.resume=t.resumeSessionId,n.forkSession=t.forkSession??!1);let o=Bm({prompt:t.prompt,options:n});return{messages:this.adaptMessages(o),async setPermissionMode(s){typeof o.setPermissionMode=="function"&&await o.setPermissionMode(s)},async streamInput(s){typeof o.streamInput=="function"&&await o.streamInput(s)},async interrupt(){typeof o.interrupt=="function"&&await o.interrupt()}}}buildUserMessage(t,r){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:r}}async*adaptMessages(t){for await(let r of t){let n=r;if(n.type==="system"&&n.subtype==="init")yield{type:"init",session_id:n.session_id??""};else if(n.type==="system"&&n.subtype==="status"&&n.permissionMode)yield{type:"permission_mode_change",mode:n.permissionMode};else if(n.type==="assistant")for(let o of n.message?.content??[])o.type==="text"?yield{type:"text",text:o.text}:o.type==="tool_use"&&(yield{type:"tool_use",name:o.name,input:o.input});else n.type==="result"&&(yield{type:"result",data:{success:n.subtype==="success",duration_ms:n.duration_ms??0,total_cost_usd:n.total_cost_usd??0,num_turns:n.num_turns??0,result:n.result,session_id:n.session_id??""}})}}};import{parse as ff,resolve as gf}from"path";import{Codex as ja}from"@openai/codex-sdk";import{randomUUID as Hm}from"node:crypto";import{lstat as Vm,mkdir as xo,readFile as Fa,readlink as qm,realpath as zm,rename as Qm,rm as pn,symlink as Ym,writeFile as Na}from"node:fs/promises";import{homedir as Jm,tmpdir as Ua}from"node:os";import{dirname as Xm,join as je,resolve as Zm}from"node:path";var ef=50,tf=3e4,rf=je(Ua(),"openclaw-codex-auth.lock");function nf(e,t){let r={};for(let[n,o]of Object.entries(e))typeof o=="string"&&(r[n]=o);return r.HOME=t,r}function of(e){return new Promise(t=>setTimeout(t,e))}async function Da(e){try{return await Vm(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function va(e,t){if(await Da(t)){if(await qm(t)===e)return;await pn(t,{recursive:!0,force:!0})}await Ym(e,t)}function sf(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return null;let r=Number(t);if(Number.isFinite(r))return r;let n=Date.parse(t);if(Number.isFinite(n))return n}return null}async function _a(e){let t;try{t=await Fa(e,"utf8")}catch(r){return r.code==="ENOENT",null}try{let r=JSON.parse(t);if(!r||typeof r!="object")return null;let n=sf(r.last_refresh);return n===null?null:{lastRefresh:n,raw:t}}catch{return null}}async function La(e,t){await xo(Xm(e),{recursive:!0});let r=`${e}.tmp`;await Na(r,t,"utf8"),await Qm(r,e)}async function af(e,t){try{let r=await Fa(e,"utf8");await La(t,r)}catch(r){if(r.code!=="ENOENT")throw r;await pn(t,{force:!0})}}async function uf(e,t){let r=await _a(e);if(!r)return;let n=await _a(t);n&&r.lastRefresh<=n.lastRefresh||await La(t,r.raw)}async function cf(e,t,r){let n=Date.now()+t;for(;;)try{await xo(e);break}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=n)throw new Error(`Timed out waiting for Codex auth lock at ${e}`);await of(r)}try{await Na(je(e,"holder.json"),JSON.stringify({pid:process.pid,acquired_at:new Date().toISOString()}),"utf8")}catch{}let o=!1;return async()=>{o||(o=!0,await pn(e,{recursive:!0,force:!0}))}}async function Ka(e=process.env,t={}){let r=e.HOME??Jm(),n=await zm(r).catch(()=>Zm(r)),o=je(n,".codex"),s=je(o,"auth.json"),i=je(o,"sessions"),a=je(o,"config.toml"),d=await Da(a)?a:void 0,m=t.tempRootDir??Ua(),y=je(m,`openclaw-codex-auth-${Hm()}`),f=je(y,".codex"),c=je(f,"auth.json"),w=t.lockDir??rf,S=t.lockTimeoutMs??tf,k=t.lockRetryMs??ef;return await xo(f,{recursive:!0}),await va(i,je(f,"sessions")),d&&await va(d,je(f,"config.toml")),{tempHome:y,tempCodexDir:f,canonicalHome:n,canonicalCodexDir:o,canonicalAuthPath:s,canonicalSessionsPath:i,canonicalConfigPath:d,env:nf(e,y),async prepareForTurn(){let x=await cf(w,S,k);try{await af(s,c)}catch(b){throw await x(),b}let T=!1;return async()=>{if(!T){T=!0;try{await uf(c,s)}finally{await x()}}}},async cleanup(){await pn(y,{recursive:!0,force:!0})}}}var df=["proceed","continue","implement","apply","run","merge","deploy","commit"],lf=["shall i proceed","do you want me to","would you like me to","please confirm","should i continue","can i proceed","should i proceed","should i go ahead","want me to continue","approve and i'll","confirm and i'll"],pf=["why this failed was","why did this fail","what failed","what happened","how can i help","is this clear","any questions","anything else","let me know","would you like a summary"];function mf(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function mn(e){let t=mf(e);if(!t||pf.some(n=>t.includes(n)))return!1;let r=df.some(n=>t.includes(n));return lf.some(n=>t.includes(n))?r||t.includes("confirm"):t.endsWith("?")?r:!1}var Ba=1e4,Wa="codex:waiting-for-user",hf=1.1/1e6,yf=.275/1e6,If=4.4/1e6,wf="OPENCLAW_CODEX_HEARTBEAT_MS",Sf="OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS",xf="OPENCLAW_CODEX_AUTH_STRATEGY";function bf(e){if(!e)return 0;let t=e.cached_input_tokens??0,r=Math.max(0,(e.input_tokens??0)-t),n=e.output_tokens??0;return r*hf+t*yf+n*If}function Ga(e,t={}){return{success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,session_id:e,...t}}function kf(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return String(e);let t=e;return typeof t.message?.content=="string"?t.message.content:typeof t.text=="string"?t.text:String(e)}function Pf(e){return["[SYSTEM: First turn only. Do not implement yet.]","Start by producing a concise implementation plan only.","Then end your response with an explicit question asking whether you should proceed with implementation.","",e].join(`
86
+ `)}function Ha(e){return e instanceof Error?e.message:String(e)}function Tf(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Af(e){return ff(gf(e)).root||"/"}function $f(e){let r=[Af(e)];return r.push(...Tf(process.env[Sf])),[...new Set(r)]}function Rf(e,t){let n=(t??e.permissionMode)==="bypassPermissions"?$f(e.cwd):void 0;return{model:e.model,modelReasoningEffort:e.reasoningEffort,workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:e.codexApprovalPolicy??"on-request",skipGitRepoCheck:!0,additionalDirectories:n}}var fn=class{constructor(t={}){this.deps=t}name="codex";supportedPermissionModes=["default","plan","bypassPermissions"];questionToolNames=[Wa];planApprovalToolNames=[];activityHeartbeatMs(){let t=Number.parseInt(process.env[wf]??String(Ba),10);return!Number.isFinite(t)||t<=0?Ba:t}createCodexClient(t){return this.deps.createCodex?.({env:t})??(t?new ja({env:t}):new ja)}launch(t){let n=process.env[xf]==="legacy"?void 0:this.deps.createAuthWorkspace?.(process.env)??Ka(process.env),o=t.permissionMode==="plan",s=t.permissionMode==="plan"?"default":t.permissionMode,i=t.resumeSessionId,a=0,d=0,m=this.activityHeartbeatMs(),y,f,c=!1,w=!0,S,k=!1,x=[],T=null,b=!1,E=!1;function P(){T&&(T(),T=null)}function A(X){x.push(X),P()}function de(){b=!0,P()}function ke(X){!X||E||(E=!0,A({type:"init",session_id:X}))}async function*ht(){for(;;){for(;x.length>0;)yield x.shift();if(b)return;await new Promise(X=>{T=X})}}let Et=()=>Rf(t,s),Tn=X=>(y||(y=this.createCodexClient(X)),f||(w&&t.resumeSessionId?f=y.resumeThread(t.resumeSessionId,Et()):i?f=y.resumeThread(i,Et()):f=y.startThread(Et())),c&&i&&(f=y.resumeThread(i,Et()),c=!1),f),tt=async X=>{let An=Date.now();d+=1;let $o="",$n=!1,Ro=!1,Rn,Cn,Co=!1,tu=w&&o?Pf(X):X,Pr=yt=>{$n||($n=!0,A({type:"result",data:Ga(i??"",{duration_ms:Date.now()-An,total_cost_usd:a,num_turns:d,...yt,session_id:i??""})}))},Mn=async()=>{!Cn||Co||(Co=!0,await Cn())};try{let yt=n?await n:void 0;yt&&(Cn=await yt.prepareForTurn());let On=Tn(yt?.env),Mo=On.id??i??void 0;Mo&&(i=Mo),S=new AbortController,t.abortController?.signal.aborted&&S.abort(t.abortController.signal.reason),Rn=setInterval(()=>{A({type:"activity"})},m);let ru=await On.runStreamed(tu,{signal:S.signal});for await(let le of ru.events)if(await Mn(),le.type==="thread.started"&&(i=le.thread_id),ke(i??On.id??void 0),le.type!=="thread.started"){if(le.type==="item.completed"){(le.item.type==="agent_message"||le.item.type==="reasoning")&&($o+=`${le.item.text}
87
+ `,A({type:"text",text:le.item.text}));continue}if(le.type==="error"){S?.signal.aborted&&k||A({type:"text",text:`[codex:error] ${le.message}`});continue}if(le.type==="turn.failed"){if(S?.signal.aborted&&k){k=!1,Ro=!0,c=!0;break}Pr({success:!1,result:le.error.message,session_id:i??""});continue}if(le.type==="turn.completed"){a+=bf(le.usage);let Oo=$o.slice(-500);mn(Oo)&&A({type:"tool_use",name:Wa,input:{text:Oo}}),Pr({success:!0,session_id:i??""})}}if(await Mn(),Ro)return;$n||Pr({success:!1,result:"Codex turn ended without terminal event",session_id:i??""})}catch(yt){if(await Mn(),S?.signal.aborted&&k){k=!1,c=!0;return}Pr({success:!1,result:Ha(yt),session_id:i??""})}finally{Rn&&clearInterval(Rn),S=void 0,w=!1}},We=()=>{S?.abort(t.abortController?.signal.reason??"interrupted")};return t.abortController?.signal&&t.abortController.signal.addEventListener("abort",We),(async()=>{try{let X=t.prompt;if(typeof X=="string"){await tt(X);return}for await(let An of X)if(t.abortController?.signal.aborted||(await tt(kf(An)),t.abortController?.signal.aborted))break}finally{if(t.abortController?.signal.removeEventListener("abort",We),n)try{await(await n).cleanup()}catch{}de()}})().catch(X=>{A({type:"result",data:Ga(i??"",{success:!1,result:Ha(X),total_cost_usd:a,num_turns:d,session_id:i??""})}),t.abortController?.signal.removeEventListener("abort",We),de()}),{messages:ht(),async setPermissionMode(X){s=X,c=!0},async interrupt(){S&&(k=!0,S.abort("interrupted"))}}}buildUserMessage(t,r){return{type:"user",text:t,session_id:r}}};var bo=new Map;function Va(e){bo.set(e.name,e)}function ko(e){let t=bo.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...bo.keys()].join(", ")}`);return t}function qa(){return ko(pt())}Va(new ln);Va(new fn);var za=2e3,vf=120*1e3;function gn(e){return e instanceof Error?e.message:String(e)}var _f={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},Po=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(t){this.queue.push(t),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})}}},hn=class extends Cf{id;name;harnessSessionId;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;worktreePath;originalWorkdir;worktreeBranch;worktreeStrategy;worktreeBaseBranch;outputMode;multiTurn;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;pendingPlanApproval=!1;planFilePath;killReason="unknown";waitingForInputFired=!1;lastTurnHadQuestion=!1;planModeApproved=!1;turnInProgress=!0;canUseTool;autoRespondCount=0;timers=new Map;constructor(t,r){super(),this.id=Ma(8),this.name=r,this.harness=t.harness?ko(t.harness):qa(),this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??mt(this.harness.name),this.reasoningEffort=t.reasoningEffort??Yt(this.harness.name),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??N.permissionMode,this.codexApprovalPolicy=this.harness.name==="codex"?t.codexApprovalPolicy??$t(this.harness.name)??N.codexApprovalPolicy:void 0,this.currentPermissionMode=this.harness.name==="codex"&&this.permissionMode==="plan"?"default":this.permissionMode,this.originChannel=t.originChannel,this.originThreadId=t.originThreadId,this.originAgentId=t.originAgentId,this.originSessionKey=t.originSessionKey,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.worktreeStrategy=t.worktreeStrategy,this.worktreeBaseBranch=t.worktreeBaseBranch,this.outputMode=t.outputMode,this.canUseTool=t.canUseTool,this.startedAt=Date.now(),this.abortController=new AbortController}get status(){return this._status}get harnessName(){return this.harness.name}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this._status!=="running"?this._status:this.harness.name==="codex"?"implementing":this.pendingPlanApproval?"awaiting-plan-approval":this.currentPermissionMode==="plan"?"planning":"implementing"}transition(t){if(!_f[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let r=this._status;this._status=t,this.emit("statusChange",this,t,r)}setTimer(t,r,n){this.clearTimer(t),this.timers.set(t,setTimeout(n,r))}clearTimer(t){let r=this.timers.get(t);r&&(clearTimeout(r),this.timers.delete(t))}clearAllTimers(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}async start(){try{let t;this.multiTurn?(this.messageStream=new Po,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let r=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,abortController:this.abortController,mcpServers:Qi(),canUseTool:this.canUseTool});this.harnessHandle=r,this.setTimer("startup",vf,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let r=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:r});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let r=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${r}`,n),this.isActive&&this.transitionToTerminal("failed",{error:r})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.waitingForInputFired=!1,this.turnInProgress=!0;let r=t;if(this.pendingModeSwitch){let n=this.pendingModeSwitch,o=!1,s=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(n),this.currentPermissionMode=n,this.pendingModeSwitch=void 0,s=!0,o=!0}catch(i){throw console.error(`[Session ${this.id}] setPermissionMode(${n}) FAILED: ${gn(i)}`),this.pendingPlanApproval=!0,new Error(`Failed to switch permission mode to ${n}: ${gn(i)}`)}else this.pendingModeSwitch=void 0,s=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);s&&(this.pendingPlanApproval=!1,n!=="plan"&&(this.planModeApproved=!0)),o&&(r=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
47
88
 
48
- ${t}`,this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan"}catch(i){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${Vn(i)}`)}}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(n,this.harnessSessionId??""));else if(this.harnessHandle?.streamInput){let r=this.harness.buildUserMessage(n,this.harnessSessionId??"");async function*o(){yield r}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){return!this.turnInProgress||!this.harnessHandle?.interrupt?!1:(await this.harnessHandle.interrupt(),!0)}switchPermissionMode(t){this.pendingModeSwitch=t}get isActive(){return this._status==="starting"||this._status==="running"}kill(t){this.transitionToTerminal("killed",{reason:t})}complete(t="done"){this.transitionToTerminal("completed",{reason:t})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}resetIdleTimer(){if(!this.multiTurn)return;let t=(F.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",t,()=>{this._status==="running"&&this.kill("idle-timeout")})}teardown(){this.clearAllTimers(),this.completedAt||(this.completedAt=Date.now()),this.messageStream&&this.messageStream.end(),this.harnessHandle?.interrupt&&this.harnessHandle.interrupt().catch(t=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${Vn(t)}`)}),this.abortController.abort()}transitionToTerminal(t,n={}){this.isActive&&(this.turnInProgress=!1,n.reason&&(this.killReason=n.reason),n.error!==void 0&&(this.error=n.error),this.completedAt=Date.now(),this.transition(t),this.teardown())}async consumeMessages(t){for await(let n of t){if(!this.isActive)break;if(this.resetIdleTimer(),n.type==="init")this.clearTimer("startup"),this.harnessSessionId=n.session_id,this._status==="starting"&&this.transition("running");else if(n.type==="text")this.waitingForInputFired=!1,this.pendingPlanApproval||(this.lastTurnHadQuestion=!1),this.outputBuffer.push(n.text),this.outputBuffer.length>ua&&this.outputBuffer.splice(0,this.outputBuffer.length-ua),this.emit("output",this,n.text);else if(n.type==="tool_use")this.harness.questionToolNames.includes(n.name)?(this.lastTurnHadQuestion=!0,this.currentPermissionMode==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0)):this.harness.planApprovalToolNames.includes(n.name)&&!this.planModeApproved&&(this.lastTurnHadQuestion=!0,this.pendingPlanApproval=!0),this.emit("toolUse",this,n.name,n.input);else if(n.type==="permission_mode_change"){let r=this.currentPermissionMode;this.currentPermissionMode=n.mode,n.mode!=="plan"&&r==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0,this.lastTurnHadQuestion=!0)}else if(n.type==="result"){if(this.result={subtype:n.data.success?"success":"error",duration_ms:n.data.duration_ms,total_cost_usd:n.data.total_cost_usd,num_turns:n.data.num_turns,result:n.data.result,is_error:!n.data.success,session_id:n.data.session_id},this.costUsd=n.data.total_cost_usd,this.multiTurn&&this.messageStream&&n.data.success){this.resetIdleTimer(),this.currentPermissionMode==="plan"&&!this.pendingPlanApproval&&!this.planModeApproved&&(this.pendingPlanApproval=!0);let o=this.pendingPlanApproval||this.lastTurnHadQuestion,i=this.messageStream?.hasPending()===!0;this.turnInProgress=i,o&&!this.waitingForInputFired?(this.waitingForInputFired=!0,this.emit("turnEnd",this,!0)):i||o||(this.emit("turnEnd",this,!1),this.complete("done"))}else this.turnInProgress=!1,this.transitionToTerminal(n.data.success?"completed":"failed");this.lastTurnHadQuestion=!1}else n.type}}};import{mkdirSync as Rl,readFileSync as Ol,readdirSync as Cl,renameSync as Ml,statSync as El,unlinkSync as Fl,writeFileSync as da}from"fs";import{homedir as kl,tmpdir as ca}from"os";import{dirname as $l,join as Wn}from"path";function vl(e){let t=e.OPENCLAW_HOME?.trim();return t||Wn(kl(),".openclaw")}function Nl(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||Wn(vl(e),"code-agent-sessions.json")}var Ul=new Set(["completed","failed","killed"]),_l=new Set(["running","completed","failed","killed"]),Ll=1440*60*1e3;function ma(e){return e instanceof Error?e.message:String(e)}function Kl(e){return!!e&&typeof e=="object"}function Bn(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function ht(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function pa(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Dl(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function jl(e){return e==="default"||e==="plan"||e==="acceptEdits"||e==="bypassPermissions"?e:void 0}function Gl(e){return e==="never"||e==="on-request"?e:void 0}function Vl(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function Hl(e){if(typeof e=="string"&&_l.has(e))return e==="running"?"killed":e}function Bl(e){if(!Kl(e))return;let t=Bn(e.harnessSessionId);if(!t)return;let n=Hl(e.status);if(n)return{sessionId:ht(e.sessionId),harnessSessionId:t,name:Bn(e.name,t),prompt:Bn(e.prompt),workdir:Bn(e.workdir,"(unknown)"),model:ht(e.model),reasoningEffort:Dl(e.reasoningEffort),createdAt:pa(e.createdAt),completedAt:pa(e.completedAt),status:n,killReason:Vl(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:ht(e.originAgentId),originChannel:ht(e.originChannel),originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originSessionKey:ht(e.originSessionKey),outputPath:ht(e.outputPath),harness:ht(e.harness),currentPermissionMode:jl(e.currentPermissionMode),codexApprovalPolicy:Gl(e.codexApprovalPolicy)}}var qn=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;indexPath;constructor(t={}){let n=t.env??process.env;this.indexPath=t.indexPath??Nl(n),n.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){try{let t=Ol(this.indexPath,"utf-8"),n=JSON.parse(t);if(!Array.isArray(n))return;let r=!1;for(let o of n){let i=Bl(o);if(!i){r=!0;continue}this.persisted.set(i.harnessSessionId,i),i.sessionId&&this.idIndex.set(i.sessionId,i.harnessSessionId),i.name&&this.nameIndex.set(i.name,i.harnessSessionId)}r&&this.saveIndex()}catch{}}saveIndex(){try{Rl($l(this.indexPath),{recursive:!0});let t=this.indexPath+".tmp";da(t,JSON.stringify([...this.persisted.values()],null,2),"utf-8"),Ml(t,this.indexPath)}catch(t){console.warn(`[SessionStore] Failed to save session index: ${ma(t)}`)}}markRunning(t){if(!t.harnessSessionId)return;let n={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy};this.persisted.set(n.harnessSessionId,n),this.idIndex.set(t.id,n.harnessSessionId),this.nameIndex.set(t.name,n.harnessSessionId),this.saveIndex()}hasRecordedSession(t){return this.idIndex.has(t)}persistTerminal(t){if(!t.harnessSessionId)return;let n;try{let o=Wn(ca(),`openclaw-agent-${t.id}.txt`),i=t.getOutput().join(`
49
- `);i.length>0&&(da(o,i,"utf-8"),n=o)}catch(o){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${ma(o)}`)}let r={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,completedAt:t.completedAt,status:t.status,killReason:t.killReason,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,outputPath:n,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy};this.persisted.set(t.harnessSessionId,r),this.idIndex.set(t.id,t.harnessSessionId),this.nameIndex.set(t.name,t.harnessSessionId),this.saveIndex()}getLatestPersistedByName(t){let n,r=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=0;for(let c of this.persisted.values()){if(c.name!==t){s++;continue}let p=c.createdAt??Number.NEGATIVE_INFINITY,f=c.completedAt??Number.NEGATIVE_INFINITY;(p>r||p===r&&f>o||p===r&&f===o&&s>i)&&(n=c,r=p,o=f,i=s),s++}return n}resolveHarnessSessionId(t,n){if(n)return n;let r=this.idIndex.get(t);if(r&&this.persisted.has(r))return r;let o=this.getLatestPersistedByName(t);if(o)return o.harnessSessionId;if(this.persisted.has(t)||/^[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){let n=this.persisted.get(t);if(n)return n;let r=this.idIndex.get(t);return r?this.persisted.get(r):this.getLatestPersistedByName(t)}listPersistedSessions(){return[...this.persisted.values()].sort((t,n)=>(n.completedAt??0)-(t.completedAt??0))}cleanupTmpOutputFiles(t){try{let n=ca(),r=Cl(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r)try{let i=Wn(n,o),s=El(i).mtimeMs;t-s>Ll&&Fl(i)}catch{}}catch{}}evictOldestPersisted(t){let n=this.listPersistedSessions();if(n.length<=t)return;let r=n.slice(t);for(let o of r){this.persisted.delete(o.harnessSessionId);for(let[i,s]of this.idIndex)s===o.harnessSessionId&&this.idIndex.delete(i);for(let[i,s]of this.nameIndex)s===o.harnessSessionId&&this.nameIndex.delete(i)}this.saveIndex()}shouldGcActiveSession(t,n,r){return!t.completedAt||!Ul.has(t.status)?!1:n-t.completedAt>r}};var Wl=new Set(["completed","failed","killed"]),zn=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(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),Wl.has(r)&&this.metrics.sessionsByStatus[r]++,t.completedAt){let i=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||n>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:n,prompt:rt(t.prompt,80)})}getMetrics(){return{totalCostUsd:this.metrics.totalCostUsd,costPerDay:new Map(this.metrics.costPerDay),sessionsByStatus:{...this.metrics.sessionsByStatus},totalLaunched:this.metrics.totalLaunched,totalDurationMs:this.metrics.totalDurationMs,sessionsWithDuration:this.metrics.sessionsWithDuration,mostExpensive:this.metrics.mostExpensive?{...this.metrics.mostExpensive}:null}}};import{execFile as ql}from"child_process";import{randomUUID as zl}from"crypto";var la=3e4,Yl=2e3,Jl=2e4,Yn=4,Jn=class{pendingRetryTimers=new Set;clearPendingRetries(){for(let t of this.pendingRetryTimers)clearTimeout(t);this.pendingRetryTimers.clear()}getOriginSessionKey(t){let n=t.originSessionKey?.trim();return n||void 0}getOriginThreadId(t){let n=t.originThreadId;return n==null?void 0:String(n).trim()||void 0}parseNotificationRoute(t){let n=t.originChannel?.trim(),r=this.getOriginThreadId(t);if(n){let s=n.split("|").map(c=>c.trim()).filter(Boolean);if(s.length>=2){let[c,p,f]=s,b=f??p,k=f?p:void 0;if(c&&b)return{channel:c,target:b,accountId:k,threadId:r??this.parseThreadIdFromSessionKey(t.originSessionKey)}}}let o=this.getOriginSessionKey(t);if(!o)return;let i=o.match(/^agent:[^:]+:telegram:(?:direct|dm|group|channel):([^:]+)(?::topic:(\d+))?$/i);if(i?.[1])return{channel:"telegram",target:i[1],threadId:r??i[2]}}parseThreadIdFromSessionKey(t){return t?t.match(/:topic:(\d+)$/)?.[1]:void 0}retryDelayMs(t){let n=Math.max(0,t-1),r=Yl*2**n;return Math.min(r,Jl)}executeWithRetries(t,n,r=1){let o=Date.now();console.info(`[WakeDispatcher] ${n.target} ${n.phase} started attempt ${r}/${Yn} for ${n.label} session=${n.sessionId}`),ql("openclaw",t,{timeout:la},i=>{let s=Date.now()-o;if(!i){console.info(`[WakeDispatcher] ${n.target} ${n.phase} completed attempt ${r}/${Yn} for ${n.label} session=${n.sessionId} in ${s}ms`);return}let c=`[WakeDispatcher] ${n.target} ${n.phase} failed`;if(r>=Yn){console.error(`${c} after ${r} attempts for ${n.label} session=${n.sessionId} in ${s}ms: ${i.message}`),n.onFinalFailure?.();return}let p=this.retryDelayMs(r);console.error(`${c} attempt ${r}/${Yn} for ${n.label} session=${n.sessionId} in ${s}ms: ${i.message}. Retrying in ${p}ms`);let f=setTimeout(()=>{this.pendingRetryTimers.delete(f),this.executeWithRetries(t,n,r+1)},p);this.pendingRetryTimers.add(f)})}fireChatSendWithRetry(t,n,r,o,i,s=!1,c){let p=["gateway","call","chat.send","--expect-final","--timeout",String(la),"--params",JSON.stringify({sessionKey:t,message:n,deliver:s,idempotencyKey:zl()})];this.executeWithRetries(p,{label:r,sessionId:o,target:"chat.send",phase:i,onFinalFailure:c})}fireDirectNotificationWithRetry(t,n,r,o,i){let s=["message","send","--channel",t.channel,"--target",t.target,"--message",n];t.accountId&&s.push("--account",t.accountId),t.threadId&&s.push("--thread-id",t.threadId),this.executeWithRetries(s,{label:r,sessionId:o,target:"message.send",phase:"notify",onFinalFailure:i})}fireSystemEventWithRetry(t,n,r,o){let i=["system","event","--text",t,"--mode","now"];this.executeWithRetries(i,{label:n,sessionId:r,target:"system.event",phase:o})}sendUserNotification(t,n,r,o){let i=this.parseNotificationRoute(t);if(!i){this.fireSystemEventWithRetry(n,`${r}-notify-system`,o,"notify");return}this.fireDirectNotificationWithRetry(i,n,`${r}-notify`,o,()=>{this.fireSystemEventWithRetry(n,`${r}-notify-fallback`,o,"notify")})}dispatchSessionNotification(t,n){let r=this.getOriginSessionKey(t),o=n.notifyUser??(n.wakeMessage?"on-wake-fallback":"always"),i=n.userMessage?.trim(),s=n.wakeMessage?.trim();if(o==="always"&&i&&this.sendUserNotification(t,i,n.label,t.id),!!s){if(!r){o==="on-wake-fallback"&&i&&this.sendUserNotification(t,i,n.label,t.id),this.fireSystemEventWithRetry(s,`${n.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(r,s,`${n.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(s,`${n.label}-wake-fallback`,t.id,"wake")})}}};function Zl(){let e=process.env.OPENCLAW_CODE_AGENT_PLAN_WORKFLOW_PATH?.trim();if(e)return e;let t=Ql(ga(import.meta.url)),n=[Yr(process.cwd(),"workflows","plan-approval.lobster"),Yr(t,"..","workflows","plan-approval.lobster"),Yr(t,"..","..","workflows","plan-approval.lobster")];for(let r of n)if(Xl(r))return r;return ga(new URL("../workflows/plan-approval.lobster",import.meta.url))}var ef=Zl(),Jr=new Set(["completed","failed","killed"]),Xn=new Set(["starting","running"]),tf=5e3,nf=3e4;function rf(e){let t=e.trim();if(!t)return;let n=i=>typeof i=="string"&&i.trim().length>0&&/^[A-Za-z0-9._:-]+$/.test(i.trim()),r=[t];for(let i of t.split(/\r?\n/)){let s=i.trim();s.startsWith("{")&&s.endsWith("}")&&r.push(s)}for(let i of r)try{let s=JSON.parse(i),c=s?.resumeToken??s?.requiresApproval?.resumeToken??s?.details?.requiresApproval?.resumeToken;if(n(c))return c.trim()}catch{}let o=t.match(/"resumeToken"\s*:\s*"([^"]+)"/);if(o&&n(o[1]))return o[1].trim()}var Qn=class{sessions=new Map;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;store;metrics;wakeDispatcher;constructor(t=20,n=50){this.maxSessions=t,this.maxPersistedSessions=n,this.store=new qn,this.metrics=new zn,this.wakeDispatcher=new Jn}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(t){let n=new Set([...this.sessions.values()].filter(o=>Xn.has(o.status)).map(o=>o.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}-${r}`);)r++;return`${t}-${r}`}spawn(t,n={}){if([...this.sessions.values()].filter(c=>Xn.has(c.status)).length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);let o=t.name||Ci(t.prompt),i=this.uniqueName(o);i!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${i}" (active session with same name exists)`);let s=new Hn(t,i);if(this.sessions.set(s.id,s),this.metrics.incrementLaunched(),s.on("statusChange",(c,p)=>{p==="running"&&s.harnessSessionId?this.store.markRunning(s):Jr.has(p)&&this.onSessionTerminal(s)}),s.on("turnEnd",(c,p)=>{this.onTurnEnd(s,p)}),s.start(),n.notifyLaunch!==!1){let c=`\u{1F680} [${s.name}] Launched | ${s.workdir} | ${s.model??"default"}`;this.notifySession(s,c,"launch")}return s}async spawnAndAwaitRunning(t,n={}){let r=this.spawn(t,n);return await this.waitForRunningSession(r),r}async waitForRunningSession(t){if(t.status==="running")return;if(Jr.has(t.status))throw new Error(this.describeLaunchFailure(t));let n=t.on?.bind(t),r=t.off?.bind(t)??t.removeListener?.bind(t);if(!n||!r)throw new Error(`Session ${t.name} [${t.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(p,f)=>{if(f==="running"){c(),o();return}Jr.has(f)&&(c(),i(new Error(this.describeLaunchFailure(t))))},c=()=>{r("statusChange",s)};n("statusChange",s)})}describeLaunchFailure(t){let n=t.killReason?` (reason: ${t.killReason})`:"",r=t.error||t.result?.result||`status=${t.status}${n}`;return`Session ${t.name} [${t.id}] failed to start: ${r}`}onSessionTerminal(t){if(this.persistSession(t),this.lastWaitingEventTimestamps.delete(t.id),t.killReason==="done")return;if(t.status==="completed"){if(!this.shouldEmitTerminalWake(t))return;this.triggerAgentEvent(t);return}if(t.status==="failed"){if(!this.shouldEmitTerminalWake(t))return;let i=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`,s=rt(i,200);this.triggerFailedEvent(t,s);return}let n=`$${(t.costUsd??0).toFixed(2)}`,r=_e(t.duration);if(t.killReason==="idle-timeout"){this.notifySession(t,`\u{1F4A4} [${t.name}] Idle timeout | ${n} | ${r}`);return}let o=this.getStoppedStatusLabel(t.killReason);this.notifySession(t,`\u26D4 [${t.name}] ${o} | ${n} | ${r}`)}getStoppedStatusLabel(t){switch(t){case"user":return"Stopped by user";case"shutdown":return"Stopped by shutdown";case"startup-timeout":return"Stopped by startup timeout";case"unknown":case void 0:return"Stopped unexpectedly";default:return"Stopped"}}persistSession(t){this.store.hasRecordedSession(t.id)||this.metrics.recordSession(t),this.store.persistTerminal(t)}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(t){this.metrics.recordSession(t)}notifySession(t,n,r="notification"){this.dispatchSessionNotification(t,{label:r,userMessage:n,notifyUser:"always"})}dispatchSessionNotification(t,n){this.wakeDispatcher.dispatchSessionNotification(t,n)}runLobsterApproval(t,n){let r=JSON.stringify({session_id:t.id,session_name:t.name,plan_summary:n}),o=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"run",pipeline:ef,argsJson:r,timeoutMs:0})];fa("openclaw",o,{timeout:nf},(i,s,c)=>{if(i){console.error(`[SessionManager] Lobster launch failed for session=${t.id}: ${i.message}`),this.notifySession(t,`\u{1F4CB} [${t.name}] Plan ready \u2014 Lobster gate failed, please review manually:
89
+ ${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved){let n=this.harness.planApprovalToolNames;if(r=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below,${n.length>0?` then call ${n.join(" or ")} again to re-submit for approval.`:" then re-submit your revised plan for approval."} Do NOT start implementing yet.]
50
90
 
51
- ${rt(n,800)}`);return}let p=typeof s=="string"?s:String(s??""),f=typeof c=="string"?c:String(c??""),b=rf(`${p}
52
- ${f}`);if(!b){let X=`${p}
53
- ${f}`.trim().substring(0,200);console.warn(`[SessionManager] Lobster response missing resume token for session=${t.id}: ${X}`)}b&&(t.lobsterResumeToken=b);let k=[`\u{1F4CB} [${t.name}] Plan ready for approval`,"",rt(n,1200),"",`Session: ${t.name} (${t.id})`,"",'To approve: reply "approve"',"To reject: reply with feedback"];this.notifySession(t,k.join(`
54
- `))})}resumeLobsterApproval(t,n){let r=n?3e4:1e4;return new Promise((o,i)=>{let s=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"resume",token:t,approve:n})];fa("openclaw",s,{timeout:r},c=>{c?(console.error(`[SessionManager] Lobster resume failed (approve=${n}): ${c.message}`),i(c)):o()})})}debounceWaitingEvent(t){let n=Date.now(),r=this.lastWaitingEventTimestamps.get(t);return r&&n-r<tf?!1:(this.lastWaitingEventTimestamps.set(t,n),!0)}originThreadLine(t){return t.originThreadId!=null?`Session origin thread: ${t.originThreadId}`:""}extractLastOutputLine(t){return t.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(t,n=1e3){let r=t.getOutput(20).join(`
55
- `);return r.length>n?Ei(r,n):r}triggerAgentEvent(t){let n=this.getOutputPreview(t),r=["Coding agent session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Output preview:",n,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${t.id}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.","3. Notify the user with a summary of what was done."].join(`
56
- `),o=`$${(t.costUsd??0).toFixed(2)}`,i=_e(t.duration),s=`\u2705 [${t.name}] Completed | ${o} | ${i}`;this.dispatchSessionNotification(t,{label:"completed",userMessage:s,wakeMessage:r,notifyUser:"always"})}triggerFailedEvent(t,n){let r=this.getOutputPreview(t),o=r.trim()?["","Output preview:",r]:[],i=["Coding agent session failed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Failure summary:",n,...o,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${t.id}', full=true) to inspect the full failure context.`,"2. If the failure is a launch/config issue or other recoverable error, relaunch the task now or continue it yourself.","3. Notify the user with the failure cause and the next action you are taking."].join(`
57
- `),s=`$${(t.costUsd??0).toFixed(2)}`,c=_e(t.duration),p=[`\u274C [${t.name}] Failed | ${s} | ${c}`,` \u26A0\uFE0F ${n}`].join(`
58
- `);this.dispatchSessionNotification(t,{label:"failed",userMessage:p,wakeMessage:i,notifyUser:"always"})}triggerWaitingForInputEvent(t){if(!this.debounceWaitingEvent(t.id))return;let n=this.getOutputPreview(t),r=t.pendingPlanApproval,o=r?`\u{1F4CB} [${t.name}] Plan ready for review:
91
+ ${t}`,this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan"}catch(s){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${gn(s)}`)}}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(r,this.harnessSessionId??""));else if(this.harnessHandle?.streamInput){let n=this.harness.buildUserMessage(r,this.harnessSessionId??"");async function*o(){yield n}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){return!this.turnInProgress||!this.harnessHandle?.interrupt?!1:(await this.harnessHandle.interrupt(),!0)}switchPermissionMode(t){this.pendingModeSwitch=t}get isActive(){return this._status==="starting"||this._status==="running"}kill(t){this.transitionToTerminal("killed",{reason:t})}complete(t="done"){this.transitionToTerminal("completed",{reason:t})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}resetIdleTimer(){if(!this.multiTurn)return;let t=(N.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",t,()=>{this._status==="running"&&this.kill("idle-timeout")})}teardown(){this.clearAllTimers(),this.completedAt||(this.completedAt=Date.now()),this.messageStream&&this.messageStream.end(),this.harnessHandle?.interrupt&&this.harnessHandle.interrupt().catch(t=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${gn(t)}`)}),this.abortController.abort()}transitionToTerminal(t,r={}){this.isActive&&(this.turnInProgress=!1,r.reason&&(this.killReason=r.reason),r.error!==void 0&&(this.error=r.error),this.completedAt=Date.now(),this.transition(t),this.teardown())}async consumeMessages(t){for await(let r of t){if(!this.isActive)break;if(this.resetIdleTimer(),r.type==="init")this.clearTimer("startup"),this.harnessSessionId=r.session_id,this._status==="starting"&&this.transition("running");else if(r.type==="text"){this.waitingForInputFired=!1,this.pendingPlanApproval||(this.lastTurnHadQuestion=!1),this.outputBuffer.push(r.text),this.outputBuffer.length>za&&this.outputBuffer.splice(0,this.outputBuffer.length-za);try{Mf(Ef(Of(),`openclaw-agent-${this.id}.txt`),r.text+`
92
+ `,"utf-8")}catch{}this.emit("output",this,r.text)}else if(r.type==="tool_use"){if(r.name==="Write"){let n=r.input;typeof n?.file_path=="string"&&n.file_path.includes("/.claude/plans/")&&(this.planFilePath=n.file_path)}this.harness.questionToolNames.includes(r.name)?(this.lastTurnHadQuestion=!0,this.currentPermissionMode==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0)):this.harness.planApprovalToolNames.includes(r.name)&&!this.planModeApproved&&(this.lastTurnHadQuestion=!0,this.pendingPlanApproval=!0),this.emit("toolUse",this,r.name,r.input)}else if(r.type==="permission_mode_change"){let n=this.currentPermissionMode;this.currentPermissionMode=r.mode,r.mode!=="plan"&&n==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0,this.lastTurnHadQuestion=!0)}else if(r.type==="result"){if(this.result={subtype:r.data.success?"success":"error",duration_ms:r.data.duration_ms,total_cost_usd:r.data.total_cost_usd,num_turns:r.data.num_turns,result:r.data.result,is_error:!r.data.success,session_id:r.data.session_id},this.costUsd=r.data.total_cost_usd,this.multiTurn&&this.messageStream&&r.data.success){this.resetIdleTimer(),this.currentPermissionMode==="plan"&&!this.pendingPlanApproval&&!this.planModeApproved&&(this.pendingPlanApproval=!0);let o=this.pendingPlanApproval||this.lastTurnHadQuestion,s=this.messageStream?.hasPending()===!0;this.turnInProgress=s,o&&!this.waitingForInputFired?(this.waitingForInputFired=!0,this.emit("turnEnd",this,!0)):s||o||(this.emit("turnEnd",this,!1),this.complete("done"))}else this.turnInProgress=!1,this.transitionToTerminal(r.data.success?"completed":"failed");this.lastTurnHadQuestion=!1}else r.type}}};import{existsSync as Ff,mkdirSync as Nf,readFileSync as Uf,readdirSync as Df,renameSync as Lf,statSync as Kf,unlinkSync as jf,writeFileSync as Qa}from"fs";import{homedir as Bf,tmpdir as Ya}from"os";import{dirname as Wf,join as In}from"path";function Gf(e){let t=e.OPENCLAW_HOME?.trim();return t||In(Bf(),".openclaw")}function Hf(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||In(Gf(e),"code-agent-sessions.json")}var Vf=new Set(["completed","failed","killed"]),qf=new Set(["running","completed","failed","killed"]),zf=1440*60*1e3;function Ja(e){return e instanceof Error?e.message:String(e)}function Qf(e){return!!e&&typeof e=="object"}function yn(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function Be(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function To(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Yf(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function Jf(e){return e==="default"||e==="plan"||e==="bypassPermissions"?e:void 0}function Xf(e){return e==="never"||e==="on-request"?e:void 0}function Zf(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function eg(e){if(typeof e=="string"&&qf.has(e))return e==="running"?"killed":e}function tg(e){if(!Qf(e))return;let t=yn(e.harnessSessionId);if(!t)return;let r=eg(e.status);if(r)return{sessionId:Be(e.sessionId),harnessSessionId:t,name:yn(e.name,t),prompt:yn(e.prompt),workdir:yn(e.workdir,"(unknown)"),model:Be(e.model),reasoningEffort:Yf(e.reasoningEffort),createdAt:To(e.createdAt),completedAt:To(e.completedAt),status:r,killReason:Zf(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:Be(e.originAgentId),originChannel:Be(e.originChannel),originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originSessionKey:Be(e.originSessionKey),outputPath:Be(e.outputPath),harness:Be(e.harness),currentPermissionMode:Jf(e.currentPermissionMode),codexApprovalPolicy:Xf(e.codexApprovalPolicy),worktreePath:Be(e.worktreePath),worktreeBranch:Be(e.worktreeBranch),worktreeStrategy:e.worktreeStrategy==="off"||e.worktreeStrategy==="manual"||e.worktreeStrategy==="ask"||e.worktreeStrategy==="auto-merge"||e.worktreeStrategy==="auto-pr"?e.worktreeStrategy:void 0,worktreeMerged:typeof e.worktreeMerged=="boolean"?e.worktreeMerged:void 0,worktreeMergedAt:Be(e.worktreeMergedAt),worktreePrUrl:Be(e.worktreePrUrl),worktreePrNumber:To(e.worktreePrNumber)}}var wn=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;indexPath;constructor(t={}){let r=t.env??process.env;this.indexPath=t.indexPath??Hf(r),r.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){try{let t=Uf(this.indexPath,"utf-8"),r=JSON.parse(t);if(!Array.isArray(r))return;let n=!1;for(let o of r){let s=tg(o);if(!s){n=!0;continue}this.persisted.set(s.harnessSessionId,s),s.sessionId&&this.idIndex.set(s.sessionId,s.harnessSessionId),s.name&&this.nameIndex.set(s.name,s.harnessSessionId)}n&&this.saveIndex()}catch{}}saveIndex(){try{Nf(Wf(this.indexPath),{recursive:!0});let t=this.indexPath+".tmp";Qa(t,JSON.stringify([...this.persisted.values()],null,2),"utf-8"),Lf(t,this.indexPath)}catch(t){console.warn(`[SessionStore] Failed to save session index: ${Ja(t)}`)}}markRunning(t){if(!t.harnessSessionId)return;let r={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.originalWorkdir??t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch??(t.worktreePath?se(t.worktreePath):void 0),worktreeStrategy:t.worktreeStrategy};this.persisted.set(r.harnessSessionId,r),this.idIndex.set(t.id,r.harnessSessionId),this.nameIndex.set(t.name,r.harnessSessionId),this.saveIndex()}hasRecordedSession(t){return this.idIndex.has(t)}persistTerminal(t){if(!t.harnessSessionId)return;let r;try{let o=In(Ya(),`openclaw-agent-${t.id}.txt`);if(Ff(o))r=o;else{let s=t.getOutput().join(`
93
+ `);s.length>0&&(Qa(o,s,"utf-8"),r=o)}}catch(o){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${Ja(o)}`)}let n={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.originalWorkdir??t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,completedAt:t.completedAt,status:t.status,killReason:t.killReason,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,outputPath:r,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch??(t.worktreePath?se(t.worktreePath):void 0),worktreeStrategy:t.worktreeStrategy};this.persisted.set(t.harnessSessionId,n),this.idIndex.set(t.id,t.harnessSessionId),this.nameIndex.set(t.name,t.harnessSessionId),this.saveIndex()}getLatestPersistedByName(t){let r,n=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=0;for(let a of this.persisted.values()){if(a.name!==t){i++;continue}let d=a.createdAt??Number.NEGATIVE_INFINITY,m=a.completedAt??Number.NEGATIVE_INFINITY;(d>n||d===n&&m>o||d===n&&m===o&&i>s)&&(r=a,n=d,o=m,s=i),i++}return r}resolveHarnessSessionId(t,r){if(r)return r;let n=this.idIndex.get(t);if(n&&this.persisted.has(n))return n;let o=this.getLatestPersistedByName(t);if(o)return o.harnessSessionId;if(this.persisted.has(t)||/^[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){let r=this.persisted.get(t);if(r)return r;let n=this.idIndex.get(t);return n?this.persisted.get(n):this.getLatestPersistedByName(t)}listPersistedSessions(){return[...this.persisted.values()].sort((t,r)=>(r.completedAt??0)-(t.completedAt??0))}cleanupTmpOutputFiles(t){try{let r=Ya(),n=Df(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let s=In(r,o),i=Kf(s).mtimeMs;t-i>zf&&jf(s)}catch{}}catch{}}evictOldestPersisted(t){let r=this.listPersistedSessions();if(r.length<=t)return;let n=r.slice(t);for(let o of n){this.persisted.delete(o.harnessSessionId);for(let[s,i]of this.idIndex)i===o.harnessSessionId&&this.idIndex.delete(s);for(let[s,i]of this.nameIndex)i===o.harnessSessionId&&this.nameIndex.delete(s)}this.saveIndex()}shouldGcActiveSession(t,r,n){return!t.completedAt||!Vf.has(t.status)?!1:r-t.completedAt>n}};var rg=new Set(["completed","failed","killed"]),Sn=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(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),rg.has(n)&&this.metrics.sessionsByStatus[n]++,t.completedAt){let s=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=s,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||r>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:r,prompt:Rt(t.prompt,80)})}getMetrics(){return{totalCostUsd:this.metrics.totalCostUsd,costPerDay:new Map(this.metrics.costPerDay),sessionsByStatus:{...this.metrics.sessionsByStatus},totalLaunched:this.metrics.totalLaunched,totalDurationMs:this.metrics.totalDurationMs,sessionsWithDuration:this.metrics.sessionsWithDuration,mostExpensive:this.metrics.mostExpensive?{...this.metrics.mostExpensive}:null}}};import{execFile as ng}from"child_process";import{randomUUID as og}from"crypto";var Xa=3e4,sg=2e3,ig=2e4,xn=4,bn=class{pendingRetryTimers=new Map;constructor(){process.on("beforeExit",()=>{this.pendingRetryTimers.size>0&&console.warn(`[WakeDispatcher] beforeExit: ${this.pendingRetryTimers.size} pending retry timer(s) still active \u2014 event loop should stay alive, investigate if process exits prematurely.`)});let t=r=>{this.pendingRetryTimers.size!==0&&console.warn(`[WakeDispatcher] ${r}: ${this.pendingRetryTimers.size} pending retry timer(s) will be abandoned on hard exit.`)};process.once("SIGTERM",()=>t("SIGTERM")),process.once("SIGINT",()=>t("SIGINT"))}clearPendingRetries(){for(let t of this.pendingRetryTimers.values())for(let r of t)clearTimeout(r);this.pendingRetryTimers.clear()}clearRetryTimersForSession(t){let r=this.pendingRetryTimers.get(t);if(r){for(let n of r)clearTimeout(n);this.pendingRetryTimers.delete(t)}}getOriginSessionKey(t){let r=t.originSessionKey?.trim();return r||void 0}getOriginThreadId(t){let r=t.originThreadId;return r==null?void 0:String(r).trim()||void 0}parseNotificationRoute(t){let r=t.originChannel?.trim(),n=this.getOriginThreadId(t);if(r){let a=r.split("|").map(d=>d.trim()).filter(Boolean);if(a.length>=2){let[d,m,y]=a,f=y??m,c=y?m:void 0;if(d&&f){let w=f;if(d==="discord"&&/^\d+$/.test(f)){let k=(t.originSessionKey??"").match(/^agent:[^:]+:discord:(channel|user):/i);k?.[1]&&(w=`${k[1]}:${f}`)}return{channel:d,target:w,accountId:c,threadId:n??this.parseThreadIdFromSessionKey(t.originSessionKey)}}}}let o=this.getOriginSessionKey(t);if(!o)return;let s=o.match(/^agent:[^:]+:telegram:(?:direct|dm|group|channel):([^:]+)(?::topic:(\d+))?$/i);if(s?.[1])return{channel:"telegram",target:s[1],threadId:n??s[2]};let i=o.match(/^agent:[^:]+:discord:(direct|dm|channel|group):(\d+)$/i);if(i?.[2]){let a=i[1].toLowerCase(),d=i[2];return{channel:"discord",target:a==="direct"||a==="dm"?`user:${d}`:`channel:${d}`,threadId:n}}}parseThreadIdFromSessionKey(t){return t?t.match(/:topic:(\d+)$/)?.[1]:void 0}retryDelayMs(t){let r=Math.max(0,t-1),n=sg*2**r;return Math.min(n,ig)}executeWithRetries(t,r,n=1){let o=Date.now();console.info(`[WakeDispatcher] ${r.target} ${r.phase} started attempt ${n}/${xn} for ${r.label} session=${r.sessionId}`),console.info(`[WakeDispatcher] dispatching notification: label=${r.label} session=${r.sessionId}`),ng("openclaw",t,{timeout:Xa},(s,i,a)=>{let d=Date.now()-o;if(!s){console.info(`[WakeDispatcher] ${r.target} ${r.phase} completed attempt ${n}/${xn} for ${r.label} session=${r.sessionId} in ${d}ms`),r.onSuccess?.();return}let m=a?.trim()?` | stderr: ${a.trim()}`:"",y=`[WakeDispatcher] ${r.target} ${r.phase} failed`;if(n>=xn){console.error(`${y} after ${n} attempts for ${r.label} session=${r.sessionId} in ${d}ms: ${s.message}${m}`),r.onFinalFailure?.();return}let f=this.retryDelayMs(n);console.error(`${y} attempt ${n}/${xn} for ${r.label} session=${r.sessionId} in ${d}ms: ${s.message}${m}. Retrying in ${f}ms`);let c=setTimeout(()=>{let w=this.pendingRetryTimers.get(r.sessionId);w&&(w.delete(c),w.size===0&&this.pendingRetryTimers.delete(r.sessionId)),this.executeWithRetries(t,r,n+1)},f);this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(c)})}fireChatSendWithRetry(t,r,n,o,s,i=!1,a){let d=["gateway","call","chat.send","--expect-final","--timeout",String(Xa),"--params",JSON.stringify({sessionKey:t,message:r,deliver:i,idempotencyKey:og()})];this.executeWithRetries(d,{label:n,sessionId:o,target:"chat.send",phase:s,onFinalFailure:a})}fireDirectNotificationWithRetry(t,r,n,o,s,i,a){let d=["message","send","--channel",t.channel,"--target",t.target,"--message",r];if(t.accountId&&d.push("--account",t.accountId),t.threadId&&d.push("--thread-id",t.threadId),s&&t.channel==="telegram"){let m=s.map(y=>y.map(f=>({text:f.label,callback_data:f.callbackData})));d.push("--buttons",JSON.stringify(m))}this.executeWithRetries(d,{label:n,sessionId:o,target:"message.send",phase:"notify",onSuccess:a,onFinalFailure:i})}fireSystemEventWithRetry(t,r,n,o,s,i){let a=["system","event","--text",t,"--mode","now"];this.executeWithRetries(a,{label:r,sessionId:n,target:"system.event",phase:o,onSuccess:i,onFinalFailure:s})}sendUserNotification(t,r,n,o,s,i,a){let d=this.parseNotificationRoute(t);if(!d){this.fireSystemEventWithRetry(r,`${n}-notify-system`,o,"notify",i,a);return}this.fireDirectNotificationWithRetry(d,r,`${n}-notify`,o,s,()=>{this.fireSystemEventWithRetry(r,`${n}-notify-fallback`,o,"notify",i,a)},a)}dispatchSessionNotification(t,r){let n=this.getOriginSessionKey(t),o=r.wakeMessageOnNotifySuccess!=null||r.wakeMessageOnNotifyFailed!=null,s=r.notifyUser??(r.wakeMessage?"on-wake-fallback":"always"),i=r.userMessage?.trim(),a=r.wakeMessage?.trim(),d=r.buttons;if(o){let m=r.wakeMessageOnNotifySuccess?.trim(),y=r.wakeMessageOnNotifyFailed?.trim(),f=S=>{if(S){if(!n){this.fireSystemEventWithRetry(S,`${r.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(n,S,`${r.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(S,`${r.label}-wake-fallback`,t.id,"wake")})}},c=m?()=>f(m):void 0,w=y?()=>{r.onUserNotifyFailed?.(),f(y)}:r.onUserNotifyFailed;i?this.sendUserNotification(t,i,r.label,t.id,d,w,c):w&&w();return}if(s==="always"&&i&&this.sendUserNotification(t,i,r.label,t.id,d,r.onUserNotifyFailed),!!a){if(!n){s==="on-wake-fallback"&&i&&this.sendUserNotification(t,i,r.label,t.id,d,r.onUserNotifyFailed),this.fireSystemEventWithRetry(a,`${r.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(n,a,`${r.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(a,`${r.label}-wake-fallback`,t.id,"wake")})}}};var Ao=new Set(["completed","failed","killed"]),kn=new Set(["starting","running"]),ug=5e3;var Pn=class{sessions=new Map;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueues=new Map;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;constructor(t=20,r=50){this.maxSessions=t,this.maxPersistedSessions=r,this.store=new wn,this.metrics=new Sn,this.wakeDispatcher=new bn}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(t){let r=new Set([...this.sessions.values()].filter(o=>kn.has(o.status)).map(o=>o.name));if(!r.has(t))return t;let n=2;for(;r.has(`${t}-${n}`);)n++;return`${t}-${n}`}spawn(t,r={}){if([...this.sessions.values()].filter(A=>kn.has(A.status)).length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);let o=t.name||ra(t.prompt),s=this.uniqueName(o);s!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${s}" (active session with same name exists)`);let i,a,d=t.resumeSessionId??t.resumeWorktreeFrom;if(d){let A=this.store.getPersistedSession(d);if(A&&(!t.worktreeStrategy&&A.worktreeStrategy&&(t.worktreeStrategy=A.worktreeStrategy),A.worktreePath))if(ag(A.worktreePath))console.info(`[SessionManager] Resuming with existing worktree: ${A.worktreePath}`),t.workdir=A.worktreePath,i=A.worktreePath,a=A.worktreeBranch??se(A.worktreePath);else if(A.worktreeBranch&&A.workdir)try{let ke=A.workdir;rn(ke);let ht=So(ke,A.worktreeBranch.replace(/^agent\//,""));console.info(`[SessionManager] Recreated worktree from branch ${A.worktreeBranch}: ${ht}`),t.workdir=ht,i=ht,a=A.worktreeBranch}catch(ke){console.warn(`[SessionManager] Failed to recreate worktree for resume: ${ke instanceof Error?ke.message:String(ke)}, using original workdir`),t.workdir=A.workdir}else console.warn(`[SessionManager] Worktree ${A.worktreePath} no longer exists and cannot be recreated, using original workdir`),t.workdir=A.workdir}let m=t.workdir,y=!1,f=!1,w=!!!(t.resumeSessionId??t.resumeWorktreeFrom)&&N.defaultWorktreeStrategy&&N.defaultWorktreeStrategy!=="delegate"?N.defaultWorktreeStrategy:t.worktreeStrategy??N.defaultWorktreeStrategy;w&&!t.worktreeStrategy&&(t.worktreeStrategy=w);let S=!t.resumeSessionId&&!i&&w&&w!=="off";if(S&&ha(t.workdir))if(!ya())console.warn("[SessionManager] Insufficient space for worktree (< 100MB), skipping worktree creation"),y=!0;else try{i=So(t.workdir,s),m=i,a=se(i),console.log(`[SessionManager] Created worktree at ${i}`)}catch(A){y=!0,console.warn(`[SessionManager] Failed to create worktree: ${A instanceof Error?A.message:String(A)}, using original workdir`)}else S&&(f=!0,console.info(`[SessionManager] Worktree creation skipped for "${s}" \u2014 workdir is not a git repo`));let k=t.systemPrompt;if(i&&a){let A=["","You are working in a git worktree.",`Worktree path: ${i}`,`Branch: ${a}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${i}.`,`Do NOT edit files directly in ${t.workdir} (the original workspace).`,`If your task references files by absolute path under ${t.workdir}, rewrite those`,"paths relative to your current working directory. For example:",` "${t.workdir}/src/file.py" \u2192 use relative path "src/file.py"`,"","Commit all your file changes to this branch before finishing.","Use `git add` and `git commit`. Do NOT run `git checkout`, `git switch`, or `git reset --hard` as these will detach or corrupt the worktree HEAD."].join(`
94
+ `);k=(t.systemPrompt??"")+A}let x=t.harness??"claude-code",T=this,b,E=x==="claude-code"&&!t.canUseTool?async(A,de)=>{if(!b)throw new Error("canUseTool called before session ID was set");return T.handleAskUserQuestion(b,de)}:t.canUseTool,P=new hn({...t,workdir:m,systemPrompt:k,canUseTool:E},s);if(b=P.id,i&&(P.worktreePath=i,P.originalWorkdir=t.workdir,P.worktreeBranch=a),this.sessions.set(P.id,P),this.metrics.incrementLaunched(),P.on("statusChange",(A,de)=>{de==="running"&&P.harnessSessionId?this.store.markRunning(P):Ao.has(de)&&this.onSessionTerminal(P).catch(ke=>{console.error(`[SessionManager] onSessionTerminal threw for session ${P.id}:`,ke)})}),P.on("turnEnd",(A,de)=>{this.onTurnEnd(P,de)}),P.start(),r.notifyLaunch!==!1){let A=P.worktreePath?`${P.worktreePath} (worktree of ${P.originalWorkdir})`:P.workdir,de=`\u{1F680} [${P.name}] Launched | ${A} | ${P.model??"default"}`;this.notifySession(P,de,"launch")}if(y){let A=`\u26A0\uFE0F [${P.name}] Worktree creation failed \u2014 session running in original workdir`;this.wakeDispatcher.dispatchSessionNotification(P,{label:"worktree-creation-failed",userMessage:A})}return f&&this.wakeDispatcher.dispatchSessionNotification(P,{label:"worktree-skipped-not-git-remote",userMessage:`\u26A0\uFE0F [${P.name}] Worktree creation skipped \u2014 workdir is not a git repo with a remote. Running in original workdir.`}),P}async spawnAndAwaitRunning(t,r={}){let n=this.spawn(t,r);return await this.waitForRunningSession(n),n}async waitForRunningSession(t){if(t.status==="running")return;if(Ao.has(t.status))throw new Error(this.describeLaunchFailure(t));let r=t.on?.bind(t),n=t.off?.bind(t)??t.removeListener?.bind(t);if(!r||!n)throw new Error(`Session ${t.name} [${t.id}] did not expose lifecycle events during startup.`);await new Promise((o,s)=>{let i=(d,m)=>{if(m==="running"){a(),o();return}Ao.has(m)&&(a(),s(new Error(this.describeLaunchFailure(t))))},a=()=>{n("statusChange",i)};r("statusChange",i)})}describeLaunchFailure(t){let r=t.killReason?` (reason: ${t.killReason})`:"",n=t.error||t.result?.result||`status=${t.status}${r}`;return`Session ${t.name} [${t.id}] failed to start: ${n}`}async handleWorktreeStrategy(t){if(this.isAlreadyMerged(t.harnessSessionId))return console.info(`[SessionManager] handleWorktreeStrategy: session "${t.name}" already merged \u2014 skipping strategy handling`),!0;if(t.status!=="completed")return!1;let r=t.worktreeStrategy;if(!r||r==="off"||r==="manual")return!1;let n=t.originalWorkdir,o=t.worktreePath,s=se(o)??t.worktreeBranch;if(!s)return this.dispatchSessionNotification(t,{label:"worktree-no-branch-name",userMessage:`\u26A0\uFE0F [${t.name}] Cannot determine branch name for worktree ${o}. The worktree may have been removed or is in detached HEAD state. Manual cleanup may be needed.`}),!0;let i=t.worktreeBaseBranch??Ke(n);if(!nn(n,s,i))return this.dispatchSessionNotification(t,{label:"worktree-no-commits-ahead",userMessage:`\u26A0\uFE0F [${t.name}] Auto-merge: branch '${s}' has no commits ahead of '${i}'.
95
+ Changes may be uncommitted. Check worktree directory: ${o}`}),!0;let a=Ct(n,s,i);if(!a)return console.warn(`[SessionManager] Failed to get diff summary for ${s}, skipping merge-back`),!1;let d=a.commitMessages.slice(0,5).map(f=>`\u2022 ${f.hash} ${f.message} (${f.author})`).join(`
96
+ `),m=a.commits>5?`
97
+ ...and ${a.commits-5} more`:"",y=[`\u{1F500} Session ${t.name} completed with changes`,"",`Branch: ${s} \u2192 ${i}`,`Commits: ${a.commits} | Files: ${a.filesChanged} | +${a.insertions} / -${a.deletions}`,"",d+m].join(`
98
+ `);if(r==="ask"){gt(n,s);let f=a.commitMessages.slice(0,5).map(x=>`\u2022 ${x.hash} ${x.message} (${x.author})`),c=a.commits>5?`...and ${a.commits-5} more`:"",w=[`\u{1F500} Session \`${t.name}\` completed with changes \u2014 decision required`,"",`Branch: \`${s}\` \u2192 \`${i}\``,`Commits: ${a.commits} | Files: ${a.filesChanged} | +${a.insertions} / -${a.deletions}`,"",...f,...c?[c]:[]].join(`
99
+ `),S=[`[WORKTREE DECISION REQUIRED] Session "${t.name}" completed with changes.`,"",`Branch: ${s} \u2192 ${i}`,`Commits: ${a.commits} | Files: ${a.filesChanged} | +${a.insertions} / -${a.deletions}`,"",...f,...c?[c]:[],"","Present this to the user and wait for their choice:",` 1. Merge: agent_merge(session="${t.name}", base_branch="${i}")`,` 2. Open PR: agent_pr(session="${t.name}")`,"","Wait for user reply before acting."].join(`
100
+ `),k=[[{label:"\u2B07\uFE0F Merge locally",callbackData:`code-agent:merge:${t.id}`},{label:"\u{1F500} Create PR",callbackData:`code-agent:pr:${t.id}`}]];return this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-ask",userMessage:w,notifyUser:"always",buttons:k,wakeMessageOnNotifySuccess:"Worktree strategy buttons delivered to user. Wait for their button callback \u2014 do NOT act on this worktree yourself. The user has already received the full diff summary and decision buttons. Do NOT send a duplicate completion message.",wakeMessageOnNotifyFailed:S}),t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{pendingWorktreeDecisionSince:new Date().toISOString()}),!0}if(r==="delegate"){gt(n,s);let f=a.commitMessages.slice(0,5).map(x=>`\u2022 ${x.hash} ${x.message} (${x.author})`),c=a.commits>5?`...and ${a.commits-5} more`:"",w=`\u{1F916} Delegating merge decision for \`${s}\` to orchestrator`,S=t.prompt?t.prompt.slice(0,500):"(no prompt)",k=[`[DELEGATED WORKTREE DECISION] Session "${t.name}" completed with changes.`,"",`Branch: ${s} \u2192 ${i}`,`Commits: ${a.commits} | Files: ${a.filesChanged} | +${a.insertions} / -${a.deletions}`,"",...f,...c?[c]:[],"","Original task prompt (first 500 chars):",S,"","\u2501\u2501\u2501 DECISION REQUIRED \u2501\u2501\u2501","You are the delegated decision-maker for this worktree branch.","","MERGE if:"," - Changes match the original task scope"," - No breaking changes or architectural concerns",` \u2192 agent_merge(session="${t.name}", base_branch="${i}")`,"","OPEN PR if:"," - Changes are non-trivial and benefit from review"," - User has previously requested PRs for this kind of work"," - You are unsure \u2014 PRs are the safer default",` \u2192 agent_pr(session="${t.name}")`,"","ESCALATE to user if:"," - Scope is ambiguous or changes are risky"," - User has standing preferences that apply here","","Always notify the user briefly with what you decided and why."].join(`
101
+ `);return this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-delegate",userMessage:w,wakeMessage:k,notifyUser:"always"}),t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{pendingWorktreeDecisionSince:new Date().toISOString()}),!0}if(r==="auto-merge")return this.isAlreadyMerged(t.harnessSessionId)||await this.enqueueMerge(n,async()=>{if(this.isAlreadyMerged(t.harnessSessionId))return;let f=on(n,s,i);if(f.success){Mt(n,s),t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString()});let c=`\u2705 [${t.name}] Merged ${s} \u2192 ${i} locally. Branch cleaned up.`;f.stashPopConflict?c+=`
102
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${f.stashRef??"stash@{0}"}\` in ${n} to review stashed changes.`:f.stashed&&(c+=`
103
+ (Pre-existing changes on ${i} were auto-stashed and restored.)`),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-success",userMessage:c})}else if(f.conflictFiles&&f.conflictFiles.length>0){let c=["Resolve merge conflicts in the following files and commit the resolution:","",...f.conflictFiles.map(w=>`- ${w}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${s}"`].join(`
104
+ `);try{this.spawn({prompt:c,workdir:n,name:`${t.name}-conflict-resolver`,harness:"claude-code",permissionMode:"bypassPermissions",multiTurn:!0}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-conflict",userMessage:`\u26A0\uFE0F [${t.name}] Merge conflicts in ${f.conflictFiles.length} file(s) \u2014 spawned conflict resolver session`,buttons:[[{label:"\u{1F500} Open PR instead",callbackData:`code-agent:open-pr:${t.id}`}]]})}catch(w){this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-conflict-spawn-failed",userMessage:`\u274C [${t.name}] Merge conflicts detected, but failed to spawn resolver: ${w instanceof Error?w.message:String(w)}`})}}else{let c=f.dirtyError?`\u274C [${t.name}] Merge blocked: ${f.error}`:`\u274C [${t.name}] Merge failed: ${f.error??"unknown error"}`;this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-error",userMessage:c})}},()=>{this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-queued",userMessage:`\u{1F550} [${t.name}] Merge queued \u2014 another merge for this repo is in progress. Will notify when complete.`})}),!0;if(r==="auto-pr"){if(!et()){console.warn("[SessionManager] GitHub CLI not available, falling back to 'ask' strategy");let c=[y,"","(GitHub CLI not available for auto-PR)","","Reply with one of the following:",`1. Merge to ${i}`].join(`
105
+ `);return this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-fallback-ask",userMessage:c,buttons:[[{label:"\u2705 Merge instead",callbackData:`code-agent:merge:${t.id}`}]]}),!0}if(!gt(n,s))return this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-push-failed",userMessage:`\u274C [${t.name}] Failed to push ${s} \u2014 cannot create/update PR`}),!0;let f=er(n,s);if(f.exists&&f.state==="open"){if(a&&a.commits>0){let c=["\u{1F504} **New commits pushed**","",`${a.commits} commits (+${a.insertions} / -${a.deletions})`,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
106
+ `),w=an(n,f.number,c);t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:f.url,worktreePrNumber:f.number}),w?this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-updated",userMessage:`\u2705 [${t.name}] PR updated: ${f.url} (+${a.commits} commits)`}):this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-updated-no-comment",userMessage:`\u26A0\uFE0F [${t.name}] Pushed to ${f.url} (comment failed)`})}else t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:f.url,worktreePrNumber:f.number}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-up-to-date",userMessage:`\u2139\uFE0F [${t.name}] PR up to date: ${f.url}`});return!0}else{if(f.exists&&f.state==="merged")return t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:f.url,worktreePrNumber:f.number}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-merged",userMessage:`\u2705 [${t.name}] PR already merged: ${f.url}`}),!0;if(f.exists&&f.state==="closed")return t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:f.url,worktreePrNumber:f.number}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-closed",userMessage:`\u26A0\uFE0F [${t.name}] PR was closed without merging: ${f.url}`,buttons:[[{label:"\u{1F195} New PR",callbackData:`code-agent:new-pr:${t.id}`},{label:"\u2705 Merge locally",callbackData:`code-agent:merge-locally:${t.id}`}]]}),!0;{let c=`[openclaw-code-agent] ${t.name}`,w=[`Automated changes from OpenClaw Code Agent session: ${t.name}`,"","## Summary",`${a.commits} commits, ${a.filesChanged} files changed (+${a.insertions} / -${a.deletions})`,"","## Commits",d+m,"","---","\u{1F916} Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
107
+ `),S=sn(n,s,i,c,w);if(S.success&&S.prUrl){let k=er(n,s);t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:S.prUrl,worktreePrNumber:k.number}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-success",userMessage:`\u{1F500} [${t.name}] PR created: ${S.prUrl}`})}else this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-error",userMessage:`\u274C [${t.name}] Failed to create PR: ${S.error??"unknown error"}`});return!0}}}return!1}async onSessionTerminal(t){this.persistSession(t),this.lastWaitingEventTimestamps.delete(t.id);let r=!1;t.worktreePath&&t.originalWorkdir&&(r=await this.handleWorktreeStrategy(t));let n=!1;if(t.worktreePath&&t.originalWorkdir&&t.status==="failed"&&t.costUsd===0&&t.duration<3e4){let d=t.originalWorkdir,m=se(t.worktreePath);console.info(`[SessionManager] Early startup failure for "${t.name}" \u2014 auto-cleaning worktree (cost=$${t.costUsd.toFixed(2)}, duration=${t.duration}ms)`),br(d,t.worktreePath),m&&Mt(d,m),t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePath:void 0,worktreeBranch:void 0}),n=!0}let o=!!t.harnessSessionId&&!!this.store.getPersistedSession(t.harnessSessionId)?.pendingWorktreeDecisionSince;if(!n&&t.worktreePath&&t.originalWorkdir&&(o?console.info(`[SessionManager] Skipping worktree directory removal for "${t.name}" \u2014 pendingWorktreeDecision is set (ask-strategy button callback may still fire).`):br(t.originalWorkdir,t.worktreePath)),t.killReason==="done"){if(r||this.lastTurnCompleteMarkers.has(t.id)||!this.shouldEmitTerminalWake(t))return;this.triggerAgentEvent(t);return}if(t.status==="completed"){if(!this.shouldEmitTerminalWake(t))return;this.triggerAgentEvent(t);return}if(t.status==="failed"){if(!this.shouldEmitTerminalWake(t))return;let d=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`,m=Rt(d,200);this.triggerFailedEvent(t,m,n);return}let s=`$${(t.costUsd??0).toFixed(2)}`,i=qe(t.duration);if(t.killReason==="idle-timeout"){this.notifySession(t,`\u{1F4A4} [${t.name}] Idle timeout | ${s} | ${i}`),this.wakeDispatcher.clearRetryTimersForSession(t.id);return}let a=this.getStoppedStatusLabel(t.killReason);this.notifySession(t,`\u26D4 [${t.name}] ${a} | ${s} | ${i}`),this.wakeDispatcher.clearRetryTimersForSession(t.id)}getStoppedStatusLabel(t){switch(t){case"user":return"Stopped by user";case"shutdown":return"Stopped by shutdown";case"startup-timeout":return"Stopped by startup timeout";case"unknown":case void 0:return"Stopped unexpectedly";default:return"Stopped"}}persistSession(t){this.store.hasRecordedSession(t.id)||this.metrics.recordSession(t),this.store.persistTerminal(t)}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(t){this.metrics.recordSession(t)}notifySession(t,r,n="notification"){this.dispatchSessionNotification(t,{label:n,userMessage:r,notifyUser:"always"})}dispatchSessionNotification(t,r){this.wakeDispatcher.dispatchSessionNotification(t,r)}debounceWaitingEvent(t){let r=Date.now(),n=this.lastWaitingEventTimestamps.get(t);return n&&r-n<ug?!1:(this.lastWaitingEventTimestamps.set(t,r),!0)}originThreadLine(t){return t.originThreadId!=null?`Session origin thread: ${t.originThreadId}`:""}extractLastOutputLine(t){return t.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(t,r=1e3){let n=t.getOutput(20).join(`
108
+ `);return n.length>r?oa(n,r):n}triggerAgentEvent(t){let r=this.getOutputPreview(t),n=["Coding agent session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","(Note: a turn-complete wake may have already been sent for this session. If you already acted on it, treat this as confirmation \u2014 do not repeat actions.)","","Output preview:",r,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${t.id}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.","3. Notify the user with a summary of what was done."].join(`
109
+ `),o=`$${(t.costUsd??0).toFixed(2)}`,s=qe(t.duration),i=t.outputMode==="deliverable"?`\u{1F4C4} [${t.name}] Deliverable ready | ${o} | ${s}`:`\u2705 [${t.name}] Completed | ${o} | ${s}`;this.dispatchSessionNotification(t,{label:"completed",userMessage:i,wakeMessage:n,notifyUser:"always"})}triggerFailedEvent(t,r,n=!1){let o=this.getOutputPreview(t),s=o.trim()?["","Output preview:",o]:[],i=n?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[],a=["Coding agent session failed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),`Harness session ID: ${t.harnessSessionId??"unknown"}`,"","Failure summary:",r,...s,...i,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${t.id}', full=true) to inspect the full failure context.`,"2. If the failure is a runtime error (usage limit, API error, crash), resume with a different harness:",` agent_launch(resume_session_id='${t.harnessSessionId??"unknown"}', harness='claude-code', ...)`," Note: agent_respond also resumes, but uses the same harness (may hit the same error)."," If the failure is a launch/config issue, relaunch fresh with agent_launch(prompt=...).","3. Notify the user with the failure cause and the next action you are taking."].join(`
110
+ `),d=`$${(t.costUsd??0).toFixed(2)}`,m=qe(t.duration),y=[`\u274C [${t.name}] Failed | ${d} | ${m}`,` \u26A0\uFE0F ${r}`].join(`
111
+ `),f=[[{label:"\u{1F504} Retry",callbackData:`code-agent:retry:${t.id}`},{label:"\u{1F4CB} View output",callbackData:`code-agent:view-output:${t.id}`}]];this.dispatchSessionNotification(t,{label:"failed",userMessage:y,wakeMessage:a,notifyUser:"always",buttons:f})}triggerWaitingForInputEvent(t){if(!this.debounceWaitingEvent(t.id))return;let r=this.getOutputPreview(t),n=t.pendingPlanApproval,o=n?`\u{1F4CB} [${t.name}] Plan ready for review:
59
112
 
60
- ${n}
113
+ ${r}
61
114
 
62
- Reply to approve or provide feedback.`:`\u2753 [${t.name}] Waiting for input`,i;if(r){let s=F.planApproval??"delegate";if(s==="ask"){this.runLobsterApproval(t,n);return}else s==="delegate"?i=["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"Permission mode: plan \u2192 will switch to bypassPermissions on approval","","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${t.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",n,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Notify the user \u2501\u2501\u2501","After reading the full plan, use the message tool to send the user a summary that includes:","- What files/components will be changed","- Risk level (low/medium/high) and why","- Scope: does this match the original task or has it expanded?","- Any concerns or assumptions the plan makes","This message creates accountability \u2014 you cannot approve blindly.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","You are the delegated decision-maker. Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- You have sent the user the summary message","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,"If escalating: tell the user you need their decision and WAIT for his explicit response.",`To request changes: agent_respond(session='${t.id}', message='<your feedback>') \u2014 do NOT set approve=true. The agent will revise the plan.`].join(`
115
+ Reply to approve or provide feedback.`:`\u2753 [${t.name}] Waiting for input`,s=n?N.planApproval??"delegate":void 0,i;if(n){let d=s??"delegate";d==="delegate"?i=["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"Permission mode: plan \u2192 will switch to bypassPermissions on approval","","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${t.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",r,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Notify the user \u2501\u2501\u2501","After reading the full plan, use the message tool to send the user a summary that includes:","- What files/components will be changed","- Risk level (low/medium/high) and why","- Scope: does this match the original task or has it expanded?","- Any concerns or assumptions the plan makes","This message creates accountability \u2014 you cannot approve blindly.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","You are the delegated decision-maker. Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- You have sent the user the summary message","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,"If escalating: tell the user you need their decision and WAIT for his explicit response.",`To request changes: agent_respond(session='${t.id}', message='<your feedback>') \u2014 do NOT set approve=true. The agent will revise the plan.`].join(`
116
+ `):d==="ask"?i=["[USER APPROVAL REQUESTED] Coding agent session has finished its plan. The user has been notified via Telegram and must approve directly.",`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"","DO NOT approve this plan yourself. Wait for the user's explicit approval or rejection.","Once the user responds, forward their decision:",` To approve: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,` To request changes: agent_respond(session='${t.id}', message='<user feedback>')`,"","Preview (truncated):",r].join(`
63
117
  `):i=["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`].join(`
64
- `)}else i=[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 forward the agent's EXACT question to the user. Do NOT add your own analysis, commentary, or interpretation. Do NOT "nudge" or "poke" the session.]`,"",`${t.multiTurn?"Multi-turn session":"Session"} is waiting for input.`,`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"","Last output:",n,"",`Use agent_respond(session='${t.id}', message='...') to send a reply, or agent_output(session='${t.id}', full: true) to see full context before deciding.`].join(`
65
- `);this.dispatchSessionNotification(t,{label:r?"plan-approval":"waiting",userMessage:o,wakeMessage:i,notifyUser:r?"always":"on-wake-fallback"})}onTurnEnd(t,n){if(n||t.pendingPlanApproval){this.triggerWaitingForInputEvent(t);return}this.shouldEmitTurnCompleteWake(t)&&this.triggerTurnCompleteEventWithSignal(t)}shouldEmitTurnCompleteWake(t){let n=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===n?!1:(this.lastTurnCompleteMarkers.set(t.id,n),!0)}shouldEmitTerminalWake(t){let n=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===n?!1:(this.lastTerminalWakeMarkers.set(t.id,n),!0)}triggerTurnCompleteEventWithSignal(t){let n=this.getOutputPreview(t),r=jn(n),o=`$${(t.costUsd??0).toFixed(2)}`,i=r?"yes":"no",s=`\u23F8\uFE0F [${t.name}] Paused after turn | Auto-resumable | ${o} | Waiting input: ${i}`,c=["Coding agent session turn ended.",`Name: ${t.name}`,`ID: ${t.id}`,`Status: ${t.status}`,"",`Looks like waiting for user input: ${i}`,"","Last output (~20 lines):",n,...this.originThreadLine(t)?["",this.originThreadLine(t)]:[]].join(`
66
- `);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:s,wakeMessage:c,notifyUser:"always"})}resolve(t){let n=this.sessions.get(t);if(n)return n;let r=[...this.sessions.values()].filter(i=>i.name===t);if(r.length===0)return;let o=r.filter(i=>Xn.has(i.status));return o.length>0?o.sort((i,s)=>s.startedAt-i.startedAt)[0]:r.sort((i,s)=>s.startedAt-i.startedAt)[0]}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,n){let r=this.sessions.get(t);return r?(r.kill(n??"user"),!0):!1}killAll(t="user"){for(let n of this.sessions.values())Xn.has(n.status)&&this.kill(n.id,t);this.wakeDispatcher.clearPendingRetries()}resolveHarnessSessionId(t){let n=this.resolve(t);return this.store.resolveHarnessSessionId(t,n?.harnessSessionId)}getPersistedSession(t){return this.store.getPersistedSession(t)}listPersistedSessions(){return this.store.listPersistedSessions()}cleanup(){let t=Date.now(),n=(F.sessionGcAgeMinutes??1440)*6e4;for(let[r,o]of this.sessions)this.store.shouldGcActiveSession(o,t,n)&&(this.persistSession(o),this.sessions.delete(r),this.lastWaitingEventTimestamps.delete(r),this.lastTurnCompleteMarkers.delete(r),this.lastTerminalWakeMarkers.delete(r));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}};function oO(e){let t=null,n=null;e.registerTool(r=>Oi(r),{optional:!1}),e.registerTool(r=>Fi(r),{optional:!1}),e.registerTool(r=>ki(r),{optional:!1}),e.registerTool(r=>$i(r),{optional:!1}),e.registerTool(r=>Ni(r),{optional:!1}),e.registerTool(r=>Ui(r),{optional:!1}),_i(e),Li(e),Ki(e),Di(e),ji(e),Gi(e),Vi(e),e.registerService({id:"openclaw-code-agent",start:r=>{let o=e.pluginConfig??e.getConfig?.()??{};wi(o),t=new Qn(F.maxSessions,F.maxPersistedSessions),Vr(t),n=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{t&&t.killAll("shutdown"),n&&clearInterval(n),n=null,t=null,Vr(null)}})}export{oO as register};
118
+ `)}else i=[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 forward the agent's EXACT question to the user. Do NOT add your own analysis, commentary, or interpretation. Do NOT "nudge" or "poke" the session.]`,"",`${t.multiTurn?"Multi-turn session":"Session"} is waiting for input.`,`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"","Last output:",r,"",`Use agent_respond(session='${t.id}', message='...') to send a reply, or agent_output(session='${t.id}', full: true) to see full context before deciding.`].join(`
119
+ `);let a=n&&s==="ask"?[[{label:"\u2705 Approve",callbackData:`code-agent:approve:${t.id}`},{label:"\u274C Reject",callbackData:`code-agent:reject:${t.id}`},{label:"\u270F\uFE0F Revise",callbackData:`code-agent:revise:${t.id}`}]]:n?void 0:[[{label:"\u{1F4AC} Reply",callbackData:`code-agent:reply:${t.id}`}]];n&&s==="ask"?this.dispatchSessionNotification(t,{label:"plan-approval",userMessage:o,notifyUser:"always",buttons:a,wakeMessageOnNotifySuccess:"Plan approval buttons delivered to user. Wait for their button callback \u2014 do NOT approve or reject this plan yourself.",wakeMessageOnNotifyFailed:i}):this.dispatchSessionNotification(t,{label:n?"plan-approval":"waiting",userMessage:o,wakeMessage:i,notifyUser:"always",buttons:a})}onTurnEnd(t,r){if(r||t.pendingPlanApproval){this.triggerWaitingForInputEvent(t);return}if(t.worktreeStrategy==="ask"||t.worktreeStrategy==="delegate"){console.info(`[SessionManager] Suppressing turn-complete wake for session ${t.id} (worktreeStrategy=${t.worktreeStrategy}) \u2014 worktree notification will follow.`);return}this.shouldEmitTurnCompleteWake(t)&&this.triggerTurnCompleteEventWithSignal(t)}shouldEmitTurnCompleteWake(t){let r=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===r?(console.info(`[SessionManager] shouldEmitTurnCompleteWake: debounced for session ${t.id} (marker unchanged: ${r})`),!1):(this.lastTurnCompleteMarkers.set(t.id,r),!0)}shouldEmitTerminalWake(t){let r=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===r?!1:(this.lastTerminalWakeMarkers.set(t.id,r),!0)}triggerTurnCompleteEventWithSignal(t){console.info(`[SessionManager] turn-complete wake dispatching for session ${t.id} (turns=${t.result?.num_turns??0}, strategy=${t.worktreeStrategy??"none"})`);let r=this.getOutputPreview(t),n=mn(r),o=`$${(t.costUsd??0).toFixed(2)}`,s=n?"yes":"no",i=`\u23F8\uFE0F [${t.name}] Paused after turn | Auto-resumable | ${o} | Waiting input: ${s}`,a=["Coding agent session turn ended.",`Name: ${t.name}`,`ID: ${t.id}`,`Status: ${t.status}`,"",`Looks like waiting for user input: ${s}`,"","Last output (~20 lines):",r,...this.originThreadLine(t)?["",this.originThreadLine(t)]:[]].join(`
120
+ `);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:i,wakeMessage:a,notifyUser:"always",onUserNotifyFailed:()=>{console.warn(`[SessionManager] turn-complete delivery failed for session ${t.id} \u2014 firing terminal notification as fallback`),this.shouldEmitTerminalWake(t)&&this.triggerAgentEvent(t)}})}resolve(t){let r=this.sessions.get(t);if(r)return r;let n=[...this.sessions.values()].filter(s=>s.name===t);if(n.length===0)return;let o=n.filter(s=>kn.has(s.status));return o.length>0?o.sort((s,i)=>i.startedAt-s.startedAt)[0]:n.sort((s,i)=>i.startedAt-s.startedAt)[0]}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,r){let n=this.sessions.get(t);return n?(n.kill(r??"user"),!0):!1}killAll(t="user"){for(let r of this.sessions.values())kn.has(r.status)&&this.kill(r.id,t)}resolveHarnessSessionId(t){let r=this.resolve(t);return this.store.resolveHarnessSessionId(t,r?.harnessSessionId)}getPersistedSession(t){return this.store.getPersistedSession(t)}isAlreadyMerged(t){return t?this.store.getPersistedSession(t)?.worktreeMerged===!0:!1}async enqueueMerge(t,r,n){let o=this.mergeQueues.get(t);o!==void 0&&n&&n();let s=(o??Promise.resolve()).catch(()=>{}).then(()=>r()),i=s.catch(()=>{});return this.mergeQueues.set(t,i),i.finally(()=>{this.mergeQueues.get(t)===i&&this.mergeQueues.delete(t)}),s}updatePersistedSession(t,r){let n=this.store.getPersistedSession(t);return n?(Object.assign(n,r),this.store.saveIndex(),!0):!1}listPersistedSessions(){return this.store.listPersistedSessions()}remindStaleDecisions(){let r=Date.now();for(let n of this.store.listPersistedSessions()){if(!n.pendingWorktreeDecisionSince||n.worktreeMerged||n.worktreePrUrl)continue;let o=r-new Date(n.pendingWorktreeDecisionSince).getTime();if(o<36e5||n.lastWorktreeReminderAt&&r-new Date(n.lastWorktreeReminderAt).getTime()<36e5)continue;let s=Math.floor(o/(3600*1e3)),i=[`\u23F0 Reminder: branch \`${n.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${n.name} | Pending: ${s}h`,"",`agent_merge(session="${n.name}") or agent_pr(session="${n.name}") or agent_worktree_cleanup() to resolve.`].join(`
121
+ `);try{this.sendReminderNotification(n,i)}catch(a){console.warn(`[SessionManager] Failed to send stale-decision reminder for session ${n.name}: ${a instanceof Error?a.message:String(a)}`)}this.updatePersistedSession(n.harnessSessionId,{lastWorktreeReminderAt:new Date().toISOString()})}}sendReminderNotification(t,r){let n={id:t.harnessSessionId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey};this.wakeDispatcher.dispatchSessionNotification(n,{label:`worktree-stale-reminder-${t.name}`,userMessage:r,notifyUser:"always",buttons:[[{label:"\u2B07\uFE0F Merge locally",callbackData:`code-agent:merge:${t.harnessSessionId}`},{label:"\u{1F500} Create PR",callbackData:`code-agent:open-pr:${t.harnessSessionId}`}]]})}async handleAskUserQuestion(t,r){let o=this.sessions.get(t);if(!o)throw new Error(`Session "${t}" not found for AskUserQuestion intercept`);let i=r?.questions??[];if(i.length===0)throw new Error("AskUserQuestion: no questions in input");let a=i[0],d=a.options??[],m=[`[ASK USER QUESTION] Session "${o.name}" has a question requiring user input.`,"",`Question: ${a.question}`,...d.length>0?["Options:",...d.map((c,w)=>` ${w+1}. ${c.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${o.id}", message="<answer>") with their answer.`].join(`
122
+ `),y;d.length>0&&(y=[d.map((c,w)=>({label:c.label,callbackData:`code-agent:question-answer:${o.id}:${w}`}))]);let f=[`\u2753 [${o.name}] ${a.question}`].join(`
123
+ `);return new Promise((c,w)=>{let S=setTimeout(()=>{this.pendingAskUserQuestions.delete(t),w(new Error(`AskUserQuestion timed out after 600s for session "${o.name}"`))},6e5);this.pendingAskUserQuestions.set(t,{resolve:c,reject:w,questions:i,timeoutHandle:S}),this.wakeDispatcher.dispatchSessionNotification(o,{label:"ask-user-question",userMessage:f,notifyUser:"always",buttons:y,wakeMessageOnNotifySuccess:"AskUserQuestion buttons delivered to user. Await their selection \u2014 do NOT answer this question yourself.",wakeMessageOnNotifyFailed:m})})}resolveAskUserQuestion(t,r){let n=this.pendingAskUserQuestions.get(t);if(!n){console.warn(`[SessionManager] resolveAskUserQuestion: no pending question for session "${t}"`);return}clearTimeout(n.timeoutHandle),this.pendingAskUserQuestions.delete(t);let o=n.questions[0],s=o.options??[],i=s[r];if(!i){n.reject(new Error(`AskUserQuestion: invalid option index ${r} (${s.length} options available)`));return}n.resolve({behavior:"allow",updatedInput:{questions:n.questions,answers:{[o.question]:i.label}}})}cleanup(){let t=Date.now();this.remindStaleDecisions();let r=(N.sessionGcAgeMinutes??1440)*6e4;for(let[n,o]of this.sessions)this.store.shouldGcActiveSession(o,t,r)&&(this.persistSession(o),this.sessions.delete(n),this.lastWaitingEventTimestamps.delete(n),this.lastTurnCompleteMarkers.delete(n),this.lastTerminalWakeMarkers.delete(n));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}};function mg(e){let t=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"1",10)||1,r=t*60*60*1e3,n=Date.now()-r,o=new Set,s=process.env.OPENCLAW_WORKTREE_DIR??N.worktreeDir;if(s)o.add(s);else for(let a of e.listPersistedSessions())if(a.workdir)try{let d=pg("git",["rev-parse","--show-toplevel"],{cwd:a.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();d&&o.add(Za(d,".worktrees"))}catch{}if(o.size===0)return;let i=0;for(let a of o)try{let d=cg(a);for(let m of d){if(!m.startsWith("openclaw-worktree-"))continue;let y=Za(a,m);try{let f=dg(y);if(!f.isDirectory()||f.mtimeMs>n)continue;lg(y,{recursive:!0,force:!0}),i++}catch(f){console.warn(`[index] Failed to clean up orphaned worktree ${y}: ${f instanceof Error?f.message:String(f)}`)}}}catch{}i>0&&console.info(`[index] Cleaned up ${i} orphaned worktree(s) at startup (age > ${t}h)`)}function oC(e){let t=null,r=null;e.registerTool(n=>ea(n),{optional:!1}),e.registerTool(n=>aa(n),{optional:!1}),e.registerTool(n=>ua(n),{optional:!1}),e.registerTool(n=>Zr(n),{optional:!1}),e.registerTool(n=>da(n),{optional:!1}),e.registerTool(n=>la(n),{optional:!1}),e.registerTool(n=>cn(n),{optional:!1}),e.registerTool(n=>kr(n),{optional:!1}),e.registerTool(n=>Ia(n),{optional:!1}),e.registerTool(n=>wa(n),{optional:!1}),e.registerInteractiveHandler(Sa()),xa(e),ba(e),ka(e),Pa(e),Ta(e),Aa(e),$a(e),e.registerService({id:"openclaw-code-agent",start:n=>{let o=e.pluginConfig??e.getConfig?.()??{};Yi(o),t=new Pn(N.maxSessions,N.maxPersistedSessions),ho(t),mg(t),r=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{t&&t.killAll("shutdown"),r&&clearInterval(r),r=null,t=null,ho(null)}})}export{oC as register};