openclaw-code-agent 4.0.1 → 4.1.1

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,27 +1,27 @@
1
- var Ug=Object.defineProperty;var u=(t,e)=>()=>(t&&(e=t(t=0)),e);var co=(t,e)=>{for(var r in e)Ug(t,r,{get:e[r],enumerable:!0})};var Me={};co(Me,{HasPropertyKey:()=>mo,IsArray:()=>pe,IsAsyncIterator:()=>Ds,IsBigInt:()=>pn,IsBoolean:()=>Dt,IsDate:()=>pr,IsFunction:()=>Ns,IsIterator:()=>Fs,IsNull:()=>Ls,IsNumber:()=>Ge,IsObject:()=>j,IsRegExp:()=>cn,IsString:()=>Q,IsSymbol:()=>Ws,IsUint8Array:()=>Nt,IsUndefined:()=>ce});function mo(t,e){return e in t}function Ds(t){return j(t)&&!pe(t)&&!Nt(t)&&Symbol.asyncIterator in t}function pe(t){return Array.isArray(t)}function pn(t){return typeof t=="bigint"}function Dt(t){return typeof t=="boolean"}function pr(t){return t instanceof globalThis.Date}function Ns(t){return typeof t=="function"}function Fs(t){return j(t)&&!pe(t)&&!Nt(t)&&Symbol.iterator in t}function Ls(t){return t===null}function Ge(t){return typeof t=="number"}function j(t){return typeof t=="object"&&t!==null}function cn(t){return t instanceof globalThis.RegExp}function Q(t){return typeof t=="string"}function Ws(t){return typeof t=="symbol"}function Nt(t){return t instanceof globalThis.Uint8Array}function ce(t){return t===void 0}var De=u(()=>{});function Kg(t){return t.map(e=>fo(e))}function Vg(t){return new Date(t.getTime())}function qg(t){return new Uint8Array(t)}function jg(t){return new RegExp(t.source,t.flags)}function Gg(t){let e={};for(let r of Object.getOwnPropertyNames(t))e[r]=fo(t[r]);for(let r of Object.getOwnPropertySymbols(t))e[r]=fo(t[r]);return e}function fo(t){return pe(t)?Kg(t):pr(t)?Vg(t):Nt(t)?qg(t):cn(t)?jg(t):j(t)?Gg(t):t}function ee(t){return fo(t)}var We=u(()=>{De()});function Or(t,e){return e===void 0?ee(t):ee({...e,...t})}var go=u(()=>{We()});var Bs=u(()=>{go();We()});function kl(t){return t!==null&&typeof t=="object"}function vl(t){return globalThis.Array.isArray(t)&&!globalThis.ArrayBuffer.isView(t)}function Pl(t){return t===void 0}function wl(t){return typeof t=="number"}var Il=u(()=>{});var xl=u(()=>{Il()});var ho,bl=u(()=>{xl();(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=kl(s);return t.AllowArrayObject?a:a&&!vl(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?wl(s):Number.isFinite(s)}t.IsNumberLike=o;function i(s){let a=Pl(s);return t.AllowNullVoid?a||s===null:a}t.IsVoidLike=i})(ho||(ho={}))});function Hg(t){return globalThis.Object.freeze(t).map(e=>mn(e))}function zg(t){let e={};for(let r of Object.getOwnPropertyNames(t))e[r]=mn(t[r]);for(let r of Object.getOwnPropertySymbols(t))e[r]=mn(t[r]);return globalThis.Object.freeze(e)}function mn(t){return pe(t)?Hg(t):pr(t)?t:Nt(t)?t:cn(t)?t:j(t)?zg(t):t}var Al=u(()=>{De()});function h(t,e){let r=e!==void 0?{...e,...t}:t;switch(ho.InstanceMode){case"freeze":return mn(r);case"clone":return ee(r);default:return r}}var T=u(()=>{bl();Al();We()});var Ft=u(()=>{T()});var we,Rl=u(()=>{we=class extends Error{constructor(e){super(e)}}});var At=u(()=>{Rl()});var ge,mt,be,rt,P,fn=u(()=>{ge=Symbol.for("TypeBox.Transform"),mt=Symbol.for("TypeBox.Readonly"),be=Symbol.for("TypeBox.Optional"),rt=Symbol.for("TypeBox.Hint"),P=Symbol.for("TypeBox.Kind")});var M=u(()=>{fn()});function Dr(t){return j(t)&&t[mt]==="Readonly"}function Be(t){return j(t)&&t[be]==="Optional"}function Us(t){return F(t,"Any")}function Ks(t){return F(t,"Argument")}function ft(t){return F(t,"Array")}function cr(t){return F(t,"AsyncIterator")}function mr(t){return F(t,"BigInt")}function Lt(t){return F(t,"Boolean")}function gt(t){return F(t,"Computed")}function ht(t){return F(t,"Constructor")}function Qg(t){return F(t,"Date")}function St(t){return F(t,"Function")}function yt(t){return F(t,"Integer")}function ie(t){return F(t,"Intersect")}function fr(t){return F(t,"Iterator")}function F(t,e){return j(t)&&P in t&&t[P]===e}function So(t){return Dt(t)||Ge(t)||Q(t)}function He(t){return F(t,"Literal")}function ze(t){return F(t,"MappedKey")}function te(t){return F(t,"MappedResult")}function Ht(t){return F(t,"Never")}function Jg(t){return F(t,"Not")}function gn(t){return F(t,"Null")}function kt(t){return F(t,"Number")}function me(t){return F(t,"Object")}function gr(t){return F(t,"Promise")}function hr(t){return F(t,"Record")}function de(t){return F(t,"Ref")}function Vs(t){return F(t,"RegExp")}function Wt(t){return F(t,"String")}function hn(t){return F(t,"Symbol")}function Qe(t){return F(t,"TemplateLiteral")}function Yg(t){return F(t,"This")}function zt(t){return j(t)&&ge in t}function Je(t){return F(t,"Tuple")}function Sn(t){return F(t,"Undefined")}function L(t){return F(t,"Union")}function Xg(t){return F(t,"Uint8Array")}function Zg(t){return F(t,"Unknown")}function eh(t){return F(t,"Unsafe")}function th(t){return F(t,"Void")}function rh(t){return j(t)&&P in t&&Q(t[P])}function Ye(t){return Us(t)||Ks(t)||ft(t)||Lt(t)||mr(t)||cr(t)||gt(t)||ht(t)||Qg(t)||St(t)||yt(t)||ie(t)||fr(t)||He(t)||ze(t)||te(t)||Ht(t)||Jg(t)||gn(t)||kt(t)||me(t)||gr(t)||hr(t)||de(t)||Vs(t)||Wt(t)||hn(t)||Qe(t)||Yg(t)||Je(t)||Sn(t)||L(t)||Xg(t)||Zg(t)||eh(t)||th(t)||rh(t)}var B=u(()=>{De();M()});var c={};co(c,{IsAny:()=>_l,IsArgument:()=>$l,IsArray:()=>El,IsAsyncIterator:()=>Ol,IsBigInt:()=>Dl,IsBoolean:()=>Nl,IsComputed:()=>Fl,IsConstructor:()=>Ll,IsDate:()=>Wl,IsFunction:()=>Bl,IsImport:()=>dh,IsInteger:()=>Ul,IsIntersect:()=>Kl,IsIterator:()=>Vl,IsKind:()=>gu,IsKindOf:()=>E,IsLiteral:()=>kn,IsLiteralBoolean:()=>lh,IsLiteralNumber:()=>jl,IsLiteralString:()=>ql,IsLiteralValue:()=>Gl,IsMappedKey:()=>Hl,IsMappedResult:()=>zl,IsNever:()=>Ql,IsNot:()=>Jl,IsNull:()=>Yl,IsNumber:()=>Xl,IsObject:()=>Zl,IsOptional:()=>ah,IsPromise:()=>eu,IsProperties:()=>yo,IsReadonly:()=>sh,IsRecord:()=>tu,IsRecursive:()=>uh,IsRef:()=>ru,IsRegExp:()=>nu,IsSchema:()=>Ie,IsString:()=>ou,IsSymbol:()=>iu,IsTemplateLiteral:()=>su,IsThis:()=>au,IsTransform:()=>du,IsTuple:()=>lu,IsUint8Array:()=>pu,IsUndefined:()=>uu,IsUnion:()=>Hs,IsUnionLiteral:()=>ph,IsUnknown:()=>cu,IsUnsafe:()=>mu,IsVoid:()=>fu,TypeGuardUnknownTypeError:()=>qs});function Tl(t){try{return new RegExp(t),!0}catch{return!1}}function js(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 Ml(t){return Gs(t)||Ie(t)}function yn(t){return ce(t)||pn(t)}function J(t){return ce(t)||Ge(t)}function Gs(t){return ce(t)||Dt(t)}function G(t){return ce(t)||Q(t)}function oh(t){return ce(t)||Q(t)&&js(t)&&Tl(t)}function ih(t){return ce(t)||Q(t)&&js(t)}function Cl(t){return ce(t)||Ie(t)}function sh(t){return j(t)&&t[mt]==="Readonly"}function ah(t){return j(t)&&t[be]==="Optional"}function _l(t){return E(t,"Any")&&G(t.$id)}function $l(t){return E(t,"Argument")&&Ge(t.index)}function El(t){return E(t,"Array")&&t.type==="array"&&G(t.$id)&&Ie(t.items)&&J(t.minItems)&&J(t.maxItems)&&Gs(t.uniqueItems)&&Cl(t.contains)&&J(t.minContains)&&J(t.maxContains)}function Ol(t){return E(t,"AsyncIterator")&&t.type==="AsyncIterator"&&G(t.$id)&&Ie(t.items)}function Dl(t){return E(t,"BigInt")&&t.type==="bigint"&&G(t.$id)&&yn(t.exclusiveMaximum)&&yn(t.exclusiveMinimum)&&yn(t.maximum)&&yn(t.minimum)&&yn(t.multipleOf)}function Nl(t){return E(t,"Boolean")&&t.type==="boolean"&&G(t.$id)}function Fl(t){return E(t,"Computed")&&Q(t.target)&&pe(t.parameters)&&t.parameters.every(e=>Ie(e))}function Ll(t){return E(t,"Constructor")&&t.type==="Constructor"&&G(t.$id)&&pe(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function Wl(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 Bl(t){return E(t,"Function")&&t.type==="Function"&&G(t.$id)&&pe(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function dh(t){return E(t,"Import")&&mo(t,"$defs")&&j(t.$defs)&&yo(t.$defs)&&mo(t,"$ref")&&Q(t.$ref)&&t.$ref in t.$defs}function Ul(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 yo(t){return j(t)&&Object.entries(t).every(([e,r])=>js(e)&&Ie(r))}function Kl(t){return E(t,"Intersect")&&!(Q(t.type)&&t.type!=="object")&&pe(t.allOf)&&t.allOf.every(e=>Ie(e)&&!du(e))&&G(t.type)&&(Gs(t.unevaluatedProperties)||Cl(t.unevaluatedProperties))&&G(t.$id)}function Vl(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 ql(t){return kn(t)&&Q(t.const)}function jl(t){return kn(t)&&Ge(t.const)}function lh(t){return kn(t)&&Dt(t.const)}function kn(t){return E(t,"Literal")&&G(t.$id)&&Gl(t.const)}function Gl(t){return Dt(t)||Ge(t)||Q(t)}function Hl(t){return E(t,"MappedKey")&&pe(t.keys)&&t.keys.every(e=>Ge(e)||Q(e))}function zl(t){return E(t,"MappedResult")&&yo(t.properties)}function Ql(t){return E(t,"Never")&&j(t.not)&&Object.getOwnPropertyNames(t.not).length===0}function Jl(t){return E(t,"Not")&&Ie(t.not)}function Yl(t){return E(t,"Null")&&t.type==="null"&&G(t.$id)}function Xl(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 Zl(t){return E(t,"Object")&&t.type==="object"&&G(t.$id)&&yo(t.properties)&&Ml(t.additionalProperties)&&J(t.minProperties)&&J(t.maxProperties)}function eu(t){return E(t,"Promise")&&t.type==="Promise"&&G(t.$id)&&Ie(t.item)}function tu(t){return E(t,"Record")&&t.type==="object"&&G(t.$id)&&Ml(t.additionalProperties)&&j(t.patternProperties)&&(e=>{let r=Object.getOwnPropertyNames(e.patternProperties);return r.length===1&&Tl(r[0])&&j(e.patternProperties)&&Ie(e.patternProperties[r[0]])})(t)}function uh(t){return j(t)&&rt in t&&t[rt]==="Recursive"}function ru(t){return E(t,"Ref")&&G(t.$id)&&Q(t.$ref)}function nu(t){return E(t,"RegExp")&&G(t.$id)&&Q(t.source)&&Q(t.flags)&&J(t.maxLength)&&J(t.minLength)}function ou(t){return E(t,"String")&&t.type==="string"&&G(t.$id)&&J(t.minLength)&&J(t.maxLength)&&oh(t.pattern)&&ih(t.format)}function iu(t){return E(t,"Symbol")&&t.type==="symbol"&&G(t.$id)}function su(t){return E(t,"TemplateLiteral")&&t.type==="string"&&Q(t.pattern)&&t.pattern[0]==="^"&&t.pattern[t.pattern.length-1]==="$"}function au(t){return E(t,"This")&&G(t.$id)&&Q(t.$ref)}function du(t){return j(t)&&ge in t}function lu(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 uu(t){return E(t,"Undefined")&&t.type==="undefined"&&G(t.$id)}function ph(t){return Hs(t)&&t.anyOf.every(e=>ql(e)||jl(e))}function Hs(t){return E(t,"Union")&&G(t.$id)&&j(t)&&pe(t.anyOf)&&t.anyOf.every(e=>Ie(e))}function pu(t){return E(t,"Uint8Array")&&t.type==="Uint8Array"&&G(t.$id)&&J(t.minByteLength)&&J(t.maxByteLength)}function cu(t){return E(t,"Unknown")&&G(t.$id)}function mu(t){return E(t,"Unsafe")}function fu(t){return E(t,"Void")&&t.type==="void"&&G(t.$id)}function gu(t){return j(t)&&P in t&&Q(t[P])&&!nh.includes(t[P])}function Ie(t){return j(t)&&(_l(t)||$l(t)||El(t)||Nl(t)||Dl(t)||Ol(t)||Fl(t)||Ll(t)||Wl(t)||Bl(t)||Ul(t)||Kl(t)||Vl(t)||kn(t)||Hl(t)||zl(t)||Ql(t)||Jl(t)||Yl(t)||Xl(t)||Zl(t)||eu(t)||tu(t)||ru(t)||nu(t)||ou(t)||iu(t)||su(t)||au(t)||lu(t)||uu(t)||Hs(t)||pu(t)||cu(t)||mu(t)||fu(t)||gu(t))}var qs,nh,hu=u(()=>{De();M();At();qs=class extends we{},nh=["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 zs=u(()=>{B();hu();De()});var Su=u(()=>{});var yu=u(()=>{Su()});var Qs,vn,Js,ch,pb,Qt,Jt,ku,vu=u(()=>{Qs="(true|false)",vn="(0|[1-9][0-9]*)",Js="(.*)",ch="(?!.*)",pb=`^${Qs}$`,Qt=`^${vn}$`,Jt=`^${Js}$`,ku=`^${ch}$`});var Pn=u(()=>{vu()});var Pu=u(()=>{});var wu=u(()=>{});var Iu=u(()=>{Pu();wu()});function xu(t,e){return t.includes(e)}function bu(t){return[...new Set(t)]}function gh(t,e){return t.filter(r=>e.includes(r))}function hh(t,e){return t.reduce((r,n)=>gh(r,n),e)}function Au(t){return t.length===1?t[0]:t.length>1?hh(t.slice(1),t[0]):[]}function Ru(t){let e=[];for(let r of t)e.push(...r);return e}var Tu=u(()=>{});var wn=u(()=>{Tu()});function Yt(t){return h({[P]:"Any"},t)}var Mu=u(()=>{Ft();M()});var In=u(()=>{Mu()});function Nr(t,e){return h({[P]:"Array",type:"array",items:t},e)}var Cu=u(()=>{T();M()});var xn=u(()=>{Cu()});function _u(t){return h({[P]:"Argument",index:t})}var $u=u(()=>{T();M()});var Ys=u(()=>{$u()});function Fr(t,e){return h({[P]:"AsyncIterator",type:"AsyncIterator",items:t},e)}var Eu=u(()=>{M();T()});var bn=u(()=>{Eu()});function Z(t,e,r){return h({[P]:"Computed",target:t,parameters:e},r)}var Ou=u(()=>{Ft();fn()});var Xt=u(()=>{Ou()});function Sh(t,e){let{[e]:r,...n}=t;return n}function se(t,e){return e.reduce((r,n)=>Sh(r,n),t)}var ko=u(()=>{});var Ut=u(()=>{ko()});function W(t){return h({[P]:"Never",not:{}},t)}var Du=u(()=>{T();M()});var Ae=u(()=>{Du()});var Nu=u(()=>{});function U(t){return h({[P]:"MappedResult",properties:t})}var Xs=u(()=>{T();M()});function Lr(t,e,r){return h({[P]:"Constructor",type:"Constructor",parameters:t,returns:e},r)}var Fu=u(()=>{T();M()});var An=u(()=>{Fu()});function Rt(t,e,r){return h({[P]:"Function",type:"Function",parameters:t,returns:e},r)}var Lu=u(()=>{T();M()});var Sr=u(()=>{Lu()});function Rn(t,e){return h({[P]:"Union",anyOf:t},e)}var Zs=u(()=>{T();M()});function yh(t){return t.some(e=>Be(e))}function Wu(t){return t.map(e=>Be(e)?kh(e):e)}function kh(t){return se(t,[be])}function vh(t,e){return yh(t)?Ce(Rn(Wu(t),e)):Rn(Wu(t),e)}function Tt(t,e){return t.length===1?h(t[0],e):t.length===0?W(e):vh(t,e)}var Bu=u(()=>{T();M();Ut();Ae();Kt();Zs();B()});var Uu=u(()=>{});function q(t,e){return t.length===0?W(e):t.length===1?h(t[0],e):Rn(t,e)}var Ku=u(()=>{Ae();T();Zs()});var he=u(()=>{Bu();Uu();Ku()});function Ph(t){return t.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function ea(t,e,r){return t[e]===r&&t.charCodeAt(e-1)!==92}function Vt(t,e){return ea(t,e,"(")}function Tn(t,e){return ea(t,e,")")}function Vu(t,e){return ea(t,e,"|")}function wh(t){if(!(Vt(t,0)&&Tn(t,t.length-1)))return!1;let e=0;for(let r=0;r<t.length;r++)if(Vt(t,r)&&(e+=1),Tn(t,r)&&(e-=1),e===0&&r!==t.length-1)return!1;return!0}function Ih(t){return t.slice(1,t.length-1)}function xh(t){let e=0;for(let r=0;r<t.length;r++)if(Vt(t,r)&&(e+=1),Tn(t,r)&&(e-=1),Vu(t,r)&&e===0)return!0;return!1}function bh(t){for(let e=0;e<t.length;e++)if(Vt(t,e))return!0;return!1}function Ah(t){let[e,r]=[0,0],n=[];for(let i=0;i<t.length;i++)if(Vt(t,i)&&(e+=1),Tn(t,i)&&(e-=1),Vu(t,i)&&e===0){let s=t.slice(r,i);s.length>0&&n.push(Wr(s)),r=i+1}let o=t.slice(r);return o.length>0&&n.push(Wr(o)),n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"or",expr:n}}function Rh(t){function e(o,i){if(!Vt(o,i))throw new vo("TemplateLiteralParser: Index must point to open parens");let s=0;for(let a=i;a<o.length;a++)if(Vt(o,a)&&(s+=1),Tn(o,a)&&(s-=1),s===0)return[i,a];throw new vo("TemplateLiteralParser: Unclosed group parens in expression")}function r(o,i){for(let s=i;s<o.length;s++)if(Vt(o,s))return[i,s];return[i,o.length]}let n=[];for(let o=0;o<t.length;o++)if(Vt(t,o)){let[i,s]=e(t,o),a=t.slice(i,s+1);n.push(Wr(a)),o=s}else{let[i,s]=r(t,o),a=t.slice(i,s);a.length>0&&n.push(Wr(a)),o=s-1}return n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"and",expr:n}}function Wr(t){return wh(t)?Wr(Ih(t)):xh(t)?Ah(t):bh(t)?Rh(t):{type:"const",const:Ph(t)}}function Br(t){return Wr(t.slice(1,t.length-1))}var vo,Po=u(()=>{At();vo=class extends we{}});function Th(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 Mh(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 Ch(t){return t.type==="const"&&t.const===".*"}function yr(t){return Th(t)||Ch(t)?!1:Mh(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 ta("Unknown expression type")})()}function qu(t){let e=Br(t.pattern);return yr(e)}var ta,ra=u(()=>{Po();At();ta=class extends we{}});function*ju(t){if(t.length===1)return yield*t[0];for(let e of t[0])for(let r of ju(t.slice(1)))yield`${e}${r}`}function*_h(t){return yield*ju(t.expr.map(e=>[...Mn(e)]))}function*$h(t){for(let e of t.expr)yield*Mn(e)}function*Eh(t){return yield t.const}function*Mn(t){return t.type==="and"?yield*_h(t):t.type==="or"?yield*$h(t):t.type==="const"?yield*Eh(t):(()=>{throw new na("Unknown expression")})()}function wo(t){let e=Br(t.pattern);return yr(e)?[...Mn(e)]:[]}var na,oa=u(()=>{ra();Po();At();na=class extends we{}});function V(t,e){return h({[P]:"Literal",const:t,type:typeof t},e)}var Gu=u(()=>{T();M()});var Ue=u(()=>{Gu()});function Io(t){return h({[P]:"Boolean",type:"boolean"},t)}var Hu=u(()=>{M();Ft()});var xo=u(()=>{Hu()});function Ur(t){return h({[P]:"BigInt",type:"bigint"},t)}var zu=u(()=>{M();Ft()});var Cn=u(()=>{zu()});function nt(t){return h({[P]:"Number",type:"number"},t)}var Qu=u(()=>{T();M()});var kr=u(()=>{Qu()});function vt(t){return h({[P]:"String",type:"string"},t)}var Ju=u(()=>{T();M()});var Kr=u(()=>{Ju()});function*Oh(t){let e=t.trim().replace(/"|'/g,"");return e==="boolean"?yield Io():e==="number"?yield nt():e==="bigint"?yield Ur():e==="string"?yield vt():yield(()=>{let r=e.split("|").map(n=>V(n.trim()));return r.length===0?W():r.length===1?r[0]:Tt(r)})()}function*Dh(t){if(t[1]!=="{"){let e=V("$"),r=ia(t.slice(1));return yield*[e,...r]}for(let e=2;e<t.length;e++)if(t[e]==="}"){let r=Oh(t.slice(2,e)),n=ia(t.slice(e+1));return yield*[...r,...n]}yield V(t)}function*ia(t){for(let e=0;e<t.length;e++)if(t[e]==="$"){let r=V(t.slice(0,e)),n=Dh(t.slice(e));return yield*[r,...n]}yield V(t)}function Yu(t){return[...ia(t)]}var sa=u(()=>{Ue();xo();Cn();kr();Kr();he();Ae()});function Nh(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xu(t,e){return Qe(t)?t.pattern.slice(1,t.pattern.length-1):L(t)?`(${t.anyOf.map(r=>Xu(r,e)).join("|")})`:kt(t)?`${e}${vn}`:yt(t)?`${e}${vn}`:mr(t)?`${e}${vn}`:Wt(t)?`${e}${Js}`:He(t)?`${e}${Nh(t.const.toString())}`:Lt(t)?`${e}${Qs}`:(()=>{throw new aa(`Unexpected Kind '${t[P]}'`)})()}function da(t){return`^${t.map(e=>Xu(e,"")).join("")}$`}var aa,la=u(()=>{Pn();M();At();B();aa=class extends we{}});function vr(t){let r=wo(t).map(n=>V(n));return Tt(r)}var Zu=u(()=>{he();Ue();oa()});function bo(t,e){let r=Q(t)?da(Yu(t)):da(t);return h({[P]:"TemplateLiteral",type:"string",pattern:r},e)}var ep=u(()=>{T();sa();la();De();M()});var qt=u(()=>{ra();oa();sa();Po();la();Zu();ep()});function Fh(t){return wo(t).map(r=>r.toString())}function Lh(t){let e=[];for(let r of t)e.push(...Ke(r));return e}function Wh(t){return[t.toString()]}function Ke(t){return[...new Set(Qe(t)?Fh(t):L(t)?Lh(t.anyOf):He(t)?Wh(t.const):kt(t)?["[number]"]:yt(t)?["[number]"]:[])]}var Ao=u(()=>{qt();B()});function Bh(t,e,r){let n={};for(let o of Object.getOwnPropertyNames(e))n[o]=Zt(t,Ke(e[o]),r);return n}function Uh(t,e,r){return Bh(t,e.properties,r)}function tp(t,e,r){let n=Uh(t,e,r);return U(n)}var ua=u(()=>{ve();Ao();Mt()});function np(t,e){return t.map(r=>op(r,e))}function Kh(t){return t.filter(e=>!Ht(e))}function Vh(t,e){return Ro(Kh(np(t,e)))}function qh(t){return t.some(e=>Ht(e))?[]:t}function jh(t,e){return Tt(qh(np(t,e)))}function Gh(t,e){return e in t?t[e]:e==="[number]"?Tt(t):W()}function Hh(t,e){return e==="[number]"?t:W()}function zh(t,e){return e in t?t[e]:W()}function op(t,e){return ie(t)?Vh(t.allOf,e):L(t)?jh(t.anyOf,e):Je(t)?Gh(t.items??[],e):ft(t)?Hh(t.items,e):me(t)?zh(t.properties,e):W()}function pa(t,e){return e.map(r=>op(t,r))}function rp(t,e){return Tt(pa(t,e))}function Zt(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)?tp(t,e,r):ze(e)?ip(t,e,r):h(Ye(e)?rp(t,Ke(e)):rp(t,e),r)}var ca=u(()=>{T();At();Xt();Ae();ot();he();Ao();ma();ua();B()});function Qh(t,e,r){return{[e]:Zt(t,[e],ee(r))}}function Jh(t,e,r){return e.reduce((n,o)=>({...n,...Qh(t,o,r)}),{})}function Yh(t,e,r){return Jh(t,e.keys,r)}function ip(t,e,r){let n=Yh(t,e,r);return U(n)}var ma=u(()=>{ca();ve();We()});var Mt=u(()=>{ma();ua();Ao();ca()});function Vr(t,e){return h({[P]:"Iterator",type:"Iterator",items:t},e)}var sp=u(()=>{T();M()});var _n=u(()=>{sp()});function Xh(t){return globalThis.Object.keys(t).filter(e=>!Be(t[e]))}function Zh(t,e){let r=Xh(t),n=r.length>0?{[P]:"Object",type:"object",required:r,properties:t}:{[P]:"Object",type:"object",properties:t};return h(n,e)}var H,ap=u(()=>{T();M();B();H=Zh});var Xe=u(()=>{ap()});function To(t,e){return h({[P]:"Promise",type:"Promise",item:t},e)}var dp=u(()=>{T();M()});var Mo=u(()=>{dp()});function eS(t){return h(se(t,[mt]))}function tS(t){return h({...t,[mt]:"Readonly"})}function rS(t,e){return e===!1?eS(t):tS(t)}function Ve(t,e){let r=e??!0;return te(t)?lp(t,r):rS(t,r)}var fa=u(()=>{T();M();Ut();ga();B()});function nS(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Ve(t[n],e);return r}function oS(t,e){return nS(t.properties,e)}function lp(t,e){let r=oS(t,e);return U(r)}var ga=u(()=>{ve();fa()});var Pr=u(()=>{ga();fa()});function it(t,e){return h(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 up=u(()=>{T();M()});var er=u(()=>{up()});function pp(t,e){return t in e?st(t,e[t]):U(e)}function iS(t){return{[t]:V(t)}}function sS(t){let e={};for(let r of t)e[r]=V(r);return e}function aS(t,e){return xu(e,t)?iS(t):sS(e)}function dS(t,e){let r=aS(t,e);return pp(t,r)}function $n(t,e){return e.map(r=>st(t,r))}function lS(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,[be]))):Dr(e)?Ve(st(t,se(e,[mt]))):te(e)?pp(t,e.properties):ze(e)?dS(t,e.keys):ht(e)?Lr($n(t,e.parameters),st(t,e.returns),r):St(e)?Rt($n(t,e.parameters),st(t,e.returns),r):cr(e)?Fr(st(t,e.items),r):fr(e)?Vr(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(lS(t,e.properties),r):ft(e)?Nr(st(t,e.items),r):gr(e)?To(st(t,e.item),r):e}function uS(t,e){let r={};for(let n of t)r[n]=st(n,e);return r}function cp(t,e,r){let n=Ye(t)?Ke(t):t,o=e({[P]:"MappedKey",keys:n}),i=uS(n,o);return H(i,r)}var mp=u(()=>{M();Ut();xn();bn();An();Sr();Mt();ot();_n();Ue();Xe();Kt();Mo();Pr();er();he();wn();Xs();B()});var ve=u(()=>{Nu();Xs();mp()});function pS(t){return h(se(t,[be]))}function cS(t){return h({...t,[be]:"Optional"})}function mS(t,e){return e===!1?pS(t):cS(t)}function Ce(t,e){let r=e??!0;return te(t)?fp(t,r):mS(t,r)}var ha=u(()=>{T();M();Ut();Sa();B()});function fS(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Ce(t[n],e);return r}function gS(t,e){return fS(t.properties,e)}function fp(t,e){let r=gS(t,e);return U(r)}var Sa=u(()=>{ve();ha()});var Kt=u(()=>{Sa();ha()});function En(t,e={}){let r=t.every(o=>me(o)),n=Ye(e.unevaluatedProperties)?{unevaluatedProperties:e.unevaluatedProperties}:{};return h(e.unevaluatedProperties===!1||Ye(e.unevaluatedProperties)||r?{...n,[P]:"Intersect",type:"object",allOf:t}:{...n,[P]:"Intersect",allOf:t},e)}var ya=u(()=>{T();M();B()});function hS(t){return t.every(e=>Be(e))}function SS(t){return se(t,[be])}function gp(t){return t.map(e=>Be(e)?SS(e):e)}function yS(t,e){return hS(t)?Ce(En(gp(t),e)):En(gp(t),e)}function Ro(t,e={}){if(t.length===1)return h(t[0],e);if(t.length===0)return W(e);if(t.some(r=>zt(r)))throw new Error("Cannot intersect transform types");return yS(t,e)}var hp=u(()=>{M();T();Ut();Ae();Kt();ya();B()});var Sp=u(()=>{});function _e(t,e){if(t.length===1)return h(t[0],e);if(t.length===0)return W(e);if(t.some(r=>zt(r)))throw new Error("Cannot intersect transform types");return En(t,e)}var yp=u(()=>{T();Ae();ya();B()});var ot=u(()=>{hp();Sp();yp()});function Ct(...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 h({[P]:"Ref",$ref:e},r)}var kp=u(()=>{At();T();M()});var wr=u(()=>{kp()});function kS(t,e){return Z("Awaited",[Z(t,e)])}function vS(t){return Z("Awaited",[Ct(t)])}function PS(t){return _e(vp(t))}function wS(t){return q(vp(t))}function IS(t){return qr(t)}function vp(t){return t.map(e=>qr(e))}function qr(t,e){return h(gt(t)?kS(t.target,t.parameters):ie(t)?PS(t.allOf):L(t)?wS(t.anyOf):gr(t)?IS(t.item):de(t)?vS(t.$ref):t,e)}var Pp=u(()=>{T();Xt();ot();he();wr();B()});var Co=u(()=>{Pp()});function wp(t){let e=[];for(let r of t)e.push(On(r));return e}function xS(t){let e=wp(t);return Ru(e)}function bS(t){let e=wp(t);return Au(e)}function AS(t){return t.map((e,r)=>r.toString())}function RS(t){return["[number]"]}function TS(t){return globalThis.Object.getOwnPropertyNames(t)}function MS(t){return CS?globalThis.Object.getOwnPropertyNames(t).map(r=>r[0]==="^"&&r[r.length-1]==="$"?r.slice(1,r.length-1):r):[]}function On(t){return ie(t)?xS(t.allOf):L(t)?bS(t.anyOf):Je(t)?AS(t.items??[]):ft(t)?RS(t.items):me(t)?TS(t.properties):hr(t)?MS(t.patternProperties):[]}var CS,ka=u(()=>{wn();B();CS=!1});function _S(t,e){return Z("KeyOf",[Z(t,e)])}function $S(t){return Z("KeyOf",[Ct(t)])}function ES(t,e){let r=On(t),n=OS(r),o=Tt(n);return h(o,e)}function OS(t){return t.map(e=>e==="[number]"?nt():V(e))}function jr(t,e){return gt(t)?_S(t.target,t.parameters):de(t)?$S(t.$ref):te(t)?Ip(t,e):ES(t,e)}var va=u(()=>{T();Ue();kr();Xt();wr();ka();he();Pa();B()});function DS(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=jr(t[n],ee(e));return r}function NS(t,e){return DS(t.properties,e)}function Ip(t,e){let r=NS(t,e);return U(r)}var Pa=u(()=>{ve();va();We()});var xp=u(()=>{});var Dn=u(()=>{Pa();xp();ka();va()});function FS(t){let e=[];for(let r of t)e.push(...On(r));return bu(e)}function LS(t){return t.filter(e=>!Ht(e))}function WS(t,e){let r=[];for(let n of t)r.push(...pa(n,[e]));return LS(r)}function BS(t,e){let r={};for(let n of e)r[n]=Ro(WS(t,n));return r}function bp(t,e){let r=FS(t),n=BS(t,r);return H(n,e)}var Ap=u(()=>{ot();Mt();Dn();Xe();wn();B()});var wa=u(()=>{Ap()});function _o(t){return h({[P]:"Date",type:"Date"},t)}var Rp=u(()=>{M();T()});var $o=u(()=>{Rp()});function Eo(t){return h({[P]:"Null",type:"null"},t)}var Tp=u(()=>{T();M()});var Oo=u(()=>{Tp()});function Do(t){return h({[P]:"Symbol",type:"symbol"},t)}var Mp=u(()=>{T();M()});var No=u(()=>{Mp()});function Fo(t){return h({[P]:"Undefined",type:"undefined"},t)}var Cp=u(()=>{T();M()});var Lo=u(()=>{Cp()});function Wo(t){return h({[P]:"Uint8Array",type:"Uint8Array"},t)}var _p=u(()=>{T();M()});var Bo=u(()=>{_p()});function tr(t){return h({[P]:"Unknown"},t)}var $p=u(()=>{T();M()});var Gr=u(()=>{$p()});function US(t){return t.map(e=>Ia(e,!1))}function KS(t){let e={};for(let r of globalThis.Object.getOwnPropertyNames(t))e[r]=Ve(Ia(t[r],!1));return e}function Uo(t,e){return e===!0?t:Ve(t)}function Ia(t,e){return Ds(t)?Uo(Yt(),e):Fs(t)?Uo(Yt(),e):pe(t)?Ve(it(US(t))):Nt(t)?Wo():pr(t)?_o():j(t)?Uo(H(KS(t)),e):Ns(t)?Uo(Rt([],tr()),e):ce(t)?Fo():Ls(t)?Eo():Ws(t)?Do():pn(t)?Ur():Ge(t)?V(t):Dt(t)?V(t):Q(t)?V(t):H({})}function Ep(t,e){return h(Ia(t,!0),e)}var Op=u(()=>{In();Cn();$o();Sr();Ue();Oo();Xe();No();er();Pr();Lo();Bo();Gr();Ft();De()});var xa=u(()=>{Op()});function Dp(t,e){return ht(t)?it(t.parameters,e):W(e)}var Np=u(()=>{er();Ae();B()});var ba=u(()=>{Np()});function Fp(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 Lp=u(()=>{Ue();M();he();De()});var Aa=u(()=>{Lp()});function at(t){return t===S.False?t:S.True}function Hr(t){throw new Ta(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)?jp(t,e):c.IsIntersect(e)?Ko(t,e):c.IsUnion(e)?$a(t,e):c.IsUnknown(e)?Qp(t,e):c.IsAny(e)?_a(t,e):Hr("StructuralRight")}function _a(t,e){return S.True}function VS(t,e){return c.IsIntersect(e)?Ko(t,e):c.IsUnion(e)&&e.anyOf.some(r=>c.IsAny(r)||c.IsUnknown(r))?S.True:c.IsUnion(e)?S.Union:c.IsUnknown(e)||c.IsAny(e)?S.True:S.Union}function qS(t,e){return c.IsUnknown(t)?S.False:c.IsAny(t)?S.Union:c.IsNever(t)?S.True:S.False}function jS(t,e){return c.IsObject(e)&&Vo(e)?S.True:Se(e)?ye(t,e):c.IsArray(e)?at(z(t.items,e.items)):S.False}function GS(t,e){return Se(e)?ye(t,e):c.IsAsyncIterator(e)?at(z(t.items,e.items)):S.False}function HS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsBigInt(e)?S.True:S.False}function Vp(t,e){return c.IsLiteralBoolean(t)||c.IsBoolean(t)?S.True:S.False}function zS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsBoolean(e)?S.True:S.False}function QS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsConstructor(e)?t.parameters.length>e.parameters.length?S.False:t.parameters.every((r,n)=>at(z(e.parameters[n],r))===S.True)?at(z(t.returns,e.returns)):S.False:S.False}function JS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsDate(e)?S.True:S.False}function YS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsFunction(e)?t.parameters.length>e.parameters.length?S.False:t.parameters.every((r,n)=>at(z(e.parameters[n],r))===S.True)?at(z(t.returns,e.returns)):S.False:S.False}function qp(t,e){return c.IsLiteral(t)&&Me.IsNumber(t.const)||c.IsNumber(t)||c.IsInteger(t)?S.True:S.False}function XS(t,e){return c.IsInteger(e)||c.IsNumber(e)?S.True:Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):S.False}function Ko(t,e){return e.allOf.every(r=>z(t,r)===S.True)?S.True:S.False}function ZS(t,e){return t.allOf.some(r=>z(r,e)===S.True)?S.True:S.False}function ey(t,e){return Se(e)?ye(t,e):c.IsIterator(e)?at(z(t.items,e.items)):S.False}function ty(t,e){return c.IsLiteral(e)&&e.const===t.const?S.True:Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsString(e)?zp(t,e):c.IsNumber(e)?Gp(t,e):c.IsInteger(e)?qp(t,e):c.IsBoolean(e)?Vp(t,e):S.False}function jp(t,e){return S.False}function ry(t,e){return S.True}function Wp(t){let[e,r]=[t,0];for(;c.IsNot(e);)e=e.not,r+=1;return r%2===0?e:tr()}function ny(t,e){return c.IsNot(t)?z(Wp(t),e):c.IsNot(e)?z(t,Wp(e)):Hr("Invalid fallthrough for Not")}function oy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsNull(e)?S.True:S.False}function Gp(t,e){return c.IsLiteralNumber(t)||c.IsNumber(t)||c.IsInteger(t)?S.True:S.False}function iy(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)?S.True:S.False}function qe(t,e){return Object.getOwnPropertyNames(t.properties).length===e}function Bp(t){return Vo(t)}function Up(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 Ra(t){return qe(t,0)}function Kp(t){return qe(t,0)}function sy(t){return qe(t,0)}function ay(t){return qe(t,0)}function dy(t){return Vo(t)}function ly(t){let e=nt();return qe(t,0)||qe(t,1)&&"length"in t.properties&&at(z(t.properties.length,e))===S.True}function uy(t){return qe(t,0)}function Vo(t){let e=nt();return qe(t,0)||qe(t,1)&&"length"in t.properties&&at(z(t.properties.length,e))===S.True}function py(t){let e=Rt([Yt()],Yt());return qe(t,0)||qe(t,1)&&"then"in t.properties&&at(z(t.properties.then,e))===S.True}function Hp(t,e){return z(t,e)===S.False||c.IsOptional(t)&&!c.IsOptional(e)?S.False:S.True}function $e(t,e){return c.IsUnknown(t)?S.False:c.IsAny(t)?S.Union:c.IsNever(t)||c.IsLiteralString(t)&&Bp(e)||c.IsLiteralNumber(t)&&Ra(e)||c.IsLiteralBoolean(t)&&Kp(e)||c.IsSymbol(t)&&Up(e)||c.IsBigInt(t)&&sy(e)||c.IsString(t)&&Bp(e)||c.IsSymbol(t)&&Up(e)||c.IsNumber(t)&&Ra(e)||c.IsInteger(t)&&Ra(e)||c.IsBoolean(t)&&Kp(e)||c.IsUint8Array(t)&&dy(e)||c.IsDate(t)&&ay(e)||c.IsConstructor(t)&&uy(e)||c.IsFunction(t)&&ly(e)?S.True:c.IsRecord(t)&&c.IsString(Ma(t))?e[rt]==="Record"?S.True:S.False:c.IsRecord(t)&&c.IsNumber(Ma(t))&&qe(e,0)?S.True:S.False}function cy(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 S.False;if(c.IsOptional(e.properties[r]))return S.True;if(Hp(t.properties[r],e.properties[r])===S.False)return S.False}return S.True})():S.False}function my(t,e){return Se(e)?ye(t,e):c.IsObject(e)&&py(e)?S.True:c.IsPromise(e)?at(z(t.item,e.item)):S.False}function Ma(t){return Qt in t.patternProperties?nt():Jt in t.patternProperties?vt():Hr("Unknown record key pattern")}function Ca(t){return Qt in t.patternProperties?t.patternProperties[Qt]:Jt in t.patternProperties?t.patternProperties[Jt]:Hr("Unable to get record value schema")}function dt(t,e){let[r,n]=[Ma(e),Ca(e)];return c.IsLiteralString(t)&&c.IsNumber(r)&&at(z(t,n))===S.True?S.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(Hp(n,t.properties[o])===S.False)return S.False;return S.True})():S.False}function fy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?z(Ca(t),Ca(e)):S.False}function gy(t,e){let r=c.IsRegExp(t)?vt():t,n=c.IsRegExp(e)?vt():e;return z(r,n)}function zp(t,e){return c.IsLiteral(t)&&Me.IsString(t.const)||c.IsString(t)?S.True:S.False}function hy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsString(e)?S.True:S.False}function Sy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsSymbol(e)?S.True:S.False}function yy(t,e){return c.IsTemplateLiteral(t)?z(vr(t),e):c.IsTemplateLiteral(e)?z(t,vr(e)):Hr("Invalid fallthrough for TemplateLiteral")}function ky(t,e){return c.IsArray(e)&&t.items!==void 0&&t.items.every(r=>z(r,e.items)===S.True)}function vy(t,e){return c.IsNever(t)?S.True:c.IsUnknown(t)?S.False:c.IsAny(t)?S.Union:S.False}function Py(t,e){return Se(e)?ye(t,e):c.IsObject(e)&&Vo(e)||c.IsArray(e)&&ky(t,e)?S.True:c.IsTuple(e)?Me.IsUndefined(t.items)&&!Me.IsUndefined(e.items)||!Me.IsUndefined(t.items)&&Me.IsUndefined(e.items)?S.False:Me.IsUndefined(t.items)&&!Me.IsUndefined(e.items)||t.items.every((r,n)=>z(r,e.items[n])===S.True)?S.True:S.False:S.False}function wy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsUint8Array(e)?S.True:S.False}function Iy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsVoid(e)?Ay(t,e):c.IsUndefined(e)?S.True:S.False}function $a(t,e){return e.anyOf.some(r=>z(t,r)===S.True)?S.True:S.False}function xy(t,e){return t.anyOf.every(r=>z(r,e)===S.True)?S.True:S.False}function Qp(t,e){return S.True}function by(t,e){return c.IsNever(e)?jp(t,e):c.IsIntersect(e)?Ko(t,e):c.IsUnion(e)?$a(t,e):c.IsAny(e)?_a(t,e):c.IsString(e)?zp(t,e):c.IsNumber(e)?Gp(t,e):c.IsInteger(e)?qp(t,e):c.IsBoolean(e)?Vp(t,e):c.IsArray(e)?qS(t,e):c.IsTuple(e)?vy(t,e):c.IsObject(e)?$e(t,e):c.IsUnknown(e)?S.True:S.False}function Ay(t,e){return c.IsUndefined(t)||c.IsUndefined(t)?S.True:S.False}function Ry(t,e){return c.IsIntersect(e)?Ko(t,e):c.IsUnion(e)?$a(t,e):c.IsUnknown(e)?Qp(t,e):c.IsAny(e)?_a(t,e):c.IsObject(e)?$e(t,e):c.IsVoid(e)?S.True:S.False}function z(t,e){return c.IsTemplateLiteral(t)||c.IsTemplateLiteral(e)?yy(t,e):c.IsRegExp(t)||c.IsRegExp(e)?gy(t,e):c.IsNot(t)||c.IsNot(e)?ny(t,e):c.IsAny(t)?VS(t,e):c.IsArray(t)?jS(t,e):c.IsBigInt(t)?HS(t,e):c.IsBoolean(t)?zS(t,e):c.IsAsyncIterator(t)?GS(t,e):c.IsConstructor(t)?QS(t,e):c.IsDate(t)?JS(t,e):c.IsFunction(t)?YS(t,e):c.IsInteger(t)?XS(t,e):c.IsIntersect(t)?ZS(t,e):c.IsIterator(t)?ey(t,e):c.IsLiteral(t)?ty(t,e):c.IsNever(t)?ry(t,e):c.IsNull(t)?oy(t,e):c.IsNumber(t)?iy(t,e):c.IsObject(t)?cy(t,e):c.IsRecord(t)?fy(t,e):c.IsString(t)?hy(t,e):c.IsSymbol(t)?Sy(t,e):c.IsTuple(t)?Py(t,e):c.IsPromise(t)?my(t,e):c.IsUint8Array(t)?wy(t,e):c.IsUndefined(t)?Iy(t,e):c.IsUnion(t)?xy(t,e):c.IsUnknown(t)?by(t,e):c.IsVoid(t)?Ry(t,e):Hr(`Unknown left type operand '${t[P]}'`)}function rr(t,e){return z(t,e)}var Ta,S,Ea=u(()=>{In();Sr();kr();Kr();Gr();qt();Pn();M();At();zs();Ta=class extends we{};(function(t){t[t.Union=0]="Union",t[t.True=1]="True",t[t.False=2]="False"})(S||(S={}))});function Ty(t,e,r,n,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=zr(t[s],e,r,n,ee(o));return i}function My(t,e,r,n,o){return Ty(t.properties,e,r,n,o)}function Jp(t,e,r,n,o){let i=My(t,e,r,n,o);return U(i)}var Oa=u(()=>{ve();qo();We()});function Cy(t,e,r,n){let o=rr(t,e);return o===S.Union?q([r,n]):o===S.True?r:n}function zr(t,e,r,n,o){return te(t)?Jp(t,e,r,n,o):ze(t)?h(Yp(t,e,r,n,o)):h(Cy(t,e,r,n),o)}var qo=u(()=>{T();he();Ea();Da();Oa();B()});function _y(t,e,r,n,o){return{[t]:zr(V(t),e,r,n,ee(o))}}function $y(t,e,r,n,o){return t.reduce((i,s)=>({...i,..._y(s,e,r,n,o)}),{})}function Ey(t,e,r,n,o){return $y(t.keys,e,r,n,o)}function Yp(t,e,r,n,o){let i=Ey(t,e,r,n,o);return U(i)}var Da=u(()=>{ve();Ue();qo();We()});var Xp=u(()=>{});var Nn=u(()=>{Ea();Da();Oa();Xp();qo()});function Zp(t,e){return Qr(vr(t),e)}var Na=u(()=>{jo();qt()});function Oy(t,e){let r=t.filter(n=>rr(n,e)===S.False);return r.length===1?r[0]:q(r)}function Qr(t,e,r={}){return Qe(t)?h(Zp(t,e),r):te(t)?h(ec(t,e),r):h(L(t)?Oy(t.anyOf,e):rr(t,e)!==S.False?W():t,r)}var jo=u(()=>{T();he();Ae();Nn();Fa();Na();B()});function Dy(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Qr(t[n],e);return r}function Ny(t,e){return Dy(t.properties,e)}function ec(t,e){let r=Ny(t,e);return U(r)}var Fa=u(()=>{ve();jo()});var La=u(()=>{Fa();Na();jo()});function tc(t,e){return Jr(vr(t),e)}var Wa=u(()=>{Go();qt()});function Fy(t,e){let r=t.filter(n=>rr(n,e)!==S.False);return r.length===1?r[0]:q(r)}function Jr(t,e,r){return Qe(t)?h(tc(t,e),r):te(t)?h(rc(t,e),r):h(L(t)?Fy(t.anyOf,e):rr(t,e)!==S.False?t:W(),r)}var Go=u(()=>{T();he();Ae();Nn();Ba();Wa();B()});function Ly(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Jr(t[n],e);return r}function Wy(t,e){return Ly(t.properties,e)}function rc(t,e){let r=Wy(t,e);return U(r)}var Ba=u(()=>{ve();Go()});var Ua=u(()=>{Ba();Wa();Go()});function nc(t,e){return ht(t)?h(t.returns,e):W(e)}var oc=u(()=>{T();Ae();B()});var Ka=u(()=>{oc()});function Ho(t){return Ve(Ce(t))}var ic=u(()=>{Pr();Kt()});var zo=u(()=>{ic()});function Ir(t,e,r){return h({[P]:"Record",type:"object",patternProperties:{[t]:e}},r)}function Va(t,e,r){let n={};for(let o of t)n[o]=e;return H(n,{...r,[rt]:"Record"})}function By(t,e,r){return qu(t)?Va(Ke(t),e,r):Ir(t.pattern,e,r)}function Uy(t,e,r){return Va(Ke(q(t)),e,r)}function Ky(t,e,r){return Va([t.toString()],e,r)}function Vy(t,e,r){return Ir(t.source,e,r)}function qy(t,e,r){let n=ce(t.pattern)?Jt:t.pattern;return Ir(n,e,r)}function jy(t,e,r){return Ir(Jt,e,r)}function Gy(t,e,r){return Ir(ku,e,r)}function Hy(t,e,r){return H({true:e,false:e},r)}function zy(t,e,r){return Ir(Qt,e,r)}function Qy(t,e,r){return Ir(Qt,e,r)}function Qo(t,e,r={}){return L(t)?Uy(t.anyOf,e,r):Qe(t)?By(t,e,r):He(t)?Ky(t.const,e,r):Lt(t)?Hy(t,e,r):yt(t)?zy(t,e,r):kt(t)?Qy(t,e,r):Vs(t)?Vy(t,e,r):Wt(t)?qy(t,e,r):Us(t)?jy(t,e,r):Ht(t)?Gy(t,e,r):W(r)}function Jo(t){return globalThis.Object.getOwnPropertyNames(t.patternProperties)[0]}function sc(t){let e=Jo(t);return e===Jt?vt():e===Qt?nt():vt({pattern:e})}function Yo(t){return t.patternProperties[Jo(t)]}var ac=u(()=>{T();M();Ae();kr();Xe();Kr();he();qt();Pn();Mt();De();B()});var Fn=u(()=>{ac()});function Jy(t,e){return e.parameters=Ln(t,e.parameters),e.returns=Pt(t,e.returns),e}function Yy(t,e){return e.parameters=Ln(t,e.parameters),e.returns=Pt(t,e.returns),e}function Xy(t,e){return e.allOf=Ln(t,e.allOf),e}function Zy(t,e){return e.anyOf=Ln(t,e.anyOf),e}function ek(t,e){return ce(e.items)||(e.items=Ln(t,e.items)),e}function tk(t,e){return e.items=Pt(t,e.items),e}function rk(t,e){return e.items=Pt(t,e.items),e}function nk(t,e){return e.items=Pt(t,e.items),e}function ok(t,e){return e.item=Pt(t,e.item),e}function ik(t,e){let r=lk(t,e.properties);return{...e,...H(r)}}function sk(t,e){let r=Pt(t,sc(e)),n=Pt(t,Yo(e)),o=Qo(r,n);return{...e,...o}}function ak(t,e){return e.index in t?t[e.index]:tr()}function dk(t,e){let r=Dr(e),n=Be(e),o=Pt(t,e);return r&&n?Ho(o):r&&!n?Ve(o):!r&&n?Ce(o):o}function lk(t,e){return globalThis.Object.getOwnPropertyNames(e).reduce((r,n)=>({...r,[n]:dk(t,e[n])}),{})}function Ln(t,e){return e.map(r=>Pt(t,r))}function Pt(t,e){return ht(e)?Jy(t,e):St(e)?Yy(t,e):ie(e)?Xy(t,e):L(e)?Zy(t,e):Je(e)?ek(t,e):ft(e)?tk(t,e):cr(e)?rk(t,e):fr(e)?nk(t,e):gr(e)?ok(t,e):me(e)?ik(t,e):hr(e)?sk(t,e):Ks(e)?ak(t,e):e}function dc(t,e){return Pt(e,Or(t))}var lc=u(()=>{go();Gr();zo();Pr();Kt();Xe();Fn();De();B()});var qa=u(()=>{lc()});function uc(t){return h({[P]:"Integer",type:"integer"},t)}var pc=u(()=>{T();M()});var ja=u(()=>{pc()});function uk(t,e,r){return{[t]:wt(V(t),e,ee(r))}}function pk(t,e,r){return t.reduce((o,i)=>({...o,...uk(i,e,r)}),{})}function ck(t,e,r){return pk(t.keys,e,r)}function cc(t,e,r){let n=ck(t,e,r);return U(n)}var Ga=u(()=>{ve();xr();Ue();We()});function mk(t){let[e,r]=[t.slice(0,1),t.slice(1)];return[e.toLowerCase(),r].join("")}function fk(t){let[e,r]=[t.slice(0,1),t.slice(1)];return[e.toUpperCase(),r].join("")}function gk(t){return t.toUpperCase()}function hk(t){return t.toLowerCase()}function Sk(t,e,r){let n=Br(t.pattern);if(!yr(n))return{...t,pattern:mc(t.pattern,e)};let s=[...Mn(n)].map(l=>V(l)),a=fc(s,e),d=q(a);return bo([d],r)}function mc(t,e){return typeof t=="string"?e==="Uncapitalize"?mk(t):e==="Capitalize"?fk(t):e==="Uppercase"?gk(t):e==="Lowercase"?hk(t):t:t.toString()}function fc(t,e){return t.map(r=>wt(r,e))}function wt(t,e,r={}){return ze(t)?cc(t,e,r):Qe(t)?Sk(t,e,r):L(t)?q(fc(t.anyOf,e),r):He(t)?V(mc(t.const,e),r):h(t,r)}var xr=u(()=>{T();qt();Ga();Ue();he();B()});function gc(t,e={}){return wt(t,"Capitalize",e)}var hc=u(()=>{xr()});function Sc(t,e={}){return wt(t,"Lowercase",e)}var yc=u(()=>{xr()});function kc(t,e={}){return wt(t,"Uncapitalize",e)}var vc=u(()=>{xr()});function Pc(t,e={}){return wt(t,"Uppercase",e)}var wc=u(()=>{xr()});var Ha=u(()=>{hc();Ga();xr();yc();vc();wc()});function yk(t,e,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(t))n[o]=nr(t[o],e,ee(r));return n}function kk(t,e,r){return yk(t.properties,e,r)}function Ic(t,e,r){let n=kk(t,e,r);return U(n)}var za=u(()=>{ve();Xo();We()});function vk(t,e){return t.map(r=>Qa(r,e))}function Pk(t,e){return t.map(r=>Qa(r,e))}function wk(t,e){let{[e]:r,...n}=t;return n}function Ik(t,e){return e.reduce((r,n)=>wk(r,n),t)}function xk(t,e,r){let n=se(t,[ge,"$id","required","properties"]),o=Ik(r,e);return H(o,n)}function bk(t){let e=t.reduce((r,n)=>So(n)?[...r,V(n)]:r,[]);return q(e)}function Qa(t,e){return ie(t)?_e(vk(t.allOf,e)):L(t)?q(Pk(t.anyOf,e)):me(t)?xk(t,e,t.properties):H({})}function nr(t,e,r){let n=pe(e)?bk(e):e,o=Ye(e)?Ke(e):e,i=de(t),s=de(e);return te(t)?Ic(t,o,r):ze(e)?xc(t,e,r):i&&s?Z("Omit",[t,n],r):!i&&s?Z("Omit",[t,n],r):i&&!s?Z("Omit",[t,n],r):h({...Qa(t,o),...r})}var Xo=u(()=>{T();ko();fn();Xt();Ue();Mt();ot();he();Xe();Ja();za();B();De()});function Ak(t,e,r){return{[e]:nr(t,[e],ee(r))}}function Rk(t,e,r){return e.reduce((n,o)=>({...n,...Ak(t,o,r)}),{})}function Tk(t,e,r){return Rk(t,e.keys,r)}function xc(t,e,r){let n=Tk(t,e,r);return U(n)}var Ja=u(()=>{ve();Xo();We()});var Zo=u(()=>{Ja();za();Xo()});function Mk(t,e,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(t))n[o]=or(t[o],e,ee(r));return n}function Ck(t,e,r){return Mk(t.properties,e,r)}function bc(t,e,r){let n=Ck(t,e,r);return U(n)}var Ya=u(()=>{ve();ei();We()});function _k(t,e){return t.map(r=>Xa(r,e))}function $k(t,e){return t.map(r=>Xa(r,e))}function Ek(t,e){let r={};for(let n of e)n in t&&(r[n]=t[n]);return r}function Ok(t,e,r){let n=se(t,[ge,"$id","required","properties"]),o=Ek(r,e);return H(o,n)}function Dk(t){let e=t.reduce((r,n)=>So(n)?[...r,V(n)]:r,[]);return q(e)}function Xa(t,e){return ie(t)?_e(_k(t.allOf,e)):L(t)?q($k(t.anyOf,e)):me(t)?Ok(t,e,t.properties):H({})}function or(t,e,r){let n=pe(e)?Dk(e):e,o=Ye(e)?Ke(e):e,i=de(t),s=de(e);return te(t)?bc(t,o,r):ze(e)?Ac(t,e,r):i&&s?Z("Pick",[t,n],r):!i&&s?Z("Pick",[t,n],r):i&&!s?Z("Pick",[t,n],r):h({...Xa(t,o),...r})}var ei=u(()=>{T();ko();Xt();ot();Ue();Xe();he();Mt();fn();B();De();Za();Ya()});function Nk(t,e,r){return{[e]:or(t,[e],ee(r))}}function Fk(t,e,r){return e.reduce((n,o)=>({...n,...Nk(t,o,r)}),{})}function Lk(t,e,r){return Fk(t,e.keys,r)}function Ac(t,e,r){let n=Lk(t,e,r);return U(n)}var Za=u(()=>{ve();ei();We()});var ti=u(()=>{Za();Ya();ei()});function Wk(t,e){return Z("Partial",[Z(t,e)])}function Bk(t){return Z("Partial",[Ct(t)])}function Uk(t){let e={};for(let r of globalThis.Object.getOwnPropertyNames(t))e[r]=Ce(t[r]);return e}function Kk(t,e){let r=se(t,[ge,"$id","required","properties"]),n=Uk(e);return H(n,r)}function Rc(t){return t.map(e=>Tc(e))}function Tc(t){return gt(t)?Wk(t.target,t.parameters):de(t)?Bk(t.$ref):ie(t)?_e(Rc(t.allOf)):L(t)?q(Rc(t.anyOf)):me(t)?Kk(t,t.properties):mr(t)||Lt(t)||yt(t)||He(t)||gn(t)||kt(t)||Wt(t)||hn(t)||Sn(t)?t:H({})}function Yr(t,e){return te(t)?Mc(t,e):h({...Tc(t),...e})}var ed=u(()=>{T();Xt();Kt();Xe();ot();he();wr();Ut();M();td();B()});function Vk(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Yr(t[n],ee(e));return r}function qk(t,e){return Vk(t.properties,e)}function Mc(t,e){let r=qk(t,e);return U(r)}var td=u(()=>{ve();ed();We()});var ri=u(()=>{td();ed()});function jk(t,e){return Z("Required",[Z(t,e)])}function Gk(t){return Z("Required",[Ct(t)])}function Hk(t){let e={};for(let r of globalThis.Object.getOwnPropertyNames(t))e[r]=se(t[r],[be]);return e}function zk(t,e){let r=se(t,[ge,"$id","required","properties"]),n=Hk(e);return H(n,r)}function Cc(t){return t.map(e=>_c(e))}function _c(t){return gt(t)?jk(t.target,t.parameters):de(t)?Gk(t.$ref):ie(t)?_e(Cc(t.allOf)):L(t)?q(Cc(t.anyOf)):me(t)?zk(t,t.properties):mr(t)||Lt(t)||yt(t)||He(t)||gn(t)||kt(t)||Wt(t)||hn(t)||Sn(t)?t:H({})}function Xr(t,e){return te(t)?$c(t,e):h({..._c(t),...e})}var rd=u(()=>{T();Xt();Xe();ot();he();wr();M();Ut();nd();B()});function Qk(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Xr(t[n],e);return r}function Jk(t,e){return Qk(t.properties,e)}function $c(t,e){let r=Jk(t,e);return U(r)}var nd=u(()=>{ve();rd()});var ni=u(()=>{nd();rd()});function Yk(t,e){return e.map(r=>de(r)?od(t,r.$ref):Ze(t,r))}function od(t,e){return e in t?de(t[e])?od(t,t[e].$ref):Ze(t,t[e]):W()}function Xk(t){return qr(t[0])}function Zk(t){return Zt(t[0],t[1])}function ev(t){return jr(t[0])}function tv(t){return Yr(t[0])}function rv(t){return nr(t[0],t[1])}function nv(t){return or(t[0],t[1])}function ov(t){return Xr(t[0])}function iv(t,e,r){let n=Yk(t,r);return e==="Awaited"?Xk(n):e==="Index"?Zk(n):e==="KeyOf"?ev(n):e==="Partial"?tv(n):e==="Omit"?rv(n):e==="Pick"?nv(n):e==="Required"?ov(n):W()}function sv(t,e){return Nr(Ze(t,e))}function av(t,e){return Fr(Ze(t,e))}function dv(t,e,r){return Lr(Wn(t,e),Ze(t,r))}function lv(t,e,r){return Rt(Wn(t,e),Ze(t,r))}function uv(t,e){return _e(Wn(t,e))}function pv(t,e){return Vr(Ze(t,e))}function cv(t,e){return H(globalThis.Object.keys(e).reduce((r,n)=>({...r,[n]:Ze(t,e[n])}),{}))}function mv(t,e){let[r,n]=[Ze(t,Yo(e)),Jo(e)],o=Or(e);return o.patternProperties[n]=r,o}function fv(t,e){return de(e)?{...od(t,e.$ref),[ge]:e[ge]}:e}function gv(t,e){return it(Wn(t,e))}function hv(t,e){return q(Wn(t,e))}function Wn(t,e){return e.map(r=>Ze(t,r))}function Ze(t,e){return Be(e)?h(Ze(t,se(e,[be])),e):Dr(e)?h(Ze(t,se(e,[mt])),e):zt(e)?h(fv(t,e),e):ft(e)?h(sv(t,e.items),e):cr(e)?h(av(t,e.items),e):gt(e)?h(iv(t,e.target,e.parameters)):ht(e)?h(dv(t,e.parameters,e.returns),e):St(e)?h(lv(t,e.parameters,e.returns),e):ie(e)?h(uv(t,e.allOf),e):fr(e)?h(pv(t,e.items),e):me(e)?h(cv(t,e.properties),e):hr(e)?h(mv(t,e)):Je(e)?h(gv(t,e.items||[]),e):L(e)?h(hv(t,e.anyOf),e):e}function Sv(t,e){return e in t?Ze(t,t[e]):W()}function Ec(t){return globalThis.Object.getOwnPropertyNames(t).reduce((e,r)=>({...e,[r]:Sv(t,r)}),{})}var Oc=u(()=>{Ft();Bs();Ut();xn();Co();bn();An();Mt();Sr();ot();_n();Dn();Xe();Zo();ti();Ae();ri();Fn();ni();er();he();M();B()});function Dc(t){return new id(t)}var id,Nc=u(()=>{Ft();M();Oc();id=class{constructor(e){let r=Ec(e),n=this.WithIdentifiers(r);this.$defs=n}Import(e,r){let n={...this.$defs,[e]:h(this.$defs[e],r)};return h({[P]:"Import",$defs:n,$ref:e})}WithIdentifiers(e){return globalThis.Object.getOwnPropertyNames(e).reduce((r,n)=>({...r,[n]:{...e[n],$id:n}}),{})}}});var sd=u(()=>{Nc()});function Fc(t,e){return h({[P]:"Not",not:t},e)}var Lc=u(()=>{T();M()});var ad=u(()=>{Lc()});function Wc(t,e){return St(t)?it(t.parameters,e):W()}var Bc=u(()=>{er();Ae();B()});var dd=u(()=>{Bc()});function Uc(t,e={}){ce(e.$id)&&(e.$id=`T${yv++}`);let r=Or(t({[P]:"This",$ref:`${e.$id}`}));return r.$id=e.$id,h({[rt]:"Recursive",...r},e)}var yv,Kc=u(()=>{go();T();De();M();yv=0});var ld=u(()=>{Kc()});function Vc(t,e){let r=Q(t)?new globalThis.RegExp(t):t;return h({[P]:"RegExp",type:"RegExp",source:r.source,flags:r.flags},e)}var qc=u(()=>{T();De();M()});var ud=u(()=>{qc()});function kv(t){return ie(t)?t.allOf:L(t)?t.anyOf:Je(t)?t.items??[]:[]}function jc(t){return kv(t)}var Gc=u(()=>{B()});var pd=u(()=>{Gc()});function Hc(t,e){return St(t)?h(t.returns,e):W(e)}var zc=u(()=>{T();Ae();B()});var cd=u(()=>{zc()});var Qc=u(()=>{});var Jc=u(()=>{});var Yc=u(()=>{Qc();Jc()});var Xc=u(()=>{});var Zc=u(()=>{Xc()});function em(t){return new md(t)}var md,fd,tm=u(()=>{M();B();md=class{constructor(e){this.schema=e}Decode(e){return new fd(this.schema,e)}},fd=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 zt(this.schema)?this.EncodeTransform(e,this.schema):this.EncodeSchema(e,this.schema)}}});var gd=u(()=>{tm()});function rm(t={}){return h({[P]:t[P]??"Unsafe"},t)}var nm=u(()=>{T();M()});var hd=u(()=>{nm()});function om(t){return h({[P]:"Void",type:"void"},t)}var im=u(()=>{T();M()});var Sd=u(()=>{im()});var yd={};co(yd,{Any:()=>Yt,Argument:()=>_u,Array:()=>Nr,AsyncIterator:()=>Fr,Awaited:()=>qr,BigInt:()=>Ur,Boolean:()=>Io,Capitalize:()=>gc,Composite:()=>bp,Const:()=>Ep,Constructor:()=>Lr,ConstructorParameters:()=>Dp,Date:()=>_o,Enum:()=>Fp,Exclude:()=>Qr,Extends:()=>zr,Extract:()=>Jr,Function:()=>Rt,Index:()=>Zt,InstanceType:()=>nc,Instantiate:()=>dc,Integer:()=>uc,Intersect:()=>_e,Iterator:()=>Vr,KeyOf:()=>jr,Literal:()=>V,Lowercase:()=>Sc,Mapped:()=>cp,Module:()=>Dc,Never:()=>W,Not:()=>Fc,Null:()=>Eo,Number:()=>nt,Object:()=>H,Omit:()=>nr,Optional:()=>Ce,Parameters:()=>Wc,Partial:()=>Yr,Pick:()=>or,Promise:()=>To,Readonly:()=>Ve,ReadonlyOptional:()=>Ho,Record:()=>Qo,Recursive:()=>Uc,Ref:()=>Ct,RegExp:()=>Vc,Required:()=>Xr,Rest:()=>jc,ReturnType:()=>Hc,String:()=>vt,Symbol:()=>Do,TemplateLiteral:()=>bo,Transform:()=>em,Tuple:()=>it,Uint8Array:()=>Wo,Uncapitalize:()=>kc,Undefined:()=>Fo,Union:()=>q,Unknown:()=>tr,Unsafe:()=>rm,Uppercase:()=>Pc,Void:()=>om});var sm=u(()=>{In();Ys();xn();bn();Co();Cn();xo();wa();xa();An();ba();$o();Aa();La();Nn();Ua();Sr();Mt();Ka();qa();ja();ot();Ha();_n();Dn();Ue();ve();sd();Ae();ad();Oo();kr();Xe();Zo();Kt();dd();ri();ti();Mo();Pr();zo();Fn();ld();wr();ud();ni();pd();cd();Kr();No();qt();gd();er();Bo();Lo();he();Gr();hd();Sd()});var p,am=u(()=>{sm();p=yd});var Ee=u(()=>{Bs();Ft();At();zs();yu();Pn();Iu();wn();M();In();xn();Ys();bn();Co();Cn();xo();wa();xa();An();ba();$o();Aa();La();Nn();Ua();Sr();Mt();Ka();qa();ja();ot();_n();Ha();Dn();Ue();sd();ve();Ae();ad();Oo();kr();Xe();Zo();Kt();dd();ri();ti();Mo();Pr();zo();Fn();ld();wr();ud();ni();pd();cd();Yc();Zc();Kr();No();qt();gd();er();Bo();Lo();he();Gr();hd();Sd();am()});function kd(t){v=t}function vd(t){fe=t}var v,fe,Y=u(()=>{v=null,fe=null});function dm(t){let e=t.chatId.trim(),r=t.topicId.trim();return!/^-?\d+$/.test(e)||!/^\d+$/.test(r)?null:`${e}:topic:${r}`}function xv(t){let e=t.conversationId.trim(),r=e.match(/^(-?\d+):topic:(\d+)$/i);if(r?.[1]&&r[2]){let i=dm({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=dm({chatId:n,topicId:e});return o?{chatId:n,topicId:e,canonicalConversationId:o}:null}function bv(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 Av(t,e){if(!/^\d+$/.test(t))return t;let r=bv(e);return r?`${r}:${t}`:`channel:${t}`}function Rv(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 Tv(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 Mv(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||!Iv.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 Cv(t,e=xv){try{return e({conversationId:t})}catch{return null}}function Pd(t){return{provider:"system",target:"system",sessionKey:t?.trim()||void 0}}function wd(t,e){return{...t,threadId:e??t.threadId}}function $v(t,e,r){return t==="telegram"&&r?.provider==="telegram"&&!!r.target&&e!==r.target}function Ev(t){let e=t?.trim();if(!e)return;let r=Mv(e);if(!r)return;let{provider:n,kind:o,rawId:i}=r,s=Tv(i),a=null;if(n==="telegram")try{a=_v.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 Id(t){let e=t?.match(/:topic:(\d+)$/);return e?parseInt(e[1],10):void 0}function Ov(t){return!!(t?.provider&&t.target&&t.provider!=="system"&&t.target!=="system")}function Bn(t,e,r){let n=Ev(r),o=e!=null?String(e):void 0,i=t?.trim();if(!i||i.toLowerCase()==="unknown")return n?wd(n,o):Pd(r);let s=i.split("|").map(k=>k.trim());if(s.length<2)return n?wd(n,o):Pd(r);let[a,d,l]=s,m=s.length>=3?l:d,g=s.length>=3?d:void 0,y=a?.toLowerCase();if(!y||!m)return n?wd(n,o):Pd(r);let f=y==="discord"?Av(m,r):m;return $v(y,f,n)?{provider:y,accountId:g,target:n.target,threadId:o??n.threadId,sessionKey:r?.trim()||void 0}:{provider:y,accountId:g,target:f,threadId:o??(n?.provider===y?n.threadId:void 0),sessionKey:r?.trim()||void 0}}function Zr(t){return Bn(Rv(t.route)??t.originChannel,t.route?.threadId??t.originThreadId,t.route?.sessionKey??t.originSessionKey)??t.route}function ii(t){let e=Zr(t);return Ov(e)?e:void 0}var Iv,_v,br=u(()=>{Iv=new Set(["telegram","discord","slack","system","mattermost","feishu","line","whatsapp","signal","matrix","googlechat","bluebubbles","imessage","msteams"]);_v={safeParseTelegramTopicConversation:Cv}});import{readFileSync as Dv}from"fs";import{homedir as Nv}from"os";import{join as Fv}from"path";function um(){if(Un!==void 0)return Un;try{let t=Dv(Fv(Nv(),".claude.json"),"utf-8");Un=JSON.parse(t).mcpServers??{}}catch{Un={}}return Un}function pm(t){let e=t.defaultHarness??lm,r={};for(let[n,o]of Object.entries(si))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??lm}function cm(t){let e=si[t],r=_.harnesses[t];return{...e,...r,allowedModels:r?.allowedModels??e?.allowedModels}}function $t(t){return cm(t).defaultModel}function en(t){return _.harnesses[t]?.allowedModels??_.allowedModels}function lt(t){return cm(t).reasoningEffort}function _t(t){return t==null?void 0:String(t).trim()||void 0}function Ad(t){return{channel:_t(t?.deliveryContext?.channel),to:_t(t?.deliveryContext?.to),accountId:_t(t?.deliveryContext?.accountId),threadId:_t(t?.deliveryContext?.threadId)}}function mm(t,e,r){if(!(!t||!e))return r?`${t}|${r}|${e}`:`${t}|${e}`}function xd(t){return _t(t?.requesterSenderId??t?.senderId)}function bd(t){return(_t(t.deliveryContext?.channel)??t.messageChannel??t.channel)?.toLowerCase()!=="telegram"?!1:!!Id(t.sessionKey)}function ai(t){let e=Ad(t),r=mm(e.channel,e.to,e.accountId);if(r)return r;if(t.messageChannel){let n=t.messageChannel.split("|");if(n.length>=3)return t.messageChannel;if(t.agentAccountId&&n.length>=2)return`${n[0]}|${t.agentAccountId}|${n.slice(1).join("|")}`;let o=_t(t.chatId);if(n.length===1&&o)return`${n[0]}|${o}`;let i=xd(t);if(n.length===1&&i&&!bd(t))return`${n[0]}|${i}`}if(t.workspaceDir){let n=Vn(t.workspaceDir);if(n)return n}if(t.messageChannel&&t.messageChannel.includes("|"))return t.messageChannel}function jt(t,e){if(e&&String(e).includes("|"))return String(e);let r=Ad(t),n=mm(r.channel,r.to,r.accountId);if(n)return n;if(t?.channelId&&String(t.channelId).includes("|"))return String(t.channelId);if(t?.messageChannel){let a=String(t.messageChannel);if(a.includes("|"))return a;let d=_t(t.chatId);if(d)return`${a}|${d}`;let l=xd(t);if(l&&!bd(t))return`${a}|${l}`}let o=_t(t?.channel),i=_t(t?.chatId);if(o&&i)return`${o}|${i}`;let s=xd(t);return o&&s&&!bd(t)?`${o}|${s}`:t?.id&&/^-?\d+$/.test(String(t.id))?`telegram|${t.id}`:_.fallbackChannel??"unknown"}function Kn(t){return Ad(t).threadId??t?.messageThreadId??void 0}function Et(t,e,r){return Bn(jt(t,e),Kn(t),r??t?.sessionKey)}function Vn(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 fm(t){return Id(t)}var Un,lm,si,_,Re=u(()=>{br();lm="claude-code",si={"claude-code":{defaultModel:"anthropic/claude-sonnet-4-7",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.5",allowedModels:["gpt-5.5","gpt-5.5-pro"],reasoningEffort:"medium"}};_={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"ask",harnesses:{"claude-code":{...si["claude-code"]},codex:{...si.codex}}}});function di(t){return{type:"backend_ref",ref:t}}function li(t){return{type:"run_started",...t?{runId:t}:{}}}function qn(t){return{type:"text_delta",text:t}}function gm(t,e){return{type:"tool_call",name:t,input:e}}function ui(t){return{type:"pending_input",state:t}}function nn(t){return t?{type:"pending_input_resolved",requestId:t}:{type:"pending_input_resolved"}}function pi(t,e){return{type:"plan_artifact",artifact:t,finalized:e}}function ci(t){return t?{type:"settings_changed",permissionMode:t}:{type:"settings_changed"}}function Ar(t){return{type:"run_completed",data:t}}var rn,Rd=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 fi from"@anthropic-ai/claude-agent-sdk";function Lv(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 Wv(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 mi,hm=u(()=>{Rd();mi=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,allowedTools:e.allowedTools,systemPrompt:e.systemPrompt,includePartialMessages:!0,abortController:e.abortController,mcpServers:e.mcpServers,...d?{canUseTool:async(k,A)=>{if(k!=="AskUserQuestion")return{behavior:"allow"};let b=Wv(a,++s,A);r.enqueue(ui(b));try{let w=await d(k,A);return r.enqueue(nn(b.requestId)),w}catch(w){throw r.enqueue(nn(b.requestId)),w}}}:{}};e.resumeSessionId&&(l.resume=e.resumeSessionId,l.forkSession=e.forkSession??!1);let m=e.prompt,g=this.deps.query??fi.query,y=this.deps.startup??fi.startup,f=(async()=>{if(typeof y!="function")return g({prompt:m,options:l});let k=await y({options:l});try{return k.query(m)}catch(A){throw await k.close?.(),A}})();return(async()=>{try{let k=await f;for await(let A of k){let b=A;if(b.type==="system"&&b.subtype==="init"){a=b.session_id??a,r.enqueue(di({kind:"claude-code",conversationId:a}));continue}if(b.type==="system"&&b.subtype==="status"&&b.permissionMode){r.enqueue(ci(b.permissionMode));continue}if(b.type==="assistant"){n||(n=!0,r.enqueue(li()));for(let w of b.message?.content??[]){if(w.type==="text"){o+=o?`
3
- ${w.text}`:w.text,r.enqueue(qn(w.text));continue}w.type==="tool_use"&&((w.name==="ExitPlanMode"||w.name==="set_permission_mode")&&(i=!0),w.name!=="AskUserQuestion"&&r.enqueue(gm(w.name,w.input)))}continue}if(b.type==="result"){let w=o.trim();if(w&&(e.permissionMode==="plan"||i)){let C={explanation:void 0,steps:[],markdown:w};r.enqueue(pi(C,!0))}r.enqueue(Ar({success:b.subtype==="success",duration_ms:b.duration_ms??0,total_cost_usd:b.total_cost_usd??0,num_turns:b.num_turns??0,result:Lv(b),session_id:b.session_id??a})),o="",i=!1,n=!1}}}finally{r.close()}})().catch(k=>{r.enqueue(Ar({success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,result:k instanceof Error?k.message:String(k),session_id:a})),r.close()}),{messages:r.messages(),async setPermissionMode(k){let A=await f;typeof A.setPermissionMode=="function"&&await A.setPermissionMode(k)},async streamInput(k){let A=await f;typeof A.streamInput=="function"&&await A.streamInput(k)},async interrupt(){let k=await f;typeof k.interrupt=="function"&&await k.interrupt()}}}buildUserMessage(e,r){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:r}}}});import{spawn as Bv}from"node:child_process";import Uv from"node:readline";function Kv(t){return t instanceof Error?t.message:String(t)}function Vv(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}async function qv(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:Kv(n)}})}}}var gi,Sm=u(()=>{gi=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=Bv(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,Uv.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=Vv(e);r&&await qv(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 jv(t){return t instanceof Error?t.message:String(t)}function ym(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function ir(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>ir(r)).join("");let e=X(t);if(!e)return"";for(let r of["delta","text","content","message","input","output","parts"]){let n=ir(e[r]);if(n)return n}for(let r of["item","turn","thread","response","result","data"]){let n=ir(e[r]);if(n)return n}return""}function jn(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 hi(t,e,r=0){if(r>6)return;if(Array.isArray(t)){for(let i of t){let s=hi(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=hi(i,e,r+1);if(s)return s}}function Gn(t){return{threadId:jn(t).threadId,cwd:hi(t,["cwd","workdir","directory"])}}function km(t){let e=t?.trim();return!!(e&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(e))}function vm(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 Si(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 Gv(t,e=!1){let r=X(t);if(!r)return"";let n=X(r.item)??r;return le(n,["type"])?.toLowerCase()!=="agentmessage"?"":e?ir(n):le(n,["text"],{trim:!1})??ir(n)}function Pm(t,e){let r=t.trim().toLowerCase();return r==="item/agentmessage/delta"?{mode:"delta",text:ir(e),itemId:Si(e)}:r==="item/completed"?{mode:"snapshot",text:Gv(e),itemId:Si(e)}:{mode:"ignore",text:""}}function wm(t){return{itemId:Si(t),delta:ir(t)}}function Im(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 xm(t){let e=X(t);if(!e)return{};let r=X(e.item)??e;return le(r,["type"])?.toLowerCase()!=="plan"?{}:{itemId:Si(r),text:le(r,["text"],{trim:!1})??ir(r)}}function bm(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 Am(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 Hv(t,e){let r=jv(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 Qv(t){return zv.has(t.trim().toLowerCase())}function Jv(t){let e=X(t);return e?!!le(e,["threadId","thread_id"]):!1}async function Hn(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(Qv(r)&&!Jv(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,!Hv(o,r))continue}}throw e instanceof Error?e:new Error(String(e))}function Rm(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 Tm(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 Yv(t){return[{type:"text",text:t}]}function Xv(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 Mm(t){let e={threadId:t.threadId,input:Yv(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=Xv(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 Cm(t){return[{threadId:t.threadId,turnId:t.turnId}]}function Zv(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 eP(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 _m(t,e,r){let n=t.trim().toLowerCase(),o=Zv(r),i=hi(r,["question","prompt","message","text","summary","reason"])??void 0,s=n.includes("requestapproval"),a=s?o.map(d=>({kind:"approval",label:d,decision:eP(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 $m(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function Td(t,e){let r=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:r,sandbox:r==="never"?"danger-full-access":void 0}}var zv,Em=u(()=>{zv=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function Om(t){return t instanceof Error?t.message:String(t)}function iP(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 tP,Rr,rP,nP,oP,yi,Dm=u(()=>{Sm();Rd();Em();tP="1.0",Rr=6e4,rP="OPENCLAW_CODEX_APP_SERVER_COMMAND",nP="OPENCLAW_CODEX_APP_SERVER_ARGS",oP="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";yi=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[rP]?.trim()||"codex",args:ym(process.env[nP]),requestTimeoutMs:Number.parseInt(process.env[oP]??String(Rr),10)||Rr},n=this.deps.createClient?.(r)??new gi(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,g=0,y="",f=[],k,A=new Map,b=new Set,w=D=>{let N=D?.trim();if(!N)return;let K=e.originalWorkdir?.trim()||e.cwd.trim();e.worktreeStrategy&&e.worktreeStrategy!=="off"&&N!==K&&km(N)&&(a=N,d=vm(N))},C=()=>{i&&o.enqueue(di({kind:"codex-app-server",conversationId:i,...s?{runId:s}:{},...d?{worktreeId:d}:{},...a?{worktreePath:a}:{}}))};n.setNotificationHandler(async(D,N)=>{let K=D.trim().toLowerCase(),ue=jn(N),ct=Gn(N);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=Im(N);y=Te.explanation??y,Te.steps.length>0&&(f=Te.steps);return}if(K==="item/plan/delta"){let Te=wm(N);if(Te.itemId&&Te.delta){let Gt=A.get(Te.itemId)??"";A.set(Te.itemId,`${Gt}${Te.delta}`)}return}if(K==="item/completed"){let Te=xm(N);if(Te.text?.trim()){let Gt={explanation:y||void 0,steps:f,markdown:Te.text.trim()};o.enqueue(pi(Gt,!0));return}}let ae=Pm(K,N);if(ae.mode==="delta"&&ae.text){ae.itemId&&b.add(ae.itemId),o.enqueue(qn(ae.text));return}ae.mode==="snapshot"&&ae.text&&(!ae.itemId||!b.has(ae.itemId))&&o.enqueue(qn(ae.text)),(K==="turn/completed"||K==="turn/failed"||K==="turn/cancelled")&&k&&(k.method=D,k.params=N,k.resolve())}),n.setRequestHandler(async(D,N)=>{if(!$m(D))return{};let K=jn(N),ue=Gn(N);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=_m(D,ct,N),Te=D.trim().toLowerCase(),Gt=ae.options,po=ae.actions??[],Wg=await new Promise(Bg=>{m={requestId:ct,methodLower:Te,state:ae,options:Gt,actions:po,resolveResponse:Bg},o.enqueue(ui(ae))});return m=void 0,o.enqueue(nn(ct)),Wg});let I=async()=>{await n.connect(),await n.request("initialize",{protocolVersion:tP,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},Rr),await n.notify("initialized",{})},R=async()=>{let D=Td(l,e.codexApprovalPolicy);if(i){let ue=await Hn({client:n,methods:["thread/resume"],payloads:Tm({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:D.approvalPolicy,sandbox:D.sandbox}),timeoutMs:Rr}),ct=Gn(ue);i=ct.threadId??i,w(ct.cwd),C();return}let N=await Hn({client:n,methods:["thread/start","thread/new"],payloads:Rm({cwd:e.originalWorkdir?.trim()||e.cwd,model:e.model,approvalPolicy:D.approvalPolicy,sandbox:D.sandbox}),timeoutMs:Rr}),K=Gn(N);if(i=K.threadId,!i)throw new Error("Codex App Server did not return a thread id.");w(K.cwd),C()},O=async D=>{await R(),o.enqueue(li()),g+=1,y="",f=[],A.clear(),b.clear();let N="",K,ue,ct=new Promise(ae=>{ue=ae});k={resolve:ue};try{let ae=Td(l,e.codexApprovalPolicy),Te=await Hn({client:n,methods:["turn/start"],payloads:Mm({threadId:i,prompt:D,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,permissionMode:l,approvalPolicy:ae.approvalPolicy,sandbox:ae.sandbox}),timeoutMs:Rr}),Gt=jn(Te);Gt.runId&&(s=Gt.runId,C()),await ct,N=k?.method??"turn/failed",K=k?.params;let po=bm(N,K);o.enqueue(Ar({success:po==="completed",outcome:po,duration_ms:0,total_cost_usd:0,num_turns:g,result:Am(N,K),session_id:i}))}catch(ae){o.enqueue(Ar({success:!1,duration_ms:0,total_cost_usd:0,num_turns:g,result:Om(ae),session_id:i??""}))}finally{k=void 0}},Le=async D=>m?(m.methodLower.includes("requestapproval")?m.resolveResponse({decision:D.trim()||"decline"}):m.resolveResponse({text:D.trim()}),!0):!1,Sl=async D=>{let N=m;if(!N)return!1;let K=N.actions[D];if(K?.kind==="approval")return N.resolveResponse({decision:K.responseDecision,...K.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:K.proposedExecpolicyAmendment}:{}}),!0;let ue=N.options[D];return ue?(N.methodLower.includes("requestapproval")?N.resolveResponse({decision:ue}):N.resolveResponse({option:ue,index:D}),!0):!1},yl=typeof e.prompt=="string"?(async function*(){yield{type:"user",text:e.prompt,session_id:e.resumeSessionId??""}})():e.prompt;return(async()=>{try{await I();for await(let D of yl){let N=iP(D).trim();!N||await Le(N)||await O(N)}}catch(D){o.enqueue(Ar({success:!1,duration_ms:0,total_cost_usd:0,num_turns:g,result:Om(D),session_id:i??e.resumeSessionId??""}))}finally{await n.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(D){l=D,o.enqueue(ci(D))},async submitPendingInputOption(D){return Sl(D)},async submitPendingInputText(D){return Le(D)},async interrupt(){!i||!s||await Hn({client:n,methods:["turn/interrupt"],payloads:Cm({threadId:i,turnId:s}),timeoutMs:Rr}).catch(()=>{})}}}buildUserMessage(e,r){return{type:"user",text:e,session_id:r}}}});function Nm(t){Md.set(t.name,t)}function zn(t){let e=Md.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...Md.keys()].join(", ")}`);return e}function Fm(){return zn(Pe())}var Md,Cd=u(()=>{hm();Dm();Re();Md=new Map;Nm(new mi);Nm(new yi)});function $(t){return t.backendRef?.conversationId??t.harnessSessionId}function re(t){return t.id??t.sessionId??t.name??$(t)??t.harnessSessionId}function sP(t){return t.harnessSessionId}function et(t){let e=[re(t),$(t),sP(t)].filter(r=>!!r);return[...new Set(e)]}function _d(t){return t.harnessName??t.persistedHarness??Pe()}function ki(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return zn(_d(t)).capabilities.worktrees}catch{return"plugin-managed"}}function $d(t){return t==="native-execution"||t==="native-restore"}function Lm(t){return t==="native-restore"}function aP(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function Ne(t){return $d(ki(t))&&aP(t)}var ke=u(()=>{Re();Cd()});import{execFileSync as xe}from"child_process";import*as Ri from"fs";import{tmpdir as xP}from"os";import{dirname as Zm,join as bP}from"path";function AP(t){try{return xe("git",["rev-parse","--show-toplevel"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function Ti(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(_.worktreeDir)return _.worktreeDir;if(t){let e=AP(t);if(e)return bP(e,".worktrees")}return xP()}function ef(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function Mi(t){try{let e=xe("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")?Zm(e):void 0}catch{return}}function RP(){if(bi!==void 0)return bi;try{return xe("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),bi=!0,!0}catch{return bi=!1,!1}}function sr(){if(Ai!==void 0)return Ai;try{return xe("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Ai=!0,!0}catch{return Ai=!1,!1}}function Dd(t){if(!RP())return!1;try{return xe("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function tf(t){try{let e=MP(t);if(!e)return console.warn(`[worktree] Failed to resolve free-space probe path for ${Ti(t)}`),!0;let r=Ri.statfsSync(e),n=r.bavail*r.bsize;return CP(n)}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function Yn(t,e){try{return xe("git",["-C",t,"rev-parse","--verify",e],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function TP(t){let e=t;for(;;){if(Ri.existsSync(e))return e;let r=Zm(e);if(r===e)return;e=r}}function MP(t){return TP(Ti(t))}function CP(t){return t>=104857600}function ar(t){let e=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(e)return e;try{let n=xe("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 xe("git",["-C",t,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return xe("git",["-C",t,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function Ci(t){try{let r=xe("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 Nd(t,e,r){try{let n=xe("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 rf(t,e,r){try{let n=xe("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 nf(t,e,r){try{return xe("git",["-C",t,"merge-base","--is-ancestor",e,r],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function of(t,e,r){try{let n=xe("git",["-C",t,"merge-tree","--write-tree",r,e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=xe("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 Ot(t,e){try{return xe("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 sf(t,e){if(e)return e;let r;try{r=xe("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}try{let n=xe("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 bi,Ai,Xn=u(()=>{Re()});import{execFileSync as Zn}from"child_process";import{existsSync as _P,mkdirSync as af,rmSync as Fd}from"fs";function $P(t,e){return!!(t&&typeof t=="object"&&"code"in t&&t.code===e)}function Ld(t,e,r={}){let n=ef(e),o=Ti(t);af(o,{recursive:!0});let i=r.allowExistingBranch===!0,s,a,d=10,l=!1;for(let g=0;g<d;g++){let y=g===0?"":`-${Math.random().toString(16).slice(2,6)}`,f=`${o}/openclaw-worktree-${n}${y}`,k=`agent/${n}${y}`;if(!i&&Yn(t,k))continue;let A=!1;do{A=!1;try{af(f,{recursive:!1}),s=f,a=k;break}catch(b){if($P(b,"EEXIST")){if(i&&g===0&&!l)try{Fd(f,{recursive:!0,force:!0}),l=!0,A=!0}catch(w){throw new Error(`Failed to recreate existing worktree branch ${k}: could not clear blocked path ${f}: ${w instanceof Error?w.message:String(w)}`)}else if(i&&g===0)throw new Error(`Failed to recreate existing worktree branch ${k}: path ${f} remains blocked after one cleanup attempt`);continue}throw b}}while(A);if(s&&a)break}if(!s||!a)throw new Error(`Failed to create unique worktree directory and branch after ${d} attempts`);let m=Yn(t,a);try{m?Zn("git",["-C",t,"worktree","add",s,a],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):Zn("git",["-C",t,"worktree","add","-b",a,s],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(g){try{Fd(s,{recursive:!0,force:!0})}catch{}throw g}return s}function EP(t){if(!_P(t))return[];try{let e=Zn("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=EP(e);if(o.length>0&&!n)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${e}: ${o[0]}`),!1;try{return Zn("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 Fd(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 _i(t){try{Zn("git",["-C",t,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var df=u(()=>{Xn()});import{execFileSync as ne}from"child_process";import{existsSync as OP}from"fs";function Mr(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 g=s.match(/(\d+)\s+insertions?\(/);g&&(d=parseInt(g[1],10));let y=s.match(/(\d+)\s+deletions?\(/);y&&(l=parseInt(y[1],10));let k=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),b=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,I,R]=w.split("|");return{hash:C||"",message:I||"",author:R||""}});return{commits:o,filesChanged:a,insertions:d,deletions:l,changedFiles:k,commitMessages:b}}catch(n){console.warn(`[worktree] Failed to get diff summary: ${n instanceof Error?n.message:String(n)}`);return}}function $i(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 Ei(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 g=!1;if(i)try{ne("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{g=!0}return{success:!0,stashed:i||void 0,stashRef:s,stashPopConflict:g||void 0}}let d=o&&OP(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 g;try{g=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(!g.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 Wd=u(()=>{});import{execFileSync as Oi}from"child_process";function lf(t,e,r,n,o,i){if(!sr())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s;if(i)try{let g=Oi("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[:/]([^/]+)\/[^/]+(?:\.git)?$/);g&&(s=g[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:Oi("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 eo(t,e,r){if(!sr())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=Oi("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 uf(t,e,r,n){if(!sr())return!1;try{let o=["pr","comment",String(e),"--body",r];return n&&o.push("--repo",n),Oi("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 Cr(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 Bd=u(()=>{Xn()});import{existsSync as Ud}from"fs";function pf(){return new Date().toISOString()}function DP(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:pf(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function NP(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(Ud(t.workdir)?ar(t.workdir):void 0)}function to(t,e={}){let r=DP(t),n=pf(),o=new Set,i=Ud(t.workdir),s=!!(t.worktreePath&&Ud(t.worktreePath)),a=t.worktreeBranch,d=NP(t),l=!1,m=!1,g=!1,y=!1,f,k,A=t.worktreePrUrl?"open":"none",b=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=Yn(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=rf(t.workdir,a,d);f=Le?.ahead,k=Le?.behind,g=nf(t.workdir,a,d),g?o.add("topology_merged"):(y=of(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=eo(t.workdir,a,t.worktreePrTargetRepo??r.targetRepo);A=Le.state,b=Le.url??b,w=Le.number??w}A==="open"&&o.add("pr_open"),A==="merged"&&!g&&!y&&o.add("pr_merged_not_reflected_locally");let C=r.state;g?C="merged":y?C="released":!l&&r.state==="pending_decision"&&(C="cleanup_failed");let I=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"),R=!I&&(C==="merged"||C==="released"||r.state==="dismissed"||r.state==="no_change"),O={checkedAt:n,repoExists:i,branchExists:l,worktreeExists:s,activeSession:e.activeSession===!0,dirtyTracked:m,topologyMerged:g,releaseNoopMerge:y,branchAheadCount:f,baseAheadCount:k,prState:A,prUrl:b,prNumber:w,reasons:[...o]};return{lifecycle:r,evidence:O,derivedState:C,cleanupSafe:R,preserve:I,reasons:[...o]}}var Di=u(()=>{Xn();Bd();Wd()});var ut=u(()=>{Xn();df();Wd();Bd();Di()});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 Tf(t){return t.persistedSession?et(t.persistedSession):[]}function uw(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 ji(t,e,r={}){let{activeSession:n,persistedSession:o}=uw(t,e),i=to({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 Gi(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 Hi(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 zi(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 no=u(()=>{ke();Di()});var Mf={};co(Mf,{makeAgentPrTool:()=>oo});import{existsSync as cw}from"fs";function mw(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function oo(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(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}],meta:{success:!1,state:"error"}};if(!mw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!sr())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(v,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"}};cw(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${l}" via originalWorkdir (${a})`);let m=r.base_branch??ar(a),g=n.persistedRef,y=sf(a,r.target_repo??i?.worktreePrTargetRepo);if(!$i(a,l))return{content:[{type:"text",text:`\u274C Failed to push ${l} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let f=eo(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}).
1
+ var Th=Object.defineProperty;var u=(t,e)=>()=>(t&&(e=t(t=0)),e);var Po=(t,e)=>{for(var n in e)Th(t,n,{get:e[n],enumerable:!0})};var Ee={};Po(Ee,{HasPropertyKey:()=>wo,IsArray:()=>me,IsAsyncIterator:()=>Ys,IsBigInt:()=>yr,IsBoolean:()=>Wt,IsDate:()=>yn,IsFunction:()=>Xs,IsIterator:()=>Zs,IsNull:()=>ea,IsNumber:()=>ze,IsObject:()=>G,IsRegExp:()=>kr,IsString:()=>J,IsSymbol:()=>ta,IsUint8Array:()=>Bt,IsUndefined:()=>fe});function wo(t,e){return e in t}function Ys(t){return G(t)&&!me(t)&&!Bt(t)&&Symbol.asyncIterator in t}function me(t){return Array.isArray(t)}function yr(t){return typeof t=="bigint"}function Wt(t){return typeof t=="boolean"}function yn(t){return t instanceof globalThis.Date}function Xs(t){return typeof t=="function"}function Zs(t){return G(t)&&!me(t)&&!Bt(t)&&Symbol.iterator in t}function ea(t){return t===null}function ze(t){return typeof t=="number"}function G(t){return typeof t=="object"&&t!==null}function kr(t){return t instanceof globalThis.RegExp}function J(t){return typeof t=="string"}function ta(t){return typeof t=="symbol"}function Bt(t){return t instanceof globalThis.Uint8Array}function fe(t){return t===void 0}var Le=u(()=>{});function Mh(t){return t.map(e=>Io(e))}function Ch(t){return new Date(t.getTime())}function _h(t){return new Uint8Array(t)}function Eh(t){return new RegExp(t.source,t.flags)}function $h(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=Io(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=Io(t[n]);return e}function Io(t){return me(t)?Mh(t):yn(t)?Ch(t):Bt(t)?_h(t):kr(t)?Eh(t):G(t)?$h(t):t}function te(t){return Io(t)}var Ue=u(()=>{Le()});function Un(t,e){return e===void 0?te(t):te({...e,...t})}var bo=u(()=>{Ue()});var na=u(()=>{bo();Ue()});function Gl(t){return t!==null&&typeof t=="object"}function Hl(t){return globalThis.Array.isArray(t)&&!globalThis.ArrayBuffer.isView(t)}function zl(t){return t===void 0}function Ql(t){return typeof t=="number"}var Jl=u(()=>{});var Yl=u(()=>{Jl()});var xo,Xl=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 n(s){let a=Gl(s);return t.AllowArrayObject?a:a&&!Hl(s)}t.IsObjectLike=n;function r(s){return n(s)&&!(s instanceof Date)&&!(s instanceof Uint8Array)}t.IsRecordLike=r;function o(s){return t.AllowNaN?Ql(s):Number.isFinite(s)}t.IsNumberLike=o;function i(s){let a=zl(s);return t.AllowNullVoid?a||s===null:a}t.IsVoidLike=i})(xo||(xo={}))});function Oh(t){return globalThis.Object.freeze(t).map(e=>vr(e))}function Nh(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=vr(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=vr(t[n]);return globalThis.Object.freeze(e)}function vr(t){return me(t)?Oh(t):yn(t)?t:Bt(t)?t:kr(t)?t:G(t)?Nh(t):t}var Zl=u(()=>{Le()});function h(t,e){let n=e!==void 0?{...e,...t}:t;switch(xo.InstanceMode){case"freeze":return vr(n);case"clone":return te(n);default:return n}}var T=u(()=>{Xl();Zl();Ue()});var Ut=u(()=>{T()});var be,eu=u(()=>{be=class extends Error{constructor(e){super(e)}}});var Ct=u(()=>{eu()});var Se,yt,Re,it,P,Pr=u(()=>{Se=Symbol.for("TypeBox.Transform"),yt=Symbol.for("TypeBox.Readonly"),Re=Symbol.for("TypeBox.Optional"),it=Symbol.for("TypeBox.Hint"),P=Symbol.for("TypeBox.Kind")});var M=u(()=>{Pr()});function Kn(t){return G(t)&&t[yt]==="Readonly"}function Ke(t){return G(t)&&t[Re]==="Optional"}function ra(t){return F(t,"Any")}function oa(t){return F(t,"Argument")}function kt(t){return F(t,"Array")}function kn(t){return F(t,"AsyncIterator")}function vn(t){return F(t,"BigInt")}function Kt(t){return F(t,"Boolean")}function vt(t){return F(t,"Computed")}function Pt(t){return F(t,"Constructor")}function Dh(t){return F(t,"Date")}function wt(t){return F(t,"Function")}function It(t){return F(t,"Integer")}function se(t){return F(t,"Intersect")}function Pn(t){return F(t,"Iterator")}function F(t,e){return G(t)&&P in t&&t[P]===e}function Ao(t){return Wt(t)||ze(t)||J(t)}function Qe(t){return F(t,"Literal")}function Je(t){return F(t,"MappedKey")}function ne(t){return F(t,"MappedResult")}function Yt(t){return F(t,"Never")}function Fh(t){return F(t,"Not")}function wr(t){return F(t,"Null")}function bt(t){return F(t,"Number")}function ge(t){return F(t,"Object")}function wn(t){return F(t,"Promise")}function In(t){return F(t,"Record")}function ue(t){return F(t,"Ref")}function ia(t){return F(t,"RegExp")}function Vt(t){return F(t,"String")}function Ir(t){return F(t,"Symbol")}function Ye(t){return F(t,"TemplateLiteral")}function Lh(t){return F(t,"This")}function Xt(t){return G(t)&&Se in t}function Xe(t){return F(t,"Tuple")}function br(t){return F(t,"Undefined")}function L(t){return F(t,"Union")}function Wh(t){return F(t,"Uint8Array")}function Bh(t){return F(t,"Unknown")}function Uh(t){return F(t,"Unsafe")}function Kh(t){return F(t,"Void")}function Vh(t){return G(t)&&P in t&&J(t[P])}function Ze(t){return ra(t)||oa(t)||kt(t)||Kt(t)||vn(t)||kn(t)||vt(t)||Pt(t)||Dh(t)||wt(t)||It(t)||se(t)||Pn(t)||Qe(t)||Je(t)||ne(t)||Yt(t)||Fh(t)||wr(t)||bt(t)||ge(t)||wn(t)||In(t)||ue(t)||ia(t)||Vt(t)||Ir(t)||Ye(t)||Lh(t)||Xe(t)||br(t)||L(t)||Wh(t)||Bh(t)||Uh(t)||Kh(t)||Vh(t)}var B=u(()=>{Le();M()});var m={};Po(m,{IsAny:()=>ou,IsArgument:()=>iu,IsArray:()=>su,IsAsyncIterator:()=>au,IsBigInt:()=>du,IsBoolean:()=>lu,IsComputed:()=>uu,IsConstructor:()=>pu,IsDate:()=>cu,IsFunction:()=>mu,IsImport:()=>Qh,IsInteger:()=>fu,IsIntersect:()=>gu,IsIterator:()=>hu,IsKind:()=>Ku,IsKindOf:()=>$,IsLiteral:()=>Ar,IsLiteralBoolean:()=>Jh,IsLiteralNumber:()=>yu,IsLiteralString:()=>Su,IsLiteralValue:()=>ku,IsMappedKey:()=>vu,IsMappedResult:()=>Pu,IsNever:()=>wu,IsNot:()=>Iu,IsNull:()=>bu,IsNumber:()=>xu,IsObject:()=>Au,IsOptional:()=>zh,IsPromise:()=>Ru,IsProperties:()=>Ro,IsReadonly:()=>Hh,IsRecord:()=>Tu,IsRecursive:()=>Yh,IsRef:()=>Mu,IsRegExp:()=>Cu,IsSchema:()=>xe,IsString:()=>_u,IsSymbol:()=>Eu,IsTemplateLiteral:()=>$u,IsThis:()=>Ou,IsTransform:()=>Nu,IsTuple:()=>Du,IsUint8Array:()=>Lu,IsUndefined:()=>Fu,IsUnion:()=>la,IsUnionLiteral:()=>Xh,IsUnknown:()=>Wu,IsUnsafe:()=>Bu,IsVoid:()=>Uu,TypeGuardUnknownTypeError:()=>sa});function tu(t){try{return new RegExp(t),!0}catch{return!1}}function aa(t){if(!J(t))return!1;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function nu(t){return da(t)||xe(t)}function xr(t){return fe(t)||yr(t)}function Y(t){return fe(t)||ze(t)}function da(t){return fe(t)||Wt(t)}function H(t){return fe(t)||J(t)}function jh(t){return fe(t)||J(t)&&aa(t)&&tu(t)}function Gh(t){return fe(t)||J(t)&&aa(t)}function ru(t){return fe(t)||xe(t)}function Hh(t){return G(t)&&t[yt]==="Readonly"}function zh(t){return G(t)&&t[Re]==="Optional"}function ou(t){return $(t,"Any")&&H(t.$id)}function iu(t){return $(t,"Argument")&&ze(t.index)}function su(t){return $(t,"Array")&&t.type==="array"&&H(t.$id)&&xe(t.items)&&Y(t.minItems)&&Y(t.maxItems)&&da(t.uniqueItems)&&ru(t.contains)&&Y(t.minContains)&&Y(t.maxContains)}function au(t){return $(t,"AsyncIterator")&&t.type==="AsyncIterator"&&H(t.$id)&&xe(t.items)}function du(t){return $(t,"BigInt")&&t.type==="bigint"&&H(t.$id)&&xr(t.exclusiveMaximum)&&xr(t.exclusiveMinimum)&&xr(t.maximum)&&xr(t.minimum)&&xr(t.multipleOf)}function lu(t){return $(t,"Boolean")&&t.type==="boolean"&&H(t.$id)}function uu(t){return $(t,"Computed")&&J(t.target)&&me(t.parameters)&&t.parameters.every(e=>xe(e))}function pu(t){return $(t,"Constructor")&&t.type==="Constructor"&&H(t.$id)&&me(t.parameters)&&t.parameters.every(e=>xe(e))&&xe(t.returns)}function cu(t){return $(t,"Date")&&t.type==="Date"&&H(t.$id)&&Y(t.exclusiveMaximumTimestamp)&&Y(t.exclusiveMinimumTimestamp)&&Y(t.maximumTimestamp)&&Y(t.minimumTimestamp)&&Y(t.multipleOfTimestamp)}function mu(t){return $(t,"Function")&&t.type==="Function"&&H(t.$id)&&me(t.parameters)&&t.parameters.every(e=>xe(e))&&xe(t.returns)}function Qh(t){return $(t,"Import")&&wo(t,"$defs")&&G(t.$defs)&&Ro(t.$defs)&&wo(t,"$ref")&&J(t.$ref)&&t.$ref in t.$defs}function fu(t){return $(t,"Integer")&&t.type==="integer"&&H(t.$id)&&Y(t.exclusiveMaximum)&&Y(t.exclusiveMinimum)&&Y(t.maximum)&&Y(t.minimum)&&Y(t.multipleOf)}function Ro(t){return G(t)&&Object.entries(t).every(([e,n])=>aa(e)&&xe(n))}function gu(t){return $(t,"Intersect")&&!(J(t.type)&&t.type!=="object")&&me(t.allOf)&&t.allOf.every(e=>xe(e)&&!Nu(e))&&H(t.type)&&(da(t.unevaluatedProperties)||ru(t.unevaluatedProperties))&&H(t.$id)}function hu(t){return $(t,"Iterator")&&t.type==="Iterator"&&H(t.$id)&&xe(t.items)}function $(t,e){return G(t)&&P in t&&t[P]===e}function Su(t){return Ar(t)&&J(t.const)}function yu(t){return Ar(t)&&ze(t.const)}function Jh(t){return Ar(t)&&Wt(t.const)}function Ar(t){return $(t,"Literal")&&H(t.$id)&&ku(t.const)}function ku(t){return Wt(t)||ze(t)||J(t)}function vu(t){return $(t,"MappedKey")&&me(t.keys)&&t.keys.every(e=>ze(e)||J(e))}function Pu(t){return $(t,"MappedResult")&&Ro(t.properties)}function wu(t){return $(t,"Never")&&G(t.not)&&Object.getOwnPropertyNames(t.not).length===0}function Iu(t){return $(t,"Not")&&xe(t.not)}function bu(t){return $(t,"Null")&&t.type==="null"&&H(t.$id)}function xu(t){return $(t,"Number")&&t.type==="number"&&H(t.$id)&&Y(t.exclusiveMaximum)&&Y(t.exclusiveMinimum)&&Y(t.maximum)&&Y(t.minimum)&&Y(t.multipleOf)}function Au(t){return $(t,"Object")&&t.type==="object"&&H(t.$id)&&Ro(t.properties)&&nu(t.additionalProperties)&&Y(t.minProperties)&&Y(t.maxProperties)}function Ru(t){return $(t,"Promise")&&t.type==="Promise"&&H(t.$id)&&xe(t.item)}function Tu(t){return $(t,"Record")&&t.type==="object"&&H(t.$id)&&nu(t.additionalProperties)&&G(t.patternProperties)&&(e=>{let n=Object.getOwnPropertyNames(e.patternProperties);return n.length===1&&tu(n[0])&&G(e.patternProperties)&&xe(e.patternProperties[n[0]])})(t)}function Yh(t){return G(t)&&it in t&&t[it]==="Recursive"}function Mu(t){return $(t,"Ref")&&H(t.$id)&&J(t.$ref)}function Cu(t){return $(t,"RegExp")&&H(t.$id)&&J(t.source)&&J(t.flags)&&Y(t.maxLength)&&Y(t.minLength)}function _u(t){return $(t,"String")&&t.type==="string"&&H(t.$id)&&Y(t.minLength)&&Y(t.maxLength)&&jh(t.pattern)&&Gh(t.format)}function Eu(t){return $(t,"Symbol")&&t.type==="symbol"&&H(t.$id)}function $u(t){return $(t,"TemplateLiteral")&&t.type==="string"&&J(t.pattern)&&t.pattern[0]==="^"&&t.pattern[t.pattern.length-1]==="$"}function Ou(t){return $(t,"This")&&H(t.$id)&&J(t.$ref)}function Nu(t){return G(t)&&Se in t}function Du(t){return $(t,"Tuple")&&t.type==="array"&&H(t.$id)&&ze(t.minItems)&&ze(t.maxItems)&&t.minItems===t.maxItems&&(fe(t.items)&&fe(t.additionalItems)&&t.minItems===0||me(t.items)&&t.items.every(e=>xe(e)))}function Fu(t){return $(t,"Undefined")&&t.type==="undefined"&&H(t.$id)}function Xh(t){return la(t)&&t.anyOf.every(e=>Su(e)||yu(e))}function la(t){return $(t,"Union")&&H(t.$id)&&G(t)&&me(t.anyOf)&&t.anyOf.every(e=>xe(e))}function Lu(t){return $(t,"Uint8Array")&&t.type==="Uint8Array"&&H(t.$id)&&Y(t.minByteLength)&&Y(t.maxByteLength)}function Wu(t){return $(t,"Unknown")&&H(t.$id)}function Bu(t){return $(t,"Unsafe")}function Uu(t){return $(t,"Void")&&t.type==="void"&&H(t.$id)}function Ku(t){return G(t)&&P in t&&J(t[P])&&!qh.includes(t[P])}function xe(t){return G(t)&&(ou(t)||iu(t)||su(t)||lu(t)||du(t)||au(t)||uu(t)||pu(t)||cu(t)||mu(t)||fu(t)||gu(t)||hu(t)||Ar(t)||vu(t)||Pu(t)||wu(t)||Iu(t)||bu(t)||xu(t)||Au(t)||Ru(t)||Tu(t)||Mu(t)||Cu(t)||_u(t)||Eu(t)||$u(t)||Ou(t)||Du(t)||Fu(t)||la(t)||Lu(t)||Wu(t)||Bu(t)||Uu(t)||Ku(t))}var sa,qh,Vu=u(()=>{Le();M();Ct();sa=class extends be{},qh=["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 ua=u(()=>{B();Vu();Le()});var qu=u(()=>{});var ju=u(()=>{qu()});var pa,Rr,ca,Zh,wA,Zt,en,Gu,Hu=u(()=>{pa="(true|false)",Rr="(0|[1-9][0-9]*)",ca="(.*)",Zh="(?!.*)",wA=`^${pa}$`,Zt=`^${Rr}$`,en=`^${ca}$`,Gu=`^${Zh}$`});var Tr=u(()=>{Hu()});var zu=u(()=>{});var Qu=u(()=>{});var Ju=u(()=>{zu();Qu()});function Yu(t,e){return t.includes(e)}function Xu(t){return[...new Set(t)]}function nS(t,e){return t.filter(n=>e.includes(n))}function rS(t,e){return t.reduce((n,r)=>nS(n,r),e)}function Zu(t){return t.length===1?t[0]:t.length>1?rS(t.slice(1),t[0]):[]}function ep(t){let e=[];for(let n of t)e.push(...n);return e}var tp=u(()=>{});var Mr=u(()=>{tp()});function tn(t){return h({[P]:"Any"},t)}var np=u(()=>{Ut();M()});var Cr=u(()=>{np()});function Vn(t,e){return h({[P]:"Array",type:"array",items:t},e)}var rp=u(()=>{T();M()});var _r=u(()=>{rp()});function op(t){return h({[P]:"Argument",index:t})}var ip=u(()=>{T();M()});var ma=u(()=>{ip()});function qn(t,e){return h({[P]:"AsyncIterator",type:"AsyncIterator",items:t},e)}var sp=u(()=>{M();T()});var Er=u(()=>{sp()});function ee(t,e,n){return h({[P]:"Computed",target:t,parameters:e},n)}var ap=u(()=>{Ut();Pr()});var nn=u(()=>{ap()});function oS(t,e){let{[e]:n,...r}=t;return r}function ae(t,e){return e.reduce((n,r)=>oS(n,r),t)}var To=u(()=>{});var jt=u(()=>{To()});function W(t){return h({[P]:"Never",not:{}},t)}var dp=u(()=>{T();M()});var Te=u(()=>{dp()});var lp=u(()=>{});function U(t){return h({[P]:"MappedResult",properties:t})}var fa=u(()=>{T();M()});function jn(t,e,n){return h({[P]:"Constructor",type:"Constructor",parameters:t,returns:e},n)}var up=u(()=>{T();M()});var $r=u(()=>{up()});function _t(t,e,n){return h({[P]:"Function",type:"Function",parameters:t,returns:e},n)}var pp=u(()=>{T();M()});var bn=u(()=>{pp()});function Or(t,e){return h({[P]:"Union",anyOf:t},e)}var ga=u(()=>{T();M()});function iS(t){return t.some(e=>Ke(e))}function cp(t){return t.map(e=>Ke(e)?sS(e):e)}function sS(t){return ae(t,[Re])}function aS(t,e){return iS(t)?$e(Or(cp(t),e)):Or(cp(t),e)}function Et(t,e){return t.length===1?h(t[0],e):t.length===0?W(e):aS(t,e)}var mp=u(()=>{T();M();jt();Te();Gt();ga();B()});var fp=u(()=>{});function q(t,e){return t.length===0?W(e):t.length===1?h(t[0],e):Or(t,e)}var gp=u(()=>{Te();T();ga()});var ye=u(()=>{mp();fp();gp()});function dS(t){return t.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function ha(t,e,n){return t[e]===n&&t.charCodeAt(e-1)!==92}function Ht(t,e){return ha(t,e,"(")}function Nr(t,e){return ha(t,e,")")}function hp(t,e){return ha(t,e,"|")}function lS(t){if(!(Ht(t,0)&&Nr(t,t.length-1)))return!1;let e=0;for(let n=0;n<t.length;n++)if(Ht(t,n)&&(e+=1),Nr(t,n)&&(e-=1),e===0&&n!==t.length-1)return!1;return!0}function uS(t){return t.slice(1,t.length-1)}function pS(t){let e=0;for(let n=0;n<t.length;n++)if(Ht(t,n)&&(e+=1),Nr(t,n)&&(e-=1),hp(t,n)&&e===0)return!0;return!1}function cS(t){for(let e=0;e<t.length;e++)if(Ht(t,e))return!0;return!1}function mS(t){let[e,n]=[0,0],r=[];for(let i=0;i<t.length;i++)if(Ht(t,i)&&(e+=1),Nr(t,i)&&(e-=1),hp(t,i)&&e===0){let s=t.slice(n,i);s.length>0&&r.push(Gn(s)),n=i+1}let o=t.slice(n);return o.length>0&&r.push(Gn(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function fS(t){function e(o,i){if(!Ht(o,i))throw new Mo("TemplateLiteralParser: Index must point to open parens");let s=0;for(let a=i;a<o.length;a++)if(Ht(o,a)&&(s+=1),Nr(o,a)&&(s-=1),s===0)return[i,a];throw new Mo("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,i){for(let s=i;s<o.length;s++)if(Ht(o,s))return[i,s];return[i,o.length]}let r=[];for(let o=0;o<t.length;o++)if(Ht(t,o)){let[i,s]=e(t,o),a=t.slice(i,s+1);r.push(Gn(a)),o=s}else{let[i,s]=n(t,o),a=t.slice(i,s);a.length>0&&r.push(Gn(a)),o=s-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function Gn(t){return lS(t)?Gn(uS(t)):pS(t)?mS(t):cS(t)?fS(t):{type:"const",const:dS(t)}}function Hn(t){return Gn(t.slice(1,t.length-1))}var Mo,Co=u(()=>{Ct();Mo=class extends be{}});function gS(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 hS(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 SS(t){return t.type==="const"&&t.const===".*"}function xn(t){return gS(t)||SS(t)?!1:hS(t)?!0:t.type==="and"?t.expr.every(e=>xn(e)):t.type==="or"?t.expr.every(e=>xn(e)):t.type==="const"?!0:(()=>{throw new Sa("Unknown expression type")})()}function Sp(t){let e=Hn(t.pattern);return xn(e)}var Sa,ya=u(()=>{Co();Ct();Sa=class extends be{}});function*yp(t){if(t.length===1)return yield*t[0];for(let e of t[0])for(let n of yp(t.slice(1)))yield`${e}${n}`}function*yS(t){return yield*yp(t.expr.map(e=>[...Dr(e)]))}function*kS(t){for(let e of t.expr)yield*Dr(e)}function*vS(t){return yield t.const}function*Dr(t){return t.type==="and"?yield*yS(t):t.type==="or"?yield*kS(t):t.type==="const"?yield*vS(t):(()=>{throw new ka("Unknown expression")})()}function _o(t){let e=Hn(t.pattern);return xn(e)?[...Dr(e)]:[]}var ka,va=u(()=>{ya();Co();Ct();ka=class extends be{}});function V(t,e){return h({[P]:"Literal",const:t,type:typeof t},e)}var kp=u(()=>{T();M()});var Ve=u(()=>{kp()});function Eo(t){return h({[P]:"Boolean",type:"boolean"},t)}var vp=u(()=>{M();Ut()});var $o=u(()=>{vp()});function zn(t){return h({[P]:"BigInt",type:"bigint"},t)}var Pp=u(()=>{M();Ut()});var Fr=u(()=>{Pp()});function st(t){return h({[P]:"Number",type:"number"},t)}var wp=u(()=>{T();M()});var An=u(()=>{wp()});function xt(t){return h({[P]:"String",type:"string"},t)}var Ip=u(()=>{T();M()});var Qn=u(()=>{Ip()});function*PS(t){let e=t.trim().replace(/"|'/g,"");return e==="boolean"?yield Eo():e==="number"?yield st():e==="bigint"?yield zn():e==="string"?yield xt():yield(()=>{let n=e.split("|").map(r=>V(r.trim()));return n.length===0?W():n.length===1?n[0]:Et(n)})()}function*wS(t){if(t[1]!=="{"){let e=V("$"),n=Pa(t.slice(1));return yield*[e,...n]}for(let e=2;e<t.length;e++)if(t[e]==="}"){let n=PS(t.slice(2,e)),r=Pa(t.slice(e+1));return yield*[...n,...r]}yield V(t)}function*Pa(t){for(let e=0;e<t.length;e++)if(t[e]==="$"){let n=V(t.slice(0,e)),r=wS(t.slice(e));return yield*[n,...r]}yield V(t)}function bp(t){return[...Pa(t)]}var wa=u(()=>{Ve();$o();Fr();An();Qn();ye();Te()});function IS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xp(t,e){return Ye(t)?t.pattern.slice(1,t.pattern.length-1):L(t)?`(${t.anyOf.map(n=>xp(n,e)).join("|")})`:bt(t)?`${e}${Rr}`:It(t)?`${e}${Rr}`:vn(t)?`${e}${Rr}`:Vt(t)?`${e}${ca}`:Qe(t)?`${e}${IS(t.const.toString())}`:Kt(t)?`${e}${pa}`:(()=>{throw new Ia(`Unexpected Kind '${t[P]}'`)})()}function ba(t){return`^${t.map(e=>xp(e,"")).join("")}$`}var Ia,xa=u(()=>{Tr();M();Ct();B();Ia=class extends be{}});function Rn(t){let n=_o(t).map(r=>V(r));return Et(n)}var Ap=u(()=>{ye();Ve();va()});function Oo(t,e){let n=J(t)?ba(bp(t)):ba(t);return h({[P]:"TemplateLiteral",type:"string",pattern:n},e)}var Rp=u(()=>{T();wa();xa();Le();M()});var zt=u(()=>{ya();va();wa();Co();xa();Ap();Rp()});function bS(t){return _o(t).map(n=>n.toString())}function xS(t){let e=[];for(let n of t)e.push(...qe(n));return e}function AS(t){return[t.toString()]}function qe(t){return[...new Set(Ye(t)?bS(t):L(t)?xS(t.anyOf):Qe(t)?AS(t.const):bt(t)?["[number]"]:It(t)?["[number]"]:[])]}var No=u(()=>{zt();B()});function RS(t,e,n){let r={};for(let o of Object.getOwnPropertyNames(e))r[o]=rn(t,qe(e[o]),n);return r}function TS(t,e,n){return RS(t,e.properties,n)}function Tp(t,e,n){let r=TS(t,e,n);return U(r)}var Aa=u(()=>{we();No();$t()});function Cp(t,e){return t.map(n=>_p(n,e))}function MS(t){return t.filter(e=>!Yt(e))}function CS(t,e){return Do(MS(Cp(t,e)))}function _S(t){return t.some(e=>Yt(e))?[]:t}function ES(t,e){return Et(_S(Cp(t,e)))}function $S(t,e){return e in t?t[e]:e==="[number]"?Et(t):W()}function OS(t,e){return e==="[number]"?t:W()}function NS(t,e){return e in t?t[e]:W()}function _p(t,e){return se(t)?CS(t.allOf,e):L(t)?ES(t.anyOf,e):Xe(t)?$S(t.items??[],e):kt(t)?OS(t.items,e):ge(t)?NS(t.properties,e):W()}function Ra(t,e){return e.map(n=>_p(t,n))}function Mp(t,e){return Et(Ra(t,e))}function rn(t,e,n){if(ue(t)||ue(e)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!Ze(t)||!Ze(e))throw new be(r);return ee("Index",[t,e])}return ne(e)?Tp(t,e,n):Je(e)?Ep(t,e,n):h(Ze(e)?Mp(t,qe(e)):Mp(t,e),n)}var Ta=u(()=>{T();Ct();nn();Te();at();ye();No();Ma();Aa();B()});function DS(t,e,n){return{[e]:rn(t,[e],te(n))}}function FS(t,e,n){return e.reduce((r,o)=>({...r,...DS(t,o,n)}),{})}function LS(t,e,n){return FS(t,e.keys,n)}function Ep(t,e,n){let r=LS(t,e,n);return U(r)}var Ma=u(()=>{Ta();we();Ue()});var $t=u(()=>{Ma();Aa();No();Ta()});function Jn(t,e){return h({[P]:"Iterator",type:"Iterator",items:t},e)}var $p=u(()=>{T();M()});var Lr=u(()=>{$p()});function WS(t){return globalThis.Object.keys(t).filter(e=>!Ke(t[e]))}function BS(t,e){let n=WS(t),r=n.length>0?{[P]:"Object",type:"object",required:n,properties:t}:{[P]:"Object",type:"object",properties:t};return h(r,e)}var z,Op=u(()=>{T();M();B();z=BS});var et=u(()=>{Op()});function Fo(t,e){return h({[P]:"Promise",type:"Promise",item:t},e)}var Np=u(()=>{T();M()});var Lo=u(()=>{Np()});function US(t){return h(ae(t,[yt]))}function KS(t){return h({...t,[yt]:"Readonly"})}function VS(t,e){return e===!1?US(t):KS(t)}function je(t,e){let n=e??!0;return ne(t)?Dp(t,n):VS(t,n)}var Ca=u(()=>{T();M();jt();_a();B()});function qS(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=je(t[r],e);return n}function jS(t,e){return qS(t.properties,e)}function Dp(t,e){let n=jS(t,e);return U(n)}var _a=u(()=>{we();Ca()});var Tn=u(()=>{_a();Ca()});function dt(t,e){return h(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 Fp=u(()=>{T();M()});var on=u(()=>{Fp()});function Lp(t,e){return t in e?lt(t,e[t]):U(e)}function GS(t){return{[t]:V(t)}}function HS(t){let e={};for(let n of t)e[n]=V(n);return e}function zS(t,e){return Yu(e,t)?GS(t):HS(e)}function QS(t,e){let n=zS(t,e);return Lp(t,n)}function Wr(t,e){return e.map(n=>lt(t,n))}function JS(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=lt(t,e[r]);return n}function lt(t,e){let n={...e};return Ke(e)?$e(lt(t,ae(e,[Re]))):Kn(e)?je(lt(t,ae(e,[yt]))):ne(e)?Lp(t,e.properties):Je(e)?QS(t,e.keys):Pt(e)?jn(Wr(t,e.parameters),lt(t,e.returns),n):wt(e)?_t(Wr(t,e.parameters),lt(t,e.returns),n):kn(e)?qn(lt(t,e.items),n):Pn(e)?Jn(lt(t,e.items),n):se(e)?Oe(Wr(t,e.allOf),n):L(e)?q(Wr(t,e.anyOf),n):Xe(e)?dt(Wr(t,e.items??[]),n):ge(e)?z(JS(t,e.properties),n):kt(e)?Vn(lt(t,e.items),n):wn(e)?Fo(lt(t,e.item),n):e}function YS(t,e){let n={};for(let r of t)n[r]=lt(r,e);return n}function Wp(t,e,n){let r=Ze(t)?qe(t):t,o=e({[P]:"MappedKey",keys:r}),i=YS(r,o);return z(i,n)}var Bp=u(()=>{M();jt();_r();Er();$r();bn();$t();at();Lr();Ve();et();Gt();Lo();Tn();on();ye();Mr();fa();B()});var we=u(()=>{lp();fa();Bp()});function XS(t){return h(ae(t,[Re]))}function ZS(t){return h({...t,[Re]:"Optional"})}function ey(t,e){return e===!1?XS(t):ZS(t)}function $e(t,e){let n=e??!0;return ne(t)?Up(t,n):ey(t,n)}var Ea=u(()=>{T();M();jt();$a();B()});function ty(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=$e(t[r],e);return n}function ny(t,e){return ty(t.properties,e)}function Up(t,e){let n=ny(t,e);return U(n)}var $a=u(()=>{we();Ea()});var Gt=u(()=>{$a();Ea()});function Br(t,e={}){let n=t.every(o=>ge(o)),r=Ze(e.unevaluatedProperties)?{unevaluatedProperties:e.unevaluatedProperties}:{};return h(e.unevaluatedProperties===!1||Ze(e.unevaluatedProperties)||n?{...r,[P]:"Intersect",type:"object",allOf:t}:{...r,[P]:"Intersect",allOf:t},e)}var Oa=u(()=>{T();M();B()});function ry(t){return t.every(e=>Ke(e))}function oy(t){return ae(t,[Re])}function Kp(t){return t.map(e=>Ke(e)?oy(e):e)}function iy(t,e){return ry(t)?$e(Br(Kp(t),e)):Br(Kp(t),e)}function Do(t,e={}){if(t.length===1)return h(t[0],e);if(t.length===0)return W(e);if(t.some(n=>Xt(n)))throw new Error("Cannot intersect transform types");return iy(t,e)}var Vp=u(()=>{M();T();jt();Te();Gt();Oa();B()});var qp=u(()=>{});function Oe(t,e){if(t.length===1)return h(t[0],e);if(t.length===0)return W(e);if(t.some(n=>Xt(n)))throw new Error("Cannot intersect transform types");return Br(t,e)}var jp=u(()=>{T();Te();Oa();B()});var at=u(()=>{Vp();qp();jp()});function Ot(...t){let[e,n]=typeof t[0]=="string"?[t[0],t[1]]:[t[0].$id,t[1]];if(typeof e!="string")throw new be("Ref: $ref must be a string");return h({[P]:"Ref",$ref:e},n)}var Gp=u(()=>{Ct();T();M()});var Mn=u(()=>{Gp()});function sy(t,e){return ee("Awaited",[ee(t,e)])}function ay(t){return ee("Awaited",[Ot(t)])}function dy(t){return Oe(Hp(t))}function ly(t){return q(Hp(t))}function uy(t){return Yn(t)}function Hp(t){return t.map(e=>Yn(e))}function Yn(t,e){return h(vt(t)?sy(t.target,t.parameters):se(t)?dy(t.allOf):L(t)?ly(t.anyOf):wn(t)?uy(t.item):ue(t)?ay(t.$ref):t,e)}var zp=u(()=>{T();nn();at();ye();Mn();B()});var Wo=u(()=>{zp()});function Qp(t){let e=[];for(let n of t)e.push(Ur(n));return e}function py(t){let e=Qp(t);return ep(e)}function cy(t){let e=Qp(t);return Zu(e)}function my(t){return t.map((e,n)=>n.toString())}function fy(t){return["[number]"]}function gy(t){return globalThis.Object.getOwnPropertyNames(t)}function hy(t){return Sy?globalThis.Object.getOwnPropertyNames(t).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function Ur(t){return se(t)?py(t.allOf):L(t)?cy(t.anyOf):Xe(t)?my(t.items??[]):kt(t)?fy(t.items):ge(t)?gy(t.properties):In(t)?hy(t.patternProperties):[]}var Sy,Na=u(()=>{Mr();B();Sy=!1});function yy(t,e){return ee("KeyOf",[ee(t,e)])}function ky(t){return ee("KeyOf",[Ot(t)])}function vy(t,e){let n=Ur(t),r=Py(n),o=Et(r);return h(o,e)}function Py(t){return t.map(e=>e==="[number]"?st():V(e))}function Xn(t,e){return vt(t)?yy(t.target,t.parameters):ue(t)?ky(t.$ref):ne(t)?Jp(t,e):vy(t,e)}var Da=u(()=>{T();Ve();An();nn();Mn();Na();ye();Fa();B()});function wy(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=Xn(t[r],te(e));return n}function Iy(t,e){return wy(t.properties,e)}function Jp(t,e){let n=Iy(t,e);return U(n)}var Fa=u(()=>{we();Da();Ue()});var Yp=u(()=>{});var Kr=u(()=>{Fa();Yp();Na();Da()});function by(t){let e=[];for(let n of t)e.push(...Ur(n));return Xu(e)}function xy(t){return t.filter(e=>!Yt(e))}function Ay(t,e){let n=[];for(let r of t)n.push(...Ra(r,[e]));return xy(n)}function Ry(t,e){let n={};for(let r of e)n[r]=Do(Ay(t,r));return n}function Xp(t,e){let n=by(t),r=Ry(t,n);return z(r,e)}var Zp=u(()=>{at();$t();Kr();et();Mr();B()});var La=u(()=>{Zp()});function Bo(t){return h({[P]:"Date",type:"Date"},t)}var ec=u(()=>{M();T()});var Uo=u(()=>{ec()});function Ko(t){return h({[P]:"Null",type:"null"},t)}var tc=u(()=>{T();M()});var Vo=u(()=>{tc()});function qo(t){return h({[P]:"Symbol",type:"symbol"},t)}var nc=u(()=>{T();M()});var jo=u(()=>{nc()});function Go(t){return h({[P]:"Undefined",type:"undefined"},t)}var rc=u(()=>{T();M()});var Ho=u(()=>{rc()});function zo(t){return h({[P]:"Uint8Array",type:"Uint8Array"},t)}var oc=u(()=>{T();M()});var Qo=u(()=>{oc()});function sn(t){return h({[P]:"Unknown"},t)}var ic=u(()=>{T();M()});var Zn=u(()=>{ic()});function Ty(t){return t.map(e=>Wa(e,!1))}function My(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=je(Wa(t[n],!1));return e}function Jo(t,e){return e===!0?t:je(t)}function Wa(t,e){return Ys(t)?Jo(tn(),e):Zs(t)?Jo(tn(),e):me(t)?je(dt(Ty(t))):Bt(t)?zo():yn(t)?Bo():G(t)?Jo(z(My(t)),e):Xs(t)?Jo(_t([],sn()),e):fe(t)?Go():ea(t)?Ko():ta(t)?qo():yr(t)?zn():ze(t)?V(t):Wt(t)?V(t):J(t)?V(t):z({})}function sc(t,e){return h(Wa(t,!0),e)}var ac=u(()=>{Cr();Fr();Uo();bn();Ve();Vo();et();jo();on();Tn();Ho();Qo();Zn();Ut();Le()});var Ba=u(()=>{ac()});function dc(t,e){return Pt(t)?dt(t.parameters,e):W(e)}var lc=u(()=>{on();Te();B()});var Ua=u(()=>{lc()});function uc(t,e){if(fe(t))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(t).filter(i=>isNaN(i)).map(i=>t[i]),o=[...new Set(n)].map(i=>V(i));return q(o,{...e,[it]:"Enum"})}var pc=u(()=>{Ve();M();ye();Le()});var Ka=u(()=>{pc()});function ut(t){return t===S.False?t:S.True}function er(t){throw new qa(t)}function ke(t){return m.IsNever(t)||m.IsIntersect(t)||m.IsUnion(t)||m.IsUnknown(t)||m.IsAny(t)}function ve(t,e){return m.IsNever(e)?yc(t,e):m.IsIntersect(e)?Yo(t,e):m.IsUnion(e)?za(t,e):m.IsUnknown(e)?wc(t,e):m.IsAny(e)?Ha(t,e):er("StructuralRight")}function Ha(t,e){return S.True}function Cy(t,e){return m.IsIntersect(e)?Yo(t,e):m.IsUnion(e)&&e.anyOf.some(n=>m.IsAny(n)||m.IsUnknown(n))?S.True:m.IsUnion(e)?S.Union:m.IsUnknown(e)||m.IsAny(e)?S.True:S.Union}function _y(t,e){return m.IsUnknown(t)?S.False:m.IsAny(t)?S.Union:m.IsNever(t)?S.True:S.False}function Ey(t,e){return m.IsObject(e)&&Xo(e)?S.True:ke(e)?ve(t,e):m.IsArray(e)?ut(Q(t.items,e.items)):S.False}function $y(t,e){return ke(e)?ve(t,e):m.IsAsyncIterator(e)?ut(Q(t.items,e.items)):S.False}function Oy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsBigInt(e)?S.True:S.False}function hc(t,e){return m.IsLiteralBoolean(t)||m.IsBoolean(t)?S.True:S.False}function Ny(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsBoolean(e)?S.True:S.False}function Dy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsConstructor(e)?t.parameters.length>e.parameters.length?S.False:t.parameters.every((n,r)=>ut(Q(e.parameters[r],n))===S.True)?ut(Q(t.returns,e.returns)):S.False:S.False}function Fy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsDate(e)?S.True:S.False}function Ly(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsFunction(e)?t.parameters.length>e.parameters.length?S.False:t.parameters.every((n,r)=>ut(Q(e.parameters[r],n))===S.True)?ut(Q(t.returns,e.returns)):S.False:S.False}function Sc(t,e){return m.IsLiteral(t)&&Ee.IsNumber(t.const)||m.IsNumber(t)||m.IsInteger(t)?S.True:S.False}function Wy(t,e){return m.IsInteger(e)||m.IsNumber(e)?S.True:ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):S.False}function Yo(t,e){return e.allOf.every(n=>Q(t,n)===S.True)?S.True:S.False}function By(t,e){return t.allOf.some(n=>Q(n,e)===S.True)?S.True:S.False}function Uy(t,e){return ke(e)?ve(t,e):m.IsIterator(e)?ut(Q(t.items,e.items)):S.False}function Ky(t,e){return m.IsLiteral(e)&&e.const===t.const?S.True:ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsString(e)?Pc(t,e):m.IsNumber(e)?kc(t,e):m.IsInteger(e)?Sc(t,e):m.IsBoolean(e)?hc(t,e):S.False}function yc(t,e){return S.False}function Vy(t,e){return S.True}function cc(t){let[e,n]=[t,0];for(;m.IsNot(e);)e=e.not,n+=1;return n%2===0?e:sn()}function qy(t,e){return m.IsNot(t)?Q(cc(t),e):m.IsNot(e)?Q(t,cc(e)):er("Invalid fallthrough for Not")}function jy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsNull(e)?S.True:S.False}function kc(t,e){return m.IsLiteralNumber(t)||m.IsNumber(t)||m.IsInteger(t)?S.True:S.False}function Gy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsInteger(e)||m.IsNumber(e)?S.True:S.False}function Ge(t,e){return Object.getOwnPropertyNames(t.properties).length===e}function mc(t){return Xo(t)}function fc(t){return Ge(t,0)||Ge(t,1)&&"description"in t.properties&&m.IsUnion(t.properties.description)&&t.properties.description.anyOf.length===2&&(m.IsString(t.properties.description.anyOf[0])&&m.IsUndefined(t.properties.description.anyOf[1])||m.IsString(t.properties.description.anyOf[1])&&m.IsUndefined(t.properties.description.anyOf[0]))}function Va(t){return Ge(t,0)}function gc(t){return Ge(t,0)}function Hy(t){return Ge(t,0)}function zy(t){return Ge(t,0)}function Qy(t){return Xo(t)}function Jy(t){let e=st();return Ge(t,0)||Ge(t,1)&&"length"in t.properties&&ut(Q(t.properties.length,e))===S.True}function Yy(t){return Ge(t,0)}function Xo(t){let e=st();return Ge(t,0)||Ge(t,1)&&"length"in t.properties&&ut(Q(t.properties.length,e))===S.True}function Xy(t){let e=_t([tn()],tn());return Ge(t,0)||Ge(t,1)&&"then"in t.properties&&ut(Q(t.properties.then,e))===S.True}function vc(t,e){return Q(t,e)===S.False||m.IsOptional(t)&&!m.IsOptional(e)?S.False:S.True}function Ne(t,e){return m.IsUnknown(t)?S.False:m.IsAny(t)?S.Union:m.IsNever(t)||m.IsLiteralString(t)&&mc(e)||m.IsLiteralNumber(t)&&Va(e)||m.IsLiteralBoolean(t)&&gc(e)||m.IsSymbol(t)&&fc(e)||m.IsBigInt(t)&&Hy(e)||m.IsString(t)&&mc(e)||m.IsSymbol(t)&&fc(e)||m.IsNumber(t)&&Va(e)||m.IsInteger(t)&&Va(e)||m.IsBoolean(t)&&gc(e)||m.IsUint8Array(t)&&Qy(e)||m.IsDate(t)&&zy(e)||m.IsConstructor(t)&&Yy(e)||m.IsFunction(t)&&Jy(e)?S.True:m.IsRecord(t)&&m.IsString(ja(t))?e[it]==="Record"?S.True:S.False:m.IsRecord(t)&&m.IsNumber(ja(t))&&Ge(e,0)?S.True:S.False}function Zy(t,e){return ke(e)?ve(t,e):m.IsRecord(e)?pt(t,e):m.IsObject(e)?(()=>{for(let n of Object.getOwnPropertyNames(e.properties)){if(!(n in t.properties)&&!m.IsOptional(e.properties[n]))return S.False;if(m.IsOptional(e.properties[n]))return S.True;if(vc(t.properties[n],e.properties[n])===S.False)return S.False}return S.True})():S.False}function ek(t,e){return ke(e)?ve(t,e):m.IsObject(e)&&Xy(e)?S.True:m.IsPromise(e)?ut(Q(t.item,e.item)):S.False}function ja(t){return Zt in t.patternProperties?st():en in t.patternProperties?xt():er("Unknown record key pattern")}function Ga(t){return Zt in t.patternProperties?t.patternProperties[Zt]:en in t.patternProperties?t.patternProperties[en]:er("Unable to get record value schema")}function pt(t,e){let[n,r]=[ja(e),Ga(e)];return m.IsLiteralString(t)&&m.IsNumber(n)&&ut(Q(t,r))===S.True?S.True:m.IsUint8Array(t)&&m.IsNumber(n)||m.IsString(t)&&m.IsNumber(n)||m.IsArray(t)&&m.IsNumber(n)?Q(t,r):m.IsObject(t)?(()=>{for(let o of Object.getOwnPropertyNames(t.properties))if(vc(r,t.properties[o])===S.False)return S.False;return S.True})():S.False}function tk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?Q(Ga(t),Ga(e)):S.False}function nk(t,e){let n=m.IsRegExp(t)?xt():t,r=m.IsRegExp(e)?xt():e;return Q(n,r)}function Pc(t,e){return m.IsLiteral(t)&&Ee.IsString(t.const)||m.IsString(t)?S.True:S.False}function rk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsString(e)?S.True:S.False}function ok(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsSymbol(e)?S.True:S.False}function ik(t,e){return m.IsTemplateLiteral(t)?Q(Rn(t),e):m.IsTemplateLiteral(e)?Q(t,Rn(e)):er("Invalid fallthrough for TemplateLiteral")}function sk(t,e){return m.IsArray(e)&&t.items!==void 0&&t.items.every(n=>Q(n,e.items)===S.True)}function ak(t,e){return m.IsNever(t)?S.True:m.IsUnknown(t)?S.False:m.IsAny(t)?S.Union:S.False}function dk(t,e){return ke(e)?ve(t,e):m.IsObject(e)&&Xo(e)||m.IsArray(e)&&sk(t,e)?S.True:m.IsTuple(e)?Ee.IsUndefined(t.items)&&!Ee.IsUndefined(e.items)||!Ee.IsUndefined(t.items)&&Ee.IsUndefined(e.items)?S.False:Ee.IsUndefined(t.items)&&!Ee.IsUndefined(e.items)||t.items.every((n,r)=>Q(n,e.items[r])===S.True)?S.True:S.False:S.False}function lk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsUint8Array(e)?S.True:S.False}function uk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?Ne(t,e):m.IsRecord(e)?pt(t,e):m.IsVoid(e)?mk(t,e):m.IsUndefined(e)?S.True:S.False}function za(t,e){return e.anyOf.some(n=>Q(t,n)===S.True)?S.True:S.False}function pk(t,e){return t.anyOf.every(n=>Q(n,e)===S.True)?S.True:S.False}function wc(t,e){return S.True}function ck(t,e){return m.IsNever(e)?yc(t,e):m.IsIntersect(e)?Yo(t,e):m.IsUnion(e)?za(t,e):m.IsAny(e)?Ha(t,e):m.IsString(e)?Pc(t,e):m.IsNumber(e)?kc(t,e):m.IsInteger(e)?Sc(t,e):m.IsBoolean(e)?hc(t,e):m.IsArray(e)?_y(t,e):m.IsTuple(e)?ak(t,e):m.IsObject(e)?Ne(t,e):m.IsUnknown(e)?S.True:S.False}function mk(t,e){return m.IsUndefined(t)||m.IsUndefined(t)?S.True:S.False}function fk(t,e){return m.IsIntersect(e)?Yo(t,e):m.IsUnion(e)?za(t,e):m.IsUnknown(e)?wc(t,e):m.IsAny(e)?Ha(t,e):m.IsObject(e)?Ne(t,e):m.IsVoid(e)?S.True:S.False}function Q(t,e){return m.IsTemplateLiteral(t)||m.IsTemplateLiteral(e)?ik(t,e):m.IsRegExp(t)||m.IsRegExp(e)?nk(t,e):m.IsNot(t)||m.IsNot(e)?qy(t,e):m.IsAny(t)?Cy(t,e):m.IsArray(t)?Ey(t,e):m.IsBigInt(t)?Oy(t,e):m.IsBoolean(t)?Ny(t,e):m.IsAsyncIterator(t)?$y(t,e):m.IsConstructor(t)?Dy(t,e):m.IsDate(t)?Fy(t,e):m.IsFunction(t)?Ly(t,e):m.IsInteger(t)?Wy(t,e):m.IsIntersect(t)?By(t,e):m.IsIterator(t)?Uy(t,e):m.IsLiteral(t)?Ky(t,e):m.IsNever(t)?Vy(t,e):m.IsNull(t)?jy(t,e):m.IsNumber(t)?Gy(t,e):m.IsObject(t)?Zy(t,e):m.IsRecord(t)?tk(t,e):m.IsString(t)?rk(t,e):m.IsSymbol(t)?ok(t,e):m.IsTuple(t)?dk(t,e):m.IsPromise(t)?ek(t,e):m.IsUint8Array(t)?lk(t,e):m.IsUndefined(t)?uk(t,e):m.IsUnion(t)?pk(t,e):m.IsUnknown(t)?ck(t,e):m.IsVoid(t)?fk(t,e):er(`Unknown left type operand '${t[P]}'`)}function an(t,e){return Q(t,e)}var qa,S,Qa=u(()=>{Cr();bn();An();Qn();Zn();zt();Tr();M();Ct();ua();qa=class extends be{};(function(t){t[t.Union=0]="Union",t[t.True=1]="True",t[t.False=2]="False"})(S||(S={}))});function gk(t,e,n,r,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=tr(t[s],e,n,r,te(o));return i}function hk(t,e,n,r,o){return gk(t.properties,e,n,r,o)}function Ic(t,e,n,r,o){let i=hk(t,e,n,r,o);return U(i)}var Ja=u(()=>{we();Zo();Ue()});function Sk(t,e,n,r){let o=an(t,e);return o===S.Union?q([n,r]):o===S.True?n:r}function tr(t,e,n,r,o){return ne(t)?Ic(t,e,n,r,o):Je(t)?h(bc(t,e,n,r,o)):h(Sk(t,e,n,r),o)}var Zo=u(()=>{T();ye();Qa();Ya();Ja();B()});function yk(t,e,n,r,o){return{[t]:tr(V(t),e,n,r,te(o))}}function kk(t,e,n,r,o){return t.reduce((i,s)=>({...i,...yk(s,e,n,r,o)}),{})}function vk(t,e,n,r,o){return kk(t.keys,e,n,r,o)}function bc(t,e,n,r,o){let i=vk(t,e,n,r,o);return U(i)}var Ya=u(()=>{we();Ve();Zo();Ue()});var xc=u(()=>{});var Vr=u(()=>{Qa();Ya();Ja();xc();Zo()});function Ac(t,e){return nr(Rn(t),e)}var Xa=u(()=>{ei();zt()});function Pk(t,e){let n=t.filter(r=>an(r,e)===S.False);return n.length===1?n[0]:q(n)}function nr(t,e,n={}){return Ye(t)?h(Ac(t,e),n):ne(t)?h(Rc(t,e),n):h(L(t)?Pk(t.anyOf,e):an(t,e)!==S.False?W():t,n)}var ei=u(()=>{T();ye();Te();Vr();Za();Xa();B()});function wk(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=nr(t[r],e);return n}function Ik(t,e){return wk(t.properties,e)}function Rc(t,e){let n=Ik(t,e);return U(n)}var Za=u(()=>{we();ei()});var ed=u(()=>{Za();Xa();ei()});function Tc(t,e){return rr(Rn(t),e)}var td=u(()=>{ti();zt()});function bk(t,e){let n=t.filter(r=>an(r,e)!==S.False);return n.length===1?n[0]:q(n)}function rr(t,e,n){return Ye(t)?h(Tc(t,e),n):ne(t)?h(Mc(t,e),n):h(L(t)?bk(t.anyOf,e):an(t,e)!==S.False?t:W(),n)}var ti=u(()=>{T();ye();Te();Vr();nd();td();B()});function xk(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=rr(t[r],e);return n}function Ak(t,e){return xk(t.properties,e)}function Mc(t,e){let n=Ak(t,e);return U(n)}var nd=u(()=>{we();ti()});var rd=u(()=>{nd();td();ti()});function Cc(t,e){return Pt(t)?h(t.returns,e):W(e)}var _c=u(()=>{T();Te();B()});var od=u(()=>{_c()});function ni(t){return je($e(t))}var Ec=u(()=>{Tn();Gt()});var ri=u(()=>{Ec()});function Cn(t,e,n){return h({[P]:"Record",type:"object",patternProperties:{[t]:e}},n)}function id(t,e,n){let r={};for(let o of t)r[o]=e;return z(r,{...n,[it]:"Record"})}function Rk(t,e,n){return Sp(t)?id(qe(t),e,n):Cn(t.pattern,e,n)}function Tk(t,e,n){return id(qe(q(t)),e,n)}function Mk(t,e,n){return id([t.toString()],e,n)}function Ck(t,e,n){return Cn(t.source,e,n)}function _k(t,e,n){let r=fe(t.pattern)?en:t.pattern;return Cn(r,e,n)}function Ek(t,e,n){return Cn(en,e,n)}function $k(t,e,n){return Cn(Gu,e,n)}function Ok(t,e,n){return z({true:e,false:e},n)}function Nk(t,e,n){return Cn(Zt,e,n)}function Dk(t,e,n){return Cn(Zt,e,n)}function oi(t,e,n={}){return L(t)?Tk(t.anyOf,e,n):Ye(t)?Rk(t,e,n):Qe(t)?Mk(t.const,e,n):Kt(t)?Ok(t,e,n):It(t)?Nk(t,e,n):bt(t)?Dk(t,e,n):ia(t)?Ck(t,e,n):Vt(t)?_k(t,e,n):ra(t)?Ek(t,e,n):Yt(t)?$k(t,e,n):W(n)}function ii(t){return globalThis.Object.getOwnPropertyNames(t.patternProperties)[0]}function $c(t){let e=ii(t);return e===en?xt():e===Zt?st():xt({pattern:e})}function si(t){return t.patternProperties[ii(t)]}var Oc=u(()=>{T();M();Te();An();et();Qn();ye();zt();Tr();$t();Le();B()});var qr=u(()=>{Oc()});function Fk(t,e){return e.parameters=jr(t,e.parameters),e.returns=At(t,e.returns),e}function Lk(t,e){return e.parameters=jr(t,e.parameters),e.returns=At(t,e.returns),e}function Wk(t,e){return e.allOf=jr(t,e.allOf),e}function Bk(t,e){return e.anyOf=jr(t,e.anyOf),e}function Uk(t,e){return fe(e.items)||(e.items=jr(t,e.items)),e}function Kk(t,e){return e.items=At(t,e.items),e}function Vk(t,e){return e.items=At(t,e.items),e}function qk(t,e){return e.items=At(t,e.items),e}function jk(t,e){return e.item=At(t,e.item),e}function Gk(t,e){let n=Jk(t,e.properties);return{...e,...z(n)}}function Hk(t,e){let n=At(t,$c(e)),r=At(t,si(e)),o=oi(n,r);return{...e,...o}}function zk(t,e){return e.index in t?t[e.index]:sn()}function Qk(t,e){let n=Kn(e),r=Ke(e),o=At(t,e);return n&&r?ni(o):n&&!r?je(o):!n&&r?$e(o):o}function Jk(t,e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,r)=>({...n,[r]:Qk(t,e[r])}),{})}function jr(t,e){return e.map(n=>At(t,n))}function At(t,e){return Pt(e)?Fk(t,e):wt(e)?Lk(t,e):se(e)?Wk(t,e):L(e)?Bk(t,e):Xe(e)?Uk(t,e):kt(e)?Kk(t,e):kn(e)?Vk(t,e):Pn(e)?qk(t,e):wn(e)?jk(t,e):ge(e)?Gk(t,e):In(e)?Hk(t,e):oa(e)?zk(t,e):e}function Nc(t,e){return At(e,Un(t))}var Dc=u(()=>{bo();Zn();ri();Tn();Gt();et();qr();Le();B()});var sd=u(()=>{Dc()});function Fc(t){return h({[P]:"Integer",type:"integer"},t)}var Lc=u(()=>{T();M()});var ad=u(()=>{Lc()});function Yk(t,e,n){return{[t]:Rt(V(t),e,te(n))}}function Xk(t,e,n){return t.reduce((o,i)=>({...o,...Yk(i,e,n)}),{})}function Zk(t,e,n){return Xk(t.keys,e,n)}function Wc(t,e,n){let r=Zk(t,e,n);return U(r)}var dd=u(()=>{we();_n();Ve();Ue()});function ev(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toLowerCase(),n].join("")}function tv(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toUpperCase(),n].join("")}function nv(t){return t.toUpperCase()}function rv(t){return t.toLowerCase()}function ov(t,e,n){let r=Hn(t.pattern);if(!xn(r))return{...t,pattern:Bc(t.pattern,e)};let s=[...Dr(r)].map(l=>V(l)),a=Uc(s,e),d=q(a);return Oo([d],n)}function Bc(t,e){return typeof t=="string"?e==="Uncapitalize"?ev(t):e==="Capitalize"?tv(t):e==="Uppercase"?nv(t):e==="Lowercase"?rv(t):t:t.toString()}function Uc(t,e){return t.map(n=>Rt(n,e))}function Rt(t,e,n={}){return Je(t)?Wc(t,e,n):Ye(t)?ov(t,e,n):L(t)?q(Uc(t.anyOf,e),n):Qe(t)?V(Bc(t.const,e),n):h(t,n)}var _n=u(()=>{T();zt();dd();Ve();ye();B()});function Kc(t,e={}){return Rt(t,"Capitalize",e)}var Vc=u(()=>{_n()});function qc(t,e={}){return Rt(t,"Lowercase",e)}var jc=u(()=>{_n()});function Gc(t,e={}){return Rt(t,"Uncapitalize",e)}var Hc=u(()=>{_n()});function zc(t,e={}){return Rt(t,"Uppercase",e)}var Qc=u(()=>{_n()});var ld=u(()=>{Vc();dd();_n();jc();Hc();Qc()});function iv(t,e,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(t))r[o]=dn(t[o],e,te(n));return r}function sv(t,e,n){return iv(t.properties,e,n)}function Jc(t,e,n){let r=sv(t,e,n);return U(r)}var ud=u(()=>{we();ai();Ue()});function av(t,e){return t.map(n=>pd(n,e))}function dv(t,e){return t.map(n=>pd(n,e))}function lv(t,e){let{[e]:n,...r}=t;return r}function uv(t,e){return e.reduce((n,r)=>lv(n,r),t)}function pv(t,e,n){let r=ae(t,[Se,"$id","required","properties"]),o=uv(n,e);return z(o,r)}function cv(t){let e=t.reduce((n,r)=>Ao(r)?[...n,V(r)]:n,[]);return q(e)}function pd(t,e){return se(t)?Oe(av(t.allOf,e)):L(t)?q(dv(t.anyOf,e)):ge(t)?pv(t,e,t.properties):z({})}function dn(t,e,n){let r=me(e)?cv(e):e,o=Ze(e)?qe(e):e,i=ue(t),s=ue(e);return ne(t)?Jc(t,o,n):Je(e)?Yc(t,e,n):i&&s?ee("Omit",[t,r],n):!i&&s?ee("Omit",[t,r],n):i&&!s?ee("Omit",[t,r],n):h({...pd(t,o),...n})}var ai=u(()=>{T();To();Pr();nn();Ve();$t();at();ye();et();cd();ud();B();Le()});function mv(t,e,n){return{[e]:dn(t,[e],te(n))}}function fv(t,e,n){return e.reduce((r,o)=>({...r,...mv(t,o,n)}),{})}function gv(t,e,n){return fv(t,e.keys,n)}function Yc(t,e,n){let r=gv(t,e,n);return U(r)}var cd=u(()=>{we();ai();Ue()});var di=u(()=>{cd();ud();ai()});function hv(t,e,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(t))r[o]=ln(t[o],e,te(n));return r}function Sv(t,e,n){return hv(t.properties,e,n)}function Xc(t,e,n){let r=Sv(t,e,n);return U(r)}var md=u(()=>{we();li();Ue()});function yv(t,e){return t.map(n=>fd(n,e))}function kv(t,e){return t.map(n=>fd(n,e))}function vv(t,e){let n={};for(let r of e)r in t&&(n[r]=t[r]);return n}function Pv(t,e,n){let r=ae(t,[Se,"$id","required","properties"]),o=vv(n,e);return z(o,r)}function wv(t){let e=t.reduce((n,r)=>Ao(r)?[...n,V(r)]:n,[]);return q(e)}function fd(t,e){return se(t)?Oe(yv(t.allOf,e)):L(t)?q(kv(t.anyOf,e)):ge(t)?Pv(t,e,t.properties):z({})}function ln(t,e,n){let r=me(e)?wv(e):e,o=Ze(e)?qe(e):e,i=ue(t),s=ue(e);return ne(t)?Xc(t,o,n):Je(e)?Zc(t,e,n):i&&s?ee("Pick",[t,r],n):!i&&s?ee("Pick",[t,r],n):i&&!s?ee("Pick",[t,r],n):h({...fd(t,o),...n})}var li=u(()=>{T();To();nn();at();Ve();et();ye();$t();Pr();B();Le();gd();md()});function Iv(t,e,n){return{[e]:ln(t,[e],te(n))}}function bv(t,e,n){return e.reduce((r,o)=>({...r,...Iv(t,o,n)}),{})}function xv(t,e,n){return bv(t,e.keys,n)}function Zc(t,e,n){let r=xv(t,e,n);return U(r)}var gd=u(()=>{we();li();Ue()});var ui=u(()=>{gd();md();li()});function Av(t,e){return ee("Partial",[ee(t,e)])}function Rv(t){return ee("Partial",[Ot(t)])}function Tv(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=$e(t[n]);return e}function Mv(t,e){let n=ae(t,[Se,"$id","required","properties"]),r=Tv(e);return z(r,n)}function em(t){return t.map(e=>tm(e))}function tm(t){return vt(t)?Av(t.target,t.parameters):ue(t)?Rv(t.$ref):se(t)?Oe(em(t.allOf)):L(t)?q(em(t.anyOf)):ge(t)?Mv(t,t.properties):vn(t)||Kt(t)||It(t)||Qe(t)||wr(t)||bt(t)||Vt(t)||Ir(t)||br(t)?t:z({})}function or(t,e){return ne(t)?nm(t,e):h({...tm(t),...e})}var hd=u(()=>{T();nn();Gt();et();at();ye();Mn();jt();M();Sd();B()});function Cv(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=or(t[r],te(e));return n}function _v(t,e){return Cv(t.properties,e)}function nm(t,e){let n=_v(t,e);return U(n)}var Sd=u(()=>{we();hd();Ue()});var pi=u(()=>{Sd();hd()});function Ev(t,e){return ee("Required",[ee(t,e)])}function $v(t){return ee("Required",[Ot(t)])}function Ov(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=ae(t[n],[Re]);return e}function Nv(t,e){let n=ae(t,[Se,"$id","required","properties"]),r=Ov(e);return z(r,n)}function rm(t){return t.map(e=>om(e))}function om(t){return vt(t)?Ev(t.target,t.parameters):ue(t)?$v(t.$ref):se(t)?Oe(rm(t.allOf)):L(t)?q(rm(t.anyOf)):ge(t)?Nv(t,t.properties):vn(t)||Kt(t)||It(t)||Qe(t)||wr(t)||bt(t)||Vt(t)||Ir(t)||br(t)?t:z({})}function ir(t,e){return ne(t)?im(t,e):h({...om(t),...e})}var yd=u(()=>{T();nn();et();at();ye();Mn();M();jt();kd();B()});function Dv(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=ir(t[r],e);return n}function Fv(t,e){return Dv(t.properties,e)}function im(t,e){let n=Fv(t,e);return U(n)}var kd=u(()=>{we();yd()});var ci=u(()=>{kd();yd()});function Lv(t,e){return e.map(n=>ue(n)?vd(t,n.$ref):tt(t,n))}function vd(t,e){return e in t?ue(t[e])?vd(t,t[e].$ref):tt(t,t[e]):W()}function Wv(t){return Yn(t[0])}function Bv(t){return rn(t[0],t[1])}function Uv(t){return Xn(t[0])}function Kv(t){return or(t[0])}function Vv(t){return dn(t[0],t[1])}function qv(t){return ln(t[0],t[1])}function jv(t){return ir(t[0])}function Gv(t,e,n){let r=Lv(t,n);return e==="Awaited"?Wv(r):e==="Index"?Bv(r):e==="KeyOf"?Uv(r):e==="Partial"?Kv(r):e==="Omit"?Vv(r):e==="Pick"?qv(r):e==="Required"?jv(r):W()}function Hv(t,e){return Vn(tt(t,e))}function zv(t,e){return qn(tt(t,e))}function Qv(t,e,n){return jn(Gr(t,e),tt(t,n))}function Jv(t,e,n){return _t(Gr(t,e),tt(t,n))}function Yv(t,e){return Oe(Gr(t,e))}function Xv(t,e){return Jn(tt(t,e))}function Zv(t,e){return z(globalThis.Object.keys(e).reduce((n,r)=>({...n,[r]:tt(t,e[r])}),{}))}function eP(t,e){let[n,r]=[tt(t,si(e)),ii(e)],o=Un(e);return o.patternProperties[r]=n,o}function tP(t,e){return ue(e)?{...vd(t,e.$ref),[Se]:e[Se]}:e}function nP(t,e){return dt(Gr(t,e))}function rP(t,e){return q(Gr(t,e))}function Gr(t,e){return e.map(n=>tt(t,n))}function tt(t,e){return Ke(e)?h(tt(t,ae(e,[Re])),e):Kn(e)?h(tt(t,ae(e,[yt])),e):Xt(e)?h(tP(t,e),e):kt(e)?h(Hv(t,e.items),e):kn(e)?h(zv(t,e.items),e):vt(e)?h(Gv(t,e.target,e.parameters)):Pt(e)?h(Qv(t,e.parameters,e.returns),e):wt(e)?h(Jv(t,e.parameters,e.returns),e):se(e)?h(Yv(t,e.allOf),e):Pn(e)?h(Xv(t,e.items),e):ge(e)?h(Zv(t,e.properties),e):In(e)?h(eP(t,e)):Xe(e)?h(nP(t,e.items||[]),e):L(e)?h(rP(t,e.anyOf),e):e}function oP(t,e){return e in t?tt(t,t[e]):W()}function sm(t){return globalThis.Object.getOwnPropertyNames(t).reduce((e,n)=>({...e,[n]:oP(t,n)}),{})}var am=u(()=>{Ut();na();jt();_r();Wo();Er();$r();$t();bn();at();Lr();Kr();et();di();ui();Te();pi();qr();ci();on();ye();M();B()});function dm(t){return new Pd(t)}var Pd,lm=u(()=>{Ut();M();am();Pd=class{constructor(e){let n=sm(e),r=this.WithIdentifiers(n);this.$defs=r}Import(e,n){let r={...this.$defs,[e]:h(this.$defs[e],n)};return h({[P]:"Import",$defs:r,$ref:e})}WithIdentifiers(e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,r)=>({...n,[r]:{...e[r],$id:r}}),{})}}});var wd=u(()=>{lm()});function um(t,e){return h({[P]:"Not",not:t},e)}var pm=u(()=>{T();M()});var Id=u(()=>{pm()});function cm(t,e){return wt(t)?dt(t.parameters,e):W()}var mm=u(()=>{on();Te();B()});var bd=u(()=>{mm()});function fm(t,e={}){fe(e.$id)&&(e.$id=`T${iP++}`);let n=Un(t({[P]:"This",$ref:`${e.$id}`}));return n.$id=e.$id,h({[it]:"Recursive",...n},e)}var iP,gm=u(()=>{bo();T();Le();M();iP=0});var xd=u(()=>{gm()});function hm(t,e){let n=J(t)?new globalThis.RegExp(t):t;return h({[P]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},e)}var Sm=u(()=>{T();Le();M()});var Ad=u(()=>{Sm()});function sP(t){return se(t)?t.allOf:L(t)?t.anyOf:Xe(t)?t.items??[]:[]}function ym(t){return sP(t)}var km=u(()=>{B()});var Rd=u(()=>{km()});function vm(t,e){return wt(t)?h(t.returns,e):W(e)}var Pm=u(()=>{T();Te();B()});var Td=u(()=>{Pm()});var wm=u(()=>{});var Im=u(()=>{});var bm=u(()=>{wm();Im()});var xm=u(()=>{});var Am=u(()=>{xm()});function Rm(t){return new Md(t)}var Md,Cd,Tm=u(()=>{M();B();Md=class{constructor(e){this.schema=e}Decode(e){return new Cd(this.schema,e)}},Cd=class{constructor(e,n){this.schema=e,this.decode=n}EncodeTransform(e,n){let i={Encode:s=>n[Se].Encode(e(s)),Decode:s=>this.decode(n[Se].Decode(s))};return{...n,[Se]:i}}EncodeSchema(e,n){let r={Decode:this.decode,Encode:e};return{...n,[Se]:r}}Encode(e){return Xt(this.schema)?this.EncodeTransform(e,this.schema):this.EncodeSchema(e,this.schema)}}});var _d=u(()=>{Tm()});function Mm(t={}){return h({[P]:t[P]??"Unsafe"},t)}var Cm=u(()=>{T();M()});var Ed=u(()=>{Cm()});function _m(t){return h({[P]:"Void",type:"void"},t)}var Em=u(()=>{T();M()});var $d=u(()=>{Em()});var Od={};Po(Od,{Any:()=>tn,Argument:()=>op,Array:()=>Vn,AsyncIterator:()=>qn,Awaited:()=>Yn,BigInt:()=>zn,Boolean:()=>Eo,Capitalize:()=>Kc,Composite:()=>Xp,Const:()=>sc,Constructor:()=>jn,ConstructorParameters:()=>dc,Date:()=>Bo,Enum:()=>uc,Exclude:()=>nr,Extends:()=>tr,Extract:()=>rr,Function:()=>_t,Index:()=>rn,InstanceType:()=>Cc,Instantiate:()=>Nc,Integer:()=>Fc,Intersect:()=>Oe,Iterator:()=>Jn,KeyOf:()=>Xn,Literal:()=>V,Lowercase:()=>qc,Mapped:()=>Wp,Module:()=>dm,Never:()=>W,Not:()=>um,Null:()=>Ko,Number:()=>st,Object:()=>z,Omit:()=>dn,Optional:()=>$e,Parameters:()=>cm,Partial:()=>or,Pick:()=>ln,Promise:()=>Fo,Readonly:()=>je,ReadonlyOptional:()=>ni,Record:()=>oi,Recursive:()=>fm,Ref:()=>Ot,RegExp:()=>hm,Required:()=>ir,Rest:()=>ym,ReturnType:()=>vm,String:()=>xt,Symbol:()=>qo,TemplateLiteral:()=>Oo,Transform:()=>Rm,Tuple:()=>dt,Uint8Array:()=>zo,Uncapitalize:()=>Gc,Undefined:()=>Go,Union:()=>q,Unknown:()=>sn,Unsafe:()=>Mm,Uppercase:()=>zc,Void:()=>_m});var $m=u(()=>{Cr();ma();_r();Er();Wo();Fr();$o();La();Ba();$r();Ua();Uo();Ka();ed();Vr();rd();bn();$t();od();sd();ad();at();ld();Lr();Kr();Ve();we();wd();Te();Id();Vo();An();et();di();Gt();bd();pi();ui();Lo();Tn();ri();qr();xd();Mn();Ad();ci();Rd();Td();Qn();jo();zt();_d();on();Qo();Ho();ye();Zn();Ed();$d()});var c,Om=u(()=>{$m();c=Od});var De=u(()=>{na();Ut();Ct();ua();ju();Tr();Ju();Mr();M();Cr();_r();ma();Er();Wo();Fr();$o();La();Ba();$r();Ua();Uo();Ka();ed();Vr();rd();bn();$t();od();sd();ad();at();Lr();ld();Kr();Ve();wd();we();Te();Id();Vo();An();et();di();Gt();bd();pi();ui();Lo();Tn();ri();qr();xd();Mn();Ad();ci();Rd();Td();bm();Am();Qn();jo();zt();_d();on();Qo();Ho();ye();Zn();Ed();$d();Om()});function Nd(t){v=t}function Dd(t){he=t}var v,he,X=u(()=>{v=null,he=null});function Nm(t){let e=t.chatId.trim(),n=t.topicId.trim();return!/^-?\d+$/.test(e)||!/^\d+$/.test(n)?null:`${e}:topic:${n}`}function pP(t){let e=t.conversationId.trim(),n=e.match(/^(-?\d+):topic:(\d+)$/i);if(n?.[1]&&n[2]){let i=Nm({chatId:n[1],topicId:n[2]});return i?{chatId:n[1],topicId:n[2],canonicalConversationId:i}:null}if(!/^\d+$/.test(e))return null;let r=t.parentConversationId?.trim();if(!r||!/^-?\d+$/.test(r))return null;let o=Nm({chatId:r,topicId:e});return o?{chatId:r,topicId:e,canonicalConversationId:o}:null}function cP(t){if(!t)return;let e=t.match(/^agent:[^:]+:discord:(direct|dm|channel|group):/i);if(!e?.[1])return;let n=e[1].toLowerCase();return n==="direct"||n==="dm"?"user":"channel"}function mP(t,e){if(!/^\d+$/.test(t))return t;let n=cP(e);return n?`${n}:${t}`:`channel:${t}`}function fP(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 gP(t){let e=t.toLowerCase(),n=[":thread:",":topic:"];for(let r of n){let o=e.lastIndexOf(r);if(o===-1)continue;let i=t.slice(0,o).trim(),s=t.slice(o+r.length).trim()||void 0;return{id:i||t,threadId:s}}return{id:t}}function hP(t){let e=t?.trim();if(!e)return;let n=e.split(":").filter(Boolean);if(n[0]?.trim().toLowerCase()==="agent")for(let r=2;r<=n.length-3;r+=1){let o=n[r]?.trim().toLowerCase();if(!o||!uP.has(o))continue;let i=n[r+1]?.trim().toLowerCase(),s=n.slice(r+2).join(":").trim();if(!(!i||!s))return{provider:o,kind:i,rawId:s}}}function SP(t,e=pP){try{return e({conversationId:t})}catch{return null}}function Fd(t){return{provider:"system",target:"system",sessionKey:t?.trim()||void 0}}function Ld(t,e){return{...t,threadId:e??t.threadId}}function kP(t,e,n){return t==="telegram"&&n?.provider==="telegram"&&!!n.target&&e!==n.target}function vP(t){let e=t?.trim();if(!e)return;let n=hP(e);if(!n)return;let{provider:r,kind:o,rawId:i}=n,s=gP(i),a=null;if(r==="telegram")try{a=yP.safeParseTelegramTopicConversation(i)}catch{a=null}let d=a?.chatId??s.id,l=a?.topicId??s.threadId,p=r==="discord"?o==="direct"||o==="dm"?`user:${d}`:`channel:${d}`:d;return{provider:r,target:p,threadId:l,sessionKey:e}}function Wd(t){let e=t?.match(/:topic:(\d+)$/);return e?parseInt(e[1],10):void 0}function PP(t){return!!(t?.provider&&t.target&&t.provider!=="system"&&t.target!=="system")}function Hr(t,e,n){let r=vP(n),o=e!=null?String(e):void 0,i=t?.trim();if(!i||i.toLowerCase()==="unknown")return r?Ld(r,o):Fd(n);let s=i.split("|").map(k=>k.trim());if(s.length<2)return r?Ld(r,o):Fd(n);let[a,d,l]=s,p=s.length>=3?l:d,f=s.length>=3?d:void 0,y=a?.toLowerCase();if(!y||!p)return r?Ld(r,o):Fd(n);let g=y==="discord"?mP(p,n):p;return kP(y,g,r)?{provider:y,accountId:f,target:r.target,threadId:o??r.threadId,sessionKey:n?.trim()||void 0}:{provider:y,accountId:f,target:g,threadId:o??(r?.provider===y?r.threadId:void 0),sessionKey:n?.trim()||void 0}}function sr(t){return Hr(fP(t.route)??t.originChannel,t.route?.threadId??t.originThreadId,t.route?.sessionKey??t.originSessionKey)??t.route}function fi(t){let e=sr(t);return PP(e)?e:void 0}var uP,yP,En=u(()=>{uP=new Set(["telegram","discord","slack","system","mattermost","feishu","line","whatsapp","signal","matrix","googlechat","bluebubbles","imessage","msteams"]);yP={safeParseTelegramTopicConversation:SP}});import{readFileSync as wP}from"fs";import{homedir as IP}from"os";import{join as bP}from"path";function Fm(){if(zr!==void 0)return zr;try{let t=wP(bP(IP(),".claude.json"),"utf-8");zr=JSON.parse(t).mcpServers??{}}catch{zr={}}return zr}function Lm(t){let e=t.defaultHarness??Dm,n={};for(let[r,o]of Object.entries(gi))n[r]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[r,o]of Object.entries(t.harnesses??{})){let i=n[r]??{},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),n[r]=s}if(t.defaultModel!==void 0){let r=n[e]??{};n[e]={...r,defaultModel:t.harnesses?.[e]?.defaultModel??t.defaultModel,allowedModels:t.harnesses?.[e]?.allowedModels!==void 0?r.allowedModels:t.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${e}.defaultModel instead.`)}if(t.model!==void 0){let r=n.codex??{};n.codex={...r,defaultModel:t.harnesses?.codex?.defaultModel??t.model,allowedModels:t.harnesses?.codex?.allowedModels!==void 0?r.allowedModels:t.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(t.reasoningEffort!==void 0){let r=n.codex??{};n.codex={...r,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[r,o]of Object.entries(n))t.harnesses?.[r]?.allowedModels===void 0&&(n[r]={...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??"delegate",defaultHarness:e,harnesses:n,allowedModels:t.allowedModels,defaultWorktreeStrategy:t.defaultWorktreeStrategy??"delegate",worktreeDir:t.worktreeDir}}function Ie(){return _.defaultHarness??Dm}function Wm(t){let e=gi[t],n=_.harnesses[t];return{...e,...n,allowedModels:n?.allowedModels??e?.allowedModels}}function Dt(t){return Wm(t).defaultModel}function ar(t){return _.harnesses[t]?.allowedModels??_.allowedModels}function ct(t){return Wm(t).reasoningEffort}function Nt(t){return t==null?void 0:String(t).trim()||void 0}function Kd(t){return{channel:Nt(t?.deliveryContext?.channel),to:Nt(t?.deliveryContext?.to),accountId:Nt(t?.deliveryContext?.accountId),threadId:Nt(t?.deliveryContext?.threadId)}}function Bm(t,e,n){if(!(!t||!e))return n?`${t}|${n}|${e}`:`${t}|${e}`}function Bd(t){return Nt(t?.requesterSenderId??t?.senderId)}function Ud(t){return(Nt(t.deliveryContext?.channel)??t.messageChannel??t.channel)?.toLowerCase()!=="telegram"?!1:!!Wd(t.sessionKey)}function hi(t){let e=Kd(t),n=Bm(e.channel,e.to,e.accountId);if(n)return n;if(t.messageChannel){let r=t.messageChannel.split("|");if(r.length>=3)return t.messageChannel;if(t.agentAccountId&&r.length>=2)return`${r[0]}|${t.agentAccountId}|${r.slice(1).join("|")}`;let o=Nt(t.chatId);if(r.length===1&&o)return`${r[0]}|${o}`;let i=Bd(t);if(r.length===1&&i&&!Ud(t))return`${r[0]}|${i}`}if(t.workspaceDir){let r=Jr(t.workspaceDir);if(r)return r}if(t.messageChannel&&t.messageChannel.includes("|"))return t.messageChannel}function Qt(t,e){if(e&&String(e).includes("|"))return String(e);let n=Kd(t),r=Bm(n.channel,n.to,n.accountId);if(r)return r;if(t?.channelId&&String(t.channelId).includes("|"))return String(t.channelId);if(t?.messageChannel){let a=String(t.messageChannel);if(a.includes("|"))return a;let d=Nt(t.chatId);if(d)return`${a}|${d}`;let l=Bd(t);if(l&&!Ud(t))return`${a}|${l}`}let o=Nt(t?.channel),i=Nt(t?.chatId);if(o&&i)return`${o}|${i}`;let s=Bd(t);return o&&s&&!Ud(t)?`${o}|${s}`:t?.id&&/^-?\d+$/.test(String(t.id))?`telegram|${t.id}`:_.fallbackChannel??"unknown"}function Qr(t){return Kd(t).threadId??t?.messageThreadId??void 0}function Ft(t,e,n){return Hr(Qt(t,e),Qr(t),n??t?.sessionKey)}function Jr(t){let e=_.agentChannels;if(!e)return;let n=i=>i.replace(/\/+$/,""),r=n(t),o=Object.entries(e).sort((i,s)=>s[0].length-i[0].length);for(let[i,s]of o)if(r===n(i)||r.startsWith(n(i)+"/"))return s}function Um(t){return Wd(t)}var zr,Dm,gi,_,Me=u(()=>{En();Dm="claude-code",gi={"claude-code":{defaultModel:"anthropic/claude-sonnet-4-7",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.5",allowedModels:["gpt-5.5","gpt-5.5-pro"],reasoningEffort:"medium"}};_={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",defaultWorktreeStrategy:"delegate",harnesses:{"claude-code":{...gi["claude-code"]},codex:{...gi.codex}}}});function Si(t){return{type:"backend_ref",ref:t}}function yi(t){return{type:"run_started",...t?{runId:t}:{}}}function Yr(t){return{type:"text_delta",text:t}}function Km(t,e){return{type:"tool_call",name:t,input:e}}function ki(t){return{type:"pending_input",state:t}}function ur(t){return t?{type:"pending_input_resolved",requestId:t}:{type:"pending_input_resolved"}}function vi(t,e){return{type:"plan_artifact",artifact:t,finalized:e}}function Pi(t){return t?{type:"settings_changed",permissionMode:t}:{type:"settings_changed"}}function $n(t){return{type:"run_completed",data:t}}var lr,Vd=u(()=>{lr=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(n=>{e.resolvePending=n})}})()}}});import*as Ii from"@anthropic-ai/claude-agent-sdk";function xP(t){if(typeof t.result=="string"&&t.result.length>0)return t.result;if(Array.isArray(t.errors)){let e=t.errors.filter(n=>typeof n=="string"&&n.length>0);if(e.length>0)return e.join(`
2
+ `)}}function AP(t,e,n){let o=(Array.isArray(n.questions)?n.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 wi,Vm=u(()=>{Vd();wi=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 n=new lr,r=!1,o="",i=!1,s=0,a=e.resumeSessionId??"",d=e.canUseTool,l={cwd:e.cwd,model:e.model,...e.reasoningEffort?{effort:e.reasoningEffort}:{},permissionMode:e.permissionMode,allowDangerouslySkipPermissions:!0,allowedTools:e.allowedTools,systemPrompt:e.systemPrompt,includePartialMessages:!0,abortController:e.abortController,mcpServers:e.mcpServers,...d?{canUseTool:async(k,A)=>{if(k!=="AskUserQuestion")return{behavior:"allow"};let x=AP(a,++s,A);n.enqueue(ki(x));try{let w=await d(k,A);return n.enqueue(ur(x.requestId)),w}catch(w){throw n.enqueue(ur(x.requestId)),w}}}:{}};e.resumeSessionId&&(l.resume=e.resumeSessionId,l.forkSession=e.forkSession??!1);let p=e.prompt,f=this.deps.query??Ii.query,y=this.deps.startup??Ii.startup,g=(async()=>{if(typeof y!="function")return f({prompt:p,options:l});let k=await y({options:l});try{return k.query(p)}catch(A){throw await k.close?.(),A}})();return(async()=>{try{let k=await g;for await(let A of k){let x=A;if(x.type==="system"&&x.subtype==="init"){a=x.session_id??a,n.enqueue(Si({kind:"claude-code",conversationId:a}));continue}if(x.type==="system"&&x.subtype==="status"&&x.permissionMode){n.enqueue(Pi(x.permissionMode));continue}if(x.type==="assistant"){r||(r=!0,n.enqueue(yi()));for(let w of x.message?.content??[]){if(w.type==="text"){o+=o?`
3
+ ${w.text}`:w.text,n.enqueue(Yr(w.text));continue}w.type==="tool_use"&&((w.name==="ExitPlanMode"||w.name==="set_permission_mode")&&(i=!0),w.name!=="AskUserQuestion"&&n.enqueue(Km(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};n.enqueue(vi(C,!0))}n.enqueue($n({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:xP(x),session_id:x.session_id??a})),o="",i=!1,r=!1}}}finally{n.close()}})().catch(k=>{n.enqueue($n({success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,result:k instanceof Error?k.message:String(k),session_id:a})),n.close()}),{messages:n.messages(),async setPermissionMode(k){let A=await g;typeof A.setPermissionMode=="function"&&await A.setPermissionMode(k)},async streamInput(k){let A=await g;typeof A.streamInput=="function"&&await A.streamInput(k)},async interrupt(){let k=await g;typeof k.interrupt=="function"&&await k.interrupt()}}}buildUserMessage(e,n){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:n}}}});import{spawn as RP}from"node:child_process";import TP from"node:readline";function MP(t){return t instanceof Error?t.message:String(t)}function CP(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}async function _P(t,e){if(t.id!=null&&(Object.hasOwn(t,"result")||Object.hasOwn(t,"error"))){let r=String(t.id),o=e.pending.get(r);if(!o)return;if(clearTimeout(o.timer),e.pending.delete(r),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 n=t.method?.trim();if(n){if(t.id==null){await e.onNotification(n,t.params);return}try{let r=await e.onRequest(n,t.params);e.respond({jsonrpc:"2.0",id:t.id,result:r??{}})}catch(r){e.respond({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:MP(r)}})}}}var bi,qm=u(()=>{bi=class{constructor(e,n,r){this.command=e;this.args=n;this.requestTimeoutMs=r}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=RP(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,TP.createInterface({input:e.stdout}).on("line",r=>{this.handleLine(r)}),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,n){this.write({jsonrpc:"2.0",method:e,params:n??{}})}async request(e,n,r){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,r??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:n??{}}),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 n=CP(e);n&&await _P(n,{pending:this.pending,onNotification:this.onNotification,onRequest:this.onRequest,respond:r=>this.write(r)})}flushPending(e){for(let[n,r]of this.pending)clearTimeout(r.timer),r.reject(e),this.pending.delete(n)}}});function Z(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function pe(t,e,n){for(let r of e){let o=t?.[r];if(typeof o!="string")continue;let i=n?.trim===!1?o:o.trim();if(i)return i}}function EP(t){return t instanceof Error?t.message:String(t)}function jm(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function un(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>un(n)).join("");let e=Z(t);if(!e)return"";for(let n of["delta","text","content","message","input","output","parts"]){let r=un(e[n]);if(r)return r}for(let n of["item","turn","thread","response","result","data"]){let r=un(e[n]);if(r)return r}return""}function Xr(t){let e=Z(t);if(!e)return{};let n=Z(e.thread)??Z(e.session),r=Z(e.turn)??Z(e.run),o=Z(e.item),i=Z(e.serverRequest);return{threadId:pe(e,["threadId","thread_id","conversationId","conversation_id"])??pe(n,["id","threadId","thread_id","conversationId"]),runId:pe(e,["turnId","turn_id","runId","run_id"])??pe(r,["id","turnId","turn_id","runId","run_id"]),requestId:pe(e,["requestId","request_id","serverRequestId"])??pe(i,["id","requestId","request_id"]),itemId:pe(e,["itemId","item_id"])??pe(o,["id","itemId","item_id"])}}function xi(t,e,n=0){if(n>6)return;if(Array.isArray(t)){for(let i of t){let s=xi(i,e,n+1);if(s)return s}return}let r=Z(t);if(!r)return;let o=pe(r,e);if(o)return o;for(let i of Object.values(r)){let s=xi(i,e,n+1);if(s)return s}}function Zr(t){return{threadId:Xr(t).threadId,cwd:xi(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 n=e.split(/[/\\]+/).filter(Boolean),r=n.lastIndexOf("worktrees");if(!(r<0||r+1>=n.length))return n[r+1]}function Ai(t){let e=Z(t);if(!e)return;let n=Z(e.item)??e;return pe(n,["id","itemId","item_id","messageId","message_id"])}function $P(t,e=!1){let n=Z(t);if(!n)return"";let r=Z(n.item)??n;return pe(r,["type"])?.toLowerCase()!=="agentmessage"?"":e?un(r):pe(r,["text"],{trim:!1})??un(r)}function zm(t,e){let n=t.trim().toLowerCase();return n==="item/agentmessage/delta"?{mode:"delta",text:un(e),itemId:Ai(e)}:n==="item/completed"?{mode:"snapshot",text:$P(e),itemId:Ai(e)}:{mode:"ignore",text:""}}function Qm(t){return{itemId:Ai(t),delta:un(t)}}function Jm(t){let e=Z(t),n=Z(e?.plan),o=(Array.isArray(e?.plan)?e.plan:Array.isArray(n?.steps)?n.steps:[]).map(i=>{let s=Z(i),a=pe(s,["step","title","text"]);if(!a)return null;let d=pe(s,["status"])?.toLowerCase()??"pending";return{step:a,status:d==="inprogress"||d==="in_progress"?"inProgress":d==="completed"?"completed":"pending"}}).filter(Boolean);return{explanation:pe(n,["explanation"])??pe(e,["explanation"]),steps:o}}function Ym(t){let e=Z(t);if(!e)return{};let n=Z(e.item)??e;return pe(n,["type"])?.toLowerCase()!=="plan"?{}:{itemId:Ai(n),text:pe(n,["text"],{trim:!1})??un(n)}}function Xm(t,e){let n=t.trim().toLowerCase();if(n==="turn/failed")return"failed";if(n==="turn/cancelled")return"interrupted";let r=Z(e)??{},o=Z(r.turn)??r,i=pe(o,["status"])?.toLowerCase();return i==="failed"?"failed":i==="interrupted"||i==="cancelled"?"interrupted":"completed"}function Zm(t,e){let n=Z(e)??{},r=Z(n.turn)??n,o=Z(r.error)??Z(n.error);if(o)return pe(o,["message","text","summary","reason"])}function OP(t,e){let n=EP(t).toLowerCase();return n.includes("method not found")||n.includes("unknown method")?!0:n.includes("unknown variant")?e?n.includes(`unknown variant \`${e.toLowerCase()}\``):!0:!1}function DP(t){return NP.has(t.trim().toLowerCase())}function FP(t){let e=Z(t);return e?!!pe(e,["threadId","thread_id"]):!1}async function eo(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 n of t.methods)for(let r of t.payloads){if(DP(n)&&!FP(r))throw new Error(`codex app server request missing threadId: ${n}`);try{return await t.client.request(n,r,t.timeoutMs)}catch(o){if(e=o,!OP(o,n))continue}}throw e instanceof Error?e:new Error(String(e))}function ef(t){let e={cwd:t.cwd};t.model?.trim()&&(e.model=t.model.trim()),t.reasoningEffort?.trim()&&(e.reasoningEffort=t.reasoningEffort.trim()),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim());let n={cwd:t.cwd};return t.reasoningEffort?.trim()&&(n.reasoning_effort=t.reasoningEffort.trim()),t.approvalPolicy?.trim()&&(n.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(n.sandbox=t.sandbox.trim()),[e,n,{}]}function tf(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 LP(t){return[{type:"text",text:t}]}function WP(t,e,n,r){let o=e?.trim(),i=n?.trim(),s=r?.trim();if(t!=="plan")return o||i||s?{mode:"default",settings:{...o?{model:o}:{},...i?{reasoningEffort:i}:{},developerInstructions:s??null}}:void 0;if(!(!o&&!i&&!s))return{mode:"plan",settings:{...o?{model:o}:{},...i?{reasoningEffort:i}:{},developerInstructions:s??null}}}function nf(t){let e={threadId:t.threadId,input:LP(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 n=WP(t.permissionMode??"default",t.model,t.reasoningEffort,t.systemPrompt);return n?[{...e,collaborationMode:n},{...e,collaboration_mode:{mode:n.mode,settings:{...typeof n.settings.model=="string"?{model:n.settings.model}:{},...typeof n.settings.reasoningEffort=="string"?{reasoning_effort:n.settings.reasoningEffort}:{},developer_instructions:n.settings.developerInstructions??null}}},e]:[e]}function rf(t){return[{threadId:t.threadId,turnId:t.turnId}]}function BP(t){let e=Z(t);if(!e)return[];let n=e.options??e.choices??e.availableDecisions??e.decisions;return Array.isArray(n)?n.map(r=>typeof r=="string"?r.trim():pe(Z(r),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function UP(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 of(t,e,n){let r=t.trim().toLowerCase(),o=BP(n),i=xi(n,["question","prompt","message","text","summary","reason"])??void 0,s=r.includes("requestapproval"),a=s?o.map(d=>({kind:"approval",label:d,decision:UP(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 sf(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function qd(t,e){let n=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:n,sandbox:n==="never"?"danger-full-access":void 0}}var NP,af=u(()=>{NP=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function df(t){return t instanceof Error?t.message:String(t)}function GP(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 KP,On,VP,qP,jP,Ri,lf=u(()=>{qm();Vd();af();KP="1.0",On=6e4,VP="OPENCLAW_CODEX_APP_SERVER_COMMAND",qP="OPENCLAW_CODEX_APP_SERVER_ARGS",jP="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";Ri=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 n={command:process.env[VP]?.trim()||"codex",args:jm(process.env[qP]),requestTimeoutMs:Number.parseInt(process.env[jP]??String(On),10)||On},r=this.deps.createClient?.(n)??new bi(n.command,n.args,n.requestTimeoutMs),o=new lr,i=e.resumeSessionId,s,a=e.backendRef?.worktreePath,d=e.backendRef?.worktreeId,l=e.permissionMode??"default",p,f=0,y="",g=[],k,A=new Map,x=new Set,w=N=>{let D=N?.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(Si({kind:"codex-app-server",conversationId:i,...s?{runId:s}:{},...d?{worktreeId:d}:{},...a?{worktreePath:a}:{}}))};r.setNotificationHandler(async(N,D)=>{let K=N.trim().toLowerCase(),ce=Xr(D),St=Zr(D);if(ce.threadId&&i&&ce.threadId!==i)return;if(ce.threadId&&(i=ce.threadId),ce.runId&&(s=ce.runId),w(St.cwd),(ce.threadId||ce.runId||St.cwd)&&C(),K==="serverrequest/resolved"){p&&(o.enqueue(ur(p.requestId)),p=void 0);return}if(K==="turn/plan/updated"){let _e=Jm(D);y=_e.explanation??y,_e.steps.length>0&&(g=_e.steps);return}if(K==="item/plan/delta"){let _e=Qm(D);if(_e.itemId&&_e.delta){let Jt=A.get(_e.itemId)??"";A.set(_e.itemId,`${Jt}${_e.delta}`)}return}if(K==="item/completed"){let _e=Ym(D);if(_e.text?.trim()){let Jt={explanation:y||void 0,steps:g,markdown:_e.text.trim()};o.enqueue(vi(Jt,!0));return}}let le=zm(K,D);if(le.mode==="delta"&&le.text){le.itemId&&x.add(le.itemId),o.enqueue(Yr(le.text));return}le.mode==="snapshot"&&le.text&&(!le.itemId||!x.has(le.itemId))&&o.enqueue(Yr(le.text)),(K==="turn/completed"||K==="turn/failed"||K==="turn/cancelled")&&k&&(k.method=N,k.params=D,k.resolve())}),r.setRequestHandler(async(N,D)=>{if(!sf(N))return{};let K=Xr(D),ce=Zr(D);if(K.threadId&&i&&K.threadId!==i)return{};K.threadId&&(i=K.threadId),K.runId&&(s=K.runId),w(ce.cwd),(K.threadId||K.runId||ce.cwd)&&C();let St=K.requestId??`${i??"codex"}-${Date.now().toString(36)}`,le=of(N,St,D),_e=N.trim().toLowerCase(),Jt=le.options,vo=le.actions??[],Ah=await new Promise(Rh=>{p={requestId:St,methodLower:_e,state:le,options:Jt,actions:vo,resolveResponse:Rh},o.enqueue(ki(le))});return p=void 0,o.enqueue(ur(St)),Ah});let I=async()=>{await r.connect(),await r.request("initialize",{protocolVersion:KP,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},On),await r.notify("initialized",{})},R=async()=>{let N=qd(l,e.codexApprovalPolicy);if(i){let ce=await eo({client:r,methods:["thread/resume"],payloads:tf({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:N.approvalPolicy,sandbox:N.sandbox}),timeoutMs:On}),St=Zr(ce);i=St.threadId??i,w(St.cwd),C();return}let D=await eo({client:r,methods:["thread/start","thread/new"],payloads:ef({cwd:e.originalWorkdir?.trim()||e.cwd,model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:N.approvalPolicy,sandbox:N.sandbox}),timeoutMs:On}),K=Zr(D);if(i=K.threadId,!i)throw new Error("Codex App Server did not return a thread id.");w(K.cwd),C()},O=async N=>{await R(),o.enqueue(yi()),f+=1,y="",g=[],A.clear(),x.clear();let D="",K,ce,St=new Promise(le=>{ce=le});k={resolve:ce};try{let le=qd(l,e.codexApprovalPolicy),_e=await eo({client:r,methods:["turn/start"],payloads:nf({threadId:i,prompt:N,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,permissionMode:l,approvalPolicy:le.approvalPolicy,sandbox:le.sandbox}),timeoutMs:On}),Jt=Xr(_e);Jt.runId&&(s=Jt.runId,C()),await St,D=k?.method??"turn/failed",K=k?.params;let vo=Xm(D,K);o.enqueue($n({success:vo==="completed",outcome:vo,duration_ms:0,total_cost_usd:0,num_turns:f,result:Zm(D,K),session_id:i}))}catch(le){o.enqueue($n({success:!1,duration_ms:0,total_cost_usd:0,num_turns:f,result:df(le),session_id:i??""}))}finally{k=void 0}},Be=async N=>p?(p.methodLower.includes("requestapproval")?p.resolveResponse({decision:N.trim()||"decline"}):p.resolveResponse({text:N.trim()}),!0):!1,ql=async N=>{let D=p;if(!D)return!1;let K=D.actions[N];if(K?.kind==="approval")return D.resolveResponse({decision:K.responseDecision,...K.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:K.proposedExecpolicyAmendment}:{}}),!0;let ce=D.options[N];return ce?(D.methodLower.includes("requestapproval")?D.resolveResponse({decision:ce}):D.resolveResponse({option:ce,index:N}),!0):!1},jl=typeof e.prompt=="string"?(async function*(){yield{type:"user",text:e.prompt,session_id:e.resumeSessionId??""}})():e.prompt;return(async()=>{try{await I();for await(let N of jl){let D=GP(N).trim();!D||await Be(D)||await O(D)}}catch(N){o.enqueue($n({success:!1,duration_ms:0,total_cost_usd:0,num_turns:f,result:df(N),session_id:i??e.resumeSessionId??""}))}finally{await r.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(N){l=N,o.enqueue(Pi(N))},async submitPendingInputOption(N){return ql(N)},async submitPendingInputText(N){return Be(N)},async interrupt(){!i||!s||await eo({client:r,methods:["turn/interrupt"],payloads:rf({threadId:i,turnId:s}),timeoutMs:On}).catch(()=>{})}}}buildUserMessage(e,n){return{type:"user",text:e,session_id:n}}}});function uf(t){jd.set(t.name,t)}function to(t){let e=jd.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...jd.keys()].join(", ")}`);return e}function pf(){return to(Ie())}var jd,Gd=u(()=>{Vm();lf();Me();jd=new Map;uf(new wi);uf(new Ri)});function E(t){return t.backendRef?.conversationId??t.harnessSessionId}function re(t){return t.id??t.sessionId??t.name??E(t)??t.harnessSessionId}function HP(t){return t.harnessSessionId}function nt(t){let e=[re(t),E(t),HP(t)].filter(n=>!!n);return[...new Set(e)]}function Hd(t){return t.harnessName??t.persistedHarness??Ie()}function Ti(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return to(Hd(t)).capabilities.worktrees}catch{return"plugin-managed"}}function zd(t){return t==="native-execution"||t==="native-restore"}function cf(t){return t==="native-restore"}function zP(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function We(t){return zd(Ti(t))&&zP(t)}var Pe=u(()=>{Me();Gd()});import{execFileSync as Ae}from"child_process";import*as Ki from"fs";import{tmpdir as vw}from"os";import{dirname as Nf,join as Pw}from"path";function ww(t){try{return Ae("git",["rev-parse","--show-toplevel"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function Vi(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(_.worktreeDir)return _.worktreeDir;if(t){let e=ww(t);if(e)return Pw(e,".worktrees")}return vw()}function Df(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function qi(t){try{let e=Ae("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")?Nf(e):void 0}catch{return}}function Iw(){if(Bi!==void 0)return Bi;try{return Ae("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Bi=!0,!0}catch{return Bi=!1,!1}}function pn(){if(Ui!==void 0)return Ui;try{return Ae("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Ui=!0,!0}catch{return Ui=!1,!1}}function el(t){if(!Iw())return!1;try{return Ae("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Ff(t){try{let e=xw(t);if(!e)return console.warn(`[worktree] Failed to resolve free-space probe path for ${Vi(t)}`),!0;let n=Ki.statfsSync(e),r=n.bavail*n.bsize;return Aw(r)}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function so(t,e){try{return Ae("git",["-C",t,"rev-parse","--verify",e],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function bw(t){let e=t;for(;;){if(Ki.existsSync(e))return e;let n=Nf(e);if(n===e)return;e=n}}function xw(t){return bw(Vi(t))}function Aw(t){return t>=104857600}function cn(t){let e=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(e)return e;try{let r=Ae("git",["-C",t,"rev-parse","--abbrev-ref","origin/HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().replace(/^origin\//,"");if(r)return r}catch{}try{return Ae("git",["-C",t,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return Ae("git",["-C",t,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function ji(t){try{let n=Ae("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n==="HEAD"){console.warn(`[worktree] Worktree ${t} is in detached HEAD state \u2014 cannot determine branch name`);return}return n||void 0}catch{return}}function tl(t,e,n){try{let r=Ae("git",["-C",t,"rev-list","--count",`${n}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(r.trim(),10)>0}catch{return!1}}function Lf(t,e,n){try{let r=Ae("git",["-C",t,"rev-list","--left-right","--count",`${e}...${n}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),[o,i]=r.split(/\s+/);return{ahead:parseInt(o??"0",10)||0,behind:parseInt(i??"0",10)||0}}catch{return}}function Wf(t,e,n){try{return Ae("git",["-C",t,"merge-base","--is-ancestor",e,n],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Bf(t,e,n){try{let r=Ae("git",["-C",t,"merge-tree","--write-tree",n,e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=Ae("git",["-C",t,"rev-parse",`${n}^{tree}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return!!r&&r===o}catch{return!1}}function Lt(t,e){try{return Ae("git",["-C",t,"branch","-D",e],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to delete branch ${e}: ${n instanceof Error?n.message:String(n)}`),!1}}function Uf(t,e){if(e)return e;let n;try{n=Ae("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}try{let r=Ae("git",["-C",t,"remote","get-url","upstream"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r&&r!==n){let o=r.match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/);if(o)return o[1]}}catch{}}var Bi,Ui,ao=u(()=>{Me()});import{execFileSync as lo}from"child_process";import{existsSync as Rw,mkdirSync as Kf,rmSync as nl}from"fs";function Tw(t,e){return!!(t&&typeof t=="object"&&"code"in t&&t.code===e)}function rl(t,e,n={}){let r=Df(e),o=Vi(t);Kf(o,{recursive:!0});let i=n.allowExistingBranch===!0,s,a,d=10,l=!1;for(let f=0;f<d;f++){let y=f===0?"":`-${Math.random().toString(16).slice(2,6)}`,g=`${o}/openclaw-worktree-${r}${y}`,k=`agent/${r}${y}`;if(!i&&so(t,k))continue;let A=!1;do{A=!1;try{Kf(g,{recursive:!1}),s=g,a=k;break}catch(x){if(Tw(x,"EEXIST")){if(i&&f===0&&!l)try{nl(g,{recursive:!0,force:!0}),l=!0,A=!0}catch(w){throw new Error(`Failed to recreate existing worktree branch ${k}: could not clear blocked path ${g}: ${w instanceof Error?w.message:String(w)}`)}else if(i&&f===0)throw new Error(`Failed to recreate existing worktree branch ${k}: path ${g} remains blocked after one cleanup attempt`);continue}throw x}}while(A);if(s&&a)break}if(!s||!a)throw new Error(`Failed to create unique worktree directory and branch after ${d} attempts`);let p=so(t,a);try{p?lo("git",["-C",t,"worktree","add",s,a],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):lo("git",["-C",t,"worktree","add","-b",a,s],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(f){try{nl(s,{recursive:!0,force:!0})}catch{}throw f}return s}function Mw(t){if(!Rw(t))return[];try{let e=lo("git",["-C",t,"status","--porcelain","--untracked-files=all"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e?e.split(`
5
+ `).map(n=>n.trim()).filter(Boolean):[]}catch{return[]}}function rt(t,e,n={}){let r=n.destructive===!0,o=Mw(e);if(o.length>0&&!r)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${e}: ${o[0]}`),!1;try{return lo("git",["-C",t,"worktree","remove",...r?["--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)}`),!r)return!1;try{return nl(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 Gi(t){try{lo("git",["-C",t,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var Vf=u(()=>{ao()});import{execFileSync as oe}from"child_process";import{existsSync as Cw}from"fs";function Dn(t,e,n){try{let r=oe("git",["-C",t,"rev-list","--count",`${n}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(r.trim(),10),s=oe("git",["-C",t,"diff","--shortstat",`${n}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,l=0,p=s.match(/(\d+)\s+files?\s+changed/);p&&(a=parseInt(p[1],10));let f=s.match(/(\d+)\s+insertions?\(/);f&&(d=parseInt(f[1],10));let y=s.match(/(\d+)\s+deletions?\(/);y&&(l=parseInt(y[1],10));let k=oe("git",["-C",t,"diff","--name-only","--diff-filter=ACMR",`${n}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
6
+ `).map(w=>w.trim()).filter(Boolean),x=oe("git",["-C",t,"log",`${n}..${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,I,R]=w.split("|");return{hash:C||"",message:I||"",author:R||""}});return{commits:o,filesChanged:a,insertions:d,deletions:l,changedFiles:k,commitMessages:x}}catch(r){console.warn(`[worktree] Failed to get diff summary: ${r instanceof Error?r.message:String(r)}`);return}}function Hi(t,e,n="origin"){try{return oe("git",["-C",t,"push",n,e],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){return console.warn(`[worktree] Failed to push branch ${e}: ${r instanceof Error?r.message:String(r)}`),!1}}function fr(t){try{return oe("git",["-C",t,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
8
+ `).some(n=>n.length>0&&!n.startsWith("??")&&!n.startsWith("!!"))}catch{return!1}}function zi(t,e,n,r="merge",o){let i=!1,s,a=d=>{if(i)try{oe("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(r==="squash"){if(oe("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),fr(t)){let y;try{y=oe("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(g){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${g instanceof Error?g.message:String(g)}. Commit or stash changes manually, then retry.`}}if(!y.includes("No local changes to save")){i=!0;try{s=oe("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}oe("git",["-C",t,"merge","--squash",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),oe("git",["-C",t,"commit","-m",`Squash merge ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let f=!1;if(i)try{oe("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{f=!0}return{success:!0,stashed:i||void 0,stashRef:s,stashPopConflict:f||void 0}}let d=o&&Cw(o),l=d?o:t;if(d||oe("git",["-C",t,"checkout",e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),fr(t)){let f;try{f=oe("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(y){try{oe("git",["-C",t,"checkout",n],{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(!f.includes("No local changes to save")){i=!0;try{s=oe("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{oe("git",["-C",l,"rebase",n],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{oe("git",["-C",l,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{oe("git",["-C",t,"checkout",n],{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 ${n} hit conflicts.`,"To resolve manually:",` cd ${l}`,` git rebase ${n}`," # resolve conflicts in each file, then:"," git add <file>"," git rebase --continue"," # repeat until rebase finishes, then re-run agent_merge."].join(`
9
+ `)}}oe("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),oe("git",["-C",t,"merge","--ff-only",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let p=!1;if(i)try{oe("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{p=!0}return{success:!0,fastForward:!0,stashed:i||void 0,stashRef:s,stashPopConflict:p||void 0}}catch(d){try{oe("git",["-C",t,"checkout",n],{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 ol=u(()=>{});import{execFileSync as Qi}from"child_process";function qf(t,e,n,r,o,i){if(!pn())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s;if(i)try{let f=Qi("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[:/]([^/]+)\/[^/]+(?:\.git)?$/);f&&(s=f[1])}catch{}let a=["pr","create","--base",n];return i&&a.push("--repo",i),s?a.push("--head",`${s}:${e}`):a.push("--head",e),r&&o?a.push("--title",r,"--body",o):a.push("--fill-verbose"),{success:!0,prUrl:Qi("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 uo(t,e,n){if(!pn())return{exists:!1,state:"none"};try{let r=["pr","list","--head",e,"--state","all","--json","url,number,title,state","--jq",".[0]"];n&&r.push("--repo",n);let i=Qi("gh",r,{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(r){return console.warn(`[worktree] Failed to sync PR status for ${e}: ${r instanceof Error?r.message:String(r)}`),{exists:!1,state:"none"}}}function jf(t,e,n,r){if(!pn())return!1;try{let o=["pr","comment",String(e),"--body",n];return r&&o.push("--repo",r),Qi("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 Fn(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 il=u(()=>{ao()});import{existsSync as sl}from"fs";function Gf(){return new Date().toISOString()}function _w(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:Gf(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function Ew(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(sl(t.workdir)?cn(t.workdir):void 0)}function po(t,e={}){let n=_w(t),r=Gf(),o=new Set,i=sl(t.workdir),s=!!(t.worktreePath&&sl(t.worktreePath)),a=t.worktreeBranch,d=Ew(t),l=!1,p=!1,f=!1,y=!1,g,k,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"),n.state==="pending_decision"&&o.add("pending_decision"),n.state==="merge_conflict_resolving"&&o.add("merge_conflict_resolving"),i&&a&&(l=so(t.workdir,a),l||o.add("branch_missing")),s&&t.worktreePath&&(p=fr(t.worktreePath),p&&o.add("dirty_tracked_changes")),i&&l&&d){let Be=Lf(t.workdir,a,d);g=Be?.ahead,k=Be?.behind,f=Wf(t.workdir,a,d),f?o.add("topology_merged"):(y=Bf(t.workdir,a,d),y&&o.add("merge_noop_content_already_on_base"),!y&&(g??0)>0&&o.add("unique_content"))}else d||o.add("base_branch_missing");if(e.includePrSync&&i&&a){let Be=uo(t.workdir,a,t.worktreePrTargetRepo??n.targetRepo);A=Be.state,x=Be.url??x,w=Be.number??w}A==="open"&&o.add("pr_open"),A==="merged"&&!f&&!y&&o.add("pr_merged_not_reflected_locally");let C=n.state;f?C="merged":y?C="released":!l&&n.state==="pending_decision"&&(C="cleanup_failed");let I=e.activeSession||p||n.state==="pending_decision"||n.state==="merge_conflict_resolving"||n.state==="pr_open"||A==="open"||o.has("pr_merged_not_reflected_locally"),R=!I&&(C==="merged"||C==="released"||n.state==="dismissed"||n.state==="no_change"),O={checkedAt:r,repoExists:i,branchExists:l,worktreeExists:s,activeSession:e.activeSession===!0,dirtyTracked:p,topologyMerged:f,releaseNoopMerge:y,branchAheadCount:g,baseAheadCount:k,prState:A,prUrl:x,prNumber:w,reasons:[...o]};return{lifecycle:n,evidence:O,derivedState:C,cleanupSafe:R,preserve:I,reasons:[...o]}}var Ji=u(()=>{ao();il();ol()});var mt=u(()=>{ao();Vf();ol();il();Ji()});function gr(t,e){let n=t.resolve(e),r=t.getPersistedSession(e),o=n?re(n):r?re(r):void 0;return{activeSession:n,persistedSession:r,persistedRef:o,sessionName:n?.name??r?.name??e,worktreePath:n?.worktreePath??r?.worktreePath,originalWorkdir:n?.originalWorkdir??r?.workdir,branchName:n?.worktreeBranch??r?.worktreeBranch,notificationTarget:n??(r?{id:o??e,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route}:void 0)}}function ag(t){return t.persistedSession?nt(t.persistedSession):[]}function uI(t,e){let n=[e.id,e.backendConversationId,e.harnessSessionId,e.name],r,o;for(let i of n)if(i&&(r??=t.resolve(i),o??=t.getPersistedSession(i),r&&o))break;return{activeSession:r,persistedSession:o}}function is(t,e,n={}){let{activeSession:r,persistedSession:o}=uI(t,e),i=po({workdir:e.workdir,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeBaseBranch:n.baseBranch??o?.worktreeBaseBranch,worktreePrTargetRepo:o?.worktreePrTargetRepo,worktreePushRemote:o?.worktreePushRemote,worktreePrUrl:o?.worktreePrUrl,worktreePrNumber:o?.worktreePrNumber,worktreeLifecycle:o?.worktreeLifecycle},{activeSession:!!(r&&(r.status==="starting"||r.status==="running")),includePrSync:!!(o?.worktreeLifecycle?.state==="pr_open"||o?.worktreePrUrl)});return{activeSession:r,persistedSession:o,resolvedLifecycle:i}}function ss(t){let e=t.list("all").filter(o=>o.worktreePath),n=t.listPersistedSessions().filter(o=>o.worktreePath),r=new Map;for(let o of n){if(!o.worktreePath)continue;let i=E(o),s=o.sessionId??i??o.harnessSessionId;s&&r.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&&r.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:E(o),harnessSessionId:o.harnessSessionId});return Array.from(r.values())}function as(t,e){return t.id===e||t.name===e||t.backendConversationId===e||t.harnessSessionId===e}function Wn(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 ds(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 mo=u(()=>{Pe();Ji()});var dg={};Po(dg,{makeAgentPrTool:()=>fo});import{existsSync as cI}from"fs";function mI(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function fo(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:c.Object({session:c.String({description:"Session name or ID to create/update PR for"}),title:c.Optional(c.String({description:"PR title (default: auto-generated from session name)"})),body:c.Optional(c.String({description:"PR body (default: auto-generated from commit summary)"})),base_branch:c.Optional(c.String({description:"Base branch for the PR (default: detected from repo)"})),force_new:c.Optional(c.Boolean({description:"Force creation of a new PR even if one exists (default: false)"})),target_repo:c.Optional(c.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex'). Auto-detected from 'upstream' remote if not set."}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}],meta:{success:!1,state:"error"}};if(!mI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!pn())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 r=gr(v,n.session),o=r.activeSession,i=r.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}],meta:{success:!1,state:"error"}};let{worktreePath:s,originalWorkdir:a,sessionName:d,branchName:l}=r;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${n.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"}};cI(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${l}" via originalWorkdir (${a})`);let p=n.base_branch??cn(a),f=r.persistedRef,y=Uf(a,n.target_repo??i?.worktreePrTargetRepo);if(!Hi(a,l))return{content:[{type:"text",text:`\u274C Failed to push ${l} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let g=uo(a,l,y);if(n.force_new&&g.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${l} (${g.state}).
10
10
 
11
- Existing PR: ${f.url}
11
+ Existing PR: ${g.url}
12
12
 
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 k=Mr(a,l,m);if(k&&k.commits>0){let A=k.commitMessages.slice(0,5).map(I=>`\u2022 ${I.hash} ${I.message} (${I.author})`).join(`
14
- `),b=k.commits>5?`
15
- ...and ${k.commits-5} more commits`:"",w=["\u{1F504} **New commits pushed**","",`${k.commits} new commits (+${k.insertions} / -${k.deletions})`,"","### Latest commits:",A+b,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
16
- `);if(uf(a,f.number,w,y)){g&&v.updatePersistedSession(g,{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 I=Cr({kind:"pr-updated",branch:l,prUrl:f.url});return v.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(g.exists&&g.state==="open"){let k=Dn(a,l,p);if(k&&k.commits>0){let A=k.commitMessages.slice(0,5).map(I=>`\u2022 ${I.hash} ${I.message} (${I.author})`).join(`
14
+ `),x=k.commits>5?`
15
+ ...and ${k.commits-5} more commits`:"",w=["\u{1F504} **New commits pushed**","",`${k.commits} new commits (+${k.insertions} / -${k.deletions})`,"","### Latest commits:",A+x,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
16
+ `);if(jf(a,g.number,w,y)){f&&v.updatePersistedSession(f,{worktreePrUrl:g.url,worktreePrNumber:g.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:p,targetRepo:y,pushRemote:i?.worktreePushRemote}});let I=Fn({kind:"pr-updated",branch:l,prUrl:g.url});return v.notifyWorktreeOutcome(r.notificationTarget,I),{content:[{type:"text",text:`${I}
17
17
 
18
- \u{1F4DD} Added comment detailing ${k.commits} new commits (+${k.insertions} / -${k.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
+ \u{1F4DD} Added comment detailing ${k.commits} new commits (+${k.insertions} / -${k.deletions})`}],meta:{success:!0,state:"pr_updated"}}}else return{content:[{type:"text",text:`\u26A0\uFE0F Pushed to ${g.url} but failed to add comment.
19
19
 
20
- ${k.commits} new commits (+${k.insertions} / -${k.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return g&&v.updatePersistedSession(g,{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
+ ${k.commits} new commits (+${k.insertions} / -${k.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return f&&v.updatePersistedSession(f,{worktreePrUrl:g.url,worktreePrNumber:g.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:p,targetRepo:y,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${g.url}
21
21
 
22
- No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else{if(f.exists&&f.state==="merged")return g&&v.updatePersistedSession(g,{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
+ No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else{if(g.exists&&g.state==="merged")return f&&v.updatePersistedSession(f,{worktreePrUrl:g.url,worktreePrNumber:g.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:p,targetRepo:y,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2705 PR was already merged: ${g.url}
23
23
 
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
+ The worktree branch ${l} can be cleaned up with agent_merge(delete_branch=true).`}],meta:{success:!0,state:"merged"}};if(g.exists&&g.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${g.url}
25
25
 
26
26
  What would you like to do?
27
27
 
@@ -29,188 +29,190 @@ What would you like to do?
29
29
  2. Close and delete the branch with agent_merge(delete_branch=true), then start a new session/worktree
30
30
  3. Manually delete the closed PR on GitHub, then call agent_pr(force_new=true) to create a fresh PR
31
31
 
32
- (This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let k=r.title??`[openclaw-code-agent] ${d}`,A=r.body;if(!A){let w=Mr(a,l,m);if(w){let C=w.commitMessages.slice(0,5).map(R=>`\u2022 ${R.hash} ${R.message} (${R.author})`).join(`
32
+ (This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let k=n.title??`[openclaw-code-agent] ${d}`,A=n.body;if(!A){let w=Dn(a,l,p);if(w){let C=w.commitMessages.slice(0,5).map(R=>`\u2022 ${R.hash} ${R.message} (${R.author})`).join(`
33
33
  `),I=w.commits>5?`
34
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+I,"","---","\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 b=lf(a,l,m,k,A,y);if(b.success&&b.prUrl){let w=eo(a,l,y);g&&v.updatePersistedSession(g,{worktreePrUrl:b.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=Cr({kind:"pr-opened",branch:l,targetRepo:y,prUrl:b.prUrl});return v.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: ${b.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var Ji=u(()=>{Ee();Y();ut();no()});import{readdirSync as Rx,statSync as Tx,rmSync as Mx}from"fs";import{execFileSync as Cx}from"child_process";import{join as Lg}from"path";Ee();Y();function vv(t){return t.length>80?`${t.slice(0,80)}...`:t}function Pv(t){return t.worktreePath?!t.originalWorkdir||t.originalWorkdir===t.worktreePath?`${t.worktreePath} (worktree)`:`${t.worktreePath} (worktree of ${t.originalWorkdir})`:t.workdir}function wv(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: ${Pv(t)}`,` Model: ${t.model??"default"}`,` Prompt: "${vv(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 oi(t,e){return wv({...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 Ed(t){return"id"in t?t.id:t.sessionId}function Qn(t){return t.status==="completed"||t.killReason==="done"}function dP(t){return Qn(t)&&t.backendRef?.kind==="codex-app-server"&&!!$(t)}function lP(t){return(t.killReason==="shutdown"||t.killReason==="startup-timeout")&&!$(t)}function Jn(t){if(t.status==="running")return{kind:"direct",reason:"already_running"};let e=Ed(t);if(Qn(t)&&!dP(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 lP(t)?{kind:"relaunch",stableSessionId:e}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:e}}Re();import{existsSync as Km}from"fs";ke();function Wm(t){return t==null?void 0:String(t).trim()||void 0}function uP(t){return t.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function pP(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=uP(n?.[2]??"");if(o.startsWith("/")&&Km(o))return o}}function Bm(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&&Wm(t.originThreadId)===Wm(e.originThreadId)}function Um(t){return t.slice(0,3).map(e=>` - ${e.name} [${e.ref}] | status=${e.status}${e.lifecycle?` | lifecycle=${e.lifecycle}`:""}`).join(`
38
- `)}function cP(t,e){let r=[],n=[],o=new Set;for(let i of t.list?.("all")??[]){if(!Bm(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||!Bm(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 mP(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 Vm(t,e,r){let n=t.workdir||pP(t.prompt)||e.workspaceDir||_.defaultWorkdir||process.cwd();if(!Km(n))return{kind:"error",text:`Error: Working directory does not exist: ${n}`};let o=t.harness??Pe(),i=$t(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&&!mP(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=ai(e),m=jt(e,l||Vn(n)),g=e.sessionKey||void 0,y=fm(g)??Kn(e);if(!t.resume_session_id&&!t.force_new_session){let R=cP(r,{workdir:n,originSessionKey:g,originChannel:m,originThreadId:y});if(R.resumable.length>0||R.active.length>0){let O=R.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",Um(R.resumable),"","Resume the latest one with:",` agent_respond(session='${R.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${R.resumable[0].ref}', fork_session=true)`].join(`
39
- `):"",Le=R.active.length>0?[R.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",Um(R.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${R.active[0].ref}', message='<next instruction>')`].join(`
40
- `):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",O,Le,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
35
+ `)}else A=`Automated changes from OpenClaw Code Agent session: ${d}`}let x=qf(a,l,p,k,A,y);if(x.success&&x.prUrl){let w=uo(a,l,y);f&&v.updatePersistedSession(f,{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:p,targetRepo:y,pushRemote:i?.worktreePushRemote}});let C=Fn({kind:"pr-opened",branch:l,targetRepo:y,prUrl:x.prUrl});return v.notifyWorktreeOutcome(r.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 us=u(()=>{De();X();mt();mo()});import{readdirSync as Lx,statSync as Wx,rmSync as Bx}from"fs";import{execFileSync as Ux}from"child_process";import{join as xh}from"path";De();X();function aP(t){return t.length>80?`${t.slice(0,80)}...`:t}function dP(t){return t.worktreePath?!t.originalWorkdir||t.originalWorkdir===t.worktreePath?`${t.worktreePath} (worktree)`:`${t.worktreePath} (worktree of ${t.originalWorkdir})`:t.workdir}function lP(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: ${dP(t)}`,` Model: ${t.model??"default"}`,` Prompt: "${aP(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 mi(t,e){return lP({...t,sessionId:e.id,sessionName:e.name,model:e.model,reasoningEffort:e.reasoningEffort,worktreeStrategy:e.worktreeStrategy??"off",worktreePath:e.worktreePath,originalWorkdir:e.originalWorkdir})}Me();function dr(t){let{requestedResumeSessionId:e,activeSession:n,persistedSession:r}=t;return e?n?{resumeSessionId:e,clearedPersistedCodexResume:!1}:r?.harness==="codex"&&r.backendRef?.kind!=="codex-app-server"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:e,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}Pe();function Qd(t){return"id"in t?t.id:t.sessionId}function no(t){return t.status==="completed"||t.killReason==="done"}function QP(t){return no(t)&&t.backendRef?.kind==="codex-app-server"&&!!E(t)}function JP(t){return(t.killReason==="shutdown"||t.killReason==="startup-timeout")&&!E(t)}function ro(t){if(t.status==="running")return{kind:"direct",reason:"already_running"};let e=Qd(t);if(no(t)&&!QP(t))return{kind:"unavailable",reason:"completed",stableSessionId:e};let n=E(t);if(n){let r="harnessName"in t?void 0:t,{resumeSessionId:o,clearedPersistedCodexResume:i}=dr({requestedResumeSessionId:n,activeSession:"harnessName"in t?{harnessSessionId:n}:void 0,persistedSession:r?{harness:r.harness,backendRef:r.backendRef}:void 0});return o?{kind:"resume",resumeSessionId:o,stableSessionId:e,clearedPersistedCodexResume:i}:{kind:"unavailable",reason:"legacy_non_resumable",stableSessionId:e,clearedPersistedCodexResume:i}}return JP(t)?{kind:"relaunch",stableSessionId:e}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:e}}Me();import{existsSync as hf}from"fs";Pe();function mf(t){return t==null?void 0:String(t).trim()||void 0}function YP(t){return t.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function XP(t){let e=t.split(/\n\s*\n/,1)[0]?.split(`
37
+ `).map(n=>n.trim()).filter(Boolean)??[];if(e.length!==0)for(let n of e){let r=n.match(/^(Workdir|Repo):\s*(.+)$/),o=YP(r?.[2]??"");if(o.startsWith("/")&&hf(o))return o}}function ff(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&&mf(t.originThreadId)===mf(e.originThreadId)}function gf(t){return t.slice(0,3).map(e=>` - ${e.name} [${e.ref}] | status=${e.status}${e.lifecycle?` | lifecycle=${e.lifecycle}`:""}`).join(`
38
+ `)}function ZP(t,e){let n=[],r=[],o=new Set;for(let i of t.list?.("all")??[]){if(!ff(i,e))continue;let s=i.id;if(!o.has(s)){if(o.add(s),i.isExplicitlyResumable){n.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0});continue}(i.status==="starting"||i.status==="running")&&r.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!1})}}for(let i of t.listPersistedSessions?.()??[]){if(!i.resumable||!ff(i,e))continue;let s=re(i)??i.harnessSessionId,a=i.sessionId??E(i)??i.harnessSessionId;!s||!a||o.has(a)||(o.add(a),n.push({ref:s,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0}))}return{resumable:n,active:r}}function ew(t,e){if(!e||e.length===0)return!0;if(!t)return!1;let n=t.toLowerCase();return e.some(r=>n.includes(r.toLowerCase()))}function Sf(t,e,n){let r=t.workdir||XP(t.prompt)||e.workspaceDir||_.defaultWorkdir||process.cwd();if(!hf(r))return{kind:"error",text:`Error: Working directory does not exist: ${r}`};let o=t.harness??Ie(),i=Dt(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=ar(o);if(d&&d.length>0&&!ew(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=hi(e),p=Qt(e,l||Jr(r)),f=e.sessionKey||void 0,y=Um(f)??Qr(e);if(!t.resume_session_id&&!t.force_new_session){let R=ZP(n,{workdir:r,originSessionKey:f,originChannel:p,originThreadId:y});if(R.resumable.length>0||R.active.length>0){let O=R.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",gf(R.resumable),"","Resume the latest one with:",` agent_respond(session='${R.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${R.resumable[0].ref}', fork_session=true)`].join(`
39
+ `):"",Be=R.active.length>0?[R.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",gf(R.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${R.active[0].ref}', message='<next instruction>')`].join(`
40
+ `):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",O,Be,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
41
41
  `)].filter(Boolean).join(`
42
42
 
43
- `)}}}let f=t.resume_session_id,k=f?r.resolve?.(f):void 0,A=f?r.getPersistedSession?.(f):void 0;if(f){let R=r.resolveBackendConversationId?.(f)??r.resolveHarnessSessionId?.(f);if(!R)return{kind:"error",text:`Error: Could not resolve resume_session_id "${f}" to a session ID. Use agent_sessions to list available sessions.`};f=R}let{resumeSessionId:b,clearedPersistedCodexResume:w}=tn({requestedResumeSessionId:f,activeSession:k?{harnessSessionId:k.backendConversationId??k.harnessSessionId}:void 0,persistedSession:A?{harness:A.harness,backendRef:A.backendRef}:void 0}),C=t.permission_mode??_.permissionMode,I=t.plan_approval??_.planApproval;return{kind:"resolved",workdir:n,harness:o,resolvedModel:s,permissionMode:C,planApproval:I,originChannel:m,originThreadId:y,originSessionKey:g,route:Et(e,m,g),resumeSessionId:b,resolvedResumeId:f,clearedPersistedCodexResume:w,reasoningEffort:lt(o)}}function fP(t){return t instanceof Error?t.message:String(t)}function qm(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function gP(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function hP(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function jm(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(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!gP(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=Vm(r,t,v);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:g,route:y,resumeSessionId:f,resolvedResumeId:k,clearedPersistedCodexResume:A,reasoningEffort:b}=n,w=r.resume_session_id?v.resolve(r.resume_session_id)??v.getPersistedSession(r.resume_session_id):void 0,C=!r.fork_session&&w?Jn(w):void 0;if(C?.kind==="direct")return{content:[{type:"text",text:`Session ${w.name} [${qm(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} [${qm(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 I=v.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:b,systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,resumeSessionId:C?.kind==="resume"?C.resumeSessionId:f,resumeWorktreeFrom:k,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:g,route:y,harness:i,worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,worktreePrTargetRepo:r.worktree_pr_target_repo});return{content:[{type:"text",text:hP(v)?v.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},I):oi({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:I.id,name:I.name,model:I.model,reasoningEffort:I.reasoningEffort??lt(i),worktreeStrategy:I.worktreeStrategy??r.worktree_strategy??_.defaultWorktreeStrategy??"off",worktreePath:I.worktreePath,originalWorkdir:I.originalWorkdir})}]}}catch(n){let o=fP(n),i=o.includes("Max sessions")?"":`
44
-
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 Kd,readFileSync as hf}from"fs";import{EventEmitter as FP}from"events";import{webcrypto as Hm}from"node:crypto";var Gm="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var SP=128,Tr,on;function yP(t){!Tr||Tr.length<t?(Tr=Buffer.allocUnsafe(t*SP),Hm.getRandomValues(Tr),on=0):on+t>Tr.length&&(Hm.getRandomValues(Tr),on=0),on+=t}function vi(t=21){yP(t|=0);let e="";for(let r=on-t;r<on;r++)e+=Gm[Tr[r]&63];return e}Cd();Re();ke();var zm={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},Qm=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function kP(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:kP(t)}}function Od(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":Qm.has(e.worktreeState)?"terminal":t.lifecycle});case"delivery.state_set":return Oe({...t,deliveryState:e.deliveryState})}}function Jm(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=Od(r,{type:"worktree.decision_requested"}):Qm.has(r.worktreeState)&&(r={...r,lifecycle:"terminal"}),Oe(r)}var Pi=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 vP}from"fs";import{tmpdir as PP}from"os";import{join as wP}from"path";var Ym=2e3;function sn(t){return wP(PP(),`openclaw-agent-${t}.txt`)}function IP(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 Xm(t,e,r){IP(t,r),t.length>Ym&&t.splice(0,t.length-Ym);try{vP(sn(e),r,"utf-8")}catch{}return t}var wi=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 Ii=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 xi=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 LP=120*1e3;function Ni(t){return t instanceof Error?t.message:String(t)}var Fi=class extends FP{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 wi;constructor(e,r){super(),this.id=e.sessionIdOverride??vi(8),this.name=r,this.harness=e.harness?zn(e.harness):Fm(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??$t(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 Ii({appendOutput:n=>Xm(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 xi({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??=Ci(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(!zm[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 Pi,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:um(),canUseTool:this.canUseTool});this.harnessHandle=r,this.setTimer("startup",LP,()=>{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: ${Ni(s)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${n}: ${Ni(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.]
48
-
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.]
50
-
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: ${Ni(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: ${Ni(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=Od(this.controlStateSnapshot(),e);this.applyControlState(r)}applyControlPatch(e){let r=Jm(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 WP=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 mf(t){let r=t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!WP.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var cf={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 ff(t){let e=cf[t.phase]??cf[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 Li(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 Wi(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 gf(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 BP=50,UP=1,KP=new Set(["starting","running","completed","failed","killed"]),VP=5,qP=1440*60*1e3;function jP(t){let e=Number(t);return!Number.isFinite(e)||e<UP?BP:Math.floor(e)}function GP(t){return typeof t=="string"&&KP.has(t)}function HP(t){let e=t.split(`
58
- `);return e.at(-1)===""&&e.pop(),e}function Sf(t){return t.backendRef?.conversationId??t.harnessSessionId}function yf(t,e,r){let n=hf(t,"utf-8"),o=HP(n);return e.full?o:o.slice(-r)}function zP(t,e,r){if(t.status!=="starting"&&t.status!=="running")return null;let n=sn(t.id);if(!Kd(n))return null;try{return yf(n,e,r)}catch{return null}}function QP(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 JP(t){return[`Session: ${t.name||t.sessionId||Sf(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 YP(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?`
43
+ `)}}}let g=t.resume_session_id,k=g?n.resolve?.(g):void 0,A=g?n.getPersistedSession?.(g):void 0;if(g){let R=n.resolveBackendConversationId?.(g)??n.resolveHarnessSessionId?.(g);if(!R)return{kind:"error",text:`Error: Could not resolve resume_session_id "${g}" to a session ID. Use agent_sessions to list available sessions.`};g=R}let{resumeSessionId:x,clearedPersistedCodexResume:w}=dr({requestedResumeSessionId:g,activeSession:k?{harnessSessionId:k.backendConversationId??k.harnessSessionId}:void 0,persistedSession:A?{harness:A.harness,backendRef:A.backendRef}:void 0}),C=t.permission_mode??_.permissionMode,I=t.plan_approval??_.planApproval;return{kind:"resolved",workdir:r,harness:o,resolvedModel:s,permissionMode:C,planApproval:I,originChannel:p,originThreadId:y,originSessionKey:f,route:Ft(e,p,f),resumeSessionId:x,resolvedResumeId:g,clearedPersistedCodexResume:w,reasoningEffort:ct(o)}}Pe();function Tt(t){let e=Math.floor(t/1e3),n=Math.floor(e/60),r=e%60;return n>0?`${n}m${r}s`:`${r}s`}var tw=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 kf(t){let n=t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!tw.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var yf={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 vf(t){let e=yf[t.phase]??yf[t.status]??"\u2753",n=Tt(t.duration),r=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}] (${n}${i}) \u2014 ${r}`,` \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=E(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(`
44
+ `)}function Mi(t,e){let n=t.sessionsWithDuration>0?t.totalDurationMs/t.sessionsWithDuration:0,{completed:r,failed:o,killed:i}=t.sessionsByStatus,s=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${t.totalLaunched}`,` Running: ${e}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${n>0?Tt(n):"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(`
45
+ `)}function Ce(t,e){return e<=0?"":t.length<=e?t:e<=3?".".repeat(e):t.slice(0,e-3)+"..."}function Ci(t,e){let n=t.split(`
46
+ `),r=[],o=0;for(let i=n.length-1;i>=0;i--){let s=n[i].length+(r.length>0?1:0);if(o+s>e&&r.length>0)break;r.unshift(n[i]),o+=s}return r.join(`
47
+ `)}function Pf(t,e){let n=t.split(`
48
+ `),r=[],o=0;for(let i=0;i<n.length;i++){let s=n[i].length+(r.length>0?1:0);if(o+s>e&&r.length>0)break;r.push(n[i]),o+=s}return r.join(`
49
+ `)}var oo,io,pr=!1;function wf(t){try{return t?.config?.current?.()}catch{return}}function _i(t,e){if(t&&typeof t=="object"){oo=t,arguments.length>=2?(io=e,pr=!0):pr||(io=wf(oo),pr=!0);return}oo=void 0,io=void 0,pr=!1}function Ei(){return oo}function If(){return pr||(io=wf(oo),pr=!0),io}var nw="openclaw-code-agent",rw=160,$i={create(){},progress(){},finalize(){}};function Oi(t,e){let n=e instanceof Error?e.message:String(e);console.warn(`[SessionTaskLifecycle] ${t} failed: ${n}`)}function ow(t,e){if(e.applied===!1){let n=e.code?` (${e.code})`:"";console.warn(`[SessionTaskLifecycle] ${t} mutation was not applied${n}`)}}function iw(t){let e=t.prompt.trim().replace(/\s+/g," ");return Ce(e||t.name,rw)}function sw(t){if(t.status==="starting"||t.lifecycle==="starting")return"Starting";if(t.lifecycle==="active")return"Running";if(t.lifecycle==="awaiting_plan_decision")return"Waiting for plan approval";if(t.lifecycle==="awaiting_user_input")return"Waiting for input";if(t.lifecycle==="awaiting_worktree_decision")return"Waiting for worktree decision";if(t.lifecycle==="suspended")return"Suspended after idle timeout"}function aw(t){if(t.status==="completed")return"succeeded";if(t.status==="failed")return"failed";if(t.status==="killed")return t.killReason==="idle-timeout"||t.killReason==="startup-timeout"?"timed_out":"cancelled"}function Jd(t,e){return t==="completed"?"Completed":t==="failed"?"Failed":e==="idle-timeout"?"Timed out after idle timeout":e==="startup-timeout"?"Timed out during startup":e==="shutdown"?"Cancelled during shutdown":e==="user"?"Cancelled by user":"Cancelled"}function dw(t){return t.lifecycle==="awaiting_plan_decision"||t.lifecycle==="awaiting_user_input"||t.lifecycle==="awaiting_worktree_decision"||t.lifecycle==="suspended"}function Yd(t,e,n){return{phase:e,integration:"phase-1-managed-task-flow",sessionId:t.id,sessionName:t.name,sessionStatus:t.status,sessionLifecycle:t.lifecycle,summary:n}}function lw(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.createManaged=="function"&&typeof e.resume=="function"&&typeof e.setWaiting=="function"&&typeof e.finish=="function"&&typeof e.fail=="function"}function bf(t,e){if(e.applied)return e.flow;let n=e.current;return n?.flowId&&typeof n.revision=="number"?n:t}var Xd=class{constructor(e){this.taskFlow=e}taskFlow;flow;finalized=!1;lastProgressKey;create(e){if(this.flow||this.finalized)return;let n="Starting",r=Date.now();try{this.flow=this.taskFlow.createManaged({controllerId:nw,goal:iw(e),status:"running",notifyPolicy:"silent",currentStep:n,stateJson:Yd(e,"created",n),createdAt:e.startedAt,updatedAt:r}),this.lastProgressKey=this.progressKey(e,n)}catch(o){Oi("create",o)}}progress(e){if(!this.flow||this.finalized)return;let n=sw(e);if(!n)return;let r=this.progressKey(e,n);if(r!==this.lastProgressKey)try{let o=Yd(e,"progress",n),i=Date.now(),s=dw(e)?this.taskFlow.setWaiting({flowId:this.flow.flowId,expectedRevision:this.flow.revision,currentStep:n,stateJson:o,waitJson:{reason:n,sessionId:e.id},blockedSummary:n,updatedAt:i}):this.taskFlow.resume({flowId:this.flow.flowId,expectedRevision:this.flow.revision,status:"running",currentStep:n,stateJson:o,updatedAt:i});this.flow=bf(this.flow,s),this.lastProgressKey=r}catch(o){Oi("progress",o)}}finalize(e){if(!this.flow||this.finalized)return;let n=aw(e);if(!n)return;let r=n==="succeeded"?"Completed":n==="failed"?"Failed":Jd(e.status,e.killReason);try{let o=e.completedAt??Date.now(),i={...Yd(e,"terminal",r),terminalStatus:n,terminalSummary:Jd(e.status,e.killReason),...e.status==="failed"&&e.error?{error:e.error}:{}},s=n==="succeeded"?this.taskFlow.finish({flowId:this.flow.flowId,expectedRevision:this.flow.revision,stateJson:i,updatedAt:o,endedAt:o}):this.taskFlow.fail({flowId:this.flow.flowId,expectedRevision:this.flow.revision,stateJson:i,blockedSummary:Jd(e.status,e.killReason),updatedAt:o,endedAt:o});ow("finalize",s),this.flow=bf(this.flow,s),this.finalized=!0}catch(o){Oi("finalize",o)}}progressKey(e,n){return`${e.status}:${e.lifecycle}:${n}`}};function xf(t){if(!t.sessionKey?.trim())return $i;try{let e=Ei()?.taskFlow?.fromToolContext;if(typeof e!="function")return $i;let n=e(t);return lw(n)?new Xd(n):$i}catch(e){return Oi("resolve",e),$i}}function uw(t){return t instanceof Error?t.message:String(t)}function Af(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function pw(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function cw(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function Rf(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:c.Object({prompt:c.String({description:"The task prompt to execute"}),name:c.Optional(c.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:c.Optional(c.String({description:"Working directory (defaults to cwd)"})),model:c.Optional(c.String({description:"Model name to use"})),system_prompt:c.Optional(c.String({description:"Additional system prompt"})),allowed_tools:c.Optional(c.Array(c.String(),{description:"List of allowed tools"})),resume_session_id:c.Optional(c.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:c.Optional(c.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),force_new_session:c.Optional(c.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:c.Optional(c.Union([c.Literal("default"),c.Literal("plan"),c.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:c.Optional(c.Union([c.Literal("ask"),c.Literal("delegate"),c.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:c.Optional(c.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."})),worktree_strategy:c.Optional(c.Union([c.Literal("off"),c.Literal("manual"),c.Literal("ask"),c.Literal("delegate"),c.Literal("auto-merge"),c.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:c.Optional(c.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),worktree_pr_target_repo:c.Optional(c.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,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!pw(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};n.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${n.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${t.agentId}" will be used for origin routing instead.`);try{let r=Sf(n,t,v);if(r.kind!=="resolved")return{content:[{type:"text",text:r.text}]};let{workdir:o,harness:i,resolvedModel:s,permissionMode:a,planApproval:d,originChannel:l,originThreadId:p,originSessionKey:f,route:y,resumeSessionId:g,resolvedResumeId:k,clearedPersistedCodexResume:A,reasoningEffort:x}=r,w=n.resume_session_id?v.resolve(n.resume_session_id)??v.getPersistedSession(n.resume_session_id):void 0,C=!n.fork_session&&w?ro(w):void 0;if(C?.kind==="direct")return{content:[{type:"text",text:`Session ${w.name} [${Af(w,n.resume_session_id)}] is already running. Use agent_respond(session='${n.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} [${Af(w,n.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 I=v.spawn({prompt:n.prompt,sessionIdOverride:n.fork_session?void 0:C?.kind==="resume"||C?.kind==="relaunch"?C.stableSessionId:void 0,name:n.name,workdir:o,model:s,reasoningEffort:x,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:C?.kind==="resume"?C.resumeSessionId:g,resumeWorktreeFrom:k,forkSession:g?n.fork_session:!1,multiTurn:!0,permissionMode:a,planApproval:d,codexApprovalPolicy:i==="codex"?"never":void 0,originChannel:l,originThreadId:p,originAgentId:t.agentId||void 0,originSessionKey:f,route:y,harness:i,taskLifecycle:xf(t),worktreeStrategy:n.worktree_strategy,worktreeBaseBranch:n.worktree_base_branch,worktreePrTargetRepo:n.worktree_pr_target_repo});return{content:[{type:"text",text:cw(v)?v.formatLaunchResult({prompt:n.prompt,workdir:o,harness:i,permissionMode:a??_.permissionMode,planApproval:d,forceNewSession:n.force_new_session,resumeSessionId:n.resume_session_id,forkSession:n.fork_session,clearedPersistedCodexResume:A},I):mi({prompt:n.prompt,workdir:o,harness:i,permissionMode:a??_.permissionMode,planApproval:d,resumeSessionId:n.resume_session_id,forkSession:n.fork_session,forceNewSession:n.force_new_session,clearedPersistedCodexResume:A},{id:I.id,name:I.name,model:I.model,reasoningEffort:I.reasoningEffort??ct(i),worktreeStrategy:I.worktreeStrategy??n.worktree_strategy??_.defaultWorktreeStrategy??"off",worktreePath:I.worktreePath,originalWorkdir:I.originalWorkdir})}]}}catch(r){let o=uw(r),i=o.includes("Max sessions")?"":`
50
+
51
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}De();X();Me();import{existsSync as al,readFileSync as zf}from"fs";import{EventEmitter as $w}from"events";import{webcrypto as Mf}from"node:crypto";var Tf="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var mw=128,Nn,cr;function fw(t){!Nn||Nn.length<t?(Nn=Buffer.allocUnsafe(t*mw),Mf.getRandomValues(Nn),cr=0):cr+t>Nn.length&&(Mf.getRandomValues(Nn),cr=0),cr+=t}function Ni(t=21){fw(t|=0);let e="";for(let n=cr-t;n<cr;n++)e+=Tf[Nn[n]&63];return e}Gd();Me();Pe();var Cf={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},_f=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function gw(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 Fe(t){return{...t,approvalExecutionState:gw(t)}}function Zd(t,e){switch(e.type){case"initialize":return Fe({...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"?Fe({...t,status:e.status,lifecycle:"starting",runtimeState:"live"}):e.status==="running"?Fe({...t,status:e.status,lifecycle:t.lifecycle==="starting"||t.lifecycle==="suspended"?"active":t.lifecycle,runtimeState:"live"}):Fe({...t,status:e.status,runtimeState:"stopped",lifecycle:t.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return Fe({...t,currentPermissionMode:e.currentPermissionMode});case"turn.started":return Fe({...t,lifecycle:"active",runtimeState:"live"});case"input.requested":return Fe({...t,lifecycle:t.pendingPlanApproval?"awaiting_plan_decision":"awaiting_user_input"});case"plan.requested":if(t.planModeApproved)return t;{let n=t.pendingPlanApproval&&t.approvalState==="pending"&&t.planApprovalContext===e.context,r=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=n||r||o?t.planDecisionVersion:t.planDecisionVersion+1;return Fe({...t,pendingPlanApproval:!0,planApprovalContext:e.context,approvalState:"pending",planDecisionVersion:i,actionablePlanDecisionVersion:i,canonicalPlanPromptVersion:n?t.canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:n?t.approvalPromptRequiredVersion:void 0,approvalPromptVersion:n?t.approvalPromptVersion:void 0,approvalPromptStatus:n?t.approvalPromptStatus:"not_sent",approvalPromptTransport:n?t.approvalPromptTransport:"none",approvalPromptMessageKind:n?t.approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:n?t.approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:n?t.approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:n?t.approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"})}case"plan.cleared":return Fe({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,approvalState:t.approvalState==="pending"?"not_required":t.approvalState});case"plan.approved":return Fe({...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 Fe({...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 Fe({...t,lifecycle:e.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return Fe({...t,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return Fe({...t,worktreeState:e.worktreeState,lifecycle:e.worktreeState==="pending_decision"?"awaiting_worktree_decision":_f.has(e.worktreeState)?"terminal":t.lifecycle});case"delivery.state_set":return Fe({...t,deliveryState:e.deliveryState})}}function Ef(t,e){let n={...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&&(n={...n,pendingPlanApproval:!1}),n.pendingPlanApproval?n={...n,approvalState:"pending",actionablePlanDecisionVersion:n.actionablePlanDecisionVersion??n.planDecisionVersion,lifecycle:"awaiting_plan_decision"}:n.approvalState==="changes_requested"&&(n={...n,actionablePlanDecisionVersion:void 0,lifecycle:"awaiting_user_input"}),e.pendingWorktreeDecisionSince!==void 0||n.worktreeState==="pending_decision"?n=Zd(n,{type:"worktree.decision_requested"}):_f.has(n.worktreeState)&&(n={...n,lifecycle:"terminal"}),Fe(n)}var Di=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 hw}from"fs";import{tmpdir as Sw}from"os";import{join as yw}from"path";var $f=2e3;function mr(t){return yw(Sw(),`openclaw-agent-${t}.txt`)}function kw(t,e){if(!e)return;let n=e.split(`
52
+ `),[r="",...o]=n;t.length===0?t.push(r):t[t.length-1]+=r;for(let i of o)t.push(i)}function Of(t,e,n){kw(t,n),t.length>$f&&t.splice(0,t.length-$f);try{hw(mr(e),n,"utf-8")}catch{}return t}var Fi=class{timers=new Map;get size(){return this.timers.size}set(e,n,r){this.clear(e);let o=setTimeout(r,n);o.unref?.(),this.timers.set(e,o)}clear(e){let n=this.timers.get(e);n&&(clearTimeout(n),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var Li=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,n){this.waitingForInputFired=!1,n||(this.lastTurnHadQuestion=!1),this.deps.appendOutput(e),this.currentTurnText+=this.currentTurnText?`
53
+ ${e}`:e,this.deps.emitOutput(e)}noteToolCall(e){let{name:n,input:r,currentPermissionMode:o,permissionMode:i,planModeApproved:s}=e;if(n==="Write"){let a=r;typeof a?.file_path=="string"&&a.file_path.includes("/.claude/plans/")&&this.deps.setPlanFilePath(a.file_path)}n==="AskUserQuestion"?(this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),(o==="plan"||i==="plan")&&!s&&this.deps.markPendingPlanApproval("plan-mode")):(n==="ExitPlanMode"||n==="set_permission_mode")&&!s&&(this.lastTurnHadQuestion=!0,this.deps.markPendingPlanApproval("plan-mode")),this.deps.emitToolUse(n,r)}notePendingInput(){this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),this.waitingForInputFired||(this.waitingForInputFired=!0,this.deps.emitTurnEnd(!0))}clearResolvedPendingInput(e,n){if(!(!e||n?.requestId===e))return n}notePlanArtifact(e,n){if(this.currentTurnPlanArtifact=e,this.deps.setLatestPlanArtifact(e),!n)return;let r=e.markdown.trim();!r||this.currentTurnText.trim()===r||(this.deps.appendOutput(r),this.currentTurnText=r,this.deps.emitOutput(r))}noteSettingsChanged(e){let{oldMode:n,permissionMode:r,planModeApproved:o}=e;if(r)return r!=="plan"&&n==="plan"&&!o&&(this.deps.markPendingPlanApproval("plan-mode"),this.lastTurnHadQuestion=!0),r}finishSuccessfulTurn(e){let{currentPermissionMode:n,permissionMode:r,pendingPlanApproval:o,planModeApproved:i,pendingInputState:s,hasPendingMessages:a}=e,d=o;(n==="plan"||r==="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 Wi=class{constructor(e){this.deps=e}deps;applyMessage(e,n){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,n.pendingPlanApproval);return}if(e.type==="tool_call"){this.deps.noteToolCall({name:e.name,input:e.input,currentPermissionMode:n.currentPermissionMode,permissionMode:n.permissionMode,planModeApproved:n.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,n.pendingInputState));return}if(e.type==="plan_artifact"){this.deps.notePlanArtifact(e);return}if(e.type==="settings_changed"){let r=this.deps.noteSettingsChanged({oldMode:n.currentPermissionMode,permissionMode:e.permissionMode,planModeApproved:n.planModeApproved});r&&this.deps.setCurrentPermissionMode(r);return}if(e.type==="run_completed"){this.deps.handleRunCompleted(e.data);return}e.type}};mt();var Ow=120*1e3;function Yi(t){return t instanceof Error?t.message:String(t)}var Xi=class extends $w{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 Fi;constructor(e,n){super(),this.id=e.sessionIdOverride??Ni(8),this.name=n,this.harness=e.harness?to(e.harness):pf(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??Dt(this.harness.name),this.reasoningEffort=e.reasoningEffort??ct(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 Li({appendOutput:r=>Of(this.outputBuffer,this.id,r),emitOutput:r=>this.emit("output",this,r),emitToolUse:(r,o)=>this.emit("toolUse",this,r,o),emitTurnEnd:r=>this.emit("turnEnd",this,r),markPendingPlanApproval:r=>this.markPendingPlanApproval(r),markAwaitingUserInput:()=>this.markAwaitingUserInput(),applyInputRequested:()=>this.applyControlEvent({type:"input.requested"}),completeTurn:()=>{this.applyControlEvent({type:"terminal.entered"}),this.complete("done")},setPlanFilePath:r=>{this.planFilePath=r},setLatestPlanArtifact:r=>{this.latestPlanArtifact=r;let o=this.pendingPlanApproval?this.actionablePlanDecisionVersion??this.planDecisionVersion:void 0;this.latestPlanArtifactVersion=o&&o>0?o:void 0}}),this.harnessEvents=new Wi({clearStartupTimer:()=>this.clearTimer("startup"),assignBackendRef:r=>{this.backendRef=r,this.harnessSessionId=r.conversationId,r.worktreePath&&(this.worktreePath=r.worktreePath,this.originalWorkdir??=this.workdir,this.worktreeBranch??=ji(r.worktreePath),this.worktreeStrategy&&this.worktreeStrategy!=="off"&&this.applyControlEvent({type:"worktree.state_set",worktreeState:"provisioned"}))},noteRunStarted:r=>{this.backendRef&&(this.backendRef={...this.backendRef,runId:r})},transitionRunning:()=>{this._status==="starting"&&this.transition("running")},noteTextDelta:(r,o)=>this.turnRuntime.noteTextDelta(r,o),noteToolCall:r=>this.turnRuntime.noteToolCall(r),setPendingInputState:r=>{this.pendingInputState=r},notePendingInput:()=>this.turnRuntime.notePendingInput(),clearResolvedPendingInput:(r,o)=>this.turnRuntime.clearResolvedPendingInput(r,o),notePlanArtifact:r=>this.turnRuntime.notePlanArtifact(r.artifact,r.finalized),noteSettingsChanged:r=>this.turnRuntime.noteSettingsChanged(r),setCurrentPermissionMode:r=>{this.currentPermissionMode=r,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:r})},handleRunCompleted:r=>{let o=r.outcome??(r.success?"completed":"failed");this.result={subtype:o==="interrupted"?"interrupted":r.success?"success":"error",duration_ms:r.duration_ms,total_cost_usd:r.total_cost_usd,num_turns:r.num_turns,result:r.result,is_error:o==="failed",session_id:r.session_id},this.costUsd=r.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 E(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(!Cf[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 n=this._status;this._status=e,this.applyControlEvent({type:"status.transition",status:e}),this.emit("statusChange",this,e,n)}setTimer(e,n,r){this.timers.set(e,n,r)}clearTimer(e){this.timers.clear(e)}clearAllTimers(){this.timers.clearAll()}markPendingPlanApproval(e){let n=this.latestPlanArtifactVersion;this.approvalRationale=void 0,this.applyControlEvent({type:"plan.requested",context:e});let r=this.actionablePlanDecisionVersion??this.planDecisionVersion;this.currentTurnPlanArtifact&&r>0?(this.latestPlanArtifact=this.currentTurnPlanArtifact,this.latestPlanArtifactVersion=r):n!==r&&(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 Di,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),e=this.messageStream):e=this.prompt;let n=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:Fm(),canUseTool:this.canUseTool});this.harnessHandle=n,this.setTimer("startup",Ow,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(e){let n=e instanceof Error?e.message:String(e);this.transitionToTerminal("failed",{error:n});return}this.consumeMessages(this.harnessHandle.messages).catch(e=>{let n=e instanceof Error?e.message:String(e),r=e instanceof Error?e.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${n}`,r),this.isActive&&this.transitionToTerminal("failed",{error:n})})}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 n=e;if(this.pendingModeSwitch){let r=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(r),this.currentPermissionMode=r,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:r}),this.pendingModeSwitch=void 0,i=!0,o=!0}catch(s){throw console.error(`[Session ${this.id}] setPermissionMode(${r}) FAILED: ${Yi(s)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${r}: ${Yi(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(),r!=="plan"&&this.applyControlEvent({type:"plan.approved"})),o&&(n=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
54
+
55
+ ${e}`)}else if((this.pendingPlanApproval||this.approvalState==="changes_requested")&&!this.planModeApproved&&(this.approvalState!=="changes_requested"&&this.applyControlEvent({type:"plan.changes_requested"}),n=`[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.]
56
+
57
+ ${e}`,this.harnessHandle?.setPermissionMode))try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan",this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:"plan"})}catch(r){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${Yi(r)}`)}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(n,this.backendConversationId??""));else if(this.harnessHandle?.streamInput){let r=this.harness.buildUserMessage(n,this.backendConversationId??"");async function*o(){yield r}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){return!this.turnInProgress||!this.harnessHandle?.interrupt?!1:(await this.harnessHandle.interrupt(),!0)}async submitPendingInputOption(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputOption)return!1;let n=await this.harnessHandle.submitPendingInputOption(e);return n&&(this.waitingForInputFired=!1),n}async submitPendingInputText(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputText)return!1;let n=await this.harnessHandle.submitPendingInputText(e);return n&&(this.waitingForInputFired=!1),n}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: ${Yi(e)}`)}),this.abortController.abort(),this.applyControlEvent({type:"terminal.entered",suspended:this.lifecycle==="suspended"})}transitionToTerminal(e,n={}){this.isActive&&(this.turnInProgress=!1,n.reason&&(this.killReason=n.reason),n.error!==void 0&&(this.error=n.error),this.completedAt=Date.now(),this.applyControlEvent({type:"terminal.entered",suspended:e==="killed"&&n.reason==="idle-timeout"}),this.transition(e),this.teardown())}async consumeMessages(e){for await(let n of e){if(!this.isActive)break;this.resetIdleTimer(),this.harnessEvents.applyMessage(n,{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 n=Zd(this.controlStateSnapshot(),e);this.applyControlState(n)}applyControlPatch(e){let n=Ef(this.controlStateSnapshot(),e);this.applyControlState(n)}setControlField(e,n){this.applyControlPatch({[e]:n})}applyControlState(e){let n=this.lifecycle;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,n!==this.lifecycle&&this.emit("lifecycleChange",this,this.lifecycle,n)}};var Nw=50,Dw=1,Fw=new Set(["starting","running","completed","failed","killed"]),Lw=5,Ww=1440*60*1e3;function Bw(t){let e=Number(t);return!Number.isFinite(e)||e<Dw?Nw:Math.floor(e)}function Uw(t){return typeof t=="string"&&Fw.has(t)}function Kw(t){let e=t.split(`
58
+ `);return e.at(-1)===""&&e.pop(),e}function dl(t){return t.backendRef?.conversationId??t.harnessSessionId}function Qf(t,e,n){let r=zf(t,"utf-8"),o=Kw(r);return e.full?o:o.slice(-n)}function Vw(t,e,n){if(t.status!=="starting"&&t.status!=="running")return null;let r=mr(t.id);if(!al(r))return null;try{return Qf(r,e,n)}catch{return null}}function qw(t){let e=Tt(t.duration),n=` | Cost: $${t.costUsd.toFixed(4)}`,r=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()}${r}${o}${n} | Duration: ${e}`,`${"\u2500".repeat(60)}`].join(`
59
+ `)}function Jf(t,e){let n=t.name||t.sessionId||dl(t)||"unknown",r=t.lifecycle?` | Phase: ${t.lifecycle}`:"";return[`Session: ${n} | Status: ${t.status.toUpperCase()}${r} | Cost: $${t.costUsd.toFixed(4)}`,e,`${"\u2500".repeat(60)}`].join(`
60
+ `)}function jw(t){return`(retrieved from ${t.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`}function Gw(t){return t.outputPath?`(persisted session metadata recovered; output file is unavailable at ${t.outputPath})`:"(persisted session metadata recovered; no output file was recorded)"}function Hf(t,e){let n=Jf(t,Gw(t)),r=dl(t),o=r?`
61
+ Backend session: ${r}`:"";return`${n}
62
+ (no persisted output available: ${e})${o}`}function Hw(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?`
61
63
  (no output yet)
62
64
  ${e.join(`
63
65
  `)}`:`
64
- (no output yet)`}function Bi(t,e,r={}){let n=jP(r.lines),o=t.resolve(e);if(!o){let l=t.getPersistedSession(e);if(l?.outputPath&&Kd(l.outputPath))try{let m=yf(l.outputPath,r,n).join(`
65
- `),g=JP(l);return m?`${g}
66
- ${m}`:`${g}
67
- (output file was empty)`}catch(m){let g=m instanceof Error?m.message:String(m);return`Error: Session "${e}" was cleaned up (expired) and output file could not be read: ${g}`}return`Error: Session "${e}" not found.`}let i=zP(o,r,n),s=i&&i.length>0?i:r.full?o.getOutput():o.getOutput(n),a=QP(o),d=s.length===0?`${a}${YP(o)}`:`${a}
66
+ (no output yet)`}function Zi(t,e,n={}){let r=Bw(n.lines),o=t.resolve(e);if(!o){let l=t.getPersistedSession(e);if(l?.outputPath&&al(l.outputPath))try{let p=Qf(l.outputPath,n,r).join(`
67
+ `),f=Jf(l,jw(l));return p?`${f}
68
+ ${p}`:`${f}
69
+ (output file was empty)`}catch(p){let f=p instanceof Error?p.message:String(p);return`Error: Session "${e}" was cleaned up (expired) and output file could not be read: ${f}`}return l?.outputPath?Hf(l,`output file is missing at ${l.outputPath}`):l?Hf(l,"no outputPath is stored for this recovered session"):`Error: Session "${e}" not found.`}let i=Vw(o,n,r),s=i&&i.length>0?i:n.full?o.getOutput():o.getOutput(r),a=qw(o),d=s.length===0?`${a}${Hw(o)}`:`${a}
68
70
  ${s.join(`
69
- `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(Kd(o.planFilePath)){let l=hf(o.planFilePath,"utf-8"),m="\u2500".repeat(60);return`${d}
70
- ${m}
71
+ `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(al(o.planFilePath)){let l=zf(o.planFilePath,"utf-8"),p="\u2500".repeat(60);return`${d}
72
+ ${p}
71
73
  Plan file: ${o.planFilePath}
72
- ${m}
73
- ${l}`}}catch{}return d}function Ui(t,e="all",r,n={}){let o=t.listPersistedSessions()??[],s=XP(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()-qP;s=s.filter(d=>(d.startedAt??0)>=a)}else s=s.slice(0,VP);return s.length===0?"No sessions found.":s.map(a=>ff(a)).join(`
74
+ ${p}
75
+ ${l}`}}catch{}return d}function es(t,e="all",n,r={}){let o=t.listPersistedSessions()??[],s=zw(t.list("all"),o);if(e!=="all"&&(s=s.filter(a=>a.status===e)),n&&(s=s.filter(a=>a.originChannel===n)),r.full){let a=Date.now()-Ww;s=s.filter(d=>(d.startedAt??0)>=a)}else s=s.slice(0,Lw);return s.length===0?"No sessions found.":s.map(a=>vf(a)).join(`
74
76
 
75
- `)}function XP(t,e){let r=new Map;for(let n of e){if(!GP(n.status))continue;let o=n.completedAt??Date.now(),i=n.createdAt??o,s=Sf(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 ZP(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 kf(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(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=ZP(r),o=t?.workspaceDir?Vn(t.workspaceDir):void 0,i=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:Ui(v,n,o,{full:i})}]}}}}Ee();Y();function Ki(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 ew(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 vf(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 v?ew(r)?{content:[{type:"text",text:Ki(v,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 tw(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Vi(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 v?tw(r)?{content:[{type:"text",text:Bi(v,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 rw=10;function qd(t){return t instanceof Error?t.message:String(t)}function _r(t){return re(t)??t.harnessSessionId??"unknown-session"}function Pf(t){return t.status!=="running"&&!!t.pendingPlanApproval&&!!$(t)}function ro(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='${_r(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='${_r(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='${_r(t)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${_r(t)}', message='<next instruction>') to continue the running session.`,o=r?` ${r}`:"";return{text:`Resume unavailable for session ${t.name} [${_r(t)}] (${e}).${o} ${n}`,isError:!0}}async function wf(t,e,r){try{let n={prompt:e.prompt,sessionIdOverride:Ed(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} [${_r(e)}]: ${qd(n)}`,isError:!0}}}var nw=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
77
+ `)}function zw(t,e){let n=new Map;for(let r of e){if(!Uw(r.status))continue;let o=r.completedAt??Date.now(),i=r.createdAt??o,s=dl(r),a=r.sessionId??`persisted:${s??r.harnessSessionId}`;n.set(a,{id:r.sessionId??s??r.harnessSessionId,name:r.name||r.sessionId||s||r.harnessSessionId,status:r.status,startedAt:r.createdAt??0,completedAt:r.completedAt,duration:Math.max(0,o-i),prompt:r.prompt??"",workdir:r.workdir??"(unknown)",costUsd:r.costUsd??0,multiTurn:!0,phase:r.lifecycle??r.status,lifecycle:r.lifecycle,resumable:r.resumable,harness:r.harness,backendRef:r.backendRef,harnessSessionId:r.harnessSessionId,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,approvalExecutionState:r.approvalExecutionState,originChannel:r.originChannel,originThreadId:r.originThreadId,worktreePath:r.worktreePath,worktreeBranch:r.worktreeBranch,worktreeStrategy:r.worktreeStrategy,worktreeMerged:r.worktreeMerged,worktreeMergedAt:r.worktreeMergedAt,worktreePrUrl:r.worktreePrUrl})}for(let r of t)n.set(r.id,{id:r.id,name:r.name,status:r.status,startedAt:r.startedAt,completedAt:r.completedAt,duration:r.duration,prompt:r.prompt,workdir:r.originalWorkdir??r.workdir,costUsd:r.costUsd,multiTurn:r.multiTurn,phase:r.phase,lifecycle:r.lifecycle,resumable:r.isExplicitlyResumable,harness:r.harnessName,backendRef:r.backendRef,harnessSessionId:r.harnessSessionId,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,approvalExecutionState:r.approvalExecutionState,originChannel:r.originChannel,originThreadId:r.originThreadId,worktreePath:r.worktreePath,worktreeBranch:r.worktreeBranch,worktreeStrategy:r.worktreeStrategy,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0});return[...n.values()].sort((r,o)=>(o.startedAt??0)-(r.startedAt??0))}function Qw(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 Yf(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:c.Object({status:c.Optional(c.Union([c.Literal("all"),c.Literal("running"),c.Literal("completed"),c.Literal("failed"),c.Literal("killed")],{description:'Filter by status (default "all")'})),full:c.Optional(c.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=Qw(n),o=t?.workspaceDir?Jr(t.workspaceDir):void 0,i=!!(n&&typeof n=="object"&&n.full===!0);return{content:[{type:"text",text:es(v,r,o,{full:i})}]}}}}De();X();function ts(t,e,n){let r=t.resolve(e);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`:n==="completed"?(r.complete(),`Session ${r.name} [${r.id}] marked as completed.`):(t.kill(r.id),`Session ${r.name} [${r.id}] has been terminated.`):`Error: Session "${e}" not found.`}function Jw(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 Xf(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:c.Object({session:c.String({description:"Session name or ID to terminate"}),reason:c.Optional(c.Union([c.Literal("completed"),c.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(e,n){return v?Jw(n)?{content:[{type:"text",text:ts(v,n.session,n.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}De();X();function Yw(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ns(t){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:c.Object({session:c.String({description:"Session name or ID to get output from"}),lines:c.Optional(c.Number({description:"Number of recent lines to show (default 50)"})),full:c.Optional(c.Boolean({description:"Show all available output"}))}),async execute(e,n){return v?Yw(n)?{content:[{type:"text",text:Zi(v,n.session,{full:n.full,lines:n.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}De();X();Me();Pe();var Xw=10;function ul(t){return t instanceof Error?t.message:String(t)}function Ln(t){return re(t)??t.harnessSessionId??"unknown-session"}function Zf(t){return t.status!=="running"&&!!t.pendingPlanApproval&&!!E(t)}function co(t,e,n){let r=e==="completed"?`This session is closed by default. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Ln(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='${Ln(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='${Ln(t)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${Ln(t)}', message='<next instruction>') to continue the running session.`,o=n?` ${n}`:"";return{text:`Resume unavailable for session ${t.name} [${Ln(t)}] (${e}).${o} ${r}`,isError:!0}}async function eg(t,e,n){try{let r={prompt:e.prompt,sessionIdOverride:Qd(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(r,{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(r){return{text:`Error relaunching session ${e.name} [${Ln(e)}]: ${ul(r)}`,isError:!0}}}var Zw=`[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
78
 
77
- `;function If(t){let e=t?.replace(/\s+/g," ").trim();if(e)return Fe(e,240)}function Vd(t){if(t.approvalState==="changes_requested"&&!qi(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 qi(t){return t.pendingPlanApproval?(t.approvalState==="changes_requested"?t.actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion)>0:!1}function ow(t){return Vd(t)?!1:qi(t)||t.currentPermissionMode==="plan"}async function iw(t,e,r,n={}){let o=Jn(e);if(!(o.kind==="resume"||Pf(e)))return;let s=!!(n.approve&&ow(e)),a=s?If(n.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?wf(t,e,r):ro(e,o.reason);let d={prompt:s?nw+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 ro(e,"missing_backend_state",`Backend resume failed: ${qd(d)}`)}}async function xt(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"}:Jn(o);if(e.approve){let a=Vd(o);if(a)return{text:a,isError:!0}}if(i.kind==="resume"||Pf(o)){let a=await iw(t,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(a)return a}else{if(i.kind==="relaunch")return wf(t,o,e.message);if(i.kind==="unavailable")return ro(o,i.reason)}if(!r)return Qn(n)?ro(n,"completed"):{text:`Error: Session ${n.name} [${_r(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return Qn(r)?ro(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??rw;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=Vd(r);if(f)return{text:f,isError:!0}}if(!e.approve&&r.pendingInputState?.allowsFreeText&&await r.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let k=Fe(e.message,100);t.notifySession(r,`\u21AA\uFE0F [${r.name}] "${k}"`,"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&&qi(r)),m=l?If(e.approvalRationale):void 0,g="";if(e.approve&&qi(r)?(r.switchPermissionMode("bypassPermissions"),r.approvalRationale=m):e.approve&&r.currentPermissionMode==="default"?r.switchPermissionMode("bypassPermissions"):e.approve&&r.currentPermissionMode==="bypassPermissions"?g=`
79
- \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:e.approve?g=`
80
- \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:(r.pendingPlanApproval||r.approvalState==="changes_requested")&&(g=`
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}"`,g,"Use agent_output to see the response."].filter(Boolean).join(`
82
- `)}}catch(a){return{text:`Error sending message to session ${r.name} [${r.id}]: ${qd(a)}`,isError:!0}}}function sw(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 xf(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(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!sw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve?, approval_rationale? }."}]};let n=await xt(v,{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 aw(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function bf(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(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!aw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, summary }."}]};let n=v.requestPlanApprovalFromUser(r.session,r.summary);return{isError:n.startsWith("Error:"),content:[{type:"text",text:n}]}}}}Ee();Y();Re();function dw(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 lw(t,e){let r=Et(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 Af(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(!v)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 { report_id, report_text, plan_prompt, plan_workdir }."}]};let n=lw(t,r);return!n?.provider||!n.target?{content:[{type:"text",text:"Error: Could not resolve a direct delivery route for the monitor report."}]}:(v.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 Rf(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(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=v.getMetrics(),o=v.list("running").length;return{content:[{type:"text",text:Li(n,o)}]}}}}Ee();Re();Y();ut();no();import{existsSync as jd}from"fs";function pw(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Qi(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(!v)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 { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=dn(v,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.`}]};jd(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${a})`);let l=a;if(!jd(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let m=r.base_branch??ar(l),g=m,y=r.strategy??"merge",f=r.push===!0,k=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)"}]},b=n.persistedRef;return await v.enqueueMerge(l,async()=>{let w=v.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=Mr(l,d,m),I=Ei(l,d,g,y,s);if(I.success){if(f&&!$i(l,g)){A={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${g} locally, but failed to push ${g}`}]};return}k&&Ot(l,d);let R=!1;if(jd(s)&&(R=tt(l,s),_i(l)),w)for(let N of Tf({...n,persistedSession:w}))v.updatePersistedSession(N,{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 O=Cr({kind:"merge",branch:d,base:m,filesChanged:C?.filesChanged,insertions:C?.insertions,deletions:C?.deletions});v.notifyWorktreeOutcome(n.notificationTarget,O);let D=`\u2705 ${I.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${g}.${f?" Pushed.":""}${k?R?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;I.stashPopConflict?D+=`
83
- \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${I.stashRef??"stash@{0}"}\` in ${l} to review stashed changes.`:I.stashed&&(D+=`
84
- (Pre-existing changes on ${g} were auto-stashed and restored.)`),A={content:[{type:"text",text:D}]}}else if(I.rebaseConflict)A={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
79
+ `;function tg(t){let e=t?.replace(/\s+/g," ").trim();if(e)return Ce(e,240)}function ll(t){if(t.approvalState==="changes_requested"&&!rs(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 rs(t){return t.pendingPlanApproval?(t.approvalState==="changes_requested"?t.actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion)>0:!1}function eI(t){return ll(t)?!1:rs(t)||t.currentPermissionMode==="plan"}function tI(t,e){let n=t.updatePersistedSession;if(typeof n!="function")return;let r=e.controlStateSnapshot();n.call(t,e.id,{lifecycle:r.lifecycle,approvalState:r.approvalState,approvalExecutionState:r.approvalExecutionState,runtimeState:r.runtimeState,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,pendingPlanApproval:r.pendingPlanApproval,planApprovalContext:r.planApprovalContext,planDecisionVersion:r.planDecisionVersion,actionablePlanDecisionVersion:r.actionablePlanDecisionVersion,planModeApproved:r.planModeApproved,approvalRationale:e.approvalRationale})}async function nI(t,e,n,r={}){let o=ro(e);if(!(o.kind==="resume"||Zf(e)))return;let s=!!(r.approve&&eI(e)),a=s?tg(r.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?eg(t,e,n):co(e,o.reason);let d={prompt:s?Zw+n:n,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 co(e,"missing_backend_state",`Backend resume failed: ${ul(d)}`)}}async function Mt(t,e){let n=t.resolve(e.session),r=n?void 0:t.getPersistedSession(e.session);if(!n&&!r)return{text:`Error: Session "${e.session}" not found.`,isError:!0};let o=n??r,i=o.status==="running"?{kind:"direct"}:ro(o);if(e.approve){let a=ll(o);if(a)return{text:a,isError:!0}}if(i.kind==="resume"||Zf(o)){let a=await nI(t,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(a)return a}else{if(i.kind==="relaunch")return eg(t,o,e.message);if(i.kind==="unavailable")return co(o,i.reason)}if(!n)return no(r)?co(r,"completed"):{text:`Error: Session ${r.name} [${Ln(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return no(n)?co(n,"completed"):{text:`Error: Session ${n.name} [${n.id}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};let s=_.maxAutoResponds??Xw;if(e.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=s)return{text:`\u26A0\uFE0F Auto-respond limit reached (${n.autoRespondCount}/${s}). Ask the user to provide the answer for session ${n.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{if(e.approve){let g=ll(n);if(g)return{text:g,isError:!0}}if(!e.approve&&n.pendingInputState?.allowsFreeText&&await n.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let k=Ce(e.message,100);t.notifySession(n,`\u21AA\uFE0F [${n.name}] "${k}"`,"agent-respond")}e.userInitiated||n.incrementAutoRespond();let g=Ce(e.message,80);return{text:[`Pending input answered for session ${n.name} [${n.id}].`,` Message: "${g}"`,"Use agent_output to see the response."].join(`
80
+ `)}}let d=!1;e.interrupt&&(d=await n.interrupt());let l=!!(e.approve&&rs(n)),p=l?tg(e.approvalRationale):void 0,f="";if(e.approve&&rs(n)?(n.switchPermissionMode("bypassPermissions"),n.approvalRationale=p):e.approve&&n.currentPermissionMode==="default"?n.switchPermissionMode("bypassPermissions"):e.approve&&n.currentPermissionMode==="bypassPermissions"?f=`
81
+ \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:e.approve?f=`
82
+ \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:(n.pendingPlanApproval||n.approvalState==="changes_requested")&&(f=`
83
+ \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`),await n.sendMessage(e.message),l&&tI(t,n),l)t.notifySession(n,`\u{1F44D} [${n.name}] Plan approved`,"plan-approved");else if(e.userInitiated){let g=Ce(e.message,100);t.notifySession(n,`\u21AA\uFE0F [${n.name}] "${g}"`,"agent-respond")}e.userInitiated||n.incrementAutoRespond();let y=Ce(e.message,80);return l?{text:`Plan approved for session ${n.name} [${n.id}]. Use agent_output to see the response.`}:{text:[`Message sent to session ${n.name} [${n.id}].`,d?" (redirected active turn first)":e.interrupt?" (no active turn to interrupt)":"",` Message: "${y}"`,f,"Use agent_output to see the response."].filter(Boolean).join(`
84
+ `)}}catch(a){return{text:`Error sending message to session ${n.name} [${n.id}]: ${ul(a)}`,isError:!0}}}function rI(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 ng(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:c.Object({session:c.String({description:"Session name or ID to respond to"}),message:c.String({description:"The message to send to the session"}),interrupt:c.Optional(c.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:c.Optional(c.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:c.Optional(c.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:c.Optional(c.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,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!rI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve?, approval_rationale? }."}]};let r=await Mt(v,{session:n.session,message:n.message,interrupt:n.interrupt,userInitiated:n.userInitiated,approve:n.approve,approvalRationale:n.approval_rationale});return{isError:r.isError??!1,content:[{type:"text",text:r.text}]}}}}De();X();function oI(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function rg(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:c.Object({session:c.String({description:"Session name or ID awaiting plan approval"}),summary:c.String({description:"Concise user-facing summary of scope, risk, and any concerns that should accompany the approval buttons"})}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!oI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, summary }."}]};let r=v.requestPlanApprovalFromUser(n.session,n.summary);return{isError:r.startsWith("Error:"),content:[{type:"text",text:r}]}}}}De();X();Me();var pl=["off","manual","ask","delegate","auto-merge","auto-pr"],os=new Set(pl),iI=["low","medium","high","xhigh","max"],og=new Set(iI);function sI(t){return typeof t=="string"&&os.has(t)}var aI=c.Union(pl.map(t=>c.Literal(t)),{description:"Optional worktree strategy for the planning session. Use auto-pr for monitor follow-up that should branch and open/update a PR after approved implementation."});function dI(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_worktree_strategy==null||sI(e.plan_worktree_strategy))&&(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 lI(t,e){let n=Ft(t,e.target_channel,e.target_session_key);if(n)return e.target_thread_id!=null&&(n.threadId=String(e.target_thread_id)),n}function ig(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:c.Object({report_id:c.String({description:"Stable report identifier, for example 'openclaw-release-v2026.3.31'."}),report_text:c.String({description:"Final user-facing report text to deliver."}),plan_prompt:c.String({description:"Prompt to seed into the plan-only session when the user clicks Start Plan."}),plan_workdir:c.String({description:"Working directory for the planning session."}),plan_worktree_strategy:c.Optional(aI),plan_name:c.Optional(c.String({description:"Optional explicit session name for the planning session."})),target_channel:c.Optional(c.String({description:"Optional explicit route like 'telegram|-1003863755361'."})),target_thread_id:c.Optional(c.Union([c.String(),c.Number()],{description:"Optional explicit topic/thread id."})),target_session_key:c.Optional(c.String({description:"Optional explicit session key for wake routing."}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!dI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { report_id, report_text, plan_prompt, plan_workdir }."}]};let r=lI(t,n);return!r?.provider||!r.target?{content:[{type:"text",text:"Error: Could not resolve a direct delivery route for the monitor report."}]}:(v.sendMonitorReport({reportId:n.report_id,route:r,text:n.report_text,planName:n.plan_name??n.report_id,planPrompt:n.plan_prompt,planWorkdir:n.plan_workdir,planWorktreeStrategy:n.plan_worktree_strategy}),{content:[{type:"text",text:`Interactive monitor report queued for ${r.provider}|${r.target}${r.threadId?`#${r.threadId}`:""}.`}]})}}}De();X();function sg(t){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:c.Object({}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=v.getMetrics(),o=v.list("running").length;return{content:[{type:"text",text:Mi(r,o)}]}}}}De();Me();X();mt();mo();import{existsSync as cl}from"fs";function pI(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ls(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:c.Object({session:c.String({description:"Session name or ID to merge"}),base_branch:c.Optional(c.String({description:"Base branch to merge into (default: main)"})),strategy:c.Optional(c.Union([c.Literal("merge"),c.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:c.Optional(c.Boolean({description:"Push the base branch after successful merge (default: false)"})),delete_branch:c.Optional(c.Boolean({description:"Delete the worktree branch after successful merge (default: true)"}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!pI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let r=gr(v,n.session),o=r.activeSession,i=r.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${n.session}" not found.`}]};let{worktreePath:s,originalWorkdir:a,branchName:d}=r;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${n.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.`}]};cl(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${a})`);let l=a;if(!cl(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let p=n.base_branch??cn(l),f=p,y=n.strategy??"merge",g=n.push===!0,k=n.delete_branch!==!1;if(i?.worktreeLifecycle?.state==="merged"||i?.worktreeMerged)return{content:[{type:"text",text:`\u2139\uFE0F Session "${n.session}" is already merged.`}]};let A={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]},x=r.persistedRef;return await v.enqueueMerge(l,async()=>{let w=v.getPersistedSession(n.session);if(w?.worktreeLifecycle?.state==="merged"||w?.worktreeMerged){A={content:[{type:"text",text:`\u2139\uFE0F Session "${n.session}" was already merged while waiting in queue.`}]};return}let C=Dn(l,d,p),I=zi(l,d,f,y,s);if(I.success){if(g&&!Hi(l,f)){A={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${f} locally, but failed to push ${f}`}]};return}k&&Lt(l,d);let R=!1;if(cl(s)&&(R=rt(l,s),Gi(l)),w)for(let D of ag({...r,persistedSession:w}))v.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:p,targetRepo:w.worktreePrTargetRepo,pushRemote:w.worktreePushRemote}});let O=Fn({kind:"merge",branch:d,base:p,filesChanged:C?.filesChanged,insertions:C?.insertions,deletions:C?.deletions});v.notifyWorktreeOutcome(r.notificationTarget,O);let N=`\u2705 ${I.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${f}.${g?" Pushed.":""}${k?R?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;I.stashPopConflict?N+=`
85
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${I.stashRef??"stash@{0}"}\` in ${l} to review stashed changes.`:I.stashed&&(N+=`
86
+ (Pre-existing changes on ${f} were auto-stashed and restored.)`),A={content:[{type:"text",text:N}]}}else if(I.rebaseConflict)A={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
85
87
 
86
88
  ${I.error}`}]};else if(I.conflictFiles&&I.conflictFiles.length>0){let R=["Resolve merge conflicts in the following files and commit the resolution:","",...I.conflictFiles.map(O=>`- ${O}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${d}"`].join(`
87
- `);try{let O=v.spawn({prompt:R,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 ${I.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${O.name}`}]}}catch(O){A={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${O instanceof Error?O.message:String(O)}`}]}}}else A={content:[{type:"text",text:I.dirtyError?`\u274C Merge blocked: ${I.error}`:`\u274C Merge failed: ${I.error??"unknown error"}`}]}}),A}}}Ji();Ee();Y();ke();ut();no();function fw(t){return!!t&&typeof t=="object"}function Cf(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(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!fw(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 v.dismissWorktree(n)}]};let a=Gi(v);if(n&&(a=a.filter(f=>Hi(f,n)),a.length===0)){let f=dn(v,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=[],g=[];for(let f of a){let{persistedSession:k,activeSession:A,resolvedLifecycle:b}=ji(v,f,{baseBranch:r.base_branch});if(!b.cleanupSafe){if(s){let w=b.reasons.length>0?b.reasons.map(zi).join(", "):$r(b.derivedState);l.push(`${f.name} [kept: ${w}]`)}continue}if(d.push(`${f.name} (${$r(b.derivedState)})`),!i)try{let w=f.workdir;if(!((k??A)&&Ne(k??A))&&f.worktreePath&&tt(w,f.worktreePath,{destructive:!1}),f.worktreeBranch&&Ot(w,f.worktreeBranch),k){let I=b.derivedState==="merged"||b.derivedState==="released"?b.derivedState:b.lifecycle.state;v.updatePersistedSession(f.id,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeMerged:I==="merged"?!0:k.worktreeMerged,worktreeMergedAt:I==="merged"?k.worktreeMergedAt??new Date().toISOString():k.worktreeMergedAt,worktreeLifecycle:{...k.worktreeLifecycle??b.lifecycle,state:I,updatedAt:new Date().toISOString(),resolvedAt:k.worktreeLifecycle?.resolvedAt??new Date().toISOString(),resolutionSource:k.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:r.base_branch??b.lifecycle.baseBranch??k.worktreeBaseBranch,targetRepo:k.worktreePrTargetRepo,pushRemote:k.worktreePushRemote,notes:b.reasons}})}m.push(`${f.name} (${$r(b.derivedState)})`)}catch(w){g.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 (${g.length}): ${g.join(", ")||"(none)"}`)),{content:[{type:"text",text:y.join(`
88
- `)}]}}}}Ee();Y();no();function gw(t){return!0}function _f(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(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!gw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let n=r.session,o=Gi(v);if(n&&(o=o.filter(s=>Hi(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}=ji(v,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(zi).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
89
- `).trim()}]}}}}Ee();Y();Re();import{existsSync as hw}from"fs";function Yi(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 Sw(t){return!t||typeof t!="object"?!1:typeof t.goal=="string"}function $f(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(!Sw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let n=r.workdir||t.workspaceDir||_.defaultWorkdir||process.cwd();if(!hw(n))return{content:[{type:"text",text:`Error: Working directory does not exist: ${n}`}]};let o=(r.verifier_commands??[]).map((f,k)=>({label:`check-${k+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??$t(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(!Yi(a,d))return{content:[{type:"text",text:`Error: Model "${a}" is not allowed. Permitted models: ${d?.join(", ")}`}]};let l=t.sessionKey||void 0,m=ai(t),g=jt(t,m),y=Et(t,g,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:g,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 Ef(t,e){return t.split(`
91
- `).map(r=>`${e}${r}`)}function yw(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 dr(t){if(t)return{phase:t.phase,awaitingInput:t.isAwaitingInput??!!t.pendingInputState,latestOutput:yw(t.getOutput(20))}}function lr(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(...Ef(t.lastVerifierSummary," "))),e?.latestOutput&&(n.push(" Latest activity:"),n.push(...Ef(e.latestOutput," "))),t.waitingForUserReason&&n.push(` Waiting on user: ${t.waitingForUserReason}`),t.failureReason&&n.push(` Failure: ${t.failureReason}`),n.join(`
93
- `)}Y();function Of(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?v?.resolve(i.sessionId):void 0;return{content:[{type:"text",text:lr(i,dr(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?v?.resolve(i.sessionId):void 0;return lr(i,dr(s))}).join(`
94
-
95
- `)}]}}}}Ee();Y();function kw(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function Df(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(!kw(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();Ji();var ln="code-agent";function vw(t){let e=t.trim().replace(new RegExp(`^${ln}:`),"");return e||null}async function Xi(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 Gd(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 Pw(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function ww(t,e){if(Pw(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 Iw(t){let e="callback"in t?t.callback?.payload:void 0,r="interaction"in t?t.interaction?.payload:void 0;return e??r??""}function Hd(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function xw(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(Hd(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(Hd(o))return;if(xw(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(!Hd(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 zd(t="telegram"){return{channel:t,namespace:ln,handler:async e=>{if(!e.auth.isAuthorizedSender)return await oe(e,"\u26D4 Unauthorized."),{handled:!0};let r=Iw(e),n=vw(r);if(!n)return await oe(e,`\u26A0\uFE0F Unrecognized callback payload: "${r}".`),{handled:!0};if(!v)return await oe(e,"\u26A0\uFE0F Code agent service not running."),{handled:!0};let o=v.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=v.resolve?.(i)??v.getPersistedSession?.(i),a=s?.name??i,d=ww(o,s);if(d)return await pt(e),await oe(e,`\u26A0\uFE0F ${d}`),{handled:!0};let l=v.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 Xi(e,`\u2705 Merge selected for [${a}]`);let m=await Qi().execute("callback",{session:i});await oe(e,Gd(m));break}case"worktree-decide-later":{await Xi(e,`\u23ED\uFE0F Deferred for [${a}]`);let m=v.snoozeWorktreeDecision(i);await oe(e,m.startsWith("Error")?m:"\u23ED\uFE0F Snoozed 24h");break}case"worktree-dismiss":{await Xi(e,`\u{1F5D1}\uFE0F Discarded for [${a}]`);let m=await v.dismissWorktree(i);await oe(e,(m.startsWith("Error"),m));break}case"worktree-create-pr":case"worktree-update-pr":{await Xi(e,o.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${a}]`:`\u{1F4EC} PR selected for [${a}]`);let m=await oo().execute("callback",{session:i});await oe(e,Gd(m));break}case"worktree-view-pr":{await pt(e);let m=v.getPersistedSession?.(i),g=o.targetUrl??m?.worktreePrUrl;await oe(e,g?`PR: ${g}`:"\u26A0\uFE0F PR URL is no longer available.");break}case"plan-approve":{await pt(e),v.clearPlanDecisionTokens(i);let m=await xt(v,{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),v.clearPlanDecisionTokens(i);let m=v.resolve(i);if(m)m.approvalState="rejected",v.kill(m.id,"user"),await oe(e,`\u274C Plan rejected for [${m.name}]. Session stopped.`);else{let g=v.getPersistedSession?.(i);g?(v.updatePersistedSession?.(i,{approvalState:"rejected",lifecycle:"terminal",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:(g.planDecisionVersion??0)+1}),await oe(e,`\u274C Plan rejected for [${g.name??a}]. Session remains stopped.`)):await oe(e,"\u274C Plan rejected.")}break}case"plan-request-changes":{await pt(e);let m=v.resolve?.(i),g=v.getPersistedSession?.(i),y=m?.name??g?.name??i,f=(m?.planDecisionVersion??g?.planDecisionVersion??0)+1;v.clearPlanDecisionTokens(i),v.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=v.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 xt(v,{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 Vi().execute("callback",{session:i,lines:50});await oe(e,Gd(m));break}case"question-answer":{if(await pt(e),o.optionIndex==null){await oe(e,"\u26A0\uFE0F Invalid question-answer action.");break}await v.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 bw(t){return t instanceof Error?t.message:String(t)}function Nf(t){t.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!v)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=$t(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=v.spawn({prompt:i,name:n,workdir:_.defaultWorkdir||process.cwd(),model:a,reasoningEffort:lt(s),codexApprovalPolicy:s==="codex"?"never":void 0,originChannel:jt(e),originThreadId:Kn(e),route:Et(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=bw(s),d=a.includes("Max sessions")?"":`
97
-
98
- Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${d}`}}}})}Y();function Ff(t){t.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").split(/\s+/).includes("--full");return{text:Ui(v,"all",void 0,{full:r})}}})}Y();function Lf(t){t.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=e.args?.trim();return r?{text:Ki(v,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}Y();function Wf(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(!v)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 xt(v,{session:s,message:a,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}Y();function Bf(t){t.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let e=v.getMetrics(),r=v.list("running").length;return{text:Li(e,r)}}})}Y();var Aw=50;function Uf(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(!v)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=Aw;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:Bi(v,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}Y();Re();import{existsSync as Rw}from"fs";function Tw(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 Kf(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=Tw(r),o,i=_.defaultWorkdir||process.cwd(),s,a,d="bypassPermissions",l,m,g,y=[],f=[];for(let I=0;I<n.length;I++){let R=n[I];if(R==="--name"&&I+1<n.length)o=n[++I];else if(R==="--workdir"&&I+1<n.length)i=n[++I];else if(R==="--model"&&I+1<n.length)s=n[++I];else if(R==="--max-iterations"&&I+1<n.length){let O=parseInt(n[++I],10);!Number.isNaN(O)&&O>0&&(a=O)}else if(R==="--permission-mode"&&I+1<n.length){let O=n[++I];if(O==="default"||O==="plan"||O==="bypassPermissions")d=O;else return{text:`Error: Invalid permission mode "${O}".`}}else if(R==="--harness"&&I+1<n.length)l=n[++I];else if(R==="--mode"&&I+1<n.length){let O=n[++I];if(O==="ralph"||O==="verifier")m=O;else return{text:`Error: Invalid goal mode "${O}". Use ralph or verifier.`}}else if(R==="--completion-promise"&&I+1<n.length)g=n[++I];else if(R==="--verify"&&I+1<n.length){let O=n[++I].trim();if(!O)return{text:"Error: --verify commands must not be empty."};y.push(O)}else f.push(R)}let k=f.join(" ").trim();if(!k)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(!Rw(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 b=l??Pe(),w=s??$t(b);if(!w)return{text:`Error: No default model configured for harness "${b}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${b}.defaultModel or pass model explicitly.`};let C=en(b);if(!Yi(w,C))return{text:`Error: Model "${w}" is not allowed. Permitted models: ${C?.join(", ")}`};try{let I=Et(e),R=await fe.launchTask({goal:k,name:o,workdir:i,model:w,reasoningEffort:lt(b),maxIterations:a,permissionMode:d,harness:b,loopMode:A,completionPromise:g,originChannel:jt(e),originThreadId:I?.threadId,originSessionKey:e.sessionKey,route:I,verifierCommands:y.map((O,Le)=>({label:`check-${Le+1}`,command:O}))});return{text:["Goal task launched.",` Name: ${R.name}`,` ID: ${R.id}`,` Session: ${R.sessionName} [${R.sessionId}]`,` Harness: ${b}`,` Loop mode: ${R.loopMode}`,...R.loopMode==="ralph"?[` Completion promise: ${R.completionPromise}`]:[],` Max iterations: ${R.maxIterations}`,` Goal: "${k.length>100?`${k.slice(0,100)}...`:k}"`].join(`
100
- `)}}catch(I){return{text:`Error launching goal task: ${I.message}`}}}})}Y();function Vf(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?v?.resolve(o.sessionId):void 0;return{text:lr(o,dr(i))}}let n=fe.listTasks();return n.length===0?{text:"No goal tasks found."}:{text:n.map(o=>{let i=o.sessionId?v?.resolve(o.sessionId):void 0;return lr(o,dr(i))}).join(`
101
-
102
- `)}}})}Y();function qf(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 Uw}from"child_process";import{createHash as Zf}from"crypto";import{existsSync as Mw,mkdirSync as Cw,readFileSync as _w,renameSync as $w,writeFileSync as Ew}from"fs";import{homedir as Ow}from"os";import{dirname as Dw,join as jf}from"path";function Nw(t){let e=t.OPENCLAW_HOME?.trim();return e||jf(Ow(),".openclaw")}function Fw(t){let e=t.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||jf(Nw(t),"code-agent-goal-tasks.json")}function Lw(t){return t instanceof Error?t.message:String(t)}function Ww(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 Bw(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:Ww(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 Zi=class{path;tasks=new Map;constructor(e=process.env){this.path=Fw(e),this.load()}load(){try{if(!Mw(this.path))return;let e=_w(this.path,"utf8"),r=JSON.parse(e);if(!Array.isArray(r))return;for(let n of r){let o=Bw(n);o&&this.tasks.set(o.id,o)}this.save()}catch{}}save(){try{Cw(Dw(this.path),{recursive:!0});let e=`${this.path}.tmp`;Ew(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),$w(e,this.path)}catch(e){console.warn(`[GoalTaskStore] Failed to save ${this.path}: ${Lw(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)}};br();var Kw=8,eg=600*1e3,Vw=4e3,Qd=1200,qw="DONE",jw=["BASH_ENV","ENV"];function Gw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function io(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 Gf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hf(t){let e=t?.trim();return e&&e.length>0?e:qw}function Hw(t){return t.route??Bn(t.originChannel,t.originThreadId,t.originSessionKey)}function Jd(t){return t.map((e,r)=>({label:e.label.trim()||`check-${r+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??eg})).filter(e=>e.command.length>0)}function zw(t){return t.loopMode==="verifier"}function Qw(t){return Jd(t.verifierCommands).length>0}function zf(t){return zw(t)&&!Qw(t)}function es(){return"Verifier-mode goal tasks require at least one verifier command."}function Qf(t){let e=t.steps.filter(r=>!r.ok).map(r=>`${r.label}:${r.exitCode}:${ur(r.output,12)}`).join(`
105
- `);return Zf("sha1").update(e).digest("hex")}function Jw(t){return Zf("sha1").update(ur(t,24)).digest("hex")}function Jf(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 Yw(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(`
89
+ `);try{let O=v.spawn({prompt:R,workdir:l,name:`${n.session}-conflict-resolver`,harness:Ie(),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 ${I.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${O.name}`}]}}catch(O){A={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${O instanceof Error?O.message:String(O)}`}]}}}else A={content:[{type:"text",text:I.dirtyError?`\u274C Merge blocked: ${I.error}`:`\u274C Merge failed: ${I.error??"unknown error"}`}]}}),A}}}us();De();X();Pe();mt();mo();function fI(t){return!!t&&typeof t=="object"}function lg(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:c.Object({workdir:c.Optional(c.String({description:"Restrict cleanup to sessions rooted in this repository"})),base_branch:c.Optional(c.String({description:"Override base branch for lifecycle resolution"})),mode:c.Optional(c.Union([c.Literal("preview_safe"),c.Literal("clean_safe"),c.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:c.Optional(c.Boolean({description:"Deprecated. Safe cleanup never removes live sessions."})),force:c.Optional(c.Boolean({description:"Deprecated alias for skip_session_check."})),dry_run:c.Optional(c.Boolean({description:"Show what would be cleaned without deleting anything."})),session:c.Optional(c.String({description:"Session name or ID to clean or dismiss."})),dismiss_session:c.Optional(c.Boolean({description:"When true and session is provided, permanently dismiss the worktree."}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!fI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, mode?, dry_run?, session?, dismiss_session? }."}]};let r=n.session,o=n.mode??(n.dry_run===!0?"preview_safe":"clean_safe"),i=o!=="clean_safe",s=o==="preview_all"||o==="clean_safe";if(r&&n.dismiss_session===!0)return{content:[{type:"text",text:await v.dismissWorktree(r)}]};let a=ss(v);if(r&&(a=a.filter(g=>as(g,r)),a.length===0)){let g=gr(v,r);if(!g.persistedSession&&!g.activeSession)return{content:[{type:"text",text:`Error: Session "${r}" not found.`}]}}if(n.workdir&&(a=a.filter(g=>g.workdir===n.workdir)),a.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let d=[],l=[],p=[],f=[];for(let g of a){let{persistedSession:k,activeSession:A,resolvedLifecycle:x}=is(v,g,{baseBranch:n.base_branch});if(!x.cleanupSafe){if(s){let w=x.reasons.length>0?x.reasons.map(ds).join(", "):Wn(x.derivedState);l.push(`${g.name} [kept: ${w}]`)}continue}if(d.push(`${g.name} (${Wn(x.derivedState)})`),!i)try{let w=g.workdir;if(!((k??A)&&We(k??A))&&g.worktreePath&&rt(w,g.worktreePath,{destructive:!1}),g.worktreeBranch&&Lt(w,g.worktreeBranch),k){let I=x.derivedState==="merged"||x.derivedState==="released"?x.derivedState:x.lifecycle.state;v.updatePersistedSession(g.id,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeMerged:I==="merged"?!0:k.worktreeMerged,worktreeMergedAt:I==="merged"?k.worktreeMergedAt??new Date().toISOString():k.worktreeMergedAt,worktreeLifecycle:{...k.worktreeLifecycle??x.lifecycle,state:I,updatedAt:new Date().toISOString(),resolvedAt:k.worktreeLifecycle?.resolvedAt??new Date().toISOString(),resolutionSource:k.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:n.base_branch??x.lifecycle.baseBranch??k.worktreeBaseBranch,targetRepo:k.worktreePrTargetRepo,pushRemote:k.worktreePushRemote,notes:x.reasons}})}p.push(`${g.name} (${Wn(x.derivedState)})`)}catch(w){f.push(`${g.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 (${p.length}): ${p.join(", ")||"(none)"}`),y.push(` FAILURES (${f.length}): ${f.join(", ")||"(none)"}`)),{content:[{type:"text",text:y.join(`
90
+ `)}]}}}}De();X();mo();function gI(t){return!0}function ug(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:c.Object({session:c.Optional(c.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(e,n){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!gI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let r=n.session,o=ss(v);if(r&&(o=o.filter(s=>as(s,r)),o.length===0))return{content:[{type:"text",text:`Error: Session "${r}" 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}=is(v,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:${Wn(d.lifecycle.state)}`),d.derivedState!==d.lifecycle.state&&i.push(` Derived: ${Wn(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(ds).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
91
+ `).trim()}]}}}}De();X();Me();import{existsSync as hI}from"fs";function ps(t,e){if(!e||e.length===0)return!0;if(!t)return!1;let n=t.toLowerCase();return e.some(r=>n.includes(r.toLowerCase()))}function SI(t){return!t||typeof t!="object"?!1:typeof t.goal=="string"}function pg(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:c.Object({goal:c.String({description:"End goal for the autonomous task"}),verifier_commands:c.Optional(c.Array(c.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:c.Optional(c.String({description:"Short task name (kebab-case preferred)"})),workdir:c.Optional(c.String({description:"Working directory (defaults to cwd / configured workspace)"})),model:c.Optional(c.String({description:"Model name to use"})),system_prompt:c.Optional(c.String({description:"Additional system prompt"})),allowed_tools:c.Optional(c.Array(c.String(),{description:"Allowed tools for the underlying agent session"})),max_iterations:c.Optional(c.Number({description:"Maximum verifier-driven repair iterations",minimum:1})),goal_mode:c.Optional(c.Union([c.Literal("ralph"),c.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:c.Optional(c.String({description:"Exact completion promise for Ralph-mode loops. Defaults to 'DONE'."})),permission_mode:c.Optional(c.Union([c.Literal("default"),c.Literal("plan"),c.Literal("bypassPermissions")],{description:"Permission mode for the underlying agent session. Defaults to bypassPermissions for autonomous goal loops."})),harness:c.Optional(c.String({description:"Agent harness to use (e.g. 'codex' or 'claude-code')."}))}),async execute(e,n){if(!he)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!SI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let r=n.workdir||t.workspaceDir||_.defaultWorkdir||process.cwd();if(!hI(r))return{content:[{type:"text",text:`Error: Working directory does not exist: ${r}`}]};let o=(n.verifier_commands??[]).map((g,k)=>({label:`check-${k+1}`,command:g.trim()})).filter(g=>g.command.length>0),i=n.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=n.harness??Ie(),a=n.model??Dt(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=ar(s);if(!ps(a,d))return{content:[{type:"text",text:`Error: Model "${a}" is not allowed. Permitted models: ${d?.join(", ")}`}]};let l=t.sessionKey||void 0,p=hi(t),f=Qt(t,p),y=Ft(t,f,l);try{let g=await he.launchTask({goal:n.goal,name:n.name,workdir:r,model:a,reasoningEffort:ct(s),systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,maxIterations:n.max_iterations,permissionMode:n.permission_mode??"bypassPermissions",loopMode:i,completionPromise:n.completion_promise,originChannel:f,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: ${g.name}`,` ID: ${g.id}`,` Dir: ${g.workdir}`,` Session: ${g.sessionName} [${g.sessionId}]`,` Harness: ${s}`,` Model: ${a}`,` Loop mode: ${g.loopMode}`,` Max iterations: ${g.maxIterations}`,` Goal: "${n.goal.length>100?`${n.goal.slice(0,100)}...`:n.goal}"`,...g.loopMode==="ralph"?[` Completion promise: ${g.completionPromise}`]:[" Verifiers:",...o.map(A=>` - ${A.command}`)],"","Use goal_status to follow progress or goal_stop to terminate the task."].join(`
92
+ `)}]}}catch(g){return{content:[{type:"text",text:`Error launching goal task: ${g instanceof Error?g.message:String(g)}`}]}}}}}De();function cg(t,e){return t.split(`
93
+ `).map(n=>`${e}${n}`)}function yI(t,e=8,n=600){let r=t.map(i=>i.trimEnd()).filter(i=>i.trim().length>0);if(r.length===0)return;let o=r.slice(-e).join(`
94
+ `);return o.length<=n?o:`...${o.slice(-(n-3))}`}function mn(t){if(t)return{phase:t.phase,awaitingInput:t.isAwaitingInput??!!t.pendingInputState,latestOutput:yI(t.getOutput(20))}}function fn(t,e){let n=t.loopMode??"verifier",r=[`${t.name} [${t.id}]`,` Status: ${t.status}`,...n==="ralph"?[" Loop mode: ralph",` Iteration: ${t.iteration}/${t.maxIterations}`]:[` Repair iteration: ${t.iteration}/${t.maxIterations}`],` Workdir: ${t.workdir}`];return n==="ralph"&&t.completionPromise&&r.push(` Completion promise: ${t.completionPromise}`),t.sessionId&&r.push(` Session: ${t.sessionName??"(unknown)"} [${t.sessionId}]`),e?.phase&&r.push(` Phase: ${e.phase}`),e?.awaitingInput!==void 0&&r.push(` Awaiting input: ${e.awaitingInput?"yes":"no"}`),t.lastVerifierSummary&&(r.push(" Last verifier:"),r.push(...cg(t.lastVerifierSummary," "))),e?.latestOutput&&(r.push(" Latest activity:"),r.push(...cg(e.latestOutput," "))),t.waitingForUserReason&&r.push(` Waiting on user: ${t.waitingForUserReason}`),t.failureReason&&r.push(` Failure: ${t.failureReason}`),r.join(`
95
+ `)}X();function mg(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:c.Object({task:c.Optional(c.String({description:"Task name or ID. Omit to list all tasks."}))}),async execute(e,n){if(!he)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};let r=n&&typeof n=="object"&&typeof n.task=="string"?n.task:void 0;if(r){let i=he.getTask(r);if(!i)return{content:[{type:"text",text:`Error: Goal task "${r}" not found.`}]};let s=i.sessionId?v?.resolve(i.sessionId):void 0;return{content:[{type:"text",text:fn(i,mn(s))}]}}let o=he.listTasks();return o.length===0?{content:[{type:"text",text:"No goal tasks found."}]}:{content:[{type:"text",text:o.map(i=>{let s=i.sessionId?v?.resolve(i.sessionId):void 0;return fn(i,mn(s))}).join(`
96
+
97
+ `)}]}}}}De();X();function kI(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function fg(t){return{name:"goal_stop",description:"Stop an explicit goal task and kill its underlying agent session.",parameters:c.Object({task:c.String({description:"Goal task name or ID"})}),async execute(e,n){if(!he)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!kI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let r=he.stopTask(n.task);return r?{content:[{type:"text",text:r.action==="already_terminal"?`Task is already ${r.task.status}.`:`Task "${r.task.name}" (${r.task.id}) stopped.`}]}:{content:[{type:"text",text:`Error: Goal task "${n.task}" not found.`}]}}}}X();us();import{createHash as vI}from"crypto";var ot="code-agent";var PI=new Set(["1","true","yes","on"]);function wI(){let t=process.env.OPENCLAW_CODE_AGENT_BUTTON_DIAGNOSTICS?.trim().toLowerCase();return!!(t&&PI.has(t))}function hr(t){if(!(typeof t!="string"||t.length===0))return vI("sha256").update(t).digest("hex").slice(0,12)}function gg(t){return typeof t.callbackData=="string"?t.callbackData:typeof t.value=="string"?t.value:void 0}function de(t){let e=(t??[]).filter(r=>Array.isArray(r)&&r.length>0),n=e.flat();return{buttonRows:e.length||void 0,buttonCount:n.length||void 0,buttonLabels:n.length>0?n.map(r=>typeof r.label=="string"?r.label:void 0):void 0,callbackByteLengths:n.length>0?n.map(r=>{let o=gg(r);return o?Buffer.byteLength(o,"utf8"):void 0}):void 0,callbackHashes:n.length>0?n.map(r=>hr(gg(r))):void 0,buttonStyles:n.length>0?n.map(r=>typeof r.style=="string"?r.style:void 0):void 0}}function gn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Sg(t){let e=gn(t),n=Array.isArray(e?.blocks)?e.blocks:void 0;if(n)return n.map(r=>gn(r)?.type).filter(r=>typeof r=="string"&&r.length>0)}function yg(t){let e=gn(t),n=Array.isArray(e?.blocks)?e.blocks:void 0;if(!n)return;let r=n.map(o=>{let i=gn(o);return i?.type!=="buttons"||!Array.isArray(i.buttons)?[]:i.buttons}).filter(o=>o.length>0);return r.length>0?r:void 0}function fl(t){let e=yg(t);return{presentationBlockTypes:Sg(t),...de(e)}}function gl(t){let e=gn(t),n=e?.interactive,r=gn(e?.channelData),o=gn(r?.telegram),i=Array.isArray(o?.buttons)?o.buttons:void 0;return{renderedPayloadKeys:e?Object.keys(e).sort():void 0,interactiveBlockTypes:Sg(n),...hg("interactive",de(yg(n))),...hg("telegramChannelData",de(i)),hasPresentation:!!e?.presentation,hasInteractive:!!n,hasTelegramChannelDataButtons:!!i?.some(s=>s.length>0)}}function kg(t){let e=gn(t);return e?{sendResultKeys:Object.keys(e).sort(),messageId:ml(e.messageId),chatId:ml(e.chatId),telegramThreadId:ml(e.messageThreadId??e.threadId),channel:typeof e.channel=="string"?e.channel:void 0}:{sendResultType:typeof t}}function ml(t){return typeof t=="string"||typeof t=="number"?t:void 0}function hg(t,e){let n={};for(let[r,o]of Object.entries(e))o!==void 0&&(n[`${t}${r.charAt(0).toUpperCase()}${r.slice(1)}`]=o);return n}function j(t,e){if(!wI())return;let n=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));console.info(`[CodeAgentButtonDiagnostics] ${JSON.stringify({event:t,callbackNamespace:ot,...n})}`)}function II(t){let e=t.trim().replace(new RegExp(`^${ot}:`),"");return e||null}async function cs(t,e){try{await ft(t,{text:e})}catch(n){let r=n instanceof Error?n.message:String(n);console.warn(`[callback-handler] Failed to resolve worktree prompt: ${r}`)}}function hl(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 bI(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function xI(t,e){if(bI(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 AI(t){let e="callback"in t?t.callback?.payload:void 0,n="interaction"in t?t.interaction?.payload:void 0;return e??n??""}function Sl(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function RI(t){let e=t instanceof Error?t.message:String(t);return/empty message/i.test(e)}async function ft(t,e={}){let n=t.respond,{text:r}=e;if(t.channel==="telegram"){if(typeof r=="string"&&typeof n.editMessage=="function")try{await n.editMessage({text:r,buttons:[]});return}catch(o){if(Sl(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 n.clearButtons=="function"&&await n.clearButtons();return}if(typeof n.clearComponents=="function")try{await n.clearComponents(typeof r=="string"?{text:r}:void 0);return}catch(o){if(Sl(o))return;if(RI(o)){if(typeof r!="string"&&typeof n.acknowledge=="function"){await n.acknowledge();return}typeof r!="string"&&typeof n.acknowledge!="function"&&console.warn("[callback-handler] clearComponents failed with empty-message error and no acknowledge fallback available")}else{if(typeof r!="string")throw o;{let i=o instanceof Error?o.message:String(o);console.warn(`[callback-handler] clearComponents failed before text fallback: ${i}`)}}}if(typeof r=="string"&&typeof n.editMessage=="function")try{await n.editMessage({text:r})}catch(o){if(!Sl(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 n.clearButtons=="function"&&await n.clearButtons()}async function ie(t,e){if(t.channel==="telegram"){await t.respond.reply({text:e});return}await t.respond.reply({text:e,ephemeral:!0})}function yl(t="telegram"){return j("callback_handler_registered",{channel:t,namespace:ot}),{channel:t,namespace:ot,handler:async e=>{if(!e.auth.isAuthorizedSender)return await ie(e,"\u26D4 Unauthorized."),{handled:!0};let n=AI(e),r=II(n);if(j("callback_received",{channel:e.channel,namespace:ot,payloadByteLength:Buffer.byteLength(n,"utf8"),tokenHash:hr(r),isAuthorizedSender:e.auth.isAuthorizedSender}),!r)return await ie(e,`\u26A0\uFE0F Unrecognized callback payload: "${n}".`),{handled:!0};if(!v)return await ie(e,"\u26A0\uFE0F Code agent service not running."),{handled:!0};let o=v.getActionToken(r);if(j("callback_token_lookup_completed",{channel:e.channel,namespace:ot,tokenHash:hr(r),tokenFound:!!o,actionKind:o?.kind,sessionId:o?.sessionId,planDecisionVersion:o?.planDecisionVersion}),!o)return await ie(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};let i=o.sessionId,s=v.resolve?.(i)??v.getPersistedSession?.(i),a=s?.name??i,d=xI(o,s);if(j("callback_plan_validation_completed",{channel:e.channel,namespace:ot,tokenHash:hr(r),actionKind:o.kind,sessionId:i,sessionName:a,planDecisionVersion:o.planDecisionVersion,valid:!d}),d)return await ft(e),await ie(e,`\u26A0\uFE0F ${d}`),{handled:!0};let l=v.consumeActionToken(r);if(j("callback_token_consume_completed",{channel:e.channel,namespace:ot,tokenHash:hr(r),consumed:!!l,actionKind:l?.kind,sessionId:l?.sessionId,planDecisionVersion:l?.planDecisionVersion}),!l)return await ie(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};switch(l.kind){case"worktree-merge":{await cs(e,`\u2705 Merge selected for [${a}]`);let p=await ls().execute("callback",{session:i});await ie(e,hl(p));break}case"worktree-decide-later":{await cs(e,`\u23ED\uFE0F Deferred for [${a}]`);let p=v.snoozeWorktreeDecision(i);await ie(e,p.startsWith("Error")?p:"\u23ED\uFE0F Snoozed 24h");break}case"worktree-dismiss":{await cs(e,`\u{1F5D1}\uFE0F Discarded for [${a}]`);let p=await v.dismissWorktree(i);await ie(e,(p.startsWith("Error"),p));break}case"worktree-create-pr":case"worktree-update-pr":{await cs(e,o.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${a}]`:`\u{1F4EC} PR selected for [${a}]`);let p=await fo().execute("callback",{session:i});await ie(e,hl(p));break}case"worktree-view-pr":{await ft(e);let p=v.getPersistedSession?.(i),f=o.targetUrl??p?.worktreePrUrl;await ie(e,f?`PR: ${f}`:"\u26A0\uFE0F PR URL is no longer available.");break}case"plan-approve":{await ft(e),v.clearPlanDecisionTokens(i);let p=await Mt(v,{session:i,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});p.isError&&await ie(e,`\u26A0\uFE0F ${p.text}`);break}case"plan-reject":{await ft(e),v.clearPlanDecisionTokens(i);let p=v.resolve(i);if(p)p.approvalState="rejected",v.kill(p.id,"user"),await ie(e,`\u274C Plan rejected for [${p.name}]. Session stopped.`);else{let f=v.getPersistedSession?.(i);f?(v.updatePersistedSession?.(i,{approvalState:"rejected",lifecycle:"terminal",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:(f.planDecisionVersion??0)+1}),await ie(e,`\u274C Plan rejected for [${f.name??a}]. Session remains stopped.`)):await ie(e,"\u274C Plan rejected.")}break}case"plan-request-changes":{await ft(e);let p=v.resolve?.(i),f=v.getPersistedSession?.(i),y=p?.name??f?.name??i,g=(p?.planDecisionVersion??f?.planDecisionVersion??0)+1;v.clearPlanDecisionTokens(i),v.updatePersistedSession(i,{approvalState:"changes_requested",lifecycle:"awaiting_user_input",pendingPlanApproval:!1,planDecisionVersion:g,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 ie(e,`\u270F\uFE0F Type your revision feedback for [${y}] and I'll forward it to the agent.`);break}case"monitor-start-plan":{if(await ft(e),!l.launchPrompt||!l.launchWorkdir){await ie(e,"\u26A0\uFE0F This release action is missing the plan launch context.");break}let p=v.launchMonitorPlan({route:l.route,prompt:l.launchPrompt,workdir:l.launchWorkdir,name:l.launchName,worktreeStrategy:l.launchWorktreeStrategy});await ie(e,`\u25B6\uFE0F Planning session started: ${p.name} [${p.id}]`);break}case"monitor-dismiss":{await ft(e),await ie(e,"\u2705 Dismissed.");break}case"session-restart":case"session-resume":{await ft(e);let p=await Mt(v,{session:i,message:"Continue where you left off.",userInitiated:!0});await ie(e,p.isError?`\u26A0\uFE0F ${p.text}`:`\u25B6\uFE0F ${p.text}`);break}case"view-output":{await ft(e);let p=await ns().execute("callback",{session:i,lines:50});await ie(e,hl(p));break}case"question-answer":{if(await ft(e),o.optionIndex==null){await ie(e,"\u26A0\uFE0F Invalid question-answer action.");break}await v.resolvePendingInputOption(i,o.optionIndex),await ie(e,"\u2705 Answer submitted.");break}default:{await ft(e),await ie(e,"\u26A0\uFE0F Unknown callback action.");break}}return{handled:!0}}}}X();Me();function TI(t){return t instanceof Error?t.message:String(t)}function vg(t){t.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:"Usage: /agent [--name <name>] <prompt>"};let r,o=n.match(/^--name\s+(\S+)\s+/);o&&(r=o[1],n=n.slice(o[0].length).trim());let i=n;if(!i)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let s=Ie(),a=Dt(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=v.spawn({prompt:i,name:r,workdir:_.defaultWorkdir||process.cwd(),model:a,reasoningEffort:ct(s),codexApprovalPolicy:s==="codex"?"never":void 0,originChannel:Qt(e),originThreadId:Qr(e),route:Ft(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(`
98
+ `)}}catch(s){let a=TI(s),d=a.includes("Max sessions")?"":`
99
+
100
+ Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${d}`}}}})}X();function Pg(t){t.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(e.args??"").split(/\s+/).includes("--full");return{text:es(v,"all",void 0,{full:n})}}})}X();function wg(t){t.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=e.args?.trim();return n?{text:ts(v,n,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}X();function Ig(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(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:`Usage: /agent_respond <id-or-name> <message>
101
+ /agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!0,o=o.slice(12).trim());let i=o.indexOf(" ");if(i===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let s=o.slice(0,i),a=o.slice(i+1).trim();return a?{text:(await Mt(v,{session:s,message:a,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}X();function bg(t){t.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let e=v.getMetrics(),n=v.list("running").length;return{text:Mi(e,n)}}})}X();var MI=50;function xg(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(!v)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=n.split(/\s+/),o="",i=!1,s=MI;for(let d=0;d<r.length;d++)if(r[d]==="--full")i=!0;else if(r[d]==="--lines"&&d+1<r.length){let l=parseInt(r[d+1],10);!isNaN(l)&&l>0&&(s=l),d++}else o||(o=r[d]);return o?{text:Zi(v,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}X();Me();import{existsSync as CI}from"fs";function _I(t){let e=t.match(/"[^"]*"|'[^']*'|\S+/g);return e?e.map(n=>n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n):[]}function Ag(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(!he)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)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 r=_I(n),o,i=_.defaultWorkdir||process.cwd(),s,a,d="bypassPermissions",l,p,f,y=[],g=[];for(let I=0;I<r.length;I++){let R=r[I];if(R==="--name"&&I+1<r.length)o=r[++I];else if(R==="--workdir"&&I+1<r.length)i=r[++I];else if(R==="--model"&&I+1<r.length)s=r[++I];else if(R==="--max-iterations"&&I+1<r.length){let O=parseInt(r[++I],10);!Number.isNaN(O)&&O>0&&(a=O)}else if(R==="--permission-mode"&&I+1<r.length){let O=r[++I];if(O==="default"||O==="plan"||O==="bypassPermissions")d=O;else return{text:`Error: Invalid permission mode "${O}".`}}else if(R==="--harness"&&I+1<r.length)l=r[++I];else if(R==="--mode"&&I+1<r.length){let O=r[++I];if(O==="ralph"||O==="verifier")p=O;else return{text:`Error: Invalid goal mode "${O}". Use ralph or verifier.`}}else if(R==="--completion-promise"&&I+1<r.length)f=r[++I];else if(R==="--verify"&&I+1<r.length){let O=r[++I].trim();if(!O)return{text:"Error: --verify commands must not be empty."};y.push(O)}else g.push(R)}let k=g.join(" ").trim();if(!k)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(!CI(i))return{text:`Error: Working directory does not exist: ${i}`};let A=p??(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??Ie(),w=s??Dt(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=ar(x);if(!ps(w,C))return{text:`Error: Model "${w}" is not allowed. Permitted models: ${C?.join(", ")}`};try{let I=Ft(e),R=await he.launchTask({goal:k,name:o,workdir:i,model:w,reasoningEffort:ct(x),maxIterations:a,permissionMode:d,harness:x,loopMode:A,completionPromise:f,originChannel:Qt(e),originThreadId:I?.threadId,originSessionKey:e.sessionKey,route:I,verifierCommands:y.map((O,Be)=>({label:`check-${Be+1}`,command:O}))});return{text:["Goal task launched.",` Name: ${R.name}`,` ID: ${R.id}`,` Session: ${R.sessionName} [${R.sessionId}]`,` Harness: ${x}`,` Loop mode: ${R.loopMode}`,...R.loopMode==="ralph"?[` Completion promise: ${R.completionPromise}`]:[],` Max iterations: ${R.maxIterations}`,` Goal: "${k.length>100?`${k.slice(0,100)}...`:k}"`].join(`
102
+ `)}}catch(I){return{text:`Error launching goal task: ${I.message}`}}}})}X();function Rg(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(!he)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(n){let o=he.getTask(n);if(!o)return{text:`Error: Goal task "${n}" not found.`};let i=o.sessionId?v?.resolve(o.sessionId):void 0;return{text:fn(o,mn(i))}}let r=he.listTasks();return r.length===0?{text:"No goal tasks found."}:{text:r.map(o=>{let i=o.sessionId?v?.resolve(o.sessionId):void 0;return fn(o,mn(i))}).join(`
103
+
104
+ `)}}})}X();function Tg(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(!he)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:"Usage: /goal_stop <task-id-or-name>"};let r=he.stopTask(n);return r?r.action==="already_terminal"?{text:`Task is already ${r.task.status}.`}:{text:`Task "${r.task.name}" (${r.task.id}) stopped.`}:{text:`Error: Goal task "${n}" not found.`}}})}import{execFile as qI}from"child_process";import{createHash as Fg}from"crypto";import{existsSync as EI,mkdirSync as $I,readFileSync as OI,renameSync as NI,writeFileSync as DI}from"fs";import{homedir as FI}from"os";import{dirname as LI,join as Mg}from"path";function WI(t){let e=t.OPENCLAW_HOME?.trim();return e||Mg(FI(),".openclaw")}function BI(t){let e=t.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||Mg(WI(t),"code-agent-goal-tasks.json")}function UI(t){return t instanceof Error?t.message:String(t)}function KI(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 VI(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 n=e.status,r=n==="running"||n==="waiting_for_session"?"waiting_for_session":n;return{id:e.id,name:e.name,goal:e.goal,workdir:e.workdir,status:r,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:KI(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 ms=class{path;tasks=new Map;constructor(e=process.env){this.path=BI(e),this.load()}load(){try{if(!EI(this.path))return;let e=OI(this.path,"utf8"),n=JSON.parse(e);if(!Array.isArray(n))return;for(let r of n){let o=VI(r);o&&this.tasks.set(o.id,o)}this.save()}catch{}}save(){try{$I(LI(this.path),{recursive:!0});let e=`${this.path}.tmp`;DI(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),NI(e,this.path)}catch(e){console.warn(`[GoalTaskStore] Failed to save ${this.path}: ${UI(e)}`)}}upsert(e){this.tasks.set(e.id,e),this.save()}get(e){let n=this.tasks.get(e);return n||[...this.tasks.values()].find(r=>r.name===e)}list(){return[...this.tasks.values()].sort((e,n)=>n.createdAt-e.createdAt)}};En();var jI=8,Lg=600*1e3,GI=4e3,kl=1200,HI="DONE",zI=["BASH_ENV","ENV"];function QI(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function go(t,e){return t.length<=e?t:`${t.slice(0,e-3)}...`}function hn(t,e=20){let n=t.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0);return n.length<=e?n.join(`
105
+ `):n.slice(-e).join(`
106
+ `)}function Cg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _g(t){let e=t?.trim();return e&&e.length>0?e:HI}function JI(t){return t.route??Hr(t.originChannel,t.originThreadId,t.originSessionKey)}function vl(t){return t.map((e,n)=>({label:e.label.trim()||`check-${n+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??Lg})).filter(e=>e.command.length>0)}function YI(t){return t.loopMode==="verifier"}function XI(t){return vl(t.verifierCommands).length>0}function Eg(t){return YI(t)&&!XI(t)}function fs(){return"Verifier-mode goal tasks require at least one verifier command."}function $g(t){let e=t.steps.filter(n=>!n.ok).map(n=>`${n.label}:${n.exitCode}:${hn(n.output,12)}`).join(`
107
+ `);return Fg("sha1").update(e).digest("hex")}function ZI(t){return Fg("sha1").update(hn(t,24)).digest("hex")}function Og(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 eb(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(`
108
+ `);let e=t.verifierCommands.map(n=>`- ${n.label}: ${n.command}`).join(`
107
109
  `);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 Yf(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(`
110
+ `)}function Ng(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
111
  `):["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 Xw(t,e){let r=e.steps.filter(o=>!o.ok).map(o=>[`- ${o.label} failed (exit ${o.exitCode})`,ur(o.output,18)].join(`
112
+ `)}function tb(t,e){let n=e.steps.filter(o=>!o.ok).map(o=>[`- ${o.label} failed (exit ${o.exitCode})`,hn(o.output,18)].join(`
111
113
  `)).join(`
112
114
 
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 Zw(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 eI(t,e){let r=e.steps.filter(n=>!n.ok).map(n=>[`- ${n.label} failed (exit ${n.exitCode})`,ur(n.output,18)].join(`
115
+ `);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:",n,"","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(`
116
+ `)}function nb(t,e){let n=hn(e,18)||"(no meaningful output)",r=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}.`,`- ${r}`,"","Latest output / blockers:",n,"","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(`
117
+ `)}function rb(t,e){let n=e.steps.filter(r=>!r.ok).map(r=>[`- ${r.label} failed (exit ${r.exitCode})`,hn(r.output,18)].join(`
116
118
  `)).join(`
117
119
 
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 tI(t,e){let r=e.trim();if(!r)return!1;let n=new RegExp(`(^|\\n)\\s*${Gf(r)}\\s*(\\n|$)`,"i"),o=new RegExp(`<promise>\\s*${Gf(r)}\\s*<\\/promise>`,"i");return n.test(t)||o.test(t)}function Xf(t){return t.steps.map(e=>`${e.ok?"PASS":"FAIL"} ${e.label} (exit ${e.exitCode}, ${Math.round(e.durationMs)}ms)`).join(`
120
- `)}function Er(t){return t instanceof Error?t.message:String(t)}function rI(t){return t==="succeeded"||t==="failed"||t==="stopped"}function nI(t){return io(t.error?.trim()||"Underlying session failed.",Qd)}function oI(t=process.env){let e={...t};for(let r of jw)delete e[r];return e}function iI(t,e){return new Promise(r=>{let n=Date.now();Uw("bash",["-lc",e.command],{cwd:t,timeout:e.timeoutMs??eg,maxBuffer:1024*1024,env:oI()},(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:io(l||"(no output)",Vw)})})})}var ts=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 Zi}start(){this.started||(this.started=!0,!this.restorePromise&&(this.restorePromise=this.restoreRecoverableTasks().catch(e=>{console.warn(`[GoalController] Failed to restore recoverable tasks: ${Er(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=Jd(e.verifierCommands);if(r==="verifier"&&n.length===0)throw new Error(es());let i={id:vi(8),name:Gw(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??Kw,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:Hf(e.completionPromise),verifierCommands:n,repeatedFailureCount:0},s=await this.spawnTaskSession(i,Yw(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
120
+ `);return["You emitted the completion promise, but the external verifiers did not pass.","","Goal:",t.goal,"","Verifier failures:",n,"","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(`
121
+ `)}function ob(t,e){let n=e.trim();if(!n)return!1;let r=new RegExp(`(^|\\n)\\s*${Cg(n)}\\s*(\\n|$)`,"i"),o=new RegExp(`<promise>\\s*${Cg(n)}\\s*<\\/promise>`,"i");return r.test(t)||o.test(t)}function Dg(t){return t.steps.map(e=>`${e.ok?"PASS":"FAIL"} ${e.label} (exit ${e.exitCode}, ${Math.round(e.durationMs)}ms)`).join(`
122
+ `)}function Bn(t){return t instanceof Error?t.message:String(t)}function ib(t){return t==="succeeded"||t==="failed"||t==="stopped"}function sb(t){return go(t.error?.trim()||"Underlying session failed.",kl)}function ab(t=process.env){let e={...t};for(let n of zI)delete e[n];return e}function db(t,e){return new Promise(n=>{let r=Date.now();qI("bash",["-lc",e.command],{cwd:t,timeout:e.timeoutMs??Lg,maxBuffer:1024*1024,env:ab()},(o,i,s)=>{let a=Date.now()-r,d=typeof o?.code=="number"?o.code:o?1:0,l=`${i??""}${s?`
123
+ ${s}`:""}`.trim();n({label:e.label,command:e.command,ok:!o,exitCode:d,durationMs:a,output:go(l||"(no output)",GI)})})})}var gs=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 ms}start(){this.started||(this.started=!0,!this.restorePromise&&(this.restorePromise=this.restoreRecoverableTasks().catch(e=>{console.warn(`[GoalController] Failed to restore recoverable tasks: ${Bn(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 n=e.loopMode??"verifier",r=vl(e.verifierCommands);if(n==="verifier"&&r.length===0)throw new Error(fs());let i={id:Ni(8),name:QI(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??jI,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:n,completionPromise:_g(e.completionPromise),verifierCommands:r,repeatedFailureCount:0},s=await this.spawnTaskSession(i,eb(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
124
 
123
125
  Goal:
124
- ${io(i.goal,500)}`,"goal-task-started"),i}stopTask(e){let r=this.store.get(e);if(r)return rI(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:Hw(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(zf(e)){this.markTaskFailed(e,es());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,Yf(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: ${Er(n)}`)}}}async runVerifiers(e){let r=Jd(e.verifierCommands);if(r.length===0){let s={status:"fail",steps:[{label:"verifier-config",command:"(none configured)",ok:!1,exitCode:1,durationMs:0,output:es()}],summary:"",fingerprint:""};return s.fingerprint=Qf(s),s.summary=Xf(s),s}let n=[];for(let s of r)n.push(await iI(e.workdir,s));let i={status:n.every(s=>s.ok)?"pass":"fail",steps:n,summary:"",fingerprint:""};return i.fingerprint=Qf(i),i.summary=Xf(i),i}notify(e,r,n){this.sessionManager.emitGoalTaskUpdate(e,r,n)}notifyIterationStatus(e,r,n){let o=dr(n??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0)),i=`${r}
126
-
127
- ${lr(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}): ${Er(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=io(r,Qd),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=io(r,Qd),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 xt(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=Jf(n);if(!o){this.markTaskFailedWaitingForUser(e,ur(n,24)||"The session is waiting for user input.");return}let i=await xt(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: ${Er(o)}`)}}async handleTerminalSession(e,r){if(r.status==="failed"){this.markTaskFailed(e,nI(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 xt(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=Jf(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,Yf(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=Hf(e.completionPromise);if(tI(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 g=eI(e,m);try{let y=await this.resumeTaskSession(e,g,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: ${Er(y)}`)}return}let d=Jw(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=Zw(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: ${Er(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=Xw(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: ${Er(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(zf(e)){this.markTaskFailed(e,es());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 sI,realpathSync as aI}from"fs";import{resolve as dI}from"path";function tg(t){if(!t)return;let e=dI(t);try{if(sI(e))return aI.native(e)}catch{}return e}function rs(t,e){return!t||!e?!1:tg(t)===tg(e)}ke();Re();import{existsSync as lI}from"fs";ke();ut();function rg(t){return t instanceof Error?t.message:String(t)}function uI(t){let e=t.worktreeStrategy??_.defaultWorktreeStrategy;return!!e&&e!=="off"&&$d(ki({harnessName:t.harness??Pe(),backendRef:t.backendRef}))}function pI(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 cI(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=Mi(n.worktreePath);return n.workdir&&s&&rs(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=Lm(ki({persistedHarness:n.harness,backendRef:n.backendRef}))&&!!n.backendRef?.worktreePath;if(lI(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{_i(o);let s=Ld(o,n.worktreeBranch.replace(/^agent\//,""),{allowExistingBranch:!0});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: ${rg(s)}, using original workdir`),{actualWorkdir:o,originalWorkdir:o,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom}}}function ng(t,e,r){let{actualWorkdir:n,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}=cI(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 g=uI(t),y=!t.resumeSessionId&&!i&&m&&m!=="off"&&!g;if(g&&!Dd(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${m}" requires a git worktree, but "${o}" is not a git repository.`);if(y&&Dd(o)){if(!tf(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=Ld(o,e),n=i,s=Ci(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: ${rg(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?pI(t.systemPrompt,o,i,s):t.systemPrompt,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}}var ns=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,r){return ng(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 os=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 mI=new Set(["starting","running"]),is=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),mI.has(i.status)&&(!n||i.startedAt>n.startedAt)&&(n=i));return n??o}};ke();ke();ut();var ss=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??ar(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=Mr(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 Yd(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function as(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:Yd(t,{state:"pending_decision",updatedAt:r,notes:e.notes})};return e.clearResolverSessionId&&(n.autoMergeResolverSessionId=void 0),n}function og(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:Yd(t,{state:"merge_conflict_resolving",updatedAt:o,notes:n.notes})}}function ig(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:Yd(t,{state:"merged",updatedAt:r,resolvedAt:n,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}ut();var ds=class{constructor(e){this.deps=e;this.actions=new ss({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,as(e,r))}markAutoMergeConflictResolving(e,r,n){this.updatePersistedSessionFor(e,og(e,r,n,{notes:[`resolver_session:${r}`]}))}markMerged(e){this.updatePersistedSessionFor(e,ig(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){Ot(r,n),this.markMerged(e);let d=Cr({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 VI,writeFileSync as qI}from"fs";br();import{randomUUID as fI}from"crypto";function gI(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var ls=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:fI(),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||!gI(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 us=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 LI,mkdirSync as WI,readFileSync as BI,readdirSync as Zd,renameSync as cg,statSync as mg,unlinkSync as fg,writeFileSync as gg}from"fs";import{tmpdir as el}from"os";import{dirname as UI,join as fs}from"path";import{homedir as hI}from"node:os";import{join as SI}from"node:path";function sg(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let r=t.HOME?.trim()||hI();return SI(r,".openclaw")}br();var ps=6,yI=new Set(["running","completed","failed","killed"]);function so(t){return!!t&&typeof t=="object"}function un(t,e=""){return typeof t=="string"&&t.trim().length>0?t:e}function x(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 kI(t){return t==="low"||t==="medium"||t==="high"?t:void 0}function ag(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function vI(t){return t==="never"||t==="on-request"?"never":void 0}function PI(t){return t==="approve"||t==="ask"||t==="delegate"?t:void 0}function wI(t){if(t==="plan-mode"||t==="codex-first-turn-plan"||t==="soft-plan")return"plan-mode"}function II(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function dg(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 xI(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function bI(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 AI(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 RI(t){return t==="live"||t==="stopped"?t:void 0}function TI(t){return t==="not_sent"||t==="sending"||t==="delivered"||t==="fallback_delivered"||t==="failed"?t:void 0}function MI(t){return t==="direct-telegram"?"direct-message":t==="none"||t==="direct-message"||t==="wake-only"?t:void 0}function CI(t){return t==="none"||t==="canonical_buttons"||t==="explicit_fallback_text"?t:void 0}function _I(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function $I(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 EI(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 lg(t){if(!so(t))return;let e=x(t.provider),r=x(t.accountId),n=x(t.target),o=x(t.threadId),i=x(t.sessionKey);if(!(!e||!n))return{provider:e,accountId:r,target:n,threadId:o,sessionKey:i}}function OI(t,e,r){if(so(t)){let n=x(t.kind),o=x(t.conversationId);if(o&&(n==="claude-code"||n==="codex-app-server"))return{kind:n,conversationId:o,runId:x(t.runId),worktreeId:x(t.worktreeId),worktreePath:x(t.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:r}}function DI(t){if(!so(t))return;let e=AI(t.state),r=x(t.updatedAt);if(!e||!r)return;let n=x(t.resolutionSource);return{state:e,updatedAt:r,resolvedAt:x(t.resolvedAt),resolutionSource:n==="agent_merge"||n==="agent_pr"||n==="strategy_no_change"||n==="lifecycle_resolver"||n==="dismiss"||n==="maintenance"?n:void 0,baseBranch:x(t.baseBranch),targetRepo:x(t.targetRepo),pushRemote:x(t.pushRemote),notes:Array.isArray(t.notes)?t.notes.filter(o=>typeof o=="string"&&o.length>0):void 0}}function NI(t){let e=new Date(0).toISOString(),r=x(t.worktreeMergedAt)??x(t.worktreeDismissedAt)??x(t.pendingWorktreeDecisionSince)??e;if(t.worktreeMerged===!0)return{state:"merged",updatedAt:r,resolvedAt:x(t.worktreeMergedAt)??r,resolutionSource:"agent_merge",baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:r,resolvedAt:x(t.worktreeDismissedAt)??r,resolutionSource:"dismiss",baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.worktreeDisposition==="no-change-cleaned")return{state:"no_change",updatedAt:r,resolvedAt:r,resolutionSource:"strategy_no_change",baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.worktreeDisposition==="pr-opened"||t.worktreeState==="pr_open")return{state:"pr_open",updatedAt:r,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:r,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:r,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(x(t.worktreePath)||x(t.worktreeBranch))return{state:"provisioned",updatedAt:r,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)}}function FI(t){if(typeof t=="string"&&yI.has(t))return t==="running"?"killed":t}function ug(t){if(!so(t))return;let e=un(t.harnessSessionId);if(!e)return;let r=FI(t.status);if(!r)return;let n=t.status==="running",o=x(t.worktreePath),i=x(t.worktreeBranch),s=x(t.originChannel),a=typeof t.originThreadId=="string"||typeof t.originThreadId=="number"?t.originThreadId:void 0,d=x(t.originSessionKey),l=lg(t.route);if(!l)return;let m=Zr({route:l,originChannel:s,originThreadId:a,originSessionKey:d});if(!m||o&&!i)return;let g=x(t.harness),y=OI(t.backendRef,g,e),f=DI(t.worktreeLifecycle)??NI(t);return{sessionId:x(t.sessionId),harnessSessionId:e,backendRef:y,name:un(t.name,e),prompt:un(t.prompt),workdir:un(t.workdir,"(unknown)"),model:x(t.model),reasoningEffort:kI(t.reasoningEffort),createdAt:je(t.createdAt),completedAt:je(t.completedAt),status:r,lifecycle:n?dg(t.lifecycle)??"suspended":dg(t.lifecycle),approvalState:xI(t.approvalState),worktreeState:bI(t.worktreeState),runtimeState:n?"stopped":RI(t.runtimeState),deliveryState:_I(t.deliveryState),completionWakeIssuedAt:x(t.completionWakeIssuedAt),completionWakeSucceededAt:x(t.completionWakeSucceededAt),completionWakeFailedAt:x(t.completionWakeFailedAt),completionWakeSummaryRequired:t.completionWakeSummaryRequired===!0?!0:void 0,killReason:II(t.killReason),costUsd:typeof t.costUsd=="number"&&Number.isFinite(t.costUsd)?t.costUsd:0,originAgentId:x(t.originAgentId),originChannel:s,originThreadId:a,originSessionKey:d,route:m,outputPath:x(t.outputPath),harness:g,requestedPermissionMode:ag(t.requestedPermissionMode),currentPermissionMode:ag(t.currentPermissionMode),approvalExecutionState:$I(t.approvalExecutionState),approvalRationale:x(t.approvalRationale),planModeApproved:t.planModeApproved===!0,pendingPlanApproval:t.pendingPlanApproval===!0,planApprovalContext:wI(t.planApprovalContext),planDecisionVersion:je(t.planDecisionVersion),actionablePlanDecisionVersion:je(t.actionablePlanDecisionVersion),canonicalPlanPromptVersion:je(t.canonicalPlanPromptVersion),approvalPromptRequiredVersion:je(t.approvalPromptRequiredVersion),approvalPromptVersion:je(t.approvalPromptVersion),approvalPromptStatus:TI(t.approvalPromptStatus),approvalPromptTransport:MI(t.approvalPromptTransport),approvalPromptMessageKind:CI(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:x(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:x(t.approvalPromptDeliveredAt),approvalPromptFailedAt:x(t.approvalPromptFailedAt),planApproval:PI(t.planApproval),codexApprovalPolicy:vI(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:x(t.worktreeMergedAt),worktreePrUrl:x(t.worktreePrUrl),worktreePrNumber:je(t.worktreePrNumber),pendingWorktreeDecisionSince:x(t.pendingWorktreeDecisionSince),lastWorktreeReminderAt:x(t.lastWorktreeReminderAt),worktreeBaseBranch:x(t.worktreeBaseBranch),worktreePrTargetRepo:x(t.worktreePrTargetRepo),autoMergeParentSessionId:x(t.autoMergeParentSessionId),autoMergeConflictResolutionAttemptCount:je(t.autoMergeConflictResolutionAttemptCount),autoMergeResolverSessionId:x(t.autoMergeResolverSessionId),worktreePushRemote:x(t.worktreePushRemote),worktreeDecisionSnoozedUntil:x(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:x(t.worktreeDismissedAt),worktreeLifecycle:f,resumable:n?!0:t.resumable===!0}}function pg(t){if(!so(t))return;let e=EI(t.kind),r=un(t.id),n=un(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:x(t.label),targetUrl:x(t.targetUrl),route:lg(t.route),launchName:x(t.launchName),launchPrompt:x(t.launchPrompt),launchWorkdir:x(t.launchWorkdir)}}function cs(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 Xd(t){return!!t&&typeof t=="object"}function tl(t){return t instanceof Error?t.message:String(t)}function hg(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||fs(sg(t),"code-agent-sessions.json")}function Sg(t,e,r){try{WI(UI(t),{recursive:!0});let n=t+".tmp";gg(n,JSON.stringify({schemaVersion:ps,sessions:e,actionTokens:r},null,2),"utf-8"),cg(n,t)}catch(n){console.warn(`[SessionStore] Failed to save session index: ${tl(n)}`)}}function ms(t,e){try{if(!LI(t))return;let r=`${t}.legacy-${Date.now()}.json`;cg(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: ${tl(r)}`)}}function KI(t,e){try{if(e.length===0)return;let r=`${t}.codex-sdk-legacy-${Date.now()}.json`;gg(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: ${tl(r)}`)}}function yg(t,e){try{let r=el(),n=Zd(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let i=fs(r,o),s=mg(i).mtimeMs;t-s>e&&fg(i)}catch{}}catch{}}function kg(t,e){try{let r=el(),n=Zd(r).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of n)try{let s=fs(r,i),a=mg(s).mtimeMs+e;if(a<=t)return t;o=o==null?a:Math.min(o,a)}catch{}return o}catch{return}}function vg(t){try{let e=new Set(t),r=el(),n=Zd(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n){let i=fs(r,o);if(!e.has(i))try{fg(i)}catch{}}}catch{}}function Pg(t){let{indexPath:e,clearAll:r,indexPersistedEntry:n,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:s}=t;try{let a=BI(e,"utf-8"),d=JSON.parse(a);if(Array.isArray(d)){ms(e,"legacy array store"),s();return}if(!Xd(d)||d.schemaVersion!==ps&&d.schemaVersion!==4){ms(e,`schema mismatch (expected v${ps})`),s();return}let l=Array.isArray(d.sessions)?d.sessions:[],m=[];for(let y of l){if(Xd(y)&&y.harness==="codex"){let k=Xd(y.backendRef)?y.backendRef:void 0;if((typeof k?.kind=="string"?k.kind:void 0)!=="codex-app-server"){m.push(y);continue}}let f=ug(y);if(!f){r(),ms(e,"invalid v4 session entry"),s();return}n(f)}m.length>0&&(KI(e,m),s());let g=Array.isArray(d.actionTokens)?d.actionTokens:[];for(let y of g){let f=pg(y);if(!f){r(),ms(e,"invalid v4 action token"),s();return}o(f)}i()}catch{}}var jI=new Set(["completed","failed","killed"]),rl=1440*60*1e3;function GI(t){return t instanceof Error?t.message:String(t)}var gs=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??hg(r),this.actionTokenStore=new ls(()=>this.saveIndex(),rl),this.actionTokens=this.actionTokenStore.tokens,this.queries=new us({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(){Pg({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(){Sg(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){cs(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){return e.backendRef??{kind:_d(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=Zr({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};cs(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=Zr({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!n)return;let o;try{let s=sn(e.id);if(VI(s))o=s;else{let a=e.getOutput().join(`
149
- `);a.length>0&&(qI(s,a,"utf-8"),o=s)}}catch(s){console.warn(`[SessionStore] Failed to write output file for session ${e.id}: ${GI(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};cs(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),yg(e,rl)}getNextTmpOutputCleanupAt(e){return kg(e,rl)}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||!jI.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(){vg(this.getReferencedOutputPaths())}};var HI=new Set(["completed","failed","killed"]),hs=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),HI.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*as wg from"child_process";var nl=3e4,zI=2e3,QI=2e4,bt=4;function ao(t){return t instanceof Error?t.message:String(t)}function JI(){return new Error(`Dispatch timed out after ${nl}ms`)}function YI(t){if(!(t instanceof Error))return!1;let e=t;return e.killed===!0&&e.signal==="SIGTERM"}var XI={execFile:wg.execFile},Ss=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,...r.dispatchContext,attempt:o,maxAttempts:bt}),XI.execFile("openclaw",e,{timeout:nl},(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,...r.dispatchContext,attempt:o,maxAttempts:bt,elapsedMs:l}),r.onSuccess?.(),n?.();return}let m=d?.trim()?` | stderr: ${d.trim()}`:"";if(r.target==="message.send"&&YI(s)){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:bt,elapsedMs:l,error:`${ao(s)}${m}`,terminal:!0,ambiguousResult:!0}),r.onAmbiguousResult?.(),n?.();return}if(o>=bt){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:bt,elapsedMs:l,error:`${ao(s)}${m}`,terminal:!0}),r.onFinalFailure?.(),n?.();return}let y=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,...r.dispatchContext,attempt:o,maxAttempts:bt,elapsedMs:l,retryDelayMs:y,error:`${ao(s)}${m}`});let f={timer:setTimeout(()=>{let k=this.pendingRetryTimers.get(r.sessionId);k&&(k.delete(f),k.size===0&&this.pendingRetryTimers.delete(r.sessionId)),this.executeNow(e,r,n,o+1)},y),onCleared:n};f.timer.unref?.(),this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(f)})}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,...r.dispatchContext,attempt:o,maxAttempts:bt}),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,...r.dispatchContext,attempt:o,maxAttempts:bt,elapsedMs:s}),r.onSuccess?.(),n?.()}).catch(s=>{if(this.disposed){n?.();return}let a=Date.now()-i;if(o>=bt){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,...r.dispatchContext,attempt:o,maxAttempts:bt,elapsedMs:a,error:ao(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,...r.dispatchContext,attempt:o,maxAttempts:bt,elapsedMs:a,retryDelayMs:d,error:ao(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(JI()))},nl);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=zI*2**r;return Math.min(n,QI)}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)}};br();var ys=class{resolve(e){let r=ii(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 ZI}from"crypto";var ks=class{constructor(e={}){this.options=e}options;buildChatSendArgs(e,r,n){return["gateway","call","chat.send","--expect-final","--timeout","30000","--params",JSON.stringify({sessionKey:e,message:r,deliver:n,idempotencyKey:ZI()})]}buildDirectNotificationArgs(e,r,n){let o=(n??[]).filter(s=>Array.isArray(s)&&s.length>0).map(s=>({type:"buttons",buttons:s.map(a=>({label:a.label,value:this.prefixCallbackData(a.callbackData),...a.style?{style:a.style}:{}}))})),i=["message","send","--channel",e.channel,"--target",e.target,"--message",r];return e.accountId&&i.push("--account",e.accountId),e.threadId&&i.push("--thread-id",e.threadId),o.length>0&&i.push("--presentation",JSON.stringify({blocks:o})),i}prefixCallbackData(e){return e.startsWith(`${ln}:`)?e:`${ln}:${e}`}buildSystemEventArgs(e){return["system","event","--text",e,"--mode","now"]}};var vs=class{routes=new ys;transport;executor=new Ss;constructor(e={}){this.transport=e.transport??new ks(e.transportOptions)}clearPendingRetries(){this.executor.clearPendingRetries()}clearRetryTimersForSession(e){this.executor.clearRetryTimersForSession(e)}dispose(){this.executor.dispose()}buildDispatchContext(e){let r=e.buttons??[],n=r.flat();return{transportRoute:e.routeSummary,transportChannel:e.route?.channel??"system",transportTarget:e.route?.target??"system",transportAccountId:e.route?.accountId,transportThreadId:e.route?.threadId,transportSessionKey:e.route?.sessionKey,messageTextLength:e.text.length,buttonsPresent:n.length>0,buttonRows:r.length||void 0,buttonCount:n.length||void 0,buttonLabels:n.length>0?n.map(o=>o.label):void 0,maxCallbackDataLength:n.length>0?Math.max(...n.map(o=>o.callbackData.length)):void 0}}sendWake(e,r,n,o,i,s){let a=this.routes.resolve(e),d=a?.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",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:r}),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",dispatchContext:this.buildDispatchContext({routeSummary:`session:${d}`,route:a,text:r}),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",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:r}),onSuccess:s,onFinalFailure:i})}})}sendUserNotification(e,r,n,o,i,s){let a=!!o?.some(m=>Array.isArray(m)&&m.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",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:r,buttons:o}),orderingKey:l,onSuccess:s,onFinalFailure:i});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",dispatchContext:this.buildDispatchContext({routeSummary:this.routes.summary(d),route:d,text:r,buttons:o}),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",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:r}),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(),g=k=>{k&&(n?.onWakeStarted?.(),this.sendWake(e,k,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded))},y=()=>{n?.onNotifySucceeded?.(),l&&g(l)},f=m?()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.(),g(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 Ps=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,style:this.resolveButtonStyle(r)}}resolveButtonStyle(e){switch(e){case"plan-approve":case"worktree-create-pr":case"worktree-update-pr":case"monitor-start-plan":return"primary";case"worktree-merge":case"session-resume":case"session-restart":return"success";case"plan-reject":case"worktree-dismiss":return"danger";default:return"secondary"}}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 ws=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"||e.completionWakeSummaryRequired!==!0))return{completionWakeSummaryRequired:!0}}};ut();import{existsSync as ex}from"fs";var Is=class{getCompletionState(e,r,n,o){return Nd(e,n,o)?"has-commits":Nd(e,o,n)?"base-advanced":an(r)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(e,r,n){if(!e.worktreePath||!e.workdir||!ex(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 xs=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((g,y)=>` ${y+1}. ${g.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
150
- `);return new Promise((g,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:g,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 tx(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 bs(t){let e=tx(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function lo(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 rx(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function ol(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 nx(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 il(t){let{session:e,originThreadLine:r,preview:n}=t,o=`$${(e.costUsd??0).toFixed(2)}`,i=It(e.duration),s=rx(),a=d=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,r,...bs(e),"","Output preview:",n,"",...nx({contract:s,canonicalStatusDelivered:d}),"",...ol({sessionId:e.id,canonicalStatusDelivered:d})].join(`
152
- `);return{userMessage:`\u2705 [${e.name}] Completed | ${o} | ${i}`,wakeMessageOnNotifySuccess:a(!0),wakeMessageOnNotifyFailed:a(!1),followupContract:s}}function sl(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,...bs(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 al(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 dl(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 ll(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 ul(t){let{sessionName:e,sessionId:r,cleanupSummary:n,preview:o,originThreadLine:i,requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:m,approvalPromptStatus:g,approvalPromptMessageKind:y,approvalPromptDeliveredAt:f}=t,k=o.trim()?["","Output preview:",o]:[];return["Coding agent session completed with no repository changes.",`Name: ${e} | ID: ${r}`,`Worktree outcome: ${n}`,...i?[i]:[],...bs({requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:m,approvalPromptStatus:g,approvalPromptMessageKind:y,approvalPromptDeliveredAt:f}),...k,"",...ol({sessionId:r,canonicalStatusDetail:"The plugin already sent the canonical completion status to the user, including that no repo changes were kept."})].join(`
158
- `)}function pl(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 bg=3200,cl=3e3,ox=2400,ix=120,sx=5,ax=280,Ig=1400,xg="- Additional plan details omitted for brevity.";function Ag(t){return t.replace(/^#{1,6}\s+/,"").replace(/^[-*+]\s+/,"").replace(/^\d+[.)]\s+/,"").replace(/^`([^`]+)`$/,"$1").trim()}function dx(t){return t.split(`
159
- `).map(e=>e.trim()).filter(Boolean).map(Ag).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 lx(t){return t.split(`
160
- `).map(e=>e.trim()).filter(Boolean).map(Ag).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 ml(t){let e=dx(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 ux(t){let e=[],r=!1;for(let o of t){let i=o.replace(/\s+/g," ").trim();if(!i)continue;let s=Fe(i,ax);s.length<i.length&&(r=!0);let a=`- ${s}`;if(e.length>=sx||[...e,a].join(`
163
- `).length>Ig){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,xg].join(`
164
- `).length>Ig;)n.pop();return[...n,xg]}function fl(t){return ux(lx(t)).join(`
165
- `)}function px(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 cx(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 px(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 Rg(t){return Fe(t.trim(),ix)}function Tg(t,e){return e?t?`
126
+ ${go(i.goal,500)}`,"goal-task-started"),i}stopTask(e){let n=this.store.get(e);if(n)return ib(n.status)?{task:n,action:"already_terminal"}:(n.sessionId&&this.sessionManager.kill(n.sessionId,"user"),this.markTaskStopped(n,"Stopped by user."),{task:n,action:"stopped"})}async spawnTaskSession(e,n){return this.spawnManagedTaskSession(e,n)}async spawnManagedTaskSession(e,n,r){let o=r?this.sessionManager.resolveHarnessSessionId(r)??r:void 0,i=r?this.sessionManager.resolve(r):void 0,s=o?this.sessionManager.getPersistedSession(o)??this.sessionManager.getPersistedSession(r??o):void 0,{resumeSessionId:a}=dr({requestedResumeSessionId:o,activeSession:i?{harnessSessionId:i.harnessSessionId}:void 0,persistedSession:s?{harness:s.harness,backendRef:s.backendRef}:void 0}),d={prompt:n,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:JI(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,n,r){if(!r.harnessSessionId){let i=await this.spawnTaskSession(e,["The previous session ended without a resumable harness session id.","Continue working on the same goal.","",n].join(`
127
+ `));return this.attachSessionObservers(e,i),i}let o=await this.spawnManagedTaskSession(e,n,r.harnessSessionId);return this.attachSessionObservers(e,o),o}resolveResumeSessionId(e){if(e.harnessSessionId)return e.harnessSessionId;if(e.sessionId){let r=this.sessionManager.resolveHarnessSessionId(e.sessionId);if(r)return r}let n=this.sessionManager.resolveHarnessSessionId(e.name);if(n)return n}captureRecoverableTasks(){for(let e of this.store.list()){if(e.status!=="running"&&e.status!=="waiting_for_session")continue;let n=e.sessionId?this.sessionManager.resolve(e.sessionId):void 0;n&&(e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??e.harnessSessionId,e.route=n.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(Eg(e)){this.markTaskFailed(e,fs());continue}if(e.sessionId){let r=this.sessionManager.resolve(e.sessionId);if(r&&(r.status==="starting"||r.status==="running"))continue}let n=this.resolveResumeSessionId(e);if(!n){this.markTaskFailed(e,"Goal task could not be resumed after gateway restart because no resumable session id was available.");continue}try{let r=await this.spawnManagedTaskSession(e,Ng(e),n);if(!this.started){e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId??n,e.route=r.route??e.route,e.status="waiting_for_session",e.updatedAt=Date.now(),this.store.upsert(e),this.sessionManager.kill(r.id,"shutdown");break}this.attachSessionObservers(e,r),e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId??n,e.route=r.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`,r),this.scheduleTaskEvaluation(e.id,"restore",r.id)}catch(r){this.markTaskFailed(e,`Failed to resume the goal task after gateway restart: ${Bn(r)}`)}}}async runVerifiers(e){let n=vl(e.verifierCommands);if(n.length===0){let s={status:"fail",steps:[{label:"verifier-config",command:"(none configured)",ok:!1,exitCode:1,durationMs:0,output:fs()}],summary:"",fingerprint:""};return s.fingerprint=$g(s),s.summary=Dg(s),s}let r=[];for(let s of n)r.push(await db(e.workdir,s));let i={status:r.every(s=>s.ok)?"pass":"fail",steps:r,summary:"",fingerprint:""};return i.fingerprint=$g(i),i.summary=Dg(i),i}notify(e,n,r){this.sessionManager.emitGoalTaskUpdate(e,n,r)}notifyIterationStatus(e,n,r){let o=mn(r??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0)),i=`${n}
128
+
129
+ ${fn(e,o)}`;this.notify(e,i,"goal-task-progress")}setTaskRunningWithSession(e,n){e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId,e.route=n.route??e.route,e.status="running",e.waitingForUserReason=void 0,e.updatedAt=Date.now(),this.store.upsert(e)}attachSessionObservers(e,n){if(this.observerDisposers.has(n.id))return;let r=(i,s)=>{(s==="completed"||s==="failed"||s==="killed")&&(this.removeSessionObserver(n.id),this.scheduleTaskEvaluation(e.id,`status:${s}`,n.id))},o=()=>{let i=this.store.get(e.id);i&&(i.sessionId=n.id,i.sessionName=n.name,i.harnessSessionId=n.harnessSessionId,i.route=n.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`,n),this.scheduleTaskEvaluation(e.id,"turnEnd",n.id))};n.on("statusChange",r),n.on("turnEnd",o),this.observerDisposers.set(n.id,()=>{n.off?.("statusChange",r),n.off?.("turnEnd",o),n.removeListener?.("statusChange",r),n.removeListener?.("turnEnd",o)})}scheduleTaskEvaluation(e,n,r){if(!this.started)return;let o=this.scheduledEvaluations.get(e);if(o){!o.sessionId&&r&&(o.sessionId=r);return}let i={timer:setTimeout(()=>{this.scheduledEvaluations.delete(e),this.evaluateTask(e,n,i.sessionId).catch(s=>{console.warn(`[GoalController] evaluateTask error (${n}): ${Bn(s)}`)})},0),sessionId:r};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 n=this.observerDisposers.get(e);n&&(this.observerDisposers.delete(e),n())}markTaskFailed(e,n){e.status="failed",e.failureReason=go(n,kl),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u274C [${e.name}] Goal task failed
130
+
131
+ ${e.failureReason}`,"goal-task-failed")}markTaskFailedWaitingForUser(e,n){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${n}`)}markTaskSucceeded(e,n){e.status="succeeded",e.lastVerifierSummary=n,e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u2705 [${e.name}] Goal task succeeded
132
+
133
+ ${n}`,"goal-task-succeeded")}markTaskStopped(e,n){e.status="stopped",e.failureReason=go(n,kl),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u26D4 [${e.name}] Goal task stopped
134
+
135
+ ${e.failureReason}`,"goal-task-stopped")}async handleRunningSession(e,n){if(n.pendingPlanApproval){let s=await Mt(this.sessionManager,{session:n.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});s.isError&&this.markTaskFailed(e,s.text);return}if(!n.pendingInputState){this.setTaskRunningWithSession(e,n);return}let r=n.getOutput(30).join(`
136
+ `),o=Og(r);if(!o){this.markTaskFailedWaitingForUser(e,hn(r,24)||"The session is waiting for user input.");return}let i=await Mt(this.sessionManager,{session:n.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,n,r){try{let o=await this.resumeTaskSession(e,r,n);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: ${Bn(o)}`)}}async handleTerminalSession(e,n){if(n.status==="failed"){this.markTaskFailed(e,sb(n));return}if(n.status==="killed"&&n.killReason==="user"){this.markTaskStopped(e,"Stopped by user.");return}if(n.status==="killed"&&n.killReason==="idle-timeout"){let i=n.getOutput(60).join(`
137
+ `);if(n.pendingPlanApproval){let s=await Mt(this.sessionManager,{session:n.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});if(s.isError){this.markTaskFailed(e,s.text);return}let a=this.sessionManager.resolve(n.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(n.pendingInputState){let s=Og(i);if(!s){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${hn(i,24)||"The goal task hit idle timeout while waiting for user input."}`);return}await this.resumeAfterIdleTimeout(e,n,["The previous session hit idle timeout while waiting for a response.",`Use this response and continue the goal: ${s}`].join(`
138
+
139
+ `));return}await this.resumeAfterIdleTimeout(e,n,Ng(e));return}if(n.status==="killed"&&n.killReason!=="done"){this.markTaskFailed(e,`Underlying session was killed (${n.killReason}).`);return}if(e.loopMode==="ralph"){let i=n.getOutput(200).join(`
140
+ `),s=_g(e.completionPromise);if(ob(i,s)){if(e.verifierCommands.length===0){this.markTaskSucceeded(e,`Completion promise "${s}" detected in agent output.`);return}let p=await this.runVerifiers(e);if(e.lastVerifierSummary=p.summary,e.updatedAt=Date.now(),p.status==="pass"){this.markTaskSucceeded(e,[`Completion promise "${s}" detected.`,p.summary].join(`
141
+ `));return}if(e.lastVerifierFingerprint===p.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=p.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}).`,p.summary].join(`
142
+ `));return}e.iteration+=1;let f=rb(e,p);try{let y=await this.resumeTaskSession(e,f,n);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: ${Bn(y)}`)}return}let d=ZI(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:",hn(i,20)||"(no output)"].join(`
143
+ `));return}e.iteration+=1;let l=nb(e,i);try{let p=await this.resumeTaskSession(e,l,n);this.setTaskRunningWithSession(e,p),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Ralph iteration continued`),this.scheduleTaskEvaluation(e.id,"ralph-continue",p.id)}catch(p){this.markTaskFailed(e,`Failed to continue the Ralph goal task: ${Bn(p)}`)}return}let r=await this.runVerifiers(e);if(e.lastVerifierSummary=r.summary,e.updatedAt=Date.now(),r.status==="pass"){this.markTaskSucceeded(e,r.summary);return}if(e.lastVerifierFingerprint===r.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=r.fingerprint,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Verifier did not pass before hitting the iteration budget (${e.maxIterations}).`,r.summary].join(`
144
+ `));return}e.iteration+=1;let o=tb(e,r);try{let i=await this.resumeTaskSession(e,o,n);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: ${Bn(i)}`)}}async evaluateTask(e,n,r){this.restorePromise&&await this.restorePromise;let o=this.store.get(e);o&&await this.reconcileTask(o,n,r)}async reconcileTask(e,n="manual",r){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)&&r?this.dirtyEvaluationSessionIds.set(e.id,r):this.dirtyEvaluationSessionIds.has(e.id)||this.dirtyEvaluationSessionIds.set(e.id,r);return}this.inFlight.add(e.id);try{if(r&&e.sessionId&&e.sessionId!==r){let i=this.sessionManager.resolve(r);if(i&&(i.status==="completed"||i.status==="failed"||i.status==="killed"))return}let o=r?this.sessionManager.resolve(r)??(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(Eg(e)){this.markTaskFailed(e,fs());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,`${n}:dirty`,o)}}}}};Me();import{existsSync as lb,realpathSync as ub}from"fs";import{resolve as pb}from"path";function Wg(t){if(!t)return;let e=pb(t);try{if(lb(e))return ub.native(e)}catch{}return e}function hs(t,e){return!t||!e?!1:Wg(t)===Wg(e)}Pe();Me();import{existsSync as cb}from"fs";Pe();mt();function Bg(t){return t instanceof Error?t.message:String(t)}function mb(t){let e=t.worktreeStrategy??_.defaultWorktreeStrategy;return!!e&&e!=="off"&&zd(Ti({harnessName:t.harness??Ie(),backendRef:t.backendRef}))}function fb(t,e,n,r){let o=["","You are working in a git worktree.",`Worktree path: ${n}`,`Branch: ${r}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${n}.`,`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(`
145
+ `);return(t??"")+o}function gb(t,e){let n=t.resumeSessionId??t.resumeWorktreeFrom;if(!n)return{};let r=e(n);if(!r)return{};let o=(()=>{if(r.workdir&&r.workdir!==r.worktreePath)return r.workdir;if(r.worktreePath){let s=qi(r.worktreePath);return r.workdir&&s&&hs(r.workdir,s)?r.workdir:s??r.workdir}return r.workdir})();if(!t.worktreeStrategy&&r.worktreeStrategy&&(t.worktreeStrategy=r.worktreeStrategy),!t.planApproval&&r.planApproval&&(t.planApproval=r.planApproval),!r.worktreePath)return{};if(!r.worktreeBranch)throw new Error(`Cannot resume session "${n}": persisted worktree metadata is missing worktreeBranch.`);let i=cf(Ti({persistedHarness:r.harness,backendRef:r.backendRef}))&&!!r.backendRef?.worktreePath;if(cb(r.worktreePath))return console.info(`[SessionManager] Resuming with existing worktree: ${r.worktreePath}`),{actualWorkdir:r.worktreePath,originalWorkdir:o??r.worktreePath,worktreePath:r.worktreePath,worktreeBranchName:r.worktreeBranch};if(!o)return console.warn(`[SessionManager] Worktree ${r.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 ${r.worktreePath} is missing; resuming from original workdir and letting the backend restore thread state.`),{actualWorkdir:o,originalWorkdir:o,worktreeBranchName:r.worktreeBranch,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom};try{Gi(o);let s=rl(o,r.worktreeBranch.replace(/^agent\//,""),{allowExistingBranch:!0});return console.info(`[SessionManager] Recreated worktree from branch ${r.worktreeBranch}: ${s}`),{actualWorkdir:s,originalWorkdir:o,worktreePath:s,worktreeBranchName:r.worktreeBranch}}catch(s){return console.warn(`[SessionManager] Failed to recreate worktree for resume: ${Bg(s)}, using original workdir`),{actualWorkdir:o,originalWorkdir:o,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom}}}function Ug(t,e,n){let{actualWorkdir:r,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}=gb(t,n);a&&(t.resumeSessionId=void 0),d&&(t.resumeWorktreeFrom=void 0),r??=t.workdir,o??=t.workdir;let l=!!(t.resumeSessionId??t.resumeWorktreeFrom),p=t.worktreeStrategy??_.defaultWorktreeStrategy;p&&(t.worktreeStrategy=p);let f=mb(t),y=!t.resumeSessionId&&!i&&p&&p!=="off"&&!f;if(f&&!el(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${p}" requires a git worktree, but "${o}" is not a git repository.`);if(y&&el(o)){if(!Ff(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=rl(o,e),r=i,s=ji(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);console.log(`[SessionManager] Created worktree at ${i}`)}catch(g){throw new Error(`Cannot launch session "${e}": worktree creation failed: ${Bg(g)}`)}}else if(y)throw new Error(`Cannot launch session "${e}": worktree strategy "${p}" requires a git worktree, but "${o}" is not a git repository.`);return l&&i&&(r=i),{actualWorkdir:r,originalWorkdir:o,effectiveSystemPrompt:i&&s?fb(t.systemPrompt,o,i,s):t.systemPrompt,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}}var Ss=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,n){return Ug(e,n,this.getPersistedSession)}hydrateSpawnedSession(e,n,r){r.worktreeStrategy&&r.worktreeStrategy!=="off"&&(e.originalWorkdir=n.originalWorkdir),n.worktreePath&&(e.worktreePath=n.worktreePath,e.worktreeBranch=n.worktreeBranchName,e.worktreeState="provisioned"),r.worktreePrTargetRepo&&(e.worktreePrTargetRepo=r.worktreePrTargetRepo)}};Pe();var ys=class{constructor(e){this.deps=e}deps;applySessionPatch(e,n){let r=this.deps.store.getPersistedSession(e);r&&(Object.assign(r,n),this.deps.store.assertPersistedEntry(r));let o=this.findActiveSessionForRef(e,r);return o&&this.applyPatchToActiveSession(o,n),!r&&!o?!1:(r&&this.deps.store.saveIndex(),!0)}matchesExistingSession(e,n){if(!n)return!1;let r=E(e),o=E(n);return!!(n.sessionId&&e.id===n.sessionId||o&&o===r||n?.harnessSessionId&&e.harnessSessionId===n.harnessSessionId||n?.name&&e.name===n.name)}findActiveSessionForRef(e,n){let r=this.deps.resolveSession(e);if(r)return r;for(let o of this.deps.sessions.values())if(re(o)===e||E(o)===e||o.harnessSessionId===e||this.matchesExistingSession(o,n))return o}applyPatchToActiveSession(e,n){this.applyControlStatePatch(e,n),this.applySessionMetadataPatch(e,n),this.applyWorktreeMetadataPatch(e,n)}applyControlStatePatch(e,n){let r={lifecycle:n.lifecycle,approvalState:n.approvalState,approvalExecutionState:n.approvalExecutionState,worktreeState:n.worktreeState,runtimeState:n.runtimeState,deliveryState:n.deliveryState,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,pendingPlanApproval:n.pendingPlanApproval,planApprovalContext:n.planApprovalContext,planDecisionVersion:n.planDecisionVersion,actionablePlanDecisionVersion:n.actionablePlanDecisionVersion,canonicalPlanPromptVersion:n.canonicalPlanPromptVersion,approvalPromptRequiredVersion:n.approvalPromptRequiredVersion,approvalPromptVersion:n.approvalPromptVersion,approvalPromptStatus:n.approvalPromptStatus,approvalPromptTransport:n.approvalPromptTransport,approvalPromptMessageKind:n.approvalPromptMessageKind,approvalPromptLastAttemptAt:n.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:n.approvalPromptDeliveredAt,approvalPromptFailedAt:n.approvalPromptFailedAt,planModeApproved:n.planModeApproved,pendingWorktreeDecisionSince:n.pendingWorktreeDecisionSince};if(typeof e.applyControlPatch=="function"){e.applyControlPatch(r);return}this.assignIfDefined(e,"lifecycle",n.lifecycle),this.assignIfDefined(e,"approvalState",n.approvalState),this.assignIfDefined(e,"approvalExecutionState",n.approvalExecutionState),this.assignIfDefined(e,"worktreeState",n.worktreeState),this.assignIfDefined(e,"runtimeState",n.runtimeState),this.assignIfDefined(e,"deliveryState",n.deliveryState),this.assignIfDefined(e,"requestedPermissionMode",n.requestedPermissionMode),this.assignIfDefined(e,"currentPermissionMode",n.currentPermissionMode),this.assignIfDefined(e,"pendingPlanApproval",n.pendingPlanApproval),this.assignIfDefined(e,"planApprovalContext",n.planApprovalContext),this.assignIfDefined(e,"planDecisionVersion",n.planDecisionVersion),this.assignIfDefined(e,"actionablePlanDecisionVersion",n.actionablePlanDecisionVersion),this.assignIfDefined(e,"canonicalPlanPromptVersion",n.canonicalPlanPromptVersion),this.assignIfDefined(e,"approvalPromptRequiredVersion",n.approvalPromptRequiredVersion),this.assignIfDefined(e,"approvalPromptVersion",n.approvalPromptVersion),this.assignIfDefined(e,"approvalPromptStatus",n.approvalPromptStatus),this.assignIfDefined(e,"approvalPromptTransport",n.approvalPromptTransport),this.assignIfDefined(e,"approvalPromptMessageKind",n.approvalPromptMessageKind),this.assignIfDefined(e,"approvalPromptLastAttemptAt",n.approvalPromptLastAttemptAt),this.assignIfDefined(e,"approvalPromptDeliveredAt",n.approvalPromptDeliveredAt),this.assignIfDefined(e,"approvalPromptFailedAt",n.approvalPromptFailedAt),this.setControlFieldIfDefined(e,"planModeApproved",n.planModeApproved)}applySessionMetadataPatch(e,n){this.assignIfDefined(e,"approvalRationale",n.approvalRationale)}applyWorktreeMetadataPatch(e,n){this.assignIfDefined(e,"worktreePath",n.worktreePath),this.assignIfDefined(e,"worktreeBranch",n.worktreeBranch),this.assignIfDefined(e,"worktreePrUrl",n.worktreePrUrl),this.assignIfDefined(e,"worktreePrNumber",n.worktreePrNumber),this.assignIfDefined(e,"worktreeMerged",n.worktreeMerged),this.assignIfDefined(e,"worktreeMergedAt",n.worktreeMergedAt),this.assignIfDefined(e,"worktreeDisposition",n.worktreeDisposition),this.assignIfDefined(e,"worktreePrTargetRepo",n.worktreePrTargetRepo),this.assignIfDefined(e,"worktreePushRemote",n.worktreePushRemote),this.assignIfDefined(e,"worktreeLifecycle",n.worktreeLifecycle),"autoMergeParentSessionId"in n&&(e.autoMergeParentSessionId=n.autoMergeParentSessionId),"autoMergeConflictResolutionAttemptCount"in n&&(e.autoMergeConflictResolutionAttemptCount=n.autoMergeConflictResolutionAttemptCount),"autoMergeResolverSessionId"in n&&(e.autoMergeResolverSessionId=n.autoMergeResolverSessionId)}assignIfDefined(e,n,r){r!==void 0&&(e[n]=r)}setControlFieldIfDefined(e,n,r){r!==void 0&&e.setControlField?.(n,r)}};Pe();var hb=new Set(["starting","running"]),ks=class{constructor(e,n){this.sessions=e;this.store=n}sessions;store;resolveActive(e){let n=this.sessions.get(e);return n||(this.findPreferredMatch(e,r=>r.name===e)??this.findPreferredMatch(e,r=>E(r)===e)??this.findPreferredMatch(e,r=>r.harnessSessionId===e))}getPersistedSession(e){return this.store.getPersistedSession(e)}resolveBackendConversationId(e){let n=this.resolveActive(e);return this.store.resolveBackendConversationId(e,n?E(n)??n.harnessSessionId:void 0)}findPreferredMatch(e,n){let r,o;for(let i of this.sessions.values())n(i,e)&&((!o||i.startedAt>o.startedAt)&&(o=i),hb.has(i.status)&&(!r||i.startedAt>r.startedAt)&&(r=i));return r??o}};Pe();Pe();mt();var vs=class{constructor(e){this.deps=e}deps;async plan(e){let n=re(e)??e.harnessSessionId;if(this.deps.isAlreadyMerged(n))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 r=e.worktreeStrategy;if(!r||r==="off"||r==="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??cn(i),d=this.deps.getWorktreeCompletionState(i,o,s,a);if(d==="no-change")return{kind:"no-change",repoDir:i,worktreePath:o,nativeBackendWorktree:We(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=Dn(i,s,a);return l?{kind:"decision",strategy:r,repoDir:i,worktreePath:o,branchName:s,baseBranch:a,diffSummary:l,sessionRef:n??void 0}:(console.warn(`[SessionManager] Failed to get diff summary for ${s}, skipping merge-back`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}})}};function Pl(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function Ps(t,e={}){let n=e.updatedAt??new Date().toISOString(),r={pendingWorktreeDecisionSince:e.pendingSince??n,lastWorktreeReminderAt:void 0,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision",worktreeLifecycle:Pl(t,{state:"pending_decision",updatedAt:n,notes:e.notes})};return e.clearResolverSessionId&&(r.autoMergeResolverSessionId=void 0),r}function Kg(t,e,n,r={}){let o=r.updatedAt??new Date().toISOString();return{autoMergeConflictResolutionAttemptCount:n,autoMergeResolverSessionId:e,pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,lifecycle:"terminal",worktreeState:"merge_conflict_resolving",worktreeLifecycle:Pl(t,{state:"merge_conflict_resolving",updatedAt:o,notes:r.notes})}}function Vg(t,e={}){let n=e.updatedAt??new Date().toISOString(),r=e.resolvedAt??n,o={worktreeMerged:!0,worktreeMergedAt:e.mergedAt??r,lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:Pl(t,{state:"merged",updatedAt:n,resolvedAt:r,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}mt();var ws=class{constructor(e){this.deps=e;this.actions=new vs({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(n=>typeof n=="string").join(`
146
+ `)}notifyAutoMergeConflictEscalation(e,n,r){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 \`${n}\` was preserved for manual follow-up.`,"",r].join(`
147
+ `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}updatePersistedSessionFor(e,n){for(let r of nt(e))this.deps.updatePersistedSession(r,n)}markPendingDecision(e,n={}){this.updatePersistedSessionFor(e,Ps(e,n))}markAutoMergeConflictResolving(e,n,r){this.updatePersistedSessionFor(e,Kg(e,n,r,{notes:[`resolver_session:${n}`]}))}markMerged(e){this.updatePersistedSessionFor(e,Vg(e,{clearResolverSessionId:!0}))}async handleWorktreeStrategy(e){let n=await this.actions.plan(e);return n.kind==="skip"?n.result:n.kind==="notify"?(this.deps.dispatchSessionNotification(e,{label:n.label,userMessage:n.message}),{notificationSent:!0,worktreeRemoved:!1}):n.kind==="no-change"?this.handleNoChange(e,n.repoDir,n.worktreePath,n.nativeBackendWorktree):n.strategy==="ask"?this.handleAskStrategy(e,n.branchName,n.baseBranch,n.diffSummary):n.strategy==="delegate"?this.handleDelegateStrategy(e,n.branchName,n.baseBranch,n.diffSummary):n.strategy==="auto-merge"?(await this.handleAutoMergeStrategy(e,n.repoDir,n.worktreePath,n.branchName,n.baseBranch,n.diffSummary,n.sessionRef),{notificationSent:!0,worktreeRemoved:!1}):n.strategy==="auto-pr"?this.handleAutoPrStrategy(e,n.baseBranch):{notificationSent:!1,worktreeRemoved:!1}}async handleNoChange(e,n,r,o=We(e)){let i=o?!0:rt(n,r);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:r,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:r,preview:this.deps.getOutputPreview(e),originThreadLine:this.deps.originThreadLine(e)})),{notificationSent:!0,worktreeRemoved:i}}handleAskStrategy(e,n,r,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildAskNotification({session:e,branchName:n,baseBranch:r,diffSummary:o,buttons:this.deps.getWorktreeDecisionButtons(e.id)})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleDelegateStrategy(e,n,r,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildDelegateNotification({session:e,branchName:n,baseBranch:r,diffSummary:o})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleAutoMergeSuccess(e,n,r,o,i,s){Lt(n,r),this.markMerged(e);let d=Fn({kind:"merge",branch:r,base:o,filesChanged:i.filesChanged,insertions:i.insertions,deletions:i.deletions});s.stashPopConflict?d+=`
148
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${s.stashRef??"stash@{0}"}\` in ${n} to review stashed changes.`:s.stashed&&(d+=`
149
+ (Pre-existing changes on ${o} were auto-stashed and restored.)`),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-success",userMessage:d})}async handleInitialAutoMergeConflict(e,n,r,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 ${r}.`);return}let d=this.buildConflictResolverPrompt({session:e,repoDir:n,worktreePath:r,branchName:o,baseBranch:i,mergeError:s});try{let l=await this.deps.spawnConflictResolver({session:e,repoDir:n,worktreePath:r,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,n,r,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 \`${n}\` was preserved for manual follow-up in ${r}.`].join(`
150
+ `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}async handleAutoMergeStrategy(e,n,r,o,i,s,a=re(e)??e.harnessSessionId){this.deps.isAlreadyMerged(a)||e.autoMergeResolverSessionId||await this.deps.enqueueMerge(n,async()=>{if(this.deps.isAlreadyMerged(a))return;let d=this.deps.mergeBranch(n,o,i,"merge",r);if(d.success){this.handleAutoMergeSuccess(e,n,o,i,s,d);return}if(d.rebaseConflict){await this.handleInitialAutoMergeConflict(e,n,r,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,r,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,n){return this.updatePersistedSessionFor(e,{lifecycle:"terminal",worktreeState:"pr_in_progress"}),(await this.deps.runAutoPr(e,n)).success||(this.markPendingDecision(e),this.deps.dispatchSessionNotification(e,{label:"worktree-auto-pr-failed",userMessage:`\u26A0\uFE0F [${e.name}] Auto-PR did not complete. The worktree is preserved for an explicit merge or PR decision.`,buttons:this.deps.getWorktreeDecisionButtons(e.id)})),{notificationSent:!0,worktreeRemoved:!1}}};import{existsSync as Hb,writeFileSync as zb}from"fs";En();import{randomUUID as Sb}from"crypto";function yb(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var Is=class{constructor(e,n){this.onChange=e;this.retentionMs=n}onChange;retentionMs;tokens=new Map;afterChange;replaceAll(e){this.tokens.clear();for(let n of e)this.tokens.set(n.id,n)}clear(){this.tokens.clear(),this.notifyChanged()}listForPersistence(){return[...this.tokens.values()]}createActionToken(e,n,r={}){let o={id:Sb(),sessionId:e,kind:n,createdAt:Date.now(),...r};return this.tokens.set(o.id,o),this.notifyChanged(),o}getActionToken(e){let n=this.tokens.get(e);if(n){if(n.expiresAt!=null&&n.expiresAt<=Date.now()){this.tokens.delete(e),this.notifyChanged();return}return n}}consumeActionToken(e){let n=this.getActionToken(e);if(!(!n||n.consumedAt!=null))return n.consumedAt=Date.now(),this.notifyChanged(),n}deleteActionTokensForSession(e){let n=!1;for(let[r,o]of this.tokens)o.sessionId===e&&(this.tokens.delete(r),n=!0);n&&this.notifyChanged()}deletePlanDecisionTokensForSession(e,n){let r=!1;for(let[o,i]of this.tokens)i.sessionId!==e||!yb(i.kind)||n!=null&&i.planDecisionVersion===n||(this.tokens.delete(o),r=!0);r&&this.notifyChanged()}purgeExpiredActionTokens(e=Date.now()){let n=!1;for(let[r,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(r),n=!0)}n&&this.notifyChanged()}nextExpiryAt(){let e;for(let n of this.tokens.values()){let r=[n.expiresAt,n.consumedAt!=null?n.consumedAt+this.retentionMs:void 0].filter(o=>o!=null&&Number.isFinite(o));for(let o of r)(e==null||o<e)&&(e=o)}return e}setAfterChangeListener(e){this.afterChange=e}notifyChanged(){this.onChange(),this.afterChange?.()}};Pe();Pe();var bs=class{constructor(e){this.indexes=e}indexes;hasRecordedSession(e){return this.indexes.idIndex.has(e)}getLatestPersistedByName(e){let n,r=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>r||d===r&&l>o||d===r&&l===o&&s>i)&&(n=a,r=d,o=l,i=s),s++}return n}resolveBackendConversationId(e,n){if(n)return n;let r=this.indexes.idIndex.get(e);if(r){let s=this.indexes.persisted.get(r);return(s?E(s):void 0)??r}let o=this.getLatestPersistedByName(e);if(o)return E(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(e);if(i){let s=this.indexes.persisted.get(i);return(s?E(s):void 0)??i}if(this.indexes.persisted.has(e)){let s=this.indexes.persisted.get(e);return s?E(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,n){return this.resolveBackendConversationId(e,n)}getPersistedSession(e){let n=this.indexes.idIndex.get(e);if(n)return this.indexes.persisted.get(n);let r=this.getLatestPersistedByName(e);if(r)return r;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,n)=>(n.completedAt??0)-(e.completedAt??0))}};import{existsSync as Kb,mkdirSync as Vb,readFileSync as qb,readdirSync as Il,renameSync as Jg,statSync as Yg,unlinkSync as Xg,writeFileSync as Zg}from"fs";import{tmpdir as bl}from"os";import{dirname as jb,join as Ts}from"path";import{homedir as kb}from"node:os";import{join as vb}from"node:path";function qg(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let n=t.HOME?.trim()||kb();return vb(n,".openclaw")}En();var xs=6,Pb=new Set(["running","completed","failed","killed"]);function ho(t){return!!t&&typeof t=="object"}function Sr(t,e=""){return typeof t=="string"&&t.trim().length>0?t:e}function b(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function He(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function wb(t){return typeof t=="string"&&og.has(t)?t:void 0}function jg(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function Ib(t){return t==="never"||t==="on-request"?"never":void 0}function bb(t){return t==="approve"||t==="ask"||t==="delegate"?t:void 0}function xb(t){if(t==="plan-mode"||t==="codex-first-turn-plan"||t==="soft-plan")return"plan-mode"}function Gg(t){return typeof t=="string"&&os.has(t)?t:void 0}function Ab(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function Rb(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 Tb(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function Mb(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 Cb(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 _b(t){return t==="live"||t==="stopped"?t:void 0}function Eb(t){return t==="not_sent"||t==="sending"||t==="delivered"||t==="fallback_delivered"||t==="failed"?t:void 0}function $b(t){return t==="direct-telegram"?"direct-message":t==="none"||t==="direct-message"||t==="wake-only"?t:void 0}function Ob(t){return t==="none"||t==="canonical_buttons"||t==="explicit_fallback_text"?t:void 0}function Nb(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function Db(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 Fb(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 Hg(t){if(!ho(t))return;let e=b(t.provider),n=b(t.accountId),r=b(t.target),o=b(t.threadId),i=b(t.sessionKey);if(!(!e||!r))return{provider:e,accountId:n,target:r,threadId:o,sessionKey:i}}function Lb(t,e,n){if(ho(t)){let r=b(t.kind),o=b(t.conversationId);if(o&&(r==="claude-code"||r==="codex-app-server"))return{kind:r,conversationId:o,runId:b(t.runId),worktreeId:b(t.worktreeId),worktreePath:b(t.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:n}}function Wb(t){if(!ho(t))return;let e=Cb(t.state),n=b(t.updatedAt);if(!e||!n)return;let r=b(t.resolutionSource);return{state:e,updatedAt:n,resolvedAt:b(t.resolvedAt),resolutionSource:r==="agent_merge"||r==="agent_pr"||r==="strategy_no_change"||r==="lifecycle_resolver"||r==="dismiss"||r==="maintenance"?r:void 0,baseBranch:b(t.baseBranch),targetRepo:b(t.targetRepo),pushRemote:b(t.pushRemote),notes:Array.isArray(t.notes)?t.notes.filter(o=>typeof o=="string"&&o.length>0):void 0}}function Bb(t){let e=new Date(0).toISOString(),n=b(t.worktreeMergedAt)??b(t.worktreeDismissedAt)??b(t.pendingWorktreeDecisionSince)??e;if(t.worktreeMerged===!0)return{state:"merged",updatedAt:n,resolvedAt:b(t.worktreeMergedAt)??n,resolutionSource:"agent_merge",baseBranch:b(t.worktreeBaseBranch),targetRepo:b(t.worktreePrTargetRepo),pushRemote:b(t.worktreePushRemote)};if(t.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:n,resolvedAt:b(t.worktreeDismissedAt)??n,resolutionSource:"dismiss",baseBranch:b(t.worktreeBaseBranch),targetRepo:b(t.worktreePrTargetRepo),pushRemote:b(t.worktreePushRemote)};if(t.worktreeDisposition==="no-change-cleaned")return{state:"no_change",updatedAt:n,resolvedAt:n,resolutionSource:"strategy_no_change",baseBranch:b(t.worktreeBaseBranch),targetRepo:b(t.worktreePrTargetRepo),pushRemote:b(t.worktreePushRemote)};if(t.worktreeDisposition==="pr-opened"||t.worktreeState==="pr_open")return{state:"pr_open",updatedAt:n,baseBranch:b(t.worktreeBaseBranch),targetRepo:b(t.worktreePrTargetRepo),pushRemote:b(t.worktreePushRemote)};if(t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:n,baseBranch:b(t.worktreeBaseBranch),targetRepo:b(t.worktreePrTargetRepo),pushRemote:b(t.worktreePushRemote)};if(t.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:n,baseBranch:b(t.worktreeBaseBranch),targetRepo:b(t.worktreePrTargetRepo),pushRemote:b(t.worktreePushRemote)};if(b(t.worktreePath)||b(t.worktreeBranch))return{state:"provisioned",updatedAt:n,baseBranch:b(t.worktreeBaseBranch),targetRepo:b(t.worktreePrTargetRepo),pushRemote:b(t.worktreePushRemote)}}function Ub(t){if(typeof t=="string"&&Pb.has(t))return t==="running"?"killed":t}function zg(t){if(!ho(t))return;let e=Sr(t.harnessSessionId);if(!e)return;let n=Ub(t.status);if(!n)return;let r=t.status==="running",o=b(t.worktreePath),i=b(t.worktreeBranch),s=b(t.originChannel),a=typeof t.originThreadId=="string"||typeof t.originThreadId=="number"?t.originThreadId:void 0,d=b(t.originSessionKey),l=Hg(t.route);if(!l)return;let p=sr({route:l,originChannel:s,originThreadId:a,originSessionKey:d});if(!p||o&&!i)return;let f=b(t.harness),y=Lb(t.backendRef,f,e),g=Wb(t.worktreeLifecycle)??Bb(t);return{sessionId:b(t.sessionId),harnessSessionId:e,backendRef:y,name:Sr(t.name,e),prompt:Sr(t.prompt),workdir:Sr(t.workdir,"(unknown)"),model:b(t.model),reasoningEffort:wb(t.reasoningEffort),createdAt:He(t.createdAt),completedAt:He(t.completedAt),status:n,lifecycle:r?"suspended":Rb(t.lifecycle),approvalState:Tb(t.approvalState),worktreeState:Mb(t.worktreeState),runtimeState:r?"stopped":_b(t.runtimeState),deliveryState:Nb(t.deliveryState),completionWakeIssuedAt:b(t.completionWakeIssuedAt),completionWakeSucceededAt:b(t.completionWakeSucceededAt),completionWakeFailedAt:b(t.completionWakeFailedAt),completionWakeSummaryRequired:t.completionWakeSummaryRequired===!0?!0:void 0,killReason:Ab(t.killReason),costUsd:typeof t.costUsd=="number"&&Number.isFinite(t.costUsd)?t.costUsd:0,originAgentId:b(t.originAgentId),originChannel:s,originThreadId:a,originSessionKey:d,route:p,outputPath:b(t.outputPath),harness:f,requestedPermissionMode:jg(t.requestedPermissionMode),currentPermissionMode:jg(t.currentPermissionMode),approvalExecutionState:Db(t.approvalExecutionState),approvalRationale:b(t.approvalRationale),planModeApproved:t.planModeApproved===!0,pendingPlanApproval:t.pendingPlanApproval===!0,planApprovalContext:xb(t.planApprovalContext),planDecisionVersion:He(t.planDecisionVersion),actionablePlanDecisionVersion:He(t.actionablePlanDecisionVersion),canonicalPlanPromptVersion:He(t.canonicalPlanPromptVersion),approvalPromptRequiredVersion:He(t.approvalPromptRequiredVersion),approvalPromptVersion:He(t.approvalPromptVersion),approvalPromptStatus:Eb(t.approvalPromptStatus),approvalPromptTransport:$b(t.approvalPromptTransport),approvalPromptMessageKind:Ob(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:b(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:b(t.approvalPromptDeliveredAt),approvalPromptFailedAt:b(t.approvalPromptFailedAt),planApproval:bb(t.planApproval),codexApprovalPolicy:Ib(t.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:Gg(t.worktreeStrategy),worktreeMerged:typeof t.worktreeMerged=="boolean"?t.worktreeMerged:void 0,worktreeMergedAt:b(t.worktreeMergedAt),worktreePrUrl:b(t.worktreePrUrl),worktreePrNumber:He(t.worktreePrNumber),pendingWorktreeDecisionSince:b(t.pendingWorktreeDecisionSince),lastWorktreeReminderAt:b(t.lastWorktreeReminderAt),worktreeBaseBranch:b(t.worktreeBaseBranch),worktreePrTargetRepo:b(t.worktreePrTargetRepo),autoMergeParentSessionId:b(t.autoMergeParentSessionId),autoMergeConflictResolutionAttemptCount:He(t.autoMergeConflictResolutionAttemptCount),autoMergeResolverSessionId:b(t.autoMergeResolverSessionId),worktreePushRemote:b(t.worktreePushRemote),worktreeDecisionSnoozedUntil:b(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:b(t.worktreeDismissedAt),worktreeLifecycle:g,resumable:r?!0:t.resumable===!0}}function Qg(t){if(!ho(t))return;let e=Fb(t.kind),n=Sr(t.id),r=Sr(t.sessionId),o=He(t.createdAt);if(!(!n||!r||!e||o==null))return{id:n,sessionId:r,kind:e,createdAt:o,planDecisionVersion:He(t.planDecisionVersion),expiresAt:He(t.expiresAt),consumedAt:He(t.consumedAt),optionIndex:He(t.optionIndex),label:b(t.label),targetUrl:b(t.targetUrl),route:Hg(t.route),launchName:b(t.launchName),launchPrompt:b(t.launchPrompt),launchWorkdir:b(t.launchWorkdir),launchWorktreeStrategy:Gg(t.launchWorktreeStrategy)}}function As(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 wl(t){return!!t&&typeof t=="object"}function xl(t){return t instanceof Error?t.message:String(t)}function eh(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||Ts(qg(t),"code-agent-sessions.json")}function th(t,e,n){try{Vb(jb(t),{recursive:!0});let r=t+".tmp";Zg(r,JSON.stringify({schemaVersion:xs,sessions:e,actionTokens:n},null,2),"utf-8"),Jg(r,t)}catch(r){console.warn(`[SessionStore] Failed to save session index: ${xl(r)}`)}}function Rs(t,e){try{if(!Kb(t))return;let n=`${t}.legacy-${Date.now()}.json`;Jg(t,n),console.warn(`[SessionStore] Breaking upgrade: archived ${e} session store to ${n}. Legacy sessions are not loaded by this release.`)}catch(n){console.warn(`[SessionStore] Failed to archive legacy session store: ${xl(n)}`)}}function Gb(t,e){try{if(e.length===0)return;let n=`${t}.codex-sdk-legacy-${Date.now()}.json`;Zg(n,JSON.stringify(e,null,2),"utf-8"),console.warn(`[SessionStore] Breaking Codex transport upgrade: archived ${e.length} legacy Codex SDK session(s) to ${n}. They are not loaded by the App Server backend.`)}catch(n){console.warn(`[SessionStore] Failed to archive legacy Codex SDK sessions: ${xl(n)}`)}}function nh(t,e){try{let n=bl(),r=Il(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r)try{let i=Ts(n,o),s=Yg(i).mtimeMs;t-s>e&&Xg(i)}catch{}}catch{}}function rh(t,e){try{let n=bl(),r=Il(n).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of r)try{let s=Ts(n,i),a=Yg(s).mtimeMs+e;if(a<=t)return t;o=o==null?a:Math.min(o,a)}catch{}return o}catch{return}}function oh(t){try{let e=new Set(t),n=bl(),r=Il(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r){let i=Ts(n,o);if(!e.has(i))try{Xg(i)}catch{}}}catch{}}function ih(t){let{indexPath:e,clearAll:n,indexPersistedEntry:r,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:s}=t;try{let a=qb(e,"utf-8"),d=JSON.parse(a);if(Array.isArray(d)){Rs(e,"legacy array store"),s();return}if(!wl(d)||d.schemaVersion!==xs&&d.schemaVersion!==4){Rs(e,`schema mismatch (expected v${xs})`),s();return}let l=Array.isArray(d.sessions)?d.sessions:[],p=[];for(let y of l){if(wl(y)&&y.harness==="codex"){let k=wl(y.backendRef)?y.backendRef:void 0;if((typeof k?.kind=="string"?k.kind:void 0)!=="codex-app-server"){p.push(y);continue}}let g=zg(y);if(!g){n(),Rs(e,"invalid v4 session entry"),s();return}r(g)}p.length>0&&(Gb(e,p),s());let f=Array.isArray(d.actionTokens)?d.actionTokens:[];for(let y of f){let g=Qg(y);if(!g){n(),Rs(e,"invalid v4 action token"),s();return}o(g)}i()}catch{}}var Qb=new Set(["completed","failed","killed"]),Al=1440*60*1e3;function Jb(t){return t instanceof Error?t.message:String(t)}var Ms=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;backendIdIndex=new Map;actionTokens;actionTokenStore;indexPath;queries;constructor(e={}){let n=e.env??process.env;this.indexPath=e.indexPath??eh(n),this.actionTokenStore=new Is(()=>this.saveIndex(),Al),this.actionTokens=this.actionTokenStore.tokens,this.queries=new bs({persisted:this.persisted,idIndex:this.idIndex,nameIndex:this.nameIndex,backendIdIndex:this.backendIdIndex}),n.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){ih({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(){th(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){As(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){return e.backendRef??{kind:Hd(e)==="codex"?"codex-app-server":"claude-code",conversationId:e.harnessSessionId}}indexPersistedEntry(e){let n=this.getEntryStorageKey(e);this.persisted.set(n,e),e.sessionId&&this.idIndex.set(e.sessionId,n),e.name&&this.nameIndex.set(e.name,n);let r=E(e);r&&this.backendIdIndex.set(r,n)}removePersistedIndexes(e){let n=this.getEntryStorageKey(e);this.persisted.delete(n);for(let[r,o]of this.idIndex)o===n&&this.idIndex.delete(r);for(let[r,o]of this.nameIndex)o===n&&this.nameIndex.delete(r);for(let[r,o]of this.backendIdIndex)o===n&&this.backendIdIndex.delete(r)}markRunning(e){if(!e.harnessSessionId)return;let n=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1},r=sr({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!r)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:r,harness:e.harnessName,requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:n.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};As(o),this.indexPersistedEntry(o),this.saveIndex()}hasRecordedSession(e){return this.queries.hasRecordedSession(e)}persistTerminal(e){if(!e.harnessSessionId)return;let n=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1},r=sr({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!r)return;let o;try{let s=mr(e.id);if(Hb(s))o=s;else{let a=e.getOutput().join(`
151
+ `);a.length>0&&(zb(s,a,"utf-8"),o=s)}}catch(s){console.warn(`[SessionStore] Failed to write output file for session ${e.id}: ${Jb(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:r,outputPath:o,harness:e.harnessName,requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:n.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};As(i),this.indexPersistedEntry(i),this.saveIndex()}getLatestPersistedByName(e){return this.queries.getLatestPersistedByName(e)}resolveBackendConversationId(e,n){return this.queries.resolveBackendConversationId(e,n)}resolveHarnessSessionId(e,n){return this.queries.resolveHarnessSessionId(e,n)}getPersistedSession(e){return this.queries.getPersistedSession(e)}listPersistedSessions(){return this.queries.listPersistedSessions()}cleanupTmpOutputFiles(e){this.actionTokenStore.purgeExpiredActionTokens(e),nh(e,Al)}getNextTmpOutputCleanupAt(e){return rh(e,Al)}evictOldestPersisted(e){let n=this.listPersistedSessions();if(n.length<=e)return[];let r=n.slice(e);for(let o of r)this.removePersistedIndexes(o);return this.saveIndex(),r}shouldGcActiveSession(e,n,r){return!e.completedAt||!Qb.has(e.status)?!1:n-e.completedAt>r}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 n of this.persisted.values())if(n.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(){oh(this.getReferencedOutputPaths())}};var Yb=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 n=e.costUsd??0,r=e.status;this.metrics.totalCostUsd+=n;let o=new Date(e.completedAt??e.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+n),Yb.has(r)&&this.metrics.sessionsByStatus[r]++,e.completedAt){let i=e.completedAt-e.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||n>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:e.id,name:e.name,costUsd:n,prompt:Ce(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*as ah from"child_process";var sh=5e3,Xb={execFile:ah.execFile},Sn=class extends Error{constructor(e){super(e),this.name="MissingRuntimeDirectNotificationCapabilityError"}},_s=class{constructor(e=Xb.execFile){this.execFile=e}execFile;async send(e,n,r){j("direct_send_started",{...gt(e),messageTextLength:n.length,...de(r)});try{await this.sendViaRuntime(e,n,r),j("direct_send_succeeded",{...gt(e),deliveryPath:"runtime",...de(r)});return}catch(o){if(!(o instanceof Sn))throw j("direct_send_failed",{...gt(e),deliveryPath:"runtime",...de(r),error:Rl(o)}),o;j("direct_send_runtime_capability_missing",{...gt(e),deliveryPath:"runtime",...de(r),reason:o.message}),await this.sendViaBoundedCliFallback(e,n,r,o.message),j("direct_send_succeeded",{...gt(e),deliveryPath:"cli-fallback",...de(r)})}}async sendViaRuntime(e,n,r){let o=Ei(),i=If(),s=o?.channel?.outbound?.loadAdapter;if(!o)throw new Sn("OpenClaw plugin runtime is unavailable for direct notification delivery");if(i==null)throw new Sn("OpenClaw runtime config snapshot is unavailable for direct notification delivery");if(!o.channel)throw new Sn(`OpenClaw plugin runtime channel surface is unavailable for direct notification delivery (runtimeVersion=${Tl(o)})`);if(!o.channel.outbound)throw new Sn(`OpenClaw plugin runtime channel outbound surface is unavailable for direct notification delivery (runtimeVersion=${Tl(o)})`);if(!s)throw new Sn(`OpenClaw plugin runtime channel outbound loadAdapter is unavailable for direct notification delivery (runtimeVersion=${Tl(o)})`);let a=await s(e.channel);if(!a)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" is unavailable`);let d=Es(r);if(j("runtime_adapter_loaded",{...gt(e),adapterHasRenderPresentation:typeof a.renderPresentation=="function",adapterHasSendPayload:typeof a.sendPayload=="function",adapterHasSendText:typeof a.sendText=="function",...de(r),...d?fl(d):{}}),d){await this.sendPresentation(a,i,e,n,d);return}if(!a.sendText)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" cannot send text`);await a.sendText({cfg:i,to:e.target,text:n,accountId:e.accountId,threadId:e.threadId})}async sendPresentation(e,n,r,o,i){let s={text:o,presentation:i};j("presentation_render_started",{...gt(r),messageTextLength:o.length,adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...fl(i)});let a={cfg:n,to:r.target,text:o,payload:s,accountId:r.accountId,threadId:r.threadId},d=e.renderPresentation?await e.renderPresentation({payload:s,presentation:i,ctx:a}):s;if(j("presentation_render_completed",{...gt(r),adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...gl(d)}),!d||typeof d!="object"||!e.sendPayload)throw new Error(`OpenClaw outbound adapter for channel "${r.channel}" cannot preserve interactive presentation`);let l=await e.sendPayload({...a,payload:d});j("presentation_send_payload_completed",{...gt(r),...gl(d),...kg(l)})}sendViaBoundedCliFallback(e,n,r,o){return new Promise((i,s)=>{let a=Zb(e,n,r);j("direct_send_cli_fallback_started",{...gt(e),deliveryPath:"cli-fallback",reason:o,messageTextLength:n.length,...de(r)}),this.execFile("openclaw",a,{timeout:sh,killSignal:"SIGKILL"},(d,l,p)=>{if(!d){j("direct_send_cli_fallback_completed",{...gt(e),deliveryPath:"cli-fallback",...de(r)}),i();return}let f=p?.trim()?` | stderr: ${p.trim()}`:"";j("direct_send_cli_fallback_failed",{...gt(e),deliveryPath:"cli-fallback",...de(r),error:Rl(d),stderrLength:p?.length}),s(new Error(`${o}; bounded openclaw message send fallback failed within ${sh}ms timeout: ${Rl(d)}${f}`))})})}};function gt(t){return{channel:t.channel,target:t.target,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey}}function Zb(t,e,n){let r=Es(n),o=["message","send","--channel",t.channel,"--target",t.target,"--message",e];return t.accountId&&o.push("--account",t.accountId),t.threadId&&o.push("--thread-id",t.threadId),r&&o.push("--presentation",JSON.stringify(r)),o}function Rl(t){return t instanceof Error?t.message:String(t)}function Tl(t){if(!t||typeof t!="object")return"unknown";let e=t.version;return typeof e=="string"&&e.trim()?e:"unknown"}function Es(t){let e=(t??[]).filter(n=>Array.isArray(n)&&n.length>0).map(n=>({type:"buttons",buttons:n.map(r=>({label:r.label,value:ex(r.callbackData),...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function ex(t){return t.startsWith(`${ot}:`)?t:`${ot}:${t}`}import*as dh from"child_process";var Ml=3e4,tx=2e3,nx=2e4,ht=4;function So(t){return t instanceof Error?t.message:String(t)}function rx(){return new Error(`Dispatch timed out after ${Ml}ms`)}function ox(t){if(!(t instanceof Error))return!1;let e=t;return e.killed===!0&&e.signal==="SIGKILL"}var ix={execFile:dh.execFile},$s=class{pendingRetryTimers=new Map;orderedDispatchTails=new Map;disposed=!1;clearPendingRetries(){for(let e of this.pendingRetryTimers.values())for(let n of e)clearTimeout(n.timer),n.onCleared?.();this.pendingRetryTimers.clear()}clearRetryTimersForSession(e){let n=this.pendingRetryTimers.get(e);if(n){for(let r of n)clearTimeout(r.timer),r.onCleared?.();this.pendingRetryTimers.delete(e)}}dispose(){this.disposed=!0,this.clearPendingRetries(),this.orderedDispatchTails.clear()}execute(e,n,r=1){if(!this.disposed){if(r===1&&n.orderingKey){this.enqueueOrderedDispatch(n.orderingKey,o=>this.executeNow(e,n,o,r));return}this.executeNow(e,n,void 0,r)}}executePromise(e,n,r=1){if(!this.disposed){if(r===1&&n.orderingKey){this.enqueueOrderedDispatch(n.orderingKey,o=>this.executePromiseNow(e,n,o,r));return}this.executePromiseNow(e,n,void 0,r)}}executeNow(e,n,r,o=1){if(this.disposed){r?.();return}let i=Date.now();o===1&&n.onStarted?.(),this.log("info","dispatch_started",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:ht}),ix.execFile("openclaw",e,{timeout:Ml,killSignal:"SIGKILL"},(s,a,d)=>{if(this.disposed){r?.();return}let l=Date.now()-i;if(!s){this.log("info","dispatch_succeeded",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:l}),n.onSuccess?.(),r?.();return}let p=d?.trim()?` | stderr: ${d.trim()}`:"";if(n.target==="message.send"&&ox(s)){this.log("error","dispatch_failed",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:l,error:`${So(s)}${p}`,terminal:!0,ambiguousResult:!0}),n.onAmbiguousResult?.(),r?.();return}if(o>=ht||n.terminalOnFailure===!0){this.log("error","dispatch_failed",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:l,error:`${So(s)}${p}`,terminal:!0}),n.onFinalFailure?.(),r?.();return}let y=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:l,retryDelayMs:y,error:`${So(s)}${p}`});let g={timer:setTimeout(()=>{let k=this.pendingRetryTimers.get(n.sessionId);k&&(k.delete(g),k.size===0&&this.pendingRetryTimers.delete(n.sessionId)),this.executeNow(e,n,r,o+1)},y),onCleared:r};g.timer.unref?.(),this.pendingRetryTimers.has(n.sessionId)||this.pendingRetryTimers.set(n.sessionId,new Set),this.pendingRetryTimers.get(n.sessionId).add(g)})}executePromiseNow(e,n,r,o=1){if(this.disposed){r?.();return}let i=Date.now();o===1&&n.onStarted?.(),this.log("info","dispatch_started",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:ht}),this.executePromiseWithTimeout(e).then(()=>{if(this.disposed){r?.();return}let s=Date.now()-i;this.log("info","dispatch_succeeded",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:s}),n.onSuccess?.(),r?.()}).catch(s=>{if(this.disposed){r?.();return}let a=Date.now()-i;if(o>=ht||n.terminalOnFailure===!0){this.log("error","dispatch_failed",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:a,error:So(s),terminal:!0,...n.terminalOnFailure===!0&&o<ht?{terminalReason:"non_retryable"}:{}}),n.onFinalFailure?.(),r?.();return}let d=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:n.label,sessionId:n.sessionId,target:n.target,phase:n.phase,messageKind:n.messageKind,route:n.routeSummary,...n.dispatchContext,attempt:o,maxAttempts:ht,elapsedMs:a,retryDelayMs:d,error:So(s)});let l={timer:setTimeout(()=>{let p=this.pendingRetryTimers.get(n.sessionId);p&&(p.delete(l),p.size===0&&this.pendingRetryTimers.delete(n.sessionId)),this.executePromiseNow(e,n,r,o+1)},d),onCleared:r};l.timer.unref?.(),this.pendingRetryTimers.has(n.sessionId)||this.pendingRetryTimers.set(n.sessionId,new Set),this.pendingRetryTimers.get(n.sessionId).add(l)})}executePromiseWithTimeout(e){return new Promise((n,r)=>{let o=!1,i=setTimeout(()=>{o||(o=!0,r(rx()))},Ml);i.unref?.(),Promise.resolve().then(e).then(()=>{o||(o=!0,clearTimeout(i),n())}).catch(s=>{o||(o=!0,clearTimeout(i),r(s))})})}retryDelayMs(e){let n=Math.max(0,e-1),r=tx*2**n;return Math.min(r,nx)}enqueueOrderedDispatch(e,n){let o=(this.orderedDispatchTails.get(e)??Promise.resolve()).catch(()=>{}).then(()=>{if(!this.disposed)return new Promise(i=>{let s=!1;n(()=>{s||(s=!0,i())})})});this.orderedDispatchTails.set(e,o),o.finally(()=>{this.orderedDispatchTails.get(e)===o&&this.orderedDispatchTails.delete(e)})}log(e,n,r){let o=`[WakeDispatcher] ${JSON.stringify({event:n,...r})}`;if(e==="error"){console.error(o);return}console.info(o)}};En();var Os=class{resolve(e){let n=fi(e);if(!(!n?.provider||!n.target))return{channel:n.provider,target:n.target,accountId:n.accountId,threadId:n.threadId,sessionKey:n.sessionKey}}summary(e){if(!e)return"system";let n=e.accountId?`|${e.accountId}`:"",r=e.threadId?`#${e.threadId}`:"";return`${e.channel}${n}|${e.target}${r}`}};import{randomUUID as sx}from"crypto";var Ns=class{constructor(e={}){this.options=e}options;buildChatSendArgs(e,n,r){return["gateway","call","chat.send","--expect-final","--timeout","30000","--params",JSON.stringify({sessionKey:e,message:n,deliver:r,idempotencyKey:sx()})]}buildDirectNotificationArgs(e,n,r){let o=Es(r),i=["message","send","--channel",e.channel,"--target",e.target,"--message",n];return e.accountId&&i.push("--account",e.accountId),e.threadId&&i.push("--thread-id",e.threadId),o&&i.push("--presentation",JSON.stringify(o)),i}buildSystemEventArgs(e){return["system","event","--text",e,"--mode","now"]}};var Ds=class{routes=new Os;transport;directNotifications;executor=new $s;constructor(e={}){this.transport=e.transport??new Ns(e.transportOptions),this.directNotifications=e.directNotifications===void 0?new _s:e.directNotifications}clearPendingRetries(){this.executor.clearPendingRetries()}clearRetryTimersForSession(e){this.executor.clearRetryTimersForSession(e)}dispose(){this.executor.dispose()}buildDispatchContext(e){let n=e.buttons??[],r=n.flat();return{transportRoute:e.routeSummary,transportChannel:e.route?.channel??"system",transportTarget:e.route?.target??"system",transportAccountId:e.route?.accountId,transportThreadId:e.route?.threadId,transportSessionKey:e.route?.sessionKey,messageTextLength:e.text.length,buttonsPresent:r.length>0,buttonRows:n.length||void 0,buttonCount:r.length||void 0,buttonLabels:r.length>0?r.map(o=>o.label):void 0,maxCallbackDataLength:r.length>0?Math.max(...r.map(o=>o.callbackData.length)):void 0}}sendWake(e,n,r,o,i,s){let a=this.routes.resolve(e),d=a?.sessionKey?.trim();if(!d){this.executor.execute(this.transport.buildSystemEventArgs(n),{label:`${r}-system`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:n}),onSuccess:s,onFinalFailure:i});return}this.executor.execute(this.transport.buildChatSendArgs(d,n,!0),{label:r,sessionId:e.id,target:"chat.send",phase:o,routeSummary:`session:${d}`,messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:`session:${d}`,route:a,text:n}),onSuccess:s,onFinalFailure:()=>{this.executor.execute(this.transport.buildSystemEventArgs(n),{label:`${r}-fallback`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:n}),onSuccess:s,onFinalFailure:i})}})}sendUserNotification(e,n,r,o,i,s,a=!1){let d=!!o?.some(g=>Array.isArray(g)&&g.length>0),l=this.routes.resolve(e);j("wake_notify_selected",{sessionId:e.id,sessionName:e.name,label:r,messageTextLength:n.length,requireDirectDelivery:a,hasDirectNotificationTransport:!!this.directNotifications,routeSummary:l?this.routes.summary(l):"system",channel:l?.channel,target:l?.target,accountId:l?.accountId,threadId:l?.threadId,sessionKey:l?.sessionKey,...de(o)});let p=l?`notify:${l.channel}|${l.accountId??""}|${l.target}|${l.threadId??""}`:`notify:system:${e.id}`;if(!l){if(j("wake_notify_no_direct_route",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:d,...de(o)}),a){console.warn(`[WakeDispatcher] Direct notification "${r}" for session ${e.id} has no direct route; reporting delivery failure instead of using system fallback.`),i?.();return}if(d){console.warn(`[WakeDispatcher] Interactive notification "${r}" 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(n),{label:`${r}-notify-system`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:n,buttons:o}),orderingKey:p,onSuccess:s,onFinalFailure:i});return}let f=()=>{if(j("wake_notify_direct_failed",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:d,channel:l.channel,target:l.target,accountId:l.accountId,threadId:l.threadId,sessionKey:l.sessionKey,...de(o)}),a){console.warn(`[WakeDispatcher] Direct notification "${r}" for session ${e.id} failed direct delivery; reporting delivery failure instead of using system fallback.`),i?.();return}if(d){console.warn(`[WakeDispatcher] Interactive notification "${r}" for session ${e.id} failed direct delivery; refusing text-only fallback because buttons would be lost.`),i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(n),{label:`${r}-notify-fallback`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:n}),orderingKey:p,onSuccess:s,onFinalFailure:i})},y={label:`${r}-notify`,sessionId:e.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(l),messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:this.routes.summary(l),route:l,text:n,buttons:o}),orderingKey:p,onSuccess:s,onAmbiguousResult:f,onFinalFailure:f,terminalOnFailure:this.directNotifications?!0:void 0};if(this.directNotifications){j("wake_notify_dispatching_direct_runtime",{sessionId:e.id,sessionName:e.name,label:r,channel:l.channel,target:l.target,accountId:l.accountId,threadId:l.threadId,sessionKey:l.sessionKey,...de(o)}),this.executor.executePromise(()=>this.directNotifications.send(l,n,o),y);return}j("wake_notify_dispatching_cli_message_send",{sessionId:e.id,sessionName:e.name,label:r,channel:l.channel,target:l.target,accountId:l.accountId,threadId:l.threadId,sessionKey:l.sessionKey,...de(o)}),this.executor.execute(this.transport.buildDirectNotificationArgs(l,n,o),y)}sendUserNotificationSequence(e,n,r,o,i,s=!1){let a=n.map(l=>({text:l.text.trim(),buttons:l.buttons})).filter(l=>l.text.length>0);if(a.length===0){o?.();return}j("wake_notify_sequence_started",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:a.length,buttonChunkIndexes:a.map((l,p)=>l.buttons?.some(f=>Array.isArray(f)&&f.length>0)?p+1:void 0).filter(l=>typeof l=="number"),requireDirectDelivery:s});let d=l=>{let p=a[l];if(!p){j("wake_notify_sequence_succeeded",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:a.length}),i?.();return}let f=l===0?o:i;j("wake_notify_sequence_chunk_selected",{sessionId:e.id,sessionName:e.name,label:r,chunkIndex:l+1,chunkCount:a.length,messageTextLength:p.text.length,failureHandler:l===0?"all-failed":"sequence-success",...de(p.buttons)}),this.sendUserNotification(e,p.text,`${r}-part-${l+1}`,p.buttons,f,()=>d(l+1),s)};d(0)}dispatchSessionNotification(e,n){let r=n.hooks,o=n.wakeMessageOnNotifySuccess!=null||n.wakeMessageOnNotifyFailed!=null,i=n.notifyUser??(n.wakeMessage?"on-wake-fallback":"always"),s=(n.userMessages?.length?n.userMessages:n.userMessage?.trim()?[{text:n.userMessage.trim(),buttons:n.buttons}]:[]).map(l=>({text:l.text.trim(),buttons:l.buttons})).filter(l=>l.text.length>0),a=s[0]?.text,d=n.wakeMessage?.trim();if(o){let l=n.wakeMessageOnNotifySuccess?.trim(),p=n.wakeMessageOnNotifyFailed?.trim(),f=k=>{k&&(r?.onWakeStarted?.(),this.sendWake(e,k,`${n.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded))},y=()=>{r?.onNotifySucceeded?.(),l&&f(l)},g=p?()=>{r?.onNotifyFailed?.(),n.onUserNotifyFailed?.(),f(p)}:()=>{r?.onNotifyFailed?.(),n.onUserNotifyFailed?.()};s.length>0?(r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,g,y,n.requireDirectUserNotification===!0)):g();return}i==="always"&&s.length>0&&(r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,()=>{r?.onNotifyFailed?.(),n.onUserNotifyFailed?.()},()=>r?.onNotifySucceeded?.(),n.requireDirectUserNotification===!0)),d&&(r?.onWakeStarted?.(),i==="on-wake-fallback"&&s.length>0&&!this.routes.resolve(e)?.sessionKey&&(r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,()=>{r?.onNotifyFailed?.(),n.onUserNotifyFailed?.()},()=>r?.onNotifySucceeded?.())),this.sendWake(e,d,`${n.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded))}};var Fs=class{constructor(e,n){this.actionTokens=e;this.isGitHubCliAvailable=n}actionTokens;isGitHubCliAvailable;createActionToken(e,n,r={}){return this.actionTokens.createActionToken(e,n,{expiresAt:Date.now()+10080*60*1e3,...r})}consumeActionToken(e){return this.actionTokens.consumeActionToken(e)}getActionToken(e){return this.actionTokens.getActionToken(e)}clearPlanDecisionTokens(e,n){this.actionTokens.deletePlanDecisionTokensForSession(e,n)}makeActionButton(e,n,r,o={}){let i=this.createActionToken(e,n,{label:r,...o});return{label:r,callbackData:i.id,style:this.resolveButtonStyle(n)}}resolveButtonStyle(e){switch(e){case"plan-approve":case"worktree-create-pr":case"worktree-update-pr":case"monitor-start-plan":return"primary";case"worktree-merge":case"session-resume":case"session-restart":return"success";case"plan-reject":case"worktree-dismiss":return"danger";default:return"secondary"}}getWorktreeDecisionButtons(e,n){if(!n)return[];let r=[],o=[this.makeActionButton(e,"worktree-merge","Merge")];if(this.isGitHubCliAvailable())n.worktreePrUrl?(o.push(this.makeActionButton(e,"worktree-view-pr","View PR",{targetUrl:n.worktreePrUrl})),r.push(o),r.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")),r.push(o),r.push([this.makeActionButton(e,"worktree-decide-later","Later"),this.makeActionButton(e,"worktree-dismiss","Discard")]));else return r.push([...o,this.makeActionButton(e,"worktree-decide-later","Later")]),r.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),r;return n.worktreePrUrl&&r.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),r}getPlanApprovalButtons(e,n){let r=[[this.makeActionButton(e,"plan-approve","Approve",{planDecisionVersion:n?.planDecisionVersion}),this.makeActionButton(e,"plan-request-changes","Revise",{planDecisionVersion:n?.planDecisionVersion}),this.makeActionButton(e,"plan-reject","Reject",{planDecisionVersion:n?.planDecisionVersion})]];return j("plan_approval_buttons_created",{sessionId:e,planDecisionVersion:n?.planDecisionVersion,...de(r)}),r}getResumeButtons(e,n){let r=[];return n.isExplicitlyResumable&&r.push(this.makeActionButton(e,"session-resume","Resume")),r.push(this.makeActionButton(e,"view-output","View output")),[r]}getQuestionButtons(e,n){if(n.length!==0)return[n.map((r,o)=>this.makeActionButton(e,"question-answer",r.label,{optionIndex:o}))]}getMonitorReportButtons(e){let{reportId:n,route:r,planName:o,planPrompt:i,planWorkdir:s,planWorktreeStrategy:a}=e,d=[[this.makeActionButton(n,"monitor-start-plan","Start Plan",{route:r,launchName:o,launchPrompt:i,launchWorkdir:s,launchWorktreeStrategy:a}),this.makeActionButton(n,"monitor-dismiss","Dismiss",{route:r})]];return j("monitor_report_buttons_created",{reportId:n,planName:o,channel:r.provider,target:r.target,accountId:r.accountId,threadId:r.threadId,sessionKey:r.sessionKey,planPromptLength:i.length,planWorkdirLength:s.length,planWorktreeStrategy:a,...de(d)}),d}};Pe();var Ls=class{constructor(e,n){this.wakeDispatcher=e;this.applyPersistedPatch=n}wakeDispatcher;applyPersistedPatch;dispatch(e,n){let r=this.getDeliveryRef(e),o=this.buildCompletionWakePatch(n),i=!!(n.wakeMessage?.trim()||n.wakeMessageOnNotifySuccess?.trim()),s=!!(n.wakeMessage?.trim()||n.wakeMessageOnNotifyFailed?.trim()),a={onNotifyStarted:()=>{this.applyDeliveryState(r,"notifying"),n.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{this.applyDeliveryState(r,i?"wake_pending":"idle"),n.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{this.applyDeliveryState(r,s?"wake_pending":"failed"),n.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyPersistedPatchWithCompletionWake(r,"wake_pending",o,{completionWakeIssuedAt:new Date().toISOString(),completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0}),n.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{this.applyPersistedPatchWithCompletionWake(r,"idle",o,{completionWakeSucceededAt:new Date().toISOString(),completionWakeFailedAt:void 0}),n.hooks?.onWakeSucceeded?.()},onWakeFailed:()=>{this.applyPersistedPatchWithCompletionWake(r,"failed",o,{completionWakeFailedAt:new Date().toISOString()}),n.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(e,{...n,hooks:a})}notifyWorktreeOutcome(e,n){this.dispatch(e,{label:"worktree-outcome",userMessage:n,notifyUser:"always"})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(e){return re(e)??E(e)??""}applyDeliveryState(e,n){!e||!n||this.applyPersistedPatch(e,{deliveryState:n})}applyPersistedPatchWithCompletionWake(e,n,r,o){!e||!n||this.applyPersistedPatch(e,r?{deliveryState:n,...r,...o}:{deliveryState:n})}buildCompletionWakePatch(e){if(!(e.label!=="completed"||e.completionWakeSummaryRequired!==!0))return{completionWakeSummaryRequired:!0}}};mt();import{existsSync as ax}from"fs";var Ws=class{getCompletionState(e,n,r,o){return tl(e,r,o)?"has-commits":tl(e,o,r)?"base-advanced":fr(n)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(e,n,r){if(!e.worktreePath||!e.workdir||!ax(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&&n-i>=r}};var Bs=class{constructor(e,n,r,o){this.pendingQuestions=e;this.dispatchSessionNotification=n;this.clearWaitingTimestamp=r;this.getQuestionButtons=o}pendingQuestions;dispatchSessionNotification;clearWaitingTimestamp;getQuestionButtons;async handleAskUserQuestion(e,n){let i=n?.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}`,p=[`[ASK USER QUESTION] Session "${e.name}" has a question requiring user input.`,"",`Question: ${s.question}`,...a.length>0?["Options:",...a.map((f,y)=>` ${y+1}. ${f.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
152
+ `);return new Promise((f,y)=>{let g=setTimeout(()=>{this.pendingQuestions.delete(e.id),y(new Error(`AskUserQuestion timed out after 600s for session "${e.name}"`))},6e5);g.unref?.(),this.pendingQuestions.set(e.id,{resolve:f,reject:y,questions:i,timeoutHandle:g}),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(`
153
+ `),wakeMessageOnNotifyFailed:p})})}resolveAskUserQuestion(e,n){let r=this.pendingQuestions.get(e);if(!r){console.warn(`[SessionQuestionService] resolveAskUserQuestion: no pending question for session "${e}"`);return}clearTimeout(r.timeoutHandle),this.pendingQuestions.delete(e);let o=r.questions[0],i=o.options??[],s=i[n];if(!s){r.reject(new Error(`AskUserQuestion: invalid option index ${n} (${i.length} options available)`));return}this.clearWaitingTimestamp(e),r.resolve({behavior:"allow",updatedInput:{questions:r.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 dx(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 Us(t){let e=dx(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function yo(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 lx(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function Cl(t){let{sessionId:e,canonicalStatusDetail:n,canonicalStatusDelivered:r=!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. ${n??(r?"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.",...r?["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 ux(t){let{contract:e,canonicalStatusDelivered:n}=t;return["Completion diagnostics:",`- Canonical completion status delivered to user: ${n?"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 _l(t){let{session:e,originThreadLine:n,preview:r}=t,o=`$${(e.costUsd??0).toFixed(2)}`,i=Tt(e.duration),s=lx(),a=d=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,n,...Us(e),"","Output preview:",r,"",...ux({contract:s,canonicalStatusDelivered:d}),"",...Cl({sessionId:e.id,canonicalStatusDelivered:d})].join(`
154
+ `);return{userMessage:`\u2705 [${e.name}] Completed | ${o} | ${i}`,wakeMessageOnNotifySuccess:a(!0),wakeMessageOnNotifyFailed:a(!1),followupContract:s}}function El(t){let{session:e,originThreadLine:n,errorSummary:r,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)}`,p=Tt(e.duration);return{userMessage:[`\u274C [${e.name}] Failed | ${l} | ${p}`,` \u26A0\uFE0F ${r}`].join(`
155
+ `),wakeMessage:["Coding agent session failed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,n,...Us(e),...e.harnessSessionId?[`Backend conversation ID: ${e.harnessSessionId}`]:[],"","Failure summary:",r,...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(`
156
+ `),buttons:s}}function $l(t){let{session:e,originThreadLine:n,preview:r}=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):",r,...n?["",n]:[]].join(`
157
+ `)}}function Ol(t){let{sessionName:e,sessionId:n,branchName:r,baseBranch:o,promptSnippet:i,commitLines:s,moreNote:a,diffSummary:d}=t;return[`[DELEGATED WORKTREE DECISION] Session "${e}" completed with changes.`,"",`Session ID: ${n}`,`Branch: ${r} \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(`
158
+ `)}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(`
159
+ `)}function Dl(t){let{sessionName:e,sessionId:n,cleanupSummary:r,preview:o,originThreadLine:i,requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:p,approvalPromptStatus:f,approvalPromptMessageKind:y,approvalPromptDeliveredAt:g}=t,k=o.trim()?["","Output preview:",o]:[];return["Coding agent session completed with no repository changes.",`Name: ${e} | ID: ${n}`,`Worktree outcome: ${r}`,...i?[i]:[],...Us({requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:p,approvalPromptStatus:f,approvalPromptMessageKind:y,approvalPromptDeliveredAt:g}),...k,"",...Cl({sessionId:n,canonicalStatusDetail:"The plugin already sent the canonical completion status to the user, including that no repo changes were kept."})].join(`
160
+ `)}function Fl(t){let e=[],n=t.changedFiles.slice(0,3).map(o=>`\`${o}\``);if(n.length>0){let o=t.changedFiles.length-n.length;e.push(o>0?`Touches ${n.join(", ")} and ${o} more file${o===1?"":"s"}`:`Touches ${n.join(", ")}`)}let r=[...new Set(t.commitMessages.map(o=>o.message.trim()).filter(Boolean))].slice(0,2);return r.length>0&&e.push(`Recent work: ${r.join("; ")}`),e}var ph=3200,Ll=3e3,px=2400,cx=120,mx=5,fx=280,lh=1400,uh="- Additional plan details omitted for brevity.";function ch(t){return t.replace(/^#{1,6}\s+/,"").replace(/^[-*+]\s+/,"").replace(/^\d+[.)]\s+/,"").replace(/^`([^`]+)`$/,"$1").trim()}function gx(t){return t.split(`
161
+ `).map(e=>e.trim()).filter(Boolean).map(ch).map(e=>Ce(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 hx(t){return t.split(`
162
+ `).map(e=>e.trim()).filter(Boolean).map(ch).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 Wl(t){let e=gx(t);return e.length===0?`Review summary:
163
+ - Plan details are available in the full session output.`:["Review summary:",...e.slice(0,6).map(n=>`- ${n}`)].join(`
164
+ `)}function Sx(t){let e=[],n=!1;for(let o of t){let i=o.replace(/\s+/g," ").trim();if(!i)continue;let s=Ce(i,fx);s.length<i.length&&(n=!0);let a=`- ${s}`;if(e.length>=mx||[...e,a].join(`
165
+ `).length>lh){n=!0;break}e.push(a)}if(e.length===0)return["- Plan details are available in the full session output."];if(!n)return e;let r=[...e];for(;r.length>0&&[...r,uh].join(`
166
+ `).length>lh;)r.pop();return[...r,uh]}function Bl(t){return Sx(hx(t)).join(`
167
+ `)}function yx(t,e){let n=[],r=t.trim();for(;r.length>e;){let o=r.lastIndexOf(" ",e);o<Math.floor(e*.6)&&(o=e),n.push(r.slice(0,o).trimEnd()),r=r.slice(o).trimStart()}return r.length>0&&n.push(r),n}function kx(t,e){let n=t.split(`
168
+ `),r=[],o="",i=()=>{o.trim().length>0&&(r.push(o.trimEnd()),o="")};for(let s of n){if(s.length>e){i();for(let d of yx(s,e))r.push(d);continue}let a=o.length>0?`${o}
169
+ ${s}`:s;if(a.length>e){i(),o=s;continue}o=a}return i(),r}function mh(t){return Ce(t.trim(),cx)}function fh(t,e){return e?t?`
168
170
 
169
171
  Choose Approve, Revise, or Reject below.`:`
170
172
 
171
173
  Approval is still pending for this plan version.`:`
172
174
 
173
- Continued in next message.`}function mx(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=`\u{1F4CB} [${e}] Plan v${r??"?"} ready for approval:`,s=`
175
+ Continued in next message.`}function vx(t){let{sessionName:e,actionableVersion:n,fullPlanText:r,hasButtons:o}=t,i=`\u{1F4CB} [${e}] Plan v${n??"?"} ready for approval:`,s=`
174
176
 
175
177
  Full plan (truncated):
176
- `,a=Tg(o,!0),d=Math.max(0,cl-i.length-s.length-a.length);return`${i}${s}${Fe(n,d)}${a}`}function fx(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=Rg(e),s=ox;for(;s>0;){let a=cx(n,s),d=a.map((g,y)=>{let f=a.length,k=[`\u{1F4CB} [${i}] Plan v${r??"?"} ready for approval (${y+1}/${f}):`,"",y===0?"Full plan:":""].filter(Boolean).join(`
177
- `),A=Tg(o,y===f-1);return`${k}
178
- ${g}${A}`}),l=d.reduce((g,y)=>Math.max(g,y.length),0);if(l<=cl)return d;let m=l-cl;s-=Math.max(m,50)}return[mx({sessionName:i,actionableVersion:r,fullPlanText:n,hasButtons:o})]}function gl(t){let{preview:e,artifact:r}=t,n=r?.markdown?.trim();return n&&n.length<=bg?`Full plan:
179
- ${n}`:ml(n||e)}function Mg(t){let{sessionName:e,actionableVersion:r,preview:n,artifact:o,hasButtons:i}=t,s=o?.markdown?.trim(),a=Rg(e);if(s){let l=`\u{1F4CB} [${a}] Plan v${r??"?"} ready for approval:
178
+ `,a=fh(o,!0),d=Math.max(0,Ll-i.length-s.length-a.length);return`${i}${s}${Ce(r,d)}${a}`}function Px(t){let{sessionName:e,actionableVersion:n,fullPlanText:r,hasButtons:o}=t,i=mh(e),s=px;for(;s>0;){let a=kx(r,s),d=a.map((f,y)=>{let g=a.length,k=[`\u{1F4CB} [${i}] Plan v${n??"?"} ready for approval (${y+1}/${g}):`,"",y===0?"Full plan:":""].filter(Boolean).join(`
179
+ `),A=fh(o,y===g-1);return`${k}
180
+ ${f}${A}`}),l=d.reduce((f,y)=>Math.max(f,y.length),0);if(l<=Ll)return d;let p=l-Ll;s-=Math.max(p,50)}return[vx({sessionName:i,actionableVersion:n,fullPlanText:r,hasButtons:o})]}function Ul(t){let{preview:e,artifact:n}=t,r=n?.markdown?.trim();return r&&r.length<=ph?`Full plan:
181
+ ${r}`:Wl(r||e)}function gh(t){let{sessionName:e,actionableVersion:n,preview:r,artifact:o,hasButtons:i}=t,s=o?.markdown?.trim(),a=mh(e);if(s){let l=`\u{1F4CB} [${a}] Plan v${n??"?"} ready for approval:
180
182
 
181
183
  Full plan:
182
184
  ${s}
183
185
 
184
- ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`;return l.length<=bg?{displayMode:"single-full-plan",userMessages:[l],reviewSummary:`Full plan:
185
- ${s}`}:{displayMode:"chunked-full-plan",userMessages:fx({sessionName:e,actionableVersion:r,fullPlanText:s,hasButtons:i}),reviewSummary:ml(s)}}let d=ml(n);return{displayMode:"summary",userMessages:[`\u{1F4CB} [${a}] Plan v${r??"?"} ready for approval:
186
+ ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`;return l.length<=ph?{displayMode:"single-full-plan",userMessages:[l],reviewSummary:`Full plan:
187
+ ${s}`}:{displayMode:"chunked-full-plan",userMessages:Px({sessionName:e,actionableVersion:n,fullPlanText:s,hasButtons:i}),reviewSummary:Wl(s)}}let d=Wl(r);return{displayMode:"summary",userMessages:[`\u{1F4CB} [${a}] Plan v${n??"?"} ready for approval:
186
188
 
187
189
  ${d}
188
190
 
189
- ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`],reviewSummary:d}}var Cg=700;function gx(t){let e=t?.trim();return e||void 0}function hx(t,e){let r=e?.trim();if(!r)return;if(!t)return r;let n=t.trim(),o=r.split(`
190
- `).map(a=>a.trimEnd());for(;o.length>0&&!o[o.length-1]?.trim();)o.pop();for(;o.length>0&&o[o.length-1]?.trim()===n;)o.pop();let s=o.filter((a,d,l)=>{let m=a.trim();return!m||m!==n?!0:!l.some((y,f)=>f!==d&&y.trim().length>0&&y.trim()!==n)}).join(`
191
- `).trim();if(!(!s||s===n))return s.length>Cg?Wi(s,Cg):s}function Sx(t){let e=gx(t.questionText)??"The session is waiting for your reply.",r=hx(e,t.contextPreview);return r?[`\u2753 [${t.sessionName}] Question waiting for reply:`,"","Question:",e,"","Recent context:",r].join(`
191
+ ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`],reviewSummary:d}}var hh=700;function wx(t){let e=t?.trim();return e||void 0}function Ix(t,e){let n=e?.trim();if(!n)return;if(!t)return n;let r=t.trim(),o=n.split(`
192
+ `).map(a=>a.trimEnd());for(;o.length>0&&!o[o.length-1]?.trim();)o.pop();for(;o.length>0&&o[o.length-1]?.trim()===r;)o.pop();let s=o.filter((a,d,l)=>{let p=a.trim();return!p||p!==r?!0:!l.some((y,g)=>g!==d&&y.trim().length>0&&y.trim()!==r)}).join(`
193
+ `).trim();if(!(!s||s===r))return s.length>hh?Ci(s,hh):s}function bx(t){let e=wx(t.questionText)??"The session is waiting for your reply.",n=Ix(e,t.contextPreview);return n?[`\u2753 [${t.sessionName}] Question waiting for reply:`,"","Question:",e,"","Recent context:",n].join(`
192
194
  `):`\u2753 [${t.sessionName}] Question waiting for reply:
193
195
 
194
- ${e}`}function yx(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function uo(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(`
195
- `)}function hl(t){let{session:e,preview:r,questionText:n,questionContextPreview:o,planArtifact:i,originThreadLine:s,planApprovalMode:a,planApprovalButtons:d,questionButtons:l}=t,m=e.pendingPlanApproval,g=e.actionablePlanDecisionVersion??e.planDecisionVersion,y=yx(e,g),f=a??"delegate",k=m&&f==="ask"&&!y?Mg({sessionName:e.name,actionableVersion:g,preview:r,artifact:i,hasButtons:!!d}):void 0,A=m?k?.reviewSummary??gl({preview:r,artifact:i}):void 0,b=m?k&&k.userMessages.length===1?k.userMessages[0]:void 0:Sx({sessionName:e.name,questionText:n??r,contextPreview:o}),w=m&&k&&k.userMessages.length>1?k.userMessages.map((I,R,O)=>({text:I,buttons:R===O.length-1?d:void 0})):void 0;if(m){let I=f,R="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return I==="delegate"?{label:"plan-approval",userMessage:b,userMessages:w,planReviewSummary:A,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${g??"?"}`,s,R,"","\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(`
196
- `)}:I==="ask"?{label:"plan-approval",userMessage:b,userMessages:w,planReviewSummary:A,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${g??"?"}`,s,R,"","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(`
197
- `),buttons:w?void 0:d}:{label:"plan-approval",userMessage:b,planReviewSummary:A,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`].join(`
198
- `)}}let C=e.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:b,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: ${e.name} | ID: ${e.id}`,s,"","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(`
199
- `),buttons:l}}ke();var As=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:ll(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(`
200
- `);this.dispatchNotification(n,{label:`worktree-stale-reminder-${e.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(re(e)??e.harnessSessionId)})}};ut();ke();br();import{existsSync as kx,readFileSync as vx}from"fs";function _g(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function Px(t,e){if(t.latestPlanArtifactVersion===e&&t.latestPlanArtifact)return t.latestPlanArtifact;let r=t.planFilePath?.trim();if(!(!r||!kx(r)))try{let n=vx(r,"utf-8").trim();return n?{markdown:n,steps:[]}:void 0}catch{return}}var Rs=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(`
201
- `)}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(`
202
- `)}dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",userMessage:uo({session:e,summary:n}),notifyUser:"always",hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-message",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-message",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"}))}shouldRequestCompletionFollowup(e){return e.originSessionKey?.trim()?.startsWith("agent:main:cron:")?!1:!!ii(e)}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&&Ot(a,d),m){for(let g of et(e))this.deps.updatePersistedSession(g,{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=_g(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(`
196
+ ${e}`}function xx(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function ko(t){let{session:e,summary:n}=t,r=e.actionablePlanDecisionVersion??e.planDecisionVersion;return[`\u{1F4CB} [${e.name}] Plan v${r??"?"} 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:","",n].join(`
197
+ `)}function Kl(t){let{session:e,preview:n,questionText:r,questionContextPreview:o,planArtifact:i,originThreadLine:s,planApprovalMode:a,planApprovalButtons:d,questionButtons:l}=t,p=e.pendingPlanApproval,f=e.actionablePlanDecisionVersion??e.planDecisionVersion,y=xx(e,f),g=a??"delegate",k=p&&g==="ask"&&!y?gh({sessionName:e.name,actionableVersion:f,preview:n,artifact:i,hasButtons:!!d}):void 0,A=p?k?.reviewSummary??Ul({preview:n,artifact:i}):void 0,x=p?k&&k.userMessages.length===1?k.userMessages[0]:void 0:bx({sessionName:e.name,questionText:r??n,contextPreview:o}),w=p&&k&&k.userMessages.length>1?k.userMessages.map((I,R,O)=>({text:I,buttons:R===O.length-1?d:void 0})):void 0;if(p){let I=g,R="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return I==="delegate"?{label:"plan-approval",userMessage:x,userMessages:w,planReviewSummary:A,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${f??"?"}`,s,R,"","\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):",n,"","\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(`
198
+ `)}:I==="ask"?{label:"plan-approval",userMessage:x,userMessages:w,planReviewSummary:A,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${f??"?"}`,s,R,"","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):",n].join(`
199
+ `),buttons:w?void 0:d}:{label:"plan-approval",userMessage:x,planReviewSummary:A,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`].join(`
200
+ `)}}let C=e.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:x,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: ${e.name} | ID: ${e.id}`,s,"","Last output:",n,"",`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(`
201
+ `),buttons:l}}Pe();var Ks=class t{constructor(e,n,r,o){this.buildRoutingProxy=e;this.dispatchNotification=n;this.updatePersistedSession=r;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 n=e.worktreeState==="pending_decision"||e.lifecycle==="awaiting_worktree_decision",r=e.worktreeState==null&&e.lifecycle==null&&!e.worktreeMerged&&!e.worktreePrUrl;if(!n&&!r)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,n=Date.now()){let r=this.getNextReminderAt(e);if(r==null||r>n)return!1;let o=n-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 nt(e))this.updatePersistedSession(s,{lastWorktreeReminderAt:new Date(n).toISOString()});return!0}sendReminderNotification(e,n){let r=this.buildRoutingProxy({id:e.sessionId??e.name??E(e)??e.harnessSessionId,sessionId:e.sessionId,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef,route:e.route});if(e.worktreeStrategy==="delegate"){this.dispatchNotification(r,{label:`worktree-stale-reminder-${e.name}`,wakeMessage:Nl(e,n),notifyUser:"never"});return}let o=[`\u23F0 Reminder: branch \`${e.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${e.name} | Pending: ${n}h`,"",`agent_merge(session="${e.name}") or agent_pr(session="${e.name}") or agent_worktree_cleanup() to resolve.`].join(`
202
+ `);this.dispatchNotification(r,{label:`worktree-stale-reminder-${e.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(re(e)??e.harnessSessionId)})}};mt();Pe();En();import{existsSync as Ax,readFileSync as Rx}from"fs";function Sh(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function Tx(t,e){if(t.latestPlanArtifactVersion===e&&t.latestPlanArtifact)return t.latestPlanArtifact;let n=t.planFilePath?.trim();if(!(!n||!Ax(n)))try{let r=Rx(n,"utf-8").trim();return r?{markdown:r,steps:[]}:void 0}catch{return}}var Vs=class{constructor(e){this.deps=e}deps;buildPlanApprovalWakeText(e,n,r=!1){return[r?"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${n??"?"}`,`Wait for their ${r?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
203
+ `)}buildPlanApprovalDeliveryFailureWake(e,n){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${n??"?"}`,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(`
204
+ `)}dispatchPlanApprovalFallback(e,n,r){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",userMessage:ko({session:e,summary:r}),notifyUser:"always",hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,n,!0),wakeMessageOnNotifyFailed:this.buildPlanApprovalDeliveryFailureWake(e,n)})}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"}))}shouldRequestCompletionFollowup(e){return e.originSessionKey?.trim()?.startsWith("agent:main:cron:")?!1:!!fi(e)}handleTurnEnd(e,n){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(n||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 n={notificationSent:!1,worktreeRemoved:!1};e.worktreePath&&e.originalWorkdir&&(n=await this.deps.handleWorktreeStrategy(e));let r=!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=We(e);console.info(`[SessionManager] Early startup failure for "${e.name}" \u2014 auto-cleaning worktree (cost=$${e.costUsd.toFixed(2)}, duration=${e.duration}ms)`);let p=!1;if(a&&!l&&(p=rt(a,e.worktreePath)),a&&d&&!l&&p&&Lt(a,d),p){for(let f of nt(e))this.deps.updatePersistedSession(f,{worktreePath:void 0,worktreeBranch:void 0});r=!0}}let o=e.worktreeStrategy&&e.worktreeStrategy!=="off"&&e.worktreeStrategy!=="manual";if(!r&&e.worktreePath&&e.originalWorkdir){let a=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),d=We(e);n.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&&rt(a,e.worktreePath)}if(e.killReason==="done"){if(n.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,Ce(a,200),r);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=Sh(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(`
203
205
  `),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(`
204
- `)}),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(`
205
- `),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}] ${lo(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"&&_g(e,n),i=e.pendingPlanApproval?void 0:this.deps.getOutputPreview(e),s=!e.pendingPlanApproval&&e.pendingInputState?.promptText?e.pendingInputState.promptText:!e.pendingPlanApproval&&i!==void 0?i:this.deps.getOutputPreview(e,e.pendingPlanApproval&&r!=="delegate"?Number.POSITIVE_INFINITY:void 0),a=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(g=>({label:g}))):void 0,d=Px(e,n),l=hl({session:e,preview:s,questionText:e.pendingPlanApproval?void 0:e.pendingInputState?.promptText,questionContextPreview:i,planArtifact:d,originThreadLine:this.deps.originThreadLine(e),planApprovalMode:r,planApprovalButtons:a,questionButtons:e.pendingPlanApproval?void 0:a}),m=l.planReviewSummary??s;if(l.label==="plan-approval"&&r==="ask"&&o){this.deps.dispatchSessionNotification(e,{label:l.label,userMessage:l.userMessage,userMessages:l.userMessages,notifyUser:"never",buttons:l.buttons,wakeMessage:l.wakeMessage});return}if(l.label==="plan-approval"&&r==="ask"){this.deps.dispatchSessionNotification(e,{label:l.label,userMessage:l.userMessage,userMessages:l.userMessages,notifyUser:"always",buttons:l.buttons,hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{canonicalPlanPromptVersion:n,approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,n,m),wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,n)});return}if(l.label==="plan-approval"){this.deps.dispatchSessionNotification(e,{label:l.label,userMessage:l.userMessage,wakeMessage:l.wakeMessage,notifyUser:"never",buttons:l.buttons});return}this.deps.dispatchSessionNotification(e,{label:l.label,userMessage:l.userMessage,notifyUser:"always",buttons:l.buttons,wakeMessageOnNotifyFailed:l.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=al({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=this.shouldRequestCompletionFollowup(e),o=il({session:e,originThreadLine:this.deps.originThreadLine(e),preview:r}),i;this.deps.dispatchSessionNotification(e,{label:"completed",userMessage:o.userMessage,notifyUser:"always",completionWakeSummaryRequired:n,wakeMessageOnNotifySuccess:n?o.wakeMessageOnNotifySuccess:void 0,wakeMessageOnNotifyFailed:n?o.wakeMessageOnNotifyFailed:void 0,hooks:{onNotifySucceeded:()=>{i=!0,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_succeeded",canonicalStatusDelivered:i,followupSummaryRequired:n})},onNotifyFailed:()=>{i=!1,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_failed",canonicalStatusDelivered:i,followupSummaryRequired:n})},onWakeSucceeded:()=>{this.logCompletionWakeDiagnostic({session:e,event:"completion_wake_succeeded",canonicalStatusDelivered:i,followupSummaryRequired:n})}}})}emitFailed(e,r,n){let o=sl({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 wx}from"fs";var Ts=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&&wx(i)&&tt(s,i,{destructive:!0}),a&&Ot(s,a);for(let g of et(n??r))this.deps.updatePersistedSession(g,{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 $g=new Set(["starting","running"]),Ms=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>$g.has(e.status)).length}uniqueName(e){let r=new Set([...this.sessions.values()].filter(o=>$g.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 Cs=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 _s=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:ul({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=pl(i),d=i.commitMessages.slice(0,5).map(g=>`\u2022 ${g.hash} ${g.message} (${g.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(g=>`- ${g}`),""]:[],"Recent commits:",...d,...l?[l]:[],"",`\u26A0\uFE0F Discard will permanently delete branch \`${n}\` and all local changes. This cannot be undone.`].join(`
206
- `),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(`
207
- `),wakeMessageOnNotifyFailed:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",m,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
208
- `)}}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:dl({sessionName:r.name,sessionId:r.id,branchName:n,baseBranch:o,promptSnippet:d,commitLines:s,moreNote:a,diffSummary:i}),notifyUser:"never"}}};Di();ut();var $s=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 Ix}from"fs";var Eg=new Set(["completed","failed","killed"]),xx=new Set(["starting","running"]),bx=5e3,Og=10080*60*1e3,Ax=300*1e3,Dg="tmp-output:cleanup",Es=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 $s;constructor(e=20,r=50,n={}){this.maxSessions=e,this.maxPersistedSessions=r,this.registry=new Ms,this.sessions=this.registry.sessions,this.store=new gs(n.store),this.metrics=new hs,this.wakeDispatcher=new vs,this.interactions=new Ps(this.store.actionTokenStore,sr),this.references=new is(this.sessions,this.store),this.stateSync=new os({store:this.store,sessions:this.sessions,resolveSession:o=>this.references.resolveActive(o)}),this.notifications=new ws(this.wakeDispatcher,(o,i)=>this.stateSync.applySessionPatch(o,i)),this.store.onActionTokensChanged(()=>this.syncActionTokenExpiryDeadline()),this.worktrees=new Is,this.restore=new ns(o=>this.store.getPersistedSession(o)),this.worktreeMessages=new _s,this.worktreeStrategy=new ds({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:Ei,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(()=>(Ji(),Mf));return{success:(await s().execute("auto-pr",{session:o.id,base_branch:i}))?.meta?.success===!0}}}),this.questions=new xs(this.pendingAskUserQuestions,(o,i)=>this.dispatchSessionNotification(o,i),o=>{this.lastWaitingEventTimestamps.delete(o)},(o,i)=>this.interactions.getQuestionButtons(o,i)),this.reminders=new As(o=>this.buildRoutingProxy(o),(o,i)=>this.notifications.dispatch(o,i),(o,i)=>this.updatePersistedSession(o,i),o=>this.getWorktreeDecisionButtons(o)),this.lifecycle=new Rs({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 Ts({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 Cs({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=to(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+Og,()=>{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()+Ax))})}reconcileResolvedWorktreeRetention(e,r){let n=to(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<Og))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(Dg);let r=this.store.getNextTmpOutputCleanupAt(e);r!=null&&this.maintenance.schedule(Dg,r,()=>{let n=Date.now();this.store.cleanupTmpOutputFiles(n),this.syncTmpOutputCleanupDeadline(n)})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.store.hasOutputPathReference(e)))try{Ix(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||mf(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,g=new Fi({...e,workdir:s.actualWorkdir,systemPrompt:s.effectiveSystemPrompt,canUseTool:m},i);return l=g.id,this.registry.add(g),this.metrics.incrementLaunched(),this.runtimeBootstrap.initializeSession(g,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(Eg.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}Eg.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 oi({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(`
209
- `)}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(`
210
- `)}dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",userMessage:uo({session:e,summary:n}),notifyUser:"always",hooks:{onNotifyStarted:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-message",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-message",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=fl(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}),g=[`\u{1F4CB} [${a.name}] Plan v${l??"?"} needs your decision:`,"","Why this was escalated:","",o,"","Choose Approve, Revise, or Reject below."].join(`
211
- `);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:g,notifyUser:"always",buttons:m,hooks:{onNotifyStarted:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptStatus:"sending",approvalPromptVersion:l,approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.updatePersistedSession(d,{canonicalPlanPromptVersion:l,approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",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||!rs(e,r))||!r?e:Mi(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,as({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(`
212
- `),buttons:[[this.makeActionButton(r,"worktree-create-pr","Open PR")]]})}getStoppedStatusLabel(e){return lo(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<bx?!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(`
213
- `):this.selectCompletionPreviewSource(e);return n?i:i.length>r?this.shouldPreferTailPreview(e)?Wi(i,r):gf(i,r):i}selectCompletionPreviewSource(e){let r=typeof e.getOutput=="function"?e.getOutput():[],n=r.join(`
214
- `).trim();return n?this.shouldPreferTailPreview(e)?this.extractLastSubstantiveBlock(n)??n:r.slice(-20).join(`
215
- `):""}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(`
216
- `)?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())xx.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 Ng;function Os(t){if(t&&typeof t=="object"){Ng=t;return}Ng=void 0}Re();import{definePluginEntry as Fg}from"openclaw/plugin-sdk/core";function _x(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=Cx("git",["rev-parse","--show-toplevel"],{cwd:d.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();l&&i.add(Lg(l,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let d of i)try{let l=Rx(d);for(let m of l){if(!m.startsWith("openclaw-worktree-"))continue;let g=Lg(d,m);try{let y=Tx(g);if(!y.isDirectory()||y.mtimeMs>n||o.has(g))continue;Mx(g,{recursive:!0,force:!0}),a++}catch(y){console.warn(`[index] Failed to clean up orphaned worktree ${g}: ${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 $x(t){let e=null,r=null,n=t.registerTool;Os(t.runtime),n(o=>jm(o),{optional:!1}),n(o=>kf(o),{optional:!1}),n(o=>vf(o),{optional:!1}),n(o=>Vi(o),{optional:!1}),n(o=>xf(o),{optional:!1}),n(o=>bf(o),{optional:!1}),n(o=>Af(o),{optional:!1}),n(o=>Rf(o),{optional:!1}),n(o=>Qi(o),{optional:!1}),n(o=>oo(o),{optional:!1}),n(o=>Cf(o),{optional:!1}),n(o=>_f(o),{optional:!1}),n(o=>$f(o),{optional:!1}),n(o=>Of(o),{optional:!1}),n(o=>Df(o),{optional:!1}),t.registerInteractiveHandler(zd("telegram")),t.registerInteractiveHandler(zd("discord")),Nf(t),Ff(t),Lf(t),Wf(t),Bf(t),Uf(t),Kf(t),Vf(t),qf(t),t.registerService({id:"openclaw-code-agent",start:o=>{let i=t.pluginConfig??{};pm(i),Os(t.runtime),e=new Es(_.maxSessions,_.maxPersistedSessions),r=new ts(e),kd(e),vd(r),r.start(),_x(e),e.bootstrapMaintenanceSchedules()},stop:()=>{r&&r.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),r=null,e=null,Os(void 0),vd(null),kd(null)}})}var xG=Fg({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:$x});export{xG as default,$x as register};
206
+ `)}),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} | ${Tt(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(`
207
+ `),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} | ${Tt(s)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(e.id,e)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.notifySession(e,`\u26D4 [${e.name}] ${yo(e.killReason)} | ${i} | ${Tt(s)}`),this.deps.clearRetryTimersForSession(e.id)}emitWaitingForInput(e){if(!this.deps.debounceWaitingEvent(e.id))return;let n=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0,r=e.actionablePlanDecisionVersion??e.planDecisionVersion,o=e.pendingPlanApproval&&n==="ask"&&Sh(e,r),i=e.pendingPlanApproval?void 0:this.deps.getOutputPreview(e),s=!e.pendingPlanApproval&&e.pendingInputState?.promptText?e.pendingInputState.promptText:!e.pendingPlanApproval&&i!==void 0?i:this.deps.getOutputPreview(e,e.pendingPlanApproval&&n!=="delegate"?Number.POSITIVE_INFINITY:void 0),a=e.pendingPlanApproval&&n==="ask"&&!o?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:r}):!e.pendingPlanApproval&&e.pendingInputState?.options.length?this.deps.getQuestionButtons(e.id,e.pendingInputState.options.map(f=>({label:f}))):void 0,d=Tx(e,r),l=Kl({session:e,preview:s,questionText:e.pendingPlanApproval?void 0:e.pendingInputState?.promptText,questionContextPreview:i,planArtifact:d,originThreadLine:this.deps.originThreadLine(e),planApprovalMode:n,planApprovalButtons:a,questionButtons:e.pendingPlanApproval?void 0:a}),p=l.planReviewSummary??s;if(l.label==="plan-approval"&&n==="ask"&&o){this.deps.dispatchSessionNotification(e,{label:l.label,userMessage:l.userMessage,userMessages:l.userMessages,notifyUser:"never",buttons:l.buttons,wakeMessage:l.wakeMessage});return}if(l.label==="plan-approval"&&n==="ask"){this.deps.dispatchSessionNotification(e,{label:l.label,userMessage:l.userMessage,userMessages:l.userMessages,notifyUser:"always",buttons:l.buttons,hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{canonicalPlanPromptVersion:r,approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,r,p),wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,r)});return}if(l.label==="plan-approval"){this.deps.dispatchSessionNotification(e,{label:l.label,userMessage:l.userMessage,wakeMessage:l.wakeMessage,notifyUser:"never",buttons:l.buttons});return}this.deps.dispatchSessionNotification(e,{label:l.label,userMessage:l.userMessage,notifyUser:"always",buttons:l.buttons,wakeMessageOnNotifyFailed:l.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 n=$l({session:e,originThreadLine:this.deps.originThreadLine(e),preview:this.deps.getOutputPreview(e)});this.deps.dispatchSessionNotification(e,{label:"turn-complete",userMessage:n.userMessage,wakeMessage:n.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 n=this.deps.getOutputPreview(e),r=this.shouldRequestCompletionFollowup(e),o=_l({session:e,originThreadLine:this.deps.originThreadLine(e),preview:n}),i;this.deps.dispatchSessionNotification(e,{label:"completed",userMessage:o.userMessage,notifyUser:"always",completionWakeSummaryRequired:r,requireDirectUserNotification:!0,wakeMessageOnNotifySuccess:r?o.wakeMessageOnNotifySuccess:void 0,wakeMessageOnNotifyFailed:r?o.wakeMessageOnNotifyFailed:void 0,hooks:{onNotifySucceeded:()=>{i=!0,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_succeeded",canonicalStatusDelivered:i,followupSummaryRequired:r})},onNotifyFailed:()=>{i=!1,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_failed",canonicalStatusDelivered:i,followupSummaryRequired:r})},onWakeSucceeded:()=>{this.logCompletionWakeDiagnostic({session:e,event:"completion_wake_succeeded",canonicalStatusDelivered:i,followupSummaryRequired:r})}}})}emitFailed(e,n,r){let o=El({session:e,originThreadLine:this.deps.originThreadLine(e),errorSummary:n,preview:this.deps.getOutputPreview(e),worktreeAutoCleaned:r,failedButtons:this.deps.getResumeButtons(e.id,e)});this.deps.dispatchSessionNotification(e,{label:"failed",userMessage:o.userMessage,wakeMessage:o.wakeMessage,notifyUser:"always",buttons:o.buttons})}};Pe();mt();import{existsSync as Mx}from"fs";var qs=class{constructor(e){this.deps=e}deps;async dismissWorktree(e){let n=this.deps.getPersistedSession(e),r=this.deps.resolveActiveSession(e),o=r??n;if(!o)return`Error: Session "${e}" not found.`;let i=r?.worktreePath??n?.worktreePath,s=this.deps.resolveWorktreeRepoDir(r?.originalWorkdir??n?.workdir,i),a=r?.worktreeBranch??n?.worktreeBranch,d=r?.name??n?.name??e;if(!s)return`Error: No workdir found for session "${e}".`;let l=We(o);!l&&i&&Mx(i)&&rt(s,i,{destructive:!0}),a&&Lt(s,a);for(let f of nt(r??n))this.deps.updatePersistedSession(f,{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:n?.worktreeLifecycle?.baseBranch,targetRepo:n?.worktreePrTargetRepo,pushRemote:n?.worktreePushRemote}});let p=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(r??n??{id:e})??e,sessionId:n?.sessionId,harnessSessionId:r?.harnessSessionId??n?.harnessSessionId,backendRef:r?.backendRef??n?.backendRef,route:r?.route??n?.route}),{label:"worktree-dismissed",userMessage:p,notifyUser:"always"}),p}snoozeWorktreeDecision(e){let n=this.deps.getPersistedSession(e);if(!n)return`Error: Session "${e}" not found.`;let r=new Date(Date.now()+1440*60*1e3).toISOString();for(let s of nt(n))this.deps.updatePersistedSession(s,{worktreeDecisionSnoozedUntil:r,lastWorktreeReminderAt:new Date().toISOString()});let i=`\u23ED\uFE0F Reminder snoozed 24h for \`${n.worktreeBranch??"unknown"}\` (session: ${n.name})`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:re(n)??E(n)??n.harnessSessionId,sessionId:n.sessionId,harnessSessionId:n.harnessSessionId,backendRef:n.backendRef,route:n.route}),{label:"worktree-snoozed",userMessage:i,notifyUser:"always"}),i}};var yh=new Set(["starting","running"]),js=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>yh.has(e.status)).length}uniqueName(e){let n=new Set([...this.sessions.values()].filter(o=>yh.has(o.status)).map(o=>o.name));if(!n.has(e))return e;let r=2;for(;n.has(`${e}-${r}`);)r+=1;return`${e}-${r}`}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 Gs=class{constructor(e){this.deps=e}deps;initializeSession(e,n,r,o={}){if(this.deps.hydrateSpawnedSession(e,n,r),r.taskLifecycle?.create(e),e.on("statusChange",(i,s)=>{s==="running"?(e.harnessSessionId&&this.deps.markRunning(e),r.taskLifecycle?.progress(e)):(s==="completed"||s==="failed"||s==="killed")&&(r.taskLifecycle?.finalize(e),this.deps.handleTerminal(e).catch(a=>{console.error(`[SessionRuntimeBootstrap] handleTerminal threw for session ${e.id}:`,a)}))}),e.on("lifecycleChange",(i,s)=>{r.taskLifecycle?.progress(e)}),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 Hs=class{buildNoChangeNotification(e){let{session:n,nativeBackendWorktree:r,cleanupSucceeded:o,worktreePath:i,preview:s,originThreadLine:a}=e,d=o?r?"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?r?`\u2139\uFE0F [${n.name}] Session completed with no changes \u2014 native backend worktree released for backend cleanup`:`\u2139\uFE0F [${n.name}] Session completed with no changes \u2014 worktree cleaned up`:`\u26A0\uFE0F [${n.name}] Session completed with no changes, but worktree cleanup failed. Worktree still exists at ${i}`,wakeMessage:Dl({sessionName:n.name,sessionId:n.id,cleanupSummary:d,preview:s,originThreadLine:a,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,approvalState:n.approvalState,planApproval:n.planApproval,approvalPromptStatus:n.approvalPromptStatus,approvalPromptMessageKind:n.approvalPromptMessageKind,approvalPromptDeliveredAt:n.approvalPromptDeliveredAt}),notifyUser:"always"}}buildAskNotification(e){let{session:n,branchName:r,baseBranch:o,diffSummary:i,buttons:s}=e,a=Fl(i),d=i.commitMessages.slice(0,5).map(f=>`\u2022 ${f.hash} ${f.message} (${f.author})`),l=i.commits>5?`...and ${i.commits-5} more`:"",p=n.worktreePrTargetRepo?`Branch: \`${r}\` \u2192 \`${o}\` | PR target: ${n.worktreePrTargetRepo}`:`Branch: \`${r}\` \u2192 \`${o}\``;return{label:"worktree-merge-ask",userMessage:[`\u{1F500} Worktree decision required for session \`${n.name}\``,"",p,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"",...a.length>0?["Summary:",...a.map(f=>`- ${f}`),""]:[],"Recent commits:",...d,...l?[l]:[],"",`\u26A0\uFE0F Discard will permanently delete branch \`${r}\` and all local changes. This cannot be undone.`].join(`
208
+ `),notifyUser:"always",buttons:s,wakeMessageOnNotifySuccess:["Worktree decision buttons delivered to the user.",`Session: ${n.name} | ID: ${n.id}`,p,"Wait for their button callback \u2014 do NOT act on this worktree yourself."].join(`
209
+ `),wakeMessageOnNotifyFailed:[`\u{1F500} Worktree decision required for session \`${n.name}\``,"",p,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
210
+ `)}}buildDelegateNotification(e){let{session:n,branchName:r,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=n.prompt?n.prompt.slice(0,500):"(no prompt)";return{label:"worktree-delegate",wakeMessage:Ol({sessionName:n.name,sessionId:n.id,branchName:r,baseBranch:o,promptSnippet:d,commitLines:s,moreNote:a,diffSummary:i}),notifyUser:"never"}}};Ji();mt();var zs=class t{timers=new Map;disposed=!1;static MAX_DELAY_MS=2147483647;schedule(e,n,r){if(this.disposed)return;this.cancel(e);let o=Math.max(0,n-Date.now()),i=setTimeout(()=>{if(this.timers.delete(e),!this.disposed){if(n-Date.now()>0){this.schedule(e,n,r);return}r()}},Math.min(o,t.MAX_DELAY_MS));i.unref?.(),this.timers.set(e,i)}cancel(e){let n=this.timers.get(e);n&&(clearTimeout(n),this.timers.delete(e))}cancelPrefix(e){for(let n of this.timers.keys())n.startsWith(e)&&this.cancel(n)}dispose(){this.disposed=!0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};import{unlinkSync as Cx}from"fs";var kh=new Set(["completed","failed","killed"]),_x=new Set(["starting","running"]),Ex=5e3,vh=10080*60*1e3,$x=300*1e3,Ph="tmp-output:cleanup",Qs=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 zs;constructor(e=20,n=50,r={}){this.maxSessions=e,this.maxPersistedSessions=n,this.registry=new js,this.sessions=this.registry.sessions,this.store=new Ms(r.store),this.metrics=new Cs,this.wakeDispatcher=new Ds,this.interactions=new Fs(this.store.actionTokenStore,pn),this.references=new ks(this.sessions,this.store),this.stateSync=new ys({store:this.store,sessions:this.sessions,resolveSession:o=>this.references.resolveActive(o)}),this.notifications=new Ls(this.wakeDispatcher,(o,i)=>this.stateSync.applySessionPatch(o,i)),this.store.onActionTokensChanged(()=>this.syncActionTokenExpiryDeadline()),this.worktrees=new Ws,this.restore=new Ss(o=>this.store.getPersistedSession(o)),this.worktreeMessages=new Hs,this.worktreeStrategy=new ws({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:zi,spawnConflictResolver:async({session:o,worktreePath:i,prompt:s})=>this.spawn({prompt:s,workdir:i,name:`${o.name}-conflict-resolver`,harness:o.harnessName||Ie(),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(()=>(us(),dg));return{success:(await s().execute("auto-pr",{session:o.id,base_branch:i}))?.meta?.success===!0}}}),this.questions=new Bs(this.pendingAskUserQuestions,(o,i)=>this.dispatchSessionNotification(o,i),o=>{this.lastWaitingEventTimestamps.delete(o)},(o,i)=>this.interactions.getQuestionButtons(o,i)),this.reminders=new Ks(o=>this.buildRoutingProxy(o),(o,i)=>this.notifications.dispatch(o,i),(o,i)=>this.updatePersistedSession(o,i),o=>this.getWorktreeDecisionButtons(o)),this.lifecycle=new Vs({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 qs({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 Gs({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)??e.harnessSessionId}runtimeGcKey(e){return`runtime-gc:${e}`}persistedMaintenanceKey(e,n){return`persisted:${e}:${n}`}runtimeGcMaxAgeMs(){return(_.sessionGcAgeMinutes??1440)*6e4}syncRuntimeGcDeadline(e){if(!e.completedAt)return;let n=this.runtimeGcKey(e.id);this.maintenance.schedule(n,e.completedAt+this.runtimeGcMaxAgeMs(),()=>{let r=this.sessions.get(e.id);if(!r||!r.completedAt)return;let o=this.runtimeGcMaxAgeMs();if(!this.store.shouldGcActiveSession(r,Date.now(),o)){this.syncRuntimeGcDeadline(r);return}this.registry.remove(e.id),this.persistSession(r,{scheduleRuntimeGc:!1}),this.lastWaitingEventTimestamps.delete(e.id),this.lastTurnCompleteMarkers.delete(e.id),this.lastTerminalWakeMarkers.delete(e.id)})}cancelPersistedMaintenance(e){let n=this.persistedMaintenanceRef(e);n&&this.maintenance.cancelPrefix(`persisted:${n}:`)}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 n=this.persistedMaintenanceRef(e);if(!n)return;this.maintenance.cancel(this.persistedMaintenanceKey(n,"worktree-reminder"));let r=this.reminders.getNextReminderAt(e);r!=null&&this.schedulePersistedWorktreeReminder(n,r),this.maintenance.cancel(this.persistedMaintenanceKey(n,"worktree-retention"));let o=po(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(n,"worktree-retention"),a+vh,()=>{let d=this.store.getPersistedSession(n);d&&this.reconcileResolvedWorktreeRetention(d,Date.now())})}}schedulePersistedWorktreeReminder(e,n){let r=this.persistedMaintenanceKey(e,"worktree-reminder");this.maintenance.schedule(r,n,()=>{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()+$x))})}reconcileResolvedWorktreeRetention(e,n){let r=po(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(!(!r.cleanupSafe&&!s||!i||n-i<vh))try{if(!e.worktreePath&&!We(e))return;let a=this.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!a)return;let d=We(e)?!1:rt(a,e.worktreePath);if(!We(e)&&!d)return;for(let l of nt(e))this.updatePersistedSession(l,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeLifecycle:{...e.worktreeLifecycle??r.lifecycle,state:r.derivedState,updatedAt:new Date(n).toISOString(),resolvedAt:e.worktreeLifecycle?.resolvedAt??new Date(n).toISOString(),resolutionSource:e.worktreeLifecycle?.resolutionSource??"maintenance",notes:r.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 n=this.store.getNextActionTokenExpiry();n!=null&&this.maintenance.schedule(e,n,()=>{this.store.purgeExpiredActionTokens(Date.now())})}syncTmpOutputCleanupDeadline(e=Date.now()){this.maintenance.cancel(Ph);let n=this.store.getNextTmpOutputCleanupAt(e);n!=null&&this.maintenance.schedule(Ph,n,()=>{let r=Date.now();this.store.cleanupTmpOutputFiles(r),this.syncTmpOutputCleanupDeadline(r)})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.store.hasOutputPathReference(e)))try{Cx(e)}catch{}}enforcePersistedRetention(){let e=this.store.evictOldestPersisted(this.maxPersistedSessions);for(let n of e)this.cancelPersistedMaintenance(n),n.sessionId&&this.maintenance.cancel(this.runtimeGcKey(n.sessionId)),this.cleanupOutputPathIfUnreferenced(n.outputPath)}bootstrapMaintenanceSchedules(){let e=Date.now();this.store.cleanupTmpOutputFiles(e);for(let n of this.store.listPersistedSessions())this.syncPersistedSessionMaintenance(n);this.syncActionTokenExpiryDeadline(),this.store.cleanupOrphanOutputFiles(),this.syncTmpOutputCleanupDeadline(e)}disposeMaintenance(){this.maintenance.dispose()}spawn(e,n={}){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||kf(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,p=a==="claude-code"&&!e.canUseTool?async(y,g)=>{if(!l)throw new Error("canUseTool called before session ID was set");return d.handleAskUserQuestion(l,g)}:e.canUseTool,f=new Xi({...e,workdir:s.actualWorkdir,systemPrompt:s.effectiveSystemPrompt,canUseTool:p},i);return l=f.id,this.registry.add(f),this.metrics.incrementLaunched(),this.runtimeBootstrap.initializeSession(f,s,e,n)}async spawnAndAwaitRunning(e,n={}){let r=this.spawn(e,n);return await this.waitForRunningSession(r),r}async waitForRunningSession(e){if(e.status==="running")return;if(kh.has(e.status))throw new Error(this.describeLaunchFailure(e));let n=e.on?.bind(e),r=e.off?.bind(e)??e.removeListener?.bind(e);if(!n||!r)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}kh.has(l)&&(a(),i(new Error(this.describeLaunchFailure(e))))},a=()=>{r("statusChange",s)};n("statusChange",s)})}describeLaunchFailure(e){let n=e.killReason?` (reason: ${e.killReason})`:"",r=e.error||e.result?.result||`status=${e.status}${n}`;return`Session ${e.name} [${e.id}] failed to start: ${r}`}formatLaunchResult(e,n){return mi({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},n)}shouldRunWorktreeStrategy(e){let n=e.lifecycle;return!(n==="starting"||n==="awaiting_plan_decision"||n==="awaiting_user_input"||e.pendingPlanApproval)}makeActionButton(e,n,r,o={}){return this.interactions.makeActionButton(e,n,r,o)}consumeActionToken(e){return this.interactions.consumeActionToken(e)}getActionToken(e){return this.interactions.getActionToken(e)}clearPlanDecisionTokens(e,n){this.interactions.clearPlanDecisionTokens(e,n)}hasProvablePlanReviewPrompt(e,n){return n!=null&&e.approvalPromptRequiredVersion===n&&(e.approvalPromptStatus==="delivered"||e.approvalPromptStatus==="fallback_delivered")}buildPlanApprovalWakeText(e,n,r=!1){return[r?"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${n??"?"}`,`Wait for their ${r?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
211
+ `)}buildPlanApprovalDeliveryFailureWake(e,n){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${n??"?"}`,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(`
212
+ `)}dispatchPlanApprovalFallback(e,n,r){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",userMessage:ko({session:e,summary:r}),notifyUser:"always",hooks:{onNotifyStarted:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,n,!0),wakeMessageOnNotifyFailed:this.buildPlanApprovalDeliveryFailureWake(e,n)})}getWorktreeDecisionButtons(e){let n=this.resolve(e)??this.getPersistedSession(e);if(!(!n||n.worktreeStrategy==="delegate"))return this.interactions.getWorktreeDecisionButtons(e,n)}getWorktreeCompletionState(e,n,r,o){return this.worktrees.getCompletionState(e,n,r,o)}notifyWorktreeOutcome(e,n){this.notifications.notifyWorktreeOutcome(e,n)}requestPlanApprovalFromUser(e,n){let r=n.trim();if(!r)return"Error: summary must not be empty.";let o=Bl(r),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 p=this.interactions.getPlanApprovalButtons(d,{...a,planDecisionVersion:l}),f=[`\u{1F4CB} [${a.name}] Plan v${l??"?"} needs your decision:`,"","Why this was escalated:","",o,"","Choose Approve, Revise, or Reject below."].join(`
213
+ `);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:f,notifyUser:"always",buttons:p,hooks:{onNotifyStarted:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptStatus:"sending",approvalPromptVersion:l,approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.updatePersistedSession(d,{canonicalPlanPromptVersion:l,approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",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)??e.harnessSessionId??"unknown-session",name:e.name,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef?{...e.backendRef}:void 0,route:e.route}}resolveWorktreeRepoDir(e,n){return e&&(!n||!hs(e,n))||!n?e:qi(n)??e}formatLaunchWorkdirLabel(e){if(!e.worktreePath)return e.workdir;let n=this.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath);return!n||n===e.worktreePath?e.worktreePath:`${e.worktreePath} (worktree of ${n})`}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 n=e.autoMergeParentSessionId;if(!n)return;let r=this.resolve(n),o=this.getPersistedSession(n),i=r??(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 ${n} could not be found.`);return}if(e.status==="completed"&&r){this.updatePersistedSession(n,{autoMergeResolverSessionId:void 0}),await this.handleWorktreeStrategy(r);return}let s=r?.worktreeBranch??o?.worktreeBranch??"unknown",a=r?.worktreePath??o?.worktreePath??"(unknown worktree)",d=r?.worktreeBaseBranch??o?.worktreeBaseBranch,l=r?.worktreePrTargetRepo??o?.worktreePrTargetRepo,p=r?.worktreePushRemote??o?.worktreePushRemote;this.updatePersistedSession(n,Ps({worktreeBaseBranch:d,worktreePrTargetRepo:l,worktreePushRemote:p},{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(`
214
+ `),buttons:[[this.makeActionButton(n,"worktree-create-pr","Open PR")]]})}getStoppedStatusLabel(e){return yo(e)}persistSession(e,n={}){let r=n.scheduleRuntimeGc??!0;this.store.hasRecordedSession(e.id)||this.metrics.recordSession(e),this.store.persistTerminal(e),r&&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,n,r="notification"){this.dispatchSessionNotification(e,{label:r,userMessage:n,notifyUser:"always"})}sendMonitorReport(e){let n=this.interactions.getMonitorReportButtons({reportId:e.reportId,route:e.route,planName:e.planName,planPrompt:e.planPrompt,planWorkdir:e.planWorkdir,planWorktreeStrategy:e.planWorktreeStrategy});this.dispatchSessionNotification(this.buildRoutingProxy({id:e.reportId,route:e.route}),{label:"monitor-report",userMessage:e.text,notifyUser:"always",buttons:n})}emitGoalTaskUpdate(e,n,r="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:r,userMessage:n,notifyUser:"always"})}launchMonitorPlan(e){let n=e.route??{provider:"system",target:"system"};return this.spawn({prompt:e.prompt,workdir:e.workdir,name:e.name,harness:Ie(),permissionMode:"plan",planApproval:"ask",worktreeStrategy:e.worktreeStrategy??"off",multiTurn:!0,route:n,originChannel:this.originChannelFromRoute(n),originThreadId:n.threadId,originSessionKey:n.sessionKey})}dispatchSessionNotification(e,n){this.notifications.dispatch(e,n)}originChannelFromRoute(e){return e.accountId?`${e.provider}|${e.accountId}|${e.target}`:`${e.provider}|${e.target}`}debounceWaitingEvent(e){let n=Date.now(),r=this.lastWaitingEventTimestamps.get(e);return r&&n-r<Ex?!1:(this.lastWaitingEventTimestamps.set(e,n),!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,n=1e3){let r=!Number.isFinite(n),o=typeof e.getOutput=="function"?e.getOutput():[],i=r?o.join(`
215
+ `):this.selectCompletionPreviewSource(e);return r?i:i.length>n?this.shouldPreferTailPreview(e)?Ci(i,n):Pf(i,n):i}selectCompletionPreviewSource(e){let n=typeof e.getOutput=="function"?e.getOutput():[],r=n.join(`
216
+ `).trim();return r?this.shouldPreferTailPreview(e)?this.extractLastSubstantiveBlock(r)??r:n.slice(-20).join(`
217
+ `):""}shouldPreferTailPreview(e){if(e.status==="completed"||e.killReason==="done")return!0;let n=e;return n.approvalState==="approved"||n.planModeApproved===!0||(n.planDecisionVersion??0)>0}extractLastSubstantiveBlock(e){let r=e.split(/\n\s*\n+/).map(o=>o.trim()).filter(o=>/[A-Za-z0-9]/.test(o)).at(-1);if(r)return r.length>=120||r.includes(`
218
+ `)?r:void 0}triggerAgentEvent(e){this.lifecycle.emitCompleted(e)}triggerFailedEvent(e,n,r=!1){this.lifecycle.emitFailed(e,n,r)}triggerWaitingForInputEvent(e){this.lifecycle.emitWaitingForInput(e)}resolvePlanApprovalMode(e){return e.planApproval??_.planApproval??"delegate"}onTurnEnd(e,n){this.lifecycle.handleTurnEnd(e,n)}shouldEmitTurnCompleteWake(e){let n=`${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(e.id)===n?(console.info(`[SessionManager] shouldEmitTurnCompleteWake: debounced for session ${e.id} (marker unchanged: ${n})`),!1):(this.lastTurnCompleteMarkers.set(e.id,n),!0)}shouldEmitTerminalWake(e){let n=`${e.status}|${e.completedAt??0}|${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.killReason}`;return this.lastTerminalWakeMarkers.get(e.id)===n?!1:(this.lastTerminalWakeMarkers.set(e.id,n),!0)}triggerTurnCompleteEventWithSignal(e){this.lifecycle.emitTurnComplete(e)}resolve(e){return this.references.resolveActive(e)}get(e){return this.registry.get(e)}list(e){let n=this.registry.list();return e&&e!=="all"&&(n=n.filter(r=>r.status===e)),n.sort((r,o)=>o.startedAt-r.startedAt)}kill(e,n){let r=this.registry.get(e);return r?(r.kill(n??"user"),!0):!1}killAll(e="user"){for(let n of this.sessions.values())_x.has(n.status)&&this.kill(n.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 n=this.store.getPersistedSession(e);return n?.worktreeMerged===!0||n?.worktreeLifecycle?.state==="merged"||n?.worktreeLifecycle?.state==="released"}async enqueueMerge(e,n,r){let o=this.mergeQueues.get(e);o!==void 0&&r&&r();let i=(o??Promise.resolve()).catch(()=>{}).then(()=>n()),s=i.catch(()=>{});return this.mergeQueues.set(e,s),s.finally(()=>{this.mergeQueues.get(e)===s&&this.mergeQueues.delete(e)}),i}updatePersistedSession(e,n){let r=this.stateSync.applySessionPatch(e,n);return r&&this.onPersistedSessionChanged(this.store.getPersistedSession(e)),r}listPersistedSessions(){return this.store.listPersistedSessions()}async handleAskUserQuestion(e,n){let r=this.sessions.get(e);if(!r)throw new Error(`Session "${e}" not found for AskUserQuestion intercept`);return this.questions.handleAskUserQuestion(r,n)}resolveAskUserQuestion(e,n){this.questions.resolveAskUserQuestion(e,n)}async resolvePendingInputOption(e,n){let r=this.sessions.get(e);return r&&await r.submitPendingInputOption(n)?(this.lastWaitingEventTimestamps.delete(e),!0):(this.questions.resolveAskUserQuestion(e,n),!0)}dispose(){this.disposeMaintenance(),this.questions.dispose(),this.notifications.dispose()}};X();Me();var Ih=class{#t;#n;#e=new Map;constructor(t){this.#t=wh(t,1),this.#n=this.#t}get maxEntries(){return this.#n}get size(){return this.#e.size}setMaxEntriesForTest(t){this.#n=typeof t=="number"?wh(t,this.#t):this.#t,this.#r()}clear(){this.#e.clear()}get(t){let e=this.getResult(t);return e.hit?e.value:void 0}getResult(t){if(!this.#e.has(t))return{hit:!1};let e=this.#e.get(t);return this.#e.delete(t),this.#e.set(t,e),{hit:!0,value:e}}set(t,e){this.#e.has(t)&&this.#e.delete(t),this.#e.set(t,e),this.#r()}#r(){for(;this.#e.size>this.#n;){let t=this.#e.keys().next();if(t.done)break;this.#e.delete(t.value)}}};function wh(t,e){return!Number.isFinite(t)||t<=0?e:Math.max(1,Math.floor(t))}var Ox="\\x1b\\[[\\x20-\\x3f]*[\\x40-\\x7e]",Nx="\\x1b\\]8;;.*?(?:\\x1b\\\\|\\x07)|\\x1b\\]8;;(?:\\x1b\\\\|\\x07)",v1=new RegExp(Ox,"g"),P1=new RegExp(Nx,"g"),w1=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;import{createRequire as Dx}from"node:module";var $1=Dx(import.meta.url);var O1=new Ih(512);function bh(t){return{success:!1,error:{issues:[{path:[],message:t}]}}}function Vl(){return{safeParse(t){return t===void 0?{success:!0,data:void 0}:!t||typeof t!="object"||Array.isArray(t)?bh("expected config object"):Object.keys(t).length>0?bh("config must be empty"):{success:!0,data:t}},jsonSchema:{type:"object",additionalProperties:!1,properties:{}}}}function Fx(t,e){let n=!1,r;return()=>(n||(r=(typeof t=="function"?t():t)??e,n=!0),r)}function Js({id:t,name:e,description:n,kind:r,configSchema:o=Vl,reload:i,nodeHostCommands:s,securityAuditCollectors:a,register:d}){let l=Fx(o);return{id:t,name:e,description:n,...r?{kind:r}:{},...i?{reload:i}:{},...s?{nodeHostCommands:s}:{},...a?{securityAuditCollectors:a}:{},get configSchema(){return l()},register:d}}function Kx(t){let e=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"168",10)||168,n=e*60*60*1e3,r=Date.now()-n,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=Ux("git",["rev-parse","--show-toplevel"],{cwd:d.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();l&&i.add(xh(l,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let d of i)try{let l=Lx(d);for(let p of l){if(!p.startsWith("openclaw-worktree-"))continue;let f=xh(d,p);try{let y=Wx(f);if(!y.isDirectory()||y.mtimeMs>r||o.has(f))continue;Bx(f,{recursive:!0,force:!0}),a++}catch(y){console.warn(`[index] Failed to clean up orphaned worktree ${f}: ${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 Vx(t){let e=null,n=null,r=t.registerTool;_i(t.runtime),r(o=>Rf(o),{optional:!1,name:"agent_launch"}),r(o=>Yf(o),{optional:!1,name:"agent_sessions"}),r(o=>Xf(o),{optional:!1,name:"agent_kill"}),r(o=>ns(o),{optional:!1,name:"agent_output"}),r(o=>ng(o),{optional:!1,name:"agent_respond"}),r(o=>rg(o),{optional:!1,name:"agent_request_plan_approval"}),r(o=>ig(o),{optional:!1,name:"agent_send_monitor_report"}),r(o=>sg(o),{optional:!1,name:"agent_stats"}),r(o=>ls(o),{optional:!1,name:"agent_merge"}),r(o=>fo(o),{optional:!1,name:"agent_pr"}),r(o=>lg(o),{optional:!1,name:"agent_worktree_cleanup"}),r(o=>ug(o),{optional:!1,name:"agent_worktree_status"}),r(o=>pg(o),{optional:!1,name:"goal_launch"}),r(o=>mg(o),{optional:!1,name:"goal_status"}),r(o=>fg(o),{optional:!1,name:"goal_stop"}),t.registerInteractiveHandler(yl("telegram")),t.registerInteractiveHandler(yl("discord")),vg(t),Pg(t),wg(t),Ig(t),bg(t),xg(t),Ag(t),Rg(t),Tg(t),t.registerService({id:"openclaw-code-agent",start:o=>{let i=t.pluginConfig??{};Lm(i),_i(t.runtime,o.config),e=new Qs(_.maxSessions,_.maxPersistedSessions),n=new gs(e),Nd(e),Dd(n),n.start(),Kx(e),e.bootstrapMaintenanceSchedules()},stop:()=>{n&&n.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),n=null,e=null,_i(void 0),Dd(null),Nd(null)}})}var TH=Js({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:Vx});export{TH as default,Vx as register};