openclaw-code-agent 3.1.0 → 3.2.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,26 +1,27 @@
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}).
1
+ var Fg=Object.defineProperty;var u=(t,e)=>()=>(t&&(e=t(t=0)),e);var lo=(t,e)=>{for(var r in e)Fg(t,r,{get:e[r],enumerable:!0})};var Me={};lo(Me,{HasPropertyKey:()=>uo,IsArray:()=>pe,IsAsyncIterator:()=>$s,IsBigInt:()=>un,IsBoolean:()=>Ot,IsDate:()=>pr,IsFunction:()=>Es,IsIterator:()=>Os,IsNull:()=>Ds,IsNumber:()=>Ge,IsObject:()=>j,IsRegExp:()=>pn,IsString:()=>Q,IsSymbol:()=>Ns,IsUint8Array:()=>Dt,IsUndefined:()=>ce});function uo(t,e){return e in t}function $s(t){return j(t)&&!pe(t)&&!Dt(t)&&Symbol.asyncIterator in t}function pe(t){return Array.isArray(t)}function un(t){return typeof t=="bigint"}function Ot(t){return typeof t=="boolean"}function pr(t){return t instanceof globalThis.Date}function Es(t){return typeof t=="function"}function Os(t){return j(t)&&!pe(t)&&!Dt(t)&&Symbol.iterator in t}function Ds(t){return t===null}function Ge(t){return typeof t=="number"}function j(t){return typeof t=="object"&&t!==null}function pn(t){return t instanceof globalThis.RegExp}function Q(t){return typeof t=="string"}function Ns(t){return typeof t=="symbol"}function Dt(t){return t instanceof globalThis.Uint8Array}function ce(t){return t===void 0}var De=u(()=>{});function Lg(t){return t.map(e=>po(e))}function Wg(t){return new Date(t.getTime())}function Bg(t){return new Uint8Array(t)}function Ug(t){return new RegExp(t.source,t.flags)}function Kg(t){let e={};for(let r of Object.getOwnPropertyNames(t))e[r]=po(t[r]);for(let r of Object.getOwnPropertySymbols(t))e[r]=po(t[r]);return e}function po(t){return pe(t)?Lg(t):pr(t)?Wg(t):Dt(t)?Bg(t):pn(t)?Ug(t):j(t)?Kg(t):t}function ee(t){return po(t)}var We=u(()=>{De()});function Er(t,e){return e===void 0?ee(t):ee({...e,...t})}var co=u(()=>{We()});var Fs=u(()=>{co();We()});function ml(t){return t!==null&&typeof t=="object"}function fl(t){return globalThis.Array.isArray(t)&&!globalThis.ArrayBuffer.isView(t)}function gl(t){return t===void 0}function hl(t){return typeof t=="number"}var Sl=u(()=>{});var yl=u(()=>{Sl()});var mo,kl=u(()=>{yl();(function(t){t.InstanceMode="default",t.ExactOptionalPropertyTypes=!1,t.AllowArrayObject=!1,t.AllowNaN=!1,t.AllowNullVoid=!1;function e(s,a){return t.ExactOptionalPropertyTypes?a in s:s[a]!==void 0}t.IsExactOptionalProperty=e;function r(s){let a=ml(s);return t.AllowArrayObject?a:a&&!fl(s)}t.IsObjectLike=r;function n(s){return r(s)&&!(s instanceof Date)&&!(s instanceof Uint8Array)}t.IsRecordLike=n;function o(s){return t.AllowNaN?hl(s):Number.isFinite(s)}t.IsNumberLike=o;function i(s){let a=gl(s);return t.AllowNullVoid?a||s===null:a}t.IsVoidLike=i})(mo||(mo={}))});function Vg(t){return globalThis.Object.freeze(t).map(e=>cn(e))}function qg(t){let e={};for(let r of Object.getOwnPropertyNames(t))e[r]=cn(t[r]);for(let r of Object.getOwnPropertySymbols(t))e[r]=cn(t[r]);return globalThis.Object.freeze(e)}function cn(t){return pe(t)?Vg(t):pr(t)?t:Dt(t)?t:pn(t)?t:j(t)?qg(t):t}var vl=u(()=>{De()});function g(t,e){let r=e!==void 0?{...e,...t}:t;switch(mo.InstanceMode){case"freeze":return cn(r);case"clone":return ee(r);default:return r}}var R=u(()=>{kl();vl();We()});var Nt=u(()=>{R()});var we,Pl=u(()=>{we=class extends Error{constructor(e){super(e)}}});var xt=u(()=>{Pl()});var ge,mt,xe,rt,P,mn=u(()=>{ge=Symbol.for("TypeBox.Transform"),mt=Symbol.for("TypeBox.Readonly"),xe=Symbol.for("TypeBox.Optional"),rt=Symbol.for("TypeBox.Hint"),P=Symbol.for("TypeBox.Kind")});var T=u(()=>{mn()});function Or(t){return j(t)&&t[mt]==="Readonly"}function Be(t){return j(t)&&t[xe]==="Optional"}function Ls(t){return N(t,"Any")}function Ws(t){return N(t,"Argument")}function ft(t){return N(t,"Array")}function cr(t){return N(t,"AsyncIterator")}function mr(t){return N(t,"BigInt")}function Ft(t){return N(t,"Boolean")}function gt(t){return N(t,"Computed")}function ht(t){return N(t,"Constructor")}function jg(t){return N(t,"Date")}function St(t){return N(t,"Function")}function yt(t){return N(t,"Integer")}function ie(t){return N(t,"Intersect")}function fr(t){return N(t,"Iterator")}function N(t,e){return j(t)&&P in t&&t[P]===e}function fo(t){return Ot(t)||Ge(t)||Q(t)}function He(t){return N(t,"Literal")}function ze(t){return N(t,"MappedKey")}function te(t){return N(t,"MappedResult")}function Gt(t){return N(t,"Never")}function Gg(t){return N(t,"Not")}function fn(t){return N(t,"Null")}function kt(t){return N(t,"Number")}function me(t){return N(t,"Object")}function gr(t){return N(t,"Promise")}function hr(t){return N(t,"Record")}function de(t){return N(t,"Ref")}function Bs(t){return N(t,"RegExp")}function Lt(t){return N(t,"String")}function gn(t){return N(t,"Symbol")}function Qe(t){return N(t,"TemplateLiteral")}function Hg(t){return N(t,"This")}function Ht(t){return j(t)&&ge in t}function Je(t){return N(t,"Tuple")}function hn(t){return N(t,"Undefined")}function L(t){return N(t,"Union")}function zg(t){return N(t,"Uint8Array")}function Qg(t){return N(t,"Unknown")}function Jg(t){return N(t,"Unsafe")}function Yg(t){return N(t,"Void")}function Xg(t){return j(t)&&P in t&&Q(t[P])}function Ye(t){return Ls(t)||Ws(t)||ft(t)||Ft(t)||mr(t)||cr(t)||gt(t)||ht(t)||jg(t)||St(t)||yt(t)||ie(t)||fr(t)||He(t)||ze(t)||te(t)||Gt(t)||Gg(t)||fn(t)||kt(t)||me(t)||gr(t)||hr(t)||de(t)||Bs(t)||Lt(t)||gn(t)||Qe(t)||Hg(t)||Je(t)||hn(t)||L(t)||zg(t)||Qg(t)||Jg(t)||Yg(t)||Xg(t)}var B=u(()=>{De();T()});var c={};lo(c,{IsAny:()=>xl,IsArgument:()=>Al,IsArray:()=>Rl,IsAsyncIterator:()=>Tl,IsBigInt:()=>Ml,IsBoolean:()=>Cl,IsComputed:()=>_l,IsConstructor:()=>$l,IsDate:()=>El,IsFunction:()=>Ol,IsImport:()=>oh,IsInteger:()=>Dl,IsIntersect:()=>Nl,IsIterator:()=>Fl,IsKind:()=>lu,IsKindOf:()=>E,IsLiteral:()=>yn,IsLiteralBoolean:()=>ih,IsLiteralNumber:()=>Wl,IsLiteralString:()=>Ll,IsLiteralValue:()=>Bl,IsMappedKey:()=>Ul,IsMappedResult:()=>Kl,IsNever:()=>Vl,IsNot:()=>ql,IsNull:()=>jl,IsNumber:()=>Gl,IsObject:()=>Hl,IsOptional:()=>nh,IsPromise:()=>zl,IsProperties:()=>go,IsReadonly:()=>rh,IsRecord:()=>Ql,IsRecursive:()=>sh,IsRef:()=>Jl,IsRegExp:()=>Yl,IsSchema:()=>Ie,IsString:()=>Xl,IsSymbol:()=>Zl,IsTemplateLiteral:()=>eu,IsThis:()=>tu,IsTransform:()=>ru,IsTuple:()=>nu,IsUint8Array:()=>iu,IsUndefined:()=>ou,IsUnion:()=>qs,IsUnionLiteral:()=>ah,IsUnknown:()=>su,IsUnsafe:()=>au,IsVoid:()=>du,TypeGuardUnknownTypeError:()=>Us});function wl(t){try{return new RegExp(t),!0}catch{return!1}}function Ks(t){if(!Q(t))return!1;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(r>=7&&r<=13||r===27||r===127)return!1}return!0}function Il(t){return Vs(t)||Ie(t)}function Sn(t){return ce(t)||un(t)}function J(t){return ce(t)||Ge(t)}function Vs(t){return ce(t)||Ot(t)}function G(t){return ce(t)||Q(t)}function eh(t){return ce(t)||Q(t)&&Ks(t)&&wl(t)}function th(t){return ce(t)||Q(t)&&Ks(t)}function bl(t){return ce(t)||Ie(t)}function rh(t){return j(t)&&t[mt]==="Readonly"}function nh(t){return j(t)&&t[xe]==="Optional"}function xl(t){return E(t,"Any")&&G(t.$id)}function Al(t){return E(t,"Argument")&&Ge(t.index)}function Rl(t){return E(t,"Array")&&t.type==="array"&&G(t.$id)&&Ie(t.items)&&J(t.minItems)&&J(t.maxItems)&&Vs(t.uniqueItems)&&bl(t.contains)&&J(t.minContains)&&J(t.maxContains)}function Tl(t){return E(t,"AsyncIterator")&&t.type==="AsyncIterator"&&G(t.$id)&&Ie(t.items)}function Ml(t){return E(t,"BigInt")&&t.type==="bigint"&&G(t.$id)&&Sn(t.exclusiveMaximum)&&Sn(t.exclusiveMinimum)&&Sn(t.maximum)&&Sn(t.minimum)&&Sn(t.multipleOf)}function Cl(t){return E(t,"Boolean")&&t.type==="boolean"&&G(t.$id)}function _l(t){return E(t,"Computed")&&Q(t.target)&&pe(t.parameters)&&t.parameters.every(e=>Ie(e))}function $l(t){return E(t,"Constructor")&&t.type==="Constructor"&&G(t.$id)&&pe(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function El(t){return E(t,"Date")&&t.type==="Date"&&G(t.$id)&&J(t.exclusiveMaximumTimestamp)&&J(t.exclusiveMinimumTimestamp)&&J(t.maximumTimestamp)&&J(t.minimumTimestamp)&&J(t.multipleOfTimestamp)}function Ol(t){return E(t,"Function")&&t.type==="Function"&&G(t.$id)&&pe(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function oh(t){return E(t,"Import")&&uo(t,"$defs")&&j(t.$defs)&&go(t.$defs)&&uo(t,"$ref")&&Q(t.$ref)&&t.$ref in t.$defs}function Dl(t){return E(t,"Integer")&&t.type==="integer"&&G(t.$id)&&J(t.exclusiveMaximum)&&J(t.exclusiveMinimum)&&J(t.maximum)&&J(t.minimum)&&J(t.multipleOf)}function go(t){return j(t)&&Object.entries(t).every(([e,r])=>Ks(e)&&Ie(r))}function Nl(t){return E(t,"Intersect")&&!(Q(t.type)&&t.type!=="object")&&pe(t.allOf)&&t.allOf.every(e=>Ie(e)&&!ru(e))&&G(t.type)&&(Vs(t.unevaluatedProperties)||bl(t.unevaluatedProperties))&&G(t.$id)}function Fl(t){return E(t,"Iterator")&&t.type==="Iterator"&&G(t.$id)&&Ie(t.items)}function E(t,e){return j(t)&&P in t&&t[P]===e}function Ll(t){return yn(t)&&Q(t.const)}function Wl(t){return yn(t)&&Ge(t.const)}function ih(t){return yn(t)&&Ot(t.const)}function yn(t){return E(t,"Literal")&&G(t.$id)&&Bl(t.const)}function Bl(t){return Ot(t)||Ge(t)||Q(t)}function Ul(t){return E(t,"MappedKey")&&pe(t.keys)&&t.keys.every(e=>Ge(e)||Q(e))}function Kl(t){return E(t,"MappedResult")&&go(t.properties)}function Vl(t){return E(t,"Never")&&j(t.not)&&Object.getOwnPropertyNames(t.not).length===0}function ql(t){return E(t,"Not")&&Ie(t.not)}function jl(t){return E(t,"Null")&&t.type==="null"&&G(t.$id)}function Gl(t){return E(t,"Number")&&t.type==="number"&&G(t.$id)&&J(t.exclusiveMaximum)&&J(t.exclusiveMinimum)&&J(t.maximum)&&J(t.minimum)&&J(t.multipleOf)}function Hl(t){return E(t,"Object")&&t.type==="object"&&G(t.$id)&&go(t.properties)&&Il(t.additionalProperties)&&J(t.minProperties)&&J(t.maxProperties)}function zl(t){return E(t,"Promise")&&t.type==="Promise"&&G(t.$id)&&Ie(t.item)}function Ql(t){return E(t,"Record")&&t.type==="object"&&G(t.$id)&&Il(t.additionalProperties)&&j(t.patternProperties)&&(e=>{let r=Object.getOwnPropertyNames(e.patternProperties);return r.length===1&&wl(r[0])&&j(e.patternProperties)&&Ie(e.patternProperties[r[0]])})(t)}function sh(t){return j(t)&&rt in t&&t[rt]==="Recursive"}function Jl(t){return E(t,"Ref")&&G(t.$id)&&Q(t.$ref)}function Yl(t){return E(t,"RegExp")&&G(t.$id)&&Q(t.source)&&Q(t.flags)&&J(t.maxLength)&&J(t.minLength)}function Xl(t){return E(t,"String")&&t.type==="string"&&G(t.$id)&&J(t.minLength)&&J(t.maxLength)&&eh(t.pattern)&&th(t.format)}function Zl(t){return E(t,"Symbol")&&t.type==="symbol"&&G(t.$id)}function eu(t){return E(t,"TemplateLiteral")&&t.type==="string"&&Q(t.pattern)&&t.pattern[0]==="^"&&t.pattern[t.pattern.length-1]==="$"}function tu(t){return E(t,"This")&&G(t.$id)&&Q(t.$ref)}function ru(t){return j(t)&&ge in t}function nu(t){return E(t,"Tuple")&&t.type==="array"&&G(t.$id)&&Ge(t.minItems)&&Ge(t.maxItems)&&t.minItems===t.maxItems&&(ce(t.items)&&ce(t.additionalItems)&&t.minItems===0||pe(t.items)&&t.items.every(e=>Ie(e)))}function ou(t){return E(t,"Undefined")&&t.type==="undefined"&&G(t.$id)}function ah(t){return qs(t)&&t.anyOf.every(e=>Ll(e)||Wl(e))}function qs(t){return E(t,"Union")&&G(t.$id)&&j(t)&&pe(t.anyOf)&&t.anyOf.every(e=>Ie(e))}function iu(t){return E(t,"Uint8Array")&&t.type==="Uint8Array"&&G(t.$id)&&J(t.minByteLength)&&J(t.maxByteLength)}function su(t){return E(t,"Unknown")&&G(t.$id)}function au(t){return E(t,"Unsafe")}function du(t){return E(t,"Void")&&t.type==="void"&&G(t.$id)}function lu(t){return j(t)&&P in t&&Q(t[P])&&!Zg.includes(t[P])}function Ie(t){return j(t)&&(xl(t)||Al(t)||Rl(t)||Cl(t)||Ml(t)||Tl(t)||_l(t)||$l(t)||El(t)||Ol(t)||Dl(t)||Nl(t)||Fl(t)||yn(t)||Ul(t)||Kl(t)||Vl(t)||ql(t)||jl(t)||Gl(t)||Hl(t)||zl(t)||Ql(t)||Jl(t)||Yl(t)||Xl(t)||Zl(t)||eu(t)||tu(t)||nu(t)||ou(t)||qs(t)||iu(t)||su(t)||au(t)||du(t)||lu(t))}var Us,Zg,uu=u(()=>{De();T();xt();Us=class extends we{},Zg=["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 js=u(()=>{B();uu();De()});var pu=u(()=>{});var cu=u(()=>{pu()});var Gs,kn,Hs,dh,nx,zt,Qt,mu,fu=u(()=>{Gs="(true|false)",kn="(0|[1-9][0-9]*)",Hs="(.*)",dh="(?!.*)",nx=`^${Gs}$`,zt=`^${kn}$`,Qt=`^${Hs}$`,mu=`^${dh}$`});var vn=u(()=>{fu()});var gu=u(()=>{});var hu=u(()=>{});var Su=u(()=>{gu();hu()});function yu(t,e){return t.includes(e)}function ku(t){return[...new Set(t)]}function ph(t,e){return t.filter(r=>e.includes(r))}function ch(t,e){return t.reduce((r,n)=>ph(r,n),e)}function vu(t){return t.length===1?t[0]:t.length>1?ch(t.slice(1),t[0]):[]}function Pu(t){let e=[];for(let r of t)e.push(...r);return e}var wu=u(()=>{});var Pn=u(()=>{wu()});function Jt(t){return g({[P]:"Any"},t)}var Iu=u(()=>{Nt();T()});var wn=u(()=>{Iu()});function Dr(t,e){return g({[P]:"Array",type:"array",items:t},e)}var bu=u(()=>{R();T()});var In=u(()=>{bu()});function xu(t){return g({[P]:"Argument",index:t})}var Au=u(()=>{R();T()});var zs=u(()=>{Au()});function Nr(t,e){return g({[P]:"AsyncIterator",type:"AsyncIterator",items:t},e)}var Ru=u(()=>{T();R()});var bn=u(()=>{Ru()});function Z(t,e,r){return g({[P]:"Computed",target:t,parameters:e},r)}var Tu=u(()=>{Nt();mn()});var Yt=u(()=>{Tu()});function mh(t,e){let{[e]:r,...n}=t;return n}function se(t,e){return e.reduce((r,n)=>mh(r,n),t)}var ho=u(()=>{});var Bt=u(()=>{ho()});function W(t){return g({[P]:"Never",not:{}},t)}var Mu=u(()=>{R();T()});var Ae=u(()=>{Mu()});var Cu=u(()=>{});function U(t){return g({[P]:"MappedResult",properties:t})}var Qs=u(()=>{R();T()});function Fr(t,e,r){return g({[P]:"Constructor",type:"Constructor",parameters:t,returns:e},r)}var _u=u(()=>{R();T()});var xn=u(()=>{_u()});function At(t,e,r){return g({[P]:"Function",type:"Function",parameters:t,returns:e},r)}var $u=u(()=>{R();T()});var Sr=u(()=>{$u()});function An(t,e){return g({[P]:"Union",anyOf:t},e)}var Js=u(()=>{R();T()});function fh(t){return t.some(e=>Be(e))}function Eu(t){return t.map(e=>Be(e)?gh(e):e)}function gh(t){return se(t,[xe])}function hh(t,e){return fh(t)?Ce(An(Eu(t),e)):An(Eu(t),e)}function Rt(t,e){return t.length===1?g(t[0],e):t.length===0?W(e):hh(t,e)}var Ou=u(()=>{R();T();Bt();Ae();Ut();Js();B()});var Du=u(()=>{});function q(t,e){return t.length===0?W(e):t.length===1?g(t[0],e):An(t,e)}var Nu=u(()=>{Ae();R();Js()});var he=u(()=>{Ou();Du();Nu()});function Sh(t){return t.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Ys(t,e,r){return t[e]===r&&t.charCodeAt(e-1)!==92}function Kt(t,e){return Ys(t,e,"(")}function Rn(t,e){return Ys(t,e,")")}function Fu(t,e){return Ys(t,e,"|")}function yh(t){if(!(Kt(t,0)&&Rn(t,t.length-1)))return!1;let e=0;for(let r=0;r<t.length;r++)if(Kt(t,r)&&(e+=1),Rn(t,r)&&(e-=1),e===0&&r!==t.length-1)return!1;return!0}function kh(t){return t.slice(1,t.length-1)}function vh(t){let e=0;for(let r=0;r<t.length;r++)if(Kt(t,r)&&(e+=1),Rn(t,r)&&(e-=1),Fu(t,r)&&e===0)return!0;return!1}function Ph(t){for(let e=0;e<t.length;e++)if(Kt(t,e))return!0;return!1}function wh(t){let[e,r]=[0,0],n=[];for(let i=0;i<t.length;i++)if(Kt(t,i)&&(e+=1),Rn(t,i)&&(e-=1),Fu(t,i)&&e===0){let s=t.slice(r,i);s.length>0&&n.push(Lr(s)),r=i+1}let o=t.slice(r);return o.length>0&&n.push(Lr(o)),n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"or",expr:n}}function Ih(t){function e(o,i){if(!Kt(o,i))throw new So("TemplateLiteralParser: Index must point to open parens");let s=0;for(let a=i;a<o.length;a++)if(Kt(o,a)&&(s+=1),Rn(o,a)&&(s-=1),s===0)return[i,a];throw new So("TemplateLiteralParser: Unclosed group parens in expression")}function r(o,i){for(let s=i;s<o.length;s++)if(Kt(o,s))return[i,s];return[i,o.length]}let n=[];for(let o=0;o<t.length;o++)if(Kt(t,o)){let[i,s]=e(t,o),a=t.slice(i,s+1);n.push(Lr(a)),o=s}else{let[i,s]=r(t,o),a=t.slice(i,s);a.length>0&&n.push(Lr(a)),o=s-1}return n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"and",expr:n}}function Lr(t){return yh(t)?Lr(kh(t)):vh(t)?wh(t):Ph(t)?Ih(t):{type:"const",const:Sh(t)}}function Wr(t){return Lr(t.slice(1,t.length-1))}var So,yo=u(()=>{xt();So=class extends we{}});function bh(t){return t.type==="or"&&t.expr.length===2&&t.expr[0].type==="const"&&t.expr[0].const==="0"&&t.expr[1].type==="const"&&t.expr[1].const==="[1-9][0-9]*"}function xh(t){return t.type==="or"&&t.expr.length===2&&t.expr[0].type==="const"&&t.expr[0].const==="true"&&t.expr[1].type==="const"&&t.expr[1].const==="false"}function Ah(t){return t.type==="const"&&t.const===".*"}function yr(t){return bh(t)||Ah(t)?!1:xh(t)?!0:t.type==="and"?t.expr.every(e=>yr(e)):t.type==="or"?t.expr.every(e=>yr(e)):t.type==="const"?!0:(()=>{throw new Xs("Unknown expression type")})()}function Lu(t){let e=Wr(t.pattern);return yr(e)}var Xs,Zs=u(()=>{yo();xt();Xs=class extends we{}});function*Wu(t){if(t.length===1)return yield*t[0];for(let e of t[0])for(let r of Wu(t.slice(1)))yield`${e}${r}`}function*Rh(t){return yield*Wu(t.expr.map(e=>[...Tn(e)]))}function*Th(t){for(let e of t.expr)yield*Tn(e)}function*Mh(t){return yield t.const}function*Tn(t){return t.type==="and"?yield*Rh(t):t.type==="or"?yield*Th(t):t.type==="const"?yield*Mh(t):(()=>{throw new ea("Unknown expression")})()}function ko(t){let e=Wr(t.pattern);return yr(e)?[...Tn(e)]:[]}var ea,ta=u(()=>{Zs();yo();xt();ea=class extends we{}});function V(t,e){return g({[P]:"Literal",const:t,type:typeof t},e)}var Bu=u(()=>{R();T()});var Ue=u(()=>{Bu()});function vo(t){return g({[P]:"Boolean",type:"boolean"},t)}var Uu=u(()=>{T();Nt()});var Po=u(()=>{Uu()});function Br(t){return g({[P]:"BigInt",type:"bigint"},t)}var Ku=u(()=>{T();Nt()});var Mn=u(()=>{Ku()});function nt(t){return g({[P]:"Number",type:"number"},t)}var Vu=u(()=>{R();T()});var kr=u(()=>{Vu()});function vt(t){return g({[P]:"String",type:"string"},t)}var qu=u(()=>{R();T()});var Ur=u(()=>{qu()});function*Ch(t){let e=t.trim().replace(/"|'/g,"");return e==="boolean"?yield vo():e==="number"?yield nt():e==="bigint"?yield Br():e==="string"?yield vt():yield(()=>{let r=e.split("|").map(n=>V(n.trim()));return r.length===0?W():r.length===1?r[0]:Rt(r)})()}function*_h(t){if(t[1]!=="{"){let e=V("$"),r=ra(t.slice(1));return yield*[e,...r]}for(let e=2;e<t.length;e++)if(t[e]==="}"){let r=Ch(t.slice(2,e)),n=ra(t.slice(e+1));return yield*[...r,...n]}yield V(t)}function*ra(t){for(let e=0;e<t.length;e++)if(t[e]==="$"){let r=V(t.slice(0,e)),n=_h(t.slice(e));return yield*[r,...n]}yield V(t)}function ju(t){return[...ra(t)]}var na=u(()=>{Ue();Po();Mn();kr();Ur();he();Ae()});function $h(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gu(t,e){return Qe(t)?t.pattern.slice(1,t.pattern.length-1):L(t)?`(${t.anyOf.map(r=>Gu(r,e)).join("|")})`:kt(t)?`${e}${kn}`:yt(t)?`${e}${kn}`:mr(t)?`${e}${kn}`:Lt(t)?`${e}${Hs}`:He(t)?`${e}${$h(t.const.toString())}`:Ft(t)?`${e}${Gs}`:(()=>{throw new oa(`Unexpected Kind '${t[P]}'`)})()}function ia(t){return`^${t.map(e=>Gu(e,"")).join("")}$`}var oa,sa=u(()=>{vn();T();xt();B();oa=class extends we{}});function vr(t){let r=ko(t).map(n=>V(n));return Rt(r)}var Hu=u(()=>{he();Ue();ta()});function wo(t,e){let r=Q(t)?ia(ju(t)):ia(t);return g({[P]:"TemplateLiteral",type:"string",pattern:r},e)}var zu=u(()=>{R();na();sa();De();T()});var Vt=u(()=>{Zs();ta();na();yo();sa();Hu();zu()});function Eh(t){return ko(t).map(r=>r.toString())}function Oh(t){let e=[];for(let r of t)e.push(...Ke(r));return e}function Dh(t){return[t.toString()]}function Ke(t){return[...new Set(Qe(t)?Eh(t):L(t)?Oh(t.anyOf):He(t)?Dh(t.const):kt(t)?["[number]"]:yt(t)?["[number]"]:[])]}var Io=u(()=>{Vt();B()});function Nh(t,e,r){let n={};for(let o of Object.getOwnPropertyNames(e))n[o]=Xt(t,Ke(e[o]),r);return n}function Fh(t,e,r){return Nh(t,e.properties,r)}function Qu(t,e,r){let n=Fh(t,e,r);return U(n)}var aa=u(()=>{ve();Io();Tt()});function Yu(t,e){return t.map(r=>Xu(r,e))}function Lh(t){return t.filter(e=>!Gt(e))}function Wh(t,e){return bo(Lh(Yu(t,e)))}function Bh(t){return t.some(e=>Gt(e))?[]:t}function Uh(t,e){return Rt(Bh(Yu(t,e)))}function Kh(t,e){return e in t?t[e]:e==="[number]"?Rt(t):W()}function Vh(t,e){return e==="[number]"?t:W()}function qh(t,e){return e in t?t[e]:W()}function Xu(t,e){return ie(t)?Wh(t.allOf,e):L(t)?Uh(t.anyOf,e):Je(t)?Kh(t.items??[],e):ft(t)?Vh(t.items,e):me(t)?qh(t.properties,e):W()}function da(t,e){return e.map(r=>Xu(t,r))}function Ju(t,e){return Rt(da(t,e))}function Xt(t,e,r){if(de(t)||de(e)){let n="Index types using Ref parameters require both Type and Key to be of TSchema";if(!Ye(t)||!Ye(e))throw new we(n);return Z("Index",[t,e])}return te(e)?Qu(t,e,r):ze(e)?Zu(t,e,r):g(Ye(e)?Ju(t,Ke(e)):Ju(t,e),r)}var la=u(()=>{R();xt();Yt();Ae();ot();he();Io();ua();aa();B()});function jh(t,e,r){return{[e]:Xt(t,[e],ee(r))}}function Gh(t,e,r){return e.reduce((n,o)=>({...n,...jh(t,o,r)}),{})}function Hh(t,e,r){return Gh(t,e.keys,r)}function Zu(t,e,r){let n=Hh(t,e,r);return U(n)}var ua=u(()=>{la();ve();We()});var Tt=u(()=>{ua();aa();Io();la()});function Kr(t,e){return g({[P]:"Iterator",type:"Iterator",items:t},e)}var ep=u(()=>{R();T()});var Cn=u(()=>{ep()});function zh(t){return globalThis.Object.keys(t).filter(e=>!Be(t[e]))}function Qh(t,e){let r=zh(t),n=r.length>0?{[P]:"Object",type:"object",required:r,properties:t}:{[P]:"Object",type:"object",properties:t};return g(n,e)}var H,tp=u(()=>{R();T();B();H=Qh});var Xe=u(()=>{tp()});function xo(t,e){return g({[P]:"Promise",type:"Promise",item:t},e)}var rp=u(()=>{R();T()});var Ao=u(()=>{rp()});function Jh(t){return g(se(t,[mt]))}function Yh(t){return g({...t,[mt]:"Readonly"})}function Xh(t,e){return e===!1?Jh(t):Yh(t)}function Ve(t,e){let r=e??!0;return te(t)?np(t,r):Xh(t,r)}var pa=u(()=>{R();T();Bt();ca();B()});function Zh(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Ve(t[n],e);return r}function eS(t,e){return Zh(t.properties,e)}function np(t,e){let r=eS(t,e);return U(r)}var ca=u(()=>{ve();pa()});var Pr=u(()=>{ca();pa()});function it(t,e){return g(t.length>0?{[P]:"Tuple",type:"array",items:t,additionalItems:!1,minItems:t.length,maxItems:t.length}:{[P]:"Tuple",type:"array",minItems:t.length,maxItems:t.length},e)}var op=u(()=>{R();T()});var Zt=u(()=>{op()});function ip(t,e){return t in e?st(t,e[t]):U(e)}function tS(t){return{[t]:V(t)}}function rS(t){let e={};for(let r of t)e[r]=V(r);return e}function nS(t,e){return yu(e,t)?tS(t):rS(e)}function oS(t,e){let r=nS(t,e);return ip(t,r)}function _n(t,e){return e.map(r=>st(t,r))}function iS(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=st(t,e[n]);return r}function st(t,e){let r={...e};return Be(e)?Ce(st(t,se(e,[xe]))):Or(e)?Ve(st(t,se(e,[mt]))):te(e)?ip(t,e.properties):ze(e)?oS(t,e.keys):ht(e)?Fr(_n(t,e.parameters),st(t,e.returns),r):St(e)?At(_n(t,e.parameters),st(t,e.returns),r):cr(e)?Nr(st(t,e.items),r):fr(e)?Kr(st(t,e.items),r):ie(e)?_e(_n(t,e.allOf),r):L(e)?q(_n(t,e.anyOf),r):Je(e)?it(_n(t,e.items??[]),r):me(e)?H(iS(t,e.properties),r):ft(e)?Dr(st(t,e.items),r):gr(e)?xo(st(t,e.item),r):e}function sS(t,e){let r={};for(let n of t)r[n]=st(n,e);return r}function sp(t,e,r){let n=Ye(t)?Ke(t):t,o=e({[P]:"MappedKey",keys:n}),i=sS(n,o);return H(i,r)}var ap=u(()=>{T();Bt();In();bn();xn();Sr();Tt();ot();Cn();Ue();Xe();Ut();Ao();Pr();Zt();he();Pn();Qs();B()});var ve=u(()=>{Cu();Qs();ap()});function aS(t){return g(se(t,[xe]))}function dS(t){return g({...t,[xe]:"Optional"})}function lS(t,e){return e===!1?aS(t):dS(t)}function Ce(t,e){let r=e??!0;return te(t)?dp(t,r):lS(t,r)}var ma=u(()=>{R();T();Bt();fa();B()});function uS(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Ce(t[n],e);return r}function pS(t,e){return uS(t.properties,e)}function dp(t,e){let r=pS(t,e);return U(r)}var fa=u(()=>{ve();ma()});var Ut=u(()=>{fa();ma()});function $n(t,e={}){let r=t.every(o=>me(o)),n=Ye(e.unevaluatedProperties)?{unevaluatedProperties:e.unevaluatedProperties}:{};return g(e.unevaluatedProperties===!1||Ye(e.unevaluatedProperties)||r?{...n,[P]:"Intersect",type:"object",allOf:t}:{...n,[P]:"Intersect",allOf:t},e)}var ga=u(()=>{R();T();B()});function cS(t){return t.every(e=>Be(e))}function mS(t){return se(t,[xe])}function lp(t){return t.map(e=>Be(e)?mS(e):e)}function fS(t,e){return cS(t)?Ce($n(lp(t),e)):$n(lp(t),e)}function bo(t,e={}){if(t.length===1)return g(t[0],e);if(t.length===0)return W(e);if(t.some(r=>Ht(r)))throw new Error("Cannot intersect transform types");return fS(t,e)}var up=u(()=>{T();R();Bt();Ae();Ut();ga();B()});var pp=u(()=>{});function _e(t,e){if(t.length===1)return g(t[0],e);if(t.length===0)return W(e);if(t.some(r=>Ht(r)))throw new Error("Cannot intersect transform types");return $n(t,e)}var cp=u(()=>{R();Ae();ga();B()});var ot=u(()=>{up();pp();cp()});function Mt(...t){let[e,r]=typeof t[0]=="string"?[t[0],t[1]]:[t[0].$id,t[1]];if(typeof e!="string")throw new we("Ref: $ref must be a string");return g({[P]:"Ref",$ref:e},r)}var mp=u(()=>{xt();R();T()});var wr=u(()=>{mp()});function gS(t,e){return Z("Awaited",[Z(t,e)])}function hS(t){return Z("Awaited",[Mt(t)])}function SS(t){return _e(fp(t))}function yS(t){return q(fp(t))}function kS(t){return Vr(t)}function fp(t){return t.map(e=>Vr(e))}function Vr(t,e){return g(gt(t)?gS(t.target,t.parameters):ie(t)?SS(t.allOf):L(t)?yS(t.anyOf):gr(t)?kS(t.item):de(t)?hS(t.$ref):t,e)}var gp=u(()=>{R();Yt();ot();he();wr();B()});var Ro=u(()=>{gp()});function hp(t){let e=[];for(let r of t)e.push(En(r));return e}function vS(t){let e=hp(t);return Pu(e)}function PS(t){let e=hp(t);return vu(e)}function wS(t){return t.map((e,r)=>r.toString())}function IS(t){return["[number]"]}function bS(t){return globalThis.Object.getOwnPropertyNames(t)}function xS(t){return AS?globalThis.Object.getOwnPropertyNames(t).map(r=>r[0]==="^"&&r[r.length-1]==="$"?r.slice(1,r.length-1):r):[]}function En(t){return ie(t)?vS(t.allOf):L(t)?PS(t.anyOf):Je(t)?wS(t.items??[]):ft(t)?IS(t.items):me(t)?bS(t.properties):hr(t)?xS(t.patternProperties):[]}var AS,ha=u(()=>{Pn();B();AS=!1});function RS(t,e){return Z("KeyOf",[Z(t,e)])}function TS(t){return Z("KeyOf",[Mt(t)])}function MS(t,e){let r=En(t),n=CS(r),o=Rt(n);return g(o,e)}function CS(t){return t.map(e=>e==="[number]"?nt():V(e))}function qr(t,e){return gt(t)?RS(t.target,t.parameters):de(t)?TS(t.$ref):te(t)?Sp(t,e):MS(t,e)}var Sa=u(()=>{R();Ue();kr();Yt();wr();ha();he();ya();B()});function _S(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=qr(t[n],ee(e));return r}function $S(t,e){return _S(t.properties,e)}function Sp(t,e){let r=$S(t,e);return U(r)}var ya=u(()=>{ve();Sa();We()});var yp=u(()=>{});var On=u(()=>{ya();yp();ha();Sa()});function ES(t){let e=[];for(let r of t)e.push(...En(r));return ku(e)}function OS(t){return t.filter(e=>!Gt(e))}function DS(t,e){let r=[];for(let n of t)r.push(...da(n,[e]));return OS(r)}function NS(t,e){let r={};for(let n of e)r[n]=bo(DS(t,n));return r}function kp(t,e){let r=ES(t),n=NS(t,r);return H(n,e)}var vp=u(()=>{ot();Tt();On();Xe();Pn();B()});var ka=u(()=>{vp()});function To(t){return g({[P]:"Date",type:"Date"},t)}var Pp=u(()=>{T();R()});var Mo=u(()=>{Pp()});function Co(t){return g({[P]:"Null",type:"null"},t)}var wp=u(()=>{R();T()});var _o=u(()=>{wp()});function $o(t){return g({[P]:"Symbol",type:"symbol"},t)}var Ip=u(()=>{R();T()});var Eo=u(()=>{Ip()});function Oo(t){return g({[P]:"Undefined",type:"undefined"},t)}var bp=u(()=>{R();T()});var Do=u(()=>{bp()});function No(t){return g({[P]:"Uint8Array",type:"Uint8Array"},t)}var xp=u(()=>{R();T()});var Fo=u(()=>{xp()});function er(t){return g({[P]:"Unknown"},t)}var Ap=u(()=>{R();T()});var jr=u(()=>{Ap()});function FS(t){return t.map(e=>va(e,!1))}function LS(t){let e={};for(let r of globalThis.Object.getOwnPropertyNames(t))e[r]=Ve(va(t[r],!1));return e}function Lo(t,e){return e===!0?t:Ve(t)}function va(t,e){return $s(t)?Lo(Jt(),e):Os(t)?Lo(Jt(),e):pe(t)?Ve(it(FS(t))):Dt(t)?No():pr(t)?To():j(t)?Lo(H(LS(t)),e):Es(t)?Lo(At([],er()),e):ce(t)?Oo():Ds(t)?Co():Ns(t)?$o():un(t)?Br():Ge(t)?V(t):Ot(t)?V(t):Q(t)?V(t):H({})}function Rp(t,e){return g(va(t,!0),e)}var Tp=u(()=>{wn();Mn();Mo();Sr();Ue();_o();Xe();Eo();Zt();Pr();Do();Fo();jr();Nt();De()});var Pa=u(()=>{Tp()});function Mp(t,e){return ht(t)?it(t.parameters,e):W(e)}var Cp=u(()=>{Zt();Ae();B()});var wa=u(()=>{Cp()});function _p(t,e){if(ce(t))throw new Error("Enum undefined or empty");let r=globalThis.Object.getOwnPropertyNames(t).filter(i=>isNaN(i)).map(i=>t[i]),o=[...new Set(r)].map(i=>V(i));return q(o,{...e,[rt]:"Enum"})}var $p=u(()=>{Ue();T();he();De()});var Ia=u(()=>{$p()});function at(t){return t===h.False?t:h.True}function Gr(t){throw new xa(t)}function Se(t){return c.IsNever(t)||c.IsIntersect(t)||c.IsUnion(t)||c.IsUnknown(t)||c.IsAny(t)}function ye(t,e){return c.IsNever(e)?Wp(t,e):c.IsIntersect(e)?Wo(t,e):c.IsUnion(e)?Ma(t,e):c.IsUnknown(e)?Vp(t,e):c.IsAny(e)?Ta(t,e):Gr("StructuralRight")}function Ta(t,e){return h.True}function WS(t,e){return c.IsIntersect(e)?Wo(t,e):c.IsUnion(e)&&e.anyOf.some(r=>c.IsAny(r)||c.IsUnknown(r))?h.True:c.IsUnion(e)?h.Union:c.IsUnknown(e)||c.IsAny(e)?h.True:h.Union}function BS(t,e){return c.IsUnknown(t)?h.False:c.IsAny(t)?h.Union:c.IsNever(t)?h.True:h.False}function US(t,e){return c.IsObject(e)&&Bo(e)?h.True:Se(e)?ye(t,e):c.IsArray(e)?at(z(t.items,e.items)):h.False}function KS(t,e){return Se(e)?ye(t,e):c.IsAsyncIterator(e)?at(z(t.items,e.items)):h.False}function VS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsBigInt(e)?h.True:h.False}function Fp(t,e){return c.IsLiteralBoolean(t)||c.IsBoolean(t)?h.True:h.False}function qS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsBoolean(e)?h.True:h.False}function jS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsConstructor(e)?t.parameters.length>e.parameters.length?h.False:t.parameters.every((r,n)=>at(z(e.parameters[n],r))===h.True)?at(z(t.returns,e.returns)):h.False:h.False}function GS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsDate(e)?h.True:h.False}function HS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsFunction(e)?t.parameters.length>e.parameters.length?h.False:t.parameters.every((r,n)=>at(z(e.parameters[n],r))===h.True)?at(z(t.returns,e.returns)):h.False:h.False}function Lp(t,e){return c.IsLiteral(t)&&Me.IsNumber(t.const)||c.IsNumber(t)||c.IsInteger(t)?h.True:h.False}function zS(t,e){return c.IsInteger(e)||c.IsNumber(e)?h.True:Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):h.False}function Wo(t,e){return e.allOf.every(r=>z(t,r)===h.True)?h.True:h.False}function QS(t,e){return t.allOf.some(r=>z(r,e)===h.True)?h.True:h.False}function JS(t,e){return Se(e)?ye(t,e):c.IsIterator(e)?at(z(t.items,e.items)):h.False}function YS(t,e){return c.IsLiteral(e)&&e.const===t.const?h.True:Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsString(e)?Kp(t,e):c.IsNumber(e)?Bp(t,e):c.IsInteger(e)?Lp(t,e):c.IsBoolean(e)?Fp(t,e):h.False}function Wp(t,e){return h.False}function XS(t,e){return h.True}function Ep(t){let[e,r]=[t,0];for(;c.IsNot(e);)e=e.not,r+=1;return r%2===0?e:er()}function ZS(t,e){return c.IsNot(t)?z(Ep(t),e):c.IsNot(e)?z(t,Ep(e)):Gr("Invalid fallthrough for Not")}function ey(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsNull(e)?h.True:h.False}function Bp(t,e){return c.IsLiteralNumber(t)||c.IsNumber(t)||c.IsInteger(t)?h.True:h.False}function ty(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsInteger(e)||c.IsNumber(e)?h.True:h.False}function qe(t,e){return Object.getOwnPropertyNames(t.properties).length===e}function Op(t){return Bo(t)}function Dp(t){return qe(t,0)||qe(t,1)&&"description"in t.properties&&c.IsUnion(t.properties.description)&&t.properties.description.anyOf.length===2&&(c.IsString(t.properties.description.anyOf[0])&&c.IsUndefined(t.properties.description.anyOf[1])||c.IsString(t.properties.description.anyOf[1])&&c.IsUndefined(t.properties.description.anyOf[0]))}function ba(t){return qe(t,0)}function Np(t){return qe(t,0)}function ry(t){return qe(t,0)}function ny(t){return qe(t,0)}function oy(t){return Bo(t)}function iy(t){let e=nt();return qe(t,0)||qe(t,1)&&"length"in t.properties&&at(z(t.properties.length,e))===h.True}function sy(t){return qe(t,0)}function Bo(t){let e=nt();return qe(t,0)||qe(t,1)&&"length"in t.properties&&at(z(t.properties.length,e))===h.True}function ay(t){let e=At([Jt()],Jt());return qe(t,0)||qe(t,1)&&"then"in t.properties&&at(z(t.properties.then,e))===h.True}function Up(t,e){return z(t,e)===h.False||c.IsOptional(t)&&!c.IsOptional(e)?h.False:h.True}function $e(t,e){return c.IsUnknown(t)?h.False:c.IsAny(t)?h.Union:c.IsNever(t)||c.IsLiteralString(t)&&Op(e)||c.IsLiteralNumber(t)&&ba(e)||c.IsLiteralBoolean(t)&&Np(e)||c.IsSymbol(t)&&Dp(e)||c.IsBigInt(t)&&ry(e)||c.IsString(t)&&Op(e)||c.IsSymbol(t)&&Dp(e)||c.IsNumber(t)&&ba(e)||c.IsInteger(t)&&ba(e)||c.IsBoolean(t)&&Np(e)||c.IsUint8Array(t)&&oy(e)||c.IsDate(t)&&ny(e)||c.IsConstructor(t)&&sy(e)||c.IsFunction(t)&&iy(e)?h.True:c.IsRecord(t)&&c.IsString(Aa(t))?e[rt]==="Record"?h.True:h.False:c.IsRecord(t)&&c.IsNumber(Aa(t))&&qe(e,0)?h.True:h.False}function dy(t,e){return Se(e)?ye(t,e):c.IsRecord(e)?dt(t,e):c.IsObject(e)?(()=>{for(let r of Object.getOwnPropertyNames(e.properties)){if(!(r in t.properties)&&!c.IsOptional(e.properties[r]))return h.False;if(c.IsOptional(e.properties[r]))return h.True;if(Up(t.properties[r],e.properties[r])===h.False)return h.False}return h.True})():h.False}function ly(t,e){return Se(e)?ye(t,e):c.IsObject(e)&&ay(e)?h.True:c.IsPromise(e)?at(z(t.item,e.item)):h.False}function Aa(t){return zt in t.patternProperties?nt():Qt in t.patternProperties?vt():Gr("Unknown record key pattern")}function Ra(t){return zt in t.patternProperties?t.patternProperties[zt]:Qt in t.patternProperties?t.patternProperties[Qt]:Gr("Unable to get record value schema")}function dt(t,e){let[r,n]=[Aa(e),Ra(e)];return c.IsLiteralString(t)&&c.IsNumber(r)&&at(z(t,n))===h.True?h.True:c.IsUint8Array(t)&&c.IsNumber(r)||c.IsString(t)&&c.IsNumber(r)||c.IsArray(t)&&c.IsNumber(r)?z(t,n):c.IsObject(t)?(()=>{for(let o of Object.getOwnPropertyNames(t.properties))if(Up(n,t.properties[o])===h.False)return h.False;return h.True})():h.False}function uy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?z(Ra(t),Ra(e)):h.False}function py(t,e){let r=c.IsRegExp(t)?vt():t,n=c.IsRegExp(e)?vt():e;return z(r,n)}function Kp(t,e){return c.IsLiteral(t)&&Me.IsString(t.const)||c.IsString(t)?h.True:h.False}function cy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsString(e)?h.True:h.False}function my(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsSymbol(e)?h.True:h.False}function fy(t,e){return c.IsTemplateLiteral(t)?z(vr(t),e):c.IsTemplateLiteral(e)?z(t,vr(e)):Gr("Invalid fallthrough for TemplateLiteral")}function gy(t,e){return c.IsArray(e)&&t.items!==void 0&&t.items.every(r=>z(r,e.items)===h.True)}function hy(t,e){return c.IsNever(t)?h.True:c.IsUnknown(t)?h.False:c.IsAny(t)?h.Union:h.False}function Sy(t,e){return Se(e)?ye(t,e):c.IsObject(e)&&Bo(e)||c.IsArray(e)&&gy(t,e)?h.True:c.IsTuple(e)?Me.IsUndefined(t.items)&&!Me.IsUndefined(e.items)||!Me.IsUndefined(t.items)&&Me.IsUndefined(e.items)?h.False:Me.IsUndefined(t.items)&&!Me.IsUndefined(e.items)||t.items.every((r,n)=>z(r,e.items[n])===h.True)?h.True:h.False:h.False}function yy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsUint8Array(e)?h.True:h.False}function ky(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsVoid(e)?wy(t,e):c.IsUndefined(e)?h.True:h.False}function Ma(t,e){return e.anyOf.some(r=>z(t,r)===h.True)?h.True:h.False}function vy(t,e){return t.anyOf.every(r=>z(r,e)===h.True)?h.True:h.False}function Vp(t,e){return h.True}function Py(t,e){return c.IsNever(e)?Wp(t,e):c.IsIntersect(e)?Wo(t,e):c.IsUnion(e)?Ma(t,e):c.IsAny(e)?Ta(t,e):c.IsString(e)?Kp(t,e):c.IsNumber(e)?Bp(t,e):c.IsInteger(e)?Lp(t,e):c.IsBoolean(e)?Fp(t,e):c.IsArray(e)?BS(t,e):c.IsTuple(e)?hy(t,e):c.IsObject(e)?$e(t,e):c.IsUnknown(e)?h.True:h.False}function wy(t,e){return c.IsUndefined(t)||c.IsUndefined(t)?h.True:h.False}function Iy(t,e){return c.IsIntersect(e)?Wo(t,e):c.IsUnion(e)?Ma(t,e):c.IsUnknown(e)?Vp(t,e):c.IsAny(e)?Ta(t,e):c.IsObject(e)?$e(t,e):c.IsVoid(e)?h.True:h.False}function z(t,e){return c.IsTemplateLiteral(t)||c.IsTemplateLiteral(e)?fy(t,e):c.IsRegExp(t)||c.IsRegExp(e)?py(t,e):c.IsNot(t)||c.IsNot(e)?ZS(t,e):c.IsAny(t)?WS(t,e):c.IsArray(t)?US(t,e):c.IsBigInt(t)?VS(t,e):c.IsBoolean(t)?qS(t,e):c.IsAsyncIterator(t)?KS(t,e):c.IsConstructor(t)?jS(t,e):c.IsDate(t)?GS(t,e):c.IsFunction(t)?HS(t,e):c.IsInteger(t)?zS(t,e):c.IsIntersect(t)?QS(t,e):c.IsIterator(t)?JS(t,e):c.IsLiteral(t)?YS(t,e):c.IsNever(t)?XS(t,e):c.IsNull(t)?ey(t,e):c.IsNumber(t)?ty(t,e):c.IsObject(t)?dy(t,e):c.IsRecord(t)?uy(t,e):c.IsString(t)?cy(t,e):c.IsSymbol(t)?my(t,e):c.IsTuple(t)?Sy(t,e):c.IsPromise(t)?ly(t,e):c.IsUint8Array(t)?yy(t,e):c.IsUndefined(t)?ky(t,e):c.IsUnion(t)?vy(t,e):c.IsUnknown(t)?Py(t,e):c.IsVoid(t)?Iy(t,e):Gr(`Unknown left type operand '${t[P]}'`)}function tr(t,e){return z(t,e)}var xa,h,Ca=u(()=>{wn();Sr();kr();Ur();jr();Vt();vn();T();xt();js();xa=class extends we{};(function(t){t[t.Union=0]="Union",t[t.True=1]="True",t[t.False=2]="False"})(h||(h={}))});function by(t,e,r,n,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=Hr(t[s],e,r,n,ee(o));return i}function xy(t,e,r,n,o){return by(t.properties,e,r,n,o)}function qp(t,e,r,n,o){let i=xy(t,e,r,n,o);return U(i)}var _a=u(()=>{ve();Uo();We()});function Ay(t,e,r,n){let o=tr(t,e);return o===h.Union?q([r,n]):o===h.True?r:n}function Hr(t,e,r,n,o){return te(t)?qp(t,e,r,n,o):ze(t)?g(jp(t,e,r,n,o)):g(Ay(t,e,r,n),o)}var Uo=u(()=>{R();he();Ca();$a();_a();B()});function Ry(t,e,r,n,o){return{[t]:Hr(V(t),e,r,n,ee(o))}}function Ty(t,e,r,n,o){return t.reduce((i,s)=>({...i,...Ry(s,e,r,n,o)}),{})}function My(t,e,r,n,o){return Ty(t.keys,e,r,n,o)}function jp(t,e,r,n,o){let i=My(t,e,r,n,o);return U(i)}var $a=u(()=>{ve();Ue();Uo();We()});var Gp=u(()=>{});var Dn=u(()=>{Ca();$a();_a();Gp();Uo()});function Hp(t,e){return zr(vr(t),e)}var Ea=u(()=>{Ko();Vt()});function Cy(t,e){let r=t.filter(n=>tr(n,e)===h.False);return r.length===1?r[0]:q(r)}function zr(t,e,r={}){return Qe(t)?g(Hp(t,e),r):te(t)?g(zp(t,e),r):g(L(t)?Cy(t.anyOf,e):tr(t,e)!==h.False?W():t,r)}var Ko=u(()=>{R();he();Ae();Dn();Oa();Ea();B()});function _y(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=zr(t[n],e);return r}function $y(t,e){return _y(t.properties,e)}function zp(t,e){let r=$y(t,e);return U(r)}var Oa=u(()=>{ve();Ko()});var Da=u(()=>{Oa();Ea();Ko()});function Qp(t,e){return Qr(vr(t),e)}var Na=u(()=>{Vo();Vt()});function Ey(t,e){let r=t.filter(n=>tr(n,e)!==h.False);return r.length===1?r[0]:q(r)}function Qr(t,e,r){return Qe(t)?g(Qp(t,e),r):te(t)?g(Jp(t,e),r):g(L(t)?Ey(t.anyOf,e):tr(t,e)!==h.False?t:W(),r)}var Vo=u(()=>{R();he();Ae();Dn();Fa();Na();B()});function Oy(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Qr(t[n],e);return r}function Dy(t,e){return Oy(t.properties,e)}function Jp(t,e){let r=Dy(t,e);return U(r)}var Fa=u(()=>{ve();Vo()});var La=u(()=>{Fa();Na();Vo()});function Yp(t,e){return ht(t)?g(t.returns,e):W(e)}var Xp=u(()=>{R();Ae();B()});var Wa=u(()=>{Xp()});function qo(t){return Ve(Ce(t))}var Zp=u(()=>{Pr();Ut()});var jo=u(()=>{Zp()});function Ir(t,e,r){return g({[P]:"Record",type:"object",patternProperties:{[t]:e}},r)}function Ba(t,e,r){let n={};for(let o of t)n[o]=e;return H(n,{...r,[rt]:"Record"})}function Ny(t,e,r){return Lu(t)?Ba(Ke(t),e,r):Ir(t.pattern,e,r)}function Fy(t,e,r){return Ba(Ke(q(t)),e,r)}function Ly(t,e,r){return Ba([t.toString()],e,r)}function Wy(t,e,r){return Ir(t.source,e,r)}function By(t,e,r){let n=ce(t.pattern)?Qt:t.pattern;return Ir(n,e,r)}function Uy(t,e,r){return Ir(Qt,e,r)}function Ky(t,e,r){return Ir(mu,e,r)}function Vy(t,e,r){return H({true:e,false:e},r)}function qy(t,e,r){return Ir(zt,e,r)}function jy(t,e,r){return Ir(zt,e,r)}function Go(t,e,r={}){return L(t)?Fy(t.anyOf,e,r):Qe(t)?Ny(t,e,r):He(t)?Ly(t.const,e,r):Ft(t)?Vy(t,e,r):yt(t)?qy(t,e,r):kt(t)?jy(t,e,r):Bs(t)?Wy(t,e,r):Lt(t)?By(t,e,r):Ls(t)?Uy(t,e,r):Gt(t)?Ky(t,e,r):W(r)}function Ho(t){return globalThis.Object.getOwnPropertyNames(t.patternProperties)[0]}function ec(t){let e=Ho(t);return e===Qt?vt():e===zt?nt():vt({pattern:e})}function zo(t){return t.patternProperties[Ho(t)]}var tc=u(()=>{R();T();Ae();kr();Xe();Ur();he();Vt();vn();Tt();De();B()});var Nn=u(()=>{tc()});function Gy(t,e){return e.parameters=Fn(t,e.parameters),e.returns=Pt(t,e.returns),e}function Hy(t,e){return e.parameters=Fn(t,e.parameters),e.returns=Pt(t,e.returns),e}function zy(t,e){return e.allOf=Fn(t,e.allOf),e}function Qy(t,e){return e.anyOf=Fn(t,e.anyOf),e}function Jy(t,e){return ce(e.items)||(e.items=Fn(t,e.items)),e}function Yy(t,e){return e.items=Pt(t,e.items),e}function Xy(t,e){return e.items=Pt(t,e.items),e}function Zy(t,e){return e.items=Pt(t,e.items),e}function ek(t,e){return e.item=Pt(t,e.item),e}function tk(t,e){let r=ik(t,e.properties);return{...e,...H(r)}}function rk(t,e){let r=Pt(t,ec(e)),n=Pt(t,zo(e)),o=Go(r,n);return{...e,...o}}function nk(t,e){return e.index in t?t[e.index]:er()}function ok(t,e){let r=Or(e),n=Be(e),o=Pt(t,e);return r&&n?qo(o):r&&!n?Ve(o):!r&&n?Ce(o):o}function ik(t,e){return globalThis.Object.getOwnPropertyNames(e).reduce((r,n)=>({...r,[n]:ok(t,e[n])}),{})}function Fn(t,e){return e.map(r=>Pt(t,r))}function Pt(t,e){return ht(e)?Gy(t,e):St(e)?Hy(t,e):ie(e)?zy(t,e):L(e)?Qy(t,e):Je(e)?Jy(t,e):ft(e)?Yy(t,e):cr(e)?Xy(t,e):fr(e)?Zy(t,e):gr(e)?ek(t,e):me(e)?tk(t,e):hr(e)?rk(t,e):Ws(e)?nk(t,e):e}function rc(t,e){return Pt(e,Er(t))}var nc=u(()=>{co();jr();jo();Pr();Ut();Xe();Nn();De();B()});var Ua=u(()=>{nc()});function oc(t){return g({[P]:"Integer",type:"integer"},t)}var ic=u(()=>{R();T()});var Ka=u(()=>{ic()});function sk(t,e,r){return{[t]:wt(V(t),e,ee(r))}}function ak(t,e,r){return t.reduce((o,i)=>({...o,...sk(i,e,r)}),{})}function dk(t,e,r){return ak(t.keys,e,r)}function sc(t,e,r){let n=dk(t,e,r);return U(n)}var Va=u(()=>{ve();br();Ue();We()});function lk(t){let[e,r]=[t.slice(0,1),t.slice(1)];return[e.toLowerCase(),r].join("")}function uk(t){let[e,r]=[t.slice(0,1),t.slice(1)];return[e.toUpperCase(),r].join("")}function pk(t){return t.toUpperCase()}function ck(t){return t.toLowerCase()}function mk(t,e,r){let n=Wr(t.pattern);if(!yr(n))return{...t,pattern:ac(t.pattern,e)};let s=[...Tn(n)].map(l=>V(l)),a=dc(s,e),d=q(a);return wo([d],r)}function ac(t,e){return typeof t=="string"?e==="Uncapitalize"?lk(t):e==="Capitalize"?uk(t):e==="Uppercase"?pk(t):e==="Lowercase"?ck(t):t:t.toString()}function dc(t,e){return t.map(r=>wt(r,e))}function wt(t,e,r={}){return ze(t)?sc(t,e,r):Qe(t)?mk(t,e,r):L(t)?q(dc(t.anyOf,e),r):He(t)?V(ac(t.const,e),r):g(t,r)}var br=u(()=>{R();Vt();Va();Ue();he();B()});function lc(t,e={}){return wt(t,"Capitalize",e)}var uc=u(()=>{br()});function pc(t,e={}){return wt(t,"Lowercase",e)}var cc=u(()=>{br()});function mc(t,e={}){return wt(t,"Uncapitalize",e)}var fc=u(()=>{br()});function gc(t,e={}){return wt(t,"Uppercase",e)}var hc=u(()=>{br()});var qa=u(()=>{uc();Va();br();cc();fc();hc()});function fk(t,e,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(t))n[o]=rr(t[o],e,ee(r));return n}function gk(t,e,r){return fk(t.properties,e,r)}function Sc(t,e,r){let n=gk(t,e,r);return U(n)}var ja=u(()=>{ve();Qo();We()});function hk(t,e){return t.map(r=>Ga(r,e))}function Sk(t,e){return t.map(r=>Ga(r,e))}function yk(t,e){let{[e]:r,...n}=t;return n}function kk(t,e){return e.reduce((r,n)=>yk(r,n),t)}function vk(t,e,r){let n=se(t,[ge,"$id","required","properties"]),o=kk(r,e);return H(o,n)}function Pk(t){let e=t.reduce((r,n)=>fo(n)?[...r,V(n)]:r,[]);return q(e)}function Ga(t,e){return ie(t)?_e(hk(t.allOf,e)):L(t)?q(Sk(t.anyOf,e)):me(t)?vk(t,e,t.properties):H({})}function rr(t,e,r){let n=pe(e)?Pk(e):e,o=Ye(e)?Ke(e):e,i=de(t),s=de(e);return te(t)?Sc(t,o,r):ze(e)?yc(t,e,r):i&&s?Z("Omit",[t,n],r):!i&&s?Z("Omit",[t,n],r):i&&!s?Z("Omit",[t,n],r):g({...Ga(t,o),...r})}var Qo=u(()=>{R();ho();mn();Yt();Ue();Tt();ot();he();Xe();Ha();ja();B();De()});function wk(t,e,r){return{[e]:rr(t,[e],ee(r))}}function Ik(t,e,r){return e.reduce((n,o)=>({...n,...wk(t,o,r)}),{})}function bk(t,e,r){return Ik(t,e.keys,r)}function yc(t,e,r){let n=bk(t,e,r);return U(n)}var Ha=u(()=>{ve();Qo();We()});var Jo=u(()=>{Ha();ja();Qo()});function xk(t,e,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(t))n[o]=nr(t[o],e,ee(r));return n}function Ak(t,e,r){return xk(t.properties,e,r)}function kc(t,e,r){let n=Ak(t,e,r);return U(n)}var za=u(()=>{ve();Yo();We()});function Rk(t,e){return t.map(r=>Qa(r,e))}function Tk(t,e){return t.map(r=>Qa(r,e))}function Mk(t,e){let r={};for(let n of e)n in t&&(r[n]=t[n]);return r}function Ck(t,e,r){let n=se(t,[ge,"$id","required","properties"]),o=Mk(r,e);return H(o,n)}function _k(t){let e=t.reduce((r,n)=>fo(n)?[...r,V(n)]:r,[]);return q(e)}function Qa(t,e){return ie(t)?_e(Rk(t.allOf,e)):L(t)?q(Tk(t.anyOf,e)):me(t)?Ck(t,e,t.properties):H({})}function nr(t,e,r){let n=pe(e)?_k(e):e,o=Ye(e)?Ke(e):e,i=de(t),s=de(e);return te(t)?kc(t,o,r):ze(e)?vc(t,e,r):i&&s?Z("Pick",[t,n],r):!i&&s?Z("Pick",[t,n],r):i&&!s?Z("Pick",[t,n],r):g({...Qa(t,o),...r})}var Yo=u(()=>{R();ho();Yt();ot();Ue();Xe();he();Tt();mn();B();De();Ja();za()});function $k(t,e,r){return{[e]:nr(t,[e],ee(r))}}function Ek(t,e,r){return e.reduce((n,o)=>({...n,...$k(t,o,r)}),{})}function Ok(t,e,r){return Ek(t,e.keys,r)}function vc(t,e,r){let n=Ok(t,e,r);return U(n)}var Ja=u(()=>{ve();Yo();We()});var Xo=u(()=>{Ja();za();Yo()});function Dk(t,e){return Z("Partial",[Z(t,e)])}function Nk(t){return Z("Partial",[Mt(t)])}function Fk(t){let e={};for(let r of globalThis.Object.getOwnPropertyNames(t))e[r]=Ce(t[r]);return e}function Lk(t,e){let r=se(t,[ge,"$id","required","properties"]),n=Fk(e);return H(n,r)}function Pc(t){return t.map(e=>wc(e))}function wc(t){return gt(t)?Dk(t.target,t.parameters):de(t)?Nk(t.$ref):ie(t)?_e(Pc(t.allOf)):L(t)?q(Pc(t.anyOf)):me(t)?Lk(t,t.properties):mr(t)||Ft(t)||yt(t)||He(t)||fn(t)||kt(t)||Lt(t)||gn(t)||hn(t)?t:H({})}function Jr(t,e){return te(t)?Ic(t,e):g({...wc(t),...e})}var Ya=u(()=>{R();Yt();Ut();Xe();ot();he();wr();Bt();T();Xa();B()});function Wk(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Jr(t[n],ee(e));return r}function Bk(t,e){return Wk(t.properties,e)}function Ic(t,e){let r=Bk(t,e);return U(r)}var Xa=u(()=>{ve();Ya();We()});var Zo=u(()=>{Xa();Ya()});function Uk(t,e){return Z("Required",[Z(t,e)])}function Kk(t){return Z("Required",[Mt(t)])}function Vk(t){let e={};for(let r of globalThis.Object.getOwnPropertyNames(t))e[r]=se(t[r],[xe]);return e}function qk(t,e){let r=se(t,[ge,"$id","required","properties"]),n=Vk(e);return H(n,r)}function bc(t){return t.map(e=>xc(e))}function xc(t){return gt(t)?Uk(t.target,t.parameters):de(t)?Kk(t.$ref):ie(t)?_e(bc(t.allOf)):L(t)?q(bc(t.anyOf)):me(t)?qk(t,t.properties):mr(t)||Ft(t)||yt(t)||He(t)||fn(t)||kt(t)||Lt(t)||gn(t)||hn(t)?t:H({})}function Yr(t,e){return te(t)?Ac(t,e):g({...xc(t),...e})}var Za=u(()=>{R();Yt();Xe();ot();he();wr();T();Bt();ed();B()});function jk(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Yr(t[n],e);return r}function Gk(t,e){return jk(t.properties,e)}function Ac(t,e){let r=Gk(t,e);return U(r)}var ed=u(()=>{ve();Za()});var ei=u(()=>{ed();Za()});function Hk(t,e){return e.map(r=>de(r)?td(t,r.$ref):Ze(t,r))}function td(t,e){return e in t?de(t[e])?td(t,t[e].$ref):Ze(t,t[e]):W()}function zk(t){return Vr(t[0])}function Qk(t){return Xt(t[0],t[1])}function Jk(t){return qr(t[0])}function Yk(t){return Jr(t[0])}function Xk(t){return rr(t[0],t[1])}function Zk(t){return nr(t[0],t[1])}function ev(t){return Yr(t[0])}function tv(t,e,r){let n=Hk(t,r);return e==="Awaited"?zk(n):e==="Index"?Qk(n):e==="KeyOf"?Jk(n):e==="Partial"?Yk(n):e==="Omit"?Xk(n):e==="Pick"?Zk(n):e==="Required"?ev(n):W()}function rv(t,e){return Dr(Ze(t,e))}function nv(t,e){return Nr(Ze(t,e))}function ov(t,e,r){return Fr(Ln(t,e),Ze(t,r))}function iv(t,e,r){return At(Ln(t,e),Ze(t,r))}function sv(t,e){return _e(Ln(t,e))}function av(t,e){return Kr(Ze(t,e))}function dv(t,e){return H(globalThis.Object.keys(e).reduce((r,n)=>({...r,[n]:Ze(t,e[n])}),{}))}function lv(t,e){let[r,n]=[Ze(t,zo(e)),Ho(e)],o=Er(e);return o.patternProperties[n]=r,o}function uv(t,e){return de(e)?{...td(t,e.$ref),[ge]:e[ge]}:e}function pv(t,e){return it(Ln(t,e))}function cv(t,e){return q(Ln(t,e))}function Ln(t,e){return e.map(r=>Ze(t,r))}function Ze(t,e){return Be(e)?g(Ze(t,se(e,[xe])),e):Or(e)?g(Ze(t,se(e,[mt])),e):Ht(e)?g(uv(t,e),e):ft(e)?g(rv(t,e.items),e):cr(e)?g(nv(t,e.items),e):gt(e)?g(tv(t,e.target,e.parameters)):ht(e)?g(ov(t,e.parameters,e.returns),e):St(e)?g(iv(t,e.parameters,e.returns),e):ie(e)?g(sv(t,e.allOf),e):fr(e)?g(av(t,e.items),e):me(e)?g(dv(t,e.properties),e):hr(e)?g(lv(t,e)):Je(e)?g(pv(t,e.items||[]),e):L(e)?g(cv(t,e.anyOf),e):e}function mv(t,e){return e in t?Ze(t,t[e]):W()}function Rc(t){return globalThis.Object.getOwnPropertyNames(t).reduce((e,r)=>({...e,[r]:mv(t,r)}),{})}var Tc=u(()=>{Nt();Fs();Bt();In();Ro();bn();xn();Tt();Sr();ot();Cn();On();Xe();Jo();Xo();Ae();Zo();Nn();ei();Zt();he();T();B()});function Mc(t){return new rd(t)}var rd,Cc=u(()=>{Nt();T();Tc();rd=class{constructor(e){let r=Rc(e),n=this.WithIdentifiers(r);this.$defs=n}Import(e,r){let n={...this.$defs,[e]:g(this.$defs[e],r)};return g({[P]:"Import",$defs:n,$ref:e})}WithIdentifiers(e){return globalThis.Object.getOwnPropertyNames(e).reduce((r,n)=>({...r,[n]:{...e[n],$id:n}}),{})}}});var nd=u(()=>{Cc()});function _c(t,e){return g({[P]:"Not",not:t},e)}var $c=u(()=>{R();T()});var od=u(()=>{$c()});function Ec(t,e){return St(t)?it(t.parameters,e):W()}var Oc=u(()=>{Zt();Ae();B()});var id=u(()=>{Oc()});function Dc(t,e={}){ce(e.$id)&&(e.$id=`T${fv++}`);let r=Er(t({[P]:"This",$ref:`${e.$id}`}));return r.$id=e.$id,g({[rt]:"Recursive",...r},e)}var fv,Nc=u(()=>{co();R();De();T();fv=0});var sd=u(()=>{Nc()});function Fc(t,e){let r=Q(t)?new globalThis.RegExp(t):t;return g({[P]:"RegExp",type:"RegExp",source:r.source,flags:r.flags},e)}var Lc=u(()=>{R();De();T()});var ad=u(()=>{Lc()});function gv(t){return ie(t)?t.allOf:L(t)?t.anyOf:Je(t)?t.items??[]:[]}function Wc(t){return gv(t)}var Bc=u(()=>{B()});var dd=u(()=>{Bc()});function Uc(t,e){return St(t)?g(t.returns,e):W(e)}var Kc=u(()=>{R();Ae();B()});var ld=u(()=>{Kc()});var Vc=u(()=>{});var qc=u(()=>{});var jc=u(()=>{Vc();qc()});var Gc=u(()=>{});var Hc=u(()=>{Gc()});function zc(t){return new ud(t)}var ud,pd,Qc=u(()=>{T();B();ud=class{constructor(e){this.schema=e}Decode(e){return new pd(this.schema,e)}},pd=class{constructor(e,r){this.schema=e,this.decode=r}EncodeTransform(e,r){let i={Encode:s=>r[ge].Encode(e(s)),Decode:s=>this.decode(r[ge].Decode(s))};return{...r,[ge]:i}}EncodeSchema(e,r){let n={Decode:this.decode,Encode:e};return{...r,[ge]:n}}Encode(e){return Ht(this.schema)?this.EncodeTransform(e,this.schema):this.EncodeSchema(e,this.schema)}}});var cd=u(()=>{Qc()});function Jc(t={}){return g({[P]:t[P]??"Unsafe"},t)}var Yc=u(()=>{R();T()});var md=u(()=>{Yc()});function Xc(t){return g({[P]:"Void",type:"void"},t)}var Zc=u(()=>{R();T()});var fd=u(()=>{Zc()});var gd={};lo(gd,{Any:()=>Jt,Argument:()=>xu,Array:()=>Dr,AsyncIterator:()=>Nr,Awaited:()=>Vr,BigInt:()=>Br,Boolean:()=>vo,Capitalize:()=>lc,Composite:()=>kp,Const:()=>Rp,Constructor:()=>Fr,ConstructorParameters:()=>Mp,Date:()=>To,Enum:()=>_p,Exclude:()=>zr,Extends:()=>Hr,Extract:()=>Qr,Function:()=>At,Index:()=>Xt,InstanceType:()=>Yp,Instantiate:()=>rc,Integer:()=>oc,Intersect:()=>_e,Iterator:()=>Kr,KeyOf:()=>qr,Literal:()=>V,Lowercase:()=>pc,Mapped:()=>sp,Module:()=>Mc,Never:()=>W,Not:()=>_c,Null:()=>Co,Number:()=>nt,Object:()=>H,Omit:()=>rr,Optional:()=>Ce,Parameters:()=>Ec,Partial:()=>Jr,Pick:()=>nr,Promise:()=>xo,Readonly:()=>Ve,ReadonlyOptional:()=>qo,Record:()=>Go,Recursive:()=>Dc,Ref:()=>Mt,RegExp:()=>Fc,Required:()=>Yr,Rest:()=>Wc,ReturnType:()=>Uc,String:()=>vt,Symbol:()=>$o,TemplateLiteral:()=>wo,Transform:()=>zc,Tuple:()=>it,Uint8Array:()=>No,Uncapitalize:()=>mc,Undefined:()=>Oo,Union:()=>q,Unknown:()=>er,Unsafe:()=>Jc,Uppercase:()=>gc,Void:()=>Xc});var em=u(()=>{wn();zs();In();bn();Ro();Mn();Po();ka();Pa();xn();wa();Mo();Ia();Da();Dn();La();Sr();Tt();Wa();Ua();Ka();ot();qa();Cn();On();Ue();ve();nd();Ae();od();_o();kr();Xe();Jo();Ut();id();Zo();Xo();Ao();Pr();jo();Nn();sd();wr();ad();ei();dd();ld();Ur();Eo();Vt();cd();Zt();Fo();Do();he();jr();md();fd()});var p,tm=u(()=>{em();p=gd});var Ee=u(()=>{Fs();Nt();xt();js();cu();vn();Su();Pn();T();wn();In();zs();bn();Ro();Mn();Po();ka();Pa();xn();wa();Mo();Ia();Da();Dn();La();Sr();Tt();Wa();Ua();Ka();ot();Cn();qa();On();Ue();nd();ve();Ae();od();_o();kr();Xe();Jo();Ut();id();Zo();Xo();Ao();Pr();jo();Nn();sd();wr();ad();ei();dd();ld();jc();Hc();Ur();Eo();Vt();cd();Zt();Fo();Do();he();jr();md();fd();tm()});function hd(t){k=t}function Sd(t){fe=t}var k,fe,Y=u(()=>{k=null,fe=null});function rm(t){let e=t.chatId.trim(),r=t.topicId.trim();return!/^-?\d+$/.test(e)||!/^\d+$/.test(r)?null:`${e}:topic:${r}`}function vv(t){let e=t.conversationId.trim(),r=e.match(/^(-?\d+):topic:(\d+)$/i);if(r?.[1]&&r[2]){let i=rm({chatId:r[1],topicId:r[2]});return i?{chatId:r[1],topicId:r[2],canonicalConversationId:i}:null}if(!/^\d+$/.test(e))return null;let n=t.parentConversationId?.trim();if(!n||!/^-?\d+$/.test(n))return null;let o=rm({chatId:n,topicId:e});return o?{chatId:n,topicId:e,canonicalConversationId:o}:null}function Pv(t){if(!t)return;let e=t.match(/^agent:[^:]+:discord:(direct|dm|channel|group):/i);if(!e?.[1])return;let r=e[1].toLowerCase();return r==="direct"||r==="dm"?"user":"channel"}function wv(t,e){if(!/^\d+$/.test(t))return t;let r=Pv(e);return r?`${r}:${t}`:`channel:${t}`}function Iv(t){if(!(!t?.provider||!t.target)&&!(t.provider==="system"||t.target==="system"))return t.accountId?`${t.provider}|${t.accountId}|${t.target}`:`${t.provider}|${t.target}`}function bv(t){let e=t.toLowerCase(),r=[":thread:",":topic:"];for(let n of r){let o=e.lastIndexOf(n);if(o===-1)continue;let i=t.slice(0,o).trim(),s=t.slice(o+n.length).trim()||void 0;return{id:i||t,threadId:s}}return{id:t}}function xv(t){let e=t?.trim();if(!e)return;let r=e.split(":").filter(Boolean);if(r[0]?.trim().toLowerCase()==="agent")for(let n=2;n<=r.length-3;n+=1){let o=r[n]?.trim().toLowerCase();if(!o||!kv.has(o))continue;let i=r[n+1]?.trim().toLowerCase(),s=r.slice(n+2).join(":").trim();if(!(!i||!s))return{provider:o,kind:i,rawId:s}}}function Av(t,e=vv){try{return e({conversationId:t})}catch{return null}}function yd(t){return{provider:"system",target:"system",sessionKey:t?.trim()||void 0}}function kd(t,e){return{...t,threadId:e??t.threadId}}function Tv(t,e,r){return t==="telegram"&&r?.provider==="telegram"&&!!r.target&&e!==r.target}function Mv(t){let e=t?.trim();if(!e)return;let r=xv(e);if(!r)return;let{provider:n,kind:o,rawId:i}=r,s=bv(i),a=null;if(n==="telegram")try{a=Rv.safeParseTelegramTopicConversation(i)}catch{a=null}let d=a?.chatId??s.id,l=a?.topicId??s.threadId,m=n==="discord"?o==="direct"||o==="dm"?`user:${d}`:`channel:${d}`:d;return{provider:n,target:m,threadId:l,sessionKey:e}}function vd(t){let e=t?.match(/:topic:(\d+)$/);return e?parseInt(e[1],10):void 0}function Cv(t){return!!(t?.provider&&t.target&&t.provider!=="system"&&t.target!=="system")}function Wn(t,e,r){let n=Mv(r),o=e!=null?String(e):void 0,i=t?.trim();if(!i||i.toLowerCase()==="unknown")return n?kd(n,o):yd(r);let s=i.split("|").map(v=>v.trim());if(s.length<2)return n?kd(n,o):yd(r);let[a,d,l]=s,m=s.length>=3?l:d,S=s.length>=3?d:void 0,y=a?.toLowerCase();if(!y||!m)return n?kd(n,o):yd(r);let f=y==="discord"?wv(m,r):m;return Tv(y,f,n)?{provider:y,accountId:S,target:n.target,threadId:o??n.threadId,sessionKey:r?.trim()||void 0}:{provider:y,accountId:S,target:f,threadId:o??(n?.provider===y?n.threadId:void 0),sessionKey:r?.trim()||void 0}}function Xr(t){return Wn(Iv(t.route)??t.originChannel,t.route?.threadId??t.originThreadId,t.route?.sessionKey??t.originSessionKey)??t.route}function nm(t){let e=Xr(t);return Cv(e)?e:void 0}var kv,Rv,Zr=u(()=>{kv=new Set(["telegram","discord","slack","system","mattermost","feishu","line","whatsapp","signal","matrix","googlechat","bluebubbles","imessage","msteams"]);Rv={safeParseTelegramTopicConversation:Av}});import{readFileSync as _v}from"fs";import{homedir as $v}from"os";import{join as Ev}from"path";function im(){if(Bn!==void 0)return Bn;try{let t=_v(Ev($v(),".claude.json"),"utf-8");Bn=JSON.parse(t).mcpServers??{}}catch{Bn={}}return Bn}function sm(t){let e=t.defaultHarness??om,r={};for(let[n,o]of Object.entries(ri))r[n]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[n,o]of Object.entries(t.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(t.defaultModel!==void 0){let n=r[e]??{};r[e]={...n,defaultModel:t.harnesses?.[e]?.defaultModel??t.defaultModel,allowedModels:t.harnesses?.[e]?.allowedModels!==void 0?n.allowedModels:t.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${e}.defaultModel instead.`)}if(t.model!==void 0){let n=r.codex??{};r.codex={...n,defaultModel:t.harnesses?.codex?.defaultModel??t.model,allowedModels:t.harnesses?.codex?.allowedModels!==void 0?n.allowedModels:t.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(t.reasoningEffort!==void 0){let n=r.codex??{};r.codex={...n,reasoningEffort:t.harnesses?.codex?.reasoningEffort??t.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(t.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))t.harnesses?.[n]?.allowedModels===void 0&&(r[n]={...o,allowedModels:void 0})}_={maxSessions:t.maxSessions??20,defaultWorkdir:t.defaultWorkdir,idleTimeoutMinutes:t.idleTimeoutMinutes??15,sessionGcAgeMinutes:t.sessionGcAgeMinutes??1440,maxPersistedSessions:t.maxPersistedSessions??1e4,fallbackChannel:t.fallbackChannel,agentChannels:t.agentChannels,maxAutoResponds:t.maxAutoResponds??10,permissionMode:t.permissionMode??"plan",planApproval:t.planApproval??"ask",defaultHarness:e,harnesses:r,allowedModels:t.allowedModels,defaultWorktreeStrategy:t.defaultWorktreeStrategy??"off",worktreeDir:t.worktreeDir}}function Pe(){return _.defaultHarness??om}function am(t){let e=ri[t],r=_.harnesses[t];return{...e,...r,allowedModels:r?.allowedModels??e?.allowedModels}}function Ct(t){return am(t).defaultModel}function en(t){return _.harnesses[t]?.allowedModels??_.allowedModels}function lt(t){return am(t).reasoningEffort}function Pd(t){return(t.messageChannel??t.channel)?.toLowerCase()!=="telegram"?!1:!!vd(t.sessionKey)}function ni(t){if(t.messageChannel){let e=t.messageChannel.split("|");if(e.length>=3)return t.messageChannel;if(t.agentAccountId&&e.length>=2)return`${e[0]}|${t.agentAccountId}|${e.slice(1).join("|")}`;if(e.length===1&&t.chatId)return`${e[0]}|${t.chatId}`;if(e.length===1&&t.senderId&&!Pd(t))return`${e[0]}|${t.senderId}`}if(t.workspaceDir){let e=Kn(t.workspaceDir);if(e)return e}if(t.messageChannel&&t.messageChannel.includes("|"))return t.messageChannel}function qt(t,e){if(e&&String(e).includes("|"))return String(e);if(t?.channelId&&String(t.channelId).includes("|"))return String(t.channelId);if(t?.messageChannel){let r=String(t.messageChannel);if(r.includes("|"))return r;if(t.chatId)return`${r}|${t.chatId}`;if(t.senderId&&!Pd(t))return`${r}|${t.senderId}`}return t?.channel&&t?.chatId?`${t.channel}|${t.chatId}`:t?.channel&&t?.senderId&&!Pd(t)?`${t.channel}|${t.senderId}`:t?.id&&/^-?\d+$/.test(String(t.id))?`telegram|${t.id}`:_.fallbackChannel??"unknown"}function Un(t){return t?.messageThreadId??void 0}function _t(t,e,r){return Wn(qt(t,e),Un(t),r??t?.sessionKey)}function Kn(t){let e=_.agentChannels;if(!e)return;let r=i=>i.replace(/\/+$/,""),n=r(t),o=Object.entries(e).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 dm(t){return vd(t)}var Bn,om,ri,_,Re=u(()=>{Zr();om="claude-code",ri={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium"}};_={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"ask",harnesses:{"claude-code":{...ri["claude-code"]},codex:{...ri.codex}}}});function oi(t){return{type:"backend_ref",ref:t}}function ii(t){return{type:"run_started",...t?{runId:t}:{}}}function Vn(t){return{type:"text_delta",text:t}}function lm(t,e){return{type:"tool_call",name:t,input:e}}function si(t){return{type:"pending_input",state:t}}function nn(t){return t?{type:"pending_input_resolved",requestId:t}:{type:"pending_input_resolved"}}function ai(t,e){return{type:"plan_artifact",artifact:t,finalized:e}}function di(t){return t?{type:"settings_changed",permissionMode:t}:{type:"settings_changed"}}function xr(t){return{type:"run_completed",data:t}}var rn,wd=u(()=>{rn=class{queue=[];resolvePending=null;done=!1;enqueue(e){this.queue.push(e),this.flush()}close(){this.done=!0,this.flush()}flush(){this.resolvePending&&(this.resolvePending(),this.resolvePending=null)}messages(){let e=this;return(async function*(){for(;;){for(;e.queue.length>0;)yield e.queue.shift();if(e.done)return;await new Promise(r=>{e.resolvePending=r})}})()}}});import*as ui from"@anthropic-ai/claude-agent-sdk";import{dirname as um,join as pm}from"path";import{fileURLToPath as Ov}from"url";import{createRequire as Dv}from"module";function Nv(t){if(typeof t.result=="string"&&t.result.length>0)return t.result;if(Array.isArray(t.errors)){let e=t.errors.filter(r=>typeof r=="string"&&r.length>0);if(e.length>0)return e.join(`
2
+ `)}}function Fv(t,e,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:`${t||"claude"}-ask-${e}`,kind:"question",promptText:i,options:s,allowsFreeText:s.length===0||o.multiSelect===!0}}var li,cm=u(()=>{wd();li=class{constructor(e={}){this.deps=e}deps;name="claude-code";backendKind="claude-code";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!1,nativePlanArtifacts:!1,worktrees:"plugin-managed"};launch(e){let r=new rn,n=!1,o="",i=!1,s=0,a=e.resumeSessionId??"",d=e.canUseTool,l={cwd:e.cwd,model:e.model,permissionMode:e.permissionMode,allowDangerouslySkipPermissions:!0,pathToClaudeCodeExecutable:(()=>{try{let A=Dv(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return pm(um(A),"cli.js")}catch{let v=um(Ov(import.meta.url));return pm(v,"..","node_modules","@anthropic-ai","claude-agent-sdk","cli.js")}})(),allowedTools:e.allowedTools,systemPrompt:e.systemPrompt,includePartialMessages:!0,abortController:e.abortController,mcpServers:e.mcpServers,...d?{canUseTool:async(v,A)=>{if(v!=="AskUserQuestion")return{behavior:"allow"};let x=Fv(a,++s,A);r.enqueue(si(x));try{let w=await d(v,A);return r.enqueue(nn(x.requestId)),w}catch(w){throw r.enqueue(nn(x.requestId)),w}}}:{}};e.resumeSessionId&&(l.resume=e.resumeSessionId,l.forkSession=e.forkSession??!1);let m=e.prompt,S=this.deps.query??ui.query,y=this.deps.startup??ui.startup,f=(async()=>{if(typeof y!="function")return S({prompt:m,options:l});let v=await y({options:l});try{return v.query(m)}catch(A){throw await v.close?.(),A}})();return(async()=>{try{let v=await f;for await(let A of v){let x=A;if(x.type==="system"&&x.subtype==="init"){a=x.session_id??a,r.enqueue(oi({kind:"claude-code",conversationId:a}));continue}if(x.type==="system"&&x.subtype==="status"&&x.permissionMode){r.enqueue(di(x.permissionMode));continue}if(x.type==="assistant"){n||(n=!0,r.enqueue(ii()));for(let w of x.message?.content??[]){if(w.type==="text"){o+=o?`
3
+ ${w.text}`:w.text,r.enqueue(Vn(w.text));continue}w.type==="tool_use"&&((w.name==="ExitPlanMode"||w.name==="set_permission_mode")&&(i=!0),w.name!=="AskUserQuestion"&&r.enqueue(lm(w.name,w.input)))}continue}if(x.type==="result"){let w=o.trim();if(w&&(e.permissionMode==="plan"||i)){let C={explanation:void 0,steps:[],markdown:w};r.enqueue(ai(C,!0))}r.enqueue(xr({success:x.subtype==="success",duration_ms:x.duration_ms??0,total_cost_usd:x.total_cost_usd??0,num_turns:x.num_turns??0,result:Nv(x),session_id:x.session_id??a})),o="",i=!1,n=!1}}}finally{r.close()}})().catch(v=>{r.enqueue(xr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,result:v instanceof Error?v.message:String(v),session_id:a})),r.close()}),{messages:r.messages(),async setPermissionMode(v){let A=await f;typeof A.setPermissionMode=="function"&&await A.setPermissionMode(v)},async streamInput(v){let A=await f;typeof A.streamInput=="function"&&await A.streamInput(v)},async interrupt(){let v=await f;typeof v.interrupt=="function"&&await v.interrupt()}}}buildUserMessage(e,r){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:r}}}});import{spawn as Lv}from"node:child_process";import Wv from"node:readline";function Bv(t){return t instanceof Error?t.message:String(t)}function Uv(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}async function Kv(t,e){if(t.id!=null&&(Object.hasOwn(t,"result")||Object.hasOwn(t,"error"))){let n=String(t.id),o=e.pending.get(n);if(!o)return;if(clearTimeout(o.timer),e.pending.delete(n),t.error){o.reject(new Error(`codex app server rpc error (${t.error.code??"unknown"}): ${t.error.message??"unknown error"}`));return}o.resolve(t.result);return}let r=t.method?.trim();if(r){if(t.id==null){await e.onNotification(r,t.params);return}try{let n=await e.onRequest(r,t.params);e.respond({jsonrpc:"2.0",id:t.id,result:n??{}})}catch(n){e.respond({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:Bv(n)}})}}}var pi,mm=u(()=>{pi=class{constructor(e,r,n){this.command=e;this.args=r;this.requestTimeoutMs=n}command;args;requestTimeoutMs;process=null;pending=new Map;counter=0;onNotification=()=>{};onRequest=async()=>({});setNotificationHandler(e){this.onNotification=e}setRequestHandler(e){this.onRequest=e}async connect(){if(this.process)return;let e=Lv(this.command,["app-server",...this.args],{stdio:["pipe","pipe","pipe"],env:process.env});if(!e.stdin||!e.stdout||!e.stderr)throw new Error("codex app server stdio pipes unavailable");this.process=e,Wv.createInterface({input:e.stdout}).on("line",n=>{this.handleLine(n)}),e.stderr.on("data",()=>{}),e.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 e=this.process;this.process=null,e&&e.kill()}async notify(e,r){this.write({jsonrpc:"2.0",method:e,params:r??{}})}async request(e,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: ${e}`))},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:e,params:r??{}}),await i}write(e){if(!this.process?.stdin)throw new Error("codex app server stdio not connected");this.process.stdin.write(`${JSON.stringify(e)}
4
+ `)}async handleLine(e){let r=Uv(e);r&&await Kv(r,{pending:this.pending,onNotification:this.onNotification,onRequest:this.onRequest,respond:n=>this.write(n)})}flushPending(e){for(let[r,n]of this.pending)clearTimeout(n.timer),n.reject(e),this.pending.delete(r)}}});function X(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function le(t,e,r){for(let n of e){let o=t?.[n];if(typeof o!="string")continue;let i=r?.trim===!1?o:o.trim();if(i)return i}}function Vv(t){return t instanceof Error?t.message:String(t)}function fm(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function or(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>or(r)).join("");let e=X(t);if(!e)return"";for(let r of["delta","text","content","message","input","output","parts"]){let n=or(e[r]);if(n)return n}for(let r of["item","turn","thread","response","result","data"]){let n=or(e[r]);if(n)return n}return""}function qn(t){let e=X(t);if(!e)return{};let r=X(e.thread)??X(e.session),n=X(e.turn)??X(e.run),o=X(e.item),i=X(e.serverRequest);return{threadId:le(e,["threadId","thread_id","conversationId","conversation_id"])??le(r,["id","threadId","thread_id","conversationId"]),runId:le(e,["turnId","turn_id","runId","run_id"])??le(n,["id","turnId","turn_id","runId","run_id"]),requestId:le(e,["requestId","request_id","serverRequestId"])??le(i,["id","requestId","request_id"]),itemId:le(e,["itemId","item_id"])??le(o,["id","itemId","item_id"])}}function ci(t,e,r=0){if(r>6)return;if(Array.isArray(t)){for(let i of t){let s=ci(i,e,r+1);if(s)return s}return}let n=X(t);if(!n)return;let o=le(n,e);if(o)return o;for(let i of Object.values(n)){let s=ci(i,e,r+1);if(s)return s}}function jn(t){return{threadId:qn(t).threadId,cwd:ci(t,["cwd","workdir","directory"])}}function gm(t){let e=t?.trim();return!!(e&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(e))}function hm(t){let e=t?.trim();if(!e)return;let r=e.split(/[/\\]+/).filter(Boolean),n=r.lastIndexOf("worktrees");if(!(n<0||n+1>=r.length))return r[n+1]}function mi(t){let e=X(t);if(!e)return;let r=X(e.item)??e;return le(r,["id","itemId","item_id","messageId","message_id"])}function qv(t,e=!1){let r=X(t);if(!r)return"";let n=X(r.item)??r;return le(n,["type"])?.toLowerCase()!=="agentmessage"?"":e?or(n):le(n,["text"],{trim:!1})??or(n)}function Sm(t,e){let r=t.trim().toLowerCase();return r==="item/agentmessage/delta"?{mode:"delta",text:or(e),itemId:mi(e)}:r==="item/completed"?{mode:"snapshot",text:qv(e),itemId:mi(e)}:{mode:"ignore",text:""}}function ym(t){return{itemId:mi(t),delta:or(t)}}function km(t){let e=X(t),r=X(e?.plan),o=(Array.isArray(e?.plan)?e.plan:Array.isArray(r?.steps)?r.steps:[]).map(i=>{let s=X(i),a=le(s,["step","title","text"]);if(!a)return null;let d=le(s,["status"])?.toLowerCase()??"pending";return{step:a,status:d==="inprogress"||d==="in_progress"?"inProgress":d==="completed"?"completed":"pending"}}).filter(Boolean);return{explanation:le(r,["explanation"])??le(e,["explanation"]),steps:o}}function vm(t){let e=X(t);if(!e)return{};let r=X(e.item)??e;return le(r,["type"])?.toLowerCase()!=="plan"?{}:{itemId:mi(r),text:le(r,["text"],{trim:!1})??or(r)}}function Pm(t,e){let r=t.trim().toLowerCase();if(r==="turn/failed")return"failed";if(r==="turn/cancelled")return"interrupted";let n=X(e)??{},o=X(n.turn)??n,i=le(o,["status"])?.toLowerCase();return i==="failed"?"failed":i==="interrupted"||i==="cancelled"?"interrupted":"completed"}function wm(t,e){let r=X(e)??{},n=X(r.turn)??r,o=X(n.error)??X(r.error);if(o)return le(o,["message","text","summary","reason"])}function jv(t,e){let r=Vv(t).toLowerCase();return r.includes("method not found")||r.includes("unknown method")?!0:r.includes("unknown variant")?e?r.includes(`unknown variant \`${e.toLowerCase()}\``):!0:!1}function Hv(t){return Gv.has(t.trim().toLowerCase())}function zv(t){let e=X(t);return e?!!le(e,["threadId","thread_id"]):!1}async function Gn(t){if(t.payloads.length===0)throw new Error(`codex app server request skipped: no payloads for ${t.methods.join(", ")||"<none>"}`);let e;for(let r of t.methods)for(let n of t.payloads){if(Hv(r)&&!zv(n))throw new Error(`codex app server request missing threadId: ${r}`);try{return await t.client.request(r,n,t.timeoutMs)}catch(o){if(e=o,!jv(o,r))continue}}throw e instanceof Error?e:new Error(String(e))}function Im(t){let e={cwd:t.cwd};t.model?.trim()&&(e.model=t.model.trim()),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim());let r={cwd:t.cwd};return t.approvalPolicy?.trim()&&(r.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(r.sandbox=t.sandbox.trim()),[e,r,{}]}function bm(t){let e={threadId:t.threadId,persistExtendedHistory:!1};return t.model?.trim()&&(e.model=t.model.trim()),t.reasoningEffort?.trim()&&(e.reasoningEffort=t.reasoningEffort.trim()),t.cwd?.trim()&&(e.cwd=t.cwd.trim()),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim()),[e]}function Qv(t){return[{type:"text",text:t}]}function Jv(t,e,r,n){let o=e?.trim(),i=n?.trim();if(t!=="plan")return o||i?{mode:"default",settings:{...o?{model:o}:{},...r?.trim()?{reasoningEffort:r.trim()}:{},developerInstructions:i??null}}:void 0;if(!(!o&&!i))return{mode:"plan",settings:{...o?{model:o}:{},...r?.trim()?{reasoningEffort:r.trim()}:{},developerInstructions:i??null}}}function xm(t){let e={threadId:t.threadId,input:Qv(t.prompt)};t.model?.trim()&&(e.model=t.model.trim()),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim());let r=Jv(t.permissionMode??"default",t.model,t.reasoningEffort,t.systemPrompt);return r?[{...e,collaborationMode:r},{...e,collaboration_mode:{mode:r.mode,settings:{...typeof r.settings.model=="string"?{model:r.settings.model}:{},...typeof r.settings.reasoningEffort=="string"?{reasoning_effort:r.settings.reasoningEffort}:{},developer_instructions:r.settings.developerInstructions??null}}},e]:[e]}function Am(t){return[{threadId:t.threadId,turnId:t.turnId}]}function Yv(t){let e=X(t);if(!e)return[];let r=e.options??e.choices??e.availableDecisions??e.decisions;return Array.isArray(r)?r.map(n=>typeof n=="string"?n.trim():le(X(n),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function Xv(t){let e=t.trim().toLowerCase();return e.includes("session")?"acceptForSession":/cancel|abort|stop/.test(e)?"cancel":/deny|decline|reject|block|no/.test(e)?"decline":/approve|allow|accept|yes/.test(e)?"accept":t.trim()}function Rm(t,e,r){let n=t.trim().toLowerCase(),o=Yv(r),i=ci(r,["question","prompt","message","text","summary","reason"])??void 0,s=n.includes("requestapproval"),a=s?o.map(d=>({kind:"approval",label:d,decision:Xv(d),responseDecision:d})):o.map(d=>({kind:"option",label:d,value:d}));return{requestId:e,kind:s?"approval":"question",promptText:i,options:o,actions:a,allowsFreeText:!0}}function Tm(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function Id(t,e){let r=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:r,sandbox:r==="never"?"danger-full-access":void 0}}var Gv,Mm=u(()=>{Gv=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function Cm(t){return t instanceof Error?t.message:String(t)}function nP(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return String(t);let e=t;return typeof e.message?.content=="string"?e.message.content:typeof e.text=="string"?e.text:String(t)}var Zv,Ar,eP,tP,rP,fi,_m=u(()=>{mm();wd();Mm();Zv="1.0",Ar=6e4,eP="OPENCLAW_CODEX_APP_SERVER_COMMAND",tP="OPENCLAW_CODEX_APP_SERVER_ARGS",rP="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";fi=class{constructor(e={}){this.deps=e}deps;name="codex";backendKind="codex-app-server";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!0,nativePlanArtifacts:!0,worktrees:"native-restore"};launch(e){let r={command:process.env[eP]?.trim()||"codex",args:fm(process.env[tP]),requestTimeoutMs:Number.parseInt(process.env[rP]??String(Ar),10)||Ar},n=this.deps.createClient?.(r)??new pi(r.command,r.args,r.requestTimeoutMs),o=new rn,i=e.resumeSessionId,s,a=e.backendRef?.worktreePath,d=e.backendRef?.worktreeId,l=e.permissionMode??"default",m,S=0,y="",f=[],v,A=new Map,x=new Set,w=O=>{let D=O?.trim();if(!D)return;let K=e.originalWorkdir?.trim()||e.cwd.trim();e.worktreeStrategy&&e.worktreeStrategy!=="off"&&D!==K&&gm(D)&&(a=D,d=hm(D))},C=()=>{i&&o.enqueue(oi({kind:"codex-app-server",conversationId:i,...s?{runId:s}:{},...d?{worktreeId:d}:{},...a?{worktreePath:a}:{}}))};n.setNotificationHandler(async(O,D)=>{let K=O.trim().toLowerCase(),ue=qn(D),ct=jn(D);if(ue.threadId&&i&&ue.threadId!==i)return;if(ue.threadId&&(i=ue.threadId),ue.runId&&(s=ue.runId),w(ct.cwd),(ue.threadId||ue.runId||ct.cwd)&&C(),K==="serverrequest/resolved"){m&&(o.enqueue(nn(m.requestId)),m=void 0);return}if(K==="turn/plan/updated"){let Te=km(D);y=Te.explanation??y,Te.steps.length>0&&(f=Te.steps);return}if(K==="item/plan/delta"){let Te=ym(D);if(Te.itemId&&Te.delta){let jt=A.get(Te.itemId)??"";A.set(Te.itemId,`${jt}${Te.delta}`)}return}if(K==="item/completed"){let Te=vm(D);if(Te.text?.trim()){let jt={explanation:y||void 0,steps:f,markdown:Te.text.trim()};o.enqueue(ai(jt,!0));return}}let ae=Sm(K,D);if(ae.mode==="delta"&&ae.text){ae.itemId&&x.add(ae.itemId),o.enqueue(Vn(ae.text));return}ae.mode==="snapshot"&&ae.text&&(!ae.itemId||!x.has(ae.itemId))&&o.enqueue(Vn(ae.text)),(K==="turn/completed"||K==="turn/failed"||K==="turn/cancelled")&&v&&(v.method=O,v.params=D,v.resolve())}),n.setRequestHandler(async(O,D)=>{if(!Tm(O))return{};let K=qn(D),ue=jn(D);if(K.threadId&&i&&K.threadId!==i)return{};K.threadId&&(i=K.threadId),K.runId&&(s=K.runId),w(ue.cwd),(K.threadId||K.runId||ue.cwd)&&C();let ct=K.requestId??`${i??"codex"}-${Date.now().toString(36)}`,ae=Rm(O,ct,D),Te=O.trim().toLowerCase(),jt=ae.options,ao=ae.actions??[],Dg=await new Promise(Ng=>{m={requestId:ct,methodLower:Te,state:ae,options:jt,actions:ao,resolveResponse:Ng},o.enqueue(si(ae))});return m=void 0,o.enqueue(nn(ct)),Dg});let b=async()=>{await n.connect(),await n.request("initialize",{protocolVersion:Zv,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},Ar),await n.notify("initialized",{})},M=async()=>{let O=Id(l,e.codexApprovalPolicy);if(i){let ue=await Gn({client:n,methods:["thread/resume"],payloads:bm({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:O.approvalPolicy,sandbox:O.sandbox}),timeoutMs:Ar}),ct=jn(ue);i=ct.threadId??i,w(ct.cwd),C();return}let D=await Gn({client:n,methods:["thread/start","thread/new"],payloads:Im({cwd:e.originalWorkdir?.trim()||e.cwd,model:e.model,approvalPolicy:O.approvalPolicy,sandbox:O.sandbox}),timeoutMs:Ar}),K=jn(D);if(i=K.threadId,!i)throw new Error("Codex App Server did not return a thread id.");w(K.cwd),C()},F=async O=>{await M(),o.enqueue(ii()),S+=1,y="",f=[],A.clear(),x.clear();let D="",K,ue,ct=new Promise(ae=>{ue=ae});v={resolve:ue};try{let ae=Id(l,e.codexApprovalPolicy),Te=await Gn({client:n,methods:["turn/start"],payloads:xm({threadId:i,prompt:O,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,permissionMode:l,approvalPolicy:ae.approvalPolicy,sandbox:ae.sandbox}),timeoutMs:Ar}),jt=qn(Te);jt.runId&&(s=jt.runId,C()),await ct,D=v?.method??"turn/failed",K=v?.params;let ao=Pm(D,K);o.enqueue(xr({success:ao==="completed",outcome:ao,duration_ms:0,total_cost_usd:0,num_turns:S,result:wm(D,K),session_id:i}))}catch(ae){o.enqueue(xr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:S,result:Cm(ae),session_id:i??""}))}finally{v=void 0}},Le=async O=>m?(m.methodLower.includes("requestapproval")?m.resolveResponse({decision:O.trim()||"decline"}):m.resolveResponse({text:O.trim()}),!0):!1,pl=async O=>{let D=m;if(!D)return!1;let K=D.actions[O];if(K?.kind==="approval")return D.resolveResponse({decision:K.responseDecision,...K.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:K.proposedExecpolicyAmendment}:{}}),!0;let ue=D.options[O];return ue?(D.methodLower.includes("requestapproval")?D.resolveResponse({decision:ue}):D.resolveResponse({option:ue,index:O}),!0):!1},cl=typeof e.prompt=="string"?(async function*(){yield{type:"user",text:e.prompt,session_id:e.resumeSessionId??""}})():e.prompt;return(async()=>{try{await b();for await(let O of cl){let D=nP(O).trim();!D||await Le(D)||await F(D)}}catch(O){o.enqueue(xr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:S,result:Cm(O),session_id:i??e.resumeSessionId??""}))}finally{await n.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(O){l=O,o.enqueue(di(O))},async submitPendingInputOption(O){return pl(O)},async submitPendingInputText(O){return Le(O)},async interrupt(){!i||!s||await Gn({client:n,methods:["turn/interrupt"],payloads:Am({threadId:i,turnId:s}),timeoutMs:Ar}).catch(()=>{})}}}buildUserMessage(e,r){return{type:"user",text:e,session_id:r}}}});function $m(t){bd.set(t.name,t)}function Hn(t){let e=bd.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...bd.keys()].join(", ")}`);return e}function Em(){return Hn(Pe())}var bd,xd=u(()=>{cm();_m();Re();bd=new Map;$m(new li);$m(new fi)});function $(t){return t.backendRef?.conversationId??t.harnessSessionId}function re(t){return t.id??t.sessionId??t.name??$(t)??t.harnessSessionId}function oP(t){return t.harnessSessionId}function et(t){let e=[re(t),$(t),oP(t)].filter(r=>!!r);return[...new Set(e)]}function Ad(t){return t.harnessName??t.persistedHarness??Pe()}function gi(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return Hn(Ad(t)).capabilities.worktrees}catch{return"plugin-managed"}}function Rd(t){return t==="native-execution"||t==="native-restore"}function Om(t){return t==="native-restore"}function iP(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function Ne(t){return Rd(gi(t))&&iP(t)}var ke=u(()=>{Re();xd()});import{execFileSync as be}from"child_process";import*as Ii from"fs";import{tmpdir as wP}from"os";import{dirname as Qm,join as IP}from"path";function bP(t){try{return be("git",["rev-parse","--show-toplevel"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function bi(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(_.worktreeDir)return _.worktreeDir;if(t){let e=bP(t);if(e)return IP(e,".worktrees")}return wP()}function Jm(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function xi(t){try{let e=be("git",["-C",t,"rev-parse","--git-common-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e&&e.endsWith("/.git")?Qm(e):void 0}catch{return}}function xP(){if(Pi!==void 0)return Pi;try{return be("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Pi=!0,!0}catch{return Pi=!1,!1}}function ir(){if(wi!==void 0)return wi;try{return be("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),wi=!0,!0}catch{return wi=!1,!1}}function Cd(t){if(!xP())return!1;try{return be("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Ym(t){try{let e=RP(t);if(!e)return console.warn(`[worktree] Failed to resolve free-space probe path for ${bi(t)}`),!0;let r=Ii.statfsSync(e),n=r.bavail*r.bsize;return TP(n)}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function Ai(t,e){try{return be("git",["-C",t,"rev-parse","--verify",e],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function AP(t){let e=t;for(;;){if(Ii.existsSync(e))return e;let r=Qm(e);if(r===e)return;e=r}}function RP(t){return AP(bi(t))}function TP(t){return t>=104857600}function sr(t){let e=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(e)return e;try{let n=be("git",["-C",t,"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 be("git",["-C",t,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return be("git",["-C",t,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function Ri(t){try{let r=be("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r==="HEAD"){console.warn(`[worktree] Worktree ${t} is in detached HEAD state \u2014 cannot determine branch name`);return}return r||void 0}catch{return}}function _d(t,e,r){try{let n=be("git",["-C",t,"rev-list","--count",`${r}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(n.trim(),10)>0}catch{return!1}}function Xm(t,e,r){try{let n=be("git",["-C",t,"rev-list","--left-right","--count",`${e}...${r}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),[o,i]=n.split(/\s+/);return{ahead:parseInt(o??"0",10)||0,behind:parseInt(i??"0",10)||0}}catch{return}}function Zm(t,e,r){try{return be("git",["-C",t,"merge-base","--is-ancestor",e,r],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function ef(t,e,r){try{let n=be("git",["-C",t,"merge-tree","--write-tree",r,e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=be("git",["-C",t,"rev-parse",`${r}^{tree}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return!!n&&n===o}catch{return!1}}function $t(t,e){try{return be("git",["-C",t,"branch","-D",e],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){return console.warn(`[worktree] Failed to delete branch ${e}: ${r instanceof Error?r.message:String(r)}`),!1}}function tf(t,e){if(e)return e;let r;try{r=be("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}try{let n=be("git",["-C",t,"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 Pi,wi,Jn=u(()=>{Re()});import{execFileSync as Yn}from"child_process";import{existsSync as MP,mkdirSync as rf,rmSync as nf}from"fs";function $d(t,e){let r=Jm(e),n=bi(t);rf(n,{recursive:!0});let o,i,s=10;for(let d=0;d<s;d++){let l=d===0?"":`-${Math.random().toString(16).slice(2,6)}`,m=`${n}/openclaw-worktree-${r}${l}`,S=`agent/${r}${l}`;try{rf(m,{recursive:!1}),o=m,i=S;break}catch(y){if(y&&typeof y=="object"&&"code"in y&&y.code==="EEXIST")continue;throw y}}if(!o||!i)throw new Error(`Failed to create unique worktree directory after ${s} attempts`);let a=Ai(t,i);try{a?Yn("git",["-C",t,"worktree","add",o,i],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):Yn("git",["-C",t,"worktree","add","-b",i,o],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(d){try{nf(o,{recursive:!0,force:!0})}catch{}throw d}return o}function CP(t){if(!MP(t))return[];try{let e=Yn("git",["-C",t,"status","--porcelain","--untracked-files=all"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e?e.split(`
5
+ `).map(r=>r.trim()).filter(Boolean):[]}catch{return[]}}function tt(t,e,r={}){let n=r.destructive===!0,o=CP(e);if(o.length>0&&!n)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${e}: ${o[0]}`),!1;try{return Yn("git",["-C",t,"worktree","remove",...n?["--force"]:[],e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(i){if(console.warn(`[worktree] git worktree remove failed for ${e}: ${i instanceof Error?i.message:String(i)}`),!n)return!1;try{return nf(e,{recursive:!0,force:!0}),console.info(`[worktree] Fallback rmSync succeeded for ${e}`),!0}catch(s){return console.error(`[worktree] Both git worktree remove and rmSync failed for ${e}: ${s instanceof Error?s.message:String(s)}`),!1}}}function Ti(t){try{Yn("git",["-C",t,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var of=u(()=>{Jn()});import{execFileSync as ne}from"child_process";import{existsSync as _P}from"fs";function Tr(t,e,r){try{let n=ne("git",["-C",t,"rev-list","--count",`${r}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(n.trim(),10),s=ne("git",["-C",t,"diff","--shortstat",`${r}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,l=0,m=s.match(/(\d+)\s+files?\s+changed/);m&&(a=parseInt(m[1],10));let S=s.match(/(\d+)\s+insertions?\(/);S&&(d=parseInt(S[1],10));let y=s.match(/(\d+)\s+deletions?\(/);y&&(l=parseInt(y[1],10));let v=ne("git",["-C",t,"diff","--name-only","--diff-filter=ACMR",`${r}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
6
+ `).map(w=>w.trim()).filter(Boolean),x=ne("git",["-C",t,"log",`${r}..${e}`,"--format=%h|%s|%an","-n","5"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
7
+ `).filter(Boolean).map(w=>{let[C,b,M]=w.split("|");return{hash:C||"",message:b||"",author:M||""}});return{commits:o,filesChanged:a,insertions:d,deletions:l,changedFiles:v,commitMessages:x}}catch(n){console.warn(`[worktree] Failed to get diff summary: ${n instanceof Error?n.message:String(n)}`);return}}function Mi(t,e,r="origin"){try{return ne("git",["-C",t,"push",r,e],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to push branch ${e}: ${n instanceof Error?n.message:String(n)}`),!1}}function an(t){try{return ne("git",["-C",t,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
8
+ `).some(r=>r.length>0&&!r.startsWith("??")&&!r.startsWith("!!"))}catch{return!1}}function Ci(t,e,r,n="merge",o){let i=!1,s,a=d=>{if(i)try{ne("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(n==="squash"){if(ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),an(t)){let y;try{y=ne("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(f){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${f instanceof Error?f.message:String(f)}. Commit or stash changes manually, then retry.`}}if(!y.includes("No local changes to save")){i=!0;try{s=ne("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}ne("git",["-C",t,"merge","--squash",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ne("git",["-C",t,"commit","-m",`Squash merge ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let S=!1;if(i)try{ne("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{S=!0}return{success:!0,stashed:i||void 0,stashRef:s,stashPopConflict:S||void 0}}let d=o&&_P(o),l=d?o:t;if(d||ne("git",["-C",t,"checkout",e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),an(t)){let S;try{S=ne("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(y){try{ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}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=ne("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{ne("git",["-C",l,"rebase",r],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{ne("git",["-C",l,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(t),{success:!1,rebaseConflict:!0,stashed:i||void 0,stashRef:s,error:[`Rebase of ${e} onto ${r} hit conflicts.`,"To resolve manually:",` cd ${l}`,` 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(`
9
+ `)}}ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ne("git",["-C",t,"merge","--ff-only",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let m=!1;if(i)try{ne("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{m=!0}return{success:!0,fastForward:!0,stashed:i||void 0,stashRef:s,stashPopConflict:m||void 0}}catch(d){try{ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(t),{success:!1,error:d instanceof Error?d.message:String(d),stashed:i||void 0,stashRef:s}}}var Ed=u(()=>{});import{execFileSync as _i}from"child_process";function sf(t,e,r,n,o,i){if(!ir())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s;if(i)try{let S=_i("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[:/]([^/]+)\/[^/]+(?:\.git)?$/);S&&(s=S[1])}catch{}let a=["pr","create","--base",r];return i&&a.push("--repo",i),s?a.push("--head",`${s}:${e}`):a.push("--head",e),n&&o?a.push("--title",n,"--body",o):a.push("--fill-verbose"),{success:!0,prUrl:_i("gh",a,{cwd:t,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}function Xn(t,e,r){if(!ir())return{exists:!1,state:"none"};try{let n=["pr","list","--head",e,"--state","all","--json","url,number,title,state","--jq",".[0]"];r&&n.push("--repo",r);let i=_i("gh",n,{cwd:t,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 ${e}: ${n instanceof Error?n.message:String(n)}`),{exists:!1,state:"none"}}}function af(t,e,r,n){if(!ir())return!1;try{let o=["pr","comment",String(e),"--body",r];return n&&o.push("--repo",n),_i("gh",o,{cwd:t,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(o){return console.warn(`[worktree] Failed to comment on PR #${e}: ${o instanceof Error?o.message:String(o)}`),!1}}function Mr(t){if(t.kind==="merge"){let e=t.filesChanged!==void 0?` (${t.filesChanged} files, +${t.insertions??0}/-${t.deletions??0})`:"";return`\u2705 Merged: ${t.branch} \u2192 ${t.base??"main"}${e}`}return t.kind==="pr-updated"?`\u2705 PR updated: ${t.prUrl??""}`:t.targetRepo?`\u2705 PR opened against ${t.targetRepo}: ${t.prUrl??""}`:`\u2705 PR opened: ${t.prUrl??""}`}var Od=u(()=>{Jn()});import{existsSync as Dd}from"fs";function df(){return new Date().toISOString()}function $P(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:df(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function EP(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(Dd(t.workdir)?sr(t.workdir):void 0)}function Zn(t,e={}){let r=$P(t),n=df(),o=new Set,i=Dd(t.workdir),s=!!(t.worktreePath&&Dd(t.worktreePath)),a=t.worktreeBranch,d=EP(t),l=!1,m=!1,S=!1,y=!1,f,v,A=t.worktreePrUrl?"open":"none",x=t.worktreePrUrl,w=t.worktreePrNumber;if(i||o.add("repo_missing"),a||o.add("branch_missing"),!s&&t.worktreePath&&o.add("worktree_missing"),e.activeSession&&o.add("active_session"),r.state==="pending_decision"&&o.add("pending_decision"),r.state==="merge_conflict_resolving"&&o.add("merge_conflict_resolving"),i&&a&&(l=Ai(t.workdir,a),l||o.add("branch_missing")),s&&t.worktreePath&&(m=an(t.worktreePath),m&&o.add("dirty_tracked_changes")),i&&l&&d){let Le=Xm(t.workdir,a,d);f=Le?.ahead,v=Le?.behind,S=Zm(t.workdir,a,d),S?o.add("topology_merged"):(y=ef(t.workdir,a,d),y&&o.add("merge_noop_content_already_on_base"),!y&&(f??0)>0&&o.add("unique_content"))}else d||o.add("base_branch_missing");if(e.includePrSync&&i&&a){let Le=Xn(t.workdir,a,t.worktreePrTargetRepo??r.targetRepo);A=Le.state,x=Le.url??x,w=Le.number??w}A==="open"&&o.add("pr_open"),A==="merged"&&!S&&!y&&o.add("pr_merged_not_reflected_locally");let C=r.state;S?C="merged":y?C="released":!l&&r.state==="pending_decision"&&(C="cleanup_failed");let b=e.activeSession||m||r.state==="pending_decision"||r.state==="merge_conflict_resolving"||r.state==="pr_open"||A==="open"||o.has("pr_merged_not_reflected_locally"),M=!b&&(C==="merged"||C==="released"||r.state==="dismissed"||r.state==="no_change"),F={checkedAt:n,repoExists:i,branchExists:l,worktreeExists:s,activeSession:e.activeSession===!0,dirtyTracked:m,topologyMerged:S,releaseNoopMerge:y,branchAheadCount:f,baseAheadCount:v,prState:A,prUrl:x,prNumber:w,reasons:[...o]};return{lifecycle:r,evidence:F,derivedState:C,cleanupSafe:M,preserve:b,reasons:[...o]}}var $i=u(()=>{Jn();Od();Ed()});var ut=u(()=>{Jn();of();Ed();Od();$i()});function dn(t,e){let r=t.resolve(e),n=t.getPersistedSession(e),o=r?re(r):n?re(n):void 0;return{activeSession:r,persistedSession:n,persistedRef:o,sessionName:r?.name??n?.name??e,worktreePath:r?.worktreePath??n?.worktreePath,originalWorkdir:r?.originalWorkdir??n?.workdir,branchName:r?.worktreeBranch??n?.worktreeBranch,notificationTarget:r??(n?{id:o??e,harnessSessionId:n.harnessSessionId,backendRef:n.backendRef,route:n.route}:void 0)}}function Af(t){return t.persistedSession?et(t.persistedSession):[]}function aw(t,e){let r=[e.id,e.backendConversationId,e.harnessSessionId,e.name],n,o;for(let i of r)if(i&&(n??=t.resolve(i),o??=t.getPersistedSession(i),n&&o))break;return{activeSession:n,persistedSession:o}}function Ui(t,e,r={}){let{activeSession:n,persistedSession:o}=aw(t,e),i=Zn({workdir:e.workdir,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeBaseBranch:r.baseBranch??o?.worktreeBaseBranch,worktreePrTargetRepo:o?.worktreePrTargetRepo,worktreePushRemote:o?.worktreePushRemote,worktreePrUrl:o?.worktreePrUrl,worktreePrNumber:o?.worktreePrNumber,worktreeLifecycle:o?.worktreeLifecycle},{activeSession:!!(n&&(n.status==="starting"||n.status==="running")),includePrSync:!!(o?.worktreeLifecycle?.state==="pr_open"||o?.worktreePrUrl)});return{activeSession:n,persistedSession:o,resolvedLifecycle:i}}function Ki(t){let e=t.list("all").filter(o=>o.worktreePath),r=t.listPersistedSessions().filter(o=>o.worktreePath),n=new Map;for(let o of r){if(!o.worktreePath)continue;let i=$(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 e)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:$(o),harnessSessionId:o.harnessSessionId});return Array.from(n.values())}function Vi(t,e){return t.id===e||t.name===e||t.backendConversationId===e||t.harnessSessionId===e}function _r(t){switch(t){case"none":return"none";case"provisioned":return"active";case"pending_decision":return"needs decision";case"merge_conflict_resolving":return"conflict resolving";case"pr_open":return"pr open";case"merged":return"merged";case"released":return"released";case"dismissed":return"dismissed";case"no_change":return"no change";case"cleanup_failed":return"cleanup failed";default:return t}}function qi(t){switch(t){case"active_session":return"active session";case"pending_decision":return"pending decision";case"merge_conflict_resolving":return"conflict resolving";case"dirty_tracked_changes":return"dirty worktree";case"unique_content":return"still has unique content";case"topology_merged":return"merged by ancestry";case"merge_noop_content_already_on_base":return"content already on base";case"pr_open":return"PR open";case"pr_merged_not_reflected_locally":return"merged PR not reflected locally";case"repo_missing":return"repo missing";case"branch_missing":return"branch missing";case"worktree_missing":return"worktree missing";case"base_branch_missing":return"base branch missing";default:return t.replaceAll("_"," ")}}var to=u(()=>{ke();$i()});var Rf={};lo(Rf,{makeAgentPrTool:()=>ro});import{existsSync as lw}from"fs";function uw(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ro(t){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:p.Object({session:p.String({description:"Session name or ID to create/update PR for"}),title:p.Optional(p.String({description:"PR title (default: auto-generated from session name)"})),body:p.Optional(p.String({description:"PR body (default: auto-generated from commit summary)"})),base_branch:p.Optional(p.String({description:"Base branch for the PR (default: detected from repo)"})),force_new:p.Optional(p.Boolean({description:"Force creation of a new PR even if one exists (default: false)"})),target_repo:p.Optional(p.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex'). Auto-detected from 'upstream' remote if not set."}))}),async execute(e,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(!uw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!ir())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=dn(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:l}=n;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}],meta:{success:!1,state:"error"}};if(!l)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"}};lw(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${l}" via originalWorkdir (${a})`);let m=r.base_branch??sr(a),S=n.persistedRef,y=tf(a,r.target_repo??i?.worktreePrTargetRepo);if(!Mi(a,l))return{content:[{type:"text",text:`\u274C Failed to push ${l} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let f=Xn(a,l,y);if(r.force_new&&f.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${l} (${f.state}).
9
10
 
10
- Existing PR: ${y.url}
11
+ Existing PR: ${f.url}
11
12
 
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}
13
+ 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(f.exists&&f.state==="open"){let v=Tr(a,l,m);if(v&&v.commits>0){let A=v.commitMessages.slice(0,5).map(b=>`\u2022 ${b.hash} ${b.message} (${b.author})`).join(`
14
+ `),x=v.commits>5?`
15
+ ...and ${v.commits-5} more commits`:"",w=["\u{1F504} **New commits pushed**","",`${v.commits} new commits (+${v.insertions} / -${v.deletions})`,"","### Latest commits:",A+x,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
16
+ `);if(af(a,f.number,w,y)){S&&k.updatePersistedSession(S,{worktreePrUrl:f.url,worktreePrNumber:f.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:m,targetRepo:y,pushRemote:i?.worktreePushRemote}});let b=Mr({kind:"pr-updated",branch:l,prUrl:f.url});return k.notifyWorktreeOutcome(n.notificationTarget,b),{content:[{type:"text",text:`${b}
16
17
 
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
+ \u{1F4DD} Added comment detailing ${v.commits} new commits (+${v.insertions} / -${v.deletions})`}],meta:{success:!0,state:"pr_updated"}}}else return{content:[{type:"text",text:`\u26A0\uFE0F Pushed to ${f.url} but failed to add comment.
18
19
 
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
+ ${v.commits} new commits (+${v.insertions} / -${v.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return S&&k.updatePersistedSession(S,{worktreePrUrl:f.url,worktreePrNumber:f.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:m,targetRepo:y,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${f.url}
20
21
 
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
+ No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else{if(f.exists&&f.state==="merged")return S&&k.updatePersistedSession(S,{worktreePrUrl:f.url,worktreePrNumber:f.number,worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDisposition:"merged",worktreeLifecycle:{state:"merged",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"agent_pr",baseBranch:m,targetRepo:y,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2705 PR was already merged: ${f.url}
22
23
 
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
+ The worktree branch ${l} can be cleaned up with agent_merge(delete_branch=true).`}],meta:{success:!0,state:"merged"}};if(f.exists&&f.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${f.url}
24
25
 
25
26
  What would you like to do?
26
27
 
@@ -28,101 +29,185 @@ What would you like to do?
28
29
  2. Close and delete the branch with agent_merge(delete_branch=true), then start a new session/worktree
29
30
  3. Manually delete the closed PR on GitHub, then call agent_pr(force_new=true) to create a fresh PR
30
31
 
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(`
32
+ (This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let v=r.title??`[openclaw-code-agent] ${d}`,A=r.body;if(!A){let w=Tr(a,l,m);if(w){let C=w.commitMessages.slice(0,5).map(M=>`\u2022 ${M.hash} ${M.message} (${M.author})`).join(`
33
+ `),b=w.commits>5?`
34
+ ...and ${w.commits-5} more`:"";A=[`Automated changes from OpenClaw Code Agent session: ${d}`,"","## Summary",`${w.commits} commits, ${w.filesChanged} files changed (+${w.insertions} / -${w.deletions})`,"","## Commits",C+b,"","---","\u{1F916} Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
35
+ `)}else A=`Automated changes from OpenClaw Code Agent session: ${d}`}let x=sf(a,l,m,v,A,y);if(x.success&&x.prUrl){let w=Xn(a,l,y);S&&k.updatePersistedSession(S,{worktreePrUrl:x.prUrl,worktreePrNumber:w.number,lifecycle:"terminal",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeState:"pr_open",worktreeDisposition:"pr-opened",worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:m,targetRepo:y,pushRemote:i?.worktreePushRemote}});let C=Mr({kind:"pr-opened",branch:l,targetRepo:y,prUrl:x.prUrl});return k.notifyWorktreeOutcome(n.notificationTarget,C),{content:[{type:"text",text:C}],meta:{success:!0,state:"created"}}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${x.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var Gi=u(()=>{Ee();Y();ut();to()});import{readdirSync as kb,statSync as vb,rmSync as Pb}from"fs";import{execFileSync as wb}from"child_process";import{join as Og}from"path";Ee();Y();function hv(t){return t.length>80?`${t.slice(0,80)}...`:t}function Sv(t){return t.worktreePath?!t.originalWorkdir||t.originalWorkdir===t.worktreePath?`${t.worktreePath} (worktree)`:`${t.worktreePath} (worktree of ${t.originalWorkdir})`:t.workdir}function yv(t){let e=["Session launched successfully.",` Name: ${t.sessionName}`,` ID: ${t.sessionId}`,` Harness: ${t.harness}`,` Permission mode: ${t.permissionMode}`,` Plan approval: ${t.planApproval}`,` Worktree strategy: ${t.worktreeStrategy??"off"}`,` Resolved workdir: ${Sv(t)}`,` Model: ${t.model??"default"}`,` Prompt: "${hv(t.prompt)}"`];return t.reasoningEffort&&e.push(` Reasoning effort: ${t.reasoningEffort}`),t.resumeSessionId?e.push(` Resume: ${t.resumeSessionId}${t.forkSession?" (forked)":""}`):t.forceNewSession&&e.push(" Force new session: true"),t.clearedPersistedCodexResume&&e.push(" Thread state: historical Codex state cleared; starting a fresh thread."),e.push(" Mode: multi-turn (use agent_respond to send follow-up messages)"),e.push("","Use agent_sessions to check status, agent_output to see output."),e.join(`
36
+ `)}function ti(t,e){return yv({...t,sessionId:e.id,sessionName:e.name,model:e.model,reasoningEffort:e.reasoningEffort,worktreeStrategy:e.worktreeStrategy??"off",worktreePath:e.worktreePath,originalWorkdir:e.originalWorkdir})}Re();function tn(t){let{requestedResumeSessionId:e,activeSession:r,persistedSession:n}=t;return e?r?{resumeSessionId:e,clearedPersistedCodexResume:!1}:n?.harness==="codex"&&n.backendRef?.kind!=="codex-app-server"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:e,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}ke();function Td(t){return"id"in t?t.id:t.sessionId}function zn(t){return t.status==="completed"||t.killReason==="done"}function sP(t){return zn(t)&&t.backendRef?.kind==="codex-app-server"&&!!$(t)}function aP(t){return(t.killReason==="shutdown"||t.killReason==="startup-timeout")&&!$(t)}function Qn(t){if(t.status==="running")return{kind:"direct",reason:"already_running"};let e=Td(t);if(zn(t)&&!sP(t))return{kind:"unavailable",reason:"completed",stableSessionId:e};let r=$(t);if(r){let n="harnessName"in t?void 0:t,{resumeSessionId:o,clearedPersistedCodexResume:i}=tn({requestedResumeSessionId:r,activeSession:"harnessName"in t?{harnessSessionId:r}:void 0,persistedSession:n?{harness:n.harness,backendRef:n.backendRef}:void 0});return o?{kind:"resume",resumeSessionId:o,stableSessionId:e,clearedPersistedCodexResume:i}:{kind:"unavailable",reason:"legacy_non_resumable",stableSessionId:e,clearedPersistedCodexResume:i}}return aP(t)?{kind:"relaunch",stableSessionId:e}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:e}}Re();import{existsSync as Lm}from"fs";ke();function Dm(t){return t==null?void 0:String(t).trim()||void 0}function dP(t){return t.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function lP(t){let e=t.split(/\n\s*\n/,1)[0]?.split(`
37
+ `).map(r=>r.trim()).filter(Boolean)??[];if(e.length!==0)for(let r of e){let n=r.match(/^(Workdir|Repo):\s*(.+)$/),o=dP(n?.[2]??"");if(o.startsWith("/")&&Lm(o))return o}}function Nm(t,e){return t.workdir!==e.workdir?!1:e.originSessionKey&&t.originSessionKey?t.originSessionKey===e.originSessionKey:!e.originChannel||!t.originChannel?!1:t.originChannel===e.originChannel&&Dm(t.originThreadId)===Dm(e.originThreadId)}function Fm(t){return t.slice(0,3).map(e=>` - ${e.name} [${e.ref}] | status=${e.status}${e.lifecycle?` | lifecycle=${e.lifecycle}`:""}`).join(`
38
+ `)}function uP(t,e){let r=[],n=[],o=new Set;for(let i of t.list?.("all")??[]){if(!Nm(i,e))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 t.listPersistedSessions?.()??[]){if(!i.resumable||!Nm(i,e))continue;let s=re(i)??i.harnessSessionId,a=i.sessionId??$(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 pP(t,e){if(!e||e.length===0)return!0;if(!t)return!1;let r=t.toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function Wm(t,e,r){let n=t.workdir||lP(t.prompt)||e.workspaceDir||_.defaultWorkdir||process.cwd();if(!Lm(n))return{kind:"error",text:`Error: Working directory does not exist: ${n}`};let o=t.harness??Pe(),i=Ct(o),s=t.model??i,a=t.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=en(o);if(d&&d.length>0&&!pP(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 l=ni(e),m=qt(e,l||Kn(n)),S=e.sessionKey||void 0,y=dm(S)??Un(e);if(!t.resume_session_id&&!t.force_new_session){let M=uP(r,{workdir:n,originSessionKey:S,originChannel:m,originThreadId:y});if(M.resumable.length>0||M.active.length>0){let F=M.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",Fm(M.resumable),"","Resume the latest one with:",` agent_respond(session='${M.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${M.resumable[0].ref}', fork_session=true)`].join(`
39
+ `):"",Le=M.active.length>0?[M.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",Fm(M.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${M.active[0].ref}', message='<next instruction>')`].join(`
40
+ `):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",F,Le,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
40
41
  `)].filter(Boolean).join(`
41
42
 
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
+ `)}}}let f=t.resume_session_id,v=f?r.resolve?.(f):void 0,A=f?r.getPersistedSession?.(f):void 0;if(f){let M=r.resolveBackendConversationId?.(f)??r.resolveHarnessSessionId?.(f);if(!M)return{kind:"error",text:`Error: Could not resolve resume_session_id "${f}" to a session ID. Use agent_sessions to list available sessions.`};f=M}let{resumeSessionId:x,clearedPersistedCodexResume:w}=tn({requestedResumeSessionId:f,activeSession:v?{harnessSessionId:v.backendConversationId??v.harnessSessionId}:void 0,persistedSession:A?{harness:A.harness,backendRef:A.backendRef}:void 0}),C=t.permission_mode??_.permissionMode,b=t.plan_approval??_.planApproval;return{kind:"resolved",workdir:n,harness:o,resolvedModel:s,permissionMode:C,planApproval:b,originChannel:m,originThreadId:y,originSessionKey:S,route:_t(e,m,S),resumeSessionId:x,resolvedResumeId:f,clearedPersistedCodexResume:w,reasoningEffort:lt(o)}}function cP(t){return t instanceof Error?t.message:String(t)}function Bm(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function mP(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function fP(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function Um(t){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:p.Object({prompt:p.String({description:"The task prompt to execute"}),name:p.Optional(p.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:p.Optional(p.String({description:"Working directory (defaults to cwd)"})),model:p.Optional(p.String({description:"Model name to use"})),system_prompt:p.Optional(p.String({description:"Additional system prompt"})),allowed_tools:p.Optional(p.Array(p.String(),{description:"List of allowed tools"})),resume_session_id:p.Optional(p.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:p.Optional(p.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),force_new_session:p.Optional(p.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:p.Optional(p.Union([p.Literal("default"),p.Literal("plan"),p.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:p.Optional(p.Union([p.Literal("ask"),p.Literal("delegate"),p.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:p.Optional(p.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."})),worktree_strategy:p.Optional(p.Union([p.Literal("off"),p.Literal("manual"),p.Literal("ask"),p.Literal("delegate"),p.Literal("auto-merge"),p.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:p.Optional(p.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),worktree_pr_target_repo:p.Optional(p.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(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!mP(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="${t.agentId}" will be used for origin routing instead.`);try{let n=Wm(r,t,k);if(n.kind!=="resolved")return{content:[{type:"text",text:n.text}]};let{workdir:o,harness:i,resolvedModel:s,permissionMode:a,planApproval:d,originChannel:l,originThreadId:m,originSessionKey:S,route:y,resumeSessionId:f,resolvedResumeId:v,clearedPersistedCodexResume:A,reasoningEffort:x}=n,w=r.resume_session_id?k.resolve(r.resume_session_id)??k.getPersistedSession(r.resume_session_id):void 0,C=!r.fork_session&&w?Qn(w):void 0;if(C?.kind==="direct")return{content:[{type:"text",text:`Session ${w.name} [${Bm(w,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(C?.kind==="unavailable")return{content:[{type:"text",text:`Resume unavailable for session ${w.name} [${Bm(w,r.resume_session_id)}] (${C.reason}). Use agent_launch(prompt='<new task>') for a fresh session or set fork_session=true to fork from prior context.`}]};let b=k.spawn({prompt:r.prompt,sessionIdOverride:r.fork_session?void 0:C?.kind==="resume"||C?.kind==="relaunch"?C.stableSessionId:void 0,name:r.name,workdir:o,model:s,reasoningEffort:x,systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,resumeSessionId:C?.kind==="resume"?C.resumeSessionId:f,resumeWorktreeFrom:v,forkSession:f?r.fork_session:!1,multiTurn:!0,permissionMode:a,planApproval:d,codexApprovalPolicy:i==="codex"?"never":void 0,originChannel:l,originThreadId:m,originAgentId:t.agentId||void 0,originSessionKey:S,route:y,harness:i,worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,worktreePrTargetRepo:r.worktree_pr_target_repo});return{content:[{type:"text",text:fP(k)?k.formatLaunchResult({prompt:r.prompt,workdir:o,harness:i,permissionMode:a??_.permissionMode,planApproval:d,forceNewSession:r.force_new_session,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,clearedPersistedCodexResume:A},b):ti({prompt:r.prompt,workdir:o,harness:i,permissionMode:a??_.permissionMode,planApproval:d,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,forceNewSession:r.force_new_session,clearedPersistedCodexResume:A},{id:b.id,name:b.name,model:b.model,reasoningEffort:b.reasoningEffort??lt(i),worktreeStrategy:b.worktreeStrategy??r.worktree_strategy??_.defaultWorktreeStrategy??"off",worktreePath:b.worktreePath,originalWorkdir:b.originalWorkdir})}]}}catch(n){let o=cP(n),i=o.includes("Max sessions")?"":`
43
44
 
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.]
45
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}Ee();Y();Re();import{existsSync as Nd,readFileSync as ff}from"fs";import{EventEmitter as OP}from"events";import{webcrypto as Vm}from"node:crypto";var Km="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var gP=128,Rr,on;function hP(t){!Rr||Rr.length<t?(Rr=Buffer.allocUnsafe(t*gP),Vm.getRandomValues(Rr),on=0):on+t>Rr.length&&(Vm.getRandomValues(Rr),on=0),on+=t}function hi(t=21){hP(t|=0);let e="";for(let r=on-t;r<on;r++)e+=Km[Rr[r]&63];return e}xd();Re();ke();var qm={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},jm=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function SP(t){return t.requestedPermissionMode!=="plan"?"not_plan_gated":t.pendingPlanApproval?"awaiting_approval":t.planModeApproved?"approved_then_implemented":t.currentPermissionMode!=="plan"?"implemented_without_required_approval":"awaiting_plan_output"}function Oe(t){return{...t,approvalExecutionState:SP(t)}}function Md(t,e){switch(e.type){case"initialize":return Oe({...t,worktreeState:e.hasWorktree&&t.worktreeState==="none"?"provisioned":t.worktreeState,lifecycle:t.status==="starting"?"starting":t.lifecycle,runtimeState:t.status==="starting"?"live":t.runtimeState});case"status.transition":return e.status==="starting"?Oe({...t,status:e.status,lifecycle:"starting",runtimeState:"live"}):e.status==="running"?Oe({...t,status:e.status,lifecycle:t.lifecycle==="starting"||t.lifecycle==="suspended"?"active":t.lifecycle,runtimeState:"live"}):Oe({...t,status:e.status,runtimeState:"stopped",lifecycle:t.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return Oe({...t,currentPermissionMode:e.currentPermissionMode});case"turn.started":return Oe({...t,lifecycle:"active",runtimeState:"live"});case"input.requested":return Oe({...t,lifecycle:t.pendingPlanApproval?"awaiting_plan_decision":"awaiting_user_input"});case"plan.requested":if(t.planModeApproved)return t;{let r=t.pendingPlanApproval&&t.approvalState==="pending"&&t.planApprovalContext===e.context,n=t.pendingPlanApproval&&t.approvalState==="changes_requested"&&t.planApprovalContext===e.context&&t.planDecisionVersion>0,o=!t.pendingPlanApproval&&t.approvalState==="changes_requested"&&t.planApprovalContext===e.context&&t.planDecisionVersion>0,i=r||n||o?t.planDecisionVersion:t.planDecisionVersion+1;return Oe({...t,pendingPlanApproval:!0,planApprovalContext:e.context,approvalState:"pending",planDecisionVersion:i,actionablePlanDecisionVersion:i,canonicalPlanPromptVersion:r?t.canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:r?t.approvalPromptRequiredVersion:void 0,approvalPromptVersion:r?t.approvalPromptVersion:void 0,approvalPromptStatus:r?t.approvalPromptStatus:"not_sent",approvalPromptTransport:r?t.approvalPromptTransport:"none",approvalPromptMessageKind:r?t.approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:r?t.approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:r?t.approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:r?t.approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"})}case"plan.cleared":return Oe({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,approvalState:t.approvalState==="pending"?"not_required":t.approvalState});case"plan.approved":return Oe({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,planModeApproved:!0,approvalState:"approved",planDecisionVersion:t.planDecisionVersion+1,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",lifecycle:t.status==="running"?"active":t.lifecycle});case"plan.changes_requested":return Oe({...t,pendingPlanApproval:!0,approvalState:"changes_requested",planDecisionVersion:t.planDecisionVersion+1,actionablePlanDecisionVersion:void 0,canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:void 0,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",approvalPromptTransport:"none",approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"});case"terminal.entered":return Oe({...t,lifecycle:e.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return Oe({...t,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return Oe({...t,worktreeState:e.worktreeState,lifecycle:e.worktreeState==="pending_decision"?"awaiting_worktree_decision":jm.has(e.worktreeState)?"terminal":t.lifecycle});case"delivery.state_set":return Oe({...t,deliveryState:e.deliveryState})}}function Gm(t,e){let r={...t,...e.lifecycle!==void 0?{lifecycle:e.lifecycle}:{},...e.approvalState!==void 0?{approvalState:e.approvalState}:{},...e.approvalExecutionState!==void 0?{approvalExecutionState:e.approvalExecutionState}:{},...e.worktreeState!==void 0?{worktreeState:e.worktreeState}:{},...e.runtimeState!==void 0?{runtimeState:e.runtimeState}:{},...e.deliveryState!==void 0?{deliveryState:e.deliveryState}:{},...e.requestedPermissionMode!==void 0?{requestedPermissionMode:e.requestedPermissionMode}:{},...e.currentPermissionMode!==void 0?{currentPermissionMode:e.currentPermissionMode}:{},...e.pendingPlanApproval!==void 0?{pendingPlanApproval:e.pendingPlanApproval}:{},...e.planApprovalContext!==void 0?{planApprovalContext:e.planApprovalContext}:{},...e.planDecisionVersion!==void 0?{planDecisionVersion:e.planDecisionVersion}:{},...e.actionablePlanDecisionVersion!==void 0?{actionablePlanDecisionVersion:e.actionablePlanDecisionVersion}:{},...e.canonicalPlanPromptVersion!==void 0?{canonicalPlanPromptVersion:e.canonicalPlanPromptVersion}:{},...e.approvalPromptRequiredVersion!==void 0?{approvalPromptRequiredVersion:e.approvalPromptRequiredVersion}:{},...e.approvalPromptVersion!==void 0?{approvalPromptVersion:e.approvalPromptVersion}:{},...e.approvalPromptStatus!==void 0?{approvalPromptStatus:e.approvalPromptStatus}:{},...e.approvalPromptTransport!==void 0?{approvalPromptTransport:e.approvalPromptTransport}:{},...e.approvalPromptMessageKind!==void 0?{approvalPromptMessageKind:e.approvalPromptMessageKind}:{},...e.approvalPromptLastAttemptAt!==void 0?{approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt}:{},...e.approvalPromptDeliveredAt!==void 0?{approvalPromptDeliveredAt:e.approvalPromptDeliveredAt}:{},...e.approvalPromptFailedAt!==void 0?{approvalPromptFailedAt:e.approvalPromptFailedAt}:{},...e.planModeApproved!==void 0?{planModeApproved:e.planModeApproved}:{}};return e.approvalState==="changes_requested"&&e.pendingPlanApproval===void 0&&(r={...r,pendingPlanApproval:!1}),r.pendingPlanApproval?r={...r,approvalState:"pending",actionablePlanDecisionVersion:r.actionablePlanDecisionVersion??r.planDecisionVersion,lifecycle:"awaiting_plan_decision"}:r.approvalState==="changes_requested"&&(r={...r,actionablePlanDecisionVersion:void 0,lifecycle:"awaiting_user_input"}),e.pendingWorktreeDecisionSince!==void 0||r.worktreeState==="pending_decision"?r=Md(r,{type:"worktree.decision_requested"}):jm.has(r.worktreeState)&&(r={...r,lifecycle:"terminal"}),Oe(r)}var Si=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(e){this.queue.push(e),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(e=>{this.resolve=e})}}};import{appendFileSync as yP}from"fs";import{tmpdir as kP}from"os";import{join as vP}from"path";var Hm=2e3;function sn(t){return vP(kP(),`openclaw-agent-${t}.txt`)}function PP(t,e){if(!e)return;let r=e.split(`
46
+ `),[n="",...o]=r;t.length===0?t.push(n):t[t.length-1]+=n;for(let i of o)t.push(i)}function zm(t,e,r){PP(t,r),t.length>Hm&&t.splice(0,t.length-Hm);try{yP(sn(e),r,"utf-8")}catch{}return t}var yi=class{timers=new Map;get size(){return this.timers.size}set(e,r,n){this.clear(e);let o=setTimeout(n,r);o.unref?.(),this.timers.set(e,o)}clear(e){let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var ki=class{constructor(e){this.deps=e}deps;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(e,r){this.waitingForInputFired=!1,r||(this.lastTurnHadQuestion=!1),this.deps.appendOutput(e),this.currentTurnText+=this.currentTurnText?`
47
+ ${e}`:e,this.deps.emitOutput(e)}noteToolCall(e){let{name:r,input:n,currentPermissionMode:o,permissionMode:i,planModeApproved:s}=e;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(e,r){if(!(!e||r?.requestId===e))return r}notePlanArtifact(e,r){if(this.currentTurnPlanArtifact=e,this.deps.setLatestPlanArtifact(e),!r)return;let n=e.markdown.trim();!n||this.currentTurnText.trim()===n||(this.deps.appendOutput(n),this.currentTurnText=n,this.deps.emitOutput(n))}noteSettingsChanged(e){let{oldMode:r,permissionMode:n,planModeApproved:o}=e;if(n)return n!=="plan"&&r==="plan"&&!o&&(this.deps.markPendingPlanApproval("plan-mode"),this.lastTurnHadQuestion=!0),n}finishSuccessfulTurn(e){let{currentPermissionMode:r,permissionMode:n,pendingPlanApproval:o,planModeApproved:i,pendingInputState:s,hasPendingMessages:a}=e,d=o;(r==="plan"||n==="plan")&&!d&&!i&&(this.deps.markPendingPlanApproval("plan-mode"),d=!0);let l=d||this.lastTurnHadQuestion||!!s;this.turnInProgress=a,l&&!this.waitingForInputFired?(this.waitingForInputFired=!0,d||this.deps.markAwaitingUserInput(),this.deps.emitTurnEnd(!0)):!a&&!l&&(this.deps.completeTurn(),this.deps.emitTurnEnd(!1))}finishTerminalTurn(){this.turnInProgress=!1}finishInterruptedTurn(e){this.turnInProgress=e,this.waitingForInputFired=!1,this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}resetAfterRun(){this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}};var vi=class{constructor(e){this.deps=e}deps;applyMessage(e,r){if(e.type==="backend_ref"){this.deps.clearStartupTimer(),this.deps.assignBackendRef({...e.ref}),this.deps.transitionRunning();return}if(e.type==="run_started"){e.runId&&this.deps.noteRunStarted(e.runId);return}if(e.type==="text_delta"){this.deps.noteTextDelta(e.text,r.pendingPlanApproval);return}if(e.type==="tool_call"){this.deps.noteToolCall({name:e.name,input:e.input,currentPermissionMode:r.currentPermissionMode,permissionMode:r.permissionMode,planModeApproved:r.planModeApproved});return}if(e.type==="pending_input"){this.deps.setPendingInputState(e.state),this.deps.notePendingInput();return}if(e.type==="pending_input_resolved"){this.deps.setPendingInputState(this.deps.clearResolvedPendingInput(e.requestId,r.pendingInputState));return}if(e.type==="plan_artifact"){this.deps.notePlanArtifact(e);return}if(e.type==="settings_changed"){let n=this.deps.noteSettingsChanged({oldMode:r.currentPermissionMode,permissionMode:e.permissionMode,planModeApproved:r.planModeApproved});n&&this.deps.setCurrentPermissionMode(n);return}if(e.type==="run_completed"){this.deps.handleRunCompleted(e.data);return}e.type}};ut();var DP=120*1e3;function Ei(t){return t instanceof Error?t.message:String(t)}var Oi=class extends OP{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;autoMergeParentSessionId;autoMergeConflictResolutionAttemptCount;autoMergeResolverSessionId;worktreePushRemote;worktreeDisposition;worktreePrUrl;worktreePrNumber;worktreeMerged;worktreeMergedAt;worktreeLifecycle;worktreeState="none";multiTurn;goalTaskId;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;route;pendingInputState;pendingPlanApproval=!1;planApprovalContext;planDecisionVersion=0;actionablePlanDecisionVersion;canonicalPlanPromptVersion;approvalPromptRequiredVersion;approvalPromptVersion;approvalPromptStatus="not_sent";approvalPromptTransport="none";approvalPromptMessageKind="none";approvalPromptLastAttemptAt;approvalPromptDeliveredAt;approvalPromptFailedAt;planFilePath;killReason="unknown";planModeApproved=!1;turnRuntime;harnessEvents;lifecycle="starting";approvalState="not_required";approvalExecutionState="not_plan_gated";approvalRationale;latestPlanArtifact;latestPlanArtifactVersion;runtimeState="live";deliveryState="idle";canUseTool;autoRespondCount=0;timers=new yi;constructor(e,r){super(),this.id=e.sessionIdOverride??hi(8),this.name=r,this.harness=e.harness?Hn(e.harness):Em(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??Ct(this.harness.name),this.reasoningEffort=e.reasoningEffort??lt(this.harness.name),this.systemPrompt=e.systemPrompt,this.allowedTools=e.allowedTools,this.permissionMode=e.permissionMode??_.permissionMode,this.requestedPermissionMode=e.requestedPermissionMode??this.permissionMode,this.planApproval=e.planApproval??_.planApproval,this.codexApprovalPolicy=this.harness.name==="codex"?"never":void 0,this.currentPermissionMode=this.permissionMode,this.originChannel=e.originChannel,this.originThreadId=e.originThreadId,this.originAgentId=e.originAgentId,this.originSessionKey=e.originSessionKey,this.route=e.route?{...e.route}:void 0,this.backendRef=e.backendRef?{...e.backendRef}:void 0,this.resumeSessionId=e.resumeSessionId,this.forkSession=e.forkSession,this.multiTurn=e.multiTurn??!0,this.goalTaskId=e.goalTaskId,this.worktreeStrategy=e.worktreeStrategy,this.worktreeBaseBranch=e.worktreeBaseBranch,e.worktreePrTargetRepo&&(this.worktreePrTargetRepo=e.worktreePrTargetRepo),e.autoMergeParentSessionId&&(this.autoMergeParentSessionId=e.autoMergeParentSessionId),e.autoMergeConflictResolutionAttemptCount!==void 0&&(this.autoMergeConflictResolutionAttemptCount=e.autoMergeConflictResolutionAttemptCount),e.autoMergeResolverSessionId&&(this.autoMergeResolverSessionId=e.autoMergeResolverSessionId),this.canUseTool=e.canUseTool,this.startedAt=Date.now(),this.abortController=new AbortController,this.turnRuntime=new ki({appendOutput:n=>zm(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},setLatestPlanArtifact:n=>{this.latestPlanArtifact=n;let o=this.pendingPlanApproval?this.actionablePlanDecisionVersion??this.planDecisionVersion:void 0;this.latestPlanArtifactVersion=o&&o>0?o:void 0}}),this.harnessEvents=new vi({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??=Ri(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=>{let o=n.outcome??(n.success?"completed":"failed");this.result={subtype:o==="interrupted"?"interrupted":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:o==="failed",session_id:n.session_id},this.costUsd=n.total_cost_usd;let i=this.multiTurn&&this.messageStream&&o==="interrupted",s=this.multiTurn&&this.messageStream&&o==="completed";i?(this.resetIdleTimer(),this.turnRuntime.finishInterruptedTurn(this.messageStream?.hasPending()===!0)):s?(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(o==="completed"?"completed":"failed")),this.turnRuntime.resetAfterRun(),this.pendingInputState=void 0}}),this.applyControlEvent({type:"initialize",hasWorktree:!!(this.worktreeStrategy&&this.worktreeStrategy!=="off")}),(e.planModeApproved!==void 0||e.approvalState!==void 0||e.approvalExecutionState!==void 0||e.approvalRationale!==void 0||e.pendingPlanApproval!==void 0||e.planApprovalContext!==void 0||e.planDecisionVersion!==void 0||e.actionablePlanDecisionVersion!==void 0||e.canonicalPlanPromptVersion!==void 0||e.approvalPromptRequiredVersion!==void 0||e.approvalPromptVersion!==void 0||e.approvalPromptStatus!==void 0||e.approvalPromptTransport!==void 0||e.approvalPromptMessageKind!==void 0||e.approvalPromptLastAttemptAt!==void 0||e.approvalPromptDeliveredAt!==void 0||e.approvalPromptFailedAt!==void 0)&&this.applyControlPatch({...e.planModeApproved!==void 0?{planModeApproved:e.planModeApproved}:{},...e.approvalState!==void 0?{approvalState:e.approvalState}:{},...e.approvalExecutionState!==void 0?{approvalExecutionState:e.approvalExecutionState}:{},...e.pendingPlanApproval!==void 0?{pendingPlanApproval:e.pendingPlanApproval}:{},...e.planApprovalContext!==void 0?{planApprovalContext:e.planApprovalContext}:{},...e.planDecisionVersion!==void 0?{planDecisionVersion:e.planDecisionVersion}:{},...e.actionablePlanDecisionVersion!==void 0?{actionablePlanDecisionVersion:e.actionablePlanDecisionVersion}:{},...e.canonicalPlanPromptVersion!==void 0?{canonicalPlanPromptVersion:e.canonicalPlanPromptVersion}:{},...e.approvalPromptRequiredVersion!==void 0?{approvalPromptRequiredVersion:e.approvalPromptRequiredVersion}:{},...e.approvalPromptVersion!==void 0?{approvalPromptVersion:e.approvalPromptVersion}:{},...e.approvalPromptStatus!==void 0?{approvalPromptStatus:e.approvalPromptStatus}:{},...e.approvalPromptTransport!==void 0?{approvalPromptTransport:e.approvalPromptTransport}:{},...e.approvalPromptMessageKind!==void 0?{approvalPromptMessageKind:e.approvalPromptMessageKind}:{},...e.approvalPromptLastAttemptAt!==void 0?{approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt}:{},...e.approvalPromptDeliveredAt!==void 0?{approvalPromptDeliveredAt:e.approvalPromptDeliveredAt}:{},...e.approvalPromptFailedAt!==void 0?{approvalPromptFailedAt:e.approvalPromptFailedAt}:{}}),this.approvalRationale=e.approvalRationale}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 $(this)}get waitingForInputFired(){return this.turnRuntime.waitingForInputFired}set waitingForInputFired(e){this.turnRuntime.waitingForInputFired=e}get lastTurnHadQuestion(){return this.turnRuntime.lastTurnHadQuestion}set lastTurnHadQuestion(e){this.turnRuntime.lastTurnHadQuestion=e}get turnInProgress(){return this.turnRuntime.turnInProgress}set turnInProgress(e){this.turnRuntime.turnInProgress=e}get currentTurnText(){return this.turnRuntime.currentTurnText}set currentTurnText(e){this.turnRuntime.currentTurnText=e}get currentTurnPlanArtifact(){return this.turnRuntime.currentTurnPlanArtifact}set currentTurnPlanArtifact(e){this.turnRuntime.currentTurnPlanArtifact=e}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(e){if(!qm[this._status].includes(e))throw new Error(`Session state error: cannot transition from ${this._status} to ${e}. This is an internal error \u2014 please report it.`);let r=this._status;this._status=e,this.applyControlEvent({type:"status.transition",status:e}),this.emit("statusChange",this,e,r)}setTimer(e,r,n){this.timers.set(e,r,n)}clearTimer(e){this.timers.clear(e)}clearAllTimers(){this.timers.clearAll()}markPendingPlanApproval(e){let r=this.latestPlanArtifactVersion;this.approvalRationale=void 0,this.applyControlEvent({type:"plan.requested",context:e});let n=this.actionablePlanDecisionVersion??this.planDecisionVersion;this.currentTurnPlanArtifact&&n>0?(this.latestPlanArtifact=this.currentTurnPlanArtifact,this.latestPlanArtifactVersion=n):r!==n&&(this.latestPlanArtifact=void 0,this.latestPlanArtifactVersion=void 0)}clearPendingPlanApproval(){this.applyControlEvent({type:"plan.cleared"})}markAwaitingUserInput(){this.applyControlEvent({type:"input.requested"})}async start(){try{let e;this.multiTurn?(this.messageStream=new Si,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),e=this.messageStream):e=this.prompt;let r=this.harness.launch({prompt:e,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:im(),canUseTool:this.canUseTool});this.harnessHandle=r,this.setTimer("startup",DP,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(e){let r=e instanceof Error?e.message:String(e);this.transitionToTerminal("failed",{error:r});return}this.consumeMessages(this.harnessHandle.messages).catch(e=>{let r=e instanceof Error?e.message:String(e),n=e instanceof Error?e.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${r}`,n),this.isActive&&this.transitionToTerminal("failed",{error:r})})}async sendMessage(e){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=e;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: ${Ei(s)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${n}: ${Ei(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
 
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
+ ${e}`)}else if((this.pendingPlanApproval||this.approvalState==="changes_requested")&&!this.planModeApproved&&(this.approvalState!=="changes_requested"&&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
 
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?`
51
+ ${e}`,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: ${Ei(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(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputOption)return!1;let r=await this.harnessHandle.submitPendingInputOption(e);return r&&(this.waitingForInputFired=!1),r}async submitPendingInputText(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputText)return!1;let r=await this.harnessHandle.submitPendingInputText(e);return r&&(this.waitingForInputFired=!1),r}switchPermissionMode(e){this.pendingModeSwitch=e}get isActive(){return this._status==="starting"||this._status==="running"}kill(e){this.transitionToTerminal("killed",{reason:e})}complete(e="done"){this.transitionToTerminal("completed",{reason:e})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(e){return e===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-e)}resetIdleTimer(){if(!this.multiTurn)return;let e=(_.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",e,()=>{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(e=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${Ei(e)}`)}),this.abortController.abort(),this.applyControlEvent({type:"terminal.entered",suspended:this.lifecycle==="suspended"})}transitionToTerminal(e,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:e==="killed"&&r.reason==="idle-timeout"}),this.transition(e),this.teardown())}async consumeMessages(e){for await(let r of e){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,actionablePlanDecisionVersion:this.actionablePlanDecisionVersion,canonicalPlanPromptVersion:this.canonicalPlanPromptVersion,approvalPromptRequiredVersion:this.approvalPromptRequiredVersion,approvalPromptVersion:this.approvalPromptVersion,approvalPromptStatus:this.approvalPromptStatus,approvalPromptTransport:this.approvalPromptTransport,approvalPromptMessageKind:this.approvalPromptMessageKind,approvalPromptLastAttemptAt:this.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:this.approvalPromptDeliveredAt,approvalPromptFailedAt:this.approvalPromptFailedAt,planModeApproved:this.planModeApproved}}applyControlEvent(e){let r=Md(this.controlStateSnapshot(),e);this.applyControlState(r)}applyControlPatch(e){let r=Gm(this.controlStateSnapshot(),e);this.applyControlState(r)}applyControlState(e){this.lifecycle=e.lifecycle,this.approvalState=e.approvalState,this.approvalExecutionState=e.approvalExecutionState,this.worktreeState=e.worktreeState,this.runtimeState=e.runtimeState,this.deliveryState=e.deliveryState,this.pendingPlanApproval=e.pendingPlanApproval,this.planApprovalContext=e.planApprovalContext,this.planDecisionVersion=e.planDecisionVersion,this.actionablePlanDecisionVersion=e.actionablePlanDecisionVersion,this.canonicalPlanPromptVersion=e.canonicalPlanPromptVersion,this.approvalPromptRequiredVersion=e.approvalPromptRequiredVersion,this.approvalPromptVersion=e.approvalPromptVersion,this.approvalPromptStatus=e.approvalPromptStatus,this.approvalPromptTransport=e.approvalPromptTransport,this.approvalPromptMessageKind=e.approvalPromptMessageKind,this.approvalPromptLastAttemptAt=e.approvalPromptLastAttemptAt,this.approvalPromptDeliveredAt=e.approvalPromptDeliveredAt,this.approvalPromptFailedAt=e.approvalPromptFailedAt,this.planModeApproved=e.planModeApproved}};ke();function It(t){let e=Math.floor(t/1e3),r=Math.floor(e/60),n=e%60;return r>0?`${r}m${n}s`:`${n}s`}var NP=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 uf(t){let r=t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!NP.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var lf={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 pf(t){let e=lf[t.phase]??lf[t.status]??"\u2753",r=It(t.duration),n=t.multiTurn?"multi-turn":"single",o=t.prompt.length>80?t.prompt.slice(0,80)+"...":t.prompt,i=t.costUsd>0?` | $${t.costUsd.toFixed(2)}`:"",s=[`${e} ${t.name} [${t.id}] (${r}${i}) \u2014 ${n}`,` \u{1F4C1} ${t.workdir}`,` \u{1F4DD} "${o}"`];if(t.worktreePath&&t.worktreeBranch){let d=` \u{1F33F} Worktree: ${t.worktreeBranch}`;t.worktreeMerged?d+=" [merged \u2713]":t.worktreePrUrl?d+=` [PR: ${t.worktreePrUrl}]`:d+=" [not merged]",s.push(d)}t.phase!==t.status&&s.push(` \u2699\uFE0F Phase: ${t.phase}`),t.lifecycle&&t.lifecycle!==t.phase&&s.push(` \u{1F504} Lifecycle: ${t.lifecycle}`),(t.requestedPermissionMode||t.currentPermissionMode||t.approvalExecutionState)&&s.push(` \u{1F510} Approval: ${t.approvalExecutionState??"unknown"} (requested=${t.requestedPermissionMode??"unknown"}, effective=${t.currentPermissionMode??"unknown"})`),t.resumable&&s.push(" \u21A9\uFE0F Resumable: yes"),t.harness&&s.push(` \u{1F9F0} Harness: ${t.harness}`);let a=$(t);return a&&s.push(` \u{1F517} Backend ID: ${a}`),t.resumeSessionId&&s.push(` \u21A9\uFE0F Resumed from: ${t.resumeSessionId}${t.forkSession?" (forked)":""}`),s.join(`
52
+ `)}function Di(t,e){let r=t.sessionsWithDuration>0?t.totalDurationMs/t.sessionsWithDuration:0,{completed:n,failed:o,killed:i}=t.sessionsByStatus,s=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${t.totalLaunched}`,` Running: ${e}`,` Completed: ${n}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${r>0?It(r):"n/a"}`];if(t.mostExpensive){let a=t.mostExpensive;s.push("","\u{1F3C6} Notable session",` ${a.name} [${a.id}]`,` \u{1F4DD} "${a.prompt}"`)}return s.join(`
53
+ `)}function Fe(t,e){return e<=0?"":t.length<=e?t:e<=3?".".repeat(e):t.slice(0,e-3)+"..."}function cf(t,e){let r=t.split(`
54
+ `),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>e&&n.length>0)break;n.unshift(r[i]),o+=s}return n.join(`
55
+ `)}function mf(t,e){let r=t.split(`
56
+ `),n=[],o=0;for(let i=0;i<r.length;i++){let s=r[i].length+(n.length>0?1:0);if(o+s>e&&n.length>0)break;n.push(r[i]),o+=s}return n.join(`
57
+ `)}var FP=50,LP=1,WP=new Set(["starting","running","completed","failed","killed"]),BP=5,UP=1440*60*1e3;function KP(t){let e=Number(t);return!Number.isFinite(e)||e<LP?FP:Math.floor(e)}function VP(t){return typeof t=="string"&&WP.has(t)}function qP(t){let e=t.split(`
58
+ `);return e.at(-1)===""&&e.pop(),e}function gf(t){return t.backendRef?.conversationId??t.harnessSessionId}function hf(t,e,r){let n=ff(t,"utf-8"),o=qP(n);return e.full?o:o.slice(-r)}function jP(t,e,r){if(t.status!=="starting"&&t.status!=="running")return null;let n=sn(t.id);if(!Nd(n))return null;try{return hf(n,e,r)}catch{return null}}function GP(t){let e=It(t.duration),r=` | Cost: $${t.costUsd.toFixed(4)}`,n=t.phase?` | Phase: ${t.phase}`:"",o=t.lifecycle&&t.lifecycle!==t.phase?` | Lifecycle: ${t.lifecycle}`:"";return[`Session: ${t.name} [${t.id}] | Status: ${t.status.toUpperCase()}${n}${o}${r} | Duration: ${e}`,`${"\u2500".repeat(60)}`].join(`
59
+ `)}function HP(t){return[`Session: ${t.name||t.sessionId||gf(t)||"unknown"} | Status: ${t.status.toUpperCase()} | Cost: $${t.costUsd.toFixed(4)}`,`(retrieved from ${t.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`,`${"\u2500".repeat(60)}`].join(`
60
+ `)}function zP(t){let e=[];return t.error&&e.push(`Error: ${t.error}`),t.result?.result&&e.push(`Result: ${t.result.result}`),t.result&&e.push(`Result status: ${t.result.subtype}`),e.length>0?`
60
61
  (no output yet)
61
- ${t.join(`
62
+ ${e.join(`
62
63
  `)}`:`
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}
64
+ (no output yet)`}function Ni(t,e,r={}){let n=KP(r.lines),o=t.resolve(e);if(!o){let l=t.getPersistedSession(e);if(l?.outputPath&&Nd(l.outputPath))try{let m=hf(l.outputPath,r,n).join(`
65
+ `),S=HP(l);return m?`${S}
66
+ ${m}`:`${S}
67
+ (output file was empty)`}catch(m){let S=m instanceof Error?m.message:String(m);return`Error: Session "${e}" was cleaned up (expired) and output file could not be read: ${S}`}return`Error: Session "${e}" not found.`}let i=jP(o,r,n),s=i&&i.length>0?i:r.full?o.getOutput():o.getOutput(n),a=GP(o),d=s.length===0?`${a}${zP(o)}`:`${a}
67
68
  ${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}
69
+ `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(Nd(o.planFilePath)){let l=ff(o.planFilePath,"utf-8"),m="\u2500".repeat(60);return`${d}
70
+ ${m}
70
71
  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};
72
+ ${m}
73
+ ${l}`}}catch{}return d}function Fi(t,e="all",r,n={}){let o=t.listPersistedSessions()??[],s=QP(t.list("all"),o);if(e!=="all"&&(s=s.filter(a=>a.status===e)),r&&(s=s.filter(a=>a.originChannel===r)),n.full){let a=Date.now()-UP;s=s.filter(d=>(d.startedAt??0)>=a)}else s=s.slice(0,BP);return s.length===0?"No sessions found.":s.map(a=>pf(a)).join(`
74
+
75
+ `)}function QP(t,e){let r=new Map;for(let n of e){if(!VP(n.status))continue;let o=n.completedAt??Date.now(),i=n.createdAt??o,s=gf(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 t)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 JP(t){if(!t||typeof t!="object")return"all";let e=t.status;switch(e){case"running":case"completed":case"failed":case"killed":case"all":return e;default:return"all"}}function Sf(t){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:p.Object({status:p.Optional(p.Union([p.Literal("all"),p.Literal("running"),p.Literal("completed"),p.Literal("failed"),p.Literal("killed")],{description:'Filter by status (default "all")'})),full:p.Optional(p.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=JP(r),o=t?.workspaceDir?Kn(t.workspaceDir):void 0,i=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:Fi(k,n,o,{full:i})}]}}}}Ee();Y();function Li(t,e,r){let n=t.resolve(e);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.`):(t.kill(n.id),`Session ${n.name} [${n.id}] has been terminated.`):`Error: Session "${e}" not found.`}function YP(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session!="string"?!1:e.reason===void 0?!0:e.reason==="completed"||e.reason==="killed"}function yf(t){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:p.Object({session:p.String({description:"Session name or ID to terminate"}),reason:p.Optional(p.Union([p.Literal("completed"),p.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(e,r){return k?YP(r)?{content:[{type:"text",text:Li(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."}]}}}}Ee();Y();function XP(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Wi(t){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:p.Object({session:p.String({description:"Session name or ID to get output from"}),lines:p.Optional(p.Number({description:"Number of recent lines to show (default 50)"})),full:p.Optional(p.Boolean({description:"Show all available output"}))}),async execute(e,r){return k?XP(r)?{content:[{type:"text",text:Ni(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."}]}}}}Ee();Y();Re();ke();var ZP=10;function Ld(t){return t instanceof Error?t.message:String(t)}function Cr(t){return re(t)??t.harnessSessionId??"unknown-session"}function kf(t){return t.status!=="running"&&!!t.pendingPlanApproval&&!!$(t)}function eo(t,e,r){let n=e==="completed"?`This session is closed by default. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Cr(t)}', fork_session=true, prompt='<new task>').`:e==="legacy_non_resumable"?`Persisted historical backend state is intentionally non-resumable here. Launch fresh, or fork with agent_launch(resume_session_id='${Cr(t)}', fork_session=true, prompt='<new task>').`:e==="missing_backend_state"?`No resumable backend state is available. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Cr(t)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${Cr(t)}', message='<next instruction>') to continue the running session.`,o=r?` ${r}`:"";return{text:`Resume unavailable for session ${t.name} [${Cr(t)}] (${e}).${o} ${n}`,isError:!0}}async function vf(t,e,r){try{let n={prompt:e.prompt,sessionIdOverride:Td(e),workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,worktreeStrategy:e.worktreeStrategy,multiTurn:!0,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,permissionMode:e.currentPermissionMode,requestedPermissionMode:e.requestedPermissionMode??e.currentPermissionMode,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,harness:"harnessName"in e?e.harnessName:e.harness},o=await t.spawnAndAwaitRunning(n,{notifyLaunch:!1});return t.notifySession(o,`\u25B6\uFE0F [${o.name}] Relaunched fresh`),{text:`Session ${e.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 ${e.name} [${Cr(e)}]: ${Ld(n)}`,isError:!0}}}var ew=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
76
+
77
+ `;function Pf(t){let e=t?.replace(/\s+/g," ").trim();if(e)return Fe(e,240)}function Fd(t){if(t.approvalState==="changes_requested"&&!Bi(t))return`Plan changes were already requested for session ${t.name}. Wait for the revised plan before approving.`;if(t.approvalState==="rejected")return`Plan for session ${t.name} was already rejected.`}function Bi(t){return t.pendingPlanApproval?(t.approvalState==="changes_requested"?t.actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion)>0:!1}function tw(t){return Fd(t)?!1:Bi(t)||t.currentPermissionMode==="plan"}async function rw(t,e,r,n={}){let o=Qn(e);if(!(o.kind==="resume"||kf(e)))return;let s=!!(n.approve&&tw(e)),a=s?Pf(n.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?vf(t,e,r):eo(e,o.reason);let d={prompt:s?ew+r:r,sessionIdOverride:o.stableSessionId,workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,resumeSessionId:o.resumeSessionId,multiTurn:!0,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,permissionMode:s?"bypassPermissions":e.currentPermissionMode,requestedPermissionMode:e.requestedPermissionMode??e.currentPermissionMode,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,pendingPlanApproval:s?!1:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:s?void 0:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,...s?{approvalState:"approved",approvalExecutionState:"approved_then_implemented",approvalRationale:a,planModeApproved:!0}:{},harness:"harnessName"in e?e.harnessName:e.harness},l=await t.spawnAndAwaitRunning(d,{notifyLaunch:!1});return s?(t.notifySession(l,`\u{1F44D} [${l.name}] Plan approved (resumed)`,"plan-approved"),{text:`Plan approved for session ${l.name} [${l.id}]. Session resumed in bypassPermissions mode. Use agent_output to see the response.`}):(t.notifySession(l,`\u25B6\uFE0F [${l.name}] Auto-resumed`),{text:`Auto-resumed session ${l.name} [${l.id}]. Use agent_output to see the response.`})}catch(d){return eo(e,"missing_backend_state",`Backend resume failed: ${Ld(d)}`)}}async function bt(t,e){let r=t.resolve(e.session),n=r?void 0:t.getPersistedSession(e.session);if(!r&&!n)return{text:`Error: Session "${e.session}" not found.`,isError:!0};let o=r??n,i=o.status==="running"?{kind:"direct"}:Qn(o);if(e.approve){let a=Fd(o);if(a)return{text:a,isError:!0}}if(i.kind==="resume"||kf(o)){let a=await rw(t,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(a)return a}else{if(i.kind==="relaunch")return vf(t,o,e.message);if(i.kind==="unavailable")return eo(o,i.reason)}if(!r)return zn(n)?eo(n,"completed"):{text:`Error: Session ${n.name} [${Cr(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return zn(r)?eo(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=_.maxAutoResponds??ZP;if(e.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(e.approve){let f=Fd(r);if(f)return{text:f,isError:!0}}if(!e.approve&&r.pendingInputState?.allowsFreeText&&await r.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let v=Fe(e.message,100);t.notifySession(r,`\u21AA\uFE0F [${r.name}] "${v}"`,"agent-respond")}e.userInitiated||r.incrementAutoRespond();let f=Fe(e.message,80);return{text:[`Pending input answered for session ${r.name} [${r.id}].`,` Message: "${f}"`,"Use agent_output to see the response."].join(`
78
+ `)}}let d=!1;e.interrupt&&(d=await r.interrupt());let l=!!(e.approve&&Bi(r)),m=l?Pf(e.approvalRationale):void 0,S="";if(e.approve&&Bi(r)?(r.switchPermissionMode("bypassPermissions"),r.approvalRationale=m):e.approve&&r.currentPermissionMode==="default"?r.switchPermissionMode("bypassPermissions"):e.approve&&r.currentPermissionMode==="bypassPermissions"?S=`
79
+ \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:e.approve?S=`
80
+ \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:(r.pendingPlanApproval||r.approvalState==="changes_requested")&&(S=`
81
+ \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(e.message),l)t.notifySession(r,`\u{1F44D} [${r.name}] Plan approved`,"plan-approved");else if(e.userInitiated){let f=Fe(e.message,100);t.notifySession(r,`\u21AA\uFE0F [${r.name}] "${f}"`,"agent-respond")}e.userInitiated||r.incrementAutoRespond();let y=Fe(e.message,80);return l?{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}].`,d?" (redirected active turn first)":e.interrupt?" (no active turn to interrupt)":"",` Message: "${y}"`,S,"Use agent_output to see the response."].filter(Boolean).join(`
82
+ `)}}catch(a){return{text:`Error sending message to session ${r.name} [${r.id}]: ${Ld(a)}`,isError:!0}}}function nw(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.message=="string"&&(e.approval_rationale===void 0||typeof e.approval_rationale=="string")}function wf(t){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:p.Object({session:p.String({description:"Session name or ID to respond to"}),message:p.String({description:"The message to send to the session"}),interrupt:p.Optional(p.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:p.Optional(p.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:p.Optional(p.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."})),approval_rationale:p.Optional(p.String({description:"Optional structured rationale for a direct delegated plan approval. Use this instead of embedding the rationale in message text when approve=true for a pending plan."}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!nw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve?, approval_rationale? }."}]};let n=await bt(k,{session:r.session,message:r.message,interrupt:r.interrupt,userInitiated:r.userInitiated,approve:r.approve,approvalRationale:r.approval_rationale});return{isError:n.isError??!1,content:[{type:"text",text:n.text}]}}}}Ee();Y();function ow(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function If(t){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:p.Object({session:p.String({description:"Session name or ID awaiting plan approval"}),summary:p.String({description:"Concise user-facing summary of scope, risk, and any concerns that should accompany the approval buttons"})}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!ow(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}]}}}}Ee();Y();Re();function iw(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.report_id=="string"&&typeof e.report_text=="string"&&typeof e.plan_prompt=="string"&&typeof e.plan_workdir=="string"&&(e.plan_name==null||typeof e.plan_name=="string")&&(e.target_channel==null||typeof e.target_channel=="string")&&(e.target_thread_id==null||typeof e.target_thread_id=="string"||typeof e.target_thread_id=="number")&&(e.target_session_key==null||typeof e.target_session_key=="string")}function sw(t,e){let r=_t(t,e.target_channel,e.target_session_key);if(r)return e.target_thread_id!=null&&(r.threadId=String(e.target_thread_id)),r}function bf(t){return{name:"agent_send_monitor_report",description:"Post a monitor report to the current or explicit chat route with human-gated inline buttons. Use this for release reports that should offer a Start Plan action directly in Telegram.",parameters:p.Object({report_id:p.String({description:"Stable report identifier, for example 'openclaw-release-v2026.3.31'."}),report_text:p.String({description:"Final user-facing report text to deliver."}),plan_prompt:p.String({description:"Prompt to seed into the plan-only session when the user clicks Start Plan."}),plan_workdir:p.String({description:"Working directory for the planning session."}),plan_name:p.Optional(p.String({description:"Optional explicit session name for the planning session."})),target_channel:p.Optional(p.String({description:"Optional explicit route like 'telegram|-1003863755361'."})),target_thread_id:p.Optional(p.Union([p.String(),p.Number()],{description:"Optional explicit topic/thread id."})),target_session_key:p.Optional(p.String({description:"Optional explicit session key for wake routing."}))}),async execute(e,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 { report_id, report_text, plan_prompt, plan_workdir }."}]};let n=sw(t,r);return!n?.provider||!n.target?{content:[{type:"text",text:"Error: Could not resolve a direct delivery route for the monitor report."}]}:(k.sendMonitorReport({reportId:r.report_id,route:n,text:r.report_text,planName:r.plan_name??r.report_id,planPrompt:r.plan_prompt,planWorkdir:r.plan_workdir}),{content:[{type:"text",text:`Interactive monitor report queued for ${n.provider}|${n.target}${n.threadId?`#${n.threadId}`:""}.`}]})}}}Ee();Y();function xf(t){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:p.Object({}),async execute(e,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:Di(n,o)}]}}}}Ee();Re();Y();ut();to();import{existsSync as Wd}from"fs";function dw(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ji(t){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:p.Object({session:p.String({description:"Session name or ID to merge"}),base_branch:p.Optional(p.String({description:"Base branch to merge into (default: main)"})),strategy:p.Optional(p.Union([p.Literal("merge"),p.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:p.Optional(p.Boolean({description:"Push the base branch after successful merge (default: false)"})),delete_branch:p.Optional(p.Boolean({description:"Delete the worktree branch after successful merge (default: true)"}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!dw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=dn(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.`}]};Wd(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${a})`);let l=a;if(!Wd(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let m=r.base_branch??sr(l),S=m,y=r.strategy??"merge",f=r.push===!0,v=r.delete_branch!==!1;if(i?.worktreeLifecycle?.state==="merged"||i?.worktreeMerged)return{content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" is already merged.`}]};let A={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]},x=n.persistedRef;return await k.enqueueMerge(l,async()=>{let w=k.getPersistedSession(r.session);if(w?.worktreeLifecycle?.state==="merged"||w?.worktreeMerged){A={content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" was already merged while waiting in queue.`}]};return}let C=Tr(l,d,m),b=Ci(l,d,S,y,s);if(b.success){if(f&&!Mi(l,S)){A={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${S} locally, but failed to push ${S}`}]};return}v&&$t(l,d);let M=!1;if(Wd(s)&&(M=tt(l,s),Ti(l)),w)for(let D of Af({...n,persistedSession:w}))k.updatePersistedSession(D,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDisposition:"merged",worktreeLifecycle:{state:"merged",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"agent_merge",baseBranch:m,targetRepo:w.worktreePrTargetRepo,pushRemote:w.worktreePushRemote}});let F=Mr({kind:"merge",branch:d,base:m,filesChanged:C?.filesChanged,insertions:C?.insertions,deletions:C?.deletions});k.notifyWorktreeOutcome(n.notificationTarget,F);let O=`\u2705 ${b.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${S}.${f?" Pushed.":""}${v?M?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;b.stashPopConflict?O+=`
83
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${b.stashRef??"stash@{0}"}\` in ${l} to review stashed changes.`:b.stashed&&(O+=`
84
+ (Pre-existing changes on ${S} were auto-stashed and restored.)`),A={content:[{type:"text",text:O}]}}else if(b.rebaseConflict)A={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
85
+
86
+ ${b.error}`}]};else if(b.conflictFiles&&b.conflictFiles.length>0){let M=["Resolve merge conflicts in the following files and commit the resolution:","",...b.conflictFiles.map(F=>`- ${F}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${d}"`].join(`
87
+ `);try{let F=k.spawn({prompt:M,workdir:l,name:`${r.session}-conflict-resolver`,harness:Pe(),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});A={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${b.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${F.name}`}]}}catch(F){A={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${F instanceof Error?F.message:String(F)}`}]}}}else A={content:[{type:"text",text:b.dirtyError?`\u274C Merge blocked: ${b.error}`:`\u274C Merge failed: ${b.error??"unknown error"}`}]}}),A}}}Gi();Ee();Y();ke();ut();to();function pw(t){return!!t&&typeof t=="object"}function Tf(t){return{name:"agent_worktree_cleanup",description:"Manage worktree cleanup with lifecycle-aware safety rules. Use preview_safe to list what Clean all safe would remove, clean_safe to execute it, or preview_all to see both safe and retained sandboxes with kept reasons.",parameters:p.Object({workdir:p.Optional(p.String({description:"Restrict cleanup to sessions rooted in this repository"})),base_branch:p.Optional(p.String({description:"Override base branch for lifecycle resolution"})),mode:p.Optional(p.Union([p.Literal("preview_safe"),p.Literal("clean_safe"),p.Literal("preview_all")],{description:"Cleanup mode. preview_safe shows what Clean all safe would remove, clean_safe performs that cleanup, preview_all shows both safe and retained worktrees. Defaults to preview_safe when dry_run=true, otherwise clean_safe."})),skip_session_check:p.Optional(p.Boolean({description:"Deprecated. Safe cleanup never removes live sessions."})),force:p.Optional(p.Boolean({description:"Deprecated alias for skip_session_check."})),dry_run:p.Optional(p.Boolean({description:"Show what would be cleaned without deleting anything."})),session:p.Optional(p.String({description:"Session name or ID to clean or dismiss."})),dismiss_session:p.Optional(p.Boolean({description:"When true and session is provided, permanently dismiss the worktree."}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!pw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, mode?, dry_run?, session?, dismiss_session? }."}]};let n=r.session,o=r.mode??(r.dry_run===!0?"preview_safe":"clean_safe"),i=o!=="clean_safe",s=o==="preview_all"||o==="clean_safe";if(n&&r.dismiss_session===!0)return{content:[{type:"text",text:await k.dismissWorktree(n)}]};let a=Ki(k);if(n&&(a=a.filter(f=>Vi(f,n)),a.length===0)){let f=dn(k,n);if(!f.persistedSession&&!f.activeSession)return{content:[{type:"text",text:`Error: Session "${n}" not found.`}]}}if(r.workdir&&(a=a.filter(f=>f.workdir===r.workdir)),a.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let d=[],l=[],m=[],S=[];for(let f of a){let{persistedSession:v,activeSession:A,resolvedLifecycle:x}=Ui(k,f,{baseBranch:r.base_branch});if(!x.cleanupSafe){if(s){let w=x.reasons.length>0?x.reasons.map(qi).join(", "):_r(x.derivedState);l.push(`${f.name} [kept: ${w}]`)}continue}if(d.push(`${f.name} (${_r(x.derivedState)})`),!i)try{let w=f.workdir;if(!((v??A)&&Ne(v??A))&&f.worktreePath&&tt(w,f.worktreePath,{destructive:!1}),f.worktreeBranch&&$t(w,f.worktreeBranch),v){let b=x.derivedState==="merged"||x.derivedState==="released"?x.derivedState:x.lifecycle.state;k.updatePersistedSession(f.id,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeMerged:b==="merged"?!0:v.worktreeMerged,worktreeMergedAt:b==="merged"?v.worktreeMergedAt??new Date().toISOString():v.worktreeMergedAt,worktreeLifecycle:{...v.worktreeLifecycle??x.lifecycle,state:b,updatedAt:new Date().toISOString(),resolvedAt:v.worktreeLifecycle?.resolvedAt??new Date().toISOString(),resolutionSource:v.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:r.base_branch??x.lifecycle.baseBranch??v.worktreeBaseBranch,targetRepo:v.worktreePrTargetRepo,pushRemote:v.worktreePushRemote,notes:x.reasons}})}m.push(`${f.name} (${_r(x.derivedState)})`)}catch(w){S.push(`${f.name}: ${w instanceof Error?w.message:String(w)}`)}}let y=[o==="clean_safe"?"Clean all safe:":o==="preview_all"?"Worktree lifecycle review:":"Clean all safe preview:"];return y.push(` SAFE ${i?"NOW":"FOUND"} (${d.length}): ${d.join(", ")||"(none)"}`),s&&y.push(` KEPT (${l.length}): ${l.join(", ")||"(none)"}`),i||(y.push(` CLEANED (${m.length}): ${m.join(", ")||"(none)"}`),y.push(` FAILURES (${S.length}): ${S.join(", ")||"(none)"}`)),{content:[{type:"text",text:y.join(`
88
+ `)}]}}}}Ee();Y();to();function cw(t){return!0}function Mf(t){return{name:"agent_worktree_status",description:"Show lifecycle-first worktree status for coding agent sessions. Displays product-facing lifecycle state, released handling, cleanup safety, and retained reasons.",parameters:p.Object({session:p.Optional(p.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!cw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let n=r.session,o=Ki(k);if(n&&(o=o.filter(s=>Vi(s,n)),o.length===0))return{content:[{type:"text",text:`Error: Session "${n}" not found or has no worktree.`}]};if(o.length===0)return{content:[{type:"text",text:"No sessions with worktrees found."}]};let i=[];for(let s of o){let{persistedSession:a,resolvedLifecycle:d}=Ui(k,s),l=d.cleanupSafe?"safe now":d.preserve?"preserve":"blocked";i.push(`Session: ${s.name} [${s.id}]`),i.push(` Branch: ${s.worktreeBranch??"(unknown)"} \u2192 ${d.lifecycle.baseBranch??a?.worktreeBaseBranch??"main"}`),i.push(` Repo: ${s.workdir}`),i.push(` Lifecycle:${_r(d.lifecycle.state)}`),d.derivedState!==d.lifecycle.state&&i.push(` Derived: ${_r(d.derivedState)}`),i.push(` Cleanup: ${l}`),d.evidence.prUrl&&i.push(` PR: ${d.evidence.prUrl} (${d.evidence.prState??"unknown"})`),(d.evidence.branchAheadCount!=null||d.evidence.baseAheadCount!=null)&&i.push(` Ahead: ${d.evidence.branchAheadCount??0} ahead / ${d.evidence.baseAheadCount??0} behind`),i.push(` Reasons: ${d.reasons.length>0?d.reasons.map(qi).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
89
+ `).trim()}]}}}}Ee();Y();Re();import{existsSync as mw}from"fs";function Hi(t,e){if(!e||e.length===0)return!0;if(!t)return!1;let r=t.toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function fw(t){return!t||typeof t!="object"?!1:typeof t.goal=="string"}function Cf(t){return{name:"goal_launch",description:"Launch an explicit goal loop. Use this only when the user specifically asks for a goal task, Ralph-style autonomous loop, iterative loop, autonomous repair loop, or keep-going-until-checks-pass workflow. This is not the default session path.",parameters:p.Object({goal:p.String({description:"End goal for the autonomous task"}),verifier_commands:p.Optional(p.Array(p.String({description:"Shell command that must pass for the goal to be considered complete"}),{minItems:1,description:"Verifier commands run after each coding turn"})),name:p.Optional(p.String({description:"Short task name (kebab-case preferred)"})),workdir:p.Optional(p.String({description:"Working directory (defaults to cwd / configured workspace)"})),model:p.Optional(p.String({description:"Model name to use"})),system_prompt:p.Optional(p.String({description:"Additional system prompt"})),allowed_tools:p.Optional(p.Array(p.String(),{description:"Allowed tools for the underlying agent session"})),max_iterations:p.Optional(p.Number({description:"Maximum verifier-driven repair iterations",minimum:1})),goal_mode:p.Optional(p.Union([p.Literal("ralph"),p.Literal("verifier")],{description:"Loop strategy. 'ralph' repeats until a completion promise appears. 'verifier' repeats until verifier commands pass. Defaults to 'ralph' when no verifiers are provided, otherwise 'verifier'."})),completion_promise:p.Optional(p.String({description:"Exact completion promise for Ralph-mode loops. Defaults to 'DONE'."})),permission_mode:p.Optional(p.Union([p.Literal("default"),p.Literal("plan"),p.Literal("bypassPermissions")],{description:"Permission mode for the underlying agent session. Defaults to bypassPermissions for autonomous goal loops."})),harness:p.Optional(p.String({description:"Agent harness to use (e.g. 'codex' or 'claude-code')."}))}),async execute(e,r){if(!fe)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!fw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let n=r.workdir||t.workspaceDir||_.defaultWorkdir||process.cwd();if(!mw(n))return{content:[{type:"text",text:`Error: Working directory does not exist: ${n}`}]};let o=(r.verifier_commands??[]).map((f,v)=>({label:`check-${v+1}`,command:f.trim()})).filter(f=>f.command.length>0),i=r.goal_mode??(o.length>0?"verifier":"ralph");if(i==="verifier"&&o.length===0)return{content:[{type:"text",text:"Error: verifier_commands must contain at least one non-empty command for verifier goal mode."}]};let s=r.harness??Pe(),a=r.model??Ct(s);if(!a)return{content:[{type:"text",text:`Error: No default model configured for harness "${s}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${s}.defaultModel or pass model explicitly.`}]};let d=en(s);if(!Hi(a,d))return{content:[{type:"text",text:`Error: Model "${a}" is not allowed. Permitted models: ${d?.join(", ")}`}]};let l=t.sessionKey||void 0,m=ni(t),S=qt(t,m),y=_t(t,S,l);try{let f=await fe.launchTask({goal:r.goal,name:r.name,workdir:n,model:a,reasoningEffort:lt(s),systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,maxIterations:r.max_iterations,permissionMode:r.permission_mode??"bypassPermissions",loopMode:i,completionPromise:r.completion_promise,originChannel:S,originThreadId:y?.threadId,originAgentId:t.agentId||void 0,originSessionKey:l,route:y,harness:s,verifierCommands:o});return{content:[{type:"text",text:["Goal task launched successfully.",` Name: ${f.name}`,` ID: ${f.id}`,` Dir: ${f.workdir}`,` Session: ${f.sessionName} [${f.sessionId}]`,` Harness: ${s}`,` Model: ${a}`,` Loop mode: ${f.loopMode}`,` Max iterations: ${f.maxIterations}`,` Goal: "${r.goal.length>100?`${r.goal.slice(0,100)}...`:r.goal}"`,...f.loopMode==="ralph"?[` Completion promise: ${f.completionPromise}`]:[" Verifiers:",...o.map(A=>` - ${A.command}`)],"","Use goal_status to follow progress or goal_stop to terminate the task."].join(`
90
+ `)}]}}catch(f){return{content:[{type:"text",text:`Error launching goal task: ${f instanceof Error?f.message:String(f)}`}]}}}}}Ee();function _f(t,e){return t.split(`
91
+ `).map(r=>`${e}${r}`)}function gw(t,e=8,r=600){let n=t.map(i=>i.trimEnd()).filter(i=>i.trim().length>0);if(n.length===0)return;let o=n.slice(-e).join(`
92
+ `);return o.length<=r?o:`...${o.slice(-(r-3))}`}function ar(t){if(t)return{phase:t.phase,awaitingInput:t.isAwaitingInput??!!t.pendingInputState,latestOutput:gw(t.getOutput(20))}}function dr(t,e){let r=t.loopMode??"verifier",n=[`${t.name} [${t.id}]`,` Status: ${t.status}`,...r==="ralph"?[" Loop mode: ralph",` Iteration: ${t.iteration}/${t.maxIterations}`]:[` Repair iteration: ${t.iteration}/${t.maxIterations}`],` Workdir: ${t.workdir}`];return r==="ralph"&&t.completionPromise&&n.push(` Completion promise: ${t.completionPromise}`),t.sessionId&&n.push(` Session: ${t.sessionName??"(unknown)"} [${t.sessionId}]`),e?.phase&&n.push(` Phase: ${e.phase}`),e?.awaitingInput!==void 0&&n.push(` Awaiting input: ${e.awaitingInput?"yes":"no"}`),t.lastVerifierSummary&&(n.push(" Last verifier:"),n.push(..._f(t.lastVerifierSummary," "))),e?.latestOutput&&(n.push(" Latest activity:"),n.push(..._f(e.latestOutput," "))),t.waitingForUserReason&&n.push(` Waiting on user: ${t.waitingForUserReason}`),t.failureReason&&n.push(` Failure: ${t.failureReason}`),n.join(`
93
+ `)}Y();function $f(t){return{name:"goal_status",description:"Show status for explicit goal tasks managed by the goal controller. Use this to inspect one goal task or list all goal tasks.",parameters:p.Object({task:p.Optional(p.String({description:"Task name or ID. Omit to list all tasks."}))}),async execute(e,r){if(!fe)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};let n=r&&typeof r=="object"&&typeof r.task=="string"?r.task:void 0;if(n){let i=fe.getTask(n);if(!i)return{content:[{type:"text",text:`Error: Goal task "${n}" not found.`}]};let s=i.sessionId?k?.resolve(i.sessionId):void 0;return{content:[{type:"text",text:dr(i,ar(s))}]}}let o=fe.listTasks();return o.length===0?{content:[{type:"text",text:"No goal tasks found."}]}:{content:[{type:"text",text:o.map(i=>{let s=i.sessionId?k?.resolve(i.sessionId):void 0;return dr(i,ar(s))}).join(`
94
+
95
+ `)}]}}}}Ee();Y();function hw(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function Ef(t){return{name:"goal_stop",description:"Stop an explicit goal task and kill its underlying agent session.",parameters:p.Object({task:p.String({description:"Goal task name or ID"})}),async execute(e,r){if(!fe)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!hw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let n=fe.stopTask(r.task);return n?{content:[{type:"text",text:n.action==="already_terminal"?`Task is already ${n.task.status}.`:`Task "${n.task.name}" (${n.task.id}) stopped.`}]}:{content:[{type:"text",text:`Error: Goal task "${r.task}" not found.`}]}}}}Y();Gi();var lr="code-agent";function Sw(t){let e=t.trim().replace(new RegExp(`^${lr}:`),"");return e||null}async function zi(t,e){try{await pt(t,{text:e})}catch(r){let n=r instanceof Error?r.message:String(r);console.warn(`[callback-handler] Failed to resolve worktree prompt: ${n}`)}}function Bd(t){if(t&&typeof t=="object"&&"content"in t&&Array.isArray(t.content)){let e=t.content[0];return typeof e?.text=="string"?e.text:"(done)"}return"(done)"}function yw(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function kw(t,e){if(yw(t.kind)){if(!e)return"This plan decision is stale because the session is no longer available.";if(t.planDecisionVersion!=null&&(e.actionablePlanDecisionVersion??e.planDecisionVersion)!=null&&t.planDecisionVersion!==(e.actionablePlanDecisionVersion??e.planDecisionVersion))return"This plan decision is stale because a newer plan review state already exists.";if(!e.pendingPlanApproval)return"This plan is no longer awaiting approval.";if(t.kind==="plan-approve"&&e.approvalState==="changes_requested"&&!e.pendingPlanApproval)return"Changes were already requested for this plan. Wait for the revised plan before approving.";if(t.kind==="plan-request-changes"&&e.approvalState==="changes_requested")return"Changes were already requested for this plan. Send your feedback to the agent instead."}}function vw(t){let e="callback"in t?t.callback?.payload:void 0,r="interaction"in t?t.interaction?.payload:void 0;return e??r??""}function Ud(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function Pw(t){let e=t instanceof Error?t.message:String(t);return/empty message/i.test(e)}async function pt(t,e={}){let r=t.respond,{text:n}=e;if(t.channel==="telegram"){if(typeof n=="string"&&typeof r.editMessage=="function")try{await r.editMessage({text:n,buttons:[]});return}catch(o){if(Ud(o))return;let i=o instanceof Error?o.message:String(o);console.warn(`[callback-handler] Failed to edit Telegram worktree prompt before clearing buttons: ${i}`)}typeof r.clearButtons=="function"&&await r.clearButtons();return}if(typeof r.clearComponents=="function")try{await r.clearComponents(typeof n=="string"?{text:n}:void 0);return}catch(o){if(Ud(o))return;if(Pw(o)){if(typeof n!="string"&&typeof r.acknowledge=="function"){await r.acknowledge();return}typeof n!="string"&&typeof r.acknowledge!="function"&&console.warn("[callback-handler] clearComponents failed with empty-message error and no acknowledge fallback available")}else{if(typeof n!="string")throw o;{let i=o instanceof Error?o.message:String(o);console.warn(`[callback-handler] clearComponents failed before text fallback: ${i}`)}}}if(typeof n=="string"&&typeof r.editMessage=="function")try{await r.editMessage({text:n})}catch(o){if(!Ud(o)){let i=o instanceof Error?o.message:String(o);console.warn(`[callback-handler] Failed to edit worktree prompt before clearing interactive state: ${i}`)}}typeof r.clearButtons=="function"&&await r.clearButtons()}async function oe(t,e){if(t.channel==="telegram"){await t.respond.reply({text:e});return}await t.respond.reply({text:e,ephemeral:!0})}function Kd(t="telegram"){return{channel:t,namespace:lr,handler:async e=>{if(!e.auth.isAuthorizedSender)return await oe(e,"\u26D4 Unauthorized."),{handled:!0};let r=vw(e),n=Sw(r);if(!n)return await oe(e,`\u26A0\uFE0F Unrecognized callback payload: "${r}".`),{handled:!0};if(!k)return await oe(e,"\u26A0\uFE0F Code agent service not running."),{handled:!0};let o=k.getActionToken(n);if(!o)return await oe(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};let i=o.sessionId,s=k.resolve?.(i)??k.getPersistedSession?.(i),a=s?.name??i,d=kw(o,s);if(d)return await pt(e),await oe(e,`\u26A0\uFE0F ${d}`),{handled:!0};let l=k.consumeActionToken(n);if(!l)return await oe(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};switch(l.kind){case"worktree-merge":{await zi(e,`\u2705 Merge selected for [${a}]`);let m=await ji().execute("callback",{session:i});await oe(e,Bd(m));break}case"worktree-decide-later":{await zi(e,`\u23ED\uFE0F Deferred for [${a}]`);let m=k.snoozeWorktreeDecision(i);await oe(e,m.startsWith("Error")?m:"\u23ED\uFE0F Snoozed 24h");break}case"worktree-dismiss":{await zi(e,`\u{1F5D1}\uFE0F Discarded for [${a}]`);let m=await k.dismissWorktree(i);await oe(e,(m.startsWith("Error"),m));break}case"worktree-create-pr":case"worktree-update-pr":{await zi(e,o.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${a}]`:`\u{1F4EC} PR selected for [${a}]`);let m=await ro().execute("callback",{session:i});await oe(e,Bd(m));break}case"worktree-view-pr":{await pt(e);let m=k.getPersistedSession?.(i),S=o.targetUrl??m?.worktreePrUrl;await oe(e,S?`PR: ${S}`:"\u26A0\uFE0F PR URL is no longer available.");break}case"plan-approve":{await pt(e),k.clearPlanDecisionTokens(i);let m=await bt(k,{session:i,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});m.isError&&await oe(e,`\u26A0\uFE0F ${m.text}`);break}case"plan-reject":{await pt(e),k.clearPlanDecisionTokens(i);let m=k.resolve(i);if(m)m.approvalState="rejected",k.kill(m.id,"user"),await oe(e,`\u274C Plan rejected for [${m.name}]. Session stopped.`);else{let S=k.getPersistedSession?.(i);S?(k.updatePersistedSession?.(i,{approvalState:"rejected",lifecycle:"terminal",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:(S.planDecisionVersion??0)+1}),await oe(e,`\u274C Plan rejected for [${S.name??a}]. Session remains stopped.`)):await oe(e,"\u274C Plan rejected.")}break}case"plan-request-changes":{await pt(e);let m=k.resolve?.(i),S=k.getPersistedSession?.(i),y=m?.name??S?.name??i,f=(m?.planDecisionVersion??S?.planDecisionVersion??0)+1;k.clearPlanDecisionTokens(i),k.updatePersistedSession(i,{approvalState:"changes_requested",lifecycle:"awaiting_user_input",pendingPlanApproval:!1,planDecisionVersion:f,actionablePlanDecisionVersion:void 0,canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:void 0,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",approvalPromptTransport:"none",approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:void 0}),await oe(e,`\u270F\uFE0F Type your revision feedback for [${y}] and I'll forward it to the agent.`);break}case"monitor-start-plan":{if(await pt(e),!l.launchPrompt||!l.launchWorkdir){await oe(e,"\u26A0\uFE0F This release action is missing the plan launch context.");break}let m=k.launchMonitorPlan({route:l.route,prompt:l.launchPrompt,workdir:l.launchWorkdir,name:l.launchName});await oe(e,`\u25B6\uFE0F Planning session started: ${m.name} [${m.id}]`);break}case"monitor-dismiss":{await pt(e),await oe(e,"\u2705 Dismissed.");break}case"session-restart":case"session-resume":{await pt(e);let m=await bt(k,{session:i,message:"Continue where you left off.",userInitiated:!0});await oe(e,m.isError?`\u26A0\uFE0F ${m.text}`:`\u25B6\uFE0F ${m.text}`);break}case"view-output":{await pt(e);let m=await Wi().execute("callback",{session:i,lines:50});await oe(e,Bd(m));break}case"question-answer":{if(await pt(e),o.optionIndex==null){await oe(e,"\u26A0\uFE0F Invalid question-answer action.");break}await k.resolvePendingInputOption(i,o.optionIndex),await oe(e,"\u2705 Answer submitted.");break}default:{await pt(e),await oe(e,"\u26A0\uFE0F Unknown callback action.");break}}return{handled:!0}}}}Y();Re();function ww(t){return t instanceof Error?t.message:String(t)}function Of(t){t.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.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=Pe(),a=Ct(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:_.defaultWorkdir||process.cwd(),model:a,reasoningEffort:lt(s),codexApprovalPolicy:s==="codex"?"never":void 0,originChannel:qt(e),originThreadId:Un(e),route:_t(e),harness:s}),l=i.length>80?i.slice(0,80)+"...":i;return{text:["Session launched.",` Name: ${d.name}`,` ID: ${d.id}`,` Prompt: "${l}"`,` Status: ${d.status}`].join(`
96
+ `)}}catch(s){let a=ww(s),d=a.includes("Max sessions")?"":`
97
+
98
+ Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${d}`}}}})}Y();function Df(t){t.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").split(/\s+/).includes("--full");return{text:Fi(k,"all",void 0,{full:r})}}})}Y();function Nf(t){t.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=e.args?.trim();return r?{text:Li(k,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}Y();function Ff(t){t.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 e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:`Usage: /agent_respond <id-or-name> <message>
99
+ /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 bt(k,{session:s,message:a,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}Y();function Lf(t){t.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 e=k.getMetrics(),r=k.list("running").length;return{text:Di(e,r)}}})}Y();var Iw=50;function Wf(t){t.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:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let n=r.split(/\s+/),o="",i=!1,s=Iw;for(let d=0;d<n.length;d++)if(n[d]==="--full")i=!0;else if(n[d]==="--lines"&&d+1<n.length){let l=parseInt(n[d+1],10);!isNaN(l)&&l>0&&(s=l),d++}else o||(o=n[d]);return o?{text:Ni(k,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}Y();Re();import{existsSync as bw}from"fs";function xw(t){let e=t.match(/"[^"]*"|'[^']*'|\S+/g);return e?e.map(r=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r):[]}function Bf(t){t.registerCommand({name:"goal",description:"Launch an explicit goal task (Ralph-style completion loop or verifier-driven loop)",acceptsArgs:!0,requireAuth:!0,handler:async e=>{if(!fe)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>"};let n=xw(r),o,i=_.defaultWorkdir||process.cwd(),s,a,d="bypassPermissions",l,m,S,y=[],f=[];for(let b=0;b<n.length;b++){let M=n[b];if(M==="--name"&&b+1<n.length)o=n[++b];else if(M==="--workdir"&&b+1<n.length)i=n[++b];else if(M==="--model"&&b+1<n.length)s=n[++b];else if(M==="--max-iterations"&&b+1<n.length){let F=parseInt(n[++b],10);!Number.isNaN(F)&&F>0&&(a=F)}else if(M==="--permission-mode"&&b+1<n.length){let F=n[++b];if(F==="default"||F==="plan"||F==="bypassPermissions")d=F;else return{text:`Error: Invalid permission mode "${F}".`}}else if(M==="--harness"&&b+1<n.length)l=n[++b];else if(M==="--mode"&&b+1<n.length){let F=n[++b];if(F==="ralph"||F==="verifier")m=F;else return{text:`Error: Invalid goal mode "${F}". Use ralph or verifier.`}}else if(M==="--completion-promise"&&b+1<n.length)S=n[++b];else if(M==="--verify"&&b+1<n.length){let F=n[++b].trim();if(!F)return{text:"Error: --verify commands must not be empty."};y.push(F)}else f.push(M)}let v=f.join(" ").trim();if(!v)return{text:"Usage: /goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>"};if(!bw(i))return{text:`Error: Working directory does not exist: ${i}`};let A=m??(y.length>0?"verifier":"ralph");if(A==="verifier"&&y.length===0)return{text:"Error: verifier mode requires at least one --verify command."};let x=l??Pe(),w=s??Ct(x);if(!w)return{text:`Error: No default model configured for harness "${x}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${x}.defaultModel or pass model explicitly.`};let C=en(x);if(!Hi(w,C))return{text:`Error: Model "${w}" is not allowed. Permitted models: ${C?.join(", ")}`};try{let b=_t(e),M=await fe.launchTask({goal:v,name:o,workdir:i,model:w,reasoningEffort:lt(x),maxIterations:a,permissionMode:d,harness:x,loopMode:A,completionPromise:S,originChannel:qt(e),originThreadId:b?.threadId,originSessionKey:e.sessionKey,route:b,verifierCommands:y.map((F,Le)=>({label:`check-${Le+1}`,command:F}))});return{text:["Goal task launched.",` Name: ${M.name}`,` ID: ${M.id}`,` Session: ${M.sessionName} [${M.sessionId}]`,` Harness: ${x}`,` Loop mode: ${M.loopMode}`,...M.loopMode==="ralph"?[` Completion promise: ${M.completionPromise}`]:[],` Max iterations: ${M.maxIterations}`,` Goal: "${v.length>100?`${v.slice(0,100)}...`:v}"`].join(`
100
+ `)}}catch(b){return{text:`Error launching goal task: ${b.message}`}}}})}Y();function Uf(t){t.registerCommand({name:"goal_status",description:"Show one goal task or list all explicit goal tasks. Usage: /goal_status [<task-id-or-name>]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!fe)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(r){let o=fe.getTask(r);if(!o)return{text:`Error: Goal task "${r}" not found.`};let i=o.sessionId?k?.resolve(o.sessionId):void 0;return{text:dr(o,ar(i))}}let n=fe.listTasks();return n.length===0?{text:"No goal tasks found."}:{text:n.map(o=>{let i=o.sessionId?k?.resolve(o.sessionId):void 0;return dr(o,ar(i))}).join(`
101
+
102
+ `)}}})}Y();function Kf(t){t.registerCommand({name:"goal_stop",description:"Stop a goal task. Usage: /goal_stop <task-id-or-name>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!fe)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /goal_stop <task-id-or-name>"};let n=fe.stopTask(r);return n?n.action==="already_terminal"?{text:`Task is already ${n.task.status}.`}:{text:`Task "${n.task.name}" (${n.task.id}) stopped.`}:{text:`Error: Goal task "${r}" not found.`}}})}import{execFile as Lw}from"child_process";import{createHash as Yf}from"crypto";import{existsSync as Aw,mkdirSync as Rw,readFileSync as Tw,renameSync as Mw,writeFileSync as Cw}from"fs";import{homedir as _w}from"os";import{dirname as $w,join as Vf}from"path";function Ew(t){let e=t.OPENCLAW_HOME?.trim();return e||Vf(_w(),".openclaw")}function Ow(t){let e=t.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||Vf(Ew(t),"code-agent-goal-tasks.json")}function Dw(t){return t instanceof Error?t.message:String(t)}function Nw(t){if(!t||typeof t!="object")return;let e=t;if(!(typeof e.provider!="string"||typeof e.target!="string"))return{provider:e.provider,target:e.target,accountId:typeof e.accountId=="string"?e.accountId:void 0,threadId:typeof e.threadId=="string"?e.threadId:void 0,sessionKey:typeof e.sessionKey=="string"?e.sessionKey:void 0}}function Fw(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.id!="string"||typeof e.name!="string"||typeof e.goal!="string"||typeof e.workdir!="string"||typeof e.status!="string")return;let r=e.status,n=r==="running"||r==="waiting_for_session"?"waiting_for_session":r;return{id:e.id,name:e.name,goal:e.goal,workdir:e.workdir,status:n,createdAt:typeof e.createdAt=="number"?e.createdAt:Date.now(),updatedAt:typeof e.updatedAt=="number"?e.updatedAt:Date.now(),iteration:typeof e.iteration=="number"?e.iteration:0,maxIterations:typeof e.maxIterations=="number"?e.maxIterations:8,sessionId:typeof e.sessionId=="string"?e.sessionId:void 0,sessionName:typeof e.sessionName=="string"?e.sessionName:void 0,harnessSessionId:typeof e.harnessSessionId=="string"?e.harnessSessionId:void 0,model:typeof e.model=="string"?e.model:void 0,reasoningEffort:typeof e.reasoningEffort=="string"?e.reasoningEffort:void 0,systemPrompt:typeof e.systemPrompt=="string"?e.systemPrompt:void 0,allowedTools:Array.isArray(e.allowedTools)?e.allowedTools.filter(o=>typeof o=="string"):void 0,originChannel:typeof e.originChannel=="string"?e.originChannel:void 0,originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originAgentId:typeof e.originAgentId=="string"?e.originAgentId:void 0,originSessionKey:typeof e.originSessionKey=="string"?e.originSessionKey:void 0,route:Nw(e.route),harness:typeof e.harness=="string"?e.harness:void 0,permissionMode:typeof e.permissionMode=="string"?e.permissionMode:void 0,loopMode:e.loopMode==="ralph"?"ralph":"verifier",completionPromise:typeof e.completionPromise=="string"?e.completionPromise:void 0,verifierCommands:Array.isArray(e.verifierCommands)?e.verifierCommands.filter(o=>!!o&&typeof o=="object"&&typeof o.label=="string"&&typeof o.command=="string"):[],lastVerifierSummary:typeof e.lastVerifierSummary=="string"?e.lastVerifierSummary:void 0,lastVerifierFingerprint:typeof e.lastVerifierFingerprint=="string"?e.lastVerifierFingerprint:void 0,repeatedFailureCount:typeof e.repeatedFailureCount=="number"?e.repeatedFailureCount:0,waitingForUserReason:typeof e.waitingForUserReason=="string"?e.waitingForUserReason:void 0,failureReason:typeof e.failureReason=="string"?e.failureReason:void 0}}var Qi=class{path;tasks=new Map;constructor(e=process.env){this.path=Ow(e),this.load()}load(){try{if(!Aw(this.path))return;let e=Tw(this.path,"utf8"),r=JSON.parse(e);if(!Array.isArray(r))return;for(let n of r){let o=Fw(n);o&&this.tasks.set(o.id,o)}this.save()}catch{}}save(){try{Rw($w(this.path),{recursive:!0});let e=`${this.path}.tmp`;Cw(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),Mw(e,this.path)}catch(e){console.warn(`[GoalTaskStore] Failed to save ${this.path}: ${Dw(e)}`)}}upsert(e){this.tasks.set(e.id,e),this.save()}get(e){let r=this.tasks.get(e);return r||[...this.tasks.values()].find(n=>n.name===e)}list(){return[...this.tasks.values()].sort((e,r)=>r.createdAt-e.createdAt)}};Zr();var Ww=8,Xf=600*1e3,Bw=4e3,Vd=1200,Uw="DONE";function Kw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function no(t,e){return t.length<=e?t:`${t.slice(0,e-3)}...`}function ur(t,e=20){let r=t.split(/\r?\n/).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);return r.length<=e?r.join(`
103
+ `):r.slice(-e).join(`
104
+ `)}function qf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jf(t){let e=t?.trim();return e&&e.length>0?e:Uw}function Vw(t){return t.route??Wn(t.originChannel,t.originThreadId,t.originSessionKey)}function qd(t){return t.map((e,r)=>({label:e.label.trim()||`check-${r+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??Xf})).filter(e=>e.command.length>0)}function qw(t){return t.loopMode==="verifier"}function jw(t){return qd(t.verifierCommands).length>0}function Gf(t){return qw(t)&&!jw(t)}function Ji(){return"Verifier-mode goal tasks require at least one verifier command."}function Hf(t){let e=t.steps.filter(r=>!r.ok).map(r=>`${r.label}:${r.exitCode}:${ur(r.output,12)}`).join(`
105
+ `);return Yf("sha1").update(e).digest("hex")}function Gw(t){return Yf("sha1").update(ur(t,24)).digest("hex")}function zf(t){let e=t.toLowerCase().replace(/\s+/g," ").trim();if(!e)return;if(/\b(can i|may i|should i|do you want me to|would you like me to)\b/.test(e)&&/\b(read|write|edit|modify|change|inspect|search|run|execute|install|delete|move|rename|open)\b/.test(e))return"Yes, proceed.";if(/\b(should i continue|shall i continue|want me to continue|should i proceed|shall i proceed|can i proceed|go ahead)\b/.test(e))return"Yes, continue."}function Hw(t){if(t.loopMode==="ralph")return["You are working inside a Ralph Wiggum-style autonomous loop.","","Goal:",t.goal,"","Loop rules:","- Keep making concrete progress toward the goal in this repository.","- An external controller will continue looping until you emit the completion promise or the iteration budget is exhausted.",`- When the goal is truly complete, output this exact marker on its own line: <promise>${t.completionPromise}</promise>`,"- Do not output that completion marker early, approximately, or with altered spelling.","- If you are not done yet, do not emit the completion marker.","- Do not ask to stop or wait for confirmation unless blocked by a real product, architecture, credential, or approval decision.","- Re-run useful local checks before ending each turn.",t.verifierCommands.length>0?"- External verifier commands will also be run after you claim completion.":"- There may not be external verifiers, so your completion promise is the success gate."].join(`
106
+ `);let e=t.verifierCommands.map(r=>`- ${r.label}: ${r.command}`).join(`
107
+ `);return["You are working on an autonomous goal-driven task.","","Goal:",t.goal,"","Working rules:","- Make concrete progress toward the goal in this repository.","- An external controller will run these verifier commands after your turn:",e,"- If any verifier fails, you will receive the exact failures and must continue fixing the remaining gaps.","- Do not stop early just because you think the task is probably done.","- Do not ask for confirmation unless you are blocked by a real product, architecture, or credential decision.","- Before ending a turn, run any local checks you think are useful."].join(`
108
+ `)}function Qf(t){return t.loopMode==="ralph"?["The OpenClaw gateway restarted while this Ralph-style goal task was running.","Resume from the prior session context and continue immediately.","","Goal:",t.goal,"","Instructions:","- Continue from the current repo state and prior session context without restarting from scratch.",`- Only emit <promise>${t.completionPromise}</promise> when the goal is actually complete.`,"- The external controller will keep looping until that marker appears or the iteration budget is exhausted.","- Do not ask for confirmation just because the gateway restarted."].join(`
109
+ `):["The OpenClaw gateway restarted while this autonomous goal task was running.","Resume from the prior session context and continue toward the same goal immediately.","","Goal:",t.goal,"","Instructions:","- Re-orient yourself from the existing repo state and prior session context.","- Continue the task without restarting from scratch unless the prior approach is clearly invalid.","- The external controller will continue running verifier commands after your turns.","- Do not ask for confirmation just because the gateway restarted."].join(`
110
+ `)}function zw(t,e){let r=e.steps.filter(o=>!o.ok).map(o=>[`- ${o.label} failed (exit ${o.exitCode})`,ur(o.output,18)].join(`
111
+ `)).join(`
112
+
113
+ `);return["The external verifier did not pass.",t.repeatedFailureCount>=2?"The same verifier fingerprint has repeated. Use a different debugging strategy than your previous attempt.":"Fix only the remaining issues from the verifier output below.","","Goal:",t.goal,"","Verifier failures:",r,"","Instructions:","- Continue from the current code state and prior session context.","- Make the minimum necessary changes to satisfy the remaining verifier failures.","- Re-run relevant checks yourself before ending the turn.","- Do not ask for confirmation unless you are truly blocked on a human decision."].join(`
114
+ `)}function Qw(t,e){let r=ur(e,18)||"(no meaningful output)",n=t.repeatedFailureCount>=2?"The loop has repeated without converging. Use a different strategy than the previous attempt.":"Continue from the current repo state and prior session context.";return["Continue the same Ralph-style goal task.","","Goal:",t.goal,"","Status:",`- The last turn ended without the completion promise <promise>${t.completionPromise}</promise>.`,`- Current iteration: ${t.iteration}/${t.maxIterations}.`,`- ${n}`,"","Latest output / blockers:",r,"","Instructions:","- Keep working until the goal is actually complete.",`- Only emit <promise>${t.completionPromise}</promise> when all requested work is done.`,"- If you are not done, do not emit the completion promise.",t.verifierCommands.length>0?"- If you believe you are done, make sure the expected verifiers are likely to pass before emitting the completion promise.":"- There may not be external verifiers, so your completion promise is the success signal."].join(`
115
+ `)}function Jw(t,e){let r=e.steps.filter(n=>!n.ok).map(n=>[`- ${n.label} failed (exit ${n.exitCode})`,ur(n.output,18)].join(`
116
+ `)).join(`
117
+
118
+ `);return["You emitted the completion promise, but the external verifiers did not pass.","","Goal:",t.goal,"","Verifier failures:",r,"","Instructions:","- Continue from the current repo state and fix only the remaining gaps.",`- Do not emit <promise>${t.completionPromise}</promise> again until the goal is fully complete and the failing checks are addressed.`,"- Re-run relevant checks yourself before ending the turn."].join(`
119
+ `)}function Yw(t,e){let r=e.trim();if(!r)return!1;let n=new RegExp(`(^|\\n)\\s*${qf(r)}\\s*(\\n|$)`,"i"),o=new RegExp(`<promise>\\s*${qf(r)}\\s*<\\/promise>`,"i");return n.test(t)||o.test(t)}function Jf(t){return t.steps.map(e=>`${e.ok?"PASS":"FAIL"} ${e.label} (exit ${e.exitCode}, ${Math.round(e.durationMs)}ms)`).join(`
120
+ `)}function $r(t){return t instanceof Error?t.message:String(t)}function Xw(t){return t==="succeeded"||t==="failed"||t==="stopped"}function Zw(t){return no(t.error?.trim()||"Underlying session failed.",Vd)}function eI(t,e){return new Promise(r=>{let n=Date.now();Lw("bash",["-lc",e.command],{cwd:t,timeout:e.timeoutMs??Xf,maxBuffer:1024*1024},(o,i,s)=>{let a=Date.now()-n,d=typeof o?.code=="number"?o.code:o?1:0,l=`${i??""}${s?`
121
+ ${s}`:""}`.trim();r({label:e.label,command:e.command,ok:!o,exitCode:d,durationMs:a,output:no(l||"(no output)",Bw)})})})}var Yi=class{store;sessionManager;restorePromise=null;inFlight=new Set;observerDisposers=new Map;scheduledEvaluations=new Map;dirtyEvaluations=new Set;dirtyEvaluationSessionIds=new Map;started=!1;constructor(e){this.sessionManager=e,this.store=new Qi}start(){this.started||(this.started=!0,!this.restorePromise&&(this.restorePromise=this.restoreRecoverableTasks().catch(e=>{console.warn(`[GoalController] Failed to restore recoverable tasks: ${$r(e)}`)}).finally(()=>{this.restorePromise=null})))}stop(){this.started=!1,this.clearScheduledEvaluations(),this.detachSessionObservers(),this.captureRecoverableTasks(),this.store.save()}listTasks(){return this.store.list()}getTask(e){return this.store.get(e)}async launchTask(e){let r=e.loopMode??"verifier",n=qd(e.verifierCommands);if(r==="verifier"&&n.length===0)throw new Error(Ji());let i={id:hi(8),name:Kw(e.name??e.goal),goal:e.goal.trim(),workdir:e.workdir,status:"waiting_for_session",createdAt:Date.now(),updatedAt:Date.now(),iteration:0,maxIterations:e.maxIterations??Ww,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,allowedTools:e.allowedTools,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,harness:e.harness,permissionMode:e.permissionMode??"bypassPermissions",loopMode:r,completionPromise:jf(e.completionPromise),verifierCommands:n,repeatedFailureCount:0},s=await this.spawnTaskSession(i,Hw(i));return this.attachSessionObservers(i,s),i.sessionId=s.id,i.sessionName=s.name,i.harnessSessionId=s.harnessSessionId,i.status="running",i.updatedAt=Date.now(),this.store.upsert(i),this.scheduleTaskEvaluation(i.id,"launch",s.id),this.notify(i,`\u{1F3AF} [${i.name}] Goal task started
122
+
123
+ Goal:
124
+ ${no(i.goal,500)}`,"goal-task-started"),i}stopTask(e){let r=this.store.get(e);if(r)return Xw(r.status)?{task:r,action:"already_terminal"}:(r.sessionId&&this.sessionManager.kill(r.sessionId,"user"),this.markTaskStopped(r,"Stopped by user."),{task:r,action:"stopped"})}async spawnTaskSession(e,r){return this.spawnManagedTaskSession(e,r)}async spawnManagedTaskSession(e,r,n){let o=n?this.sessionManager.resolveHarnessSessionId(n)??n:void 0,i=n?this.sessionManager.resolve(n):void 0,s=o?this.sessionManager.getPersistedSession(o)??this.sessionManager.getPersistedSession(n??o):void 0,{resumeSessionId:a}=tn({requestedResumeSessionId:o,activeSession:i?{harnessSessionId:i.harnessSessionId}:void 0,persistedSession:s?{harness:s.harness,backendRef:s.backendRef}:void 0}),d={prompt:r,name:e.name,workdir:e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,allowedTools:e.allowedTools,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:Vw(e),permissionMode:e.permissionMode,multiTurn:!0,goalTaskId:e.id,harness:e.harness,resumeSessionId:a,resumeWorktreeFrom:o,worktreeStrategy:"off"};return this.sessionManager.spawnAndAwaitRunning(d,{notifyLaunch:!1})}async resumeTaskSession(e,r,n){if(!n.harnessSessionId){let i=await this.spawnTaskSession(e,["The previous session ended without a resumable harness session id.","Continue working on the same goal.","",r].join(`
125
+ `));return this.attachSessionObservers(e,i),i}let o=await this.spawnManagedTaskSession(e,r,n.harnessSessionId);return this.attachSessionObservers(e,o),o}resolveResumeSessionId(e){if(e.harnessSessionId)return e.harnessSessionId;if(e.sessionId){let n=this.sessionManager.resolveHarnessSessionId(e.sessionId);if(n)return n}let r=this.sessionManager.resolveHarnessSessionId(e.name);if(r)return r}captureRecoverableTasks(){for(let e of this.store.list()){if(e.status!=="running"&&e.status!=="waiting_for_session")continue;let r=e.sessionId?this.sessionManager.resolve(e.sessionId):void 0;r&&(e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId??e.harnessSessionId,e.route=r.route??e.route,e.updatedAt=Date.now(),e.status="waiting_for_session",this.store.upsert(e))}}async restoreRecoverableTasks(){for(let e of this.store.list()){if(!this.started)break;if(e.status==="waiting_for_user"){this.markTaskFailed(e,"Goal task was waiting for user input and cannot continue autonomously");continue}if(e.status!=="waiting_for_session"&&e.status!=="running")continue;if(Gf(e)){this.markTaskFailed(e,Ji());continue}if(e.sessionId){let n=this.sessionManager.resolve(e.sessionId);if(n&&(n.status==="starting"||n.status==="running"))continue}let r=this.resolveResumeSessionId(e);if(!r){this.markTaskFailed(e,"Goal task could not be resumed after gateway restart because no resumable session id was available.");continue}try{let n=await this.spawnManagedTaskSession(e,Qf(e),r);if(!this.started){e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??r,e.route=n.route??e.route,e.status="waiting_for_session",e.updatedAt=Date.now(),this.store.upsert(e),this.sessionManager.kill(n.id,"shutdown");break}this.attachSessionObservers(e,n),e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??r,e.route=n.route??e.route,e.status="running",e.updatedAt=Date.now(),this.store.upsert(e),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after gateway restart`,n),this.scheduleTaskEvaluation(e.id,"restore",n.id)}catch(n){this.markTaskFailed(e,`Failed to resume the goal task after gateway restart: ${$r(n)}`)}}}async runVerifiers(e){let r=qd(e.verifierCommands);if(r.length===0){let s={status:"fail",steps:[{label:"verifier-config",command:"(none configured)",ok:!1,exitCode:1,durationMs:0,output:Ji()}],summary:"",fingerprint:""};return s.fingerprint=Hf(s),s.summary=Jf(s),s}let n=[];for(let s of r)n.push(await eI(e.workdir,s));let i={status:n.every(s=>s.ok)?"pass":"fail",steps:n,summary:"",fingerprint:""};return i.fingerprint=Hf(i),i.summary=Jf(i),i}notify(e,r,n){this.sessionManager.emitGoalTaskUpdate(e,r,n)}notifyIterationStatus(e,r,n){let o=ar(n??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0)),i=`${r}
126
+
127
+ ${dr(e,o)}`;this.notify(e,i,"goal-task-progress")}setTaskRunningWithSession(e,r){e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId,e.route=r.route??e.route,e.status="running",e.waitingForUserReason=void 0,e.updatedAt=Date.now(),this.store.upsert(e)}attachSessionObservers(e,r){if(this.observerDisposers.has(r.id))return;let n=(i,s)=>{(s==="completed"||s==="failed"||s==="killed")&&(this.removeSessionObserver(r.id),this.scheduleTaskEvaluation(e.id,`status:${s}`,r.id))},o=()=>{let i=this.store.get(e.id);i&&(i.sessionId=r.id,i.sessionName=r.name,i.harnessSessionId=r.harnessSessionId,i.route=r.route??i.route,i.updatedAt=Date.now(),i.status==="waiting_for_session"&&(i.status="running"),this.store.upsert(i),this.notifyIterationStatus(i,`\u{1F504} [${i.name}] Coding turn complete`,r),this.scheduleTaskEvaluation(e.id,"turnEnd",r.id))};r.on("statusChange",n),r.on("turnEnd",o),this.observerDisposers.set(r.id,()=>{r.off?.("statusChange",n),r.off?.("turnEnd",o),r.removeListener?.("statusChange",n),r.removeListener?.("turnEnd",o)})}scheduleTaskEvaluation(e,r,n){if(!this.started)return;let o=this.scheduledEvaluations.get(e);if(o){!o.sessionId&&n&&(o.sessionId=n);return}let i={timer:setTimeout(()=>{this.scheduledEvaluations.delete(e),this.evaluateTask(e,r,i.sessionId).catch(s=>{console.warn(`[GoalController] evaluateTask error (${r}): ${$r(s)}`)})},0),sessionId:n};i.timer.unref?.(),this.scheduledEvaluations.set(e,i)}clearScheduledEvaluations(){for(let e of this.scheduledEvaluations.values())clearTimeout(e.timer);this.scheduledEvaluations.clear(),this.dirtyEvaluations.clear(),this.dirtyEvaluationSessionIds.clear()}detachSessionObservers(){for(let e of[...this.observerDisposers.keys()])this.removeSessionObserver(e)}removeSessionObserver(e){let r=this.observerDisposers.get(e);r&&(this.observerDisposers.delete(e),r())}markTaskFailed(e,r){e.status="failed",e.failureReason=no(r,Vd),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u274C [${e.name}] Goal task failed
128
+
129
+ ${e.failureReason}`,"goal-task-failed")}markTaskFailedWaitingForUser(e,r){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${r}`)}markTaskSucceeded(e,r){e.status="succeeded",e.lastVerifierSummary=r,e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u2705 [${e.name}] Goal task succeeded
130
+
131
+ ${r}`,"goal-task-succeeded")}markTaskStopped(e,r){e.status="stopped",e.failureReason=no(r,Vd),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u26D4 [${e.name}] Goal task stopped
132
+
133
+ ${e.failureReason}`,"goal-task-stopped")}async handleRunningSession(e,r){if(r.pendingPlanApproval){let s=await bt(this.sessionManager,{session:r.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});s.isError&&this.markTaskFailed(e,s.text);return}if(!r.pendingInputState){this.setTaskRunningWithSession(e,r);return}let n=r.getOutput(30).join(`
134
+ `),o=zf(n);if(!o){this.markTaskFailedWaitingForUser(e,ur(n,24)||"The session is waiting for user input.");return}let i=await bt(this.sessionManager,{session:r.id,message:o,userInitiated:!1});if(i.isError||i.text.includes("Auto-respond limit reached")){this.markTaskFailedWaitingForUser(e,i.text);return}e.status="running",e.waitingForUserReason=void 0,e.updatedAt=Date.now(),this.store.upsert(e)}async resumeAfterIdleTimeout(e,r,n){try{let o=await this.resumeTaskSession(e,n,r);this.setTaskRunningWithSession(e,o),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after idle timeout`,o),this.scheduleTaskEvaluation(e.id,"idle-timeout-resume",o.id)}catch(o){this.markTaskFailed(e,`Failed to resume the goal task after idle timeout: ${$r(o)}`)}}async handleTerminalSession(e,r){if(r.status==="failed"){this.markTaskFailed(e,Zw(r));return}if(r.status==="killed"&&r.killReason==="user"){this.markTaskStopped(e,"Stopped by user.");return}if(r.status==="killed"&&r.killReason==="idle-timeout"){let i=r.getOutput(60).join(`
135
+ `);if(r.pendingPlanApproval){let s=await bt(this.sessionManager,{session:r.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});if(s.isError){this.markTaskFailed(e,s.text);return}let a=this.sessionManager.resolve(r.id);if(!a){this.markTaskFailed(e,"Failed to resolve the resumed goal task session after idle timeout plan approval.");return}this.attachSessionObservers(e,a),this.setTaskRunningWithSession(e,a),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after idle timeout`,a),this.scheduleTaskEvaluation(e.id,"idle-timeout-plan-resume",a.id);return}if(r.pendingInputState){let s=zf(i);if(!s){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${ur(i,24)||"The goal task hit idle timeout while waiting for user input."}`);return}await this.resumeAfterIdleTimeout(e,r,["The previous session hit idle timeout while waiting for a response.",`Use this response and continue the goal: ${s}`].join(`
136
+
137
+ `));return}await this.resumeAfterIdleTimeout(e,r,Qf(e));return}if(r.status==="killed"&&r.killReason!=="done"){this.markTaskFailed(e,`Underlying session was killed (${r.killReason}).`);return}if(e.loopMode==="ralph"){let i=r.getOutput(200).join(`
138
+ `),s=jf(e.completionPromise);if(Yw(i,s)){if(e.verifierCommands.length===0){this.markTaskSucceeded(e,`Completion promise "${s}" detected in agent output.`);return}let m=await this.runVerifiers(e);if(e.lastVerifierSummary=m.summary,e.updatedAt=Date.now(),m.status==="pass"){this.markTaskSucceeded(e,[`Completion promise "${s}" detected.`,m.summary].join(`
139
+ `));return}if(e.lastVerifierFingerprint===m.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=m.fingerprint,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Goal task emitted completion promise but verifiers still failed before hitting the iteration budget (${e.maxIterations}).`,m.summary].join(`
140
+ `));return}e.iteration+=1;let S=Jw(e,m);try{let y=await this.resumeTaskSession(e,S,r);this.setTaskRunningWithSession(e,y),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Completion claimed but verifiers still failed`),this.scheduleTaskEvaluation(e.id,"ralph-verifier-resume",y.id)}catch(y){this.markTaskFailed(e,`Failed to resume the Ralph goal task after verifier failure: ${$r(y)}`)}return}let d=Gw(i);if(e.lastVerifierFingerprint===d?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=d,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Completion promise "${s}" was not emitted before hitting the iteration budget (${e.maxIterations}).`,"Latest output:",ur(i,20)||"(no output)"].join(`
141
+ `));return}e.iteration+=1;let l=Qw(e,i);try{let m=await this.resumeTaskSession(e,l,r);this.setTaskRunningWithSession(e,m),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Ralph iteration continued`),this.scheduleTaskEvaluation(e.id,"ralph-continue",m.id)}catch(m){this.markTaskFailed(e,`Failed to continue the Ralph goal task: ${$r(m)}`)}return}let n=await this.runVerifiers(e);if(e.lastVerifierSummary=n.summary,e.updatedAt=Date.now(),n.status==="pass"){this.markTaskSucceeded(e,n.summary);return}if(e.lastVerifierFingerprint===n.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=n.fingerprint,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Verifier did not pass before hitting the iteration budget (${e.maxIterations}).`,n.summary].join(`
142
+ `));return}e.iteration+=1;let o=zw(e,n);try{let i=await this.resumeTaskSession(e,o,r);this.setTaskRunningWithSession(e,i),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Repair iteration started after verifier failure`),this.scheduleTaskEvaluation(e.id,"repair-resume",i.id)}catch(i){this.markTaskFailed(e,`Failed to resume the goal task: ${$r(i)}`)}}async evaluateTask(e,r,n){this.restorePromise&&await this.restorePromise;let o=this.store.get(e);o&&await this.reconcileTask(o,r,n)}async reconcileTask(e,r="manual",n){if(!(e.status==="succeeded"||e.status==="failed"||e.status==="stopped")){if(this.inFlight.has(e.id)){this.dirtyEvaluations.add(e.id),!this.dirtyEvaluationSessionIds.get(e.id)&&n?this.dirtyEvaluationSessionIds.set(e.id,n):this.dirtyEvaluationSessionIds.has(e.id)||this.dirtyEvaluationSessionIds.set(e.id,n);return}this.inFlight.add(e.id);try{if(n&&e.sessionId&&e.sessionId!==n){let i=this.sessionManager.resolve(n);if(i&&(i.status==="completed"||i.status==="failed"||i.status==="killed"))return}let o=n?this.sessionManager.resolve(n)??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0):e.sessionId?this.sessionManager.resolve(e.sessionId):void 0;if(e.status==="waiting_for_user"){this.markTaskFailed(e,"Goal task was waiting for user input and cannot continue autonomously");return}if(Gf(e)){this.markTaskFailed(e,Ji());return}if(!o){this.markTaskFailed(e,"Underlying session could not be found.");return}if(e.sessionName=o.name,e.harnessSessionId=o.harnessSessionId,e.route=o.route??e.route,e.updatedAt=Date.now(),this.store.upsert(e),o.status==="starting"||o.status==="running"){await this.handleRunningSession(e,o);return}await this.handleTerminalSession(e,o)}finally{if(this.inFlight.delete(e.id),this.dirtyEvaluations.has(e.id)){this.dirtyEvaluations.delete(e.id);let o=this.dirtyEvaluationSessionIds.get(e.id);this.dirtyEvaluationSessionIds.delete(e.id),this.scheduleTaskEvaluation(e.id,`${r}:dirty`,o)}}}}};Re();import{existsSync as tI,realpathSync as rI}from"fs";import{resolve as nI}from"path";function Zf(t){if(!t)return;let e=nI(t);try{if(tI(e))return rI.native(e)}catch{}return e}function Xi(t,e){return!t||!e?!1:Zf(t)===Zf(e)}ke();Re();import{existsSync as oI}from"fs";ke();ut();function eg(t){return t instanceof Error?t.message:String(t)}function iI(t){let e=t.worktreeStrategy??_.defaultWorktreeStrategy;return!!e&&e!=="off"&&Rd(gi({harnessName:t.harness??Pe(),backendRef:t.backendRef}))}function sI(t,e,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 ${e} (the original workspace).`,`If your task references files by absolute path under ${e}, rewrite those`,"paths relative to your current working directory. For example:",` "${e}/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(`
143
+ `);return(t??"")+o}function aI(t,e){let r=t.resumeSessionId??t.resumeWorktreeFrom;if(!r)return{};let n=e(r);if(!n)return{};let o=(()=>{if(n.workdir&&n.workdir!==n.worktreePath)return n.workdir;if(n.worktreePath){let s=xi(n.worktreePath);return n.workdir&&s&&Xi(n.workdir,s)?n.workdir:s??n.workdir}return n.workdir})();if(!t.worktreeStrategy&&n.worktreeStrategy&&(t.worktreeStrategy=n.worktreeStrategy),!t.planApproval&&n.planApproval&&(t.planApproval=n.planApproval),!n.worktreePath)return{};if(!n.worktreeBranch)throw new Error(`Cannot resume session "${r}": persisted worktree metadata is missing worktreeBranch.`);let i=Om(gi({persistedHarness:n.harness,backendRef:n.backendRef}))&&!!n.backendRef?.worktreePath;if(oI(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:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.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:!!t.resumeWorktreeFrom};try{Ti(o);let s=$d(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: ${eg(s)}, using original workdir`),{actualWorkdir:o,originalWorkdir:o,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom}}}function tg(t,e,r){let{actualWorkdir:n,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}=aI(t,r);a&&(t.resumeSessionId=void 0),d&&(t.resumeWorktreeFrom=void 0),n??=t.workdir,o??=t.workdir;let l=!!(t.resumeSessionId??t.resumeWorktreeFrom),m=t.worktreeStrategy??_.defaultWorktreeStrategy;m&&(t.worktreeStrategy=m);let S=iI(t),y=!t.resumeSessionId&&!i&&m&&m!=="off"&&!S;if(S&&!Cd(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${m}" requires a git worktree, but "${o}" is not a git repository.`);if(y&&Cd(o)){if(!Ym(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=$d(o,e),n=i,s=Ri(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);console.log(`[SessionManager] Created worktree at ${i}`)}catch(f){throw new Error(`Cannot launch session "${e}": worktree creation failed: ${eg(f)}`)}}else if(y)throw new Error(`Cannot launch session "${e}": worktree strategy "${m}" requires a git worktree, but "${o}" is not a git repository.`);return l&&i&&(n=i),{actualWorkdir:n,originalWorkdir:o,effectiveSystemPrompt:i&&s?sI(t.systemPrompt,o,i,s):t.systemPrompt,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}}var Zi=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,r){return tg(e,r,this.getPersistedSession)}hydrateSpawnedSession(e,r,n){n.worktreeStrategy&&n.worktreeStrategy!=="off"&&(e.originalWorkdir=r.originalWorkdir),r.worktreePath&&(e.worktreePath=r.worktreePath,e.worktreeBranch=r.worktreeBranchName,e.worktreeState="provisioned"),n.worktreePrTargetRepo&&(e.worktreePrTargetRepo=n.worktreePrTargetRepo)}};ke();var es=class{constructor(e){this.deps=e}deps;applySessionPatch(e,r){let n=this.deps.store.getPersistedSession(e);n&&(Object.assign(n,r),this.deps.store.assertPersistedEntry(n));let o=this.findActiveSessionForRef(e,n);return o&&this.applyPatchToActiveSession(o,r),!n&&!o?!1:(n&&this.deps.store.saveIndex(),!0)}matchesExistingSession(e,r){if(!r)return!1;let n=$(e),o=$(r);return!!(r.sessionId&&e.id===r.sessionId||o&&o===n||r?.harnessSessionId&&e.harnessSessionId===r.harnessSessionId||r?.name&&e.name===r.name)}findActiveSessionForRef(e,r){let n=this.deps.resolveSession(e);if(n)return n;for(let o of this.deps.sessions.values())if(re(o)===e||$(o)===e||o.harnessSessionId===e||this.matchesExistingSession(o,r))return o}applyPatchToActiveSession(e,r){this.applyControlStatePatch(e,r),this.applySessionMetadataPatch(e,r),this.applyWorktreeMetadataPatch(e,r)}applyControlStatePatch(e,r){let n={lifecycle:r.lifecycle,approvalState:r.approvalState,worktreeState:r.worktreeState,runtimeState:r.runtimeState,deliveryState:r.deliveryState,pendingPlanApproval:r.pendingPlanApproval,planApprovalContext:r.planApprovalContext,planDecisionVersion:r.planDecisionVersion,actionablePlanDecisionVersion:r.actionablePlanDecisionVersion,canonicalPlanPromptVersion:r.canonicalPlanPromptVersion,approvalPromptRequiredVersion:r.approvalPromptRequiredVersion,approvalPromptVersion:r.approvalPromptVersion,approvalPromptStatus:r.approvalPromptStatus,approvalPromptTransport:r.approvalPromptTransport,approvalPromptMessageKind:r.approvalPromptMessageKind,approvalPromptLastAttemptAt:r.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:r.approvalPromptDeliveredAt,approvalPromptFailedAt:r.approvalPromptFailedAt,pendingWorktreeDecisionSince:r.pendingWorktreeDecisionSince};if(typeof e.applyControlPatch=="function"){e.applyControlPatch(n);return}this.assignIfDefined(e,"lifecycle",r.lifecycle),this.assignIfDefined(e,"approvalState",r.approvalState),this.assignIfDefined(e,"worktreeState",r.worktreeState),this.assignIfDefined(e,"runtimeState",r.runtimeState),this.assignIfDefined(e,"deliveryState",r.deliveryState),this.assignIfDefined(e,"pendingPlanApproval",r.pendingPlanApproval),this.assignIfDefined(e,"planApprovalContext",r.planApprovalContext),this.assignIfDefined(e,"planDecisionVersion",r.planDecisionVersion),this.assignIfDefined(e,"actionablePlanDecisionVersion",r.actionablePlanDecisionVersion),this.assignIfDefined(e,"canonicalPlanPromptVersion",r.canonicalPlanPromptVersion),this.assignIfDefined(e,"approvalPromptRequiredVersion",r.approvalPromptRequiredVersion),this.assignIfDefined(e,"approvalPromptVersion",r.approvalPromptVersion),this.assignIfDefined(e,"approvalPromptStatus",r.approvalPromptStatus),this.assignIfDefined(e,"approvalPromptTransport",r.approvalPromptTransport),this.assignIfDefined(e,"approvalPromptMessageKind",r.approvalPromptMessageKind),this.assignIfDefined(e,"approvalPromptLastAttemptAt",r.approvalPromptLastAttemptAt),this.assignIfDefined(e,"approvalPromptDeliveredAt",r.approvalPromptDeliveredAt),this.assignIfDefined(e,"approvalPromptFailedAt",r.approvalPromptFailedAt)}applySessionMetadataPatch(e,r){this.assignIfDefined(e,"approvalRationale",r.approvalRationale)}applyWorktreeMetadataPatch(e,r){this.assignIfDefined(e,"worktreePath",r.worktreePath),this.assignIfDefined(e,"worktreeBranch",r.worktreeBranch),this.assignIfDefined(e,"worktreePrUrl",r.worktreePrUrl),this.assignIfDefined(e,"worktreePrNumber",r.worktreePrNumber),this.assignIfDefined(e,"worktreeMerged",r.worktreeMerged),this.assignIfDefined(e,"worktreeMergedAt",r.worktreeMergedAt),this.assignIfDefined(e,"worktreeDisposition",r.worktreeDisposition),this.assignIfDefined(e,"worktreePrTargetRepo",r.worktreePrTargetRepo),this.assignIfDefined(e,"worktreePushRemote",r.worktreePushRemote),this.assignIfDefined(e,"worktreeLifecycle",r.worktreeLifecycle),"autoMergeParentSessionId"in r&&(e.autoMergeParentSessionId=r.autoMergeParentSessionId),"autoMergeConflictResolutionAttemptCount"in r&&(e.autoMergeConflictResolutionAttemptCount=r.autoMergeConflictResolutionAttemptCount),"autoMergeResolverSessionId"in r&&(e.autoMergeResolverSessionId=r.autoMergeResolverSessionId)}assignIfDefined(e,r,n){n!==void 0&&(e[r]=n)}};ke();var dI=new Set(["starting","running"]),ts=class{constructor(e,r){this.sessions=e;this.store=r}sessions;store;resolveActive(e){let r=this.sessions.get(e);return r||(this.findPreferredMatch(e,n=>n.name===e)??this.findPreferredMatch(e,n=>$(n)===e)??this.findPreferredMatch(e,n=>n.harnessSessionId===e))}getPersistedSession(e){return this.store.getPersistedSession(e)}resolveBackendConversationId(e){let r=this.resolveActive(e);return this.store.resolveBackendConversationId(e,r?$(r)??r.harnessSessionId:void 0)}findPreferredMatch(e,r){let n,o;for(let i of this.sessions.values())r(i,e)&&((!o||i.startedAt>o.startedAt)&&(o=i),dI.has(i.status)&&(!n||i.startedAt>n.startedAt)&&(n=i));return n??o}};ke();ke();ut();var rs=class{constructor(e){this.deps=e}deps;async plan(e){let r=re(e)??e.harnessSessionId;if(this.deps.isAlreadyMerged(r))return console.info(`[SessionManager] handleWorktreeStrategy: session "${e.name}" already merged \u2014 skipping strategy handling`),{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};if(e.status!=="completed")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};if(!this.deps.shouldRunWorktreeStrategy(e))return console.info(`[SessionManager] handleWorktreeStrategy: skipping \u2014 session "${e.name}" is in phase "${e.phase}"`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let n=e.worktreeStrategy;if(!n||n==="off"||n==="manual")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let o=e.worktreePath,i=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,o),s=e.worktreeBranch;if(!i)return{kind:"notify",label:"worktree-missing-repo-dir",message:`\u26A0\uFE0F [${e.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 [${e.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=e.worktreeBaseBranch??sr(i),d=this.deps.getWorktreeCompletionState(i,o,s,a);if(d==="no-change")return{kind:"no-change",repoDir:i,worktreePath:o,nativeBackendWorktree:Ne(e)};if(d==="base-advanced")return{kind:"notify",label:"worktree-no-commits-ahead",message:`\u26A0\uFE0F [${e.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 [${e.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 l=Tr(i,s,a);return l?{kind:"decision",strategy:n,repoDir:i,worktreePath:o,branchName:s,baseBranch:a,diffSummary:l,sessionRef:r??void 0}:(console.warn(`[SessionManager] Failed to get diff summary for ${s}, skipping merge-back`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}})}};function jd(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function ns(t,e={}){let r=e.updatedAt??new Date().toISOString(),n={pendingWorktreeDecisionSince:e.pendingSince??r,lastWorktreeReminderAt:void 0,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision",worktreeLifecycle:jd(t,{state:"pending_decision",updatedAt:r,notes:e.notes})};return e.clearResolverSessionId&&(n.autoMergeResolverSessionId=void 0),n}function rg(t,e,r,n={}){let o=n.updatedAt??new Date().toISOString();return{autoMergeConflictResolutionAttemptCount:r,autoMergeResolverSessionId:e,pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,lifecycle:"terminal",worktreeState:"merge_conflict_resolving",worktreeLifecycle:jd(t,{state:"merge_conflict_resolving",updatedAt:o,notes:n.notes})}}function ng(t,e={}){let r=e.updatedAt??new Date().toISOString(),n=e.resolvedAt??r,o={worktreeMerged:!0,worktreeMergedAt:e.mergedAt??n,lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:jd(t,{state:"merged",updatedAt:r,resolvedAt:n,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}ut();var os=class{constructor(e){this.deps=e;this.actions=new rs({shouldRunWorktreeStrategy:e.shouldRunWorktreeStrategy,isAlreadyMerged:e.isAlreadyMerged,resolveWorktreeRepoDir:e.resolveWorktreeRepoDir,getWorktreeCompletionState:e.getWorktreeCompletionState})}deps;actions;buildConflictResolverPrompt(e){return["Resolve the git rebase conflict for the auto-merge worktree and finish the rebase cleanly.","",`Original session: ${e.session.name} [${e.session.id}]`,`Repository root: ${e.repoDir}`,`Conflicted worktree: ${e.worktreePath}`,`Branch: ${e.branchName}`,`Base branch: ${e.baseBranch}`,"","Requirements:","- Work only inside the conflicted worktree.","- Inspect the current rebase state and resolve only the necessary conflict hunks.","- Make only minimal follow-up edits needed to keep the rebased branch correct.","- Continue the rebase until it completes successfully.","- Run relevant local verification before you finish.","- Do not broaden scope or start unrelated refactors.",`- Stop only when the branch is cleanly rebased onto ${e.baseBranch}.`,e.mergeError?"":void 0,e.mergeError?"Rebase failure details:":void 0,e.mergeError].filter(r=>typeof r=="string").join(`
144
+ `)}notifyAutoMergeConflictEscalation(e,r,n){this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-escalated",userMessage:[`\u26A0\uFE0F [${e.name}] Auto-merge could not finish after one conflict-resolution attempt.`,`Branch \`${r}\` was preserved for manual follow-up.`,"",n].join(`
145
+ `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}updatePersistedSessionFor(e,r){for(let n of et(e))this.deps.updatePersistedSession(n,r)}markPendingDecision(e,r={}){this.updatePersistedSessionFor(e,ns(e,r))}markAutoMergeConflictResolving(e,r,n){this.updatePersistedSessionFor(e,rg(e,r,n,{notes:[`resolver_session:${r}`]}))}markMerged(e){this.updatePersistedSessionFor(e,ng(e,{clearResolverSessionId:!0}))}async handleWorktreeStrategy(e){let r=await this.actions.plan(e);return r.kind==="skip"?r.result:r.kind==="notify"?(this.deps.dispatchSessionNotification(e,{label:r.label,userMessage:r.message}),{notificationSent:!0,worktreeRemoved:!1}):r.kind==="no-change"?this.handleNoChange(e,r.repoDir,r.worktreePath,r.nativeBackendWorktree):r.strategy==="ask"?this.handleAskStrategy(e,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="delegate"?this.handleDelegateStrategy(e,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="auto-merge"?(await this.handleAutoMergeStrategy(e,r.repoDir,r.worktreePath,r.branchName,r.baseBranch,r.diffSummary,r.sessionRef),{notificationSent:!0,worktreeRemoved:!1}):r.strategy==="auto-pr"?this.handleAutoPrStrategy(e,r.baseBranch):{notificationSent:!1,worktreeRemoved:!1}}async handleNoChange(e,r,n,o=Ne(e)){let i=o?!0:tt(r,n);return i?(e.worktreePath=void 0,this.updatePersistedSessionFor(e,{worktreePath:void 0,worktreeDisposition:"no-change-cleaned",worktreeState:"none",worktreeLifecycle:{state:"no_change",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"strategy_no_change",baseBranch:e.worktreeBaseBranch,targetRepo:e.worktreePrTargetRepo,pushRemote:e.worktreePushRemote}}),this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildNoChangeNotification({session:e,nativeBackendWorktree:o,cleanupSucceeded:!0,worktreePath:n,preview:this.deps.getOutputPreview(e),originThreadLine:this.deps.originThreadLine(e)}))):this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildNoChangeNotification({session:e,nativeBackendWorktree:o,cleanupSucceeded:!1,worktreePath:n,preview:this.deps.getOutputPreview(e),originThreadLine:this.deps.originThreadLine(e)})),{notificationSent:!0,worktreeRemoved:i}}handleAskStrategy(e,r,n,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildAskNotification({session:e,branchName:r,baseBranch:n,diffSummary:o,buttons:this.deps.getWorktreeDecisionButtons(e.id)})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleDelegateStrategy(e,r,n,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildDelegateNotification({session:e,branchName:r,baseBranch:n,diffSummary:o})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleAutoMergeSuccess(e,r,n,o,i,s){$t(r,n),this.markMerged(e);let d=Mr({kind:"merge",branch:n,base:o,filesChanged:i.filesChanged,insertions:i.insertions,deletions:i.deletions});s.stashPopConflict?d+=`
146
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${s.stashRef??"stash@{0}"}\` in ${r} to review stashed changes.`:s.stashed&&(d+=`
147
+ (Pre-existing changes on ${o} were auto-stashed and restored.)`),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-success",userMessage:d})}async handleInitialAutoMergeConflict(e,r,n,o,i,s){let a=e.autoMergeConflictResolutionAttemptCount??0;if(a>=1){this.markPendingDecision(e,{notes:["auto_merge_conflict_retry_exhausted"],clearResolverSessionId:!0}),this.notifyAutoMergeConflictEscalation(e,o,`The rebased branch still conflicts with \`${i}\`. Open a PR or resolve manually in ${n}.`);return}let d=this.buildConflictResolverPrompt({session:e,repoDir:r,worktreePath:n,branchName:o,baseBranch:i,mergeError:s});try{let l=await this.deps.spawnConflictResolver({session:e,repoDir:r,worktreePath:n,branchName:o,baseBranch:i,prompt:d});this.markAutoMergeConflictResolving(e,l.id,a+1),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-resolving",userMessage:`\u26A0\uFE0F [${e.name}] Auto-merge hit a rebase conflict. Started resolver session ${l.name} and will retry automatically if it succeeds.`})}catch(l){this.markPendingDecision(e,{notes:["auto_merge_conflict_resolver_spawn_failed"]}),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-spawn-failed",userMessage:`\u274C [${e.name}] Auto-merge hit a rebase conflict and failed to start the resolver: ${l instanceof Error?l.message:String(l)}`,buttons:[[this.deps.makeOpenPrButton(e.id)]]})}}handleAutoMergeRetryFailure(e,r,n,o){this.markPendingDecision(e,{notes:["auto_merge_conflict_retry_failed"],clearResolverSessionId:!0}),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",userMessage:[o,"","Auto-merge retry did not complete after conflict resolution.",`Branch \`${r}\` was preserved for manual follow-up in ${n}.`].join(`
148
+ `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}async handleAutoMergeStrategy(e,r,n,o,i,s,a=re(e)??e.harnessSessionId){this.deps.isAlreadyMerged(a)||e.autoMergeResolverSessionId||await this.deps.enqueueMerge(r,async()=>{if(this.deps.isAlreadyMerged(a))return;let d=this.deps.mergeBranch(r,o,i,"merge",n);if(d.success){this.handleAutoMergeSuccess(e,r,o,i,s,d);return}if(d.rebaseConflict){await this.handleInitialAutoMergeConflict(e,r,n,o,i,d.error);return}let l=d.dirtyError?`\u274C [${e.name}] Merge blocked: ${d.error}`:`\u274C [${e.name}] Merge failed: ${d.error??"unknown error"}`;if(e.worktreeState==="merge_conflict_resolving"||e.worktreeLifecycle?.state==="merge_conflict_resolving"){this.handleAutoMergeRetryFailure(e,o,n,l);return}this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",userMessage:l})},()=>{this.deps.dispatchSessionNotification(e,{label:"worktree-merge-queued",userMessage:`\u{1F550} [${e.name}] Merge queued \u2014 another merge for this repo is in progress. Will notify when complete.`})})}async handleAutoPrStrategy(e,r){return this.updatePersistedSessionFor(e,{lifecycle:"terminal",worktreeState:"pr_in_progress"}),(await this.deps.runAutoPr(e,r)).success||this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}};import{existsSync as LI,writeFileSync as WI}from"fs";Zr();import{randomUUID as lI}from"crypto";function uI(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var is=class{constructor(e,r){this.onChange=e;this.retentionMs=r}onChange;retentionMs;tokens=new Map;afterChange;replaceAll(e){this.tokens.clear();for(let r of e)this.tokens.set(r.id,r)}clear(){this.tokens.clear(),this.notifyChanged()}listForPersistence(){return[...this.tokens.values()]}createActionToken(e,r,n={}){let o={id:lI(),sessionId:e,kind:r,createdAt:Date.now(),...n};return this.tokens.set(o.id,o),this.notifyChanged(),o}getActionToken(e){let r=this.tokens.get(e);if(r){if(r.expiresAt!=null&&r.expiresAt<=Date.now()){this.tokens.delete(e),this.notifyChanged();return}return r}}consumeActionToken(e){let r=this.getActionToken(e);if(!(!r||r.consumedAt!=null))return r.consumedAt=Date.now(),this.notifyChanged(),r}deleteActionTokensForSession(e){let r=!1;for(let[n,o]of this.tokens)o.sessionId===e&&(this.tokens.delete(n),r=!0);r&&this.notifyChanged()}deletePlanDecisionTokensForSession(e,r){let n=!1;for(let[o,i]of this.tokens)i.sessionId!==e||!uI(i.kind)||r!=null&&i.planDecisionVersion===r||(this.tokens.delete(o),n=!0);n&&this.notifyChanged()}purgeExpiredActionTokens(e=Date.now()){let r=!1;for(let[n,o]of this.tokens){let i=o.expiresAt!=null&&o.expiresAt<=e,s=o.consumedAt!=null&&e-o.consumedAt>this.retentionMs;(i||s)&&(this.tokens.delete(n),r=!0)}r&&this.notifyChanged()}nextExpiryAt(){let e;for(let r of this.tokens.values()){let n=[r.expiresAt,r.consumedAt!=null?r.consumedAt+this.retentionMs:void 0].filter(o=>o!=null&&Number.isFinite(o));for(let o of n)(e==null||o<e)&&(e=o)}return e}setAfterChangeListener(e){this.afterChange=e}notifyChanged(){this.onChange(),this.afterChange?.()}};ke();ke();var ss=class{constructor(e){this.indexes=e}indexes;hasRecordedSession(e){return this.indexes.idIndex.has(e)}getLatestPersistedByName(e){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!==e){s++;continue}let d=a.createdAt??Number.NEGATIVE_INFINITY,l=a.completedAt??Number.NEGATIVE_INFINITY;(d>n||d===n&&l>o||d===n&&l===o&&s>i)&&(r=a,n=d,o=l,i=s),s++}return r}resolveBackendConversationId(e,r){if(r)return r;let n=this.indexes.idIndex.get(e);if(n){let s=this.indexes.persisted.get(n);return(s?$(s):void 0)??n}let o=this.getLatestPersistedByName(e);if(o)return $(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(e);if(i){let s=this.indexes.persisted.get(i);return(s?$(s):void 0)??i}if(this.indexes.persisted.has(e)){let s=this.indexes.persisted.get(e);return s?$(s)??e:e}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))return e}resolveHarnessSessionId(e,r){return this.resolveBackendConversationId(e,r)}getPersistedSession(e){let r=this.indexes.idIndex.get(e);if(r)return this.indexes.persisted.get(r);let n=this.getLatestPersistedByName(e);if(n)return n;let o=this.indexes.backendIdIndex.get(e);return o?this.indexes.persisted.get(o):this.indexes.persisted.get(e)}listPersistedSessions(){return[...this.indexes.persisted.values()].sort((e,r)=>(r.completedAt??0)-(e.completedAt??0))}};import{existsSync as EI,mkdirSync as OI,readFileSync as DI,readdirSync as Hd,renameSync as ug,statSync as pg,unlinkSync as cg,writeFileSync as mg}from"fs";import{tmpdir as zd}from"os";import{dirname as NI,join as us}from"path";import{homedir as pI}from"node:os";import{join as cI}from"node:path";function og(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let r=t.HOME?.trim()||pI();return cI(r,".openclaw")}Zr();var as=6,mI=new Set(["running","completed","failed","killed"]);function oo(t){return!!t&&typeof t=="object"}function ln(t,e=""){return typeof t=="string"&&t.trim().length>0?t:e}function I(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function je(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function fI(t){return t==="low"||t==="medium"||t==="high"?t:void 0}function ig(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function gI(t){return t==="never"||t==="on-request"?"never":void 0}function hI(t){return t==="approve"||t==="ask"||t==="delegate"?t:void 0}function SI(t){if(t==="plan-mode"||t==="codex-first-turn-plan"||t==="soft-plan")return"plan-mode"}function yI(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function sg(t){return t==="starting"||t==="active"||t==="awaiting_plan_decision"||t==="awaiting_user_input"||t==="awaiting_worktree_decision"||t==="suspended"||t==="terminal"?t:void 0}function kI(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function vI(t){return t==="none"||t==="provisioned"||t==="pending_decision"||t==="merge_conflict_resolving"||t==="merge_in_progress"||t==="pr_in_progress"||t==="merged"||t==="released"||t==="pr_open"||t==="dismissed"||t==="cleanup_failed"?t:void 0}function PI(t){return t==="none"||t==="provisioned"||t==="pending_decision"||t==="merge_conflict_resolving"||t==="pr_open"||t==="merged"||t==="released"||t==="dismissed"||t==="no_change"||t==="cleanup_failed"?t:void 0}function wI(t){return t==="live"||t==="stopped"?t:void 0}function II(t){return t==="not_sent"||t==="sending"||t==="delivered"||t==="fallback_delivered"||t==="failed"?t:void 0}function bI(t){return t==="none"||t==="direct-telegram"||t==="wake-only"?t:void 0}function xI(t){return t==="none"||t==="canonical_buttons"||t==="explicit_fallback_text"?t:void 0}function AI(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function RI(t){return t==="awaiting_plan_output"||t==="awaiting_approval"||t==="approved_then_implemented"||t==="implemented_without_required_approval"||t==="not_plan_gated"?t:void 0}function TI(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"||t==="monitor-start-plan"||t==="monitor-dismiss"||t==="worktree-merge"||t==="worktree-create-pr"||t==="worktree-update-pr"||t==="worktree-view-pr"||t==="worktree-decide-later"||t==="worktree-dismiss"||t==="session-resume"||t==="session-restart"||t==="view-output"||t==="question-answer"?t:void 0}function ag(t){if(!oo(t))return;let e=I(t.provider),r=I(t.accountId),n=I(t.target),o=I(t.threadId),i=I(t.sessionKey);if(!(!e||!n))return{provider:e,accountId:r,target:n,threadId:o,sessionKey:i}}function MI(t,e,r){if(oo(t)){let n=I(t.kind),o=I(t.conversationId);if(o&&(n==="claude-code"||n==="codex-app-server"))return{kind:n,conversationId:o,runId:I(t.runId),worktreeId:I(t.worktreeId),worktreePath:I(t.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:r}}function CI(t){if(!oo(t))return;let e=PI(t.state),r=I(t.updatedAt);if(!e||!r)return;let n=I(t.resolutionSource);return{state:e,updatedAt:r,resolvedAt:I(t.resolvedAt),resolutionSource:n==="agent_merge"||n==="agent_pr"||n==="strategy_no_change"||n==="lifecycle_resolver"||n==="dismiss"||n==="maintenance"?n:void 0,baseBranch:I(t.baseBranch),targetRepo:I(t.targetRepo),pushRemote:I(t.pushRemote),notes:Array.isArray(t.notes)?t.notes.filter(o=>typeof o=="string"&&o.length>0):void 0}}function _I(t){let e=new Date(0).toISOString(),r=I(t.worktreeMergedAt)??I(t.worktreeDismissedAt)??I(t.pendingWorktreeDecisionSince)??e;if(t.worktreeMerged===!0)return{state:"merged",updatedAt:r,resolvedAt:I(t.worktreeMergedAt)??r,resolutionSource:"agent_merge",baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:r,resolvedAt:I(t.worktreeDismissedAt)??r,resolutionSource:"dismiss",baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.worktreeDisposition==="no-change-cleaned")return{state:"no_change",updatedAt:r,resolvedAt:r,resolutionSource:"strategy_no_change",baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.worktreeDisposition==="pr-opened"||t.worktreeState==="pr_open")return{state:"pr_open",updatedAt:r,baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:r,baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:r,baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(I(t.worktreePath)||I(t.worktreeBranch))return{state:"provisioned",updatedAt:r,baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)}}function $I(t){if(typeof t=="string"&&mI.has(t))return t==="running"?"killed":t}function dg(t){if(!oo(t))return;let e=ln(t.harnessSessionId);if(!e)return;let r=$I(t.status);if(!r)return;let n=t.status==="running",o=I(t.worktreePath),i=I(t.worktreeBranch),s=I(t.originChannel),a=typeof t.originThreadId=="string"||typeof t.originThreadId=="number"?t.originThreadId:void 0,d=I(t.originSessionKey),l=ag(t.route);if(!l)return;let m=Xr({route:l,originChannel:s,originThreadId:a,originSessionKey:d});if(!m||o&&!i)return;let S=I(t.harness),y=MI(t.backendRef,S,e),f=CI(t.worktreeLifecycle)??_I(t);return{sessionId:I(t.sessionId),harnessSessionId:e,backendRef:y,name:ln(t.name,e),prompt:ln(t.prompt),workdir:ln(t.workdir,"(unknown)"),model:I(t.model),reasoningEffort:fI(t.reasoningEffort),createdAt:je(t.createdAt),completedAt:je(t.completedAt),status:r,lifecycle:n?sg(t.lifecycle)??"suspended":sg(t.lifecycle),approvalState:kI(t.approvalState),worktreeState:vI(t.worktreeState),runtimeState:n?"stopped":wI(t.runtimeState),deliveryState:AI(t.deliveryState),completionWakeIssuedAt:I(t.completionWakeIssuedAt),completionWakeSucceededAt:I(t.completionWakeSucceededAt),completionWakeFailedAt:I(t.completionWakeFailedAt),completionWakeSummaryRequired:t.completionWakeSummaryRequired===!0?!0:void 0,killReason:yI(t.killReason),costUsd:typeof t.costUsd=="number"&&Number.isFinite(t.costUsd)?t.costUsd:0,originAgentId:I(t.originAgentId),originChannel:s,originThreadId:a,originSessionKey:d,route:m,outputPath:I(t.outputPath),harness:S,requestedPermissionMode:ig(t.requestedPermissionMode),currentPermissionMode:ig(t.currentPermissionMode),approvalExecutionState:RI(t.approvalExecutionState),approvalRationale:I(t.approvalRationale),planModeApproved:t.planModeApproved===!0,pendingPlanApproval:t.pendingPlanApproval===!0,planApprovalContext:SI(t.planApprovalContext),planDecisionVersion:je(t.planDecisionVersion),actionablePlanDecisionVersion:je(t.actionablePlanDecisionVersion),canonicalPlanPromptVersion:je(t.canonicalPlanPromptVersion),approvalPromptRequiredVersion:je(t.approvalPromptRequiredVersion),approvalPromptVersion:je(t.approvalPromptVersion),approvalPromptStatus:II(t.approvalPromptStatus),approvalPromptTransport:bI(t.approvalPromptTransport),approvalPromptMessageKind:xI(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:I(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:I(t.approvalPromptDeliveredAt),approvalPromptFailedAt:I(t.approvalPromptFailedAt),planApproval:hI(t.planApproval),codexApprovalPolicy:gI(t.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:t.worktreeStrategy==="off"||t.worktreeStrategy==="manual"||t.worktreeStrategy==="ask"||t.worktreeStrategy==="delegate"||t.worktreeStrategy==="auto-merge"||t.worktreeStrategy==="auto-pr"?t.worktreeStrategy:void 0,worktreeMerged:typeof t.worktreeMerged=="boolean"?t.worktreeMerged:void 0,worktreeMergedAt:I(t.worktreeMergedAt),worktreePrUrl:I(t.worktreePrUrl),worktreePrNumber:je(t.worktreePrNumber),pendingWorktreeDecisionSince:I(t.pendingWorktreeDecisionSince),lastWorktreeReminderAt:I(t.lastWorktreeReminderAt),worktreeBaseBranch:I(t.worktreeBaseBranch),worktreePrTargetRepo:I(t.worktreePrTargetRepo),autoMergeParentSessionId:I(t.autoMergeParentSessionId),autoMergeConflictResolutionAttemptCount:je(t.autoMergeConflictResolutionAttemptCount),autoMergeResolverSessionId:I(t.autoMergeResolverSessionId),worktreePushRemote:I(t.worktreePushRemote),worktreeDecisionSnoozedUntil:I(t.worktreeDecisionSnoozedUntil),worktreeDisposition:t.worktreeDisposition==="active"||t.worktreeDisposition==="pr-opened"||t.worktreeDisposition==="merged"||t.worktreeDisposition==="dismissed"||t.worktreeDisposition==="no-change-cleaned"?t.worktreeDisposition:void 0,worktreeDismissedAt:I(t.worktreeDismissedAt),worktreeLifecycle:f,resumable:n?!0:t.resumable===!0}}function lg(t){if(!oo(t))return;let e=TI(t.kind),r=ln(t.id),n=ln(t.sessionId),o=je(t.createdAt);if(!(!r||!n||!e||o==null))return{id:r,sessionId:n,kind:e,createdAt:o,planDecisionVersion:je(t.planDecisionVersion),expiresAt:je(t.expiresAt),consumedAt:je(t.consumedAt),optionIndex:je(t.optionIndex),label:I(t.label),targetUrl:I(t.targetUrl),route:ag(t.route),launchName:I(t.launchName),launchPrompt:I(t.launchPrompt),launchWorkdir:I(t.launchWorkdir)}}function ds(t){if(!t.backendRef?.kind||!t.backendRef.conversationId)throw new Error(`Persisted session ${t.harnessSessionId} is missing required backend ref metadata.`);if(!t.route?.provider||!t.route.target)throw new Error(`Persisted session ${t.harnessSessionId} is missing required route metadata.`);if(t.worktreePath&&!t.worktreeBranch)throw new Error(`Persisted session ${t.harnessSessionId} is missing required worktreeBranch metadata.`)}function Gd(t){return!!t&&typeof t=="object"}function Qd(t){return t instanceof Error?t.message:String(t)}function fg(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||us(og(t),"code-agent-sessions.json")}function gg(t,e,r){try{OI(NI(t),{recursive:!0});let n=t+".tmp";mg(n,JSON.stringify({schemaVersion:as,sessions:e,actionTokens:r},null,2),"utf-8"),ug(n,t)}catch(n){console.warn(`[SessionStore] Failed to save session index: ${Qd(n)}`)}}function ls(t,e){try{if(!EI(t))return;let r=`${t}.legacy-${Date.now()}.json`;ug(t,r),console.warn(`[SessionStore] Breaking upgrade: archived ${e} session store to ${r}. Legacy sessions are not loaded by this release.`)}catch(r){console.warn(`[SessionStore] Failed to archive legacy session store: ${Qd(r)}`)}}function FI(t,e){try{if(e.length===0)return;let r=`${t}.codex-sdk-legacy-${Date.now()}.json`;mg(r,JSON.stringify(e,null,2),"utf-8"),console.warn(`[SessionStore] Breaking Codex transport upgrade: archived ${e.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: ${Qd(r)}`)}}function hg(t,e){try{let r=zd(),n=Hd(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let i=us(r,o),s=pg(i).mtimeMs;t-s>e&&cg(i)}catch{}}catch{}}function Sg(t,e){try{let r=zd(),n=Hd(r).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of n)try{let s=us(r,i),a=pg(s).mtimeMs+e;if(a<=t)return t;o=o==null?a:Math.min(o,a)}catch{}return o}catch{return}}function yg(t){try{let e=new Set(t),r=zd(),n=Hd(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n){let i=us(r,o);if(!e.has(i))try{cg(i)}catch{}}}catch{}}function kg(t){let{indexPath:e,clearAll:r,indexPersistedEntry:n,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:s}=t;try{let a=DI(e,"utf-8"),d=JSON.parse(a);if(Array.isArray(d)){ls(e,"legacy array store"),s();return}if(!Gd(d)||d.schemaVersion!==as&&d.schemaVersion!==4){ls(e,`schema mismatch (expected v${as})`),s();return}let l=Array.isArray(d.sessions)?d.sessions:[],m=[];for(let y of l){if(Gd(y)&&y.harness==="codex"){let v=Gd(y.backendRef)?y.backendRef:void 0;if((typeof v?.kind=="string"?v.kind:void 0)!=="codex-app-server"){m.push(y);continue}}let f=dg(y);if(!f){r(),ls(e,"invalid v4 session entry"),s();return}n(f)}m.length>0&&(FI(e,m),s());let S=Array.isArray(d.actionTokens)?d.actionTokens:[];for(let y of S){let f=lg(y);if(!f){r(),ls(e,"invalid v4 action token"),s();return}o(f)}i()}catch{}}var BI=new Set(["completed","failed","killed"]),Jd=1440*60*1e3;function UI(t){return t instanceof Error?t.message:String(t)}var ps=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;backendIdIndex=new Map;actionTokens;actionTokenStore;indexPath;queries;constructor(e={}){let r=e.env??process.env;this.indexPath=e.indexPath??fg(r),this.actionTokenStore=new is(()=>this.saveIndex(),Jd),this.actionTokens=this.actionTokenStore.tokens,this.queries=new ss({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(){kg({indexPath:this.indexPath,clearAll:()=>{this.persisted.clear(),this.idIndex.clear(),this.nameIndex.clear(),this.backendIdIndex.clear(),this.actionTokenStore.clear()},indexPersistedEntry:e=>this.indexPersistedEntry(e),setActionToken:e=>{this.actionTokens.set(e.id,e)},purgeExpiredActionTokens:()=>this.actionTokenStore.purgeExpiredActionTokens(),saveIndex:()=>this.saveIndex()})}saveIndex(){gg(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){ds(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){return e.backendRef??{kind:Ad(e)==="codex"?"codex-app-server":"claude-code",conversationId:e.harnessSessionId}}indexPersistedEntry(e){let r=this.getEntryStorageKey(e);this.persisted.set(r,e),e.sessionId&&this.idIndex.set(e.sessionId,r),e.name&&this.nameIndex.set(e.name,r);let n=$(e);n&&this.backendIdIndex.set(n,r)}removePersistedIndexes(e){let r=this.getEntryStorageKey(e);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(e){if(!e.harnessSessionId)return;let r=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1},n=Xr({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!n)return;let o={sessionId:e.id,harnessSessionId:e.harnessSessionId,backendRef:this.buildPersistedBackendRef(e),name:e.name,prompt:e.prompt,workdir:e.originalWorkdir??e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,createdAt:e.startedAt,status:"running",lifecycle:e.lifecycle,approvalState:e.approvalState,worktreeState:e.worktreeState,runtimeState:e.runtimeState,deliveryState:e.deliveryState,costUsd:0,originAgentId:e.originAgentId,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey,route:n,harness:e.harnessName,requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:r.planModeApproved,pendingPlanApproval:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeStrategy:e.worktreeStrategy,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,autoMergeParentSessionId:e.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:e.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:e.autoMergeResolverSessionId,worktreeLifecycle:e.worktreeLifecycle,resumable:e.isExplicitlyResumable};ds(o),this.indexPersistedEntry(o),this.saveIndex()}hasRecordedSession(e){return this.queries.hasRecordedSession(e)}persistTerminal(e){if(!e.harnessSessionId)return;let r=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1},n=Xr({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!n)return;let o;try{let s=sn(e.id);if(LI(s))o=s;else{let a=e.getOutput().join(`
149
+ `);a.length>0&&(WI(s,a,"utf-8"),o=s)}}catch(s){console.warn(`[SessionStore] Failed to write output file for session ${e.id}: ${UI(s)}`)}let i={sessionId:e.id,harnessSessionId:e.harnessSessionId,backendRef:this.buildPersistedBackendRef(e),name:e.name,prompt:e.prompt,workdir:e.originalWorkdir??e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,createdAt:e.startedAt,completedAt:e.completedAt,status:e.status,lifecycle:e.lifecycle,approvalState:e.approvalState,worktreeState:e.worktreeState,runtimeState:e.runtimeState,deliveryState:e.deliveryState,killReason:e.killReason,costUsd:e.costUsd,originAgentId:e.originAgentId,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey,route:n,outputPath:o,harness:e.harnessName,requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:r.planModeApproved,pendingPlanApproval:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeStrategy:e.worktreeStrategy,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,autoMergeParentSessionId:e.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:e.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:e.autoMergeResolverSessionId,worktreeLifecycle:e.worktreeLifecycle,resumable:e.isExplicitlyResumable};ds(i),this.indexPersistedEntry(i),this.saveIndex()}getLatestPersistedByName(e){return this.queries.getLatestPersistedByName(e)}resolveBackendConversationId(e,r){return this.queries.resolveBackendConversationId(e,r)}resolveHarnessSessionId(e,r){return this.queries.resolveHarnessSessionId(e,r)}getPersistedSession(e){return this.queries.getPersistedSession(e)}listPersistedSessions(){return this.queries.listPersistedSessions()}cleanupTmpOutputFiles(e){this.actionTokenStore.purgeExpiredActionTokens(e),hg(e,Jd)}getNextTmpOutputCleanupAt(e){return Sg(e,Jd)}evictOldestPersisted(e){let r=this.listPersistedSessions();if(r.length<=e)return[];let n=r.slice(e);for(let o of n)this.removePersistedIndexes(o);return this.saveIndex(),n}shouldGcActiveSession(e,r,n){return!e.completedAt||!BI.has(e.status)?!1:r-e.completedAt>n}getActionToken(e){return this.actionTokenStore.getActionToken(e)}consumeActionToken(e){return this.actionTokenStore.consumeActionToken(e)}deleteActionTokensForSession(e){this.actionTokenStore.deleteActionTokensForSession(e)}purgeExpiredActionTokens(e=Date.now()){this.actionTokenStore.purgeExpiredActionTokens(e)}getNextActionTokenExpiry(){return this.actionTokenStore.nextExpiryAt()}onActionTokensChanged(e){this.actionTokenStore.setAfterChangeListener(e)}hasOutputPathReference(e){for(let r of this.persisted.values())if(r.outputPath===e)return!0;return!1}getReferencedOutputPaths(){return[...new Set([...this.persisted.values()].map(e=>e.outputPath).filter(e=>typeof e=="string"&&e.length>0))]}cleanupOrphanOutputFiles(){yg(this.getReferencedOutputPaths())}};var KI=new Set(["completed","failed","killed"]),cs=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(e){let r=e.costUsd??0,n=e.status;this.metrics.totalCostUsd+=r;let o=new Date(e.completedAt??e.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+r),KI.has(n)&&this.metrics.sessionsByStatus[n]++,e.completedAt){let i=e.completedAt-e.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||r>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:e.id,name:e.name,costUsd:r,prompt:Fe(e.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 VI}from"child_process";var Yd=3e4,qI=2e3,jI=2e4,Et=4;function ms(t){return t instanceof Error?t.message:String(t)}function GI(){return new Error(`Dispatch timed out after ${Yd}ms`)}var fs=class{pendingRetryTimers=new Map;orderedDispatchTails=new Map;disposed=!1;clearPendingRetries(){for(let e of this.pendingRetryTimers.values())for(let r of e)clearTimeout(r.timer),r.onCleared?.();this.pendingRetryTimers.clear()}clearRetryTimersForSession(e){let r=this.pendingRetryTimers.get(e);if(r){for(let n of r)clearTimeout(n.timer),n.onCleared?.();this.pendingRetryTimers.delete(e)}}dispose(){this.disposed=!0,this.clearPendingRetries(),this.orderedDispatchTails.clear()}execute(e,r,n=1){if(!this.disposed){if(n===1&&r.orderingKey){this.enqueueOrderedDispatch(r.orderingKey,o=>this.executeNow(e,r,o,n));return}this.executeNow(e,r,void 0,n)}}executePromise(e,r,n=1){if(!this.disposed){if(n===1&&r.orderingKey){this.enqueueOrderedDispatch(r.orderingKey,o=>this.executePromiseNow(e,r,o,n));return}this.executePromiseNow(e,r,void 0,n)}}executeNow(e,r,n,o=1){if(this.disposed){n?.();return}let i=Date.now();o===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:o,maxAttempts:Et}),VI("openclaw",e,{timeout:Yd},(s,a,d)=>{if(this.disposed){n?.();return}let l=Date.now()-i;if(!s){this.log("info","dispatch_succeeded",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et,elapsedMs:l}),r.onSuccess?.(),n?.();return}let m=d?.trim()?` | stderr: ${d.trim()}`:"";if(o>=Et){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et,elapsedMs:l,error:`${ms(s)}${m}`,terminal:!0}),r.onFinalFailure?.(),n?.();return}let S=this.retryDelayMs(o);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:o,maxAttempts:Et,elapsedMs:l,retryDelayMs:S,error:`${ms(s)}${m}`});let y={timer:setTimeout(()=>{let f=this.pendingRetryTimers.get(r.sessionId);f&&(f.delete(y),f.size===0&&this.pendingRetryTimers.delete(r.sessionId)),this.executeNow(e,r,n,o+1)},S),onCleared:n};y.timer.unref?.(),this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(y)})}executePromiseNow(e,r,n,o=1){if(this.disposed){n?.();return}let i=Date.now();o===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:o,maxAttempts:Et}),this.executePromiseWithTimeout(e).then(()=>{if(this.disposed){n?.();return}let s=Date.now()-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:o,maxAttempts:Et,elapsedMs:s}),r.onSuccess?.(),n?.()}).catch(s=>{if(this.disposed){n?.();return}let a=Date.now()-i;if(o>=Et){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et,elapsedMs:a,error:ms(s),terminal:!0}),r.onFinalFailure?.(),n?.();return}let d=this.retryDelayMs(o);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:o,maxAttempts:Et,elapsedMs:a,retryDelayMs:d,error:ms(s)});let l={timer:setTimeout(()=>{let m=this.pendingRetryTimers.get(r.sessionId);m&&(m.delete(l),m.size===0&&this.pendingRetryTimers.delete(r.sessionId)),this.executePromiseNow(e,r,n,o+1)},d),onCleared:n};l.timer.unref?.(),this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(l)})}executePromiseWithTimeout(e){return new Promise((r,n)=>{let o=!1,i=setTimeout(()=>{o||(o=!0,n(GI()))},Yd);i.unref?.(),Promise.resolve().then(e).then(()=>{o||(o=!0,clearTimeout(i),r())}).catch(s=>{o||(o=!0,clearTimeout(i),n(s))})})}retryDelayMs(e){let r=Math.max(0,e-1),n=qI*2**r;return Math.min(n,jI)}enqueueOrderedDispatch(e,r){let o=(this.orderedDispatchTails.get(e)??Promise.resolve()).catch(()=>{}).then(()=>{if(!this.disposed)return new Promise(i=>{let s=!1;r(()=>{s||(s=!0,i())})})});this.orderedDispatchTails.set(e,o),o.finally(()=>{this.orderedDispatchTails.get(e)===o&&this.orderedDispatchTails.delete(e)})}log(e,r,n){let o=`[WakeDispatcher] ${JSON.stringify({event:r,...n})}`;if(e==="error"){console.error(o);return}console.info(o)}};Zr();var gs=class{resolve(e){let r=nm(e);if(!(!r?.provider||!r.target))return{channel:r.provider,target:r.target,accountId:r.accountId,threadId:r.threadId,sessionKey:r.sessionKey}}summary(e){if(!e)return"system";let r=e.accountId?`|${e.accountId}`:"",n=e.threadId?`#${e.threadId}`:"";return`${e.channel}${r}|${e.target}${n}`}};import{randomUUID as HI}from"crypto";function zI(){return process.env.OPENCLAW_CODE_AGENT_DISCORD_SDK_MODULE_URL??"openclaw/plugin-sdk/discord"}var hs=class{discordComponentSenderPromise=null;buildChatSendArgs(e,r,n){return["gateway","call","chat.send","--expect-final","--timeout","30000","--params",JSON.stringify({sessionKey:e,message:r,deliver:n,idempotencyKey:HI()})]}buildDirectNotificationArgs(e,r,n){let o=["message","send","--channel",e.channel,"--target",e.target,"--message",r];return e.accountId&&o.push("--account",e.accountId),e.threadId&&o.push("--thread-id",e.threadId),n&&e.channel==="telegram"&&o.push("--buttons",JSON.stringify(n.map(i=>i.map(s=>({text:s.label,callback_data:s.callbackData.startsWith(`${lr}:`)?s.callbackData:`${lr}:${s.callbackData}`}))))),o}prefixCallbackData(e){return e.startsWith(`${lr}:`)?e:`${lr}:${e}`}resolveDiscordButtonStyle(e){let r=e.trim().toLowerCase();return r==="approve"||r==="open pr"?"primary":r==="merge"||r==="resume"?"success":r==="reject"||r==="discard"?"danger":"secondary"}buildDiscordComponentSpec(e){let r=[];for(let n of e)if(!(!Array.isArray(n)||n.length===0))for(let o=0;o<n.length;o+=5){let i=n.slice(o,o+5);r.push({type:"actions",buttons:i.map(s=>({label:s.label,callbackData:this.prefixCallbackData(s.callbackData),style:this.resolveDiscordButtonStyle(s.label)}))})}return{blocks:r}}resolveDiscordComponentTarget(e){let r=e.threadId?.trim();return r?`channel:${r}`:e.target}async loadDiscordComponentSender(){return this.discordComponentSenderPromise||(this.discordComponentSenderPromise=import(zI()).then(e=>{if(typeof e.sendDiscordComponentMessage!="function")throw new Error("OpenClaw Discord component sender export is unavailable");return e.sendDiscordComponentMessage}).catch(e=>{throw this.discordComponentSenderPromise=null,e})),this.discordComponentSenderPromise}async sendDiscordComponents(e,r){await(await this.loadDiscordComponentSender())(this.resolveDiscordComponentTarget(e),this.buildDiscordComponentSpec(r),e.accountId?{accountId:e.accountId}:void 0)}buildSystemEventArgs(e){return["system","event","--text",e,"--mode","now"]}};var Ss=class{routes=new gs;transport=new hs;executor=new fs;clearPendingRetries(){this.executor.clearPendingRetries()}clearRetryTimersForSession(e){this.executor.clearRetryTimersForSession(e)}dispose(){this.executor.dispose()}sendWake(e,r,n,o,i,s){let d=this.routes.resolve(e)?.sessionKey?.trim();if(!d){this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-system`,sessionId:e.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:e.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:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",onSuccess:s,onFinalFailure:i})}})}sendUserNotification(e,r,n,o,i,s){let a=!!(o&&o.length>0),d=this.routes.resolve(e),l=d?`notify:${d.channel}|${d.accountId??""}|${d.target}|${d.threadId??""}`:`notify:system:${e.id}`;if(!d){if(a){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${e.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:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",orderingKey:l,onSuccess:s,onFinalFailure:i});return}if(a&&d.channel==="discord"){let m=()=>{this.executor.executePromise(()=>this.transport.sendDiscordComponents(d,o),{label:`${n}-notify-components`,sessionId:e.id,target:"discord.components",phase:"notify",routeSummary:this.routes.summary(d),messageKind:"notify",onSuccess:s,onFinalFailure:()=>{console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${e.id} failed Discord component delivery.`),i?.()}})};if(r){this.executor.execute(this.transport.buildDirectNotificationArgs(d,r),{label:`${n}-notify-text`,sessionId:e.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(d),messageKind:"notify",orderingKey:l,onSuccess:m,onFinalFailure:i});return}m();return}this.executor.execute(this.transport.buildDirectNotificationArgs(d,r,o),{label:`${n}-notify`,sessionId:e.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(d),messageKind:"notify",orderingKey:l,onSuccess:s,onFinalFailure:()=>{if(a){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${e.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:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",orderingKey:l,onSuccess:s,onFinalFailure:i})}})}sendUserNotificationSequence(e,r,n,o,i){let s=r.map(d=>({text:d.text.trim(),buttons:d.buttons})).filter(d=>d.text.length>0);if(s.length===0){o?.();return}let a=d=>{let l=s[d];if(!l){i?.();return}let m=d===0?o:i;this.sendUserNotification(e,l.text,`${n}-part-${d+1}`,l.buttons,m,()=>a(d+1))};a(0)}dispatchSessionNotification(e,r){let n=r.hooks,o=r.wakeMessageOnNotifySuccess!=null||r.wakeMessageOnNotifyFailed!=null,i=r.notifyUser??(r.wakeMessage?"on-wake-fallback":"always"),s=(r.userMessages?.length?r.userMessages:r.userMessage?.trim()?[{text:r.userMessage.trim(),buttons:r.buttons}]:[]).map(l=>({text:l.text.trim(),buttons:l.buttons})).filter(l=>l.text.length>0),a=s[0]?.text,d=r.wakeMessage?.trim();if(o){let l=r.wakeMessageOnNotifySuccess?.trim(),m=r.wakeMessageOnNotifyFailed?.trim(),S=v=>{v&&(n?.onWakeStarted?.(),this.sendWake(e,v,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded))},y=()=>{n?.onNotifySucceeded?.(),l&&S(l)},f=m?()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.(),S(m)}:()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()};s.length>0?(n?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,r.label,f,y)):f();return}i==="always"&&s.length>0&&(n?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,r.label,()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()},()=>n?.onNotifySucceeded?.())),d&&(n?.onWakeStarted?.(),i==="on-wake-fallback"&&s.length>0&&!this.routes.resolve(e)?.sessionKey&&(n?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,r.label,()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()},()=>n?.onNotifySucceeded?.())),this.sendWake(e,d,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded))}};var ys=class{constructor(e,r){this.actionTokens=e;this.isGitHubCliAvailable=r}actionTokens;isGitHubCliAvailable;createActionToken(e,r,n={}){return this.actionTokens.createActionToken(e,r,{expiresAt:Date.now()+10080*60*1e3,...n})}consumeActionToken(e){return this.actionTokens.consumeActionToken(e)}getActionToken(e){return this.actionTokens.getActionToken(e)}clearPlanDecisionTokens(e,r){this.actionTokens.deletePlanDecisionTokensForSession(e,r)}makeActionButton(e,r,n,o={}){let i=this.createActionToken(e,r,{label:n,...o});return{label:n,callbackData:i.id}}getWorktreeDecisionButtons(e,r){if(!r)return[];let n=[],o=[this.makeActionButton(e,"worktree-merge","Merge")];if(this.isGitHubCliAvailable())r.worktreePrUrl?(o.push(this.makeActionButton(e,"worktree-view-pr","View PR",{targetUrl:r.worktreePrUrl})),n.push(o),n.push([this.makeActionButton(e,"worktree-update-pr","Sync PR"),this.makeActionButton(e,"worktree-decide-later","Later")])):(o.push(this.makeActionButton(e,"worktree-create-pr","Open PR")),n.push(o),n.push([this.makeActionButton(e,"worktree-decide-later","Later"),this.makeActionButton(e,"worktree-dismiss","Discard")]));else return n.push([...o,this.makeActionButton(e,"worktree-decide-later","Later")]),n.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),n;return r.worktreePrUrl&&n.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),n}getPlanApprovalButtons(e,r){return[[this.makeActionButton(e,"plan-approve","Approve",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(e,"plan-request-changes","Revise",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(e,"plan-reject","Reject",{planDecisionVersion:r?.planDecisionVersion})]]}getResumeButtons(e,r){let n=[];return r.isExplicitlyResumable&&n.push(this.makeActionButton(e,"session-resume","Resume")),n.push(this.makeActionButton(e,"view-output","View output")),[n]}getQuestionButtons(e,r){if(r.length!==0)return[r.map((n,o)=>this.makeActionButton(e,"question-answer",n.label,{optionIndex:o}))]}getMonitorReportButtons(e){let{reportId:r,route:n,planName:o,planPrompt:i,planWorkdir:s}=e;return[[this.makeActionButton(r,"monitor-start-plan","Start Plan",{route:n,launchName:o,launchPrompt:i,launchWorkdir:s}),this.makeActionButton(r,"monitor-dismiss","Dismiss",{route:n})]]}};ke();var ks=class{constructor(e,r){this.wakeDispatcher=e;this.applyPersistedPatch=r}wakeDispatcher;applyPersistedPatch;dispatch(e,r){let n=this.getDeliveryRef(e),o=this.buildCompletionWakePatch(r),i=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifySuccess?.trim()),s=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifyFailed?.trim()),a={onNotifyStarted:()=>{this.applyDeliveryState(n,"notifying"),r.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{this.applyDeliveryState(n,i?"wake_pending":"idle"),r.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{this.applyDeliveryState(n,s?"wake_pending":"failed"),r.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyPersistedPatchWithCompletionWake(n,"wake_pending",o,{completionWakeIssuedAt:new Date().toISOString(),completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0}),r.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{this.applyPersistedPatchWithCompletionWake(n,"idle",o,{completionWakeSucceededAt:new Date().toISOString(),completionWakeFailedAt:void 0}),r.hooks?.onWakeSucceeded?.()},onWakeFailed:()=>{this.applyPersistedPatchWithCompletionWake(n,"failed",o,{completionWakeFailedAt:new Date().toISOString()}),r.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(e,{...r,hooks:a})}notifyWorktreeOutcome(e,r){this.dispatch(e,{label:"worktree-outcome",userMessage:r,notifyUser:"always"})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(e){return re(e)??$(e)??""}applyDeliveryState(e,r){!e||!r||this.applyPersistedPatch(e,{deliveryState:r})}applyPersistedPatchWithCompletionWake(e,r,n,o){!e||!r||this.applyPersistedPatch(e,n?{deliveryState:r,...n,...o}:{deliveryState:r})}buildCompletionWakePatch(e){if(e.label==="completed")return{completionWakeSummaryRequired:!0}}};ut();import{existsSync as QI}from"fs";var vs=class{getCompletionState(e,r,n,o){return _d(e,n,o)?"has-commits":_d(e,o,n)?"base-advanced":an(r)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(e,r,n){if(!e.worktreePath||!e.workdir||!QI(e.worktreePath)||e.pendingWorktreeDecisionSince||e.worktreeState==="pending_decision")return!1;let o=e.worktreeMergedAt??e.worktreeDismissedAt??e.completedAt??e.createdAt,i=typeof o=="string"?new Date(o).getTime():Number(o??0);return!!i&&r-i>=n}};var Ps=class{constructor(e,r,n,o){this.pendingQuestions=e;this.dispatchSessionNotification=r;this.clearWaitingTimestamp=n;this.getQuestionButtons=o}pendingQuestions;dispatchSessionNotification;clearWaitingTimestamp;getQuestionButtons;async handleAskUserQuestion(e,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(e.id,a),l=`\u2753 [${e.name}] ${s.question}`,m=[`[ASK USER QUESTION] Session "${e.name}" has a question requiring user input.`,"",`Question: ${s.question}`,...a.length>0?["Options:",...a.map((S,y)=>` ${y+1}. ${S.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
150
+ `);return new Promise((S,y)=>{let f=setTimeout(()=>{this.pendingQuestions.delete(e.id),y(new Error(`AskUserQuestion timed out after 600s for session "${e.name}"`))},6e5);f.unref?.(),this.pendingQuestions.set(e.id,{resolve:S,reject:y,questions:i,timeoutHandle:f}),this.dispatchSessionNotification(e,{label:"ask-user-question",userMessage:l,notifyUser:"always",buttons:d,wakeMessageOnNotifySuccess:["AskUserQuestion delivered to the user.",`Session: ${e.name} | ID: ${e.id}`,`Question: ${s.question}`,"Await their selection \u2014 do NOT answer this question yourself."].join(`
151
+ `),wakeMessageOnNotifyFailed:m})})}resolveAskUserQuestion(e,r){let n=this.pendingQuestions.get(e);if(!n){console.warn(`[SessionQuestionService] resolveAskUserQuestion: no pending question for session "${e}"`);return}clearTimeout(n.timeoutHandle),this.pendingQuestions.delete(e);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(e),n.resolve({behavior:"allow",updatedInput:{questions:n.questions,answers:{[o.question]:s.label}}})}dispose(){for(let e of this.pendingQuestions.values())clearTimeout(e.timeoutHandle),e.reject(new Error("SessionManager disposed before AskUserQuestion resolved."));this.pendingQuestions.clear()}};function JI(t){if(t.requestedPermissionMode==="plan"){if(t.approvalExecutionState==="approved_then_implemented"){if(t.planApproval==="ask"&&t.approvalPromptStatus==="delivered"&&t.approvalPromptMessageKind==="canonical_buttons"&&t.approvalPromptDeliveredAt)return"Approval interpretation: canonical Approve/Revise/Reject buttons were delivered, and implementation after approval was expected.";if(t.approvalState==="approved")return"Approval interpretation: explicit plan approval was recorded before implementation, so leaving plan-only mode was expected."}if(t.approvalExecutionState==="implemented_without_required_approval")return"Approval interpretation: implementation left plan-only mode without a recorded approval."}}function ws(t){let e=JI(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function io(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"}}function YI(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function Xd(t){let{sessionId:e,canonicalStatusDetail:r,canonicalStatusDelivered:n=!0}=t;return["[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${e}', 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. ${r??(n?"The plugin already sent the canonical completion status to the user.":"The plugin did not confirm delivery of the canonical completion status to the user.")}`,"4. Unless you are silently continuing an internal multi-phase pipeline or there is still no meaningful confirmed outcome to report, you must send the user a short factual completion summary for this completed session.","5. This requirement applies to ordinary terminal/manual completions too, not just delegated worktree decisions.","6. That follow-up belongs to you alone; keep it brief, concrete, and grounded in reliable result data.",...n?["7. Do NOT repeat the plugin's status line, and do NOT rely on the plugin to summarize the completed work for you."]:["7. Because canonical status delivery was not confirmed, account for that gap yourself when you follow up; do NOT assume the plugin already reached the user."]]}function XI(t){let{contract:e,canonicalStatusDelivered:r}=t;return["Completion diagnostics:",`- Canonical completion status delivered to user: ${r?"yes":"no"}`,`- Plugin requested short factual follow-up summary: ${e.requiresShortFactualSummary?"yes":"no"}`,`- Contract applies to ordinary terminal/manual completions: ${e.appliesToOrdinaryTerminalCompletions?"yes":"no"}`]}function Zd(t){let{session:e,originThreadLine:r,preview:n}=t,o=`$${(e.costUsd??0).toFixed(2)}`,i=It(e.duration),s=YI(),a=d=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,r,...ws(e),"","Output preview:",n,"",...XI({contract:s,canonicalStatusDelivered:d}),"",...Xd({sessionId:e.id,canonicalStatusDelivered:d})].join(`
152
+ `);return{userMessage:`\u2705 [${e.name}] Completed | ${o} | ${i}`,wakeMessageOnNotifySuccess:a(!0),wakeMessageOnNotifyFailed:a(!1),followupContract:s}}function el(t){let{session:e,originThreadLine:r,errorSummary:n,preview:o,worktreeAutoCleaned:i,failedButtons:s}=t,a=o.trim()?["","Output preview:",o]:[],d=i?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[],l=`$${(e.costUsd??0).toFixed(2)}`,m=It(e.duration);return{userMessage:[`\u274C [${e.name}] Failed | ${l} | ${m}`,` \u26A0\uFE0F ${n}`].join(`
153
+ `),wakeMessage:["Coding agent session failed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,r,...ws(e),...e.harnessSessionId?[`Backend conversation ID: ${e.harnessSessionId}`]:[],"","Failure summary:",n,...a,...d,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${e.id}', full=true) to inspect the full failure context.`,`2. Continue the same session with agent_respond(session='${e.id}', message='<next instruction>').`,` If you intentionally want to fork or switch harnesses, launch a new session with agent_launch(resume_session_id='${e.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(`
154
+ `),buttons:s}}function tl(t){let{session:e,originThreadLine:r,preview:n}=t,o=`$${(e.costUsd??0).toFixed(2)}`;return{userMessage:`\u23F8\uFE0F [${e.name}] Turn completed | ${o}`,wakeMessage:["Coding agent session turn ended.",`Name: ${e.name}`,`ID: ${e.id}`,`Status: ${e.status}`,`Lifecycle: ${e.lifecycle}`,"","Last output (~20 lines):",n,...r?["",r]:[]].join(`
155
+ `)}}function rl(t){let{sessionName:e,sessionId:r,branchName:n,baseBranch:o,promptSnippet:i,commitLines:s,moreNote:a,diffSummary:d}=t;return[`[DELEGATED WORKTREE DECISION] Session "${e}" 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="${e}", 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(`
156
+ `)}function nl(t,e){return[`[DELEGATED WORKTREE DECISION REMINDER] Session "${t.name}" still has an unresolved worktree decision.`,"",`Session ID: ${t.sessionId??t.harnessSessionId}`,`Branch: ${t.worktreeBranch??"unknown"}`,`Pending: ${e}h`,"","Resolve it now:",`- agent_merge(session="${t.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(`
157
+ `)}function ol(t){let{sessionName:e,sessionId:r,cleanupSummary:n,preview:o,originThreadLine:i,requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:m,approvalPromptStatus:S,approvalPromptMessageKind:y,approvalPromptDeliveredAt:f}=t,v=o.trim()?["","Output preview:",o]:[];return["Coding agent session completed with no repository changes.",`Name: ${e} | ID: ${r}`,`Worktree outcome: ${n}`,...i?[i]:[],...ws({requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:m,approvalPromptStatus:S,approvalPromptMessageKind:y,approvalPromptDeliveredAt:f}),...v,"",...Xd({sessionId:r,canonicalStatusDetail:"The plugin already sent the canonical completion status to the user, including that no repo changes were kept."})].join(`
158
+ `)}function il(t){let e=[],r=t.changedFiles.slice(0,3).map(o=>`\`${o}\``);if(r.length>0){let o=t.changedFiles.length-r.length;e.push(o>0?`Touches ${r.join(", ")} and ${o} more file${o===1?"":"s"}`:`Touches ${r.join(", ")}`)}let n=[...new Set(t.commitMessages.map(o=>o.message.trim()).filter(Boolean))].slice(0,2);return n.length>0&&e.push(`Recent work: ${n.join("; ")}`),e}var wg=3200,sl=3e3,ZI=2400,eb=120,tb=5,rb=280,vg=1400,Pg="- Additional plan details omitted for brevity.";function Ig(t){return t.replace(/^#{1,6}\s+/,"").replace(/^[-*+]\s+/,"").replace(/^\d+[.)]\s+/,"").replace(/^`([^`]+)`$/,"$1").trim()}function nb(t){return t.split(`
159
+ `).map(e=>e.trim()).filter(Boolean).map(Ig).map(e=>Fe(e,220)).filter(e=>e.length>0).filter(e=>!/^(plan|proposed plan|implementation plan|review summary|full plan)[:]?$/i.test(e)).filter(e=>!/^(should|can|could|would|will)\b.*\?$/i.test(e)).filter(e=>!/^(thinking|checking|considering|analyzing)\b/i.test(e))}function ob(t){return t.split(`
160
+ `).map(e=>e.trim()).filter(Boolean).map(Ig).filter(e=>e.length>0).filter(e=>!/^(plan|proposed plan|implementation plan|review summary|summary|why this was escalated|full plan)[:]?$/i.test(e)).filter(e=>!/^(should|can|could|would|will)\b.*\?$/i.test(e)).filter(e=>!/^(thinking|checking|considering|analyzing)\b/i.test(e))}function al(t){let e=nb(t);return e.length===0?`Review summary:
161
+ - Plan details are available in the full session output.`:["Review summary:",...e.slice(0,6).map(r=>`- ${r}`)].join(`
162
+ `)}function ib(t){let e=[],r=!1;for(let o of t){let i=o.replace(/\s+/g," ").trim();if(!i)continue;let s=Fe(i,rb);s.length<i.length&&(r=!0);let a=`- ${s}`;if(e.length>=tb||[...e,a].join(`
163
+ `).length>vg){r=!0;break}e.push(a)}if(e.length===0)return["- Plan details are available in the full session output."];if(!r)return e;let n=[...e];for(;n.length>0&&[...n,Pg].join(`
164
+ `).length>vg;)n.pop();return[...n,Pg]}function dl(t){return ib(ob(t)).join(`
165
+ `)}function sb(t,e){let r=[],n=t.trim();for(;n.length>e;){let o=n.lastIndexOf(" ",e);o<Math.floor(e*.6)&&(o=e),r.push(n.slice(0,o).trimEnd()),n=n.slice(o).trimStart()}return n.length>0&&r.push(n),r}function ab(t,e){let r=t.split(`
166
+ `),n=[],o="",i=()=>{o.trim().length>0&&(n.push(o.trimEnd()),o="")};for(let s of r){if(s.length>e){i();for(let d of sb(s,e))n.push(d);continue}let a=o.length>0?`${o}
167
+ ${s}`:s;if(a.length>e){i(),o=s;continue}o=a}return i(),n}function bg(t){return Fe(t.trim(),eb)}function xg(t,e){return e?t?`
168
+
169
+ Choose Approve, Revise, or Reject below.`:`
170
+
171
+ Approval is still pending for this plan version.`:`
172
+
173
+ Continued in next message.`}function db(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=`\u{1F4CB} [${e}] Plan v${r??"?"} ready for approval:`,s=`
174
+
175
+ Full plan (truncated):
176
+ `,a=xg(o,!0),d=Math.max(0,sl-i.length-s.length-a.length);return`${i}${s}${Fe(n,d)}${a}`}function lb(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=bg(e),s=ZI;for(;s>0;){let a=ab(n,s),d=a.map((S,y)=>{let f=a.length,v=[`\u{1F4CB} [${i}] Plan v${r??"?"} ready for approval (${y+1}/${f}):`,"",y===0?"Full plan:":""].filter(Boolean).join(`
177
+ `),A=xg(o,y===f-1);return`${v}
178
+ ${S}${A}`}),l=d.reduce((S,y)=>Math.max(S,y.length),0);if(l<=sl)return d;let m=l-sl;s-=Math.max(m,50)}return[db({sessionName:i,actionableVersion:r,fullPlanText:n,hasButtons:o})]}function ll(t){let{preview:e,artifact:r}=t,n=r?.markdown?.trim();return n&&n.length<=wg?`Full plan:
179
+ ${n}`:al(n||e)}function Ag(t){let{sessionName:e,actionableVersion:r,preview:n,artifact:o,hasButtons:i}=t,s=o?.markdown?.trim(),a=bg(e);if(s){let l=`\u{1F4CB} [${a}] Plan v${r??"?"} ready for approval:
180
+
181
+ Full plan:
182
+ ${s}
183
+
184
+ ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`;return l.length<=wg?{displayMode:"single-full-plan",userMessages:[l],reviewSummary:`Full plan:
185
+ ${s}`}:{displayMode:"chunked-full-plan",userMessages:lb({sessionName:e,actionableVersion:r,fullPlanText:s,hasButtons:i}),reviewSummary:al(s)}}let d=al(n);return{displayMode:"summary",userMessages:[`\u{1F4CB} [${a}] Plan v${r??"?"} ready for approval:
186
+
187
+ ${d}
188
+
189
+ ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`],reviewSummary:d}}function ub(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function so(t){let{session:e,summary:r}=t,n=e.actionablePlanDecisionVersion??e.planDecisionVersion;return[`\u{1F4CB} [${e.name}] Plan v${n??"?"} needs your decision.`,"","Interactive Approve / Revise / Reject buttons could not be delivered, so reply here instead:",'- Reply "approve" to approve and start implementation','- Reply "reject" to reject and stop the session',"- Any other reply will be sent back as revision feedback","","Why this was escalated:","",r].join(`
190
+ `)}function ul(t){let{session:e,preview:r,planArtifact:n,originThreadLine:o,planApprovalMode:i,planApprovalButtons:s,questionButtons:a}=t,d=e.pendingPlanApproval,l=e.actionablePlanDecisionVersion??e.planDecisionVersion,m=ub(e,l),S=i??"delegate",y=d&&S==="ask"&&!m?Ag({sessionName:e.name,actionableVersion:l,preview:r,artifact:n,hasButtons:!!s}):void 0,f=d?y?.reviewSummary??ll({preview:r,artifact:n}):void 0,v=d?y&&y.userMessages.length===1?y.userMessages[0]:void 0:`\u2753 [${e.name}] Question waiting for reply:
191
+
192
+ ${r}`,A=d&&y&&y.userMessages.length>1?y.userMessages.map((w,C,b)=>({text:w,buttons:C===b.length-1?s:void 0})):void 0;if(d){let w=S,C="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return w==="delegate"?{label:"plan-approval",userMessage:v,userMessages:A,planReviewSummary:f,wakeMessage:["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${e.name} | ID: ${e.id} | Plan v${l??"?"}`,o,C,"","\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='${e.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.","If you approve directly, you own the user-facing explanation of what was approved and why.","Keep it short and user-facing: one sentence is usually enough.","","\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='${e.id}', message='Approved. Go ahead.', approve=true, approval_rationale='<brief reason>').`,"That rationale should say why approval was safe: for example scope match, low risk, or no meaningful ambiguity.","After approving directly, send the user a short plain-text follow-up explaining what was approved and why.","The plugin's thumbs-up line is only the minimal approval acknowledgment, not the explanation.",`If escalating: call agent_request_plan_approval(session='${e.id}', summary='...') exactly once so the plugin posts the single canonical Approve / Revise / Reject prompt.`,"That summary must concisely explain why this was escalated, plus 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='${e.id}', message='<your feedback>') and do NOT set approve=true. The agent will revise the plan.`].join(`
193
+ `)}:w==="ask"?{label:"plan-approval",userMessage:v,userMessages:A,planReviewSummary:f,wakeMessage:["[USER APPROVAL REQUESTED] Coding agent session has finished its plan. The user has been notified via Telegram and must approve directly.",`Name: ${e.name} | ID: ${e.id} | Plan v${l??"?"}`,o,C,"","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='${e.id}', message='Approved. Go ahead.', approve=true)`,` To request changes: agent_respond(session='${e.id}', message='<user feedback>')`,"","Preview (truncated):",r].join(`
194
+ `),buttons:A?void 0:s}:{label:"plan-approval",userMessage:v,planReviewSummary:f,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`].join(`
195
+ `)}}let x=e.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:v,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.]`,"",`${x} is waiting for a genuine user reply.`,`Name: ${e.name} | ID: ${e.id}`,o,"","Last output:",r,"",`Use agent_respond(session='${e.id}', message='...') to send a reply, or agent_output(session='${e.id}', full: true) to see full context before deciding.`].join(`
196
+ `),buttons:a}}ke();var Is=class t{constructor(e,r,n,o){this.buildRoutingProxy=e;this.dispatchNotification=r;this.updatePersistedSession=n;this.getWorktreeDecisionButtons=o}buildRoutingProxy;dispatchNotification;updatePersistedSession;getWorktreeDecisionButtons;static REMINDER_THRESHOLD_MS=10800*1e3;static REMINDER_INTERVAL_MS=10800*1e3;getNextReminderAt(e){if(!e.pendingWorktreeDecisionSince)return;let r=e.worktreeState==="pending_decision"||e.lifecycle==="awaiting_worktree_decision",n=e.worktreeState==null&&e.lifecycle==null&&!e.worktreeMerged&&!e.worktreePrUrl;if(!r&&!n)return;let o=new Date(e.pendingWorktreeDecisionSince).getTime();if(!Number.isFinite(o))return;let i=[o+t.REMINDER_THRESHOLD_MS];if(e.worktreeDecisionSnoozedUntil){let s=new Date(e.worktreeDecisionSnoozedUntil).getTime();Number.isFinite(s)&&i.push(s)}if(e.lastWorktreeReminderAt){let s=new Date(e.lastWorktreeReminderAt).getTime();Number.isFinite(s)&&i.push(s+t.REMINDER_INTERVAL_MS)}return Math.max(...i)}sendReminderIfDue(e,r=Date.now()){let n=this.getNextReminderAt(e);if(n==null||n>r)return!1;let o=r-new Date(e.pendingWorktreeDecisionSince).getTime(),i=Math.floor(Math.max(0,o)/(3600*1e3));try{this.sendReminderNotification(e,i)}catch(s){return console.warn(`[SessionReminderService] Failed to send stale-decision reminder for session ${e.name}: ${s instanceof Error?s.message:String(s)}`),!1}for(let s of et(e))this.updatePersistedSession(s,{lastWorktreeReminderAt:new Date(r).toISOString()});return!0}sendReminderNotification(e,r){let n=this.buildRoutingProxy({id:e.sessionId??e.name??$(e)??e.harnessSessionId,sessionId:e.sessionId,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef,route:e.route});if(e.worktreeStrategy==="delegate"){this.dispatchNotification(n,{label:`worktree-stale-reminder-${e.name}`,wakeMessage:nl(e,r),notifyUser:"never"});return}let o=[`\u23F0 Reminder: branch \`${e.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${e.name} | Pending: ${r}h`,"",`agent_merge(session="${e.name}") or agent_pr(session="${e.name}") or agent_worktree_cleanup() to resolve.`].join(`
197
+ `);this.dispatchNotification(n,{label:`worktree-stale-reminder-${e.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(re(e)??e.harnessSessionId)})}};ut();ke();import{existsSync as pb,readFileSync as cb}from"fs";function Rg(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function mb(t,e){if(t.latestPlanArtifactVersion===e&&t.latestPlanArtifact)return t.latestPlanArtifact;let r=t.planFilePath?.trim();if(!(!r||!pb(r)))try{let n=cb(r,"utf-8").trim();return n?{markdown:n,steps:[]}:void 0}catch{return}}var bs=class{constructor(e){this.deps=e}deps;buildPlanApprovalWakeText(e,r,n=!1){return[n?"Plan review fallback text delivered to the user because interactive buttons could not be delivered.":"Plan approval buttons delivered to the user.",`Session: ${e.name} | ID: ${e.id} | Plan v${r??"?"}`,`Wait for their ${n?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
198
+ `)}buildPlanApprovalDeliveryFailureWake(e,r){return["[PLAN APPROVAL DELIVERY FAILED] The plugin could not deliver the canonical plan review buttons or the explicit fallback text to the user.",`Name: ${e.name} | ID: ${e.id} | Plan v${r??"?"}`,this.deps.originThreadLine(e),"","No user-visible actionable review prompt is confirmed for this plan version.","Intervene manually before assuming the user saw the plan review request."].join(`
199
+ `)}dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",userMessage:so({session:e,summary:n}),notifyUser:"always",hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"failed",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,r,!0),wakeMessageOnNotifyFailed:this.buildPlanApprovalDeliveryFailureWake(e,r)})}logCompletionWakeDiagnostic(e){console.info(JSON.stringify({event:e.event,sessionId:e.session.id,sessionName:e.session.name,canonicalStatusDelivered:e.canonicalStatusDelivered,requestedShortFactualSummary:e.followupSummaryRequired,completionKind:"terminal"}))}handleTurnEnd(e,r){if(e.status!=="running"){console.info(`[SessionManager] Suppressing turn-end wake for session ${e.id} (status=${e.status}) \u2014 terminal notification owns the completion path.`);return}if(!e.goalTaskId){if(r||e.pendingPlanApproval){this.emitWaitingForInput(e);return}if(e.worktreeStrategy==="ask"||e.worktreeStrategy==="delegate"){console.info(`[SessionManager] Suppressing turn-complete wake for session ${e.id} (worktreeStrategy=${e.worktreeStrategy}) \u2014 worktree notification will follow.`);return}this.deps.shouldEmitTurnCompleteWake(e)&&this.emitTurnComplete(e)}}async handleSessionTerminal(e){if(this.deps.persistSession(e),this.deps.clearWaitingTimestamp(e.id),e.goalTaskId){this.deps.clearRetryTimersForSession(e.id);return}let r={notificationSent:!1,worktreeRemoved:!1};e.worktreePath&&e.originalWorkdir&&(r=await this.deps.handleWorktreeStrategy(e));let n=!1;if(e.worktreePath&&e.originalWorkdir&&e.status==="failed"&&e.costUsd===0&&e.duration<3e4){let a=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),d=e.worktreeBranch,l=Ne(e);console.info(`[SessionManager] Early startup failure for "${e.name}" \u2014 auto-cleaning worktree (cost=$${e.costUsd.toFixed(2)}, duration=${e.duration}ms)`);let m=!1;if(a&&!l&&(m=tt(a,e.worktreePath)),a&&d&&!l&&m&&$t(a,d),m){for(let S of et(e))this.deps.updatePersistedSession(S,{worktreePath:void 0,worktreeBranch:void 0});n=!0}}let o=e.worktreeStrategy&&e.worktreeStrategy!=="off"&&e.worktreeStrategy!=="manual";if(!n&&e.worktreePath&&e.originalWorkdir){let a=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),d=Ne(e);r.worktreeRemoved?console.info(`[SessionManager] Worktree already removed for "${e.name}" during strategy handling.`):o?console.info(`[SessionManager] Keeping worktree alive for "${e.name}" (strategy=${e.worktreeStrategy}) \u2014 will be cleaned up on explicit resolution.`):a&&!d&&tt(a,e.worktreePath)}if(e.killReason==="done"){if(r.notificationSent||this.deps.hasTurnCompleteWakeMarker(e.id)||!this.deps.shouldEmitTerminalWake(e))return;this.emitCompleted(e);return}if(e.status==="completed"){if(!this.deps.shouldEmitTerminalWake(e))return;this.emitCompleted(e);return}if(e.status==="failed"){if(!this.deps.shouldEmitTerminalWake(e))return;let a=e.error||e.result?.is_error&&e.result.result||e.result?.result||this.deps.extractLastOutputLine(e)||`Session failed with no error details (session=${e.id}, subtype=${e.result?.subtype??"none"}, turns=${e.result?.num_turns??0})`;this.emitFailed(e,Fe(a,200),n);return}let i=`$${(e.costUsd??0).toFixed(2)}`,s=e.duration;if(e.killReason==="idle-timeout"){let a=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0;if(e.pendingPlanApproval){let d=e.actionablePlanDecisionVersion??e.planDecisionVersion,l=Rg(e,d);if(a==="delegate"){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",wakeMessage:["[DELEGATED PLAN APPROVAL REMINDER] Plan review is still pending after the session hit idle timeout.",`Name: ${e.name} | ID: ${e.id}`,this.deps.originThreadLine(e),"The agent already produced a plan and is waiting for a delegated decision.","Review privately first. Approve directly with agent_respond(..., approve=true, approval_rationale='...') if the plan is clearly within scope and low risk.","Escalate only if needed via agent_request_plan_approval(summary='...').","If you approve directly, follow up with a short user-facing explanation; the plugin's thumbs-up line is only the minimal approval acknowledgment.","If a canonical approval prompt was already posted for this plan version, do not restate it in plain text."].join(`
200
+ `),notifyUser:"never"}),this.deps.clearRetryTimersForSession(e.id);return}if(a==="ask"&&l){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",notifyUser:"never",wakeMessage:["[PLAN APPROVAL REMINDER] The user already has an actionable plan review prompt for this plan version.",`Name: ${e.name} | ID: ${e.id} | Plan v${d??"?"}`,this.deps.originThreadLine(e),"Do NOT post another approval summary unless canonical delivery is known to be missing."].join(`
201
+ `)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",userMessage:[`\u{1F4CB} [${e.name}] Plan v${d??"?"} still awaiting approval after idle timeout | ${i} | ${It(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(`
202
+ `),notifyUser:"always",buttons:a==="ask"&&!l?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:d}):void 0}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.dispatchSessionNotification(e,{label:"suspended",userMessage:`\u{1F4A4} [${e.name}] Suspended after idle timeout | ${i} | ${It(s)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(e.id,e)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.notifySession(e,`\u26D4 [${e.name}] ${io(e.killReason)} | ${i} | ${It(s)}`),this.deps.clearRetryTimersForSession(e.id)}emitWaitingForInput(e){if(!this.deps.debounceWaitingEvent(e.id))return;let r=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0,n=e.actionablePlanDecisionVersion??e.planDecisionVersion,o=e.pendingPlanApproval&&r==="ask"&&Rg(e,n),i=!e.pendingPlanApproval&&e.pendingInputState?.promptText?e.pendingInputState.promptText:this.deps.getOutputPreview(e,e.pendingPlanApproval&&r!=="delegate"?Number.POSITIVE_INFINITY:void 0),s=e.pendingPlanApproval&&r==="ask"&&!o?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:n}):!e.pendingPlanApproval&&e.pendingInputState?.options.length?this.deps.getQuestionButtons(e.id,e.pendingInputState.options.map(m=>({label:m}))):void 0,a=mb(e,n),d=ul({session:e,preview:i,planArtifact:a,originThreadLine:this.deps.originThreadLine(e),planApprovalMode:r,planApprovalButtons:s,questionButtons:e.pendingPlanApproval?void 0:s}),l=d.planReviewSummary??i;if(d.label==="plan-approval"&&r==="ask"&&o){this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,userMessages:d.userMessages,notifyUser:"never",buttons:d.buttons,wakeMessage:d.wakeMessage});return}if(d.label==="plan-approval"&&r==="ask"){this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,userMessages:d.userMessages,notifyUser:"always",buttons:d.buttons,hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"sending",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{canonicalPlanPromptVersion:n,approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"failed",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,n,l),wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,n)});return}if(d.label==="plan-approval"){this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,wakeMessage:d.wakeMessage,notifyUser:"never",buttons:d.buttons});return}this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,notifyUser:"always",buttons:d.buttons,wakeMessageOnNotifyFailed:d.wakeMessage})}emitTurnComplete(e){console.info(`[SessionManager] turn-complete wake dispatching for session ${e.id} (turns=${e.result?.num_turns??0}, strategy=${e.worktreeStrategy??"none"})`);let r=tl({session:e,originThreadLine:this.deps.originThreadLine(e),preview:this.deps.getOutputPreview(e)});this.deps.dispatchSessionNotification(e,{label:"turn-complete",userMessage:r.userMessage,wakeMessage:r.wakeMessage,notifyUser:"always",onUserNotifyFailed:()=>{console.warn(`[SessionManager] turn-complete delivery failed for session ${e.id} \u2014 firing terminal notification as fallback`),this.deps.shouldEmitTerminalWake(e)&&this.emitCompleted(e)}})}emitCompleted(e){let r=this.deps.getOutputPreview(e),n=Zd({session:e,originThreadLine:this.deps.originThreadLine(e),preview:r}),o;this.deps.dispatchSessionNotification(e,{label:"completed",userMessage:n.userMessage,notifyUser:"always",wakeMessageOnNotifySuccess:n.wakeMessageOnNotifySuccess,wakeMessageOnNotifyFailed:n.wakeMessageOnNotifyFailed,hooks:{onNotifySucceeded:()=>{o=!0,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_succeeded",canonicalStatusDelivered:o,followupSummaryRequired:n.followupContract.requiresShortFactualSummary})},onNotifyFailed:()=>{o=!1,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_failed",canonicalStatusDelivered:o,followupSummaryRequired:n.followupContract.requiresShortFactualSummary})},onWakeSucceeded:()=>{this.logCompletionWakeDiagnostic({session:e,event:"completion_wake_succeeded",canonicalStatusDelivered:o,followupSummaryRequired:n.followupContract.requiresShortFactualSummary})}}})}emitFailed(e,r,n){let o=el({session:e,originThreadLine:this.deps.originThreadLine(e),errorSummary:r,preview:this.deps.getOutputPreview(e),worktreeAutoCleaned:n,failedButtons:this.deps.getResumeButtons(e.id,e)});this.deps.dispatchSessionNotification(e,{label:"failed",userMessage:o.userMessage,wakeMessage:o.wakeMessage,notifyUser:"always",buttons:o.buttons})}};ke();ut();import{existsSync as fb}from"fs";var xs=class{constructor(e){this.deps=e}deps;async dismissWorktree(e){let r=this.deps.getPersistedSession(e),n=this.deps.resolveActiveSession(e),o=n??r;if(!o)return`Error: Session "${e}" 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??e;if(!s)return`Error: No workdir found for session "${e}".`;let l=Ne(o);!l&&i&&fb(i)&&tt(s,i,{destructive:!0}),a&&$t(s,a);for(let S of et(n??r))this.deps.updatePersistedSession(S,{worktreeDisposition:"dismissed",worktreeDismissedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,worktreeState:"dismissed",lifecycle:"terminal",worktreePath:void 0,worktreeBranch:void 0,worktreeLifecycle:{state:"dismissed",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"dismiss",baseBranch:r?.worktreeLifecycle?.baseBranch,targetRepo:r?.worktreePrTargetRepo,pushRemote:r?.worktreePushRemote}});let m=l?`\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:re(n??r??{id:e})??e,sessionId:r?.sessionId,harnessSessionId:n?.harnessSessionId??r?.harnessSessionId,backendRef:n?.backendRef??r?.backendRef,route:n?.route??r?.route}),{label:"worktree-dismissed",userMessage:m,notifyUser:"always"}),m}snoozeWorktreeDecision(e){let r=this.deps.getPersistedSession(e);if(!r)return`Error: Session "${e}" not found.`;let n=new Date(Date.now()+1440*60*1e3).toISOString();for(let s of et(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:re(r)??$(r)??r.harnessSessionId,sessionId:r.sessionId,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route}),{label:"worktree-snoozed",userMessage:i,notifyUser:"always"}),i}};var Tg=new Set(["starting","running"]),As=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>Tg.has(e.status)).length}uniqueName(e){let r=new Set([...this.sessions.values()].filter(o=>Tg.has(o.status)).map(o=>o.name));if(!r.has(e))return e;let n=2;for(;r.has(`${e}-${n}`);)n+=1;return`${e}-${n}`}add(e){this.sessions.set(e.id,e)}remove(e){this.sessions.delete(e)}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()]}};var Rs=class{constructor(e){this.deps=e}deps;initializeSession(e,r,n,o={}){if(this.deps.hydrateSpawnedSession(e,r,n),e.on("statusChange",(i,s)=>{s==="running"&&e.harnessSessionId?this.deps.markRunning(e):(s==="completed"||s==="failed"||s==="killed")&&this.deps.handleTerminal(e).catch(a=>{console.error(`[SessionRuntimeBootstrap] handleTerminal threw for session ${e.id}:`,a)})}),e.on("turnEnd",(i,s)=>{this.deps.handleTurnEnd(e,s)}),e.start(),o.notifyLaunch!==!1){let i=this.deps.formatLaunchWorkdirLabel(e),s=`\u{1F680} [${e.name}] Launched | ${i} | ${e.model??"default"}`;this.deps.notifySession(e,s,"launch")}return e}};var Ts=class{buildNoChangeNotification(e){let{session:r,nativeBackendWorktree:n,cleanupSucceeded:o,worktreePath:i,preview:s,originThreadLine:a}=e,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:ol({sessionName:r.name,sessionId:r.id,cleanupSummary:d,preview:s,originThreadLine:a,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,approvalExecutionState:r.approvalExecutionState,approvalState:r.approvalState,planApproval:r.planApproval,approvalPromptStatus:r.approvalPromptStatus,approvalPromptMessageKind:r.approvalPromptMessageKind,approvalPromptDeliveredAt:r.approvalPromptDeliveredAt}),notifyUser:"always"}}buildAskNotification(e){let{session:r,branchName:n,baseBranch:o,diffSummary:i,buttons:s}=e,a=il(i),d=i.commitMessages.slice(0,5).map(S=>`\u2022 ${S.hash} ${S.message} (${S.author})`),l=i.commits>5?`...and ${i.commits-5} more`:"",m=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}\``,"",m,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"",...a.length>0?["Summary:",...a.map(S=>`- ${S}`),""]:[],"Recent commits:",...d,...l?[l]:[],"",`\u26A0\uFE0F Discard will permanently delete branch \`${n}\` and all local changes. This cannot be undone.`].join(`
203
+ `),notifyUser:"always",buttons:s,wakeMessageOnNotifySuccess:["Worktree decision buttons delivered to the user.",`Session: ${r.name} | ID: ${r.id}`,m,"Wait for their button callback \u2014 do NOT act on this worktree yourself."].join(`
204
+ `),wakeMessageOnNotifyFailed:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",m,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
205
+ `)}}buildDelegateNotification(e){let{session:r,branchName:n,baseBranch:o,diffSummary:i}=e,s=i.commitMessages.slice(0,5).map(l=>`\u2022 ${l.hash} ${l.message} (${l.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:rl({sessionName:r.name,sessionId:r.id,branchName:n,baseBranch:o,promptSnippet:d,commitLines:s,moreNote:a,diffSummary:i}),notifyUser:"never"}}};$i();ut();var Ms=class t{timers=new Map;disposed=!1;static MAX_DELAY_MS=2147483647;schedule(e,r,n){if(this.disposed)return;this.cancel(e);let o=Math.max(0,r-Date.now()),i=setTimeout(()=>{if(this.timers.delete(e),!this.disposed){if(r-Date.now()>0){this.schedule(e,r,n);return}n()}},Math.min(o,t.MAX_DELAY_MS));i.unref?.(),this.timers.set(e,i)}cancel(e){let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}cancelPrefix(e){for(let r of this.timers.keys())r.startsWith(e)&&this.cancel(r)}dispose(){this.disposed=!0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};import{unlinkSync as gb}from"fs";var Mg=new Set(["completed","failed","killed"]),hb=new Set(["starting","running"]),Sb=5e3,Cg=10080*60*1e3,yb=300*1e3,_g="tmp-output:cleanup",Cs=class{registry;sessions;maxSessions;maxPersistedSessions;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;maintenance=new Ms;constructor(e=20,r=50,n={}){this.maxSessions=e,this.maxPersistedSessions=r,this.registry=new As,this.sessions=this.registry.sessions,this.store=new ps(n.store),this.metrics=new cs,this.wakeDispatcher=new Ss,this.interactions=new ys(this.store.actionTokenStore,ir),this.references=new ts(this.sessions,this.store),this.stateSync=new es({store:this.store,sessions:this.sessions,resolveSession:o=>this.references.resolveActive(o)}),this.notifications=new ks(this.wakeDispatcher,(o,i)=>this.stateSync.applySessionPatch(o,i)),this.store.onActionTokensChanged(()=>this.syncActionTokenExpiryDeadline()),this.worktrees=new vs,this.restore=new Zi(o=>this.store.getPersistedSession(o)),this.worktreeMessages=new Ts,this.worktreeStrategy=new os({shouldRunWorktreeStrategy:o=>this.shouldRunWorktreeStrategy(o),isAlreadyMerged:o=>this.isAlreadyMerged(o),resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),getWorktreeCompletionState:(o,i,s,a)=>this.getWorktreeCompletionState(o,i,s,a),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),dispatchSessionNotification:(o,i)=>this.dispatchSessionNotification(o,i),getOutputPreview:(o,i)=>this.getOutputPreview(o,i),originThreadLine:o=>this.originThreadLine(o),getWorktreeDecisionButtons:o=>this.getWorktreeDecisionButtons(o),makeOpenPrButton:o=>this.makeActionButton(o,"worktree-create-pr","Open PR"),worktreeMessages:this.worktreeMessages,enqueueMerge:(o,i,s)=>this.enqueueMerge(o,i,s),mergeBranch:Ci,spawnConflictResolver:async({session:o,worktreePath:i,prompt:s})=>this.spawn({prompt:s,workdir:i,name:`${o.name}-conflict-resolver`,harness:o.harnessName||Pe(),model:o.model,reasoningEffort:o.reasoningEffort,permissionMode:"bypassPermissions",multiTurn:!0,worktreeStrategy:"off",autoMergeParentSessionId:o.id,route:o.route,originChannel:o.originChannel,originThreadId:o.originThreadId,originAgentId:o.originAgentId,originSessionKey:o.originSessionKey},{notifyLaunch:!1}),runAutoPr:async(o,i)=>{let{makeAgentPrTool:s}=await Promise.resolve().then(()=>(Gi(),Rf));return{success:(await s().execute("auto-pr",{session:o.id,base_branch:i}))?.meta?.success===!0}}}),this.questions=new Ps(this.pendingAskUserQuestions,(o,i)=>this.dispatchSessionNotification(o,i),o=>{this.lastWaitingEventTimestamps.delete(o)},(o,i)=>this.interactions.getQuestionButtons(o,i)),this.reminders=new Is(o=>this.buildRoutingProxy(o),(o,i)=>this.notifications.dispatch(o,i),(o,i)=>this.updatePersistedSession(o,i),o=>this.getWorktreeDecisionButtons(o)),this.lifecycle=new bs({persistSession:o=>this.persistSession(o),clearWaitingTimestamp:o=>{this.lastWaitingEventTimestamps.delete(o)},handleWorktreeStrategy:o=>this.handleWorktreeStrategy(o),resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),dispatchSessionNotification:(o,i)=>this.dispatchSessionNotification(o,i),notifySession:(o,i,s)=>this.notifySession(o,i,s),clearRetryTimersForSession:o=>this.wakeDispatcher.clearRetryTimersForSession(o),hasTurnCompleteWakeMarker:o=>this.lastTurnCompleteMarkers.has(o),shouldEmitTurnCompleteWake:o=>this.shouldEmitTurnCompleteWake(o),shouldEmitTerminalWake:o=>this.shouldEmitTerminalWake(o),resolvePlanApprovalMode:o=>this.resolvePlanApprovalMode(o),getPlanApprovalButtons:(o,i)=>this.interactions.getPlanApprovalButtons(o,i),getResumeButtons:(o,i)=>this.interactions.getResumeButtons(o,i),getQuestionButtons:(o,i)=>this.interactions.getQuestionButtons(o,i),extractLastOutputLine:o=>this.extractLastOutputLine(o),getOutputPreview:(o,i)=>this.getOutputPreview(o,i),originThreadLine:o=>this.originThreadLine(o),debounceWaitingEvent:o=>this.debounceWaitingEvent(o),isAlreadyMerged:o=>this.isAlreadyMerged(o)}),this.worktreeDecisions=new xs({getPersistedSession:o=>this.store.getPersistedSession(o),resolveActiveSession:o=>this.references.resolveActive(o),resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),dispatchNotification:(o,i)=>this.notifications.dispatch(o,i),buildRoutingProxy:o=>this.buildRoutingProxy(o)}),this.runtimeBootstrap=new Rs({hydrateSpawnedSession:(o,i,s)=>{this.restore.hydrateSpawnedSession(o,i,s)},markRunning:o=>{this.store.markRunning(o),this.onPersistedSessionChanged(this.store.getPersistedSession(o.id))},handleTerminal:async o=>this.onSessionTerminal(o),handleTurnEnd:(o,i)=>this.onTurnEnd(o,i),formatLaunchWorkdirLabel:o=>this.formatLaunchWorkdirLabel(o),notifySession:(o,i,s)=>this.notifySession(o,i,s)})}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(e){return this.registry.uniqueName(e)}persistedMaintenanceRef(e){return e.sessionId??$(e)??e.harnessSessionId}runtimeGcKey(e){return`runtime-gc:${e}`}persistedMaintenanceKey(e,r){return`persisted:${e}:${r}`}runtimeGcMaxAgeMs(){return(_.sessionGcAgeMinutes??1440)*6e4}syncRuntimeGcDeadline(e){if(!e.completedAt)return;let r=this.runtimeGcKey(e.id);this.maintenance.schedule(r,e.completedAt+this.runtimeGcMaxAgeMs(),()=>{let n=this.sessions.get(e.id);if(!n||!n.completedAt)return;let o=this.runtimeGcMaxAgeMs();if(!this.store.shouldGcActiveSession(n,Date.now(),o)){this.syncRuntimeGcDeadline(n);return}this.registry.remove(e.id),this.persistSession(n,{scheduleRuntimeGc:!1}),this.lastWaitingEventTimestamps.delete(e.id),this.lastTurnCompleteMarkers.delete(e.id),this.lastTerminalWakeMarkers.delete(e.id)})}cancelPersistedMaintenance(e){let r=this.persistedMaintenanceRef(e);r&&this.maintenance.cancelPrefix(`persisted:${r}:`)}onPersistedSessionChanged(e){e&&(this.syncPersistedSessionMaintenance(e),this.enforcePersistedRetention())}isLegacyResolvedWorktree(e){return e.worktreeMerged===!0||e.worktreeDisposition==="dismissed"||e.worktreeDisposition==="no-change-cleaned"||e.worktreeState==="merged"||e.worktreeState==="dismissed"}syncPersistedSessionMaintenance(e){let r=this.persistedMaintenanceRef(e);if(!r)return;this.maintenance.cancel(this.persistedMaintenanceKey(r,"worktree-reminder"));let n=this.reminders.getNextReminderAt(e);n!=null&&this.schedulePersistedWorktreeReminder(r,n),this.maintenance.cancel(this.persistedMaintenanceKey(r,"worktree-retention"));let o=Zn(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),i=e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0),s=this.isLegacyResolvedWorktree(e);if((o.cleanupSafe||s)&&typeof i=="string"){let a=new Date(i).getTime();Number.isFinite(a)&&this.maintenance.schedule(this.persistedMaintenanceKey(r,"worktree-retention"),a+Cg,()=>{let d=this.store.getPersistedSession(r);d&&this.reconcileResolvedWorktreeRetention(d,Date.now())})}}schedulePersistedWorktreeReminder(e,r){let n=this.persistedMaintenanceKey(e,"worktree-reminder");this.maintenance.schedule(n,r,()=>{let o=this.store.getPersistedSession(e);if(!o||this.reminders.sendReminderIfDue(o,Date.now()))return;let s=this.reminders.getNextReminderAt(o);s!=null&&this.schedulePersistedWorktreeReminder(e,Math.max(s,Date.now()+yb))})}reconcileResolvedWorktreeRetention(e,r){let n=Zn(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),o=e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0),i=o?new Date(o).getTime():0,s=this.isLegacyResolvedWorktree(e);if(!(!n.cleanupSafe&&!s||!i||r-i<Cg))try{if(!e.worktreePath&&!Ne(e))return;let a=this.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!a)return;let d=Ne(e)?!1:tt(a,e.worktreePath);if(!Ne(e)&&!d)return;for(let l of et(e))this.updatePersistedSession(l,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeLifecycle:{...e.worktreeLifecycle??n.lifecycle,state:n.derivedState,updatedAt:new Date(r).toISOString(),resolvedAt:e.worktreeLifecycle?.resolvedAt??new Date(r).toISOString(),resolutionSource:e.worktreeLifecycle?.resolutionSource??"maintenance",notes:n.reasons}})}catch(a){console.warn(`[SessionManager] Failed maintenance cleanup for worktree ${e.worktreePath}: ${a instanceof Error?a.message:String(a)}`)}}syncActionTokenExpiryDeadline(){let e="tokens:expiry";this.maintenance.cancel(e);let r=this.store.getNextActionTokenExpiry();r!=null&&this.maintenance.schedule(e,r,()=>{this.store.purgeExpiredActionTokens(Date.now())})}syncTmpOutputCleanupDeadline(e=Date.now()){this.maintenance.cancel(_g);let r=this.store.getNextTmpOutputCleanupAt(e);r!=null&&this.maintenance.schedule(_g,r,()=>{let n=Date.now();this.store.cleanupTmpOutputFiles(n),this.syncTmpOutputCleanupDeadline(n)})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.store.hasOutputPathReference(e)))try{gb(e)}catch{}}enforcePersistedRetention(){let e=this.store.evictOldestPersisted(this.maxPersistedSessions);for(let r of e)this.cancelPersistedMaintenance(r),r.sessionId&&this.maintenance.cancel(this.runtimeGcKey(r.sessionId)),this.cleanupOutputPathIfUnreferenced(r.outputPath)}bootstrapMaintenanceSchedules(){let e=Date.now();this.store.cleanupTmpOutputFiles(e);for(let r of this.store.listPersistedSessions())this.syncPersistedSessionMaintenance(r);this.syncActionTokenExpiryDeadline(),this.store.cleanupOrphanOutputFiles(),this.syncTmpOutputCleanupDeadline(e)}disposeMaintenance(){this.maintenance.dispose()}spawn(e,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(e.sessionIdOverride){let y=this.registry.get(e.sessionIdOverride);if(y?.status==="starting"||y?.status==="running")throw new Error(`Cannot reuse session ID ${e.sessionIdOverride}: that session is still ${y.status}.`);y&&this.registry.remove(y.id),this.lastWaitingEventTimestamps.delete(e.sessionIdOverride),this.lastTurnCompleteMarkers.delete(e.sessionIdOverride),this.lastTerminalWakeMarkers.delete(e.sessionIdOverride),this.maintenance.cancel(this.runtimeGcKey(e.sessionIdOverride))}let o=e.name||uf(e.prompt),i=this.uniqueName(o);if(i!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${i}" (active session with same name exists)`),!e.route?.provider||!e.route.target)throw new Error(`Cannot launch session "${i}": missing explicit route metadata.`);let s=this.restore.prepareSpawn(e,i),a=e.harness??"claude-code",d=this,l,m=a==="claude-code"&&!e.canUseTool?async(y,f)=>{if(!l)throw new Error("canUseTool called before session ID was set");return d.handleAskUserQuestion(l,f)}:e.canUseTool,S=new Oi({...e,workdir:s.actualWorkdir,systemPrompt:s.effectiveSystemPrompt,canUseTool:m},i);return l=S.id,this.registry.add(S),this.metrics.incrementLaunched(),this.runtimeBootstrap.initializeSession(S,s,e,r)}async spawnAndAwaitRunning(e,r={}){let n=this.spawn(e,r);return await this.waitForRunningSession(n),n}async waitForRunningSession(e){if(e.status==="running")return;if(Mg.has(e.status))throw new Error(this.describeLaunchFailure(e));let r=e.on?.bind(e),n=e.off?.bind(e)??e.removeListener?.bind(e);if(!r||!n)throw new Error(`Session ${e.name} [${e.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(d,l)=>{if(l==="running"){a(),o();return}Mg.has(l)&&(a(),i(new Error(this.describeLaunchFailure(e))))},a=()=>{n("statusChange",s)};r("statusChange",s)})}describeLaunchFailure(e){let r=e.killReason?` (reason: ${e.killReason})`:"",n=e.error||e.result?.result||`status=${e.status}${r}`;return`Session ${e.name} [${e.id}] failed to start: ${n}`}formatLaunchResult(e,r){return ti({prompt:e.prompt,workdir:e.workdir,harness:e.harness,permissionMode:e.permissionMode??_.permissionMode,planApproval:e.planApproval,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,forceNewSession:e.forceNewSession,clearedPersistedCodexResume:e.clearedPersistedCodexResume},r)}shouldRunWorktreeStrategy(e){let r=e.lifecycle;return!(r==="starting"||r==="awaiting_plan_decision"||r==="awaiting_user_input"||e.pendingPlanApproval)}makeActionButton(e,r,n,o={}){return this.interactions.makeActionButton(e,r,n,o)}consumeActionToken(e){return this.interactions.consumeActionToken(e)}getActionToken(e){return this.interactions.getActionToken(e)}clearPlanDecisionTokens(e,r){this.interactions.clearPlanDecisionTokens(e,r)}hasProvablePlanReviewPrompt(e,r){return r!=null&&e.approvalPromptRequiredVersion===r&&(e.approvalPromptStatus==="delivered"||e.approvalPromptStatus==="fallback_delivered")}buildPlanApprovalWakeText(e,r,n=!1){return[n?"Plan review fallback text delivered to the user because interactive buttons could not be delivered.":"Plan approval buttons delivered to the user.",`Session: ${e.name} | ID: ${e.id} | Plan v${r??"?"}`,`Wait for their ${n?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
206
+ `)}buildPlanApprovalDeliveryFailureWake(e,r){return["[PLAN APPROVAL DELIVERY FAILED] The plugin could not deliver the canonical plan review buttons or the explicit fallback text to the user.",`Name: ${e.name} | ID: ${e.id} | Plan v${r??"?"}`,e.originThreadId!=null?`Origin thread: ${e.originThreadId}`:"","","No user-visible actionable review prompt is confirmed for this plan version.","Intervene manually before assuming the user saw the plan review request."].filter(Boolean).join(`
207
+ `)}dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",userMessage:so({session:e,summary:n}),notifyUser:"always",hooks:{onNotifyStarted:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"failed",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,r,!0),wakeMessageOnNotifyFailed:this.buildPlanApprovalDeliveryFailureWake(e,r)})}getWorktreeDecisionButtons(e){let r=this.resolve(e)??this.getPersistedSession(e);if(!(!r||r.worktreeStrategy==="delegate"))return this.interactions.getWorktreeDecisionButtons(e,r)}getWorktreeCompletionState(e,r,n,o){return this.worktrees.getCompletionState(e,r,n,o)}notifyWorktreeOutcome(e,r){this.notifications.notifyWorktreeOutcome(e,r)}requestPlanApprovalFromUser(e,r){let n=r.trim();if(!n)return"Error: summary must not be empty.";let o=dl(n),i=this.resolve(e),s=i?void 0:this.getPersistedSession(e),a=i??s;if(!a)return`Error: Session "${e}" not found.`;if(!a.pendingPlanApproval)return`Error: Session "${e}" is not awaiting plan approval.`;let d=re(i??s??{id:e})??e;if(this.resolvePlanApprovalMode(a)!=="delegate")return`Error: Session "${e}" already uses direct user plan approval. Do not send a duplicate approval prompt.`;let l=a.actionablePlanDecisionVersion??a.planDecisionVersion;if(this.hasProvablePlanReviewPrompt(a,l))return[`An actionable plan review prompt already exists for session ${a.name} [${d}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ");if(a.deliveryState==="notifying")return[`A plan approval prompt is already being delivered for session ${a.name} [${d}].`,"Wait for delivery to finish before retrying."].join(" ");let m=this.interactions.getPlanApprovalButtons(d,{...a,planDecisionVersion:l}),S=[`\u{1F4CB} [${a.name}] Plan v${l??"?"} needs your decision:`,"","Why this was escalated:","",o,"","Choose Approve, Revise, or Reject below."].join(`
208
+ `);return this.notifications.dispatch(this.buildRoutingProxy({id:d,name:a.name,sessionId:s?.sessionId,harnessSessionId:i?.harnessSessionId??s?.harnessSessionId,backendRef:i?.backendRef??s?.backendRef,route:i?.route??s?.route}),{label:"plan-approval",userMessage:S,notifyUser:"always",buttons:m,hooks:{onNotifyStarted:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptStatus:"sending",approvalPromptVersion:l,approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.updatePersistedSession(d,{canonicalPlanPromptVersion:l,approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"failed",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(this.buildRoutingProxy({id:d,name:a.name,sessionId:s?.sessionId,harnessSessionId:i?.harnessSessionId??s?.harnessSessionId,backendRef:i?.backendRef??s?.backendRef,route:i?.route??s?.route}),l,o),wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText({id:d,name:a.name},l)}),[`Canonical plan approval prompt sent for session ${a.name} [${d}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ")}buildRoutingProxy(e){return{id:re(e)??$(e)??e.harnessSessionId??"unknown-session",name:e.name,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef?{...e.backendRef}:void 0,route:e.route}}resolveWorktreeRepoDir(e,r){return e&&(!r||!Xi(e,r))||!r?e:xi(r)??e}formatLaunchWorkdirLabel(e){if(!e.worktreePath)return e.workdir;let r=this.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath);return!r||r===e.worktreePath?e.worktreePath:`${e.worktreePath} (worktree of ${r})`}async dismissWorktree(e){return this.worktreeDecisions.dismissWorktree(e)}snoozeWorktreeDecision(e){return this.worktreeDecisions.snoozeWorktreeDecision(e)}async handleWorktreeStrategy(e){return this.worktreeStrategy.handleWorktreeStrategy(e)}async onSessionTerminal(e){if(e.autoMergeParentSessionId){await this.handleAutoMergeResolverTerminal(e);return}return this.lifecycle.handleSessionTerminal(e)}async handleAutoMergeResolverTerminal(e){this.persistSession(e),this.lastWaitingEventTimestamps.delete(e.id),this.wakeDispatcher.clearRetryTimersForSession(e.id);let r=e.autoMergeParentSessionId;if(!r)return;let n=this.resolve(r),o=this.getPersistedSession(r),i=n??(o?this.buildRoutingProxy({id:o.sessionId,name:o.name,sessionId:o.sessionId,harnessSessionId:o.harnessSessionId,backendRef:o.backendRef,route:o.route}):void 0);if(!i){console.warn(`[SessionManager] Auto-merge resolver ${e.id} completed, but original session ${r} could not be found.`);return}if(e.status==="completed"&&n){this.updatePersistedSession(r,{autoMergeResolverSessionId:void 0}),await this.handleWorktreeStrategy(n);return}let s=n?.worktreeBranch??o?.worktreeBranch??"unknown",a=n?.worktreePath??o?.worktreePath??"(unknown worktree)",d=n?.worktreeBaseBranch??o?.worktreeBaseBranch,l=n?.worktreePrTargetRepo??o?.worktreePrTargetRepo,m=n?.worktreePushRemote??o?.worktreePushRemote;this.updatePersistedSession(r,ns({worktreeBaseBranch:d,worktreePrTargetRepo:l,worktreePushRemote:m},{clearResolverSessionId:!0,notes:[e.status==="completed"?"auto_merge_conflict_resolver_completed_without_retry_target":"auto_merge_conflict_resolver_failed"]})),this.dispatchSessionNotification(i,{label:"worktree-merge-conflict-resolver-failed",userMessage:[`\u26A0\uFE0F [${i.name}] Auto-merge conflict resolution did not complete successfully.`,`Branch \`${s}\` was preserved for manual follow-up in ${a}.`,e.status==="completed"?"The resolver finished, but the original session could not be resumed for the merge retry.":`Resolver session ${e.name} ended with status=${e.status}.`].join(`
209
+ `),buttons:[[this.makeActionButton(r,"worktree-create-pr","Open PR")]]})}getStoppedStatusLabel(e){return io(e)}persistSession(e,r={}){let n=r.scheduleRuntimeGc??!0;this.store.hasRecordedSession(e.id)||this.metrics.recordSession(e),this.store.persistTerminal(e),n&&this.syncRuntimeGcDeadline(e),this.onPersistedSessionChanged(this.store.getPersistedSession(e.id)),this.syncTmpOutputCleanupDeadline()}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(e){this.metrics.recordSession(e)}notifySession(e,r,n="notification"){this.dispatchSessionNotification(e,{label:n,userMessage:r,notifyUser:"always"})}sendMonitorReport(e){let r=this.interactions.getMonitorReportButtons({reportId:e.reportId,route:e.route,planName:e.planName,planPrompt:e.planPrompt,planWorkdir:e.planWorkdir});this.dispatchSessionNotification(this.buildRoutingProxy({id:e.reportId,route:e.route}),{label:"monitor-report",userMessage:e.text,notifyUser:"always",buttons:r})}emitGoalTaskUpdate(e,r,n="goal-task"){let o=this.buildRoutingProxy({id:e.sessionId??e.id,route:e.route});o.originChannel=e.originChannel,o.originThreadId=e.originThreadId,o.originSessionKey=e.originSessionKey,this.dispatchSessionNotification(o,{label:n,userMessage:r,notifyUser:"always"})}launchMonitorPlan(e){let r=e.route??{provider:"system",target:"system"};return this.spawn({prompt:e.prompt,workdir:e.workdir,name:e.name,harness:Pe(),permissionMode:"plan",planApproval:"ask",worktreeStrategy:"off",multiTurn:!0,route:r,originChannel:this.originChannelFromRoute(r),originThreadId:r.threadId,originSessionKey:r.sessionKey})}dispatchSessionNotification(e,r){this.notifications.dispatch(e,r)}originChannelFromRoute(e){return e.accountId?`${e.provider}|${e.accountId}|${e.target}`:`${e.provider}|${e.target}`}debounceWaitingEvent(e){let r=Date.now(),n=this.lastWaitingEventTimestamps.get(e);return n&&r-n<Sb?!1:(this.lastWaitingEventTimestamps.set(e,r),!0)}originThreadLine(e){return e.originThreadId!=null?`Session origin thread: ${e.originThreadId}`:""}extractLastOutputLine(e){return e.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(e,r=1e3){let n=!Number.isFinite(r),o=typeof e.getOutput=="function"?e.getOutput():[],i=n?o.join(`
210
+ `):this.selectCompletionPreviewSource(e);return n?i:i.length>r?this.shouldPreferTailPreview(e)?cf(i,r):mf(i,r):i}selectCompletionPreviewSource(e){let r=typeof e.getOutput=="function"?e.getOutput():[],n=r.join(`
211
+ `).trim();return n?this.shouldPreferTailPreview(e)?this.extractLastSubstantiveBlock(n)??n:r.slice(-20).join(`
212
+ `):""}shouldPreferTailPreview(e){if(e.status==="completed"||e.killReason==="done")return!0;let r=e;return r.approvalState==="approved"||r.planModeApproved===!0||(r.planDecisionVersion??0)>0}extractLastSubstantiveBlock(e){let n=e.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(`
213
+ `)?n:void 0}triggerAgentEvent(e){this.lifecycle.emitCompleted(e)}triggerFailedEvent(e,r,n=!1){this.lifecycle.emitFailed(e,r,n)}triggerWaitingForInputEvent(e){this.lifecycle.emitWaitingForInput(e)}resolvePlanApprovalMode(e){return e.planApproval??_.planApproval??"delegate"}onTurnEnd(e,r){this.lifecycle.handleTurnEnd(e,r)}shouldEmitTurnCompleteWake(e){let r=`${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(e.id)===r?(console.info(`[SessionManager] shouldEmitTurnCompleteWake: debounced for session ${e.id} (marker unchanged: ${r})`),!1):(this.lastTurnCompleteMarkers.set(e.id,r),!0)}shouldEmitTerminalWake(e){let r=`${e.status}|${e.completedAt??0}|${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.killReason}`;return this.lastTerminalWakeMarkers.get(e.id)===r?!1:(this.lastTerminalWakeMarkers.set(e.id,r),!0)}triggerTurnCompleteEventWithSignal(e){this.lifecycle.emitTurnComplete(e)}resolve(e){return this.references.resolveActive(e)}get(e){return this.registry.get(e)}list(e){let r=this.registry.list();return e&&e!=="all"&&(r=r.filter(n=>n.status===e)),r.sort((n,o)=>o.startedAt-n.startedAt)}kill(e,r){let n=this.registry.get(e);return n?(n.kill(r??"user"),!0):!1}killAll(e="user"){for(let r of this.sessions.values())hb.has(r.status)&&this.kill(r.id,e)}resolveBackendConversationId(e){return this.references.resolveBackendConversationId(e)}resolveHarnessSessionId(e){return this.resolveBackendConversationId(e)}getPersistedSession(e){return this.references.getPersistedSession(e)}isAlreadyMerged(e){if(!e)return!1;let r=this.store.getPersistedSession(e);return r?.worktreeMerged===!0||r?.worktreeLifecycle?.state==="merged"||r?.worktreeLifecycle?.state==="released"}async enqueueMerge(e,r,n){let o=this.mergeQueues.get(e);o!==void 0&&n&&n();let i=(o??Promise.resolve()).catch(()=>{}).then(()=>r()),s=i.catch(()=>{});return this.mergeQueues.set(e,s),s.finally(()=>{this.mergeQueues.get(e)===s&&this.mergeQueues.delete(e)}),i}updatePersistedSession(e,r){let n=this.stateSync.applySessionPatch(e,r);return n&&this.onPersistedSessionChanged(this.store.getPersistedSession(e)),n}listPersistedSessions(){return this.store.listPersistedSessions()}async handleAskUserQuestion(e,r){let n=this.sessions.get(e);if(!n)throw new Error(`Session "${e}" not found for AskUserQuestion intercept`);return this.questions.handleAskUserQuestion(n,r)}resolveAskUserQuestion(e,r){this.questions.resolveAskUserQuestion(e,r)}async resolvePendingInputOption(e,r){let n=this.sessions.get(e);return n&&await n.submitPendingInputOption(r)?(this.lastWaitingEventTimestamps.delete(e),!0):(this.questions.resolveAskUserQuestion(e,r),!0)}dispose(){this.disposeMaintenance(),this.questions.dispose(),this.notifications.dispose()}};Y();var $g;function _s(t){if(t&&typeof t=="object"){$g=t;return}$g=void 0}Re();import{definePluginEntry as Eg}from"openclaw/plugin-sdk/core";function Ib(t){let e=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"168",10)||168,r=e*60*60*1e3,n=Date.now()-r,o=new Set(t.listPersistedSessions().map(d=>d.worktreePath).filter(d=>typeof d=="string"&&d.length>0)),i=new Set,s=process.env.OPENCLAW_WORKTREE_DIR??_.worktreeDir;if(s)i.add(s);else for(let d of t.listPersistedSessions())if(d.workdir)try{let l=wb("git",["rev-parse","--show-toplevel"],{cwd:d.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();l&&i.add(Og(l,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let d of i)try{let l=kb(d);for(let m of l){if(!m.startsWith("openclaw-worktree-"))continue;let S=Og(d,m);try{let y=vb(S);if(!y.isDirectory()||y.mtimeMs>n||o.has(S))continue;Pb(S,{recursive:!0,force:!0}),a++}catch(y){console.warn(`[index] Failed to clean up orphaned worktree ${S}: ${y instanceof Error?y.message:String(y)}`)}}}catch{}a>0&&console.info(`[index] Cleaned up ${a} orphaned worktree(s) at startup (age > ${e}h)`)}function bb(t){let e=null,r=null,n=t.registerTool;_s(t.runtime),n(o=>Um(o),{optional:!1}),n(o=>Sf(o),{optional:!1}),n(o=>yf(o),{optional:!1}),n(o=>Wi(o),{optional:!1}),n(o=>wf(o),{optional:!1}),n(o=>If(o),{optional:!1}),n(o=>bf(o),{optional:!1}),n(o=>xf(o),{optional:!1}),n(o=>ji(o),{optional:!1}),n(o=>ro(o),{optional:!1}),n(o=>Tf(o),{optional:!1}),n(o=>Mf(o),{optional:!1}),n(o=>Cf(o),{optional:!1}),n(o=>$f(o),{optional:!1}),n(o=>Ef(o),{optional:!1}),t.registerInteractiveHandler(Kd("telegram")),t.registerInteractiveHandler(Kd("discord")),Of(t),Df(t),Nf(t),Ff(t),Lf(t),Wf(t),Bf(t),Uf(t),Kf(t),t.registerService({id:"openclaw-code-agent",start:o=>{let i=t.pluginConfig??{};sm(i),_s(t.runtime),e=new Cs(_.maxSessions,_.maxPersistedSessions),r=new Yi(e),hd(e),Sd(r),r.start(),Ib(e),e.bootstrapMaintenanceSchedules()},stop:()=>{r&&r.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),r=null,e=null,_s(void 0),Sd(null),hd(null)}})}var yG=Eg({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:bb});export{yG as default,bb as register};