openclaw-code-agent 4.2.0 → 4.2.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,25 +1,25 @@
1
- var Gh=Object.defineProperty;var p=(t,e)=>()=>(t&&(e=t(t=0)),e);var bo=(t,e)=>{for(var n in e)Gh(t,n,{get:e[n],enumerable:!0})};var _e={};bo(_e,{HasPropertyKey:()=>xo,IsArray:()=>ce,IsAsyncIterator:()=>aa,IsBigInt:()=>kr,IsBoolean:()=>Nt,IsDate:()=>gn,IsFunction:()=>da,IsIterator:()=>la,IsNull:()=>ua,IsNumber:()=>He,IsObject:()=>G,IsRegExp:()=>vr,IsString:()=>Q,IsSymbol:()=>pa,IsUint8Array:()=>Ft,IsUndefined:()=>me});function xo(t,e){return e in t}function aa(t){return G(t)&&!ce(t)&&!Ft(t)&&Symbol.asyncIterator in t}function ce(t){return Array.isArray(t)}function kr(t){return typeof t=="bigint"}function Nt(t){return typeof t=="boolean"}function gn(t){return t instanceof globalThis.Date}function da(t){return typeof t=="function"}function la(t){return G(t)&&!ce(t)&&!Ft(t)&&Symbol.iterator in t}function ua(t){return t===null}function He(t){return typeof t=="number"}function G(t){return typeof t=="object"&&t!==null}function vr(t){return t instanceof globalThis.RegExp}function Q(t){return typeof t=="string"}function pa(t){return typeof t=="symbol"}function Ft(t){return t instanceof globalThis.Uint8Array}function me(t){return t===void 0}var Fe=p(()=>{});function jh(t){return t.map(e=>Ao(e))}function Hh(t){return new Date(t.getTime())}function zh(t){return new Uint8Array(t)}function Qh(t){return new RegExp(t.source,t.flags)}function Jh(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=Ao(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=Ao(t[n]);return e}function Ao(t){return ce(t)?jh(t):gn(t)?Hh(t):Ft(t)?zh(t):vr(t)?Qh(t):G(t)?Jh(t):t}function ee(t){return Ao(t)}var Be=p(()=>{Fe()});function Ln(t,e){return e===void 0?ee(t):ee({...e,...t})}var Ro=p(()=>{Be()});var ca=p(()=>{Ro();Be()});function su(t){return t!==null&&typeof t=="object"}function au(t){return globalThis.Array.isArray(t)&&!globalThis.ArrayBuffer.isView(t)}function du(t){return t===void 0}function lu(t){return typeof t=="number"}var uu=p(()=>{});var pu=p(()=>{uu()});var To,cu=p(()=>{pu();(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=su(s);return t.AllowArrayObject?a:a&&!au(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?lu(s):Number.isFinite(s)}t.IsNumberLike=o;function i(s){let a=du(s);return t.AllowNullVoid?a||s===null:a}t.IsVoidLike=i})(To||(To={}))});function Yh(t){return globalThis.Object.freeze(t).map(e=>Pr(e))}function Xh(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=Pr(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=Pr(t[n]);return globalThis.Object.freeze(e)}function Pr(t){return ce(t)?Yh(t):gn(t)?t:Ft(t)?t:vr(t)?t:G(t)?Xh(t):t}var mu=p(()=>{Fe()});function g(t,e){let n=e!==void 0?{...e,...t}:t;switch(To.InstanceMode){case"freeze":return Pr(n);case"clone":return ee(n);default:return n}}var R=p(()=>{cu();mu();Be()});var Lt=p(()=>{R()});var we,fu=p(()=>{we=class extends Error{constructor(e){super(e)}}});var Ct=p(()=>{fu()});var Se,yt,Ae,st,w,wr=p(()=>{Se=Symbol.for("TypeBox.Transform"),yt=Symbol.for("TypeBox.Readonly"),Ae=Symbol.for("TypeBox.Optional"),st=Symbol.for("TypeBox.Hint"),w=Symbol.for("TypeBox.Kind")});var T=p(()=>{wr()});function Wn(t){return G(t)&&t[yt]==="Readonly"}function Ue(t){return G(t)&&t[Ae]==="Optional"}function ma(t){return D(t,"Any")}function fa(t){return D(t,"Argument")}function kt(t){return D(t,"Array")}function hn(t){return D(t,"AsyncIterator")}function Sn(t){return D(t,"BigInt")}function Wt(t){return D(t,"Boolean")}function vt(t){return D(t,"Computed")}function Pt(t){return D(t,"Constructor")}function Zh(t){return D(t,"Date")}function wt(t){return D(t,"Function")}function It(t){return D(t,"Integer")}function oe(t){return D(t,"Intersect")}function yn(t){return D(t,"Iterator")}function D(t,e){return G(t)&&w in t&&t[w]===e}function Co(t){return Nt(t)||He(t)||Q(t)}function ze(t){return D(t,"Literal")}function Qe(t){return D(t,"MappedKey")}function te(t){return D(t,"MappedResult")}function Ht(t){return D(t,"Never")}function eS(t){return D(t,"Not")}function Ir(t){return D(t,"Null")}function bt(t){return D(t,"Number")}function fe(t){return D(t,"Object")}function kn(t){return D(t,"Promise")}function vn(t){return D(t,"Record")}function de(t){return D(t,"Ref")}function ga(t){return D(t,"RegExp")}function Bt(t){return D(t,"String")}function br(t){return D(t,"Symbol")}function Je(t){return D(t,"TemplateLiteral")}function tS(t){return D(t,"This")}function zt(t){return G(t)&&Se in t}function Ye(t){return D(t,"Tuple")}function xr(t){return D(t,"Undefined")}function F(t){return D(t,"Union")}function nS(t){return D(t,"Uint8Array")}function rS(t){return D(t,"Unknown")}function oS(t){return D(t,"Unsafe")}function iS(t){return D(t,"Void")}function sS(t){return G(t)&&w in t&&Q(t[w])}function Xe(t){return ma(t)||fa(t)||kt(t)||Wt(t)||Sn(t)||hn(t)||vt(t)||Pt(t)||Zh(t)||wt(t)||It(t)||oe(t)||yn(t)||ze(t)||Qe(t)||te(t)||Ht(t)||eS(t)||Ir(t)||bt(t)||fe(t)||kn(t)||vn(t)||de(t)||ga(t)||Bt(t)||br(t)||Je(t)||tS(t)||Ye(t)||xr(t)||F(t)||nS(t)||rS(t)||oS(t)||iS(t)||sS(t)}var W=p(()=>{Fe();T()});var m={};bo(m,{IsAny:()=>yu,IsArgument:()=>ku,IsArray:()=>vu,IsAsyncIterator:()=>Pu,IsBigInt:()=>wu,IsBoolean:()=>Iu,IsComputed:()=>bu,IsConstructor:()=>xu,IsDate:()=>Au,IsFunction:()=>Ru,IsImport:()=>cS,IsInteger:()=>Tu,IsIntersect:()=>Cu,IsIterator:()=>Mu,IsKind:()=>np,IsKindOf:()=>E,IsLiteral:()=>Rr,IsLiteralBoolean:()=>mS,IsLiteralNumber:()=>Eu,IsLiteralString:()=>_u,IsLiteralValue:()=>Ou,IsMappedKey:()=>$u,IsMappedResult:()=>Du,IsNever:()=>Nu,IsNot:()=>Fu,IsNull:()=>Lu,IsNumber:()=>Wu,IsObject:()=>Bu,IsOptional:()=>pS,IsPromise:()=>Uu,IsProperties:()=>Mo,IsReadonly:()=>uS,IsRecord:()=>Ku,IsRecursive:()=>fS,IsRef:()=>Vu,IsRegExp:()=>qu,IsSchema:()=>Ie,IsString:()=>Gu,IsSymbol:()=>ju,IsTemplateLiteral:()=>Hu,IsThis:()=>zu,IsTransform:()=>Qu,IsTuple:()=>Ju,IsUint8Array:()=>Xu,IsUndefined:()=>Yu,IsUnion:()=>ka,IsUnionLiteral:()=>gS,IsUnknown:()=>Zu,IsUnsafe:()=>ep,IsVoid:()=>tp,TypeGuardUnknownTypeError:()=>ha});function gu(t){try{return new RegExp(t),!0}catch{return!1}}function Sa(t){if(!Q(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 hu(t){return ya(t)||Ie(t)}function Ar(t){return me(t)||kr(t)}function J(t){return me(t)||He(t)}function ya(t){return me(t)||Nt(t)}function j(t){return me(t)||Q(t)}function dS(t){return me(t)||Q(t)&&Sa(t)&&gu(t)}function lS(t){return me(t)||Q(t)&&Sa(t)}function Su(t){return me(t)||Ie(t)}function uS(t){return G(t)&&t[yt]==="Readonly"}function pS(t){return G(t)&&t[Ae]==="Optional"}function yu(t){return E(t,"Any")&&j(t.$id)}function ku(t){return E(t,"Argument")&&He(t.index)}function vu(t){return E(t,"Array")&&t.type==="array"&&j(t.$id)&&Ie(t.items)&&J(t.minItems)&&J(t.maxItems)&&ya(t.uniqueItems)&&Su(t.contains)&&J(t.minContains)&&J(t.maxContains)}function Pu(t){return E(t,"AsyncIterator")&&t.type==="AsyncIterator"&&j(t.$id)&&Ie(t.items)}function wu(t){return E(t,"BigInt")&&t.type==="bigint"&&j(t.$id)&&Ar(t.exclusiveMaximum)&&Ar(t.exclusiveMinimum)&&Ar(t.maximum)&&Ar(t.minimum)&&Ar(t.multipleOf)}function Iu(t){return E(t,"Boolean")&&t.type==="boolean"&&j(t.$id)}function bu(t){return E(t,"Computed")&&Q(t.target)&&ce(t.parameters)&&t.parameters.every(e=>Ie(e))}function xu(t){return E(t,"Constructor")&&t.type==="Constructor"&&j(t.$id)&&ce(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function Au(t){return E(t,"Date")&&t.type==="Date"&&j(t.$id)&&J(t.exclusiveMaximumTimestamp)&&J(t.exclusiveMinimumTimestamp)&&J(t.maximumTimestamp)&&J(t.minimumTimestamp)&&J(t.multipleOfTimestamp)}function Ru(t){return E(t,"Function")&&t.type==="Function"&&j(t.$id)&&ce(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function cS(t){return E(t,"Import")&&xo(t,"$defs")&&G(t.$defs)&&Mo(t.$defs)&&xo(t,"$ref")&&Q(t.$ref)&&t.$ref in t.$defs}function Tu(t){return E(t,"Integer")&&t.type==="integer"&&j(t.$id)&&J(t.exclusiveMaximum)&&J(t.exclusiveMinimum)&&J(t.maximum)&&J(t.minimum)&&J(t.multipleOf)}function Mo(t){return G(t)&&Object.entries(t).every(([e,n])=>Sa(e)&&Ie(n))}function Cu(t){return E(t,"Intersect")&&!(Q(t.type)&&t.type!=="object")&&ce(t.allOf)&&t.allOf.every(e=>Ie(e)&&!Qu(e))&&j(t.type)&&(ya(t.unevaluatedProperties)||Su(t.unevaluatedProperties))&&j(t.$id)}function Mu(t){return E(t,"Iterator")&&t.type==="Iterator"&&j(t.$id)&&Ie(t.items)}function E(t,e){return G(t)&&w in t&&t[w]===e}function _u(t){return Rr(t)&&Q(t.const)}function Eu(t){return Rr(t)&&He(t.const)}function mS(t){return Rr(t)&&Nt(t.const)}function Rr(t){return E(t,"Literal")&&j(t.$id)&&Ou(t.const)}function Ou(t){return Nt(t)||He(t)||Q(t)}function $u(t){return E(t,"MappedKey")&&ce(t.keys)&&t.keys.every(e=>He(e)||Q(e))}function Du(t){return E(t,"MappedResult")&&Mo(t.properties)}function Nu(t){return E(t,"Never")&&G(t.not)&&Object.getOwnPropertyNames(t.not).length===0}function Fu(t){return E(t,"Not")&&Ie(t.not)}function Lu(t){return E(t,"Null")&&t.type==="null"&&j(t.$id)}function Wu(t){return E(t,"Number")&&t.type==="number"&&j(t.$id)&&J(t.exclusiveMaximum)&&J(t.exclusiveMinimum)&&J(t.maximum)&&J(t.minimum)&&J(t.multipleOf)}function Bu(t){return E(t,"Object")&&t.type==="object"&&j(t.$id)&&Mo(t.properties)&&hu(t.additionalProperties)&&J(t.minProperties)&&J(t.maxProperties)}function Uu(t){return E(t,"Promise")&&t.type==="Promise"&&j(t.$id)&&Ie(t.item)}function Ku(t){return E(t,"Record")&&t.type==="object"&&j(t.$id)&&hu(t.additionalProperties)&&G(t.patternProperties)&&(e=>{let n=Object.getOwnPropertyNames(e.patternProperties);return n.length===1&&gu(n[0])&&G(e.patternProperties)&&Ie(e.patternProperties[n[0]])})(t)}function fS(t){return G(t)&&st in t&&t[st]==="Recursive"}function Vu(t){return E(t,"Ref")&&j(t.$id)&&Q(t.$ref)}function qu(t){return E(t,"RegExp")&&j(t.$id)&&Q(t.source)&&Q(t.flags)&&J(t.maxLength)&&J(t.minLength)}function Gu(t){return E(t,"String")&&t.type==="string"&&j(t.$id)&&J(t.minLength)&&J(t.maxLength)&&dS(t.pattern)&&lS(t.format)}function ju(t){return E(t,"Symbol")&&t.type==="symbol"&&j(t.$id)}function Hu(t){return E(t,"TemplateLiteral")&&t.type==="string"&&Q(t.pattern)&&t.pattern[0]==="^"&&t.pattern[t.pattern.length-1]==="$"}function zu(t){return E(t,"This")&&j(t.$id)&&Q(t.$ref)}function Qu(t){return G(t)&&Se in t}function Ju(t){return E(t,"Tuple")&&t.type==="array"&&j(t.$id)&&He(t.minItems)&&He(t.maxItems)&&t.minItems===t.maxItems&&(me(t.items)&&me(t.additionalItems)&&t.minItems===0||ce(t.items)&&t.items.every(e=>Ie(e)))}function Yu(t){return E(t,"Undefined")&&t.type==="undefined"&&j(t.$id)}function gS(t){return ka(t)&&t.anyOf.every(e=>_u(e)||Eu(e))}function ka(t){return E(t,"Union")&&j(t.$id)&&G(t)&&ce(t.anyOf)&&t.anyOf.every(e=>Ie(e))}function Xu(t){return E(t,"Uint8Array")&&t.type==="Uint8Array"&&j(t.$id)&&J(t.minByteLength)&&J(t.maxByteLength)}function Zu(t){return E(t,"Unknown")&&j(t.$id)}function ep(t){return E(t,"Unsafe")}function tp(t){return E(t,"Void")&&t.type==="void"&&j(t.$id)}function np(t){return G(t)&&w in t&&Q(t[w])&&!aS.includes(t[w])}function Ie(t){return G(t)&&(yu(t)||ku(t)||vu(t)||Iu(t)||wu(t)||Pu(t)||bu(t)||xu(t)||Au(t)||Ru(t)||Tu(t)||Cu(t)||Mu(t)||Rr(t)||$u(t)||Du(t)||Nu(t)||Fu(t)||Lu(t)||Wu(t)||Bu(t)||Uu(t)||Ku(t)||Vu(t)||qu(t)||Gu(t)||ju(t)||Hu(t)||zu(t)||Ju(t)||Yu(t)||ka(t)||Xu(t)||Zu(t)||ep(t)||tp(t)||np(t))}var ha,aS,rp=p(()=>{Fe();T();Ct();ha=class extends we{},aS=["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 va=p(()=>{W();rp();Fe()});var op=p(()=>{});var ip=p(()=>{op()});var Pa,Tr,wa,hS,QA,Qt,Jt,sp,ap=p(()=>{Pa="(true|false)",Tr="(0|[1-9][0-9]*)",wa="(.*)",hS="(?!.*)",QA=`^${Pa}$`,Qt=`^${Tr}$`,Jt=`^${wa}$`,sp=`^${hS}$`});var Cr=p(()=>{ap()});var dp=p(()=>{});var lp=p(()=>{});var up=p(()=>{dp();lp()});function pp(t,e){return t.includes(e)}function cp(t){return[...new Set(t)]}function kS(t,e){return t.filter(n=>e.includes(n))}function vS(t,e){return t.reduce((n,r)=>kS(n,r),e)}function mp(t){return t.length===1?t[0]:t.length>1?vS(t.slice(1),t[0]):[]}function fp(t){let e=[];for(let n of t)e.push(...n);return e}var gp=p(()=>{});var Mr=p(()=>{gp()});function Yt(t){return g({[w]:"Any"},t)}var hp=p(()=>{Lt();T()});var _r=p(()=>{hp()});function Bn(t,e){return g({[w]:"Array",type:"array",items:t},e)}var Sp=p(()=>{R();T()});var Er=p(()=>{Sp()});function yp(t){return g({[w]:"Argument",index:t})}var kp=p(()=>{R();T()});var Ia=p(()=>{kp()});function Un(t,e){return g({[w]:"AsyncIterator",type:"AsyncIterator",items:t},e)}var vp=p(()=>{T();R()});var Or=p(()=>{vp()});function Z(t,e,n){return g({[w]:"Computed",target:t,parameters:e},n)}var Pp=p(()=>{Lt();wr()});var Xt=p(()=>{Pp()});function PS(t,e){let{[e]:n,...r}=t;return r}function ie(t,e){return e.reduce((n,r)=>PS(n,r),t)}var _o=p(()=>{});var Kt=p(()=>{_o()});function L(t){return g({[w]:"Never",not:{}},t)}var wp=p(()=>{R();T()});var Re=p(()=>{wp()});var Ip=p(()=>{});function B(t){return g({[w]:"MappedResult",properties:t})}var ba=p(()=>{R();T()});function Kn(t,e,n){return g({[w]:"Constructor",type:"Constructor",parameters:t,returns:e},n)}var bp=p(()=>{R();T()});var $r=p(()=>{bp()});function Mt(t,e,n){return g({[w]:"Function",type:"Function",parameters:t,returns:e},n)}var xp=p(()=>{R();T()});var Pn=p(()=>{xp()});function Dr(t,e){return g({[w]:"Union",anyOf:t},e)}var xa=p(()=>{R();T()});function wS(t){return t.some(e=>Ue(e))}function Ap(t){return t.map(e=>Ue(e)?IS(e):e)}function IS(t){return ie(t,[Ae])}function bS(t,e){return wS(t)?Ee(Dr(Ap(t),e)):Dr(Ap(t),e)}function _t(t,e){return t.length===1?g(t[0],e):t.length===0?L(e):bS(t,e)}var Rp=p(()=>{R();T();Kt();Re();Vt();xa();W()});var Tp=p(()=>{});function V(t,e){return t.length===0?L(e):t.length===1?g(t[0],e):Dr(t,e)}var Cp=p(()=>{Re();R();xa()});var ye=p(()=>{Rp();Tp();Cp()});function xS(t){return t.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Aa(t,e,n){return t[e]===n&&t.charCodeAt(e-1)!==92}function qt(t,e){return Aa(t,e,"(")}function Nr(t,e){return Aa(t,e,")")}function Mp(t,e){return Aa(t,e,"|")}function AS(t){if(!(qt(t,0)&&Nr(t,t.length-1)))return!1;let e=0;for(let n=0;n<t.length;n++)if(qt(t,n)&&(e+=1),Nr(t,n)&&(e-=1),e===0&&n!==t.length-1)return!1;return!0}function RS(t){return t.slice(1,t.length-1)}function TS(t){let e=0;for(let n=0;n<t.length;n++)if(qt(t,n)&&(e+=1),Nr(t,n)&&(e-=1),Mp(t,n)&&e===0)return!0;return!1}function CS(t){for(let e=0;e<t.length;e++)if(qt(t,e))return!0;return!1}function MS(t){let[e,n]=[0,0],r=[];for(let i=0;i<t.length;i++)if(qt(t,i)&&(e+=1),Nr(t,i)&&(e-=1),Mp(t,i)&&e===0){let s=t.slice(n,i);s.length>0&&r.push(Vn(s)),n=i+1}let o=t.slice(n);return o.length>0&&r.push(Vn(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function _S(t){function e(o,i){if(!qt(o,i))throw new Eo("TemplateLiteralParser: Index must point to open parens");let s=0;for(let a=i;a<o.length;a++)if(qt(o,a)&&(s+=1),Nr(o,a)&&(s-=1),s===0)return[i,a];throw new Eo("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,i){for(let s=i;s<o.length;s++)if(qt(o,s))return[i,s];return[i,o.length]}let r=[];for(let o=0;o<t.length;o++)if(qt(t,o)){let[i,s]=e(t,o),a=t.slice(i,s+1);r.push(Vn(a)),o=s}else{let[i,s]=n(t,o),a=t.slice(i,s);a.length>0&&r.push(Vn(a)),o=s-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function Vn(t){return AS(t)?Vn(RS(t)):TS(t)?MS(t):CS(t)?_S(t):{type:"const",const:xS(t)}}function qn(t){return Vn(t.slice(1,t.length-1))}var Eo,Oo=p(()=>{Ct();Eo=class extends we{}});function ES(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 OS(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 $S(t){return t.type==="const"&&t.const===".*"}function wn(t){return ES(t)||$S(t)?!1:OS(t)?!0:t.type==="and"?t.expr.every(e=>wn(e)):t.type==="or"?t.expr.every(e=>wn(e)):t.type==="const"?!0:(()=>{throw new Ra("Unknown expression type")})()}function _p(t){let e=qn(t.pattern);return wn(e)}var Ra,Ta=p(()=>{Oo();Ct();Ra=class extends we{}});function*Ep(t){if(t.length===1)return yield*t[0];for(let e of t[0])for(let n of Ep(t.slice(1)))yield`${e}${n}`}function*DS(t){return yield*Ep(t.expr.map(e=>[...Fr(e)]))}function*NS(t){for(let e of t.expr)yield*Fr(e)}function*FS(t){return yield t.const}function*Fr(t){return t.type==="and"?yield*DS(t):t.type==="or"?yield*NS(t):t.type==="const"?yield*FS(t):(()=>{throw new Ca("Unknown expression")})()}function $o(t){let e=qn(t.pattern);return wn(e)?[...Fr(e)]:[]}var Ca,Ma=p(()=>{Ta();Oo();Ct();Ca=class extends we{}});function K(t,e){return g({[w]:"Literal",const:t,type:typeof t},e)}var Op=p(()=>{R();T()});var Ke=p(()=>{Op()});function Do(t){return g({[w]:"Boolean",type:"boolean"},t)}var $p=p(()=>{T();Lt()});var No=p(()=>{$p()});function Gn(t){return g({[w]:"BigInt",type:"bigint"},t)}var Dp=p(()=>{T();Lt()});var Lr=p(()=>{Dp()});function at(t){return g({[w]:"Number",type:"number"},t)}var Np=p(()=>{R();T()});var In=p(()=>{Np()});function xt(t){return g({[w]:"String",type:"string"},t)}var Fp=p(()=>{R();T()});var jn=p(()=>{Fp()});function*LS(t){let e=t.trim().replace(/"|'/g,"");return e==="boolean"?yield Do():e==="number"?yield at():e==="bigint"?yield Gn():e==="string"?yield xt():yield(()=>{let n=e.split("|").map(r=>K(r.trim()));return n.length===0?L():n.length===1?n[0]:_t(n)})()}function*WS(t){if(t[1]!=="{"){let e=K("$"),n=_a(t.slice(1));return yield*[e,...n]}for(let e=2;e<t.length;e++)if(t[e]==="}"){let n=LS(t.slice(2,e)),r=_a(t.slice(e+1));return yield*[...n,...r]}yield K(t)}function*_a(t){for(let e=0;e<t.length;e++)if(t[e]==="$"){let n=K(t.slice(0,e)),r=WS(t.slice(e));return yield*[n,...r]}yield K(t)}function Lp(t){return[..._a(t)]}var Ea=p(()=>{Ke();No();Lr();In();jn();ye();Re()});function BS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wp(t,e){return Je(t)?t.pattern.slice(1,t.pattern.length-1):F(t)?`(${t.anyOf.map(n=>Wp(n,e)).join("|")})`:bt(t)?`${e}${Tr}`:It(t)?`${e}${Tr}`:Sn(t)?`${e}${Tr}`:Bt(t)?`${e}${wa}`:ze(t)?`${e}${BS(t.const.toString())}`:Wt(t)?`${e}${Pa}`:(()=>{throw new Oa(`Unexpected Kind '${t[w]}'`)})()}function $a(t){return`^${t.map(e=>Wp(e,"")).join("")}$`}var Oa,Da=p(()=>{Cr();T();Ct();W();Oa=class extends we{}});function bn(t){let n=$o(t).map(r=>K(r));return _t(n)}var Bp=p(()=>{ye();Ke();Ma()});function Fo(t,e){let n=Q(t)?$a(Lp(t)):$a(t);return g({[w]:"TemplateLiteral",type:"string",pattern:n},e)}var Up=p(()=>{R();Ea();Da();Fe();T()});var Gt=p(()=>{Ta();Ma();Ea();Oo();Da();Bp();Up()});function US(t){return $o(t).map(n=>n.toString())}function KS(t){let e=[];for(let n of t)e.push(...Ve(n));return e}function VS(t){return[t.toString()]}function Ve(t){return[...new Set(Je(t)?US(t):F(t)?KS(t.anyOf):ze(t)?VS(t.const):bt(t)?["[number]"]:It(t)?["[number]"]:[])]}var Lo=p(()=>{Gt();W()});function qS(t,e,n){let r={};for(let o of Object.getOwnPropertyNames(e))r[o]=Zt(t,Ve(e[o]),n);return r}function GS(t,e,n){return qS(t,e.properties,n)}function Kp(t,e,n){let r=GS(t,e,n);return B(r)}var Na=p(()=>{Pe();Lo();Et()});function qp(t,e){return t.map(n=>Gp(n,e))}function jS(t){return t.filter(e=>!Ht(e))}function HS(t,e){return Wo(jS(qp(t,e)))}function zS(t){return t.some(e=>Ht(e))?[]:t}function QS(t,e){return _t(zS(qp(t,e)))}function JS(t,e){return e in t?t[e]:e==="[number]"?_t(t):L()}function YS(t,e){return e==="[number]"?t:L()}function XS(t,e){return e in t?t[e]:L()}function Gp(t,e){return oe(t)?HS(t.allOf,e):F(t)?QS(t.anyOf,e):Ye(t)?JS(t.items??[],e):kt(t)?YS(t.items,e):fe(t)?XS(t.properties,e):L()}function Fa(t,e){return e.map(n=>Gp(t,n))}function Vp(t,e){return _t(Fa(t,e))}function Zt(t,e,n){if(de(t)||de(e)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!Xe(t)||!Xe(e))throw new we(r);return Z("Index",[t,e])}return te(e)?Kp(t,e,n):Qe(e)?jp(t,e,n):g(Xe(e)?Vp(t,Ve(e)):Vp(t,e),n)}var La=p(()=>{R();Ct();Xt();Re();dt();ye();Lo();Wa();Na();W()});function ZS(t,e,n){return{[e]:Zt(t,[e],ee(n))}}function ey(t,e,n){return e.reduce((r,o)=>({...r,...ZS(t,o,n)}),{})}function ty(t,e,n){return ey(t,e.keys,n)}function jp(t,e,n){let r=ty(t,e,n);return B(r)}var Wa=p(()=>{La();Pe();Be()});var Et=p(()=>{Wa();Na();Lo();La()});function Hn(t,e){return g({[w]:"Iterator",type:"Iterator",items:t},e)}var Hp=p(()=>{R();T()});var Wr=p(()=>{Hp()});function ny(t){return globalThis.Object.keys(t).filter(e=>!Ue(t[e]))}function ry(t,e){let n=ny(t),r=n.length>0?{[w]:"Object",type:"object",required:n,properties:t}:{[w]:"Object",type:"object",properties:t};return g(r,e)}var H,zp=p(()=>{R();T();W();H=ry});var Ze=p(()=>{zp()});function Bo(t,e){return g({[w]:"Promise",type:"Promise",item:t},e)}var Qp=p(()=>{R();T()});var Uo=p(()=>{Qp()});function oy(t){return g(ie(t,[yt]))}function iy(t){return g({...t,[yt]:"Readonly"})}function sy(t,e){return e===!1?oy(t):iy(t)}function qe(t,e){let n=e??!0;return te(t)?Jp(t,n):sy(t,n)}var Ba=p(()=>{R();T();Kt();Ua();W()});function ay(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=qe(t[r],e);return n}function dy(t,e){return ay(t.properties,e)}function Jp(t,e){let n=dy(t,e);return B(n)}var Ua=p(()=>{Pe();Ba()});var xn=p(()=>{Ua();Ba()});function lt(t,e){return g(t.length>0?{[w]:"Tuple",type:"array",items:t,additionalItems:!1,minItems:t.length,maxItems:t.length}:{[w]:"Tuple",type:"array",minItems:t.length,maxItems:t.length},e)}var Yp=p(()=>{R();T()});var en=p(()=>{Yp()});function Xp(t,e){return t in e?ut(t,e[t]):B(e)}function ly(t){return{[t]:K(t)}}function uy(t){let e={};for(let n of t)e[n]=K(n);return e}function py(t,e){return pp(e,t)?ly(t):uy(e)}function cy(t,e){let n=py(t,e);return Xp(t,n)}function Br(t,e){return e.map(n=>ut(t,n))}function my(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ut(t,e[r]);return n}function ut(t,e){let n={...e};return Ue(e)?Ee(ut(t,ie(e,[Ae]))):Wn(e)?qe(ut(t,ie(e,[yt]))):te(e)?Xp(t,e.properties):Qe(e)?cy(t,e.keys):Pt(e)?Kn(Br(t,e.parameters),ut(t,e.returns),n):wt(e)?Mt(Br(t,e.parameters),ut(t,e.returns),n):hn(e)?Un(ut(t,e.items),n):yn(e)?Hn(ut(t,e.items),n):oe(e)?Oe(Br(t,e.allOf),n):F(e)?V(Br(t,e.anyOf),n):Ye(e)?lt(Br(t,e.items??[]),n):fe(e)?H(my(t,e.properties),n):kt(e)?Bn(ut(t,e.items),n):kn(e)?Bo(ut(t,e.item),n):e}function fy(t,e){let n={};for(let r of t)n[r]=ut(r,e);return n}function Zp(t,e,n){let r=Xe(t)?Ve(t):t,o=e({[w]:"MappedKey",keys:r}),i=fy(r,o);return H(i,n)}var ec=p(()=>{T();Kt();Er();Or();$r();Pn();Et();dt();Wr();Ke();Ze();Vt();Uo();xn();en();ye();Mr();ba();W()});var Pe=p(()=>{Ip();ba();ec()});function gy(t){return g(ie(t,[Ae]))}function hy(t){return g({...t,[Ae]:"Optional"})}function Sy(t,e){return e===!1?gy(t):hy(t)}function Ee(t,e){let n=e??!0;return te(t)?tc(t,n):Sy(t,n)}var Ka=p(()=>{R();T();Kt();Va();W()});function yy(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=Ee(t[r],e);return n}function ky(t,e){return yy(t.properties,e)}function tc(t,e){let n=ky(t,e);return B(n)}var Va=p(()=>{Pe();Ka()});var Vt=p(()=>{Va();Ka()});function Ur(t,e={}){let n=t.every(o=>fe(o)),r=Xe(e.unevaluatedProperties)?{unevaluatedProperties:e.unevaluatedProperties}:{};return g(e.unevaluatedProperties===!1||Xe(e.unevaluatedProperties)||n?{...r,[w]:"Intersect",type:"object",allOf:t}:{...r,[w]:"Intersect",allOf:t},e)}var qa=p(()=>{R();T();W()});function vy(t){return t.every(e=>Ue(e))}function Py(t){return ie(t,[Ae])}function nc(t){return t.map(e=>Ue(e)?Py(e):e)}function wy(t,e){return vy(t)?Ee(Ur(nc(t),e)):Ur(nc(t),e)}function Wo(t,e={}){if(t.length===1)return g(t[0],e);if(t.length===0)return L(e);if(t.some(n=>zt(n)))throw new Error("Cannot intersect transform types");return wy(t,e)}var rc=p(()=>{T();R();Kt();Re();Vt();qa();W()});var oc=p(()=>{});function Oe(t,e){if(t.length===1)return g(t[0],e);if(t.length===0)return L(e);if(t.some(n=>zt(n)))throw new Error("Cannot intersect transform types");return Ur(t,e)}var ic=p(()=>{R();Re();qa();W()});var dt=p(()=>{rc();oc();ic()});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 we("Ref: $ref must be a string");return g({[w]:"Ref",$ref:e},n)}var sc=p(()=>{Ct();R();T()});var An=p(()=>{sc()});function Iy(t,e){return Z("Awaited",[Z(t,e)])}function by(t){return Z("Awaited",[Ot(t)])}function xy(t){return Oe(ac(t))}function Ay(t){return V(ac(t))}function Ry(t){return zn(t)}function ac(t){return t.map(e=>zn(e))}function zn(t,e){return g(vt(t)?Iy(t.target,t.parameters):oe(t)?xy(t.allOf):F(t)?Ay(t.anyOf):kn(t)?Ry(t.item):de(t)?by(t.$ref):t,e)}var dc=p(()=>{R();Xt();dt();ye();An();W()});var Ko=p(()=>{dc()});function lc(t){let e=[];for(let n of t)e.push(Kr(n));return e}function Ty(t){let e=lc(t);return fp(e)}function Cy(t){let e=lc(t);return mp(e)}function My(t){return t.map((e,n)=>n.toString())}function _y(t){return["[number]"]}function Ey(t){return globalThis.Object.getOwnPropertyNames(t)}function Oy(t){return $y?globalThis.Object.getOwnPropertyNames(t).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function Kr(t){return oe(t)?Ty(t.allOf):F(t)?Cy(t.anyOf):Ye(t)?My(t.items??[]):kt(t)?_y(t.items):fe(t)?Ey(t.properties):vn(t)?Oy(t.patternProperties):[]}var $y,Ga=p(()=>{Mr();W();$y=!1});function Dy(t,e){return Z("KeyOf",[Z(t,e)])}function Ny(t){return Z("KeyOf",[Ot(t)])}function Fy(t,e){let n=Kr(t),r=Ly(n),o=_t(r);return g(o,e)}function Ly(t){return t.map(e=>e==="[number]"?at():K(e))}function Qn(t,e){return vt(t)?Dy(t.target,t.parameters):de(t)?Ny(t.$ref):te(t)?uc(t,e):Fy(t,e)}var ja=p(()=>{R();Ke();In();Xt();An();Ga();ye();Ha();W()});function Wy(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=Qn(t[r],ee(e));return n}function By(t,e){return Wy(t.properties,e)}function uc(t,e){let n=By(t,e);return B(n)}var Ha=p(()=>{Pe();ja();Be()});var pc=p(()=>{});var Vr=p(()=>{Ha();pc();Ga();ja()});function Uy(t){let e=[];for(let n of t)e.push(...Kr(n));return cp(e)}function Ky(t){return t.filter(e=>!Ht(e))}function Vy(t,e){let n=[];for(let r of t)n.push(...Fa(r,[e]));return Ky(n)}function qy(t,e){let n={};for(let r of e)n[r]=Wo(Vy(t,r));return n}function cc(t,e){let n=Uy(t),r=qy(t,n);return H(r,e)}var mc=p(()=>{dt();Et();Vr();Ze();Mr();W()});var za=p(()=>{mc()});function Vo(t){return g({[w]:"Date",type:"Date"},t)}var fc=p(()=>{T();R()});var qo=p(()=>{fc()});function Go(t){return g({[w]:"Null",type:"null"},t)}var gc=p(()=>{R();T()});var jo=p(()=>{gc()});function Ho(t){return g({[w]:"Symbol",type:"symbol"},t)}var hc=p(()=>{R();T()});var zo=p(()=>{hc()});function Qo(t){return g({[w]:"Undefined",type:"undefined"},t)}var Sc=p(()=>{R();T()});var Jo=p(()=>{Sc()});function Yo(t){return g({[w]:"Uint8Array",type:"Uint8Array"},t)}var yc=p(()=>{R();T()});var Xo=p(()=>{yc()});function tn(t){return g({[w]:"Unknown"},t)}var kc=p(()=>{R();T()});var Jn=p(()=>{kc()});function Gy(t){return t.map(e=>Qa(e,!1))}function jy(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=qe(Qa(t[n],!1));return e}function Zo(t,e){return e===!0?t:qe(t)}function Qa(t,e){return aa(t)?Zo(Yt(),e):la(t)?Zo(Yt(),e):ce(t)?qe(lt(Gy(t))):Ft(t)?Yo():gn(t)?Vo():G(t)?Zo(H(jy(t)),e):da(t)?Zo(Mt([],tn()),e):me(t)?Qo():ua(t)?Go():pa(t)?Ho():kr(t)?Gn():He(t)?K(t):Nt(t)?K(t):Q(t)?K(t):H({})}function vc(t,e){return g(Qa(t,!0),e)}var Pc=p(()=>{_r();Lr();qo();Pn();Ke();jo();Ze();zo();en();xn();Jo();Xo();Jn();Lt();Fe()});var Ja=p(()=>{Pc()});function wc(t,e){return Pt(t)?lt(t.parameters,e):L(e)}var Ic=p(()=>{en();Re();W()});var Ya=p(()=>{Ic()});function bc(t,e){if(me(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=>K(i));return V(o,{...e,[st]:"Enum"})}var xc=p(()=>{Ke();T();ye();Fe()});var Xa=p(()=>{xc()});function pt(t){return t===h.False?t:h.True}function Yn(t){throw new ed(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)?Ec(t,e):m.IsIntersect(e)?ei(t,e):m.IsUnion(e)?od(t,e):m.IsUnknown(e)?Nc(t,e):m.IsAny(e)?rd(t,e):Yn("StructuralRight")}function rd(t,e){return h.True}function Hy(t,e){return m.IsIntersect(e)?ei(t,e):m.IsUnion(e)&&e.anyOf.some(n=>m.IsAny(n)||m.IsUnknown(n))?h.True:m.IsUnion(e)?h.Union:m.IsUnknown(e)||m.IsAny(e)?h.True:h.Union}function zy(t,e){return m.IsUnknown(t)?h.False:m.IsAny(t)?h.Union:m.IsNever(t)?h.True:h.False}function Qy(t,e){return m.IsObject(e)&&ti(e)?h.True:ke(e)?ve(t,e):m.IsArray(e)?pt(z(t.items,e.items)):h.False}function Jy(t,e){return ke(e)?ve(t,e):m.IsAsyncIterator(e)?pt(z(t.items,e.items)):h.False}function Yy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsBigInt(e)?h.True:h.False}function Mc(t,e){return m.IsLiteralBoolean(t)||m.IsBoolean(t)?h.True:h.False}function Xy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsBoolean(e)?h.True:h.False}function Zy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsConstructor(e)?t.parameters.length>e.parameters.length?h.False:t.parameters.every((n,r)=>pt(z(e.parameters[r],n))===h.True)?pt(z(t.returns,e.returns)):h.False:h.False}function ek(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsDate(e)?h.True:h.False}function tk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsFunction(e)?t.parameters.length>e.parameters.length?h.False:t.parameters.every((n,r)=>pt(z(e.parameters[r],n))===h.True)?pt(z(t.returns,e.returns)):h.False:h.False}function _c(t,e){return m.IsLiteral(t)&&_e.IsNumber(t.const)||m.IsNumber(t)||m.IsInteger(t)?h.True:h.False}function nk(t,e){return m.IsInteger(e)||m.IsNumber(e)?h.True:ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):h.False}function ei(t,e){return e.allOf.every(n=>z(t,n)===h.True)?h.True:h.False}function rk(t,e){return t.allOf.some(n=>z(n,e)===h.True)?h.True:h.False}function ok(t,e){return ke(e)?ve(t,e):m.IsIterator(e)?pt(z(t.items,e.items)):h.False}function ik(t,e){return m.IsLiteral(e)&&e.const===t.const?h.True:ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsString(e)?Dc(t,e):m.IsNumber(e)?Oc(t,e):m.IsInteger(e)?_c(t,e):m.IsBoolean(e)?Mc(t,e):h.False}function Ec(t,e){return h.False}function sk(t,e){return h.True}function Ac(t){let[e,n]=[t,0];for(;m.IsNot(e);)e=e.not,n+=1;return n%2===0?e:tn()}function ak(t,e){return m.IsNot(t)?z(Ac(t),e):m.IsNot(e)?z(t,Ac(e)):Yn("Invalid fallthrough for Not")}function dk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsNull(e)?h.True:h.False}function Oc(t,e){return m.IsLiteralNumber(t)||m.IsNumber(t)||m.IsInteger(t)?h.True:h.False}function lk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsInteger(e)||m.IsNumber(e)?h.True:h.False}function Ge(t,e){return Object.getOwnPropertyNames(t.properties).length===e}function Rc(t){return ti(t)}function Tc(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 Za(t){return Ge(t,0)}function Cc(t){return Ge(t,0)}function uk(t){return Ge(t,0)}function pk(t){return Ge(t,0)}function ck(t){return ti(t)}function mk(t){let e=at();return Ge(t,0)||Ge(t,1)&&"length"in t.properties&&pt(z(t.properties.length,e))===h.True}function fk(t){return Ge(t,0)}function ti(t){let e=at();return Ge(t,0)||Ge(t,1)&&"length"in t.properties&&pt(z(t.properties.length,e))===h.True}function gk(t){let e=Mt([Yt()],Yt());return Ge(t,0)||Ge(t,1)&&"then"in t.properties&&pt(z(t.properties.then,e))===h.True}function $c(t,e){return z(t,e)===h.False||m.IsOptional(t)&&!m.IsOptional(e)?h.False:h.True}function $e(t,e){return m.IsUnknown(t)?h.False:m.IsAny(t)?h.Union:m.IsNever(t)||m.IsLiteralString(t)&&Rc(e)||m.IsLiteralNumber(t)&&Za(e)||m.IsLiteralBoolean(t)&&Cc(e)||m.IsSymbol(t)&&Tc(e)||m.IsBigInt(t)&&uk(e)||m.IsString(t)&&Rc(e)||m.IsSymbol(t)&&Tc(e)||m.IsNumber(t)&&Za(e)||m.IsInteger(t)&&Za(e)||m.IsBoolean(t)&&Cc(e)||m.IsUint8Array(t)&&ck(e)||m.IsDate(t)&&pk(e)||m.IsConstructor(t)&&fk(e)||m.IsFunction(t)&&mk(e)?h.True:m.IsRecord(t)&&m.IsString(td(t))?e[st]==="Record"?h.True:h.False:m.IsRecord(t)&&m.IsNumber(td(t))&&Ge(e,0)?h.True:h.False}function hk(t,e){return ke(e)?ve(t,e):m.IsRecord(e)?ct(t,e):m.IsObject(e)?(()=>{for(let n of Object.getOwnPropertyNames(e.properties)){if(!(n in t.properties)&&!m.IsOptional(e.properties[n]))return h.False;if(m.IsOptional(e.properties[n]))return h.True;if($c(t.properties[n],e.properties[n])===h.False)return h.False}return h.True})():h.False}function Sk(t,e){return ke(e)?ve(t,e):m.IsObject(e)&&gk(e)?h.True:m.IsPromise(e)?pt(z(t.item,e.item)):h.False}function td(t){return Qt in t.patternProperties?at():Jt in t.patternProperties?xt():Yn("Unknown record key pattern")}function nd(t){return Qt in t.patternProperties?t.patternProperties[Qt]:Jt in t.patternProperties?t.patternProperties[Jt]:Yn("Unable to get record value schema")}function ct(t,e){let[n,r]=[td(e),nd(e)];return m.IsLiteralString(t)&&m.IsNumber(n)&&pt(z(t,r))===h.True?h.True:m.IsUint8Array(t)&&m.IsNumber(n)||m.IsString(t)&&m.IsNumber(n)||m.IsArray(t)&&m.IsNumber(n)?z(t,r):m.IsObject(t)?(()=>{for(let o of Object.getOwnPropertyNames(t.properties))if($c(r,t.properties[o])===h.False)return h.False;return h.True})():h.False}function yk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?z(nd(t),nd(e)):h.False}function kk(t,e){let n=m.IsRegExp(t)?xt():t,r=m.IsRegExp(e)?xt():e;return z(n,r)}function Dc(t,e){return m.IsLiteral(t)&&_e.IsString(t.const)||m.IsString(t)?h.True:h.False}function vk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsString(e)?h.True:h.False}function Pk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsSymbol(e)?h.True:h.False}function wk(t,e){return m.IsTemplateLiteral(t)?z(bn(t),e):m.IsTemplateLiteral(e)?z(t,bn(e)):Yn("Invalid fallthrough for TemplateLiteral")}function Ik(t,e){return m.IsArray(e)&&t.items!==void 0&&t.items.every(n=>z(n,e.items)===h.True)}function bk(t,e){return m.IsNever(t)?h.True:m.IsUnknown(t)?h.False:m.IsAny(t)?h.Union:h.False}function xk(t,e){return ke(e)?ve(t,e):m.IsObject(e)&&ti(e)||m.IsArray(e)&&Ik(t,e)?h.True:m.IsTuple(e)?_e.IsUndefined(t.items)&&!_e.IsUndefined(e.items)||!_e.IsUndefined(t.items)&&_e.IsUndefined(e.items)?h.False:_e.IsUndefined(t.items)&&!_e.IsUndefined(e.items)||t.items.every((n,r)=>z(n,e.items[r])===h.True)?h.True:h.False:h.False}function Ak(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsUint8Array(e)?h.True:h.False}function Rk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsVoid(e)?Mk(t,e):m.IsUndefined(e)?h.True:h.False}function od(t,e){return e.anyOf.some(n=>z(t,n)===h.True)?h.True:h.False}function Tk(t,e){return t.anyOf.every(n=>z(n,e)===h.True)?h.True:h.False}function Nc(t,e){return h.True}function Ck(t,e){return m.IsNever(e)?Ec(t,e):m.IsIntersect(e)?ei(t,e):m.IsUnion(e)?od(t,e):m.IsAny(e)?rd(t,e):m.IsString(e)?Dc(t,e):m.IsNumber(e)?Oc(t,e):m.IsInteger(e)?_c(t,e):m.IsBoolean(e)?Mc(t,e):m.IsArray(e)?zy(t,e):m.IsTuple(e)?bk(t,e):m.IsObject(e)?$e(t,e):m.IsUnknown(e)?h.True:h.False}function Mk(t,e){return m.IsUndefined(t)||m.IsUndefined(t)?h.True:h.False}function _k(t,e){return m.IsIntersect(e)?ei(t,e):m.IsUnion(e)?od(t,e):m.IsUnknown(e)?Nc(t,e):m.IsAny(e)?rd(t,e):m.IsObject(e)?$e(t,e):m.IsVoid(e)?h.True:h.False}function z(t,e){return m.IsTemplateLiteral(t)||m.IsTemplateLiteral(e)?wk(t,e):m.IsRegExp(t)||m.IsRegExp(e)?kk(t,e):m.IsNot(t)||m.IsNot(e)?ak(t,e):m.IsAny(t)?Hy(t,e):m.IsArray(t)?Qy(t,e):m.IsBigInt(t)?Yy(t,e):m.IsBoolean(t)?Xy(t,e):m.IsAsyncIterator(t)?Jy(t,e):m.IsConstructor(t)?Zy(t,e):m.IsDate(t)?ek(t,e):m.IsFunction(t)?tk(t,e):m.IsInteger(t)?nk(t,e):m.IsIntersect(t)?rk(t,e):m.IsIterator(t)?ok(t,e):m.IsLiteral(t)?ik(t,e):m.IsNever(t)?sk(t,e):m.IsNull(t)?dk(t,e):m.IsNumber(t)?lk(t,e):m.IsObject(t)?hk(t,e):m.IsRecord(t)?yk(t,e):m.IsString(t)?vk(t,e):m.IsSymbol(t)?Pk(t,e):m.IsTuple(t)?xk(t,e):m.IsPromise(t)?Sk(t,e):m.IsUint8Array(t)?Ak(t,e):m.IsUndefined(t)?Rk(t,e):m.IsUnion(t)?Tk(t,e):m.IsUnknown(t)?Ck(t,e):m.IsVoid(t)?_k(t,e):Yn(`Unknown left type operand '${t[w]}'`)}function nn(t,e){return z(t,e)}var ed,h,id=p(()=>{_r();Pn();In();jn();Jn();Gt();Cr();T();Ct();va();ed=class extends we{};(function(t){t[t.Union=0]="Union",t[t.True=1]="True",t[t.False=2]="False"})(h||(h={}))});function Ek(t,e,n,r,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=Xn(t[s],e,n,r,ee(o));return i}function Ok(t,e,n,r,o){return Ek(t.properties,e,n,r,o)}function Fc(t,e,n,r,o){let i=Ok(t,e,n,r,o);return B(i)}var sd=p(()=>{Pe();ni();Be()});function $k(t,e,n,r){let o=nn(t,e);return o===h.Union?V([n,r]):o===h.True?n:r}function Xn(t,e,n,r,o){return te(t)?Fc(t,e,n,r,o):Qe(t)?g(Lc(t,e,n,r,o)):g($k(t,e,n,r),o)}var ni=p(()=>{R();ye();id();ad();sd();W()});function Dk(t,e,n,r,o){return{[t]:Xn(K(t),e,n,r,ee(o))}}function Nk(t,e,n,r,o){return t.reduce((i,s)=>({...i,...Dk(s,e,n,r,o)}),{})}function Fk(t,e,n,r,o){return Nk(t.keys,e,n,r,o)}function Lc(t,e,n,r,o){let i=Fk(t,e,n,r,o);return B(i)}var ad=p(()=>{Pe();Ke();ni();Be()});var Wc=p(()=>{});var qr=p(()=>{id();ad();sd();Wc();ni()});function Bc(t,e){return Zn(bn(t),e)}var dd=p(()=>{ri();Gt()});function Lk(t,e){let n=t.filter(r=>nn(r,e)===h.False);return n.length===1?n[0]:V(n)}function Zn(t,e,n={}){return Je(t)?g(Bc(t,e),n):te(t)?g(Uc(t,e),n):g(F(t)?Lk(t.anyOf,e):nn(t,e)!==h.False?L():t,n)}var ri=p(()=>{R();ye();Re();qr();ld();dd();W()});function Wk(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=Zn(t[r],e);return n}function Bk(t,e){return Wk(t.properties,e)}function Uc(t,e){let n=Bk(t,e);return B(n)}var ld=p(()=>{Pe();ri()});var ud=p(()=>{ld();dd();ri()});function Kc(t,e){return er(bn(t),e)}var pd=p(()=>{oi();Gt()});function Uk(t,e){let n=t.filter(r=>nn(r,e)!==h.False);return n.length===1?n[0]:V(n)}function er(t,e,n){return Je(t)?g(Kc(t,e),n):te(t)?g(Vc(t,e),n):g(F(t)?Uk(t.anyOf,e):nn(t,e)!==h.False?t:L(),n)}var oi=p(()=>{R();ye();Re();qr();cd();pd();W()});function Kk(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=er(t[r],e);return n}function Vk(t,e){return Kk(t.properties,e)}function Vc(t,e){let n=Vk(t,e);return B(n)}var cd=p(()=>{Pe();oi()});var md=p(()=>{cd();pd();oi()});function qc(t,e){return Pt(t)?g(t.returns,e):L(e)}var Gc=p(()=>{R();Re();W()});var fd=p(()=>{Gc()});function ii(t){return qe(Ee(t))}var jc=p(()=>{xn();Vt()});var si=p(()=>{jc()});function Rn(t,e,n){return g({[w]:"Record",type:"object",patternProperties:{[t]:e}},n)}function gd(t,e,n){let r={};for(let o of t)r[o]=e;return H(r,{...n,[st]:"Record"})}function qk(t,e,n){return _p(t)?gd(Ve(t),e,n):Rn(t.pattern,e,n)}function Gk(t,e,n){return gd(Ve(V(t)),e,n)}function jk(t,e,n){return gd([t.toString()],e,n)}function Hk(t,e,n){return Rn(t.source,e,n)}function zk(t,e,n){let r=me(t.pattern)?Jt:t.pattern;return Rn(r,e,n)}function Qk(t,e,n){return Rn(Jt,e,n)}function Jk(t,e,n){return Rn(sp,e,n)}function Yk(t,e,n){return H({true:e,false:e},n)}function Xk(t,e,n){return Rn(Qt,e,n)}function Zk(t,e,n){return Rn(Qt,e,n)}function ai(t,e,n={}){return F(t)?Gk(t.anyOf,e,n):Je(t)?qk(t,e,n):ze(t)?jk(t.const,e,n):Wt(t)?Yk(t,e,n):It(t)?Xk(t,e,n):bt(t)?Zk(t,e,n):ga(t)?Hk(t,e,n):Bt(t)?zk(t,e,n):ma(t)?Qk(t,e,n):Ht(t)?Jk(t,e,n):L(n)}function di(t){return globalThis.Object.getOwnPropertyNames(t.patternProperties)[0]}function Hc(t){let e=di(t);return e===Jt?xt():e===Qt?at():xt({pattern:e})}function li(t){return t.patternProperties[di(t)]}var zc=p(()=>{R();T();Re();In();Ze();jn();ye();Gt();Cr();Et();Fe();W()});var Gr=p(()=>{zc()});function ev(t,e){return e.parameters=jr(t,e.parameters),e.returns=At(t,e.returns),e}function tv(t,e){return e.parameters=jr(t,e.parameters),e.returns=At(t,e.returns),e}function nv(t,e){return e.allOf=jr(t,e.allOf),e}function rv(t,e){return e.anyOf=jr(t,e.anyOf),e}function ov(t,e){return me(e.items)||(e.items=jr(t,e.items)),e}function iv(t,e){return e.items=At(t,e.items),e}function sv(t,e){return e.items=At(t,e.items),e}function av(t,e){return e.items=At(t,e.items),e}function dv(t,e){return e.item=At(t,e.item),e}function lv(t,e){let n=mv(t,e.properties);return{...e,...H(n)}}function uv(t,e){let n=At(t,Hc(e)),r=At(t,li(e)),o=ai(n,r);return{...e,...o}}function pv(t,e){return e.index in t?t[e.index]:tn()}function cv(t,e){let n=Wn(e),r=Ue(e),o=At(t,e);return n&&r?ii(o):n&&!r?qe(o):!n&&r?Ee(o):o}function mv(t,e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,r)=>({...n,[r]:cv(t,e[r])}),{})}function jr(t,e){return e.map(n=>At(t,n))}function At(t,e){return Pt(e)?ev(t,e):wt(e)?tv(t,e):oe(e)?nv(t,e):F(e)?rv(t,e):Ye(e)?ov(t,e):kt(e)?iv(t,e):hn(e)?sv(t,e):yn(e)?av(t,e):kn(e)?dv(t,e):fe(e)?lv(t,e):vn(e)?uv(t,e):fa(e)?pv(t,e):e}function Qc(t,e){return At(e,Ln(t))}var Jc=p(()=>{Ro();Jn();si();xn();Vt();Ze();Gr();Fe();W()});var hd=p(()=>{Jc()});function Yc(t){return g({[w]:"Integer",type:"integer"},t)}var Xc=p(()=>{R();T()});var Sd=p(()=>{Xc()});function fv(t,e,n){return{[t]:Rt(K(t),e,ee(n))}}function gv(t,e,n){return t.reduce((o,i)=>({...o,...fv(i,e,n)}),{})}function hv(t,e,n){return gv(t.keys,e,n)}function Zc(t,e,n){let r=hv(t,e,n);return B(r)}var yd=p(()=>{Pe();Tn();Ke();Be()});function Sv(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toLowerCase(),n].join("")}function yv(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toUpperCase(),n].join("")}function kv(t){return t.toUpperCase()}function vv(t){return t.toLowerCase()}function Pv(t,e,n){let r=qn(t.pattern);if(!wn(r))return{...t,pattern:em(t.pattern,e)};let s=[...Fr(r)].map(l=>K(l)),a=tm(s,e),d=V(a);return Fo([d],n)}function em(t,e){return typeof t=="string"?e==="Uncapitalize"?Sv(t):e==="Capitalize"?yv(t):e==="Uppercase"?kv(t):e==="Lowercase"?vv(t):t:t.toString()}function tm(t,e){return t.map(n=>Rt(n,e))}function Rt(t,e,n={}){return Qe(t)?Zc(t,e,n):Je(t)?Pv(t,e,n):F(t)?V(tm(t.anyOf,e),n):ze(t)?K(em(t.const,e),n):g(t,n)}var Tn=p(()=>{R();Gt();yd();Ke();ye();W()});function nm(t,e={}){return Rt(t,"Capitalize",e)}var rm=p(()=>{Tn()});function om(t,e={}){return Rt(t,"Lowercase",e)}var im=p(()=>{Tn()});function sm(t,e={}){return Rt(t,"Uncapitalize",e)}var am=p(()=>{Tn()});function dm(t,e={}){return Rt(t,"Uppercase",e)}var lm=p(()=>{Tn()});var kd=p(()=>{rm();yd();Tn();im();am();lm()});function wv(t,e,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(t))r[o]=rn(t[o],e,ee(n));return r}function Iv(t,e,n){return wv(t.properties,e,n)}function um(t,e,n){let r=Iv(t,e,n);return B(r)}var vd=p(()=>{Pe();ui();Be()});function bv(t,e){return t.map(n=>Pd(n,e))}function xv(t,e){return t.map(n=>Pd(n,e))}function Av(t,e){let{[e]:n,...r}=t;return r}function Rv(t,e){return e.reduce((n,r)=>Av(n,r),t)}function Tv(t,e,n){let r=ie(t,[Se,"$id","required","properties"]),o=Rv(n,e);return H(o,r)}function Cv(t){let e=t.reduce((n,r)=>Co(r)?[...n,K(r)]:n,[]);return V(e)}function Pd(t,e){return oe(t)?Oe(bv(t.allOf,e)):F(t)?V(xv(t.anyOf,e)):fe(t)?Tv(t,e,t.properties):H({})}function rn(t,e,n){let r=ce(e)?Cv(e):e,o=Xe(e)?Ve(e):e,i=de(t),s=de(e);return te(t)?um(t,o,n):Qe(e)?pm(t,e,n):i&&s?Z("Omit",[t,r],n):!i&&s?Z("Omit",[t,r],n):i&&!s?Z("Omit",[t,r],n):g({...Pd(t,o),...n})}var ui=p(()=>{R();_o();wr();Xt();Ke();Et();dt();ye();Ze();wd();vd();W();Fe()});function Mv(t,e,n){return{[e]:rn(t,[e],ee(n))}}function _v(t,e,n){return e.reduce((r,o)=>({...r,...Mv(t,o,n)}),{})}function Ev(t,e,n){return _v(t,e.keys,n)}function pm(t,e,n){let r=Ev(t,e,n);return B(r)}var wd=p(()=>{Pe();ui();Be()});var pi=p(()=>{wd();vd();ui()});function Ov(t,e,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(t))r[o]=on(t[o],e,ee(n));return r}function $v(t,e,n){return Ov(t.properties,e,n)}function cm(t,e,n){let r=$v(t,e,n);return B(r)}var Id=p(()=>{Pe();ci();Be()});function Dv(t,e){return t.map(n=>bd(n,e))}function Nv(t,e){return t.map(n=>bd(n,e))}function Fv(t,e){let n={};for(let r of e)r in t&&(n[r]=t[r]);return n}function Lv(t,e,n){let r=ie(t,[Se,"$id","required","properties"]),o=Fv(n,e);return H(o,r)}function Wv(t){let e=t.reduce((n,r)=>Co(r)?[...n,K(r)]:n,[]);return V(e)}function bd(t,e){return oe(t)?Oe(Dv(t.allOf,e)):F(t)?V(Nv(t.anyOf,e)):fe(t)?Lv(t,e,t.properties):H({})}function on(t,e,n){let r=ce(e)?Wv(e):e,o=Xe(e)?Ve(e):e,i=de(t),s=de(e);return te(t)?cm(t,o,n):Qe(e)?mm(t,e,n):i&&s?Z("Pick",[t,r],n):!i&&s?Z("Pick",[t,r],n):i&&!s?Z("Pick",[t,r],n):g({...bd(t,o),...n})}var ci=p(()=>{R();_o();Xt();dt();Ke();Ze();ye();Et();wr();W();Fe();xd();Id()});function Bv(t,e,n){return{[e]:on(t,[e],ee(n))}}function Uv(t,e,n){return e.reduce((r,o)=>({...r,...Bv(t,o,n)}),{})}function Kv(t,e,n){return Uv(t,e.keys,n)}function mm(t,e,n){let r=Kv(t,e,n);return B(r)}var xd=p(()=>{Pe();ci();Be()});var mi=p(()=>{xd();Id();ci()});function Vv(t,e){return Z("Partial",[Z(t,e)])}function qv(t){return Z("Partial",[Ot(t)])}function Gv(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=Ee(t[n]);return e}function jv(t,e){let n=ie(t,[Se,"$id","required","properties"]),r=Gv(e);return H(r,n)}function fm(t){return t.map(e=>gm(e))}function gm(t){return vt(t)?Vv(t.target,t.parameters):de(t)?qv(t.$ref):oe(t)?Oe(fm(t.allOf)):F(t)?V(fm(t.anyOf)):fe(t)?jv(t,t.properties):Sn(t)||Wt(t)||It(t)||ze(t)||Ir(t)||bt(t)||Bt(t)||br(t)||xr(t)?t:H({})}function tr(t,e){return te(t)?hm(t,e):g({...gm(t),...e})}var Ad=p(()=>{R();Xt();Vt();Ze();dt();ye();An();Kt();T();Rd();W()});function Hv(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=tr(t[r],ee(e));return n}function zv(t,e){return Hv(t.properties,e)}function hm(t,e){let n=zv(t,e);return B(n)}var Rd=p(()=>{Pe();Ad();Be()});var fi=p(()=>{Rd();Ad()});function Qv(t,e){return Z("Required",[Z(t,e)])}function Jv(t){return Z("Required",[Ot(t)])}function Yv(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=ie(t[n],[Ae]);return e}function Xv(t,e){let n=ie(t,[Se,"$id","required","properties"]),r=Yv(e);return H(r,n)}function Sm(t){return t.map(e=>ym(e))}function ym(t){return vt(t)?Qv(t.target,t.parameters):de(t)?Jv(t.$ref):oe(t)?Oe(Sm(t.allOf)):F(t)?V(Sm(t.anyOf)):fe(t)?Xv(t,t.properties):Sn(t)||Wt(t)||It(t)||ze(t)||Ir(t)||bt(t)||Bt(t)||br(t)||xr(t)?t:H({})}function nr(t,e){return te(t)?km(t,e):g({...ym(t),...e})}var Td=p(()=>{R();Xt();Ze();dt();ye();An();T();Kt();Cd();W()});function Zv(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=nr(t[r],e);return n}function eP(t,e){return Zv(t.properties,e)}function km(t,e){let n=eP(t,e);return B(n)}var Cd=p(()=>{Pe();Td()});var gi=p(()=>{Cd();Td()});function tP(t,e){return e.map(n=>de(n)?Md(t,n.$ref):et(t,n))}function Md(t,e){return e in t?de(t[e])?Md(t,t[e].$ref):et(t,t[e]):L()}function nP(t){return zn(t[0])}function rP(t){return Zt(t[0],t[1])}function oP(t){return Qn(t[0])}function iP(t){return tr(t[0])}function sP(t){return rn(t[0],t[1])}function aP(t){return on(t[0],t[1])}function dP(t){return nr(t[0])}function lP(t,e,n){let r=tP(t,n);return e==="Awaited"?nP(r):e==="Index"?rP(r):e==="KeyOf"?oP(r):e==="Partial"?iP(r):e==="Omit"?sP(r):e==="Pick"?aP(r):e==="Required"?dP(r):L()}function uP(t,e){return Bn(et(t,e))}function pP(t,e){return Un(et(t,e))}function cP(t,e,n){return Kn(Hr(t,e),et(t,n))}function mP(t,e,n){return Mt(Hr(t,e),et(t,n))}function fP(t,e){return Oe(Hr(t,e))}function gP(t,e){return Hn(et(t,e))}function hP(t,e){return H(globalThis.Object.keys(e).reduce((n,r)=>({...n,[r]:et(t,e[r])}),{}))}function SP(t,e){let[n,r]=[et(t,li(e)),di(e)],o=Ln(e);return o.patternProperties[r]=n,o}function yP(t,e){return de(e)?{...Md(t,e.$ref),[Se]:e[Se]}:e}function kP(t,e){return lt(Hr(t,e))}function vP(t,e){return V(Hr(t,e))}function Hr(t,e){return e.map(n=>et(t,n))}function et(t,e){return Ue(e)?g(et(t,ie(e,[Ae])),e):Wn(e)?g(et(t,ie(e,[yt])),e):zt(e)?g(yP(t,e),e):kt(e)?g(uP(t,e.items),e):hn(e)?g(pP(t,e.items),e):vt(e)?g(lP(t,e.target,e.parameters)):Pt(e)?g(cP(t,e.parameters,e.returns),e):wt(e)?g(mP(t,e.parameters,e.returns),e):oe(e)?g(fP(t,e.allOf),e):yn(e)?g(gP(t,e.items),e):fe(e)?g(hP(t,e.properties),e):vn(e)?g(SP(t,e)):Ye(e)?g(kP(t,e.items||[]),e):F(e)?g(vP(t,e.anyOf),e):e}function PP(t,e){return e in t?et(t,t[e]):L()}function vm(t){return globalThis.Object.getOwnPropertyNames(t).reduce((e,n)=>({...e,[n]:PP(t,n)}),{})}var Pm=p(()=>{Lt();ca();Kt();Er();Ko();Or();$r();Et();Pn();dt();Wr();Vr();Ze();pi();mi();Re();fi();Gr();gi();en();ye();T();W()});function wm(t){return new _d(t)}var _d,Im=p(()=>{Lt();T();Pm();_d=class{constructor(e){let n=vm(e),r=this.WithIdentifiers(n);this.$defs=r}Import(e,n){let r={...this.$defs,[e]:g(this.$defs[e],n)};return g({[w]:"Import",$defs:r,$ref:e})}WithIdentifiers(e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,r)=>({...n,[r]:{...e[r],$id:r}}),{})}}});var Ed=p(()=>{Im()});function bm(t,e){return g({[w]:"Not",not:t},e)}var xm=p(()=>{R();T()});var Od=p(()=>{xm()});function Am(t,e){return wt(t)?lt(t.parameters,e):L()}var Rm=p(()=>{en();Re();W()});var $d=p(()=>{Rm()});function Tm(t,e={}){me(e.$id)&&(e.$id=`T${wP++}`);let n=Ln(t({[w]:"This",$ref:`${e.$id}`}));return n.$id=e.$id,g({[st]:"Recursive",...n},e)}var wP,Cm=p(()=>{Ro();R();Fe();T();wP=0});var Dd=p(()=>{Cm()});function Mm(t,e){let n=Q(t)?new globalThis.RegExp(t):t;return g({[w]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},e)}var _m=p(()=>{R();Fe();T()});var Nd=p(()=>{_m()});function IP(t){return oe(t)?t.allOf:F(t)?t.anyOf:Ye(t)?t.items??[]:[]}function Em(t){return IP(t)}var Om=p(()=>{W()});var Fd=p(()=>{Om()});function $m(t,e){return wt(t)?g(t.returns,e):L(e)}var Dm=p(()=>{R();Re();W()});var Ld=p(()=>{Dm()});var Nm=p(()=>{});var Fm=p(()=>{});var Lm=p(()=>{Nm();Fm()});var Wm=p(()=>{});var Bm=p(()=>{Wm()});function Um(t){return new Wd(t)}var Wd,Bd,Km=p(()=>{T();W();Wd=class{constructor(e){this.schema=e}Decode(e){return new Bd(this.schema,e)}},Bd=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 zt(this.schema)?this.EncodeTransform(e,this.schema):this.EncodeSchema(e,this.schema)}}});var Ud=p(()=>{Km()});function Vm(t={}){return g({[w]:t[w]??"Unsafe"},t)}var qm=p(()=>{R();T()});var Kd=p(()=>{qm()});function Gm(t){return g({[w]:"Void",type:"void"},t)}var jm=p(()=>{R();T()});var Vd=p(()=>{jm()});var qd={};bo(qd,{Any:()=>Yt,Argument:()=>yp,Array:()=>Bn,AsyncIterator:()=>Un,Awaited:()=>zn,BigInt:()=>Gn,Boolean:()=>Do,Capitalize:()=>nm,Composite:()=>cc,Const:()=>vc,Constructor:()=>Kn,ConstructorParameters:()=>wc,Date:()=>Vo,Enum:()=>bc,Exclude:()=>Zn,Extends:()=>Xn,Extract:()=>er,Function:()=>Mt,Index:()=>Zt,InstanceType:()=>qc,Instantiate:()=>Qc,Integer:()=>Yc,Intersect:()=>Oe,Iterator:()=>Hn,KeyOf:()=>Qn,Literal:()=>K,Lowercase:()=>om,Mapped:()=>Zp,Module:()=>wm,Never:()=>L,Not:()=>bm,Null:()=>Go,Number:()=>at,Object:()=>H,Omit:()=>rn,Optional:()=>Ee,Parameters:()=>Am,Partial:()=>tr,Pick:()=>on,Promise:()=>Bo,Readonly:()=>qe,ReadonlyOptional:()=>ii,Record:()=>ai,Recursive:()=>Tm,Ref:()=>Ot,RegExp:()=>Mm,Required:()=>nr,Rest:()=>Em,ReturnType:()=>$m,String:()=>xt,Symbol:()=>Ho,TemplateLiteral:()=>Fo,Transform:()=>Um,Tuple:()=>lt,Uint8Array:()=>Yo,Uncapitalize:()=>sm,Undefined:()=>Qo,Union:()=>V,Unknown:()=>tn,Unsafe:()=>Vm,Uppercase:()=>dm,Void:()=>Gm});var Hm=p(()=>{_r();Ia();Er();Or();Ko();Lr();No();za();Ja();$r();Ya();qo();Xa();ud();qr();md();Pn();Et();fd();hd();Sd();dt();kd();Wr();Vr();Ke();Pe();Ed();Re();Od();jo();In();Ze();pi();Vt();$d();fi();mi();Uo();xn();si();Gr();Dd();An();Nd();gi();Fd();Ld();jn();zo();Gt();Ud();en();Xo();Jo();ye();Jn();Kd();Vd()});var c,zm=p(()=>{Hm();c=qd});var De=p(()=>{ca();Lt();Ct();va();ip();Cr();up();Mr();T();_r();Er();Ia();Or();Ko();Lr();No();za();Ja();$r();Ya();qo();Xa();ud();qr();md();Pn();Et();fd();hd();Sd();dt();Wr();kd();Vr();Ke();Ed();Pe();Re();Od();jo();In();Ze();pi();Vt();$d();fi();mi();Uo();xn();si();Gr();Dd();An();Nd();gi();Fd();Ld();Lm();Bm();jn();zo();Gt();Ud();en();Xo();Jo();ye();Jn();Kd();Vd();zm()});function Gd(t){v=t}function jd(t){ge=t}var v,ge,Y=p(()=>{v=null,ge=null});function Qm(t){let e=t.chatId.trim(),n=t.topicId.trim();return!/^-?\d+$/.test(e)||!/^\d+$/.test(n)?null:`${e}:topic:${n}`}function TP(t){let e=t.conversationId.trim(),n=e.match(/^(-?\d+):topic:(\d+)$/i);if(n?.[1]&&n[2]){let i=Qm({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=Qm({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 _P(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 EP(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 OP(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||!RP.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 $P(t,e=TP){try{return e({conversationId:t})}catch{return null}}function Hd(t){return{provider:"system",target:"system",sessionKey:t?.trim()||void 0}}function zd(t,e){return{...t,threadId:e??t.threadId}}function NP(t,e,n){return t==="telegram"&&n?.provider==="telegram"&&!!n.target&&e!==n.target}function FP(t){let e=t?.trim();if(!e)return;let n=OP(e);if(!n)return;let{provider:r,kind:o,rawId:i}=n,s=EP(i),a=null;if(r==="telegram")try{a=DP.safeParseTelegramTopicConversation(i)}catch{a=null}let d=a?.chatId??s.id,l=a?.topicId??s.threadId,u=r==="discord"?o==="direct"||o==="dm"?`user:${d}`:`channel:${d}`:d;return{provider:r,target:u,threadId:l,sessionKey:e}}function Qd(t){let e=t?.match(/:topic:(\d+)$/);return e?parseInt(e[1],10):void 0}function LP(t){return!!(t?.provider&&t.target&&t.provider!=="system"&&t.target!=="system")}function zr(t,e,n){let r=FP(n),o=e!=null?String(e):void 0,i=t?.trim();if(!i||i.toLowerCase()==="unknown")return r?zd(r,o):Hd(n);let s=i.split("|").map(k=>k.trim());if(s.length<2)return r?zd(r,o):Hd(n);let[a,d,l]=s,u=s.length>=3?l:d,f=s.length>=3?d:void 0,S=a?.toLowerCase();if(!S||!u)return r?zd(r,o):Hd(n);let y=S==="discord"?MP(u,n):u;return NP(S,y,r)?{provider:S,accountId:f,target:r.target,threadId:o??r.threadId,sessionKey:n?.trim()||void 0}:{provider:S,accountId:f,target:y,threadId:o??(r?.provider===S?r.threadId:void 0),sessionKey:n?.trim()||void 0}}function rr(t){return zr(_P(t.route)??t.originChannel,t.route?.threadId??t.originThreadId,t.route?.sessionKey??t.originSessionKey)??t.route}function Si(t){let e=rr(t);return LP(e)?e:void 0}var RP,DP,Cn=p(()=>{RP=new Set(["telegram","discord","slack","system","mattermost","feishu","line","whatsapp","signal","matrix","googlechat","bluebubbles","imessage","msteams"]);DP={safeParseTelegramTopicConversation:$P}});import{readFileSync as WP}from"fs";import{homedir as BP}from"os";import{join as UP}from"path";function Ym(){if(Qr!==void 0)return Qr;try{let t=WP(UP(BP(),".claude.json"),"utf-8");Qr=JSON.parse(t).mcpServers??{}}catch{Qr={}}return Qr}function Xm(t){let e=t.defaultHarness??Jm,n={};for(let[r,o]of Object.entries(yi))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 Le(){return _.defaultHarness??Jm}function Zm(t){let e=yi[t],n=_.harnesses[t];return{...e,...n,allowedModels:n?.allowedModels??e?.allowedModels}}function or(t){return Zm(t).defaultModel}function ki(t){return _.harnesses[t]?.allowedModels??_.allowedModels}function sn(t){return Zm(t).reasoningEffort}function $t(t){return t==null?void 0:String(t).trim()||void 0}function Xd(t){return{channel:$t(t?.deliveryContext?.channel),to:$t(t?.deliveryContext?.to),accountId:$t(t?.deliveryContext?.accountId),threadId:$t(t?.deliveryContext?.threadId)}}function ef(t,e,n){if(!(!t||!e))return n?`${t}|${n}|${e}`:`${t}|${e}`}function Jd(t){return $t(t?.requesterSenderId??t?.senderId)}function Yd(t){return($t(t.deliveryContext?.channel)??t.messageChannel??t.channel)?.toLowerCase()!=="telegram"?!1:!!Qd(t.sessionKey)}function vi(t){let e=Xd(t),n=ef(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=$t(t.chatId);if(r.length===1&&o)return`${r[0]}|${o}`;let i=Jd(t);if(r.length===1&&i&&!Yd(t))return`${r[0]}|${i}`}if(t.workspaceDir){let r=Yr(t.workspaceDir);if(r)return r}if(t.messageChannel&&t.messageChannel.includes("|"))return t.messageChannel}function Jr(t,e){if(e&&String(e).includes("|"))return String(e);let n=Xd(t),r=ef(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=$t(t.chatId);if(d)return`${a}|${d}`;let l=Jd(t);if(l&&!Yd(t))return`${a}|${l}`}let o=$t(t?.channel),i=$t(t?.chatId);if(o&&i)return`${o}|${i}`;let s=Jd(t);return o&&s&&!Yd(t)?`${o}|${s}`:t?.id&&/^-?\d+$/.test(String(t.id))?`telegram|${t.id}`:_.fallbackChannel??"unknown"}function Zd(t){return Xd(t).threadId??t?.messageThreadId??void 0}function ir(t,e,n){return zr(Jr(t,e),Zd(t),n??t?.sessionKey)}function Yr(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 tf(t){return Qd(t)}var Qr,Jm,yi,_,Te=p(()=>{Cn();Jm="claude-code",yi={"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":{...yi["claude-code"]},codex:{...yi.codex}}}});function Pi(t){return{type:"backend_ref",ref:t}}function wi(t){return{type:"run_started",...t?{runId:t}:{}}}function Xr(t){return{type:"text_delta",text:t}}function nf(t,e){return{type:"tool_call",name:t,input:e}}function Ii(t){return{type:"pending_input",state:t}}function dr(t){return t?{type:"pending_input_resolved",requestId:t}:{type:"pending_input_resolved"}}function bi(t,e){return{type:"plan_artifact",artifact:t,finalized:e}}function xi(t){return t?{type:"settings_changed",permissionMode:t}:{type:"settings_changed"}}function Mn(t){return{type:"run_completed",data:t}}var ar,el=p(()=>{ar=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 Ri from"@anthropic-ai/claude-agent-sdk";function KP(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 VP(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 Ai,rf=p(()=>{el();Ai=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 ar,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,b)=>{if(k!=="AskUserQuestion")return{behavior:"allow"};let P=VP(a,++s,b);n.enqueue(Ii(P));try{let I=await d(k,b);return n.enqueue(dr(P.requestId)),I}catch(I){throw n.enqueue(dr(P.requestId)),I}}}:{}};e.resumeSessionId&&(l.resume=e.resumeSessionId,l.forkSession=e.forkSession??!1);let u=e.prompt,f=this.deps.query??Ri.query,S=this.deps.startup??Ri.startup,y=(async()=>{if(typeof S!="function")return f({prompt:u,options:l});let k=await S({options:l});try{return k.query(u)}catch(b){throw await k.close?.(),b}})();return(async()=>{try{let k=await y;for await(let b of k){let P=b;if(P.type==="system"&&P.subtype==="init"){a=P.session_id??a,n.enqueue(Pi({kind:"claude-code",conversationId:a}));continue}if(P.type==="system"&&P.subtype==="status"&&P.permissionMode){n.enqueue(xi(P.permissionMode));continue}if(P.type==="assistant"){r||(r=!0,n.enqueue(wi()));for(let I of P.message?.content??[]){if(I.type==="text"){o+=o?`
3
- ${I.text}`:I.text,n.enqueue(Xr(I.text));continue}I.type==="tool_use"&&((I.name==="ExitPlanMode"||I.name==="set_permission_mode")&&(i=!0),I.name!=="AskUserQuestion"&&n.enqueue(nf(I.name,I.input)))}continue}if(P.type==="result"){let I=o.trim();if(I&&(e.permissionMode==="plan"||i)){let A={explanation:void 0,steps:[],markdown:I};n.enqueue(bi(A,!0))}n.enqueue(Mn({success:P.subtype==="success",duration_ms:P.duration_ms??0,total_cost_usd:P.total_cost_usd??0,num_turns:P.num_turns??0,result:KP(P),session_id:P.session_id??a})),o="",i=!1,r=!1}}}finally{n.close()}})().catch(k=>{n.enqueue(Mn({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 b=await y;typeof b.setPermissionMode=="function"&&await b.setPermissionMode(k)},async streamInput(k){let b=await y;typeof b.streamInput=="function"&&await b.streamInput(k)},async interrupt(){let k=await y;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 qP}from"node:child_process";import GP from"node:readline";function jP(t){return t instanceof Error?t.message:String(t)}function HP(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}async function zP(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:jP(r)}})}}}var Ti,of=p(()=>{Ti=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=qP(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,GP.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=HP(e);n&&await zP(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 X(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function le(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 QP(t){return t instanceof Error?t.message:String(t)}function sf(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function an(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>an(n)).join("");let e=X(t);if(!e)return"";for(let n of["delta","text","content","message","input","output","parts"]){let r=an(e[n]);if(r)return r}for(let n of["item","turn","thread","response","result","data"]){let r=an(e[n]);if(r)return r}return""}function Zr(t){let e=X(t);if(!e)return{};let n=X(e.thread)??X(e.session),r=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(n,["id","threadId","thread_id","conversationId"]),runId:le(e,["turnId","turn_id","runId","run_id"])??le(r,["id","turnId","turn_id","runId","run_id"]),requestId:le(e,["requestId","request_id","serverRequestId"])??le(i,["id","requestId","request_id"]),itemId:le(e,["itemId","item_id"])??le(o,["id","itemId","item_id"])}}function Ci(t,e,n=0){if(n>6)return;if(Array.isArray(t)){for(let i of t){let s=Ci(i,e,n+1);if(s)return s}return}let r=X(t);if(!r)return;let o=le(r,e);if(o)return o;for(let i of Object.values(r)){let s=Ci(i,e,n+1);if(s)return s}}function eo(t){return{threadId:Zr(t).threadId,cwd:Ci(t,["cwd","workdir","directory"])}}function af(t){let e=t?.trim();return!!(e&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(e))}function df(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 Mi(t){let e=X(t);if(!e)return;let n=X(e.item)??e;return le(n,["id","itemId","item_id","messageId","message_id"])}function JP(t,e=!1){let n=X(t);if(!n)return"";let r=X(n.item)??n;return le(r,["type"])?.toLowerCase()!=="agentmessage"?"":e?an(r):le(r,["text"],{trim:!1})??an(r)}function lf(t,e){let n=t.trim().toLowerCase();return n==="item/agentmessage/delta"?{mode:"delta",text:an(e),itemId:Mi(e)}:n==="item/completed"?{mode:"snapshot",text:JP(e),itemId:Mi(e)}:{mode:"ignore",text:""}}function uf(t){return{itemId:Mi(t),delta:an(t)}}function pf(t){let e=X(t),n=X(e?.plan),o=(Array.isArray(e?.plan)?e.plan:Array.isArray(n?.steps)?n.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(n,["explanation"])??le(e,["explanation"]),steps:o}}function cf(t){let e=X(t);if(!e)return{};let n=X(e.item)??e;return le(n,["type"])?.toLowerCase()!=="plan"?{}:{itemId:Mi(n),text:le(n,["text"],{trim:!1})??an(n)}}function mf(t,e){let n=t.trim().toLowerCase();if(n==="turn/failed")return"failed";if(n==="turn/cancelled")return"interrupted";let r=X(e)??{},o=X(r.turn)??r,i=le(o,["status"])?.toLowerCase();return i==="failed"?"failed":i==="interrupted"||i==="cancelled"?"interrupted":"completed"}function ff(t,e){let n=X(e)??{},r=X(n.turn)??n,o=X(r.error)??X(n.error);if(o)return le(o,["message","text","summary","reason"])}function YP(t,e){let n=QP(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 ZP(t){return XP.has(t.trim().toLowerCase())}function ew(t){let e=X(t);return e?!!le(e,["threadId","thread_id"]):!1}async function to(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(ZP(n)&&!ew(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,!YP(o,n))continue}}throw e instanceof Error?e:new Error(String(e))}function gf(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 hf(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 tw(t){return[{type:"text",text:t}]}function nw(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 Sf(t){let e={threadId:t.threadId,input:tw(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=nw(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 yf(t){return[{threadId:t.threadId,turnId:t.turnId}]}function rw(t){let e=X(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():le(X(r),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function ow(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 kf(t,e,n){let r=t.trim().toLowerCase(),o=rw(n),i=Ci(n,["question","prompt","message","text","summary","reason"])??void 0,s=r.includes("requestapproval"),a=s?o.map(d=>({kind:"approval",label:d,decision:ow(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 vf(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function tl(t,e){let n=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:n,sandbox:n==="never"?"danger-full-access":void 0}}var XP,Pf=p(()=>{XP=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function wf(t){return t instanceof Error?t.message:String(t)}function lw(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 iw,_n,sw,aw,dw,_i,If=p(()=>{of();el();Pf();iw="1.0",_n=6e4,sw="OPENCLAW_CODEX_APP_SERVER_COMMAND",aw="OPENCLAW_CODEX_APP_SERVER_ARGS",dw="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";_i=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[sw]?.trim()||"codex",args:sf(process.env[aw]),requestTimeoutMs:Number.parseInt(process.env[dw]??String(_n),10)||_n},r=this.deps.createClient?.(n)??new Ti(n.command,n.args,n.requestTimeoutMs),o=new ar,i=e.resumeSessionId,s,a=e.backendRef?.worktreePath,d=e.backendRef?.worktreeId,l=e.permissionMode??"default",u,f=0,S="",y=[],k,b=new Map,P=new Set,I=O=>{let $=O?.trim();if(!$)return;let U=e.originalWorkdir?.trim()||e.cwd.trim();e.worktreeStrategy&&e.worktreeStrategy!=="off"&&$!==U&&af($)&&(a=$,d=df($))},A=()=>{i&&o.enqueue(Pi({kind:"codex-app-server",conversationId:i,...s?{runId:s}:{},...d?{worktreeId:d}:{},...a?{worktreePath:a}:{}}))};r.setNotificationHandler(async(O,$)=>{let U=O.trim().toLowerCase(),pe=Zr($),St=eo($);if(pe.threadId&&i&&pe.threadId!==i)return;if(pe.threadId&&(i=pe.threadId),pe.runId&&(s=pe.runId),I(St.cwd),(pe.threadId||pe.runId||St.cwd)&&A(),U==="serverrequest/resolved"){u&&(o.enqueue(dr(u.requestId)),u=void 0);return}if(U==="turn/plan/updated"){let Me=pf($);S=Me.explanation??S,Me.steps.length>0&&(y=Me.steps);return}if(U==="item/plan/delta"){let Me=uf($);if(Me.itemId&&Me.delta){let jt=b.get(Me.itemId)??"";b.set(Me.itemId,`${jt}${Me.delta}`)}return}if(U==="item/completed"){let Me=cf($);if(Me.text?.trim()){let jt={explanation:S||void 0,steps:y,markdown:Me.text.trim()};o.enqueue(bi(jt,!0));return}}let ae=lf(U,$);if(ae.mode==="delta"&&ae.text){ae.itemId&&P.add(ae.itemId),o.enqueue(Xr(ae.text));return}ae.mode==="snapshot"&&ae.text&&(!ae.itemId||!P.has(ae.itemId))&&o.enqueue(Xr(ae.text)),(U==="turn/completed"||U==="turn/failed"||U==="turn/cancelled")&&k&&(k.method=O,k.params=$,k.resolve())}),r.setRequestHandler(async(O,$)=>{if(!vf(O))return{};let U=Zr($),pe=eo($);if(U.threadId&&i&&U.threadId!==i)return{};U.threadId&&(i=U.threadId),U.runId&&(s=U.runId),I(pe.cwd),(U.threadId||U.runId||pe.cwd)&&A();let St=U.requestId??`${i??"codex"}-${Date.now().toString(36)}`,ae=kf(O,St,$),Me=O.trim().toLowerCase(),jt=ae.options,Io=ae.actions??[],Vh=await new Promise(qh=>{u={requestId:St,methodLower:Me,state:ae,options:jt,actions:Io,resolveResponse:qh},o.enqueue(Ii(ae))});return u=void 0,o.enqueue(dr(St)),Vh});let C=async()=>{await r.connect(),await r.request("initialize",{protocolVersion:iw,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},_n),await r.notify("initialized",{})},N=async()=>{let O=tl(l,e.codexApprovalPolicy);if(i){let pe=await to({client:r,methods:["thread/resume"],payloads:hf({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:O.approvalPolicy,sandbox:O.sandbox}),timeoutMs:_n}),St=eo(pe);i=St.threadId??i,I(St.cwd),A();return}let $=await to({client:r,methods:["thread/start","thread/new"],payloads:gf({cwd:e.originalWorkdir?.trim()||e.cwd,model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:O.approvalPolicy,sandbox:O.sandbox}),timeoutMs:_n}),U=eo($);if(i=U.threadId,!i)throw new Error("Codex App Server did not return a thread id.");I(U.cwd),A()},xe=async O=>{await N(),o.enqueue(wi()),f+=1,S="",y=[],b.clear(),P.clear();let $="",U,pe,St=new Promise(ae=>{pe=ae});k={resolve:pe};try{let ae=tl(l,e.codexApprovalPolicy),Me=await to({client:r,methods:["turn/start"],payloads:Sf({threadId:i,prompt:O,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,permissionMode:l,approvalPolicy:ae.approvalPolicy,sandbox:ae.sandbox}),timeoutMs:_n}),jt=Zr(Me);jt.runId&&(s=jt.runId,A()),await St,$=k?.method??"turn/failed",U=k?.params;let Io=mf($,U);o.enqueue(Mn({success:Io==="completed",outcome:Io,duration_ms:0,total_cost_usd:0,num_turns:f,result:ff($,U),session_id:i}))}catch(ae){o.enqueue(Mn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:f,result:wf(ae),session_id:i??""}))}finally{k=void 0}},it=async O=>u?(u.methodLower.includes("requestapproval")?u.resolveResponse({decision:O.trim()||"decline"}):u.resolveResponse({text:O.trim()}),!0):!1,ou=async O=>{let $=u;if(!$)return!1;let U=$.actions[O];if(U?.kind==="approval")return $.resolveResponse({decision:U.responseDecision,...U.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:U.proposedExecpolicyAmendment}:{}}),!0;let pe=$.options[O];return pe?($.methodLower.includes("requestapproval")?$.resolveResponse({decision:pe}):$.resolveResponse({option:pe,index:O}),!0):!1},iu=typeof e.prompt=="string"?(async function*(){yield{type:"user",text:e.prompt,session_id:e.resumeSessionId??""}})():e.prompt;return(async()=>{try{await C();for await(let O of iu){let $=lw(O).trim();!$||await it($)||await xe($)}}catch(O){o.enqueue(Mn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:f,result:wf(O),session_id:i??e.resumeSessionId??""}))}finally{await r.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(O){l=O,o.enqueue(xi(O))},async submitPendingInputOption(O){return ou(O)},async submitPendingInputText(O){return it(O)},async interrupt(){!i||!s||await to({client:r,methods:["turn/interrupt"],payloads:yf({threadId:i,turnId:s}),timeoutMs:_n}).catch(()=>{})}}}buildUserMessage(e,n){return{type:"user",text:e,session_id:n}}}});function bf(t){nl.set(t.name,t)}function no(t){let e=nl.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...nl.keys()].join(", ")}`);return e}function xf(){return no(Le())}var nl,rl=p(()=>{rf();If();Te();nl=new Map;bf(new Ai);bf(new _i)});function M(t){return t.backendRef?.conversationId??t.harnessSessionId}function ne(t){return t.id??t.sessionId??t.name??M(t)??t.harnessSessionId}function uw(t){return t.harnessSessionId}function tt(t){let e=[ne(t),M(t),uw(t)].filter(n=>!!n);return[...new Set(e)]}function ol(t){return t.harnessName??t.persistedHarness??Le()}function Ei(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return no(ol(t)).capabilities.worktrees}catch{return"plugin-managed"}}function il(t){return t==="native-execution"||t==="native-restore"}function Af(t){return t==="native-restore"}function pw(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function We(t){return il(Ei(t))&&pw(t)}var he=p(()=>{Te();rl()});import{execFileSync as be}from"child_process";import*as Qi from"fs";import{tmpdir as Nw}from"os";import{dirname as Hf,join as Fw}from"path";function Lw(t){try{return be("git",["rev-parse","--show-toplevel"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function Ji(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(_.worktreeDir)return _.worktreeDir;if(t){let e=Lw(t);if(e)return Fw(e,".worktrees")}return Nw()}function zf(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function Yi(t){try{let e=be("git",["-C",t,"rev-parse","--git-common-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e&&e.endsWith("/.git")?Hf(e):void 0}catch{return}}function Ww(){if(Hi!==void 0)return Hi;try{return be("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Hi=!0,!0}catch{return Hi=!1,!1}}function dn(){if(zi!==void 0)return zi;try{return be("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),zi=!0,!0}catch{return zi=!1,!1}}function pl(t){if(!Ww())return!1;try{return be("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Qf(t){try{let e=Uw(t);if(!e)return console.warn(`[worktree] Failed to resolve free-space probe path for ${Ji(t)}`),!0;let n=Qi.statfsSync(e),r=n.bavail*n.bsize;return Kw(r)}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function ao(t,e){try{return be("git",["-C",t,"rev-parse","--verify",e],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Bw(t){let e=t;for(;;){if(Qi.existsSync(e))return e;let n=Hf(e);if(n===e)return;e=n}}function Uw(t){return Bw(Ji(t))}function Kw(t){return t>=104857600}function ln(t){let e=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(e)return e;try{let r=be("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 be("git",["-C",t,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return be("git",["-C",t,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function Xi(t){try{let n=be("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 cl(t,e,n){try{let r=be("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 Jf(t,e,n){try{let r=be("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 Yf(t,e,n){try{return be("git",["-C",t,"merge-base","--is-ancestor",e,n],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Xf(t,e,n){try{let r=be("git",["-C",t,"merge-tree","--write-tree",n,e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=be("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 Dt(t,e){try{return be("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 Zf(t,e){if(e)return e;let n;try{n=be("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}try{let r=be("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 Hi,zi,lo=p(()=>{Te()});import{execFileSync as uo}from"child_process";import{existsSync as Vw,mkdirSync as eg,rmSync as ml}from"fs";function qw(t,e){return!!(t&&typeof t=="object"&&"code"in t&&t.code===e)}function fl(t,e,n={}){let r=zf(e),o=Ji(t);eg(o,{recursive:!0});let i=n.allowExistingBranch===!0,s,a,d=10,l=!1;for(let f=0;f<d;f++){let S=f===0?"":`-${Math.random().toString(16).slice(2,6)}`,y=`${o}/openclaw-worktree-${r}${S}`,k=`agent/${r}${S}`;if(!i&&ao(t,k))continue;let b=!1;do{b=!1;try{eg(y,{recursive:!1}),s=y,a=k;break}catch(P){if(qw(P,"EEXIST")){if(i&&f===0&&!l)try{ml(y,{recursive:!0,force:!0}),l=!0,b=!0}catch(I){throw new Error(`Failed to recreate existing worktree branch ${k}: could not clear blocked path ${y}: ${I instanceof Error?I.message:String(I)}`)}else if(i&&f===0)throw new Error(`Failed to recreate existing worktree branch ${k}: path ${y} remains blocked after one cleanup attempt`);continue}throw P}}while(b);if(s&&a)break}if(!s||!a)throw new Error(`Failed to create unique worktree directory and branch after ${d} attempts`);let u=ao(t,a);try{u?uo("git",["-C",t,"worktree","add",s,a],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):uo("git",["-C",t,"worktree","add","-b",a,s],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(f){try{ml(s,{recursive:!0,force:!0})}catch{}throw f}return s}function Gw(t){if(!Vw(t))return[];try{let e=uo("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 nt(t,e,n={}){let r=n.destructive===!0,o=Gw(e);if(o.length>0&&!r)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${e}: ${o[0]}`),!1;try{return uo("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 ml(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 Zi(t){try{uo("git",["-C",t,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var tg=p(()=>{lo()});import{execFileSync as re}from"child_process";import{existsSync as jw}from"fs";function On(t,e,n){try{let r=re("git",["-C",t,"rev-list","--count",`${n}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(r.trim(),10),s=re("git",["-C",t,"diff","--shortstat",`${n}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,l=0,u=s.match(/(\d+)\s+files?\s+changed/);u&&(a=parseInt(u[1],10));let f=s.match(/(\d+)\s+insertions?\(/);f&&(d=parseInt(f[1],10));let S=s.match(/(\d+)\s+deletions?\(/);S&&(l=parseInt(S[1],10));let k=re("git",["-C",t,"diff","--name-only","--diff-filter=ACMR",`${n}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
1
+ var Gh=Object.defineProperty;var p=(t,e)=>()=>(t&&(e=t(t=0)),e);var xo=(t,e)=>{for(var n in e)Gh(t,n,{get:e[n],enumerable:!0})};var _e={};xo(_e,{HasPropertyKey:()=>Ao,IsArray:()=>ce,IsAsyncIterator:()=>aa,IsBigInt:()=>vr,IsBoolean:()=>Nt,IsDate:()=>gn,IsFunction:()=>da,IsIterator:()=>la,IsNull:()=>ua,IsNumber:()=>He,IsObject:()=>G,IsRegExp:()=>Pr,IsString:()=>Q,IsSymbol:()=>pa,IsUint8Array:()=>Ft,IsUndefined:()=>me});function Ao(t,e){return e in t}function aa(t){return G(t)&&!ce(t)&&!Ft(t)&&Symbol.asyncIterator in t}function ce(t){return Array.isArray(t)}function vr(t){return typeof t=="bigint"}function Nt(t){return typeof t=="boolean"}function gn(t){return t instanceof globalThis.Date}function da(t){return typeof t=="function"}function la(t){return G(t)&&!ce(t)&&!Ft(t)&&Symbol.iterator in t}function ua(t){return t===null}function He(t){return typeof t=="number"}function G(t){return typeof t=="object"&&t!==null}function Pr(t){return t instanceof globalThis.RegExp}function Q(t){return typeof t=="string"}function pa(t){return typeof t=="symbol"}function Ft(t){return t instanceof globalThis.Uint8Array}function me(t){return t===void 0}var Fe=p(()=>{});function jh(t){return t.map(e=>Ro(e))}function Hh(t){return new Date(t.getTime())}function zh(t){return new Uint8Array(t)}function Qh(t){return new RegExp(t.source,t.flags)}function Jh(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=Ro(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=Ro(t[n]);return e}function Ro(t){return ce(t)?jh(t):gn(t)?Hh(t):Ft(t)?zh(t):Pr(t)?Qh(t):G(t)?Jh(t):t}function ee(t){return Ro(t)}var Be=p(()=>{Fe()});function Ln(t,e){return e===void 0?ee(t):ee({...e,...t})}var To=p(()=>{Be()});var ca=p(()=>{To();Be()});function iu(t){return t!==null&&typeof t=="object"}function su(t){return globalThis.Array.isArray(t)&&!globalThis.ArrayBuffer.isView(t)}function au(t){return t===void 0}function du(t){return typeof t=="number"}var lu=p(()=>{});var uu=p(()=>{lu()});var Co,pu=p(()=>{uu();(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=iu(s);return t.AllowArrayObject?a:a&&!su(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?du(s):Number.isFinite(s)}t.IsNumberLike=o;function i(s){let a=au(s);return t.AllowNullVoid?a||s===null:a}t.IsVoidLike=i})(Co||(Co={}))});function Yh(t){return globalThis.Object.freeze(t).map(e=>wr(e))}function Xh(t){let e={};for(let n of Object.getOwnPropertyNames(t))e[n]=wr(t[n]);for(let n of Object.getOwnPropertySymbols(t))e[n]=wr(t[n]);return globalThis.Object.freeze(e)}function wr(t){return ce(t)?Yh(t):gn(t)?t:Ft(t)?t:Pr(t)?t:G(t)?Xh(t):t}var cu=p(()=>{Fe()});function h(t,e){let n=e!==void 0?{...e,...t}:t;switch(Co.InstanceMode){case"freeze":return wr(n);case"clone":return ee(n);default:return n}}var R=p(()=>{pu();cu();Be()});var Lt=p(()=>{R()});var we,mu=p(()=>{we=class extends Error{constructor(e){super(e)}}});var Ct=p(()=>{mu()});var Se,yt,Ae,st,w,Ir=p(()=>{Se=Symbol.for("TypeBox.Transform"),yt=Symbol.for("TypeBox.Readonly"),Ae=Symbol.for("TypeBox.Optional"),st=Symbol.for("TypeBox.Hint"),w=Symbol.for("TypeBox.Kind")});var T=p(()=>{Ir()});function Wn(t){return G(t)&&t[yt]==="Readonly"}function Ue(t){return G(t)&&t[Ae]==="Optional"}function ma(t){return D(t,"Any")}function fa(t){return D(t,"Argument")}function kt(t){return D(t,"Array")}function hn(t){return D(t,"AsyncIterator")}function Sn(t){return D(t,"BigInt")}function Wt(t){return D(t,"Boolean")}function vt(t){return D(t,"Computed")}function Pt(t){return D(t,"Constructor")}function Zh(t){return D(t,"Date")}function wt(t){return D(t,"Function")}function It(t){return D(t,"Integer")}function oe(t){return D(t,"Intersect")}function yn(t){return D(t,"Iterator")}function D(t,e){return G(t)&&w in t&&t[w]===e}function Mo(t){return Nt(t)||He(t)||Q(t)}function ze(t){return D(t,"Literal")}function Qe(t){return D(t,"MappedKey")}function te(t){return D(t,"MappedResult")}function Ht(t){return D(t,"Never")}function eS(t){return D(t,"Not")}function br(t){return D(t,"Null")}function bt(t){return D(t,"Number")}function fe(t){return D(t,"Object")}function kn(t){return D(t,"Promise")}function vn(t){return D(t,"Record")}function de(t){return D(t,"Ref")}function ga(t){return D(t,"RegExp")}function Bt(t){return D(t,"String")}function xr(t){return D(t,"Symbol")}function Je(t){return D(t,"TemplateLiteral")}function tS(t){return D(t,"This")}function zt(t){return G(t)&&Se in t}function Ye(t){return D(t,"Tuple")}function Ar(t){return D(t,"Undefined")}function F(t){return D(t,"Union")}function nS(t){return D(t,"Uint8Array")}function rS(t){return D(t,"Unknown")}function oS(t){return D(t,"Unsafe")}function iS(t){return D(t,"Void")}function sS(t){return G(t)&&w in t&&Q(t[w])}function Xe(t){return ma(t)||fa(t)||kt(t)||Wt(t)||Sn(t)||hn(t)||vt(t)||Pt(t)||Zh(t)||wt(t)||It(t)||oe(t)||yn(t)||ze(t)||Qe(t)||te(t)||Ht(t)||eS(t)||br(t)||bt(t)||fe(t)||kn(t)||vn(t)||de(t)||ga(t)||Bt(t)||xr(t)||Je(t)||tS(t)||Ye(t)||Ar(t)||F(t)||nS(t)||rS(t)||oS(t)||iS(t)||sS(t)}var W=p(()=>{Fe();T()});var m={};xo(m,{IsAny:()=>Su,IsArgument:()=>yu,IsArray:()=>ku,IsAsyncIterator:()=>vu,IsBigInt:()=>Pu,IsBoolean:()=>wu,IsComputed:()=>Iu,IsConstructor:()=>bu,IsDate:()=>xu,IsFunction:()=>Au,IsImport:()=>cS,IsInteger:()=>Ru,IsIntersect:()=>Tu,IsIterator:()=>Cu,IsKind:()=>tp,IsKindOf:()=>E,IsLiteral:()=>Tr,IsLiteralBoolean:()=>mS,IsLiteralNumber:()=>_u,IsLiteralString:()=>Mu,IsLiteralValue:()=>Eu,IsMappedKey:()=>Ou,IsMappedResult:()=>$u,IsNever:()=>Du,IsNot:()=>Nu,IsNull:()=>Fu,IsNumber:()=>Lu,IsObject:()=>Wu,IsOptional:()=>pS,IsPromise:()=>Bu,IsProperties:()=>_o,IsReadonly:()=>uS,IsRecord:()=>Uu,IsRecursive:()=>fS,IsRef:()=>Ku,IsRegExp:()=>Vu,IsSchema:()=>Ie,IsString:()=>qu,IsSymbol:()=>Gu,IsTemplateLiteral:()=>ju,IsThis:()=>Hu,IsTransform:()=>zu,IsTuple:()=>Qu,IsUint8Array:()=>Yu,IsUndefined:()=>Ju,IsUnion:()=>ka,IsUnionLiteral:()=>gS,IsUnknown:()=>Xu,IsUnsafe:()=>Zu,IsVoid:()=>ep,TypeGuardUnknownTypeError:()=>ha});function fu(t){try{return new RegExp(t),!0}catch{return!1}}function Sa(t){if(!Q(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 gu(t){return ya(t)||Ie(t)}function Rr(t){return me(t)||vr(t)}function J(t){return me(t)||He(t)}function ya(t){return me(t)||Nt(t)}function j(t){return me(t)||Q(t)}function dS(t){return me(t)||Q(t)&&Sa(t)&&fu(t)}function lS(t){return me(t)||Q(t)&&Sa(t)}function hu(t){return me(t)||Ie(t)}function uS(t){return G(t)&&t[yt]==="Readonly"}function pS(t){return G(t)&&t[Ae]==="Optional"}function Su(t){return E(t,"Any")&&j(t.$id)}function yu(t){return E(t,"Argument")&&He(t.index)}function ku(t){return E(t,"Array")&&t.type==="array"&&j(t.$id)&&Ie(t.items)&&J(t.minItems)&&J(t.maxItems)&&ya(t.uniqueItems)&&hu(t.contains)&&J(t.minContains)&&J(t.maxContains)}function vu(t){return E(t,"AsyncIterator")&&t.type==="AsyncIterator"&&j(t.$id)&&Ie(t.items)}function Pu(t){return E(t,"BigInt")&&t.type==="bigint"&&j(t.$id)&&Rr(t.exclusiveMaximum)&&Rr(t.exclusiveMinimum)&&Rr(t.maximum)&&Rr(t.minimum)&&Rr(t.multipleOf)}function wu(t){return E(t,"Boolean")&&t.type==="boolean"&&j(t.$id)}function Iu(t){return E(t,"Computed")&&Q(t.target)&&ce(t.parameters)&&t.parameters.every(e=>Ie(e))}function bu(t){return E(t,"Constructor")&&t.type==="Constructor"&&j(t.$id)&&ce(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function xu(t){return E(t,"Date")&&t.type==="Date"&&j(t.$id)&&J(t.exclusiveMaximumTimestamp)&&J(t.exclusiveMinimumTimestamp)&&J(t.maximumTimestamp)&&J(t.minimumTimestamp)&&J(t.multipleOfTimestamp)}function Au(t){return E(t,"Function")&&t.type==="Function"&&j(t.$id)&&ce(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function cS(t){return E(t,"Import")&&Ao(t,"$defs")&&G(t.$defs)&&_o(t.$defs)&&Ao(t,"$ref")&&Q(t.$ref)&&t.$ref in t.$defs}function Ru(t){return E(t,"Integer")&&t.type==="integer"&&j(t.$id)&&J(t.exclusiveMaximum)&&J(t.exclusiveMinimum)&&J(t.maximum)&&J(t.minimum)&&J(t.multipleOf)}function _o(t){return G(t)&&Object.entries(t).every(([e,n])=>Sa(e)&&Ie(n))}function Tu(t){return E(t,"Intersect")&&!(Q(t.type)&&t.type!=="object")&&ce(t.allOf)&&t.allOf.every(e=>Ie(e)&&!zu(e))&&j(t.type)&&(ya(t.unevaluatedProperties)||hu(t.unevaluatedProperties))&&j(t.$id)}function Cu(t){return E(t,"Iterator")&&t.type==="Iterator"&&j(t.$id)&&Ie(t.items)}function E(t,e){return G(t)&&w in t&&t[w]===e}function Mu(t){return Tr(t)&&Q(t.const)}function _u(t){return Tr(t)&&He(t.const)}function mS(t){return Tr(t)&&Nt(t.const)}function Tr(t){return E(t,"Literal")&&j(t.$id)&&Eu(t.const)}function Eu(t){return Nt(t)||He(t)||Q(t)}function Ou(t){return E(t,"MappedKey")&&ce(t.keys)&&t.keys.every(e=>He(e)||Q(e))}function $u(t){return E(t,"MappedResult")&&_o(t.properties)}function Du(t){return E(t,"Never")&&G(t.not)&&Object.getOwnPropertyNames(t.not).length===0}function Nu(t){return E(t,"Not")&&Ie(t.not)}function Fu(t){return E(t,"Null")&&t.type==="null"&&j(t.$id)}function Lu(t){return E(t,"Number")&&t.type==="number"&&j(t.$id)&&J(t.exclusiveMaximum)&&J(t.exclusiveMinimum)&&J(t.maximum)&&J(t.minimum)&&J(t.multipleOf)}function Wu(t){return E(t,"Object")&&t.type==="object"&&j(t.$id)&&_o(t.properties)&&gu(t.additionalProperties)&&J(t.minProperties)&&J(t.maxProperties)}function Bu(t){return E(t,"Promise")&&t.type==="Promise"&&j(t.$id)&&Ie(t.item)}function Uu(t){return E(t,"Record")&&t.type==="object"&&j(t.$id)&&gu(t.additionalProperties)&&G(t.patternProperties)&&(e=>{let n=Object.getOwnPropertyNames(e.patternProperties);return n.length===1&&fu(n[0])&&G(e.patternProperties)&&Ie(e.patternProperties[n[0]])})(t)}function fS(t){return G(t)&&st in t&&t[st]==="Recursive"}function Ku(t){return E(t,"Ref")&&j(t.$id)&&Q(t.$ref)}function Vu(t){return E(t,"RegExp")&&j(t.$id)&&Q(t.source)&&Q(t.flags)&&J(t.maxLength)&&J(t.minLength)}function qu(t){return E(t,"String")&&t.type==="string"&&j(t.$id)&&J(t.minLength)&&J(t.maxLength)&&dS(t.pattern)&&lS(t.format)}function Gu(t){return E(t,"Symbol")&&t.type==="symbol"&&j(t.$id)}function ju(t){return E(t,"TemplateLiteral")&&t.type==="string"&&Q(t.pattern)&&t.pattern[0]==="^"&&t.pattern[t.pattern.length-1]==="$"}function Hu(t){return E(t,"This")&&j(t.$id)&&Q(t.$ref)}function zu(t){return G(t)&&Se in t}function Qu(t){return E(t,"Tuple")&&t.type==="array"&&j(t.$id)&&He(t.minItems)&&He(t.maxItems)&&t.minItems===t.maxItems&&(me(t.items)&&me(t.additionalItems)&&t.minItems===0||ce(t.items)&&t.items.every(e=>Ie(e)))}function Ju(t){return E(t,"Undefined")&&t.type==="undefined"&&j(t.$id)}function gS(t){return ka(t)&&t.anyOf.every(e=>Mu(e)||_u(e))}function ka(t){return E(t,"Union")&&j(t.$id)&&G(t)&&ce(t.anyOf)&&t.anyOf.every(e=>Ie(e))}function Yu(t){return E(t,"Uint8Array")&&t.type==="Uint8Array"&&j(t.$id)&&J(t.minByteLength)&&J(t.maxByteLength)}function Xu(t){return E(t,"Unknown")&&j(t.$id)}function Zu(t){return E(t,"Unsafe")}function ep(t){return E(t,"Void")&&t.type==="void"&&j(t.$id)}function tp(t){return G(t)&&w in t&&Q(t[w])&&!aS.includes(t[w])}function Ie(t){return G(t)&&(Su(t)||yu(t)||ku(t)||wu(t)||Pu(t)||vu(t)||Iu(t)||bu(t)||xu(t)||Au(t)||Ru(t)||Tu(t)||Cu(t)||Tr(t)||Ou(t)||$u(t)||Du(t)||Nu(t)||Fu(t)||Lu(t)||Wu(t)||Bu(t)||Uu(t)||Ku(t)||Vu(t)||qu(t)||Gu(t)||ju(t)||Hu(t)||Qu(t)||Ju(t)||ka(t)||Yu(t)||Xu(t)||Zu(t)||ep(t)||tp(t))}var ha,aS,np=p(()=>{Fe();T();Ct();ha=class extends we{},aS=["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 va=p(()=>{W();np();Fe()});var rp=p(()=>{});var op=p(()=>{rp()});var Pa,Cr,wa,hS,QA,Qt,Jt,ip,sp=p(()=>{Pa="(true|false)",Cr="(0|[1-9][0-9]*)",wa="(.*)",hS="(?!.*)",QA=`^${Pa}$`,Qt=`^${Cr}$`,Jt=`^${wa}$`,ip=`^${hS}$`});var Mr=p(()=>{sp()});var ap=p(()=>{});var dp=p(()=>{});var lp=p(()=>{ap();dp()});function up(t,e){return t.includes(e)}function pp(t){return[...new Set(t)]}function kS(t,e){return t.filter(n=>e.includes(n))}function vS(t,e){return t.reduce((n,r)=>kS(n,r),e)}function cp(t){return t.length===1?t[0]:t.length>1?vS(t.slice(1),t[0]):[]}function mp(t){let e=[];for(let n of t)e.push(...n);return e}var fp=p(()=>{});var _r=p(()=>{fp()});function Yt(t){return h({[w]:"Any"},t)}var gp=p(()=>{Lt();T()});var Er=p(()=>{gp()});function Bn(t,e){return h({[w]:"Array",type:"array",items:t},e)}var hp=p(()=>{R();T()});var Or=p(()=>{hp()});function Sp(t){return h({[w]:"Argument",index:t})}var yp=p(()=>{R();T()});var Ia=p(()=>{yp()});function Un(t,e){return h({[w]:"AsyncIterator",type:"AsyncIterator",items:t},e)}var kp=p(()=>{T();R()});var $r=p(()=>{kp()});function Z(t,e,n){return h({[w]:"Computed",target:t,parameters:e},n)}var vp=p(()=>{Lt();Ir()});var Xt=p(()=>{vp()});function PS(t,e){let{[e]:n,...r}=t;return r}function ie(t,e){return e.reduce((n,r)=>PS(n,r),t)}var Eo=p(()=>{});var Kt=p(()=>{Eo()});function L(t){return h({[w]:"Never",not:{}},t)}var Pp=p(()=>{R();T()});var Re=p(()=>{Pp()});var wp=p(()=>{});function B(t){return h({[w]:"MappedResult",properties:t})}var ba=p(()=>{R();T()});function Kn(t,e,n){return h({[w]:"Constructor",type:"Constructor",parameters:t,returns:e},n)}var Ip=p(()=>{R();T()});var Dr=p(()=>{Ip()});function Mt(t,e,n){return h({[w]:"Function",type:"Function",parameters:t,returns:e},n)}var bp=p(()=>{R();T()});var Pn=p(()=>{bp()});function Nr(t,e){return h({[w]:"Union",anyOf:t},e)}var xa=p(()=>{R();T()});function wS(t){return t.some(e=>Ue(e))}function xp(t){return t.map(e=>Ue(e)?IS(e):e)}function IS(t){return ie(t,[Ae])}function bS(t,e){return wS(t)?Ee(Nr(xp(t),e)):Nr(xp(t),e)}function _t(t,e){return t.length===1?h(t[0],e):t.length===0?L(e):bS(t,e)}var Ap=p(()=>{R();T();Kt();Re();Vt();xa();W()});var Rp=p(()=>{});function V(t,e){return t.length===0?L(e):t.length===1?h(t[0],e):Nr(t,e)}var Tp=p(()=>{Re();R();xa()});var ye=p(()=>{Ap();Rp();Tp()});function xS(t){return t.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Aa(t,e,n){return t[e]===n&&t.charCodeAt(e-1)!==92}function qt(t,e){return Aa(t,e,"(")}function Fr(t,e){return Aa(t,e,")")}function Cp(t,e){return Aa(t,e,"|")}function AS(t){if(!(qt(t,0)&&Fr(t,t.length-1)))return!1;let e=0;for(let n=0;n<t.length;n++)if(qt(t,n)&&(e+=1),Fr(t,n)&&(e-=1),e===0&&n!==t.length-1)return!1;return!0}function RS(t){return t.slice(1,t.length-1)}function TS(t){let e=0;for(let n=0;n<t.length;n++)if(qt(t,n)&&(e+=1),Fr(t,n)&&(e-=1),Cp(t,n)&&e===0)return!0;return!1}function CS(t){for(let e=0;e<t.length;e++)if(qt(t,e))return!0;return!1}function MS(t){let[e,n]=[0,0],r=[];for(let i=0;i<t.length;i++)if(qt(t,i)&&(e+=1),Fr(t,i)&&(e-=1),Cp(t,i)&&e===0){let s=t.slice(n,i);s.length>0&&r.push(Vn(s)),n=i+1}let o=t.slice(n);return o.length>0&&r.push(Vn(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function _S(t){function e(o,i){if(!qt(o,i))throw new Oo("TemplateLiteralParser: Index must point to open parens");let s=0;for(let a=i;a<o.length;a++)if(qt(o,a)&&(s+=1),Fr(o,a)&&(s-=1),s===0)return[i,a];throw new Oo("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,i){for(let s=i;s<o.length;s++)if(qt(o,s))return[i,s];return[i,o.length]}let r=[];for(let o=0;o<t.length;o++)if(qt(t,o)){let[i,s]=e(t,o),a=t.slice(i,s+1);r.push(Vn(a)),o=s}else{let[i,s]=n(t,o),a=t.slice(i,s);a.length>0&&r.push(Vn(a)),o=s-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function Vn(t){return AS(t)?Vn(RS(t)):TS(t)?MS(t):CS(t)?_S(t):{type:"const",const:xS(t)}}function qn(t){return Vn(t.slice(1,t.length-1))}var Oo,$o=p(()=>{Ct();Oo=class extends we{}});function ES(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 OS(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 $S(t){return t.type==="const"&&t.const===".*"}function wn(t){return ES(t)||$S(t)?!1:OS(t)?!0:t.type==="and"?t.expr.every(e=>wn(e)):t.type==="or"?t.expr.every(e=>wn(e)):t.type==="const"?!0:(()=>{throw new Ra("Unknown expression type")})()}function Mp(t){let e=qn(t.pattern);return wn(e)}var Ra,Ta=p(()=>{$o();Ct();Ra=class extends we{}});function*_p(t){if(t.length===1)return yield*t[0];for(let e of t[0])for(let n of _p(t.slice(1)))yield`${e}${n}`}function*DS(t){return yield*_p(t.expr.map(e=>[...Lr(e)]))}function*NS(t){for(let e of t.expr)yield*Lr(e)}function*FS(t){return yield t.const}function*Lr(t){return t.type==="and"?yield*DS(t):t.type==="or"?yield*NS(t):t.type==="const"?yield*FS(t):(()=>{throw new Ca("Unknown expression")})()}function Do(t){let e=qn(t.pattern);return wn(e)?[...Lr(e)]:[]}var Ca,Ma=p(()=>{Ta();$o();Ct();Ca=class extends we{}});function K(t,e){return h({[w]:"Literal",const:t,type:typeof t},e)}var Ep=p(()=>{R();T()});var Ke=p(()=>{Ep()});function No(t){return h({[w]:"Boolean",type:"boolean"},t)}var Op=p(()=>{T();Lt()});var Fo=p(()=>{Op()});function Gn(t){return h({[w]:"BigInt",type:"bigint"},t)}var $p=p(()=>{T();Lt()});var Wr=p(()=>{$p()});function at(t){return h({[w]:"Number",type:"number"},t)}var Dp=p(()=>{R();T()});var In=p(()=>{Dp()});function xt(t){return h({[w]:"String",type:"string"},t)}var Np=p(()=>{R();T()});var jn=p(()=>{Np()});function*LS(t){let e=t.trim().replace(/"|'/g,"");return e==="boolean"?yield No():e==="number"?yield at():e==="bigint"?yield Gn():e==="string"?yield xt():yield(()=>{let n=e.split("|").map(r=>K(r.trim()));return n.length===0?L():n.length===1?n[0]:_t(n)})()}function*WS(t){if(t[1]!=="{"){let e=K("$"),n=_a(t.slice(1));return yield*[e,...n]}for(let e=2;e<t.length;e++)if(t[e]==="}"){let n=LS(t.slice(2,e)),r=_a(t.slice(e+1));return yield*[...n,...r]}yield K(t)}function*_a(t){for(let e=0;e<t.length;e++)if(t[e]==="$"){let n=K(t.slice(0,e)),r=WS(t.slice(e));return yield*[n,...r]}yield K(t)}function Fp(t){return[..._a(t)]}var Ea=p(()=>{Ke();Fo();Wr();In();jn();ye();Re()});function BS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Lp(t,e){return Je(t)?t.pattern.slice(1,t.pattern.length-1):F(t)?`(${t.anyOf.map(n=>Lp(n,e)).join("|")})`:bt(t)?`${e}${Cr}`:It(t)?`${e}${Cr}`:Sn(t)?`${e}${Cr}`:Bt(t)?`${e}${wa}`:ze(t)?`${e}${BS(t.const.toString())}`:Wt(t)?`${e}${Pa}`:(()=>{throw new Oa(`Unexpected Kind '${t[w]}'`)})()}function $a(t){return`^${t.map(e=>Lp(e,"")).join("")}$`}var Oa,Da=p(()=>{Mr();T();Ct();W();Oa=class extends we{}});function bn(t){let n=Do(t).map(r=>K(r));return _t(n)}var Wp=p(()=>{ye();Ke();Ma()});function Lo(t,e){let n=Q(t)?$a(Fp(t)):$a(t);return h({[w]:"TemplateLiteral",type:"string",pattern:n},e)}var Bp=p(()=>{R();Ea();Da();Fe();T()});var Gt=p(()=>{Ta();Ma();Ea();$o();Da();Wp();Bp()});function US(t){return Do(t).map(n=>n.toString())}function KS(t){let e=[];for(let n of t)e.push(...Ve(n));return e}function VS(t){return[t.toString()]}function Ve(t){return[...new Set(Je(t)?US(t):F(t)?KS(t.anyOf):ze(t)?VS(t.const):bt(t)?["[number]"]:It(t)?["[number]"]:[])]}var Wo=p(()=>{Gt();W()});function qS(t,e,n){let r={};for(let o of Object.getOwnPropertyNames(e))r[o]=Zt(t,Ve(e[o]),n);return r}function GS(t,e,n){return qS(t,e.properties,n)}function Up(t,e,n){let r=GS(t,e,n);return B(r)}var Na=p(()=>{Pe();Wo();Et()});function Vp(t,e){return t.map(n=>qp(n,e))}function jS(t){return t.filter(e=>!Ht(e))}function HS(t,e){return Bo(jS(Vp(t,e)))}function zS(t){return t.some(e=>Ht(e))?[]:t}function QS(t,e){return _t(zS(Vp(t,e)))}function JS(t,e){return e in t?t[e]:e==="[number]"?_t(t):L()}function YS(t,e){return e==="[number]"?t:L()}function XS(t,e){return e in t?t[e]:L()}function qp(t,e){return oe(t)?HS(t.allOf,e):F(t)?QS(t.anyOf,e):Ye(t)?JS(t.items??[],e):kt(t)?YS(t.items,e):fe(t)?XS(t.properties,e):L()}function Fa(t,e){return e.map(n=>qp(t,n))}function Kp(t,e){return _t(Fa(t,e))}function Zt(t,e,n){if(de(t)||de(e)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!Xe(t)||!Xe(e))throw new we(r);return Z("Index",[t,e])}return te(e)?Up(t,e,n):Qe(e)?Gp(t,e,n):h(Xe(e)?Kp(t,Ve(e)):Kp(t,e),n)}var La=p(()=>{R();Ct();Xt();Re();dt();ye();Wo();Wa();Na();W()});function ZS(t,e,n){return{[e]:Zt(t,[e],ee(n))}}function ey(t,e,n){return e.reduce((r,o)=>({...r,...ZS(t,o,n)}),{})}function ty(t,e,n){return ey(t,e.keys,n)}function Gp(t,e,n){let r=ty(t,e,n);return B(r)}var Wa=p(()=>{La();Pe();Be()});var Et=p(()=>{Wa();Na();Wo();La()});function Hn(t,e){return h({[w]:"Iterator",type:"Iterator",items:t},e)}var jp=p(()=>{R();T()});var Br=p(()=>{jp()});function ny(t){return globalThis.Object.keys(t).filter(e=>!Ue(t[e]))}function ry(t,e){let n=ny(t),r=n.length>0?{[w]:"Object",type:"object",required:n,properties:t}:{[w]:"Object",type:"object",properties:t};return h(r,e)}var H,Hp=p(()=>{R();T();W();H=ry});var Ze=p(()=>{Hp()});function Uo(t,e){return h({[w]:"Promise",type:"Promise",item:t},e)}var zp=p(()=>{R();T()});var Ko=p(()=>{zp()});function oy(t){return h(ie(t,[yt]))}function iy(t){return h({...t,[yt]:"Readonly"})}function sy(t,e){return e===!1?oy(t):iy(t)}function qe(t,e){let n=e??!0;return te(t)?Qp(t,n):sy(t,n)}var Ba=p(()=>{R();T();Kt();Ua();W()});function ay(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=qe(t[r],e);return n}function dy(t,e){return ay(t.properties,e)}function Qp(t,e){let n=dy(t,e);return B(n)}var Ua=p(()=>{Pe();Ba()});var xn=p(()=>{Ua();Ba()});function lt(t,e){return h(t.length>0?{[w]:"Tuple",type:"array",items:t,additionalItems:!1,minItems:t.length,maxItems:t.length}:{[w]:"Tuple",type:"array",minItems:t.length,maxItems:t.length},e)}var Jp=p(()=>{R();T()});var en=p(()=>{Jp()});function Yp(t,e){return t in e?ut(t,e[t]):B(e)}function ly(t){return{[t]:K(t)}}function uy(t){let e={};for(let n of t)e[n]=K(n);return e}function py(t,e){return up(e,t)?ly(t):uy(e)}function cy(t,e){let n=py(t,e);return Yp(t,n)}function Ur(t,e){return e.map(n=>ut(t,n))}function my(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ut(t,e[r]);return n}function ut(t,e){let n={...e};return Ue(e)?Ee(ut(t,ie(e,[Ae]))):Wn(e)?qe(ut(t,ie(e,[yt]))):te(e)?Yp(t,e.properties):Qe(e)?cy(t,e.keys):Pt(e)?Kn(Ur(t,e.parameters),ut(t,e.returns),n):wt(e)?Mt(Ur(t,e.parameters),ut(t,e.returns),n):hn(e)?Un(ut(t,e.items),n):yn(e)?Hn(ut(t,e.items),n):oe(e)?Oe(Ur(t,e.allOf),n):F(e)?V(Ur(t,e.anyOf),n):Ye(e)?lt(Ur(t,e.items??[]),n):fe(e)?H(my(t,e.properties),n):kt(e)?Bn(ut(t,e.items),n):kn(e)?Uo(ut(t,e.item),n):e}function fy(t,e){let n={};for(let r of t)n[r]=ut(r,e);return n}function Xp(t,e,n){let r=Xe(t)?Ve(t):t,o=e({[w]:"MappedKey",keys:r}),i=fy(r,o);return H(i,n)}var Zp=p(()=>{T();Kt();Or();$r();Dr();Pn();Et();dt();Br();Ke();Ze();Vt();Ko();xn();en();ye();_r();ba();W()});var Pe=p(()=>{wp();ba();Zp()});function gy(t){return h(ie(t,[Ae]))}function hy(t){return h({...t,[Ae]:"Optional"})}function Sy(t,e){return e===!1?gy(t):hy(t)}function Ee(t,e){let n=e??!0;return te(t)?ec(t,n):Sy(t,n)}var Ka=p(()=>{R();T();Kt();Va();W()});function yy(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=Ee(t[r],e);return n}function ky(t,e){return yy(t.properties,e)}function ec(t,e){let n=ky(t,e);return B(n)}var Va=p(()=>{Pe();Ka()});var Vt=p(()=>{Va();Ka()});function Kr(t,e={}){let n=t.every(o=>fe(o)),r=Xe(e.unevaluatedProperties)?{unevaluatedProperties:e.unevaluatedProperties}:{};return h(e.unevaluatedProperties===!1||Xe(e.unevaluatedProperties)||n?{...r,[w]:"Intersect",type:"object",allOf:t}:{...r,[w]:"Intersect",allOf:t},e)}var qa=p(()=>{R();T();W()});function vy(t){return t.every(e=>Ue(e))}function Py(t){return ie(t,[Ae])}function tc(t){return t.map(e=>Ue(e)?Py(e):e)}function wy(t,e){return vy(t)?Ee(Kr(tc(t),e)):Kr(tc(t),e)}function Bo(t,e={}){if(t.length===1)return h(t[0],e);if(t.length===0)return L(e);if(t.some(n=>zt(n)))throw new Error("Cannot intersect transform types");return wy(t,e)}var nc=p(()=>{T();R();Kt();Re();Vt();qa();W()});var rc=p(()=>{});function Oe(t,e){if(t.length===1)return h(t[0],e);if(t.length===0)return L(e);if(t.some(n=>zt(n)))throw new Error("Cannot intersect transform types");return Kr(t,e)}var oc=p(()=>{R();Re();qa();W()});var dt=p(()=>{nc();rc();oc()});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 we("Ref: $ref must be a string");return h({[w]:"Ref",$ref:e},n)}var ic=p(()=>{Ct();R();T()});var An=p(()=>{ic()});function Iy(t,e){return Z("Awaited",[Z(t,e)])}function by(t){return Z("Awaited",[Ot(t)])}function xy(t){return Oe(sc(t))}function Ay(t){return V(sc(t))}function Ry(t){return zn(t)}function sc(t){return t.map(e=>zn(e))}function zn(t,e){return h(vt(t)?Iy(t.target,t.parameters):oe(t)?xy(t.allOf):F(t)?Ay(t.anyOf):kn(t)?Ry(t.item):de(t)?by(t.$ref):t,e)}var ac=p(()=>{R();Xt();dt();ye();An();W()});var Vo=p(()=>{ac()});function dc(t){let e=[];for(let n of t)e.push(Vr(n));return e}function Ty(t){let e=dc(t);return mp(e)}function Cy(t){let e=dc(t);return cp(e)}function My(t){return t.map((e,n)=>n.toString())}function _y(t){return["[number]"]}function Ey(t){return globalThis.Object.getOwnPropertyNames(t)}function Oy(t){return $y?globalThis.Object.getOwnPropertyNames(t).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function Vr(t){return oe(t)?Ty(t.allOf):F(t)?Cy(t.anyOf):Ye(t)?My(t.items??[]):kt(t)?_y(t.items):fe(t)?Ey(t.properties):vn(t)?Oy(t.patternProperties):[]}var $y,Ga=p(()=>{_r();W();$y=!1});function Dy(t,e){return Z("KeyOf",[Z(t,e)])}function Ny(t){return Z("KeyOf",[Ot(t)])}function Fy(t,e){let n=Vr(t),r=Ly(n),o=_t(r);return h(o,e)}function Ly(t){return t.map(e=>e==="[number]"?at():K(e))}function Qn(t,e){return vt(t)?Dy(t.target,t.parameters):de(t)?Ny(t.$ref):te(t)?lc(t,e):Fy(t,e)}var ja=p(()=>{R();Ke();In();Xt();An();Ga();ye();Ha();W()});function Wy(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=Qn(t[r],ee(e));return n}function By(t,e){return Wy(t.properties,e)}function lc(t,e){let n=By(t,e);return B(n)}var Ha=p(()=>{Pe();ja();Be()});var uc=p(()=>{});var qr=p(()=>{Ha();uc();Ga();ja()});function Uy(t){let e=[];for(let n of t)e.push(...Vr(n));return pp(e)}function Ky(t){return t.filter(e=>!Ht(e))}function Vy(t,e){let n=[];for(let r of t)n.push(...Fa(r,[e]));return Ky(n)}function qy(t,e){let n={};for(let r of e)n[r]=Bo(Vy(t,r));return n}function pc(t,e){let n=Uy(t),r=qy(t,n);return H(r,e)}var cc=p(()=>{dt();Et();qr();Ze();_r();W()});var za=p(()=>{cc()});function qo(t){return h({[w]:"Date",type:"Date"},t)}var mc=p(()=>{T();R()});var Go=p(()=>{mc()});function jo(t){return h({[w]:"Null",type:"null"},t)}var fc=p(()=>{R();T()});var Ho=p(()=>{fc()});function zo(t){return h({[w]:"Symbol",type:"symbol"},t)}var gc=p(()=>{R();T()});var Qo=p(()=>{gc()});function Jo(t){return h({[w]:"Undefined",type:"undefined"},t)}var hc=p(()=>{R();T()});var Yo=p(()=>{hc()});function Xo(t){return h({[w]:"Uint8Array",type:"Uint8Array"},t)}var Sc=p(()=>{R();T()});var Zo=p(()=>{Sc()});function tn(t){return h({[w]:"Unknown"},t)}var yc=p(()=>{R();T()});var Jn=p(()=>{yc()});function Gy(t){return t.map(e=>Qa(e,!1))}function jy(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=qe(Qa(t[n],!1));return e}function ei(t,e){return e===!0?t:qe(t)}function Qa(t,e){return aa(t)?ei(Yt(),e):la(t)?ei(Yt(),e):ce(t)?qe(lt(Gy(t))):Ft(t)?Xo():gn(t)?qo():G(t)?ei(H(jy(t)),e):da(t)?ei(Mt([],tn()),e):me(t)?Jo():ua(t)?jo():pa(t)?zo():vr(t)?Gn():He(t)?K(t):Nt(t)?K(t):Q(t)?K(t):H({})}function kc(t,e){return h(Qa(t,!0),e)}var vc=p(()=>{Er();Wr();Go();Pn();Ke();Ho();Ze();Qo();en();xn();Yo();Zo();Jn();Lt();Fe()});var Ja=p(()=>{vc()});function Pc(t,e){return Pt(t)?lt(t.parameters,e):L(e)}var wc=p(()=>{en();Re();W()});var Ya=p(()=>{wc()});function Ic(t,e){if(me(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=>K(i));return V(o,{...e,[st]:"Enum"})}var bc=p(()=>{Ke();T();ye();Fe()});var Xa=p(()=>{bc()});function pt(t){return t===S.False?t:S.True}function Yn(t){throw new ed(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)?_c(t,e):m.IsIntersect(e)?ti(t,e):m.IsUnion(e)?od(t,e):m.IsUnknown(e)?Dc(t,e):m.IsAny(e)?rd(t,e):Yn("StructuralRight")}function rd(t,e){return S.True}function Hy(t,e){return m.IsIntersect(e)?ti(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 zy(t,e){return m.IsUnknown(t)?S.False:m.IsAny(t)?S.Union:m.IsNever(t)?S.True:S.False}function Qy(t,e){return m.IsObject(e)&&ni(e)?S.True:ke(e)?ve(t,e):m.IsArray(e)?pt(z(t.items,e.items)):S.False}function Jy(t,e){return ke(e)?ve(t,e):m.IsAsyncIterator(e)?pt(z(t.items,e.items)):S.False}function Yy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsBigInt(e)?S.True:S.False}function Cc(t,e){return m.IsLiteralBoolean(t)||m.IsBoolean(t)?S.True:S.False}function Xy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsBoolean(e)?S.True:S.False}function Zy(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsConstructor(e)?t.parameters.length>e.parameters.length?S.False:t.parameters.every((n,r)=>pt(z(e.parameters[r],n))===S.True)?pt(z(t.returns,e.returns)):S.False:S.False}function ek(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsDate(e)?S.True:S.False}function tk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsFunction(e)?t.parameters.length>e.parameters.length?S.False:t.parameters.every((n,r)=>pt(z(e.parameters[r],n))===S.True)?pt(z(t.returns,e.returns)):S.False:S.False}function Mc(t,e){return m.IsLiteral(t)&&_e.IsNumber(t.const)||m.IsNumber(t)||m.IsInteger(t)?S.True:S.False}function nk(t,e){return m.IsInteger(e)||m.IsNumber(e)?S.True:ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):S.False}function ti(t,e){return e.allOf.every(n=>z(t,n)===S.True)?S.True:S.False}function rk(t,e){return t.allOf.some(n=>z(n,e)===S.True)?S.True:S.False}function ok(t,e){return ke(e)?ve(t,e):m.IsIterator(e)?pt(z(t.items,e.items)):S.False}function ik(t,e){return m.IsLiteral(e)&&e.const===t.const?S.True:ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsString(e)?$c(t,e):m.IsNumber(e)?Ec(t,e):m.IsInteger(e)?Mc(t,e):m.IsBoolean(e)?Cc(t,e):S.False}function _c(t,e){return S.False}function sk(t,e){return S.True}function xc(t){let[e,n]=[t,0];for(;m.IsNot(e);)e=e.not,n+=1;return n%2===0?e:tn()}function ak(t,e){return m.IsNot(t)?z(xc(t),e):m.IsNot(e)?z(t,xc(e)):Yn("Invalid fallthrough for Not")}function dk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsNull(e)?S.True:S.False}function Ec(t,e){return m.IsLiteralNumber(t)||m.IsNumber(t)||m.IsInteger(t)?S.True:S.False}function lk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsInteger(e)||m.IsNumber(e)?S.True:S.False}function Ge(t,e){return Object.getOwnPropertyNames(t.properties).length===e}function Ac(t){return ni(t)}function Rc(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 Za(t){return Ge(t,0)}function Tc(t){return Ge(t,0)}function uk(t){return Ge(t,0)}function pk(t){return Ge(t,0)}function ck(t){return ni(t)}function mk(t){let e=at();return Ge(t,0)||Ge(t,1)&&"length"in t.properties&&pt(z(t.properties.length,e))===S.True}function fk(t){return Ge(t,0)}function ni(t){let e=at();return Ge(t,0)||Ge(t,1)&&"length"in t.properties&&pt(z(t.properties.length,e))===S.True}function gk(t){let e=Mt([Yt()],Yt());return Ge(t,0)||Ge(t,1)&&"then"in t.properties&&pt(z(t.properties.then,e))===S.True}function Oc(t,e){return z(t,e)===S.False||m.IsOptional(t)&&!m.IsOptional(e)?S.False:S.True}function $e(t,e){return m.IsUnknown(t)?S.False:m.IsAny(t)?S.Union:m.IsNever(t)||m.IsLiteralString(t)&&Ac(e)||m.IsLiteralNumber(t)&&Za(e)||m.IsLiteralBoolean(t)&&Tc(e)||m.IsSymbol(t)&&Rc(e)||m.IsBigInt(t)&&uk(e)||m.IsString(t)&&Ac(e)||m.IsSymbol(t)&&Rc(e)||m.IsNumber(t)&&Za(e)||m.IsInteger(t)&&Za(e)||m.IsBoolean(t)&&Tc(e)||m.IsUint8Array(t)&&ck(e)||m.IsDate(t)&&pk(e)||m.IsConstructor(t)&&fk(e)||m.IsFunction(t)&&mk(e)?S.True:m.IsRecord(t)&&m.IsString(td(t))?e[st]==="Record"?S.True:S.False:m.IsRecord(t)&&m.IsNumber(td(t))&&Ge(e,0)?S.True:S.False}function hk(t,e){return ke(e)?ve(t,e):m.IsRecord(e)?ct(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(Oc(t.properties[n],e.properties[n])===S.False)return S.False}return S.True})():S.False}function Sk(t,e){return ke(e)?ve(t,e):m.IsObject(e)&&gk(e)?S.True:m.IsPromise(e)?pt(z(t.item,e.item)):S.False}function td(t){return Qt in t.patternProperties?at():Jt in t.patternProperties?xt():Yn("Unknown record key pattern")}function nd(t){return Qt in t.patternProperties?t.patternProperties[Qt]:Jt in t.patternProperties?t.patternProperties[Jt]:Yn("Unable to get record value schema")}function ct(t,e){let[n,r]=[td(e),nd(e)];return m.IsLiteralString(t)&&m.IsNumber(n)&&pt(z(t,r))===S.True?S.True:m.IsUint8Array(t)&&m.IsNumber(n)||m.IsString(t)&&m.IsNumber(n)||m.IsArray(t)&&m.IsNumber(n)?z(t,r):m.IsObject(t)?(()=>{for(let o of Object.getOwnPropertyNames(t.properties))if(Oc(r,t.properties[o])===S.False)return S.False;return S.True})():S.False}function yk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?z(nd(t),nd(e)):S.False}function kk(t,e){let n=m.IsRegExp(t)?xt():t,r=m.IsRegExp(e)?xt():e;return z(n,r)}function $c(t,e){return m.IsLiteral(t)&&_e.IsString(t.const)||m.IsString(t)?S.True:S.False}function vk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsString(e)?S.True:S.False}function Pk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsSymbol(e)?S.True:S.False}function wk(t,e){return m.IsTemplateLiteral(t)?z(bn(t),e):m.IsTemplateLiteral(e)?z(t,bn(e)):Yn("Invalid fallthrough for TemplateLiteral")}function Ik(t,e){return m.IsArray(e)&&t.items!==void 0&&t.items.every(n=>z(n,e.items)===S.True)}function bk(t,e){return m.IsNever(t)?S.True:m.IsUnknown(t)?S.False:m.IsAny(t)?S.Union:S.False}function xk(t,e){return ke(e)?ve(t,e):m.IsObject(e)&&ni(e)||m.IsArray(e)&&Ik(t,e)?S.True:m.IsTuple(e)?_e.IsUndefined(t.items)&&!_e.IsUndefined(e.items)||!_e.IsUndefined(t.items)&&_e.IsUndefined(e.items)?S.False:_e.IsUndefined(t.items)&&!_e.IsUndefined(e.items)||t.items.every((n,r)=>z(n,e.items[r])===S.True)?S.True:S.False:S.False}function Ak(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsUint8Array(e)?S.True:S.False}function Rk(t,e){return ke(e)?ve(t,e):m.IsObject(e)?$e(t,e):m.IsRecord(e)?ct(t,e):m.IsVoid(e)?Mk(t,e):m.IsUndefined(e)?S.True:S.False}function od(t,e){return e.anyOf.some(n=>z(t,n)===S.True)?S.True:S.False}function Tk(t,e){return t.anyOf.every(n=>z(n,e)===S.True)?S.True:S.False}function Dc(t,e){return S.True}function Ck(t,e){return m.IsNever(e)?_c(t,e):m.IsIntersect(e)?ti(t,e):m.IsUnion(e)?od(t,e):m.IsAny(e)?rd(t,e):m.IsString(e)?$c(t,e):m.IsNumber(e)?Ec(t,e):m.IsInteger(e)?Mc(t,e):m.IsBoolean(e)?Cc(t,e):m.IsArray(e)?zy(t,e):m.IsTuple(e)?bk(t,e):m.IsObject(e)?$e(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 _k(t,e){return m.IsIntersect(e)?ti(t,e):m.IsUnion(e)?od(t,e):m.IsUnknown(e)?Dc(t,e):m.IsAny(e)?rd(t,e):m.IsObject(e)?$e(t,e):m.IsVoid(e)?S.True:S.False}function z(t,e){return m.IsTemplateLiteral(t)||m.IsTemplateLiteral(e)?wk(t,e):m.IsRegExp(t)||m.IsRegExp(e)?kk(t,e):m.IsNot(t)||m.IsNot(e)?ak(t,e):m.IsAny(t)?Hy(t,e):m.IsArray(t)?Qy(t,e):m.IsBigInt(t)?Yy(t,e):m.IsBoolean(t)?Xy(t,e):m.IsAsyncIterator(t)?Jy(t,e):m.IsConstructor(t)?Zy(t,e):m.IsDate(t)?ek(t,e):m.IsFunction(t)?tk(t,e):m.IsInteger(t)?nk(t,e):m.IsIntersect(t)?rk(t,e):m.IsIterator(t)?ok(t,e):m.IsLiteral(t)?ik(t,e):m.IsNever(t)?sk(t,e):m.IsNull(t)?dk(t,e):m.IsNumber(t)?lk(t,e):m.IsObject(t)?hk(t,e):m.IsRecord(t)?yk(t,e):m.IsString(t)?vk(t,e):m.IsSymbol(t)?Pk(t,e):m.IsTuple(t)?xk(t,e):m.IsPromise(t)?Sk(t,e):m.IsUint8Array(t)?Ak(t,e):m.IsUndefined(t)?Rk(t,e):m.IsUnion(t)?Tk(t,e):m.IsUnknown(t)?Ck(t,e):m.IsVoid(t)?_k(t,e):Yn(`Unknown left type operand '${t[w]}'`)}function nn(t,e){return z(t,e)}var ed,S,id=p(()=>{Er();Pn();In();jn();Jn();Gt();Mr();T();Ct();va();ed=class extends we{};(function(t){t[t.Union=0]="Union",t[t.True=1]="True",t[t.False=2]="False"})(S||(S={}))});function Ek(t,e,n,r,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=Xn(t[s],e,n,r,ee(o));return i}function Ok(t,e,n,r,o){return Ek(t.properties,e,n,r,o)}function Nc(t,e,n,r,o){let i=Ok(t,e,n,r,o);return B(i)}var sd=p(()=>{Pe();ri();Be()});function $k(t,e,n,r){let o=nn(t,e);return o===S.Union?V([n,r]):o===S.True?n:r}function Xn(t,e,n,r,o){return te(t)?Nc(t,e,n,r,o):Qe(t)?h(Fc(t,e,n,r,o)):h($k(t,e,n,r),o)}var ri=p(()=>{R();ye();id();ad();sd();W()});function Dk(t,e,n,r,o){return{[t]:Xn(K(t),e,n,r,ee(o))}}function Nk(t,e,n,r,o){return t.reduce((i,s)=>({...i,...Dk(s,e,n,r,o)}),{})}function Fk(t,e,n,r,o){return Nk(t.keys,e,n,r,o)}function Fc(t,e,n,r,o){let i=Fk(t,e,n,r,o);return B(i)}var ad=p(()=>{Pe();Ke();ri();Be()});var Lc=p(()=>{});var Gr=p(()=>{id();ad();sd();Lc();ri()});function Wc(t,e){return Zn(bn(t),e)}var dd=p(()=>{oi();Gt()});function Lk(t,e){let n=t.filter(r=>nn(r,e)===S.False);return n.length===1?n[0]:V(n)}function Zn(t,e,n={}){return Je(t)?h(Wc(t,e),n):te(t)?h(Bc(t,e),n):h(F(t)?Lk(t.anyOf,e):nn(t,e)!==S.False?L():t,n)}var oi=p(()=>{R();ye();Re();Gr();ld();dd();W()});function Wk(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=Zn(t[r],e);return n}function Bk(t,e){return Wk(t.properties,e)}function Bc(t,e){let n=Bk(t,e);return B(n)}var ld=p(()=>{Pe();oi()});var ud=p(()=>{ld();dd();oi()});function Uc(t,e){return er(bn(t),e)}var pd=p(()=>{ii();Gt()});function Uk(t,e){let n=t.filter(r=>nn(r,e)!==S.False);return n.length===1?n[0]:V(n)}function er(t,e,n){return Je(t)?h(Uc(t,e),n):te(t)?h(Kc(t,e),n):h(F(t)?Uk(t.anyOf,e):nn(t,e)!==S.False?t:L(),n)}var ii=p(()=>{R();ye();Re();Gr();cd();pd();W()});function Kk(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=er(t[r],e);return n}function Vk(t,e){return Kk(t.properties,e)}function Kc(t,e){let n=Vk(t,e);return B(n)}var cd=p(()=>{Pe();ii()});var md=p(()=>{cd();pd();ii()});function Vc(t,e){return Pt(t)?h(t.returns,e):L(e)}var qc=p(()=>{R();Re();W()});var fd=p(()=>{qc()});function si(t){return qe(Ee(t))}var Gc=p(()=>{xn();Vt()});var ai=p(()=>{Gc()});function Rn(t,e,n){return h({[w]:"Record",type:"object",patternProperties:{[t]:e}},n)}function gd(t,e,n){let r={};for(let o of t)r[o]=e;return H(r,{...n,[st]:"Record"})}function qk(t,e,n){return Mp(t)?gd(Ve(t),e,n):Rn(t.pattern,e,n)}function Gk(t,e,n){return gd(Ve(V(t)),e,n)}function jk(t,e,n){return gd([t.toString()],e,n)}function Hk(t,e,n){return Rn(t.source,e,n)}function zk(t,e,n){let r=me(t.pattern)?Jt:t.pattern;return Rn(r,e,n)}function Qk(t,e,n){return Rn(Jt,e,n)}function Jk(t,e,n){return Rn(ip,e,n)}function Yk(t,e,n){return H({true:e,false:e},n)}function Xk(t,e,n){return Rn(Qt,e,n)}function Zk(t,e,n){return Rn(Qt,e,n)}function di(t,e,n={}){return F(t)?Gk(t.anyOf,e,n):Je(t)?qk(t,e,n):ze(t)?jk(t.const,e,n):Wt(t)?Yk(t,e,n):It(t)?Xk(t,e,n):bt(t)?Zk(t,e,n):ga(t)?Hk(t,e,n):Bt(t)?zk(t,e,n):ma(t)?Qk(t,e,n):Ht(t)?Jk(t,e,n):L(n)}function li(t){return globalThis.Object.getOwnPropertyNames(t.patternProperties)[0]}function jc(t){let e=li(t);return e===Jt?xt():e===Qt?at():xt({pattern:e})}function ui(t){return t.patternProperties[li(t)]}var Hc=p(()=>{R();T();Re();In();Ze();jn();ye();Gt();Mr();Et();Fe();W()});var jr=p(()=>{Hc()});function ev(t,e){return e.parameters=Hr(t,e.parameters),e.returns=At(t,e.returns),e}function tv(t,e){return e.parameters=Hr(t,e.parameters),e.returns=At(t,e.returns),e}function nv(t,e){return e.allOf=Hr(t,e.allOf),e}function rv(t,e){return e.anyOf=Hr(t,e.anyOf),e}function ov(t,e){return me(e.items)||(e.items=Hr(t,e.items)),e}function iv(t,e){return e.items=At(t,e.items),e}function sv(t,e){return e.items=At(t,e.items),e}function av(t,e){return e.items=At(t,e.items),e}function dv(t,e){return e.item=At(t,e.item),e}function lv(t,e){let n=mv(t,e.properties);return{...e,...H(n)}}function uv(t,e){let n=At(t,jc(e)),r=At(t,ui(e)),o=di(n,r);return{...e,...o}}function pv(t,e){return e.index in t?t[e.index]:tn()}function cv(t,e){let n=Wn(e),r=Ue(e),o=At(t,e);return n&&r?si(o):n&&!r?qe(o):!n&&r?Ee(o):o}function mv(t,e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,r)=>({...n,[r]:cv(t,e[r])}),{})}function Hr(t,e){return e.map(n=>At(t,n))}function At(t,e){return Pt(e)?ev(t,e):wt(e)?tv(t,e):oe(e)?nv(t,e):F(e)?rv(t,e):Ye(e)?ov(t,e):kt(e)?iv(t,e):hn(e)?sv(t,e):yn(e)?av(t,e):kn(e)?dv(t,e):fe(e)?lv(t,e):vn(e)?uv(t,e):fa(e)?pv(t,e):e}function zc(t,e){return At(e,Ln(t))}var Qc=p(()=>{To();Jn();ai();xn();Vt();Ze();jr();Fe();W()});var hd=p(()=>{Qc()});function Jc(t){return h({[w]:"Integer",type:"integer"},t)}var Yc=p(()=>{R();T()});var Sd=p(()=>{Yc()});function fv(t,e,n){return{[t]:Rt(K(t),e,ee(n))}}function gv(t,e,n){return t.reduce((o,i)=>({...o,...fv(i,e,n)}),{})}function hv(t,e,n){return gv(t.keys,e,n)}function Xc(t,e,n){let r=hv(t,e,n);return B(r)}var yd=p(()=>{Pe();Tn();Ke();Be()});function Sv(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toLowerCase(),n].join("")}function yv(t){let[e,n]=[t.slice(0,1),t.slice(1)];return[e.toUpperCase(),n].join("")}function kv(t){return t.toUpperCase()}function vv(t){return t.toLowerCase()}function Pv(t,e,n){let r=qn(t.pattern);if(!wn(r))return{...t,pattern:Zc(t.pattern,e)};let s=[...Lr(r)].map(l=>K(l)),a=em(s,e),d=V(a);return Lo([d],n)}function Zc(t,e){return typeof t=="string"?e==="Uncapitalize"?Sv(t):e==="Capitalize"?yv(t):e==="Uppercase"?kv(t):e==="Lowercase"?vv(t):t:t.toString()}function em(t,e){return t.map(n=>Rt(n,e))}function Rt(t,e,n={}){return Qe(t)?Xc(t,e,n):Je(t)?Pv(t,e,n):F(t)?V(em(t.anyOf,e),n):ze(t)?K(Zc(t.const,e),n):h(t,n)}var Tn=p(()=>{R();Gt();yd();Ke();ye();W()});function tm(t,e={}){return Rt(t,"Capitalize",e)}var nm=p(()=>{Tn()});function rm(t,e={}){return Rt(t,"Lowercase",e)}var om=p(()=>{Tn()});function im(t,e={}){return Rt(t,"Uncapitalize",e)}var sm=p(()=>{Tn()});function am(t,e={}){return Rt(t,"Uppercase",e)}var dm=p(()=>{Tn()});var kd=p(()=>{nm();yd();Tn();om();sm();dm()});function wv(t,e,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(t))r[o]=rn(t[o],e,ee(n));return r}function Iv(t,e,n){return wv(t.properties,e,n)}function lm(t,e,n){let r=Iv(t,e,n);return B(r)}var vd=p(()=>{Pe();pi();Be()});function bv(t,e){return t.map(n=>Pd(n,e))}function xv(t,e){return t.map(n=>Pd(n,e))}function Av(t,e){let{[e]:n,...r}=t;return r}function Rv(t,e){return e.reduce((n,r)=>Av(n,r),t)}function Tv(t,e,n){let r=ie(t,[Se,"$id","required","properties"]),o=Rv(n,e);return H(o,r)}function Cv(t){let e=t.reduce((n,r)=>Mo(r)?[...n,K(r)]:n,[]);return V(e)}function Pd(t,e){return oe(t)?Oe(bv(t.allOf,e)):F(t)?V(xv(t.anyOf,e)):fe(t)?Tv(t,e,t.properties):H({})}function rn(t,e,n){let r=ce(e)?Cv(e):e,o=Xe(e)?Ve(e):e,i=de(t),s=de(e);return te(t)?lm(t,o,n):Qe(e)?um(t,e,n):i&&s?Z("Omit",[t,r],n):!i&&s?Z("Omit",[t,r],n):i&&!s?Z("Omit",[t,r],n):h({...Pd(t,o),...n})}var pi=p(()=>{R();Eo();Ir();Xt();Ke();Et();dt();ye();Ze();wd();vd();W();Fe()});function Mv(t,e,n){return{[e]:rn(t,[e],ee(n))}}function _v(t,e,n){return e.reduce((r,o)=>({...r,...Mv(t,o,n)}),{})}function Ev(t,e,n){return _v(t,e.keys,n)}function um(t,e,n){let r=Ev(t,e,n);return B(r)}var wd=p(()=>{Pe();pi();Be()});var ci=p(()=>{wd();vd();pi()});function Ov(t,e,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(t))r[o]=on(t[o],e,ee(n));return r}function $v(t,e,n){return Ov(t.properties,e,n)}function pm(t,e,n){let r=$v(t,e,n);return B(r)}var Id=p(()=>{Pe();mi();Be()});function Dv(t,e){return t.map(n=>bd(n,e))}function Nv(t,e){return t.map(n=>bd(n,e))}function Fv(t,e){let n={};for(let r of e)r in t&&(n[r]=t[r]);return n}function Lv(t,e,n){let r=ie(t,[Se,"$id","required","properties"]),o=Fv(n,e);return H(o,r)}function Wv(t){let e=t.reduce((n,r)=>Mo(r)?[...n,K(r)]:n,[]);return V(e)}function bd(t,e){return oe(t)?Oe(Dv(t.allOf,e)):F(t)?V(Nv(t.anyOf,e)):fe(t)?Lv(t,e,t.properties):H({})}function on(t,e,n){let r=ce(e)?Wv(e):e,o=Xe(e)?Ve(e):e,i=de(t),s=de(e);return te(t)?pm(t,o,n):Qe(e)?cm(t,e,n):i&&s?Z("Pick",[t,r],n):!i&&s?Z("Pick",[t,r],n):i&&!s?Z("Pick",[t,r],n):h({...bd(t,o),...n})}var mi=p(()=>{R();Eo();Xt();dt();Ke();Ze();ye();Et();Ir();W();Fe();xd();Id()});function Bv(t,e,n){return{[e]:on(t,[e],ee(n))}}function Uv(t,e,n){return e.reduce((r,o)=>({...r,...Bv(t,o,n)}),{})}function Kv(t,e,n){return Uv(t,e.keys,n)}function cm(t,e,n){let r=Kv(t,e,n);return B(r)}var xd=p(()=>{Pe();mi();Be()});var fi=p(()=>{xd();Id();mi()});function Vv(t,e){return Z("Partial",[Z(t,e)])}function qv(t){return Z("Partial",[Ot(t)])}function Gv(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=Ee(t[n]);return e}function jv(t,e){let n=ie(t,[Se,"$id","required","properties"]),r=Gv(e);return H(r,n)}function mm(t){return t.map(e=>fm(e))}function fm(t){return vt(t)?Vv(t.target,t.parameters):de(t)?qv(t.$ref):oe(t)?Oe(mm(t.allOf)):F(t)?V(mm(t.anyOf)):fe(t)?jv(t,t.properties):Sn(t)||Wt(t)||It(t)||ze(t)||br(t)||bt(t)||Bt(t)||xr(t)||Ar(t)?t:H({})}function tr(t,e){return te(t)?gm(t,e):h({...fm(t),...e})}var Ad=p(()=>{R();Xt();Vt();Ze();dt();ye();An();Kt();T();Rd();W()});function Hv(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=tr(t[r],ee(e));return n}function zv(t,e){return Hv(t.properties,e)}function gm(t,e){let n=zv(t,e);return B(n)}var Rd=p(()=>{Pe();Ad();Be()});var gi=p(()=>{Rd();Ad()});function Qv(t,e){return Z("Required",[Z(t,e)])}function Jv(t){return Z("Required",[Ot(t)])}function Yv(t){let e={};for(let n of globalThis.Object.getOwnPropertyNames(t))e[n]=ie(t[n],[Ae]);return e}function Xv(t,e){let n=ie(t,[Se,"$id","required","properties"]),r=Yv(e);return H(r,n)}function hm(t){return t.map(e=>Sm(e))}function Sm(t){return vt(t)?Qv(t.target,t.parameters):de(t)?Jv(t.$ref):oe(t)?Oe(hm(t.allOf)):F(t)?V(hm(t.anyOf)):fe(t)?Xv(t,t.properties):Sn(t)||Wt(t)||It(t)||ze(t)||br(t)||bt(t)||Bt(t)||xr(t)||Ar(t)?t:H({})}function nr(t,e){return te(t)?ym(t,e):h({...Sm(t),...e})}var Td=p(()=>{R();Xt();Ze();dt();ye();An();T();Kt();Cd();W()});function Zv(t,e){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=nr(t[r],e);return n}function eP(t,e){return Zv(t.properties,e)}function ym(t,e){let n=eP(t,e);return B(n)}var Cd=p(()=>{Pe();Td()});var hi=p(()=>{Cd();Td()});function tP(t,e){return e.map(n=>de(n)?Md(t,n.$ref):et(t,n))}function Md(t,e){return e in t?de(t[e])?Md(t,t[e].$ref):et(t,t[e]):L()}function nP(t){return zn(t[0])}function rP(t){return Zt(t[0],t[1])}function oP(t){return Qn(t[0])}function iP(t){return tr(t[0])}function sP(t){return rn(t[0],t[1])}function aP(t){return on(t[0],t[1])}function dP(t){return nr(t[0])}function lP(t,e,n){let r=tP(t,n);return e==="Awaited"?nP(r):e==="Index"?rP(r):e==="KeyOf"?oP(r):e==="Partial"?iP(r):e==="Omit"?sP(r):e==="Pick"?aP(r):e==="Required"?dP(r):L()}function uP(t,e){return Bn(et(t,e))}function pP(t,e){return Un(et(t,e))}function cP(t,e,n){return Kn(zr(t,e),et(t,n))}function mP(t,e,n){return Mt(zr(t,e),et(t,n))}function fP(t,e){return Oe(zr(t,e))}function gP(t,e){return Hn(et(t,e))}function hP(t,e){return H(globalThis.Object.keys(e).reduce((n,r)=>({...n,[r]:et(t,e[r])}),{}))}function SP(t,e){let[n,r]=[et(t,ui(e)),li(e)],o=Ln(e);return o.patternProperties[r]=n,o}function yP(t,e){return de(e)?{...Md(t,e.$ref),[Se]:e[Se]}:e}function kP(t,e){return lt(zr(t,e))}function vP(t,e){return V(zr(t,e))}function zr(t,e){return e.map(n=>et(t,n))}function et(t,e){return Ue(e)?h(et(t,ie(e,[Ae])),e):Wn(e)?h(et(t,ie(e,[yt])),e):zt(e)?h(yP(t,e),e):kt(e)?h(uP(t,e.items),e):hn(e)?h(pP(t,e.items),e):vt(e)?h(lP(t,e.target,e.parameters)):Pt(e)?h(cP(t,e.parameters,e.returns),e):wt(e)?h(mP(t,e.parameters,e.returns),e):oe(e)?h(fP(t,e.allOf),e):yn(e)?h(gP(t,e.items),e):fe(e)?h(hP(t,e.properties),e):vn(e)?h(SP(t,e)):Ye(e)?h(kP(t,e.items||[]),e):F(e)?h(vP(t,e.anyOf),e):e}function PP(t,e){return e in t?et(t,t[e]):L()}function km(t){return globalThis.Object.getOwnPropertyNames(t).reduce((e,n)=>({...e,[n]:PP(t,n)}),{})}var vm=p(()=>{Lt();ca();Kt();Or();Vo();$r();Dr();Et();Pn();dt();Br();qr();Ze();ci();fi();Re();gi();jr();hi();en();ye();T();W()});function Pm(t){return new _d(t)}var _d,wm=p(()=>{Lt();T();vm();_d=class{constructor(e){let n=km(e),r=this.WithIdentifiers(n);this.$defs=r}Import(e,n){let r={...this.$defs,[e]:h(this.$defs[e],n)};return h({[w]:"Import",$defs:r,$ref:e})}WithIdentifiers(e){return globalThis.Object.getOwnPropertyNames(e).reduce((n,r)=>({...n,[r]:{...e[r],$id:r}}),{})}}});var Ed=p(()=>{wm()});function Im(t,e){return h({[w]:"Not",not:t},e)}var bm=p(()=>{R();T()});var Od=p(()=>{bm()});function xm(t,e){return wt(t)?lt(t.parameters,e):L()}var Am=p(()=>{en();Re();W()});var $d=p(()=>{Am()});function Rm(t,e={}){me(e.$id)&&(e.$id=`T${wP++}`);let n=Ln(t({[w]:"This",$ref:`${e.$id}`}));return n.$id=e.$id,h({[st]:"Recursive",...n},e)}var wP,Tm=p(()=>{To();R();Fe();T();wP=0});var Dd=p(()=>{Tm()});function Cm(t,e){let n=Q(t)?new globalThis.RegExp(t):t;return h({[w]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},e)}var Mm=p(()=>{R();Fe();T()});var Nd=p(()=>{Mm()});function IP(t){return oe(t)?t.allOf:F(t)?t.anyOf:Ye(t)?t.items??[]:[]}function _m(t){return IP(t)}var Em=p(()=>{W()});var Fd=p(()=>{Em()});function Om(t,e){return wt(t)?h(t.returns,e):L(e)}var $m=p(()=>{R();Re();W()});var Ld=p(()=>{$m()});var Dm=p(()=>{});var Nm=p(()=>{});var Fm=p(()=>{Dm();Nm()});var Lm=p(()=>{});var Wm=p(()=>{Lm()});function Bm(t){return new Wd(t)}var Wd,Bd,Um=p(()=>{T();W();Wd=class{constructor(e){this.schema=e}Decode(e){return new Bd(this.schema,e)}},Bd=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 zt(this.schema)?this.EncodeTransform(e,this.schema):this.EncodeSchema(e,this.schema)}}});var Ud=p(()=>{Um()});function Km(t={}){return h({[w]:t[w]??"Unsafe"},t)}var Vm=p(()=>{R();T()});var Kd=p(()=>{Vm()});function qm(t){return h({[w]:"Void",type:"void"},t)}var Gm=p(()=>{R();T()});var Vd=p(()=>{Gm()});var qd={};xo(qd,{Any:()=>Yt,Argument:()=>Sp,Array:()=>Bn,AsyncIterator:()=>Un,Awaited:()=>zn,BigInt:()=>Gn,Boolean:()=>No,Capitalize:()=>tm,Composite:()=>pc,Const:()=>kc,Constructor:()=>Kn,ConstructorParameters:()=>Pc,Date:()=>qo,Enum:()=>Ic,Exclude:()=>Zn,Extends:()=>Xn,Extract:()=>er,Function:()=>Mt,Index:()=>Zt,InstanceType:()=>Vc,Instantiate:()=>zc,Integer:()=>Jc,Intersect:()=>Oe,Iterator:()=>Hn,KeyOf:()=>Qn,Literal:()=>K,Lowercase:()=>rm,Mapped:()=>Xp,Module:()=>Pm,Never:()=>L,Not:()=>Im,Null:()=>jo,Number:()=>at,Object:()=>H,Omit:()=>rn,Optional:()=>Ee,Parameters:()=>xm,Partial:()=>tr,Pick:()=>on,Promise:()=>Uo,Readonly:()=>qe,ReadonlyOptional:()=>si,Record:()=>di,Recursive:()=>Rm,Ref:()=>Ot,RegExp:()=>Cm,Required:()=>nr,Rest:()=>_m,ReturnType:()=>Om,String:()=>xt,Symbol:()=>zo,TemplateLiteral:()=>Lo,Transform:()=>Bm,Tuple:()=>lt,Uint8Array:()=>Xo,Uncapitalize:()=>im,Undefined:()=>Jo,Union:()=>V,Unknown:()=>tn,Unsafe:()=>Km,Uppercase:()=>am,Void:()=>qm});var jm=p(()=>{Er();Ia();Or();$r();Vo();Wr();Fo();za();Ja();Dr();Ya();Go();Xa();ud();Gr();md();Pn();Et();fd();hd();Sd();dt();kd();Br();qr();Ke();Pe();Ed();Re();Od();Ho();In();Ze();ci();Vt();$d();gi();fi();Ko();xn();ai();jr();Dd();An();Nd();hi();Fd();Ld();jn();Qo();Gt();Ud();en();Zo();Yo();ye();Jn();Kd();Vd()});var c,Hm=p(()=>{jm();c=qd});var De=p(()=>{ca();Lt();Ct();va();op();Mr();lp();_r();T();Er();Or();Ia();$r();Vo();Wr();Fo();za();Ja();Dr();Ya();Go();Xa();ud();Gr();md();Pn();Et();fd();hd();Sd();dt();Br();kd();qr();Ke();Ed();Pe();Re();Od();Ho();In();Ze();ci();Vt();$d();gi();fi();Ko();xn();ai();jr();Dd();An();Nd();hi();Fd();Ld();Fm();Wm();jn();Qo();Gt();Ud();en();Zo();Yo();ye();Jn();Kd();Vd();Hm()});function Gd(t){v=t}function jd(t){ge=t}var v,ge,Y=p(()=>{v=null,ge=null});function zm(t){let e=t.chatId.trim(),n=t.topicId.trim();return!/^-?\d+$/.test(e)||!/^\d+$/.test(n)?null:`${e}:topic:${n}`}function TP(t){let e=t.conversationId.trim(),n=e.match(/^(-?\d+):topic:(\d+)$/i);if(n?.[1]&&n[2]){let i=zm({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=zm({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 _P(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 EP(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 OP(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||!RP.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 $P(t,e=TP){try{return e({conversationId:t})}catch{return null}}function Hd(t){return{provider:"system",target:"system",sessionKey:t?.trim()||void 0}}function zd(t,e){return{...t,threadId:e??t.threadId}}function NP(t,e,n){return t==="telegram"&&n?.provider==="telegram"&&!!n.target&&e!==n.target}function FP(t){let e=t?.trim();if(!e)return;let n=OP(e);if(!n)return;let{provider:r,kind:o,rawId:i}=n,s=EP(i),a=null;if(r==="telegram")try{a=DP.safeParseTelegramTopicConversation(i)}catch{a=null}let d=a?.chatId??s.id,l=a?.topicId??s.threadId,u=r==="discord"?o==="direct"||o==="dm"?`user:${d}`:`channel:${d}`:d;return{provider:r,target:u,threadId:l,sessionKey:e}}function Qd(t){let e=t?.match(/:topic:(\d+)$/);return e?parseInt(e[1],10):void 0}function LP(t){return!!(t?.provider&&t.target&&t.provider!=="system"&&t.target!=="system")}function Qr(t,e,n){let r=FP(n),o=e!=null?String(e):void 0,i=t?.trim();if(!i||i.toLowerCase()==="unknown")return r?zd(r,o):Hd(n);let s=i.split("|").map(k=>k.trim());if(s.length<2)return r?zd(r,o):Hd(n);let[a,d,l]=s,u=s.length>=3?l:d,f=s.length>=3?d:void 0,g=a?.toLowerCase();if(!g||!u)return r?zd(r,o):Hd(n);let y=g==="discord"?MP(u,n):u;return NP(g,y,r)?{provider:g,accountId:f,target:r.target,threadId:o??r.threadId,sessionKey:n?.trim()||void 0}:{provider:g,accountId:f,target:y,threadId:o??(r?.provider===g?r.threadId:void 0),sessionKey:n?.trim()||void 0}}function rr(t){return Qr(_P(t.route)??t.originChannel,t.route?.threadId??t.originThreadId,t.route?.sessionKey??t.originSessionKey)??t.route}function yi(t){let e=rr(t);return LP(e)?e:void 0}var RP,DP,Cn=p(()=>{RP=new Set(["telegram","discord","slack","system","mattermost","feishu","line","whatsapp","signal","matrix","googlechat","bluebubbles","imessage","msteams"]);DP={safeParseTelegramTopicConversation:$P}});import{readFileSync as WP}from"fs";import{homedir as BP}from"os";import{join as UP}from"path";function Jm(){if(Jr!==void 0)return Jr;try{let t=WP(UP(BP(),".claude.json"),"utf-8");Jr=JSON.parse(t).mcpServers??{}}catch{Jr={}}return Jr}function Ym(t){let e=t.defaultHarness??Qm,n={};for(let[r,o]of Object.entries(ki))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 Le(){return _.defaultHarness??Qm}function Xm(t){let e=ki[t],n=_.harnesses[t];return{...e,...n,allowedModels:n?.allowedModels??e?.allowedModels}}function or(t){return Xm(t).defaultModel}function vi(t){return _.harnesses[t]?.allowedModels??_.allowedModels}function sn(t){return Xm(t).reasoningEffort}function $t(t){return t==null?void 0:String(t).trim()||void 0}function Xd(t){return{channel:$t(t?.deliveryContext?.channel),to:$t(t?.deliveryContext?.to),accountId:$t(t?.deliveryContext?.accountId),threadId:$t(t?.deliveryContext?.threadId)}}function Zm(t,e,n){if(!(!t||!e))return n?`${t}|${n}|${e}`:`${t}|${e}`}function Jd(t){return $t(t?.requesterSenderId??t?.senderId)}function Yd(t){return($t(t.deliveryContext?.channel)??t.messageChannel??t.channel)?.toLowerCase()!=="telegram"?!1:!!Qd(t.sessionKey)}function Pi(t){let e=Xd(t),n=Zm(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=$t(t.chatId);if(r.length===1&&o)return`${r[0]}|${o}`;let i=Jd(t);if(r.length===1&&i&&!Yd(t))return`${r[0]}|${i}`}if(t.workspaceDir){let r=Xr(t.workspaceDir);if(r)return r}if(t.messageChannel&&t.messageChannel.includes("|"))return t.messageChannel}function Yr(t,e){if(e&&String(e).includes("|"))return String(e);let n=Xd(t),r=Zm(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=$t(t.chatId);if(d)return`${a}|${d}`;let l=Jd(t);if(l&&!Yd(t))return`${a}|${l}`}let o=$t(t?.channel),i=$t(t?.chatId);if(o&&i)return`${o}|${i}`;let s=Jd(t);return o&&s&&!Yd(t)?`${o}|${s}`:t?.id&&/^-?\d+$/.test(String(t.id))?`telegram|${t.id}`:_.fallbackChannel??"unknown"}function Zd(t){return Xd(t).threadId??t?.messageThreadId??void 0}function ir(t,e,n){return Qr(Yr(t,e),Zd(t),n??t?.sessionKey)}function Xr(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 ef(t){return Qd(t)}var Jr,Qm,ki,_,Te=p(()=>{Cn();Qm="claude-code",ki={"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":{...ki["claude-code"]},codex:{...ki.codex}}}});function wi(t){return{type:"backend_ref",ref:t}}function Ii(t){return{type:"run_started",...t?{runId:t}:{}}}function Zr(t){return{type:"text_delta",text:t}}function tf(t,e){return{type:"tool_call",name:t,input:e}}function bi(t){return{type:"pending_input",state:t}}function dr(t){return t?{type:"pending_input_resolved",requestId:t}:{type:"pending_input_resolved"}}function xi(t,e){return{type:"plan_artifact",artifact:t,finalized:e}}function Ai(t){return t?{type:"settings_changed",permissionMode:t}:{type:"settings_changed"}}function Mn(t){return{type:"run_completed",data:t}}var ar,el=p(()=>{ar=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 Ti from"@anthropic-ai/claude-agent-sdk";function KP(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 VP(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 Ri,nf=p(()=>{el();Ri=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 ar,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,b)=>{if(k!=="AskUserQuestion")return{behavior:"allow"};let P=VP(a,++s,b);n.enqueue(bi(P));try{let I=await d(k,b);return n.enqueue(dr(P.requestId)),I}catch(I){throw n.enqueue(dr(P.requestId)),I}}}:{}};e.resumeSessionId&&(l.resume=e.resumeSessionId,l.forkSession=e.forkSession??!1);let u=e.prompt,f=this.deps.query??Ti.query,g=this.deps.startup??Ti.startup,y=(async()=>{if(typeof g!="function")return f({prompt:u,options:l});let k=await g({options:l});try{return k.query(u)}catch(b){throw await k.close?.(),b}})();return(async()=>{try{let k=await y;for await(let b of k){let P=b;if(P.type==="system"&&P.subtype==="init"){a=P.session_id??a,n.enqueue(wi({kind:"claude-code",conversationId:a}));continue}if(P.type==="system"&&P.subtype==="status"&&P.permissionMode){n.enqueue(Ai(P.permissionMode));continue}if(P.type==="assistant"){r||(r=!0,n.enqueue(Ii()));for(let I of P.message?.content??[]){if(I.type==="text"){o+=o?`
3
+ ${I.text}`:I.text,n.enqueue(Zr(I.text));continue}I.type==="tool_use"&&((I.name==="ExitPlanMode"||I.name==="set_permission_mode")&&(i=!0),I.name!=="AskUserQuestion"&&n.enqueue(tf(I.name,I.input)))}continue}if(P.type==="result"){let I=o.trim();if(I&&(e.permissionMode==="plan"||i)){let A={explanation:void 0,steps:[],markdown:I};n.enqueue(xi(A,!0))}n.enqueue(Mn({success:P.subtype==="success",duration_ms:P.duration_ms??0,total_cost_usd:P.total_cost_usd??0,num_turns:P.num_turns??0,result:KP(P),session_id:P.session_id??a})),o="",i=!1,r=!1}}}finally{n.close()}})().catch(k=>{n.enqueue(Mn({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 b=await y;typeof b.setPermissionMode=="function"&&await b.setPermissionMode(k)},async streamInput(k){let b=await y;typeof b.streamInput=="function"&&await b.streamInput(k)},async interrupt(){let k=await y;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 qP}from"node:child_process";import GP from"node:readline";function jP(t){return t instanceof Error?t.message:String(t)}function HP(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}async function zP(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:jP(r)}})}}}var Ci,rf=p(()=>{Ci=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=qP(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,GP.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=HP(e);n&&await zP(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 X(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function le(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 QP(t){return t instanceof Error?t.message:String(t)}function of(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function an(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>an(n)).join("");let e=X(t);if(!e)return"";for(let n of["delta","text","content","message","input","output","parts"]){let r=an(e[n]);if(r)return r}for(let n of["item","turn","thread","response","result","data"]){let r=an(e[n]);if(r)return r}return""}function eo(t){let e=X(t);if(!e)return{};let n=X(e.thread)??X(e.session),r=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(n,["id","threadId","thread_id","conversationId"]),runId:le(e,["turnId","turn_id","runId","run_id"])??le(r,["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 Mi(t,e,n=0){if(n>6)return;if(Array.isArray(t)){for(let i of t){let s=Mi(i,e,n+1);if(s)return s}return}let r=X(t);if(!r)return;let o=le(r,e);if(o)return o;for(let i of Object.values(r)){let s=Mi(i,e,n+1);if(s)return s}}function to(t){return{threadId:eo(t).threadId,cwd:Mi(t,["cwd","workdir","directory"])}}function sf(t){let e=t?.trim();return!!(e&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(e))}function af(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 _i(t){let e=X(t);if(!e)return;let n=X(e.item)??e;return le(n,["id","itemId","item_id","messageId","message_id"])}function JP(t,e=!1){let n=X(t);if(!n)return"";let r=X(n.item)??n;return le(r,["type"])?.toLowerCase()!=="agentmessage"?"":e?an(r):le(r,["text"],{trim:!1})??an(r)}function df(t,e){let n=t.trim().toLowerCase();return n==="item/agentmessage/delta"?{mode:"delta",text:an(e),itemId:_i(e)}:n==="item/completed"?{mode:"snapshot",text:JP(e),itemId:_i(e)}:{mode:"ignore",text:""}}function lf(t){return{itemId:_i(t),delta:an(t)}}function uf(t){let e=X(t),n=X(e?.plan),o=(Array.isArray(e?.plan)?e.plan:Array.isArray(n?.steps)?n.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(n,["explanation"])??le(e,["explanation"]),steps:o}}function pf(t){let e=X(t);if(!e)return{};let n=X(e.item)??e;return le(n,["type"])?.toLowerCase()!=="plan"?{}:{itemId:_i(n),text:le(n,["text"],{trim:!1})??an(n)}}function cf(t,e){let n=t.trim().toLowerCase();if(n==="turn/failed")return"failed";if(n==="turn/cancelled")return"interrupted";let r=X(e)??{},o=X(r.turn)??r,i=le(o,["status"])?.toLowerCase();return i==="failed"?"failed":i==="interrupted"||i==="cancelled"?"interrupted":"completed"}function mf(t,e){let n=X(e)??{},r=X(n.turn)??n,o=X(r.error)??X(n.error);if(o)return le(o,["message","text","summary","reason"])}function YP(t,e){let n=QP(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 ZP(t){return XP.has(t.trim().toLowerCase())}function ew(t){let e=X(t);return e?!!le(e,["threadId","thread_id"]):!1}async function no(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(ZP(n)&&!ew(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,!YP(o,n))continue}}throw e instanceof Error?e:new Error(String(e))}function ff(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 gf(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 tw(t){return[{type:"text",text:t}]}function nw(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 hf(t){let e={threadId:t.threadId,input:tw(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=nw(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 Sf(t){return[{threadId:t.threadId,turnId:t.turnId}]}function rw(t){let e=X(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():le(X(r),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function ow(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 yf(t,e,n){let r=t.trim().toLowerCase(),o=rw(n),i=Mi(n,["question","prompt","message","text","summary","reason"])??void 0,s=r.includes("requestapproval"),a=s?o.map(d=>({kind:"approval",label:d,decision:ow(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 kf(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function tl(t,e){let n=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:n,sandbox:n==="never"?"danger-full-access":void 0}}var XP,vf=p(()=>{XP=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function Pf(t){return t instanceof Error?t.message:String(t)}function lw(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 iw,_n,sw,aw,dw,Ei,wf=p(()=>{rf();el();vf();iw="1.0",_n=6e4,sw="OPENCLAW_CODEX_APP_SERVER_COMMAND",aw="OPENCLAW_CODEX_APP_SERVER_ARGS",dw="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";Ei=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[sw]?.trim()||"codex",args:of(process.env[aw]),requestTimeoutMs:Number.parseInt(process.env[dw]??String(_n),10)||_n},r=this.deps.createClient?.(n)??new Ci(n.command,n.args,n.requestTimeoutMs),o=new ar,i=e.resumeSessionId,s,a=e.backendRef?.worktreePath,d=e.backendRef?.worktreeId,l=e.permissionMode??"default",u,f=0,g="",y=[],k,b=new Map,P=new Set,I=O=>{let $=O?.trim();if(!$)return;let U=e.originalWorkdir?.trim()||e.cwd.trim();e.worktreeStrategy&&e.worktreeStrategy!=="off"&&$!==U&&sf($)&&(a=$,d=af($))},A=()=>{i&&o.enqueue(wi({kind:"codex-app-server",conversationId:i,...s?{runId:s}:{},...d?{worktreeId:d}:{},...a?{worktreePath:a}:{}}))};r.setNotificationHandler(async(O,$)=>{let U=O.trim().toLowerCase(),pe=eo($),St=to($);if(pe.threadId&&i&&pe.threadId!==i)return;if(pe.threadId&&(i=pe.threadId),pe.runId&&(s=pe.runId),I(St.cwd),(pe.threadId||pe.runId||St.cwd)&&A(),U==="serverrequest/resolved"){u&&(o.enqueue(dr(u.requestId)),u=void 0);return}if(U==="turn/plan/updated"){let Me=uf($);g=Me.explanation??g,Me.steps.length>0&&(y=Me.steps);return}if(U==="item/plan/delta"){let Me=lf($);if(Me.itemId&&Me.delta){let jt=b.get(Me.itemId)??"";b.set(Me.itemId,`${jt}${Me.delta}`)}return}if(U==="item/completed"){let Me=pf($);if(Me.text?.trim()){let jt={explanation:g||void 0,steps:y,markdown:Me.text.trim()};o.enqueue(xi(jt,!0));return}}let ae=df(U,$);if(ae.mode==="delta"&&ae.text){ae.itemId&&P.add(ae.itemId),o.enqueue(Zr(ae.text));return}ae.mode==="snapshot"&&ae.text&&(!ae.itemId||!P.has(ae.itemId))&&o.enqueue(Zr(ae.text)),(U==="turn/completed"||U==="turn/failed"||U==="turn/cancelled")&&k&&(k.method=O,k.params=$,k.resolve())}),r.setRequestHandler(async(O,$)=>{if(!kf(O))return{};let U=eo($),pe=to($);if(U.threadId&&i&&U.threadId!==i)return{};U.threadId&&(i=U.threadId),U.runId&&(s=U.runId),I(pe.cwd),(U.threadId||U.runId||pe.cwd)&&A();let St=U.requestId??`${i??"codex"}-${Date.now().toString(36)}`,ae=yf(O,St,$),Me=O.trim().toLowerCase(),jt=ae.options,bo=ae.actions??[],Vh=await new Promise(qh=>{u={requestId:St,methodLower:Me,state:ae,options:jt,actions:bo,resolveResponse:qh},o.enqueue(bi(ae))});return u=void 0,o.enqueue(dr(St)),Vh});let C=async()=>{await r.connect(),await r.request("initialize",{protocolVersion:iw,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},_n),await r.notify("initialized",{})},N=async()=>{let O=tl(l,e.codexApprovalPolicy);if(i){let pe=await no({client:r,methods:["thread/resume"],payloads:gf({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:O.approvalPolicy,sandbox:O.sandbox}),timeoutMs:_n}),St=to(pe);i=St.threadId??i,I(St.cwd),A();return}let $=await no({client:r,methods:["thread/start","thread/new"],payloads:ff({cwd:e.originalWorkdir?.trim()||e.cwd,model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:O.approvalPolicy,sandbox:O.sandbox}),timeoutMs:_n}),U=to($);if(i=U.threadId,!i)throw new Error("Codex App Server did not return a thread id.");I(U.cwd),A()},xe=async O=>{await N(),o.enqueue(Ii()),f+=1,g="",y=[],b.clear(),P.clear();let $="",U,pe,St=new Promise(ae=>{pe=ae});k={resolve:pe};try{let ae=tl(l,e.codexApprovalPolicy),Me=await no({client:r,methods:["turn/start"],payloads:hf({threadId:i,prompt:O,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,permissionMode:l,approvalPolicy:ae.approvalPolicy,sandbox:ae.sandbox}),timeoutMs:_n}),jt=eo(Me);jt.runId&&(s=jt.runId,A()),await St,$=k?.method??"turn/failed",U=k?.params;let bo=cf($,U);o.enqueue(Mn({success:bo==="completed",outcome:bo,duration_ms:0,total_cost_usd:0,num_turns:f,result:mf($,U),session_id:i}))}catch(ae){o.enqueue(Mn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:f,result:Pf(ae),session_id:i??""}))}finally{k=void 0}},it=async O=>u?(u.methodLower.includes("requestapproval")?u.resolveResponse({decision:O.trim()||"decline"}):u.resolveResponse({text:O.trim()}),!0):!1,ru=async O=>{let $=u;if(!$)return!1;let U=$.actions[O];if(U?.kind==="approval")return $.resolveResponse({decision:U.responseDecision,...U.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:U.proposedExecpolicyAmendment}:{}}),!0;let pe=$.options[O];return pe?($.methodLower.includes("requestapproval")?$.resolveResponse({decision:pe}):$.resolveResponse({option:pe,index:O}),!0):!1},ou=typeof e.prompt=="string"?(async function*(){yield{type:"user",text:e.prompt,session_id:e.resumeSessionId??""}})():e.prompt;return(async()=>{try{await C();for await(let O of ou){let $=lw(O).trim();!$||await it($)||await xe($)}}catch(O){o.enqueue(Mn({success:!1,duration_ms:0,total_cost_usd:0,num_turns:f,result:Pf(O),session_id:i??e.resumeSessionId??""}))}finally{await r.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(O){l=O,o.enqueue(Ai(O))},async submitPendingInputOption(O){return ru(O)},async submitPendingInputText(O){return it(O)},async interrupt(){!i||!s||await no({client:r,methods:["turn/interrupt"],payloads:Sf({threadId:i,turnId:s}),timeoutMs:_n}).catch(()=>{})}}}buildUserMessage(e,n){return{type:"user",text:e,session_id:n}}}});function If(t){nl.set(t.name,t)}function ro(t){let e=nl.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...nl.keys()].join(", ")}`);return e}function bf(){return ro(Le())}var nl,rl=p(()=>{nf();wf();Te();nl=new Map;If(new Ri);If(new Ei)});function M(t){return t.backendRef?.conversationId??t.harnessSessionId}function ne(t){return t.id??t.sessionId??t.name??M(t)??t.harnessSessionId}function uw(t){return t.harnessSessionId}function tt(t){let e=[ne(t),M(t),uw(t)].filter(n=>!!n);return[...new Set(e)]}function ol(t){return t.harnessName??t.persistedHarness??Le()}function Oi(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return ro(ol(t)).capabilities.worktrees}catch{return"plugin-managed"}}function il(t){return t==="native-execution"||t==="native-restore"}function xf(t){return t==="native-restore"}function pw(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function We(t){return il(Oi(t))&&pw(t)}var he=p(()=>{Te();rl()});import{execFileSync as be}from"child_process";import*as Qi from"fs";import{tmpdir as Nw}from"os";import{dirname as jf,join as Fw}from"path";function Lw(t){try{return be("git",["rev-parse","--show-toplevel"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function Ji(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(_.worktreeDir)return _.worktreeDir;if(t){let e=Lw(t);if(e)return Fw(e,".worktrees")}return Nw()}function Hf(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function Yi(t){try{let e=be("git",["-C",t,"rev-parse","--git-common-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e&&e.endsWith("/.git")?jf(e):void 0}catch{return}}function Ww(){if(Hi!==void 0)return Hi;try{return be("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Hi=!0,!0}catch{return Hi=!1,!1}}function dn(){if(zi!==void 0)return zi;try{return be("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),zi=!0,!0}catch{return zi=!1,!1}}function pl(t){if(!Ww())return!1;try{return be("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function zf(t){try{let e=Uw(t);if(!e)return console.warn(`[worktree] Failed to resolve free-space probe path for ${Ji(t)}`),!0;let n=Qi.statfsSync(e),r=n.bavail*n.bsize;return Kw(r)}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function lo(t,e){try{return be("git",["-C",t,"rev-parse","--verify",e],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Bw(t){let e=t;for(;;){if(Qi.existsSync(e))return e;let n=jf(e);if(n===e)return;e=n}}function Uw(t){return Bw(Ji(t))}function Kw(t){return t>=104857600}function ln(t){let e=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(e)return e;try{let r=be("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 be("git",["-C",t,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return be("git",["-C",t,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function Xi(t){try{let n=be("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 cl(t,e,n){try{let r=be("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 Qf(t,e,n){try{let r=be("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 Jf(t,e,n){try{return be("git",["-C",t,"merge-base","--is-ancestor",e,n],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Yf(t,e,n){try{let r=be("git",["-C",t,"merge-tree","--write-tree",n,e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=be("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 Dt(t,e){try{return be("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 Xf(t,e){if(e)return e;let n;try{n=be("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}try{let r=be("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 Hi,zi,uo=p(()=>{Te()});import{execFileSync as po}from"child_process";import{existsSync as Vw,mkdirSync as Zf,rmSync as ml}from"fs";function qw(t,e){return!!(t&&typeof t=="object"&&"code"in t&&t.code===e)}function fl(t,e,n={}){let r=Hf(e),o=Ji(t);Zf(o,{recursive:!0});let i=n.allowExistingBranch===!0,s,a,d=10,l=!1;for(let f=0;f<d;f++){let g=f===0?"":`-${Math.random().toString(16).slice(2,6)}`,y=`${o}/openclaw-worktree-${r}${g}`,k=`agent/${r}${g}`;if(!i&&lo(t,k))continue;let b=!1;do{b=!1;try{Zf(y,{recursive:!1}),s=y,a=k;break}catch(P){if(qw(P,"EEXIST")){if(i&&f===0&&!l)try{ml(y,{recursive:!0,force:!0}),l=!0,b=!0}catch(I){throw new Error(`Failed to recreate existing worktree branch ${k}: could not clear blocked path ${y}: ${I instanceof Error?I.message:String(I)}`)}else if(i&&f===0)throw new Error(`Failed to recreate existing worktree branch ${k}: path ${y} remains blocked after one cleanup attempt`);continue}throw P}}while(b);if(s&&a)break}if(!s||!a)throw new Error(`Failed to create unique worktree directory and branch after ${d} attempts`);let u=lo(t,a);try{u?po("git",["-C",t,"worktree","add",s,a],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):po("git",["-C",t,"worktree","add","-b",a,s],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(f){try{ml(s,{recursive:!0,force:!0})}catch{}throw f}return s}function Gw(t){if(!Vw(t))return[];try{let e=po("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 nt(t,e,n={}){let r=n.destructive===!0,o=Gw(e);if(o.length>0&&!r)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${e}: ${o[0]}`),!1;try{return po("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 ml(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 Zi(t){try{po("git",["-C",t,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var eg=p(()=>{uo()});import{execFileSync as re}from"child_process";import{existsSync as jw}from"fs";function On(t,e,n){try{let r=re("git",["-C",t,"rev-list","--count",`${n}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(r.trim(),10),s=re("git",["-C",t,"diff","--shortstat",`${n}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,l=0,u=s.match(/(\d+)\s+files?\s+changed/);u&&(a=parseInt(u[1],10));let f=s.match(/(\d+)\s+insertions?\(/);f&&(d=parseInt(f[1],10));let g=s.match(/(\d+)\s+deletions?\(/);g&&(l=parseInt(g[1],10));let k=re("git",["-C",t,"diff","--name-only","--diff-filter=ACMR",`${n}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
6
6
  `).map(I=>I.trim()).filter(Boolean),P=re("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(I=>{let[A,C,N]=I.split("|");return{hash:A||"",message:C||"",author:N||""}});return{commits:o,filesChanged:a,insertions:d,deletions:l,changedFiles:k,commitMessages:P}}catch(r){console.warn(`[worktree] Failed to get diff summary: ${r instanceof Error?r.message:String(r)}`);return}}function es(t,e,n="origin"){try{return re("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 cr(t){try{return re("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 ts(t,e,n,r="merge",o){let i=!1,s,a=d=>{if(i)try{re("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(r==="squash"){if(re("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),cr(t)){let S;try{S=re("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(y){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${y instanceof Error?y.message:String(y)}. Commit or stash changes manually, then retry.`}}if(!S.includes("No local changes to save")){i=!0;try{s=re("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}re("git",["-C",t,"merge","--squash",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),re("git",["-C",t,"commit","-m",`Squash merge ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let f=!1;if(i)try{re("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&&jw(o),l=d?o:t;if(d||re("git",["-C",t,"checkout",e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),cr(t)){let f;try{f=re("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(S){try{re("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${S instanceof Error?S.message:String(S)}. Commit or stash changes manually, then retry.`}}if(!f.includes("No local changes to save")){i=!0;try{s=re("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{re("git",["-C",l,"rebase",n],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{re("git",["-C",l,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{re("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
- `)}}re("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),re("git",["-C",t,"merge","--ff-only",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let u=!1;if(i)try{re("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{u=!0}return{success:!0,fastForward:!0,stashed:i||void 0,stashRef:s,stashPopConflict:u||void 0}}catch(d){try{re("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 gl=p(()=>{});import{execFileSync as ns}from"child_process";function ng(t,e,n,r,o,i){if(!dn())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s;if(i)try{let f=ns("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:ns("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 po(t,e,n){if(!dn())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=ns("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 rg(t,e,n,r){if(!dn())return!1;try{let o=["pr","comment",String(e),"--body",n];return r&&o.push("--repo",r),ns("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 $n(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 hl=p(()=>{lo()});import{existsSync as Sl}from"fs";function og(){return new Date().toISOString()}function Hw(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:og(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function zw(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(Sl(t.workdir)?ln(t.workdir):void 0)}function co(t,e={}){let n=Hw(t),r=og(),o=new Set,i=Sl(t.workdir),s=!!(t.worktreePath&&Sl(t.worktreePath)),a=t.worktreeBranch,d=zw(t),l=!1,u=!1,f=!1,S=!1,y,k,b=t.worktreePrUrl?"open":"none",P=t.worktreePrUrl,I=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=ao(t.workdir,a),l||o.add("branch_missing")),s&&t.worktreePath&&(u=cr(t.worktreePath),u&&o.add("dirty_tracked_changes")),i&&l&&d){let it=Jf(t.workdir,a,d);y=it?.ahead,k=it?.behind,f=Yf(t.workdir,a,d),f?o.add("topology_merged"):(S=Xf(t.workdir,a,d),S&&o.add("merge_noop_content_already_on_base"),!S&&(y??0)>0&&o.add("unique_content"))}else d||o.add("base_branch_missing");if(e.includePrSync&&i&&a){let it=po(t.workdir,a,t.worktreePrTargetRepo??n.targetRepo);b=it.state,P=it.url??P,I=it.number??I}b==="open"&&o.add("pr_open"),b==="merged"&&!f&&!S&&o.add("pr_merged_not_reflected_locally");let A=n.state;f?A="merged":S?A="released":!l&&n.state==="pending_decision"&&(A="cleanup_failed");let C=e.activeSession||u||n.state==="pending_decision"||n.state==="merge_conflict_resolving"||n.state==="pr_open"||b==="open"||o.has("pr_merged_not_reflected_locally"),N=!C&&(A==="merged"||A==="released"||n.state==="dismissed"||n.state==="no_change"),xe={checkedAt:r,repoExists:i,branchExists:l,worktreeExists:s,activeSession:e.activeSession===!0,dirtyTracked:u,topologyMerged:f,releaseNoopMerge:S,branchAheadCount:y,baseAheadCount:k,prState:b,prUrl:P,prNumber:I,reasons:[...o]};return{lifecycle:n,evidence:xe,derivedState:A,cleanupSafe:N,preserve:C,reasons:[...o]}}var rs=p(()=>{lo();hl();gl()});var rt=p(()=>{lo();tg();gl();hl();rs()});function mr(t,e){let n=t.resolve(e),r=t.getPersistedSession(e),o=n?ne(n):r?ne(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 Pg(t){return t.persistedSession?tt(t.persistedSession):[]}function CI(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 cs(t,e,n={}){let{activeSession:r,persistedSession:o}=CI(t,e),i=co({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 ms(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=M(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:M(o),harnessSessionId:o.harnessSessionId});return Array.from(r.values())}function fs(t,e){return t.id===e||t.name===e||t.backendConversationId===e||t.harnessSessionId===e}function Nn(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 gs(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 fo=p(()=>{he();rs()});var wg={};bo(wg,{makeAgentPrTool:()=>go});import{existsSync as _I}from"fs";function EI(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function go(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(!EI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!dn())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=mr(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"}};_I(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${l}" via originalWorkdir (${a})`);let u=n.base_branch??ln(a),f=r.persistedRef,S=Zf(a,n.target_repo??i?.worktreePrTargetRepo);if(!es(a,l))return{content:[{type:"text",text:`\u274C Failed to push ${l} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let y=po(a,l,S);if(n.force_new&&y.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${l} (${y.state}).
7
+ `).filter(Boolean).map(I=>{let[A,C,N]=I.split("|");return{hash:A||"",message:C||"",author:N||""}});return{commits:o,filesChanged:a,insertions:d,deletions:l,changedFiles:k,commitMessages:P}}catch(r){console.warn(`[worktree] Failed to get diff summary: ${r instanceof Error?r.message:String(r)}`);return}}function es(t,e,n="origin"){try{return re("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 mr(t){try{return re("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 ts(t,e,n,r="merge",o){let i=!1,s,a=d=>{if(i)try{re("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(r==="squash"){if(re("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),mr(t)){let g;try{g=re("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(y){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${y instanceof Error?y.message:String(y)}. Commit or stash changes manually, then retry.`}}if(!g.includes("No local changes to save")){i=!0;try{s=re("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}re("git",["-C",t,"merge","--squash",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),re("git",["-C",t,"commit","-m",`Squash merge ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let f=!1;if(i)try{re("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&&jw(o),l=d?o:t;if(d||re("git",["-C",t,"checkout",e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),mr(t)){let f;try{f=re("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(g){try{re("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${g instanceof Error?g.message:String(g)}. Commit or stash changes manually, then retry.`}}if(!f.includes("No local changes to save")){i=!0;try{s=re("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{re("git",["-C",l,"rebase",n],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{re("git",["-C",l,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{re("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
+ `)}}re("git",["-C",t,"checkout",n],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),re("git",["-C",t,"merge","--ff-only",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let u=!1;if(i)try{re("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{u=!0}return{success:!0,fastForward:!0,stashed:i||void 0,stashRef:s,stashPopConflict:u||void 0}}catch(d){try{re("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 gl=p(()=>{});import{execFileSync as ns}from"child_process";function tg(t,e,n,r,o,i){if(!dn())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s;if(i)try{let f=ns("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:ns("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 co(t,e,n){if(!dn())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=ns("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 ng(t,e,n,r){if(!dn())return!1;try{let o=["pr","comment",String(e),"--body",n];return r&&o.push("--repo",r),ns("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 $n(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 hl=p(()=>{uo()});import{existsSync as Sl}from"fs";function rg(){return new Date().toISOString()}function Hw(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:rg(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function zw(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(Sl(t.workdir)?ln(t.workdir):void 0)}function mo(t,e={}){let n=Hw(t),r=rg(),o=new Set,i=Sl(t.workdir),s=!!(t.worktreePath&&Sl(t.worktreePath)),a=t.worktreeBranch,d=zw(t),l=!1,u=!1,f=!1,g=!1,y,k,b=t.worktreePrUrl?"open":"none",P=t.worktreePrUrl,I=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=lo(t.workdir,a),l||o.add("branch_missing")),s&&t.worktreePath&&(u=mr(t.worktreePath),u&&o.add("dirty_tracked_changes")),i&&l&&d){let it=Qf(t.workdir,a,d);y=it?.ahead,k=it?.behind,f=Jf(t.workdir,a,d),f?o.add("topology_merged"):(g=Yf(t.workdir,a,d),g&&o.add("merge_noop_content_already_on_base"),!g&&(y??0)>0&&o.add("unique_content"))}else d||o.add("base_branch_missing");if(e.includePrSync&&i&&a){let it=co(t.workdir,a,t.worktreePrTargetRepo??n.targetRepo);b=it.state,P=it.url??P,I=it.number??I}b==="open"&&o.add("pr_open"),b==="merged"&&!f&&!g&&o.add("pr_merged_not_reflected_locally");let A=n.state;f?A="merged":g?A="released":!l&&n.state==="pending_decision"&&(A="cleanup_failed");let C=e.activeSession||u||n.state==="pending_decision"||n.state==="merge_conflict_resolving"||n.state==="pr_open"||b==="open"||o.has("pr_merged_not_reflected_locally"),N=!C&&(A==="merged"||A==="released"||n.state==="dismissed"||n.state==="no_change"),xe={checkedAt:r,repoExists:i,branchExists:l,worktreeExists:s,activeSession:e.activeSession===!0,dirtyTracked:u,topologyMerged:f,releaseNoopMerge:g,branchAheadCount:y,baseAheadCount:k,prState:b,prUrl:P,prNumber:I,reasons:[...o]};return{lifecycle:n,evidence:xe,derivedState:A,cleanupSafe:N,preserve:C,reasons:[...o]}}var rs=p(()=>{uo();hl();gl()});var rt=p(()=>{uo();eg();gl();hl();rs()});function fr(t,e){let n=t.resolve(e),r=t.getPersistedSession(e),o=n?ne(n):r?ne(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 vg(t){return t.persistedSession?tt(t.persistedSession):[]}function CI(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 cs(t,e,n={}){let{activeSession:r,persistedSession:o}=CI(t,e),i=mo({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 ms(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=M(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:M(o),harnessSessionId:o.harnessSessionId});return Array.from(r.values())}function fs(t,e){return t.id===e||t.name===e||t.backendConversationId===e||t.harnessSessionId===e}function Nn(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 gs(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 go=p(()=>{he();rs()});var Pg={};xo(Pg,{makeAgentPrTool:()=>ho});import{existsSync as _I}from"fs";function EI(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ho(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(!EI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!dn())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=fr(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"}};_I(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${l}" via originalWorkdir (${a})`);let u=n.base_branch??ln(a),f=r.persistedRef,g=Xf(a,n.target_repo??i?.worktreePrTargetRepo);if(!es(a,l))return{content:[{type:"text",text:`\u274C Failed to push ${l} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let y=co(a,l,g);if(n.force_new&&y.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${l} (${y.state}).
10
10
 
11
11
  Existing PR: ${y.url}
12
12
 
13
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(y.exists&&y.state==="open"){let k=On(a,l,u);if(k&&k.commits>0){let b=k.commitMessages.slice(0,5).map(C=>`\u2022 ${C.hash} ${C.message} (${C.author})`).join(`
14
14
  `),P=k.commits>5?`
15
15
  ...and ${k.commits-5} more commits`:"",I=["\u{1F504} **New commits pushed**","",`${k.commits} new commits (+${k.insertions} / -${k.deletions})`,"","### Latest commits:",b+P,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
16
- `);if(rg(a,y.number,I,S)){f&&v.updatePersistedSession(f,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:u,targetRepo:S,pushRemote:i?.worktreePushRemote}});let C=$n({kind:"pr-updated",branch:l,prUrl:y.url});return v.notifyWorktreeOutcome(r.notificationTarget,C),{content:[{type:"text",text:`${C}
16
+ `);if(ng(a,y.number,I,g)){f&&v.updatePersistedSession(f,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:u,targetRepo:g,pushRemote:i?.worktreePushRemote}});let C=$n({kind:"pr-updated",branch:l,prUrl:y.url});return v.notifyWorktreeOutcome(r.notificationTarget,C),{content:[{type:"text",text:`${C}
17
17
 
18
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 ${y.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 f&&v.updatePersistedSession(f,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:u,targetRepo:S,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${y.url}
20
+ ${k.commits} new commits (+${k.insertions} / -${k.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return f&&v.updatePersistedSession(f,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:u,targetRepo:g,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${y.url}
21
21
 
22
- No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else{if(y.exists&&y.state==="merged")return f&&v.updatePersistedSession(f,{worktreePrUrl:y.url,worktreePrNumber:y.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:u,targetRepo:S,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2705 PR was already merged: ${y.url}
22
+ No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else{if(y.exists&&y.state==="merged")return f&&v.updatePersistedSession(f,{worktreePrUrl:y.url,worktreePrNumber:y.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:u,targetRepo:g,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2705 PR was already merged: ${y.url}
23
23
 
24
24
  The worktree branch ${l} can be cleaned up with agent_merge(delete_branch=true).`}],meta:{success:!0,state:"merged"}};if(y.exists&&y.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${y.url}
25
25
 
@@ -32,76 +32,76 @@ What would you like to do?
32
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}`,b=n.body;if(!b){let I=On(a,l,u);if(I){let A=I.commitMessages.slice(0,5).map(N=>`\u2022 ${N.hash} ${N.message} (${N.author})`).join(`
33
33
  `),C=I.commits>5?`
34
34
  ...and ${I.commits-5} more`:"";b=[`Automated changes from OpenClaw Code Agent session: ${d}`,"","## Summary",`${I.commits} commits, ${I.filesChanged} files changed (+${I.insertions} / -${I.deletions})`,"","## Commits",A+C,"","---","\u{1F916} Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
35
- `)}else b=`Automated changes from OpenClaw Code Agent session: ${d}`}let P=ng(a,l,u,k,b,S);if(P.success&&P.prUrl){let I=po(a,l,S);f&&v.updatePersistedSession(f,{worktreePrUrl:P.prUrl,worktreePrNumber:I.number,lifecycle:"terminal",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeState:"pr_open",worktreeDisposition:"pr-opened",worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:u,targetRepo:S,pushRemote:i?.worktreePushRemote}});let A=$n({kind:"pr-opened",branch:l,targetRepo:S,prUrl:P.prUrl});return v.notifyWorktreeOutcome(r.notificationTarget,A),{content:[{type:"text",text:A}],meta:{success:!0,state:"created"}}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${P.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var Ss=p(()=>{De();Y();rt();fo()});import{readdirSync as pA,statSync as cA,rmSync as mA}from"fs";import{execFileSync as fA}from"child_process";import{join as Kh}from"path";De();Y();function bP(t){return t.length>80?`${t.slice(0,80)}...`:t}function xP(t){return t.worktreePath?!t.originalWorkdir||t.originalWorkdir===t.worktreePath?`${t.worktreePath} (worktree)`:`${t.worktreePath} (worktree of ${t.originalWorkdir})`:t.workdir}function AP(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: ${xP(t)}`,` Model: ${t.model??"default"}`,` Prompt: "${bP(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 hi(t,e){return AP({...t,sessionId:e.id,sessionName:e.name,model:e.model,reasoningEffort:e.reasoningEffort,worktreeStrategy:e.worktreeStrategy??"off",worktreePath:e.worktreePath,originalWorkdir:e.originalWorkdir})}Te();function sr(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}}he();function sl(t){return"id"in t?t.id:t.sessionId}function ro(t){return t.status==="completed"||t.killReason==="done"}function cw(t){return ro(t)&&t.backendRef?.kind==="codex-app-server"&&!!M(t)}function mw(t){return(t.killReason==="shutdown"||t.killReason==="startup-timeout")&&!M(t)}function oo(t){if(t.status==="running")return{kind:"direct",reason:"already_running"};let e=sl(t);if(ro(t)&&!cw(t))return{kind:"unavailable",reason:"completed",stableSessionId:e};let n=M(t);if(n){let r="harnessName"in t?void 0:t,{resumeSessionId:o,clearedPersistedCodexResume:i}=sr({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 mw(t)?{kind:"relaunch",stableSessionId:e}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:e}}Te();import{existsSync as Mf}from"fs";function Oi(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()))}he();function Rf(t){return t==null?void 0:String(t).trim()||void 0}function fw(t){return t.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function gw(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=fw(r?.[2]??"");if(o.startsWith("/")&&Mf(o))return o}}function Tf(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&&Rf(t.originThreadId)===Rf(e.originThreadId)}function Cf(t){return t.slice(0,3).map(e=>` - ${e.name} [${e.ref}] | status=${e.status}${e.lifecycle?` | lifecycle=${e.lifecycle}`:""}`).join(`
38
- `)}function hw(t,e){let n=[],r=[],o=new Set;for(let i of t.list?.("all")??[]){if(!Tf(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||!Tf(i,e))continue;let s=ne(i)??i.harnessSessionId,a=i.sessionId??M(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 $i(t,e,n){let r=t.workdir||gw(t.prompt)||e.workspaceDir||_.defaultWorkdir||process.cwd();if(!Mf(r))return{kind:"error",text:`Error: Working directory does not exist: ${r}`};let o=t.harness??Le(),i=or(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=ki(o);if(d&&d.length>0&&!Oi(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=vi(e),u=Jr(e,l||Yr(r)),f=e.sessionKey||void 0,S=tf(f)??Zd(e);if(!t.resume_session_id&&!t.force_new_session){let N=hw(n,{workdir:r,originSessionKey:f,originChannel:u,originThreadId:S});if(N.resumable.length>0||N.active.length>0){let xe=N.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",Cf(N.resumable),"","Resume the latest one with:",` agent_respond(session='${N.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${N.resumable[0].ref}', fork_session=true)`].join(`
39
- `):"",it=N.active.length>0?[N.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",Cf(N.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${N.active[0].ref}', message='<next instruction>')`].join(`
35
+ `)}else b=`Automated changes from OpenClaw Code Agent session: ${d}`}let P=tg(a,l,u,k,b,g);if(P.success&&P.prUrl){let I=co(a,l,g);f&&v.updatePersistedSession(f,{worktreePrUrl:P.prUrl,worktreePrNumber:I.number,lifecycle:"terminal",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeState:"pr_open",worktreeDisposition:"pr-opened",worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:u,targetRepo:g,pushRemote:i?.worktreePushRemote}});let A=$n({kind:"pr-opened",branch:l,targetRepo:g,prUrl:P.prUrl});return v.notifyWorktreeOutcome(r.notificationTarget,A),{content:[{type:"text",text:A}],meta:{success:!0,state:"created"}}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${P.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var Ss=p(()=>{De();Y();rt();go()});import{readdirSync as pA,statSync as cA,rmSync as mA}from"fs";import{execFileSync as fA}from"child_process";import{join as Kh}from"path";De();Y();function bP(t){return t.length>80?`${t.slice(0,80)}...`:t}function xP(t){return t.worktreePath?!t.originalWorkdir||t.originalWorkdir===t.worktreePath?`${t.worktreePath} (worktree)`:`${t.worktreePath} (worktree of ${t.originalWorkdir})`:t.workdir}function AP(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: ${xP(t)}`,` Model: ${t.model??"default"}`,` Prompt: "${bP(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 Si(t,e){return AP({...t,sessionId:e.id,sessionName:e.name,model:e.model,reasoningEffort:e.reasoningEffort,worktreeStrategy:e.worktreeStrategy??"off",worktreePath:e.worktreePath,originalWorkdir:e.originalWorkdir})}Te();function sr(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}}he();function sl(t){return"id"in t?t.id:t.sessionId}function oo(t){return t.status==="completed"||t.killReason==="done"}function cw(t){return oo(t)&&t.backendRef?.kind==="codex-app-server"&&!!M(t)}function mw(t){return(t.killReason==="shutdown"||t.killReason==="startup-timeout")&&!M(t)}function io(t){if(t.status==="running")return{kind:"direct",reason:"already_running"};let e=sl(t);if(oo(t)&&!cw(t))return{kind:"unavailable",reason:"completed",stableSessionId:e};let n=M(t);if(n){let r="harnessName"in t?void 0:t,{resumeSessionId:o,clearedPersistedCodexResume:i}=sr({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 mw(t)?{kind:"relaunch",stableSessionId:e}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:e}}Te();import{existsSync as Cf}from"fs";function $i(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()))}he();function Af(t){return t==null?void 0:String(t).trim()||void 0}function fw(t){return t.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function gw(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=fw(r?.[2]??"");if(o.startsWith("/")&&Cf(o))return o}}function Rf(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&&Af(t.originThreadId)===Af(e.originThreadId)}function Tf(t){return t.slice(0,3).map(e=>` - ${e.name} [${e.ref}] | status=${e.status}${e.lifecycle?` | lifecycle=${e.lifecycle}`:""}`).join(`
38
+ `)}function hw(t,e){let n=[],r=[],o=new Set;for(let i of t.list?.("all")??[]){if(!Rf(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||!Rf(i,e))continue;let s=ne(i)??i.harnessSessionId,a=i.sessionId??M(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 Di(t,e,n){let r=t.workdir||gw(t.prompt)||e.workspaceDir||_.defaultWorkdir||process.cwd();if(!Cf(r))return{kind:"error",text:`Error: Working directory does not exist: ${r}`};let o=t.harness??Le(),i=or(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=vi(o);if(d&&d.length>0&&!$i(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=Pi(e),u=Yr(e,l||Xr(r)),f=e.sessionKey||void 0,g=ef(f)??Zd(e);if(!t.resume_session_id&&!t.force_new_session){let N=hw(n,{workdir:r,originSessionKey:f,originChannel:u,originThreadId:g});if(N.resumable.length>0||N.active.length>0){let xe=N.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",Tf(N.resumable),"","Resume the latest one with:",` agent_respond(session='${N.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${N.resumable[0].ref}', fork_session=true)`].join(`
39
+ `):"",it=N.active.length>0?[N.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",Tf(N.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${N.active[0].ref}', message='<next instruction>')`].join(`
40
40
  `):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",xe,it,["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 y=t.resume_session_id,k=y?n.resolve?.(y):void 0,b=y?n.getPersistedSession?.(y):void 0;if(y){let N=n.resolveBackendConversationId?.(y)??n.resolveHarnessSessionId?.(y);if(!N)return{kind:"error",text:`Error: Could not resolve resume_session_id "${y}" to a session ID. Use agent_sessions to list available sessions.`};y=N}let{resumeSessionId:P,clearedPersistedCodexResume:I}=sr({requestedResumeSessionId:y,activeSession:k?{harnessSessionId:k.backendConversationId??k.harnessSessionId}:void 0,persistedSession:b?{harness:b.harness,backendRef:b.backendRef}:void 0}),A=t.permission_mode??_.permissionMode,C=t.plan_approval??_.planApproval;return{kind:"resolved",workdir:r,harness:o,resolvedModel:s,permissionMode:A,planApproval:C,originChannel:u,originThreadId:S,originSessionKey:f,route:ir(e,u,f),resumeSessionId:P,resolvedResumeId:y,clearedPersistedCodexResume:I,reasoningEffort:sn(o)}}he();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 Sw=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 Ef(t){let n=t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!Sw.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var _f={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 Of(t){let e=_f[t.phase]??_f[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=M(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 Di(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 Ni(t,e){let n=t.split(`
43
+ `)}}}let y=t.resume_session_id,k=y?n.resolve?.(y):void 0,b=y?n.getPersistedSession?.(y):void 0;if(y){let N=n.resolveBackendConversationId?.(y)??n.resolveHarnessSessionId?.(y);if(!N)return{kind:"error",text:`Error: Could not resolve resume_session_id "${y}" to a session ID. Use agent_sessions to list available sessions.`};y=N}let{resumeSessionId:P,clearedPersistedCodexResume:I}=sr({requestedResumeSessionId:y,activeSession:k?{harnessSessionId:k.backendConversationId??k.harnessSessionId}:void 0,persistedSession:b?{harness:b.harness,backendRef:b.backendRef}:void 0}),A=t.permission_mode??_.permissionMode,C=t.plan_approval??_.planApproval;return{kind:"resolved",workdir:r,harness:o,resolvedModel:s,permissionMode:A,planApproval:C,originChannel:u,originThreadId:g,originSessionKey:f,route:ir(e,u,f),resumeSessionId:P,resolvedResumeId:y,clearedPersistedCodexResume:I,reasoningEffort:sn(o)}}he();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 Sw=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 _f(t){let n=t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!Sw.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var Mf={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 Ef(t){let e=Mf[t.phase]??Mf[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=M(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 Ni(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 Fi(t,e){let n=t.split(`
46
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 $f(t,e){let n=t.split(`
47
+ `)}function Of(t,e){let n=t.split(`
48
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 io,so,lr=!1;function Df(t){try{return t?.config?.current?.()}catch{return}}function Fi(t,e){if(t&&typeof t=="object"){io=t,arguments.length>=2?(so=e,lr=!0):lr||(so=Df(io),lr=!0);return}io=void 0,so=void 0,lr=!1}function Li(){return io}function Nf(){return lr||(so=Df(io),lr=!0),so}var yw="openclaw-code-agent",kw=160,Wi={create(){},progress(){},finalize(){}};function Bi(t,e){let n=e instanceof Error?e.message:String(e);console.warn(`[SessionTaskLifecycle] ${t} failed: ${n}`)}function vw(t,e){if(e.applied===!1){let n=e.code?` (${e.code})`:"";console.warn(`[SessionTaskLifecycle] ${t} mutation was not applied${n}`)}}function Pw(t){let e=t.prompt.trim().replace(/\s+/g," ");return Ce(e||t.name,kw)}function ww(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 Iw(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 al(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 bw(t){return t.lifecycle==="awaiting_plan_decision"||t.lifecycle==="awaiting_user_input"||t.lifecycle==="awaiting_worktree_decision"||t.lifecycle==="suspended"}function dl(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 xw(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 Ff(t,e){if(e.applied)return e.flow;let n=e.current;return n?.flowId&&typeof n.revision=="number"?n:t}var ll=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:yw,goal:Pw(e),status:"running",notifyPolicy:"silent",currentStep:n,stateJson:dl(e,"created",n),createdAt:e.startedAt,updatedAt:r}),this.lastProgressKey=this.progressKey(e,n)}catch(o){Bi("create",o)}}progress(e){if(!this.flow||this.finalized)return;let n=ww(e);if(!n)return;let r=this.progressKey(e,n);if(r!==this.lastProgressKey)try{let o=dl(e,"progress",n),i=Date.now(),s=bw(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=Ff(this.flow,s),this.lastProgressKey=r}catch(o){Bi("progress",o)}}finalize(e){if(!this.flow||this.finalized)return;let n=Iw(e);if(!n)return;let r=n==="succeeded"?"Completed":n==="failed"?"Failed":al(e.status,e.killReason);try{let o=e.completedAt??Date.now(),i={...dl(e,"terminal",r),terminalStatus:n,terminalSummary:al(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:al(e.status,e.killReason),updatedAt:o,endedAt:o});vw("finalize",s),this.flow=Ff(this.flow,s),this.finalized=!0}catch(o){Bi("finalize",o)}}progressKey(e,n){return`${e.status}:${e.lifecycle}:${n}`}};function Ui(t){if(!t.sessionKey?.trim())return Wi;try{let e=Li()?.taskFlow?.fromToolContext;if(typeof e!="function")return Wi;let n=e(t);return xw(n)?new ll(n):Wi}catch(e){return Bi("resolve",e),Wi}}function Aw(t){return t instanceof Error?t.message:String(t)}function Lf(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function Rw(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function Tw(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function Wf(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/Open PR/Later/Discard 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(!Rw(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=$i(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:u,originSessionKey:f,route:S,resumeSessionId:y,resolvedResumeId:k,clearedPersistedCodexResume:b,reasoningEffort:P}=r,I=n.resume_session_id?v.resolve(n.resume_session_id)??v.getPersistedSession(n.resume_session_id):void 0,A=!n.fork_session&&I?oo(I):void 0;if(A?.kind==="direct")return{content:[{type:"text",text:`Session ${I.name} [${Lf(I,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(A?.kind==="unavailable")return{content:[{type:"text",text:`Resume unavailable for session ${I.name} [${Lf(I,n.resume_session_id)}] (${A.reason}). Use agent_launch(prompt='<new task>') for a fresh session or set fork_session=true to fork from prior context.`}]};let C=v.spawn({prompt:n.prompt,sessionIdOverride:n.fork_session?void 0:A?.kind==="resume"||A?.kind==="relaunch"?A.stableSessionId:void 0,name:n.name,workdir:o,model:s,reasoningEffort:P,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:A?.kind==="resume"?A.resumeSessionId:y,resumeWorktreeFrom:k,forkSession:y?n.fork_session:!1,multiTurn:!0,permissionMode:a,planApproval:d,codexApprovalPolicy:i==="codex"?"never":void 0,originChannel:l,originThreadId:u,originAgentId:t.agentId||void 0,originSessionKey:f,route:S,harness:i,taskLifecycle:Ui(t),worktreeStrategy:n.worktree_strategy,worktreeBaseBranch:n.worktree_base_branch,worktreePrTargetRepo:n.worktree_pr_target_repo});return{content:[{type:"text",text:Tw(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:b},C):hi({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:b},{id:C.id,name:C.name,model:C.model,reasoningEffort:C.reasoningEffort??sn(i),worktreeStrategy:C.worktreeStrategy??n.worktree_strategy??_.defaultWorktreeStrategy??"off",worktreePath:C.worktreePath,originalWorkdir:C.originalWorkdir})}]}}catch(r){let o=Aw(r),i=o.includes("Max sessions")?"":`
49
+ `)}var so,ao,lr=!1;function $f(t){try{return t?.config?.current?.()}catch{return}}function ur(t,e){if(t&&typeof t=="object"){so=t,arguments.length>=2?(ao=e,lr=!0):lr||(ao=$f(so),lr=!0);return}so=void 0,ao=void 0,lr=!1}function Li(){return so}function Df(){return lr||(ao=$f(so),lr=!0),ao}var yw="openclaw-code-agent",kw=160,Wi={create(){},progress(){},finalize(){}};function Bi(t,e){let n=e instanceof Error?e.message:String(e);console.warn(`[SessionTaskLifecycle] ${t} failed: ${n}`)}function vw(t,e){if(e.applied===!1){let n=e.code?` (${e.code})`:"";console.warn(`[SessionTaskLifecycle] ${t} mutation was not applied${n}`)}}function Pw(t){let e=t.prompt.trim().replace(/\s+/g," ");return Ce(e||t.name,kw)}function ww(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 Iw(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 al(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 bw(t){return t.lifecycle==="awaiting_plan_decision"||t.lifecycle==="awaiting_user_input"||t.lifecycle==="awaiting_worktree_decision"||t.lifecycle==="suspended"}function dl(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 xw(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 Nf(t,e){if(e.applied)return e.flow;let n=e.current;return n?.flowId&&typeof n.revision=="number"?n:t}var ll=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:yw,goal:Pw(e),status:"running",notifyPolicy:"silent",currentStep:n,stateJson:dl(e,"created",n),createdAt:e.startedAt,updatedAt:r}),this.lastProgressKey=this.progressKey(e,n)}catch(o){Bi("create",o)}}progress(e){if(!this.flow||this.finalized)return;let n=ww(e);if(!n)return;let r=this.progressKey(e,n);if(r!==this.lastProgressKey)try{let o=dl(e,"progress",n),i=Date.now(),s=bw(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=Nf(this.flow,s),this.lastProgressKey=r}catch(o){Bi("progress",o)}}finalize(e){if(!this.flow||this.finalized)return;let n=Iw(e);if(!n)return;let r=n==="succeeded"?"Completed":n==="failed"?"Failed":al(e.status,e.killReason);try{let o=e.completedAt??Date.now(),i={...dl(e,"terminal",r),terminalStatus:n,terminalSummary:al(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:al(e.status,e.killReason),updatedAt:o,endedAt:o});vw("finalize",s),this.flow=Nf(this.flow,s),this.finalized=!0}catch(o){Bi("finalize",o)}}progressKey(e,n){return`${e.status}:${e.lifecycle}:${n}`}};function Ui(t){if(!t.sessionKey?.trim())return Wi;try{let e=Li()?.taskFlow?.fromToolContext;if(typeof e!="function")return Wi;let n=e(t);return xw(n)?new ll(n):Wi}catch(e){return Bi("resolve",e),Wi}}function Aw(t){return t instanceof Error?t.message:String(t)}function Ff(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function Rw(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function Tw(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function Lf(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/Open PR/Later/Discard 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(!Rw(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=Di(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:u,originSessionKey:f,route:g,resumeSessionId:y,resolvedResumeId:k,clearedPersistedCodexResume:b,reasoningEffort:P}=r,I=n.resume_session_id?v.resolve(n.resume_session_id)??v.getPersistedSession(n.resume_session_id):void 0,A=!n.fork_session&&I?io(I):void 0;if(A?.kind==="direct")return{content:[{type:"text",text:`Session ${I.name} [${Ff(I,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(A?.kind==="unavailable")return{content:[{type:"text",text:`Resume unavailable for session ${I.name} [${Ff(I,n.resume_session_id)}] (${A.reason}). Use agent_launch(prompt='<new task>') for a fresh session or set fork_session=true to fork from prior context.`}]};let C=v.spawn({prompt:n.prompt,sessionIdOverride:n.fork_session?void 0:A?.kind==="resume"||A?.kind==="relaunch"?A.stableSessionId:void 0,name:n.name,workdir:o,model:s,reasoningEffort:P,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:A?.kind==="resume"?A.resumeSessionId:y,resumeWorktreeFrom:k,forkSession:y?n.fork_session:!1,multiTurn:!0,permissionMode:a,planApproval:d,codexApprovalPolicy:i==="codex"?"never":void 0,originChannel:l,originThreadId:u,originAgentId:t.agentId||void 0,originSessionKey:f,route:g,harness:i,taskLifecycle:Ui(t),worktreeStrategy:n.worktree_strategy,worktreeBaseBranch:n.worktree_base_branch,worktreePrTargetRepo:n.worktree_pr_target_repo});return{content:[{type:"text",text:Tw(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:b},C):Si({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:b},{id:C.id,name:C.name,model:C.model,reasoningEffort:C.reasoningEffort??sn(i),worktreeStrategy:C.worktreeStrategy??n.worktree_strategy??_.defaultWorktreeStrategy??"off",worktreePath:C.worktreePath,originalWorkdir:C.originalWorkdir})}]}}catch(r){let o=Aw(r),i=o.includes("Max sessions")?"":`
50
50
 
51
- Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}De();Y();Te();import{existsSync as yl,readFileSync as sg}from"fs";import{EventEmitter as Qw}from"events";import{webcrypto as Uf}from"node:crypto";var Bf="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Cw=128,En,ur;function Mw(t){if(t<0||t>1024)throw new RangeError("Wrong ID size");!En||En.length<t?(En=Buffer.allocUnsafe(t*Cw),Uf.getRandomValues(En),ur=0):ur+t>En.length&&(Uf.getRandomValues(En),ur=0),ur+=t}function Ki(t=21){Mw(t|=0);let e="";for(let n=ur-t;n<ur;n++)e+=Bf[En[n]&63];return e}rl();Te();he();var Kf={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},Vf=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function _w(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 Ne(t){return{...t,approvalExecutionState:_w(t)}}function ul(t,e){switch(e.type){case"initialize":return Ne({...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"?Ne({...t,status:e.status,lifecycle:"starting",runtimeState:"live"}):e.status==="running"?Ne({...t,status:e.status,lifecycle:t.lifecycle==="starting"||t.lifecycle==="suspended"?"active":t.lifecycle,runtimeState:"live"}):Ne({...t,status:e.status,runtimeState:"stopped",lifecycle:t.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return Ne({...t,currentPermissionMode:e.currentPermissionMode});case"turn.started":return Ne({...t,lifecycle:"active",runtimeState:"live"});case"input.requested":return Ne({...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 Ne({...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 Ne({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,approvalState:t.approvalState==="pending"?"not_required":t.approvalState});case"plan.approved":return Ne({...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 Ne({...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 Ne({...t,lifecycle:e.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return Ne({...t,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return Ne({...t,worktreeState:e.worktreeState,lifecycle:e.worktreeState==="pending_decision"?"awaiting_worktree_decision":Vf.has(e.worktreeState)?"terminal":t.lifecycle});case"delivery.state_set":return Ne({...t,deliveryState:e.deliveryState})}}function qf(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=ul(n,{type:"worktree.decision_requested"}):Vf.has(n.worktreeState)&&(n={...n,lifecycle:"terminal"}),Ne(n)}var Vi=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 Ew}from"fs";import{tmpdir as Ow}from"os";import{join as $w}from"path";var Gf=2e3;function pr(t){return $w(Ow(),`openclaw-agent-${t}.txt`)}function Dw(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 jf(t,e,n){Dw(t,n),t.length>Gf&&t.splice(0,t.length-Gf);try{Ew(pr(e),n,"utf-8")}catch{}return t}var qi=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 Gi=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 ji=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}};rt();var Jw=120*1e3;function os(t){return t instanceof Error?t.message:String(t)}var is=class extends Qw{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 qi;constructor(e,n){super(),this.id=e.sessionIdOverride??Ki(8),this.name=n,this.harness=e.harness?no(e.harness):xf(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??or(this.harness.name),this.reasoningEffort=e.reasoningEffort??sn(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 Gi({appendOutput:r=>jf(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 ji({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??=Xi(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 M(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(!Kf[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 Vi,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:Ym(),canUseTool:this.canUseTool});this.harnessHandle=n,this.setTimer("startup",Jw,()=>{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: ${os(s)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${r}: ${os(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.]
51
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}De();Y();Te();import{existsSync as yl,readFileSync as ig}from"fs";import{EventEmitter as Qw}from"events";import{webcrypto as Bf}from"node:crypto";var Wf="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Cw=128,En,pr;function Mw(t){if(t<0||t>1024)throw new RangeError("Wrong ID size");!En||En.length<t?(En=Buffer.allocUnsafe(t*Cw),Bf.getRandomValues(En),pr=0):pr+t>En.length&&(Bf.getRandomValues(En),pr=0),pr+=t}function Ki(t=21){Mw(t|=0);let e="";for(let n=pr-t;n<pr;n++)e+=Wf[En[n]&63];return e}rl();Te();he();var Uf={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},Kf=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function _w(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 Ne(t){return{...t,approvalExecutionState:_w(t)}}function ul(t,e){switch(e.type){case"initialize":return Ne({...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"?Ne({...t,status:e.status,lifecycle:"starting",runtimeState:"live"}):e.status==="running"?Ne({...t,status:e.status,lifecycle:t.lifecycle==="starting"||t.lifecycle==="suspended"?"active":t.lifecycle,runtimeState:"live"}):Ne({...t,status:e.status,runtimeState:"stopped",lifecycle:t.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return Ne({...t,currentPermissionMode:e.currentPermissionMode});case"turn.started":return Ne({...t,lifecycle:"active",runtimeState:"live"});case"input.requested":return Ne({...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 Ne({...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 Ne({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,approvalState:t.approvalState==="pending"?"not_required":t.approvalState});case"plan.approved":return Ne({...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 Ne({...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 Ne({...t,lifecycle:e.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return Ne({...t,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return Ne({...t,worktreeState:e.worktreeState,lifecycle:e.worktreeState==="pending_decision"?"awaiting_worktree_decision":Kf.has(e.worktreeState)?"terminal":t.lifecycle});case"delivery.state_set":return Ne({...t,deliveryState:e.deliveryState})}}function Vf(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=ul(n,{type:"worktree.decision_requested"}):Kf.has(n.worktreeState)&&(n={...n,lifecycle:"terminal"}),Ne(n)}var Vi=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 Ew}from"fs";import{tmpdir as Ow}from"os";import{join as $w}from"path";var qf=2e3;function cr(t){return $w(Ow(),`openclaw-agent-${t}.txt`)}function Dw(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 Gf(t,e,n){Dw(t,n),t.length>qf&&t.splice(0,t.length-qf);try{Ew(cr(e),n,"utf-8")}catch{}return t}var qi=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 Gi=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 ji=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}};rt();var Jw=120*1e3;function os(t){return t instanceof Error?t.message:String(t)}var is=class extends Qw{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 qi;constructor(e,n){super(),this.id=e.sessionIdOverride??Ki(8),this.name=n,this.harness=e.harness?ro(e.harness):bf(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??or(this.harness.name),this.reasoningEffort=e.reasoningEffort??sn(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 Gi({appendOutput:r=>Gf(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 ji({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??=Xi(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 M(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(!Uf[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 Vi,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:Jm(),canUseTool:this.canUseTool});this.harnessHandle=n,this.setTimer("startup",Jw,()=>{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: ${os(s)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${r}: ${os(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
54
 
55
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
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: ${os(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: ${os(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=ul(this.controlStateSnapshot(),e);this.applyControlState(n)}applyControlPatch(e){let n=qf(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 Yw=50,Xw=1,Zw=new Set(["starting","running","completed","failed","killed"]),eI=5,tI=1440*60*1e3;function nI(t){let e=Number(t);return!Number.isFinite(e)||e<Xw?Yw:Math.floor(e)}function rI(t){return typeof t=="string"&&Zw.has(t)}function oI(t){let e=t.split(`
58
- `);return e.at(-1)===""&&e.pop(),e}function kl(t){return t.backendRef?.conversationId??t.harnessSessionId}function ag(t,e,n){let r=sg(t,"utf-8"),o=oI(r);return e.full?o:o.slice(-n)}function iI(t,e,n){if(t.status!=="starting"&&t.status!=="running")return null;let r=pr(t.id);if(!yl(r))return null;try{return ag(r,e,n)}catch{return null}}function sI(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 dg(t,e){let n=t.name||t.sessionId||kl(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 aI(t){return`(retrieved from ${t.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`}function dI(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 ig(t,e){let n=dg(t,dI(t)),r=kl(t),o=r?`
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: ${os(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: ${os(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=ul(this.controlStateSnapshot(),e);this.applyControlState(n)}applyControlPatch(e){let n=Vf(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 Yw=50,Xw=1,Zw=new Set(["starting","running","completed","failed","killed"]),eI=5,tI=1440*60*1e3;function nI(t){let e=Number(t);return!Number.isFinite(e)||e<Xw?Yw:Math.floor(e)}function rI(t){return typeof t=="string"&&Zw.has(t)}function oI(t){let e=t.split(`
58
+ `);return e.at(-1)===""&&e.pop(),e}function kl(t){return t.backendRef?.conversationId??t.harnessSessionId}function sg(t,e,n){let r=ig(t,"utf-8"),o=oI(r);return e.full?o:o.slice(-n)}function iI(t,e,n){if(t.status!=="starting"&&t.status!=="running")return null;let r=cr(t.id);if(!yl(r))return null;try{return sg(r,e,n)}catch{return null}}function sI(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 ag(t,e){let n=t.name||t.sessionId||kl(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 aI(t){return`(retrieved from ${t.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`}function dI(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 og(t,e){let n=ag(t,dI(t)),r=kl(t),o=r?`
61
61
  Backend session: ${r}`:"";return`${n}
62
62
  (no persisted output available: ${e})${o}`}function lI(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?`
63
63
  (no output yet)
64
64
  ${e.join(`
65
65
  `)}`:`
66
- (no output yet)`}function ss(t,e,n={}){let r=nI(n.lines),o=t.resolve(e);if(!o){let l=t.getPersistedSession(e);if(l?.outputPath&&yl(l.outputPath))try{let u=ag(l.outputPath,n,r).join(`
67
- `),f=dg(l,aI(l));return u?`${f}
66
+ (no output yet)`}function ss(t,e,n={}){let r=nI(n.lines),o=t.resolve(e);if(!o){let l=t.getPersistedSession(e);if(l?.outputPath&&yl(l.outputPath))try{let u=sg(l.outputPath,n,r).join(`
67
+ `),f=ag(l,aI(l));return u?`${f}
68
68
  ${u}`:`${f}
69
- (output file was empty)`}catch(u){let f=u instanceof Error?u.message:String(u);return`Error: Session "${e}" was cleaned up (expired) and output file could not be read: ${f}`}return l?.outputPath?ig(l,`output file is missing at ${l.outputPath}`):l?ig(l,"no outputPath is stored for this recovered session"):`Error: Session "${e}" not found.`}let i=iI(o,n,r),s=i&&i.length>0?i:n.full?o.getOutput():o.getOutput(r),a=sI(o),d=s.length===0?`${a}${lI(o)}`:`${a}
69
+ (output file was empty)`}catch(u){let f=u instanceof Error?u.message:String(u);return`Error: Session "${e}" was cleaned up (expired) and output file could not be read: ${f}`}return l?.outputPath?og(l,`output file is missing at ${l.outputPath}`):l?og(l,"no outputPath is stored for this recovered session"):`Error: Session "${e}" not found.`}let i=iI(o,n,r),s=i&&i.length>0?i:n.full?o.getOutput():o.getOutput(r),a=sI(o),d=s.length===0?`${a}${lI(o)}`:`${a}
70
70
  ${s.join(`
71
- `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(yl(o.planFilePath)){let l=sg(o.planFilePath,"utf-8"),u="\u2500".repeat(60);return`${d}
71
+ `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(yl(o.planFilePath)){let l=ig(o.planFilePath,"utf-8"),u="\u2500".repeat(60);return`${d}
72
72
  ${u}
73
73
  Plan file: ${o.planFilePath}
74
74
  ${u}
75
- ${l}`}}catch{}return d}function as(t,e="all",n,r={}){let o=t.listPersistedSessions()??[],s=uI(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()-tI;s=s.filter(d=>(d.startedAt??0)>=a)}else s=s.slice(0,eI);return s.length===0?"No sessions found.":s.map(a=>Of(a)).join(`
75
+ ${l}`}}catch{}return d}function as(t,e="all",n,r={}){let o=t.listPersistedSessions()??[],s=uI(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()-tI;s=s.filter(d=>(d.startedAt??0)>=a)}else s=s.slice(0,eI);return s.length===0?"No sessions found.":s.map(a=>Ef(a)).join(`
76
76
 
77
- `)}function uI(t,e){let n=new Map;for(let r of e){if(!rI(r.status))continue;let o=r.completedAt??Date.now(),i=r.createdAt??o,s=kl(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 pI(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 lg(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=pI(n),o=t?.workspaceDir?Yr(t.workspaceDir):void 0,i=!!(n&&typeof n=="object"&&n.full===!0);return{content:[{type:"text",text:as(v,r,o,{full:i})}]}}}}De();Y();function ds(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 cI(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 ug(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?cI(n)?{content:[{type:"text",text:ds(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();Y();function mI(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ls(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?mI(n)?{content:[{type:"text",text:ss(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();Y();Te();he();var fI=10;function Pl(t){return t instanceof Error?t.message:String(t)}function Dn(t){return ne(t)??t.harnessSessionId??"unknown-session"}function pg(t){return t.status!=="running"&&!!t.pendingPlanApproval&&!!M(t)}function gI(t){let e=t.trim().toLowerCase().replace(/[.!?]+$/g,"").trim();if(e==="approve"||e==="approved")return"approve";if(e==="revise"||e==="request changes"||e==="changes requested")return"revise";if(e==="reject"||e==="rejected")return"reject"}function mo(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='${Dn(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='${Dn(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='${Dn(t)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${Dn(t)}', message='<next instruction>') to continue the running session.`,o=n?` ${n}`:"";return{text:`Resume unavailable for session ${t.name} [${Dn(t)}] (${e}).${o} ${r}`,isError:!0}}async function cg(t,e,n){try{let r={prompt:e.prompt,sessionIdOverride:sl(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} [${Dn(e)}]: ${Pl(r)}`,isError:!0}}}var hI=`[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 uI(t,e){let n=new Map;for(let r of e){if(!rI(r.status))continue;let o=r.completedAt??Date.now(),i=r.createdAt??o,s=kl(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 pI(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 dg(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=pI(n),o=t?.workspaceDir?Xr(t.workspaceDir):void 0,i=!!(n&&typeof n=="object"&&n.full===!0);return{content:[{type:"text",text:as(v,r,o,{full:i})}]}}}}De();Y();function ds(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 cI(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 lg(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?cI(n)?{content:[{type:"text",text:ds(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();Y();function mI(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ls(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?mI(n)?{content:[{type:"text",text:ss(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();Y();Te();he();var fI=10;function Pl(t){return t instanceof Error?t.message:String(t)}function Dn(t){return ne(t)??t.harnessSessionId??"unknown-session"}function ug(t){return t.status!=="running"&&!!t.pendingPlanApproval&&!!M(t)}function gI(t){let e=t.trim().toLowerCase().replace(/[.!?]+$/g,"").trim();if(e==="approve"||e==="approved")return"approve";if(e==="revise"||e==="request changes"||e==="changes requested")return"revise";if(e==="reject"||e==="rejected")return"reject"}function fo(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='${Dn(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='${Dn(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='${Dn(t)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${Dn(t)}', message='<next instruction>') to continue the running session.`,o=n?` ${n}`:"";return{text:`Resume unavailable for session ${t.name} [${Dn(t)}] (${e}).${o} ${r}`,isError:!0}}async function pg(t,e,n){try{let r={prompt:e.prompt,sessionIdOverride:sl(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} [${Dn(e)}]: ${Pl(r)}`,isError:!0}}}var hI=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
78
78
 
79
- `;function mg(t){let e=t?.replace(/\s+/g," ").trim();if(e)return Ce(e,240)}function vl(t){if(t.approvalState==="changes_requested"&&!us(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 us(t){return t.pendingPlanApproval?(t.approvalState==="changes_requested"?t.actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion)>0:!1}function SI(t){return vl(t)?!1:us(t)||t.currentPermissionMode==="plan"}function yI(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})}function kI(t){return(t.planDecisionVersion??0)+1}function fg(t,e){let n={approvalState:e,lifecycle:e==="rejected"?"terminal":"awaiting_user_input",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:kI(t),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};return e==="rejected"&&(n.runtimeState="stopped"),n}function gg(t,e){let n=t;typeof n.applyControlPatch=="function"&&n.applyControlPatch(e),Object.assign(t,e)}function wl(t,e){let n=t.resolve(e),r=n?void 0:t.getPersistedSession(e),o=n??r,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),!o)return{text:`Plan rejected for [${i}].`,isError:!1};let s=fg(o,"rejected");return n?(gg(n,s),t.updatePersistedSession?.(e,s),t.kill(n.id,"user"),{text:`Plan rejected for [${n.name}]. Session stopped.`}):(t.updatePersistedSession?.(e,s),{text:`Plan rejected for [${i}]. Session remains stopped.`})}function Il(t,e){let n=t.resolve(e),r=n?void 0:t.getPersistedSession(e),o=n??r,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),o){let s=fg(o,"changes_requested");n&&gg(n,s),t.updatePersistedSession?.(e,s)}return{text:`Type your revision feedback for [${i}] and I'll forward it to the agent.`}}async function vI(t,e,n,r={}){let o=oo(e);if(!(o.kind==="resume"||pg(e)))return;let s=!!(r.approve&&SI(e)),a=s?mg(r.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?cg(t,e,n):mo(e,o.reason);let d={prompt:s?hI+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 mo(e,"missing_backend_state",`Backend resume failed: ${Pl(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"}:oo(o),s=!e.approve&&o.lifecycle==="awaiting_plan_decision"&&o.pendingPlanApproval&&e.userInitiated?gI(e.message):void 0;if(s==="approve")return mt(t,{...e,message:"Approved. Go ahead.",approve:!0});if(s==="revise")return Il(t,n?.id??r?.sessionId??e.session);if(s==="reject")return wl(t,n?.id??r?.sessionId??e.session);if(e.approve){let d=vl(o);if(d)return{text:d,isError:!0}}if(i.kind==="resume"||pg(o)){let d=await vI(t,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(d)return d}else{if(i.kind==="relaunch")return cg(t,o,e.message);if(i.kind==="unavailable")return mo(o,i.reason)}if(!n)return ro(r)?mo(r,"completed"):{text:`Error: Session ${r.name} [${Dn(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return ro(n)?mo(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 a=_.maxAutoResponds??fI;if(e.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=a)return{text:`\u26A0\uFE0F Auto-respond limit reached (${n.autoRespondCount}/${a}). 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 k=vl(n);if(k)return{text:k,isError:!0}}if(!e.approve&&n.pendingInputState?.allowsFreeText&&await n.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let b=Ce(e.message,100);t.notifySession(n,`\u21AA\uFE0F [${n.name}] "${b}"`,"agent-respond")}e.userInitiated||n.incrementAutoRespond();let k=Ce(e.message,80);return{text:[`Pending input answered for session ${n.name} [${n.id}].`,` Message: "${k}"`,"Use agent_output to see the response."].join(`
80
- `)}}let l=!1;e.interrupt&&(l=await n.interrupt());let u=!!(e.approve&&us(n)),f=u?mg(e.approvalRationale):void 0,S="";if(e.approve&&us(n)?(n.switchPermissionMode("bypassPermissions"),n.approvalRationale=f):e.approve&&n.currentPermissionMode==="default"?n.switchPermissionMode("bypassPermissions"):e.approve&&n.currentPermissionMode==="bypassPermissions"?S=`
81
- \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:e.approve?S=`
82
- \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:(n.pendingPlanApproval||n.approvalState==="changes_requested")&&(S=`
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),u&&yI(t,n),u)t.notifySession(n,`\u{1F44D} [${n.name}] Plan approved`,"plan-approved");else if(e.userInitiated){let k=Ce(e.message,100);t.notifySession(n,`\u21AA\uFE0F [${n.name}] "${k}"`,"agent-respond")}e.userInitiated||n.incrementAutoRespond();let y=Ce(e.message,80);return u?{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}].`,l?" (redirected active turn first)":e.interrupt?" (no active turn to interrupt)":"",` Message: "${y}"`,S,"Use agent_output to see the response."].filter(Boolean).join(`
84
- `)}}catch(d){return{text:`Error sending message to session ${n.name} [${n.id}]: ${Pl(d)}`,isError:!0}}}function PI(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 hg(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(!PI(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();Y();function wI(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function Sg(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(!wI(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();Y();Te();var bl=["off","manual","ask","delegate","auto-merge","auto-pr"],ps=new Set(bl),II=["low","medium","high","xhigh","max"],yg=new Set(II);function bI(t){return typeof t=="string"&&ps.has(t)}var xI=c.Union(bl.map(t=>c.Literal(t)),{description:"Optional worktree strategy for the planning session. Use auto-pr when the follow-up should branch and open/update a PR after approved implementation."});function AI(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.offer_id=="string"&&typeof e.offer_text=="string"&&typeof e.plan_prompt=="string"&&typeof e.plan_workdir=="string"&&(e.plan_worktree_strategy==null||bI(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 RI(t,e){let n=ir(t,e.target_channel,e.target_session_key);if(n)return e.target_thread_id!=null&&(n.threadId=String(e.target_thread_id)),n}async function TI(t,e){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=RI(t,e);return!n?.provider||!n.target?{content:[{type:"text",text:"Error: Could not resolve a direct delivery route for the plan offer."}]}:(v.sendPlanOffer({offerId:e.offer_id,route:n,text:e.offer_text,planName:e.plan_name??e.offer_id,planPrompt:e.plan_prompt,planWorkdir:e.plan_workdir,planWorktreeStrategy:e.plan_worktree_strategy}),{content:[{type:"text",text:`Interactive plan offer queued for ${n.provider}|${n.target}${n.threadId?`#${n.threadId}`:""}.`}]})}function kg(t){return{name:"agent_send_plan_offer",description:"Post a user-facing message to the current or explicit chat route with human-gated Start Plan and Dismiss inline buttons. Use this when an external workflow wants the user to open a plan-only code-agent session from the message.",parameters:c.Object({offer_id:c.String({description:"Stable offer identifier, for example 'plugin-readiness-v2026.5.5'."}),offer_text:c.String({description:"Final user-facing 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(xI),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){return AI(n)?TI(t,n):{content:[{type:"text",text:"Error: Invalid parameters. Expected { offer_id, offer_text, plan_prompt, plan_workdir }."}]}}}}De();Y();function vg(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:Di(r,o)}]}}}}De();Te();Y();rt();fo();import{existsSync as xl}from"fs";function MI(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function hs(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(!MI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let r=mr(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.`}]};xl(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${a})`);let l=a;if(!xl(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let u=n.base_branch??ln(l),f=u,S=n.strategy??"merge",y=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 b={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]},P=r.persistedRef;return await v.enqueueMerge(l,async()=>{let I=v.getPersistedSession(n.session);if(I?.worktreeLifecycle?.state==="merged"||I?.worktreeMerged){b={content:[{type:"text",text:`\u2139\uFE0F Session "${n.session}" was already merged while waiting in queue.`}]};return}let A=On(l,d,u),C=ts(l,d,f,S,s);if(C.success){if(y&&!es(l,f)){b={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${f} locally, but failed to push ${f}`}]};return}k&&Dt(l,d);let N=!1;if(xl(s)&&(N=nt(l,s),Zi(l)),I)for(let $ of Pg({...r,persistedSession:I}))v.updatePersistedSession($,{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:u,targetRepo:I.worktreePrTargetRepo,pushRemote:I.worktreePushRemote}});let xe=$n({kind:"merge",branch:d,base:u,filesChanged:A?.filesChanged,insertions:A?.insertions,deletions:A?.deletions});v.notifyWorktreeOutcome(r.notificationTarget,xe);let O=`\u2705 ${C.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${f}.${y?" Pushed.":""}${k?N?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;C.stashPopConflict?O+=`
79
+ `;function cg(t){let e=t?.replace(/\s+/g," ").trim();if(e)return Ce(e,240)}function vl(t){if(t.approvalState==="changes_requested"&&!us(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 us(t){return t.pendingPlanApproval?(t.approvalState==="changes_requested"?t.actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion)>0:!1}function SI(t){return vl(t)?!1:us(t)||t.currentPermissionMode==="plan"}function yI(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})}function kI(t){return(t.planDecisionVersion??0)+1}function mg(t,e){let n={approvalState:e,lifecycle:e==="rejected"?"terminal":"awaiting_user_input",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:kI(t),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};return e==="rejected"&&(n.runtimeState="stopped"),n}function fg(t,e){let n=t;typeof n.applyControlPatch=="function"&&n.applyControlPatch(e),Object.assign(t,e)}function wl(t,e){let n=t.resolve(e),r=n?void 0:t.getPersistedSession(e),o=n??r,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),!o)return{text:`Plan rejected for [${i}].`,isError:!1};let s=mg(o,"rejected");return n?(fg(n,s),t.updatePersistedSession?.(e,s),t.kill(n.id,"user"),{text:`Plan rejected for [${n.name}]. Session stopped.`}):(t.updatePersistedSession?.(e,s),{text:`Plan rejected for [${i}]. Session remains stopped.`})}function Il(t,e){let n=t.resolve(e),r=n?void 0:t.getPersistedSession(e),o=n??r,i=o?.name??e;if(t.clearPlanDecisionTokens?.(e),o){let s=mg(o,"changes_requested");n&&fg(n,s),t.updatePersistedSession?.(e,s)}return{text:`Type your revision feedback for [${i}] and I'll forward it to the agent.`}}async function vI(t,e,n,r={}){let o=io(e);if(!(o.kind==="resume"||ug(e)))return;let s=!!(r.approve&&SI(e)),a=s?cg(r.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?pg(t,e,n):fo(e,o.reason);let d={prompt:s?hI+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 fo(e,"missing_backend_state",`Backend resume failed: ${Pl(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"}:io(o),s=!e.approve&&o.lifecycle==="awaiting_plan_decision"&&o.pendingPlanApproval&&e.userInitiated?gI(e.message):void 0;if(s==="approve")return mt(t,{...e,message:"Approved. Go ahead.",approve:!0});if(s==="revise")return Il(t,n?.id??r?.sessionId??e.session);if(s==="reject")return wl(t,n?.id??r?.sessionId??e.session);if(e.approve){let d=vl(o);if(d)return{text:d,isError:!0}}if(i.kind==="resume"||ug(o)){let d=await vI(t,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(d)return d}else{if(i.kind==="relaunch")return pg(t,o,e.message);if(i.kind==="unavailable")return fo(o,i.reason)}if(!n)return oo(r)?fo(r,"completed"):{text:`Error: Session ${r.name} [${Dn(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return oo(n)?fo(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 a=_.maxAutoResponds??fI;if(e.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=a)return{text:`\u26A0\uFE0F Auto-respond limit reached (${n.autoRespondCount}/${a}). 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 k=vl(n);if(k)return{text:k,isError:!0}}if(!e.approve&&n.pendingInputState?.allowsFreeText&&await n.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let b=Ce(e.message,100);t.notifySession(n,`\u21AA\uFE0F [${n.name}] "${b}"`,"agent-respond")}e.userInitiated||n.incrementAutoRespond();let k=Ce(e.message,80);return{text:[`Pending input answered for session ${n.name} [${n.id}].`,` Message: "${k}"`,"Use agent_output to see the response."].join(`
80
+ `)}}let l=!1;e.interrupt&&(l=await n.interrupt());let u=!!(e.approve&&us(n)),f=u?cg(e.approvalRationale):void 0,g="";if(e.approve&&us(n)?(n.switchPermissionMode("bypassPermissions"),n.approvalRationale=f):e.approve&&n.currentPermissionMode==="default"?n.switchPermissionMode("bypassPermissions"):e.approve&&n.currentPermissionMode==="bypassPermissions"?g=`
81
+ \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:e.approve?g=`
82
+ \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:(n.pendingPlanApproval||n.approvalState==="changes_requested")&&(g=`
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),u&&yI(t,n),u)t.notifySession(n,`\u{1F44D} [${n.name}] Plan approved`,"plan-approved");else if(e.userInitiated){let k=Ce(e.message,100);t.notifySession(n,`\u21AA\uFE0F [${n.name}] "${k}"`,"agent-respond")}e.userInitiated||n.incrementAutoRespond();let y=Ce(e.message,80);return u?{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}].`,l?" (redirected active turn first)":e.interrupt?" (no active turn to interrupt)":"",` Message: "${y}"`,g,"Use agent_output to see the response."].filter(Boolean).join(`
84
+ `)}}catch(d){return{text:`Error sending message to session ${n.name} [${n.id}]: ${Pl(d)}`,isError:!0}}}function PI(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 gg(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(!PI(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();Y();function wI(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function hg(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(!wI(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();Y();Te();var bl=["off","manual","ask","delegate","auto-merge","auto-pr"],ps=new Set(bl),II=["low","medium","high","xhigh","max"],Sg=new Set(II);function bI(t){return typeof t=="string"&&ps.has(t)}var xI=c.Union(bl.map(t=>c.Literal(t)),{description:"Optional worktree strategy for the planning session. Use auto-pr when the follow-up should branch and open/update a PR after approved implementation."});function AI(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.offer_id=="string"&&typeof e.offer_text=="string"&&typeof e.plan_prompt=="string"&&typeof e.plan_workdir=="string"&&(e.plan_worktree_strategy==null||bI(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 RI(t,e){let n=ir(t,e.target_channel,e.target_session_key);if(n)return e.target_thread_id!=null&&(n.threadId=String(e.target_thread_id)),n}async function TI(t,e){if(!v)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=RI(t,e);return!n?.provider||!n.target?{content:[{type:"text",text:"Error: Could not resolve a direct delivery route for the plan offer."}]}:(v.sendPlanOffer({offerId:e.offer_id,route:n,text:e.offer_text,planName:e.plan_name??e.offer_id,planPrompt:e.plan_prompt,planWorkdir:e.plan_workdir,planWorktreeStrategy:e.plan_worktree_strategy}),{content:[{type:"text",text:`Interactive plan offer queued for ${n.provider}|${n.target}${n.threadId?`#${n.threadId}`:""}.`}]})}function yg(t){return{name:"agent_send_plan_offer",description:"Post a user-facing message to the current or explicit chat route with human-gated Start Plan and Dismiss inline buttons. Use this when an external workflow wants the user to open a plan-only code-agent session from the message.",parameters:c.Object({offer_id:c.String({description:"Stable offer identifier, for example 'plugin-readiness-v2026.5.5'."}),offer_text:c.String({description:"Final user-facing 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(xI),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){return AI(n)?TI(t,n):{content:[{type:"text",text:"Error: Invalid parameters. Expected { offer_id, offer_text, plan_prompt, plan_workdir }."}]}}}}De();Y();function kg(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:Ni(r,o)}]}}}}De();Te();Y();rt();go();import{existsSync as xl}from"fs";function MI(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function hs(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(!MI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let r=fr(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.`}]};xl(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${a})`);let l=a;if(!xl(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let u=n.base_branch??ln(l),f=u,g=n.strategy??"merge",y=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 b={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]},P=r.persistedRef;return await v.enqueueMerge(l,async()=>{let I=v.getPersistedSession(n.session);if(I?.worktreeLifecycle?.state==="merged"||I?.worktreeMerged){b={content:[{type:"text",text:`\u2139\uFE0F Session "${n.session}" was already merged while waiting in queue.`}]};return}let A=On(l,d,u),C=ts(l,d,f,g,s);if(C.success){if(y&&!es(l,f)){b={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${f} locally, but failed to push ${f}`}]};return}k&&Dt(l,d);let N=!1;if(xl(s)&&(N=nt(l,s),Zi(l)),I)for(let $ of vg({...r,persistedSession:I}))v.updatePersistedSession($,{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:u,targetRepo:I.worktreePrTargetRepo,pushRemote:I.worktreePushRemote}});let xe=$n({kind:"merge",branch:d,base:u,filesChanged:A?.filesChanged,insertions:A?.insertions,deletions:A?.deletions});v.notifyWorktreeOutcome(r.notificationTarget,xe);let O=`\u2705 ${C.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${f}.${y?" Pushed.":""}${k?N?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;C.stashPopConflict?O+=`
85
85
  \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${C.stashRef??"stash@{0}"}\` in ${l} to review stashed changes.`:C.stashed&&(O+=`
86
86
  (Pre-existing changes on ${f} were auto-stashed and restored.)`),b={content:[{type:"text",text:O}]}}else if(C.rebaseConflict)b={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
87
87
 
88
88
  ${C.error}`}]};else if(C.conflictFiles&&C.conflictFiles.length>0){let N=["Resolve merge conflicts in the following files and commit the resolution:","",...C.conflictFiles.map(xe=>`- ${xe}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${d}"`].join(`
89
- `);try{let xe=v.spawn({prompt:N,workdir:l,name:`${n.session}-conflict-resolver`,harness:Le(),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});b={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${C.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${xe.name}`}]}}catch(xe){b={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${xe instanceof Error?xe.message:String(xe)}`}]}}}else b={content:[{type:"text",text:C.dirtyError?`\u274C Merge blocked: ${C.error}`:`\u274C Merge failed: ${C.error??"unknown error"}`}]}}),b}}}Ss();De();Y();he();rt();fo();function OI(t){return!!t&&typeof t=="object"}function Ig(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(!OI(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=ms(v);if(r&&(a=a.filter(y=>fs(y,r)),a.length===0)){let y=mr(v,r);if(!y.persistedSession&&!y.activeSession)return{content:[{type:"text",text:`Error: Session "${r}" not found.`}]}}if(n.workdir&&(a=a.filter(y=>y.workdir===n.workdir)),a.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let d=[],l=[],u=[],f=[];for(let y of a){let{persistedSession:k,activeSession:b,resolvedLifecycle:P}=cs(v,y,{baseBranch:n.base_branch});if(!P.cleanupSafe){if(s){let I=P.reasons.length>0?P.reasons.map(gs).join(", "):Nn(P.derivedState);l.push(`${y.name} [kept: ${I}]`)}continue}if(d.push(`${y.name} (${Nn(P.derivedState)})`),!i)try{let I=y.workdir;if(!((k??b)&&We(k??b))&&y.worktreePath&&nt(I,y.worktreePath,{destructive:!1}),y.worktreeBranch&&Dt(I,y.worktreeBranch),k){let C=P.derivedState==="merged"||P.derivedState==="released"?P.derivedState:P.lifecycle.state;v.updatePersistedSession(y.id,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeMerged:C==="merged"?!0:k.worktreeMerged,worktreeMergedAt:C==="merged"?k.worktreeMergedAt??new Date().toISOString():k.worktreeMergedAt,worktreeLifecycle:{...k.worktreeLifecycle??P.lifecycle,state:C,updatedAt:new Date().toISOString(),resolvedAt:k.worktreeLifecycle?.resolvedAt??new Date().toISOString(),resolutionSource:k.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:n.base_branch??P.lifecycle.baseBranch??k.worktreeBaseBranch,targetRepo:k.worktreePrTargetRepo,pushRemote:k.worktreePushRemote,notes:P.reasons}})}u.push(`${y.name} (${Nn(P.derivedState)})`)}catch(I){f.push(`${y.name}: ${I instanceof Error?I.message:String(I)}`)}}let S=[o==="clean_safe"?"Clean all safe:":o==="preview_all"?"Worktree lifecycle review:":"Clean all safe preview:"];return S.push(` SAFE ${i?"NOW":"FOUND"} (${d.length}): ${d.join(", ")||"(none)"}`),s&&S.push(` KEPT (${l.length}): ${l.join(", ")||"(none)"}`),i||(S.push(` CLEANED (${u.length}): ${u.join(", ")||"(none)"}`),S.push(` FAILURES (${f.length}): ${f.join(", ")||"(none)"}`)),{content:[{type:"text",text:S.join(`
90
- `)}]}}}}De();Y();fo();function $I(t){return!0}function bg(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(!$I(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let r=n.session,o=ms(v);if(r&&(o=o.filter(s=>fs(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}=cs(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:${Nn(d.lifecycle.state)}`),d.derivedState!==d.lifecycle.state&&i.push(` Derived: ${Nn(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(gs).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
91
- `).trim()}]}}}}De();Y();Te();import{existsSync as DI}from"fs";function NI(t=[]){return t.map((e,n)=>({label:`check-${n+1}`,command:e.trim()})).filter(e=>e.command.length>0)}function ys(t,e){let n=t.goal.trim();if(!n)return{kind:"error",text:"Error: goal must not be empty."};let r=t.workdir||e.workspaceDir||_.defaultWorkdir||process.cwd();if(!DI(r))return{kind:"error",text:`Error: Working directory does not exist: ${r}`};let o=NI(t.verifierCommands),i=t.goalMode??(o.length>0?"verifier":"ralph");if(i==="verifier"&&o.length===0)return{kind:"error",text:"Error: verifier mode requires at least one non-empty verifier command."};let s=t.harness??Le(),a=t.model??or(s);if(!a)return{kind:"error",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=ki(s);if(!Oi(a,d))return{kind:"error",text:`Error: Model "${a}" is not allowed. Permitted models: ${d?.join(", ")}`};let l=e.sessionKey||void 0,u=vi(e),f=Jr(e,u),S=ir(e,f,l);return{kind:"resolved",goal:n,name:t.name,workdir:r,model:a,reasoningEffort:sn(s),systemPrompt:t.systemPrompt,allowedTools:t.allowedTools,maxIterations:t.maxIterations,permissionMode:t.permissionMode??"bypassPermissions",harness:s,loopMode:i,completionPromise:t.completionPromise,originChannel:f,originThreadId:S?.threadId,originAgentId:e.agentId||void 0,originSessionKey:l,route:S,verifierCommands:o}}function ks(t,e){return["Goal task launched.",` Name: ${t.name}`,` ID: ${t.id}`,` Dir: ${t.workdir}`,` Session: ${t.sessionName} [${t.sessionId}]`,` Harness: ${e.harness}`,` Model: ${e.model}`,` Loop mode: ${t.loopMode}`,` Max iterations: ${t.maxIterations}`,` Goal: "${e.goal.length>100?`${e.goal.slice(0,100)}...`:e.goal}"`,...t.loopMode==="ralph"?[` Completion promise: ${t.completionPromise}`]:[" Verifiers:",...e.verifierCommands.map(r=>` - ${r.command}`)],"","Use goal_status to follow progress or goal_stop to terminate the task."].join(`
92
- `)}function FI(t){return!t||typeof t!="object"?!1:typeof t.goal=="string"}function xg(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(!ge)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!FI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let r=ys({goal:n.goal,verifierCommands:n.verifier_commands,name:n.name,workdir:n.workdir,model:n.model,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,maxIterations:n.max_iterations,permissionMode:n.permission_mode,harness:n.harness,goalMode:n.goal_mode,completionPromise:n.completion_promise},t);if(r.kind!=="resolved")return{content:[{type:"text",text:r.text}]};try{let o=await ge.launchTask({goal:r.goal,name:r.name,workdir:r.workdir,model:r.model,reasoningEffort:r.reasoningEffort,systemPrompt:r.systemPrompt,allowedTools:r.allowedTools,maxIterations:r.maxIterations,permissionMode:r.permissionMode,loopMode:r.loopMode,completionPromise:r.completionPromise,originChannel:r.originChannel,originThreadId:r.originThreadId,originAgentId:r.originAgentId,originSessionKey:r.originSessionKey,route:r.route,harness:r.harness,verifierCommands:r.verifierCommands});return{content:[{type:"text",text:ks(o,r)}]}}catch(o){return{content:[{type:"text",text:`Error launching goal task: ${o instanceof Error?o.message:String(o)}`}]}}}}}De();function Ag(t,e){return t.split(`
89
+ `);try{let xe=v.spawn({prompt:N,workdir:l,name:`${n.session}-conflict-resolver`,harness:Le(),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});b={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${C.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${xe.name}`}]}}catch(xe){b={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${xe instanceof Error?xe.message:String(xe)}`}]}}}else b={content:[{type:"text",text:C.dirtyError?`\u274C Merge blocked: ${C.error}`:`\u274C Merge failed: ${C.error??"unknown error"}`}]}}),b}}}Ss();De();Y();he();rt();go();function OI(t){return!!t&&typeof t=="object"}function wg(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(!OI(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=ms(v);if(r&&(a=a.filter(y=>fs(y,r)),a.length===0)){let y=fr(v,r);if(!y.persistedSession&&!y.activeSession)return{content:[{type:"text",text:`Error: Session "${r}" not found.`}]}}if(n.workdir&&(a=a.filter(y=>y.workdir===n.workdir)),a.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let d=[],l=[],u=[],f=[];for(let y of a){let{persistedSession:k,activeSession:b,resolvedLifecycle:P}=cs(v,y,{baseBranch:n.base_branch});if(!P.cleanupSafe){if(s){let I=P.reasons.length>0?P.reasons.map(gs).join(", "):Nn(P.derivedState);l.push(`${y.name} [kept: ${I}]`)}continue}if(d.push(`${y.name} (${Nn(P.derivedState)})`),!i)try{let I=y.workdir;if(!((k??b)&&We(k??b))&&y.worktreePath&&nt(I,y.worktreePath,{destructive:!1}),y.worktreeBranch&&Dt(I,y.worktreeBranch),k){let C=P.derivedState==="merged"||P.derivedState==="released"?P.derivedState:P.lifecycle.state;v.updatePersistedSession(y.id,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeMerged:C==="merged"?!0:k.worktreeMerged,worktreeMergedAt:C==="merged"?k.worktreeMergedAt??new Date().toISOString():k.worktreeMergedAt,worktreeLifecycle:{...k.worktreeLifecycle??P.lifecycle,state:C,updatedAt:new Date().toISOString(),resolvedAt:k.worktreeLifecycle?.resolvedAt??new Date().toISOString(),resolutionSource:k.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:n.base_branch??P.lifecycle.baseBranch??k.worktreeBaseBranch,targetRepo:k.worktreePrTargetRepo,pushRemote:k.worktreePushRemote,notes:P.reasons}})}u.push(`${y.name} (${Nn(P.derivedState)})`)}catch(I){f.push(`${y.name}: ${I instanceof Error?I.message:String(I)}`)}}let g=[o==="clean_safe"?"Clean all safe:":o==="preview_all"?"Worktree lifecycle review:":"Clean all safe preview:"];return g.push(` SAFE ${i?"NOW":"FOUND"} (${d.length}): ${d.join(", ")||"(none)"}`),s&&g.push(` KEPT (${l.length}): ${l.join(", ")||"(none)"}`),i||(g.push(` CLEANED (${u.length}): ${u.join(", ")||"(none)"}`),g.push(` FAILURES (${f.length}): ${f.join(", ")||"(none)"}`)),{content:[{type:"text",text:g.join(`
90
+ `)}]}}}}De();Y();go();function $I(t){return!0}function Ig(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(!$I(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let r=n.session,o=ms(v);if(r&&(o=o.filter(s=>fs(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}=cs(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:${Nn(d.lifecycle.state)}`),d.derivedState!==d.lifecycle.state&&i.push(` Derived: ${Nn(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(gs).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
91
+ `).trim()}]}}}}De();Y();Te();import{existsSync as DI}from"fs";function NI(t=[]){return t.map((e,n)=>({label:`check-${n+1}`,command:e.trim()})).filter(e=>e.command.length>0)}function ys(t,e){let n=t.goal.trim();if(!n)return{kind:"error",text:"Error: goal must not be empty."};let r=t.workdir||e.workspaceDir||_.defaultWorkdir||process.cwd();if(!DI(r))return{kind:"error",text:`Error: Working directory does not exist: ${r}`};let o=NI(t.verifierCommands),i=t.goalMode??(o.length>0?"verifier":"ralph");if(i==="verifier"&&o.length===0)return{kind:"error",text:"Error: verifier mode requires at least one non-empty verifier command."};let s=t.harness??Le(),a=t.model??or(s);if(!a)return{kind:"error",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=vi(s);if(!$i(a,d))return{kind:"error",text:`Error: Model "${a}" is not allowed. Permitted models: ${d?.join(", ")}`};let l=e.sessionKey||void 0,u=Pi(e),f=Yr(e,u),g=ir(e,f,l);return{kind:"resolved",goal:n,name:t.name,workdir:r,model:a,reasoningEffort:sn(s),systemPrompt:t.systemPrompt,allowedTools:t.allowedTools,maxIterations:t.maxIterations,permissionMode:t.permissionMode??"bypassPermissions",harness:s,loopMode:i,completionPromise:t.completionPromise,originChannel:f,originThreadId:g?.threadId,originAgentId:e.agentId||void 0,originSessionKey:l,route:g,verifierCommands:o}}function ks(t,e){return["Goal task launched.",` Name: ${t.name}`,` ID: ${t.id}`,` Dir: ${t.workdir}`,` Session: ${t.sessionName} [${t.sessionId}]`,` Harness: ${e.harness}`,` Model: ${e.model}`,` Loop mode: ${t.loopMode}`,` Max iterations: ${t.maxIterations}`,` Goal: "${e.goal.length>100?`${e.goal.slice(0,100)}...`:e.goal}"`,...t.loopMode==="ralph"?[` Completion promise: ${t.completionPromise}`]:[" Verifiers:",...e.verifierCommands.map(r=>` - ${r.command}`)],"","Use goal_status to follow progress or goal_stop to terminate the task."].join(`
92
+ `)}function FI(t){return!t||typeof t!="object"?!1:typeof t.goal=="string"}function bg(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(!ge)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!FI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let r=ys({goal:n.goal,verifierCommands:n.verifier_commands,name:n.name,workdir:n.workdir,model:n.model,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,maxIterations:n.max_iterations,permissionMode:n.permission_mode,harness:n.harness,goalMode:n.goal_mode,completionPromise:n.completion_promise},t);if(r.kind!=="resolved")return{content:[{type:"text",text:r.text}]};try{let o=await ge.launchTask({goal:r.goal,name:r.name,workdir:r.workdir,model:r.model,reasoningEffort:r.reasoningEffort,systemPrompt:r.systemPrompt,allowedTools:r.allowedTools,maxIterations:r.maxIterations,permissionMode:r.permissionMode,loopMode:r.loopMode,completionPromise:r.completionPromise,originChannel:r.originChannel,originThreadId:r.originThreadId,originAgentId:r.originAgentId,originSessionKey:r.originSessionKey,route:r.route,harness:r.harness,verifierCommands:r.verifierCommands});return{content:[{type:"text",text:ks(o,r)}]}}catch(o){return{content:[{type:"text",text:`Error launching goal task: ${o instanceof Error?o.message:String(o)}`}]}}}}}De();function xg(t,e){return t.split(`
93
93
  `).map(n=>`${e}${n}`)}function LI(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 un(t){if(t)return{phase:t.phase,awaitingInput:t.isAwaitingInput??!!t.pendingInputState,latestOutput:LI(t.getOutput(20))}}function pn(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(...Ag(t.lastVerifierSummary," "))),e?.latestOutput&&(r.push(" Latest activity:"),r.push(...Ag(e.latestOutput," "))),t.waitingForUserReason&&r.push(` Waiting on user: ${t.waitingForUserReason}`),t.failureReason&&r.push(` Failure: ${t.failureReason}`),r.join(`
95
- `)}Y();function Rg(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(!ge)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=ge.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:pn(i,un(s))}]}}let o=ge.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 pn(i,un(s))}).join(`
94
+ `);return o.length<=n?o:`...${o.slice(-(n-3))}`}function un(t){if(t)return{phase:t.phase,awaitingInput:t.isAwaitingInput??!!t.pendingInputState,latestOutput:LI(t.getOutput(20))}}function pn(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(...xg(t.lastVerifierSummary," "))),e?.latestOutput&&(r.push(" Latest activity:"),r.push(...xg(e.latestOutput," "))),t.waitingForUserReason&&r.push(` Waiting on user: ${t.waitingForUserReason}`),t.failureReason&&r.push(` Failure: ${t.failureReason}`),r.join(`
95
+ `)}Y();function Ag(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(!ge)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=ge.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:pn(i,un(s))}]}}let o=ge.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 pn(i,un(s))}).join(`
96
96
 
97
- `)}]}}}}De();Y();function WI(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function Tg(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(!ge)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!WI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let r=ge.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.`}]}}}}Y();Ss();import{createHash as BI}from"crypto";var ot="code-agent";var UI=new Set(["1","true","yes","on"]);function KI(){let t=process.env.OPENCLAW_CODE_AGENT_BUTTON_DIAGNOSTICS?.trim().toLowerCase();return!!(t&&UI.has(t))}function fr(t){if(!(typeof t!="string"||t.length===0))return BI("sha256").update(t).digest("hex").slice(0,12)}function Cg(t){return typeof t.callbackData=="string"?t.callbackData:typeof t.value=="string"?t.value:void 0}function se(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=Cg(r);return o?Buffer.byteLength(o,"utf8"):void 0}):void 0,callbackHashes:n.length>0?n.map(r=>fr(Cg(r))):void 0,buttonStyles:n.length>0?n.map(r=>typeof r.style=="string"?r.style:void 0):void 0}}function cn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function _g(t){let e=cn(t),n=Array.isArray(e?.blocks)?e.blocks:void 0;if(n)return n.map(r=>cn(r)?.type).filter(r=>typeof r=="string"&&r.length>0)}function Eg(t){let e=cn(t),n=Array.isArray(e?.blocks)?e.blocks:void 0;if(!n)return;let r=n.map(o=>{let i=cn(o);return i?.type!=="buttons"||!Array.isArray(i.buttons)?[]:i.buttons}).filter(o=>o.length>0);return r.length>0?r:void 0}function Rl(t){let e=Eg(t);return{presentationBlockTypes:_g(t),...se(e)}}function Tl(t){let e=cn(t),n=e?.interactive,r=cn(e?.channelData),o=cn(r?.telegram),i=Array.isArray(o?.buttons)?o.buttons:void 0;return{renderedPayloadKeys:e?Object.keys(e).sort():void 0,interactiveBlockTypes:_g(n),...Mg("interactive",se(Eg(n))),...Mg("telegramChannelData",se(i)),hasPresentation:!!e?.presentation,hasInteractive:!!n,hasTelegramChannelDataButtons:!!i?.some(s=>s.length>0)}}function Og(t){let e=cn(t);return e?{sendResultKeys:Object.keys(e).sort(),messageId:Al(e.messageId),chatId:Al(e.chatId),telegramThreadId:Al(e.messageThreadId??e.threadId),channel:typeof e.channel=="string"?e.channel:void 0}:{sendResultType:typeof t}}function Al(t){return typeof t=="string"||typeof t=="number"?t:void 0}function Mg(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 q(t,e){if(!KI())return;let n=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));console.info(`[CodeAgentButtonDiagnostics] ${JSON.stringify({event:t,callbackNamespace:ot,...n})}`)}function VI(t){let e=t.trim().replace(new RegExp(`^${ot}:`),"");return e||null}async function vs(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 Cl(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 qI(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function GI(t,e){if(qI(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 jI(t){let e="callback"in t?t.callback?.payload:void 0,n="interaction"in t?t.interaction?.payload:void 0;return e??n??""}function Ml(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function HI(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(Ml(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(Ml(o))return;if(HI(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(!Ml(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 ue(t,e){if(t.channel==="telegram"){await t.respond.reply({text:e});return}await t.respond.reply({text:e,ephemeral:!0})}function _l(t="telegram"){return q("callback_handler_registered",{channel:t,namespace:ot}),{channel:t,namespace:ot,handler:async e=>{if(!e.auth.isAuthorizedSender)return await ue(e,"\u26D4 Unauthorized."),{handled:!0};let n=jI(e),r=VI(n);if(q("callback_received",{channel:e.channel,namespace:ot,payloadByteLength:Buffer.byteLength(n,"utf8"),tokenHash:fr(r),isAuthorizedSender:e.auth.isAuthorizedSender}),!r)return await ue(e,`\u26A0\uFE0F Unrecognized callback payload: "${n}".`),{handled:!0};if(!v)return await ue(e,"\u26A0\uFE0F Code agent service not running."),{handled:!0};let o=v.getActionToken(r);if(q("callback_token_lookup_completed",{channel:e.channel,namespace:ot,tokenHash:fr(r),tokenFound:!!o,actionKind:o?.kind,sessionId:o?.sessionId,planDecisionVersion:o?.planDecisionVersion}),!o)return await ue(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=GI(o,s);if(q("callback_plan_validation_completed",{channel:e.channel,namespace:ot,tokenHash:fr(r),actionKind:o.kind,sessionId:i,sessionName:a,planDecisionVersion:o.planDecisionVersion,valid:!d}),d)return await ft(e),await ue(e,`\u26A0\uFE0F ${d}`),{handled:!0};let l=v.consumeActionToken(r);if(q("callback_token_consume_completed",{channel:e.channel,namespace:ot,tokenHash:fr(r),consumed:!!l,actionKind:l?.kind,sessionId:l?.sessionId,planDecisionVersion:l?.planDecisionVersion}),!l)return await ue(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};switch(l.kind){case"worktree-merge":{await vs(e,`\u2705 Merge selected for [${a}]`);let u=await hs().execute("callback",{session:i});await ue(e,Cl(u));break}case"worktree-decide-later":{await vs(e,`\u23ED\uFE0F Deferred for [${a}]`);let u=v.snoozeWorktreeDecision(i);await ue(e,u.startsWith("Error")?u:"\u23ED\uFE0F Snoozed 24h");break}case"worktree-dismiss":{await vs(e,`\u{1F5D1}\uFE0F Discarded for [${a}]`);let u=await v.dismissWorktree(i);await ue(e,(u.startsWith("Error"),u));break}case"worktree-create-pr":case"worktree-update-pr":{await vs(e,o.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${a}]`:`\u{1F4EC} PR selected for [${a}]`);let u=await go().execute("callback",{session:i});await ue(e,Cl(u));break}case"worktree-view-pr":{await ft(e);let u=v.getPersistedSession?.(i),f=o.targetUrl??u?.worktreePrUrl;await ue(e,f?`PR: ${f}`:"\u26A0\uFE0F PR URL is no longer available.");break}case"plan-approve":{await ft(e),v.clearPlanDecisionTokens(i);let u=await mt(v,{session:i,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});u.isError&&await ue(e,`\u26A0\uFE0F ${u.text}`);break}case"plan-reject":{await ft(e);let u=wl(v,i);await ue(e,`\u274C ${u.text}`);break}case"plan-request-changes":{await ft(e);let u=Il(v,i);await ue(e,`\u270F\uFE0F ${u.text}`);break}case"plan-offer-start":{if(await ft(e),!l.launchPrompt||!l.launchWorkdir){await ue(e,"\u26A0\uFE0F This action is missing the plan launch context.");break}let u=v.launchPlanOffer({route:l.route,prompt:l.launchPrompt,workdir:l.launchWorkdir,name:l.launchName,worktreeStrategy:l.launchWorktreeStrategy});await ue(e,`\u25B6\uFE0F Planning session started: ${u.name} [${u.id}]`);break}case"plan-offer-dismiss":{await ft(e),await ue(e,"\u2705 Dismissed.");break}case"session-restart":case"session-resume":{await ft(e);let u=await mt(v,{session:i,message:"Continue where you left off.",userInitiated:!0});await ue(e,u.isError?`\u26A0\uFE0F ${u.text}`:`\u25B6\uFE0F ${u.text}`);break}case"view-output":{await ft(e);let u=await ls().execute("callback",{session:i,lines:50});await ue(e,Cl(u));break}case"question-answer":{if(await ft(e),o.optionIndex==null){await ue(e,"\u26A0\uFE0F Invalid question-answer action.");break}await v.resolvePendingInputOption(i,o.optionIndex),await ue(e,"\u2705 Answer submitted.");break}default:{await ft(e),await ue(e,"\u26A0\uFE0F Unknown callback action.");break}}return{handled:!0}}}}Y();Te();function gr(t){return $g(t).map(e=>e.value)}function $g(t){return Array.from(t.matchAll(/"[^"]*"|'[^']*'|\S+/g),e=>{let n=e[0],r=e.index??0;return{value:zI(n),raw:n,start:r,end:r+n.length}})}function El(t){let[e]=$g(t);if(e)return{value:e.value,rest:t.slice(e.end).trimStart()}}function zI(t){return t.length>1&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function QI(t){return t instanceof Error?t.message:String(t)}function JI(t){let e=gr(t),n,r=e;return e[0]==="--name"&&e[1]&&(n=e[1],r=e.slice(2)),{name:n,prompt:r.join(" ").trim()}}function Dg(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{name:r,prompt:o}=JI(n);if(!o)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=$i({prompt:o,name:r},e,v);if(i.kind!=="resolved")return{text:i.text};let s=v.spawn({prompt:o,name:r,workdir:i.workdir,model:i.resolvedModel,reasoningEffort:i.reasoningEffort,codexApprovalPolicy:i.harness==="codex"?"never":void 0,originChannel:i.originChannel,originThreadId:i.originThreadId,originAgentId:e.agentId||void 0,originSessionKey:i.originSessionKey,route:i.route,harness:i.harness,permissionMode:i.permissionMode,planApproval:i.planApproval,taskLifecycle:Ui(e)});return{text:v.formatLaunchResult({prompt:o,workdir:i.workdir,harness:i.harness,permissionMode:i.permissionMode??_.permissionMode,planApproval:i.planApproval},s)}}catch(i){let s=QI(i),a=s.includes("Max sessions")?"":`
97
+ `)}]}}}}De();Y();function WI(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function Rg(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(!ge)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!WI(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let r=ge.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.`}]}}}}Y();Ss();import{createHash as BI}from"crypto";var ot="code-agent";var UI=new Set(["1","true","yes","on"]);function KI(){let t=process.env.OPENCLAW_CODE_AGENT_BUTTON_DIAGNOSTICS?.trim().toLowerCase();return!!(t&&UI.has(t))}function gr(t){if(!(typeof t!="string"||t.length===0))return BI("sha256").update(t).digest("hex").slice(0,12)}function Tg(t){return typeof t.callbackData=="string"?t.callbackData:typeof t.value=="string"?t.value:void 0}function se(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=Tg(r);return o?Buffer.byteLength(o,"utf8"):void 0}):void 0,callbackHashes:n.length>0?n.map(r=>gr(Tg(r))):void 0,buttonStyles:n.length>0?n.map(r=>typeof r.style=="string"?r.style:void 0):void 0}}function cn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Mg(t){let e=cn(t),n=Array.isArray(e?.blocks)?e.blocks:void 0;if(n)return n.map(r=>cn(r)?.type).filter(r=>typeof r=="string"&&r.length>0)}function _g(t){let e=cn(t),n=Array.isArray(e?.blocks)?e.blocks:void 0;if(!n)return;let r=n.map(o=>{let i=cn(o);return i?.type!=="buttons"||!Array.isArray(i.buttons)?[]:i.buttons}).filter(o=>o.length>0);return r.length>0?r:void 0}function Rl(t){let e=_g(t);return{presentationBlockTypes:Mg(t),...se(e)}}function Tl(t){let e=cn(t),n=e?.interactive,r=cn(e?.channelData),o=cn(r?.telegram),i=Array.isArray(o?.buttons)?o.buttons:void 0;return{renderedPayloadKeys:e?Object.keys(e).sort():void 0,interactiveBlockTypes:Mg(n),...Cg("interactive",se(_g(n))),...Cg("telegramChannelData",se(i)),hasPresentation:!!e?.presentation,hasInteractive:!!n,hasTelegramChannelDataButtons:!!i?.some(s=>s.length>0)}}function Eg(t){let e=cn(t);return e?{sendResultKeys:Object.keys(e).sort(),messageId:Al(e.messageId),chatId:Al(e.chatId),telegramThreadId:Al(e.messageThreadId??e.threadId),channel:typeof e.channel=="string"?e.channel:void 0}:{sendResultType:typeof t}}function Al(t){return typeof t=="string"||typeof t=="number"?t:void 0}function Cg(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 q(t,e){if(!KI())return;let n=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));console.info(`[CodeAgentButtonDiagnostics] ${JSON.stringify({event:t,callbackNamespace:ot,...n})}`)}function VI(t){let e=t.trim().replace(new RegExp(`^${ot}:`),"");return e||null}async function vs(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 Cl(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 qI(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function GI(t,e){if(qI(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 jI(t){let e="callback"in t?t.callback?.payload:void 0,n="interaction"in t?t.interaction?.payload:void 0;return e??n??""}function Ml(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function HI(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(Ml(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(Ml(o))return;if(HI(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(!Ml(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 ue(t,e){if(t.channel==="telegram"){await t.respond.reply({text:e});return}await t.respond.reply({text:e,ephemeral:!0})}function Og(t="telegram"){return q("callback_handler_registered",{channel:t,namespace:ot}),{channel:t,namespace:ot,handler:async e=>{if(!e.auth.isAuthorizedSender)return await ue(e,"\u26D4 Unauthorized."),{handled:!0};let n=jI(e),r=VI(n);if(q("callback_received",{channel:e.channel,namespace:ot,payloadByteLength:Buffer.byteLength(n,"utf8"),tokenHash:gr(r),isAuthorizedSender:e.auth.isAuthorizedSender}),!r)return await ue(e,`\u26A0\uFE0F Unrecognized callback payload: "${n}".`),{handled:!0};if(!v)return await ue(e,"\u26A0\uFE0F Code agent service not running."),{handled:!0};let o=v.getActionToken(r);if(q("callback_token_lookup_completed",{channel:e.channel,namespace:ot,tokenHash:gr(r),tokenFound:!!o,actionKind:o?.kind,sessionId:o?.sessionId,planDecisionVersion:o?.planDecisionVersion}),!o)return await ue(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=GI(o,s);if(q("callback_plan_validation_completed",{channel:e.channel,namespace:ot,tokenHash:gr(r),actionKind:o.kind,sessionId:i,sessionName:a,planDecisionVersion:o.planDecisionVersion,valid:!d}),d)return await ft(e),await ue(e,`\u26A0\uFE0F ${d}`),{handled:!0};let l=v.consumeActionToken(r);if(q("callback_token_consume_completed",{channel:e.channel,namespace:ot,tokenHash:gr(r),consumed:!!l,actionKind:l?.kind,sessionId:l?.sessionId,planDecisionVersion:l?.planDecisionVersion}),!l)return await ue(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};switch(l.kind){case"worktree-merge":{await vs(e,`\u2705 Merge selected for [${a}]`);let u=await hs().execute("callback",{session:i});await ue(e,Cl(u));break}case"worktree-decide-later":{await vs(e,`\u23ED\uFE0F Deferred for [${a}]`);let u=v.snoozeWorktreeDecision(i);await ue(e,u.startsWith("Error")?u:"\u23ED\uFE0F Snoozed 24h");break}case"worktree-dismiss":{await vs(e,`\u{1F5D1}\uFE0F Discarded for [${a}]`);let u=await v.dismissWorktree(i);await ue(e,(u.startsWith("Error"),u));break}case"worktree-create-pr":case"worktree-update-pr":{await vs(e,o.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${a}]`:`\u{1F4EC} PR selected for [${a}]`);let u=await ho().execute("callback",{session:i});await ue(e,Cl(u));break}case"worktree-view-pr":{await ft(e);let u=v.getPersistedSession?.(i),f=o.targetUrl??u?.worktreePrUrl;await ue(e,f?`PR: ${f}`:"\u26A0\uFE0F PR URL is no longer available.");break}case"plan-approve":{await ft(e),v.clearPlanDecisionTokens(i);let u=await mt(v,{session:i,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});u.isError&&await ue(e,`\u26A0\uFE0F ${u.text}`);break}case"plan-reject":{await ft(e);let u=wl(v,i);await ue(e,`\u274C ${u.text}`);break}case"plan-request-changes":{await ft(e);let u=Il(v,i);await ue(e,`\u270F\uFE0F ${u.text}`);break}case"plan-offer-start":{if(await ft(e),!l.launchPrompt||!l.launchWorkdir){await ue(e,"\u26A0\uFE0F This action is missing the plan launch context.");break}let u=v.launchPlanOffer({route:l.route,prompt:l.launchPrompt,workdir:l.launchWorkdir,name:l.launchName,worktreeStrategy:l.launchWorktreeStrategy});await ue(e,`\u25B6\uFE0F Planning session started: ${u.name} [${u.id}]`);break}case"plan-offer-dismiss":{await ft(e),await ue(e,"\u2705 Dismissed.");break}case"session-restart":case"session-resume":{await ft(e);let u=await mt(v,{session:i,message:"Continue where you left off.",userInitiated:!0});await ue(e,u.isError?`\u26A0\uFE0F ${u.text}`:`\u25B6\uFE0F ${u.text}`);break}case"view-output":{await ft(e);let u=await ls().execute("callback",{session:i,lines:50});await ue(e,Cl(u));break}case"question-answer":{if(await ft(e),o.optionIndex==null){await ue(e,"\u26A0\uFE0F Invalid question-answer action.");break}await v.resolvePendingInputOption(i,o.optionIndex),await ue(e,"\u2705 Answer submitted.");break}default:{await ft(e),await ue(e,"\u26A0\uFE0F Unknown callback action.");break}}return{handled:!0}}}}Y();Te();function hr(t){return $g(t).map(e=>e.value)}function $g(t){return Array.from(t.matchAll(/"[^"]*"|'[^']*'|\S+/g),e=>{let n=e[0],r=e.index??0;return{value:zI(n),raw:n,start:r,end:r+n.length}})}function _l(t){let[e]=$g(t);if(e)return{value:e.value,rest:t.slice(e.end).trimStart()}}function zI(t){return t.length>1&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function QI(t){return t instanceof Error?t.message:String(t)}function JI(t){let e=hr(t),n,r=e;return e[0]==="--name"&&e[1]&&(n=e[1],r=e.slice(2)),{name:n,prompt:r.join(" ").trim()}}function Dg(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{name:r,prompt:o}=JI(n);if(!o)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=Di({prompt:o,name:r},e,v);if(i.kind!=="resolved")return{text:i.text};let s=v.spawn({prompt:o,name:r,workdir:i.workdir,model:i.resolvedModel,reasoningEffort:i.reasoningEffort,codexApprovalPolicy:i.harness==="codex"?"never":void 0,originChannel:i.originChannel,originThreadId:i.originThreadId,originAgentId:e.agentId||void 0,originSessionKey:i.originSessionKey,route:i.route,harness:i.harness,permissionMode:i.permissionMode,planApproval:i.planApproval,taskLifecycle:Ui(e)});return{text:v.formatLaunchResult({prompt:o,workdir:i.workdir,harness:i.harness,permissionMode:i.permissionMode??_.permissionMode,planApproval:i.planApproval},s)}}catch(i){let s=QI(i),a=s.includes("Max sessions")?"":`
98
98
 
99
99
  Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${s}${a}`}}}})}Y();function Ng(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:as(v,"all",void 0,{full:n})}}})}Y();function Fg(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:ds(v,n,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}Y();function Lg(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>
100
- /agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n,i=El(o);i?.value==="--interrupt"&&(r=!0,o=i.rest);let s=El(o);if(!s)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let a=s.value,d=s.rest;return d.trim()?{text:(await mt(v,{session:a,message:d,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}Y();function Wg(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:Di(e,n)}}})}Y();var YI=50;function Bg(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=gr(n),o="",i=!1,s=YI;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:ss(v,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}Y();var Ug="Usage: /goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>";function Kg(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(!ge)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:Ug};let r=gr(n),o,i,s,a,d="bypassPermissions",l,u,f,S=[],y=[];for(let P=0;P<r.length;P++){let I=r[P];if(I==="--name"&&P+1<r.length)o=r[++P];else if(I==="--workdir"&&P+1<r.length)i=r[++P];else if(I==="--model"&&P+1<r.length)s=r[++P];else if(I==="--max-iterations"&&P+1<r.length){let A=parseInt(r[++P],10);!Number.isNaN(A)&&A>0&&(a=A)}else if(I==="--permission-mode"&&P+1<r.length){let A=r[++P];if(A==="default"||A==="plan"||A==="bypassPermissions")d=A;else return{text:`Error: Invalid permission mode "${A}".`}}else if(I==="--harness"&&P+1<r.length)l=r[++P];else if(I==="--mode"&&P+1<r.length){let A=r[++P];if(A==="ralph"||A==="verifier")u=A;else return{text:`Error: Invalid goal mode "${A}". Use ralph or verifier.`}}else if(I==="--completion-promise"&&P+1<r.length)f=r[++P];else if(I==="--verify"&&P+1<r.length){let A=r[++P].trim();if(!A)return{text:"Error: --verify commands must not be empty."};S.push(A)}else y.push(I)}let k=y.join(" ").trim();if(!k)return{text:Ug};let b=ys({goal:k,verifierCommands:S,name:o,workdir:i,model:s,maxIterations:a,permissionMode:d,harness:l,goalMode:u,completionPromise:f},e);if(b.kind!=="resolved")return{text:b.text};try{let P=await ge.launchTask({goal:b.goal,name:b.name,workdir:b.workdir,model:b.model,reasoningEffort:b.reasoningEffort,maxIterations:b.maxIterations,permissionMode:b.permissionMode,harness:b.harness,loopMode:b.loopMode,completionPromise:b.completionPromise,originChannel:b.originChannel,originThreadId:b.originThreadId,originAgentId:b.originAgentId,originSessionKey:b.originSessionKey,route:b.route,verifierCommands:b.verifierCommands});return{text:ks(P,b)}}catch(P){return{text:`Error launching goal task: ${P instanceof Error?P.message:String(P)}`}}}})}Y();function Vg(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(!ge)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(n){let o=ge.getTask(n);if(!o)return{text:`Error: Goal task "${n}" not found.`};let i=o.sessionId?v?.resolve(o.sessionId):void 0;return{text:pn(o,un(i))}}let r=ge.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 pn(o,un(i))}).join(`
100
+ /agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n,i=_l(o);i?.value==="--interrupt"&&(r=!0,o=i.rest);let s=_l(o);if(!s)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let a=s.value,d=s.rest;return d.trim()?{text:(await mt(v,{session:a,message:d,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}Y();function Wg(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:Ni(e,n)}}})}Y();var YI=50;function Bg(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=hr(n),o="",i=!1,s=YI;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:ss(v,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}Y();var Ug="Usage: /goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>";function Kg(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(!ge)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(!n)return{text:Ug};let r=hr(n),o,i,s,a,d="bypassPermissions",l,u,f,g=[],y=[];for(let P=0;P<r.length;P++){let I=r[P];if(I==="--name"&&P+1<r.length)o=r[++P];else if(I==="--workdir"&&P+1<r.length)i=r[++P];else if(I==="--model"&&P+1<r.length)s=r[++P];else if(I==="--max-iterations"&&P+1<r.length){let A=parseInt(r[++P],10);!Number.isNaN(A)&&A>0&&(a=A)}else if(I==="--permission-mode"&&P+1<r.length){let A=r[++P];if(A==="default"||A==="plan"||A==="bypassPermissions")d=A;else return{text:`Error: Invalid permission mode "${A}".`}}else if(I==="--harness"&&P+1<r.length)l=r[++P];else if(I==="--mode"&&P+1<r.length){let A=r[++P];if(A==="ralph"||A==="verifier")u=A;else return{text:`Error: Invalid goal mode "${A}". Use ralph or verifier.`}}else if(I==="--completion-promise"&&P+1<r.length)f=r[++P];else if(I==="--verify"&&P+1<r.length){let A=r[++P].trim();if(!A)return{text:"Error: --verify commands must not be empty."};g.push(A)}else y.push(I)}let k=y.join(" ").trim();if(!k)return{text:Ug};let b=ys({goal:k,verifierCommands:g,name:o,workdir:i,model:s,maxIterations:a,permissionMode:d,harness:l,goalMode:u,completionPromise:f},e);if(b.kind!=="resolved")return{text:b.text};try{let P=await ge.launchTask({goal:b.goal,name:b.name,workdir:b.workdir,model:b.model,reasoningEffort:b.reasoningEffort,maxIterations:b.maxIterations,permissionMode:b.permissionMode,harness:b.harness,loopMode:b.loopMode,completionPromise:b.completionPromise,originChannel:b.originChannel,originThreadId:b.originThreadId,originAgentId:b.originAgentId,originSessionKey:b.originSessionKey,route:b.route,verifierCommands:b.verifierCommands});return{text:ks(P,b)}}catch(P){return{text:`Error launching goal task: ${P instanceof Error?P.message:String(P)}`}}}})}Y();function Vg(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(!ge)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let n=(e.args??"").trim();if(n){let o=ge.getTask(n);if(!o)return{text:`Error: Goal task "${n}" not found.`};let i=o.sessionId?v?.resolve(o.sessionId):void 0;return{text:pn(o,un(i))}}let r=ge.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 pn(o,un(i))}).join(`
101
101
 
102
- `)}}})}Y();function qg(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(!ge)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=ge.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 ub}from"child_process";import{createHash as Zg}from"crypto";import{existsSync as XI,mkdirSync as ZI,readFileSync as eb,renameSync as tb,writeFileSync as nb}from"fs";import{homedir as rb}from"os";import{dirname as ob,join as Gg}from"path";function ib(t){let e=t.OPENCLAW_HOME?.trim();return e||Gg(rb(),".openclaw")}function sb(t){let e=t.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||Gg(ib(t),"code-agent-goal-tasks.json")}function ab(t){return t instanceof Error?t.message:String(t)}function db(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 lb(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:db(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 Ps=class{path;tasks=new Map;constructor(e=process.env){this.path=sb(e),this.load()}load(){try{if(!XI(this.path))return;let e=eb(this.path,"utf8"),n=JSON.parse(e);if(!Array.isArray(n))return;for(let r of n){let o=lb(r);o&&this.tasks.set(o.id,o)}this.save()}catch{}}save(){try{ZI(ob(this.path),{recursive:!0});let e=`${this.path}.tmp`;nb(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),tb(e,this.path)}catch(e){console.warn(`[GoalTaskStore] Failed to save ${this.path}: ${ab(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)}};Cn();var pb=8,eh=600*1e3,cb=4e3,Ol=1200,mb="DONE",fb=["BASH_ENV","ENV"];function gb(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function ho(t,e){return t.length<=e?t:`${t.slice(0,e-3)}...`}function mn(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(`
102
+ `)}}})}Y();function qg(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(!ge)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=ge.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 ub}from"child_process";import{createHash as Zg}from"crypto";import{existsSync as XI,mkdirSync as ZI,readFileSync as eb,renameSync as tb,writeFileSync as nb}from"fs";import{homedir as rb}from"os";import{dirname as ob,join as Gg}from"path";function ib(t){let e=t.OPENCLAW_HOME?.trim();return e||Gg(rb(),".openclaw")}function sb(t){let e=t.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||Gg(ib(t),"code-agent-goal-tasks.json")}function ab(t){return t instanceof Error?t.message:String(t)}function db(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 lb(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:db(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 Ps=class{path;tasks=new Map;constructor(e=process.env){this.path=sb(e),this.load()}load(){try{if(!XI(this.path))return;let e=eb(this.path,"utf8"),n=JSON.parse(e);if(!Array.isArray(n))return;for(let r of n){let o=lb(r);o&&this.tasks.set(o.id,o)}this.save()}catch{}}save(){try{ZI(ob(this.path),{recursive:!0});let e=`${this.path}.tmp`;nb(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),tb(e,this.path)}catch(e){console.warn(`[GoalTaskStore] Failed to save ${this.path}: ${ab(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)}};Cn();var pb=8,eh=600*1e3,cb=4e3,El=1200,mb="DONE",fb=["BASH_ENV","ENV"];function gb(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function So(t,e){return t.length<=e?t:`${t.slice(0,e-3)}...`}function mn(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(`
103
103
  `):n.slice(-e).join(`
104
- `)}function jg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hg(t){let e=t?.trim();return e&&e.length>0?e:mb}function hb(t){return t.route??zr(t.originChannel,t.originThreadId,t.originSessionKey)}function $l(t){return t.map((e,n)=>({label:e.label.trim()||`check-${n+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??eh})).filter(e=>e.command.length>0)}function Sb(t){return t.loopMode==="verifier"}function yb(t){return $l(t.verifierCommands).length>0}function zg(t){return Sb(t)&&!yb(t)}function ws(){return"Verifier-mode goal tasks require at least one verifier command."}function Qg(t){let e=t.steps.filter(n=>!n.ok).map(n=>`${n.label}:${n.exitCode}:${mn(n.output,12)}`).join(`
104
+ `)}function jg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hg(t){let e=t?.trim();return e&&e.length>0?e:mb}function hb(t){return t.route??Qr(t.originChannel,t.originThreadId,t.originSessionKey)}function Ol(t){return t.map((e,n)=>({label:e.label.trim()||`check-${n+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??eh})).filter(e=>e.command.length>0)}function Sb(t){return t.loopMode==="verifier"}function yb(t){return Ol(t.verifierCommands).length>0}function zg(t){return Sb(t)&&!yb(t)}function ws(){return"Verifier-mode goal tasks require at least one verifier command."}function Qg(t){let e=t.steps.filter(n=>!n.ok).map(n=>`${n.label}:${n.exitCode}:${mn(n.output,12)}`).join(`
105
105
  `);return Zg("sha1").update(e).digest("hex")}function kb(t){return Zg("sha1").update(mn(t,24)).digest("hex")}function Jg(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 vb(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
106
  `);let e=t.verifierCommands.map(n=>`- ${n.label}: ${n.command}`).join(`
107
107
  `);return["You are working on an autonomous goal-driven task.","","Goal:",t.goal,"","Working rules:","- Make concrete progress toward the goal in this repository.","- An external controller will run these verifier commands after your turn:",e,"- If any verifier fails, you will receive the exact failures and must continue fixing the remaining gaps.","- Do not stop early just because you think the task is probably done.","- Do not ask for confirmation unless you are blocked by a real product, architecture, or credential decision.","- Before ending a turn, run any local checks you think are useful."].join(`
@@ -117,18 +117,18 @@ Use /agent_sessions to see active sessions.`;return{text:`Error launching sessio
117
117
 
118
118
  `);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(`
119
119
  `)}function bb(t,e){let n=e.trim();if(!n)return!1;let r=new RegExp(`(^|\\n)\\s*${jg(n)}\\s*(\\n|$)`,"i"),o=new RegExp(`<promise>\\s*${jg(n)}\\s*<\\/promise>`,"i");return r.test(t)||o.test(t)}function Xg(t){return t.steps.map(e=>`${e.ok?"PASS":"FAIL"} ${e.label} (exit ${e.exitCode}, ${Math.round(e.durationMs)}ms)`).join(`
120
- `)}function Fn(t){return t instanceof Error?t.message:String(t)}function xb(t){return t==="succeeded"||t==="failed"||t==="stopped"}function Ab(t){return ho(t.error?.trim()||"Underlying session failed.",Ol)}function Rb(t=process.env){let e={...t};for(let n of fb)delete e[n];return e}function Tb(t,e){return new Promise(n=>{let r=Date.now();ub("bash",["-lc",e.command],{cwd:t,timeout:e.timeoutMs??eh,maxBuffer:1024*1024,env:Rb()},(o,i,s)=>{let a=Date.now()-r,d=typeof o?.code=="number"?o.code:o?1:0,l=`${i??""}${s?`
121
- ${s}`:""}`.trim();n({label:e.label,command:e.command,ok:!o,exitCode:d,durationMs:a,output:ho(l||"(no output)",cb)})})})}var Is=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 Ps}start(){this.started||(this.started=!0,!this.restorePromise&&(this.restorePromise=this.restoreRecoverableTasks().catch(e=>{console.warn(`[GoalController] Failed to restore recoverable tasks: ${Fn(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=$l(e.verifierCommands);if(n==="verifier"&&r.length===0)throw new Error(ws());let i={id:Ki(8),name:gb(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??pb,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:Hg(e.completionPromise),verifierCommands:r,repeatedFailureCount:0},s=await this.spawnTaskSession(i,vb(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
+ `)}function Fn(t){return t instanceof Error?t.message:String(t)}function xb(t){return t==="succeeded"||t==="failed"||t==="stopped"}function Ab(t){return So(t.error?.trim()||"Underlying session failed.",El)}function Rb(t=process.env){let e={...t};for(let n of fb)delete e[n];return e}function Tb(t,e){return new Promise(n=>{let r=Date.now();ub("bash",["-lc",e.command],{cwd:t,timeout:e.timeoutMs??eh,maxBuffer:1024*1024,env:Rb()},(o,i,s)=>{let a=Date.now()-r,d=typeof o?.code=="number"?o.code:o?1:0,l=`${i??""}${s?`
121
+ ${s}`:""}`.trim();n({label:e.label,command:e.command,ok:!o,exitCode:d,durationMs:a,output:So(l||"(no output)",cb)})})})}var Is=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 Ps}start(){this.started||(this.started=!0,!this.restorePromise&&(this.restorePromise=this.restoreRecoverableTasks().catch(e=>{console.warn(`[GoalController] Failed to restore recoverable tasks: ${Fn(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=Ol(e.verifierCommands);if(n==="verifier"&&r.length===0)throw new Error(ws());let i={id:Ki(8),name:gb(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??pb,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:Hg(e.completionPromise),verifierCommands:r,repeatedFailureCount:0},s=await this.spawnTaskSession(i,vb(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
122
 
123
123
  Goal:
124
- ${ho(i.goal,500)}`,"goal-task-started"),i}stopTask(e){let n=this.store.get(e);if(n)return xb(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}=sr({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:hb(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(`
125
- `));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(zg(e)){this.markTaskFailed(e,ws());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,Yg(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: ${Fn(r)}`)}}}async runVerifiers(e){let n=$l(e.verifierCommands);if(n.length===0){let s={status:"fail",steps:[{label:"verifier-config",command:"(none configured)",ok:!1,exitCode:1,durationMs:0,output:ws()}],summary:"",fingerprint:""};return s.fingerprint=Qg(s),s.summary=Xg(s),s}let r=[];for(let s of n)r.push(await Tb(e.workdir,s));let i={status:r.every(s=>s.ok)?"pass":"fail",steps:r,summary:"",fingerprint:""};return i.fingerprint=Qg(i),i.summary=Xg(i),i}notify(e,n,r){this.sessionManager.emitGoalTaskUpdate(e,n,r)}notifyIterationStatus(e,n,r){let o=un(r??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0)),i=`${n}
124
+ ${So(i.goal,500)}`,"goal-task-started"),i}stopTask(e){let n=this.store.get(e);if(n)return xb(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}=sr({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:hb(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(`
125
+ `));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(zg(e)){this.markTaskFailed(e,ws());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,Yg(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: ${Fn(r)}`)}}}async runVerifiers(e){let n=Ol(e.verifierCommands);if(n.length===0){let s={status:"fail",steps:[{label:"verifier-config",command:"(none configured)",ok:!1,exitCode:1,durationMs:0,output:ws()}],summary:"",fingerprint:""};return s.fingerprint=Qg(s),s.summary=Xg(s),s}let r=[];for(let s of n)r.push(await Tb(e.workdir,s));let i={status:r.every(s=>s.ok)?"pass":"fail",steps:r,summary:"",fingerprint:""};return i.fingerprint=Qg(i),i.summary=Xg(i),i}notify(e,n,r){this.sessionManager.emitGoalTaskUpdate(e,n,r)}notifyIterationStatus(e,n,r){let o=un(r??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0)),i=`${n}
126
126
 
127
- ${pn(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}): ${Fn(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=ho(n,Ol),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u274C [${e.name}] Goal task failed
127
+ ${pn(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}): ${Fn(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=So(n,El),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u274C [${e.name}] Goal task failed
128
128
 
129
129
  ${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
130
130
 
131
- ${n}`,"goal-task-succeeded")}markTaskStopped(e,n){e.status="stopped",e.failureReason=ho(n,Ol),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u26D4 [${e.name}] Goal task stopped
131
+ ${n}`,"goal-task-succeeded")}markTaskStopped(e,n){e.status="stopped",e.failureReason=So(n,El),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u26D4 [${e.name}] Goal task stopped
132
132
 
133
133
  ${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(`
134
134
  `),o=Jg(r);if(!o){this.markTaskFailedWaitingForUser(e,mn(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: ${Fn(o)}`)}}async handleTerminalSession(e,n){if(n.status==="failed"){this.markTaskFailed(e,Ab(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,31 +137,31 @@ ${e.failureReason}`,"goal-task-stopped")}async handleRunningSession(e,n){if(n.pe
137
137
  `));return}await this.resumeAfterIdleTimeout(e,n,Yg(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(`
138
138
  `),s=Hg(e.completionPromise);if(bb(i,s)){if(e.verifierCommands.length===0){this.markTaskSucceeded(e,`Completion promise "${s}" detected in agent output.`);return}let u=await this.runVerifiers(e);if(e.lastVerifierSummary=u.summary,e.updatedAt=Date.now(),u.status==="pass"){this.markTaskSucceeded(e,[`Completion promise "${s}" detected.`,u.summary].join(`
139
139
  `));return}if(e.lastVerifierFingerprint===u.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=u.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}).`,u.summary].join(`
140
- `));return}e.iteration+=1;let f=Ib(e,u);try{let S=await this.resumeTaskSession(e,f,n);this.setTaskRunningWithSession(e,S),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Completion claimed but verifiers still failed`),this.scheduleTaskEvaluation(e.id,"ralph-verifier-resume",S.id)}catch(S){this.markTaskFailed(e,`Failed to resume the Ralph goal task after verifier failure: ${Fn(S)}`)}return}let d=kb(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:",mn(i,20)||"(no output)"].join(`
140
+ `));return}e.iteration+=1;let f=Ib(e,u);try{let g=await this.resumeTaskSession(e,f,n);this.setTaskRunningWithSession(e,g),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Completion claimed but verifiers still failed`),this.scheduleTaskEvaluation(e.id,"ralph-verifier-resume",g.id)}catch(g){this.markTaskFailed(e,`Failed to resume the Ralph goal task after verifier failure: ${Fn(g)}`)}return}let d=kb(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:",mn(i,20)||"(no output)"].join(`
141
141
  `));return}e.iteration+=1;let l=wb(e,i);try{let u=await this.resumeTaskSession(e,l,n);this.setTaskRunningWithSession(e,u),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Ralph iteration continued`),this.scheduleTaskEvaluation(e.id,"ralph-continue",u.id)}catch(u){this.markTaskFailed(e,`Failed to continue the Ralph goal task: ${Fn(u)}`)}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(`
142
- `));return}e.iteration+=1;let o=Pb(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: ${Fn(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(zg(e)){this.markTaskFailed(e,ws());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)}}}}};Te();import{existsSync as Cb,realpathSync as Mb}from"fs";import{resolve as _b}from"path";function th(t){if(!t)return;let e=_b(t);try{if(Cb(e))return Mb.native(e)}catch{}return e}function bs(t,e){return!t||!e?!1:th(t)===th(e)}he();Te();import{existsSync as Eb}from"fs";he();rt();function nh(t){return t instanceof Error?t.message:String(t)}function Ob(t){let e=t.worktreeStrategy??_.defaultWorktreeStrategy;return!!e&&e!=="off"&&il(Ei({harnessName:t.harness??Le(),backendRef:t.backendRef}))}function $b(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(`
143
- `);return(t??"")+o}function Db(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=Yi(r.worktreePath);return r.workdir&&s&&bs(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=Af(Ei({persistedHarness:r.harness,backendRef:r.backendRef}))&&!!r.backendRef?.worktreePath;if(Eb(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{Zi(o);let s=fl(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: ${nh(s)}, using original workdir`),{actualWorkdir:o,originalWorkdir:o,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom}}}function rh(t,e,n){let{actualWorkdir:r,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}=Db(t,n);a&&(t.resumeSessionId=void 0),d&&(t.resumeWorktreeFrom=void 0),r??=t.workdir,o??=t.workdir;let l=!!(t.resumeSessionId??t.resumeWorktreeFrom),u=t.worktreeStrategy??_.defaultWorktreeStrategy;u&&(t.worktreeStrategy=u);let f=Ob(t),S=!t.resumeSessionId&&!i&&u&&u!=="off"&&!f;if(f&&!pl(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${u}" requires a git worktree, but "${o}" is not a git repository.`);if(S&&pl(o)){if(!Qf(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=fl(o,e),r=i,s=Xi(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);console.log(`[SessionManager] Created worktree at ${i}`)}catch(y){throw new Error(`Cannot launch session "${e}": worktree creation failed: ${nh(y)}`)}}else if(S)throw new Error(`Cannot launch session "${e}": worktree strategy "${u}" requires a git worktree, but "${o}" is not a git repository.`);return l&&i&&(r=i),{actualWorkdir:r,originalWorkdir:o,effectiveSystemPrompt:i&&s?$b(t.systemPrompt,o,i,s):t.systemPrompt,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}}var xs=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,n){return rh(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)}};he();var As=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=M(e),o=M(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(ne(o)===e||M(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)}};he();var Nb=new Set(["starting","running"]),Rs=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=>M(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?M(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),Nb.has(i.status)&&(!r||i.startedAt>r.startedAt)&&(r=i));return r??o}};he();he();rt();var Ts=class{constructor(e){this.deps=e}deps;async plan(e){let n=ne(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??ln(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=On(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 Dl(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function Cs(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:Dl(t,{state:"pending_decision",updatedAt:n,notes:e.notes})};return e.clearResolverSessionId&&(r.autoMergeResolverSessionId=void 0),r}function oh(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:Dl(t,{state:"merge_conflict_resolving",updatedAt:o,notes:r.notes})}}function ih(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:Dl(t,{state:"merged",updatedAt:n,resolvedAt:r,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}rt();var Ms=class{constructor(e){this.deps=e;this.actions=new Ts({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(`
142
+ `));return}e.iteration+=1;let o=Pb(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: ${Fn(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(zg(e)){this.markTaskFailed(e,ws());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)}}}}};Te();import{existsSync as Cb,realpathSync as Mb}from"fs";import{resolve as _b}from"path";function th(t){if(!t)return;let e=_b(t);try{if(Cb(e))return Mb.native(e)}catch{}return e}function bs(t,e){return!t||!e?!1:th(t)===th(e)}he();Te();import{existsSync as Eb}from"fs";he();rt();function nh(t){return t instanceof Error?t.message:String(t)}function Ob(t){let e=t.worktreeStrategy??_.defaultWorktreeStrategy;return!!e&&e!=="off"&&il(Oi({harnessName:t.harness??Le(),backendRef:t.backendRef}))}function $b(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(`
143
+ `);return(t??"")+o}function Db(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=Yi(r.worktreePath);return r.workdir&&s&&bs(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=xf(Oi({persistedHarness:r.harness,backendRef:r.backendRef}))&&!!r.backendRef?.worktreePath;if(Eb(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{Zi(o);let s=fl(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: ${nh(s)}, using original workdir`),{actualWorkdir:o,originalWorkdir:o,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom}}}function rh(t,e,n){let{actualWorkdir:r,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}=Db(t,n);a&&(t.resumeSessionId=void 0),d&&(t.resumeWorktreeFrom=void 0),r??=t.workdir,o??=t.workdir;let l=!!(t.resumeSessionId??t.resumeWorktreeFrom),u=t.worktreeStrategy??_.defaultWorktreeStrategy;u&&(t.worktreeStrategy=u);let f=Ob(t),g=!t.resumeSessionId&&!i&&u&&u!=="off"&&!f;if(f&&!pl(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${u}" requires a git worktree, but "${o}" is not a git repository.`);if(g&&pl(o)){if(!zf(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=fl(o,e),r=i,s=Xi(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);console.log(`[SessionManager] Created worktree at ${i}`)}catch(y){throw new Error(`Cannot launch session "${e}": worktree creation failed: ${nh(y)}`)}}else if(g)throw new Error(`Cannot launch session "${e}": worktree strategy "${u}" requires a git worktree, but "${o}" is not a git repository.`);return l&&i&&(r=i),{actualWorkdir:r,originalWorkdir:o,effectiveSystemPrompt:i&&s?$b(t.systemPrompt,o,i,s):t.systemPrompt,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}}var xs=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,n){return rh(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)}};he();var As=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=M(e),o=M(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(ne(o)===e||M(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)}};he();var Nb=new Set(["starting","running"]),Rs=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=>M(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?M(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),Nb.has(i.status)&&(!r||i.startedAt>r.startedAt)&&(r=i));return r??o}};he();he();rt();var Ts=class{constructor(e){this.deps=e}deps;async plan(e){let n=ne(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??ln(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=On(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 $l(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function Cs(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:$l(t,{state:"pending_decision",updatedAt:n,notes:e.notes})};return e.clearResolverSessionId&&(r.autoMergeResolverSessionId=void 0),r}function oh(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:$l(t,{state:"merge_conflict_resolving",updatedAt:o,notes:r.notes})}}function ih(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:$l(t,{state:"merged",updatedAt:n,resolvedAt:r,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}rt();var Ms=class{constructor(e){this.deps=e;this.actions=new Ts({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(`
144
144
  `)}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(`
145
145
  `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}updatePersistedSessionFor(e,n){for(let r of tt(e))this.deps.updatePersistedSession(r,n)}markPendingDecision(e,n={}){this.updatePersistedSessionFor(e,Cs(e,n))}markAutoMergeConflictResolving(e,n,r){this.updatePersistedSessionFor(e,oh(e,n,r,{notes:[`resolver_session:${n}`]}))}markMerged(e){this.updatePersistedSessionFor(e,ih(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:nt(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){Dt(n,r),this.markMerged(e);let d=$n({kind:"merge",branch:r,base:o,filesChanged:i.filesChanged,insertions:i.insertions,deletions:i.deletions});s.stashPopConflict?d+=`
146
146
  \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+=`
147
147
  (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(`
148
- `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}async handleAutoMergeStrategy(e,n,r,o,i,s,a=ne(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 mx,writeFileSync as fx}from"fs";Cn();import{randomUUID as Fb}from"crypto";function Lb(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var _s=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:Fb(),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||!Lb(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?.()}};he();he();var Es=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?M(s):void 0)??r}let o=this.getLatestPersistedByName(e);if(o)return M(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(e);if(i){let s=this.indexes.persisted.get(i);return(s?M(s):void 0)??i}if(this.indexes.persisted.has(e)){let s=this.indexes.persisted.get(e);return s?M(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 dx,mkdirSync as lx,readFileSync as ux,readdirSync as Fl,renameSync as ch,statSync as mh,unlinkSync as fh,writeFileSync as gh}from"fs";import{tmpdir as Ll}from"os";import{dirname as px,join as Ns}from"path";import{homedir as Wb}from"node:os";import{join as Bb}from"node:path";function sh(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let n=t.HOME?.trim()||Wb();return Bb(n,".openclaw")}Cn();var Os=6,Ub=new Set(["running","completed","failed","killed"]);function So(t){return!!t&&typeof t=="object"}function hr(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 Kb(t){return typeof t=="string"&&yg.has(t)?t:void 0}function ah(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function Vb(t){return t==="never"||t==="on-request"?"never":void 0}function qb(t){return t==="approve"||t==="ask"||t==="delegate"?t:void 0}function Gb(t){if(t==="plan-mode"||t==="codex-first-turn-plan"||t==="soft-plan")return"plan-mode"}function dh(t){return typeof t=="string"&&ps.has(t)?t:void 0}function jb(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function Hb(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 zb(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function Qb(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 Jb(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 Yb(t){return t==="live"||t==="stopped"?t:void 0}function Xb(t){return t==="not_sent"||t==="sending"||t==="delivered"||t==="fallback_delivered"||t==="failed"?t:void 0}function Zb(t){return t==="direct-telegram"?"direct-message":t==="none"||t==="direct-message"||t==="wake-only"?t:void 0}function ex(t){return t==="none"||t==="canonical_buttons"||t==="explicit_fallback_text"?t:void 0}function tx(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function nx(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 rx(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"||t==="plan-offer-start"||t==="plan-offer-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 lh(t){if(!So(t))return;let e=x(t.provider),n=x(t.accountId),r=x(t.target),o=x(t.threadId),i=x(t.sessionKey);if(!(!e||!r))return{provider:e,accountId:n,target:r,threadId:o,sessionKey:i}}function ox(t,e,n){if(So(t)){let r=x(t.kind),o=x(t.conversationId);if(o&&(r==="claude-code"||r==="codex-app-server"))return{kind:r,conversationId:o,runId:x(t.runId),worktreeId:x(t.worktreeId),worktreePath:x(t.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:n}}function ix(t){if(!So(t))return;let e=Jb(t.state),n=x(t.updatedAt);if(!e||!n)return;let r=x(t.resolutionSource);return{state:e,updatedAt:n,resolvedAt:x(t.resolvedAt),resolutionSource:r==="agent_merge"||r==="agent_pr"||r==="strategy_no_change"||r==="lifecycle_resolver"||r==="dismiss"||r==="maintenance"?r: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 sx(t){let e=new Date(0).toISOString(),n=x(t.worktreeMergedAt)??x(t.worktreeDismissedAt)??x(t.pendingWorktreeDecisionSince)??e;if(t.worktreeMerged===!0)return{state:"merged",updatedAt:n,resolvedAt:x(t.worktreeMergedAt)??n,resolutionSource:"agent_merge",baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:n,resolvedAt:x(t.worktreeDismissedAt)??n,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:n,resolvedAt:n,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:n,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:n,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:n,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(x(t.worktreePath)||x(t.worktreeBranch))return{state:"provisioned",updatedAt:n,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)}}function ax(t){if(typeof t=="string"&&Ub.has(t))return t==="running"?"killed":t}function uh(t){if(!So(t))return;let e=hr(t.harnessSessionId);if(!e)return;let n=ax(t.status);if(!n)return;let r=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=lh(t.route);if(!l)return;let u=rr({route:l,originChannel:s,originThreadId:a,originSessionKey:d});if(!u||o&&!i)return;let f=x(t.harness),S=ox(t.backendRef,f,e),y=ix(t.worktreeLifecycle)??sx(t);return{sessionId:x(t.sessionId),harnessSessionId:e,backendRef:S,name:hr(t.name,e),prompt:hr(t.prompt),workdir:hr(t.workdir,"(unknown)"),model:x(t.model),reasoningEffort:Kb(t.reasoningEffort),createdAt:je(t.createdAt),completedAt:je(t.completedAt),status:n,lifecycle:r?"suspended":Hb(t.lifecycle),approvalState:zb(t.approvalState),worktreeState:Qb(t.worktreeState),runtimeState:r?"stopped":Yb(t.runtimeState),deliveryState:tx(t.deliveryState),completionWakeIssuedAt:x(t.completionWakeIssuedAt),completionWakeSucceededAt:x(t.completionWakeSucceededAt),completionWakeFailedAt:x(t.completionWakeFailedAt),completionWakeSummaryRequired:t.completionWakeSummaryRequired===!0?!0:void 0,killReason:jb(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:u,outputPath:x(t.outputPath),harness:f,requestedPermissionMode:ah(t.requestedPermissionMode),currentPermissionMode:ah(t.currentPermissionMode),approvalExecutionState:nx(t.approvalExecutionState),approvalRationale:x(t.approvalRationale),planModeApproved:t.planModeApproved===!0,pendingPlanApproval:t.pendingPlanApproval===!0,planApprovalContext:Gb(t.planApprovalContext),planDecisionVersion:je(t.planDecisionVersion),actionablePlanDecisionVersion:je(t.actionablePlanDecisionVersion),canonicalPlanPromptVersion:je(t.canonicalPlanPromptVersion),approvalPromptRequiredVersion:je(t.approvalPromptRequiredVersion),approvalPromptVersion:je(t.approvalPromptVersion),approvalPromptStatus:Xb(t.approvalPromptStatus),approvalPromptTransport:Zb(t.approvalPromptTransport),approvalPromptMessageKind:ex(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:x(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:x(t.approvalPromptDeliveredAt),approvalPromptFailedAt:x(t.approvalPromptFailedAt),planApproval:qb(t.planApproval),codexApprovalPolicy:Vb(t.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:dh(t.worktreeStrategy),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:y,resumable:r?!0:t.resumable===!0}}function ph(t){if(!So(t))return;let e=rx(t.kind),n=hr(t.id),r=hr(t.sessionId),o=je(t.createdAt);if(!(!n||!r||!e||o==null))return{id:n,sessionId:r,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:lh(t.route),launchName:x(t.launchName),launchPrompt:x(t.launchPrompt),launchWorkdir:x(t.launchWorkdir),launchWorktreeStrategy:dh(t.launchWorktreeStrategy)}}function $s(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 Nl(t){return!!t&&typeof t=="object"}function Wl(t){return t instanceof Error?t.message:String(t)}function hh(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||Ns(sh(t),"code-agent-sessions.json")}function Sh(t,e,n){try{lx(px(t),{recursive:!0});let r=t+".tmp";gh(r,JSON.stringify({schemaVersion:Os,sessions:e,actionTokens:n},null,2),"utf-8"),ch(r,t)}catch(r){console.warn(`[SessionStore] Failed to save session index: ${Wl(r)}`)}}function Ds(t,e){try{if(!dx(t))return;let n=`${t}.legacy-${Date.now()}.json`;ch(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: ${Wl(n)}`)}}function cx(t,e){try{if(e.length===0)return;let n=`${t}.codex-sdk-legacy-${Date.now()}.json`;gh(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: ${Wl(n)}`)}}function yh(t,e){try{let n=Ll(),r=Fl(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r)try{let i=Ns(n,o),s=mh(i).mtimeMs;t-s>e&&fh(i)}catch{}}catch{}}function kh(t,e){try{let n=Ll(),r=Fl(n).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of r)try{let s=Ns(n,i),a=mh(s).mtimeMs+e;if(a<=t)return t;o=o==null?a:Math.min(o,a)}catch{}return o}catch{return}}function vh(t){try{let e=new Set(t),n=Ll(),r=Fl(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r){let i=Ns(n,o);if(!e.has(i))try{fh(i)}catch{}}}catch{}}function Ph(t){let{indexPath:e,clearAll:n,indexPersistedEntry:r,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:s}=t;try{let a=ux(e,"utf-8"),d=JSON.parse(a);if(Array.isArray(d)){Ds(e,"legacy array store"),s();return}if(!Nl(d)||d.schemaVersion!==Os&&d.schemaVersion!==4){Ds(e,`schema mismatch (expected v${Os})`),s();return}let l=Array.isArray(d.sessions)?d.sessions:[],u=[];for(let S of l){if(Nl(S)&&S.harness==="codex"){let k=Nl(S.backendRef)?S.backendRef:void 0;if((typeof k?.kind=="string"?k.kind:void 0)!=="codex-app-server"){u.push(S);continue}}let y=uh(S);if(!y){n(),Ds(e,"invalid v4 session entry"),s();return}r(y)}u.length>0&&(cx(e,u),s());let f=Array.isArray(d.actionTokens)?d.actionTokens:[];for(let S of f){let y=ph(S);if(!y){n(),Ds(e,"invalid v4 action token"),s();return}o(y)}i()}catch{}}var gx=new Set(["completed","failed","killed"]),Bl=1440*60*1e3;function hx(t){return t instanceof Error?t.message:String(t)}var Fs=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??hh(n),this.actionTokenStore=new _s(()=>this.saveIndex(),Bl),this.actionTokens=this.actionTokenStore.tokens,this.queries=new Es({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(){Ph({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(){Sh(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){$s(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){return e.backendRef??{kind:ol(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=M(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=rr({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};$s(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=rr({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!r)return;let o;try{let s=pr(e.id);if(mx(s))o=s;else{let a=e.getOutput().join(`
149
- `);a.length>0&&(fx(s,a,"utf-8"),o=s)}}catch(s){console.warn(`[SessionStore] Failed to write output file for session ${e.id}: ${hx(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};$s(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),yh(e,Bl)}getNextTmpOutputCleanupAt(e){return kh(e,Bl)}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||!gx.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(){vh(this.getReferencedOutputPaths())}};var Sx=new Set(["completed","failed","killed"]),Ls=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),Sx.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 Ih from"child_process";var wh=5e3,yx={execFile:Ih.execFile},fn=class extends Error{constructor(e){super(e),this.name="MissingRuntimeDirectNotificationCapabilityError"}},Ws=class{constructor(e=yx.execFile){this.execFile=e}execFile;async send(e,n,r){q("direct_send_started",{...gt(e),messageTextLength:n.length,...se(r)});try{await this.sendViaRuntime(e,n,r),q("direct_send_succeeded",{...gt(e),deliveryPath:"runtime",...se(r)});return}catch(o){if(!(o instanceof fn))throw q("direct_send_failed",{...gt(e),deliveryPath:"runtime",...se(r),error:Ul(o)}),o;q("direct_send_runtime_capability_missing",{...gt(e),deliveryPath:"runtime",...se(r),reason:o.message}),await this.sendViaBoundedCliFallback(e,n,r,o.message),q("direct_send_succeeded",{...gt(e),deliveryPath:"cli-fallback",...se(r)})}}async sendViaRuntime(e,n,r){let o=Li(),i=Nf(),s=o?.channel?.outbound?.loadAdapter;if(!o)throw new fn("OpenClaw plugin runtime is unavailable for direct notification delivery");if(i==null)throw new fn("OpenClaw runtime config snapshot is unavailable for direct notification delivery");if(!o.channel)throw new fn(`OpenClaw plugin runtime channel surface is unavailable for direct notification delivery (runtimeVersion=${Kl(o)})`);if(!o.channel.outbound)throw new fn(`OpenClaw plugin runtime channel outbound surface is unavailable for direct notification delivery (runtimeVersion=${Kl(o)})`);if(!s)throw new fn(`OpenClaw plugin runtime channel outbound loadAdapter is unavailable for direct notification delivery (runtimeVersion=${Kl(o)})`);let a=await s(e.channel);if(!a)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" is unavailable`);let d=Bs(r);if(q("runtime_adapter_loaded",{...gt(e),adapterHasRenderPresentation:typeof a.renderPresentation=="function",adapterHasSendPayload:typeof a.sendPayload=="function",adapterHasSendText:typeof a.sendText=="function",...se(r),...d?Rl(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=vx(i),a={text:o,presentation:i,interactive:s};q("presentation_render_started",{...gt(r),messageTextLength:o.length,adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...Rl(i)});let d={cfg:n,to:r.target,text:o,payload:a,accountId:r.accountId,threadId:r.threadId},l=e.renderPresentation?await e.renderPresentation({payload:a,presentation:i,ctx:d}):a,u=wx(l,s);if(q("presentation_render_completed",{...gt(r),adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...Tl(u)}),!u||typeof u!="object"||!e.sendPayload)throw new Error(`OpenClaw outbound adapter for channel "${r.channel}" cannot preserve interactive presentation`);let f=await e.sendPayload({...d,payload:u});q("presentation_send_payload_completed",{...gt(r),...Tl(u),...Og(f)})}sendViaBoundedCliFallback(e,n,r,o){return new Promise((i,s)=>{let a=kx(e,n,r);q("direct_send_cli_fallback_started",{...gt(e),deliveryPath:"cli-fallback",reason:o,messageTextLength:n.length,...se(r)}),this.execFile("openclaw",a,{timeout:wh,killSignal:"SIGKILL"},(d,l,u)=>{if(!d){q("direct_send_cli_fallback_completed",{...gt(e),deliveryPath:"cli-fallback",...se(r)}),i();return}let f=u?.trim()?` | stderr: ${u.trim()}`:"";q("direct_send_cli_fallback_failed",{...gt(e),deliveryPath:"cli-fallback",...se(r),error:Ul(d),stderrLength:u?.length}),s(new Error(`${o}; bounded openclaw message send fallback failed within ${wh}ms timeout: ${Ul(d)}${f}`))})})}};function gt(t){return{channel:t.channel,target:t.target,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey}}function kx(t,e,n){let r=Bs(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 Ul(t){return t instanceof Error?t.message:String(t)}function Kl(t){if(!t||typeof t!="object")return"unknown";let e=t.version;return typeof e=="string"&&e.trim()?e:"unknown"}function Bs(t){let e=(t??[]).filter(n=>Array.isArray(n)&&n.length>0).map(n=>({type:"buttons",buttons:n.map(r=>({label:r.label,value:Ix(r.callbackData),...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function vx(t){let e=t.blocks.filter(n=>n.type==="buttons"&&n.buttons.length>0).map(n=>({type:"buttons",buttons:n.buttons.map(r=>({label:r.label,value:r.value,...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function Px(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t.interactive;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.blocks;return Array.isArray(n)&&n.some(r=>{if(!r||typeof r!="object"||Array.isArray(r))return!1;let o=r;return o.type==="buttons"&&Array.isArray(o.buttons)&&o.buttons.length>0})}function wx(t,e){return!e||Px(t)||!t||typeof t!="object"||Array.isArray(t)?t:{...t,interactive:e}}function Ix(t){return t.startsWith(`${ot}:`)?t:`${ot}:${t}`}import*as bh from"child_process";var Sr=class{tails=new Map;enqueue(e,n,r){let o=this.tails.get(e);o!==void 0&&r?.();let s=(o?.catch(()=>{})??Promise.resolve()).then(()=>n()),a=s.catch(()=>{});return this.tails.set(e,a),a.finally(()=>{this.tails.get(e)===a&&this.tails.delete(e)}),s}clear(){this.tails.clear()}};var Vl=3e4,bx=2e3,xx=2e4,ht=4;function yo(t){return t instanceof Error?t.message:String(t)}function Ax(){return new Error(`Dispatch timed out after ${Vl}ms`)}function Rx(t){if(!(t instanceof Error))return!1;let e=t;return e.killed===!0&&e.signal==="SIGKILL"}var Tx={execFile:bh.execFile},Us=class{pendingRetryTimers=new Map;orderedDispatches=new Sr;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.orderedDispatches.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||n.shouldContinue?.()===!1){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}),Tx.execFile("openclaw",e,{timeout:Vl,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.shouldContinue?.()!==!1&&n.onSuccess?.(),r?.();return}let u=d?.trim()?` | stderr: ${d.trim()}`:"";if(n.target==="message.send"&&Rx(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:`${yo(s)}${u}`,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:`${yo(s)}${u}`,terminal:!0}),n.onFinalFailure?.(),r?.();return}let S=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:S,error:`${yo(s)}${u}`});let y={timer:setTimeout(()=>{let k=this.pendingRetryTimers.get(n.sessionId);if(k&&(k.delete(y),k.size===0&&this.pendingRetryTimers.delete(n.sessionId)),n.shouldContinue?.()===!1){r?.();return}this.executeNow(e,n,r,o+1)},S),onCleared:r};y.timer.unref?.(),this.pendingRetryTimers.has(n.sessionId)||this.pendingRetryTimers.set(n.sessionId,new Set),this.pendingRetryTimers.get(n.sessionId).add(y)})}executePromiseNow(e,n,r,o=1){if(this.disposed||n.shouldContinue?.()===!1){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.shouldContinue?.()!==!1&&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:yo(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:yo(s)});let l={timer:setTimeout(()=>{let u=this.pendingRetryTimers.get(n.sessionId);if(u&&(u.delete(l),u.size===0&&this.pendingRetryTimers.delete(n.sessionId)),n.shouldContinue?.()===!1){r?.();return}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(Ax()))},Vl);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=bx*2**n;return Math.min(r,xx)}enqueueOrderedDispatch(e,n){this.orderedDispatches.enqueue(e,async()=>{this.disposed||await new Promise(r=>{let o=!1;n(()=>{o||(o=!0,r())})})})}log(e,n,r){let o=`[WakeDispatcher] ${JSON.stringify({event:n,...r})}`;if(e==="error"){console.error(o);return}console.info(o)}};Cn();var Ks=class{resolve(e){let n=Si(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 Cx}from"crypto";var Vs=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:Cx()})]}buildDirectNotificationArgs(e,n,r){let o=Bs(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 qs=class{routes=new Ks;transport;directNotifications;executor=new Us;constructor(e={}){this.transport=e.transport??new Vs(e.transportOptions),this.directNotifications=e.directNotifications===void 0?new Ws: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,a){let d=this.routes.resolve(e),l=a;if(l?.()===!1)return;let u=d?.sessionKey?.trim();if(!u){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,shouldContinue:l});return}this.executor.execute(this.transport.buildChatSendArgs(u,n,!0),{label:r,sessionId:e.id,target:"chat.send",phase:o,routeSummary:`session:${u}`,messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:`session:${u}`,route:d,text:n}),onSuccess:s,shouldContinue:l,onFinalFailure:()=>{l?.()!==!1&&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,shouldContinue:l})}})}sendUserNotification(e,n,r,o,i,s,a=!1,d){if(d?.()===!1)return;let l=!!o?.some(k=>Array.isArray(k)&&k.length>0),u=this.routes.resolve(e);q("wake_notify_selected",{sessionId:e.id,sessionName:e.name,label:r,messageTextLength:n.length,requireDirectDelivery:a,hasDirectNotificationTransport:!!this.directNotifications,routeSummary:u?this.routes.summary(u):"system",channel:u?.channel,target:u?.target,accountId:u?.accountId,threadId:u?.threadId,sessionKey:u?.sessionKey,...se(o)});let f=u?`notify:${u.channel}|${u.accountId??""}|${u.target}|${u.threadId??""}`:`notify:system:${e.id}`;if(!u){if(q("wake_notify_no_direct_route",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:l,...se(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(l){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:f,onSuccess:s,onFinalFailure:i,shouldContinue:d});return}let S=()=>{if(q("wake_notify_direct_failed",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:l,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...se(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(l){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:f,onSuccess:s,onFinalFailure:i,shouldContinue:d})},y={label:`${r}-notify`,sessionId:e.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(u),messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:this.routes.summary(u),route:u,text:n,buttons:o}),orderingKey:f,onSuccess:s,onAmbiguousResult:S,onFinalFailure:S,terminalOnFailure:this.directNotifications?!0:void 0,shouldContinue:d};if(this.directNotifications){q("wake_notify_dispatching_direct_runtime",{sessionId:e.id,sessionName:e.name,label:r,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...se(o)}),this.executor.executePromise(()=>this.directNotifications.send(u,n,o),y);return}q("wake_notify_dispatching_cli_message_send",{sessionId:e.id,sessionName:e.name,label:r,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...se(o)}),this.executor.execute(this.transport.buildDirectNotificationArgs(u,n,o),y)}sendUserNotificationSequence(e,n,r,o,i,s=!1,a){let d=n.map(u=>({text:u.text.trim(),buttons:u.buttons})).filter(u=>u.text.length>0);if(d.length===0){o?.();return}q("wake_notify_sequence_started",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:d.length,buttonChunkIndexes:d.map((u,f)=>u.buttons?.some(S=>Array.isArray(S)&&S.length>0)?f+1:void 0).filter(u=>typeof u=="number"),requireDirectDelivery:s});let l=u=>{if(a?.()===!1)return;let f=d[u];if(!f){q("wake_notify_sequence_succeeded",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:d.length}),i?.();return}let S=u===0?o:i;q("wake_notify_sequence_chunk_selected",{sessionId:e.id,sessionName:e.name,label:r,chunkIndex:u+1,chunkCount:d.length,messageTextLength:f.text.length,failureHandler:u===0?"all-failed":"sequence-success",...se(f.buttons)}),this.sendUserNotification(e,f.text,`${r}-part-${u+1}`,f.buttons,S,()=>l(u+1),s,a)};l(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(u=>({text:u.text.trim(),buttons:u.buttons})).filter(u=>u.text.length>0),a=s[0]?.text,d=n.wakeMessage?.trim(),l=n.shouldDispatch;if(o){let u=n.wakeMessageOnNotifySuccess?.trim(),f=n.wakeMessageOnNotifyFailed?.trim(),S=b=>{b&&l?.()!==!1&&(r?.onWakeStarted?.(),this.sendWake(e,b,`${n.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded,l))},y=()=>{l?.()!==!1&&(r?.onNotifySucceeded?.(),u&&S(u))},k=f?()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.(),S(f))}:()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.())};if(s.length>0){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,k,y,n.requireDirectUserNotification===!0,l)}else k();return}if(i==="always"&&s.length>0){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.())},()=>{l?.()!==!1&&r?.onNotifySucceeded?.()},n.requireDirectUserNotification===!0,l)}if(d&&l?.()!==!1){if(r?.onWakeStarted?.(),i==="on-wake-fallback"&&s.length>0&&!this.routes.resolve(e)?.sessionKey){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.())},()=>{l?.()!==!1&&r?.onNotifySucceeded?.()},!1,l)}this.sendWake(e,d,`${n.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded,l)}}};var Gs=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"plan-offer-start":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 q("plan_approval_buttons_created",{sessionId:e,planDecisionVersion:n?.planDecisionVersion,...se(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}))]}getPlanOfferButtons(e){let{offerId:n,route:r,planName:o,planPrompt:i,planWorkdir:s,planWorktreeStrategy:a}=e,d=[[this.makeActionButton(n,"plan-offer-start","Start Plan",{route:r,launchName:o,launchPrompt:i,launchWorkdir:s,launchWorktreeStrategy:a}),this.makeActionButton(n,"plan-offer-dismiss","Dismiss",{route:r})]];return q("plan_offer_buttons_created",{offerId: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,...se(d)}),d}};he();var js=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 ne(e)??M(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}}};rt();import{existsSync as Mx}from"fs";var Hs=class{getCompletionState(e,n,r,o){return cl(e,r,o)?"has-commits":cl(e,o,r)?"base-advanced":cr(n)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(e,n,r){if(!e.worktreePath||!e.workdir||!Mx(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 zs=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}`,u=[`[ASK USER QUESTION] Session "${e.name}" has a question requiring user input.`,"",`Question: ${s.question}`,...a.length>0?["Options:",...a.map((f,S)=>` ${S+1}. ${f.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
150
- `);return new Promise((f,S)=>{let y=setTimeout(()=>{this.pendingQuestions.delete(e.id),S(new Error(`AskUserQuestion timed out after 600s for session "${e.name}"`))},6e5);y.unref?.(),this.pendingQuestions.set(e.id,{resolve:f,reject:S,questions:i,timeoutHandle:y}),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:u})})}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 _x(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 Qs(t){let e=_x(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function ko(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 Ex(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function ql(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 Ox(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 Gl(t){let{session:e,originThreadLine:n,preview:r}=t,o=`$${(e.costUsd??0).toFixed(2)}`,i=Tt(e.duration),s=Ex(),a=d=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,n,...Qs(e),"","Output preview:",r,"",...Ox({contract:s,canonicalStatusDelivered:d}),"",...ql({sessionId:e.id,canonicalStatusDelivered:d})].join(`
152
- `);return{userMessage:`\u2705 [${e.name}] Completed | ${o} | ${i}`,wakeMessageOnNotifySuccess:a(!0),wakeMessageOnNotifyFailed:a(!1),followupContract:s}}function jl(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)}`,u=Tt(e.duration);return{userMessage:[`\u274C [${e.name}] Failed | ${l} | ${u}`,` \u26A0\uFE0F ${r}`].join(`
148
+ `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}async handleAutoMergeStrategy(e,n,r,o,i,s,a=ne(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 mx,writeFileSync as fx}from"fs";Cn();import{randomUUID as Fb}from"crypto";function Lb(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var _s=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:Fb(),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||!Lb(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?.()}};he();he();var Es=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?M(s):void 0)??r}let o=this.getLatestPersistedByName(e);if(o)return M(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(e);if(i){let s=this.indexes.persisted.get(i);return(s?M(s):void 0)??i}if(this.indexes.persisted.has(e)){let s=this.indexes.persisted.get(e);return s?M(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 dx,mkdirSync as lx,readFileSync as ux,readdirSync as Nl,renameSync as ch,statSync as mh,unlinkSync as fh,writeFileSync as gh}from"fs";import{tmpdir as Fl}from"os";import{dirname as px,join as Ns}from"path";import{homedir as Wb}from"node:os";import{join as Bb}from"node:path";function sh(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let n=t.HOME?.trim()||Wb();return Bb(n,".openclaw")}Cn();var Os=6,Ub=new Set(["running","completed","failed","killed"]);function yo(t){return!!t&&typeof t=="object"}function Sr(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 Kb(t){return typeof t=="string"&&Sg.has(t)?t:void 0}function ah(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function Vb(t){return t==="never"||t==="on-request"?"never":void 0}function qb(t){return t==="approve"||t==="ask"||t==="delegate"?t:void 0}function Gb(t){if(t==="plan-mode"||t==="codex-first-turn-plan"||t==="soft-plan")return"plan-mode"}function dh(t){return typeof t=="string"&&ps.has(t)?t:void 0}function jb(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function Hb(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 zb(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function Qb(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 Jb(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 Yb(t){return t==="live"||t==="stopped"?t:void 0}function Xb(t){return t==="not_sent"||t==="sending"||t==="delivered"||t==="fallback_delivered"||t==="failed"?t:void 0}function Zb(t){return t==="direct-telegram"?"direct-message":t==="none"||t==="direct-message"||t==="wake-only"?t:void 0}function ex(t){return t==="none"||t==="canonical_buttons"||t==="explicit_fallback_text"?t:void 0}function tx(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function nx(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 rx(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"||t==="plan-offer-start"||t==="plan-offer-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 lh(t){if(!yo(t))return;let e=x(t.provider),n=x(t.accountId),r=x(t.target),o=x(t.threadId),i=x(t.sessionKey);if(!(!e||!r))return{provider:e,accountId:n,target:r,threadId:o,sessionKey:i}}function ox(t,e,n){if(yo(t)){let r=x(t.kind),o=x(t.conversationId);if(o&&(r==="claude-code"||r==="codex-app-server"))return{kind:r,conversationId:o,runId:x(t.runId),worktreeId:x(t.worktreeId),worktreePath:x(t.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:n}}function ix(t){if(!yo(t))return;let e=Jb(t.state),n=x(t.updatedAt);if(!e||!n)return;let r=x(t.resolutionSource);return{state:e,updatedAt:n,resolvedAt:x(t.resolvedAt),resolutionSource:r==="agent_merge"||r==="agent_pr"||r==="strategy_no_change"||r==="lifecycle_resolver"||r==="dismiss"||r==="maintenance"?r: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 sx(t){let e=new Date(0).toISOString(),n=x(t.worktreeMergedAt)??x(t.worktreeDismissedAt)??x(t.pendingWorktreeDecisionSince)??e;if(t.worktreeMerged===!0)return{state:"merged",updatedAt:n,resolvedAt:x(t.worktreeMergedAt)??n,resolutionSource:"agent_merge",baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:n,resolvedAt:x(t.worktreeDismissedAt)??n,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:n,resolvedAt:n,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:n,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:n,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(t.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:n,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)};if(x(t.worktreePath)||x(t.worktreeBranch))return{state:"provisioned",updatedAt:n,baseBranch:x(t.worktreeBaseBranch),targetRepo:x(t.worktreePrTargetRepo),pushRemote:x(t.worktreePushRemote)}}function ax(t){if(typeof t=="string"&&Ub.has(t))return t==="running"?"killed":t}function uh(t){if(!yo(t))return;let e=Sr(t.harnessSessionId);if(!e)return;let n=ax(t.status);if(!n)return;let r=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=lh(t.route);if(!l)return;let u=rr({route:l,originChannel:s,originThreadId:a,originSessionKey:d});if(!u||o&&!i)return;let f=x(t.harness),g=ox(t.backendRef,f,e),y=ix(t.worktreeLifecycle)??sx(t);return{sessionId:x(t.sessionId),harnessSessionId:e,backendRef:g,name:Sr(t.name,e),prompt:Sr(t.prompt),workdir:Sr(t.workdir,"(unknown)"),model:x(t.model),reasoningEffort:Kb(t.reasoningEffort),createdAt:je(t.createdAt),completedAt:je(t.completedAt),status:n,lifecycle:r?"suspended":Hb(t.lifecycle),approvalState:zb(t.approvalState),worktreeState:Qb(t.worktreeState),runtimeState:r?"stopped":Yb(t.runtimeState),deliveryState:tx(t.deliveryState),completionWakeIssuedAt:x(t.completionWakeIssuedAt),completionWakeSucceededAt:x(t.completionWakeSucceededAt),completionWakeFailedAt:x(t.completionWakeFailedAt),completionWakeSummaryRequired:t.completionWakeSummaryRequired===!0?!0:void 0,killReason:jb(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:u,outputPath:x(t.outputPath),harness:f,requestedPermissionMode:ah(t.requestedPermissionMode),currentPermissionMode:ah(t.currentPermissionMode),approvalExecutionState:nx(t.approvalExecutionState),approvalRationale:x(t.approvalRationale),planModeApproved:t.planModeApproved===!0,pendingPlanApproval:t.pendingPlanApproval===!0,planApprovalContext:Gb(t.planApprovalContext),planDecisionVersion:je(t.planDecisionVersion),actionablePlanDecisionVersion:je(t.actionablePlanDecisionVersion),canonicalPlanPromptVersion:je(t.canonicalPlanPromptVersion),approvalPromptRequiredVersion:je(t.approvalPromptRequiredVersion),approvalPromptVersion:je(t.approvalPromptVersion),approvalPromptStatus:Xb(t.approvalPromptStatus),approvalPromptTransport:Zb(t.approvalPromptTransport),approvalPromptMessageKind:ex(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:x(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:x(t.approvalPromptDeliveredAt),approvalPromptFailedAt:x(t.approvalPromptFailedAt),planApproval:qb(t.planApproval),codexApprovalPolicy:Vb(t.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:dh(t.worktreeStrategy),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:y,resumable:r?!0:t.resumable===!0}}function ph(t){if(!yo(t))return;let e=rx(t.kind),n=Sr(t.id),r=Sr(t.sessionId),o=je(t.createdAt);if(!(!n||!r||!e||o==null))return{id:n,sessionId:r,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:lh(t.route),launchName:x(t.launchName),launchPrompt:x(t.launchPrompt),launchWorkdir:x(t.launchWorkdir),launchWorktreeStrategy:dh(t.launchWorktreeStrategy)}}function $s(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 Dl(t){return!!t&&typeof t=="object"}function Ll(t){return t instanceof Error?t.message:String(t)}function hh(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||Ns(sh(t),"code-agent-sessions.json")}function Sh(t,e,n){try{lx(px(t),{recursive:!0});let r=t+".tmp";gh(r,JSON.stringify({schemaVersion:Os,sessions:e,actionTokens:n},null,2),"utf-8"),ch(r,t)}catch(r){console.warn(`[SessionStore] Failed to save session index: ${Ll(r)}`)}}function Ds(t,e){try{if(!dx(t))return;let n=`${t}.legacy-${Date.now()}.json`;ch(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: ${Ll(n)}`)}}function cx(t,e){try{if(e.length===0)return;let n=`${t}.codex-sdk-legacy-${Date.now()}.json`;gh(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: ${Ll(n)}`)}}function yh(t,e){try{let n=Fl(),r=Nl(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r)try{let i=Ns(n,o),s=mh(i).mtimeMs;t-s>e&&fh(i)}catch{}}catch{}}function kh(t,e){try{let n=Fl(),r=Nl(n).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of r)try{let s=Ns(n,i),a=mh(s).mtimeMs+e;if(a<=t)return t;o=o==null?a:Math.min(o,a)}catch{}return o}catch{return}}function vh(t){try{let e=new Set(t),n=Fl(),r=Nl(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r){let i=Ns(n,o);if(!e.has(i))try{fh(i)}catch{}}}catch{}}function Ph(t){let{indexPath:e,clearAll:n,indexPersistedEntry:r,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:s}=t;try{let a=ux(e,"utf-8"),d=JSON.parse(a);if(Array.isArray(d)){Ds(e,"legacy array store"),s();return}if(!Dl(d)||d.schemaVersion!==Os&&d.schemaVersion!==4){Ds(e,`schema mismatch (expected v${Os})`),s();return}let l=Array.isArray(d.sessions)?d.sessions:[],u=[];for(let g of l){if(Dl(g)&&g.harness==="codex"){let k=Dl(g.backendRef)?g.backendRef:void 0;if((typeof k?.kind=="string"?k.kind:void 0)!=="codex-app-server"){u.push(g);continue}}let y=uh(g);if(!y){n(),Ds(e,"invalid v4 session entry"),s();return}r(y)}u.length>0&&(cx(e,u),s());let f=Array.isArray(d.actionTokens)?d.actionTokens:[];for(let g of f){let y=ph(g);if(!y){n(),Ds(e,"invalid v4 action token"),s();return}o(y)}i()}catch{}}var gx=new Set(["completed","failed","killed"]),Wl=1440*60*1e3;function hx(t){return t instanceof Error?t.message:String(t)}var Fs=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??hh(n),this.actionTokenStore=new _s(()=>this.saveIndex(),Wl),this.actionTokens=this.actionTokenStore.tokens,this.queries=new Es({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(){Ph({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(){Sh(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){$s(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){return e.backendRef??{kind:ol(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=M(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=rr({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};$s(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=rr({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!r)return;let o;try{let s=cr(e.id);if(mx(s))o=s;else{let a=e.getOutput().join(`
149
+ `);a.length>0&&(fx(s,a,"utf-8"),o=s)}}catch(s){console.warn(`[SessionStore] Failed to write output file for session ${e.id}: ${hx(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};$s(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),yh(e,Wl)}getNextTmpOutputCleanupAt(e){return kh(e,Wl)}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||!gx.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(){vh(this.getReferencedOutputPaths())}};var Sx=new Set(["completed","failed","killed"]),Ls=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),Sx.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 Ih from"child_process";var wh=5e3,yx={execFile:Ih.execFile},fn=class extends Error{constructor(e){super(e),this.name="MissingRuntimeDirectNotificationCapabilityError"}},Ws=class{constructor(e=yx.execFile){this.execFile=e}execFile;async send(e,n,r){q("direct_send_started",{...gt(e),messageTextLength:n.length,...se(r)});try{await this.sendViaRuntime(e,n,r),q("direct_send_succeeded",{...gt(e),deliveryPath:"runtime",...se(r)});return}catch(o){if(!(o instanceof fn))throw q("direct_send_failed",{...gt(e),deliveryPath:"runtime",...se(r),error:Bl(o)}),o;q("direct_send_runtime_capability_missing",{...gt(e),deliveryPath:"runtime",...se(r),reason:o.message}),await this.sendViaBoundedCliFallback(e,n,r,o.message),q("direct_send_succeeded",{...gt(e),deliveryPath:"cli-fallback",...se(r)})}}async sendViaRuntime(e,n,r){let o=Li(),i=Df(),s=o?.channel?.outbound?.loadAdapter;if(!o)throw new fn("OpenClaw plugin runtime is unavailable for direct notification delivery");if(i==null)throw new fn("OpenClaw runtime config snapshot is unavailable for direct notification delivery");if(!o.channel)throw new fn(`OpenClaw plugin runtime channel surface is unavailable for direct notification delivery (runtimeVersion=${Ul(o)})`);if(!o.channel.outbound)throw new fn(`OpenClaw plugin runtime channel outbound surface is unavailable for direct notification delivery (runtimeVersion=${Ul(o)})`);if(!s)throw new fn(`OpenClaw plugin runtime channel outbound loadAdapter is unavailable for direct notification delivery (runtimeVersion=${Ul(o)})`);let a=await s(e.channel);if(!a)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" is unavailable`);let d=Bs(r);if(q("runtime_adapter_loaded",{...gt(e),adapterHasRenderPresentation:typeof a.renderPresentation=="function",adapterHasSendPayload:typeof a.sendPayload=="function",adapterHasSendText:typeof a.sendText=="function",...se(r),...d?Rl(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=vx(i),a={text:o,presentation:i,interactive:s};q("presentation_render_started",{...gt(r),messageTextLength:o.length,adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...Rl(i)});let d={cfg:n,to:r.target,text:o,payload:a,accountId:r.accountId,threadId:r.threadId},l=e.renderPresentation?await e.renderPresentation({payload:a,presentation:i,ctx:d}):a,u=wx(l,s);if(q("presentation_render_completed",{...gt(r),adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...Tl(u)}),!u||typeof u!="object"||!e.sendPayload)throw new Error(`OpenClaw outbound adapter for channel "${r.channel}" cannot preserve interactive presentation`);let f=await e.sendPayload({...d,payload:u});q("presentation_send_payload_completed",{...gt(r),...Tl(u),...Eg(f)})}sendViaBoundedCliFallback(e,n,r,o){return new Promise((i,s)=>{let a=kx(e,n,r);q("direct_send_cli_fallback_started",{...gt(e),deliveryPath:"cli-fallback",reason:o,messageTextLength:n.length,...se(r)}),this.execFile("openclaw",a,{timeout:wh,killSignal:"SIGKILL"},(d,l,u)=>{if(!d){q("direct_send_cli_fallback_completed",{...gt(e),deliveryPath:"cli-fallback",...se(r)}),i();return}let f=u?.trim()?` | stderr: ${u.trim()}`:"";q("direct_send_cli_fallback_failed",{...gt(e),deliveryPath:"cli-fallback",...se(r),error:Bl(d),stderrLength:u?.length}),s(new Error(`${o}; bounded openclaw message send fallback failed within ${wh}ms timeout: ${Bl(d)}${f}`))})})}};function gt(t){return{channel:t.channel,target:t.target,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey}}function kx(t,e,n){let r=Bs(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 Bl(t){return t instanceof Error?t.message:String(t)}function Ul(t){if(!t||typeof t!="object")return"unknown";let e=t.version;return typeof e=="string"&&e.trim()?e:"unknown"}function Bs(t){let e=(t??[]).filter(n=>Array.isArray(n)&&n.length>0).map(n=>({type:"buttons",buttons:n.map(r=>({label:r.label,value:Ix(r.callbackData),...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function vx(t){let e=t.blocks.filter(n=>n.type==="buttons"&&n.buttons.length>0).map(n=>({type:"buttons",buttons:n.buttons.map(r=>({label:r.label,value:r.value,...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function Px(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t.interactive;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.blocks;return Array.isArray(n)&&n.some(r=>{if(!r||typeof r!="object"||Array.isArray(r))return!1;let o=r;return o.type==="buttons"&&Array.isArray(o.buttons)&&o.buttons.length>0})}function wx(t,e){return!e||Px(t)||!t||typeof t!="object"||Array.isArray(t)?t:{...t,interactive:e}}function Ix(t){return t.startsWith(`${ot}:`)?t:`${ot}:${t}`}import*as bh from"child_process";var yr=class{tails=new Map;enqueue(e,n,r){let o=this.tails.get(e);o!==void 0&&r?.();let s=(o?.catch(()=>{})??Promise.resolve()).then(()=>n()),a=s.catch(()=>{});return this.tails.set(e,a),a.finally(()=>{this.tails.get(e)===a&&this.tails.delete(e)}),s}clear(){this.tails.clear()}};var Kl=3e4,bx=2e3,xx=2e4,ht=4;function ko(t){return t instanceof Error?t.message:String(t)}function Ax(){return new Error(`Dispatch timed out after ${Kl}ms`)}function Rx(t){if(!(t instanceof Error))return!1;let e=t;return e.killed===!0&&e.signal==="SIGKILL"}var Tx={execFile:bh.execFile},Us=class{pendingRetryTimers=new Map;orderedDispatches=new yr;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.orderedDispatches.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||n.shouldContinue?.()===!1){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}),Tx.execFile("openclaw",e,{timeout:Kl,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.shouldContinue?.()!==!1&&n.onSuccess?.(),r?.();return}let u=d?.trim()?` | stderr: ${d.trim()}`:"";if(n.target==="message.send"&&Rx(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:`${ko(s)}${u}`,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:`${ko(s)}${u}`,terminal:!0}),n.onFinalFailure?.(),r?.();return}let g=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:g,error:`${ko(s)}${u}`});let y={timer:setTimeout(()=>{let k=this.pendingRetryTimers.get(n.sessionId);if(k&&(k.delete(y),k.size===0&&this.pendingRetryTimers.delete(n.sessionId)),n.shouldContinue?.()===!1){r?.();return}this.executeNow(e,n,r,o+1)},g),onCleared:r};y.timer.unref?.(),this.pendingRetryTimers.has(n.sessionId)||this.pendingRetryTimers.set(n.sessionId,new Set),this.pendingRetryTimers.get(n.sessionId).add(y)})}executePromiseNow(e,n,r,o=1){if(this.disposed||n.shouldContinue?.()===!1){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.shouldContinue?.()!==!1&&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:ko(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:ko(s)});let l={timer:setTimeout(()=>{let u=this.pendingRetryTimers.get(n.sessionId);if(u&&(u.delete(l),u.size===0&&this.pendingRetryTimers.delete(n.sessionId)),n.shouldContinue?.()===!1){r?.();return}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(Ax()))},Kl);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=bx*2**n;return Math.min(r,xx)}enqueueOrderedDispatch(e,n){this.orderedDispatches.enqueue(e,async()=>{this.disposed||await new Promise(r=>{let o=!1;n(()=>{o||(o=!0,r())})})})}log(e,n,r){let o=`[WakeDispatcher] ${JSON.stringify({event:n,...r})}`;if(e==="error"){console.error(o);return}console.info(o)}};Cn();var Ks=class{resolve(e){let n=yi(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 Cx}from"crypto";var Vs=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:Cx()})]}buildDirectNotificationArgs(e,n,r){let o=Bs(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 qs=class{routes=new Ks;transport;directNotifications;executor=new Us;constructor(e={}){this.transport=e.transport??new Vs(e.transportOptions),this.directNotifications=e.directNotifications===void 0?new Ws: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,a){let d=this.routes.resolve(e),l=a;if(l?.()===!1)return;let u=d?.sessionKey?.trim();if(!u){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,shouldContinue:l});return}this.executor.execute(this.transport.buildChatSendArgs(u,n,!0),{label:r,sessionId:e.id,target:"chat.send",phase:o,routeSummary:`session:${u}`,messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:`session:${u}`,route:d,text:n}),onSuccess:s,shouldContinue:l,onFinalFailure:()=>{l?.()!==!1&&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,shouldContinue:l})}})}sendUserNotification(e,n,r,o,i,s,a=!1,d){if(d?.()===!1)return;let l=!!o?.some(k=>Array.isArray(k)&&k.length>0),u=this.routes.resolve(e);q("wake_notify_selected",{sessionId:e.id,sessionName:e.name,label:r,messageTextLength:n.length,requireDirectDelivery:a,hasDirectNotificationTransport:!!this.directNotifications,routeSummary:u?this.routes.summary(u):"system",channel:u?.channel,target:u?.target,accountId:u?.accountId,threadId:u?.threadId,sessionKey:u?.sessionKey,...se(o)});let f=u?`notify:${u.channel}|${u.accountId??""}|${u.target}|${u.threadId??""}`:`notify:system:${e.id}`;if(!u){if(q("wake_notify_no_direct_route",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:l,...se(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(l){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:f,onSuccess:s,onFinalFailure:i,shouldContinue:d});return}let g=()=>{if(q("wake_notify_direct_failed",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:l,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...se(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(l){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:f,onSuccess:s,onFinalFailure:i,shouldContinue:d})},y={label:`${r}-notify`,sessionId:e.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(u),messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:this.routes.summary(u),route:u,text:n,buttons:o}),orderingKey:f,onSuccess:s,onAmbiguousResult:g,onFinalFailure:g,terminalOnFailure:this.directNotifications?!0:void 0,shouldContinue:d};if(this.directNotifications){q("wake_notify_dispatching_direct_runtime",{sessionId:e.id,sessionName:e.name,label:r,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...se(o)}),this.executor.executePromise(()=>this.directNotifications.send(u,n,o),y);return}q("wake_notify_dispatching_cli_message_send",{sessionId:e.id,sessionName:e.name,label:r,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...se(o)}),this.executor.execute(this.transport.buildDirectNotificationArgs(u,n,o),y)}sendUserNotificationSequence(e,n,r,o,i,s=!1,a){let d=n.map(u=>({text:u.text.trim(),buttons:u.buttons})).filter(u=>u.text.length>0);if(d.length===0){o?.();return}q("wake_notify_sequence_started",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:d.length,buttonChunkIndexes:d.map((u,f)=>u.buttons?.some(g=>Array.isArray(g)&&g.length>0)?f+1:void 0).filter(u=>typeof u=="number"),requireDirectDelivery:s});let l=u=>{if(a?.()===!1)return;let f=d[u];if(!f){q("wake_notify_sequence_succeeded",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:d.length}),i?.();return}let g=u===0?o:i;q("wake_notify_sequence_chunk_selected",{sessionId:e.id,sessionName:e.name,label:r,chunkIndex:u+1,chunkCount:d.length,messageTextLength:f.text.length,failureHandler:u===0?"all-failed":"sequence-success",...se(f.buttons)}),this.sendUserNotification(e,f.text,`${r}-part-${u+1}`,f.buttons,g,()=>l(u+1),s,a)};l(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(u=>({text:u.text.trim(),buttons:u.buttons})).filter(u=>u.text.length>0),a=s[0]?.text,d=n.wakeMessage?.trim(),l=n.shouldDispatch;if(o){let u=n.wakeMessageOnNotifySuccess?.trim(),f=n.wakeMessageOnNotifyFailed?.trim(),g=b=>{b&&l?.()!==!1&&(r?.onWakeStarted?.(),this.sendWake(e,b,`${n.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded,l))},y=()=>{l?.()!==!1&&(r?.onNotifySucceeded?.(),u&&g(u))},k=f?()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.(),g(f))}:()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.())};if(s.length>0){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,k,y,n.requireDirectUserNotification===!0,l)}else k();return}if(i==="always"&&s.length>0){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.())},()=>{l?.()!==!1&&r?.onNotifySucceeded?.()},n.requireDirectUserNotification===!0,l)}if(d&&l?.()!==!1){if(r?.onWakeStarted?.(),i==="on-wake-fallback"&&s.length>0&&!this.routes.resolve(e)?.sessionKey){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,n.label,()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),n.onUserNotifyFailed?.())},()=>{l?.()!==!1&&r?.onNotifySucceeded?.()},!1,l)}this.sendWake(e,d,`${n.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded,l)}}};var Gs=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"plan-offer-start":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 q("plan_approval_buttons_created",{sessionId:e,planDecisionVersion:n?.planDecisionVersion,...se(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}))]}getPlanOfferButtons(e){let{offerId:n,route:r,planName:o,planPrompt:i,planWorkdir:s,planWorktreeStrategy:a}=e,d=[[this.makeActionButton(n,"plan-offer-start","Start Plan",{route:r,launchName:o,launchPrompt:i,launchWorkdir:s,launchWorktreeStrategy:a}),this.makeActionButton(n,"plan-offer-dismiss","Dismiss",{route:r})]];return q("plan_offer_buttons_created",{offerId: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,...se(d)}),d}};he();var js=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 ne(e)??M(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}}};rt();import{existsSync as Mx}from"fs";var Hs=class{getCompletionState(e,n,r,o){return cl(e,r,o)?"has-commits":cl(e,o,r)?"base-advanced":mr(n)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(e,n,r){if(!e.worktreePath||!e.workdir||!Mx(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 zs=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}`,u=[`[ASK USER QUESTION] Session "${e.name}" has a question requiring user input.`,"",`Question: ${s.question}`,...a.length>0?["Options:",...a.map((f,g)=>` ${g+1}. ${f.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
150
+ `);return new Promise((f,g)=>{let y=setTimeout(()=>{this.pendingQuestions.delete(e.id),g(new Error(`AskUserQuestion timed out after 600s for session "${e.name}"`))},6e5);y.unref?.(),this.pendingQuestions.set(e.id,{resolve:f,reject:g,questions:i,timeoutHandle:y}),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:u})})}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 _x(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 Qs(t){let e=_x(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function vo(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 Ex(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function Vl(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 Ox(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 ql(t){let{session:e,originThreadLine:n,preview:r}=t,o=`$${(e.costUsd??0).toFixed(2)}`,i=Tt(e.duration),s=Ex(),a=d=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,n,...Qs(e),"","Output preview:",r,"",...Ox({contract:s,canonicalStatusDelivered:d}),"",...Vl({sessionId:e.id,canonicalStatusDelivered:d})].join(`
152
+ `);return{userMessage:`\u2705 [${e.name}] Completed | ${o} | ${i}`,wakeMessageOnNotifySuccess:a(!0),wakeMessageOnNotifyFailed:a(!1),followupContract:s}}function Gl(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)}`,u=Tt(e.duration);return{userMessage:[`\u274C [${e.name}] Failed | ${l} | ${u}`,` \u26A0\uFE0F ${r}`].join(`
153
153
  `),wakeMessage:["Coding agent session failed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,n,...Qs(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(`
154
- `),buttons:s}}function Hl(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(`
155
- `)}}function zl(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(`
156
- `)}function Ql(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 Jl(t){let{sessionName:e,sessionId:n,cleanupSummary:r,preview:o,originThreadLine:i,requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:u,approvalPromptStatus:f,approvalPromptMessageKind:S,approvalPromptDeliveredAt:y}=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]:[],...Qs({requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:u,approvalPromptStatus:f,approvalPromptMessageKind:S,approvalPromptDeliveredAt:y}),...k,"",...ql({sessionId:n,canonicalStatusDetail:"The plugin already sent the canonical completion status to the user, including that no repo changes were kept."})].join(`
158
- `)}function Yl(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 Rh=3200,Xl=3e3,$x=2400,Dx=120,Nx=5,Fx=280,xh=1400,Ah="- Additional plan details omitted for brevity.";function Th(t){return t.replace(/^#{1,6}\s+/,"").replace(/^[-*+]\s+/,"").replace(/^\d+[.)]\s+/,"").replace(/^`([^`]+)`$/,"$1").trim()}function Lx(t){return t.split(`
154
+ `),buttons:s}}function jl(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(`
155
+ `)}}function Hl(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(`
156
+ `)}function zl(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 Ql(t){let{sessionName:e,sessionId:n,cleanupSummary:r,preview:o,originThreadLine:i,requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:u,approvalPromptStatus:f,approvalPromptMessageKind:g,approvalPromptDeliveredAt:y}=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]:[],...Qs({requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:u,approvalPromptStatus:f,approvalPromptMessageKind:g,approvalPromptDeliveredAt:y}),...k,"",...Vl({sessionId:n,canonicalStatusDetail:"The plugin already sent the canonical completion status to the user, including that no repo changes were kept."})].join(`
158
+ `)}function Jl(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 Rh=3200,Yl=3e3,$x=2400,Dx=120,Nx=5,Fx=280,xh=1400,Ah="- Additional plan details omitted for brevity.";function Th(t){return t.replace(/^#{1,6}\s+/,"").replace(/^[-*+]\s+/,"").replace(/^\d+[.)]\s+/,"").replace(/^`([^`]+)`$/,"$1").trim()}function Lx(t){return t.split(`
159
159
  `).map(e=>e.trim()).filter(Boolean).map(Th).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 Wx(t){return t.split(`
160
- `).map(e=>e.trim()).filter(Boolean).map(Th).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 Zl(t){let e=Lx(t);return e.length===0?`Review summary:
160
+ `).map(e=>e.trim()).filter(Boolean).map(Th).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 Xl(t){let e=Lx(t);return e.length===0?`Review summary:
161
161
  - Plan details are available in the full session output.`:["Review summary:",...e.slice(0,6).map(n=>`- ${n}`)].join(`
162
162
  `)}function Bx(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>=Nx||[...e,a].join(`
163
163
  `).length>xh){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,Ah].join(`
164
- `).length>xh;)r.pop();return[...r,Ah]}function eu(t){return Bx(Wx(t)).join(`
164
+ `).length>xh;)r.pop();return[...r,Ah]}function Zl(t){return Bx(Wx(t)).join(`
165
165
  `)}function Ux(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(`
166
166
  `),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 Ux(s,e))r.push(d);continue}let a=o.length>0?`${o}
167
167
  ${s}`:s;if(a.length>e){i(),o=s;continue}o=a}return i(),r}function Ch(t){return Ce(t.trim(),Dx)}function Mh(t,e){return e?t?`
@@ -173,42 +173,42 @@ Approval is still pending for this plan version.`:`
173
173
  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
174
 
175
175
  Full plan (truncated):
176
- `,a=Mh(o,!0),d=Math.max(0,Xl-i.length-s.length-a.length);return`${i}${s}${Ce(r,d)}${a}`}function qx(t){let{sessionName:e,actionableVersion:n,fullPlanText:r,hasButtons:o}=t,i=Ch(e),s=$x;for(;s>0;){let a=Kx(r,s),d=a.map((f,S)=>{let y=a.length,k=[`\u{1F4CB} [${i}] Plan v${n??"?"} ready for approval (${S+1}/${y}):`,"",S===0?"Full plan:":""].filter(Boolean).join(`
177
- `),b=Mh(o,S===y-1);return`${k}
178
- ${f}${b}`}),l=d.reduce((f,S)=>Math.max(f,S.length),0);if(l<=Xl)return d;let u=l-Xl;s-=Math.max(u,50)}return[Vx({sessionName:i,actionableVersion:n,fullPlanText:r,hasButtons:o})]}function tu(t){let{preview:e,artifact:n}=t,r=n?.markdown?.trim();return r&&r.length<=Rh?`Full plan:
179
- ${r}`:Zl(r||e)}function _h(t){let{sessionName:e,actionableVersion:n,preview:r,artifact:o,hasButtons:i}=t,s=o?.markdown?.trim(),a=Ch(e);if(s){let l=`\u{1F4CB} [${a}] Plan v${n??"?"} ready for approval:
176
+ `,a=Mh(o,!0),d=Math.max(0,Yl-i.length-s.length-a.length);return`${i}${s}${Ce(r,d)}${a}`}function qx(t){let{sessionName:e,actionableVersion:n,fullPlanText:r,hasButtons:o}=t,i=Ch(e),s=$x;for(;s>0;){let a=Kx(r,s),d=a.map((f,g)=>{let y=a.length,k=[`\u{1F4CB} [${i}] Plan v${n??"?"} ready for approval (${g+1}/${y}):`,"",g===0?"Full plan:":""].filter(Boolean).join(`
177
+ `),b=Mh(o,g===y-1);return`${k}
178
+ ${f}${b}`}),l=d.reduce((f,g)=>Math.max(f,g.length),0);if(l<=Yl)return d;let u=l-Yl;s-=Math.max(u,50)}return[Vx({sessionName:i,actionableVersion:n,fullPlanText:r,hasButtons:o})]}function eu(t){let{preview:e,artifact:n}=t,r=n?.markdown?.trim();return r&&r.length<=Rh?`Full plan:
179
+ ${r}`:Xl(r||e)}function _h(t){let{sessionName:e,actionableVersion:n,preview:r,artifact:o,hasButtons:i}=t,s=o?.markdown?.trim(),a=Ch(e);if(s){let l=`\u{1F4CB} [${a}] Plan v${n??"?"} ready for approval:
180
180
 
181
181
  Full plan:
182
182
  ${s}
183
183
 
184
184
  ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`;return l.length<=Rh?{displayMode:"single-full-plan",userMessages:[l],reviewSummary:`Full plan:
185
- ${s}`}:{displayMode:"chunked-full-plan",userMessages:qx({sessionName:e,actionableVersion:n,fullPlanText:s,hasButtons:i}),reviewSummary:Zl(s)}}let d=Zl(r);return{displayMode:"summary",userMessages:[`\u{1F4CB} [${a}] Plan v${n??"?"} ready for approval:
185
+ ${s}`}:{displayMode:"chunked-full-plan",userMessages:qx({sessionName:e,actionableVersion:n,fullPlanText:s,hasButtons:i}),reviewSummary:Xl(s)}}let d=Xl(r);return{displayMode:"summary",userMessages:[`\u{1F4CB} [${a}] Plan v${n??"?"} ready for approval:
186
186
 
187
187
  ${d}
188
188
 
189
189
  ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`],reviewSummary:d}}var Eh=700;function Gx(t){let e=t?.trim();return e||void 0}function jx(t,e){let n=e?.trim();if(!n)return;if(!t)return n;let r=t.trim(),o=n.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()===r;)o.pop();let s=o.filter((a,d,l)=>{let u=a.trim();return!u||u!==r?!0:!l.some((S,y)=>y!==d&&S.trim().length>0&&S.trim()!==r)}).join(`
191
- `).trim();if(!(!s||s===r))return s.length>Eh?Ni(s,Eh):s}function Hx(t){let e=Gx(t.questionText)??"The session is waiting for your reply.",n=jx(e,t.contextPreview);return n?[`\u2753 [${t.sessionName}] Question waiting for reply:`,"","Question:",e,"","Recent context:",n].join(`
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()===r;)o.pop();let s=o.filter((a,d,l)=>{let u=a.trim();return!u||u!==r?!0:!l.some((g,y)=>y!==d&&g.trim().length>0&&g.trim()!==r)}).join(`
191
+ `).trim();if(!(!s||s===r))return s.length>Eh?Fi(s,Eh):s}function Hx(t){let e=Gx(t.questionText)??"The session is waiting for your reply.",n=jx(e,t.contextPreview);return n?[`\u2753 [${t.sessionName}] Question waiting for reply:`,"","Question:",e,"","Recent context:",n].join(`
192
192
  `):`\u2753 [${t.sessionName}] Question waiting for reply:
193
193
 
194
- ${e}`}function zx(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function vo(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(`
195
- `)}function nu(t){let{session:e,preview:n,questionText:r,questionContextPreview:o,planArtifact:i,originThreadLine:s,planApprovalMode:a,planApprovalButtons:d,questionButtons:l}=t,u=e.pendingPlanApproval,f=e.actionablePlanDecisionVersion??e.planDecisionVersion,S=zx(e,f),y=a??"delegate",k=u&&y==="ask"&&!S?_h({sessionName:e.name,actionableVersion:f,preview:n,artifact:i,hasButtons:!!d}):void 0,b=u?k?.reviewSummary??tu({preview:n,artifact:i}):void 0,P=u?k&&k.userMessages.length===1?k.userMessages[0]:void 0:Hx({sessionName:e.name,questionText:r??n,contextPreview:o}),I=u&&k&&k.userMessages.length>1?k.userMessages.map((C,N,xe)=>({text:C,buttons:N===xe.length-1?d:void 0})):void 0;if(u){let C=y,N="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return C==="delegate"?{label:"plan-approval",userMessage:P,userMessages:I,planReviewSummary:b,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,N,"","\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(`
194
+ ${e}`}function zx(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function Po(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(`
195
+ `)}function tu(t){let{session:e,preview:n,questionText:r,questionContextPreview:o,planArtifact:i,originThreadLine:s,planApprovalMode:a,planApprovalButtons:d,questionButtons:l}=t,u=e.pendingPlanApproval,f=e.actionablePlanDecisionVersion??e.planDecisionVersion,g=zx(e,f),y=a??"delegate",k=u&&y==="ask"&&!g?_h({sessionName:e.name,actionableVersion:f,preview:n,artifact:i,hasButtons:!!d}):void 0,b=u?k?.reviewSummary??eu({preview:n,artifact:i}):void 0,P=u?k&&k.userMessages.length===1?k.userMessages[0]:void 0:Hx({sessionName:e.name,questionText:r??n,contextPreview:o}),I=u&&k&&k.userMessages.length>1?k.userMessages.map((C,N,xe)=>({text:C,buttons:N===xe.length-1?d:void 0})):void 0;if(u){let C=y,N="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return C==="delegate"?{label:"plan-approval",userMessage:P,userMessages:I,planReviewSummary:b,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,N,"","\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(`
196
196
  `)}:C==="ask"?{label:"plan-approval",userMessage:P,userMessages:I,planReviewSummary:b,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,N,"","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(`
197
197
  `),buttons:I?void 0:d}:{label:"plan-approval",userMessage:P,planReviewSummary:b,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`].join(`
198
198
  `)}}let A=e.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:P,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.]`,"",`${A} 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(`
199
- `),buttons:l}}he();var Js=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 tt(e))this.updatePersistedSession(s,{lastWorktreeReminderAt:new Date(n).toISOString()});return!0}sendReminderNotification(e,n){let r=this.buildRoutingProxy({id:e.sessionId??e.name??M(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:Ql(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(`
200
- `);this.dispatchNotification(r,{label:`worktree-stale-reminder-${e.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(ne(e)??e.harnessSessionId)})}};rt();he();Cn();function Po(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&Qx(t.approvalPromptStatus)}function Qx(t){return t==="delivered"||t==="fallback_delivered"}function wo(t,e){return!t||e==null?!1:!!(t.pendingPlanApproval&&t.approvalState==="pending"&&t.lifecycle==="awaiting_plan_decision"&&(t.actionablePlanDecisionVersion??t.planDecisionVersion)===e)}function yr(t,e,n=!1){let r="id"in t?t.id:t.sessionId??"unknown-session";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: ${t.name??"unknown"} | ID: ${r} | Plan v${e??"?"}`,`Wait for their ${n?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
199
+ `),buttons:l}}he();var Js=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 tt(e))this.updatePersistedSession(s,{lastWorktreeReminderAt:new Date(n).toISOString()});return!0}sendReminderNotification(e,n){let r=this.buildRoutingProxy({id:e.sessionId??e.name??M(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:zl(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(`
200
+ `);this.dispatchNotification(r,{label:`worktree-stale-reminder-${e.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(ne(e)??e.harnessSessionId)})}};rt();he();Cn();function wo(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&Qx(t.approvalPromptStatus)}function Qx(t){return t==="delivered"||t==="fallback_delivered"}function Io(t,e){return!t||e==null?!1:!!(t.pendingPlanApproval&&t.approvalState==="pending"&&t.lifecycle==="awaiting_plan_decision"&&(t.actionablePlanDecisionVersion??t.planDecisionVersion)===e)}function kr(t,e,n=!1){let r="id"in t?t.id:t.sessionId??"unknown-session";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: ${t.name??"unknown"} | ID: ${r} | Plan v${e??"?"}`,`Wait for their ${n?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
201
201
  `)}function Ys(t){let e="id"in t.session?t.session.id:t.session.sessionId??"unknown-session",n=t.originThreadLine??(t.session.originThreadId!=null?`Origin thread: ${t.session.originThreadId}`:"");return["[PLAN APPROVAL DELIVERY FAILED] The plugin could not deliver the canonical plan review buttons or the explicit fallback text to the user.",`Name: ${t.session.name??"unknown"} | ID: ${e} | Plan v${t.planDecisionVersion??"?"}`,n,"","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(`
202
- `)}import{existsSync as Jx,readFileSync as Yx}from"fs";function Xx(t,e){if(t.latestPlanArtifactVersion===e&&t.latestPlanArtifact)return t.latestPlanArtifact;let n=t.planFilePath?.trim();if(!(!n||!Jx(n)))try{let r=Yx(n,"utf-8").trim();return r?{markdown:r,steps:[]}:void 0}catch{return}}var Xs=class{constructor(e){this.deps=e}deps;dispatchPlanApprovalFallback(e,n,r){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",userMessage:vo({session:e,summary:r}),notifyUser:"always",shouldDispatch:()=>wo(e,n),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:yr(e,n,!0),wakeMessageOnNotifyFailed:Ys({session:e,planDecisionVersion:n,originThreadLine:this.deps.originThreadLine(e)})})}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:!!Si(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 u=!1;if(a&&!l&&(u=nt(a,e.worktreePath)),a&&d&&!l&&u&&Dt(a,d),u){for(let f of tt(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&&nt(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=Po(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(`
202
+ `)}import{existsSync as Jx,readFileSync as Yx}from"fs";function Xx(t,e){if(t.latestPlanArtifactVersion===e&&t.latestPlanArtifact)return t.latestPlanArtifact;let n=t.planFilePath?.trim();if(!(!n||!Jx(n)))try{let r=Yx(n,"utf-8").trim();return r?{markdown:r,steps:[]}:void 0}catch{return}}var Xs=class{constructor(e){this.deps=e}deps;dispatchPlanApprovalFallback(e,n,r){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",userMessage:Po({session:e,summary:r}),notifyUser:"always",shouldDispatch:()=>Io(e,n),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:kr(e,n,!0),wakeMessageOnNotifyFailed:Ys({session:e,planDecisionVersion:n,originThreadLine:this.deps.originThreadLine(e)})})}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:!!yi(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 u=!1;if(a&&!l&&(u=nt(a,e.worktreePath)),a&&d&&!l&&u&&Dt(a,d),u){for(let f of tt(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&&nt(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=wo(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
203
  `),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
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} | ${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(`
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} | ${Tt(s)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(e.id,e)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.notifySession(e,`\u26D4 [${e.name}] ${ko(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"&&Po(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=Xx(e,r),l=nu({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}),u=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()})}},shouldDispatch:()=>wo(e,r),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,r,u),wakeMessageOnNotifySuccess:yr(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=Hl({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=Gl({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=jl({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})}};he();rt();import{existsSync as Zx}from"fs";var Zs=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&&Zx(i)&&nt(s,i,{destructive:!0}),a&&Dt(s,a);for(let f of tt(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 u=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:ne(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:u,notifyUser:"always"}),u}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 tt(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:ne(n)??M(n)??n.harnessSessionId,sessionId:n.sessionId,harnessSessionId:n.harnessSessionId,backendRef:n.backendRef,route:n.route}),{label:"worktree-snoozed",userMessage:i,notifyUser:"always"}),i}};var Oh=new Set(["starting","running"]),ea=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>Oh.has(e.status)).length}uniqueName(e){let n=new Set([...this.sessions.values()].filter(o=>Oh.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 ta=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 na=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:Jl({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=Yl(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`:"",u=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}\``,"",u,`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(`
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} | ${Tt(s)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(e.id,e)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.notifySession(e,`\u26D4 [${e.name}] ${vo(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"&&wo(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=Xx(e,r),l=tu({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}),u=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()})}},shouldDispatch:()=>Io(e,r),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,r,u),wakeMessageOnNotifySuccess:kr(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=jl({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=ql({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=Gl({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})}};he();rt();import{existsSync as Zx}from"fs";var Zs=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&&Zx(i)&&nt(s,i,{destructive:!0}),a&&Dt(s,a);for(let f of tt(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 u=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:ne(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:u,notifyUser:"always"}),u}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 tt(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:ne(n)??M(n)??n.harnessSessionId,sessionId:n.sessionId,harnessSessionId:n.harnessSessionId,backendRef:n.backendRef,route:n.route}),{label:"worktree-snoozed",userMessage:i,notifyUser:"always"}),i}};var Oh=new Set(["starting","running"]),ea=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>Oh.has(e.status)).length}uniqueName(e){let n=new Set([...this.sessions.values()].filter(o=>Oh.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 ta=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 na=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:Ql({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=Jl(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`:"",u=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}\``,"",u,`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(`
206
206
  `),notifyUser:"always",buttons:s,wakeMessageOnNotifySuccess:["Worktree decision buttons delivered to the user.",`Session: ${n.name} | ID: ${n.id}`,u,"Wait for their button callback \u2014 do NOT act on this worktree yourself."].join(`
207
207
  `),wakeMessageOnNotifyFailed:[`\u{1F500} Worktree decision required for session \`${n.name}\``,"",u,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
208
- `)}}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:zl({sessionName:n.name,sessionId:n.id,branchName:r,baseBranch:o,promptSnippet:d,commitLines:s,moreNote:a,diffSummary:i}),notifyUser:"never"}}};function $h(t,e=1e3){let n=!Number.isFinite(e),r=typeof t.getOutput=="function"?t.getOutput():[],o=n?r.join(`
209
- `):eA(t);return n?o:o.length>e?Dh(t)?Ni(o,e):$f(o,e):o}function eA(t){let e=typeof t.getOutput=="function"?t.getOutput():[],n=e.join(`
208
+ `)}}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:Hl({sessionName:n.name,sessionId:n.id,branchName:r,baseBranch:o,promptSnippet:d,commitLines:s,moreNote:a,diffSummary:i}),notifyUser:"never"}}};function $h(t,e=1e3){let n=!Number.isFinite(e),r=typeof t.getOutput=="function"?t.getOutput():[],o=n?r.join(`
209
+ `):eA(t);return n?o:o.length>e?Dh(t)?Fi(o,e):Of(o,e):o}function eA(t){let e=typeof t.getOutput=="function"?t.getOutput():[],n=e.join(`
210
210
  `).trim();return n?Dh(t)?tA(n)??n:e.slice(-20).join(`
211
211
  `):""}function Dh(t){if(t.status==="completed"||t.killReason==="done")return!0;let e=t;return e.approvalState==="approved"||e.planModeApproved===!0||(e.planDecisionVersion??0)>0}function tA(t){let n=t.split(/\n\s*\n+/).map(r=>r.trim()).filter(r=>/[A-Za-z0-9]/.test(r)).at(-1);if(n)return n.length>=120||n.includes(`
212
- `)?n:void 0}rt();Te();import{unlinkSync as nA}from"fs";var ra=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()}};he();rs();rt();var Nh=10080*60*1e3,rA=300*1e3,Fh="tmp-output:cleanup";function oA(t){return t instanceof Error?t.message:String(t)}var oa=class{constructor(e){this.deps=e}deps;scheduler=new ra;schedule(e,n,r){this.scheduler.schedule(e,n,r)}cancel(e){this.scheduler.cancel(e)}cancelPrefix(e){this.scheduler.cancelPrefix(e)}bootstrapMaintenanceSchedules(){let e=Date.now();this.deps.store.cleanupTmpOutputFiles(e);for(let n of this.deps.store.listPersistedSessions())this.syncPersistedSessionMaintenance(n);this.syncActionTokenExpiryDeadline(),this.deps.store.cleanupOrphanOutputFiles(),this.syncTmpOutputCleanupDeadline(e)}syncRuntimeGcDeadline(e){if(!e.completedAt)return;let n=this.runtimeGcKey(e.id);this.schedule(n,e.completedAt+this.runtimeGcMaxAgeMs(),()=>{let r=this.deps.sessions.get(e.id);if(!r||!r.completedAt)return;let o=this.runtimeGcMaxAgeMs();if(!this.deps.store.shouldGcActiveSession(r,Date.now(),o)){this.syncRuntimeGcDeadline(r);return}this.deps.removeRuntimeSession(e.id),this.deps.persistSession(r,{scheduleRuntimeGc:!1}),this.deps.clearRuntimeSessionState(e.id)})}cancelRuntimeGc(e){this.cancel(this.runtimeGcKey(e))}cancelPersistedMaintenance(e){let n=this.persistedMaintenanceRef(e);n&&this.cancelPrefix(`persisted:${n}:`)}syncPersistedSessionMaintenance(e){let n=this.persistedMaintenanceRef(e);if(!n)return;this.cancel(this.persistedMaintenanceKey(n,"worktree-reminder"));let r=this.deps.reminders.getNextReminderAt(e);r!=null&&this.schedulePersistedWorktreeReminder(n,r),this.cancel(this.persistedMaintenanceKey(n,"worktree-retention"));let o=co(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),i=this.resolvedAtIso(e),s=this.isLegacyResolvedWorktree(e);if((o.cleanupSafe||s)&&typeof i=="string"){let a=new Date(i).getTime();Number.isFinite(a)&&this.schedule(this.persistedMaintenanceKey(n,"worktree-retention"),a+Nh,()=>{let d=this.deps.store.getPersistedSession(n);d&&this.reconcileResolvedWorktreeRetention(d,Date.now())})}}reconcileResolvedWorktreeRetention(e,n){let r=co(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),o=this.resolvedAtIso(e),i=o?new Date(o).getTime():0,s=this.isLegacyResolvedWorktree(e);if(!(!r.cleanupSafe&&!s||!i||n-i<Nh))try{if(!e.worktreePath&&!We(e))return;let a=this.deps.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!a)return;let d=We(e)?!1:nt(a,e.worktreePath);if(!We(e)&&!d)return;for(let l of tt(e))this.deps.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}: ${oA(a)}`)}}syncActionTokenExpiryDeadline(){let e="tokens:expiry";this.cancel(e);let n=this.deps.store.getNextActionTokenExpiry();n!=null&&this.schedule(e,n,()=>{this.deps.store.purgeExpiredActionTokens(Date.now())})}syncTmpOutputCleanupDeadline(e=Date.now()){this.cancel(Fh);let n=this.deps.store.getNextTmpOutputCleanupAt(e);n!=null&&this.schedule(Fh,n,()=>{let r=Date.now();this.deps.store.cleanupTmpOutputFiles(r),this.syncTmpOutputCleanupDeadline(r)})}enforcePersistedRetention(){let e=this.deps.store.evictOldestPersisted(this.deps.getMaxPersistedSessions());for(let n of e)this.cancelPersistedMaintenance(n),n.sessionId&&this.cancelRuntimeGc(n.sessionId),this.cleanupOutputPathIfUnreferenced(n.outputPath)}dispose(){this.scheduler.dispose()}persistedMaintenanceRef(e){return e.sessionId??M(e)??e.harnessSessionId}runtimeGcKey(e){return`runtime-gc:${e}`}persistedMaintenanceKey(e,n){return`persisted:${e}:${n}`}runtimeGcMaxAgeMs(){return(_.sessionGcAgeMinutes??1440)*6e4}schedulePersistedWorktreeReminder(e,n){let r=this.persistedMaintenanceKey(e,"worktree-reminder");this.schedule(r,n,()=>{let o=this.deps.store.getPersistedSession(e);if(!o||this.deps.reminders.sendReminderIfDue(o,Date.now()))return;let s=this.deps.reminders.getNextReminderAt(o);s!=null&&this.schedulePersistedWorktreeReminder(e,Math.max(s,Date.now()+rA))})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.deps.store.hasOutputPathReference(e)))try{nA(e)}catch{}}resolvedAtIso(e){return e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0)}isLegacyResolvedWorktree(e){return e.worktreeMerged===!0||e.worktreeDisposition==="dismissed"||e.worktreeDisposition==="no-change-cleaned"||e.worktreeState==="merged"||e.worktreeState==="dismissed"}};var Lh=new Set(["completed","failed","killed"]),iA=new Set(["starting","running"]),sA=5e3,ia=class{registry;sessions;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueue=new Sr;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;interactions;notifications;worktrees;questions;reminders;lifecycle;restore;stateSync;references;worktreeStrategy;worktreeDecisions;runtimeBootstrap;worktreeMessages;maintenance;constructor(e=20,n=50,r={}){this.maxSessions=e,this.maxPersistedSessions=n,this.registry=new ea,this.sessions=this.registry.sessions,this.store=new Fs(r.store),this.metrics=new Ls,this.wakeDispatcher=new qs,this.interactions=new Gs(this.store.actionTokenStore,dn),this.references=new Rs(this.sessions,this.store),this.stateSync=new As({store:this.store,sessions:this.sessions,resolveSession:o=>this.references.resolveActive(o)}),this.notifications=new js(this.wakeDispatcher,(o,i)=>this.stateSync.applySessionPatch(o,i)),this.worktrees=new Hs,this.restore=new xs(o=>this.store.getPersistedSession(o)),this.worktreeMessages=new na,this.worktreeStrategy=new Ms({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:ts,spawnConflictResolver:async({session:o,worktreePath:i,prompt:s})=>this.spawn({prompt:s,workdir:i,name:`${o.name}-conflict-resolver`,harness:o.harnessName||Le(),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(()=>(Ss(),wg));return{success:(await s().execute("auto-pr",{session:o.id,base_branch:i}))?.meta?.success===!0}}}),this.questions=new zs(this.pendingAskUserQuestions,(o,i)=>this.dispatchSessionNotification(o,i),o=>{this.lastWaitingEventTimestamps.delete(o)},(o,i)=>this.interactions.getQuestionButtons(o,i)),this.reminders=new Js(o=>this.buildRoutingProxy(o),(o,i)=>this.notifications.dispatch(o,i),(o,i)=>this.updatePersistedSession(o,i),o=>this.getWorktreeDecisionButtons(o)),this.maintenance=new oa({store:this.store,sessions:this.sessions,reminders:this.reminders,removeRuntimeSession:o=>this.registry.remove(o),persistSession:(o,i)=>this.persistSession(o,i),clearRuntimeSessionState:o=>{this.lastWaitingEventTimestamps.delete(o),this.lastTurnCompleteMarkers.delete(o),this.lastTerminalWakeMarkers.delete(o)},resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),getMaxPersistedSessions:()=>this.maxPersistedSessions}),this.store.onActionTokensChanged(()=>this.syncActionTokenExpiryDeadline()),this.lifecycle=new Xs({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 Zs({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 ta({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)}syncRuntimeGcDeadline(e){this.maintenance.syncRuntimeGcDeadline(e)}cancelPersistedMaintenance(e){this.maintenance.cancelPersistedMaintenance(e)}onPersistedSessionChanged(e){e&&(this.syncPersistedSessionMaintenance(e),this.enforcePersistedRetention())}syncPersistedSessionMaintenance(e){this.maintenance.syncPersistedSessionMaintenance(e)}reconcileResolvedWorktreeRetention(e,n){this.maintenance.reconcileResolvedWorktreeRetention(e,n)}syncActionTokenExpiryDeadline(){this.maintenance.syncActionTokenExpiryDeadline()}syncTmpOutputCleanupDeadline(e=Date.now()){this.maintenance.syncTmpOutputCleanupDeadline(e)}enforcePersistedRetention(){this.maintenance.enforcePersistedRetention()}bootstrapMaintenanceSchedules(){this.maintenance.bootstrapMaintenanceSchedules()}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 S=this.registry.get(e.sessionIdOverride);if(S?.status==="starting"||S?.status==="running")throw new Error(`Cannot reuse session ID ${e.sessionIdOverride}: that session is still ${S.status}.`);S&&this.registry.remove(S.id),this.lastWaitingEventTimestamps.delete(e.sessionIdOverride),this.lastTurnCompleteMarkers.delete(e.sessionIdOverride),this.lastTerminalWakeMarkers.delete(e.sessionIdOverride),this.maintenance.cancelRuntimeGc(e.sessionIdOverride)}let o=e.name||Ef(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,u=a==="claude-code"&&!e.canUseTool?async(S,y)=>{if(!l)throw new Error("canUseTool called before session ID was set");return d.handleAskUserQuestion(l,y)}:e.canUseTool,f=new is({...e,workdir:s.actualWorkdir,systemPrompt:s.effectiveSystemPrompt,canUseTool:u},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(Lh.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}Lh.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 hi({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)}isCurrentPendingPlanDecision(e,n){let r=this.resolve(e)??this.getPersistedSession(e);return wo(r,n)}dispatchPlanApprovalFallback(e,n,r){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",userMessage:vo({session:e,summary:r}),notifyUser:"always",shouldDispatch:()=>this.isCurrentPendingPlanDecision(e.id,n),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:yr(e,n,!0),wakeMessageOnNotifyFailed:Ys({session:e,planDecisionVersion: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=eu(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=ne(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(Po(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 u=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:u,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()})}},shouldDispatch:()=>this.isCurrentPendingPlanDecision(d,l),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:yr({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:ne(e)??M(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||!bs(e,n))||!n?e:Yi(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,u=r?.worktreePushRemote??o?.worktreePushRemote;this.updatePersistedSession(n,Cs({worktreeBaseBranch:d,worktreePrTargetRepo:l,worktreePushRemote:u},{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 ko(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"})}sendPlanOffer(e){let n=this.interactions.getPlanOfferButtons({offerId:e.offerId,route:e.route,planName:e.planName,planPrompt:e.planPrompt,planWorkdir:e.planWorkdir,planWorktreeStrategy:e.planWorktreeStrategy});this.dispatchSessionNotification(this.buildRoutingProxy({id:e.offerId,route:e.route}),{label:"plan-offer",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"})}launchPlanOffer(e){let n=e.route??{provider:"system",target:"system"};return this.spawn({prompt:e.prompt,workdir:e.workdir,name:e.name,harness:Le(),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<sA?!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){return $h(e,n)}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);if(!r)return!1;if(r.pendingPlanApproval){this.clearPlanDecisionTokens(r.id);let o={lifecycle:"terminal",runtimeState:"stopped",pendingPlanApproval:!1,planApprovalContext:void 0,approvalState:r.approvalState==="pending"?"rejected":r.approvalState,planDecisionVersion:(r.planDecisionVersion??0)+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};r.applyControlPatch(o),Object.assign(r,o),this.updatePersistedSession(r.id,o)}return r.kill(n??"user"),!0}killAll(e="user"){for(let n of this.sessions.values())iA.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){return this.mergeQueue.enqueue(e,n,r)}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()}};Y();Te();var Bh=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 aA="\\x1b\\[[\\x20-\\x3f]*[\\x40-\\x7e]",dA="\\x1b\\]8;;.*?(?:\\x1b\\\\|\\x07)|\\x1b\\]8;;(?:\\x1b\\\\|\\x07)",uH=new RegExp(aA,"g"),pH=new RegExp(dA,"g"),cH=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;import{createRequire as lA}from"node:module";var IH=lA(import.meta.url);var bH=new Bh(512);function Uh(t){return{success:!1,error:{issues:[{path:[],message:t}]}}}function ru(){return{safeParse(t){return t===void 0?{success:!0,data:void 0}:!t||typeof t!="object"||Array.isArray(t)?Uh("expected config object"):Object.keys(t).length>0?Uh("config must be empty"):{success:!0,data:t}},jsonSchema:{type:"object",additionalProperties:!1,properties:{}}}}function uA(t,e){let n=!1,r;return()=>(n||(r=(typeof t=="function"?t():t)??e,n=!0),r)}function sa({id:t,name:e,description:n,kind:r,configSchema:o=ru,reload:i,nodeHostCommands:s,securityAuditCollectors:a,register:d}){let l=uA(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 gA(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=fA("git",["rev-parse","--show-toplevel"],{cwd:d.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();l&&i.add(Kh(l,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let d of i)try{let l=pA(d);for(let u of l){if(!u.startsWith("openclaw-worktree-"))continue;let f=Kh(d,u);try{let S=cA(f);if(!S.isDirectory()||S.mtimeMs>r||o.has(f))continue;mA(f,{recursive:!0,force:!0}),a++}catch(S){console.warn(`[index] Failed to clean up orphaned worktree ${f}: ${S instanceof Error?S.message:String(S)}`)}}}catch{}a>0&&console.info(`[index] Cleaned up ${a} orphaned worktree(s) at startup (age > ${e}h)`)}function hA(t){let e=null,n=null,r=t.registerTool;Fi(t.runtime),r(o=>Wf(o),{optional:!1,name:"agent_launch"}),r(o=>lg(o),{optional:!1,name:"agent_sessions"}),r(o=>ug(o),{optional:!1,name:"agent_kill"}),r(o=>ls(o),{optional:!1,name:"agent_output"}),r(o=>hg(o),{optional:!1,name:"agent_respond"}),r(o=>Sg(o),{optional:!1,name:"agent_request_plan_approval"}),r(o=>kg(o),{optional:!1,name:"agent_send_plan_offer"}),r(o=>vg(o),{optional:!1,name:"agent_stats"}),r(o=>hs(o),{optional:!1,name:"agent_merge"}),r(o=>go(o),{optional:!1,name:"agent_pr"}),r(o=>Ig(o),{optional:!1,name:"agent_worktree_cleanup"}),r(o=>bg(o),{optional:!1,name:"agent_worktree_status"}),r(o=>xg(o),{optional:!1,name:"goal_launch"}),r(o=>Rg(o),{optional:!1,name:"goal_status"}),r(o=>Tg(o),{optional:!1,name:"goal_stop"}),t.registerInteractiveHandler(_l("telegram")),t.registerInteractiveHandler(_l("discord")),Dg(t),Ng(t),Fg(t),Lg(t),Wg(t),Bg(t),Kg(t),Vg(t),qg(t),t.registerService({id:"openclaw-code-agent",start:o=>{let i=t.pluginConfig??{};Xm(i),Fi(t.runtime,o.config),e=new ia(_.maxSessions,_.maxPersistedSessions),n=new Is(e),Gd(e),jd(n),n.start(),gA(e),e.bootstrapMaintenanceSchedules()},stop:()=>{n&&n.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),n=null,e=null,Fi(void 0),jd(null),Gd(null)}})}var yz=sa({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:hA});export{yz as default,hA as register};
212
+ `)?n:void 0}rt();Te();import{unlinkSync as nA}from"fs";var ra=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()}};he();rs();rt();var Nh=10080*60*1e3,rA=300*1e3,Fh="tmp-output:cleanup";function oA(t){return t instanceof Error?t.message:String(t)}var oa=class{constructor(e){this.deps=e}deps;scheduler=new ra;schedule(e,n,r){this.scheduler.schedule(e,n,r)}cancel(e){this.scheduler.cancel(e)}cancelPrefix(e){this.scheduler.cancelPrefix(e)}bootstrapMaintenanceSchedules(){let e=Date.now();this.deps.store.cleanupTmpOutputFiles(e);for(let n of this.deps.store.listPersistedSessions())this.syncPersistedSessionMaintenance(n);this.syncActionTokenExpiryDeadline(),this.deps.store.cleanupOrphanOutputFiles(),this.syncTmpOutputCleanupDeadline(e)}syncRuntimeGcDeadline(e){if(!e.completedAt)return;let n=this.runtimeGcKey(e.id);this.schedule(n,e.completedAt+this.runtimeGcMaxAgeMs(),()=>{let r=this.deps.sessions.get(e.id);if(!r||!r.completedAt)return;let o=this.runtimeGcMaxAgeMs();if(!this.deps.store.shouldGcActiveSession(r,Date.now(),o)){this.syncRuntimeGcDeadline(r);return}this.deps.removeRuntimeSession(e.id),this.deps.persistSession(r,{scheduleRuntimeGc:!1}),this.deps.clearRuntimeSessionState(e.id)})}cancelRuntimeGc(e){this.cancel(this.runtimeGcKey(e))}cancelPersistedMaintenance(e){let n=this.persistedMaintenanceRef(e);n&&this.cancelPrefix(`persisted:${n}:`)}syncPersistedSessionMaintenance(e){let n=this.persistedMaintenanceRef(e);if(!n)return;this.cancel(this.persistedMaintenanceKey(n,"worktree-reminder"));let r=this.deps.reminders.getNextReminderAt(e);r!=null&&this.schedulePersistedWorktreeReminder(n,r),this.cancel(this.persistedMaintenanceKey(n,"worktree-retention"));let o=mo(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),i=this.resolvedAtIso(e),s=this.isLegacyResolvedWorktree(e);if((o.cleanupSafe||s)&&typeof i=="string"){let a=new Date(i).getTime();Number.isFinite(a)&&this.schedule(this.persistedMaintenanceKey(n,"worktree-retention"),a+Nh,()=>{let d=this.deps.store.getPersistedSession(n);d&&this.reconcileResolvedWorktreeRetention(d,Date.now())})}}reconcileResolvedWorktreeRetention(e,n){let r=mo(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),o=this.resolvedAtIso(e),i=o?new Date(o).getTime():0,s=this.isLegacyResolvedWorktree(e);if(!(!r.cleanupSafe&&!s||!i||n-i<Nh))try{if(!e.worktreePath&&!We(e))return;let a=this.deps.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!a)return;let d=We(e)?!1:nt(a,e.worktreePath);if(!We(e)&&!d)return;for(let l of tt(e))this.deps.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}: ${oA(a)}`)}}syncActionTokenExpiryDeadline(){let e="tokens:expiry";this.cancel(e);let n=this.deps.store.getNextActionTokenExpiry();n!=null&&this.schedule(e,n,()=>{this.deps.store.purgeExpiredActionTokens(Date.now())})}syncTmpOutputCleanupDeadline(e=Date.now()){this.cancel(Fh);let n=this.deps.store.getNextTmpOutputCleanupAt(e);n!=null&&this.schedule(Fh,n,()=>{let r=Date.now();this.deps.store.cleanupTmpOutputFiles(r),this.syncTmpOutputCleanupDeadline(r)})}enforcePersistedRetention(){let e=this.deps.store.evictOldestPersisted(this.deps.getMaxPersistedSessions());for(let n of e)this.cancelPersistedMaintenance(n),n.sessionId&&this.cancelRuntimeGc(n.sessionId),this.cleanupOutputPathIfUnreferenced(n.outputPath)}dispose(){this.scheduler.dispose()}persistedMaintenanceRef(e){return e.sessionId??M(e)??e.harnessSessionId}runtimeGcKey(e){return`runtime-gc:${e}`}persistedMaintenanceKey(e,n){return`persisted:${e}:${n}`}runtimeGcMaxAgeMs(){return(_.sessionGcAgeMinutes??1440)*6e4}schedulePersistedWorktreeReminder(e,n){let r=this.persistedMaintenanceKey(e,"worktree-reminder");this.schedule(r,n,()=>{let o=this.deps.store.getPersistedSession(e);if(!o||this.deps.reminders.sendReminderIfDue(o,Date.now()))return;let s=this.deps.reminders.getNextReminderAt(o);s!=null&&this.schedulePersistedWorktreeReminder(e,Math.max(s,Date.now()+rA))})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.deps.store.hasOutputPathReference(e)))try{nA(e)}catch{}}resolvedAtIso(e){return e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0)}isLegacyResolvedWorktree(e){return e.worktreeMerged===!0||e.worktreeDisposition==="dismissed"||e.worktreeDisposition==="no-change-cleaned"||e.worktreeState==="merged"||e.worktreeState==="dismissed"}};var Lh=new Set(["completed","failed","killed"]),iA=new Set(["starting","running"]),sA=5e3,ia=class{registry;sessions;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueue=new yr;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;interactions;notifications;worktrees;questions;reminders;lifecycle;restore;stateSync;references;worktreeStrategy;worktreeDecisions;runtimeBootstrap;worktreeMessages;maintenance;constructor(e=20,n=50,r={}){this.maxSessions=e,this.maxPersistedSessions=n,this.registry=new ea,this.sessions=this.registry.sessions,this.store=new Fs(r.store),this.metrics=new Ls,this.wakeDispatcher=new qs,this.interactions=new Gs(this.store.actionTokenStore,dn),this.references=new Rs(this.sessions,this.store),this.stateSync=new As({store:this.store,sessions:this.sessions,resolveSession:o=>this.references.resolveActive(o)}),this.notifications=new js(this.wakeDispatcher,(o,i)=>this.stateSync.applySessionPatch(o,i)),this.worktrees=new Hs,this.restore=new xs(o=>this.store.getPersistedSession(o)),this.worktreeMessages=new na,this.worktreeStrategy=new Ms({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:ts,spawnConflictResolver:async({session:o,worktreePath:i,prompt:s})=>this.spawn({prompt:s,workdir:i,name:`${o.name}-conflict-resolver`,harness:o.harnessName||Le(),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(()=>(Ss(),Pg));return{success:(await s().execute("auto-pr",{session:o.id,base_branch:i}))?.meta?.success===!0}}}),this.questions=new zs(this.pendingAskUserQuestions,(o,i)=>this.dispatchSessionNotification(o,i),o=>{this.lastWaitingEventTimestamps.delete(o)},(o,i)=>this.interactions.getQuestionButtons(o,i)),this.reminders=new Js(o=>this.buildRoutingProxy(o),(o,i)=>this.notifications.dispatch(o,i),(o,i)=>this.updatePersistedSession(o,i),o=>this.getWorktreeDecisionButtons(o)),this.maintenance=new oa({store:this.store,sessions:this.sessions,reminders:this.reminders,removeRuntimeSession:o=>this.registry.remove(o),persistSession:(o,i)=>this.persistSession(o,i),clearRuntimeSessionState:o=>{this.lastWaitingEventTimestamps.delete(o),this.lastTurnCompleteMarkers.delete(o),this.lastTerminalWakeMarkers.delete(o)},resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),getMaxPersistedSessions:()=>this.maxPersistedSessions}),this.store.onActionTokensChanged(()=>this.syncActionTokenExpiryDeadline()),this.lifecycle=new Xs({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 Zs({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 ta({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)}syncRuntimeGcDeadline(e){this.maintenance.syncRuntimeGcDeadline(e)}cancelPersistedMaintenance(e){this.maintenance.cancelPersistedMaintenance(e)}onPersistedSessionChanged(e){e&&(this.syncPersistedSessionMaintenance(e),this.enforcePersistedRetention())}syncPersistedSessionMaintenance(e){this.maintenance.syncPersistedSessionMaintenance(e)}reconcileResolvedWorktreeRetention(e,n){this.maintenance.reconcileResolvedWorktreeRetention(e,n)}syncActionTokenExpiryDeadline(){this.maintenance.syncActionTokenExpiryDeadline()}syncTmpOutputCleanupDeadline(e=Date.now()){this.maintenance.syncTmpOutputCleanupDeadline(e)}enforcePersistedRetention(){this.maintenance.enforcePersistedRetention()}bootstrapMaintenanceSchedules(){this.maintenance.bootstrapMaintenanceSchedules()}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 g=this.registry.get(e.sessionIdOverride);if(g?.status==="starting"||g?.status==="running")throw new Error(`Cannot reuse session ID ${e.sessionIdOverride}: that session is still ${g.status}.`);g&&this.registry.remove(g.id),this.lastWaitingEventTimestamps.delete(e.sessionIdOverride),this.lastTurnCompleteMarkers.delete(e.sessionIdOverride),this.lastTerminalWakeMarkers.delete(e.sessionIdOverride),this.maintenance.cancelRuntimeGc(e.sessionIdOverride)}let o=e.name||_f(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,u=a==="claude-code"&&!e.canUseTool?async(g,y)=>{if(!l)throw new Error("canUseTool called before session ID was set");return d.handleAskUserQuestion(l,y)}:e.canUseTool,f=new is({...e,workdir:s.actualWorkdir,systemPrompt:s.effectiveSystemPrompt,canUseTool:u},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(Lh.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}Lh.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 Si({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)}isCurrentPendingPlanDecision(e,n){let r=this.resolve(e)??this.getPersistedSession(e);return Io(r,n)}dispatchPlanApprovalFallback(e,n,r){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",userMessage:Po({session:e,summary:r}),notifyUser:"always",shouldDispatch:()=>this.isCurrentPendingPlanDecision(e.id,n),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:kr(e,n,!0),wakeMessageOnNotifyFailed:Ys({session:e,planDecisionVersion: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=Zl(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=ne(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(wo(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 u=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:u,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()})}},shouldDispatch:()=>this.isCurrentPendingPlanDecision(d,l),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:kr({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:ne(e)??M(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||!bs(e,n))||!n?e:Yi(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,u=r?.worktreePushRemote??o?.worktreePushRemote;this.updatePersistedSession(n,Cs({worktreeBaseBranch:d,worktreePrTargetRepo:l,worktreePushRemote:u},{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 vo(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"})}sendPlanOffer(e){let n=this.interactions.getPlanOfferButtons({offerId:e.offerId,route:e.route,planName:e.planName,planPrompt:e.planPrompt,planWorkdir:e.planWorkdir,planWorktreeStrategy:e.planWorktreeStrategy});this.dispatchSessionNotification(this.buildRoutingProxy({id:e.offerId,route:e.route}),{label:"plan-offer",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"})}launchPlanOffer(e){let n=e.route??{provider:"system",target:"system"};return this.spawn({prompt:e.prompt,workdir:e.workdir,name:e.name,harness:Le(),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<sA?!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){return $h(e,n)}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);if(!r)return!1;if(r.pendingPlanApproval){this.clearPlanDecisionTokens(r.id);let o={lifecycle:"terminal",runtimeState:"stopped",pendingPlanApproval:!1,planApprovalContext:void 0,approvalState:r.approvalState==="pending"?"rejected":r.approvalState,planDecisionVersion:(r.planDecisionVersion??0)+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};r.applyControlPatch(o),Object.assign(r,o),this.updatePersistedSession(r.id,o)}return r.kill(n??"user"),!0}killAll(e="user"){for(let n of this.sessions.values())iA.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){return this.mergeQueue.enqueue(e,n,r)}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()}};Y();Te();var Bh=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 aA="\\x1b\\[[\\x20-\\x3f]*[\\x40-\\x7e]",dA="\\x1b\\]8;;.*?(?:\\x1b\\\\|\\x07)|\\x1b\\]8;;(?:\\x1b\\\\|\\x07)",uH=new RegExp(aA,"g"),pH=new RegExp(dA,"g"),cH=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;import{createRequire as lA}from"node:module";var IH=lA(import.meta.url);var bH=new Bh(512);function Uh(t){return{success:!1,error:{issues:[{path:[],message:t}]}}}function nu(){return{safeParse(t){return t===void 0?{success:!0,data:void 0}:!t||typeof t!="object"||Array.isArray(t)?Uh("expected config object"):Object.keys(t).length>0?Uh("config must be empty"):{success:!0,data:t}},jsonSchema:{type:"object",additionalProperties:!1,properties:{}}}}function uA(t,e){let n=!1,r;return()=>(n||(r=(typeof t=="function"?t():t)??e,n=!0),r)}function sa({id:t,name:e,description:n,kind:r,configSchema:o=nu,reload:i,nodeHostCommands:s,securityAuditCollectors:a,register:d}){let l=uA(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 gA(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=fA("git",["rev-parse","--show-toplevel"],{cwd:d.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();l&&i.add(Kh(l,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let d of i)try{let l=pA(d);for(let u of l){if(!u.startsWith("openclaw-worktree-"))continue;let f=Kh(d,u);try{let g=cA(f);if(!g.isDirectory()||g.mtimeMs>r||o.has(f))continue;mA(f,{recursive:!0,force:!0}),a++}catch(g){console.warn(`[index] Failed to clean up orphaned worktree ${f}: ${g instanceof Error?g.message:String(g)}`)}}}catch{}a>0&&console.info(`[index] Cleaned up ${a} orphaned worktree(s) at startup (age > ${e}h)`)}function hA(t){let e=null,n=null,r=!1,o=!1,i=t.registerTool;ur(t.runtime);let s=f=>{if(r){f&&!o&&(ur(t.runtime,f.config),o=!0);return}let g=t.pluginConfig??{};Ym(g),f?(ur(t.runtime,f.config),o=!0):(ur(t.runtime),o=!1),e=new ia(_.maxSessions,_.maxPersistedSessions),n=new Is(e),Gd(e),jd(n),n.start(),gA(e),e.bootstrapMaintenanceSchedules(),r=!0},a=()=>{n&&n.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),n=null,e=null,r=!1,o=!1,ur(void 0),jd(null),Gd(null)},d=(f,g)=>{i(y=>(s(),f(y)),g)},l={...t,registerCommand(f){t.registerCommand({...f,handler:g=>(s(),f.handler(g))})}},u=f=>{let g=Og(f);t.registerInteractiveHandler({...g,handler:async y=>(s(),g.handler(y))})};d(f=>Lf(f),{optional:!1,name:"agent_launch"}),d(f=>dg(f),{optional:!1,name:"agent_sessions"}),d(f=>lg(f),{optional:!1,name:"agent_kill"}),d(f=>ls(f),{optional:!1,name:"agent_output"}),d(f=>gg(f),{optional:!1,name:"agent_respond"}),d(f=>hg(f),{optional:!1,name:"agent_request_plan_approval"}),d(f=>yg(f),{optional:!1,name:"agent_send_plan_offer"}),d(f=>kg(f),{optional:!1,name:"agent_stats"}),d(f=>hs(f),{optional:!1,name:"agent_merge"}),d(f=>ho(f),{optional:!1,name:"agent_pr"}),d(f=>wg(f),{optional:!1,name:"agent_worktree_cleanup"}),d(f=>Ig(f),{optional:!1,name:"agent_worktree_status"}),d(f=>bg(f),{optional:!1,name:"goal_launch"}),d(f=>Ag(f),{optional:!1,name:"goal_status"}),d(f=>Rg(f),{optional:!1,name:"goal_stop"}),u("telegram"),u("discord"),Dg(l),Ng(l),Fg(l),Lg(l),Wg(l),Bg(l),Kg(l),Vg(l),qg(l),t.registerService({id:"openclaw-code-agent",start:s,stop:a})}var yz=sa({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:hA});export{yz as default,hA as register};