openclaw-code-agent 2.3.1 → 3.1.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,128 @@
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 uf=Object.defineProperty;var u=(e,t)=>()=>(e&&(t=e(e=0)),t);var Hn=(e,t)=>{for(var r in t)uf(e,r,{get:t[r],enumerable:!0})};var ve={};Hn(ve,{HasPropertyKey:()=>Gn,IsArray:()=>ue,IsAsyncIterator:()=>rs,IsBigInt:()=>Qr,IsBoolean:()=>Rt,IsDate:()=>Xt,IsFunction:()=>ns,IsIterator:()=>os,IsNull:()=>is,IsNumber:()=>We,IsObject:()=>j,IsRegExp:()=>Jr,IsString:()=>z,IsSymbol:()=>ss,IsUint8Array:()=>At,IsUndefined:()=>pe});function Gn(e,t){return t in e}function rs(e){return j(e)&&!ue(e)&&!At(e)&&Symbol.asyncIterator in e}function ue(e){return Array.isArray(e)}function Qr(e){return typeof e=="bigint"}function Rt(e){return typeof e=="boolean"}function Xt(e){return e instanceof globalThis.Date}function ns(e){return typeof e=="function"}function os(e){return j(e)&&!ue(e)&&!At(e)&&Symbol.iterator in e}function is(e){return e===null}function We(e){return typeof e=="number"}function j(e){return typeof e=="object"&&e!==null}function Jr(e){return e instanceof globalThis.RegExp}function z(e){return typeof e=="string"}function ss(e){return typeof e=="symbol"}function At(e){return e instanceof globalThis.Uint8Array}function pe(e){return e===void 0}var Ce=u(()=>{});function pf(e){return e.map(t=>zn(t))}function cf(e){return new Date(e.getTime())}function lf(e){return new Uint8Array(e)}function mf(e){return new RegExp(e.source,e.flags)}function ff(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=zn(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=zn(e[r]);return t}function zn(e){return ue(e)?pf(e):Xt(e)?cf(e):At(e)?lf(e):Jr(e)?mf(e):j(e)?ff(e):e}function X(e){return zn(e)}var Ee=u(()=>{Ce()});function wr(e,t){return t===void 0?X(e):X({...t,...e})}var Qn=u(()=>{Ee()});var as=u(()=>{Qn();Ee()});function Sd(e){return e!==null&&typeof e=="object"}function kd(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function yd(e){return e===void 0}function wd(e){return typeof e=="number"}var Id=u(()=>{});var xd=u(()=>{Id()});var Jn,Pd=u(()=>{xd();(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(s,a){return e.ExactOptionalPropertyTypes?a in s:s[a]!==void 0}e.IsExactOptionalProperty=t;function r(s){let a=Sd(s);return e.AllowArrayObject?a:a&&!kd(s)}e.IsObjectLike=r;function n(s){return r(s)&&!(s instanceof Date)&&!(s instanceof Uint8Array)}e.IsRecordLike=n;function o(s){return e.AllowNaN?wd(s):Number.isFinite(s)}e.IsNumberLike=o;function i(s){let a=yd(s);return e.AllowNullVoid?a||s===null:a}e.IsVoidLike=i})(Jn||(Jn={}))});function gf(e){return globalThis.Object.freeze(e).map(t=>Yr(t))}function hf(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=Yr(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=Yr(e[r]);return globalThis.Object.freeze(t)}function Yr(e){return ue(e)?gf(e):Xt(e)?e:At(e)?e:Jr(e)?e:j(e)?hf(e):e}var bd=u(()=>{Ce()});function l(e,t){let r=t!==void 0?{...t,...e}:e;switch(Jn.InstanceMode){case"freeze":return Yr(r);case"clone":return X(r);default:return r}}var P=u(()=>{Pd();bd();Ee()});var Tt=u(()=>{P()});var we,vd=u(()=>{we=class extends Error{constructor(t){super(t)}}});var kt=u(()=>{vd()});var le,it,xe,Je,w,Xr=u(()=>{le=Symbol.for("TypeBox.Transform"),it=Symbol.for("TypeBox.Readonly"),xe=Symbol.for("TypeBox.Optional"),Je=Symbol.for("TypeBox.Hint"),w=Symbol.for("TypeBox.Kind")});var b=u(()=>{Xr()});function Ir(e){return j(e)&&e[it]==="Readonly"}function $e(e){return j(e)&&e[xe]==="Optional"}function ds(e){return O(e,"Any")}function us(e){return O(e,"Argument")}function st(e){return O(e,"Array")}function Zt(e){return O(e,"AsyncIterator")}function er(e){return O(e,"BigInt")}function Mt(e){return O(e,"Boolean")}function at(e){return O(e,"Computed")}function dt(e){return O(e,"Constructor")}function Sf(e){return O(e,"Date")}function ut(e){return O(e,"Function")}function pt(e){return O(e,"Integer")}function oe(e){return O(e,"Intersect")}function tr(e){return O(e,"Iterator")}function O(e,t){return j(e)&&w in e&&e[w]===t}function Yn(e){return Rt(e)||We(e)||z(e)}function Be(e){return O(e,"Literal")}function Ke(e){return O(e,"MappedKey")}function Z(e){return O(e,"MappedResult")}function Lt(e){return O(e,"Never")}function kf(e){return O(e,"Not")}function Zr(e){return O(e,"Null")}function ct(e){return O(e,"Number")}function ce(e){return O(e,"Object")}function rr(e){return O(e,"Promise")}function nr(e){return O(e,"Record")}function se(e){return O(e,"Ref")}function ps(e){return O(e,"RegExp")}function Ct(e){return O(e,"String")}function en(e){return O(e,"Symbol")}function je(e){return O(e,"TemplateLiteral")}function yf(e){return O(e,"This")}function Ut(e){return j(e)&&le in e}function qe(e){return O(e,"Tuple")}function tn(e){return O(e,"Undefined")}function N(e){return O(e,"Union")}function wf(e){return O(e,"Uint8Array")}function If(e){return O(e,"Unknown")}function xf(e){return O(e,"Unsafe")}function Pf(e){return O(e,"Void")}function bf(e){return j(e)&&w in e&&z(e[w])}function Ve(e){return ds(e)||us(e)||st(e)||Mt(e)||er(e)||Zt(e)||at(e)||dt(e)||Sf(e)||ut(e)||pt(e)||oe(e)||tr(e)||Be(e)||Ke(e)||Z(e)||Lt(e)||kf(e)||Zr(e)||ct(e)||ce(e)||rr(e)||nr(e)||se(e)||ps(e)||Ct(e)||en(e)||je(e)||yf(e)||qe(e)||tn(e)||N(e)||wf(e)||If(e)||xf(e)||Pf(e)||bf(e)}var D=u(()=>{Ce();b()});var p={};Hn(p,{IsAny:()=>Md,IsArgument:()=>Cd,IsArray:()=>Ed,IsAsyncIterator:()=>$d,IsBigInt:()=>Od,IsBoolean:()=>_d,IsComputed:()=>Nd,IsConstructor:()=>Fd,IsDate:()=>Dd,IsFunction:()=>Ld,IsImport:()=>Cf,IsInteger:()=>Ud,IsIntersect:()=>Wd,IsIterator:()=>Bd,IsKind:()=>mu,IsKindOf:()=>M,IsLiteral:()=>nn,IsLiteralBoolean:()=>Ef,IsLiteralNumber:()=>jd,IsLiteralString:()=>Kd,IsLiteralValue:()=>qd,IsMappedKey:()=>Vd,IsMappedResult:()=>Hd,IsNever:()=>Gd,IsNot:()=>zd,IsNull:()=>Qd,IsNumber:()=>Jd,IsObject:()=>Yd,IsOptional:()=>Mf,IsPromise:()=>Xd,IsProperties:()=>Xn,IsReadonly:()=>Tf,IsRecord:()=>Zd,IsRecursive:()=>$f,IsRef:()=>eu,IsRegExp:()=>tu,IsSchema:()=>Ie,IsString:()=>ru,IsSymbol:()=>nu,IsTemplateLiteral:()=>ou,IsThis:()=>iu,IsTransform:()=>su,IsTuple:()=>au,IsUint8Array:()=>uu,IsUndefined:()=>du,IsUnion:()=>fs,IsUnionLiteral:()=>Of,IsUnknown:()=>pu,IsUnsafe:()=>cu,IsVoid:()=>lu,TypeGuardUnknownTypeError:()=>cs});function Rd(e){try{return new RegExp(e),!0}catch{return!1}}function ls(e){if(!z(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 Ad(e){return ms(e)||Ie(e)}function rn(e){return pe(e)||Qr(e)}function Q(e){return pe(e)||We(e)}function ms(e){return pe(e)||Rt(e)}function q(e){return pe(e)||z(e)}function Rf(e){return pe(e)||z(e)&&ls(e)&&Rd(e)}function Af(e){return pe(e)||z(e)&&ls(e)}function Td(e){return pe(e)||Ie(e)}function Tf(e){return j(e)&&e[it]==="Readonly"}function Mf(e){return j(e)&&e[xe]==="Optional"}function Md(e){return M(e,"Any")&&q(e.$id)}function Cd(e){return M(e,"Argument")&&We(e.index)}function Ed(e){return M(e,"Array")&&e.type==="array"&&q(e.$id)&&Ie(e.items)&&Q(e.minItems)&&Q(e.maxItems)&&ms(e.uniqueItems)&&Td(e.contains)&&Q(e.minContains)&&Q(e.maxContains)}function $d(e){return M(e,"AsyncIterator")&&e.type==="AsyncIterator"&&q(e.$id)&&Ie(e.items)}function Od(e){return M(e,"BigInt")&&e.type==="bigint"&&q(e.$id)&&rn(e.exclusiveMaximum)&&rn(e.exclusiveMinimum)&&rn(e.maximum)&&rn(e.minimum)&&rn(e.multipleOf)}function _d(e){return M(e,"Boolean")&&e.type==="boolean"&&q(e.$id)}function Nd(e){return M(e,"Computed")&&z(e.target)&&ue(e.parameters)&&e.parameters.every(t=>Ie(t))}function Fd(e){return M(e,"Constructor")&&e.type==="Constructor"&&q(e.$id)&&ue(e.parameters)&&e.parameters.every(t=>Ie(t))&&Ie(e.returns)}function Dd(e){return M(e,"Date")&&e.type==="Date"&&q(e.$id)&&Q(e.exclusiveMaximumTimestamp)&&Q(e.exclusiveMinimumTimestamp)&&Q(e.maximumTimestamp)&&Q(e.minimumTimestamp)&&Q(e.multipleOfTimestamp)}function Ld(e){return M(e,"Function")&&e.type==="Function"&&q(e.$id)&&ue(e.parameters)&&e.parameters.every(t=>Ie(t))&&Ie(e.returns)}function Cf(e){return M(e,"Import")&&Gn(e,"$defs")&&j(e.$defs)&&Xn(e.$defs)&&Gn(e,"$ref")&&z(e.$ref)&&e.$ref in e.$defs}function Ud(e){return M(e,"Integer")&&e.type==="integer"&&q(e.$id)&&Q(e.exclusiveMaximum)&&Q(e.exclusiveMinimum)&&Q(e.maximum)&&Q(e.minimum)&&Q(e.multipleOf)}function Xn(e){return j(e)&&Object.entries(e).every(([t,r])=>ls(t)&&Ie(r))}function Wd(e){return M(e,"Intersect")&&!(z(e.type)&&e.type!=="object")&&ue(e.allOf)&&e.allOf.every(t=>Ie(t)&&!su(t))&&q(e.type)&&(ms(e.unevaluatedProperties)||Td(e.unevaluatedProperties))&&q(e.$id)}function Bd(e){return M(e,"Iterator")&&e.type==="Iterator"&&q(e.$id)&&Ie(e.items)}function M(e,t){return j(e)&&w in e&&e[w]===t}function Kd(e){return nn(e)&&z(e.const)}function jd(e){return nn(e)&&We(e.const)}function Ef(e){return nn(e)&&Rt(e.const)}function nn(e){return M(e,"Literal")&&q(e.$id)&&qd(e.const)}function qd(e){return Rt(e)||We(e)||z(e)}function Vd(e){return M(e,"MappedKey")&&ue(e.keys)&&e.keys.every(t=>We(t)||z(t))}function Hd(e){return M(e,"MappedResult")&&Xn(e.properties)}function Gd(e){return M(e,"Never")&&j(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function zd(e){return M(e,"Not")&&Ie(e.not)}function Qd(e){return M(e,"Null")&&e.type==="null"&&q(e.$id)}function Jd(e){return M(e,"Number")&&e.type==="number"&&q(e.$id)&&Q(e.exclusiveMaximum)&&Q(e.exclusiveMinimum)&&Q(e.maximum)&&Q(e.minimum)&&Q(e.multipleOf)}function Yd(e){return M(e,"Object")&&e.type==="object"&&q(e.$id)&&Xn(e.properties)&&Ad(e.additionalProperties)&&Q(e.minProperties)&&Q(e.maxProperties)}function Xd(e){return M(e,"Promise")&&e.type==="Promise"&&q(e.$id)&&Ie(e.item)}function Zd(e){return M(e,"Record")&&e.type==="object"&&q(e.$id)&&Ad(e.additionalProperties)&&j(e.patternProperties)&&(t=>{let r=Object.getOwnPropertyNames(t.patternProperties);return r.length===1&&Rd(r[0])&&j(t.patternProperties)&&Ie(t.patternProperties[r[0]])})(e)}function $f(e){return j(e)&&Je in e&&e[Je]==="Recursive"}function eu(e){return M(e,"Ref")&&q(e.$id)&&z(e.$ref)}function tu(e){return M(e,"RegExp")&&q(e.$id)&&z(e.source)&&z(e.flags)&&Q(e.maxLength)&&Q(e.minLength)}function ru(e){return M(e,"String")&&e.type==="string"&&q(e.$id)&&Q(e.minLength)&&Q(e.maxLength)&&Rf(e.pattern)&&Af(e.format)}function nu(e){return M(e,"Symbol")&&e.type==="symbol"&&q(e.$id)}function ou(e){return M(e,"TemplateLiteral")&&e.type==="string"&&z(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function iu(e){return M(e,"This")&&q(e.$id)&&z(e.$ref)}function su(e){return j(e)&&le in e}function au(e){return M(e,"Tuple")&&e.type==="array"&&q(e.$id)&&We(e.minItems)&&We(e.maxItems)&&e.minItems===e.maxItems&&(pe(e.items)&&pe(e.additionalItems)&&e.minItems===0||ue(e.items)&&e.items.every(t=>Ie(t)))}function du(e){return M(e,"Undefined")&&e.type==="undefined"&&q(e.$id)}function Of(e){return fs(e)&&e.anyOf.every(t=>Kd(t)||jd(t))}function fs(e){return M(e,"Union")&&q(e.$id)&&j(e)&&ue(e.anyOf)&&e.anyOf.every(t=>Ie(t))}function uu(e){return M(e,"Uint8Array")&&e.type==="Uint8Array"&&q(e.$id)&&Q(e.minByteLength)&&Q(e.maxByteLength)}function pu(e){return M(e,"Unknown")&&q(e.$id)}function cu(e){return M(e,"Unsafe")}function lu(e){return M(e,"Void")&&e.type==="void"&&q(e.$id)}function mu(e){return j(e)&&w in e&&z(e[w])&&!vf.includes(e[w])}function Ie(e){return j(e)&&(Md(e)||Cd(e)||Ed(e)||_d(e)||Od(e)||$d(e)||Nd(e)||Fd(e)||Dd(e)||Ld(e)||Ud(e)||Wd(e)||Bd(e)||nn(e)||Vd(e)||Hd(e)||Gd(e)||zd(e)||Qd(e)||Jd(e)||Yd(e)||Xd(e)||Zd(e)||eu(e)||tu(e)||ru(e)||nu(e)||ou(e)||iu(e)||au(e)||du(e)||fs(e)||uu(e)||pu(e)||cu(e)||lu(e)||mu(e))}var cs,vf,fu=u(()=>{Ce();b();kt();cs=class extends we{},vf=["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"]});var gs=u(()=>{D();fu();Ce()});var gu=u(()=>{});var hu=u(()=>{gu()});var hs,on,Ss,_f,gx,Wt,Bt,Su,ku=u(()=>{hs="(true|false)",on="(0|[1-9][0-9]*)",Ss="(.*)",_f="(?!.*)",gx=`^${hs}$`,Wt=`^${on}$`,Bt=`^${Ss}$`,Su=`^${_f}$`});var sn=u(()=>{ku()});var yu=u(()=>{});var wu=u(()=>{});var Iu=u(()=>{yu();wu()});function xu(e,t){return e.includes(t)}function Pu(e){return[...new Set(e)]}function Df(e,t){return e.filter(r=>t.includes(r))}function Lf(e,t){return e.reduce((r,n)=>Df(r,n),t)}function bu(e){return e.length===1?e[0]:e.length>1?Lf(e.slice(1),e[0]):[]}function vu(e){let t=[];for(let r of e)t.push(...r);return t}var Ru=u(()=>{});var an=u(()=>{Ru()});function Kt(e){return l({[w]:"Any"},e)}var Au=u(()=>{Tt();b()});var dn=u(()=>{Au()});function xr(e,t){return l({[w]:"Array",type:"array",items:e},t)}var Tu=u(()=>{P();b()});var un=u(()=>{Tu()});function Mu(e){return l({[w]:"Argument",index:e})}var Cu=u(()=>{P();b()});var ks=u(()=>{Cu()});function Pr(e,t){return l({[w]:"AsyncIterator",type:"AsyncIterator",items:e},t)}var Eu=u(()=>{b();P()});var pn=u(()=>{Eu()});function Y(e,t,r){return l({[w]:"Computed",target:e,parameters:t},r)}var $u=u(()=>{Tt();Xr()});var jt=u(()=>{$u()});function Uf(e,t){let{[t]:r,...n}=e;return n}function ie(e,t){return t.reduce((r,n)=>Uf(r,n),e)}var Zn=u(()=>{});var $t=u(()=>{Zn()});function F(e){return l({[w]:"Never",not:{}},e)}var Ou=u(()=>{P();b()});var Pe=u(()=>{Ou()});var _u=u(()=>{});function L(e){return l({[w]:"MappedResult",properties:e})}var ys=u(()=>{P();b()});function br(e,t,r){return l({[w]:"Constructor",type:"Constructor",parameters:e,returns:t},r)}var Nu=u(()=>{P();b()});var cn=u(()=>{Nu()});function yt(e,t,r){return l({[w]:"Function",type:"Function",parameters:e,returns:t},r)}var Fu=u(()=>{P();b()});var or=u(()=>{Fu()});function ln(e,t){return l({[w]:"Union",anyOf:e},t)}var ws=u(()=>{P();b()});function Wf(e){return e.some(t=>$e(t))}function Du(e){return e.map(t=>$e(t)?Bf(t):t)}function Bf(e){return ie(e,[xe])}function Kf(e,t){return Wf(e)?Re(ln(Du(e),t)):ln(Du(e),t)}function wt(e,t){return e.length===1?l(e[0],t):e.length===0?F(t):Kf(e,t)}var Lu=u(()=>{P();b();$t();Pe();Ot();ws();D()});var Uu=u(()=>{});function B(e,t){return e.length===0?F(t):e.length===1?l(e[0],t):ln(e,t)}var Wu=u(()=>{Pe();P();ws()});var me=u(()=>{Lu();Uu();Wu()});function jf(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Is(e,t,r){return e[t]===r&&e.charCodeAt(t-1)!==92}function _t(e,t){return Is(e,t,"(")}function mn(e,t){return Is(e,t,")")}function Bu(e,t){return Is(e,t,"|")}function qf(e){if(!(_t(e,0)&&mn(e,e.length-1)))return!1;let t=0;for(let r=0;r<e.length;r++)if(_t(e,r)&&(t+=1),mn(e,r)&&(t-=1),t===0&&r!==e.length-1)return!1;return!0}function Vf(e){return e.slice(1,e.length-1)}function Hf(e){let t=0;for(let r=0;r<e.length;r++)if(_t(e,r)&&(t+=1),mn(e,r)&&(t-=1),Bu(e,r)&&t===0)return!0;return!1}function Gf(e){for(let t=0;t<e.length;t++)if(_t(e,t))return!0;return!1}function zf(e){let[t,r]=[0,0],n=[];for(let i=0;i<e.length;i++)if(_t(e,i)&&(t+=1),mn(e,i)&&(t-=1),Bu(e,i)&&t===0){let s=e.slice(r,i);s.length>0&&n.push(vr(s)),r=i+1}let o=e.slice(r);return o.length>0&&n.push(vr(o)),n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"or",expr:n}}function Qf(e){function t(o,i){if(!_t(o,i))throw new eo("TemplateLiteralParser: Index must point to open parens");let s=0;for(let a=i;a<o.length;a++)if(_t(o,a)&&(s+=1),mn(o,a)&&(s-=1),s===0)return[i,a];throw new eo("TemplateLiteralParser: Unclosed group parens in expression")}function r(o,i){for(let s=i;s<o.length;s++)if(_t(o,s))return[i,s];return[i,o.length]}let n=[];for(let o=0;o<e.length;o++)if(_t(e,o)){let[i,s]=t(e,o),a=e.slice(i,s+1);n.push(vr(a)),o=s}else{let[i,s]=r(e,o),a=e.slice(i,s);a.length>0&&n.push(vr(a)),o=s-1}return n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"and",expr:n}}function vr(e){return qf(e)?vr(Vf(e)):Hf(e)?zf(e):Gf(e)?Qf(e):{type:"const",const:jf(e)}}function Rr(e){return vr(e.slice(1,e.length-1))}var eo,to=u(()=>{kt();eo=class extends we{}});function Jf(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 Yf(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 Xf(e){return e.type==="const"&&e.const===".*"}function ir(e){return Jf(e)||Xf(e)?!1:Yf(e)?!0:e.type==="and"?e.expr.every(t=>ir(t)):e.type==="or"?e.expr.every(t=>ir(t)):e.type==="const"?!0:(()=>{throw new xs("Unknown expression type")})()}function Ku(e){let t=Rr(e.pattern);return ir(t)}var xs,Ps=u(()=>{to();kt();xs=class extends we{}});function*ju(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let r of ju(e.slice(1)))yield`${t}${r}`}function*Zf(e){return yield*ju(e.expr.map(t=>[...fn(t)]))}function*eg(e){for(let t of e.expr)yield*fn(t)}function*tg(e){return yield e.const}function*fn(e){return e.type==="and"?yield*Zf(e):e.type==="or"?yield*eg(e):e.type==="const"?yield*tg(e):(()=>{throw new bs("Unknown expression")})()}function ro(e){let t=Rr(e.pattern);return ir(t)?[...fn(t)]:[]}var bs,vs=u(()=>{Ps();to();kt();bs=class extends we{}});function U(e,t){return l({[w]:"Literal",const:e,type:typeof e},t)}var qu=u(()=>{P();b()});var Oe=u(()=>{qu()});function no(e){return l({[w]:"Boolean",type:"boolean"},e)}var Vu=u(()=>{b();Tt()});var oo=u(()=>{Vu()});function Ar(e){return l({[w]:"BigInt",type:"bigint"},e)}var Hu=u(()=>{b();Tt()});var gn=u(()=>{Hu()});function Ye(e){return l({[w]:"Number",type:"number"},e)}var Gu=u(()=>{P();b()});var sr=u(()=>{Gu()});function lt(e){return l({[w]:"String",type:"string"},e)}var zu=u(()=>{P();b()});var Tr=u(()=>{zu()});function*rg(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield no():t==="number"?yield Ye():t==="bigint"?yield Ar():t==="string"?yield lt():yield(()=>{let r=t.split("|").map(n=>U(n.trim()));return r.length===0?F():r.length===1?r[0]:wt(r)})()}function*ng(e){if(e[1]!=="{"){let t=U("$"),r=Rs(e.slice(1));return yield*[t,...r]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let r=rg(e.slice(2,t)),n=Rs(e.slice(t+1));return yield*[...r,...n]}yield U(e)}function*Rs(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let r=U(e.slice(0,t)),n=ng(e.slice(t));return yield*[r,...n]}yield U(e)}function Qu(e){return[...Rs(e)]}var As=u(()=>{Oe();oo();gn();sr();Tr();me();Pe()});function og(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ju(e,t){return je(e)?e.pattern.slice(1,e.pattern.length-1):N(e)?`(${e.anyOf.map(r=>Ju(r,t)).join("|")})`:ct(e)?`${t}${on}`:pt(e)?`${t}${on}`:er(e)?`${t}${on}`:Ct(e)?`${t}${Ss}`:Be(e)?`${t}${og(e.const.toString())}`:Mt(e)?`${t}${hs}`:(()=>{throw new Ts(`Unexpected Kind '${e[w]}'`)})()}function Ms(e){return`^${e.map(t=>Ju(t,"")).join("")}$`}var Ts,Cs=u(()=>{sn();b();kt();D();Ts=class extends we{}});function ar(e){let r=ro(e).map(n=>U(n));return wt(r)}var Yu=u(()=>{me();Oe();vs()});function io(e,t){let r=z(e)?Ms(Qu(e)):Ms(e);return l({[w]:"TemplateLiteral",type:"string",pattern:r},t)}var Xu=u(()=>{P();As();Cs();Ce();b()});var Nt=u(()=>{Ps();vs();As();to();Cs();Yu();Xu()});function ig(e){return ro(e).map(r=>r.toString())}function sg(e){let t=[];for(let r of e)t.push(..._e(r));return t}function ag(e){return[e.toString()]}function _e(e){return[...new Set(je(e)?ig(e):N(e)?sg(e.anyOf):Be(e)?ag(e.const):ct(e)?["[number]"]:pt(e)?["[number]"]:[])]}var so=u(()=>{Nt();D()});function dg(e,t,r){let n={};for(let o of Object.getOwnPropertyNames(t))n[o]=qt(e,_e(t[o]),r);return n}function ug(e,t,r){return dg(e,t.properties,r)}function Zu(e,t,r){let n=ug(e,t,r);return L(n)}var Es=u(()=>{Se();so();It()});function tp(e,t){return e.map(r=>rp(r,t))}function pg(e){return e.filter(t=>!Lt(t))}function cg(e,t){return ao(pg(tp(e,t)))}function lg(e){return e.some(t=>Lt(t))?[]:e}function mg(e,t){return wt(lg(tp(e,t)))}function fg(e,t){return t in e?e[t]:t==="[number]"?wt(e):F()}function gg(e,t){return t==="[number]"?e:F()}function hg(e,t){return t in e?e[t]:F()}function rp(e,t){return oe(e)?cg(e.allOf,t):N(e)?mg(e.anyOf,t):qe(e)?fg(e.items??[],t):st(e)?gg(e.items,t):ce(e)?hg(e.properties,t):F()}function $s(e,t){return t.map(r=>rp(e,r))}function ep(e,t){return wt($s(e,t))}function qt(e,t,r){if(se(e)||se(t)){let n="Index types using Ref parameters require both Type and Key to be of TSchema";if(!Ve(e)||!Ve(t))throw new we(n);return Y("Index",[e,t])}return Z(t)?Zu(e,t,r):Ke(t)?np(e,t,r):l(Ve(t)?ep(e,_e(t)):ep(e,t),r)}var Os=u(()=>{P();kt();jt();Pe();Xe();me();so();_s();Es();D()});function Sg(e,t,r){return{[t]:qt(e,[t],X(r))}}function kg(e,t,r){return t.reduce((n,o)=>({...n,...Sg(e,o,r)}),{})}function yg(e,t,r){return kg(e,t.keys,r)}function np(e,t,r){let n=yg(e,t,r);return L(n)}var _s=u(()=>{Os();Se();Ee()});var It=u(()=>{_s();Es();so();Os()});function Mr(e,t){return l({[w]:"Iterator",type:"Iterator",items:e},t)}var op=u(()=>{P();b()});var hn=u(()=>{op()});function wg(e){return globalThis.Object.keys(e).filter(t=>!$e(e[t]))}function Ig(e,t){let r=wg(e),n=r.length>0?{[w]:"Object",type:"object",required:r,properties:e}:{[w]:"Object",type:"object",properties:e};return l(n,t)}var V,ip=u(()=>{P();b();D();V=Ig});var He=u(()=>{ip()});function uo(e,t){return l({[w]:"Promise",type:"Promise",item:e},t)}var sp=u(()=>{P();b()});var po=u(()=>{sp()});function xg(e){return l(ie(e,[it]))}function Pg(e){return l({...e,[it]:"Readonly"})}function bg(e,t){return t===!1?xg(e):Pg(e)}function Ne(e,t){let r=t??!0;return Z(e)?ap(e,r):bg(e,r)}var Ns=u(()=>{P();b();$t();Fs();D()});function vg(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Ne(e[n],t);return r}function Rg(e,t){return vg(e.properties,t)}function ap(e,t){let r=Rg(e,t);return L(r)}var Fs=u(()=>{Se();Ns()});var dr=u(()=>{Fs();Ns()});function Ze(e,t){return l(e.length>0?{[w]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[w]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}var dp=u(()=>{P();b()});var Vt=u(()=>{dp()});function up(e,t){return e in t?et(e,t[e]):L(t)}function Ag(e){return{[e]:U(e)}}function Tg(e){let t={};for(let r of e)t[r]=U(r);return t}function Mg(e,t){return xu(t,e)?Ag(e):Tg(t)}function Cg(e,t){let r=Mg(e,t);return up(e,r)}function Sn(e,t){return t.map(r=>et(e,r))}function Eg(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=et(e,t[n]);return r}function et(e,t){let r={...t};return $e(t)?Re(et(e,ie(t,[xe]))):Ir(t)?Ne(et(e,ie(t,[it]))):Z(t)?up(e,t.properties):Ke(t)?Cg(e,t.keys):dt(t)?br(Sn(e,t.parameters),et(e,t.returns),r):ut(t)?yt(Sn(e,t.parameters),et(e,t.returns),r):Zt(t)?Pr(et(e,t.items),r):tr(t)?Mr(et(e,t.items),r):oe(t)?Ae(Sn(e,t.allOf),r):N(t)?B(Sn(e,t.anyOf),r):qe(t)?Ze(Sn(e,t.items??[]),r):ce(t)?V(Eg(e,t.properties),r):st(t)?xr(et(e,t.items),r):rr(t)?uo(et(e,t.item),r):t}function $g(e,t){let r={};for(let n of e)r[n]=et(n,t);return r}function pp(e,t,r){let n=Ve(e)?_e(e):e,o=t({[w]:"MappedKey",keys:n}),i=$g(n,o);return V(i,r)}var cp=u(()=>{b();$t();un();pn();cn();or();It();Xe();hn();Oe();He();Ot();po();dr();Vt();me();an();ys();D()});var Se=u(()=>{_u();ys();cp()});function Og(e){return l(ie(e,[xe]))}function _g(e){return l({...e,[xe]:"Optional"})}function Ng(e,t){return t===!1?Og(e):_g(e)}function Re(e,t){let r=t??!0;return Z(e)?lp(e,r):Ng(e,r)}var Ds=u(()=>{P();b();$t();Ls();D()});function Fg(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Re(e[n],t);return r}function Dg(e,t){return Fg(e.properties,t)}function lp(e,t){let r=Dg(e,t);return L(r)}var Ls=u(()=>{Se();Ds()});var Ot=u(()=>{Ls();Ds()});function kn(e,t={}){let r=e.every(o=>ce(o)),n=Ve(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return l(t.unevaluatedProperties===!1||Ve(t.unevaluatedProperties)||r?{...n,[w]:"Intersect",type:"object",allOf:e}:{...n,[w]:"Intersect",allOf:e},t)}var Us=u(()=>{P();b();D()});function Lg(e){return e.every(t=>$e(t))}function Ug(e){return ie(e,[xe])}function mp(e){return e.map(t=>$e(t)?Ug(t):t)}function Wg(e,t){return Lg(e)?Re(kn(mp(e),t)):kn(mp(e),t)}function ao(e,t={}){if(e.length===1)return l(e[0],t);if(e.length===0)return F(t);if(e.some(r=>Ut(r)))throw new Error("Cannot intersect transform types");return Wg(e,t)}var fp=u(()=>{b();P();$t();Pe();Ot();Us();D()});var gp=u(()=>{});function Ae(e,t){if(e.length===1)return l(e[0],t);if(e.length===0)return F(t);if(e.some(r=>Ut(r)))throw new Error("Cannot intersect transform types");return kn(e,t)}var hp=u(()=>{P();Pe();Us();D()});var Xe=u(()=>{fp();gp();hp()});function xt(...e){let[t,r]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new we("Ref: $ref must be a string");return l({[w]:"Ref",$ref:t},r)}var Sp=u(()=>{kt();P();b()});var ur=u(()=>{Sp()});function Bg(e,t){return Y("Awaited",[Y(e,t)])}function Kg(e){return Y("Awaited",[xt(e)])}function jg(e){return Ae(kp(e))}function qg(e){return B(kp(e))}function Vg(e){return Cr(e)}function kp(e){return e.map(t=>Cr(t))}function Cr(e,t){return l(at(e)?Bg(e.target,e.parameters):oe(e)?jg(e.allOf):N(e)?qg(e.anyOf):rr(e)?Vg(e.item):se(e)?Kg(e.$ref):e,t)}var yp=u(()=>{P();jt();Xe();me();ur();D()});var co=u(()=>{yp()});function wp(e){let t=[];for(let r of e)t.push(yn(r));return t}function Hg(e){let t=wp(e);return vu(t)}function Gg(e){let t=wp(e);return bu(t)}function zg(e){return e.map((t,r)=>r.toString())}function Qg(e){return["[number]"]}function Jg(e){return globalThis.Object.getOwnPropertyNames(e)}function Yg(e){return Xg?globalThis.Object.getOwnPropertyNames(e).map(r=>r[0]==="^"&&r[r.length-1]==="$"?r.slice(1,r.length-1):r):[]}function yn(e){return oe(e)?Hg(e.allOf):N(e)?Gg(e.anyOf):qe(e)?zg(e.items??[]):st(e)?Qg(e.items):ce(e)?Jg(e.properties):nr(e)?Yg(e.patternProperties):[]}var Xg,Ws=u(()=>{an();D();Xg=!1});function Zg(e,t){return Y("KeyOf",[Y(e,t)])}function eh(e){return Y("KeyOf",[xt(e)])}function th(e,t){let r=yn(e),n=rh(r),o=wt(n);return l(o,t)}function rh(e){return e.map(t=>t==="[number]"?Ye():U(t))}function Er(e,t){return at(e)?Zg(e.target,e.parameters):se(e)?eh(e.$ref):Z(e)?Ip(e,t):th(e,t)}var Bs=u(()=>{P();Oe();sr();jt();ur();Ws();me();Ks();D()});function nh(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Er(e[n],X(t));return r}function oh(e,t){return nh(e.properties,t)}function Ip(e,t){let r=oh(e,t);return L(r)}var Ks=u(()=>{Se();Bs();Ee()});var xp=u(()=>{});var wn=u(()=>{Ks();xp();Ws();Bs()});function ih(e){let t=[];for(let r of e)t.push(...yn(r));return Pu(t)}function sh(e){return e.filter(t=>!Lt(t))}function ah(e,t){let r=[];for(let n of e)r.push(...$s(n,[t]));return sh(r)}function dh(e,t){let r={};for(let n of t)r[n]=ao(ah(e,n));return r}function Pp(e,t){let r=ih(e),n=dh(e,r);return V(n,t)}var bp=u(()=>{Xe();It();wn();He();an();D()});var js=u(()=>{bp()});function lo(e){return l({[w]:"Date",type:"Date"},e)}var vp=u(()=>{b();P()});var mo=u(()=>{vp()});function fo(e){return l({[w]:"Null",type:"null"},e)}var Rp=u(()=>{P();b()});var go=u(()=>{Rp()});function ho(e){return l({[w]:"Symbol",type:"symbol"},e)}var Ap=u(()=>{P();b()});var So=u(()=>{Ap()});function ko(e){return l({[w]:"Undefined",type:"undefined"},e)}var Tp=u(()=>{P();b()});var yo=u(()=>{Tp()});function wo(e){return l({[w]:"Uint8Array",type:"Uint8Array"},e)}var Mp=u(()=>{P();b()});var Io=u(()=>{Mp()});function Ht(e){return l({[w]:"Unknown"},e)}var Cp=u(()=>{P();b()});var $r=u(()=>{Cp()});function uh(e){return e.map(t=>qs(t,!1))}function ph(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=Ne(qs(e[r],!1));return t}function xo(e,t){return t===!0?e:Ne(e)}function qs(e,t){return rs(e)?xo(Kt(),t):os(e)?xo(Kt(),t):ue(e)?Ne(Ze(uh(e))):At(e)?wo():Xt(e)?lo():j(e)?xo(V(ph(e)),t):ns(e)?xo(yt([],Ht()),t):pe(e)?ko():is(e)?fo():ss(e)?ho():Qr(e)?Ar():We(e)?U(e):Rt(e)?U(e):z(e)?U(e):V({})}function Ep(e,t){return l(qs(e,!0),t)}var $p=u(()=>{dn();gn();mo();or();Oe();go();He();So();Vt();dr();yo();Io();$r();Tt();Ce()});var Vs=u(()=>{$p()});function Op(e,t){return dt(e)?Ze(e.parameters,t):F(t)}var _p=u(()=>{Vt();Pe();D()});var Hs=u(()=>{_p()});function Np(e,t){if(pe(e))throw new Error("Enum undefined or empty");let r=globalThis.Object.getOwnPropertyNames(e).filter(i=>isNaN(i)).map(i=>e[i]),o=[...new Set(r)].map(i=>U(i));return B(o,{...t,[Je]:"Enum"})}var Fp=u(()=>{Oe();b();me();Ce()});var Gs=u(()=>{Fp()});function tt(e){return e===f.False?e:f.True}function Or(e){throw new Qs(e)}function fe(e){return p.IsNever(e)||p.IsIntersect(e)||p.IsUnion(e)||p.IsUnknown(e)||p.IsAny(e)}function ge(e,t){return p.IsNever(t)?jp(e,t):p.IsIntersect(t)?Po(e,t):p.IsUnion(t)?Zs(e,t):p.IsUnknown(t)?Gp(e,t):p.IsAny(t)?Xs(e,t):Or("StructuralRight")}function Xs(e,t){return f.True}function ch(e,t){return p.IsIntersect(t)?Po(e,t):p.IsUnion(t)&&t.anyOf.some(r=>p.IsAny(r)||p.IsUnknown(r))?f.True:p.IsUnion(t)?f.Union:p.IsUnknown(t)||p.IsAny(t)?f.True:f.Union}function lh(e,t){return p.IsUnknown(e)?f.False:p.IsAny(e)?f.Union:p.IsNever(e)?f.True:f.False}function mh(e,t){return p.IsObject(t)&&bo(t)?f.True:fe(t)?ge(e,t):p.IsArray(t)?tt(H(e.items,t.items)):f.False}function fh(e,t){return fe(t)?ge(e,t):p.IsAsyncIterator(t)?tt(H(e.items,t.items)):f.False}function gh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsBigInt(t)?f.True:f.False}function Bp(e,t){return p.IsLiteralBoolean(e)||p.IsBoolean(e)?f.True:f.False}function hh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsBoolean(t)?f.True:f.False}function Sh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsConstructor(t)?e.parameters.length>t.parameters.length?f.False:e.parameters.every((r,n)=>tt(H(t.parameters[n],r))===f.True)?tt(H(e.returns,t.returns)):f.False:f.False}function kh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsDate(t)?f.True:f.False}function yh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsFunction(t)?e.parameters.length>t.parameters.length?f.False:e.parameters.every((r,n)=>tt(H(t.parameters[n],r))===f.True)?tt(H(e.returns,t.returns)):f.False:f.False}function Kp(e,t){return p.IsLiteral(e)&&ve.IsNumber(e.const)||p.IsNumber(e)||p.IsInteger(e)?f.True:f.False}function wh(e,t){return p.IsInteger(t)||p.IsNumber(t)?f.True:fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):f.False}function Po(e,t){return t.allOf.every(r=>H(e,r)===f.True)?f.True:f.False}function Ih(e,t){return e.allOf.some(r=>H(r,t)===f.True)?f.True:f.False}function xh(e,t){return fe(t)?ge(e,t):p.IsIterator(t)?tt(H(e.items,t.items)):f.False}function Ph(e,t){return p.IsLiteral(t)&&t.const===e.const?f.True:fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsString(t)?Hp(e,t):p.IsNumber(t)?qp(e,t):p.IsInteger(t)?Kp(e,t):p.IsBoolean(t)?Bp(e,t):f.False}function jp(e,t){return f.False}function bh(e,t){return f.True}function Dp(e){let[t,r]=[e,0];for(;p.IsNot(t);)t=t.not,r+=1;return r%2===0?t:Ht()}function vh(e,t){return p.IsNot(e)?H(Dp(e),t):p.IsNot(t)?H(e,Dp(t)):Or("Invalid fallthrough for Not")}function Rh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsNull(t)?f.True:f.False}function qp(e,t){return p.IsLiteralNumber(e)||p.IsNumber(e)||p.IsInteger(e)?f.True:f.False}function Ah(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsInteger(t)||p.IsNumber(t)?f.True:f.False}function Fe(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Lp(e){return bo(e)}function Up(e){return Fe(e,0)||Fe(e,1)&&"description"in e.properties&&p.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(p.IsString(e.properties.description.anyOf[0])&&p.IsUndefined(e.properties.description.anyOf[1])||p.IsString(e.properties.description.anyOf[1])&&p.IsUndefined(e.properties.description.anyOf[0]))}function zs(e){return Fe(e,0)}function Wp(e){return Fe(e,0)}function Th(e){return Fe(e,0)}function Mh(e){return Fe(e,0)}function Ch(e){return bo(e)}function Eh(e){let t=Ye();return Fe(e,0)||Fe(e,1)&&"length"in e.properties&&tt(H(e.properties.length,t))===f.True}function $h(e){return Fe(e,0)}function bo(e){let t=Ye();return Fe(e,0)||Fe(e,1)&&"length"in e.properties&&tt(H(e.properties.length,t))===f.True}function Oh(e){let t=yt([Kt()],Kt());return Fe(e,0)||Fe(e,1)&&"then"in e.properties&&tt(H(e.properties.then,t))===f.True}function Vp(e,t){return H(e,t)===f.False||p.IsOptional(e)&&!p.IsOptional(t)?f.False:f.True}function Te(e,t){return p.IsUnknown(e)?f.False:p.IsAny(e)?f.Union:p.IsNever(e)||p.IsLiteralString(e)&&Lp(t)||p.IsLiteralNumber(e)&&zs(t)||p.IsLiteralBoolean(e)&&Wp(t)||p.IsSymbol(e)&&Up(t)||p.IsBigInt(e)&&Th(t)||p.IsString(e)&&Lp(t)||p.IsSymbol(e)&&Up(t)||p.IsNumber(e)&&zs(t)||p.IsInteger(e)&&zs(t)||p.IsBoolean(e)&&Wp(t)||p.IsUint8Array(e)&&Ch(t)||p.IsDate(e)&&Mh(t)||p.IsConstructor(e)&&$h(t)||p.IsFunction(e)&&Eh(t)?f.True:p.IsRecord(e)&&p.IsString(Js(e))?t[Je]==="Record"?f.True:f.False:p.IsRecord(e)&&p.IsNumber(Js(e))&&Fe(t,0)?f.True:f.False}function _h(e,t){return fe(t)?ge(e,t):p.IsRecord(t)?rt(e,t):p.IsObject(t)?(()=>{for(let r of Object.getOwnPropertyNames(t.properties)){if(!(r in e.properties)&&!p.IsOptional(t.properties[r]))return f.False;if(p.IsOptional(t.properties[r]))return f.True;if(Vp(e.properties[r],t.properties[r])===f.False)return f.False}return f.True})():f.False}function Nh(e,t){return fe(t)?ge(e,t):p.IsObject(t)&&Oh(t)?f.True:p.IsPromise(t)?tt(H(e.item,t.item)):f.False}function Js(e){return Wt in e.patternProperties?Ye():Bt in e.patternProperties?lt():Or("Unknown record key pattern")}function Ys(e){return Wt in e.patternProperties?e.patternProperties[Wt]:Bt in e.patternProperties?e.patternProperties[Bt]:Or("Unable to get record value schema")}function rt(e,t){let[r,n]=[Js(t),Ys(t)];return p.IsLiteralString(e)&&p.IsNumber(r)&&tt(H(e,n))===f.True?f.True:p.IsUint8Array(e)&&p.IsNumber(r)||p.IsString(e)&&p.IsNumber(r)||p.IsArray(e)&&p.IsNumber(r)?H(e,n):p.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(Vp(n,e.properties[o])===f.False)return f.False;return f.True})():f.False}function Fh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?H(Ys(e),Ys(t)):f.False}function Dh(e,t){let r=p.IsRegExp(e)?lt():e,n=p.IsRegExp(t)?lt():t;return H(r,n)}function Hp(e,t){return p.IsLiteral(e)&&ve.IsString(e.const)||p.IsString(e)?f.True:f.False}function Lh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsString(t)?f.True:f.False}function Uh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsSymbol(t)?f.True:f.False}function Wh(e,t){return p.IsTemplateLiteral(e)?H(ar(e),t):p.IsTemplateLiteral(t)?H(e,ar(t)):Or("Invalid fallthrough for TemplateLiteral")}function Bh(e,t){return p.IsArray(t)&&e.items!==void 0&&e.items.every(r=>H(r,t.items)===f.True)}function Kh(e,t){return p.IsNever(e)?f.True:p.IsUnknown(e)?f.False:p.IsAny(e)?f.Union:f.False}function jh(e,t){return fe(t)?ge(e,t):p.IsObject(t)&&bo(t)||p.IsArray(t)&&Bh(e,t)?f.True:p.IsTuple(t)?ve.IsUndefined(e.items)&&!ve.IsUndefined(t.items)||!ve.IsUndefined(e.items)&&ve.IsUndefined(t.items)?f.False:ve.IsUndefined(e.items)&&!ve.IsUndefined(t.items)||e.items.every((r,n)=>H(r,t.items[n])===f.True)?f.True:f.False:f.False}function qh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsUint8Array(t)?f.True:f.False}function Vh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsVoid(t)?zh(e,t):p.IsUndefined(t)?f.True:f.False}function Zs(e,t){return t.anyOf.some(r=>H(e,r)===f.True)?f.True:f.False}function Hh(e,t){return e.anyOf.every(r=>H(r,t)===f.True)?f.True:f.False}function Gp(e,t){return f.True}function Gh(e,t){return p.IsNever(t)?jp(e,t):p.IsIntersect(t)?Po(e,t):p.IsUnion(t)?Zs(e,t):p.IsAny(t)?Xs(e,t):p.IsString(t)?Hp(e,t):p.IsNumber(t)?qp(e,t):p.IsInteger(t)?Kp(e,t):p.IsBoolean(t)?Bp(e,t):p.IsArray(t)?lh(e,t):p.IsTuple(t)?Kh(e,t):p.IsObject(t)?Te(e,t):p.IsUnknown(t)?f.True:f.False}function zh(e,t){return p.IsUndefined(e)||p.IsUndefined(e)?f.True:f.False}function Qh(e,t){return p.IsIntersect(t)?Po(e,t):p.IsUnion(t)?Zs(e,t):p.IsUnknown(t)?Gp(e,t):p.IsAny(t)?Xs(e,t):p.IsObject(t)?Te(e,t):p.IsVoid(t)?f.True:f.False}function H(e,t){return p.IsTemplateLiteral(e)||p.IsTemplateLiteral(t)?Wh(e,t):p.IsRegExp(e)||p.IsRegExp(t)?Dh(e,t):p.IsNot(e)||p.IsNot(t)?vh(e,t):p.IsAny(e)?ch(e,t):p.IsArray(e)?mh(e,t):p.IsBigInt(e)?gh(e,t):p.IsBoolean(e)?hh(e,t):p.IsAsyncIterator(e)?fh(e,t):p.IsConstructor(e)?Sh(e,t):p.IsDate(e)?kh(e,t):p.IsFunction(e)?yh(e,t):p.IsInteger(e)?wh(e,t):p.IsIntersect(e)?Ih(e,t):p.IsIterator(e)?xh(e,t):p.IsLiteral(e)?Ph(e,t):p.IsNever(e)?bh(e,t):p.IsNull(e)?Rh(e,t):p.IsNumber(e)?Ah(e,t):p.IsObject(e)?_h(e,t):p.IsRecord(e)?Fh(e,t):p.IsString(e)?Lh(e,t):p.IsSymbol(e)?Uh(e,t):p.IsTuple(e)?jh(e,t):p.IsPromise(e)?Nh(e,t):p.IsUint8Array(e)?qh(e,t):p.IsUndefined(e)?Vh(e,t):p.IsUnion(e)?Hh(e,t):p.IsUnknown(e)?Gh(e,t):p.IsVoid(e)?Qh(e,t):Or(`Unknown left type operand '${e[w]}'`)}function Gt(e,t){return H(e,t)}var Qs,f,ea=u(()=>{dn();or();sr();Tr();$r();Nt();sn();b();kt();gs();Qs=class extends we{};(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(f||(f={}))});function Jh(e,t,r,n,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(e))i[s]=_r(e[s],t,r,n,X(o));return i}function Yh(e,t,r,n,o){return Jh(e.properties,t,r,n,o)}function zp(e,t,r,n,o){let i=Yh(e,t,r,n,o);return L(i)}var ta=u(()=>{Se();vo();Ee()});function Xh(e,t,r,n){let o=Gt(e,t);return o===f.Union?B([r,n]):o===f.True?r:n}function _r(e,t,r,n,o){return Z(e)?zp(e,t,r,n,o):Ke(e)?l(Qp(e,t,r,n,o)):l(Xh(e,t,r,n),o)}var vo=u(()=>{P();me();ea();ra();ta();D()});function Zh(e,t,r,n,o){return{[e]:_r(U(e),t,r,n,X(o))}}function eS(e,t,r,n,o){return e.reduce((i,s)=>({...i,...Zh(s,t,r,n,o)}),{})}function tS(e,t,r,n,o){return eS(e.keys,t,r,n,o)}function Qp(e,t,r,n,o){let i=tS(e,t,r,n,o);return L(i)}var ra=u(()=>{Se();Oe();vo();Ee()});var Jp=u(()=>{});var In=u(()=>{ea();ra();ta();Jp();vo()});function Yp(e,t){return Nr(ar(e),t)}var na=u(()=>{Ro();Nt()});function rS(e,t){let r=e.filter(n=>Gt(n,t)===f.False);return r.length===1?r[0]:B(r)}function Nr(e,t,r={}){return je(e)?l(Yp(e,t),r):Z(e)?l(Xp(e,t),r):l(N(e)?rS(e.anyOf,t):Gt(e,t)!==f.False?F():e,r)}var Ro=u(()=>{P();me();Pe();In();oa();na();D()});function nS(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Nr(e[n],t);return r}function oS(e,t){return nS(e.properties,t)}function Xp(e,t){let r=oS(e,t);return L(r)}var oa=u(()=>{Se();Ro()});var ia=u(()=>{oa();na();Ro()});function Zp(e,t){return Fr(ar(e),t)}var sa=u(()=>{Ao();Nt()});function iS(e,t){let r=e.filter(n=>Gt(n,t)!==f.False);return r.length===1?r[0]:B(r)}function Fr(e,t,r){return je(e)?l(Zp(e,t),r):Z(e)?l(ec(e,t),r):l(N(e)?iS(e.anyOf,t):Gt(e,t)!==f.False?e:F(),r)}var Ao=u(()=>{P();me();Pe();In();aa();sa();D()});function sS(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Fr(e[n],t);return r}function aS(e,t){return sS(e.properties,t)}function ec(e,t){let r=aS(e,t);return L(r)}var aa=u(()=>{Se();Ao()});var da=u(()=>{aa();sa();Ao()});function tc(e,t){return dt(e)?l(e.returns,t):F(t)}var rc=u(()=>{P();Pe();D()});var ua=u(()=>{rc()});function To(e){return Ne(Re(e))}var nc=u(()=>{dr();Ot()});var Mo=u(()=>{nc()});function pr(e,t,r){return l({[w]:"Record",type:"object",patternProperties:{[e]:t}},r)}function pa(e,t,r){let n={};for(let o of e)n[o]=t;return V(n,{...r,[Je]:"Record"})}function dS(e,t,r){return Ku(e)?pa(_e(e),t,r):pr(e.pattern,t,r)}function uS(e,t,r){return pa(_e(B(e)),t,r)}function pS(e,t,r){return pa([e.toString()],t,r)}function cS(e,t,r){return pr(e.source,t,r)}function lS(e,t,r){let n=pe(e.pattern)?Bt:e.pattern;return pr(n,t,r)}function mS(e,t,r){return pr(Bt,t,r)}function fS(e,t,r){return pr(Su,t,r)}function gS(e,t,r){return V({true:t,false:t},r)}function hS(e,t,r){return pr(Wt,t,r)}function SS(e,t,r){return pr(Wt,t,r)}function Co(e,t,r={}){return N(e)?uS(e.anyOf,t,r):je(e)?dS(e,t,r):Be(e)?pS(e.const,t,r):Mt(e)?gS(e,t,r):pt(e)?hS(e,t,r):ct(e)?SS(e,t,r):ps(e)?cS(e,t,r):Ct(e)?lS(e,t,r):ds(e)?mS(e,t,r):Lt(e)?fS(e,t,r):F(r)}function Eo(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function oc(e){let t=Eo(e);return t===Bt?lt():t===Wt?Ye():lt({pattern:t})}function $o(e){return e.patternProperties[Eo(e)]}var ic=u(()=>{P();b();Pe();sr();He();Tr();me();Nt();sn();It();Ce();D()});var xn=u(()=>{ic()});function kS(e,t){return t.parameters=Pn(e,t.parameters),t.returns=mt(e,t.returns),t}function yS(e,t){return t.parameters=Pn(e,t.parameters),t.returns=mt(e,t.returns),t}function wS(e,t){return t.allOf=Pn(e,t.allOf),t}function IS(e,t){return t.anyOf=Pn(e,t.anyOf),t}function xS(e,t){return pe(t.items)||(t.items=Pn(e,t.items)),t}function PS(e,t){return t.items=mt(e,t.items),t}function bS(e,t){return t.items=mt(e,t.items),t}function vS(e,t){return t.items=mt(e,t.items),t}function RS(e,t){return t.item=mt(e,t.item),t}function AS(e,t){let r=ES(e,t.properties);return{...t,...V(r)}}function TS(e,t){let r=mt(e,oc(t)),n=mt(e,$o(t)),o=Co(r,n);return{...t,...o}}function MS(e,t){return t.index in e?e[t.index]:Ht()}function CS(e,t){let r=Ir(t),n=$e(t),o=mt(e,t);return r&&n?To(o):r&&!n?Ne(o):!r&&n?Re(o):o}function ES(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:CS(e,t[n])}),{})}function Pn(e,t){return t.map(r=>mt(e,r))}function mt(e,t){return dt(t)?kS(e,t):ut(t)?yS(e,t):oe(t)?wS(e,t):N(t)?IS(e,t):qe(t)?xS(e,t):st(t)?PS(e,t):Zt(t)?bS(e,t):tr(t)?vS(e,t):rr(t)?RS(e,t):ce(t)?AS(e,t):nr(t)?TS(e,t):us(t)?MS(e,t):t}function sc(e,t){return mt(t,wr(e))}var ac=u(()=>{Qn();$r();Mo();dr();Ot();He();xn();Ce();D()});var ca=u(()=>{ac()});function dc(e){return l({[w]:"Integer",type:"integer"},e)}var uc=u(()=>{P();b()});var la=u(()=>{uc()});function $S(e,t,r){return{[e]:ft(U(e),t,X(r))}}function OS(e,t,r){return e.reduce((o,i)=>({...o,...$S(i,t,r)}),{})}function _S(e,t,r){return OS(e.keys,t,r)}function pc(e,t,r){let n=_S(e,t,r);return L(n)}var ma=u(()=>{Se();cr();Oe();Ee()});function NS(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),r].join("")}function FS(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),r].join("")}function DS(e){return e.toUpperCase()}function LS(e){return e.toLowerCase()}function US(e,t,r){let n=Rr(e.pattern);if(!ir(n))return{...e,pattern:cc(e.pattern,t)};let s=[...fn(n)].map(c=>U(c)),a=lc(s,t),d=B(a);return io([d],r)}function cc(e,t){return typeof e=="string"?t==="Uncapitalize"?NS(e):t==="Capitalize"?FS(e):t==="Uppercase"?DS(e):t==="Lowercase"?LS(e):e:e.toString()}function lc(e,t){return e.map(r=>ft(r,t))}function ft(e,t,r={}){return Ke(e)?pc(e,t,r):je(e)?US(e,t,r):N(e)?B(lc(e.anyOf,t),r):Be(e)?U(cc(e.const,t),r):l(e,r)}var cr=u(()=>{P();Nt();ma();Oe();me();D()});function mc(e,t={}){return ft(e,"Capitalize",t)}var fc=u(()=>{cr()});function gc(e,t={}){return ft(e,"Lowercase",t)}var hc=u(()=>{cr()});function Sc(e,t={}){return ft(e,"Uncapitalize",t)}var kc=u(()=>{cr()});function yc(e,t={}){return ft(e,"Uppercase",t)}var wc=u(()=>{cr()});var fa=u(()=>{fc();ma();cr();hc();kc();wc()});function WS(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=zt(e[o],t,X(r));return n}function BS(e,t,r){return WS(e.properties,t,r)}function Ic(e,t,r){let n=BS(e,t,r);return L(n)}var ga=u(()=>{Se();Oo();Ee()});function KS(e,t){return e.map(r=>ha(r,t))}function jS(e,t){return e.map(r=>ha(r,t))}function qS(e,t){let{[t]:r,...n}=e;return n}function VS(e,t){return t.reduce((r,n)=>qS(r,n),e)}function HS(e,t,r){let n=ie(e,[le,"$id","required","properties"]),o=VS(r,t);return V(o,n)}function GS(e){let t=e.reduce((r,n)=>Yn(n)?[...r,U(n)]:r,[]);return B(t)}function ha(e,t){return oe(e)?Ae(KS(e.allOf,t)):N(e)?B(jS(e.anyOf,t)):ce(e)?HS(e,t,e.properties):V({})}function zt(e,t,r){let n=ue(t)?GS(t):t,o=Ve(t)?_e(t):t,i=se(e),s=se(t);return Z(e)?Ic(e,o,r):Ke(t)?xc(e,t,r):i&&s?Y("Omit",[e,n],r):!i&&s?Y("Omit",[e,n],r):i&&!s?Y("Omit",[e,n],r):l({...ha(e,o),...r})}var Oo=u(()=>{P();Zn();Xr();jt();Oe();It();Xe();me();He();Sa();ga();D();Ce()});function zS(e,t,r){return{[t]:zt(e,[t],X(r))}}function QS(e,t,r){return t.reduce((n,o)=>({...n,...zS(e,o,r)}),{})}function JS(e,t,r){return QS(e,t.keys,r)}function xc(e,t,r){let n=JS(e,t,r);return L(n)}var Sa=u(()=>{Se();Oo();Ee()});var _o=u(()=>{Sa();ga();Oo()});function YS(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=Qt(e[o],t,X(r));return n}function XS(e,t,r){return YS(e.properties,t,r)}function Pc(e,t,r){let n=XS(e,t,r);return L(n)}var ka=u(()=>{Se();No();Ee()});function ZS(e,t){return e.map(r=>ya(r,t))}function ek(e,t){return e.map(r=>ya(r,t))}function tk(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function rk(e,t,r){let n=ie(e,[le,"$id","required","properties"]),o=tk(r,t);return V(o,n)}function nk(e){let t=e.reduce((r,n)=>Yn(n)?[...r,U(n)]:r,[]);return B(t)}function ya(e,t){return oe(e)?Ae(ZS(e.allOf,t)):N(e)?B(ek(e.anyOf,t)):ce(e)?rk(e,t,e.properties):V({})}function Qt(e,t,r){let n=ue(t)?nk(t):t,o=Ve(t)?_e(t):t,i=se(e),s=se(t);return Z(e)?Pc(e,o,r):Ke(t)?bc(e,t,r):i&&s?Y("Pick",[e,n],r):!i&&s?Y("Pick",[e,n],r):i&&!s?Y("Pick",[e,n],r):l({...ya(e,o),...r})}var No=u(()=>{P();Zn();jt();Xe();Oe();He();me();It();Xr();D();Ce();wa();ka()});function ok(e,t,r){return{[t]:Qt(e,[t],X(r))}}function ik(e,t,r){return t.reduce((n,o)=>({...n,...ok(e,o,r)}),{})}function sk(e,t,r){return ik(e,t.keys,r)}function bc(e,t,r){let n=sk(e,t,r);return L(n)}var wa=u(()=>{Se();No();Ee()});var Fo=u(()=>{wa();ka();No()});function ak(e,t){return Y("Partial",[Y(e,t)])}function dk(e){return Y("Partial",[xt(e)])}function uk(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=Re(e[r]);return t}function pk(e,t){let r=ie(e,[le,"$id","required","properties"]),n=uk(t);return V(n,r)}function vc(e){return e.map(t=>Rc(t))}function Rc(e){return at(e)?ak(e.target,e.parameters):se(e)?dk(e.$ref):oe(e)?Ae(vc(e.allOf)):N(e)?B(vc(e.anyOf)):ce(e)?pk(e,e.properties):er(e)||Mt(e)||pt(e)||Be(e)||Zr(e)||ct(e)||Ct(e)||en(e)||tn(e)?e:V({})}function Dr(e,t){return Z(e)?Ac(e,t):l({...Rc(e),...t})}var Ia=u(()=>{P();jt();Ot();He();Xe();me();ur();$t();b();xa();D()});function ck(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Dr(e[n],X(t));return r}function lk(e,t){return ck(e.properties,t)}function Ac(e,t){let r=lk(e,t);return L(r)}var xa=u(()=>{Se();Ia();Ee()});var Do=u(()=>{xa();Ia()});function mk(e,t){return Y("Required",[Y(e,t)])}function fk(e){return Y("Required",[xt(e)])}function gk(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=ie(e[r],[xe]);return t}function hk(e,t){let r=ie(e,[le,"$id","required","properties"]),n=gk(t);return V(n,r)}function Tc(e){return e.map(t=>Mc(t))}function Mc(e){return at(e)?mk(e.target,e.parameters):se(e)?fk(e.$ref):oe(e)?Ae(Tc(e.allOf)):N(e)?B(Tc(e.anyOf)):ce(e)?hk(e,e.properties):er(e)||Mt(e)||pt(e)||Be(e)||Zr(e)||ct(e)||Ct(e)||en(e)||tn(e)?e:V({})}function Lr(e,t){return Z(e)?Cc(e,t):l({...Mc(e),...t})}var Pa=u(()=>{P();jt();He();Xe();me();ur();b();$t();ba();D()});function Sk(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Lr(e[n],t);return r}function kk(e,t){return Sk(e.properties,t)}function Cc(e,t){let r=kk(e,t);return L(r)}var ba=u(()=>{Se();Pa()});var Lo=u(()=>{ba();Pa()});function yk(e,t){return t.map(r=>se(r)?va(e,r.$ref):Ge(e,r))}function va(e,t){return t in e?se(e[t])?va(e,e[t].$ref):Ge(e,e[t]):F()}function wk(e){return Cr(e[0])}function Ik(e){return qt(e[0],e[1])}function xk(e){return Er(e[0])}function Pk(e){return Dr(e[0])}function bk(e){return zt(e[0],e[1])}function vk(e){return Qt(e[0],e[1])}function Rk(e){return Lr(e[0])}function Ak(e,t,r){let n=yk(e,r);return t==="Awaited"?wk(n):t==="Index"?Ik(n):t==="KeyOf"?xk(n):t==="Partial"?Pk(n):t==="Omit"?bk(n):t==="Pick"?vk(n):t==="Required"?Rk(n):F()}function Tk(e,t){return xr(Ge(e,t))}function Mk(e,t){return Pr(Ge(e,t))}function Ck(e,t,r){return br(bn(e,t),Ge(e,r))}function Ek(e,t,r){return yt(bn(e,t),Ge(e,r))}function $k(e,t){return Ae(bn(e,t))}function Ok(e,t){return Mr(Ge(e,t))}function _k(e,t){return V(globalThis.Object.keys(t).reduce((r,n)=>({...r,[n]:Ge(e,t[n])}),{}))}function Nk(e,t){let[r,n]=[Ge(e,$o(t)),Eo(t)],o=wr(t);return o.patternProperties[n]=r,o}function Fk(e,t){return se(t)?{...va(e,t.$ref),[le]:t[le]}:t}function Dk(e,t){return Ze(bn(e,t))}function Lk(e,t){return B(bn(e,t))}function bn(e,t){return t.map(r=>Ge(e,r))}function Ge(e,t){return $e(t)?l(Ge(e,ie(t,[xe])),t):Ir(t)?l(Ge(e,ie(t,[it])),t):Ut(t)?l(Fk(e,t),t):st(t)?l(Tk(e,t.items),t):Zt(t)?l(Mk(e,t.items),t):at(t)?l(Ak(e,t.target,t.parameters)):dt(t)?l(Ck(e,t.parameters,t.returns),t):ut(t)?l(Ek(e,t.parameters,t.returns),t):oe(t)?l($k(e,t.allOf),t):tr(t)?l(Ok(e,t.items),t):ce(t)?l(_k(e,t.properties),t):nr(t)?l(Nk(e,t)):qe(t)?l(Dk(e,t.items||[]),t):N(t)?l(Lk(e,t.anyOf),t):t}function Uk(e,t){return t in e?Ge(e,e[t]):F()}function Ec(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,r)=>({...t,[r]:Uk(e,r)}),{})}var $c=u(()=>{Tt();as();$t();un();co();pn();cn();It();or();Xe();hn();wn();He();_o();Fo();Pe();Do();xn();Lo();Vt();me();b();D()});function Oc(e){return new Ra(e)}var Ra,_c=u(()=>{Tt();b();$c();Ra=class{constructor(t){let r=Ec(t),n=this.WithIdentifiers(r);this.$defs=n}Import(t,r){let n={...this.$defs,[t]:l(this.$defs[t],r)};return l({[w]:"Import",$defs:n,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:{...t[n],$id:n}}),{})}}});var Aa=u(()=>{_c()});function Nc(e,t){return l({[w]:"Not",not:e},t)}var Fc=u(()=>{P();b()});var Ta=u(()=>{Fc()});function Dc(e,t){return ut(e)?Ze(e.parameters,t):F()}var Lc=u(()=>{Vt();Pe();D()});var Ma=u(()=>{Lc()});function Uc(e,t={}){pe(t.$id)&&(t.$id=`T${Wk++}`);let r=wr(e({[w]:"This",$ref:`${t.$id}`}));return r.$id=t.$id,l({[Je]:"Recursive",...r},t)}var Wk,Wc=u(()=>{Qn();P();Ce();b();Wk=0});var Ca=u(()=>{Wc()});function Bc(e,t){let r=z(e)?new globalThis.RegExp(e):e;return l({[w]:"RegExp",type:"RegExp",source:r.source,flags:r.flags},t)}var Kc=u(()=>{P();Ce();b()});var Ea=u(()=>{Kc()});function Bk(e){return oe(e)?e.allOf:N(e)?e.anyOf:qe(e)?e.items??[]:[]}function jc(e){return Bk(e)}var qc=u(()=>{D()});var $a=u(()=>{qc()});function Vc(e,t){return ut(e)?l(e.returns,t):F(t)}var Hc=u(()=>{P();Pe();D()});var Oa=u(()=>{Hc()});var Gc=u(()=>{});var zc=u(()=>{});var Qc=u(()=>{Gc();zc()});var Jc=u(()=>{});var Yc=u(()=>{Jc()});function Xc(e){return new _a(e)}var _a,Na,Zc=u(()=>{b();D();_a=class{constructor(t){this.schema=t}Decode(t){return new Na(this.schema,t)}},Na=class{constructor(t,r){this.schema=t,this.decode=r}EncodeTransform(t,r){let i={Encode:s=>r[le].Encode(t(s)),Decode:s=>this.decode(r[le].Decode(s))};return{...r,[le]:i}}EncodeSchema(t,r){let n={Decode:this.decode,Encode:t};return{...r,[le]:n}}Encode(t){return Ut(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}}});var Fa=u(()=>{Zc()});function el(e={}){return l({[w]:e[w]??"Unsafe"},e)}var tl=u(()=>{P();b()});var Da=u(()=>{tl()});function rl(e){return l({[w]:"Void",type:"void"},e)}var nl=u(()=>{P();b()});var La=u(()=>{nl()});var Ua={};Hn(Ua,{Any:()=>Kt,Argument:()=>Mu,Array:()=>xr,AsyncIterator:()=>Pr,Awaited:()=>Cr,BigInt:()=>Ar,Boolean:()=>no,Capitalize:()=>mc,Composite:()=>Pp,Const:()=>Ep,Constructor:()=>br,ConstructorParameters:()=>Op,Date:()=>lo,Enum:()=>Np,Exclude:()=>Nr,Extends:()=>_r,Extract:()=>Fr,Function:()=>yt,Index:()=>qt,InstanceType:()=>tc,Instantiate:()=>sc,Integer:()=>dc,Intersect:()=>Ae,Iterator:()=>Mr,KeyOf:()=>Er,Literal:()=>U,Lowercase:()=>gc,Mapped:()=>pp,Module:()=>Oc,Never:()=>F,Not:()=>Nc,Null:()=>fo,Number:()=>Ye,Object:()=>V,Omit:()=>zt,Optional:()=>Re,Parameters:()=>Dc,Partial:()=>Dr,Pick:()=>Qt,Promise:()=>uo,Readonly:()=>Ne,ReadonlyOptional:()=>To,Record:()=>Co,Recursive:()=>Uc,Ref:()=>xt,RegExp:()=>Bc,Required:()=>Lr,Rest:()=>jc,ReturnType:()=>Vc,String:()=>lt,Symbol:()=>ho,TemplateLiteral:()=>io,Transform:()=>Xc,Tuple:()=>Ze,Uint8Array:()=>wo,Uncapitalize:()=>Sc,Undefined:()=>ko,Union:()=>B,Unknown:()=>Ht,Unsafe:()=>el,Uppercase:()=>yc,Void:()=>rl});var ol=u(()=>{dn();ks();un();pn();co();gn();oo();js();Vs();cn();Hs();mo();Gs();ia();In();da();or();It();ua();ca();la();Xe();fa();hn();wn();Oe();Se();Aa();Pe();Ta();go();sr();He();_o();Ot();Ma();Do();Fo();po();dr();Mo();xn();Ca();ur();Ea();Lo();$a();Oa();Tr();So();Nt();Fa();Vt();Io();yo();me();$r();Da();La()});var g,il=u(()=>{ol();g=Ua});var nt=u(()=>{as();Tt();kt();gs();hu();sn();Iu();an();b();dn();un();ks();pn();co();gn();oo();js();Vs();cn();Hs();mo();Gs();ia();In();da();or();It();ua();ca();la();Xe();hn();fa();wn();Oe();Aa();Se();Pe();Ta();go();sr();He();_o();Ot();Ma();Do();Fo();po();dr();Mo();xn();Ca();ur();Ea();Lo();$a();Oa();Qc();Yc();Tr();So();Nt();Fa();Vt();Io();yo();me();$r();Da();La();il()});function Wa(e){k=e}var k,he=u(()=>{k=null});function Vk(e){if(!e)return;let t=e.match(/^agent:[^:]+:discord:(direct|dm|channel|group):/i);if(!t?.[1])return;let r=t[1].toLowerCase();return r==="direct"||r==="dm"?"user":"channel"}function Hk(e,t){if(!/^\d+$/.test(e))return e;let r=Vk(t);return r?`${r}:${e}`:`channel:${e}`}function Gk(e){if(!(!e?.provider||!e.target)&&!(e.provider==="system"||e.target==="system"))return e.accountId?`${e.provider}|${e.accountId}|${e.target}`:`${e.provider}|${e.target}`}function zk(e){let t=e?.trim();if(!t)return;let r=t.match(/^agent:[^:]+:([^:]+):([^:]+):([^:]+)(?::topic:([^:]+))?$/i);if(!r)return;let[,n,o,i,s]=r,a=n.toLowerCase(),d=o.toLowerCase(),c=a==="discord"?d==="direct"||d==="dm"?`user:${i}`:`channel:${i}`:i;return{provider:a,target:c,threadId:s,sessionKey:t}}function sl(e){let t=e?.match(/:topic:(\d+)$/);return t?parseInt(t[1],10):void 0}function Qk(e){return!!(e?.provider&&e.target&&e.provider!=="system"&&e.target!=="system")}function Ba(e,t,r){let n=zk(r),o=t!=null?String(t):void 0,i=e?.trim();if(!i||i==="unknown")return n?{...n,threadId:o??n.threadId}:{provider:"system",target:"system",sessionKey:r?.trim()||void 0};let s=i.split("|").map(y=>y.trim()).filter(Boolean);if(s.length<2)return n?{...n,threadId:o??n.threadId}:{provider:"system",target:"system",sessionKey:r?.trim()||void 0};let[a,d,c]=s,h=c??d,m=c?d:void 0;if(!a||!h)return;let S=a==="discord"?Hk(h,r):h;return{provider:a,accountId:m,target:S,threadId:o??(n?.provider===a?n.threadId:void 0),sessionKey:r?.trim()||void 0}}function Ur(e){return Ba(Gk(e.route)??e.originChannel,e.route?.threadId??e.originThreadId,e.route?.sessionKey??e.originSessionKey)??e.route}function al(e){let t=Ur(e);return Qk(t)?t:void 0}var vn=u(()=>{});import{readFileSync as Jk}from"fs";import{homedir as Yk}from"os";import{join as Xk}from"path";function ul(){if(Rn!==void 0)return Rn;try{let e=Jk(Xk(Yk(),".claude.json"),"utf-8");Rn=JSON.parse(e).mcpServers??{}}catch{Rn={}}return Rn}function pl(e){let t=e.defaultHarness??dl,r={};for(let[n,o]of Object.entries(Wo))r[n]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[n,o]of Object.entries(e.harnesses??{})){let i=r[n]??{},s={...i,defaultModel:o.defaultModel??i.defaultModel,reasoningEffort:o.reasoningEffort??i.reasoningEffort};o.allowedModels!==void 0?s.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(s.allowedModels=void 0),r[n]=s}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.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})}E={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",planApproval:e.planApproval??"ask",defaultHarness:t,harnesses:r,allowedModels:e.allowedModels,defaultWorktreeStrategy:e.defaultWorktreeStrategy??"off",worktreeDir:e.worktreeDir}}function De(){return E.defaultHarness??dl}function cl(e){let t=Wo[e],r=E.harnesses[e];return{...t,...r,allowedModels:r?.allowedModels??t?.allowedModels}}function Wr(e){return cl(e).defaultModel}function ll(e){return E.harnesses[e]?.allowedModels??E.allowedModels}function Jt(e){return cl(e).reasoningEffort}function ml(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=Mn(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function An(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}`:E.fallbackChannel??"unknown"}function Tn(e){return e?.messageThreadId??void 0}function Bo(e,t,r){return Ba(An(e,t),Tn(e),r??e?.sessionKey)}function Mn(e){let t=E.agentChannels;if(!t)return;let r=i=>i.replace(/\/+$/,""),n=r(e),o=Object.entries(t).sort((i,s)=>s[0].length-i[0].length);for(let[i,s]of o)if(n===r(i)||n.startsWith(r(i)+"/"))return s}function fl(e){return sl(e)}var Rn,dl,Wo,E,Le=u(()=>{vn();dl="claude-code",Wo={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium"}};E={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"ask",harnesses:{"claude-code":{...Wo["claude-code"]},codex:{...Wo.codex}}}});function jo(e){return{type:"backend_ref",ref:e}}function qo(e){return{type:"run_started",...e?{runId:e}:{}}}function Cn(e){return{type:"text_delta",text:e}}function gl(e,t){return{type:"tool_call",name:e,input:t}}function Vo(e){return{type:"pending_input",state:e}}function Kr(e){return e?{type:"pending_input_resolved",requestId:e}:{type:"pending_input_resolved"}}function Ho(e,t){return{type:"plan_artifact",artifact:e,finalized:t}}function Go(e){return e?{type:"settings_changed",permissionMode:e}:{type:"settings_changed"}}function lr(e){return{type:"run_completed",data:e}}var Br,Ka=u(()=>{Br=class{queue=[];resolvePending=null;done=!1;enqueue(t){this.queue.push(t),this.flush()}close(){this.done=!0,this.flush()}flush(){this.resolvePending&&(this.resolvePending(),this.resolvePending=null)}messages(){let t=this;return(async function*(){for(;;){for(;t.queue.length>0;)yield t.queue.shift();if(t.done)return;await new Promise(r=>{t.resolvePending=r})}})()}}});import{query as Zk}from"@anthropic-ai/claude-agent-sdk";import{dirname as hl,join as Sl}from"path";import{fileURLToPath as ey}from"url";import{createRequire as ty}from"module";function ry(e,t,r){let o=(Array.isArray(r.questions)?r.questions:[])[0]??{},i=typeof o.question=="string"?o.question:void 0,s=Array.isArray(o.options)?o.options.map(a=>{if(!a||typeof a!="object")return"";let d=a.label;return typeof d=="string"?d:""}).filter(Boolean):[];return{requestId:`${e||"claude"}-ask-${t}`,kind:"question",promptText:i,options:s,allowsFreeText:s.length===0||o.multiSelect===!0}}var zo,kl=u(()=>{Ka();zo=class{name="claude-code";backendKind="claude-code";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!1,nativePlanArtifacts:!1,worktrees:"plugin-managed"};launch(t){let r=new Br,n=!1,o="",i=!1,s=0,a=t.resumeSessionId??"",d=t.canUseTool,c={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,pathToClaudeCodeExecutable:(()=>{try{let S=ty(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return Sl(hl(S),"cli.js")}catch{let m=hl(ey(import.meta.url));return Sl(m,"..","node_modules","@anthropic-ai","claude-agent-sdk","cli.js")}})(),allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers,...d?{canUseTool:async(m,S)=>{if(m!=="AskUserQuestion")return{behavior:"allow"};let y=ry(a,++s,S);r.enqueue(Vo(y));try{let x=await d(m,S);return r.enqueue(Kr(y.requestId)),x}catch(x){throw r.enqueue(Kr(y.requestId)),x}}}:{}};t.resumeSessionId&&(c.resume=t.resumeSessionId,c.forkSession=t.forkSession??!1);let h=Zk({prompt:t.prompt,options:c});return(async()=>{try{for await(let m of h){let S=m;if(S.type==="system"&&S.subtype==="init"){a=S.session_id??a,r.enqueue(jo({kind:"claude-code",conversationId:a}));continue}if(S.type==="system"&&S.subtype==="status"&&S.permissionMode){r.enqueue(Go(S.permissionMode));continue}if(S.type==="assistant"){n||(n=!0,r.enqueue(qo()));for(let y of S.message?.content??[]){if(y.type==="text"){o+=o?`
2
+ ${y.text}`:y.text,r.enqueue(Cn(y.text));continue}y.type==="tool_use"&&((y.name==="ExitPlanMode"||y.name==="set_permission_mode")&&(i=!0),y.name!=="AskUserQuestion"&&r.enqueue(gl(y.name,y.input)))}continue}if(S.type==="result"){let y=o.trim();if(y&&(t.permissionMode==="plan"||i)){let x={explanation:void 0,steps:[],markdown:y};r.enqueue(Ho(x,!0))}r.enqueue(lr({success:S.subtype==="success",duration_ms:S.duration_ms??0,total_cost_usd:S.total_cost_usd??0,num_turns:S.num_turns??0,result:S.result,session_id:S.session_id??a})),o="",i=!1,n=!1}}}finally{r.close()}})().catch(m=>{r.enqueue(lr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,result:m instanceof Error?m.message:String(m),session_id:a})),r.close()}),{messages:r.messages(),async setPermissionMode(m){typeof h.setPermissionMode=="function"&&await h.setPermissionMode(m)},async streamInput(m){typeof h.streamInput=="function"&&await h.streamInput(m)},async interrupt(){typeof h.interrupt=="function"&&await h.interrupt()}}}buildUserMessage(t,r){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:r}}}});import{spawn as ny}from"node:child_process";import oy from"node:readline";function iy(e){return e instanceof Error?e.message:String(e)}function sy(e){try{let t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}async function ay(e,t){if(e.id!=null&&(Object.hasOwn(e,"result")||Object.hasOwn(e,"error"))){let n=String(e.id),o=t.pending.get(n);if(!o)return;if(clearTimeout(o.timer),t.pending.delete(n),e.error){o.reject(new Error(`codex app server rpc error (${e.error.code??"unknown"}): ${e.error.message??"unknown error"}`));return}o.resolve(e.result);return}let r=e.method?.trim();if(r){if(e.id==null){await t.onNotification(r,e.params);return}try{let n=await t.onRequest(r,e.params);t.respond({jsonrpc:"2.0",id:e.id,result:n??{}})}catch(n){t.respond({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:iy(n)}})}}}var Qo,yl=u(()=>{Qo=class{constructor(t,r,n){this.command=t;this.args=r;this.requestTimeoutMs=n}process=null;pending=new Map;counter=0;onNotification=()=>{};onRequest=async()=>({});setNotificationHandler(t){this.onNotification=t}setRequestHandler(t){this.onRequest=t}async connect(){if(this.process)return;let t=ny(this.command,["app-server",...this.args],{stdio:["pipe","pipe","pipe"],env:process.env});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("codex app server stdio pipes unavailable");this.process=t,oy.createInterface({input:t.stdout}).on("line",n=>{this.handleLine(n)}),t.stderr.on("data",()=>{}),t.on("close",()=>{this.flushPending(new Error("codex app server stdio closed")),this.process=null})}async close(){this.flushPending(new Error("codex app server stdio closed"));let t=this.process;this.process=null,t&&t.kill()}async notify(t,r){this.write({jsonrpc:"2.0",method:t,params:r??{}})}async request(t,r,n){let o=`rpc-${++this.counter}`,i=new Promise((s,a)=>{let d=setTimeout(()=>{this.pending.delete(o),a(new Error(`codex app server timeout: ${t}`))},Math.max(100,n??this.requestTimeoutMs));d.unref?.(),this.pending.set(o,{resolve:s,reject:a,timer:d})});return this.write({jsonrpc:"2.0",id:o,method:t,params:r??{}}),await i}write(t){if(!this.process?.stdin)throw new Error("codex app server stdio not connected");this.process.stdin.write(`${JSON.stringify(t)}
3
+ `)}async handleLine(t){let r=sy(t);r&&await ay(r,{pending:this.pending,onNotification:this.onNotification,onRequest:this.onRequest,respond:n=>this.write(n)})}flushPending(t){for(let[r,n]of this.pending)clearTimeout(n.timer),n.reject(t),this.pending.delete(r)}}});function J(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ae(e,t,r){for(let n of t){let o=e?.[n];if(typeof o!="string")continue;let i=r?.trim===!1?o:o.trim();if(i)return i}}function dy(e){return e instanceof Error?e.message:String(e)}function wl(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Yt(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(r=>Yt(r)).join("");let t=J(e);if(!t)return"";for(let r of["delta","text","content","message","input","output","parts"]){let n=Yt(t[r]);if(n)return n}for(let r of["item","turn","thread","response","result","data"]){let n=Yt(t[r]);if(n)return n}return""}function En(e){let t=J(e);if(!t)return{};let r=J(t.thread)??J(t.session),n=J(t.turn)??J(t.run),o=J(t.item),i=J(t.serverRequest);return{threadId:ae(t,["threadId","thread_id","conversationId","conversation_id"])??ae(r,["id","threadId","thread_id","conversationId"]),runId:ae(t,["turnId","turn_id","runId","run_id"])??ae(n,["id","turnId","turn_id","runId","run_id"]),requestId:ae(t,["requestId","request_id","serverRequestId"])??ae(i,["id","requestId","request_id"]),itemId:ae(t,["itemId","item_id"])??ae(o,["id","itemId","item_id"])}}function Jo(e,t,r=0){if(r>6)return;if(Array.isArray(e)){for(let i of e){let s=Jo(i,t,r+1);if(s)return s}return}let n=J(e);if(!n)return;let o=ae(n,t);if(o)return o;for(let i of Object.values(n)){let s=Jo(i,t,r+1);if(s)return s}}function $n(e){return{threadId:En(e).threadId,cwd:Jo(e,["cwd","workdir","directory"])}}function Il(e){let t=e?.trim();return!!(t&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(t))}function xl(e){let t=e?.trim();if(!t)return;let r=t.split(/[/\\]+/).filter(Boolean),n=r.lastIndexOf("worktrees");if(!(n<0||n+1>=r.length))return r[n+1]}function Yo(e){let t=J(e);if(!t)return;let r=J(t.item)??t;return ae(r,["id","itemId","item_id","messageId","message_id"])}function uy(e,t=!1){let r=J(e);if(!r)return"";let n=J(r.item)??r;return ae(n,["type"])?.toLowerCase()!=="agentmessage"?"":t?Yt(n):ae(n,["text"],{trim:!1})??Yt(n)}function Pl(e,t){let r=e.trim().toLowerCase();return r==="item/agentmessage/delta"?{mode:"delta",text:Yt(t),itemId:Yo(t)}:r==="item/completed"?{mode:"snapshot",text:uy(t),itemId:Yo(t)}:{mode:"ignore",text:""}}function bl(e){return{itemId:Yo(e),delta:Yt(e)}}function vl(e){let t=J(e),r=J(t?.plan),o=(Array.isArray(t?.plan)?t.plan:Array.isArray(r?.steps)?r.steps:[]).map(i=>{let s=J(i),a=ae(s,["step","title","text"]);if(!a)return null;let d=ae(s,["status"])?.toLowerCase()??"pending";return{step:a,status:d==="inprogress"||d==="in_progress"?"inProgress":d==="completed"?"completed":"pending"}}).filter(Boolean);return{explanation:ae(r,["explanation"])??ae(t,["explanation"]),steps:o}}function Rl(e){let t=J(e);if(!t)return{};let r=J(t.item)??t;return ae(r,["type"])?.toLowerCase()!=="plan"?{}:{itemId:Yo(r),text:ae(r,["text"],{trim:!1})??Yt(r)}}function Al(e,t){let r=e.trim().toLowerCase();if(r==="turn/failed"||r==="turn/cancelled")return!1;let n=J(t)??{},o=J(n.turn)??n,i=ae(o,["status"])?.toLowerCase();return i!=="failed"&&i!=="interrupted"&&i!=="cancelled"}function Tl(e,t){let r=J(t)??{},n=J(r.turn)??r,o=J(n.error)??J(r.error);if(o)return ae(o,["message","text","summary","reason"])}function py(e,t){let r=dy(e).toLowerCase();return r.includes("method not found")||r.includes("unknown method")?!0:r.includes("unknown variant")?t?r.includes(`unknown variant \`${t.toLowerCase()}\``):!0:!1}function ly(e){return cy.has(e.trim().toLowerCase())}function my(e){let t=J(e);return t?!!ae(t,["threadId","thread_id"]):!1}async function On(e){if(e.payloads.length===0)throw new Error(`codex app server request skipped: no payloads for ${e.methods.join(", ")||"<none>"}`);let t;for(let r of e.methods)for(let n of e.payloads){if(ly(r)&&!my(n))throw new Error(`codex app server request missing threadId: ${r}`);try{return await e.client.request(r,n,e.timeoutMs)}catch(o){if(t=o,!py(o,r))continue}}throw t instanceof Error?t:new Error(String(t))}function Ml(e){let t={cwd:e.cwd};e.model?.trim()&&(t.model=e.model.trim()),e.approvalPolicy?.trim()&&(t.approvalPolicy=e.approvalPolicy.trim()),e.sandbox?.trim()&&(t.sandbox=e.sandbox.trim());let r={cwd:e.cwd};return e.approvalPolicy?.trim()&&(r.approvalPolicy=e.approvalPolicy.trim()),e.sandbox?.trim()&&(r.sandbox=e.sandbox.trim()),[t,r,{}]}function Cl(e){let t={threadId:e.threadId,persistExtendedHistory:!1};return e.model?.trim()&&(t.model=e.model.trim()),e.reasoningEffort?.trim()&&(t.reasoningEffort=e.reasoningEffort.trim()),e.cwd?.trim()&&(t.cwd=e.cwd.trim()),e.approvalPolicy?.trim()&&(t.approvalPolicy=e.approvalPolicy.trim()),e.sandbox?.trim()&&(t.sandbox=e.sandbox.trim()),[t]}function fy(e){return[{type:"text",text:e}]}function gy(e,t,r){let n=t?.trim();if(e!=="plan")return n?{mode:"default",settings:{model:n,...r?.trim()?{reasoningEffort:r.trim()}:{},developerInstructions:null}}:void 0;if(n)return{mode:"plan",settings:{model:n,...r?.trim()?{reasoningEffort:r.trim()}:{},developerInstructions:null}}}function El(e){let t={threadId:e.threadId,input:fy(e.prompt)};e.model?.trim()&&(t.model=e.model.trim()),e.approvalPolicy?.trim()&&(t.approvalPolicy=e.approvalPolicy.trim()),e.sandbox?.trim()&&(t.sandbox=e.sandbox.trim());let r=gy(e.permissionMode??"default",e.model,e.reasoningEffort);return r?[{...t,collaborationMode:r},{...t,collaboration_mode:{mode:r.mode,settings:{model:r.settings.model,...typeof r.settings.reasoningEffort=="string"?{reasoning_effort:r.settings.reasoningEffort}:{},developer_instructions:null}}},t]:[t]}function $l(e){return[{threadId:e.threadId,turnId:e.turnId}]}function hy(e){let t=J(e);if(!t)return[];let r=t.options??t.choices??t.availableDecisions??t.decisions;return Array.isArray(r)?r.map(n=>typeof n=="string"?n.trim():ae(J(n),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function Sy(e){let t=e.trim().toLowerCase();return t.includes("session")?"acceptForSession":/cancel|abort|stop/.test(t)?"cancel":/deny|decline|reject|block|no/.test(t)?"decline":/approve|allow|accept|yes/.test(t)?"accept":e.trim()}function Ol(e,t,r){let n=e.trim().toLowerCase(),o=hy(r),i=Jo(r,["question","prompt","message","text","summary","reason"])??void 0,s=n.includes("requestapproval"),a=s?o.map(d=>({kind:"approval",label:d,decision:Sy(d),responseDecision:d})):o.map(d=>({kind:"option",label:d,value:d}));return{requestId:t,kind:s?"approval":"question",promptText:i,options:o,actions:a,allowsFreeText:!0}}function _l(e){let t=e.trim().toLowerCase();return t.includes("requestuserinput")||t.includes("requestapproval")}function ja(e,t){let r=e==="bypassPermissions"?"never":t?.trim()||"never";return{approvalPolicy:r,sandbox:r==="never"?"danger-full-access":void 0}}var cy,Nl=u(()=>{cy=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function Fl(e){return e instanceof Error?e.message:String(e)}function xy(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)}var ky,mr,yy,wy,Iy,Xo,Dl=u(()=>{yl();Ka();Nl();ky="1.0",mr=6e4,yy="OPENCLAW_CODEX_APP_SERVER_COMMAND",wy="OPENCLAW_CODEX_APP_SERVER_ARGS",Iy="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";Xo=class{constructor(t={}){this.deps=t}name="codex";backendKind="codex-app-server";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!0,nativePlanArtifacts:!0,worktrees:"native-restore"};launch(t){let r={command:process.env[yy]?.trim()||"codex",args:wl(process.env[wy]),requestTimeoutMs:Number.parseInt(process.env[Iy]??String(mr),10)||mr},n=this.deps.createClient?.(r)??new Qo(r.command,r.args,r.requestTimeoutMs),o=new Br,i=t.resumeSessionId,s,a=t.backendRef?.worktreePath,d=t.backendRef?.worktreeId,c=t.permissionMode??"default",h,m=0,S="",y=[],x,$=new Map,re=new Set,R=C=>{let A=C?.trim();if(!A)return;let _=t.originalWorkdir?.trim()||t.cwd.trim();t.worktreeStrategy&&t.worktreeStrategy!=="off"&&A!==_&&Il(A)&&(a=A,d=xl(A))},W=()=>{i&&o.enqueue(jo({kind:"codex-app-server",conversationId:i,...s?{runId:s}:{},...d?{worktreeId:d}:{},...a?{worktreePath:a}:{}}))};n.setNotificationHandler(async(C,A)=>{let _=C.trim().toLowerCase(),G=En(A),ye=$n(A);if(G.threadId&&i&&G.threadId!==i)return;if(G.threadId&&(i=G.threadId),G.runId&&(s=G.runId),R(ye.cwd),(G.threadId||G.runId||ye.cwd)&&W(),_==="serverrequest/resolved"){h&&(o.enqueue(Kr(h.requestId)),h=void 0);return}if(_==="turn/plan/updated"){let be=vl(A);S=be.explanation??S,be.steps.length>0&&(y=be.steps);return}if(_==="item/plan/delta"){let be=bl(A);if(be.itemId&&be.delta){let Dt=$.get(be.itemId)??"";$.set(be.itemId,`${Dt}${be.delta}`)}return}if(_==="item/completed"){let be=Rl(A);if(be.text?.trim()){let Dt={explanation:S||void 0,steps:y,markdown:be.text.trim()};o.enqueue(Ho(Dt,!0));return}}let ne=Pl(_,A);if(ne.mode==="delta"&&ne.text){ne.itemId&&re.add(ne.itemId),o.enqueue(Cn(ne.text));return}ne.mode==="snapshot"&&ne.text&&(!ne.itemId||!re.has(ne.itemId))&&o.enqueue(Cn(ne.text)),(_==="turn/completed"||_==="turn/failed"||_==="turn/cancelled")&&x&&(x.method=C,x.params=A,x.resolve())}),n.setRequestHandler(async(C,A)=>{if(!_l(C))return{};let _=En(A),G=$n(A);if(_.threadId&&i&&_.threadId!==i)return{};_.threadId&&(i=_.threadId),_.runId&&(s=_.runId),R(G.cwd),(_.threadId||_.runId||G.cwd)&&W();let ye=_.requestId??`${i??"codex"}-${Date.now().toString(36)}`,ne=Ol(C,ye,A),be=C.trim().toLowerCase(),Dt=ne.options,sf=ne.actions??[],af=await new Promise(df=>{h={requestId:ye,methodLower:be,state:ne,options:Dt,actions:sf,resolveResponse:df},o.enqueue(Vo(ne))});return h=void 0,o.enqueue(Kr(ye)),af});let I=async()=>{await n.connect(),await n.request("initialize",{protocolVersion:ky,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},mr),await n.notify("initialized",{})},v=async()=>{let C=ja(c,t.codexApprovalPolicy);if(i){let G=await On({client:n,methods:["thread/resume"],payloads:Cl({threadId:i,model:t.model,reasoningEffort:t.reasoningEffort,approvalPolicy:C.approvalPolicy,sandbox:C.sandbox}),timeoutMs:mr}),ye=$n(G);i=ye.threadId??i,R(ye.cwd),W();return}let A=await On({client:n,methods:["thread/start","thread/new"],payloads:Ml({cwd:t.originalWorkdir?.trim()||t.cwd,model:t.model,approvalPolicy:C.approvalPolicy,sandbox:C.sandbox}),timeoutMs:mr}),_=$n(A);if(i=_.threadId,!i)throw new Error("Codex App Server did not return a thread id.");R(_.cwd),W()},de=async C=>{await v(),o.enqueue(qo()),m+=1,S="",y=[],$.clear(),re.clear();let A="",_,G,ye=new Promise(ne=>{G=ne});x={resolve:G};try{let ne=ja(c,t.codexApprovalPolicy),be=await On({client:n,methods:["turn/start"],payloads:El({threadId:i,prompt:C,model:t.model,reasoningEffort:t.reasoningEffort,permissionMode:c,approvalPolicy:ne.approvalPolicy,sandbox:ne.sandbox}),timeoutMs:mr}),Dt=En(be);Dt.runId&&(s=Dt.runId,W()),await ye,A=x?.method??"turn/failed",_=x?.params,o.enqueue(lr({success:Al(A,_),duration_ms:0,total_cost_usd:0,num_turns:m,result:Tl(A,_),session_id:i}))}catch(ne){o.enqueue(lr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:Fl(ne),session_id:i??""}))}finally{x=void 0}},yr=async C=>h?(h.methodLower.includes("requestapproval")?h.resolveResponse({decision:C.trim()||"decline"}):h.resolveResponse({text:C.trim()}),!0):!1,qn=async C=>{let A=h;if(!A)return!1;let _=A.actions[C];if(_?.kind==="approval")return A.resolveResponse({decision:_.responseDecision,..._.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:_.proposedExecpolicyAmendment}:{}}),!0;let G=A.options[C];return G?(A.methodLower.includes("requestapproval")?A.resolveResponse({decision:G}):A.resolveResponse({option:G,index:C}),!0):!1},Vn=typeof t.prompt=="string"?(async function*(){yield{type:"user",text:t.prompt,session_id:t.resumeSessionId??""}})():t.prompt;return(async()=>{try{await I();for await(let C of Vn){let A=xy(C).trim();!A||await yr(A)||await de(A)}}catch(C){o.enqueue(lr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:Fl(C),session_id:i??t.resumeSessionId??""}))}finally{await n.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(C){c=C,o.enqueue(Go(C))},async submitPendingInputOption(C){return qn(C)},async interrupt(){!i||!s||await On({client:n,methods:["turn/interrupt"],payloads:$l({threadId:i,turnId:s}),timeoutMs:mr}).catch(()=>{})}}}buildUserMessage(t,r){return{type:"user",text:t,session_id:r}}}});function Ll(e){qa.set(e.name,e)}function _n(e){let t=qa.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...qa.keys()].join(", ")}`);return t}function Ul(){return _n(De())}var qa,Va=u(()=>{kl();Dl();Le();qa=new Map;Ll(new zo);Ll(new Xo)});function T(e){return e.backendRef?.conversationId??e.harnessSessionId}function ee(e){return e.id??e.sessionId??e.name??T(e)??e.harnessSessionId}function Py(e){return e.harnessSessionId}function ze(e){let t=[ee(e),T(e),Py(e)].filter(r=>!!r);return[...new Set(t)]}function Ha(e){return e.harnessName??e.persistedHarness??De()}function Zo(e){if(e.backendRef?.kind==="codex-app-server")return"native-restore";try{return _n(Ha(e)).capabilities.worktrees}catch{return"plugin-managed"}}function Ga(e){return e==="native-execution"||e==="native-restore"}function Wl(e){return e==="native-restore"}function by(e){return!!(e.backendRef?.worktreePath||e.backendRef?.worktreeId)}function ot(e){return Ga(Zo(e))&&by(e)}var ke=u(()=>{Le();Va()});import{execFileSync as Ue}from"child_process";import{statfsSync as By}from"fs";import{tmpdir as Ky}from"os";import{dirname as jy,join as qy}from"path";function Vy(e){try{return Ue("git",["rev-parse","--show-toplevel"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function Ja(e){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(E.worktreeDir)return E.worktreeDir;if(e){let t=Vy(e);if(t)return qy(t,".worktrees")}return Ky()}function rm(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function si(e){try{let t=Ue("git",["-C",e,"rev-parse","--git-common-dir"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return t&&t.endsWith("/.git")?jy(t):void 0}catch{return}}function Hy(){if(oi!==void 0)return oi;try{return Ue("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),oi=!0,!0}catch{return oi=!1,!1}}function Pt(){if(ii!==void 0)return ii;try{return Ue("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ii=!0,!0}catch{return ii=!1,!1}}function Ya(e){if(!Hy())return!1;try{return Ue("git",["rev-parse","--git-dir"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function nm(){try{let e=Ja(),t=By(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 om(e,t){try{return Ue("git",["-C",e,"rev-parse","--verify",t],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function gt(e){let t=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(t)return t;try{let n=Ue("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 Ue("git",["-C",e,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return Ue("git",["-C",e,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function ai(e){try{let r=Ue("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 Dn(e,t,r){try{let n=Ue("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 bt(e,t){try{return Ue("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 im(e,t){if(t)return t;try{let r=Ue("git",["-C",e,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),n=Ue("git",["-C",e,"remote","get-url","upstream"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n&&n!==r){let o=n.match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/);if(o)return o[1]}}catch{}}var oi,ii,di=u(()=>{Le()});import{execFileSync as Ln}from"child_process";import{existsSync as Gy,mkdirSync as sm,rmSync as am}from"fs";function Xa(e,t){let r=rm(t),n=Ja(e);sm(n,{recursive:!0});let o,i,s=10;for(let d=0;d<s;d++){let c=d===0?"":`-${Math.random().toString(16).slice(2,6)}`,h=`${n}/openclaw-worktree-${r}${c}`,m=`agent/${r}${c}`;try{sm(h,{recursive:!1}),o=h,i=m;break}catch(S){if(S&&typeof S=="object"&&"code"in S&&S.code==="EEXIST")continue;throw S}}if(!o||!i)throw new Error(`Failed to create unique worktree directory after ${s} attempts`);let a=om(e,i);try{a?Ln("git",["-C",e,"worktree","add",o,i],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):Ln("git",["-C",e,"worktree","add","-b",i,o],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(d){try{am(o,{recursive:!0,force:!0})}catch{}throw d}return o}function zy(e){if(!Gy(e))return[];try{let t=Ln("git",["-C",e,"status","--porcelain","--untracked-files=all"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return t?t.split(`
4
+ `).map(r=>r.trim()).filter(Boolean):[]}catch{return[]}}function ht(e,t,r={}){let n=r.destructive===!0,o=zy(t);if(o.length>0&&!n)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${t}: ${o[0]}`),!1;try{return Ln("git",["-C",e,"worktree","remove",...n?["--force"]:[],t],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(i){if(console.warn(`[worktree] git worktree remove failed for ${t}: ${i instanceof Error?i.message:String(i)}`),!n)return!1;try{return am(t,{recursive:!0,force:!0}),console.info(`[worktree] Fallback rmSync succeeded for ${t}`),!0}catch(s){return console.error(`[worktree] Both git worktree remove and rmSync failed for ${t}: ${s instanceof Error?s.message:String(s)}`),!1}}}function ui(e){try{Ln("git",["-C",e,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var dm=u(()=>{di()});import{execFileSync as te}from"child_process";import{existsSync as Qy}from"fs";function Ft(e,t,r){try{let n=te("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(n.trim(),10),s=te("git",["-C",e,"diff","--shortstat",`${r}...${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,c=0,h=s.match(/(\d+)\s+files?\s+changed/);h&&(a=parseInt(h[1],10));let m=s.match(/(\d+)\s+insertions?\(/);m&&(d=parseInt(m[1],10));let S=s.match(/(\d+)\s+deletions?\(/);S&&(c=parseInt(S[1],10));let x=te("git",["-C",e,"diff","--name-only","--diff-filter=ACMR",`${r}...${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
5
+ `).map(R=>R.trim()).filter(Boolean),re=te("git",["-C",e,"log",`${r}..${t}`,"--format=%h|%s|%an","-n","5"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
6
+ `).filter(Boolean).map(R=>{let[W,I,v]=R.split("|");return{hash:W||"",message:I||"",author:v||""}});return{commits:o,filesChanged:a,insertions:d,deletions:c,changedFiles:x,commitMessages:re}}catch(n){console.warn(`[worktree] Failed to get diff summary: ${n instanceof Error?n.message:String(n)}`);return}}function ci(e,t,r="origin"){try{return te("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 pi(e){try{return te("git",["-C",e,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
7
+ `).some(r=>r.length>0&&!r.startsWith("??")&&!r.startsWith("!!"))}catch{return!1}}function li(e,t,r,n="merge",o){let i=!1,s,a=d=>{if(i)try{te("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(n==="squash"){if(te("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),pi(e)){let S;try{S=te("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(!S.includes("No local changes to save")){i=!0;try{s=te("git",["-C",e,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}te("git",["-C",e,"merge","--squash",t],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),te("git",["-C",e,"commit","-m",`Squash merge ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let m=!1;if(i)try{te("git",["-C",e,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{m=!0}return{success:!0,stashed:i||void 0,stashRef:s,stashPopConflict:m||void 0}}let d=o&&Qy(o),c=d?o:e;if(d||te("git",["-C",e,"checkout",t],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),pi(e)){let m;try{m=te("git",["-C",e,"stash","push","-m",`pre-merge stash before ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(S){try{te("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${S instanceof Error?S.message:String(S)}. Commit or stash changes manually, then retry.`}}if(!m.includes("No local changes to save")){i=!0;try{s=te("git",["-C",e,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{te("git",["-C",c,"rebase",r],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{te("git",["-C",c,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{te("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(e),{success:!1,rebaseConflict:!0,stashed:i||void 0,stashRef:s,error:[`Rebase of ${t} onto ${r} hit conflicts.`,"To resolve manually:",` cd ${c}`,` 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(`
8
+ `)}}te("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),te("git",["-C",e,"merge","--ff-only",t],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let h=!1;if(i)try{te("git",["-C",e,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{h=!0}return{success:!0,fastForward:!0,stashed:i||void 0,stashRef:s,stashPopConflict:h||void 0}}catch(d){try{te("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:i||void 0,stashRef:s}}}var um=u(()=>{});import{execFileSync as mi}from"child_process";function pm(e,t,r,n,o,i){if(!Pt())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s;if(i)try{let m=mi("git",["-C",e,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[:/]([^/]+)\/[^/]+(?:\.git)?$/);m&&(s=m[1])}catch{}let a=["pr","create","--base",r];return i&&a.push("--repo",i),s?a.push("--head",`${s}:${t}`):a.push("--head",t),n&&o?a.push("--title",n,"--body",o):a.push("--fill-verbose"),{success:!0,prUrl:mi("gh",a,{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 Za(e,t,r){if(!Pt())return{exists:!1,state:"none"};try{let n=["pr","list","--head",t,"--state","all","--json","url,number,title,state","--jq",".[0]"];r&&n.push("--repo",r);let i=mi("gh",n,{cwd:e,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!i)return{exists:!1,state:"none"};let s=JSON.parse(i),a=s.state.toLowerCase();return{exists:!0,state:a==="open"?"open":a==="merged"?"merged":a==="closed"?"closed":"none",url:s.url,number:s.number,title:s.title}}catch(n){return console.warn(`[worktree] Failed to sync PR status for ${t}: ${n instanceof Error?n.message:String(n)}`),{exists:!1,state:"none"}}}function cm(e,t,r,n){if(!Pt())return!1;try{let o=["pr","comment",String(t),"--body",r];return n&&o.push("--repo",n),mi("gh",o,{cwd:e,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(o){return console.warn(`[worktree] Failed to comment on PR #${t}: ${o instanceof Error?o.message:String(o)}`),!1}}function gr(e){if(e.kind==="merge"){let t=e.filesChanged!==void 0?` (${e.filesChanged} files, +${e.insertions??0}/-${e.deletions??0})`:"";return`\u2705 Merged: ${e.branch} \u2192 ${e.base??"main"}${t}`}return e.kind==="pr-updated"?`\u2705 PR updated: ${e.prUrl??""}`:e.targetRepo?`\u2705 PR opened against ${e.targetRepo}: ${e.prUrl??""}`:`\u2705 PR opened: ${e.prUrl??""}`}var lm=u(()=>{di()});var Qe=u(()=>{di();dm();um();lm()});function Vr(e,t){let r=e.resolve(t),n=e.getPersistedSession(t),o=r?ee(r):n?ee(n):void 0;return{activeSession:r,persistedSession:n,persistedRef:o,sessionName:r?.name??n?.name??t,worktreePath:r?.worktreePath??n?.worktreePath,originalWorkdir:r?.originalWorkdir??n?.workdir,branchName:r?.worktreeBranch??n?.worktreeBranch,notificationTarget:r??(n?{id:o??t,harnessSessionId:n.harnessSessionId,backendRef:n.backendRef,route:n.route}:void 0)}}function Ii(e){return e.persistedSession?ze(e.persistedSession):[]}function Tm(e){let t=e.list("all").filter(o=>o.worktreePath),r=e.listPersistedSessions().filter(o=>o.worktreePath),n=new Map;for(let o of r){if(!o.worktreePath)continue;let i=T(o),s=o.sessionId??i??o.harnessSessionId;s&&n.set(s,{id:o.sessionId??i??o.harnessSessionId,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.workdir,worktreeMerged:o.worktreeMerged,worktreeMergedAt:o.worktreeMergedAt,worktreePrUrl:o.worktreePrUrl,backendConversationId:i,harnessSessionId:o.harnessSessionId})}for(let o of t)o.worktreePath&&n.set(o.id,{id:o.id,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.originalWorkdir??o.workdir,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0,backendConversationId:T(o),harnessSessionId:o.harnessSessionId});return Array.from(n.values())}function nd(e,t){return e.id===t||e.name===t||e.backendConversationId===t||e.harnessSessionId===t}var Wn=u(()=>{ke()});var Mm={};Hn(Mm,{makeAgentPrTool:()=>Bn});import{existsSync as xw}from"fs";function Pw(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function Bn(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)"})),target_repo:g.Optional(g.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex'). Auto-detected from 'upstream' remote if not set."}))}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}],meta:{success:!1,state:"error"}};if(!Pw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!Pt())return{content:[{type:"text",text:"Error: GitHub CLI (gh) is not available. Install it and authenticate to create PRs."}],meta:{success:!1,state:"error"}};let n=Vr(k,r.session),o=n.activeSession,i=n.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}],meta:{success:!1,state:"error"}};let{worktreePath:s,originalWorkdir:a,sessionName:d,branchName:c}=n;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}],meta:{success:!1,state:"error"}};if(!c)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.`}],meta:{success:!1,state:"error"}};xw(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${c}" via originalWorkdir (${a})`);let h=r.base_branch??gt(a),m=n.persistedRef,S=im(a,r.target_repo??i?.worktreePrTargetRepo);if(!ci(a,c))return{content:[{type:"text",text:`\u274C Failed to push ${c} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let y=Za(a,c,S);if(r.force_new&&y.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${c} (${y.state}).
9
+
10
+ Existing PR: ${y.url}
11
+
12
+ To create a new PR, you must first close/merge the existing PR manually or use a different branch.`}],meta:{success:!1,state:"error"}};if(y.exists&&y.state==="open"){let x=Ft(a,c,h);if(x&&x.commits>0){let $=x.commitMessages.slice(0,5).map(I=>`\u2022 ${I.hash} ${I.message} (${I.author})`).join(`
13
+ `),re=x.commits>5?`
14
+ ...and ${x.commits-5} more commits`:"",R=["\u{1F504} **New commits pushed**","",`${x.commits} new commits (+${x.insertions} / -${x.deletions})`,"","### Latest commits:",$+re,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
15
+ `);if(cm(a,y.number,R,S)){m&&k.updatePersistedSession(m,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0});let I=gr({kind:"pr-updated",branch:c,prUrl:y.url});return k.notifyWorktreeOutcome(n.notificationTarget,I),{content:[{type:"text",text:`${I}
16
+
17
+ \u{1F4DD} Added comment detailing ${x.commits} new commits (+${x.insertions} / -${x.deletions})`}],meta:{success:!0,state:"pr_updated"}}}else return{content:[{type:"text",text:`\u26A0\uFE0F Pushed to ${y.url} but failed to add comment.
18
+
19
+ ${x.commits} new commits (+${x.insertions} / -${x.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return m&&k.updatePersistedSession(m,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${y.url}
20
+
21
+ No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else{if(y.exists&&y.state==="merged")return m&&k.updatePersistedSession(m,{worktreePrUrl:y.url,worktreePrNumber:y.number,worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDisposition:"merged"}),{content:[{type:"text",text:`\u2705 PR was already merged: ${y.url}
22
+
23
+ The worktree branch ${c} can be cleaned up with agent_merge(delete_branch=true).`}],meta:{success:!0,state:"merged"}};if(y.exists&&y.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${y.url}
24
+
25
+ What would you like to do?
26
+
27
+ 1. Reopen the closed PR manually on GitHub, then call agent_pr() again to update it
28
+ 2. Close and delete the branch with agent_merge(delete_branch=true), then start a new session/worktree
29
+ 3. Manually delete the closed PR on GitHub, then call agent_pr(force_new=true) to create a fresh PR
30
+
31
+ (This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let x=r.title??`[openclaw-code-agent] ${d}`,$=r.body;if(!$){let R=Ft(a,c,h);if(R){let W=R.commitMessages.slice(0,5).map(v=>`\u2022 ${v.hash} ${v.message} (${v.author})`).join(`
32
+ `),I=R.commits>5?`
33
+ ...and ${R.commits-5} more`:"";$=[`Automated changes from OpenClaw Code Agent session: ${d}`,"","## Summary",`${R.commits} commits, ${R.filesChanged} files changed (+${R.insertions} / -${R.deletions})`,"","## Commits",W+I,"","---","\u{1F916} Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
34
+ `)}else $=`Automated changes from OpenClaw Code Agent session: ${d}`}let re=pm(a,c,h,x,$,S);if(re.success&&re.prUrl){let R=Za(a,c,S);m&&k.updatePersistedSession(m,{worktreePrUrl:re.prUrl,worktreePrNumber:R.number,lifecycle:"terminal",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeState:"pr_open",worktreeDisposition:"pr-opened"});let W=gr({kind:"pr-opened",branch:c,targetRepo:S,prUrl:re.prUrl});return k.notifyWorktreeOutcome(n.notificationTarget,W),{content:[{type:"text",text:W}],meta:{success:!0,state:"created"}}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${re.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var Pi=u(()=>{nt();he();Qe();Wn()});import{readdirSync as $I,statSync as OI,rmSync as _I}from"fs";import{execFileSync as NI}from"child_process";import{join as of}from"path";nt();he();function Kk(e){return e.length>80?`${e.slice(0,80)}...`:e}function jk(e){return e.worktreePath?!e.originalWorkdir||e.originalWorkdir===e.worktreePath?`${e.worktreePath} (worktree)`:`${e.worktreePath} (worktree of ${e.originalWorkdir})`:e.workdir}function qk(e){let t=["Session launched successfully.",` Name: ${e.sessionName}`,` ID: ${e.sessionId}`,` Harness: ${e.harness}`,` Permission mode: ${e.permissionMode}`,` Plan approval: ${e.planApproval}`,` Worktree strategy: ${e.worktreeStrategy??"off"}`,` Resolved workdir: ${jk(e)}`,` Model: ${e.model??"default"}`,` Prompt: "${Kk(e.prompt)}"`];return e.reasoningEffort&&t.push(` Reasoning effort: ${e.reasoningEffort}`),e.resumeSessionId?t.push(` Resume: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`):e.forceNewSession&&t.push(" Force new session: true"),e.clearedPersistedCodexResume&&t.push(" Thread state: historical Codex state cleared; starting a fresh thread."),t.push(" Mode: multi-turn (use agent_respond to send follow-up messages)"),t.push("","Use agent_sessions to check status, agent_output to see output."),t.join(`
35
+ `)}function Uo(e,t){return qk({...e,sessionId:t.id,sessionName:t.name,model:t.model,reasoningEffort:t.reasoningEffort,worktreeStrategy:t.worktreeStrategy??"off",worktreePath:t.worktreePath,originalWorkdir:t.originalWorkdir})}Le();function Ko(e){let{requestedResumeSessionId:t,activeSession:r,persistedSession:n}=e;return t?r?{resumeSessionId:t,clearedPersistedCodexResume:!1}:n?.harness==="codex"&&n.backendRef?.kind!=="codex-app-server"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:t,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}ke();function za(e){return"id"in e?e.id:e.sessionId}function Nn(e){return e.status==="completed"||e.killReason==="done"}function vy(e){return Nn(e)&&e.backendRef?.kind==="codex-app-server"&&!!T(e)}function Ry(e){return(e.killReason==="shutdown"||e.killReason==="startup-timeout")&&!T(e)}function Fn(e){if(e.status==="running")return{kind:"direct",reason:"already_running"};let t=za(e);if(Nn(e)&&!vy(e))return{kind:"unavailable",reason:"completed",stableSessionId:t};let r=T(e);if(r){let n="harnessName"in e?void 0:e,{resumeSessionId:o,clearedPersistedCodexResume:i}=Ko({requestedResumeSessionId:r,activeSession:"harnessName"in e?{harnessSessionId:r}:void 0,persistedSession:n?{harness:n.harness,backendRef:n.backendRef}:void 0});return o?{kind:"resume",resumeSessionId:o,stableSessionId:t,clearedPersistedCodexResume:i}:{kind:"unavailable",reason:"legacy_non_resumable",stableSessionId:t,clearedPersistedCodexResume:i}}return Ry(e)?{kind:"relaunch",stableSessionId:t}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:t}}Le();import{existsSync as ql}from"fs";ke();function Bl(e){return e==null?void 0:String(e).trim()||void 0}function Ay(e){return e.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function Ty(e){let t=e.split(/\n\s*\n/,1)[0]?.split(`
36
+ `).map(r=>r.trim()).filter(Boolean)??[];if(t.length!==0)for(let r of t){let n=r.match(/^(Workdir|Repo):\s*(.+)$/),o=Ay(n?.[2]??"");if(o.startsWith("/")&&ql(o))return o}}function Kl(e,t){return e.workdir!==t.workdir?!1:t.originSessionKey&&e.originSessionKey?e.originSessionKey===t.originSessionKey:!t.originChannel||!e.originChannel?!1:e.originChannel===t.originChannel&&Bl(e.originThreadId)===Bl(t.originThreadId)}function jl(e){return e.slice(0,3).map(t=>` - ${t.name} [${t.ref}] | status=${t.status}${t.lifecycle?` | lifecycle=${t.lifecycle}`:""}`).join(`
37
+ `)}function My(e,t){let r=[],n=[],o=new Set;for(let i of e.list?.("all")??[]){if(!Kl(i,t))continue;let s=i.id;if(!o.has(s)){if(o.add(s),i.isExplicitlyResumable){r.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0});continue}(i.status==="starting"||i.status==="running")&&n.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!1})}}for(let i of e.listPersistedSessions?.()??[]){if(!i.resumable||!Kl(i,t))continue;let s=ee(i)??i.harnessSessionId,a=i.sessionId??T(i)??i.harnessSessionId;!s||!a||o.has(a)||(o.add(a),r.push({ref:s,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0}))}return{resumable:r,active:n}}function Cy(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 Vl(e,t,r){let n=e.workdir||Ty(e.prompt)||t.workspaceDir||E.defaultWorkdir||process.cwd();if(!ql(n))return{kind:"error",text:`Error: Working directory does not exist: ${n}`};let o=e.harness??De(),i=Wr(o),s=e.model??i,a=e.model!==void 0;if(!s)return{kind:"error",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=ll(o);if(d&&d.length>0&&!Cy(s,d))return{kind:"error",text:a?`Error: Model "${s}" is not allowed. Permitted models: ${d.join(", ")}`:`Error: Default model "${s||"undefined"}" is not in allowedModels (${d.join(", ")}). Update your plugin config to set a compatible defaultModel.`};let c=ml(t),h=An(t,c||Mn(n)),m=t.sessionKey||void 0,S=fl(m)??Tn(t);if(!e.resume_session_id&&!e.force_new_session){let v=My(r,{workdir:n,originSessionKey:m,originChannel:h,originThreadId:S});if(v.resumable.length>0||v.active.length>0){let de=v.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",jl(v.resumable),"","Resume the latest one with:",` agent_respond(session='${v.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${v.resumable[0].ref}', fork_session=true)`].join(`
38
+ `):"",yr=v.active.length>0?[v.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",jl(v.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${v.active[0].ref}', message='<next instruction>')`].join(`
39
+ `):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",de,yr,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
40
+ `)].filter(Boolean).join(`
41
+
42
+ `)}}}let y=e.resume_session_id,x=y?r.resolve?.(y):void 0,$=y?r.getPersistedSession?.(y):void 0;if(y){let v=r.resolveBackendConversationId?.(y)??r.resolveHarnessSessionId?.(y);if(!v)return{kind:"error",text:`Error: Could not resolve resume_session_id "${y}" to a session ID. Use agent_sessions to list available sessions.`};y=v}let{resumeSessionId:re,clearedPersistedCodexResume:R}=Ko({requestedResumeSessionId:y,activeSession:x?{harnessSessionId:x.backendConversationId??x.harnessSessionId}:void 0,persistedSession:$?{harness:$.harness,backendRef:$.backendRef}:void 0}),W=e.permission_mode??E.permissionMode,I=e.plan_approval??E.planApproval;return{kind:"resolved",workdir:n,harness:o,resolvedModel:s,permissionMode:W,planApproval:I,originChannel:h,originThreadId:S,originSessionKey:m,route:Bo(t,h,m),resumeSessionId:re,resolvedResumeId:y,clearedPersistedCodexResume:R,reasoningEffort:Jt(o)}}function Ey(e){return e instanceof Error?e.message:String(e)}function Hl(e,t){return e?("id"in e?e.id:e.sessionId)??t??"unknown-session":t??"unknown-session"}function $y(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function Oy(e){return!!e&&typeof e=="object"&&typeof e.formatLaunchResult=="function"}function Gl(e){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn \u2014 they stay open for follow-up messages via agent_respond. 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 reference to continue or fork from. Prefer the plugin session ID shown by agent_launch or agent_sessions; persisted backend conversation IDs also resolve when available."})),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."})),force_new_session:g.Optional(g.Boolean({description:"Bypass resume-first protection and start a brand-new linked session even when a resumable or active linked session already exists."})),permission_mode:g.Optional(g.Union([g.Literal("default"),g.Literal("plan"),g.Literal("bypassPermissions")],{description:"Permission mode: 'default' (plugin-managed interactive execution), 'plan' (present the plan first and block implementation until approval), 'bypassPermissions' (fully autonomous execution). Defaults to plugin config ('plan' by default)."})),plan_approval:g.Optional(g.Union([g.Literal("ask"),g.Literal("delegate"),g.Literal("approve")],{description:"Plan approval policy for this session: 'ask' (send the full plan to the user with Approve/Revise/Reject buttons), 'delegate' (orchestrator must review the full plan, then either approve directly or escalate back to the user with the same buttons), 'approve' (auto-approve after verification). Overrides the plugin-level planApproval setting."})),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("delegate"),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 Merge/PR/Decide later/Dismiss buttons), 'delegate' (orchestrator decides), 'auto-merge' (merge automatically), 'auto-pr' (open/update a PR automatically). Defaults to the plugin config when unset."})),worktree_base_branch:g.Optional(g.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),worktree_pr_target_repo:g.Optional(g.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex' for fork-to-upstream workflow). If not set, auto-detected from 'upstream' remote or defaults to 'origin'."}))}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!$y(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.`);try{let n=Vl(r,e,k);if(n.kind!=="resolved")return{content:[{type:"text",text:n.text}]};let{workdir:o,harness:i,resolvedModel:s,permissionMode:a,planApproval:d,originChannel:c,originThreadId:h,originSessionKey:m,route:S,resumeSessionId:y,resolvedResumeId:x,clearedPersistedCodexResume:$,reasoningEffort:re}=n,R=r.resume_session_id?k.resolve(r.resume_session_id)??k.getPersistedSession(r.resume_session_id):void 0,W=!r.fork_session&&R?Fn(R):void 0;if(W?.kind==="direct")return{content:[{type:"text",text:`Session ${R.name} [${Hl(R,r.resume_session_id)}] is already running. Use agent_respond(session='${r.resume_session_id}', message='<next instruction>') instead of agent_launch(resume_session_id=...).`}]};if(W?.kind==="unavailable")return{content:[{type:"text",text:`Resume unavailable for session ${R.name} [${Hl(R,r.resume_session_id)}] (${W.reason}). Use agent_launch(prompt='<new task>') for a fresh session or set fork_session=true to fork from prior context.`}]};let I=k.spawn({prompt:r.prompt,sessionIdOverride:r.fork_session?void 0:W?.kind==="resume"||W?.kind==="relaunch"?W.stableSessionId:void 0,name:r.name,workdir:o,model:s,reasoningEffort:re,systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,resumeSessionId:W?.kind==="resume"?W.resumeSessionId:y,resumeWorktreeFrom:x,forkSession:y?r.fork_session:!1,multiTurn:!0,permissionMode:a,planApproval:d,codexApprovalPolicy:i==="codex"?"never":void 0,originChannel:c,originThreadId:h,originAgentId:e.agentId||void 0,originSessionKey:m,route:S,harness:i,worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,worktreePrTargetRepo:r.worktree_pr_target_repo});return{content:[{type:"text",text:Oy(k)?k.formatLaunchResult({prompt:r.prompt,workdir:o,harness:i,permissionMode:a??E.permissionMode,planApproval:d,forceNewSession:r.force_new_session,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,clearedPersistedCodexResume:$},I):Uo({prompt:r.prompt,workdir:o,harness:i,permissionMode:a??E.permissionMode,planApproval:d,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,forceNewSession:r.force_new_session,clearedPersistedCodexResume:$},{id:I.id,name:I.name,model:I.model,reasoningEffort:I.reasoningEffort??Jt(i),worktreeStrategy:I.worktreeStrategy??r.worktree_strategy??E.defaultWorktreeStrategy??"off",worktreePath:I.worktreePath,originalWorkdir:I.originalWorkdir})}]}}catch(n){let o=Ey(n),i=o.includes("Max sessions")?"":`
43
+
44
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}nt();he();Le();import{existsSync as ed,readFileSync as km}from"fs";import{EventEmitter as Jy}from"events";import{webcrypto as Ql}from"node:crypto";var zl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var _y=128,fr,jr;function Ny(e){!fr||fr.length<e?(fr=Buffer.allocUnsafe(e*_y),Ql.getRandomValues(fr),jr=0):jr+e>fr.length&&(Ql.getRandomValues(fr),jr=0),jr+=e}function Jl(e=21){Ny(e|=0);let t="";for(let r=jr-e;r<jr;r++)t+=zl[fr[r]&63];return t}Va();Le();ke();var Yl={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},Xl=new Set(["merged","pr_open","dismissed","cleanup_failed"]);function Fy(e){return e.requestedPermissionMode!=="plan"?"not_plan_gated":e.pendingPlanApproval?"awaiting_approval":e.planModeApproved?"approved_then_implemented":e.currentPermissionMode!=="plan"?"implemented_without_required_approval":"awaiting_approval"}function Me(e){return{...e,approvalExecutionState:Fy(e)}}function Qa(e,t){switch(t.type){case"initialize":return Me({...e,worktreeState:t.hasWorktree&&e.worktreeState==="none"?"provisioned":e.worktreeState,lifecycle:e.status==="starting"?"starting":e.lifecycle,runtimeState:e.status==="starting"?"live":e.runtimeState});case"status.transition":return t.status==="starting"?Me({...e,status:t.status,lifecycle:"starting",runtimeState:"live"}):t.status==="running"?Me({...e,status:t.status,lifecycle:e.lifecycle==="starting"||e.lifecycle==="suspended"?"active":e.lifecycle,runtimeState:"live"}):Me({...e,status:t.status,runtimeState:"stopped",lifecycle:e.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return Me({...e,currentPermissionMode:t.currentPermissionMode});case"turn.started":return Me({...e,lifecycle:"active",runtimeState:"live"});case"input.requested":return Me({...e,lifecycle:e.pendingPlanApproval?"awaiting_plan_decision":"awaiting_user_input"});case"plan.requested":if(e.planModeApproved)return e;{let r=e.pendingPlanApproval&&e.approvalState==="pending"&&e.planApprovalContext===t.context;return Me({...e,pendingPlanApproval:!0,planApprovalContext:t.context,approvalState:"pending",planDecisionVersion:r?e.planDecisionVersion:e.planDecisionVersion+1,lifecycle:"awaiting_plan_decision"})}case"plan.cleared":return Me({...e,pendingPlanApproval:!1,planApprovalContext:void 0,approvalState:e.approvalState==="pending"?"not_required":e.approvalState});case"plan.approved":return Me({...e,pendingPlanApproval:!1,planApprovalContext:void 0,planModeApproved:!0,approvalState:"approved",planDecisionVersion:e.planDecisionVersion+1,lifecycle:e.status==="running"?"active":e.lifecycle});case"plan.changes_requested":return Me({...e,pendingPlanApproval:!0,approvalState:"changes_requested",planDecisionVersion:e.planDecisionVersion+1,lifecycle:"awaiting_plan_decision"});case"terminal.entered":return Me({...e,lifecycle:t.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return Me({...e,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return Me({...e,worktreeState:t.worktreeState,lifecycle:t.worktreeState==="pending_decision"?"awaiting_worktree_decision":Xl.has(t.worktreeState)?"terminal":e.lifecycle});case"delivery.state_set":return Me({...e,deliveryState:t.deliveryState})}}function Zl(e,t){let r={...e,...t.lifecycle!==void 0?{lifecycle:t.lifecycle}:{},...t.approvalState!==void 0?{approvalState:t.approvalState}:{},...t.approvalExecutionState!==void 0?{approvalExecutionState:t.approvalExecutionState}:{},...t.worktreeState!==void 0?{worktreeState:t.worktreeState}:{},...t.runtimeState!==void 0?{runtimeState:t.runtimeState}:{},...t.deliveryState!==void 0?{deliveryState:t.deliveryState}:{},...t.requestedPermissionMode!==void 0?{requestedPermissionMode:t.requestedPermissionMode}:{},...t.currentPermissionMode!==void 0?{currentPermissionMode:t.currentPermissionMode}:{},...t.pendingPlanApproval!==void 0?{pendingPlanApproval:t.pendingPlanApproval}:{},...t.planApprovalContext!==void 0?{planApprovalContext:t.planApprovalContext}:{},...t.planDecisionVersion!==void 0?{planDecisionVersion:t.planDecisionVersion}:{},...t.canonicalPlanPromptVersion!==void 0?{canonicalPlanPromptVersion:t.canonicalPlanPromptVersion}:{},...t.planModeApproved!==void 0?{planModeApproved:t.planModeApproved}:{}};return r.pendingPlanApproval&&(r={...r,approvalState:r.approvalState==="changes_requested"?"changes_requested":"pending",lifecycle:"awaiting_plan_decision"}),t.pendingWorktreeDecisionSince!==void 0||r.worktreeState==="pending_decision"?r=Qa(r,{type:"worktree.decision_requested"}):Xl.has(r.worktreeState)&&(r={...r,lifecycle:"terminal"}),Me(r)}var ei=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})}}};import{appendFileSync as Dy}from"fs";import{tmpdir as Ly}from"os";import{join as Uy}from"path";var em=2e3;function qr(e){return Uy(Ly(),`openclaw-agent-${e}.txt`)}function Wy(e,t){if(!t)return;let r=t.split(`
45
+ `),[n="",...o]=r;e.length===0?e.push(n):e[e.length-1]+=n;for(let i of o)e.push(i)}function tm(e,t,r){Wy(e,r),e.length>em&&e.splice(0,e.length-em);try{Dy(qr(t),r,"utf-8")}catch{}return e}var ti=class{timers=new Map;get size(){return this.timers.size}set(t,r,n){this.clear(t);let o=setTimeout(n,r);o.unref?.(),this.timers.set(t,o)}clear(t){let r=this.timers.get(t);r&&(clearTimeout(r),this.timers.delete(t))}clearAll(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}};var ri=class{constructor(t){this.deps=t}waitingForInputFired=!1;lastTurnHadQuestion=!1;turnInProgress=!0;currentTurnText="";currentTurnPlanArtifact;beginUserTurn(){this.waitingForInputFired=!1,this.turnInProgress=!0,this.currentTurnText="",this.currentTurnPlanArtifact=void 0,this.lastTurnHadQuestion=!1}noteTextDelta(t,r){this.waitingForInputFired=!1,r||(this.lastTurnHadQuestion=!1),this.deps.appendOutput(t),this.currentTurnText+=this.currentTurnText?`
46
+ ${t}`:t,this.deps.emitOutput(t)}noteToolCall(t){let{name:r,input:n,currentPermissionMode:o,permissionMode:i,planModeApproved:s}=t;if(r==="Write"){let a=n;typeof a?.file_path=="string"&&a.file_path.includes("/.claude/plans/")&&this.deps.setPlanFilePath(a.file_path)}r==="AskUserQuestion"?(this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),(o==="plan"||i==="plan")&&!s&&this.deps.markPendingPlanApproval("plan-mode")):(r==="ExitPlanMode"||r==="set_permission_mode")&&!s&&(this.lastTurnHadQuestion=!0,this.deps.markPendingPlanApproval("plan-mode")),this.deps.emitToolUse(r,n)}notePendingInput(){this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),this.waitingForInputFired||(this.waitingForInputFired=!0,this.deps.emitTurnEnd(!0))}clearResolvedPendingInput(t,r){if(!(!t||r?.requestId===t))return r}notePlanArtifact(t,r){if(this.currentTurnPlanArtifact=t,!r)return;let n=t.markdown.trim();!n||this.currentTurnText.trim()===n||(this.deps.appendOutput(n),this.currentTurnText=n,this.deps.emitOutput(n))}noteSettingsChanged(t){let{oldMode:r,permissionMode:n,planModeApproved:o}=t;if(n)return n!=="plan"&&r==="plan"&&!o&&(this.deps.markPendingPlanApproval("plan-mode"),this.lastTurnHadQuestion=!0),n}finishSuccessfulTurn(t){let{currentPermissionMode:r,permissionMode:n,pendingPlanApproval:o,planModeApproved:i,pendingInputState:s,hasPendingMessages:a}=t,d=o;(r==="plan"||n==="plan")&&!d&&!i&&(this.deps.markPendingPlanApproval("plan-mode"),d=!0);let c=d||this.lastTurnHadQuestion||!!s;this.turnInProgress=a,c&&!this.waitingForInputFired?(this.waitingForInputFired=!0,d||this.deps.markAwaitingUserInput(),this.deps.emitTurnEnd(!0)):!a&&!c&&(this.deps.completeTurn(),this.deps.emitTurnEnd(!1))}finishTerminalTurn(){this.turnInProgress=!1}resetAfterRun(){this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}};var ni=class{constructor(t){this.deps=t}applyMessage(t,r){if(t.type==="backend_ref"){this.deps.clearStartupTimer(),this.deps.assignBackendRef({...t.ref}),this.deps.transitionRunning();return}if(t.type==="run_started"){t.runId&&this.deps.noteRunStarted(t.runId);return}if(t.type==="text_delta"){this.deps.noteTextDelta(t.text,r.pendingPlanApproval);return}if(t.type==="tool_call"){this.deps.noteToolCall({name:t.name,input:t.input,currentPermissionMode:r.currentPermissionMode,permissionMode:r.permissionMode,planModeApproved:r.planModeApproved});return}if(t.type==="pending_input"){this.deps.setPendingInputState(t.state),this.deps.notePendingInput();return}if(t.type==="pending_input_resolved"){this.deps.setPendingInputState(this.deps.clearResolvedPendingInput(t.requestId,r.pendingInputState));return}if(t.type==="plan_artifact"){this.deps.notePlanArtifact(t);return}if(t.type==="settings_changed"){let n=this.deps.noteSettingsChanged({oldMode:r.currentPermissionMode,permissionMode:t.permissionMode,planModeApproved:r.planModeApproved});n&&this.deps.setCurrentPermissionMode(n);return}if(t.type==="run_completed"){this.deps.handleRunCompleted(t.data);return}t.type}};Qe();var Yy=120*1e3;function fi(e){return e instanceof Error?e.message:String(e)}var gi=class extends Jy{id;name;harnessSessionId;backendRef;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;requestedPermissionMode;planApproval;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;worktreePath;originalWorkdir;worktreeBranch;worktreeStrategy;worktreeBaseBranch;worktreePrTargetRepo;worktreePushRemote;worktreeDisposition;worktreePrUrl;worktreePrNumber;worktreeMerged;worktreeMergedAt;worktreeState="none";multiTurn;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;route;pendingInputState;pendingPlanApproval=!1;planApprovalContext;planDecisionVersion=0;canonicalPlanPromptVersion;planFilePath;killReason="unknown";planModeApproved=!1;turnRuntime;harnessEvents;lifecycle="starting";approvalState="not_required";approvalExecutionState="not_plan_gated";runtimeState="live";deliveryState="idle";canUseTool;autoRespondCount=0;timers=new ti;constructor(t,r){super(),this.id=t.sessionIdOverride??Jl(8),this.name=r,this.harness=t.harness?_n(t.harness):Ul(),this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??Wr(this.harness.name),this.reasoningEffort=t.reasoningEffort??Jt(this.harness.name),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??E.permissionMode,this.requestedPermissionMode=t.requestedPermissionMode??this.permissionMode,this.planApproval=t.planApproval??E.planApproval,this.codexApprovalPolicy=this.harness.name==="codex"?"never":void 0,this.currentPermissionMode=this.permissionMode,this.originChannel=t.originChannel,this.originThreadId=t.originThreadId,this.originAgentId=t.originAgentId,this.originSessionKey=t.originSessionKey,this.route=t.route?{...t.route}:void 0,this.backendRef=t.backendRef?{...t.backendRef}:void 0,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.worktreeStrategy=t.worktreeStrategy,this.worktreeBaseBranch=t.worktreeBaseBranch,t.worktreePrTargetRepo&&(this.worktreePrTargetRepo=t.worktreePrTargetRepo),this.canUseTool=t.canUseTool,this.startedAt=Date.now(),this.abortController=new AbortController,this.turnRuntime=new ri({appendOutput:n=>tm(this.outputBuffer,this.id,n),emitOutput:n=>this.emit("output",this,n),emitToolUse:(n,o)=>this.emit("toolUse",this,n,o),emitTurnEnd:n=>this.emit("turnEnd",this,n),markPendingPlanApproval:n=>this.markPendingPlanApproval(n),markAwaitingUserInput:()=>this.markAwaitingUserInput(),applyInputRequested:()=>this.applyControlEvent({type:"input.requested"}),completeTurn:()=>{this.applyControlEvent({type:"terminal.entered"}),this.complete("done")},setPlanFilePath:n=>{this.planFilePath=n}}),this.harnessEvents=new ni({clearStartupTimer:()=>this.clearTimer("startup"),assignBackendRef:n=>{this.backendRef=n,this.harnessSessionId=n.conversationId,n.worktreePath&&(this.worktreePath=n.worktreePath,this.originalWorkdir??=this.workdir,this.worktreeBranch??=ai(n.worktreePath),this.worktreeStrategy&&this.worktreeStrategy!=="off"&&this.applyControlEvent({type:"worktree.state_set",worktreeState:"provisioned"}))},noteRunStarted:n=>{this.backendRef&&(this.backendRef={...this.backendRef,runId:n})},transitionRunning:()=>{this._status==="starting"&&this.transition("running")},noteTextDelta:(n,o)=>this.turnRuntime.noteTextDelta(n,o),noteToolCall:n=>this.turnRuntime.noteToolCall(n),setPendingInputState:n=>{this.pendingInputState=n},notePendingInput:()=>this.turnRuntime.notePendingInput(),clearResolvedPendingInput:(n,o)=>this.turnRuntime.clearResolvedPendingInput(n,o),notePlanArtifact:n=>this.turnRuntime.notePlanArtifact(n.artifact,n.finalized),noteSettingsChanged:n=>this.turnRuntime.noteSettingsChanged(n),setCurrentPermissionMode:n=>{this.currentPermissionMode=n,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:n})},handleRunCompleted:n=>{this.result={subtype:n.success?"success":"error",duration_ms:n.duration_ms,total_cost_usd:n.total_cost_usd,num_turns:n.num_turns,result:n.result,is_error:!n.success,session_id:n.session_id},this.costUsd=n.total_cost_usd,this.multiTurn&&this.messageStream&&n.success?(this.resetIdleTimer(),this.turnRuntime.finishSuccessfulTurn({currentPermissionMode:this.currentPermissionMode,permissionMode:this.permissionMode,pendingPlanApproval:this.pendingPlanApproval,planModeApproved:this.planModeApproved,pendingInputState:this.pendingInputState,hasPendingMessages:this.messageStream?.hasPending()===!0})):(this.turnRuntime.finishTerminalTurn(),this.transitionToTerminal(n.success?"completed":"failed")),this.turnRuntime.resetAfterRun(),this.pendingInputState=void 0}}),this.applyControlEvent({type:"initialize",hasWorktree:!!(this.worktreeStrategy&&this.worktreeStrategy!=="off")}),(t.planModeApproved!==void 0||t.approvalState!==void 0||t.approvalExecutionState!==void 0)&&this.applyControlPatch({...t.planModeApproved!==void 0?{planModeApproved:t.planModeApproved}:{},...t.approvalState!==void 0?{approvalState:t.approvalState}:{},...t.approvalExecutionState!==void 0?{approvalExecutionState:t.approvalExecutionState}:{}})}get status(){return this._status}get harnessName(){return this.harness.name}get backendKind(){return this.harness.backendKind}get backendCapabilities(){return this.harness.capabilities}get backendConversationId(){return T(this)}get waitingForInputFired(){return this.turnRuntime.waitingForInputFired}set waitingForInputFired(t){this.turnRuntime.waitingForInputFired=t}get lastTurnHadQuestion(){return this.turnRuntime.lastTurnHadQuestion}set lastTurnHadQuestion(t){this.turnRuntime.lastTurnHadQuestion=t}get turnInProgress(){return this.turnRuntime.turnInProgress}set turnInProgress(t){this.turnRuntime.turnInProgress=t}get currentTurnText(){return this.turnRuntime.currentTurnText}set currentTurnText(t){this.turnRuntime.currentTurnText=t}get currentTurnPlanArtifact(){return this.turnRuntime.currentTurnPlanArtifact}set currentTurnPlanArtifact(t){this.turnRuntime.currentTurnPlanArtifact=t}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this.lifecycle}get isExplicitlyResumable(){return this.status!=="running"&&this.status!=="completed"&&this.killReason!=="done"&&!!this.backendConversationId}transition(t){if(!Yl[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.applyControlEvent({type:"status.transition",status:t}),this.emit("statusChange",this,t,r)}setTimer(t,r,n){this.timers.set(t,r,n)}clearTimer(t){this.timers.clear(t)}clearAllTimers(){this.timers.clearAll()}markPendingPlanApproval(t){this.applyControlEvent({type:"plan.requested",context:t})}clearPendingPlanApproval(){this.applyControlEvent({type:"plan.cleared"})}markAwaitingUserInput(){this.applyControlEvent({type:"input.requested"})}async start(){try{let t;this.multiTurn?(this.messageStream=new ei,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,backendRef:this.backendRef,worktreeStrategy:this.worktreeStrategy,originalWorkdir:this.originalWorkdir??this.workdir,abortController:this.abortController,mcpServers:ul(),canUseTool:this.canUseTool});this.harnessHandle=r,this.setTimer("startup",Yy,()=>{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.turnRuntime.beginUserTurn(),this.applyControlEvent({type:"turn.started"});let r=t;if(this.pendingModeSwitch){let n=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(n),this.currentPermissionMode=n,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:n}),this.pendingModeSwitch=void 0,i=!0,o=!0}catch(s){throw console.error(`[Session ${this.id}] setPermissionMode(${n}) FAILED: ${fi(s)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${n}: ${fi(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.clearPendingPlanApproval(),n!=="plan"&&this.applyControlEvent({type:"plan.approved"})),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
+
48
+ ${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved&&(this.applyControlEvent({type:"plan.changes_requested"}),r=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below, then re-submit your revised plan for approval. Do NOT start implementing yet.]
49
+
50
+ ${t}`,this.harnessHandle?.setPermissionMode))try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan",this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:"plan"})}catch(n){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${fi(n)}`)}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(r,this.backendConversationId??""));else if(this.harnessHandle?.streamInput){let n=this.harness.buildUserMessage(r,this.backendConversationId??"");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)}async submitPendingInputOption(t){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputOption)return!1;let r=await this.harnessHandle.submitPendingInputOption(t);return r&&(this.waitingForInputFired=!1),r}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=(E.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",t,()=>{this._status==="running"&&(this.applyControlEvent({type:"terminal.entered",suspended:!0}),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: ${fi(t)}`)}),this.abortController.abort(),this.applyControlEvent({type:"terminal.entered",suspended:this.lifecycle==="suspended"})}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.applyControlEvent({type:"terminal.entered",suspended:t==="killed"&&r.reason==="idle-timeout"}),this.transition(t),this.teardown())}async consumeMessages(t){for await(let r of t){if(!this.isActive)break;this.resetIdleTimer(),this.harnessEvents.applyMessage(r,{pendingPlanApproval:this.pendingPlanApproval,currentPermissionMode:this.currentPermissionMode,permissionMode:this.permissionMode,planModeApproved:this.planModeApproved,pendingInputState:this.pendingInputState})}}controlStateSnapshot(){return{status:this._status,lifecycle:this.lifecycle,approvalState:this.approvalState,approvalExecutionState:this.approvalExecutionState,worktreeState:this.worktreeState,runtimeState:this.runtimeState,deliveryState:this.deliveryState,requestedPermissionMode:this.requestedPermissionMode,currentPermissionMode:this.currentPermissionMode,pendingPlanApproval:this.pendingPlanApproval,planApprovalContext:this.planApprovalContext,planDecisionVersion:this.planDecisionVersion,canonicalPlanPromptVersion:this.canonicalPlanPromptVersion,planModeApproved:this.planModeApproved}}applyControlEvent(t){let r=Qa(this.controlStateSnapshot(),t);this.applyControlState(r)}applyControlPatch(t){let r=Zl(this.controlStateSnapshot(),t);this.applyControlState(r)}applyControlState(t){this.lifecycle=t.lifecycle,this.approvalState=t.approvalState,this.approvalExecutionState=t.approvalExecutionState,this.worktreeState=t.worktreeState,this.runtimeState=t.runtimeState,this.deliveryState=t.deliveryState,this.pendingPlanApproval=t.pendingPlanApproval,this.planApprovalContext=t.planApprovalContext,this.planDecisionVersion=t.planDecisionVersion,this.canonicalPlanPromptVersion=t.canonicalPlanPromptVersion,this.planModeApproved=t.planModeApproved}};ke();function St(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 Xy=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 fm(e){let r=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!Xy.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var mm={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4",awaiting_plan_decision:"\u{1F4CB}",awaiting_user_input:"\u2753",awaiting_worktree_decision:"\u{1F33F}",suspended:"\u23F8\uFE0F",terminal:"\u{1F3C1}"};function gm(e){let t=mm[e.phase]??mm[e.status]??"\u2753",r=St(e.duration),n=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}] (${r}${i}) \u2014 ${n}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];if(e.worktreePath&&e.worktreeBranch){let d=` \u{1F33F} Worktree: ${e.worktreeBranch}`;e.worktreeMerged?d+=" [merged \u2713]":e.worktreePrUrl?d+=` [PR: ${e.worktreePrUrl}]`:d+=" [not merged]",s.push(d)}e.phase!==e.status&&s.push(` \u2699\uFE0F Phase: ${e.phase}`),e.lifecycle&&e.lifecycle!==e.phase&&s.push(` \u{1F504} Lifecycle: ${e.lifecycle}`),(e.requestedPermissionMode||e.currentPermissionMode||e.approvalExecutionState)&&s.push(` \u{1F510} Approval: ${e.approvalExecutionState??"unknown"} (requested=${e.requestedPermissionMode??"unknown"}, effective=${e.currentPermissionMode??"unknown"})`),e.resumable&&s.push(" \u21A9\uFE0F Resumable: yes"),e.harness&&s.push(` \u{1F9F0} Harness: ${e.harness}`);let a=T(e);return a&&s.push(` \u{1F517} Backend ID: ${a}`),e.resumeSessionId&&s.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),s.join(`
51
+ `)}function hi(e,t){let r=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:n,failed:o,killed:i}=e.sessionsByStatus,s=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${n}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${r>0?St(r):"n/a"}`];if(e.mostExpensive){let a=e.mostExpensive;s.push("","\u{1F3C6} Notable session",` ${a.name} [${a.id}]`,` \u{1F4DD} "${a.prompt}"`)}return s.join(`
52
+ `)}function hr(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function hm(e,t){let r=e.split(`
53
+ `),n=[],o=0;for(let i=r.length-1;i>=0;i--){let s=r[i].length+(n.length>0?1:0);if(o+s>t&&n.length>0)break;n.unshift(r[i]),o+=s}return n.join(`
54
+ `)}function Sm(e,t){let r=e.split(`
55
+ `),n=[],o=0;for(let i=0;i<r.length;i++){let s=r[i].length+(n.length>0?1:0);if(o+s>t&&n.length>0)break;n.push(r[i]),o+=s}return n.join(`
56
+ `)}var Zy=50,ew=1,tw=new Set(["starting","running","completed","failed","killed"]),rw=5,nw=1440*60*1e3;function ow(e){let t=Number(e);return!Number.isFinite(t)||t<ew?Zy:Math.floor(t)}function iw(e){return typeof e=="string"&&tw.has(e)}function sw(e){let t=e.split(`
57
+ `);return t.at(-1)===""&&t.pop(),t}function ym(e){return e.backendRef?.conversationId??e.harnessSessionId}function wm(e,t,r){let n=km(e,"utf-8"),o=sw(n);return t.full?o:o.slice(-r)}function aw(e,t,r){if(e.status!=="starting"&&e.status!=="running")return null;let n=qr(e.id);if(!ed(n))return null;try{return wm(n,t,r)}catch{return null}}function dw(e){let t=St(e.duration),r=` | Cost: $${e.costUsd.toFixed(4)}`,n=e.phase?` | Phase: ${e.phase}`:"",o=e.lifecycle&&e.lifecycle!==e.phase?` | Lifecycle: ${e.lifecycle}`:"";return[`Session: ${e.name} [${e.id}] | Status: ${e.status.toUpperCase()}${n}${o}${r} | Duration: ${t}`,`${"\u2500".repeat(60)}`].join(`
58
+ `)}function uw(e){return[`Session: ${e.name||e.sessionId||ym(e)||"unknown"} | 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(`
59
+ `)}function pw(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
60
  (no output yet)
12
61
  ${t.join(`
13
62
  `)}`:`
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]
31
- /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:
33
-
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(`
35
- `)}).join(`
36
-
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.]
45
-
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.]
47
-
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:
50
-
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:
59
-
60
- ${n}
61
-
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(`
63
- `):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};
63
+ (no output yet)`}function Si(e,t,r={}){let n=ow(r.lines),o=e.resolve(t);if(!o){let c=e.getPersistedSession(t);if(c?.outputPath&&ed(c.outputPath))try{let h=wm(c.outputPath,r,n).join(`
64
+ `),m=uw(c);return h?`${m}
65
+ ${h}`:`${m}
66
+ (output file was empty)`}catch(h){let m=h instanceof Error?h.message:String(h);return`Error: Session "${t}" was cleaned up (expired) and output file could not be read: ${m}`}return`Error: Session "${t}" not found.`}let i=aw(o,r,n),s=i&&i.length>0?i:r.full?o.getOutput():o.getOutput(n),a=dw(o),d=s.length===0?`${a}${pw(o)}`:`${a}
67
+ ${s.join(`
68
+ `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(ed(o.planFilePath)){let c=km(o.planFilePath,"utf-8"),h="\u2500".repeat(60);return`${d}
69
+ ${h}
70
+ Plan file: ${o.planFilePath}
71
+ ${h}
72
+ ${c}`}}catch{}return d}function ki(e,t="all",r,n={}){let o=e.listPersistedSessions()??[],s=cw(e.list("all"),o);if(t!=="all"&&(s=s.filter(a=>a.status===t)),r&&(s=s.filter(a=>a.originChannel===r)),n.full){let a=Date.now()-nw;s=s.filter(d=>(d.startedAt??0)>=a)}else s=s.slice(0,rw);return s.length===0?"No sessions found.":s.map(a=>gm(a)).join(`
73
+
74
+ `)}function cw(e,t){let r=new Map;for(let n of t){if(!iw(n.status))continue;let o=n.completedAt??Date.now(),i=n.createdAt??o,s=ym(n),a=n.sessionId??`persisted:${s??n.harnessSessionId}`;r.set(a,{id:n.sessionId??s??n.harnessSessionId,name:n.name||n.sessionId||s||n.harnessSessionId,status:n.status,startedAt:n.createdAt??0,completedAt:n.completedAt,duration:Math.max(0,o-i),prompt:n.prompt??"",workdir:n.workdir??"(unknown)",costUsd:n.costUsd??0,multiTurn:!0,phase:n.lifecycle??n.status,lifecycle:n.lifecycle,resumable:n.resumable,harness:n.harness,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,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)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,lifecycle:n.lifecycle,resumable:n.isExplicitlyResumable,harness:n.harnessName,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,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 lw(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 Im(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(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=lw(r),o=e?.workspaceDir?Mn(e.workspaceDir):void 0,i=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:ki(k,n,o,{full:i})}]}}}}nt();he();function yi(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 mw(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 xm(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 k?mw(r)?{content:[{type:"text",text:yi(k,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."}]}}}}nt();he();function fw(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function wi(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 k?fw(r)?{content:[{type:"text",text:Si(k,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."}]}}}}nt();he();Le();ke();var gw=10;function rd(e){return e instanceof Error?e.message:String(e)}function Sr(e){return ee(e)??e.harnessSessionId??"unknown-session"}function Pm(e){return e.status!=="running"&&!!e.pendingPlanApproval&&!!T(e)}function Un(e,t,r){let n=t==="completed"?`This session is closed by default. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Sr(e)}', fork_session=true, prompt='<new task>').`:t==="legacy_non_resumable"?`Persisted historical backend state is intentionally non-resumable here. Launch fresh, or fork with agent_launch(resume_session_id='${Sr(e)}', fork_session=true, prompt='<new task>').`:t==="missing_backend_state"?`No resumable backend state is available. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Sr(e)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${Sr(e)}', message='<next instruction>') to continue the running session.`,o=r?` ${r}`:"";return{text:`Resume unavailable for session ${e.name} [${Sr(e)}] (${t}).${o} ${n}`,isError:!0}}async function bm(e,t,r){try{let n={prompt:t.prompt,sessionIdOverride:za(t),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,route:t.route,permissionMode:t.currentPermissionMode,requestedPermissionMode:t.requestedPermissionMode??t.currentPermissionMode,planApproval:t.planApproval,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} [${Sr(t)}]: ${rd(n)}`,isError:!0}}}var hw=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
75
+
76
+ `;function td(e){if(e.approvalState==="changes_requested")return`Plan changes were already requested for session ${e.name}. Wait for the revised plan before approving.`;if(e.approvalState==="rejected")return`Plan for session ${e.name} was already rejected.`}function Sw(e){return td(e)?!1:!!(e.pendingPlanApproval||e.currentPermissionMode==="plan")}async function kw(e,t,r,n={}){let o=Fn(t);if(!(o.kind==="resume"||Pm(t)))return;let s=!!(n.approve&&Sw(t));try{if(o.kind!=="resume")return o.kind==="relaunch"?bm(e,t,r):Un(t,o.reason);let a={prompt:s?hw+r:r,sessionIdOverride:o.stableSessionId,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:o.resumeSessionId,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,route:t.route,permissionMode:s?"bypassPermissions":t.currentPermissionMode,requestedPermissionMode:t.requestedPermissionMode??t.currentPermissionMode,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,...s?{approvalState:"approved",approvalExecutionState:"approved_then_implemented",planModeApproved:!0}:{},harness:"harnessName"in t?t.harnessName:t.harness},d=await e.spawnAndAwaitRunning(a,{notifyLaunch:!1});return s?(e.notifySession(d,`\u{1F44D} [${d.name}] Plan approved (resumed)`,"plan-approved"),{text:`Plan approved for session ${d.name} [${d.id}]. Session resumed in bypassPermissions mode. Use agent_output to see the response.`}):(e.notifySession(d,`\u25B6\uFE0F [${d.name}] Auto-resumed`),{text:`Auto-resumed session ${d.name} [${d.id}]. Use agent_output to see the response.`})}catch(a){return Un(t,"missing_backend_state",`Backend resume failed: ${rd(a)}`)}}async function kr(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,i=o.status==="running"?{kind:"direct"}:Fn(o);if(t.approve){let a=td(o);if(a)return{text:a,isError:!0}}if(i.kind==="resume"||Pm(o)){let a=await kw(e,o,t.message,{approve:t.approve});if(a)return a}else{if(i.kind==="relaunch")return bm(e,o,t.message);if(i.kind==="unavailable")return Un(o,i.reason)}if(!r)return Nn(n)?Un(n,"completed"):{text:`Error: Session ${n.name} [${Sr(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return Nn(r)?Un(r,"completed"):{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 s=E.maxAutoResponds??gw;if(t.userInitiated)r.resetAutoRespond();else if(r.autoRespondCount>=s)return{text:`\u26A0\uFE0F Auto-respond limit reached (${r.autoRespondCount}/${s}). 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{if(t.approve){let m=td(r);if(m)return{text:m,isError:!0}}let a=!1;t.interrupt&&(a=await r.interrupt());let d=!!(t.approve&&r.pendingPlanApproval),c="";if(t.approve&&r.pendingPlanApproval||t.approve&&r.currentPermissionMode==="default"?r.switchPermissionMode("bypassPermissions"):t.approve&&r.currentPermissionMode==="bypassPermissions"?c=`
77
+ \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:t.approve?c=`
78
+ \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:r.pendingPlanApproval&&(c=`
79
+ \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 r.sendMessage(t.message),d)e.notifySession(r,`\u{1F44D} [${r.name}] Plan approved`,"plan-approved");else if(t.userInitiated){let m=hr(t.message,100);e.notifySession(r,`\u21AA\uFE0F [${r.name}] "${m}"`,"agent-respond")}t.userInitiated||r.incrementAutoRespond();let h=hr(t.message,80);return d?{text:`Plan approved for session ${r.name} [${r.id}]. Use agent_output to see the response.`}:{text:[`Message sent to session ${r.name} [${r.id}].`,a?" (redirected active turn first)":t.interrupt?" (no active turn to interrupt)":"",` Message: "${h}"`,c,"Use agent_output to see the response."].filter(Boolean).join(`
80
+ `)}}catch(a){return{text:`Error sending message to session ${r.name} [${r.id}]: ${rd(a)}`,isError:!0}}}function yw(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function vm(e){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent session. The session must be running. All sessions are multi-turn.",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, or (2) escalate a default-mode session to skip remaining OpenClaw approval checkpoints. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."}))}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!yw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let n=await kr(k,r);return{isError:n.isError??!1,content:[{type:"text",text:n.text}]}}}}nt();he();function ww(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.summary=="string"}function Rm(e){return{name:"agent_request_plan_approval",description:"Send a plan-approval decision prompt to the user for a session that is already waiting on plan approval. Reuses the plugin's Approve/Revise/Reject buttons so the user can decide directly from the message.",parameters:g.Object({session:g.String({description:"Session name or ID awaiting plan approval"}),summary:g.String({description:"Concise user-facing summary of scope, risk, and any concerns that should accompany the approval buttons"})}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!ww(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, summary }."}]};let n=k.requestPlanApprovalFromUser(r.session,r.summary);return{isError:n.startsWith("Error:"),content:[{type:"text",text:n}]}}}}nt();he();function Am(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(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=k.getMetrics(),o=k.list("running").length;return{content:[{type:"text",text:hi(n,o)}]}}}}nt();Le();he();Qe();Wn();import{existsSync as od}from"fs";function Iw(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function xi(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 conflict-resolver session using the configured default harness.",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(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Iw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=Vr(k,r.session),o=n.activeSession,i=n.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let{worktreePath:s,originalWorkdir:a,branchName:d}=n;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}]};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.`}]};od(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${a})`);let c=a;if(!od(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let h=r.base_branch??gt(c),m=h,S=r.strategy??"merge",y=r.push===!0,x=r.delete_branch!==!1;if(i?.worktreeMerged)return{content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" is already merged.`}]};let $={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]},re=n.persistedRef;return await k.enqueueMerge(c,async()=>{let R=k.getPersistedSession(r.session);if(R?.worktreeMerged){$={content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" was already merged while waiting in queue.`}]};return}let W=Ft(c,d,h),I=li(c,d,m,S,s);if(I.success){if(y&&!ci(c,m)){$={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${m} locally, but failed to push ${m}`}]};return}x&&bt(c,d);let v=!1;if(od(s)&&(v=ht(c,s),ui(c)),R)for(let A of Ii({...n,persistedSession:R}))k.updatePersistedSession(A,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDisposition:"merged"});let de=gr({kind:"merge",branch:d,base:h,filesChanged:W?.filesChanged,insertions:W?.insertions,deletions:W?.deletions});k.notifyWorktreeOutcome(n.notificationTarget,de);let C=`\u2705 ${I.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${m}.${y?" Pushed.":""}${x?v?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;I.stashPopConflict?C+=`
81
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${I.stashRef??"stash@{0}"}\` in ${c} to review stashed changes.`:I.stashed&&(C+=`
82
+ (Pre-existing changes on ${m} were auto-stashed and restored.)`),$={content:[{type:"text",text:C}]}}else if(I.rebaseConflict)$={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
83
+
84
+ ${I.error}`}]};else if(I.conflictFiles&&I.conflictFiles.length>0){let v=["Resolve merge conflicts in the following files and commit the resolution:","",...I.conflictFiles.map(de=>`- ${de}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${d}"`].join(`
85
+ `);try{let de=k.spawn({prompt:v,workdir:c,name:`${r.session}-conflict-resolver`,harness:De(),permissionMode:"bypassPermissions",multiTurn:!0,route:o?.route??i?.route,originChannel:o?.originChannel??i?.originChannel,originThreadId:o?.originThreadId??i?.originThreadId,originAgentId:o?.originAgentId??i?.originAgentId,originSessionKey:o?.originSessionKey??i?.originSessionKey});$={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${I.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${de.name}`}]}}catch(de){$={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${de instanceof Error?de.message:String(de)}`}]}}}else $={content:[{type:"text",text:I.dirtyError?`\u274C Merge blocked: ${I.error}`:`\u274C Merge failed: ${I.error??"unknown error"}`}]}}),$}}}Pi();nt();Qe();he();Wn();import{execFileSync as Hr}from"child_process";import{existsSync as bw}from"fs";function vw(e){return!(!e||typeof e!="object")}function Rw(e){try{return Hr("git",["-C",e,"branch","--list","agent/*"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
86
+ `).map(r=>r.replace(/^\*?\s+/,"").trim()).filter(Boolean)}catch{return[]}}function Aw(e,t,r){try{let n=Hr("git",["-C",e,"merge-base",t,r],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=Hr("git",["-C",e,"rev-parse",t],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return n===o}catch{return!1}}function Tw(e,t,r){try{let n=Hr("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 Mw(e,t){if(k){for(let r of k.listPersistedSessions())if(r.worktreeBranch===t&&r.worktreePrUrl&&r.worktreeMerged!==!0)return{number:r.worktreePrNumber??0,url:r.worktreePrUrl}}if(Pt())try{let r=Hr("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 Cm(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)"})),dismiss_session:g.Optional(g.Boolean({description:"When true and session is provided, permanently dismiss the worktree \u2014 deletes the branch and worktree directory. Irreversible. (default: false)"}))}),async execute(t,r){if(!vw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, skip_session_check?, force?, dry_run?, session? }."}]};let n=r.session,o=r.dismiss_session===!0;if(n&&o&&k)return{content:[{type:"text",text:await k.dismissWorktree(n)}]};if(n&&k){let I=Vr(k,n);if(I.persistedSession)for(let v of Ii(I))k.updatePersistedSession(v,{pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0})}let i=r.workdir||process.cwd(),s=r.base_branch??gt(i),a=r.skip_session_check===!0||r.force===!0,d=r.dry_run===!0;if(!bw(i))return{content:[{type:"text",text:`Error: Working directory does not exist: ${i}`}]};try{Hr("git",["-C",i,"rev-parse","--git-dir"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{return{content:[{type:"text",text:`Error: ${i} is not a git repository`}]}}let c=Rw(i);if(c.length===0)return{content:[{type:"text",text:"No agent/* branches found."}]};let h=new Set,m=new Map;if(k){for(let I of k.list())if(I.status==="starting"||I.status==="running"){let v=I.worktreeBranch;v&&(h.add(v),m.set(v,`${I.name} is ${I.status}`))}}let S=[],y=[],x=[],$=[];for(let I of c){if(!a&&h.has(I)){let v=m.get(I)??"unknown";x.push(`${I} (session: ${v})`);continue}if(Aw(i,I,s))S.push(I);else{let v=Mw(i,I);if(v)$.push({branch:I,prNumber:v.number,prUrl:v.url});else{let de=Tw(i,I,s);y.push({branch:I,commitsAhead:de})}}}let re=(I,v)=>{let de=["agent/* branch status:"],yr=d?"WOULD DELETE":"DELETED",qn=(d?S:I).join(", ")||"(none)",Vn=v.length>0?`; ${v.length} failed: ${v.join(", ")}`:"";de.push(` ${yr} (${d?S.length:I.length}): ${qn}${Vn}`);let C=y.length>0?y.map(({branch:G,commitsAhead:ye})=>ye>0?`${G} [${ye} commit${ye!==1?"s":""} ahead]`:G).join(", "):"(none)";de.push(` KEPT \u2013 unmerged (${y.length}): ${C}`);let A=x.length>0?x.join(", "):"(none)";de.push(` KEPT \u2013 active session (${x.length}): ${A}`);let _=$.length>0?$.map(({branch:G,prNumber:ye,prUrl:ne})=>ye>0?`${G} [PR #${ye}]`:`${G} [open PR]`).join(", "):"(none)";return de.push(` KEPT \u2013 open PR (${$.length}): ${_}`),de.join(`
87
+ `)};if(d)return{content:[{type:"text",text:re([],[])}]};let R=[],W=[];for(let I of S)bt(i,I)?R.push(I):W.push(I);return{content:[{type:"text",text:re(R,W)}]}}}}nt();he();Qe();Wn();import{existsSync as Cw}from"fs";function Ew(e){return!0}function Em(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(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Ew(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let n=r.session,o=[],i=Tm(k);if(n&&(i=i.filter(c=>nd(c,n)),i.length===0))return{content:[{type:"text",text:`Error: Session "${n}" not found or has no worktree.`}]};if(i.length===0)return{content:[{type:"text",text:"No sessions with worktrees found."}]};let a=k.listPersistedSessions().filter(c=>c.pendingWorktreeDecisionSince&&!c.worktreeMerged&&!c.worktreePrUrl),d=n?a.filter(c=>nd({id:c.sessionId??c.name??c.harnessSessionId,name:c.name,backendConversationId:c.backendRef?.conversationId,harnessSessionId:c.harnessSessionId},n)):a;if(d.length>0){o.push(`\u23F3 Pending decisions (${d.length}):`),o.push("");for(let c of d){let h=new Date(c.pendingWorktreeDecisionSince),m=Date.now()-h.getTime(),S=Math.floor(m/(3600*1e3)),y=Math.floor(S/24),x=S%24,$=Math.floor(m%(3600*1e3)/6e4),re=y>0?`${y}d ${x}h`:S>0?`${S}h ${$}m`:`${$}m`,R=gt(c.workdir);o.push(`\u2022 ${c.name.padEnd(14)} ${(c.worktreeBranch??"?").padEnd(30)} \u2192 ${R.padEnd(10)} pending ${re}`)}if(o.push(""),d.length===1){let c=d[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 i){let h=c.worktreeBranch;if(!h){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 m=gt(c.workdir),S=Cw(c.workdir);if(o.push(`Session: ${c.name} [${c.id}]`),o.push(` Branch: ${h} \u2192 ${m}`),o.push(` Repo: ${c.workdir}`),c.worktreeStrategy&&o.push(` Strategy: ${c.worktreeStrategy}`),S)try{if(Dn(c.workdir,h,m)){let x=Ft(c.workdir,h,m);x?o.push(` Commits: ${x.commits} ahead of ${m} (+${x.insertions} / -${x.deletions})`):o.push(` Commits: ahead of ${m}`)}else o.push(` Commits: even with ${m}`)}catch{o.push(" Commits: (unable to check)")}else o.push(" Commits: (repo no longer exists)");if(c.worktreeMerged){let y=c.worktreeMergedAt?new Date(c.worktreeMergedAt).toLocaleString():"unknown";o.push(` Merged: Yes (${y})`)}else c.worktreePrUrl?o.push(` PR: ${c.worktreePrUrl}`):o.push(" Merged: No");o.push("")}return{content:[{type:"text",text:o.join(`
88
+ `).trim()}]}}}}he();Pi();var Gr="code-agent";function $w(e){let t=e.trim().replace(new RegExp(`^${Gr}:`),"");return t||null}async function bi(e,t){if(typeof e.respond.editMessage=="function")try{await e.respond.editMessage({text:t,buttons:[]});return}catch(r){let n=r instanceof Error?r.message:String(r);/message is not modified/i.test(n)||console.warn(`[callback-handler] Failed to edit worktree prompt: ${n}`)}await e.respond.clearButtons()}function id(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 Ow(e){return e==="plan-approve"||e==="plan-request-changes"||e==="plan-reject"}function _w(e,t){if(Ow(e.kind)){if(!t)return"This plan decision is stale because the session is no longer available.";if(e.planDecisionVersion!=null&&t.planDecisionVersion!=null&&e.planDecisionVersion!==t.planDecisionVersion)return"This plan decision is stale because a newer plan review state already exists.";if(!t.pendingPlanApproval)return"This plan is no longer awaiting approval.";if(e.kind==="plan-approve"&&t.approvalState==="changes_requested")return"Changes were already requested for this plan. Wait for the revised plan before approving.";if(e.kind==="plan-request-changes"&&t.approvalState==="changes_requested")return"Changes were already requested for this plan. Send your feedback to the agent instead."}}function sd(e="telegram"){return{channel:e,namespace:Gr,handler:async t=>{if(!t.auth.isAuthorizedSender)return await t.respond.reply({text:"\u26D4 Unauthorized."}),{handled:!0};let r=$w(t.callback.payload);if(!r)return await t.respond.reply({text:`\u26A0\uFE0F Unrecognized callback payload: "${t.callback.payload}".`}),{handled:!0};if(!k)return await t.respond.reply({text:"\u26A0\uFE0F Code agent service not running."}),{handled:!0};let n=k.consumeActionToken(r);if(!n)return await t.respond.reply({text:"\u26A0\uFE0F This action is stale or has already been used."}),{handled:!0};let o=n.sessionId,i=k.resolve?.(o)??k.getPersistedSession?.(o),s=i?.name??o,a=_w(n,i);if(a)return await t.respond.clearButtons(),await t.respond.reply({text:`\u26A0\uFE0F ${a}`}),{handled:!0};switch(n.kind){case"worktree-merge":{await bi(t,`\u2705 Merge selected for [${s}]`);let d=await xi().execute("callback",{session:o});await t.respond.reply({text:id(d)});break}case"worktree-decide-later":{await bi(t,`\u23ED\uFE0F Deferred for [${s}]`);let d=k.snoozeWorktreeDecision(o);await t.respond.reply({text:d.startsWith("Error")?d:"\u23ED\uFE0F Snoozed 24h"});break}case"worktree-dismiss":{await bi(t,`\u{1F5D1}\uFE0F Discarded for [${s}]`);let d=await k.dismissWorktree(o);await t.respond.reply({text:(d.startsWith("Error"),d)});break}case"worktree-create-pr":case"worktree-update-pr":{await bi(t,n.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${s}]`:`\u{1F4EC} PR selected for [${s}]`);let d=await Bn().execute("callback",{session:o});await t.respond.reply({text:id(d)});break}case"worktree-view-pr":{await t.respond.clearButtons();let d=k.getPersistedSession?.(o),c=n.targetUrl??d?.worktreePrUrl;await t.respond.reply({text:c?`PR: ${c}`:"\u26A0\uFE0F PR URL is no longer available."});break}case"plan-approve":{await t.respond.clearButtons();let d=await kr(k,{session:o,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});d.isError&&await t.respond.reply({text:`\u26A0\uFE0F ${d.text}`});break}case"plan-reject":{await t.respond.clearButtons();let d=k.resolve(o);if(d)d.approvalState="rejected",k.kill(d.id,"user"),await t.respond.reply({text:`\u274C Plan rejected for [${d.name}]. Session stopped.`});else{let c=k.getPersistedSession?.(o);c?(k.updatePersistedSession?.(o,{approvalState:"rejected",lifecycle:"terminal",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:(c.planDecisionVersion??0)+1}),await t.respond.reply({text:`\u274C Plan rejected for [${c.name??s}]. Session remains stopped.`})):await t.respond.reply({text:"\u274C Plan rejected."})}break}case"plan-request-changes":{await t.respond.clearButtons();let d=k.resolve?.(o),c=k.getPersistedSession?.(o),h=d?.name??c?.name??o,m=(d?.planDecisionVersion??c?.planDecisionVersion??0)+1;k.updatePersistedSession(o,{approvalState:"changes_requested",lifecycle:"awaiting_plan_decision",pendingPlanApproval:!0,planDecisionVersion:m}),await t.respond.reply({text:`\u270F\uFE0F Type your revision feedback for [${h}] and I'll forward it to the agent.`});break}case"session-restart":case"session-resume":{await t.respond.clearButtons();let d=await kr(k,{session:o,message:"Continue where you left off.",userInitiated:!0});await t.respond.reply({text:d.isError?`\u26A0\uFE0F ${d.text}`:`\u25B6\uFE0F ${d.text}`});break}case"view-output":{await t.respond.clearButtons();let d=await wi().execute("callback",{session:o,lines:50});await t.respond.reply({text:id(d)});break}case"question-answer":{if(await t.respond.clearButtons(),n.optionIndex==null){await t.respond.reply({text:"\u26A0\uFE0F Invalid question-answer action."});break}await k.resolvePendingInputOption(o,n.optionIndex),await t.respond.reply({text:"\u2705 Answer submitted."});break}default:{await t.respond.clearButtons(),await t.respond.reply({text:"\u26A0\uFE0F Unknown callback action."});break}}return{handled:!0}}}}he();Le();function Nw(e){return e instanceof Error?e.message:String(e)}function $m(e){e.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!k)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 i=r;if(!i)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let s=De(),a=Wr(s);if(!a)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 d=k.spawn({prompt:i,name:n,workdir:E.defaultWorkdir||process.cwd(),model:a,reasoningEffort:Jt(s),codexApprovalPolicy:s==="codex"?"never":void 0,originChannel:An(t),originThreadId:Tn(t),route:Bo(t),harness:s}),c=i.length>80?i.slice(0,80)+"...":i;return{text:["Session launched.",` Name: ${d.name}`,` ID: ${d.id}`,` Prompt: "${c}"`,` Status: ${d.status}`].join(`
89
+ `)}}catch(s){let a=Nw(s),d=a.includes("Max sessions")?"":`
90
+
91
+ Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${d}`}}}})}he();function Om(e){e.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").split(/\s+/).includes("--full");return{text:ki(k,"all",void 0,{full:r})}}})}he();function _m(e){e.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=t.args?.trim();return r?{text:yi(k,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}he();function Nm(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(!k)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>
92
+ /agent_respond --interrupt <id-or-name> <message>`};let n=!1,o=r;o.startsWith("--interrupt ")&&(n=!0,o=o.slice(12).trim());let i=o.indexOf(" ");if(i===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let s=o.slice(0,i),a=o.slice(i+1).trim();return a?{text:(await kr(k,{session:s,message:a,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}he();function Fm(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=k.getMetrics(),r=k.list("running").length;return{text:hi(t,r)}}})}he();var Fw=50;function Dm(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(!k)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="",i=!1,s=Fw;for(let d=0;d<n.length;d++)if(n[d]==="--full")i=!0;else if(n[d]==="--lines"&&d+1<n.length){let c=parseInt(n[d+1],10);!isNaN(c)&&c>0&&(s=c),d++}else o||(o=n[d]);return o?{text:Si(k,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}Le();import{existsSync as Dw,realpathSync as Lw}from"fs";import{resolve as Uw}from"path";function Lm(e){if(!e)return;let t=Uw(e);try{if(Dw(t))return Lw.native(t)}catch{}return t}function vi(e,t){return!e||!t?!1:Lm(e)===Lm(t)}ke();Le();import{existsSync as Ww}from"fs";ke();Qe();function Um(e){return e instanceof Error?e.message:String(e)}function Bw(e){let t=e.worktreeStrategy??E.defaultWorktreeStrategy;return!!t&&t!=="off"&&Ga(Zo({harnessName:e.harness??De(),backendRef:e.backendRef}))}function Kw(e,t,r,n){let o=["","You are working in a git worktree.",`Worktree path: ${r}`,`Branch: ${n}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${r}.`,`Do NOT edit files directly in ${t} (the original workspace).`,`If your task references files by absolute path under ${t}, rewrite those`,"paths relative to your current working directory. For example:",` "${t}/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.","","When making changes, please note:","- Do NOT commit planning documents, investigation notes, or analysis artifacts to this branch","- Only commit actual code, configuration, tests, and documentation changes that were explicitly requested as part of the task"].join(`
93
+ `);return(e??"")+o}function jw(e,t){let r=e.resumeSessionId??e.resumeWorktreeFrom;if(!r)return{};let n=t(r);if(!n)return{};let o=(()=>{if(n.workdir&&n.workdir!==n.worktreePath)return n.workdir;if(n.worktreePath){let s=si(n.worktreePath);return n.workdir&&s&&vi(n.workdir,s)?n.workdir:s??n.workdir}return n.workdir})();if(!e.worktreeStrategy&&n.worktreeStrategy&&(e.worktreeStrategy=n.worktreeStrategy),!e.planApproval&&n.planApproval&&(e.planApproval=n.planApproval),!n.worktreePath)return{};if(!n.worktreeBranch)throw new Error(`Cannot resume session "${r}": persisted worktree metadata is missing worktreeBranch.`);let i=Wl(Zo({persistedHarness:n.harness,backendRef:n.backendRef}))&&!!n.backendRef?.worktreePath;if(Ww(n.worktreePath))return console.info(`[SessionManager] Resuming with existing worktree: ${n.worktreePath}`),{actualWorkdir:n.worktreePath,originalWorkdir:o??n.worktreePath,worktreePath:n.worktreePath,worktreeBranchName:n.worktreeBranch};if(!o)return console.warn(`[SessionManager] Worktree ${n.worktreePath} no longer exists and cannot be recreated, using original workdir`),{clearedResumeSessionId:!!e.resumeSessionId,clearedResumeWorktreeFrom:!!e.resumeWorktreeFrom};if(i)return console.info(`[SessionManager] Native Codex worktree ${n.worktreePath} is missing; resuming from original workdir and letting the backend restore thread state.`),{actualWorkdir:o,originalWorkdir:o,worktreeBranchName:n.worktreeBranch,clearedResumeWorktreeFrom:!!e.resumeWorktreeFrom};try{ui(o);let s=Xa(o,n.worktreeBranch.replace(/^agent\//,""));return console.info(`[SessionManager] Recreated worktree from branch ${n.worktreeBranch}: ${s}`),{actualWorkdir:s,originalWorkdir:o,worktreePath:s,worktreeBranchName:n.worktreeBranch}}catch(s){return console.warn(`[SessionManager] Failed to recreate worktree for resume: ${Um(s)}, using original workdir`),{actualWorkdir:o,originalWorkdir:o,clearedResumeSessionId:!!e.resumeSessionId,clearedResumeWorktreeFrom:!!e.resumeWorktreeFrom}}}function Wm(e,t,r){let{actualWorkdir:n,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}=jw(e,r);a&&(e.resumeSessionId=void 0),d&&(e.resumeWorktreeFrom=void 0),n??=e.workdir,o??=e.workdir;let c=!!(e.resumeSessionId??e.resumeWorktreeFrom),h=e.worktreeStrategy??E.defaultWorktreeStrategy;h&&(e.worktreeStrategy=h);let m=Bw(e),S=!e.resumeSessionId&&!i&&h&&h!=="off"&&!m;if(m&&!Ya(o))throw new Error(`Cannot launch session "${t}": worktree strategy "${h}" requires a git worktree, but "${o}" is not a git repository.`);if(S&&Ya(o)){if(!nm())throw new Error(`Cannot launch session "${t}": insufficient space for worktree creation.`);try{if(i=Xa(o,t),n=i,s=ai(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);console.log(`[SessionManager] Created worktree at ${i}`)}catch(y){throw new Error(`Cannot launch session "${t}": worktree creation failed: ${Um(y)}`)}}else if(S)throw new Error(`Cannot launch session "${t}": worktree strategy "${h}" requires a git worktree, but "${o}" is not a git repository.`);return c&&i&&(n=i),{actualWorkdir:n,originalWorkdir:o,effectiveSystemPrompt:i&&s?Kw(e.systemPrompt,o,i,s):e.systemPrompt,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}}var Ri=class{constructor(t){this.getPersistedSession=t}prepareSpawn(t,r){return Wm(t,r,this.getPersistedSession)}hydrateSpawnedSession(t,r,n){n.worktreeStrategy&&n.worktreeStrategy!=="off"&&(t.originalWorkdir=r.originalWorkdir),r.worktreePath&&(t.worktreePath=r.worktreePath,t.worktreeBranch=r.worktreeBranchName,t.worktreeState="provisioned"),n.worktreePrTargetRepo&&(t.worktreePrTargetRepo=n.worktreePrTargetRepo)}};ke();var Ai=class{constructor(t){this.deps=t}applySessionPatch(t,r){let n=this.deps.store.getPersistedSession(t);n&&(Object.assign(n,r),this.deps.store.assertPersistedEntry(n));let o=this.findActiveSessionForRef(t,n);return o&&this.applyPatchToActiveSession(o,r),!n&&!o?!1:(n&&this.deps.store.saveIndex(),!0)}matchesExistingSession(t,r){if(!r)return!1;let n=T(t),o=T(r);return!!(r.sessionId&&t.id===r.sessionId||o&&o===n||r?.harnessSessionId&&t.harnessSessionId===r.harnessSessionId||r?.name&&t.name===r.name)}findActiveSessionForRef(t,r){let n=this.deps.resolveSession(t);if(n)return n;for(let o of this.deps.sessions.values())if(ee(o)===t||T(o)===t||o.harnessSessionId===t||this.matchesExistingSession(o,r))return o}applyPatchToActiveSession(t,r){typeof t.applyControlPatch=="function"?t.applyControlPatch({lifecycle:r.lifecycle,approvalState:r.approvalState,worktreeState:r.worktreeState,runtimeState:r.runtimeState,deliveryState:r.deliveryState,pendingPlanApproval:r.pendingPlanApproval,planApprovalContext:r.planApprovalContext,planDecisionVersion:r.planDecisionVersion,canonicalPlanPromptVersion:r.canonicalPlanPromptVersion,pendingWorktreeDecisionSince:r.pendingWorktreeDecisionSince}):(r.lifecycle!==void 0&&(t.lifecycle=r.lifecycle),r.approvalState!==void 0&&(t.approvalState=r.approvalState),r.worktreeState!==void 0&&(t.worktreeState=r.worktreeState),r.runtimeState!==void 0&&(t.runtimeState=r.runtimeState),r.deliveryState!==void 0&&(t.deliveryState=r.deliveryState),r.pendingPlanApproval!==void 0&&(t.pendingPlanApproval=r.pendingPlanApproval),r.planApprovalContext!==void 0&&(t.planApprovalContext=r.planApprovalContext),r.planDecisionVersion!==void 0&&(t.planDecisionVersion=r.planDecisionVersion),r.canonicalPlanPromptVersion!==void 0&&(t.canonicalPlanPromptVersion=r.canonicalPlanPromptVersion)),r.worktreePath!==void 0&&(t.worktreePath=r.worktreePath),r.worktreeBranch!==void 0&&(t.worktreeBranch=r.worktreeBranch),r.worktreePrUrl!==void 0&&(t.worktreePrUrl=r.worktreePrUrl),r.worktreePrNumber!==void 0&&(t.worktreePrNumber=r.worktreePrNumber),r.worktreeMerged!==void 0&&(t.worktreeMerged=r.worktreeMerged),r.worktreeMergedAt!==void 0&&(t.worktreeMergedAt=r.worktreeMergedAt),r.worktreeDisposition!==void 0&&(t.worktreeDisposition=r.worktreeDisposition),r.worktreePrTargetRepo!==void 0&&(t.worktreePrTargetRepo=r.worktreePrTargetRepo),r.worktreePushRemote!==void 0&&(t.worktreePushRemote=r.worktreePushRemote)}};ke();var qw=new Set(["starting","running"]),Ti=class{constructor(t,r){this.sessions=t;this.store=r}resolveActive(t){let r=this.sessions.get(t);if(r)return r;let n=[...this.sessions.values()],o=n.filter(a=>a.name===t);if(o.length>0)return this.pickPreferredSession(o);let i=n.filter(a=>T(a)===t);if(i.length>0)return this.pickPreferredSession(i);let s=n.filter(a=>a.harnessSessionId===t);if(s.length>0)return this.pickPreferredSession(s)}getPersistedSession(t){return this.store.getPersistedSession(t)}resolveBackendConversationId(t){let r=this.resolveActive(t);return this.store.resolveBackendConversationId(t,r?T(r)??r.harnessSessionId:void 0)}pickPreferredSession(t){let r=t.filter(o=>qw.has(o.status));return(r.length>0?r:t).sort((o,i)=>i.startedAt-o.startedAt)[0]}};ke();ke();Qe();var Mi=class{constructor(t){this.deps=t}async plan(t){let r=ee(t)??t.harnessSessionId;if(this.deps.isAlreadyMerged(r))return console.info(`[SessionManager] handleWorktreeStrategy: session "${t.name}" already merged \u2014 skipping strategy handling`),{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};if(t.status!=="completed")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};if(!this.deps.shouldRunWorktreeStrategy(t))return console.info(`[SessionManager] handleWorktreeStrategy: skipping \u2014 session "${t.name}" is in phase "${t.phase}"`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let n=t.worktreeStrategy;if(!n||n==="off"||n==="manual")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let o=t.worktreePath,i=this.deps.resolveWorktreeRepoDir(t.originalWorkdir,o),s=t.worktreeBranch;if(!i)return{kind:"notify",label:"worktree-missing-repo-dir",message:`\u26A0\uFE0F [${t.name}] Cannot determine the original repo for worktree ${o}. Manual inspection is required.`};if(!s)return{kind:"notify",label:"worktree-no-branch-name",message:`\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.`};let a=t.worktreeBaseBranch??gt(i),d=this.deps.getWorktreeCompletionState(i,o,s,a);if(d==="no-change")return{kind:"no-change",repoDir:i,worktreePath:o,nativeBackendWorktree:ot(t)};if(d==="base-advanced")return{kind:"notify",label:"worktree-no-commits-ahead",message:`\u26A0\uFE0F [${t.name}] Auto-merge: branch '${s}' has no commits ahead of '${a}', but '${a}' has new commits \u2014 commits likely landed outside the worktree branch. Verify that commits were not made directly to '${a}' instead of the worktree branch. Worktree: ${o}`};if(d==="dirty-uncommitted")return{kind:"notify",label:"worktree-dirty-uncommitted",message:`\u26A0\uFE0F [${t.name}] Session completed with uncommitted changes. The branch has no commits ahead of '${a}' but there are modified tracked files in the worktree. Check: ${o}`};let c=Ft(i,s,a);return c?{kind:"decision",strategy:n,repoDir:i,worktreePath:o,branchName:s,baseBranch:a,diffSummary:c,sessionRef:r??void 0}:(console.warn(`[SessionManager] Failed to get diff summary for ${s}, skipping merge-back`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}})}};Qe();var Ci=class{constructor(t){this.deps=t;this.actions=new Mi({shouldRunWorktreeStrategy:t.shouldRunWorktreeStrategy,isAlreadyMerged:t.isAlreadyMerged,resolveWorktreeRepoDir:t.resolveWorktreeRepoDir,getWorktreeCompletionState:t.getWorktreeCompletionState})}actions;updatePersistedSessionFor(t,r){for(let n of ze(t))this.deps.updatePersistedSession(n,r)}async handleWorktreeStrategy(t){let r=await this.actions.plan(t);return r.kind==="skip"?r.result:r.kind==="notify"?(this.deps.dispatchSessionNotification(t,{label:r.label,userMessage:r.message}),{notificationSent:!0,worktreeRemoved:!1}):r.kind==="no-change"?this.handleNoChange(t,r.repoDir,r.worktreePath,r.nativeBackendWorktree):r.strategy==="ask"?this.handleAskStrategy(t,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="delegate"?this.handleDelegateStrategy(t,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="auto-merge"?(await this.handleAutoMergeStrategy(t,r.repoDir,r.worktreePath,r.branchName,r.baseBranch,r.diffSummary,r.sessionRef),{notificationSent:!0,worktreeRemoved:!1}):r.strategy==="auto-pr"?this.handleAutoPrStrategy(t,r.baseBranch):{notificationSent:!1,worktreeRemoved:!1}}async handleNoChange(t,r,n,o=ot(t)){let i=o?!0:ht(r,n);return i?(t.worktreePath=void 0,this.updatePersistedSessionFor(t,{worktreePath:void 0,worktreeDisposition:"no-change-cleaned",worktreeState:"none"}),this.deps.dispatchSessionNotification(t,this.deps.worktreeMessages.buildNoChangeNotification({session:t,nativeBackendWorktree:o,cleanupSucceeded:!0,worktreePath:n,preview:this.deps.getOutputPreview(t),originThreadLine:this.deps.originThreadLine(t)}))):this.deps.dispatchSessionNotification(t,this.deps.worktreeMessages.buildNoChangeNotification({session:t,nativeBackendWorktree:o,cleanupSucceeded:!1,worktreePath:n,preview:this.deps.getOutputPreview(t),originThreadLine:this.deps.originThreadLine(t)})),{notificationSent:!0,worktreeRemoved:i}}handleAskStrategy(t,r,n,o){return this.deps.dispatchSessionNotification(t,this.deps.worktreeMessages.buildAskNotification({session:t,branchName:r,baseBranch:n,diffSummary:o,buttons:this.deps.getWorktreeDecisionButtons(t.id)})),this.updatePersistedSessionFor(t,{pendingWorktreeDecisionSince:new Date().toISOString(),lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"}),{notificationSent:!0,worktreeRemoved:!1}}handleDelegateStrategy(t,r,n,o){return this.deps.dispatchSessionNotification(t,this.deps.worktreeMessages.buildDelegateNotification({session:t,branchName:r,baseBranch:n,diffSummary:o})),this.updatePersistedSessionFor(t,{pendingWorktreeDecisionSince:new Date().toISOString(),lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"}),{notificationSent:!0,worktreeRemoved:!1}}async handleAutoMergeStrategy(t,r,n,o,i,s,a=ee(t)??t.harnessSessionId){this.deps.isAlreadyMerged(a)||await this.deps.enqueueMerge(r,async()=>{if(this.deps.isAlreadyMerged(a))return;let d=li(r,o,i,"merge",n);if(d.success){bt(r,o),this.updatePersistedSessionFor(t,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0});let m=gr({kind:"merge",branch:o,base:i,filesChanged:s.filesChanged,insertions:s.insertions,deletions:s.deletions});d.stashPopConflict?m+=`
94
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${d.stashRef??"stash@{0}"}\` in ${r} to review stashed changes.`:d.stashed&&(m+=`
95
+ (Pre-existing changes on ${i} were auto-stashed and restored.)`),this.deps.dispatchSessionNotification(t,{label:"worktree-merge-success",userMessage:m});return}if(d.conflictFiles&&d.conflictFiles.length>0){let h=["Resolve merge conflicts in the following files and commit the resolution:","",...d.conflictFiles.map(m=>`- ${m}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${o}"`].join(`
96
+ `);try{await this.deps.spawnConflictResolver(t,r,h),this.deps.dispatchSessionNotification(t,{label:"worktree-merge-conflict",userMessage:`\u26A0\uFE0F [${t.name}] Merge conflicts in ${d.conflictFiles.length} file(s) \u2014 spawned conflict resolver session`,buttons:[[this.deps.makeOpenPrButton(t.id)]]})}catch(m){this.deps.dispatchSessionNotification(t,{label:"worktree-merge-conflict-spawn-failed",userMessage:`\u274C [${t.name}] Merge conflicts detected, but failed to spawn resolver: ${m instanceof Error?m.message:String(m)}`})}return}let c=d.dirtyError?`\u274C [${t.name}] Merge blocked: ${d.error}`:`\u274C [${t.name}] Merge failed: ${d.error??"unknown error"}`;this.deps.dispatchSessionNotification(t,{label:"worktree-merge-error",userMessage:c})},()=>{this.deps.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.`})})}async handleAutoPrStrategy(t,r){return this.updatePersistedSessionFor(t,{lifecycle:"terminal",worktreeState:"pr_in_progress"}),(await this.deps.runAutoPr(t,r)).success||this.updatePersistedSessionFor(t,{pendingWorktreeDecisionSince:new Date().toISOString(),lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"}),{notificationSent:!0,worktreeRemoved:!1}}};import{existsSync as kI,writeFileSync as yI}from"fs";vn();import{randomUUID as Vw}from"crypto";var Ei=class{constructor(t,r){this.onChange=t;this.retentionMs=r}tokens=new Map;replaceAll(t){this.tokens.clear();for(let r of t)this.tokens.set(r.id,r)}clear(){this.tokens.clear()}listForPersistence(){return[...this.tokens.values()]}createActionToken(t,r,n={}){let o={id:Vw(),sessionId:t,kind:r,createdAt:Date.now(),...n};return this.tokens.set(o.id,o),this.onChange(),o}getActionToken(t){let r=this.tokens.get(t);if(r){if(r.expiresAt!=null&&r.expiresAt<=Date.now()){this.tokens.delete(t),this.onChange();return}return r}}consumeActionToken(t){let r=this.getActionToken(t);if(!(!r||r.consumedAt!=null))return r.consumedAt=Date.now(),this.onChange(),r}deleteActionTokensForSession(t){let r=!1;for(let[n,o]of this.tokens)o.sessionId===t&&(this.tokens.delete(n),r=!0);r&&this.onChange()}purgeExpiredActionTokens(t=Date.now()){let r=!1;for(let[n,o]of this.tokens){let i=o.expiresAt!=null&&o.expiresAt<=t,s=o.consumedAt!=null&&t-o.consumedAt>this.retentionMs;(i||s)&&(this.tokens.delete(n),r=!0)}r&&this.onChange()}};ke();ke();var $i=class{constructor(t){this.indexes=t}hasRecordedSession(t){return this.indexes.idIndex.has(t)}getLatestPersistedByName(t){let r,n=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=0;for(let a of this.indexes.persisted.values()){if(a.name!==t){s++;continue}let d=a.createdAt??Number.NEGATIVE_INFINITY,c=a.completedAt??Number.NEGATIVE_INFINITY;(d>n||d===n&&c>o||d===n&&c===o&&s>i)&&(r=a,n=d,o=c,i=s),s++}return r}resolveBackendConversationId(t,r){if(r)return r;let n=this.indexes.idIndex.get(t);if(n){let s=this.indexes.persisted.get(n);return(s?T(s):void 0)??n}let o=this.getLatestPersistedByName(t);if(o)return T(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(t);if(i){let s=this.indexes.persisted.get(i);return(s?T(s):void 0)??i}if(this.indexes.persisted.has(t)){let s=this.indexes.persisted.get(t);return s?T(s)??t:t}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return t}resolveHarnessSessionId(t,r){return this.resolveBackendConversationId(t,r)}getPersistedSession(t){let r=this.indexes.idIndex.get(t);if(r)return this.indexes.persisted.get(r);let n=this.getLatestPersistedByName(t);if(n)return n;let o=this.indexes.backendIdIndex.get(t);return o?this.indexes.persisted.get(o):this.indexes.persisted.get(t)}listPersistedSessions(){return[...this.indexes.persisted.values()].sort((t,r)=>(r.completedAt??0)-(t.completedAt??0))}};import{existsSync as uI,mkdirSync as pI,readFileSync as cI,readdirSync as lI,renameSync as Hm,statSync as mI,unlinkSync as fI,writeFileSync as Gm}from"fs";import{tmpdir as gI}from"os";import{dirname as hI,join as zm}from"path";import{homedir as Hw}from"node:os";import{join as Gw}from"node:path";function Bm(e){let t=e.OPENCLAW_HOME?.trim();if(t)return t;let r=e.HOME?.trim()||Hw();return Gw(r,".openclaw")}vn();var Oi=6,zw=new Set(["running","completed","failed","killed"]);function _i(e){return!!e&&typeof e=="object"}function zr(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function K(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function vt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Qw(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function Km(e){return e==="default"||e==="plan"||e==="bypassPermissions"?e:void 0}function Jw(e){return e==="never"||e==="on-request"?"never":void 0}function Yw(e){return e==="approve"||e==="ask"||e==="delegate"?e:void 0}function Xw(e){if(e==="plan-mode"||e==="codex-first-turn-plan"||e==="soft-plan")return"plan-mode"}function Zw(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function jm(e){return e==="starting"||e==="active"||e==="awaiting_plan_decision"||e==="awaiting_user_input"||e==="awaiting_worktree_decision"||e==="suspended"||e==="terminal"?e:void 0}function eI(e){return e==="not_required"||e==="pending"||e==="approved"||e==="changes_requested"||e==="rejected"?e:void 0}function tI(e){return e==="none"||e==="provisioned"||e==="pending_decision"||e==="merge_in_progress"||e==="pr_in_progress"||e==="merged"||e==="pr_open"||e==="dismissed"||e==="cleanup_failed"?e:void 0}function rI(e){return e==="live"||e==="stopped"?e:void 0}function nI(e){return e==="idle"||e==="notifying"||e==="wake_pending"||e==="failed"?e:void 0}function oI(e){return e==="awaiting_approval"||e==="approved_then_implemented"||e==="implemented_without_required_approval"||e==="not_plan_gated"?e:void 0}function iI(e){return e==="plan-approve"||e==="plan-request-changes"||e==="plan-reject"||e==="worktree-merge"||e==="worktree-create-pr"||e==="worktree-update-pr"||e==="worktree-view-pr"||e==="worktree-decide-later"||e==="worktree-dismiss"||e==="session-resume"||e==="session-restart"||e==="view-output"||e==="question-answer"?e:void 0}function sI(e){if(!_i(e))return;let t=K(e.provider),r=K(e.accountId),n=K(e.target),o=K(e.threadId),i=K(e.sessionKey);if(!(!t||!n))return{provider:t,accountId:r,target:n,threadId:o,sessionKey:i}}function aI(e,t,r){if(_i(e)){let n=K(e.kind),o=K(e.conversationId);if(o&&(n==="claude-code"||n==="codex-app-server"))return{kind:n,conversationId:o,runId:K(e.runId),worktreeId:K(e.worktreeId),worktreePath:K(e.worktreePath)}}if(t==="claude-code")return{kind:"claude-code",conversationId:r}}function dI(e){if(typeof e=="string"&&zw.has(e))return e==="running"?"killed":e}function qm(e){if(!_i(e))return;let t=zr(e.harnessSessionId);if(!t)return;let r=dI(e.status);if(!r)return;let n=e.status==="running",o=K(e.worktreePath),i=K(e.worktreeBranch),s=K(e.originChannel),a=typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,d=K(e.originSessionKey),c=sI(e.route);if(!c)return;let h=Ur({route:c,originChannel:s,originThreadId:a,originSessionKey:d});if(!h||o&&!i)return;let m=K(e.harness),S=aI(e.backendRef,m,t);return{sessionId:K(e.sessionId),harnessSessionId:t,backendRef:S,name:zr(e.name,t),prompt:zr(e.prompt),workdir:zr(e.workdir,"(unknown)"),model:K(e.model),reasoningEffort:Qw(e.reasoningEffort),createdAt:vt(e.createdAt),completedAt:vt(e.completedAt),status:r,lifecycle:n?jm(e.lifecycle)??"suspended":jm(e.lifecycle),approvalState:eI(e.approvalState),worktreeState:tI(e.worktreeState),runtimeState:n?"stopped":rI(e.runtimeState),deliveryState:nI(e.deliveryState),killReason:Zw(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:K(e.originAgentId),originChannel:s,originThreadId:a,originSessionKey:d,route:h,outputPath:K(e.outputPath),harness:m,requestedPermissionMode:Km(e.requestedPermissionMode),currentPermissionMode:Km(e.currentPermissionMode),approvalExecutionState:oI(e.approvalExecutionState),planModeApproved:e.planModeApproved===!0,pendingPlanApproval:e.pendingPlanApproval===!0,planApprovalContext:Xw(e.planApprovalContext),planDecisionVersion:vt(e.planDecisionVersion),canonicalPlanPromptVersion:vt(e.canonicalPlanPromptVersion),planApproval:Yw(e.planApproval),codexApprovalPolicy:Jw(e.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:e.worktreeStrategy==="off"||e.worktreeStrategy==="manual"||e.worktreeStrategy==="ask"||e.worktreeStrategy==="delegate"||e.worktreeStrategy==="auto-merge"||e.worktreeStrategy==="auto-pr"?e.worktreeStrategy:void 0,worktreeMerged:typeof e.worktreeMerged=="boolean"?e.worktreeMerged:void 0,worktreeMergedAt:K(e.worktreeMergedAt),worktreePrUrl:K(e.worktreePrUrl),worktreePrNumber:vt(e.worktreePrNumber),pendingWorktreeDecisionSince:K(e.pendingWorktreeDecisionSince),lastWorktreeReminderAt:K(e.lastWorktreeReminderAt),worktreeBaseBranch:K(e.worktreeBaseBranch),worktreePrTargetRepo:K(e.worktreePrTargetRepo),worktreePushRemote:K(e.worktreePushRemote),worktreeDecisionSnoozedUntil:K(e.worktreeDecisionSnoozedUntil),worktreeDisposition:e.worktreeDisposition==="active"||e.worktreeDisposition==="pr-opened"||e.worktreeDisposition==="merged"||e.worktreeDisposition==="dismissed"||e.worktreeDisposition==="no-change-cleaned"?e.worktreeDisposition:void 0,worktreeDismissedAt:K(e.worktreeDismissedAt),resumable:n?!0:e.resumable===!0}}function Vm(e){if(!_i(e))return;let t=iI(e.kind),r=zr(e.id),n=zr(e.sessionId),o=vt(e.createdAt);if(!(!r||!n||!t||o==null))return{id:r,sessionId:n,kind:t,createdAt:o,planDecisionVersion:vt(e.planDecisionVersion),expiresAt:vt(e.expiresAt),consumedAt:vt(e.consumedAt),optionIndex:vt(e.optionIndex),label:K(e.label),targetUrl:K(e.targetUrl)}}function Ni(e){if(!e.backendRef?.kind||!e.backendRef.conversationId)throw new Error(`Persisted session ${e.harnessSessionId} is missing required backend ref metadata.`);if(!e.route?.provider||!e.route.target)throw new Error(`Persisted session ${e.harnessSessionId} is missing required route metadata.`);if(e.worktreePath&&!e.worktreeBranch)throw new Error(`Persisted session ${e.harnessSessionId} is missing required worktreeBranch metadata.`)}function ad(e){return!!e&&typeof e=="object"}function dd(e){return e instanceof Error?e.message:String(e)}function Qm(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||zm(Bm(e),"code-agent-sessions.json")}function Jm(e,t,r){try{pI(hI(e),{recursive:!0});let n=e+".tmp";Gm(n,JSON.stringify({schemaVersion:Oi,sessions:t,actionTokens:r},null,2),"utf-8"),Hm(n,e)}catch(n){console.warn(`[SessionStore] Failed to save session index: ${dd(n)}`)}}function Fi(e,t){try{if(!uI(e))return;let r=`${e}.legacy-${Date.now()}.json`;Hm(e,r),console.warn(`[SessionStore] Breaking upgrade: archived ${t} session store to ${r}. Legacy sessions are not loaded by this release.`)}catch(r){console.warn(`[SessionStore] Failed to archive legacy session store: ${dd(r)}`)}}function SI(e,t){try{if(t.length===0)return;let r=`${e}.codex-sdk-legacy-${Date.now()}.json`;Gm(r,JSON.stringify(t,null,2),"utf-8"),console.warn(`[SessionStore] Breaking Codex transport upgrade: archived ${t.length} legacy Codex SDK session(s) to ${r}. They are not loaded by the App Server backend.`)}catch(r){console.warn(`[SessionStore] Failed to archive legacy Codex SDK sessions: ${dd(r)}`)}}function Ym(e,t){try{let r=gI(),n=lI(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let i=zm(r,o),s=mI(i).mtimeMs;e-s>t&&fI(i)}catch{}}catch{}}function Xm(e){let{indexPath:t,clearAll:r,indexPersistedEntry:n,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:s}=e;try{let a=cI(t,"utf-8"),d=JSON.parse(a);if(Array.isArray(d)){Fi(t,"legacy array store"),s();return}if(!ad(d)||d.schemaVersion!==Oi&&d.schemaVersion!==4){Fi(t,`schema mismatch (expected v${Oi})`),s();return}let c=Array.isArray(d.sessions)?d.sessions:[],h=[];for(let S of c){if(ad(S)&&S.harness==="codex"){let x=ad(S.backendRef)?S.backendRef:void 0;if((typeof x?.kind=="string"?x.kind:void 0)!=="codex-app-server"){h.push(S);continue}}let y=qm(S);if(!y){r(),Fi(t,"invalid v4 session entry"),s();return}n(y)}h.length>0&&(SI(t,h),s());let m=Array.isArray(d.actionTokens)?d.actionTokens:[];for(let S of m){let y=Vm(S);if(!y){r(),Fi(t,"invalid v4 action token"),s();return}o(y)}i()}catch{}}var wI=new Set(["completed","failed","killed"]),Zm=1440*60*1e3;function II(e){return e instanceof Error?e.message:String(e)}var Di=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;backendIdIndex=new Map;actionTokens;actionTokenStore;indexPath;queries;constructor(t={}){let r=t.env??process.env;this.indexPath=t.indexPath??Qm(r),this.actionTokenStore=new Ei(()=>this.saveIndex(),Zm),this.actionTokens=this.actionTokenStore.tokens,this.queries=new $i({persisted:this.persisted,idIndex:this.idIndex,nameIndex:this.nameIndex,backendIdIndex:this.backendIdIndex}),r.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){Xm({indexPath:this.indexPath,clearAll:()=>{this.persisted.clear(),this.idIndex.clear(),this.nameIndex.clear(),this.backendIdIndex.clear(),this.actionTokenStore.clear()},indexPersistedEntry:t=>this.indexPersistedEntry(t),setActionToken:t=>{this.actionTokens.set(t.id,t)},purgeExpiredActionTokens:()=>this.actionTokenStore.purgeExpiredActionTokens(),saveIndex:()=>this.saveIndex()})}saveIndex(){Jm(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(t){Ni(t)}getEntryStorageKey(t){return t.harnessSessionId}buildPersistedBackendRef(t){return t.backendRef??{kind:Ha(t)==="codex"?"codex-app-server":"claude-code",conversationId:t.harnessSessionId}}indexPersistedEntry(t){let r=this.getEntryStorageKey(t);this.persisted.set(r,t),t.sessionId&&this.idIndex.set(t.sessionId,r),t.name&&this.nameIndex.set(t.name,r);let n=T(t);n&&this.backendIdIndex.set(n,r)}removePersistedIndexes(t){let r=this.getEntryStorageKey(t);this.persisted.delete(r);for(let[n,o]of this.idIndex)o===r&&this.idIndex.delete(n);for(let[n,o]of this.nameIndex)o===r&&this.nameIndex.delete(n);for(let[n,o]of this.backendIdIndex)o===r&&this.backendIdIndex.delete(n)}markRunning(t){if(!t.harnessSessionId)return;let r=typeof t.controlStateSnapshot=="function"?t.controlStateSnapshot():{planModeApproved:!1},n=Ur({route:t.route,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey});if(!n)return;let o={sessionId:t.id,harnessSessionId:t.harnessSessionId,backendRef:this.buildPersistedBackendRef(t),name:t.name,prompt:t.prompt,workdir:t.originalWorkdir??t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",lifecycle:t.lifecycle,approvalState:t.approvalState,worktreeState:t.worktreeState,runtimeState:t.runtimeState,deliveryState:t.deliveryState,costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,route:n,harness:t.harnessName,requestedPermissionMode:t.requestedPermissionMode,currentPermissionMode:t.currentPermissionMode,approvalExecutionState:t.approvalExecutionState,planModeApproved:r.planModeApproved,pendingPlanApproval:t.pendingPlanApproval,planApprovalContext:t.planApprovalContext,planDecisionVersion:t.planDecisionVersion,canonicalPlanPromptVersion:t.canonicalPlanPromptVersion,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch,worktreeStrategy:t.worktreeStrategy,worktreeBaseBranch:t.worktreeBaseBranch,worktreePrTargetRepo:t.worktreePrTargetRepo,resumable:t.isExplicitlyResumable};Ni(o),this.indexPersistedEntry(o),this.saveIndex()}hasRecordedSession(t){return this.queries.hasRecordedSession(t)}persistTerminal(t){if(!t.harnessSessionId)return;let r=typeof t.controlStateSnapshot=="function"?t.controlStateSnapshot():{planModeApproved:!1},n=Ur({route:t.route,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey});if(!n)return;let o;try{let s=qr(t.id);if(kI(s))o=s;else{let a=t.getOutput().join(`
97
+ `);a.length>0&&(yI(s,a,"utf-8"),o=s)}}catch(s){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${II(s)}`)}let i={sessionId:t.id,harnessSessionId:t.harnessSessionId,backendRef:this.buildPersistedBackendRef(t),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,lifecycle:t.lifecycle,approvalState:t.approvalState,worktreeState:t.worktreeState,runtimeState:t.runtimeState,deliveryState:t.deliveryState,killReason:t.killReason,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,route:n,outputPath:o,harness:t.harnessName,requestedPermissionMode:t.requestedPermissionMode,currentPermissionMode:t.currentPermissionMode,approvalExecutionState:t.approvalExecutionState,planModeApproved:r.planModeApproved,pendingPlanApproval:t.pendingPlanApproval,planApprovalContext:t.planApprovalContext,planDecisionVersion:t.planDecisionVersion,canonicalPlanPromptVersion:t.canonicalPlanPromptVersion,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch,worktreeStrategy:t.worktreeStrategy,worktreeBaseBranch:t.worktreeBaseBranch,worktreePrTargetRepo:t.worktreePrTargetRepo,resumable:t.isExplicitlyResumable};Ni(i),this.indexPersistedEntry(i),this.saveIndex()}getLatestPersistedByName(t){return this.queries.getLatestPersistedByName(t)}resolveBackendConversationId(t,r){return this.queries.resolveBackendConversationId(t,r)}resolveHarnessSessionId(t,r){return this.queries.resolveHarnessSessionId(t,r)}getPersistedSession(t){return this.queries.getPersistedSession(t)}listPersistedSessions(){return this.queries.listPersistedSessions()}cleanupTmpOutputFiles(t){this.actionTokenStore.purgeExpiredActionTokens(t),Ym(t,Zm)}evictOldestPersisted(t){let r=this.listPersistedSessions();if(r.length<=t)return;let n=r.slice(t);for(let o of n)this.removePersistedIndexes(o);this.saveIndex()}shouldGcActiveSession(t,r,n){return!t.completedAt||!wI.has(t.status)?!1:r-t.completedAt>n}getActionToken(t){return this.actionTokenStore.getActionToken(t)}consumeActionToken(t){return this.actionTokenStore.consumeActionToken(t)}deleteActionTokensForSession(t){this.actionTokenStore.deleteActionTokensForSession(t)}purgeExpiredActionTokens(t=Date.now()){this.actionTokenStore.purgeExpiredActionTokens(t)}};var xI=new Set(["completed","failed","killed"]),Li=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),xI.has(n)&&this.metrics.sessionsByStatus[n]++,t.completedAt){let i=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||r>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:r,prompt:hr(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 PI}from"child_process";var bI=3e4,vI=2e3,RI=2e4,Kn=4;function ef(e){return e instanceof Error?e.message:String(e)}var Ui=class{pendingRetryTimers=new Map;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)}}dispose(){this.clearPendingRetries()}execute(t,r,n=1){let o=Date.now();n===1&&r.onStarted?.(),this.log("info","dispatch_started",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:n,maxAttempts:Kn}),PI("openclaw",t,{timeout:bI},(i,s,a)=>{let d=Date.now()-o;if(!i){this.log("info","dispatch_succeeded",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:n,maxAttempts:Kn,elapsedMs:d}),r.onSuccess?.();return}let c=a?.trim()?` | stderr: ${a.trim()}`:"";if(n>=Kn){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:n,maxAttempts:Kn,elapsedMs:d,error:`${ef(i)}${c}`,terminal:!0}),r.onFinalFailure?.();return}let h=this.retryDelayMs(n);this.log("error","dispatch_retry_scheduled",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:n,maxAttempts:Kn,elapsedMs:d,retryDelayMs:h,error:`${ef(i)}${c}`});let m=setTimeout(()=>{let S=this.pendingRetryTimers.get(r.sessionId);S&&(S.delete(m),S.size===0&&this.pendingRetryTimers.delete(r.sessionId)),this.execute(t,r,n+1)},h);m.unref?.(),this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(m)})}retryDelayMs(t){let r=Math.max(0,t-1),n=vI*2**r;return Math.min(n,RI)}log(t,r,n){let o=`[WakeDispatcher] ${JSON.stringify({event:r,...n})}`;if(t==="error"){console.error(o);return}console.info(o)}};vn();var Wi=class{resolve(t){let r=al(t);if(!(!r?.provider||!r.target))return{channel:r.provider,target:r.target,accountId:r.accountId,threadId:r.threadId,sessionKey:r.sessionKey}}summary(t){if(!t)return"system";let r=t.accountId?`|${t.accountId}`:"",n=t.threadId?`#${t.threadId}`:"";return`${t.channel}${r}|${t.target}${n}`}};import{randomUUID as AI}from"crypto";var Bi=class{buildChatSendArgs(t,r,n){return["gateway","call","chat.send","--expect-final","--timeout","30000","--params",JSON.stringify({sessionKey:t,message:r,deliver:n,idempotencyKey:AI()})]}buildDirectNotificationArgs(t,r,n){let o=["message","send","--channel",t.channel,"--target",t.target,"--message",r];return t.accountId&&o.push("--account",t.accountId),t.threadId&&o.push("--thread-id",t.threadId),n&&t.channel==="telegram"&&o.push("--buttons",JSON.stringify(n.map(i=>i.map(s=>({text:s.label,callback_data:s.callbackData.startsWith(`${Gr}:`)?s.callbackData:`${Gr}:${s.callbackData}`}))))),o}buildSystemEventArgs(t){return["system","event","--text",t,"--mode","now"]}};var Ki=class{routes=new Wi;transport=new Bi;executor=new Ui;clearPendingRetries(){this.executor.clearPendingRetries()}clearRetryTimersForSession(t){this.executor.clearRetryTimersForSession(t)}dispose(){this.executor.dispose()}sendWake(t,r,n,o,i,s){let d=this.routes.resolve(t)?.sessionKey?.trim();if(!d){this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-system`,sessionId:t.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",onSuccess:s,onFinalFailure:i});return}this.executor.execute(this.transport.buildChatSendArgs(d,r,!0),{label:n,sessionId:t.id,target:"chat.send",phase:o,routeSummary:`session:${d}`,messageKind:"wake",onSuccess:s,onFinalFailure:()=>{this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-fallback`,sessionId:t.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",onSuccess:s,onFinalFailure:i})}})}sendUserNotification(t,r,n,o,i,s){let a=!!(o&&o.length>0),d=this.routes.resolve(t);if(!d){if(a){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${t.id} has no direct route; refusing text-only fallback because buttons would be lost.`),i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-notify-system`,sessionId:t.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",onSuccess:s,onFinalFailure:i});return}this.executor.execute(this.transport.buildDirectNotificationArgs(d,r,o),{label:`${n}-notify`,sessionId:t.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(d),messageKind:"notify",onSuccess:s,onFinalFailure:()=>{if(a){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${t.id} failed direct delivery; refusing text-only fallback because buttons would be lost.`),i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-notify-fallback`,sessionId:t.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",onSuccess:s,onFinalFailure:i})}})}dispatchSessionNotification(t,r){let n=r.hooks,o=r.wakeMessageOnNotifySuccess!=null||r.wakeMessageOnNotifyFailed!=null,i=r.notifyUser??(r.wakeMessage?"on-wake-fallback":"always"),s=r.userMessage?.trim(),a=r.wakeMessage?.trim();if(o){let d=r.wakeMessageOnNotifySuccess?.trim(),c=r.wakeMessageOnNotifyFailed?.trim(),h=y=>{y&&(n?.onWakeStarted?.(),this.sendWake(t,y,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded))},m=()=>{n?.onNotifySucceeded?.(),d&&h(d)},S=c?()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.(),h(c)}:()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()};s?(n?.onNotifyStarted?.(),this.sendUserNotification(t,s,r.label,r.buttons,S,m)):S();return}i==="always"&&s&&(n?.onNotifyStarted?.(),this.sendUserNotification(t,s,r.label,r.buttons,()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()},()=>n?.onNotifySucceeded?.())),a&&(n?.onWakeStarted?.(),i==="on-wake-fallback"&&s&&!this.routes.resolve(t)?.sessionKey&&(n?.onNotifyStarted?.(),this.sendUserNotification(t,s,r.label,r.buttons,()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()},()=>n?.onNotifySucceeded?.())),this.sendWake(t,a,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded))}};var ji=class{constructor(t,r){this.actionTokens=t;this.isGitHubCliAvailable=r}createActionToken(t,r,n={}){return this.actionTokens.createActionToken(t,r,{expiresAt:Date.now()+10080*60*1e3,...n})}consumeActionToken(t){return this.actionTokens.consumeActionToken(t)}makeActionButton(t,r,n,o={}){let i=this.createActionToken(t,r,{label:n,...o});return{label:n,callbackData:i.id}}getWorktreeDecisionButtons(t,r){if(!r)return[];let n=[],o=[this.makeActionButton(t,"worktree-merge","Merge")];if(this.isGitHubCliAvailable())r.worktreePrUrl?(o.push(this.makeActionButton(t,"worktree-view-pr","View PR",{targetUrl:r.worktreePrUrl})),n.push(o),n.push([this.makeActionButton(t,"worktree-update-pr","Sync PR"),this.makeActionButton(t,"worktree-decide-later","Later")])):(o.push(this.makeActionButton(t,"worktree-create-pr","Open PR")),n.push(o),n.push([this.makeActionButton(t,"worktree-decide-later","Later"),this.makeActionButton(t,"worktree-dismiss","Discard")]));else return n.push([...o,this.makeActionButton(t,"worktree-decide-later","Later")]),n.push([this.makeActionButton(t,"worktree-dismiss","Discard")]),n;return r.worktreePrUrl&&n.push([this.makeActionButton(t,"worktree-dismiss","Discard")]),n}getPlanApprovalButtons(t,r){return[[this.makeActionButton(t,"plan-approve","Approve",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(t,"plan-request-changes","Revise",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(t,"plan-reject","Reject",{planDecisionVersion:r?.planDecisionVersion})]]}getResumeButtons(t,r){let n=[];return r.isExplicitlyResumable&&n.push(this.makeActionButton(t,"session-resume","Resume")),n.push(this.makeActionButton(t,"view-output","View output")),[n]}getQuestionButtons(t,r){if(r.length!==0)return[r.map((n,o)=>this.makeActionButton(t,"question-answer",n.label,{optionIndex:o}))]}};ke();var qi=class{constructor(t,r){this.wakeDispatcher=t;this.applyPersistedPatch=r}dispatch(t,r){let n=this.getDeliveryRef(t),o=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifySuccess?.trim()),i=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifyFailed?.trim()),s={onNotifyStarted:()=>{this.applyDeliveryState(n,"notifying"),r.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{this.applyDeliveryState(n,o?"wake_pending":"idle"),r.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{this.applyDeliveryState(n,i?"wake_pending":"failed"),r.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyDeliveryState(n,"wake_pending"),r.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{this.applyDeliveryState(n,"idle"),r.hooks?.onWakeSucceeded?.()},onWakeFailed:()=>{this.applyDeliveryState(n,"failed"),r.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(t,{...r,hooks:s})}notifyWorktreeOutcome(t,r){this.dispatch(t,{label:"worktree-outcome",userMessage:r,notifyUser:"always"})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(t){return ee(t)??T(t)??""}applyDeliveryState(t,r){!t||!r||this.applyPersistedPatch(t,{deliveryState:r})}};Qe();import{existsSync as TI}from"fs";var Vi=class{getCompletionState(t,r,n,o){return Dn(t,n,o)?"has-commits":Dn(t,o,n)?"base-advanced":pi(r)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(t,r,n){if(!t.worktreePath||!t.workdir||!TI(t.worktreePath)||t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return!1;let o=t.worktreeMergedAt??t.worktreeDismissedAt??t.completedAt??t.createdAt,i=typeof o=="string"?new Date(o).getTime():Number(o??0);return!!i&&r-i>=n}};var Hi=class{constructor(t,r,n,o){this.pendingQuestions=t;this.dispatchSessionNotification=r;this.clearWaitingTimestamp=n;this.getQuestionButtons=o}async handleAskUserQuestion(t,r){let i=r?.questions??[];if(i.length===0)throw new Error("AskUserQuestion: no questions in input");let s=i[0],a=s.options??[],d=this.getQuestionButtons(t.id,a),c=`\u2753 [${t.name}] ${s.question}`,h=[`[ASK USER QUESTION] Session "${t.name}" has a question requiring user input.`,"",`Question: ${s.question}`,...a.length>0?["Options:",...a.map((m,S)=>` ${S+1}. ${m.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${t.id}", message="<answer>") with their answer.`].join(`
98
+ `);return new Promise((m,S)=>{let y=setTimeout(()=>{this.pendingQuestions.delete(t.id),S(new Error(`AskUserQuestion timed out after 600s for session "${t.name}"`))},6e5);y.unref?.(),this.pendingQuestions.set(t.id,{resolve:m,reject:S,questions:i,timeoutHandle:y}),this.dispatchSessionNotification(t,{label:"ask-user-question",userMessage:c,notifyUser:"always",buttons:d,wakeMessageOnNotifySuccess:["AskUserQuestion delivered to the user.",`Session: ${t.name} | ID: ${t.id}`,`Question: ${s.question}`,"Await their selection \u2014 do NOT answer this question yourself."].join(`
99
+ `),wakeMessageOnNotifyFailed:h})})}resolveAskUserQuestion(t,r){let n=this.pendingQuestions.get(t);if(!n){console.warn(`[SessionQuestionService] resolveAskUserQuestion: no pending question for session "${t}"`);return}clearTimeout(n.timeoutHandle),this.pendingQuestions.delete(t);let o=n.questions[0],i=o.options??[],s=i[r];if(!s){n.reject(new Error(`AskUserQuestion: invalid option index ${r} (${i.length} options available)`));return}this.clearWaitingTimestamp(t),n.resolve({behavior:"allow",updatedInput:{questions:n.questions,answers:{[o.question]:s.label}}})}dispose(){for(let t of this.pendingQuestions.values())clearTimeout(t.timeoutHandle),t.reject(new Error("SessionManager disposed before AskUserQuestion resolved."));this.pendingQuestions.clear()}};function Gi(e){return[`Requested permission mode: ${e.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${e.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${e.approvalExecutionState??"unknown"}`]}function jn(e){switch(e){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"}}function ud(e){let{session:t,originThreadLine:r,preview:n}=e,o=`$${(t.costUsd??0).toFixed(2)}`,i=St(t.duration);return{userMessage:`\u2705 [${t.name}] Completed | ${o} | ${i}`,wakeMessage:["Coding agent session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,r,...Gi(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. The plugin already sent the canonical completion notification to the user.","4. Do NOT send a duplicate plain-text recap unless you need real synthesis, a concrete risk callout, or next-step guidance beyond that canonical message."].join(`
100
+ `)}}function pd(e){let{session:t,originThreadLine:r,errorSummary:n,preview:o,worktreeAutoCleaned:i,failedButtons:s}=e,a=o.trim()?["","Output preview:",o]:[],d=i?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[],c=`$${(t.costUsd??0).toFixed(2)}`,h=St(t.duration);return{userMessage:[`\u274C [${t.name}] Failed | ${c} | ${h}`,` \u26A0\uFE0F ${n}`].join(`
101
+ `),wakeMessage:["Coding agent session failed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,r,...Gi(t),...t.harnessSessionId?[`Backend conversation ID: ${t.harnessSessionId}`]:[],"","Failure summary:",n,...a,...d,"","[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. Continue the same session with agent_respond(session='${t.id}', message='<next instruction>').`,` If you intentionally want to fork or switch harnesses, launch a new session with agent_launch(resume_session_id='${t.id}', fork_session=true, ...)`," 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(`
102
+ `),buttons:s}}function cd(e){let{session:t,originThreadLine:r,preview:n}=e,o=`$${(t.costUsd??0).toFixed(2)}`;return{userMessage:`\u23F8\uFE0F [${t.name}] Turn completed | ${o}`,wakeMessage:["Coding agent session turn ended.",`Name: ${t.name}`,`ID: ${t.id}`,`Status: ${t.status}`,`Lifecycle: ${t.lifecycle}`,"","Last output (~20 lines):",n,...r?["",r]:[]].join(`
103
+ `)}}function ld(e){let{sessionName:t,sessionId:r,branchName:n,baseBranch:o,promptSnippet:i,commitLines:s,moreNote:a,diffSummary:d}=e;return[`[DELEGATED WORKTREE DECISION] Session "${t}" completed with changes.`,"",`Session ID: ${r}`,`Branch: ${n} \u2192 ${o}`,`Commits: ${d.commits} | Files: ${d.filesChanged} | +${d.insertions} / -${d.deletions}`,"",...s,...a?[a]:[],"","Original task prompt (first 500 chars):",i,"","You own the next step for this worktree.",`- Merge immediately with agent_merge(session="${t}", base_branch="${o}") if the changes are clearly in-scope and low-risk.`,"- If a PR is safer, message the user with the summary and ask for confirmation before calling agent_pr().","- If scope or risk is unclear, message the user and ask for guidance.","- Never call agent_pr() autonomously in delegate mode.","- After deciding, notify the user briefly with what you did and why."].join(`
104
+ `)}function md(e,t){return[`[DELEGATED WORKTREE DECISION REMINDER] Session "${e.name}" still has an unresolved worktree decision.`,"",`Session ID: ${e.sessionId??e.harnessSessionId}`,`Branch: ${e.worktreeBranch??"unknown"}`,`Pending: ${t}h`,"","Resolve it now:",`- agent_merge(session="${e.name}") if the diff is clearly safe and in scope`,"- If a PR is safer, ask the user before agent_pr()","- If scope or risk is unclear, ask the user for guidance","- Never call agent_pr() autonomously in delegate mode"].join(`
105
+ `)}function fd(e){let{sessionName:t,sessionId:r,cleanupSummary:n,preview:o,originThreadLine:i,requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d}=e,c=o.trim()?["","Output preview:",o]:[];return["Coding agent session completed with no repository changes.",`Name: ${t} | ID: ${r}`,`Worktree outcome: ${n}`,...i?[i]:[],...Gi({requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d}),...c,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${r}', 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. The plugin already sent the canonical completion notification to the user, including that no repo changes were kept.","4. Do NOT send a duplicate plain-text recap unless you need real synthesis, a concrete risk callout, or next-step guidance beyond that canonical message."].join(`
106
+ `)}function gd(e){let t=[],r=e.changedFiles.slice(0,3).map(o=>`\`${o}\``);if(r.length>0){let o=e.changedFiles.length-r.length;t.push(o>0?`Touches ${r.join(", ")} and ${o} more file${o===1?"":"s"}`:`Touches ${r.join(", ")}`)}let n=[...new Set(e.commitMessages.map(o=>o.message.trim()).filter(Boolean))].slice(0,2);return n.length>0&&t.push(`Recent work: ${n.join("; ")}`),t}function hd(e){let{session:t,preview:r,originThreadLine:n,planApprovalMode:o,planApprovalButtons:i,questionButtons:s}=e,a=t.pendingPlanApproval,d=a?o==="ask"?`\u{1F4CB} [${t.name}] Plan ready for approval:
107
+
108
+ ${r}
109
+
110
+ Choose Approve, Revise, or Reject below.`:void 0:`\u2753 [${t.name}] Question waiting for reply:
111
+
112
+ ${r}`;if(a){let h=o??"delegate",m="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return h==="delegate"?{label:"plan-approval",userMessage:d,wakeMessage:["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${t.name} | ID: ${t.id}`,n,m,"","\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): Review privately \u2501\u2501\u2501","You are the delegated decision-maker. Review the plan yourself before involving the user.","Do NOT post any user-facing approval summary unless you decide escalation is required.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- 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: call agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true) and do NOT show the user an approval prompt.`,`If escalating: call agent_request_plan_approval(session='${t.id}', summary='...') exactly once so the plugin posts the single canonical Approve / Revise / Reject prompt.`,"That summary must include changed files/components, risk level and why, scope match/expansion, and any concerns or assumptions.","After the canonical prompt exists, WAIT for the user's button click or explicit response and do NOT send a second plain-text recap.",`To request changes without user escalation: call agent_respond(session='${t.id}', message='<your feedback>') and do NOT set approve=true. The agent will revise the plan.`].join(`
113
+ `)}:h==="ask"?{label:"plan-approval",userMessage:d,wakeMessage:["[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}`,n,m,"","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(`
114
+ `),buttons:i}:{label:"plan-approval",userMessage:d,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`].join(`
115
+ `)}}let c=t.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:d,wakeMessage:[`[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.]`,"",`${c} is waiting for a genuine user reply.`,`Name: ${t.name} | ID: ${t.id}`,n,"","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(`
116
+ `),buttons:s}}ke();var zi=class{constructor(t,r,n,o){this.buildRoutingProxy=t;this.dispatchNotification=r;this.updatePersistedSession=n;this.getWorktreeDecisionButtons=o}remindStaleDecisions(t,r=Date.now()){for(let i of t){if(!i.pendingWorktreeDecisionSince)continue;let s=i.worktreeState==="pending_decision"||i.lifecycle==="awaiting_worktree_decision",a=i.worktreeState==null&&i.lifecycle==null&&!i.worktreeMerged&&!i.worktreePrUrl;if(!s&&!a)continue;if(i.worktreeDecisionSnoozedUntil){let h=new Date(i.worktreeDecisionSnoozedUntil).getTime();if(Number.isFinite(h)&&h>r)continue}let d=r-new Date(i.pendingWorktreeDecisionSince).getTime();if(!Number.isFinite(d)||d<108e5||i.lastWorktreeReminderAt&&r-new Date(i.lastWorktreeReminderAt).getTime()<108e5)continue;let c=Math.floor(d/(3600*1e3));try{this.sendReminderNotification(i,c)}catch(h){console.warn(`[SessionReminderService] Failed to send stale-decision reminder for session ${i.name}: ${h instanceof Error?h.message:String(h)}`)}for(let h of ze(i))this.updatePersistedSession(h,{lastWorktreeReminderAt:new Date(r).toISOString()})}}sendReminderNotification(t,r){let n=this.buildRoutingProxy({id:t.sessionId??t.name??T(t)??t.harnessSessionId,sessionId:t.sessionId,harnessSessionId:t.harnessSessionId,backendRef:t.backendRef,route:t.route});if(t.worktreeStrategy==="delegate"){this.dispatchNotification(n,{label:`worktree-stale-reminder-${t.name}`,wakeMessage:md(t,r),notifyUser:"never"});return}let o=[`\u23F0 Reminder: branch \`${t.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${t.name} | Pending: ${r}h`,"",`agent_merge(session="${t.name}") or agent_pr(session="${t.name}") or agent_worktree_cleanup() to resolve.`].join(`
117
+ `);this.dispatchNotification(n,{label:`worktree-stale-reminder-${t.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(ee(t)??t.harnessSessionId)})}};Qe();ke();var Qi=class{constructor(t){this.deps=t}handleTurnEnd(t,r){if(t.status!=="running"){console.info(`[SessionManager] Suppressing turn-end wake for session ${t.id} (status=${t.status}) \u2014 terminal notification owns the completion path.`);return}if(r||t.pendingPlanApproval){this.emitWaitingForInput(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.deps.shouldEmitTurnCompleteWake(t)&&this.emitTurnComplete(t)}async handleSessionTerminal(t){this.deps.persistSession(t),this.deps.clearWaitingTimestamp(t.id);let r={notificationSent:!1,worktreeRemoved:!1};t.worktreePath&&t.originalWorkdir&&(r=await this.deps.handleWorktreeStrategy(t));let n=!1;if(t.worktreePath&&t.originalWorkdir&&t.status==="failed"&&t.costUsd===0&&t.duration<3e4){let a=this.deps.resolveWorktreeRepoDir(t.originalWorkdir,t.worktreePath),d=t.worktreeBranch,c=ot(t);console.info(`[SessionManager] Early startup failure for "${t.name}" \u2014 auto-cleaning worktree (cost=$${t.costUsd.toFixed(2)}, duration=${t.duration}ms)`);let h=!1;if(a&&!c&&(h=ht(a,t.worktreePath)),a&&d&&!c&&h&&bt(a,d),h){for(let m of ze(t))this.deps.updatePersistedSession(m,{worktreePath:void 0,worktreeBranch:void 0});n=!0}}let o=t.worktreeStrategy&&t.worktreeStrategy!=="off"&&t.worktreeStrategy!=="manual";if(!n&&t.worktreePath&&t.originalWorkdir){let a=this.deps.resolveWorktreeRepoDir(t.originalWorkdir,t.worktreePath),d=ot(t);r.worktreeRemoved?console.info(`[SessionManager] Worktree already removed for "${t.name}" during strategy handling.`):o?console.info(`[SessionManager] Keeping worktree alive for "${t.name}" (strategy=${t.worktreeStrategy}) \u2014 will be cleaned up on explicit resolution.`):a&&!d&&ht(a,t.worktreePath)}if(t.killReason==="done"){if(r.notificationSent||this.deps.hasTurnCompleteWakeMarker(t.id)||!this.deps.shouldEmitTerminalWake(t))return;this.emitCompleted(t);return}if(t.status==="completed"){if(!this.deps.shouldEmitTerminalWake(t))return;this.emitCompleted(t);return}if(t.status==="failed"){if(!this.deps.shouldEmitTerminalWake(t))return;let a=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.deps.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`;this.emitFailed(t,hr(a,200),n);return}let i=`$${(t.costUsd??0).toFixed(2)}`,s=t.duration;if(t.killReason==="idle-timeout"){let a=t.pendingPlanApproval?this.deps.resolvePlanApprovalMode(t):void 0;if(t.pendingPlanApproval){if(a==="delegate"){this.deps.dispatchSessionNotification(t,{label:"plan-approval-timeout",wakeMessage:["[DELEGATED PLAN APPROVAL REMINDER] Plan review is still pending after the session hit idle timeout.",`Name: ${t.name} | ID: ${t.id}`,this.deps.originThreadLine(t),"The agent already produced a plan and is waiting for a delegated decision.","Review privately first. Approve directly with agent_respond(..., approve=true) if the plan is clearly within scope and low risk.","Escalate only if needed via agent_request_plan_approval(summary='...').","If a canonical approval prompt was already posted for this plan version, do not restate it in plain text."].join(`
118
+ `),notifyUser:"never"}),this.deps.clearRetryTimersForSession(t.id);return}this.deps.dispatchSessionNotification(t,{label:"plan-approval-timeout",userMessage:[`\u{1F4CB} [${t.name}] Plan still awaiting approval after idle timeout | ${i} | ${St(s)}`,"","The agent already produced a plan and is waiting for your decision.","Approve resumes the session and starts implementation.","Revise resumes it in plan mode so it can update the plan first.","Reject keeps the session stopped."].join(`
119
+ `),notifyUser:"always",buttons:a==="ask"?this.deps.getPlanApprovalButtons(t.id,t):void 0}),this.deps.clearRetryTimersForSession(t.id);return}this.deps.dispatchSessionNotification(t,{label:"suspended",userMessage:`\u{1F4A4} [${t.name}] Suspended after idle timeout | ${i} | ${St(s)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(t.id,t)}),this.deps.clearRetryTimersForSession(t.id);return}this.deps.notifySession(t,`\u26D4 [${t.name}] ${jn(t.killReason)} | ${i} | ${St(s)}`),this.deps.clearRetryTimersForSession(t.id)}emitWaitingForInput(t){if(!this.deps.debounceWaitingEvent(t.id))return;let r=t.pendingPlanApproval?this.deps.resolvePlanApprovalMode(t):void 0,n=t.planDecisionVersion,o=!t.pendingPlanApproval&&t.pendingInputState?.promptText?t.pendingInputState.promptText:this.deps.getOutputPreview(t,t.pendingPlanApproval&&r!=="delegate"?Number.POSITIVE_INFINITY:void 0),i=t.pendingPlanApproval&&r==="ask"?this.deps.getPlanApprovalButtons(t.id,t):!t.pendingPlanApproval&&t.pendingInputState?.options.length?this.deps.getQuestionButtons(t.id,t.pendingInputState.options.map(a=>({label:a}))):void 0,s=hd({session:t,preview:o,originThreadLine:this.deps.originThreadLine(t),planApprovalMode:r,planApprovalButtons:i,questionButtons:t.pendingPlanApproval?void 0:i});if(s.label==="plan-approval"&&r==="ask"){this.deps.dispatchSessionNotification(t,{label:s.label,userMessage:s.userMessage,notifyUser:"always",buttons:s.buttons,hooks:{onNotifySucceeded:()=>{this.deps.updatePersistedSession(t.id,{canonicalPlanPromptVersion:n})}},wakeMessageOnNotifySuccess:["Plan approval buttons delivered to the user.",`Session: ${t.name} | ID: ${t.id}`,"Wait for their button callback \u2014 do NOT approve or reject this plan yourself."].join(`
120
+ `),wakeMessageOnNotifyFailed:s.wakeMessage});return}if(s.label==="plan-approval"){this.deps.dispatchSessionNotification(t,{label:s.label,userMessage:s.userMessage,wakeMessage:s.wakeMessage,notifyUser:"never",buttons:s.buttons});return}this.deps.dispatchSessionNotification(t,{label:s.label,userMessage:s.userMessage,notifyUser:"always",buttons:s.buttons,wakeMessageOnNotifyFailed:s.wakeMessage})}emitTurnComplete(t){console.info(`[SessionManager] turn-complete wake dispatching for session ${t.id} (turns=${t.result?.num_turns??0}, strategy=${t.worktreeStrategy??"none"})`);let r=cd({session:t,originThreadLine:this.deps.originThreadLine(t),preview:this.deps.getOutputPreview(t)});this.deps.dispatchSessionNotification(t,{label:"turn-complete",userMessage:r.userMessage,wakeMessage:r.wakeMessage,notifyUser:"always",onUserNotifyFailed:()=>{console.warn(`[SessionManager] turn-complete delivery failed for session ${t.id} \u2014 firing terminal notification as fallback`),this.deps.shouldEmitTerminalWake(t)&&this.emitCompleted(t)}})}emitCompleted(t){let r=this.deps.getOutputPreview(t),n=ud({session:t,originThreadLine:this.deps.originThreadLine(t),preview:r});this.deps.dispatchSessionNotification(t,{label:"completed",userMessage:n.userMessage,wakeMessage:n.wakeMessage,notifyUser:"always"})}emitFailed(t,r,n){let o=pd({session:t,originThreadLine:this.deps.originThreadLine(t),errorSummary:r,preview:this.deps.getOutputPreview(t),worktreeAutoCleaned:n,failedButtons:this.deps.getResumeButtons(t.id,t)});this.deps.dispatchSessionNotification(t,{label:"failed",userMessage:o.userMessage,wakeMessage:o.wakeMessage,notifyUser:"always",buttons:o.buttons})}};ke();Qe();import{existsSync as MI}from"fs";var Ji=class{constructor(t){this.deps=t}async dismissWorktree(t){let r=this.deps.getPersistedSession(t),n=this.deps.resolveActiveSession(t),o=n??r;if(!o)return`Error: Session "${t}" not found.`;let i=n?.worktreePath??r?.worktreePath,s=this.deps.resolveWorktreeRepoDir(n?.originalWorkdir??r?.workdir,i),a=n?.worktreeBranch??r?.worktreeBranch,d=n?.name??r?.name??t;if(!s)return`Error: No workdir found for session "${t}".`;let c=ot(o);!c&&i&&MI(i)&&ht(s,i,{destructive:!0}),a&&bt(s,a);for(let m of ze(n??r))this.deps.updatePersistedSession(m,{worktreeDisposition:"dismissed",worktreeDismissedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,worktreeState:"dismissed",lifecycle:"terminal",worktreePath:void 0,worktreeBranch:void 0});let h=c?`\u{1F5D1}\uFE0F [${d}] Branch \`${a??"unknown"}\` dismissed. Native backend worktree released for backend cleanup.`:`\u{1F5D1}\uFE0F [${d}] Branch \`${a??"unknown"}\` dismissed and permanently deleted.`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:ee(n??r??{id:t})??t,sessionId:r?.sessionId,harnessSessionId:n?.harnessSessionId??r?.harnessSessionId,backendRef:n?.backendRef??r?.backendRef,route:n?.route??r?.route}),{label:"worktree-dismissed",userMessage:h,notifyUser:"always"}),h}snoozeWorktreeDecision(t){let r=this.deps.getPersistedSession(t);if(!r)return`Error: Session "${t}" not found.`;let n=new Date(Date.now()+1440*60*1e3).toISOString();for(let s of ze(r))this.deps.updatePersistedSession(s,{worktreeDecisionSnoozedUntil:n,lastWorktreeReminderAt:new Date().toISOString()});let i=`\u23ED\uFE0F Reminder snoozed 24h for \`${r.worktreeBranch??"unknown"}\` (session: ${r.name})`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:ee(r)??T(r)??r.harnessSessionId,sessionId:r.sessionId,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route}),{label:"worktree-snoozed",userMessage:i,notifyUser:"always"}),i}};var tf=new Set(["starting","running"]),Yi=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(t=>tf.has(t.status)).length}uniqueName(t){let r=new Set([...this.sessions.values()].filter(o=>tf.has(o.status)).map(o=>o.name));if(!r.has(t))return t;let n=2;for(;r.has(`${t}-${n}`);)n+=1;return`${t}-${n}`}add(t){this.sessions.set(t.id,t)}remove(t){this.sessions.delete(t)}get(t){return this.sessions.get(t)}list(){return[...this.sessions.values()]}};var Xi=class{constructor(t){this.deps=t}initializeSession(t,r,n,o={}){if(this.deps.hydrateSpawnedSession(t,r,n),t.on("statusChange",(i,s)=>{s==="running"&&t.harnessSessionId?this.deps.markRunning(t):(s==="completed"||s==="failed"||s==="killed")&&this.deps.handleTerminal(t).catch(a=>{console.error(`[SessionRuntimeBootstrap] handleTerminal threw for session ${t.id}:`,a)})}),t.on("turnEnd",(i,s)=>{this.deps.handleTurnEnd(t,s)}),t.start(),o.notifyLaunch!==!1){let i=this.deps.formatLaunchWorkdirLabel(t),s=`\u{1F680} [${t.name}] Launched | ${i} | ${t.model??"default"}`;this.deps.notifySession(t,s,"launch")}return t}};var Zi=class{buildNoChangeNotification(t){let{session:r,nativeBackendWorktree:n,cleanupSucceeded:o,worktreePath:i,preview:s,originThreadLine:a}=t,d=o?n?"native backend worktree released for backend cleanup":"worktree cleaned up":`cleanup failed; worktree still exists at ${i}`;return{label:o?"worktree-no-changes":"worktree-no-changes-cleanup-failed",userMessage:o?n?`\u2139\uFE0F [${r.name}] Session completed with no changes \u2014 native backend worktree released for backend cleanup`:`\u2139\uFE0F [${r.name}] Session completed with no changes \u2014 worktree cleaned up`:`\u26A0\uFE0F [${r.name}] Session completed with no changes, but worktree cleanup failed. Worktree still exists at ${i}`,wakeMessage:fd({sessionName:r.name,sessionId:r.id,cleanupSummary:d,preview:s,originThreadLine:a,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,approvalExecutionState:r.approvalExecutionState}),notifyUser:"always"}}buildAskNotification(t){let{session:r,branchName:n,baseBranch:o,diffSummary:i,buttons:s}=t,a=gd(i),d=i.commitMessages.slice(0,5).map(m=>`\u2022 ${m.hash} ${m.message} (${m.author})`),c=i.commits>5?`...and ${i.commits-5} more`:"",h=r.worktreePrTargetRepo?`Branch: \`${n}\` \u2192 \`${o}\` | PR target: ${r.worktreePrTargetRepo}`:`Branch: \`${n}\` \u2192 \`${o}\``;return{label:"worktree-merge-ask",userMessage:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",h,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"",...a.length>0?["Summary:",...a.map(m=>`- ${m}`),""]:[],"Recent commits:",...d,...c?[c]:[],"",`\u26A0\uFE0F Discard will permanently delete branch \`${n}\` and all local changes. This cannot be undone.`].join(`
121
+ `),notifyUser:"always",buttons:s,wakeMessageOnNotifySuccess:["Worktree decision buttons delivered to the user.",`Session: ${r.name} | ID: ${r.id}`,h,"Wait for their button callback \u2014 do NOT act on this worktree yourself."].join(`
122
+ `),wakeMessageOnNotifyFailed:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",h,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
123
+ `)}}buildDelegateNotification(t){let{session:r,branchName:n,baseBranch:o,diffSummary:i}=t,s=i.commitMessages.slice(0,5).map(c=>`\u2022 ${c.hash} ${c.message} (${c.author})`),a=i.commits>5?`...and ${i.commits-5} more`:void 0,d=r.prompt?r.prompt.slice(0,500):"(no prompt)";return{label:"worktree-delegate",wakeMessage:ld({sessionName:r.name,sessionId:r.id,branchName:n,baseBranch:o,promptSnippet:d,commitLines:s,moreNote:a,diffSummary:i}),notifyUser:"never"}}};Qe();var rf=new Set(["completed","failed","killed"]),CI=new Set(["starting","running"]),EI=5e3,es=class{registry;sessions;maxSessions;maxPersistedSessions;lastDailyMaintenanceAt=0;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueues=new Map;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;interactions;notifications;worktrees;questions;reminders;lifecycle;restore;stateSync;references;worktreeStrategy;worktreeDecisions;runtimeBootstrap;worktreeMessages;constructor(t=20,r=50){this.maxSessions=t,this.maxPersistedSessions=r,this.registry=new Yi,this.sessions=this.registry.sessions,this.store=new Di,this.metrics=new Li,this.wakeDispatcher=new Ki,this.interactions=new ji(this.store.actionTokenStore,Pt),this.references=new Ti(this.sessions,this.store),this.stateSync=new Ai({store:this.store,sessions:this.sessions,resolveSession:n=>this.references.resolveActive(n)}),this.notifications=new qi(this.wakeDispatcher,(n,o)=>this.stateSync.applySessionPatch(n,o)),this.worktrees=new Vi,this.restore=new Ri(n=>this.store.getPersistedSession(n)),this.worktreeMessages=new Zi,this.worktreeStrategy=new Ci({shouldRunWorktreeStrategy:n=>this.shouldRunWorktreeStrategy(n),isAlreadyMerged:n=>this.isAlreadyMerged(n),resolveWorktreeRepoDir:(n,o)=>this.resolveWorktreeRepoDir(n,o),getWorktreeCompletionState:(n,o,i,s)=>this.getWorktreeCompletionState(n,o,i,s),updatePersistedSession:(n,o)=>this.updatePersistedSession(n,o),dispatchSessionNotification:(n,o)=>this.dispatchSessionNotification(n,o),getOutputPreview:(n,o)=>this.getOutputPreview(n,o),originThreadLine:n=>this.originThreadLine(n),getWorktreeDecisionButtons:n=>this.getWorktreeDecisionButtons(n),makeOpenPrButton:n=>this.makeActionButton(n,"worktree-create-pr","Open PR"),worktreeMessages:this.worktreeMessages,enqueueMerge:(n,o,i)=>this.enqueueMerge(n,o,i),spawnConflictResolver:async(n,o,i)=>{this.spawn({prompt:i,workdir:o,name:`${n.name}-conflict-resolver`,harness:De(),permissionMode:"bypassPermissions",multiTurn:!0,route:n.route,originChannel:n.originChannel,originThreadId:n.originThreadId,originAgentId:n.originAgentId,originSessionKey:n.originSessionKey})},runAutoPr:async(n,o)=>{let{makeAgentPrTool:i}=await Promise.resolve().then(()=>(Pi(),Mm));return{success:(await i().execute("auto-pr",{session:n.id,base_branch:o}))?.meta?.success===!0}}}),this.questions=new Hi(this.pendingAskUserQuestions,(n,o)=>this.dispatchSessionNotification(n,o),n=>{this.lastWaitingEventTimestamps.delete(n)},(n,o)=>this.interactions.getQuestionButtons(n,o)),this.reminders=new zi(n=>this.buildRoutingProxy(n),(n,o)=>this.notifications.dispatch(n,o),(n,o)=>this.updatePersistedSession(n,o),n=>this.getWorktreeDecisionButtons(n)),this.lifecycle=new Qi({persistSession:n=>this.persistSession(n),clearWaitingTimestamp:n=>{this.lastWaitingEventTimestamps.delete(n)},handleWorktreeStrategy:n=>this.handleWorktreeStrategy(n),resolveWorktreeRepoDir:(n,o)=>this.resolveWorktreeRepoDir(n,o),updatePersistedSession:(n,o)=>this.updatePersistedSession(n,o),dispatchSessionNotification:(n,o)=>this.dispatchSessionNotification(n,o),notifySession:(n,o,i)=>this.notifySession(n,o,i),clearRetryTimersForSession:n=>this.wakeDispatcher.clearRetryTimersForSession(n),hasTurnCompleteWakeMarker:n=>this.lastTurnCompleteMarkers.has(n),shouldEmitTurnCompleteWake:n=>this.shouldEmitTurnCompleteWake(n),shouldEmitTerminalWake:n=>this.shouldEmitTerminalWake(n),resolvePlanApprovalMode:n=>this.resolvePlanApprovalMode(n),getPlanApprovalButtons:(n,o)=>this.interactions.getPlanApprovalButtons(n,o),getResumeButtons:(n,o)=>this.interactions.getResumeButtons(n,o),getQuestionButtons:(n,o)=>this.interactions.getQuestionButtons(n,o),extractLastOutputLine:n=>this.extractLastOutputLine(n),getOutputPreview:(n,o)=>this.getOutputPreview(n,o),originThreadLine:n=>this.originThreadLine(n),debounceWaitingEvent:n=>this.debounceWaitingEvent(n),isAlreadyMerged:n=>this.isAlreadyMerged(n)}),this.worktreeDecisions=new Ji({getPersistedSession:n=>this.store.getPersistedSession(n),resolveActiveSession:n=>this.references.resolveActive(n),resolveWorktreeRepoDir:(n,o)=>this.resolveWorktreeRepoDir(n,o),updatePersistedSession:(n,o)=>this.updatePersistedSession(n,o),dispatchNotification:(n,o)=>this.notifications.dispatch(n,o),buildRoutingProxy:n=>this.buildRoutingProxy(n)}),this.runtimeBootstrap=new Xi({hydrateSpawnedSession:(n,o,i)=>{this.restore.hydrateSpawnedSession(n,o,i)},markRunning:n=>this.store.markRunning(n),handleTerminal:async n=>this.onSessionTerminal(n),handleTurnEnd:(n,o)=>this.onTurnEnd(n,o),formatLaunchWorkdirLabel:n=>this.formatLaunchWorkdirLabel(n),notifySession:(n,o,i)=>this.notifySession(n,o,i)})}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(t){return this.registry.uniqueName(t)}spawn(t,r={}){if(this.registry.activeSessionCount()>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);if(t.sessionIdOverride){let S=this.registry.get(t.sessionIdOverride);if(S?.status==="starting"||S?.status==="running")throw new Error(`Cannot reuse session ID ${t.sessionIdOverride}: that session is still ${S.status}.`);S&&this.registry.remove(S.id),this.lastWaitingEventTimestamps.delete(t.sessionIdOverride),this.lastTurnCompleteMarkers.delete(t.sessionIdOverride),this.lastTerminalWakeMarkers.delete(t.sessionIdOverride)}let o=t.name||fm(t.prompt),i=this.uniqueName(o);if(i!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${i}" (active session with same name exists)`),!t.route?.provider||!t.route.target)throw new Error(`Cannot launch session "${i}": missing explicit route metadata.`);let s=this.restore.prepareSpawn(t,i),a=t.harness??"claude-code",d=this,c,h=a==="claude-code"&&!t.canUseTool?async(S,y)=>{if(!c)throw new Error("canUseTool called before session ID was set");return d.handleAskUserQuestion(c,y)}:t.canUseTool,m=new gi({...t,workdir:s.actualWorkdir,systemPrompt:s.effectiveSystemPrompt,canUseTool:h},i);return c=m.id,this.registry.add(m),this.metrics.incrementLaunched(),this.runtimeBootstrap.initializeSession(m,s,t,r)}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(rf.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,i)=>{let s=(d,c)=>{if(c==="running"){a(),o();return}rf.has(c)&&(a(),i(new Error(this.describeLaunchFailure(t))))},a=()=>{n("statusChange",s)};r("statusChange",s)})}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}`}formatLaunchResult(t,r){return Uo({prompt:t.prompt,workdir:t.workdir,harness:t.harness,permissionMode:t.permissionMode??E.permissionMode,planApproval:t.planApproval,resumeSessionId:t.resumeSessionId,forkSession:t.forkSession,forceNewSession:t.forceNewSession,clearedPersistedCodexResume:t.clearedPersistedCodexResume},r)}shouldRunWorktreeStrategy(t){let r=t.lifecycle;return!(r==="starting"||r==="awaiting_plan_decision"||r==="awaiting_user_input"||t.pendingPlanApproval)}makeActionButton(t,r,n,o={}){return this.interactions.makeActionButton(t,r,n,o)}consumeActionToken(t){return this.interactions.consumeActionToken(t)}getWorktreeDecisionButtons(t){let r=this.resolve(t)??this.getPersistedSession(t);if(!(!r||r.worktreeStrategy==="delegate"))return this.interactions.getWorktreeDecisionButtons(t,r)}getWorktreeCompletionState(t,r,n,o){return this.worktrees.getCompletionState(t,r,n,o)}notifyWorktreeOutcome(t,r){this.notifications.notifyWorktreeOutcome(t,r)}requestPlanApprovalFromUser(t,r){let n=r.trim();if(!n)return"Error: summary must not be empty.";let o=this.resolve(t),i=o?void 0:this.getPersistedSession(t),s=o??i;if(!s)return`Error: Session "${t}" not found.`;if(!s.pendingPlanApproval)return`Error: Session "${t}" is not awaiting plan approval.`;let a=ee(o??i??{id:t})??t;if(this.resolvePlanApprovalMode(s)!=="delegate")return`Error: Session "${t}" already uses direct user plan approval. Do not send a duplicate approval prompt.`;if(s.canonicalPlanPromptVersion===s.planDecisionVersion)return[`Canonical plan approval prompt already exists for session ${s.name} [${a}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ");if(s.deliveryState==="notifying")return[`A plan approval prompt is already being delivered for session ${s.name} [${a}].`,"Wait for delivery to finish before retrying."].join(" ");let d=this.interactions.getPlanApprovalButtons(a,s),c=[`\u{1F4CB} [${s.name}] Plan needs your decision:`,"",n,"","Choose Approve, Revise, or Reject below."].join(`
124
+ `);return this.notifications.dispatch(this.buildRoutingProxy({id:a,sessionId:i?.sessionId,harnessSessionId:o?.harnessSessionId??i?.harnessSessionId,backendRef:o?.backendRef??i?.backendRef,route:o?.route??i?.route}),{label:"plan-approval",userMessage:c,notifyUser:"always",buttons:d,hooks:{onNotifySucceeded:()=>{this.updatePersistedSession(a,{canonicalPlanPromptVersion:s.planDecisionVersion})}}}),[`Canonical plan approval prompt sent for session ${s.name} [${a}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ")}buildRoutingProxy(t){return{id:ee(t)??T(t)??t.harnessSessionId??"unknown-session",harnessSessionId:t.harnessSessionId,backendRef:t.backendRef?{...t.backendRef}:void 0,route:t.route}}resolveWorktreeRepoDir(t,r){return t&&(!r||!vi(t,r))||!r?t:si(r)??t}formatLaunchWorkdirLabel(t){if(!t.worktreePath)return t.workdir;let r=this.resolveWorktreeRepoDir(t.originalWorkdir,t.worktreePath);return!r||r===t.worktreePath?t.worktreePath:`${t.worktreePath} (worktree of ${r})`}async dismissWorktree(t){return this.worktreeDecisions.dismissWorktree(t)}snoozeWorktreeDecision(t){return this.worktreeDecisions.snoozeWorktreeDecision(t)}async handleWorktreeStrategy(t){return this.worktreeStrategy.handleWorktreeStrategy(t)}async onSessionTerminal(t){return this.lifecycle.handleSessionTerminal(t)}getStoppedStatusLabel(t){return jn(t)}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.notifications.dispatch(t,r)}debounceWaitingEvent(t){let r=Date.now(),n=this.lastWaitingEventTimestamps.get(t);return n&&r-n<EI?!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=!Number.isFinite(r),o=typeof t.getOutput=="function"?t.getOutput():[],i=n?o.join(`
125
+ `):this.selectCompletionPreviewSource(t);return n?i:i.length>r?this.shouldPreferTailPreview(t)?hm(i,r):Sm(i,r):i}selectCompletionPreviewSource(t){let r=typeof t.getOutput=="function"?t.getOutput():[],n=r.join(`
126
+ `).trim();return n?this.shouldPreferTailPreview(t)?this.extractLastSubstantiveBlock(n)??n:r.slice(-20).join(`
127
+ `):""}shouldPreferTailPreview(t){if(t.status==="completed"||t.killReason==="done")return!0;let r=t;return r.approvalState==="approved"||r.planModeApproved===!0||(r.planDecisionVersion??0)>0}extractLastSubstantiveBlock(t){let n=t.split(/\n\s*\n+/).map(o=>o.trim()).filter(o=>/[A-Za-z0-9]/.test(o)).at(-1);if(n)return n.length>=120||n.includes(`
128
+ `)?n:void 0}triggerAgentEvent(t){this.lifecycle.emitCompleted(t)}triggerFailedEvent(t,r,n=!1){this.lifecycle.emitFailed(t,r,n)}triggerWaitingForInputEvent(t){this.lifecycle.emitWaitingForInput(t)}resolvePlanApprovalMode(t){return t.planApproval??E.planApproval??"delegate"}onTurnEnd(t,r){this.lifecycle.handleTurnEnd(t,r)}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){this.lifecycle.emitTurnComplete(t)}resolve(t){return this.references.resolveActive(t)}get(t){return this.registry.get(t)}list(t){let r=this.registry.list();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.registry.get(t);return n?(n.kill(r??"user"),!0):!1}killAll(t="user"){for(let r of this.sessions.values())CI.has(r.status)&&this.kill(r.id,t)}resolveBackendConversationId(t){return this.references.resolveBackendConversationId(t)}resolveHarnessSessionId(t){return this.resolveBackendConversationId(t)}getPersistedSession(t){return this.references.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 i=(o??Promise.resolve()).catch(()=>{}).then(()=>r()),s=i.catch(()=>{});return this.mergeQueues.set(t,s),s.finally(()=>{this.mergeQueues.get(t)===s&&this.mergeQueues.delete(t)}),i}updatePersistedSession(t,r){return this.stateSync.applySessionPatch(t,r)}listPersistedSessions(){return this.store.listPersistedSessions()}remindStaleDecisions(){this.reminders.remindStaleDecisions(this.store.listPersistedSessions())}sendReminderNotification(t,r){let n=Date.now(),o=t.pendingWorktreeDecisionSince?new Date(t.pendingWorktreeDecisionSince).getTime():n-14400*1e3;this.reminders.remindStaleDecisions([{...t,pendingWorktreeDecisionSince:new Date(o).toISOString(),lastWorktreeReminderAt:void 0}],n)}async handleAskUserQuestion(t,r){let n=this.sessions.get(t);if(!n)throw new Error(`Session "${t}" not found for AskUserQuestion intercept`);return this.questions.handleAskUserQuestion(n,r)}resolveAskUserQuestion(t,r){this.questions.resolveAskUserQuestion(t,r)}async resolvePendingInputOption(t,r){let n=this.sessions.get(t);return n&&await n.submitPendingInputOption(r)?(this.lastWaitingEventTimestamps.delete(t),!0):(this.questions.resolveAskUserQuestion(t,r),!0)}cleanup(){let t=Date.now();this.remindStaleDecisions(),this.runDailyWorktreeMaintenance(t);let r=(E.sessionGcAgeMinutes??1440)*6e4;for(let[n,o]of this.sessions)this.store.shouldGcActiveSession(o,t,r)&&(this.persistSession(o),this.registry.remove(n),this.lastWaitingEventTimestamps.delete(n),this.lastTurnCompleteMarkers.delete(n),this.lastTerminalWakeMarkers.delete(n));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}runDailyWorktreeMaintenance(t){if(!(t-this.lastDailyMaintenanceAt<864e5)){this.lastDailyMaintenanceAt=t;for(let o of this.store.listPersistedSessions())if(this.worktrees.isResolvedWorktreeEligibleForCleanup(o,t,6048e5))try{let i=this.resolveWorktreeRepoDir(o.workdir,o.worktreePath);if(!i)continue;let s=ot(o)?!1:ht(i,o.worktreePath);if(!ot(o)&&!s)continue;for(let a of ze(o))this.updatePersistedSession(a,{worktreePath:void 0,worktreeState:"none"})}catch(i){console.warn(`[SessionManager] Failed daily cleanup for worktree ${o.worktreePath}: ${i instanceof Error?i.message:String(i)}`)}}}dispose(){this.questions.dispose(),this.notifications.dispose()}};he();var nf;function ts(e){if(e&&typeof e=="object"){nf=e;return}nf=void 0}Le();function FI(e){let t=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"168",10)||168,r=t*60*60*1e3,n=Date.now()-r,o=new Set(e.listPersistedSessions().map(d=>d.worktreePath).filter(d=>typeof d=="string"&&d.length>0)),i=new Set,s=process.env.OPENCLAW_WORKTREE_DIR??E.worktreeDir;if(s)i.add(s);else for(let d of e.listPersistedSessions())if(d.workdir)try{let c=NI("git",["rev-parse","--show-toplevel"],{cwd:d.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();c&&i.add(of(c,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let d of i)try{let c=$I(d);for(let h of c){if(!h.startsWith("openclaw-worktree-"))continue;let m=of(d,h);try{let S=OI(m);if(!S.isDirectory()||S.mtimeMs>n||o.has(m))continue;_I(m,{recursive:!0,force:!0}),a++}catch(S){console.warn(`[index] Failed to clean up orphaned worktree ${m}: ${S instanceof Error?S.message:String(S)}`)}}}catch{}a>0&&console.info(`[index] Cleaned up ${a} orphaned worktree(s) at startup (age > ${t}h)`)}function gK(e){let t=null,r=null;ts(e.runtime),e.registerTool(n=>Gl(n),{optional:!1}),e.registerTool(n=>Im(n),{optional:!1}),e.registerTool(n=>xm(n),{optional:!1}),e.registerTool(n=>wi(n),{optional:!1}),e.registerTool(n=>vm(n),{optional:!1}),e.registerTool(n=>Rm(n),{optional:!1}),e.registerTool(n=>Am(n),{optional:!1}),e.registerTool(n=>xi(n),{optional:!1}),e.registerTool(n=>Bn(n),{optional:!1}),e.registerTool(n=>Cm(n),{optional:!1}),e.registerTool(n=>Em(n),{optional:!1}),e.registerInteractiveHandler(sd("telegram")),e.registerInteractiveHandler(sd("discord")),$m(e),Om(e),_m(e),Nm(e),Fm(e),Dm(e),e.registerService({id:"openclaw-code-agent",start:n=>{let o=e.pluginConfig??e.getConfig?.()??{};pl(o),ts(e.runtime),t=new es(E.maxSessions,E.maxPersistedSessions),Wa(t),FI(t),r=setInterval(()=>t.cleanup(),300*1e3),r.unref?.()},stop:()=>{t&&t.killAll("shutdown"),r&&clearInterval(r),t&&t.dispose(),r=null,t=null,ts(void 0),Wa(null)}})}export{gK as register};