openclaw-code-agent 2.3.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,66 +1,123 @@
1
- var xa=Object.defineProperty;var sr=(e,t)=>{for(var n in t)xa(e,n,{get:t[n],enumerable:!0})};import{existsSync as Zm}from"fs";var J={};sr(J,{HasPropertyKey:()=>dn,IsArray:()=>K,IsAsyncIterator:()=>ir,IsBigInt:()=>Dt,IsBoolean:()=>Ke,IsDate:()=>it,IsFunction:()=>ar,IsIterator:()=>ur,IsNull:()=>dr,IsNumber:()=>ue,IsObject:()=>A,IsRegExp:()=>jt,IsString:()=>C,IsSymbol:()=>cr,IsUint8Array:()=>De,IsUndefined:()=>D});function dn(e,t){return t in e}function ir(e){return A(e)&&!K(e)&&!De(e)&&Symbol.asyncIterator in e}function K(e){return Array.isArray(e)}function Dt(e){return typeof e=="bigint"}function Ke(e){return typeof e=="boolean"}function it(e){return e instanceof globalThis.Date}function ar(e){return typeof e=="function"}function ur(e){return A(e)&&!K(e)&&!De(e)&&Symbol.iterator in e}function dr(e){return e===null}function ue(e){return typeof e=="number"}function A(e){return typeof e=="object"&&e!==null}function jt(e){return e instanceof globalThis.RegExp}function C(e){return typeof e=="string"}function cr(e){return typeof e=="symbol"}function De(e){return e instanceof globalThis.Uint8Array}function D(e){return e===void 0}function Sa(e){return e.map(t=>cn(t))}function Ta(e){return new Date(e.getTime())}function ba(e){return new Uint8Array(e)}function wa(e){return new RegExp(e.source,e.flags)}function Aa(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=cn(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=cn(e[n]);return t}function cn(e){return K(e)?Sa(e):it(e)?Ta(e):De(e)?ba(e):jt(e)?wa(e):A(e)?Aa(e):e}function F(e){return cn(e)}function yt(e,t){return t===void 0?F(e):F({...t,...e})}function no(e){return e!==null&&typeof e=="object"}function ro(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function oo(e){return e===void 0}function so(e){return typeof e=="number"}var mn;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(s,c){return e.ExactOptionalPropertyTypes?c in s:s[c]!==void 0}e.IsExactOptionalProperty=t;function n(s){let c=no(s);return e.AllowArrayObject?c:c&&!ro(s)}e.IsObjectLike=n;function r(s){return n(s)&&!(s instanceof Date)&&!(s instanceof Uint8Array)}e.IsRecordLike=r;function o(s){return e.AllowNaN?so(s):Number.isFinite(s)}e.IsNumberLike=o;function i(s){let c=oo(s);return e.AllowNullVoid?c||s===null:c}e.IsVoidLike=i})(mn||(mn={}));function Pa(e){return globalThis.Object.freeze(e).map(t=>Gt(t))}function Ra(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Gt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Gt(e[n]);return globalThis.Object.freeze(t)}function Gt(e){return K(e)?Pa(e):it(e)?e:De(e)?e:jt(e)?e:A(e)?Ra(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(mn.InstanceMode){case"freeze":return Gt(n);case"clone":return F(n);default:return n}}var W=class extends Error{constructor(t){super(t)}};var V=Symbol.for("TypeBox.Transform"),Ae=Symbol.for("TypeBox.Readonly"),Y=Symbol.for("TypeBox.Optional"),Ie=Symbol.for("TypeBox.Hint"),m=Symbol.for("TypeBox.Kind");function xt(e){return A(e)&&e[Ae]==="Readonly"}function re(e){return A(e)&&e[Y]==="Optional"}function mr(e){return h(e,"Any")}function pr(e){return h(e,"Argument")}function Pe(e){return h(e,"Array")}function at(e){return h(e,"AsyncIterator")}function ut(e){return h(e,"BigInt")}function je(e){return h(e,"Boolean")}function Re(e){return h(e,"Computed")}function Oe(e){return h(e,"Constructor")}function Oa(e){return h(e,"Date")}function Ce(e){return h(e,"Function")}function Me(e){return h(e,"Integer")}function v(e){return h(e,"Intersect")}function dt(e){return h(e,"Iterator")}function h(e,t){return A(e)&&m in e&&e[m]===t}function pn(e){return Ke(e)||ue(e)||C(e)}function de(e){return h(e,"Literal")}function ce(e){return h(e,"MappedKey")}function $(e){return h(e,"MappedResult")}function We(e){return h(e,"Never")}function Ca(e){return h(e,"Not")}function Vt(e){return h(e,"Null")}function Ee(e){return h(e,"Number")}function j(e){return h(e,"Object")}function ct(e){return h(e,"Promise")}function mt(e){return h(e,"Record")}function L(e){return h(e,"Ref")}function lr(e){return h(e,"RegExp")}function Ge(e){return h(e,"String")}function Ht(e){return h(e,"Symbol")}function me(e){return h(e,"TemplateLiteral")}function Ma(e){return h(e,"This")}function qe(e){return A(e)&&V in e}function pe(e){return h(e,"Tuple")}function Bt(e){return h(e,"Undefined")}function y(e){return h(e,"Union")}function Ea(e){return h(e,"Uint8Array")}function ka(e){return h(e,"Unknown")}function Fa(e){return h(e,"Unsafe")}function $a(e){return h(e,"Void")}function va(e){return A(e)&&m in e&&C(e[m])}function le(e){return mr(e)||pr(e)||Pe(e)||je(e)||ut(e)||at(e)||Re(e)||Oe(e)||Oa(e)||Ce(e)||Me(e)||v(e)||dt(e)||de(e)||ce(e)||$(e)||We(e)||Ca(e)||Vt(e)||Ee(e)||j(e)||ct(e)||mt(e)||L(e)||lr(e)||Ge(e)||Ht(e)||me(e)||Ma(e)||pe(e)||Bt(e)||y(e)||Ea(e)||ka(e)||Fa(e)||$a(e)||va(e)}var a={};sr(a,{IsAny:()=>co,IsArgument:()=>mo,IsArray:()=>po,IsAsyncIterator:()=>lo,IsBigInt:()=>fo,IsBoolean:()=>go,IsComputed:()=>Io,IsConstructor:()=>ho,IsDate:()=>yo,IsFunction:()=>xo,IsImport:()=>Da,IsInteger:()=>So,IsIntersect:()=>To,IsIterator:()=>bo,IsKind:()=>zo,IsKindOf:()=>I,IsLiteral:()=>qt,IsLiteralBoolean:()=>ja,IsLiteralNumber:()=>Ao,IsLiteralString:()=>wo,IsLiteralValue:()=>Po,IsMappedKey:()=>Ro,IsMappedResult:()=>Oo,IsNever:()=>Co,IsNot:()=>Mo,IsNull:()=>Eo,IsNumber:()=>ko,IsObject:()=>Fo,IsOptional:()=>Ka,IsPromise:()=>$o,IsProperties:()=>ln,IsReadonly:()=>La,IsRecord:()=>vo,IsRecursive:()=>Ga,IsRef:()=>No,IsRegExp:()=>Uo,IsSchema:()=>q,IsString:()=>_o,IsSymbol:()=>Lo,IsTemplateLiteral:()=>Ko,IsThis:()=>Do,IsTransform:()=>jo,IsTuple:()=>Go,IsUint8Array:()=>Ho,IsUndefined:()=>Vo,IsUnion:()=>hr,IsUnionLiteral:()=>Va,IsUnknown:()=>Bo,IsUnsafe:()=>Wo,IsVoid:()=>qo,TypeGuardUnknownTypeError:()=>fr});var fr=class extends W{},Na=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function io(e){try{return new RegExp(e),!0}catch{return!1}}function gr(e){if(!C(e))return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function ao(e){return Ir(e)||q(e)}function Wt(e){return D(e)||Dt(e)}function M(e){return D(e)||ue(e)}function Ir(e){return D(e)||Ke(e)}function P(e){return D(e)||C(e)}function Ua(e){return D(e)||C(e)&&gr(e)&&io(e)}function _a(e){return D(e)||C(e)&&gr(e)}function uo(e){return D(e)||q(e)}function La(e){return A(e)&&e[Ae]==="Readonly"}function Ka(e){return A(e)&&e[Y]==="Optional"}function co(e){return I(e,"Any")&&P(e.$id)}function mo(e){return I(e,"Argument")&&ue(e.index)}function po(e){return I(e,"Array")&&e.type==="array"&&P(e.$id)&&q(e.items)&&M(e.minItems)&&M(e.maxItems)&&Ir(e.uniqueItems)&&uo(e.contains)&&M(e.minContains)&&M(e.maxContains)}function lo(e){return I(e,"AsyncIterator")&&e.type==="AsyncIterator"&&P(e.$id)&&q(e.items)}function fo(e){return I(e,"BigInt")&&e.type==="bigint"&&P(e.$id)&&Wt(e.exclusiveMaximum)&&Wt(e.exclusiveMinimum)&&Wt(e.maximum)&&Wt(e.minimum)&&Wt(e.multipleOf)}function go(e){return I(e,"Boolean")&&e.type==="boolean"&&P(e.$id)}function Io(e){return I(e,"Computed")&&C(e.target)&&K(e.parameters)&&e.parameters.every(t=>q(t))}function ho(e){return I(e,"Constructor")&&e.type==="Constructor"&&P(e.$id)&&K(e.parameters)&&e.parameters.every(t=>q(t))&&q(e.returns)}function yo(e){return I(e,"Date")&&e.type==="Date"&&P(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function xo(e){return I(e,"Function")&&e.type==="Function"&&P(e.$id)&&K(e.parameters)&&e.parameters.every(t=>q(t))&&q(e.returns)}function Da(e){return I(e,"Import")&&dn(e,"$defs")&&A(e.$defs)&&ln(e.$defs)&&dn(e,"$ref")&&C(e.$ref)&&e.$ref in e.$defs}function So(e){return I(e,"Integer")&&e.type==="integer"&&P(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function ln(e){return A(e)&&Object.entries(e).every(([t,n])=>gr(t)&&q(n))}function To(e){return I(e,"Intersect")&&!(C(e.type)&&e.type!=="object")&&K(e.allOf)&&e.allOf.every(t=>q(t)&&!jo(t))&&P(e.type)&&(Ir(e.unevaluatedProperties)||uo(e.unevaluatedProperties))&&P(e.$id)}function bo(e){return I(e,"Iterator")&&e.type==="Iterator"&&P(e.$id)&&q(e.items)}function I(e,t){return A(e)&&m in e&&e[m]===t}function wo(e){return qt(e)&&C(e.const)}function Ao(e){return qt(e)&&ue(e.const)}function ja(e){return qt(e)&&Ke(e.const)}function qt(e){return I(e,"Literal")&&P(e.$id)&&Po(e.const)}function Po(e){return Ke(e)||ue(e)||C(e)}function Ro(e){return I(e,"MappedKey")&&K(e.keys)&&e.keys.every(t=>ue(t)||C(t))}function Oo(e){return I(e,"MappedResult")&&ln(e.properties)}function Co(e){return I(e,"Never")&&A(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Mo(e){return I(e,"Not")&&q(e.not)}function Eo(e){return I(e,"Null")&&e.type==="null"&&P(e.$id)}function ko(e){return I(e,"Number")&&e.type==="number"&&P(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function Fo(e){return I(e,"Object")&&e.type==="object"&&P(e.$id)&&ln(e.properties)&&ao(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function $o(e){return I(e,"Promise")&&e.type==="Promise"&&P(e.$id)&&q(e.item)}function vo(e){return I(e,"Record")&&e.type==="object"&&P(e.$id)&&ao(e.additionalProperties)&&A(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&io(n[0])&&A(t.patternProperties)&&q(t.patternProperties[n[0]])})(e)}function Ga(e){return A(e)&&Ie in e&&e[Ie]==="Recursive"}function No(e){return I(e,"Ref")&&P(e.$id)&&C(e.$ref)}function Uo(e){return I(e,"RegExp")&&P(e.$id)&&C(e.source)&&C(e.flags)&&M(e.maxLength)&&M(e.minLength)}function _o(e){return I(e,"String")&&e.type==="string"&&P(e.$id)&&M(e.minLength)&&M(e.maxLength)&&Ua(e.pattern)&&_a(e.format)}function Lo(e){return I(e,"Symbol")&&e.type==="symbol"&&P(e.$id)}function Ko(e){return I(e,"TemplateLiteral")&&e.type==="string"&&C(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Do(e){return I(e,"This")&&P(e.$id)&&C(e.$ref)}function jo(e){return A(e)&&V in e}function Go(e){return I(e,"Tuple")&&e.type==="array"&&P(e.$id)&&ue(e.minItems)&&ue(e.maxItems)&&e.minItems===e.maxItems&&(D(e.items)&&D(e.additionalItems)&&e.minItems===0||K(e.items)&&e.items.every(t=>q(t)))}function Vo(e){return I(e,"Undefined")&&e.type==="undefined"&&P(e.$id)}function Va(e){return hr(e)&&e.anyOf.every(t=>wo(t)||Ao(t))}function hr(e){return I(e,"Union")&&P(e.$id)&&A(e)&&K(e.anyOf)&&e.anyOf.every(t=>q(t))}function Ho(e){return I(e,"Uint8Array")&&e.type==="Uint8Array"&&P(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function Bo(e){return I(e,"Unknown")&&P(e.$id)}function Wo(e){return I(e,"Unsafe")}function qo(e){return I(e,"Void")&&e.type==="void"&&P(e.$id)}function zo(e){return A(e)&&m in e&&C(e[m])&&!Na.includes(e[m])}function q(e){return A(e)&&(co(e)||mo(e)||po(e)||go(e)||fo(e)||lo(e)||Io(e)||ho(e)||yo(e)||xo(e)||So(e)||To(e)||bo(e)||qt(e)||Ro(e)||Oo(e)||Co(e)||Mo(e)||Eo(e)||ko(e)||Fo(e)||$o(e)||vo(e)||No(e)||Uo(e)||_o(e)||Lo(e)||Ko(e)||Do(e)||Go(e)||Vo(e)||hr(e)||Ho(e)||Bo(e)||Wo(e)||qo(e)||zo(e))}var yr="(true|false)",zt="(0|[1-9][0-9]*)",xr="(.*)",Ha="(?!.*)",wf=`^${yr}$`,ze=`^${zt}$`,Ye=`^${xr}$`,Yo=`^${Ha}$`;function Jo(e,t){return e.includes(t)}function Xo(e){return[...new Set(e)]}function Ba(e,t){return e.filter(n=>t.includes(n))}function Wa(e,t){return e.reduce((n,r)=>Ba(n,r),t)}function Qo(e){return e.length===1?e[0]:e.length>1?Wa(e.slice(1),e[0]):[]}function Zo(e){let t=[];for(let n of e)t.push(...n);return t}function Je(e){return u({[m]:"Any"},e)}function St(e,t){return u({[m]:"Array",type:"array",items:e},t)}function es(e){return u({[m]:"Argument",index:e})}function Tt(e,t){return u({[m]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function k(e,t,n){return u({[m]:"Computed",target:e,parameters:t},n)}function qa(e,t){let{[t]:n,...r}=e;return r}function N(e,t){return t.reduce((n,r)=>qa(n,r),e)}function x(e){return u({[m]:"Never",not:{}},e)}function S(e){return u({[m]:"MappedResult",properties:e})}function bt(e,t,n){return u({[m]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function Ne(e,t,n){return u({[m]:"Function",type:"Function",parameters:e,returns:t},n)}function Yt(e,t){return u({[m]:"Union",anyOf:e},t)}function za(e){return e.some(t=>re(t))}function ts(e){return e.map(t=>re(t)?Ya(t):t)}function Ya(e){return N(e,[Y])}function Ja(e,t){return za(e)?X(Yt(ts(e),t)):Yt(ts(e),t)}function Ue(e,t){return e.length===1?u(e[0],t):e.length===0?x(t):Ja(e,t)}function w(e,t){return e.length===0?x(t):e.length===1?u(e[0],t):Yt(e,t)}var fn=class extends W{};function Xa(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Sr(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function He(e,t){return Sr(e,t,"(")}function Jt(e,t){return Sr(e,t,")")}function ns(e,t){return Sr(e,t,"|")}function Qa(e){if(!(He(e,0)&&Jt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(He(e,n)&&(t+=1),Jt(e,n)&&(t-=1),t===0&&n!==e.length-1)return!1;return!0}function Za(e){return e.slice(1,e.length-1)}function eu(e){let t=0;for(let n=0;n<e.length;n++)if(He(e,n)&&(t+=1),Jt(e,n)&&(t-=1),ns(e,n)&&t===0)return!0;return!1}function tu(e){for(let t=0;t<e.length;t++)if(He(e,t))return!0;return!1}function nu(e){let[t,n]=[0,0],r=[];for(let i=0;i<e.length;i++)if(He(e,i)&&(t+=1),Jt(e,i)&&(t-=1),ns(e,i)&&t===0){let s=e.slice(n,i);s.length>0&&r.push(wt(s)),n=i+1}let o=e.slice(n);return o.length>0&&r.push(wt(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function ru(e){function t(o,i){if(!He(o,i))throw new fn("TemplateLiteralParser: Index must point to open parens");let s=0;for(let c=i;c<o.length;c++)if(He(o,c)&&(s+=1),Jt(o,c)&&(s-=1),s===0)return[i,c];throw new fn("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,i){for(let s=i;s<o.length;s++)if(He(o,s))return[i,s];return[i,o.length]}let r=[];for(let o=0;o<e.length;o++)if(He(e,o)){let[i,s]=t(e,o),c=e.slice(i,s+1);r.push(wt(c)),o=s}else{let[i,s]=n(e,o),c=e.slice(i,s);c.length>0&&r.push(wt(c)),o=s-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function wt(e){return Qa(e)?wt(Za(e)):eu(e)?nu(e):tu(e)?ru(e):{type:"const",const:Xa(e)}}function At(e){return wt(e.slice(1,e.length-1))}var Tr=class extends W{};function ou(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="0"&&e.expr[1].type==="const"&&e.expr[1].const==="[1-9][0-9]*"}function su(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="true"&&e.expr[1].type==="const"&&e.expr[1].const==="false"}function iu(e){return e.type==="const"&&e.const===".*"}function pt(e){return ou(e)||iu(e)?!1:su(e)?!0:e.type==="and"?e.expr.every(t=>pt(t)):e.type==="or"?e.expr.every(t=>pt(t)):e.type==="const"?!0:(()=>{throw new Tr("Unknown expression type")})()}function rs(e){let t=At(e.pattern);return pt(t)}var br=class extends W{};function*os(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let n of os(e.slice(1)))yield`${t}${n}`}function*au(e){return yield*os(e.expr.map(t=>[...Xt(t)]))}function*uu(e){for(let t of e.expr)yield*Xt(t)}function*du(e){return yield e.const}function*Xt(e){return e.type==="and"?yield*au(e):e.type==="or"?yield*uu(e):e.type==="const"?yield*du(e):(()=>{throw new br("Unknown expression")})()}function gn(e){let t=At(e.pattern);return pt(t)?[...Xt(t)]:[]}function b(e,t){return u({[m]:"Literal",const:e,type:typeof e},t)}function In(e){return u({[m]:"Boolean",type:"boolean"},e)}function Pt(e){return u({[m]:"BigInt",type:"bigint"},e)}function he(e){return u({[m]:"Number",type:"number"},e)}function ke(e){return u({[m]:"String",type:"string"},e)}function*cu(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield In():t==="number"?yield he():t==="bigint"?yield Pt():t==="string"?yield ke():yield(()=>{let n=t.split("|").map(r=>b(r.trim()));return n.length===0?x():n.length===1?n[0]:Ue(n)})()}function*mu(e){if(e[1]!=="{"){let t=b("$"),n=wr(e.slice(1));return yield*[t,...n]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let n=cu(e.slice(2,t)),r=wr(e.slice(t+1));return yield*[...n,...r]}yield b(e)}function*wr(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=b(e.slice(0,t)),r=mu(e.slice(t));return yield*[n,...r]}yield b(e)}function ss(e){return[...wr(e)]}var Ar=class extends W{};function pu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function is(e,t){return me(e)?e.pattern.slice(1,e.pattern.length-1):y(e)?`(${e.anyOf.map(n=>is(n,t)).join("|")})`:Ee(e)?`${t}${zt}`:Me(e)?`${t}${zt}`:ut(e)?`${t}${zt}`:Ge(e)?`${t}${xr}`:de(e)?`${t}${pu(e.const.toString())}`:je(e)?`${t}${yr}`:(()=>{throw new Ar(`Unexpected Kind '${e[m]}'`)})()}function Pr(e){return`^${e.map(t=>is(t,"")).join("")}$`}function lt(e){let n=gn(e).map(r=>b(r));return Ue(n)}function hn(e,t){let n=C(e)?Pr(ss(e)):Pr(e);return u({[m]:"TemplateLiteral",type:"string",pattern:n},t)}function lu(e){return gn(e).map(n=>n.toString())}function fu(e){let t=[];for(let n of e)t.push(...oe(n));return t}function gu(e){return[e.toString()]}function oe(e){return[...new Set(me(e)?lu(e):y(e)?fu(e.anyOf):de(e)?gu(e.const):Ee(e)?["[number]"]:Me(e)?["[number]"]:[])]}function Iu(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=Xe(e,oe(t[o]),n);return r}function hu(e,t,n){return Iu(e,t.properties,n)}function as(e,t,n){let r=hu(e,t,n);return S(r)}function ds(e,t){return e.map(n=>cs(n,t))}function yu(e){return e.filter(t=>!We(t))}function xu(e,t){return yn(yu(ds(e,t)))}function Su(e){return e.some(t=>We(t))?[]:e}function Tu(e,t){return Ue(Su(ds(e,t)))}function bu(e,t){return t in e?e[t]:t==="[number]"?Ue(e):x()}function wu(e,t){return t==="[number]"?e:x()}function Au(e,t){return t in e?e[t]:x()}function cs(e,t){return v(e)?xu(e.allOf,t):y(e)?Tu(e.anyOf,t):pe(e)?bu(e.items??[],t):Pe(e)?wu(e.items,t):j(e)?Au(e.properties,t):x()}function Rr(e,t){return t.map(n=>cs(e,n))}function us(e,t){return Ue(Rr(e,t))}function Xe(e,t,n){if(L(e)||L(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!le(e)||!le(t))throw new W(r);return k("Index",[e,t])}return $(t)?as(e,t,n):ce(t)?ms(e,t,n):u(le(t)?us(e,oe(t)):us(e,t),n)}function Pu(e,t,n){return{[t]:Xe(e,[t],F(n))}}function Ru(e,t,n){return t.reduce((r,o)=>({...r,...Pu(e,o,n)}),{})}function Ou(e,t,n){return Ru(e,t.keys,n)}function ms(e,t,n){let r=Ou(e,t,n);return S(r)}function Rt(e,t){return u({[m]:"Iterator",type:"Iterator",items:e},t)}function Cu(e){return globalThis.Object.keys(e).filter(t=>!re(e[t]))}function Mu(e,t){let n=Cu(e),r=n.length>0?{[m]:"Object",type:"object",required:n,properties:e}:{[m]:"Object",type:"object",properties:e};return u(r,t)}var R=Mu;function xn(e,t){return u({[m]:"Promise",type:"Promise",item:e},t)}function Eu(e){return u(N(e,[Ae]))}function ku(e){return u({...e,[Ae]:"Readonly"})}function Fu(e,t){return t===!1?Eu(e):ku(e)}function se(e,t){let n=t??!0;return $(e)?ps(e,n):Fu(e,n)}function $u(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=se(e[r],t);return n}function vu(e,t){return $u(e.properties,t)}function ps(e,t){let n=vu(e,t);return S(n)}function ye(e,t){return u(e.length>0?{[m]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[m]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function ls(e,t){return e in t?xe(e,t[e]):S(t)}function Nu(e){return{[e]:b(e)}}function Uu(e){let t={};for(let n of e)t[n]=b(n);return t}function _u(e,t){return Jo(t,e)?Nu(e):Uu(t)}function Lu(e,t){let n=_u(e,t);return ls(e,n)}function Qt(e,t){return t.map(n=>xe(e,n))}function Ku(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=xe(e,t[r]);return n}function xe(e,t){let n={...t};return re(t)?X(xe(e,N(t,[Y]))):xt(t)?se(xe(e,N(t,[Ae]))):$(t)?ls(e,t.properties):ce(t)?Lu(e,t.keys):Oe(t)?bt(Qt(e,t.parameters),xe(e,t.returns),n):Ce(t)?Ne(Qt(e,t.parameters),xe(e,t.returns),n):at(t)?Tt(xe(e,t.items),n):dt(t)?Rt(xe(e,t.items),n):v(t)?Q(Qt(e,t.allOf),n):y(t)?w(Qt(e,t.anyOf),n):pe(t)?ye(Qt(e,t.items??[]),n):j(t)?R(Ku(e,t.properties),n):Pe(t)?St(xe(e,t.items),n):ct(t)?xn(xe(e,t.item),n):t}function Du(e,t){let n={};for(let r of e)n[r]=xe(r,t);return n}function fs(e,t,n){let r=le(e)?oe(e):e,o=t({[m]:"MappedKey",keys:r}),i=Du(r,o);return R(i,n)}function ju(e){return u(N(e,[Y]))}function Gu(e){return u({...e,[Y]:"Optional"})}function Vu(e,t){return t===!1?ju(e):Gu(e)}function X(e,t){let n=t??!0;return $(e)?gs(e,n):Vu(e,n)}function Hu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=X(e[r],t);return n}function Bu(e,t){return Hu(e.properties,t)}function gs(e,t){let n=Bu(e,t);return S(n)}function Zt(e,t={}){let n=e.every(o=>j(o)),r=le(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||le(t.unevaluatedProperties)||n?{...r,[m]:"Intersect",type:"object",allOf:e}:{...r,[m]:"Intersect",allOf:e},t)}function Wu(e){return e.every(t=>re(t))}function qu(e){return N(e,[Y])}function Is(e){return e.map(t=>re(t)?qu(t):t)}function zu(e,t){return Wu(e)?X(Zt(Is(e),t)):Zt(Is(e),t)}function yn(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>qe(n)))throw new Error("Cannot intersect transform types");return zu(e,t)}function Q(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>qe(n)))throw new Error("Cannot intersect transform types");return Zt(e,t)}function _e(...e){let[t,n]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new W("Ref: $ref must be a string");return u({[m]:"Ref",$ref:t},n)}function Yu(e,t){return k("Awaited",[k(e,t)])}function Ju(e){return k("Awaited",[_e(e)])}function Xu(e){return Q(hs(e))}function Qu(e){return w(hs(e))}function Zu(e){return Ot(e)}function hs(e){return e.map(t=>Ot(t))}function Ot(e,t){return u(Re(e)?Yu(e.target,e.parameters):v(e)?Xu(e.allOf):y(e)?Qu(e.anyOf):ct(e)?Zu(e.item):L(e)?Ju(e.$ref):e,t)}function ys(e){let t=[];for(let n of e)t.push(en(n));return t}function ed(e){let t=ys(e);return Zo(t)}function td(e){let t=ys(e);return Qo(t)}function nd(e){return e.map((t,n)=>n.toString())}function rd(e){return["[number]"]}function od(e){return globalThis.Object.getOwnPropertyNames(e)}function sd(e){return id?globalThis.Object.getOwnPropertyNames(e).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function en(e){return v(e)?ed(e.allOf):y(e)?td(e.anyOf):pe(e)?nd(e.items??[]):Pe(e)?rd(e.items):j(e)?od(e.properties):mt(e)?sd(e.patternProperties):[]}var id=!1;function ad(e,t){return k("KeyOf",[k(e,t)])}function ud(e){return k("KeyOf",[_e(e)])}function dd(e,t){let n=en(e),r=cd(n),o=Ue(r);return u(o,t)}function cd(e){return e.map(t=>t==="[number]"?he():b(t))}function Ct(e,t){return Re(e)?ad(e.target,e.parameters):L(e)?ud(e.$ref):$(e)?xs(e,t):dd(e,t)}function md(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ct(e[r],F(t));return n}function pd(e,t){return md(e.properties,t)}function xs(e,t){let n=pd(e,t);return S(n)}function ld(e){let t=[];for(let n of e)t.push(...en(n));return Xo(t)}function fd(e){return e.filter(t=>!We(t))}function gd(e,t){let n=[];for(let r of e)n.push(...Rr(r,[t]));return fd(n)}function Id(e,t){let n={};for(let r of t)n[r]=yn(gd(e,r));return n}function Ss(e,t){let n=ld(e),r=Id(e,n);return R(r,t)}function Sn(e){return u({[m]:"Date",type:"Date"},e)}function Tn(e){return u({[m]:"Null",type:"null"},e)}function bn(e){return u({[m]:"Symbol",type:"symbol"},e)}function wn(e){return u({[m]:"Undefined",type:"undefined"},e)}function An(e){return u({[m]:"Uint8Array",type:"Uint8Array"},e)}function Qe(e){return u({[m]:"Unknown"},e)}function hd(e){return e.map(t=>Or(t,!1))}function yd(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=se(Or(e[n],!1));return t}function Pn(e,t){return t===!0?e:se(e)}function Or(e,t){return ir(e)?Pn(Je(),t):ur(e)?Pn(Je(),t):K(e)?se(ye(hd(e))):De(e)?An():it(e)?Sn():A(e)?Pn(R(yd(e)),t):ar(e)?Pn(Ne([],Qe()),t):D(e)?wn():dr(e)?Tn():cr(e)?bn():Dt(e)?Pt():ue(e)?b(e):Ke(e)?b(e):C(e)?b(e):R({})}function Ts(e,t){return u(Or(e,!0),t)}function bs(e,t){return Oe(e)?ye(e.parameters,t):x(t)}function ws(e,t){if(D(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(i=>isNaN(i)).map(i=>e[i]),o=[...new Set(n)].map(i=>b(i));return w(o,{...t,[Ie]:"Enum"})}var Mr=class extends W{},d;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(d||(d={}));function Se(e){return e===d.False?e:d.True}function Mt(e){throw new Mr(e)}function H(e){return a.IsNever(e)||a.IsIntersect(e)||a.IsUnion(e)||a.IsUnknown(e)||a.IsAny(e)}function B(e,t){return a.IsNever(t)?Es(e,t):a.IsIntersect(t)?Rn(e,t):a.IsUnion(t)?$r(e,t):a.IsUnknown(t)?vs(e,t):a.IsAny(t)?Fr(e,t):Mt("StructuralRight")}function Fr(e,t){return d.True}function xd(e,t){return a.IsIntersect(t)?Rn(e,t):a.IsUnion(t)&&t.anyOf.some(n=>a.IsAny(n)||a.IsUnknown(n))?d.True:a.IsUnion(t)?d.Union:a.IsUnknown(t)||a.IsAny(t)?d.True:d.Union}function Sd(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)?d.True:d.False}function Td(e,t){return a.IsObject(t)&&On(t)?d.True:H(t)?B(e,t):a.IsArray(t)?Se(O(e.items,t.items)):d.False}function bd(e,t){return H(t)?B(e,t):a.IsAsyncIterator(t)?Se(O(e.items,t.items)):d.False}function wd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsBigInt(t)?d.True:d.False}function Cs(e,t){return a.IsLiteralBoolean(e)||a.IsBoolean(e)?d.True:d.False}function Ad(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsBoolean(t)?d.True:d.False}function Pd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsConstructor(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>Se(O(t.parameters[r],n))===d.True)?Se(O(e.returns,t.returns)):d.False:d.False}function Rd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsDate(t)?d.True:d.False}function Od(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsFunction(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>Se(O(t.parameters[r],n))===d.True)?Se(O(e.returns,t.returns)):d.False:d.False}function Ms(e,t){return a.IsLiteral(e)&&J.IsNumber(e.const)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function Cd(e,t){return a.IsInteger(t)||a.IsNumber(t)?d.True:H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):d.False}function Rn(e,t){return t.allOf.every(n=>O(e,n)===d.True)?d.True:d.False}function Md(e,t){return e.allOf.some(n=>O(n,t)===d.True)?d.True:d.False}function Ed(e,t){return H(t)?B(e,t):a.IsIterator(t)?Se(O(e.items,t.items)):d.False}function kd(e,t){return a.IsLiteral(t)&&t.const===e.const?d.True:H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsString(t)?$s(e,t):a.IsNumber(t)?ks(e,t):a.IsInteger(t)?Ms(e,t):a.IsBoolean(t)?Cs(e,t):d.False}function Es(e,t){return d.False}function Fd(e,t){return d.True}function As(e){let[t,n]=[e,0];for(;a.IsNot(t);)t=t.not,n+=1;return n%2===0?t:Qe()}function $d(e,t){return a.IsNot(e)?O(As(e),t):a.IsNot(t)?O(e,As(t)):Mt("Invalid fallthrough for Not")}function vd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsNull(t)?d.True:d.False}function ks(e,t){return a.IsLiteralNumber(e)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function Nd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsInteger(t)||a.IsNumber(t)?d.True:d.False}function ie(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Ps(e){return On(e)}function Rs(e){return ie(e,0)||ie(e,1)&&"description"in e.properties&&a.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(a.IsString(e.properties.description.anyOf[0])&&a.IsUndefined(e.properties.description.anyOf[1])||a.IsString(e.properties.description.anyOf[1])&&a.IsUndefined(e.properties.description.anyOf[0]))}function Cr(e){return ie(e,0)}function Os(e){return ie(e,0)}function Ud(e){return ie(e,0)}function _d(e){return ie(e,0)}function Ld(e){return On(e)}function Kd(e){let t=he();return ie(e,0)||ie(e,1)&&"length"in e.properties&&Se(O(e.properties.length,t))===d.True}function Dd(e){return ie(e,0)}function On(e){let t=he();return ie(e,0)||ie(e,1)&&"length"in e.properties&&Se(O(e.properties.length,t))===d.True}function jd(e){let t=Ne([Je()],Je());return ie(e,0)||ie(e,1)&&"then"in e.properties&&Se(O(e.properties.then,t))===d.True}function Fs(e,t){return O(e,t)===d.False||a.IsOptional(e)&&!a.IsOptional(t)?d.False:d.True}function Z(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)||a.IsLiteralString(e)&&Ps(t)||a.IsLiteralNumber(e)&&Cr(t)||a.IsLiteralBoolean(e)&&Os(t)||a.IsSymbol(e)&&Rs(t)||a.IsBigInt(e)&&Ud(t)||a.IsString(e)&&Ps(t)||a.IsSymbol(e)&&Rs(t)||a.IsNumber(e)&&Cr(t)||a.IsInteger(e)&&Cr(t)||a.IsBoolean(e)&&Os(t)||a.IsUint8Array(e)&&Ld(t)||a.IsDate(e)&&_d(t)||a.IsConstructor(e)&&Dd(t)||a.IsFunction(e)&&Kd(t)?d.True:a.IsRecord(e)&&a.IsString(Er(e))?t[Ie]==="Record"?d.True:d.False:a.IsRecord(e)&&a.IsNumber(Er(e))&&ie(t,0)?d.True:d.False}function Gd(e,t){return H(t)?B(e,t):a.IsRecord(t)?Te(e,t):a.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!a.IsOptional(t.properties[n]))return d.False;if(a.IsOptional(t.properties[n]))return d.True;if(Fs(e.properties[n],t.properties[n])===d.False)return d.False}return d.True})():d.False}function Vd(e,t){return H(t)?B(e,t):a.IsObject(t)&&jd(t)?d.True:a.IsPromise(t)?Se(O(e.item,t.item)):d.False}function Er(e){return ze in e.patternProperties?he():Ye in e.patternProperties?ke():Mt("Unknown record key pattern")}function kr(e){return ze in e.patternProperties?e.patternProperties[ze]:Ye in e.patternProperties?e.patternProperties[Ye]:Mt("Unable to get record value schema")}function Te(e,t){let[n,r]=[Er(t),kr(t)];return a.IsLiteralString(e)&&a.IsNumber(n)&&Se(O(e,r))===d.True?d.True:a.IsUint8Array(e)&&a.IsNumber(n)||a.IsString(e)&&a.IsNumber(n)||a.IsArray(e)&&a.IsNumber(n)?O(e,r):a.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(Fs(r,e.properties[o])===d.False)return d.False;return d.True})():d.False}function Hd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?O(kr(e),kr(t)):d.False}function Bd(e,t){let n=a.IsRegExp(e)?ke():e,r=a.IsRegExp(t)?ke():t;return O(n,r)}function $s(e,t){return a.IsLiteral(e)&&J.IsString(e.const)||a.IsString(e)?d.True:d.False}function Wd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsString(t)?d.True:d.False}function qd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsSymbol(t)?d.True:d.False}function zd(e,t){return a.IsTemplateLiteral(e)?O(lt(e),t):a.IsTemplateLiteral(t)?O(e,lt(t)):Mt("Invalid fallthrough for TemplateLiteral")}function Yd(e,t){return a.IsArray(t)&&e.items!==void 0&&e.items.every(n=>O(n,t.items)===d.True)}function Jd(e,t){return a.IsNever(e)?d.True:a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:d.False}function Xd(e,t){return H(t)?B(e,t):a.IsObject(t)&&On(t)||a.IsArray(t)&&Yd(e,t)?d.True:a.IsTuple(t)?J.IsUndefined(e.items)&&!J.IsUndefined(t.items)||!J.IsUndefined(e.items)&&J.IsUndefined(t.items)?d.False:J.IsUndefined(e.items)&&!J.IsUndefined(t.items)||e.items.every((n,r)=>O(n,t.items[r])===d.True)?d.True:d.False:d.False}function Qd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsUint8Array(t)?d.True:d.False}function Zd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsVoid(t)?nc(e,t):a.IsUndefined(t)?d.True:d.False}function $r(e,t){return t.anyOf.some(n=>O(e,n)===d.True)?d.True:d.False}function ec(e,t){return e.anyOf.every(n=>O(n,t)===d.True)?d.True:d.False}function vs(e,t){return d.True}function tc(e,t){return a.IsNever(t)?Es(e,t):a.IsIntersect(t)?Rn(e,t):a.IsUnion(t)?$r(e,t):a.IsAny(t)?Fr(e,t):a.IsString(t)?$s(e,t):a.IsNumber(t)?ks(e,t):a.IsInteger(t)?Ms(e,t):a.IsBoolean(t)?Cs(e,t):a.IsArray(t)?Sd(e,t):a.IsTuple(t)?Jd(e,t):a.IsObject(t)?Z(e,t):a.IsUnknown(t)?d.True:d.False}function nc(e,t){return a.IsUndefined(e)||a.IsUndefined(e)?d.True:d.False}function rc(e,t){return a.IsIntersect(t)?Rn(e,t):a.IsUnion(t)?$r(e,t):a.IsUnknown(t)?vs(e,t):a.IsAny(t)?Fr(e,t):a.IsObject(t)?Z(e,t):a.IsVoid(t)?d.True:d.False}function O(e,t){return a.IsTemplateLiteral(e)||a.IsTemplateLiteral(t)?zd(e,t):a.IsRegExp(e)||a.IsRegExp(t)?Bd(e,t):a.IsNot(e)||a.IsNot(t)?$d(e,t):a.IsAny(e)?xd(e,t):a.IsArray(e)?Td(e,t):a.IsBigInt(e)?wd(e,t):a.IsBoolean(e)?Ad(e,t):a.IsAsyncIterator(e)?bd(e,t):a.IsConstructor(e)?Pd(e,t):a.IsDate(e)?Rd(e,t):a.IsFunction(e)?Od(e,t):a.IsInteger(e)?Cd(e,t):a.IsIntersect(e)?Md(e,t):a.IsIterator(e)?Ed(e,t):a.IsLiteral(e)?kd(e,t):a.IsNever(e)?Fd(e,t):a.IsNull(e)?vd(e,t):a.IsNumber(e)?Nd(e,t):a.IsObject(e)?Gd(e,t):a.IsRecord(e)?Hd(e,t):a.IsString(e)?Wd(e,t):a.IsSymbol(e)?qd(e,t):a.IsTuple(e)?Xd(e,t):a.IsPromise(e)?Vd(e,t):a.IsUint8Array(e)?Qd(e,t):a.IsUndefined(e)?Zd(e,t):a.IsUnion(e)?ec(e,t):a.IsUnknown(e)?tc(e,t):a.IsVoid(e)?rc(e,t):Mt(`Unknown left type operand '${e[m]}'`)}function Ze(e,t){return O(e,t)}function oc(e,t,n,r,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(e))i[s]=Et(e[s],t,n,r,F(o));return i}function sc(e,t,n,r,o){return oc(e.properties,t,n,r,o)}function Ns(e,t,n,r,o){let i=sc(e,t,n,r,o);return S(i)}function ic(e,t,n,r){let o=Ze(e,t);return o===d.Union?w([n,r]):o===d.True?n:r}function Et(e,t,n,r,o){return $(e)?Ns(e,t,n,r,o):ce(e)?u(Us(e,t,n,r,o)):u(ic(e,t,n,r),o)}function ac(e,t,n,r,o){return{[e]:Et(b(e),t,n,r,F(o))}}function uc(e,t,n,r,o){return e.reduce((i,s)=>({...i,...ac(s,t,n,r,o)}),{})}function dc(e,t,n,r,o){return uc(e.keys,t,n,r,o)}function Us(e,t,n,r,o){let i=dc(e,t,n,r,o);return S(i)}function _s(e,t){return kt(lt(e),t)}function cc(e,t){let n=e.filter(r=>Ze(r,t)===d.False);return n.length===1?n[0]:w(n)}function kt(e,t,n={}){return me(e)?u(_s(e,t),n):$(e)?u(Ls(e,t),n):u(y(e)?cc(e.anyOf,t):Ze(e,t)!==d.False?x():e,n)}function mc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=kt(e[r],t);return n}function pc(e,t){return mc(e.properties,t)}function Ls(e,t){let n=pc(e,t);return S(n)}function Ks(e,t){return Ft(lt(e),t)}function lc(e,t){let n=e.filter(r=>Ze(r,t)!==d.False);return n.length===1?n[0]:w(n)}function Ft(e,t,n){return me(e)?u(Ks(e,t),n):$(e)?u(Ds(e,t),n):u(y(e)?lc(e.anyOf,t):Ze(e,t)!==d.False?e:x(),n)}function fc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ft(e[r],t);return n}function gc(e,t){return fc(e.properties,t)}function Ds(e,t){let n=gc(e,t);return S(n)}function js(e,t){return Oe(e)?u(e.returns,t):x(t)}function Cn(e){return se(X(e))}function ft(e,t,n){return u({[m]:"Record",type:"object",patternProperties:{[e]:t}},n)}function vr(e,t,n){let r={};for(let o of e)r[o]=t;return R(r,{...n,[Ie]:"Record"})}function Ic(e,t,n){return rs(e)?vr(oe(e),t,n):ft(e.pattern,t,n)}function hc(e,t,n){return vr(oe(w(e)),t,n)}function yc(e,t,n){return vr([e.toString()],t,n)}function xc(e,t,n){return ft(e.source,t,n)}function Sc(e,t,n){let r=D(e.pattern)?Ye:e.pattern;return ft(r,t,n)}function Tc(e,t,n){return ft(Ye,t,n)}function bc(e,t,n){return ft(Yo,t,n)}function wc(e,t,n){return R({true:t,false:t},n)}function Ac(e,t,n){return ft(ze,t,n)}function Pc(e,t,n){return ft(ze,t,n)}function Mn(e,t,n={}){return y(e)?hc(e.anyOf,t,n):me(e)?Ic(e,t,n):de(e)?yc(e.const,t,n):je(e)?wc(e,t,n):Me(e)?Ac(e,t,n):Ee(e)?Pc(e,t,n):lr(e)?xc(e,t,n):Ge(e)?Sc(e,t,n):mr(e)?Tc(e,t,n):We(e)?bc(e,t,n):x(n)}function En(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function Gs(e){let t=En(e);return t===Ye?ke():t===ze?he():ke({pattern:t})}function kn(e){return e.patternProperties[En(e)]}function Rc(e,t){return t.parameters=tn(e,t.parameters),t.returns=Fe(e,t.returns),t}function Oc(e,t){return t.parameters=tn(e,t.parameters),t.returns=Fe(e,t.returns),t}function Cc(e,t){return t.allOf=tn(e,t.allOf),t}function Mc(e,t){return t.anyOf=tn(e,t.anyOf),t}function Ec(e,t){return D(t.items)||(t.items=tn(e,t.items)),t}function kc(e,t){return t.items=Fe(e,t.items),t}function Fc(e,t){return t.items=Fe(e,t.items),t}function $c(e,t){return t.items=Fe(e,t.items),t}function vc(e,t){return t.item=Fe(e,t.item),t}function Nc(e,t){let n=Kc(e,t.properties);return{...t,...R(n)}}function Uc(e,t){let n=Fe(e,Gs(t)),r=Fe(e,kn(t)),o=Mn(n,r);return{...t,...o}}function _c(e,t){return t.index in e?e[t.index]:Qe()}function Lc(e,t){let n=xt(t),r=re(t),o=Fe(e,t);return n&&r?Cn(o):n&&!r?se(o):!n&&r?X(o):o}function Kc(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:Lc(e,t[r])}),{})}function tn(e,t){return t.map(n=>Fe(e,n))}function Fe(e,t){return Oe(t)?Rc(e,t):Ce(t)?Oc(e,t):v(t)?Cc(e,t):y(t)?Mc(e,t):pe(t)?Ec(e,t):Pe(t)?kc(e,t):at(t)?Fc(e,t):dt(t)?$c(e,t):ct(t)?vc(e,t):j(t)?Nc(e,t):mt(t)?Uc(e,t):pr(t)?_c(e,t):t}function Vs(e,t){return Fe(t,yt(e))}function Hs(e){return u({[m]:"Integer",type:"integer"},e)}function Dc(e,t,n){return{[e]:$e(b(e),t,F(n))}}function jc(e,t,n){return e.reduce((o,i)=>({...o,...Dc(i,t,n)}),{})}function Gc(e,t,n){return jc(e.keys,t,n)}function Bs(e,t,n){let r=Gc(e,t,n);return S(r)}function Vc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function Hc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function Bc(e){return e.toUpperCase()}function Wc(e){return e.toLowerCase()}function qc(e,t,n){let r=At(e.pattern);if(!pt(r))return{...e,pattern:Ws(e.pattern,t)};let s=[...Xt(r)].map(f=>b(f)),c=qs(s,t),p=w(c);return hn([p],n)}function Ws(e,t){return typeof e=="string"?t==="Uncapitalize"?Vc(e):t==="Capitalize"?Hc(e):t==="Uppercase"?Bc(e):t==="Lowercase"?Wc(e):e:e.toString()}function qs(e,t){return e.map(n=>$e(n,t))}function $e(e,t,n={}){return ce(e)?Bs(e,t,n):me(e)?qc(e,t,n):y(e)?w(qs(e.anyOf,t),n):de(e)?b(Ws(e.const,t),n):u(e,n)}function zs(e,t={}){return $e(e,"Capitalize",t)}function Ys(e,t={}){return $e(e,"Lowercase",t)}function Js(e,t={}){return $e(e,"Uncapitalize",t)}function Xs(e,t={}){return $e(e,"Uppercase",t)}function zc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=et(e[o],t,F(n));return r}function Yc(e,t,n){return zc(e.properties,t,n)}function Qs(e,t,n){let r=Yc(e,t,n);return S(r)}function Jc(e,t){return e.map(n=>Nr(n,t))}function Xc(e,t){return e.map(n=>Nr(n,t))}function Qc(e,t){let{[t]:n,...r}=e;return r}function Zc(e,t){return t.reduce((n,r)=>Qc(n,r),e)}function em(e,t,n){let r=N(e,[V,"$id","required","properties"]),o=Zc(n,t);return R(o,r)}function tm(e){let t=e.reduce((n,r)=>pn(r)?[...n,b(r)]:n,[]);return w(t)}function Nr(e,t){return v(e)?Q(Jc(e.allOf,t)):y(e)?w(Xc(e.anyOf,t)):j(e)?em(e,t,e.properties):R({})}function et(e,t,n){let r=K(t)?tm(t):t,o=le(t)?oe(t):t,i=L(e),s=L(t);return $(e)?Qs(e,o,n):ce(t)?Zs(e,t,n):i&&s?k("Omit",[e,r],n):!i&&s?k("Omit",[e,r],n):i&&!s?k("Omit",[e,r],n):u({...Nr(e,o),...n})}function nm(e,t,n){return{[t]:et(e,[t],F(n))}}function rm(e,t,n){return t.reduce((r,o)=>({...r,...nm(e,o,n)}),{})}function om(e,t,n){return rm(e,t.keys,n)}function Zs(e,t,n){let r=om(e,t,n);return S(r)}function sm(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=tt(e[o],t,F(n));return r}function im(e,t,n){return sm(e.properties,t,n)}function ei(e,t,n){let r=im(e,t,n);return S(r)}function am(e,t){return e.map(n=>Ur(n,t))}function um(e,t){return e.map(n=>Ur(n,t))}function dm(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function cm(e,t,n){let r=N(e,[V,"$id","required","properties"]),o=dm(n,t);return R(o,r)}function mm(e){let t=e.reduce((n,r)=>pn(r)?[...n,b(r)]:n,[]);return w(t)}function Ur(e,t){return v(e)?Q(am(e.allOf,t)):y(e)?w(um(e.anyOf,t)):j(e)?cm(e,t,e.properties):R({})}function tt(e,t,n){let r=K(t)?mm(t):t,o=le(t)?oe(t):t,i=L(e),s=L(t);return $(e)?ei(e,o,n):ce(t)?ti(e,t,n):i&&s?k("Pick",[e,r],n):!i&&s?k("Pick",[e,r],n):i&&!s?k("Pick",[e,r],n):u({...Ur(e,o),...n})}function pm(e,t,n){return{[t]:tt(e,[t],F(n))}}function lm(e,t,n){return t.reduce((r,o)=>({...r,...pm(e,o,n)}),{})}function fm(e,t,n){return lm(e,t.keys,n)}function ti(e,t,n){let r=fm(e,t,n);return S(r)}function gm(e,t){return k("Partial",[k(e,t)])}function Im(e){return k("Partial",[_e(e)])}function hm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=X(e[n]);return t}function ym(e,t){let n=N(e,[V,"$id","required","properties"]),r=hm(t);return R(r,n)}function ni(e){return e.map(t=>ri(t))}function ri(e){return Re(e)?gm(e.target,e.parameters):L(e)?Im(e.$ref):v(e)?Q(ni(e.allOf)):y(e)?w(ni(e.anyOf)):j(e)?ym(e,e.properties):ut(e)||je(e)||Me(e)||de(e)||Vt(e)||Ee(e)||Ge(e)||Ht(e)||Bt(e)?e:R({})}function $t(e,t){return $(e)?oi(e,t):u({...ri(e),...t})}function xm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=$t(e[r],F(t));return n}function Sm(e,t){return xm(e.properties,t)}function oi(e,t){let n=Sm(e,t);return S(n)}function Tm(e,t){return k("Required",[k(e,t)])}function bm(e){return k("Required",[_e(e)])}function wm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=N(e[n],[Y]);return t}function Am(e,t){let n=N(e,[V,"$id","required","properties"]),r=wm(t);return R(r,n)}function si(e){return e.map(t=>ii(t))}function ii(e){return Re(e)?Tm(e.target,e.parameters):L(e)?bm(e.$ref):v(e)?Q(si(e.allOf)):y(e)?w(si(e.anyOf)):j(e)?Am(e,e.properties):ut(e)||je(e)||Me(e)||de(e)||Vt(e)||Ee(e)||Ge(e)||Ht(e)||Bt(e)?e:R({})}function vt(e,t){return $(e)?ai(e,t):u({...ii(e),...t})}function Pm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=vt(e[r],t);return n}function Rm(e,t){return Pm(e.properties,t)}function ai(e,t){let n=Rm(e,t);return S(n)}function Om(e,t){return t.map(n=>L(n)?_r(e,n.$ref):fe(e,n))}function _r(e,t){return t in e?L(e[t])?_r(e,e[t].$ref):fe(e,e[t]):x()}function Cm(e){return Ot(e[0])}function Mm(e){return Xe(e[0],e[1])}function Em(e){return Ct(e[0])}function km(e){return $t(e[0])}function Fm(e){return et(e[0],e[1])}function $m(e){return tt(e[0],e[1])}function vm(e){return vt(e[0])}function Nm(e,t,n){let r=Om(e,n);return t==="Awaited"?Cm(r):t==="Index"?Mm(r):t==="KeyOf"?Em(r):t==="Partial"?km(r):t==="Omit"?Fm(r):t==="Pick"?$m(r):t==="Required"?vm(r):x()}function Um(e,t){return St(fe(e,t))}function _m(e,t){return Tt(fe(e,t))}function Lm(e,t,n){return bt(nn(e,t),fe(e,n))}function Km(e,t,n){return Ne(nn(e,t),fe(e,n))}function Dm(e,t){return Q(nn(e,t))}function jm(e,t){return Rt(fe(e,t))}function Gm(e,t){return R(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:fe(e,t[r])}),{}))}function Vm(e,t){let[n,r]=[fe(e,kn(t)),En(t)],o=yt(t);return o.patternProperties[r]=n,o}function Hm(e,t){return L(t)?{..._r(e,t.$ref),[V]:t[V]}:t}function Bm(e,t){return ye(nn(e,t))}function Wm(e,t){return w(nn(e,t))}function nn(e,t){return t.map(n=>fe(e,n))}function fe(e,t){return re(t)?u(fe(e,N(t,[Y])),t):xt(t)?u(fe(e,N(t,[Ae])),t):qe(t)?u(Hm(e,t),t):Pe(t)?u(Um(e,t.items),t):at(t)?u(_m(e,t.items),t):Re(t)?u(Nm(e,t.target,t.parameters)):Oe(t)?u(Lm(e,t.parameters,t.returns),t):Ce(t)?u(Km(e,t.parameters,t.returns),t):v(t)?u(Dm(e,t.allOf),t):dt(t)?u(jm(e,t.items),t):j(t)?u(Gm(e,t.properties),t):mt(t)?u(Vm(e,t)):pe(t)?u(Bm(e,t.items||[]),t):y(t)?u(Wm(e,t.anyOf),t):t}function qm(e,t){return t in e?fe(e,e[t]):x()}function ui(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:qm(e,n)}),{})}var Lr=class{constructor(t){let n=ui(t),r=this.WithIdentifiers(n);this.$defs=r}Import(t,n){let r={...this.$defs,[t]:u(this.$defs[t],n)};return u({[m]:"Import",$defs:r,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:{...t[r],$id:r}}),{})}};function di(e){return new Lr(e)}function ci(e,t){return u({[m]:"Not",not:e},t)}function mi(e,t){return Ce(e)?ye(e.parameters,t):x()}var zm=0;function pi(e,t={}){D(t.$id)&&(t.$id=`T${zm++}`);let n=yt(e({[m]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[Ie]:"Recursive",...n},t)}function li(e,t){let n=C(e)?new globalThis.RegExp(e):e;return u({[m]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},t)}function Ym(e){return v(e)?e.allOf:y(e)?e.anyOf:pe(e)?e.items??[]:[]}function fi(e){return Ym(e)}function gi(e,t){return Ce(e)?u(e.returns,t):x(t)}var Kr=class{constructor(t){this.schema=t}Decode(t){return new Dr(this.schema,t)}},Dr=class{constructor(t,n){this.schema=t,this.decode=n}EncodeTransform(t,n){let i={Encode:s=>n[V].Encode(t(s)),Decode:s=>this.decode(n[V].Decode(s))};return{...n,[V]:i}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[V]:r}}Encode(t){return qe(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function Ii(e){return new Kr(e)}function hi(e={}){return u({[m]:e[m]??"Unsafe"},e)}function yi(e){return u({[m]:"Void",type:"void"},e)}var jr={};sr(jr,{Any:()=>Je,Argument:()=>es,Array:()=>St,AsyncIterator:()=>Tt,Awaited:()=>Ot,BigInt:()=>Pt,Boolean:()=>In,Capitalize:()=>zs,Composite:()=>Ss,Const:()=>Ts,Constructor:()=>bt,ConstructorParameters:()=>bs,Date:()=>Sn,Enum:()=>ws,Exclude:()=>kt,Extends:()=>Et,Extract:()=>Ft,Function:()=>Ne,Index:()=>Xe,InstanceType:()=>js,Instantiate:()=>Vs,Integer:()=>Hs,Intersect:()=>Q,Iterator:()=>Rt,KeyOf:()=>Ct,Literal:()=>b,Lowercase:()=>Ys,Mapped:()=>fs,Module:()=>di,Never:()=>x,Not:()=>ci,Null:()=>Tn,Number:()=>he,Object:()=>R,Omit:()=>et,Optional:()=>X,Parameters:()=>mi,Partial:()=>$t,Pick:()=>tt,Promise:()=>xn,Readonly:()=>se,ReadonlyOptional:()=>Cn,Record:()=>Mn,Recursive:()=>pi,Ref:()=>_e,RegExp:()=>li,Required:()=>vt,Rest:()=>fi,ReturnType:()=>gi,String:()=>ke,Symbol:()=>bn,TemplateLiteral:()=>hn,Transform:()=>Ii,Tuple:()=>ye,Uint8Array:()=>An,Uncapitalize:()=>Js,Undefined:()=>wn,Union:()=>w,Unknown:()=>Qe,Unsafe:()=>hi,Uppercase:()=>Xs,Void:()=>yi});var l=jr;var g=null;function Gr(e){g=e}import{readFileSync as Jm}from"fs";import{homedir as Xm}from"os";import{join as Qm}from"path";var rn,xi="claude-code",Fn={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium",approvalPolicy:"on-request"}};function Si(){if(rn!==void 0)return rn;try{let e=Jm(Qm(Xm(),".claude.json"),"utf-8");rn=JSON.parse(e).mcpServers??{}}catch{rn={}}return rn}var E={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",codexApprovalPolicy:"on-request",harnesses:{"claude-code":{...Fn["claude-code"]},codex:{...Fn.codex}}};function Ti(e){let t=e.defaultHarness??xi,n={};for(let[r,o]of Object.entries(Fn))n[r]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[r,o]of Object.entries(e.harnesses??{})){let s={...n[r]??{},...o};o.allowedModels!==void 0?s.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(s.allowedModels=void 0),n[r]=s}if(e.defaultModel!==void 0){let r=n[t]??{};n[t]={...r,defaultModel:e.harnesses?.[t]?.defaultModel??e.defaultModel,allowedModels:e.harnesses?.[t]?.allowedModels!==void 0?r.allowedModels:e.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${t}.defaultModel instead.`)}if(e.model!==void 0){let r=n.codex??{};n.codex={...r,defaultModel:e.harnesses?.codex?.defaultModel??e.model,allowedModels:e.harnesses?.codex?.allowedModels!==void 0?r.allowedModels:e.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(e.reasoningEffort!==void 0){let r=n.codex??{};n.codex={...r,reasoningEffort:e.harnesses?.codex?.reasoningEffort??e.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(e.codexApprovalPolicy!==void 0){let r=n.codex??{};n.codex={...r,approvalPolicy:e.harnesses?.codex?.approvalPolicy??e.codexApprovalPolicy},console.warn("[openclaw-code-agent] config.codexApprovalPolicy is deprecated; use harnesses.codex.approvalPolicy instead.")}if(e.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[r,o]of Object.entries(n))e.harnesses?.[r]?.allowedModels===void 0&&(n[r]={...o,allowedModels:void 0})}E={maxSessions:e.maxSessions??20,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??15,sessionGcAgeMinutes:e.sessionGcAgeMinutes??1440,maxPersistedSessions:e.maxPersistedSessions??1e4,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10,permissionMode:e.permissionMode??"plan",codexApprovalPolicy:e.codexApprovalPolicy??"on-request",planApproval:e.planApproval??"delegate",defaultHarness:t,harnesses:n,allowedModels:e.allowedModels}}function nt(){return E.defaultHarness??xi}function Vr(e){let t=Fn[e],n=E.harnesses[e];return{...t,...n,allowedModels:n?.allowedModels??t?.allowedModels}}function rt(e){return Vr(e).defaultModel}function bi(e){return E.harnesses[e]?.allowedModels??E.allowedModels}function Nt(e){return Vr(e).reasoningEffort}function gt(e){return Vr(e).approvalPolicy}function wi(e){if(e.messageChannel){let t=e.messageChannel.split("|");if(t.length>=3)return e.messageChannel;if(e.agentAccountId&&t.length>=2)return`${t[0]}|${e.agentAccountId}|${t.slice(1).join("|")}`;if(t.length===1&&e.chatId)return`${t[0]}|${e.chatId}`;if(t.length===1&&e.senderId)return`${t[0]}|${e.senderId}`}if(e.workspaceDir){let t=on(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function Ut(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);if(e?.messageChannel){let n=String(e.messageChannel);if(n.includes("|"))return n;if(e.chatId)return`${n}|${e.chatId}`;if(e.senderId)return`${n}|${e.senderId}`}return e?.channel&&e?.chatId?`${e.channel}|${e.chatId}`:e?.channel&&e?.senderId?`${e.channel}|${e.senderId}`:e?.id&&/^-?\d+$/.test(String(e.id))?`telegram|${e.id}`:E.fallbackChannel??"unknown"}function _t(e){return e?.messageThreadId??void 0}function on(e){let t=E.agentChannels;if(!t)return;let n=i=>i.replace(/\/+$/,""),r=n(e),o=Object.entries(t).sort((i,s)=>s[0].length-i[0].length);for(let[i,s]of o)if(r===n(i)||r.startsWith(n(i)+"/"))return s}function Ai(e){if(!e)return;let t=e.match(/:topic:(\d+)$/);return t?parseInt(t[1],10):void 0}function Lt(e){let{requestedResumeSessionId:t,activeSession:n,persistedSession:r}=e;return t?n?{resumeSessionId:t,clearedPersistedCodexResume:!1}:r?.harness==="codex"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:t,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}function ep(e){return e instanceof Error?e.message:String(e)}function tp(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function np(e,t){if(!t||t.length===0)return!0;if(!e)return!1;let n=e.toLowerCase();return t.some(r=>n.includes(r.toLowerCase()))}function Pi(e){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn by default \u2014 they stay open for follow-up messages via agent_respond. Set multi_turn_disabled: true for fire-and-forget sessions. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:l.Object({prompt:l.String({description:"The task prompt to execute"}),name:l.Optional(l.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:l.Optional(l.String({description:"Working directory (defaults to cwd)"})),model:l.Optional(l.String({description:"Model name to use"})),system_prompt:l.Optional(l.String({description:"Additional system prompt"})),allowed_tools:l.Optional(l.Array(l.String(),{description:"List of allowed tools"})),resume_session_id:l.Optional(l.String({description:"Session ID to resume (from a previous session's harnessSessionId). Continues the conversation from where it left off."})),fork_session:l.Optional(l.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),multi_turn_disabled:l.Optional(l.Boolean({description:"Disable multi-turn mode. By default sessions stay open for follow-up messages. Set to true for fire-and-forget sessions."})),permission_mode:l.Optional(l.Union([l.Literal("default"),l.Literal("plan"),l.Literal("acceptEdits"),l.Literal("bypassPermissions")],{description:"Permission mode for the session. This is the plugin's orchestration mode, not the Codex SDK approval policy. Defaults to plugin config (plan by default)."})),harness:l.Optional(l.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!tp(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};n.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${n.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${e.agentId}" will be used for origin routing instead.`);let r=n.workdir||e.workspaceDir||E.defaultWorkdir||process.cwd();if(!Zm(r))return{content:[{type:"text",text:`Error: Working directory does not exist: ${r}`}]};try{let o=n.harness??nt(),i=rt(o),s=n.model??i,c=n.model!==void 0;if(!s)return{content:[{type:"text",text:`Error: No default model configured for harness "${o}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${o}.defaultModel or pass model explicitly.`}]};let p=bi(o);if(p&&p.length>0&&!np(s,p))return{content:[{type:"text",text:c?`Error: Model "${s}" is not allowed. Permitted models: ${p.join(", ")}`:`Error: Default model "${s||"undefined"}" is not in allowedModels (${p.join(", ")}). Update your plugin config to set a compatible defaultModel.`}]};let f=n.resume_session_id,T=f?g.resolve(f):void 0,U=f?g.getPersistedSession(f):void 0;if(f){let we=g.resolveHarnessSessionId(f);if(!we)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${f}" to a session ID. Use agent_sessions to list available sessions.`}]};f=we}let{resumeSessionId:te,clearedPersistedCodexResume:ge}=Lt({requestedResumeSessionId:f,activeSession:T?{harnessSessionId:T.harnessSessionId}:void 0,persistedSession:U?{harness:U.harness}:void 0}),ae=wi(e),ee=Ut(e,ae||on(r)),z=e.sessionKey||void 0;!z&&e.agentId&&console.warn(`[agent_launch] ctx.sessionKey is not populated. ctx fields: agentId=${e.agentId}, messageChannel=${e.messageChannel}, agentAccountId=${e.agentAccountId}, workspaceDir=${e.workspaceDir}`);let _=g.spawn({prompt:n.prompt,name:n.name,workdir:r,model:s,reasoningEffort:Nt(o),systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:te,forkSession:te?n.fork_session:!1,multiTurn:!n.multi_turn_disabled,permissionMode:n.permission_mode,codexApprovalPolicy:o==="codex"?gt(o)??E.codexApprovalPolicy:void 0,originChannel:ee,originThreadId:Ai(z)??_t(e),originAgentId:e.agentId||void 0,originSessionKey:z,harness:o}),Be=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,be=["Session launched successfully.",` Name: ${_.name}`,` ID: ${_.id}`,` Dir: ${r}`,` Model: ${_.model??"default"}`,` Prompt: "${Be}"`];return o==="codex"&&be.push(` Codex approval policy: ${_.codexApprovalPolicy??gt(o)??E.codexApprovalPolicy}`),n.resume_session_id&&(be.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),ge&&be.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),be.push(n.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),be.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:be.join(`
2
- `)}]}}catch(o){let i=ep(o),s=i.includes("Max sessions")?"":`
3
-
4
- Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${i}${s}`}]}}}}}import{existsSync as sp,readFileSync as ip}from"fs";function Le(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m${r}s`:`${r}s`}var rp=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 Ri(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!rp.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var op={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function Oi(e){let t=op[e.status]??"\u2753",n=Le(e.duration),r=e.multiTurn?"multi-turn":"single",o=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,i=e.costUsd>0?` | $${e.costUsd.toFixed(2)}`:"",s=[`${t} ${e.name} [${e.id}] (${n}${i}) \u2014 ${r}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];return e.phase!==e.status&&s.push(` \u2699\uFE0F Phase: ${e.phase}`),e.harness&&s.push(` \u{1F9F0} Harness: ${e.harness}`),e.harnessSessionId&&s.push(` \u{1F517} Session ID: ${e.harnessSessionId}`),e.resumeSessionId&&s.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),s.join(`
5
- `)}function $n(e,t){let n=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:r,failed:o,killed:i}=e.sessionsByStatus,s=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${n>0?Le(n):"n/a"}`];if(e.mostExpensive){let c=e.mostExpensive;s.push("","\u{1F3C6} Notable session",` ${c.name} [${c.id}]`,` \u{1F4DD} "${c.prompt}"`)}return s.join(`
6
- `)}function ot(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function Ci(e,t){let n=e.split(`
7
- `),r=[],o=0;for(let i=n.length-1;i>=0;i--){let s=n[i].length+(r.length>0?1:0);if(o+s>t&&r.length>0)break;r.unshift(n[i]),o+=s}return r.join(`
8
- `)}var ap=50,up=1,dp=new Set(["starting","running","completed","failed","killed"]),cp=5,mp=1440*60*1e3;function pp(e){let t=Number(e);return!Number.isFinite(t)||t<up?ap:Math.floor(t)}function lp(e){return typeof e=="string"&&dp.has(e)}function fp(e){let t=Le(e.duration),n=` | Cost: $${e.costUsd.toFixed(4)}`,r=e.status==="running"?` | Phase: ${e.phase}`:"";return[`Session: ${e.name} [${e.id}] | Status: ${e.status.toUpperCase()}${r}${n} | Duration: ${t}`,`${"\u2500".repeat(60)}`].join(`
9
- `)}function gp(e){return[`Session: ${e.name||e.harnessSessionId} | Status: ${e.status.toUpperCase()} | Cost: $${e.costUsd.toFixed(4)}`,`(retrieved from ${e.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`,`${"\u2500".repeat(60)}`].join(`
10
- `)}function Ip(e){let t=[];return e.error&&t.push(`Error: ${e.error}`),e.result?.result&&t.push(`Result: ${e.result.result}`),e.result&&t.push(`Result status: ${e.result.subtype}`),t.length>0?`
1
+ var nu=Object.defineProperty;var En=(e,t)=>{for(var r in t)nu(e,r,{get:t[r],enumerable:!0})};import{readdirSync as cg,statSync as dg,rmSync as lg}from"fs";import{execFileSync as pg}from"child_process";import{join as Za}from"path";import{existsSync as Up}from"fs";var ie={};En(ie,{HasPropertyKey:()=>Tr,IsArray:()=>Q,IsAsyncIterator:()=>vn,IsBigInt:()=>nr,IsBoolean:()=>ze,IsDate:()=>It,IsFunction:()=>_n,IsIterator:()=>Fn,IsNull:()=>Nn,IsNumber:()=>he,IsObject:()=>U,IsRegExp:()=>or,IsString:()=>j,IsSymbol:()=>Un,IsUint8Array:()=>Qe,IsUndefined:()=>Y});function Tr(e,t){return t in e}function vn(e){return U(e)&&!Q(e)&&!Qe(e)&&Symbol.asyncIterator in e}function Q(e){return Array.isArray(e)}function nr(e){return typeof e=="bigint"}function ze(e){return typeof e=="boolean"}function It(e){return e instanceof globalThis.Date}function _n(e){return typeof e=="function"}function Fn(e){return U(e)&&!Q(e)&&!Qe(e)&&Symbol.iterator in e}function Nn(e){return e===null}function he(e){return typeof e=="number"}function U(e){return typeof e=="object"&&e!==null}function or(e){return e instanceof globalThis.RegExp}function j(e){return typeof e=="string"}function Un(e){return typeof e=="symbol"}function Qe(e){return e instanceof globalThis.Uint8Array}function Y(e){return e===void 0}function ou(e){return e.map(t=>Ar(t))}function su(e){return new Date(e.getTime())}function iu(e){return new Uint8Array(e)}function au(e){return new RegExp(e.source,e.flags)}function uu(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=Ar(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=Ar(e[r]);return t}function Ar(e){return Q(e)?ou(e):It(e)?su(e):Qe(e)?iu(e):or(e)?au(e):U(e)?uu(e):e}function G(e){return Ar(e)}function vt(e,t){return t===void 0?G(e):G({...t,...e})}function Eo(e){return e!==null&&typeof e=="object"}function vo(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function _o(e){return e===void 0}function Fo(e){return typeof e=="number"}var $r;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(i,a){return e.ExactOptionalPropertyTypes?a in i:i[a]!==void 0}e.IsExactOptionalProperty=t;function r(i){let a=Eo(i);return e.AllowArrayObject?a:a&&!vo(i)}e.IsObjectLike=r;function n(i){return r(i)&&!(i instanceof Date)&&!(i instanceof Uint8Array)}e.IsRecordLike=n;function o(i){return e.AllowNaN?Fo(i):Number.isFinite(i)}e.IsNumberLike=o;function s(i){let a=_o(i);return e.AllowNullVoid?a||i===null:a}e.IsVoidLike=s})($r||($r={}));function cu(e){return globalThis.Object.freeze(e).map(t=>sr(t))}function du(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=sr(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=sr(e[r]);return globalThis.Object.freeze(t)}function sr(e){return Q(e)?cu(e):It(e)?e:Qe(e)?e:or(e)?e:U(e)?du(e):e}function l(e,t){let r=t!==void 0?{...t,...e}:e;switch($r.InstanceMode){case"freeze":return sr(r);case"clone":return G(r);default:return r}}var re=class extends Error{constructor(t){super(t)}};var Z=Symbol.for("TypeBox.Transform"),Me=Symbol.for("TypeBox.Readonly"),oe=Symbol.for("TypeBox.Optional"),Pe=Symbol.for("TypeBox.Hint"),h=Symbol.for("TypeBox.Kind");function _t(e){return U(e)&&e[Me]==="Readonly"}function pe(e){return U(e)&&e[oe]==="Optional"}function Dn(e){return C(e,"Any")}function Ln(e){return C(e,"Argument")}function Oe(e){return C(e,"Array")}function wt(e){return C(e,"AsyncIterator")}function St(e){return C(e,"BigInt")}function Ye(e){return C(e,"Boolean")}function Ee(e){return C(e,"Computed")}function ve(e){return C(e,"Constructor")}function lu(e){return C(e,"Date")}function _e(e){return C(e,"Function")}function Fe(e){return C(e,"Integer")}function V(e){return C(e,"Intersect")}function xt(e){return C(e,"Iterator")}function C(e,t){return U(e)&&h in e&&e[h]===t}function Rr(e){return ze(e)||he(e)||j(e)}function ye(e){return C(e,"Literal")}function Ie(e){return C(e,"MappedKey")}function H(e){return C(e,"MappedResult")}function rt(e){return C(e,"Never")}function pu(e){return C(e,"Not")}function ir(e){return C(e,"Null")}function Ne(e){return C(e,"Number")}function J(e){return C(e,"Object")}function bt(e){return C(e,"Promise")}function kt(e){return C(e,"Record")}function z(e){return C(e,"Ref")}function Kn(e){return C(e,"RegExp")}function Je(e){return C(e,"String")}function ar(e){return C(e,"Symbol")}function we(e){return C(e,"TemplateLiteral")}function mu(e){return C(e,"This")}function nt(e){return U(e)&&Z in e}function Se(e){return C(e,"Tuple")}function ur(e){return C(e,"Undefined")}function M(e){return C(e,"Union")}function fu(e){return C(e,"Uint8Array")}function gu(e){return C(e,"Unknown")}function hu(e){return C(e,"Unsafe")}function yu(e){return C(e,"Void")}function Iu(e){return U(e)&&h in e&&j(e[h])}function xe(e){return Dn(e)||Ln(e)||Oe(e)||Ye(e)||St(e)||wt(e)||Ee(e)||ve(e)||lu(e)||_e(e)||Fe(e)||V(e)||xt(e)||ye(e)||Ie(e)||H(e)||rt(e)||pu(e)||ir(e)||Ne(e)||J(e)||bt(e)||kt(e)||z(e)||Kn(e)||Je(e)||ar(e)||we(e)||mu(e)||Se(e)||ur(e)||M(e)||fu(e)||gu(e)||hu(e)||yu(e)||Iu(e)}var u={};En(u,{IsAny:()=>Lo,IsArgument:()=>Ko,IsArray:()=>jo,IsAsyncIterator:()=>Bo,IsBigInt:()=>Wo,IsBoolean:()=>Go,IsComputed:()=>Ho,IsConstructor:()=>Vo,IsDate:()=>qo,IsFunction:()=>zo,IsImport:()=>Pu,IsInteger:()=>Qo,IsIntersect:()=>Yo,IsIterator:()=>Jo,IsKind:()=>ks,IsKindOf:()=>R,IsLiteral:()=>dr,IsLiteralBoolean:()=>Tu,IsLiteralNumber:()=>Zo,IsLiteralString:()=>Xo,IsLiteralValue:()=>es,IsMappedKey:()=>ts,IsMappedResult:()=>rs,IsNever:()=>ns,IsNot:()=>os,IsNull:()=>ss,IsNumber:()=>is,IsObject:()=>as,IsOptional:()=>ku,IsPromise:()=>us,IsProperties:()=>Cr,IsReadonly:()=>bu,IsRecord:()=>cs,IsRecursive:()=>Au,IsRef:()=>ds,IsRegExp:()=>ls,IsSchema:()=>ne,IsString:()=>ps,IsSymbol:()=>ms,IsTemplateLiteral:()=>fs,IsThis:()=>gs,IsTransform:()=>hs,IsTuple:()=>ys,IsUint8Array:()=>ws,IsUndefined:()=>Is,IsUnion:()=>Gn,IsUnionLiteral:()=>$u,IsUnknown:()=>Ss,IsUnsafe:()=>xs,IsVoid:()=>bs,TypeGuardUnknownTypeError:()=>jn});var jn=class extends re{},wu=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function No(e){try{return new RegExp(e),!0}catch{return!1}}function Bn(e){if(!j(e))return!1;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=7&&r<=13||r===27||r===127)return!1}return!0}function Uo(e){return Wn(e)||ne(e)}function cr(e){return Y(e)||nr(e)}function B(e){return Y(e)||he(e)}function Wn(e){return Y(e)||ze(e)}function D(e){return Y(e)||j(e)}function Su(e){return Y(e)||j(e)&&Bn(e)&&No(e)}function xu(e){return Y(e)||j(e)&&Bn(e)}function Do(e){return Y(e)||ne(e)}function bu(e){return U(e)&&e[Me]==="Readonly"}function ku(e){return U(e)&&e[oe]==="Optional"}function Lo(e){return R(e,"Any")&&D(e.$id)}function Ko(e){return R(e,"Argument")&&he(e.index)}function jo(e){return R(e,"Array")&&e.type==="array"&&D(e.$id)&&ne(e.items)&&B(e.minItems)&&B(e.maxItems)&&Wn(e.uniqueItems)&&Do(e.contains)&&B(e.minContains)&&B(e.maxContains)}function Bo(e){return R(e,"AsyncIterator")&&e.type==="AsyncIterator"&&D(e.$id)&&ne(e.items)}function Wo(e){return R(e,"BigInt")&&e.type==="bigint"&&D(e.$id)&&cr(e.exclusiveMaximum)&&cr(e.exclusiveMinimum)&&cr(e.maximum)&&cr(e.minimum)&&cr(e.multipleOf)}function Go(e){return R(e,"Boolean")&&e.type==="boolean"&&D(e.$id)}function Ho(e){return R(e,"Computed")&&j(e.target)&&Q(e.parameters)&&e.parameters.every(t=>ne(t))}function Vo(e){return R(e,"Constructor")&&e.type==="Constructor"&&D(e.$id)&&Q(e.parameters)&&e.parameters.every(t=>ne(t))&&ne(e.returns)}function qo(e){return R(e,"Date")&&e.type==="Date"&&D(e.$id)&&B(e.exclusiveMaximumTimestamp)&&B(e.exclusiveMinimumTimestamp)&&B(e.maximumTimestamp)&&B(e.minimumTimestamp)&&B(e.multipleOfTimestamp)}function zo(e){return R(e,"Function")&&e.type==="Function"&&D(e.$id)&&Q(e.parameters)&&e.parameters.every(t=>ne(t))&&ne(e.returns)}function Pu(e){return R(e,"Import")&&Tr(e,"$defs")&&U(e.$defs)&&Cr(e.$defs)&&Tr(e,"$ref")&&j(e.$ref)&&e.$ref in e.$defs}function Qo(e){return R(e,"Integer")&&e.type==="integer"&&D(e.$id)&&B(e.exclusiveMaximum)&&B(e.exclusiveMinimum)&&B(e.maximum)&&B(e.minimum)&&B(e.multipleOf)}function Cr(e){return U(e)&&Object.entries(e).every(([t,r])=>Bn(t)&&ne(r))}function Yo(e){return R(e,"Intersect")&&!(j(e.type)&&e.type!=="object")&&Q(e.allOf)&&e.allOf.every(t=>ne(t)&&!hs(t))&&D(e.type)&&(Wn(e.unevaluatedProperties)||Do(e.unevaluatedProperties))&&D(e.$id)}function Jo(e){return R(e,"Iterator")&&e.type==="Iterator"&&D(e.$id)&&ne(e.items)}function R(e,t){return U(e)&&h in e&&e[h]===t}function Xo(e){return dr(e)&&j(e.const)}function Zo(e){return dr(e)&&he(e.const)}function Tu(e){return dr(e)&&ze(e.const)}function dr(e){return R(e,"Literal")&&D(e.$id)&&es(e.const)}function es(e){return ze(e)||he(e)||j(e)}function ts(e){return R(e,"MappedKey")&&Q(e.keys)&&e.keys.every(t=>he(t)||j(t))}function rs(e){return R(e,"MappedResult")&&Cr(e.properties)}function ns(e){return R(e,"Never")&&U(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function os(e){return R(e,"Not")&&ne(e.not)}function ss(e){return R(e,"Null")&&e.type==="null"&&D(e.$id)}function is(e){return R(e,"Number")&&e.type==="number"&&D(e.$id)&&B(e.exclusiveMaximum)&&B(e.exclusiveMinimum)&&B(e.maximum)&&B(e.minimum)&&B(e.multipleOf)}function as(e){return R(e,"Object")&&e.type==="object"&&D(e.$id)&&Cr(e.properties)&&Uo(e.additionalProperties)&&B(e.minProperties)&&B(e.maxProperties)}function us(e){return R(e,"Promise")&&e.type==="Promise"&&D(e.$id)&&ne(e.item)}function cs(e){return R(e,"Record")&&e.type==="object"&&D(e.$id)&&Uo(e.additionalProperties)&&U(e.patternProperties)&&(t=>{let r=Object.getOwnPropertyNames(t.patternProperties);return r.length===1&&No(r[0])&&U(t.patternProperties)&&ne(t.patternProperties[r[0]])})(e)}function Au(e){return U(e)&&Pe in e&&e[Pe]==="Recursive"}function ds(e){return R(e,"Ref")&&D(e.$id)&&j(e.$ref)}function ls(e){return R(e,"RegExp")&&D(e.$id)&&j(e.source)&&j(e.flags)&&B(e.maxLength)&&B(e.minLength)}function ps(e){return R(e,"String")&&e.type==="string"&&D(e.$id)&&B(e.minLength)&&B(e.maxLength)&&Su(e.pattern)&&xu(e.format)}function ms(e){return R(e,"Symbol")&&e.type==="symbol"&&D(e.$id)}function fs(e){return R(e,"TemplateLiteral")&&e.type==="string"&&j(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function gs(e){return R(e,"This")&&D(e.$id)&&j(e.$ref)}function hs(e){return U(e)&&Z in e}function ys(e){return R(e,"Tuple")&&e.type==="array"&&D(e.$id)&&he(e.minItems)&&he(e.maxItems)&&e.minItems===e.maxItems&&(Y(e.items)&&Y(e.additionalItems)&&e.minItems===0||Q(e.items)&&e.items.every(t=>ne(t)))}function Is(e){return R(e,"Undefined")&&e.type==="undefined"&&D(e.$id)}function $u(e){return Gn(e)&&e.anyOf.every(t=>Xo(t)||Zo(t))}function Gn(e){return R(e,"Union")&&D(e.$id)&&U(e)&&Q(e.anyOf)&&e.anyOf.every(t=>ne(t))}function ws(e){return R(e,"Uint8Array")&&e.type==="Uint8Array"&&D(e.$id)&&B(e.minByteLength)&&B(e.maxByteLength)}function Ss(e){return R(e,"Unknown")&&D(e.$id)}function xs(e){return R(e,"Unsafe")}function bs(e){return R(e,"Void")&&e.type==="void"&&D(e.$id)}function ks(e){return U(e)&&h in e&&j(e[h])&&!wu.includes(e[h])}function ne(e){return U(e)&&(Lo(e)||Ko(e)||jo(e)||Go(e)||Wo(e)||Bo(e)||Ho(e)||Vo(e)||qo(e)||zo(e)||Qo(e)||Yo(e)||Jo(e)||dr(e)||ts(e)||rs(e)||ns(e)||os(e)||ss(e)||is(e)||as(e)||us(e)||cs(e)||ds(e)||ls(e)||ps(e)||ms(e)||fs(e)||gs(e)||ys(e)||Is(e)||Gn(e)||ws(e)||Ss(e)||xs(e)||bs(e)||ks(e))}var Hn="(true|false)",lr="(0|[1-9][0-9]*)",Vn="(.*)",Ru="(?!.*)",Eg=`^${Hn}$`,ot=`^${lr}$`,st=`^${Vn}$`,Ps=`^${Ru}$`;function Ts(e,t){return e.includes(t)}function As(e){return[...new Set(e)]}function Cu(e,t){return e.filter(r=>t.includes(r))}function Mu(e,t){return e.reduce((r,n)=>Cu(r,n),t)}function $s(e){return e.length===1?e[0]:e.length>1?Mu(e.slice(1),e[0]):[]}function Rs(e){let t=[];for(let r of e)t.push(...r);return t}function it(e){return l({[h]:"Any"},e)}function Ft(e,t){return l({[h]:"Array",type:"array",items:e},t)}function Cs(e){return l({[h]:"Argument",index:e})}function Nt(e,t){return l({[h]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function W(e,t,r){return l({[h]:"Computed",target:e,parameters:t},r)}function Ou(e,t){let{[t]:r,...n}=e;return n}function q(e,t){return t.reduce((r,n)=>Ou(r,n),e)}function O(e){return l({[h]:"Never",not:{}},e)}function v(e){return l({[h]:"MappedResult",properties:e})}function Ut(e,t,r){return l({[h]:"Constructor",type:"Constructor",parameters:e,returns:t},r)}function Ge(e,t,r){return l({[h]:"Function",type:"Function",parameters:e,returns:t},r)}function pr(e,t){return l({[h]:"Union",anyOf:e},t)}function Eu(e){return e.some(t=>pe(t))}function Ms(e){return e.map(t=>pe(t)?vu(t):t)}function vu(e){return q(e,[oe])}function _u(e,t){return Eu(e)?ae(pr(Ms(e),t)):pr(Ms(e),t)}function He(e,t){return e.length===1?l(e[0],t):e.length===0?O(t):_u(e,t)}function F(e,t){return e.length===0?O(t):e.length===1?l(e[0],t):pr(e,t)}var Mr=class extends re{};function Fu(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function qn(e,t,r){return e[t]===r&&e.charCodeAt(t-1)!==92}function Ze(e,t){return qn(e,t,"(")}function mr(e,t){return qn(e,t,")")}function Os(e,t){return qn(e,t,"|")}function Nu(e){if(!(Ze(e,0)&&mr(e,e.length-1)))return!1;let t=0;for(let r=0;r<e.length;r++)if(Ze(e,r)&&(t+=1),mr(e,r)&&(t-=1),t===0&&r!==e.length-1)return!1;return!0}function Uu(e){return e.slice(1,e.length-1)}function Du(e){let t=0;for(let r=0;r<e.length;r++)if(Ze(e,r)&&(t+=1),mr(e,r)&&(t-=1),Os(e,r)&&t===0)return!0;return!1}function Lu(e){for(let t=0;t<e.length;t++)if(Ze(e,t))return!0;return!1}function Ku(e){let[t,r]=[0,0],n=[];for(let s=0;s<e.length;s++)if(Ze(e,s)&&(t+=1),mr(e,s)&&(t-=1),Os(e,s)&&t===0){let i=e.slice(r,s);i.length>0&&n.push(Dt(i)),r=s+1}let o=e.slice(r);return o.length>0&&n.push(Dt(o)),n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"or",expr:n}}function ju(e){function t(o,s){if(!Ze(o,s))throw new Mr("TemplateLiteralParser: Index must point to open parens");let i=0;for(let a=s;a<o.length;a++)if(Ze(o,a)&&(i+=1),mr(o,a)&&(i-=1),i===0)return[s,a];throw new Mr("TemplateLiteralParser: Unclosed group parens in expression")}function r(o,s){for(let i=s;i<o.length;i++)if(Ze(o,i))return[s,i];return[s,o.length]}let n=[];for(let o=0;o<e.length;o++)if(Ze(e,o)){let[s,i]=t(e,o),a=e.slice(s,i+1);n.push(Dt(a)),o=i}else{let[s,i]=r(e,o),a=e.slice(s,i);a.length>0&&n.push(Dt(a)),o=i-1}return n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"and",expr:n}}function Dt(e){return Nu(e)?Dt(Uu(e)):Du(e)?Ku(e):Lu(e)?ju(e):{type:"const",const:Fu(e)}}function Lt(e){return Dt(e.slice(1,e.length-1))}var zn=class extends re{};function Bu(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="0"&&e.expr[1].type==="const"&&e.expr[1].const==="[1-9][0-9]*"}function Wu(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="true"&&e.expr[1].type==="const"&&e.expr[1].const==="false"}function Gu(e){return e.type==="const"&&e.const===".*"}function Pt(e){return Bu(e)||Gu(e)?!1:Wu(e)?!0:e.type==="and"?e.expr.every(t=>Pt(t)):e.type==="or"?e.expr.every(t=>Pt(t)):e.type==="const"?!0:(()=>{throw new zn("Unknown expression type")})()}function Es(e){let t=Lt(e.pattern);return Pt(t)}var Qn=class extends re{};function*vs(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let r of vs(e.slice(1)))yield`${t}${r}`}function*Hu(e){return yield*vs(e.expr.map(t=>[...fr(t)]))}function*Vu(e){for(let t of e.expr)yield*fr(t)}function*qu(e){return yield e.const}function*fr(e){return e.type==="and"?yield*Hu(e):e.type==="or"?yield*Vu(e):e.type==="const"?yield*qu(e):(()=>{throw new Qn("Unknown expression")})()}function Or(e){let t=Lt(e.pattern);return Pt(t)?[...fr(t)]:[]}function _(e,t){return l({[h]:"Literal",const:e,type:typeof e},t)}function Er(e){return l({[h]:"Boolean",type:"boolean"},e)}function Kt(e){return l({[h]:"BigInt",type:"bigint"},e)}function Te(e){return l({[h]:"Number",type:"number"},e)}function Ue(e){return l({[h]:"String",type:"string"},e)}function*zu(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield Er():t==="number"?yield Te():t==="bigint"?yield Kt():t==="string"?yield Ue():yield(()=>{let r=t.split("|").map(n=>_(n.trim()));return r.length===0?O():r.length===1?r[0]:He(r)})()}function*Qu(e){if(e[1]!=="{"){let t=_("$"),r=Yn(e.slice(1));return yield*[t,...r]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let r=zu(e.slice(2,t)),n=Yn(e.slice(t+1));return yield*[...r,...n]}yield _(e)}function*Yn(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let r=_(e.slice(0,t)),n=Qu(e.slice(t));return yield*[r,...n]}yield _(e)}function _s(e){return[...Yn(e)]}var Jn=class extends re{};function Yu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fs(e,t){return we(e)?e.pattern.slice(1,e.pattern.length-1):M(e)?`(${e.anyOf.map(r=>Fs(r,t)).join("|")})`:Ne(e)?`${t}${lr}`:Fe(e)?`${t}${lr}`:St(e)?`${t}${lr}`:Je(e)?`${t}${Vn}`:ye(e)?`${t}${Yu(e.const.toString())}`:Ye(e)?`${t}${Hn}`:(()=>{throw new Jn(`Unexpected Kind '${e[h]}'`)})()}function Xn(e){return`^${e.map(t=>Fs(t,"")).join("")}$`}function Tt(e){let r=Or(e).map(n=>_(n));return He(r)}function vr(e,t){let r=j(e)?Xn(_s(e)):Xn(e);return l({[h]:"TemplateLiteral",type:"string",pattern:r},t)}function Ju(e){return Or(e).map(r=>r.toString())}function Xu(e){let t=[];for(let r of e)t.push(...me(r));return t}function Zu(e){return[e.toString()]}function me(e){return[...new Set(we(e)?Ju(e):M(e)?Xu(e.anyOf):ye(e)?Zu(e.const):Ne(e)?["[number]"]:Fe(e)?["[number]"]:[])]}function ec(e,t,r){let n={};for(let o of Object.getOwnPropertyNames(t))n[o]=at(e,me(t[o]),r);return n}function tc(e,t,r){return ec(e,t.properties,r)}function Ns(e,t,r){let n=tc(e,t,r);return v(n)}function Ds(e,t){return e.map(r=>Ls(r,t))}function rc(e){return e.filter(t=>!rt(t))}function nc(e,t){return _r(rc(Ds(e,t)))}function oc(e){return e.some(t=>rt(t))?[]:e}function sc(e,t){return He(oc(Ds(e,t)))}function ic(e,t){return t in e?e[t]:t==="[number]"?He(e):O()}function ac(e,t){return t==="[number]"?e:O()}function uc(e,t){return t in e?e[t]:O()}function Ls(e,t){return V(e)?nc(e.allOf,t):M(e)?sc(e.anyOf,t):Se(e)?ic(e.items??[],t):Oe(e)?ac(e.items,t):J(e)?uc(e.properties,t):O()}function Zn(e,t){return t.map(r=>Ls(e,r))}function Us(e,t){return He(Zn(e,t))}function at(e,t,r){if(z(e)||z(t)){let n="Index types using Ref parameters require both Type and Key to be of TSchema";if(!xe(e)||!xe(t))throw new re(n);return W("Index",[e,t])}return H(t)?Ns(e,t,r):Ie(t)?Ks(e,t,r):l(xe(t)?Us(e,me(t)):Us(e,t),r)}function cc(e,t,r){return{[t]:at(e,[t],G(r))}}function dc(e,t,r){return t.reduce((n,o)=>({...n,...cc(e,o,r)}),{})}function lc(e,t,r){return dc(e,t.keys,r)}function Ks(e,t,r){let n=lc(e,t,r);return v(n)}function jt(e,t){return l({[h]:"Iterator",type:"Iterator",items:e},t)}function pc(e){return globalThis.Object.keys(e).filter(t=>!pe(e[t]))}function mc(e,t){let r=pc(e),n=r.length>0?{[h]:"Object",type:"object",required:r,properties:e}:{[h]:"Object",type:"object",properties:e};return l(n,t)}var L=mc;function Fr(e,t){return l({[h]:"Promise",type:"Promise",item:e},t)}function fc(e){return l(q(e,[Me]))}function gc(e){return l({...e,[Me]:"Readonly"})}function hc(e,t){return t===!1?fc(e):gc(e)}function fe(e,t){let r=t??!0;return H(e)?js(e,r):hc(e,r)}function yc(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=fe(e[n],t);return r}function Ic(e,t){return yc(e.properties,t)}function js(e,t){let r=Ic(e,t);return v(r)}function Ae(e,t){return l(e.length>0?{[h]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[h]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function Bs(e,t){return e in t?$e(e,t[e]):v(t)}function wc(e){return{[e]:_(e)}}function Sc(e){let t={};for(let r of e)t[r]=_(r);return t}function xc(e,t){return Ts(t,e)?wc(e):Sc(t)}function bc(e,t){let r=xc(e,t);return Bs(e,r)}function gr(e,t){return t.map(r=>$e(e,r))}function kc(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=$e(e,t[n]);return r}function $e(e,t){let r={...t};return pe(t)?ae($e(e,q(t,[oe]))):_t(t)?fe($e(e,q(t,[Me]))):H(t)?Bs(e,t.properties):Ie(t)?bc(e,t.keys):ve(t)?Ut(gr(e,t.parameters),$e(e,t.returns),r):_e(t)?Ge(gr(e,t.parameters),$e(e,t.returns),r):wt(t)?Nt($e(e,t.items),r):xt(t)?jt($e(e,t.items),r):V(t)?ue(gr(e,t.allOf),r):M(t)?F(gr(e,t.anyOf),r):Se(t)?Ae(gr(e,t.items??[]),r):J(t)?L(kc(e,t.properties),r):Oe(t)?Ft($e(e,t.items),r):bt(t)?Fr($e(e,t.item),r):t}function Pc(e,t){let r={};for(let n of e)r[n]=$e(n,t);return r}function Ws(e,t,r){let n=xe(e)?me(e):e,o=t({[h]:"MappedKey",keys:n}),s=Pc(n,o);return L(s,r)}function Tc(e){return l(q(e,[oe]))}function Ac(e){return l({...e,[oe]:"Optional"})}function $c(e,t){return t===!1?Tc(e):Ac(e)}function ae(e,t){let r=t??!0;return H(e)?Gs(e,r):$c(e,r)}function Rc(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=ae(e[n],t);return r}function Cc(e,t){return Rc(e.properties,t)}function Gs(e,t){let r=Cc(e,t);return v(r)}function hr(e,t={}){let r=e.every(o=>J(o)),n=xe(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return l(t.unevaluatedProperties===!1||xe(t.unevaluatedProperties)||r?{...n,[h]:"Intersect",type:"object",allOf:e}:{...n,[h]:"Intersect",allOf:e},t)}function Mc(e){return e.every(t=>pe(t))}function Oc(e){return q(e,[oe])}function Hs(e){return e.map(t=>pe(t)?Oc(t):t)}function Ec(e,t){return Mc(e)?ae(hr(Hs(e),t)):hr(Hs(e),t)}function _r(e,t={}){if(e.length===1)return l(e[0],t);if(e.length===0)return O(t);if(e.some(r=>nt(r)))throw new Error("Cannot intersect transform types");return Ec(e,t)}function ue(e,t){if(e.length===1)return l(e[0],t);if(e.length===0)return O(t);if(e.some(r=>nt(r)))throw new Error("Cannot intersect transform types");return hr(e,t)}function Ve(...e){let[t,r]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new re("Ref: $ref must be a string");return l({[h]:"Ref",$ref:t},r)}function vc(e,t){return W("Awaited",[W(e,t)])}function _c(e){return W("Awaited",[Ve(e)])}function Fc(e){return ue(Vs(e))}function Nc(e){return F(Vs(e))}function Uc(e){return Bt(e)}function Vs(e){return e.map(t=>Bt(t))}function Bt(e,t){return l(Ee(e)?vc(e.target,e.parameters):V(e)?Fc(e.allOf):M(e)?Nc(e.anyOf):bt(e)?Uc(e.item):z(e)?_c(e.$ref):e,t)}function qs(e){let t=[];for(let r of e)t.push(yr(r));return t}function Dc(e){let t=qs(e);return Rs(t)}function Lc(e){let t=qs(e);return $s(t)}function Kc(e){return e.map((t,r)=>r.toString())}function jc(e){return["[number]"]}function Bc(e){return globalThis.Object.getOwnPropertyNames(e)}function Wc(e){return Gc?globalThis.Object.getOwnPropertyNames(e).map(r=>r[0]==="^"&&r[r.length-1]==="$"?r.slice(1,r.length-1):r):[]}function yr(e){return V(e)?Dc(e.allOf):M(e)?Lc(e.anyOf):Se(e)?Kc(e.items??[]):Oe(e)?jc(e.items):J(e)?Bc(e.properties):kt(e)?Wc(e.patternProperties):[]}var Gc=!1;function Hc(e,t){return W("KeyOf",[W(e,t)])}function Vc(e){return W("KeyOf",[Ve(e)])}function qc(e,t){let r=yr(e),n=zc(r),o=He(n);return l(o,t)}function zc(e){return e.map(t=>t==="[number]"?Te():_(t))}function Wt(e,t){return Ee(e)?Hc(e.target,e.parameters):z(e)?Vc(e.$ref):H(e)?zs(e,t):qc(e,t)}function Qc(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Wt(e[n],G(t));return r}function Yc(e,t){return Qc(e.properties,t)}function zs(e,t){let r=Yc(e,t);return v(r)}function Jc(e){let t=[];for(let r of e)t.push(...yr(r));return As(t)}function Xc(e){return e.filter(t=>!rt(t))}function Zc(e,t){let r=[];for(let n of e)r.push(...Zn(n,[t]));return Xc(r)}function ed(e,t){let r={};for(let n of t)r[n]=_r(Zc(e,n));return r}function Qs(e,t){let r=Jc(e),n=ed(e,r);return L(n,t)}function Nr(e){return l({[h]:"Date",type:"Date"},e)}function Ur(e){return l({[h]:"Null",type:"null"},e)}function Dr(e){return l({[h]:"Symbol",type:"symbol"},e)}function Lr(e){return l({[h]:"Undefined",type:"undefined"},e)}function Kr(e){return l({[h]:"Uint8Array",type:"Uint8Array"},e)}function ut(e){return l({[h]:"Unknown"},e)}function td(e){return e.map(t=>eo(t,!1))}function rd(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=fe(eo(e[r],!1));return t}function jr(e,t){return t===!0?e:fe(e)}function eo(e,t){return vn(e)?jr(it(),t):Fn(e)?jr(it(),t):Q(e)?fe(Ae(td(e))):Qe(e)?Kr():It(e)?Nr():U(e)?jr(L(rd(e)),t):_n(e)?jr(Ge([],ut()),t):Y(e)?Lr():Nn(e)?Ur():Un(e)?Dr():nr(e)?Kt():he(e)?_(e):ze(e)?_(e):j(e)?_(e):L({})}function Ys(e,t){return l(eo(e,!0),t)}function Js(e,t){return ve(e)?Ae(e.parameters,t):O(t)}function Xs(e,t){if(Y(e))throw new Error("Enum undefined or empty");let r=globalThis.Object.getOwnPropertyNames(e).filter(s=>isNaN(s)).map(s=>e[s]),o=[...new Set(r)].map(s=>_(s));return F(o,{...t,[Pe]:"Enum"})}var ro=class extends re{},p;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(p||(p={}));function Re(e){return e===p.False?e:p.True}function Gt(e){throw new ro(e)}function ee(e){return u.IsNever(e)||u.IsIntersect(e)||u.IsUnion(e)||u.IsUnknown(e)||u.IsAny(e)}function te(e,t){return u.IsNever(t)?si(e,t):u.IsIntersect(t)?Br(e,t):u.IsUnion(t)?io(e,t):u.IsUnknown(t)?ci(e,t):u.IsAny(t)?so(e,t):Gt("StructuralRight")}function so(e,t){return p.True}function nd(e,t){return u.IsIntersect(t)?Br(e,t):u.IsUnion(t)&&t.anyOf.some(r=>u.IsAny(r)||u.IsUnknown(r))?p.True:u.IsUnion(t)?p.Union:u.IsUnknown(t)||u.IsAny(t)?p.True:p.Union}function od(e,t){return u.IsUnknown(e)?p.False:u.IsAny(e)?p.Union:u.IsNever(e)?p.True:p.False}function sd(e,t){return u.IsObject(t)&&Wr(t)?p.True:ee(t)?te(e,t):u.IsArray(t)?Re(K(e.items,t.items)):p.False}function id(e,t){return ee(t)?te(e,t):u.IsAsyncIterator(t)?Re(K(e.items,t.items)):p.False}function ad(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsBigInt(t)?p.True:p.False}function ni(e,t){return u.IsLiteralBoolean(e)||u.IsBoolean(e)?p.True:p.False}function ud(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsBoolean(t)?p.True:p.False}function cd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsConstructor(t)?e.parameters.length>t.parameters.length?p.False:e.parameters.every((r,n)=>Re(K(t.parameters[n],r))===p.True)?Re(K(e.returns,t.returns)):p.False:p.False}function dd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsDate(t)?p.True:p.False}function ld(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsFunction(t)?e.parameters.length>t.parameters.length?p.False:e.parameters.every((r,n)=>Re(K(t.parameters[n],r))===p.True)?Re(K(e.returns,t.returns)):p.False:p.False}function oi(e,t){return u.IsLiteral(e)&&ie.IsNumber(e.const)||u.IsNumber(e)||u.IsInteger(e)?p.True:p.False}function pd(e,t){return u.IsInteger(t)||u.IsNumber(t)?p.True:ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):p.False}function Br(e,t){return t.allOf.every(r=>K(e,r)===p.True)?p.True:p.False}function md(e,t){return e.allOf.some(r=>K(r,t)===p.True)?p.True:p.False}function fd(e,t){return ee(t)?te(e,t):u.IsIterator(t)?Re(K(e.items,t.items)):p.False}function gd(e,t){return u.IsLiteral(t)&&t.const===e.const?p.True:ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsString(t)?ui(e,t):u.IsNumber(t)?ii(e,t):u.IsInteger(t)?oi(e,t):u.IsBoolean(t)?ni(e,t):p.False}function si(e,t){return p.False}function hd(e,t){return p.True}function Zs(e){let[t,r]=[e,0];for(;u.IsNot(t);)t=t.not,r+=1;return r%2===0?t:ut()}function yd(e,t){return u.IsNot(e)?K(Zs(e),t):u.IsNot(t)?K(e,Zs(t)):Gt("Invalid fallthrough for Not")}function Id(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsNull(t)?p.True:p.False}function ii(e,t){return u.IsLiteralNumber(e)||u.IsNumber(e)||u.IsInteger(e)?p.True:p.False}function wd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsInteger(t)||u.IsNumber(t)?p.True:p.False}function ge(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function ei(e){return Wr(e)}function ti(e){return ge(e,0)||ge(e,1)&&"description"in e.properties&&u.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(u.IsString(e.properties.description.anyOf[0])&&u.IsUndefined(e.properties.description.anyOf[1])||u.IsString(e.properties.description.anyOf[1])&&u.IsUndefined(e.properties.description.anyOf[0]))}function to(e){return ge(e,0)}function ri(e){return ge(e,0)}function Sd(e){return ge(e,0)}function xd(e){return ge(e,0)}function bd(e){return Wr(e)}function kd(e){let t=Te();return ge(e,0)||ge(e,1)&&"length"in e.properties&&Re(K(e.properties.length,t))===p.True}function Pd(e){return ge(e,0)}function Wr(e){let t=Te();return ge(e,0)||ge(e,1)&&"length"in e.properties&&Re(K(e.properties.length,t))===p.True}function Td(e){let t=Ge([it()],it());return ge(e,0)||ge(e,1)&&"then"in e.properties&&Re(K(e.properties.then,t))===p.True}function ai(e,t){return K(e,t)===p.False||u.IsOptional(e)&&!u.IsOptional(t)?p.False:p.True}function ce(e,t){return u.IsUnknown(e)?p.False:u.IsAny(e)?p.Union:u.IsNever(e)||u.IsLiteralString(e)&&ei(t)||u.IsLiteralNumber(e)&&to(t)||u.IsLiteralBoolean(e)&&ri(t)||u.IsSymbol(e)&&ti(t)||u.IsBigInt(e)&&Sd(t)||u.IsString(e)&&ei(t)||u.IsSymbol(e)&&ti(t)||u.IsNumber(e)&&to(t)||u.IsInteger(e)&&to(t)||u.IsBoolean(e)&&ri(t)||u.IsUint8Array(e)&&bd(t)||u.IsDate(e)&&xd(t)||u.IsConstructor(e)&&Pd(t)||u.IsFunction(e)&&kd(t)?p.True:u.IsRecord(e)&&u.IsString(no(e))?t[Pe]==="Record"?p.True:p.False:u.IsRecord(e)&&u.IsNumber(no(e))&&ge(t,0)?p.True:p.False}function Ad(e,t){return ee(t)?te(e,t):u.IsRecord(t)?Ce(e,t):u.IsObject(t)?(()=>{for(let r of Object.getOwnPropertyNames(t.properties)){if(!(r in e.properties)&&!u.IsOptional(t.properties[r]))return p.False;if(u.IsOptional(t.properties[r]))return p.True;if(ai(e.properties[r],t.properties[r])===p.False)return p.False}return p.True})():p.False}function $d(e,t){return ee(t)?te(e,t):u.IsObject(t)&&Td(t)?p.True:u.IsPromise(t)?Re(K(e.item,t.item)):p.False}function no(e){return ot in e.patternProperties?Te():st in e.patternProperties?Ue():Gt("Unknown record key pattern")}function oo(e){return ot in e.patternProperties?e.patternProperties[ot]:st in e.patternProperties?e.patternProperties[st]:Gt("Unable to get record value schema")}function Ce(e,t){let[r,n]=[no(t),oo(t)];return u.IsLiteralString(e)&&u.IsNumber(r)&&Re(K(e,n))===p.True?p.True:u.IsUint8Array(e)&&u.IsNumber(r)||u.IsString(e)&&u.IsNumber(r)||u.IsArray(e)&&u.IsNumber(r)?K(e,n):u.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(ai(n,e.properties[o])===p.False)return p.False;return p.True})():p.False}function Rd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?K(oo(e),oo(t)):p.False}function Cd(e,t){let r=u.IsRegExp(e)?Ue():e,n=u.IsRegExp(t)?Ue():t;return K(r,n)}function ui(e,t){return u.IsLiteral(e)&&ie.IsString(e.const)||u.IsString(e)?p.True:p.False}function Md(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsString(t)?p.True:p.False}function Od(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsSymbol(t)?p.True:p.False}function Ed(e,t){return u.IsTemplateLiteral(e)?K(Tt(e),t):u.IsTemplateLiteral(t)?K(e,Tt(t)):Gt("Invalid fallthrough for TemplateLiteral")}function vd(e,t){return u.IsArray(t)&&e.items!==void 0&&e.items.every(r=>K(r,t.items)===p.True)}function _d(e,t){return u.IsNever(e)?p.True:u.IsUnknown(e)?p.False:u.IsAny(e)?p.Union:p.False}function Fd(e,t){return ee(t)?te(e,t):u.IsObject(t)&&Wr(t)||u.IsArray(t)&&vd(e,t)?p.True:u.IsTuple(t)?ie.IsUndefined(e.items)&&!ie.IsUndefined(t.items)||!ie.IsUndefined(e.items)&&ie.IsUndefined(t.items)?p.False:ie.IsUndefined(e.items)&&!ie.IsUndefined(t.items)||e.items.every((r,n)=>K(r,t.items[n])===p.True)?p.True:p.False:p.False}function Nd(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsUint8Array(t)?p.True:p.False}function Ud(e,t){return ee(t)?te(e,t):u.IsObject(t)?ce(e,t):u.IsRecord(t)?Ce(e,t):u.IsVoid(t)?Kd(e,t):u.IsUndefined(t)?p.True:p.False}function io(e,t){return t.anyOf.some(r=>K(e,r)===p.True)?p.True:p.False}function Dd(e,t){return e.anyOf.every(r=>K(r,t)===p.True)?p.True:p.False}function ci(e,t){return p.True}function Ld(e,t){return u.IsNever(t)?si(e,t):u.IsIntersect(t)?Br(e,t):u.IsUnion(t)?io(e,t):u.IsAny(t)?so(e,t):u.IsString(t)?ui(e,t):u.IsNumber(t)?ii(e,t):u.IsInteger(t)?oi(e,t):u.IsBoolean(t)?ni(e,t):u.IsArray(t)?od(e,t):u.IsTuple(t)?_d(e,t):u.IsObject(t)?ce(e,t):u.IsUnknown(t)?p.True:p.False}function Kd(e,t){return u.IsUndefined(e)||u.IsUndefined(e)?p.True:p.False}function jd(e,t){return u.IsIntersect(t)?Br(e,t):u.IsUnion(t)?io(e,t):u.IsUnknown(t)?ci(e,t):u.IsAny(t)?so(e,t):u.IsObject(t)?ce(e,t):u.IsVoid(t)?p.True:p.False}function K(e,t){return u.IsTemplateLiteral(e)||u.IsTemplateLiteral(t)?Ed(e,t):u.IsRegExp(e)||u.IsRegExp(t)?Cd(e,t):u.IsNot(e)||u.IsNot(t)?yd(e,t):u.IsAny(e)?nd(e,t):u.IsArray(e)?sd(e,t):u.IsBigInt(e)?ad(e,t):u.IsBoolean(e)?ud(e,t):u.IsAsyncIterator(e)?id(e,t):u.IsConstructor(e)?cd(e,t):u.IsDate(e)?dd(e,t):u.IsFunction(e)?ld(e,t):u.IsInteger(e)?pd(e,t):u.IsIntersect(e)?md(e,t):u.IsIterator(e)?fd(e,t):u.IsLiteral(e)?gd(e,t):u.IsNever(e)?hd(e,t):u.IsNull(e)?Id(e,t):u.IsNumber(e)?wd(e,t):u.IsObject(e)?Ad(e,t):u.IsRecord(e)?Rd(e,t):u.IsString(e)?Md(e,t):u.IsSymbol(e)?Od(e,t):u.IsTuple(e)?Fd(e,t):u.IsPromise(e)?$d(e,t):u.IsUint8Array(e)?Nd(e,t):u.IsUndefined(e)?Ud(e,t):u.IsUnion(e)?Dd(e,t):u.IsUnknown(e)?Ld(e,t):u.IsVoid(e)?jd(e,t):Gt(`Unknown left type operand '${e[h]}'`)}function ct(e,t){return K(e,t)}function Bd(e,t,r,n,o){let s={};for(let i of globalThis.Object.getOwnPropertyNames(e))s[i]=Ht(e[i],t,r,n,G(o));return s}function Wd(e,t,r,n,o){return Bd(e.properties,t,r,n,o)}function di(e,t,r,n,o){let s=Wd(e,t,r,n,o);return v(s)}function Gd(e,t,r,n){let o=ct(e,t);return o===p.Union?F([r,n]):o===p.True?r:n}function Ht(e,t,r,n,o){return H(e)?di(e,t,r,n,o):Ie(e)?l(li(e,t,r,n,o)):l(Gd(e,t,r,n),o)}function Hd(e,t,r,n,o){return{[e]:Ht(_(e),t,r,n,G(o))}}function Vd(e,t,r,n,o){return e.reduce((s,i)=>({...s,...Hd(i,t,r,n,o)}),{})}function qd(e,t,r,n,o){return Vd(e.keys,t,r,n,o)}function li(e,t,r,n,o){let s=qd(e,t,r,n,o);return v(s)}function pi(e,t){return Vt(Tt(e),t)}function zd(e,t){let r=e.filter(n=>ct(n,t)===p.False);return r.length===1?r[0]:F(r)}function Vt(e,t,r={}){return we(e)?l(pi(e,t),r):H(e)?l(mi(e,t),r):l(M(e)?zd(e.anyOf,t):ct(e,t)!==p.False?O():e,r)}function Qd(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Vt(e[n],t);return r}function Yd(e,t){return Qd(e.properties,t)}function mi(e,t){let r=Yd(e,t);return v(r)}function fi(e,t){return qt(Tt(e),t)}function Jd(e,t){let r=e.filter(n=>ct(n,t)!==p.False);return r.length===1?r[0]:F(r)}function qt(e,t,r){return we(e)?l(fi(e,t),r):H(e)?l(gi(e,t),r):l(M(e)?Jd(e.anyOf,t):ct(e,t)!==p.False?e:O(),r)}function Xd(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=qt(e[n],t);return r}function Zd(e,t){return Xd(e.properties,t)}function gi(e,t){let r=Zd(e,t);return v(r)}function hi(e,t){return ve(e)?l(e.returns,t):O(t)}function Gr(e){return fe(ae(e))}function At(e,t,r){return l({[h]:"Record",type:"object",patternProperties:{[e]:t}},r)}function ao(e,t,r){let n={};for(let o of e)n[o]=t;return L(n,{...r,[Pe]:"Record"})}function el(e,t,r){return Es(e)?ao(me(e),t,r):At(e.pattern,t,r)}function tl(e,t,r){return ao(me(F(e)),t,r)}function rl(e,t,r){return ao([e.toString()],t,r)}function nl(e,t,r){return At(e.source,t,r)}function ol(e,t,r){let n=Y(e.pattern)?st:e.pattern;return At(n,t,r)}function sl(e,t,r){return At(st,t,r)}function il(e,t,r){return At(Ps,t,r)}function al(e,t,r){return L({true:t,false:t},r)}function ul(e,t,r){return At(ot,t,r)}function cl(e,t,r){return At(ot,t,r)}function Hr(e,t,r={}){return M(e)?tl(e.anyOf,t,r):we(e)?el(e,t,r):ye(e)?rl(e.const,t,r):Ye(e)?al(e,t,r):Fe(e)?ul(e,t,r):Ne(e)?cl(e,t,r):Kn(e)?nl(e,t,r):Je(e)?ol(e,t,r):Dn(e)?sl(e,t,r):rt(e)?il(e,t,r):O(r)}function Vr(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function yi(e){let t=Vr(e);return t===st?Ue():t===ot?Te():Ue({pattern:t})}function qr(e){return e.patternProperties[Vr(e)]}function dl(e,t){return t.parameters=Ir(e,t.parameters),t.returns=De(e,t.returns),t}function ll(e,t){return t.parameters=Ir(e,t.parameters),t.returns=De(e,t.returns),t}function pl(e,t){return t.allOf=Ir(e,t.allOf),t}function ml(e,t){return t.anyOf=Ir(e,t.anyOf),t}function fl(e,t){return Y(t.items)||(t.items=Ir(e,t.items)),t}function gl(e,t){return t.items=De(e,t.items),t}function hl(e,t){return t.items=De(e,t.items),t}function yl(e,t){return t.items=De(e,t.items),t}function Il(e,t){return t.item=De(e,t.item),t}function wl(e,t){let r=kl(e,t.properties);return{...t,...L(r)}}function Sl(e,t){let r=De(e,yi(t)),n=De(e,qr(t)),o=Hr(r,n);return{...t,...o}}function xl(e,t){return t.index in e?e[t.index]:ut()}function bl(e,t){let r=_t(t),n=pe(t),o=De(e,t);return r&&n?Gr(o):r&&!n?fe(o):!r&&n?ae(o):o}function kl(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:bl(e,t[n])}),{})}function Ir(e,t){return t.map(r=>De(e,r))}function De(e,t){return ve(t)?dl(e,t):_e(t)?ll(e,t):V(t)?pl(e,t):M(t)?ml(e,t):Se(t)?fl(e,t):Oe(t)?gl(e,t):wt(t)?hl(e,t):xt(t)?yl(e,t):bt(t)?Il(e,t):J(t)?wl(e,t):kt(t)?Sl(e,t):Ln(t)?xl(e,t):t}function Ii(e,t){return De(t,vt(e))}function wi(e){return l({[h]:"Integer",type:"integer"},e)}function Pl(e,t,r){return{[e]:Le(_(e),t,G(r))}}function Tl(e,t,r){return e.reduce((o,s)=>({...o,...Pl(s,t,r)}),{})}function Al(e,t,r){return Tl(e.keys,t,r)}function Si(e,t,r){let n=Al(e,t,r);return v(n)}function $l(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),r].join("")}function Rl(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),r].join("")}function Cl(e){return e.toUpperCase()}function Ml(e){return e.toLowerCase()}function Ol(e,t,r){let n=Lt(e.pattern);if(!Pt(n))return{...e,pattern:xi(e.pattern,t)};let i=[...fr(n)].map(m=>_(m)),a=bi(i,t),d=F(a);return vr([d],r)}function xi(e,t){return typeof e=="string"?t==="Uncapitalize"?$l(e):t==="Capitalize"?Rl(e):t==="Uppercase"?Cl(e):t==="Lowercase"?Ml(e):e:e.toString()}function bi(e,t){return e.map(r=>Le(r,t))}function Le(e,t,r={}){return Ie(e)?Si(e,t,r):we(e)?Ol(e,t,r):M(e)?F(bi(e.anyOf,t),r):ye(e)?_(xi(e.const,t),r):l(e,r)}function ki(e,t={}){return Le(e,"Capitalize",t)}function Pi(e,t={}){return Le(e,"Lowercase",t)}function Ti(e,t={}){return Le(e,"Uncapitalize",t)}function Ai(e,t={}){return Le(e,"Uppercase",t)}function El(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=dt(e[o],t,G(r));return n}function vl(e,t,r){return El(e.properties,t,r)}function $i(e,t,r){let n=vl(e,t,r);return v(n)}function _l(e,t){return e.map(r=>uo(r,t))}function Fl(e,t){return e.map(r=>uo(r,t))}function Nl(e,t){let{[t]:r,...n}=e;return n}function Ul(e,t){return t.reduce((r,n)=>Nl(r,n),e)}function Dl(e,t,r){let n=q(e,[Z,"$id","required","properties"]),o=Ul(r,t);return L(o,n)}function Ll(e){let t=e.reduce((r,n)=>Rr(n)?[...r,_(n)]:r,[]);return F(t)}function uo(e,t){return V(e)?ue(_l(e.allOf,t)):M(e)?F(Fl(e.anyOf,t)):J(e)?Dl(e,t,e.properties):L({})}function dt(e,t,r){let n=Q(t)?Ll(t):t,o=xe(t)?me(t):t,s=z(e),i=z(t);return H(e)?$i(e,o,r):Ie(t)?Ri(e,t,r):s&&i?W("Omit",[e,n],r):!s&&i?W("Omit",[e,n],r):s&&!i?W("Omit",[e,n],r):l({...uo(e,o),...r})}function Kl(e,t,r){return{[t]:dt(e,[t],G(r))}}function jl(e,t,r){return t.reduce((n,o)=>({...n,...Kl(e,o,r)}),{})}function Bl(e,t,r){return jl(e,t.keys,r)}function Ri(e,t,r){let n=Bl(e,t,r);return v(n)}function Wl(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=lt(e[o],t,G(r));return n}function Gl(e,t,r){return Wl(e.properties,t,r)}function Ci(e,t,r){let n=Gl(e,t,r);return v(n)}function Hl(e,t){return e.map(r=>co(r,t))}function Vl(e,t){return e.map(r=>co(r,t))}function ql(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function zl(e,t,r){let n=q(e,[Z,"$id","required","properties"]),o=ql(r,t);return L(o,n)}function Ql(e){let t=e.reduce((r,n)=>Rr(n)?[...r,_(n)]:r,[]);return F(t)}function co(e,t){return V(e)?ue(Hl(e.allOf,t)):M(e)?F(Vl(e.anyOf,t)):J(e)?zl(e,t,e.properties):L({})}function lt(e,t,r){let n=Q(t)?Ql(t):t,o=xe(t)?me(t):t,s=z(e),i=z(t);return H(e)?Ci(e,o,r):Ie(t)?Mi(e,t,r):s&&i?W("Pick",[e,n],r):!s&&i?W("Pick",[e,n],r):s&&!i?W("Pick",[e,n],r):l({...co(e,o),...r})}function Yl(e,t,r){return{[t]:lt(e,[t],G(r))}}function Jl(e,t,r){return t.reduce((n,o)=>({...n,...Yl(e,o,r)}),{})}function Xl(e,t,r){return Jl(e,t.keys,r)}function Mi(e,t,r){let n=Xl(e,t,r);return v(n)}function Zl(e,t){return W("Partial",[W(e,t)])}function ep(e){return W("Partial",[Ve(e)])}function tp(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=ae(e[r]);return t}function rp(e,t){let r=q(e,[Z,"$id","required","properties"]),n=tp(t);return L(n,r)}function Oi(e){return e.map(t=>Ei(t))}function Ei(e){return Ee(e)?Zl(e.target,e.parameters):z(e)?ep(e.$ref):V(e)?ue(Oi(e.allOf)):M(e)?F(Oi(e.anyOf)):J(e)?rp(e,e.properties):St(e)||Ye(e)||Fe(e)||ye(e)||ir(e)||Ne(e)||Je(e)||ar(e)||ur(e)?e:L({})}function zt(e,t){return H(e)?vi(e,t):l({...Ei(e),...t})}function np(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=zt(e[n],G(t));return r}function op(e,t){return np(e.properties,t)}function vi(e,t){let r=op(e,t);return v(r)}function sp(e,t){return W("Required",[W(e,t)])}function ip(e){return W("Required",[Ve(e)])}function ap(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=q(e[r],[oe]);return t}function up(e,t){let r=q(e,[Z,"$id","required","properties"]),n=ap(t);return L(n,r)}function _i(e){return e.map(t=>Fi(t))}function Fi(e){return Ee(e)?sp(e.target,e.parameters):z(e)?ip(e.$ref):V(e)?ue(_i(e.allOf)):M(e)?F(_i(e.anyOf)):J(e)?up(e,e.properties):St(e)||Ye(e)||Fe(e)||ye(e)||ir(e)||Ne(e)||Je(e)||ar(e)||ur(e)?e:L({})}function Qt(e,t){return H(e)?Ni(e,t):l({...Fi(e),...t})}function cp(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Qt(e[n],t);return r}function dp(e,t){return cp(e.properties,t)}function Ni(e,t){let r=dp(e,t);return v(r)}function lp(e,t){return t.map(r=>z(r)?lo(e,r.$ref):be(e,r))}function lo(e,t){return t in e?z(e[t])?lo(e,e[t].$ref):be(e,e[t]):O()}function pp(e){return Bt(e[0])}function mp(e){return at(e[0],e[1])}function fp(e){return Wt(e[0])}function gp(e){return zt(e[0])}function hp(e){return dt(e[0],e[1])}function yp(e){return lt(e[0],e[1])}function Ip(e){return Qt(e[0])}function wp(e,t,r){let n=lp(e,r);return t==="Awaited"?pp(n):t==="Index"?mp(n):t==="KeyOf"?fp(n):t==="Partial"?gp(n):t==="Omit"?hp(n):t==="Pick"?yp(n):t==="Required"?Ip(n):O()}function Sp(e,t){return Ft(be(e,t))}function xp(e,t){return Nt(be(e,t))}function bp(e,t,r){return Ut(wr(e,t),be(e,r))}function kp(e,t,r){return Ge(wr(e,t),be(e,r))}function Pp(e,t){return ue(wr(e,t))}function Tp(e,t){return jt(be(e,t))}function Ap(e,t){return L(globalThis.Object.keys(t).reduce((r,n)=>({...r,[n]:be(e,t[n])}),{}))}function $p(e,t){let[r,n]=[be(e,qr(t)),Vr(t)],o=vt(t);return o.patternProperties[n]=r,o}function Rp(e,t){return z(t)?{...lo(e,t.$ref),[Z]:t[Z]}:t}function Cp(e,t){return Ae(wr(e,t))}function Mp(e,t){return F(wr(e,t))}function wr(e,t){return t.map(r=>be(e,r))}function be(e,t){return pe(t)?l(be(e,q(t,[oe])),t):_t(t)?l(be(e,q(t,[Me])),t):nt(t)?l(Rp(e,t),t):Oe(t)?l(Sp(e,t.items),t):wt(t)?l(xp(e,t.items),t):Ee(t)?l(wp(e,t.target,t.parameters)):ve(t)?l(bp(e,t.parameters,t.returns),t):_e(t)?l(kp(e,t.parameters,t.returns),t):V(t)?l(Pp(e,t.allOf),t):xt(t)?l(Tp(e,t.items),t):J(t)?l(Ap(e,t.properties),t):kt(t)?l($p(e,t)):Se(t)?l(Cp(e,t.items||[]),t):M(t)?l(Mp(e,t.anyOf),t):t}function Op(e,t){return t in e?be(e,e[t]):O()}function Ui(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,r)=>({...t,[r]:Op(e,r)}),{})}var po=class{constructor(t){let r=Ui(t),n=this.WithIdentifiers(r);this.$defs=n}Import(t,r){let n={...this.$defs,[t]:l(this.$defs[t],r)};return l({[h]:"Import",$defs:n,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:{...t[n],$id:n}}),{})}};function Di(e){return new po(e)}function Li(e,t){return l({[h]:"Not",not:e},t)}function Ki(e,t){return _e(e)?Ae(e.parameters,t):O()}var Ep=0;function ji(e,t={}){Y(t.$id)&&(t.$id=`T${Ep++}`);let r=vt(e({[h]:"This",$ref:`${t.$id}`}));return r.$id=t.$id,l({[Pe]:"Recursive",...r},t)}function Bi(e,t){let r=j(e)?new globalThis.RegExp(e):e;return l({[h]:"RegExp",type:"RegExp",source:r.source,flags:r.flags},t)}function vp(e){return V(e)?e.allOf:M(e)?e.anyOf:Se(e)?e.items??[]:[]}function Wi(e){return vp(e)}function Gi(e,t){return _e(e)?l(e.returns,t):O(t)}var mo=class{constructor(t){this.schema=t}Decode(t){return new fo(this.schema,t)}},fo=class{constructor(t,r){this.schema=t,this.decode=r}EncodeTransform(t,r){let s={Encode:i=>r[Z].Encode(t(i)),Decode:i=>this.decode(r[Z].Decode(i))};return{...r,[Z]:s}}EncodeSchema(t,r){let n={Decode:this.decode,Encode:t};return{...r,[Z]:n}}Encode(t){return nt(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function Hi(e){return new mo(e)}function Vi(e={}){return l({[h]:e[h]??"Unsafe"},e)}function qi(e){return l({[h]:"Void",type:"void"},e)}var go={};En(go,{Any:()=>it,Argument:()=>Cs,Array:()=>Ft,AsyncIterator:()=>Nt,Awaited:()=>Bt,BigInt:()=>Kt,Boolean:()=>Er,Capitalize:()=>ki,Composite:()=>Qs,Const:()=>Ys,Constructor:()=>Ut,ConstructorParameters:()=>Js,Date:()=>Nr,Enum:()=>Xs,Exclude:()=>Vt,Extends:()=>Ht,Extract:()=>qt,Function:()=>Ge,Index:()=>at,InstanceType:()=>hi,Instantiate:()=>Ii,Integer:()=>wi,Intersect:()=>ue,Iterator:()=>jt,KeyOf:()=>Wt,Literal:()=>_,Lowercase:()=>Pi,Mapped:()=>Ws,Module:()=>Di,Never:()=>O,Not:()=>Li,Null:()=>Ur,Number:()=>Te,Object:()=>L,Omit:()=>dt,Optional:()=>ae,Parameters:()=>Ki,Partial:()=>zt,Pick:()=>lt,Promise:()=>Fr,Readonly:()=>fe,ReadonlyOptional:()=>Gr,Record:()=>Hr,Recursive:()=>ji,Ref:()=>Ve,RegExp:()=>Bi,Required:()=>Qt,Rest:()=>Wi,ReturnType:()=>Gi,String:()=>Ue,Symbol:()=>Dr,TemplateLiteral:()=>vr,Transform:()=>Hi,Tuple:()=>Ae,Uint8Array:()=>Kr,Uncapitalize:()=>Ti,Undefined:()=>Lr,Union:()=>F,Unknown:()=>ut,Unsafe:()=>Vi,Uppercase:()=>Ai,Void:()=>qi});var g=go;var I=null;function ho(e){I=e}import{readFileSync as _p}from"fs";import{homedir as Fp}from"os";import{join as Np}from"path";var Sr,zi="claude-code",zr={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium",approvalPolicy:"on-request"}};function Qi(){if(Sr!==void 0)return Sr;try{let e=_p(Np(Fp(),".claude.json"),"utf-8");Sr=JSON.parse(e).mcpServers??{}}catch{Sr={}}return Sr}var N={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"ask",codexApprovalPolicy:"on-request",harnesses:{"claude-code":{...zr["claude-code"]},codex:{...zr.codex}}};function Yi(e){let t=e.defaultHarness??zi,r={};for(let[n,o]of Object.entries(zr))r[n]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[n,o]of Object.entries(e.harnesses??{})){let i={...r[n]??{},...o};o.allowedModels!==void 0?i.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(i.allowedModels=void 0),r[n]=i}if(e.defaultModel!==void 0){let n=r[t]??{};r[t]={...n,defaultModel:e.harnesses?.[t]?.defaultModel??e.defaultModel,allowedModels:e.harnesses?.[t]?.allowedModels!==void 0?n.allowedModels:e.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${t}.defaultModel instead.`)}if(e.model!==void 0){let n=r.codex??{};r.codex={...n,defaultModel:e.harnesses?.codex?.defaultModel??e.model,allowedModels:e.harnesses?.codex?.allowedModels!==void 0?n.allowedModels:e.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(e.reasoningEffort!==void 0){let n=r.codex??{};r.codex={...n,reasoningEffort:e.harnesses?.codex?.reasoningEffort??e.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(e.codexApprovalPolicy!==void 0){let n=r.codex??{};r.codex={...n,approvalPolicy:e.harnesses?.codex?.approvalPolicy??e.codexApprovalPolicy},console.warn("[openclaw-code-agent] config.codexApprovalPolicy is deprecated; use harnesses.codex.approvalPolicy instead.")}if(e.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[n,o]of Object.entries(r))e.harnesses?.[n]?.allowedModels===void 0&&(r[n]={...o,allowedModels:void 0})}N={maxSessions:e.maxSessions??20,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??15,sessionGcAgeMinutes:e.sessionGcAgeMinutes??1440,maxPersistedSessions:e.maxPersistedSessions??1e4,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10,permissionMode:e.permissionMode??"plan",codexApprovalPolicy:e.codexApprovalPolicy??"on-request",planApproval:e.planApproval??"ask",defaultHarness:t,harnesses:r,allowedModels:e.allowedModels,defaultWorktreeStrategy:e.defaultWorktreeStrategy??"ask",worktreeDir:e.worktreeDir}}function pt(){return N.defaultHarness??zi}function yo(e){let t=zr[e],r=N.harnesses[e];return{...t,...r,allowedModels:r?.allowedModels??t?.allowedModels}}function mt(e){return yo(e).defaultModel}function Ji(e){return N.harnesses[e]?.allowedModels??N.allowedModels}function Yt(e){return yo(e).reasoningEffort}function $t(e){return yo(e).approvalPolicy}function Xi(e){if(e.messageChannel){let t=e.messageChannel.split("|");if(t.length>=3)return e.messageChannel;if(e.agentAccountId&&t.length>=2)return`${t[0]}|${e.agentAccountId}|${t.slice(1).join("|")}`;if(t.length===1&&e.chatId)return`${t[0]}|${e.chatId}`;if(t.length===1&&e.senderId)return`${t[0]}|${e.senderId}`}if(e.workspaceDir){let t=xr(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function Jt(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);if(e?.messageChannel){let r=String(e.messageChannel);if(r.includes("|"))return r;if(e.chatId)return`${r}|${e.chatId}`;if(e.senderId)return`${r}|${e.senderId}`}return e?.channel&&e?.chatId?`${e.channel}|${e.chatId}`:e?.channel&&e?.senderId?`${e.channel}|${e.senderId}`:e?.id&&/^-?\d+$/.test(String(e.id))?`telegram|${e.id}`:N.fallbackChannel??"unknown"}function Xt(e){return e?.messageThreadId??void 0}function xr(e){let t=N.agentChannels;if(!t)return;let r=s=>s.replace(/\/+$/,""),n=r(e),o=Object.entries(t).sort((s,i)=>i[0].length-s[0].length);for(let[s,i]of o)if(n===r(s)||n.startsWith(r(s)+"/"))return i}function Zi(e){if(!e)return;let t=e.match(/:topic:(\d+)$/);return t?parseInt(t[1],10):void 0}function Zt(e){let{requestedResumeSessionId:t,activeSession:r,persistedSession:n}=e;return t?r?{resumeSessionId:t,clearedPersistedCodexResume:!1}:n?.harness==="codex"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:t,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}function Dp(e){return e instanceof Error?e.message:String(e)}function Lp(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function Kp(e,t){if(!t||t.length===0)return!0;if(!e)return!1;let r=e.toLowerCase();return t.some(n=>r.includes(n.toLowerCase()))}function ea(e){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn by default \u2014 they stay open for follow-up messages via agent_respond. Set multi_turn_disabled: true for fire-and-forget sessions. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:g.Object({prompt:g.String({description:"The task prompt to execute"}),name:g.Optional(g.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:g.Optional(g.String({description:"Working directory (defaults to cwd)"})),model:g.Optional(g.String({description:"Model name to use"})),system_prompt:g.Optional(g.String({description:"Additional system prompt"})),allowed_tools:g.Optional(g.Array(g.String(),{description:"List of allowed tools"})),resume_session_id:g.Optional(g.String({description:"Session ID to resume (from a previous session's harnessSessionId). Continues the conversation from where it left off."})),fork_session:g.Optional(g.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),multi_turn_disabled:g.Optional(g.Boolean({description:"Disable multi-turn mode. By default sessions stay open for follow-up messages. Set to true for fire-and-forget sessions."})),permission_mode:g.Optional(g.Union([g.Literal("default"),g.Literal("plan"),g.Literal("bypassPermissions")],{description:"Permission mode: 'default' (standard prompts), 'plan' (present plan first, wait for approval), 'bypassPermissions' (fully autonomous execution). Defaults to plugin config ('plan' by default)."})),harness:g.Optional(g.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."})),worktree_strategy:g.Optional(g.Union([g.Literal("off"),g.Literal("manual"),g.Literal("ask"),g.Literal("auto-merge"),g.Literal("auto-pr")],{description:"Worktree strategy: 'off' (no worktree), 'manual' (create worktree but no auto merge-back), 'ask' (prompt user with options), 'auto-merge' (merge automatically), 'auto-pr' (create PR automatically). Defaults to 'off'. Only respected when `defaultWorktreeStrategy` is set to `delegate` or is unset. Otherwise the admin-configured default is used regardless."})),worktree_base_branch:g.Optional(g.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),output_mode:g.Optional(g.Literal("deliverable",{description:"Output mode: 'deliverable' sends a \u{1F4C4} Deliverable ready notification instead of \u2705 Completed when the session finishes."}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Lp(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};r.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${r.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${e.agentId}" will be used for origin routing instead.`);let n=r.workdir||e.workspaceDir||N.defaultWorkdir||process.cwd();if(!Up(n))return{content:[{type:"text",text:`Error: Working directory does not exist: ${n}`}]};try{let o=r.harness??pt(),s=mt(o),i=r.model??s,a=r.model!==void 0;if(!i)return{content:[{type:"text",text:`Error: No default model configured for harness "${o}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${o}.defaultModel or pass model explicitly.`}]};let d=Ji(o);if(d&&d.length>0&&!Kp(i,d))return{content:[{type:"text",text:a?`Error: Model "${i}" is not allowed. Permitted models: ${d.join(", ")}`:`Error: Default model "${i||"undefined"}" is not in allowedModels (${d.join(", ")}). Update your plugin config to set a compatible defaultModel.`}]};let m=r.resume_session_id,y=m?I.resolve(m):void 0,f=m?I.getPersistedSession(m):void 0;if(m){let P=I.resolveHarnessSessionId(m);if(!P)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${m}" to a session ID. Use agent_sessions to list available sessions.`}]};m=P}let{resumeSessionId:c,clearedPersistedCodexResume:w}=Zt({requestedResumeSessionId:m,activeSession:y?{harnessSessionId:y.harnessSessionId}:void 0,persistedSession:f?{harness:f.harness}:void 0}),S=Xi(e),k=Jt(e,S||xr(n)),x=e.sessionKey||void 0;!x&&e.agentId&&console.warn(`[agent_launch] ctx.sessionKey is not populated. ctx fields: agentId=${e.agentId}, messageChannel=${e.messageChannel}, agentAccountId=${e.agentAccountId}, workspaceDir=${e.workspaceDir}`);let T=I.spawn({prompt:r.prompt,name:r.name,workdir:n,model:i,reasoningEffort:Yt(o),systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,resumeSessionId:c,resumeWorktreeFrom:m,forkSession:c?r.fork_session:!1,multiTurn:!r.multi_turn_disabled,permissionMode:r.permission_mode,codexApprovalPolicy:o==="codex"?$t(o)??N.codexApprovalPolicy:void 0,originChannel:k,originThreadId:Zi(x)??Xt(e),originAgentId:e.agentId||void 0,originSessionKey:x,harness:o,worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,outputMode:r.output_mode}),b=r.prompt.length>80?r.prompt.slice(0,80)+"...":r.prompt,E=["Session launched successfully.",` Name: ${T.name}`,` ID: ${T.id}`,` Dir: ${n}`,` Model: ${T.model??"default"}`,` Prompt: "${b}"`];return o==="codex"&&E.push(` Codex approval policy: ${T.codexApprovalPolicy??$t(o)??N.codexApprovalPolicy}`),r.resume_session_id&&(E.push(` Resume: ${r.resume_session_id}${r.fork_session?" (forked)":""}`),w&&E.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),E.push(r.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),E.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:E.join(`
2
+ `)}]}}catch(o){let s=Dp(o),i=s.includes("Max sessions")?"":`
3
+
4
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${s}${i}`}]}}}}}import{existsSync as sa,readFileSync as ia}from"fs";function qe(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),n=t%60;return r>0?`${r}m${n}s`:`${n}s`}var jp=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","i","me","my","we","our","you","your","it","its","he","she","to","of","in","for","on","with","at","by","from","as","into","through","about","that","this","these","those","and","or","but","if","then","so","not","no","please","just","also","very","all","some","any","each","make","write","create","build","implement","add","update"]);function ra(e){let r=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!jp.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var ta={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",deliverable:"\u{1F4C4}",failed:"\u274C",killed:"\u26D4","awaiting-plan-approval":"\u{1F4CB}"};function na(e){let t=ta[e.phase]??ta[e.status]??"\u2753",r=qe(e.duration),n=e.multiTurn?"multi-turn":"single",o=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,s=e.costUsd>0?` | $${e.costUsd.toFixed(2)}`:"",i=[`${t} ${e.name} [${e.id}] (${r}${s}) \u2014 ${n}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];if(e.worktreePath&&e.worktreeBranch){let a=` \u{1F33F} Worktree: ${e.worktreeBranch}`;e.worktreeMerged?a+=" [merged \u2713]":e.worktreePrUrl?a+=` [PR: ${e.worktreePrUrl}]`:a+=" [not merged]",i.push(a)}return e.phase!==e.status&&i.push(` \u2699\uFE0F Phase: ${e.phase}`),e.harness&&i.push(` \u{1F9F0} Harness: ${e.harness}`),e.harnessSessionId&&i.push(` \u{1F517} Session ID: ${e.harnessSessionId}`),e.resumeSessionId&&i.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),i.join(`
5
+ `)}function Qr(e,t){let r=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:n,failed:o,killed:s}=e.sessionsByStatus,i=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${n}`,` Failed: ${o}`,` Killed: ${s}`,"",`\u23F1\uFE0F Average duration: ${r>0?qe(r):"n/a"}`];if(e.mostExpensive){let a=e.mostExpensive;i.push("","\u{1F3C6} Notable session",` ${a.name} [${a.id}]`,` \u{1F4DD} "${a.prompt}"`)}return i.join(`
6
+ `)}function Rt(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function oa(e,t){let r=e.split(`
7
+ `),n=[],o=0;for(let s=r.length-1;s>=0;s--){let i=r[s].length+(n.length>0?1:0);if(o+i>t&&n.length>0)break;n.unshift(r[s]),o+=i}return n.join(`
8
+ `)}var Bp=50,Wp=1,Gp=new Set(["starting","running","completed","failed","killed"]),Hp=5,Vp=1440*60*1e3;function qp(e){let t=Number(e);return!Number.isFinite(t)||t<Wp?Bp:Math.floor(t)}function zp(e){return typeof e=="string"&&Gp.has(e)}function Qp(e){let t=qe(e.duration),r=` | Cost: $${e.costUsd.toFixed(4)}`,n=e.status==="running"?` | Phase: ${e.phase}`:"";return[`Session: ${e.name} [${e.id}] | Status: ${e.status.toUpperCase()}${n}${r} | Duration: ${t}`,`${"\u2500".repeat(60)}`].join(`
9
+ `)}function Yp(e){return[`Session: ${e.name||e.harnessSessionId} | Status: ${e.status.toUpperCase()} | Cost: $${e.costUsd.toFixed(4)}`,`(retrieved from ${e.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`,`${"\u2500".repeat(60)}`].join(`
10
+ `)}function Jp(e){let t=[];return e.error&&t.push(`Error: ${e.error}`),e.result?.result&&t.push(`Result: ${e.result.result}`),e.result&&t.push(`Result status: ${e.result.subtype}`),t.length>0?`
11
11
  (no output yet)
12
12
  ${t.join(`
13
13
  `)}`:`
14
- (no output yet)`}function vn(e,t,n={}){let r=pp(n.lines),o=e.resolve(t);if(!o){let c=e.getPersistedSession(t);if(c?.outputPath&&sp(c.outputPath))try{let p=ip(c.outputPath,"utf-8"),f=p;!n.full&&p&&(f=p.split(`
15
- `).slice(-r).join(`
16
- `));let T=gp(c);return f?`${T}
17
- ${f}`:`${T}
18
- (output file was empty)`}catch(p){let f=p instanceof Error?p.message:String(p);return`Error: Session "${t}" was cleaned up (expired) and output file could not be read: ${f}`}return`Error: Session "${t}" not found.`}let i=n.full?o.getOutput():o.getOutput(r),s=fp(o);return i.length===0?`${s}${Ip(o)}`:`${s}
19
- ${i.join(`
20
- `)}`}function Nn(e,t="all",n,r={}){let o=e.listPersistedSessions()??[],s=hp(e.list("all"),o);if(t!=="all"&&(s=s.filter(c=>c.status===t)),n&&(s=s.filter(c=>c.originChannel===n)),r.full){let c=Date.now()-mp;s=s.filter(p=>(p.startedAt??0)>=c)}else s=s.slice(0,cp);return s.length===0?"No sessions found.":s.map(c=>Oi(c)).join(`
21
-
22
- `)}function hp(e,t){let n=new Map;for(let r of t){if(!lp(r.status))continue;let o=r.completedAt??Date.now(),i=r.createdAt??o,s=r.sessionId??`persisted:${r.harnessSessionId}`;n.set(s,{id:r.sessionId??r.harnessSessionId,name:r.name||r.harnessSessionId,status:r.status,startedAt:r.createdAt??0,completedAt:r.completedAt,duration:Math.max(0,o-i),prompt:r.prompt??"",workdir:r.workdir??"(unknown)",costUsd:r.costUsd??0,multiTurn:!0,phase:r.status,harness:r.harness,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId})}for(let r of e)n.set(r.id,{id:r.id,name:r.name,status:r.status,startedAt:r.startedAt,completedAt:r.completedAt,duration:r.duration,prompt:r.prompt,workdir:r.workdir,costUsd:r.costUsd,multiTurn:r.multiTurn,phase:r.phase,harness:r.harnessName,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId});return[...n.values()].sort((r,o)=>(o.startedAt??0)-(r.startedAt??0))}function yp(e){if(!e||typeof e!="object")return"all";let t=e.status;switch(t){case"running":case"completed":case"failed":case"killed":case"all":return t;default:return"all"}}function Mi(e){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:l.Object({status:l.Optional(l.Union([l.Literal("all"),l.Literal("running"),l.Literal("completed"),l.Literal("failed"),l.Literal("killed")],{description:'Filter by status (default "all")'})),full:l.Optional(l.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=yp(n),o=e?.workspaceDir?on(e.workspaceDir):void 0,i=!!(n&&typeof n=="object"&&n.full===!0);return{content:[{type:"text",text:Nn(g,r,o,{full:i})}]}}}}function Un(e,t,n){let r=e.resolve(t);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`:n==="completed"?(r.complete(),`Session ${r.name} [${r.id}] marked as completed.`):(e.kill(r.id),`Session ${r.name} [${r.id}] has been terminated.`):`Error: Session "${t}" not found.`}function xp(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session!="string"?!1:t.reason===void 0?!0:t.reason==="completed"||t.reason==="killed"}function Ei(e){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:l.Object({session:l.String({description:"Session name or ID to terminate"}),reason:l.Optional(l.Union([l.Literal("completed"),l.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(t,n){return g?xp(n)?{content:[{type:"text",text:Un(g,n.session,n.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}function Sp(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function ki(e){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:l.Object({session:l.String({description:"Session name or ID to get output from"}),lines:l.Optional(l.Number({description:"Number of recent lines to show (default 50)"})),full:l.Optional(l.Boolean({description:"Show all available output"}))}),async execute(t,n){return g?Sp(n)?{content:[{type:"text",text:vn(g,n.session,{full:n.full,lines:n.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}var Tp=new Set(["killed","completed","failed"]),bp=new Set(["startup-timeout"]),wp=10,Ap=100,Pp=/\b(change|swap|replace|remove|add|update|instead|don't|revise|modify)\b/i;function sn(e){return e instanceof Error?e.message:String(e)}function Rp(e,t){switch(e){case"completed":return"completed";case"failed":return"failed";default:return t==="user"?"user-killed":t==="shutdown"?"shutdown-killed":"idle-kill"}}function Fi(e){return"id"in e?e.id:e.sessionId??e.harnessSessionId}function Op(e){return e.status==="killed"&&e.completedAt==null}function Cp(e,t){return Tp.has(e.status)&&!!e.harnessSessionId&&(e.status==="failed"||e.status==="completed"&&e.killReason==="done"||e.status==="killed"&&(!bp.has(e.killReason??"")||t&&Op(e)))}function Mp(e,t){if(!(t.trim().length<Ap&&!Pp.test(t)))return{text:["Cannot approve and revise in the same call.","Your message appears to contain revision feedback. Send it first WITHOUT approve=true:",` agent_respond(session='${e}', message='<your feedback>')`,"The agent will revise the plan. Then approve the revised plan."].join(`
23
- `),isError:!0}}async function Ep(e,t,n,r={}){if(Cp(t,r.allowRecoveredRunningStub===!0))try{let o="harnessName"in t?t:void 0,i="harnessName"in t?void 0:t,{resumeSessionId:s}=Lt({requestedResumeSessionId:t.harnessSessionId,activeSession:o?{harnessSessionId:o.harnessSessionId}:void 0,persistedSession:i?{harness:i.harness}:void 0}),c={prompt:n,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:s,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,harness:"harnessName"in t?t.harnessName:t.harness},p=await e.spawnAndAwaitRunning(c,{notifyLaunch:!1}),f=Rp(t.status,t.killReason);return e.notifySession(p,`\u{1F504} [${p.name}] Auto-resumed from ${f}`),{text:`Auto-resumed ${f} session ${p.name} [${p.id}]. Use agent_output to see the response.`}}catch(o){return{text:`Error auto-resuming session ${t.name} [${Fi(t)}]: ${sn(o)}`,isError:!0}}}function kp(e,t,n){let r=t.lobsterResumeToken;if(!r)return;t.lobsterResumeToken=void 0;let o=t.pendingPlanApproval||t.currentPermissionMode==="acceptEdits"||t.currentPermissionMode==="default";if(n.approve&&o)return e.resumeLobsterApproval(r,!0).catch(i=>{console.error(`[Respond] Lobster resume failed, falling back to direct mode switch: ${sn(i)}`),t.switchPermissionMode("bypassPermissions"),t.sendMessage(n.message).catch(s=>{console.error(`[Respond] Fallback sendMessage also failed: ${sn(s)}`)})}),{text:`Plan approved. Lobster workflow resuming for session ${t.name} [${t.id}].`};e.resumeLobsterApproval(r,!1).catch(i=>{console.error(`[Respond] Lobster cancel failed (non-critical): ${sn(i)}`)})}async function _n(e,t){let n=e.resolve(t.session),r=n?void 0:e.getPersistedSession(t.session);if(!n&&!r)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let i=await Ep(e,n??r,t.message,{allowRecoveredRunningStub:!n});if(i)return i;if(!n)return{text:`Error: Session ${r.name} [${Fi(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return{text:`Error: Session ${n.name} [${n.id}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};let s=E.maxAutoResponds??wp;if(t.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=s)return{text:`\u26A0\uFE0F Auto-respond limit reached (${n.autoRespondCount}/${s}). Ask the user to provide the answer for session ${n.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};let c=kp(e,n,t);if(c)return c;try{t.interrupt&&await n.interrupt();let p="";if(t.approve&&n.pendingPlanApproval){let T=Mp(n.name,t.message);if(T)return T;n.switchPermissionMode("bypassPermissions")}else t.approve&&(n.currentPermissionMode==="acceptEdits"||n.currentPermissionMode==="default")?n.switchPermissionMode("bypassPermissions"):t.approve&&n.currentPermissionMode==="bypassPermissions"?p=`
24
- \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:t.approve?p=`
25
- \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:n.pendingPlanApproval&&(p=`
26
- \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`);await n.sendMessage(t.message),t.userInitiated||n.incrementAutoRespond();let f=ot(t.message,80);return{text:[`Message sent to session ${n.name} [${n.id}].`,t.interrupt?" (interrupted current turn first)":"",` Message: "${f}"`,p,"Use agent_output to see the response."].filter(Boolean).join(`
27
- `)}}catch(p){return{text:`Error sending message to session ${n.name} [${n.id}]: ${sn(p)}`,isError:!0}}}function Fp(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function $i(e){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent session. The session must be running. Sessions are multi-turn by default, so this works with any session unless it was launched with multi_turn_disabled: true.",parameters:l.Object({session:l.String({description:"Session name or ID to respond to"}),message:l.String({description:"The message to send to the session"}),interrupt:l.Optional(l.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:l.Optional(l.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:l.Optional(l.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode (after ExitPlanMode / set_permission_mode), or (2) escalate an acceptEdits or default mode session to skip all remaining permission prompts. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Fp(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let r=await _n(g,n);return{isError:r.isError??!1,content:[{type:"text",text:r.text}]}}}}function vi(e){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:l.Object({}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=g.getMetrics(),o=g.list("running").length;return{content:[{type:"text",text:$n(r,o)}]}}}}function $p(e){return e instanceof Error?e.message:String(e)}function Ni(e){e.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent [--name <name>] <prompt>"};let r,o=n.match(/^--name\s+(\S+)\s+/);o&&(r=o[1],n=n.slice(o[0].length).trim());let i=n;if(!i)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let s=nt(),c=rt(s);if(!c)return{text:`Error: No default model configured for harness "${s}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${s}.defaultModel or pass model explicitly via agent_launch.`};let p=g.spawn({prompt:i,name:r,workdir:E.defaultWorkdir||process.cwd(),model:c,reasoningEffort:Nt(s),codexApprovalPolicy:s==="codex"?gt(s)??E.codexApprovalPolicy:void 0,originChannel:Ut(t),originThreadId:_t(t),harness:s}),f=i.length>80?i.slice(0,80)+"...":i;return{text:["Session launched.",` Name: ${p.name}`,` ID: ${p.id}`,` Prompt: "${f}"`,` Status: ${p.status}`].join(`
28
- `)}}catch(s){let c=$p(s),p=c.includes("Max sessions")?"":`
29
-
30
- Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${c}${p}`}}}})}function Ui(e){e.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").split(/\s+/).includes("--full");return{text:Nn(g,"all",void 0,{full:n})}}})}function _i(e){e.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=t.args?.trim();return n?{text:Un(g,n,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}function vp(e){return e instanceof Error?e.message:String(e)}function Li(e){e.registerCommand({name:"agent_resume",description:"Resume a previous coding agent session. Usage: /agent_resume <id-or-name> [prompt] or /agent_resume --list to see resumable sessions.",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /agent_resume <id-or-name> [prompt]
14
+ (no output yet)`}function Yr(e,t,r={}){let n=qp(r.lines),o=e.resolve(t);if(!o){let d=e.getPersistedSession(t);if(d?.outputPath&&sa(d.outputPath))try{let m=ia(d.outputPath,"utf-8"),y=m;!r.full&&m&&(y=m.split(`
15
+ `).slice(-n).join(`
16
+ `));let f=Yp(d);return y?`${f}
17
+ ${y}`:`${f}
18
+ (output file was empty)`}catch(m){let y=m instanceof Error?m.message:String(m);return`Error: Session "${t}" was cleaned up (expired) and output file could not be read: ${y}`}return`Error: Session "${t}" not found.`}let s=r.full?o.getOutput():o.getOutput(n),i=Qp(o),a=s.length===0?`${i}${Jp(o)}`:`${i}
19
+ ${s.join(`
20
+ `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(sa(o.planFilePath)){let d=ia(o.planFilePath,"utf-8"),m="\u2500".repeat(60);return`${a}
21
+ ${m}
22
+ Plan file: ${o.planFilePath}
23
+ ${m}
24
+ ${d}`}}catch{}return a}function Jr(e,t="all",r,n={}){let o=e.listPersistedSessions()??[],i=Xp(e.list("all"),o);if(t!=="all"&&(i=i.filter(a=>a.status===t)),r&&(i=i.filter(a=>a.originChannel===r)),n.full){let a=Date.now()-Vp;i=i.filter(d=>(d.startedAt??0)>=a)}else i=i.slice(0,Hp);return i.length===0?"No sessions found.":i.map(a=>na(a)).join(`
25
+
26
+ `)}function Xp(e,t){let r=new Map;for(let n of t){if(!zp(n.status))continue;let o=n.completedAt??Date.now(),s=n.createdAt??o,i=n.sessionId??`persisted:${n.harnessSessionId}`;r.set(i,{id:n.sessionId??n.harnessSessionId,name:n.name||n.harnessSessionId,status:n.status,startedAt:n.createdAt??0,completedAt:n.completedAt,duration:Math.max(0,o-s),prompt:n.prompt??"",workdir:n.workdir??"(unknown)",costUsd:n.costUsd??0,multiTurn:!0,phase:n.status,harness:n.harness,harnessSessionId:n.harnessSessionId,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeMerged:n.worktreeMerged,worktreeMergedAt:n.worktreeMergedAt,worktreePrUrl:n.worktreePrUrl})}for(let n of e){let o;if(n.worktreePath&&n.originalWorkdir){let s=n.worktreePath.match(/openclaw-worktree-(.+)$/);s&&(o=`agent/${s[1]}`)}r.set(n.id,{id:n.id,name:n.name,status:n.status,startedAt:n.startedAt,completedAt:n.completedAt,duration:n.duration,prompt:n.prompt,workdir:n.originalWorkdir??n.workdir,costUsd:n.costUsd,multiTurn:n.multiTurn,phase:n.phase,harness:n.harnessName,harnessSessionId:n.harnessSessionId,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:o,worktreeStrategy:n.worktreeStrategy,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0})}return[...r.values()].sort((n,o)=>(o.startedAt??0)-(n.startedAt??0))}function Zp(e){if(!e||typeof e!="object")return"all";let t=e.status;switch(t){case"running":case"completed":case"failed":case"killed":case"all":return t;default:return"all"}}function aa(e){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:g.Object({status:g.Optional(g.Union([g.Literal("all"),g.Literal("running"),g.Literal("completed"),g.Literal("failed"),g.Literal("killed")],{description:'Filter by status (default "all")'})),full:g.Optional(g.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=Zp(r),o=e?.workspaceDir?xr(e.workspaceDir):void 0,s=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:Jr(I,n,o,{full:s})}]}}}}function Xr(e,t,r){let n=e.resolve(t);return n?n.status==="completed"||n.status==="failed"||n.status==="killed"?`Session ${n.name} [${n.id}] is already ${n.status}. No action needed.`:r==="completed"?(n.complete(),`Session ${n.name} [${n.id}] marked as completed.`):(e.kill(n.id),`Session ${n.name} [${n.id}] has been terminated.`):`Error: Session "${t}" not found.`}function em(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session!="string"?!1:t.reason===void 0?!0:t.reason==="completed"||t.reason==="killed"}function ua(e){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:g.Object({session:g.String({description:"Session name or ID to terminate"}),reason:g.Optional(g.Union([g.Literal("completed"),g.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(t,r){return I?em(r)?{content:[{type:"text",text:Xr(I,r.session,r.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}function tm(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function Zr(e){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:g.Object({session:g.String({description:"Session name or ID to get output from"}),lines:g.Optional(g.Number({description:"Number of recent lines to show (default 50)"})),full:g.Optional(g.Boolean({description:"Show all available output"}))}),async execute(t,r){return I?tm(r)?{content:[{type:"text",text:Yr(I,r.session,{full:r.full,lines:r.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}var rm=new Set(["killed","completed","failed"]),nm=new Set(["startup-timeout"]),om=10,sm=100,im=/\b(change|swap|replace|remove|add|update|instead|don't|revise|modify)\b/i;function Io(e){return e instanceof Error?e.message:String(e)}function wo(e){return"id"in e?e.id:e.sessionId??e.harnessSessionId}function am(e){return e.status==="killed"&&e.completedAt==null}function um(e,t){return rm.has(e.status)&&!!e.harnessSessionId&&(e.status==="failed"||e.status==="completed"&&e.killReason==="done"||e.status==="killed"&&(!nm.has(e.killReason??"")||t&&am(e)))}function cm(e){return e.killReason==="shutdown"&&!e.harnessSessionId}async function dm(e,t,r){try{let n={prompt:t.prompt,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,worktreeStrategy:t.worktreeStrategy,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,harness:"harnessName"in t?t.harnessName:t.harness},o=await e.spawnAndAwaitRunning(n,{notifyLaunch:!1});return e.notifySession(o,`\u25B6\uFE0F [${o.name}] Relaunched fresh`),{text:`Session ${t.name} was relaunched fresh \u2014 it was killed during startup before the harness initialized. New session: ${o.name} [${o.id}].`}}catch(n){return{text:`Error relaunching session ${t.name} [${wo(t)}]: ${Io(n)}`,isError:!0}}}function ca(e,t){if(!(t.trim().length<sm&&!im.test(t)))return{text:["Cannot approve and revise in the same call.","Your message appears to contain revision feedback. Send it first WITHOUT approve=true:",` agent_respond(session='${e}', message='<your feedback>')`,"The agent will revise the plan. Then approve the revised plan."].join(`
27
+ `),isError:!0}}var lm=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
28
+
29
+ `;async function pm(e,t,r,n={}){if(!um(t,n.allowRecoveredRunningStub===!0))return;let o=!!(n.approve&&t.currentPermissionMode==="plan");if(o){let s=ca(t.name,r);if(s)return s}try{let s="harnessName"in t?t:void 0,i="harnessName"in t?void 0:t,{resumeSessionId:a}=Zt({requestedResumeSessionId:t.harnessSessionId,activeSession:s?{harnessSessionId:s.harnessSessionId}:void 0,persistedSession:i?{harness:i.harness}:void 0}),d={prompt:o?lm+r:r,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:a,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:o?"bypassPermissions":t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,harness:"harnessName"in t?t.harnessName:t.harness},m=await e.spawnAndAwaitRunning(d,{notifyLaunch:!1});return o?e.notifySession(m,`\u{1F44D} [${m.name}] Plan approved (resumed)`,"plan-approved"):e.notifySession(m,`\u25B6\uFE0F [${m.name}] Auto-resumed`),{text:`Auto-resumed session ${m.name} [${m.id}]. Use agent_output to see the response.`}}catch(s){return{text:`Error auto-resuming session ${t.name} [${wo(t)}]: ${Io(s)}`,isError:!0}}}async function ft(e,t){let r=e.resolve(t.session),n=r?void 0:e.getPersistedSession(t.session);if(!r&&!n)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let o=r??n;if(cm(o))return dm(e,o,t.message);let s=await pm(e,o,t.message,{allowRecoveredRunningStub:!r,approve:t.approve});if(s)return s;if(!r)return{text:`Error: Session ${n.name} [${wo(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return{text:`Error: Session ${r.name} [${r.id}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};let i=N.maxAutoResponds??om;if(t.userInitiated)r.resetAutoRespond();else if(r.autoRespondCount>=i)return{text:`\u26A0\uFE0F Auto-respond limit reached (${r.autoRespondCount}/${i}). Ask the user to provide the answer for session ${r.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{let a=!1;t.interrupt&&(a=await r.interrupt());let d=!!(t.approve&&r.pendingPlanApproval),m="";if(t.approve&&r.pendingPlanApproval){let f=ca(r.name,t.message);if(f)return f;r.switchPermissionMode("bypassPermissions")}else t.approve&&r.currentPermissionMode==="default"?r.switchPermissionMode("bypassPermissions"):t.approve&&r.currentPermissionMode==="bypassPermissions"?m=`
30
+ \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:t.approve?m=`
31
+ \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:r.pendingPlanApproval&&(m=`
32
+ \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`);if(await r.sendMessage(t.message),d)e.notifySession(r,`\u{1F44D} [${r.name}] Plan approved`,"plan-approved");else{let f=Rt(t.message,100);e.notifySession(r,`\u21AA\uFE0F [${r.name}] "${f}"`,"agent-respond")}t.userInitiated||r.incrementAutoRespond();let y=Rt(t.message,80);return{text:[`Message sent to session ${r.name} [${r.id}].`,a?" (redirected active turn first)":t.interrupt?" (no active turn to interrupt)":"",` Message: "${y}"`,m,"Use agent_output to see the response."].filter(Boolean).join(`
33
+ `)}}catch(a){return{text:`Error sending message to session ${r.name} [${r.id}]: ${Io(a)}`,isError:!0}}}function mm(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function da(e){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent session. The session must be running. Sessions are multi-turn by default, so this works with any session unless it was launched with multi_turn_disabled: true.",parameters:g.Object({session:g.String({description:"Session name or ID to respond to"}),message:g.String({description:"The message to send to the session"}),interrupt:g.Optional(g.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:g.Optional(g.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:g.Optional(g.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode (after ExitPlanMode), or (2) escalate a default mode session to skip all remaining permission prompts. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!mm(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let n=await ft(I,r);return{isError:n.isError??!1,content:[{type:"text",text:n.text}]}}}}function la(e){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:g.Object({}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=I.getMetrics(),o=I.list("running").length;return{content:[{type:"text",text:Qr(n,o)}]}}}}import{existsSync as un}from"fs";import{resolve as bm,dirname as km}from"path";import{execFileSync as $}from"child_process";import{existsSync as fm,mkdirSync as pa,rmSync as fa,statfsSync as gm}from"fs";import{tmpdir as hm}from"os";import{join as ym}from"path";var en,tn;function Im(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function wm(e){try{return $("git",["rev-parse","--show-toplevel"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function ga(e){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(e){let t=wm(e);if(t)return ym(t,".worktrees")}return hm()}function Sm(){if(en!==void 0)return en;try{return $("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),en=!0,!0}catch{return en=!1,!1}}function et(){if(tn!==void 0)return tn;try{return $("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),tn=!0,!0}catch{return tn=!1,!1}}function ha(e){if(!Sm())return!1;try{return $("git",["rev-parse","--git-dir"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function ya(){try{let e=ga(),t=gm(e),r=t.bavail*t.bsize,n=100*1024*1024;return r>=n}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function xm(e,t){try{return $("git",["-C",e,"rev-parse","--verify",t],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function So(e,t){let r=Im(t),n=ga(e);pa(n,{recursive:!0});let o,s,i=10;for(let d=0;d<i;d++){let m=d===0?"":`-${Math.random().toString(16).slice(2,6)}`,y=`${n}/openclaw-worktree-${r}${m}`,f=`agent/${r}${m}`;try{pa(y,{recursive:!1}),o=y,s=f;break}catch(c){if(c&&typeof c=="object"&&"code"in c&&c.code==="EEXIST")continue;throw c}}if(!o||!s)throw new Error(`Failed to create unique worktree directory after ${i} attempts`);let a=xm(e,s);try{a?$("git",["-C",e,"worktree","add",o,s],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):$("git",["-C",e,"worktree","add","-b",s,o],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(d){try{fa(o,{recursive:!0,force:!0})}catch{}throw d}return o}function br(e,t){try{return $("git",["-C",e,"worktree","remove","--force",t],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){console.warn(`[worktree] git worktree remove failed for ${t}: ${r instanceof Error?r.message:String(r)}`);try{return fa(t,{recursive:!0,force:!0}),console.info(`[worktree] Fallback rmSync succeeded for ${t}`),!0}catch(n){return console.error(`[worktree] Both git worktree remove and rmSync failed for ${t}: ${n instanceof Error?n.message:String(n)}`),!1}}}function rn(e){try{$("git",["-C",e,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}function Ke(e){let t=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(t)return t;try{let n=$("git",["-C",e,"rev-parse","--abbrev-ref","origin/HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().replace(/^origin\//,"");if(n)return n}catch{}try{return $("git",["-C",e,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return $("git",["-C",e,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{}return"main"}function se(e){try{let r=$("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r==="HEAD"){console.warn(`[worktree] Worktree ${e} is in detached HEAD state \u2014 cannot determine branch name`);return}return r||void 0}catch{return}}function nn(e,t,r){try{let n=$("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(n.trim(),10)>0}catch{return!1}}function Ct(e,t,r){try{let n=$("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(n.trim(),10),i=$("git",["-C",e,"diff","--shortstat",`${r}...${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,m=0,y=i.match(/(\d+)\s+files?\s+changed/);y&&(a=parseInt(y[1],10));let f=i.match(/(\d+)\s+insertions?\(/);f&&(d=parseInt(f[1],10));let c=i.match(/(\d+)\s+deletions?\(/);c&&(m=parseInt(c[1],10));let S=$("git",["-C",e,"log",`${r}..${t}`,"--format=%h|%s|%an","-n","5"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
34
+ `).filter(Boolean).map(k=>{let[x,T,b]=k.split("|");return{hash:x||"",message:T||"",author:b||""}});return{commits:o,filesChanged:a,insertions:d,deletions:m,commitMessages:S}}catch(n){console.warn(`[worktree] Failed to get diff summary: ${n instanceof Error?n.message:String(n)}`);return}}function gt(e,t,r="origin"){try{return $("git",["-C",e,"push",r,t],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to push branch ${t}: ${n instanceof Error?n.message:String(n)}`),!1}}function ma(e){try{return $("git",["-C",e,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
35
+ `).some(r=>r.length>0&&!r.startsWith("??")&&!r.startsWith("!!"))}catch{return!1}}function on(e,t,r,n="merge",o){let s=!1,i,a=d=>{if(s)try{$("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(n==="squash"){if($("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ma(e)){let m;try{m=$("git",["-C",e,"stash","push","-m",`pre-merge stash before ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(y){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${y instanceof Error?y.message:String(y)}. Commit or stash changes manually, then retry.`}}if(!m.includes("No local changes to save")){s=!0;try{i=$("git",["-C",e,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}$("git",["-C",e,"merge","--squash",t],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),$("git",["-C",e,"commit","-m",`Squash merge ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let d=!1;if(s)try{$("git",["-C",e,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{d=!0}return{success:!0,stashed:s||void 0,stashRef:i,stashPopConflict:d||void 0}}else{let d=o&&fm(o),m=d?o:e;if(d||$("git",["-C",e,"checkout",t],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ma(e)){let f;try{f=$("git",["-C",e,"stash","push","-m",`pre-merge stash before ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(c){try{$("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${c instanceof Error?c.message:String(c)}. Commit or stash changes manually, then retry.`}}if(!f.includes("No local changes to save")){s=!0;try{i=$("git",["-C",e,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{$("git",["-C",m,"rebase",r],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{$("git",["-C",m,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{$("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(e),{success:!1,rebaseConflict:!0,stashed:s||void 0,stashRef:i,error:[`Rebase of ${t} onto ${r} hit conflicts.`,"To resolve manually:",` cd ${m}`,` git rebase ${r}`," # resolve conflicts in each file, then:"," git add <file>"," git rebase --continue"," # repeat until rebase finishes, then re-run agent_merge."].join(`
36
+ `)}}$("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),$("git",["-C",e,"merge","--ff-only",t],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let y=!1;if(s)try{$("git",["-C",e,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{y=!0}return{success:!0,fastForward:!0,stashed:s||void 0,stashRef:i,stashPopConflict:y||void 0}}}catch(d){try{$("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(e),{success:!1,error:d instanceof Error?d.message:String(d),stashed:s||void 0,stashRef:i}}}function sn(e,t,r,n,o){if(!et())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s=["pr","create","--base",r,"--head",t];return n&&o?s.push("--title",n,"--body",o):s.push("--fill-verbose"),{success:!0,prUrl:$("gh",s,{cwd:e,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}function Mt(e,t){try{return $("git",["-C",e,"branch","-D",t],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){return console.warn(`[worktree] Failed to delete branch ${t}: ${r instanceof Error?r.message:String(r)}`),!1}}function er(e,t){if(!et())return{exists:!1,state:"none"};try{let n=$("gh",["pr","list","--head",t,"--state","all","--json","url,number,title,state","--jq",".[0]"],{cwd:e,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!n)return{exists:!1,state:"none"};let o=JSON.parse(n),s,i=o.state.toLowerCase();return i==="open"?s="open":i==="merged"?s="merged":i==="closed"?s="closed":s="none",{exists:!0,state:s,url:o.url,number:o.number,title:o.title}}catch(r){return console.warn(`[worktree] Failed to sync PR status for ${t}: ${r instanceof Error?r.message:String(r)}`),{exists:!1,state:"none"}}}function an(e,t,r){if(!et())return!1;try{return $("gh",["pr","comment",String(t),"--body",r],{cwd:e,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to comment on PR #${t}: ${n instanceof Error?n.message:String(n)}`),!1}}function Pm(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function cn(e){return{name:"agent_merge",description:"Merge a worktree branch back to the base branch. Resolves session (active or persisted), gets worktree path, and performs the merge. On conflict, spawns a Claude Code conflict-resolver session.",parameters:g.Object({session:g.String({description:"Session name or ID to merge"}),base_branch:g.Optional(g.String({description:"Base branch to merge into (default: main)"})),strategy:g.Optional(g.Union([g.Literal("merge"),g.Literal("squash")],{description:"Merge strategy: 'merge' (default, fast-forward if possible; merge commit if branches have diverged) or 'squash' (squashes all commits into one)"})),push:g.Optional(g.Boolean({description:"Push the base branch after successful merge (default: false)"})),delete_branch:g.Optional(g.Boolean({description:"Delete the worktree branch after successful merge (default: true)"}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Pm(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=I.resolve(r.session),o=I.getPersistedSession(r.session);if(!n&&!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let s=n?.worktreePath??o?.worktreePath,i=n?.originalWorkdir??o?.workdir;if(!s||!i)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}]};let d=se(s)??o?.worktreeBranch;if(!d)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree at ${s}. The worktree may have been removed and no persisted branch name is available.`}]};un(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${i})`);let m=i;if(!un(i)){let k=bm(km(s),"..");if(un(k))console.warn(`[agent_merge] originalWorkdir "${i}" does not exist \u2014 falling back to derived repo root "${k}" (worktree path: ${s}).`),m=k;else return{content:[{type:"text",text:`Error: originalWorkdir "${i}" does not exist and could not derive repo root from worktree path "${s}".`}]}}let y=r.base_branch??Ke(m),f=r.strategy??"merge",c=r.push===!0,w=r.delete_branch!==!1;if(o?.worktreeMerged)return{content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" is already merged.`}]};let S={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]};return await I.enqueueMerge(m,async()=>{let k=I.getPersistedSession(r.session);if(k?.worktreeMerged){S={content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" was already merged while waiting in queue.`}]};return}let x=on(m,d,y,f,s);if(x.success){if(c&&!gt(m,y)){S={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${y} locally, but failed to push ${y}`}]};return}w&&Mt(m,d),un(s)&&(br(m,s),rn(m)),k&&I.updatePersistedSession(k.harnessSessionId,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0});let P=`\u2705 ${x.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${y}.${c?" Pushed.":""}${w?" Branch and worktree cleaned up.":""}`;x.stashPopConflict?P+=`
37
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${x.stashRef??"stash@{0}"}\` in ${m} to review stashed changes.`:x.stashed&&(P+=`
38
+ (Pre-existing changes on ${y} were auto-stashed and restored.)`),S={content:[{type:"text",text:P}]}}else if(x.rebaseConflict)S={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
39
+
40
+ ${x.error}`}]};else if(x.conflictFiles&&x.conflictFiles.length>0){let T=["Resolve merge conflicts in the following files and commit the resolution:","",...x.conflictFiles.map(b=>`- ${b}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${d}"`].join(`
41
+ `);try{let b=I.spawn({prompt:T,workdir:m,name:`${r.session}-conflict-resolver`,harness:"claude-code",permissionMode:"bypassPermissions",multiTurn:!0});S={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${x.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${b.name}`}]}}catch(b){S={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${b instanceof Error?b.message:String(b)}`}]}}}else S={content:[{type:"text",text:x.dirtyError?`\u274C Merge blocked: ${x.error}`:`\u274C Merge failed: ${x.error??"unknown error"}`}]}}),S}}}import{existsSync as Tm}from"fs";function Am(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function kr(e){return{name:"agent_pr",description:"Create or update a GitHub PR for a worktree branch. Handles full PR lifecycle: creates new PRs, updates existing open PRs with comments, and handles merged/closed PRs. Pushes the branch, syncs PR state, and persists metadata.",parameters:g.Object({session:g.String({description:"Session name or ID to create/update PR for"}),title:g.Optional(g.String({description:"PR title (default: auto-generated from session name)"})),body:g.Optional(g.String({description:"PR body (default: auto-generated from commit summary)"})),base_branch:g.Optional(g.String({description:"Base branch for the PR (default: detected from repo)"})),force_new:g.Optional(g.Boolean({description:"Force creation of a new PR even if one exists (default: false)"}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Am(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}]};if(!et())return{content:[{type:"text",text:"Error: GitHub CLI (gh) is not available. Install it and authenticate to create PRs."}]};let n=I.resolve(r.session),o=I.getPersistedSession(r.session);if(!n&&!o)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let s=n?.worktreePath??o?.worktreePath,i=n?.originalWorkdir??o?.workdir,a=n?.name??o?.name??r.session;if(!s||!i)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}]};let d=se(s),m=`agent/${a}`,y=d??o?.worktreeBranch??m;if(!y)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree ${s}. The worktree may have been removed and no persisted branch name is available.`}]};Tm(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${y}" via originalWorkdir (${i})`);let f=r.base_branch??Ke(i);if(!gt(i,y))return{content:[{type:"text",text:`\u274C Failed to push ${y} \u2014 cannot create/update PR`}]};let c=er(i,y);if(r.force_new&&c.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${y} (${c.state}).
42
+
43
+ Existing PR: ${c.url}
44
+
45
+ To create a new PR, you must first close/merge the existing PR manually or use a different branch.`}]};if(c.exists&&c.state==="open"){let w=Ct(i,y,f);if(w&&w.commits>0){let S=w.commitMessages.slice(0,5).map(b=>`\u2022 ${b.hash} ${b.message} (${b.author})`).join(`
46
+ `),k=w.commits>5?`
47
+ ...and ${w.commits-5} more commits`:"",x=["\u{1F504} **New commits pushed**","",`${w.commits} new commits (+${w.insertions} / -${w.deletions})`,"","### Latest commits:",S+k,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
48
+ `);return an(i,c.number,x)?(o&&I.updatePersistedSession(o.harnessSessionId,{worktreePrUrl:c.url,worktreePrNumber:c.number}),{content:[{type:"text",text:`\u2705 PR updated with new commits: ${c.url}
49
+
50
+ \u{1F4DD} Added comment detailing ${w.commits} new commits (+${w.insertions} / -${w.deletions})`}]}):{content:[{type:"text",text:`\u26A0\uFE0F Pushed to ${c.url} but failed to add comment.
51
+
52
+ ${w.commits} new commits (+${w.insertions} / -${w.deletions})`}]}}else return o&&I.updatePersistedSession(o.harnessSessionId,{worktreePrUrl:c.url,worktreePrNumber:c.number}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${c.url}
53
+
54
+ No new commits to push.`}]}}else{if(c.exists&&c.state==="merged")return o&&I.updatePersistedSession(o.harnessSessionId,{worktreePrUrl:c.url,worktreePrNumber:c.number}),{content:[{type:"text",text:`\u2705 PR was already merged: ${c.url}
55
+
56
+ The worktree branch ${y} can be cleaned up with agent_merge(delete_branch=true).`}]};if(c.exists&&c.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${c.url}
57
+
58
+ What would you like to do?
59
+
60
+ 1. Reopen the closed PR manually on GitHub, then call agent_pr() again to update it
61
+ 2. Close and delete the branch with agent_merge(delete_branch=true), then start a new session/worktree
62
+ 3. Manually delete the closed PR on GitHub, then call agent_pr(force_new=true) to create a fresh PR
63
+
64
+ (This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}]};{let w=r.title??`[openclaw-code-agent] ${a}`,S=r.body;if(!S){let x=Ct(i,y,f);if(x){let T=x.commitMessages.slice(0,5).map(E=>`\u2022 ${E.hash} ${E.message} (${E.author})`).join(`
65
+ `),b=x.commits>5?`
66
+ ...and ${x.commits-5} more`:"";S=[`Automated changes from OpenClaw Code Agent session: ${a}`,"","## Summary",`${x.commits} commits, ${x.filesChanged} files changed (+${x.insertions} / -${x.deletions})`,"","## Commits",T+b,"","---","\u{1F916} Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
67
+ `)}else S=`Automated changes from OpenClaw Code Agent session: ${a}`}let k=sn(i,y,f,w,S);if(k.success&&k.prUrl){let x=er(i,y);return o&&I.updatePersistedSession(o.harnessSessionId,{worktreePrUrl:k.prUrl,worktreePrNumber:x.number,pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0}),{content:[{type:"text",text:`\u{1F500} PR created: ${k.prUrl}`}]}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${k.error??"unknown error"}`}]}}}}}}import{execFileSync as tr}from"child_process";import{existsSync as $m}from"fs";function Rm(e){return!(!e||typeof e!="object")}function Cm(e){try{return tr("git",["-C",e,"branch","--list","agent/*"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
68
+ `).map(r=>r.replace(/^\*?\s+/,"").trim()).filter(Boolean)}catch{return[]}}function Mm(e,t,r){try{let n=tr("git",["-C",e,"merge-base",t,r],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=tr("git",["-C",e,"rev-parse",t],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return n===o}catch{return!1}}function Om(e,t,r){try{let n=tr("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(n.trim(),10)||0}catch{return 0}}function Em(e,t){if(I){for(let r of I.listPersistedSessions())if(r.worktreeBranch===t&&r.worktreePrUrl&&r.worktreeMerged!==!0)return{number:r.worktreePrNumber??0,url:r.worktreePrUrl}}if(et())try{let r=tr("gh",["pr","list","--head",t,"--state","open","--json","number,url"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"],cwd:e}),n=JSON.parse(r.trim());if(Array.isArray(n)&&n.length>0)return{number:n[0].number,url:n[0].url}}catch{}return null}function Ia(e){return{name:"agent_worktree_cleanup",description:"Clean up agent/* branches. Three categories are always protected from deletion: (1) branches with active running/starting sessions, (2) branches with unmerged commits ahead of the base branch, (3) branches with open GitHub PRs. Only fully merged branches with no active session or open PR are eligible for deletion. Use skip_session_check (alias: force) to bypass the active-session check only \u2014 useful when a session crashed and left a stale branch. Use session to dismiss a pending worktree decision without merging.",parameters:g.Object({workdir:g.Optional(g.String({description:"Working directory (defaults to cwd)"})),base_branch:g.Optional(g.String({description:"Base branch to check merge status against (default: main)"})),skip_session_check:g.Optional(g.Boolean({description:"Skip the check for running sessions (use only when a session crashed and left a stale branch). Does NOT override unmerged commit or open PR protection. (default: false)"})),force:g.Optional(g.Boolean({description:"Deprecated alias for skip_session_check. See skip_session_check for details."})),dry_run:g.Optional(g.Boolean({description:"Show what would be deleted without actually deleting (default: false)"})),session:g.Optional(g.String({description:"Session name or ID to dismiss/clear pending worktree decision for (optional)"}))}),async execute(t,r){if(!Rm(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, skip_session_check?, force?, dry_run?, session? }."}]};let n=r.session;if(n&&I){let b=I.getPersistedSession(n);b&&I.updatePersistedSession(b.harnessSessionId,{pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0})}let o=r.workdir||process.cwd(),s=r.base_branch??Ke(o),i=r.skip_session_check===!0||r.force===!0,a=r.dry_run===!0;if(!$m(o))return{content:[{type:"text",text:`Error: Working directory does not exist: ${o}`}]};try{tr("git",["-C",o,"rev-parse","--git-dir"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{return{content:[{type:"text",text:`Error: ${o} is not a git repository`}]}}let d=Cm(o);if(d.length===0)return{content:[{type:"text",text:"No agent/* branches found."}]};let m=new Set,y=new Map;if(I){for(let b of I.list())if(b.status==="starting"||b.status==="running"){let E=b.worktreeBranch??(b.worktreePath?se(b.worktreePath):void 0);E&&(m.add(E),y.set(E,`${b.name} is ${b.status}`))}}let f=[],c=[],w=[],S=[];for(let b of d){if(!i&&m.has(b)){let E=y.get(b)??"unknown";w.push(`${b} (session: ${E})`);continue}if(Mm(o,b,s))f.push(b);else{let E=Em(o,b);if(E)S.push({branch:b,prNumber:E.number,prUrl:E.url});else{let P=Om(o,b,s);c.push({branch:b,commitsAhead:P})}}}let k=(b,E)=>{let P=["agent/* branch status:"],A=a?"WOULD DELETE":"DELETED",de=(a?f:b).join(", ")||"(none)",ke=E.length>0?`; ${E.length} failed: ${E.join(", ")}`:"";P.push(` ${A} (${a?f.length:b.length}): ${de}${ke}`);let ht=c.length>0?c.map(({branch:tt,commitsAhead:We})=>We>0?`${tt} [${We} commit${We!==1?"s":""} ahead]`:tt).join(", "):"(none)";P.push(` KEPT \u2013 unmerged (${c.length}): ${ht}`);let Et=w.length>0?w.join(", "):"(none)";P.push(` KEPT \u2013 active session (${w.length}): ${Et}`);let Tn=S.length>0?S.map(({branch:tt,prNumber:We,prUrl:eu})=>We>0?`${tt} [PR #${We}]`:`${tt} [open PR]`).join(", "):"(none)";return P.push(` KEPT \u2013 open PR (${S.length}): ${Tn}`),P.join(`
69
+ `)};if(a)return{content:[{type:"text",text:k([],[])}]};let x=[],T=[];for(let b of f)Mt(o,b)?x.push(b):T.push(b);return{content:[{type:"text",text:k(x,T)}]}}}}import{existsSync as vm}from"fs";function _m(e){return!0}function wa(e){return{name:"agent_worktree_status",description:"Show worktree status for coding agent sessions. If session parameter is provided, shows status for that session only. Otherwise, shows all sessions with worktrees. Displays branch name, repository, strategy, commits ahead, merge status, and PR URLs.",parameters:g.Object({session:g.Optional(g.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(t,r){if(!I)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!_m(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let n=r.session,o=[],s=I.list("all").filter(c=>c.worktreePath),i=I.listPersistedSessions().filter(c=>c.worktreePath),a=new Map;for(let c of i){if(!c.worktreePath)continue;let w=c.sessionId??c.harnessSessionId;a.set(w,{id:w,name:c.name,worktreePath:c.worktreePath,worktreeBranch:c.worktreeBranch,worktreeStrategy:c.worktreeStrategy,workdir:c.workdir,worktreeMerged:c.worktreeMerged,worktreeMergedAt:c.worktreeMergedAt,worktreePrUrl:c.worktreePrUrl})}for(let c of s)c.worktreePath&&a.set(c.id,{id:c.id,name:c.name,worktreePath:c.worktreePath,worktreeBranch:se(c.worktreePath),worktreeStrategy:c.worktreeStrategy,workdir:c.originalWorkdir??c.workdir,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0});let d=Array.from(a.values());if(n&&(d=d.filter(c=>c.id===n||c.name===n),d.length===0))return{content:[{type:"text",text:`Error: Session "${n}" not found or has no worktree.`}]};if(d.length===0)return{content:[{type:"text",text:"No sessions with worktrees found."}]};let y=I.listPersistedSessions().filter(c=>c.pendingWorktreeDecisionSince&&!c.worktreeMerged&&!c.worktreePrUrl),f=n?y.filter(c=>c.harnessSessionId===n||c.name===n||c.sessionId===n):y;if(f.length>0){o.push(`\u23F3 Pending decisions (${f.length}):`),o.push("");for(let c of f){let w=new Date(c.pendingWorktreeDecisionSince),S=Date.now()-w.getTime(),k=Math.floor(S/(3600*1e3)),x=Math.floor(k/24),T=k%24,b=Math.floor(S%(3600*1e3)/6e4),E=x>0?`${x}d ${T}h`:k>0?`${k}h ${b}m`:`${b}m`,P=Ke(c.workdir);o.push(`\u2022 ${c.name.padEnd(14)} ${(c.worktreeBranch??"?").padEnd(30)} \u2192 ${P.padEnd(10)} pending ${E}`)}if(o.push(""),f.length===1){let c=f[0];o.push(`Use agent_merge(session="${c.name}") or agent_pr(session="${c.name}") to resolve.`)}else o.push('Use agent_merge(session="<name>") or agent_pr(session="<name>") to resolve.');o.push(""),o.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),o.push("All worktrees:"),o.push("")}for(let c of d){let w=c.worktreeBranch??se(c.worktreePath);if(!w){o.push(`Session: ${c.name} [${c.id}]`),o.push(` Worktree: ${c.worktreePath}`),o.push(" Status: Cannot determine branch (detached HEAD or worktree removed)"),o.push("");continue}let S=Ke(c.workdir),k=vm(c.workdir);if(o.push(`Session: ${c.name} [${c.id}]`),o.push(` Branch: ${w} \u2192 ${S}`),o.push(` Repo: ${c.workdir}`),c.worktreeStrategy&&o.push(` Strategy: ${c.worktreeStrategy}`),k)try{if(nn(c.workdir,w,S)){let T=Ct(c.workdir,w,S);T?o.push(` Commits: ${T.commits} ahead of ${S} (+${T.insertions} / -${T.deletions})`):o.push(` Commits: ahead of ${S}`)}else o.push(` Commits: even with ${S}`)}catch{o.push(" Commits: (unable to check)")}else o.push(" Commits: (repo no longer exists)");if(c.worktreeMerged){let x=c.worktreeMergedAt?new Date(c.worktreeMergedAt).toLocaleString():"unknown";o.push(` Merged: Yes (${x})`)}else c.worktreePrUrl?o.push(` PR: ${c.worktreePrUrl}`):o.push(" Merged: No");o.push("")}return{content:[{type:"text",text:o.join(`
70
+ `).trim()}]}}}}var Fm="code-agent";function Nm(e){let t=e.indexOf(":");if(t===-1)return null;let r=e.slice(0,t).trim(),n=e.slice(t+1).trim();return!r||!n?null:{action:r,sessionId:n}}function dn(e){if(e&&typeof e=="object"&&"content"in e&&Array.isArray(e.content)){let t=e.content[0];return typeof t?.text=="string"?t.text:"(done)"}return"(done)"}function Sa(){return{channel:"telegram",namespace:Fm,handler:async e=>{if(!e.auth.isAuthorizedSender)return await e.respond.reply({text:"\u26D4 Unauthorized."}),{handled:!0};let t=Nm(e.callback.payload);if(!t)return await e.respond.reply({text:`\u26A0\uFE0F Unrecognized callback payload: "${e.callback.payload}". Expected "action:session-id".`}),{handled:!0};let{action:r,sessionId:n}=t;if(!I)return await e.respond.reply({text:"\u26A0\uFE0F Code agent service not running."}),{handled:!0};switch(await e.respond.clearButtons(),r){case"merge":case"merge-locally":{{let s=I.resolve(n),i=I.getPersistedSession(n),a=s?.harnessSessionId??i?.harnessSessionId;a&&I.updatePersistedSession(a,{pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0})}let o=await cn().execute("callback",{session:n});await e.respond.reply({text:dn(o)});break}case"pr":case"open-pr":{let o=await kr().execute("callback",{session:n});await e.respond.reply({text:dn(o)});break}case"new-pr":{let o=await kr().execute("callback",{session:n,force_new:!0});await e.respond.reply({text:dn(o)});break}case"approve":{let o=await ft(I,{session:n,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});await e.respond.reply({text:o.isError?`\u26A0\uFE0F ${o.text}`:`\u{1F44D} ${o.text}`});break}case"reject":{let o=await ft(I,{session:n,message:"Plan rejected. Please stop.",userInitiated:!0});await e.respond.reply({text:o.isError?`\u26A0\uFE0F ${o.text}`:`\u274C ${o.text}`});break}case"revise":{let o=I.resolve(n),s=I.getPersistedSession(n),i=o?.name??s?.name??n;await e.respond.reply({text:`\u270F\uFE0F Type your revision feedback for [${i}] and I'll forward it to the agent.`});break}case"reply":{let o=I.resolve(n),s=I.getPersistedSession(n),i=o?.name??s?.name??n;await e.respond.reply({text:`\u{1F4AC} Type your reply for [${i}] and I'll forward it to the agent.`});break}case"retry":{let o=await ft(I,{session:n,message:"Retry.",userInitiated:!0});await e.respond.reply({text:o.isError?`\u26A0\uFE0F ${o.text}`:`\u{1F504} ${o.text}`});break}case"view-output":{let o=await Zr().execute("callback",{session:n,lines:50});await e.respond.reply({text:dn(o)});break}case"question-answer":{let o=n.lastIndexOf(":");if(o===-1){await e.respond.reply({text:`\u26A0\uFE0F Malformed question-answer payload: "${n}"`});break}let s=n.slice(0,o),i=parseInt(n.slice(o+1),10);if(isNaN(i)){await e.respond.reply({text:"\u26A0\uFE0F Invalid option index in question-answer payload."});break}I.resolveAskUserQuestion(s,i),await e.respond.reply({text:"\u2705 Answer submitted."});break}default:{await e.respond.reply({text:`\u26A0\uFE0F Unknown callback action: "${r}". Supported: merge, pr, open-pr, new-pr, approve, reject, revise, reply, retry, view-output, question-answer.`});break}}return{handled:!0}}}}function Um(e){return e instanceof Error?e.message:String(e)}function xa(e){e.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:"Usage: /agent [--name <name>] <prompt>"};let n,o=r.match(/^--name\s+(\S+)\s+/);o&&(n=o[1],r=r.slice(o[0].length).trim());let s=r;if(!s)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=pt(),a=mt(i);if(!a)return{text:`Error: No default model configured for harness "${i}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${i}.defaultModel or pass model explicitly via agent_launch.`};let d=I.spawn({prompt:s,name:n,workdir:N.defaultWorkdir||process.cwd(),model:a,reasoningEffort:Yt(i),codexApprovalPolicy:i==="codex"?$t(i)??N.codexApprovalPolicy:void 0,originChannel:Jt(t),originThreadId:Xt(t),harness:i}),m=s.length>80?s.slice(0,80)+"...":s;return{text:["Session launched.",` Name: ${d.name}`,` ID: ${d.id}`,` Prompt: "${m}"`,` Status: ${d.status}`].join(`
71
+ `)}}catch(i){let a=Um(i),d=a.includes("Max sessions")?"":`
72
+
73
+ Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${d}`}}}})}function ba(e){e.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").split(/\s+/).includes("--full");return{text:Jr(I,"all",void 0,{full:r})}}})}function ka(e){e.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=t.args?.trim();return r?{text:Xr(I,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}function Dm(e){return e instanceof Error?e.message:String(e)}function Pa(e){e.registerCommand({name:"agent_resume",description:"Resume a previous coding agent session. Usage: /agent_resume <id-or-name> [prompt] or /agent_resume --list to see resumable sessions.",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:`Usage: /agent_resume <id-or-name> [prompt]
31
74
  /agent_resume --list \u2014 list resumable sessions
32
- /agent_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let ee=g.listPersistedSessions();return ee.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
75
+ /agent_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(r==="--list"){let k=I.listPersistedSessions();return k.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
33
76
 
34
- ${ee.map(_=>{let Be=_.prompt.length>60?_.prompt.slice(0,60)+"...":_.prompt,be=_.completedAt?`completed ${Le(Date.now()-_.completedAt)} ago`:_.status;return[` ${_.name} \u2014 ${be}`,` Session ID: ${_.harnessSessionId}`,` \u{1F4C1} ${_.workdir}`,` \u{1F4DD} "${Be}"`].join(`
77
+ ${k.map(T=>{let b=T.prompt.length>60?T.prompt.slice(0,60)+"...":T.prompt,E=T.completedAt?`completed ${qe(Date.now()-T.completedAt)} ago`:T.status;return[` ${T.name} \u2014 ${E}`,` Session ID: ${T.harnessSessionId}`,` \u{1F4C1} ${T.workdir}`,` \u{1F4DD} "${b}"`].join(`
35
78
  `)}).join(`
36
79
 
37
- `)}`}}let r=!1;n.startsWith("--fork ")&&(r=!0,n=n.slice(7).trim());let o=n.indexOf(" "),i,s;o===-1?(i=n,s="Continue where you left off."):(i=n.slice(0,o),s=n.slice(o+1).trim()||"Continue where you left off.");let c=g.resolveHarnessSessionId(i);if(!c)return{text:`Error: Could not find a session ID for "${i}".
38
- Use /agent_resume --list to see available sessions.`};let p=g.resolve(i),f=g.getPersistedSession(i),{resumeSessionId:T,clearedPersistedCodexResume:U}=Lt({requestedResumeSessionId:c,activeSession:p?{harnessSessionId:p.harnessSessionId}:void 0,persistedSession:f?{harness:f.harness}:void 0}),te=f?.workdir??process.cwd(),ge=f?.harness??nt(),ae=f?.model??rt(ge);try{if(!ae)return{text:`Error: No default model configured for harness "${ge}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${ge}.defaultModel or pass model explicitly when launching a fresh session.`};let ee=g.spawn({prompt:s,workdir:te,name:f?.name,model:ae,codexApprovalPolicy:p?.codexApprovalPolicy??f?.codexApprovalPolicy,resumeSessionId:T,forkSession:T?r:!1,originChannel:Ut(t),originThreadId:_t(t)??f?.originThreadId,originAgentId:t?.agentId??f?.originAgentId,originSessionKey:t?.sessionKey??f?.originSessionKey,harness:ge}),z=s.length>80?s.slice(0,80)+"...":s;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${ee.name}`,` ID: ${ee.id}`,T?` Resume from: ${c}`:" Resume from: fresh thread",` Dir: ${te}`,` Prompt: "${z}"`,U?" Note: cleared persisted Codex thread state after restart to avoid org-mismatch resume failures.":""].join(`
39
- `)}}catch(ee){let z=vp(ee),_=z.includes("Max sessions")?"":`
40
-
41
- Use /agent_sessions to see active sessions or /agent_resume --list to see resumable sessions.`;return{text:`Error resuming session: ${z}${_}`}}}})}function Ki(e){e.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /agent_respond <id-or-name> <message>
42
- /agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!0,o=o.slice(12).trim());let i=o.indexOf(" ");if(i===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let s=o.slice(0,i),c=o.slice(i+1).trim();return c?{text:(await _n(g,{session:s,message:c,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}function Di(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=g.getMetrics(),n=g.list("running").length;return{text:$n(t,n)}}})}var Np=50;function ji(e){e.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=n.split(/\s+/),o="",i=!1,s=Np;for(let p=0;p<r.length;p++)if(r[p]==="--full")i=!0;else if(r[p]==="--lines"&&p+1<r.length){let f=parseInt(r[p+1],10);!isNaN(f)&&f>0&&(s=f),p++}else o||(o=r[p]);return o?{text:vn(g,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}import{execFile as pa}from"child_process";import{existsSync as Jl}from"fs";import{fileURLToPath as la}from"url";import{dirname as Xl,join as zr}from"path";import{EventEmitter as bl}from"events";import Vi from"crypto";var Gi="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Up=128,It,Kt,_p=e=>{!It||It.length<e?(It=Buffer.allocUnsafe(e*Up),Vi.randomFillSync(It),Kt=0):Kt+e>It.length&&(Vi.randomFillSync(It),Kt=0),Kt+=e};var Hi=(e=21)=>{_p(e|=0);let t="";for(let n=Kt-e;n<Kt;n++)t+=Gi[It[n]&63];return t};import{query as Lp}from"@anthropic-ai/claude-agent-sdk";var Ln=class{name="claude-code";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=["AskUserQuestion"];planApprovalToolNames=["ExitPlanMode","set_permission_mode"];launch(t){let n={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers};t.resumeSessionId&&(n.resume=t.resumeSessionId,n.forkSession=t.forkSession??!1);let r=Lp({prompt:t.prompt,options:n});return{messages:this.adaptMessages(r),async setPermissionMode(o){typeof r.setPermissionMode=="function"&&await r.setPermissionMode(o)},async streamInput(o){typeof r.streamInput=="function"&&await r.streamInput(o)},async interrupt(){typeof r.interrupt=="function"&&await r.interrupt()}}}buildUserMessage(t,n){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n}}async*adaptMessages(t){for await(let n of t){let r=n;if(r.type==="system"&&r.subtype==="init")yield{type:"init",session_id:r.session_id??""};else if(r.type==="system"&&r.subtype==="status"&&r.permissionMode)yield{type:"permission_mode_change",mode:r.permissionMode};else if(r.type==="assistant")for(let o of r.message?.content??[])o.type==="text"?yield{type:"text",text:o.text}:o.type==="tool_use"&&(yield{type:"tool_use",name:o.name,input:o.input});else r.type==="result"&&(yield{type:"result",data:{success:r.subtype==="success",duration_ms:r.duration_ms??0,total_cost_usd:r.total_cost_usd??0,num_turns:r.num_turns??0,result:r.result,session_id:r.session_id??""}})}}};import{parse as al,resolve as ul}from"path";import{Codex as Zi}from"@openai/codex-sdk";import{randomUUID as Kp}from"node:crypto";import{lstat as Dp,mkdir as Hr,readFile as qi,readlink as jp,realpath as Gp,rename as Vp,rm as Kn,symlink as Hp,writeFile as zi}from"node:fs/promises";import{homedir as Bp,tmpdir as Yi}from"node:os";import{dirname as Wp,join as ve,resolve as qp}from"node:path";var zp=50,Yp=3e4,Jp=ve(Yi(),"openclaw-codex-auth.lock");function Xp(e,t){let n={};for(let[r,o]of Object.entries(e))typeof o=="string"&&(n[r]=o);return n.HOME=t,n}function Qp(e){return new Promise(t=>setTimeout(t,e))}async function Ji(e){try{return await Dp(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Bi(e,t){if(await Ji(t)){if(await jp(t)===e)return;await Kn(t,{recursive:!0,force:!0})}await Hp(e,t)}function Zp(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return null;let n=Number(t);if(Number.isFinite(n))return n;let r=Date.parse(t);if(Number.isFinite(r))return r}return null}async function Wi(e){let t;try{t=await qi(e,"utf8")}catch(n){return n.code==="ENOENT",null}try{let n=JSON.parse(t);if(!n||typeof n!="object")return null;let r=Zp(n.last_refresh);return r===null?null:{lastRefresh:r,raw:t}}catch{return null}}async function Xi(e,t){await Hr(Wp(e),{recursive:!0});let n=`${e}.tmp`;await zi(n,t,"utf8"),await Vp(n,e)}async function el(e,t){try{let n=await qi(e,"utf8");await Xi(t,n)}catch(n){if(n.code!=="ENOENT")throw n;await Kn(t,{force:!0})}}async function tl(e,t){let n=await Wi(e);if(!n)return;let r=await Wi(t);r&&n.lastRefresh<=r.lastRefresh||await Xi(t,n.raw)}async function nl(e,t,n){let r=Date.now()+t;for(;;)try{await Hr(e);break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()>=r)throw new Error(`Timed out waiting for Codex auth lock at ${e}`);await Qp(n)}try{await zi(ve(e,"holder.json"),JSON.stringify({pid:process.pid,acquired_at:new Date().toISOString()}),"utf8")}catch{}let o=!1;return async()=>{o||(o=!0,await Kn(e,{recursive:!0,force:!0}))}}async function Qi(e=process.env,t={}){let n=e.HOME??Bp(),r=await Gp(n).catch(()=>qp(n)),o=ve(r,".codex"),i=ve(o,"auth.json"),s=ve(o,"sessions"),c=ve(o,"config.toml"),p=await Ji(c)?c:void 0,f=t.tempRootDir??Yi(),T=ve(f,`openclaw-codex-auth-${Kp()}`),U=ve(T,".codex"),te=ve(U,"auth.json"),ge=t.lockDir??Jp,ae=t.lockTimeoutMs??Yp,ee=t.lockRetryMs??zp;return await Hr(U,{recursive:!0}),await Bi(s,ve(U,"sessions")),p&&await Bi(p,ve(U,"config.toml")),{tempHome:T,tempCodexDir:U,canonicalHome:r,canonicalCodexDir:o,canonicalAuthPath:i,canonicalSessionsPath:s,canonicalConfigPath:p,env:Xp(e,T),async prepareForTurn(){let z=await nl(ge,ae,ee);try{await el(i,te)}catch(Be){throw await z(),Be}let _=!1;return async()=>{if(!_){_=!0;try{await tl(te,i)}finally{await z()}}}},async cleanup(){await Kn(T,{recursive:!0,force:!0})}}}var rl=["proceed","continue","implement","apply","run","merge","deploy","commit"],ol=["shall i proceed","do you want me to","would you like me to","please confirm","should i continue","can i proceed","should i proceed","should i go ahead","want me to continue","approve and i'll","confirm and i'll"],sl=["why this failed was","why did this fail","what failed","what happened","how can i help","is this clear","any questions","anything else","let me know","would you like a summary"];function il(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Dn(e){let t=il(e);if(!t||sl.some(r=>t.includes(r)))return!1;let n=rl.some(r=>t.includes(r));return ol.some(r=>t.includes(r))?n||t.includes("confirm"):t.endsWith("?")?n:!1}var ea=1e4,ta="codex:waiting-for-user",dl=1.1/1e6,cl=.275/1e6,ml=4.4/1e6,pl="OPENCLAW_CODEX_HEARTBEAT_MS",ll="OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS",fl="OPENCLAW_CODEX_AUTH_STRATEGY";function gl(e){if(!e)return 0;let t=e.cached_input_tokens??0,n=Math.max(0,(e.input_tokens??0)-t),r=e.output_tokens??0;return n*dl+t*cl+r*ml}function na(e,t={}){return{success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,session_id:e,...t}}function Il(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return String(e);let t=e;return typeof t.message?.content=="string"?t.message.content:typeof t.text=="string"?t.text:String(e)}function hl(e){return["[SYSTEM: First turn only. Do not implement yet.]","Start by producing a concise implementation plan only.","Then end your response with an explicit question asking whether you should proceed with implementation.","",e].join(`
43
- `)}function ra(e){return e instanceof Error?e.message:String(e)}function yl(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function xl(e){return al(ul(e)).root||"/"}function Sl(e){let n=[xl(e)];return n.push(...yl(process.env[ll])),[...new Set(n)]}function Tl(e,t){let r=(t??e.permissionMode)==="bypassPermissions"?Sl(e.cwd):void 0;return{model:e.model,modelReasoningEffort:e.reasoningEffort,workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:e.codexApprovalPolicy??"on-request",skipGitRepoCheck:!0,additionalDirectories:r}}var jn=class{constructor(t={}){this.deps=t}name="codex";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=[ta];planApprovalToolNames=[];activityHeartbeatMs(){let t=Number.parseInt(process.env[pl]??String(ea),10);return!Number.isFinite(t)||t<=0?ea:t}createCodexClient(t){return this.deps.createCodex?.({env:t})??(t?new Zi({env:t}):new Zi)}launch(t){let r=process.env[fl]==="legacy"?void 0:this.deps.createAuthWorkspace?.(process.env)??Qi(process.env),o=t.permissionMode==="plan",i=t.permissionMode==="plan"?"default":t.permissionMode,s=t.resumeSessionId,c=0,p=0,f=this.activityHeartbeatMs(),T,U,te=!1,ge=!0,ae,ee=[],z=null,_=!1,Be=!1;function be(){z&&(z(),z=null)}function we(G){ee.push(G),be()}function Jr(){_=!0,be()}function fa(G){!G||Be||(Be=!0,we({type:"init",session_id:G}))}async function*ga(){for(;;){for(;ee.length>0;)yield ee.shift();if(_)return;await new Promise(G=>{z=G})}}let an=()=>Tl(t,i),Ia=G=>(T||(T=this.createCodexClient(G)),U||(ge&&t.resumeSessionId?U=T.resumeThread(t.resumeSessionId,an()):s?U=T.resumeThread(s,an()):U=T.startThread(an())),te&&s&&(U=T.resumeThread(s,an()),te=!1),U),Xr=async G=>{let Zn=Date.now();p+=1;let Qr="",er=!1,tr,nr,Zr=!1,ha=ge&&o?hl(G):G,un=st=>{er||(er=!0,we({type:"result",data:na(s??"",{duration_ms:Date.now()-Zn,total_cost_usd:c,num_turns:p,...st,session_id:s??""})}))},rr=async()=>{!nr||Zr||(Zr=!0,await nr())};try{let st=r?await r:void 0;st&&(nr=await st.prepareForTurn());let or=Ia(st?.env),eo=or.id??s??void 0;eo&&(s=eo),ae=new AbortController,t.abortController?.signal.aborted&&ae.abort(t.abortController.signal.reason),tr=setInterval(()=>{we({type:"activity"})},f);let ya=await or.runStreamed(ha,{signal:ae.signal});for await(let ne of ya.events)if(await rr(),ne.type==="thread.started"&&(s=ne.thread_id),fa(s??or.id??void 0),ne.type!=="thread.started"){if(ne.type==="item.completed"){(ne.item.type==="agent_message"||ne.item.type==="reasoning")&&(Qr+=`${ne.item.text}
44
- `,we({type:"text",text:ne.item.text}));continue}if(ne.type==="error"){we({type:"text",text:`[codex:error] ${ne.message}`});continue}if(ne.type==="turn.failed"){un({success:!1,result:ne.error.message,session_id:s??""});continue}if(ne.type==="turn.completed"){c+=gl(ne.usage);let to=Qr.slice(-500);Dn(to)&&we({type:"tool_use",name:ta,input:{text:to}}),un({success:!0,session_id:s??""})}}await rr(),er||un({success:!1,result:"Codex turn ended without terminal event",session_id:s??""})}catch(st){await rr(),un({success:!1,result:ra(st),session_id:s??""})}finally{tr&&clearInterval(tr),ae=void 0,ge=!1}},Qn=()=>{ae?.abort(t.abortController?.signal.reason??"interrupted")};return t.abortController?.signal&&t.abortController.signal.addEventListener("abort",Qn),(async()=>{try{let G=t.prompt;if(typeof G=="string"){await Xr(G);return}for await(let Zn of G)if(t.abortController?.signal.aborted||(await Xr(Il(Zn)),t.abortController?.signal.aborted))break}finally{if(t.abortController?.signal.removeEventListener("abort",Qn),r)try{await(await r).cleanup()}catch{}Jr()}})().catch(G=>{we({type:"result",data:na(s??"",{success:!1,result:ra(G),total_cost_usd:c,num_turns:p,session_id:s??""})}),t.abortController?.signal.removeEventListener("abort",Qn),Jr()}),{messages:ga(),async setPermissionMode(G){i=G,te=!0},async interrupt(){ae?.abort("interrupted")}}}buildUserMessage(t,n){return{type:"user",text:t,session_id:n}}};var Br=new Map;function oa(e){Br.set(e.name,e)}function Wr(e){let t=Br.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...Br.keys()].join(", ")}`);return t}function sa(){return Wr(nt())}oa(new Ln);oa(new jn);var ia=200,wl=120*1e3;function Gn(e){return e instanceof Error?e.message:String(e)}var Al={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},qr=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(t){this.queue.push(t),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(t=>{this.resolve=t})}}},Vn=class extends bl{id;name;harnessSessionId;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;multiTurn;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;pendingPlanApproval=!1;lobsterResumeToken;killReason="unknown";waitingForInputFired=!1;lastTurnHadQuestion=!1;planModeApproved=!1;autoRespondCount=0;timers=new Map;constructor(t,n){super(),this.id=Hi(8),this.name=n,this.harness=t.harness?Wr(t.harness):sa(),this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??rt(this.harness.name),this.reasoningEffort=t.reasoningEffort??Nt(this.harness.name),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??E.permissionMode,this.codexApprovalPolicy=this.harness.name==="codex"?t.codexApprovalPolicy??gt(this.harness.name)??E.codexApprovalPolicy:void 0,this.currentPermissionMode=this.harness.name==="codex"&&this.permissionMode==="plan"?"default":this.permissionMode,this.originChannel=t.originChannel,this.originThreadId=t.originThreadId,this.originAgentId=t.originAgentId,this.originSessionKey=t.originSessionKey,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.startedAt=Date.now(),this.abortController=new AbortController}get status(){return this._status}get harnessName(){return this.harness.name}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this._status!=="running"?this._status:this.harness.name==="codex"?"implementing":this.pendingPlanApproval?"awaiting-plan-approval":this.currentPermissionMode==="plan"?"planning":"implementing"}transition(t){if(!Al[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let n=this._status;this._status=t,this.emit("statusChange",this,t,n)}setTimer(t,n,r){this.clearTimer(t),this.timers.set(t,setTimeout(r,n))}clearTimer(t){let n=this.timers.get(t);n&&(clearTimeout(n),this.timers.delete(t))}clearAllTimers(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}async start(){try{let t;this.multiTurn?(this.messageStream=new qr,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let n=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,abortController:this.abortController,mcpServers:Si()});this.harnessHandle=n,this.setTimer("startup",wl,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let n=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:n});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let n=t instanceof Error?t.message:String(t),r=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${n}`,r),this.isActive&&this.transitionToTerminal("failed",{error:n})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.waitingForInputFired=!1;let n=t;if(this.pendingModeSwitch){let r=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(r),this.currentPermissionMode=r,this.pendingModeSwitch=void 0,i=!0,o=!0}catch(s){throw console.error(`[Session ${this.id}] setPermissionMode(${r}) FAILED: ${Gn(s)}`),this.pendingPlanApproval=!0,new Error(`Failed to switch permission mode to ${r}: ${Gn(s)}`)}else this.pendingModeSwitch=void 0,i=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);i&&(this.pendingPlanApproval=!1,r!=="plan"&&(this.planModeApproved=!0)),o&&(n=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
80
+ `)}`}}let n=!1;r.startsWith("--fork ")&&(n=!0,r=r.slice(7).trim());let o=r.indexOf(" "),s,i;o===-1?(s=r,i="Continue where you left off."):(s=r.slice(0,o),i=r.slice(o+1).trim()||"Continue where you left off.");let a=I.resolveHarnessSessionId(s);if(!a)return{text:`Error: Could not find a session ID for "${s}".
81
+ Use /agent_resume --list to see available sessions.`};let d=I.resolve(s),m=I.getPersistedSession(s),{resumeSessionId:y,clearedPersistedCodexResume:f}=Zt({requestedResumeSessionId:a,activeSession:d?{harnessSessionId:d.harnessSessionId}:void 0,persistedSession:m?{harness:m.harness}:void 0}),c=m?.workdir??process.cwd(),w=m?.harness??pt(),S=m?.model??mt(w);try{if(!S)return{text:`Error: No default model configured for harness "${w}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${w}.defaultModel or pass model explicitly when launching a fresh session.`};let k=I.spawn({prompt:i,workdir:c,name:m?.name,model:S,codexApprovalPolicy:d?.codexApprovalPolicy??m?.codexApprovalPolicy,resumeSessionId:y,forkSession:y?n:!1,originChannel:Jt(t),originThreadId:Xt(t)??m?.originThreadId,originAgentId:t?.agentId??m?.originAgentId,originSessionKey:t?.sessionKey??m?.originSessionKey,harness:w}),x=i.length>80?i.slice(0,80)+"...":i;return{text:[`Session resumed${n?" (forked)":""}.`,` Name: ${k.name}`,` ID: ${k.id}`,y?` Resume from: ${a}`:" Resume from: fresh thread",` Dir: ${c}`,` Prompt: "${x}"`,f?" Note: cleared persisted Codex thread state after restart to avoid org-mismatch resume failures.":""].join(`
82
+ `)}}catch(k){let x=Dm(k),T=x.includes("Max sessions")?"":`
45
83
 
46
- ${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved){let r=this.harness.planApprovalToolNames;if(n=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below,${r.length>0?` then call ${r.join(" or ")} again to re-submit for approval.`:" then re-submit your revised plan for approval."} Do NOT start implementing yet.]
84
+ Use /agent_sessions to see active sessions or /agent_resume --list to see resumable sessions.`;return{text:`Error resuming session: ${x}${T}`}}}})}function Ta(e){e.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:`Usage: /agent_respond <id-or-name> <message>
85
+ /agent_respond --interrupt <id-or-name> <message>`};let n=!1,o=r;o.startsWith("--interrupt ")&&(n=!0,o=o.slice(12).trim());let s=o.indexOf(" ");if(s===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let i=o.slice(0,s),a=o.slice(s+1).trim();return a?{text:(await ft(I,{session:i,message:a,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}function Aa(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=I.getMetrics(),r=I.list("running").length;return{text:Qr(t,r)}}})}var Lm=50;function $a(e){e.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!I)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let n=r.split(/\s+/),o="",s=!1,i=Lm;for(let d=0;d<n.length;d++)if(n[d]==="--full")s=!0;else if(n[d]==="--lines"&&d+1<n.length){let m=parseInt(n[d+1],10);!isNaN(m)&&m>0&&(i=m),d++}else o||(o=n[d]);return o?{text:Yr(I,o,{full:s,lines:i})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}import{existsSync as ag}from"fs";import{EventEmitter as Cf}from"events";import{appendFileSync as Mf}from"fs";import{tmpdir as Of}from"os";import{join as Ef}from"path";import{webcrypto as Ca}from"node:crypto";var Ra="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Km=128,Ot,rr;function jm(e){!Ot||Ot.length<e?(Ot=Buffer.allocUnsafe(e*Km),Ca.getRandomValues(Ot),rr=0):rr+e>Ot.length&&(Ca.getRandomValues(Ot),rr=0),rr+=e}function Ma(e=21){jm(e|=0);let t="";for(let r=rr-e;r<rr;r++)t+=Ra[Ot[r]&63];return t}import{query as Bm}from"@anthropic-ai/claude-agent-sdk";import{dirname as Oa,join as Ea}from"path";import{fileURLToPath as Wm}from"url";import{createRequire as Gm}from"module";var ln=class{name="claude-code";supportedPermissionModes=["default","plan","bypassPermissions"];questionToolNames=["AskUserQuestion"];planApprovalToolNames=["ExitPlanMode","set_permission_mode"];launch(t){let r=t.canUseTool,n={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,pathToClaudeCodeExecutable:(()=>{try{let i=Gm(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return Ea(Oa(i),"cli.js")}catch{let s=Oa(Wm(import.meta.url));return Ea(s,"..","node_modules","@anthropic-ai","claude-agent-sdk","cli.js")}})(),allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers,...r?{canUseTool:async(s,i)=>s==="AskUserQuestion"?r(s,i):{behavior:"allow"}}:{}};t.resumeSessionId&&(n.resume=t.resumeSessionId,n.forkSession=t.forkSession??!1);let o=Bm({prompt:t.prompt,options:n});return{messages:this.adaptMessages(o),async setPermissionMode(s){typeof o.setPermissionMode=="function"&&await o.setPermissionMode(s)},async streamInput(s){typeof o.streamInput=="function"&&await o.streamInput(s)},async interrupt(){typeof o.interrupt=="function"&&await o.interrupt()}}}buildUserMessage(t,r){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:r}}async*adaptMessages(t){for await(let r of t){let n=r;if(n.type==="system"&&n.subtype==="init")yield{type:"init",session_id:n.session_id??""};else if(n.type==="system"&&n.subtype==="status"&&n.permissionMode)yield{type:"permission_mode_change",mode:n.permissionMode};else if(n.type==="assistant")for(let o of n.message?.content??[])o.type==="text"?yield{type:"text",text:o.text}:o.type==="tool_use"&&(yield{type:"tool_use",name:o.name,input:o.input});else n.type==="result"&&(yield{type:"result",data:{success:n.subtype==="success",duration_ms:n.duration_ms??0,total_cost_usd:n.total_cost_usd??0,num_turns:n.num_turns??0,result:n.result,session_id:n.session_id??""}})}}};import{parse as ff,resolve as gf}from"path";import{Codex as ja}from"@openai/codex-sdk";import{randomUUID as Hm}from"node:crypto";import{lstat as Vm,mkdir as xo,readFile as Fa,readlink as qm,realpath as zm,rename as Qm,rm as pn,symlink as Ym,writeFile as Na}from"node:fs/promises";import{homedir as Jm,tmpdir as Ua}from"node:os";import{dirname as Xm,join as je,resolve as Zm}from"node:path";var ef=50,tf=3e4,rf=je(Ua(),"openclaw-codex-auth.lock");function nf(e,t){let r={};for(let[n,o]of Object.entries(e))typeof o=="string"&&(r[n]=o);return r.HOME=t,r}function of(e){return new Promise(t=>setTimeout(t,e))}async function Da(e){try{return await Vm(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function va(e,t){if(await Da(t)){if(await qm(t)===e)return;await pn(t,{recursive:!0,force:!0})}await Ym(e,t)}function sf(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return null;let r=Number(t);if(Number.isFinite(r))return r;let n=Date.parse(t);if(Number.isFinite(n))return n}return null}async function _a(e){let t;try{t=await Fa(e,"utf8")}catch(r){return r.code==="ENOENT",null}try{let r=JSON.parse(t);if(!r||typeof r!="object")return null;let n=sf(r.last_refresh);return n===null?null:{lastRefresh:n,raw:t}}catch{return null}}async function La(e,t){await xo(Xm(e),{recursive:!0});let r=`${e}.tmp`;await Na(r,t,"utf8"),await Qm(r,e)}async function af(e,t){try{let r=await Fa(e,"utf8");await La(t,r)}catch(r){if(r.code!=="ENOENT")throw r;await pn(t,{force:!0})}}async function uf(e,t){let r=await _a(e);if(!r)return;let n=await _a(t);n&&r.lastRefresh<=n.lastRefresh||await La(t,r.raw)}async function cf(e,t,r){let n=Date.now()+t;for(;;)try{await xo(e);break}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=n)throw new Error(`Timed out waiting for Codex auth lock at ${e}`);await of(r)}try{await Na(je(e,"holder.json"),JSON.stringify({pid:process.pid,acquired_at:new Date().toISOString()}),"utf8")}catch{}let o=!1;return async()=>{o||(o=!0,await pn(e,{recursive:!0,force:!0}))}}async function Ka(e=process.env,t={}){let r=e.HOME??Jm(),n=await zm(r).catch(()=>Zm(r)),o=je(n,".codex"),s=je(o,"auth.json"),i=je(o,"sessions"),a=je(o,"config.toml"),d=await Da(a)?a:void 0,m=t.tempRootDir??Ua(),y=je(m,`openclaw-codex-auth-${Hm()}`),f=je(y,".codex"),c=je(f,"auth.json"),w=t.lockDir??rf,S=t.lockTimeoutMs??tf,k=t.lockRetryMs??ef;return await xo(f,{recursive:!0}),await va(i,je(f,"sessions")),d&&await va(d,je(f,"config.toml")),{tempHome:y,tempCodexDir:f,canonicalHome:n,canonicalCodexDir:o,canonicalAuthPath:s,canonicalSessionsPath:i,canonicalConfigPath:d,env:nf(e,y),async prepareForTurn(){let x=await cf(w,S,k);try{await af(s,c)}catch(b){throw await x(),b}let T=!1;return async()=>{if(!T){T=!0;try{await uf(c,s)}finally{await x()}}}},async cleanup(){await pn(y,{recursive:!0,force:!0})}}}var df=["proceed","continue","implement","apply","run","merge","deploy","commit"],lf=["shall i proceed","do you want me to","would you like me to","please confirm","should i continue","can i proceed","should i proceed","should i go ahead","want me to continue","approve and i'll","confirm and i'll"],pf=["why this failed was","why did this fail","what failed","what happened","how can i help","is this clear","any questions","anything else","let me know","would you like a summary"];function mf(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function mn(e){let t=mf(e);if(!t||pf.some(n=>t.includes(n)))return!1;let r=df.some(n=>t.includes(n));return lf.some(n=>t.includes(n))?r||t.includes("confirm"):t.endsWith("?")?r:!1}var Ba=1e4,Wa="codex:waiting-for-user",hf=1.1/1e6,yf=.275/1e6,If=4.4/1e6,wf="OPENCLAW_CODEX_HEARTBEAT_MS",Sf="OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS",xf="OPENCLAW_CODEX_AUTH_STRATEGY";function bf(e){if(!e)return 0;let t=e.cached_input_tokens??0,r=Math.max(0,(e.input_tokens??0)-t),n=e.output_tokens??0;return r*hf+t*yf+n*If}function Ga(e,t={}){return{success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,session_id:e,...t}}function kf(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return String(e);let t=e;return typeof t.message?.content=="string"?t.message.content:typeof t.text=="string"?t.text:String(e)}function Pf(e){return["[SYSTEM: First turn only. Do not implement yet.]","Start by producing a concise implementation plan only.","Then end your response with an explicit question asking whether you should proceed with implementation.","",e].join(`
86
+ `)}function Ha(e){return e instanceof Error?e.message:String(e)}function Tf(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Af(e){return ff(gf(e)).root||"/"}function $f(e){let r=[Af(e)];return r.push(...Tf(process.env[Sf])),[...new Set(r)]}function Rf(e,t){let n=(t??e.permissionMode)==="bypassPermissions"?$f(e.cwd):void 0;return{model:e.model,modelReasoningEffort:e.reasoningEffort,workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:e.codexApprovalPolicy??"on-request",skipGitRepoCheck:!0,additionalDirectories:n}}var fn=class{constructor(t={}){this.deps=t}name="codex";supportedPermissionModes=["default","plan","bypassPermissions"];questionToolNames=[Wa];planApprovalToolNames=[];activityHeartbeatMs(){let t=Number.parseInt(process.env[wf]??String(Ba),10);return!Number.isFinite(t)||t<=0?Ba:t}createCodexClient(t){return this.deps.createCodex?.({env:t})??(t?new ja({env:t}):new ja)}launch(t){let n=process.env[xf]==="legacy"?void 0:this.deps.createAuthWorkspace?.(process.env)??Ka(process.env),o=t.permissionMode==="plan",s=t.permissionMode==="plan"?"default":t.permissionMode,i=t.resumeSessionId,a=0,d=0,m=this.activityHeartbeatMs(),y,f,c=!1,w=!0,S,k=!1,x=[],T=null,b=!1,E=!1;function P(){T&&(T(),T=null)}function A(X){x.push(X),P()}function de(){b=!0,P()}function ke(X){!X||E||(E=!0,A({type:"init",session_id:X}))}async function*ht(){for(;;){for(;x.length>0;)yield x.shift();if(b)return;await new Promise(X=>{T=X})}}let Et=()=>Rf(t,s),Tn=X=>(y||(y=this.createCodexClient(X)),f||(w&&t.resumeSessionId?f=y.resumeThread(t.resumeSessionId,Et()):i?f=y.resumeThread(i,Et()):f=y.startThread(Et())),c&&i&&(f=y.resumeThread(i,Et()),c=!1),f),tt=async X=>{let An=Date.now();d+=1;let $o="",$n=!1,Ro=!1,Rn,Cn,Co=!1,tu=w&&o?Pf(X):X,Pr=yt=>{$n||($n=!0,A({type:"result",data:Ga(i??"",{duration_ms:Date.now()-An,total_cost_usd:a,num_turns:d,...yt,session_id:i??""})}))},Mn=async()=>{!Cn||Co||(Co=!0,await Cn())};try{let yt=n?await n:void 0;yt&&(Cn=await yt.prepareForTurn());let On=Tn(yt?.env),Mo=On.id??i??void 0;Mo&&(i=Mo),S=new AbortController,t.abortController?.signal.aborted&&S.abort(t.abortController.signal.reason),Rn=setInterval(()=>{A({type:"activity"})},m);let ru=await On.runStreamed(tu,{signal:S.signal});for await(let le of ru.events)if(await Mn(),le.type==="thread.started"&&(i=le.thread_id),ke(i??On.id??void 0),le.type!=="thread.started"){if(le.type==="item.completed"){(le.item.type==="agent_message"||le.item.type==="reasoning")&&($o+=`${le.item.text}
87
+ `,A({type:"text",text:le.item.text}));continue}if(le.type==="error"){S?.signal.aborted&&k||A({type:"text",text:`[codex:error] ${le.message}`});continue}if(le.type==="turn.failed"){if(S?.signal.aborted&&k){k=!1,Ro=!0,c=!0;break}Pr({success:!1,result:le.error.message,session_id:i??""});continue}if(le.type==="turn.completed"){a+=bf(le.usage);let Oo=$o.slice(-500);mn(Oo)&&A({type:"tool_use",name:Wa,input:{text:Oo}}),Pr({success:!0,session_id:i??""})}}if(await Mn(),Ro)return;$n||Pr({success:!1,result:"Codex turn ended without terminal event",session_id:i??""})}catch(yt){if(await Mn(),S?.signal.aborted&&k){k=!1,c=!0;return}Pr({success:!1,result:Ha(yt),session_id:i??""})}finally{Rn&&clearInterval(Rn),S=void 0,w=!1}},We=()=>{S?.abort(t.abortController?.signal.reason??"interrupted")};return t.abortController?.signal&&t.abortController.signal.addEventListener("abort",We),(async()=>{try{let X=t.prompt;if(typeof X=="string"){await tt(X);return}for await(let An of X)if(t.abortController?.signal.aborted||(await tt(kf(An)),t.abortController?.signal.aborted))break}finally{if(t.abortController?.signal.removeEventListener("abort",We),n)try{await(await n).cleanup()}catch{}de()}})().catch(X=>{A({type:"result",data:Ga(i??"",{success:!1,result:Ha(X),total_cost_usd:a,num_turns:d,session_id:i??""})}),t.abortController?.signal.removeEventListener("abort",We),de()}),{messages:ht(),async setPermissionMode(X){s=X,c=!0},async interrupt(){S&&(k=!0,S.abort("interrupted"))}}}buildUserMessage(t,r){return{type:"user",text:t,session_id:r}}};var bo=new Map;function Va(e){bo.set(e.name,e)}function ko(e){let t=bo.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...bo.keys()].join(", ")}`);return t}function qa(){return ko(pt())}Va(new ln);Va(new fn);var za=2e3,vf=120*1e3;function gn(e){return e instanceof Error?e.message:String(e)}var _f={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},Po=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(t){this.queue.push(t),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(t=>{this.resolve=t})}}},hn=class extends Cf{id;name;harnessSessionId;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;worktreePath;originalWorkdir;worktreeBranch;worktreeStrategy;worktreeBaseBranch;outputMode;multiTurn;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;pendingPlanApproval=!1;planFilePath;killReason="unknown";waitingForInputFired=!1;lastTurnHadQuestion=!1;planModeApproved=!1;turnInProgress=!0;canUseTool;autoRespondCount=0;timers=new Map;constructor(t,r){super(),this.id=Ma(8),this.name=r,this.harness=t.harness?ko(t.harness):qa(),this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??mt(this.harness.name),this.reasoningEffort=t.reasoningEffort??Yt(this.harness.name),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??N.permissionMode,this.codexApprovalPolicy=this.harness.name==="codex"?t.codexApprovalPolicy??$t(this.harness.name)??N.codexApprovalPolicy:void 0,this.currentPermissionMode=this.harness.name==="codex"&&this.permissionMode==="plan"?"default":this.permissionMode,this.originChannel=t.originChannel,this.originThreadId=t.originThreadId,this.originAgentId=t.originAgentId,this.originSessionKey=t.originSessionKey,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.worktreeStrategy=t.worktreeStrategy,this.worktreeBaseBranch=t.worktreeBaseBranch,this.outputMode=t.outputMode,this.canUseTool=t.canUseTool,this.startedAt=Date.now(),this.abortController=new AbortController}get status(){return this._status}get harnessName(){return this.harness.name}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this._status!=="running"?this._status:this.harness.name==="codex"?"implementing":this.pendingPlanApproval?"awaiting-plan-approval":this.currentPermissionMode==="plan"?"planning":"implementing"}transition(t){if(!_f[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let r=this._status;this._status=t,this.emit("statusChange",this,t,r)}setTimer(t,r,n){this.clearTimer(t),this.timers.set(t,setTimeout(n,r))}clearTimer(t){let r=this.timers.get(t);r&&(clearTimeout(r),this.timers.delete(t))}clearAllTimers(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}async start(){try{let t;this.multiTurn?(this.messageStream=new Po,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let r=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,abortController:this.abortController,mcpServers:Qi(),canUseTool:this.canUseTool});this.harnessHandle=r,this.setTimer("startup",vf,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let r=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:r});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let r=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${r}`,n),this.isActive&&this.transitionToTerminal("failed",{error:r})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.waitingForInputFired=!1,this.turnInProgress=!0;let r=t;if(this.pendingModeSwitch){let n=this.pendingModeSwitch,o=!1,s=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(n),this.currentPermissionMode=n,this.pendingModeSwitch=void 0,s=!0,o=!0}catch(i){throw console.error(`[Session ${this.id}] setPermissionMode(${n}) FAILED: ${gn(i)}`),this.pendingPlanApproval=!0,new Error(`Failed to switch permission mode to ${n}: ${gn(i)}`)}else this.pendingModeSwitch=void 0,s=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);s&&(this.pendingPlanApproval=!1,n!=="plan"&&(this.planModeApproved=!0)),o&&(r=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
47
88
 
48
- ${t}`,this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan"}catch(i){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${Gn(i)}`)}}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(n,this.harnessSessionId??""));else if(this.harnessHandle?.streamInput){let r=this.harness.buildUserMessage(n,this.harnessSessionId??"");async function*o(){yield r}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){this.harnessHandle?.interrupt&&await this.harnessHandle.interrupt()}switchPermissionMode(t){this.pendingModeSwitch=t}get isActive(){return this._status==="starting"||this._status==="running"}kill(t){this.transitionToTerminal("killed",{reason:t})}complete(t="done"){this.transitionToTerminal("completed",{reason:t})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}resetIdleTimer(){if(!this.multiTurn)return;let t=(E.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",t,()=>{this._status==="running"&&this.kill("idle-timeout")})}teardown(){this.clearAllTimers(),this.completedAt||(this.completedAt=Date.now()),this.messageStream&&this.messageStream.end(),this.harnessHandle?.interrupt&&this.harnessHandle.interrupt().catch(t=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${Gn(t)}`)}),this.abortController.abort()}transitionToTerminal(t,n={}){this.isActive&&(n.reason&&(this.killReason=n.reason),n.error!==void 0&&(this.error=n.error),this.completedAt=Date.now(),this.transition(t),this.teardown())}async consumeMessages(t){for await(let n of t){if(!this.isActive)break;if(this.resetIdleTimer(),n.type==="init")this.clearTimer("startup"),this.harnessSessionId=n.session_id,this._status==="starting"&&this.transition("running");else if(n.type==="text")this.waitingForInputFired=!1,this.pendingPlanApproval||(this.lastTurnHadQuestion=!1),this.outputBuffer.push(n.text),this.outputBuffer.length>ia&&this.outputBuffer.splice(0,this.outputBuffer.length-ia),this.emit("output",this,n.text);else if(n.type==="tool_use")this.harness.questionToolNames.includes(n.name)?(this.lastTurnHadQuestion=!0,this.currentPermissionMode==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0)):this.harness.planApprovalToolNames.includes(n.name)&&!this.planModeApproved&&(this.lastTurnHadQuestion=!0,this.pendingPlanApproval=!0),this.emit("toolUse",this,n.name,n.input);else if(n.type==="permission_mode_change"){let r=this.currentPermissionMode;this.currentPermissionMode=n.mode,n.mode!=="plan"&&r==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0,this.lastTurnHadQuestion=!0)}else if(n.type==="result"){if(this.result={subtype:n.data.success?"success":"error",duration_ms:n.data.duration_ms,total_cost_usd:n.data.total_cost_usd,num_turns:n.data.num_turns,result:n.data.result,is_error:!n.data.success,session_id:n.data.session_id},this.costUsd=n.data.total_cost_usd,this.multiTurn&&this.messageStream&&n.data.success){this.resetIdleTimer(),this.currentPermissionMode==="plan"&&!this.pendingPlanApproval&&!this.planModeApproved&&(this.pendingPlanApproval=!0);let o=this.pendingPlanApproval||this.lastTurnHadQuestion,i=this.messageStream?.hasPending()===!0;o&&!this.waitingForInputFired?(this.waitingForInputFired=!0,this.emit("turnEnd",this,!0)):i||o||(this.emit("turnEnd",this,!1),this.complete("done"))}else this.transitionToTerminal(n.data.success?"completed":"failed");this.lastTurnHadQuestion=!1}else n.type}}};import{mkdirSync as Pl,readFileSync as Rl,readdirSync as Ol,renameSync as Cl,statSync as Ml,unlinkSync as El,writeFileSync as aa}from"fs";import{homedir as kl,tmpdir as ua}from"os";import{dirname as Fl,join as Bn}from"path";function $l(e){let t=e.OPENCLAW_HOME?.trim();return t||Bn(kl(),".openclaw")}function vl(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||Bn($l(e),"code-agent-sessions.json")}var Nl=new Set(["completed","failed","killed"]),Ul=new Set(["running","completed","failed","killed"]),_l=1440*60*1e3;function da(e){return e instanceof Error?e.message:String(e)}function Ll(e){return!!e&&typeof e=="object"}function Hn(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function ht(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function ca(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Kl(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function Dl(e){return e==="default"||e==="plan"||e==="acceptEdits"||e==="bypassPermissions"?e:void 0}function jl(e){return e==="never"||e==="on-request"?e:void 0}function Gl(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function Vl(e){if(typeof e=="string"&&Ul.has(e))return e==="running"?"killed":e}function Hl(e){if(!Ll(e))return;let t=Hn(e.harnessSessionId);if(!t)return;let n=Vl(e.status);if(n)return{sessionId:ht(e.sessionId),harnessSessionId:t,name:Hn(e.name,t),prompt:Hn(e.prompt),workdir:Hn(e.workdir,"(unknown)"),model:ht(e.model),reasoningEffort:Kl(e.reasoningEffort),createdAt:ca(e.createdAt),completedAt:ca(e.completedAt),status:n,killReason:Gl(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:ht(e.originAgentId),originChannel:ht(e.originChannel),originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originSessionKey:ht(e.originSessionKey),outputPath:ht(e.outputPath),harness:ht(e.harness),currentPermissionMode:Dl(e.currentPermissionMode),codexApprovalPolicy:jl(e.codexApprovalPolicy)}}var Wn=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;indexPath;constructor(t={}){let n=t.env??process.env;this.indexPath=t.indexPath??vl(n),n.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){try{let t=Rl(this.indexPath,"utf-8"),n=JSON.parse(t);if(!Array.isArray(n))return;let r=!1;for(let o of n){let i=Hl(o);if(!i){r=!0;continue}this.persisted.set(i.harnessSessionId,i),i.sessionId&&this.idIndex.set(i.sessionId,i.harnessSessionId),i.name&&this.nameIndex.set(i.name,i.harnessSessionId)}r&&this.saveIndex()}catch{}}saveIndex(){try{Pl(Fl(this.indexPath),{recursive:!0});let t=this.indexPath+".tmp";aa(t,JSON.stringify([...this.persisted.values()],null,2),"utf-8"),Cl(t,this.indexPath)}catch(t){console.warn(`[SessionStore] Failed to save session index: ${da(t)}`)}}markRunning(t){if(!t.harnessSessionId)return;let n={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy};this.persisted.set(n.harnessSessionId,n),this.idIndex.set(t.id,n.harnessSessionId),this.nameIndex.set(t.name,n.harnessSessionId),this.saveIndex()}hasRecordedSession(t){return this.idIndex.has(t)}persistTerminal(t){if(!t.harnessSessionId)return;let n;try{let o=Bn(ua(),`openclaw-agent-${t.id}.txt`),i=t.getOutput().join(`
49
- `);i.length>0&&(aa(o,i,"utf-8"),n=o)}catch(o){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${da(o)}`)}let r={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,completedAt:t.completedAt,status:t.status,killReason:t.killReason,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,outputPath:n,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy};this.persisted.set(t.harnessSessionId,r),this.idIndex.set(t.id,t.harnessSessionId),this.nameIndex.set(t.name,t.harnessSessionId),this.saveIndex()}getLatestPersistedByName(t){let n,r=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=0;for(let c of this.persisted.values()){if(c.name!==t){s++;continue}let p=c.createdAt??Number.NEGATIVE_INFINITY,f=c.completedAt??Number.NEGATIVE_INFINITY;(p>r||p===r&&f>o||p===r&&f===o&&s>i)&&(n=c,r=p,o=f,i=s),s++}return n}resolveHarnessSessionId(t,n){if(n)return n;let r=this.idIndex.get(t);if(r&&this.persisted.has(r))return r;let o=this.getLatestPersistedByName(t);if(o)return o.harnessSessionId;if(this.persisted.has(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return t}getPersistedSession(t){let n=this.persisted.get(t);if(n)return n;let r=this.idIndex.get(t);return r?this.persisted.get(r):this.getLatestPersistedByName(t)}listPersistedSessions(){return[...this.persisted.values()].sort((t,n)=>(n.completedAt??0)-(t.completedAt??0))}cleanupTmpOutputFiles(t){try{let n=ua(),r=Ol(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r)try{let i=Bn(n,o),s=Ml(i).mtimeMs;t-s>_l&&El(i)}catch{}}catch{}}evictOldestPersisted(t){let n=this.listPersistedSessions();if(n.length<=t)return;let r=n.slice(t);for(let o of r){this.persisted.delete(o.harnessSessionId);for(let[i,s]of this.idIndex)s===o.harnessSessionId&&this.idIndex.delete(i);for(let[i,s]of this.nameIndex)s===o.harnessSessionId&&this.nameIndex.delete(i)}this.saveIndex()}shouldGcActiveSession(t,n,r){return!t.completedAt||!Nl.has(t.status)?!1:n-t.completedAt>r}};var Bl=new Set(["completed","failed","killed"]),qn=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(t){let n=t.costUsd??0,r=t.status;this.metrics.totalCostUsd+=n;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+n),Bl.has(r)&&this.metrics.sessionsByStatus[r]++,t.completedAt){let i=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||n>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:n,prompt:ot(t.prompt,80)})}getMetrics(){return{totalCostUsd:this.metrics.totalCostUsd,costPerDay:new Map(this.metrics.costPerDay),sessionsByStatus:{...this.metrics.sessionsByStatus},totalLaunched:this.metrics.totalLaunched,totalDurationMs:this.metrics.totalDurationMs,sessionsWithDuration:this.metrics.sessionsWithDuration,mostExpensive:this.metrics.mostExpensive?{...this.metrics.mostExpensive}:null}}};import{execFile as Wl}from"child_process";import{randomUUID as ql}from"crypto";var ma=3e4,zl=2e3,Yl=2e4,zn=4,Yn=class{pendingRetryTimers=new Set;clearPendingRetries(){for(let t of this.pendingRetryTimers)clearTimeout(t);this.pendingRetryTimers.clear()}getOriginSessionKey(t){let n=t.originSessionKey?.trim();return n||void 0}getOriginThreadId(t){let n=t.originThreadId;return n==null?void 0:String(n).trim()||void 0}parseNotificationRoute(t){let n=t.originChannel?.trim(),r=this.getOriginThreadId(t);if(n){let s=n.split("|").map(c=>c.trim()).filter(Boolean);if(s.length>=2){let[c,p,f]=s,T=f??p,U=f?p:void 0;if(c&&T)return{channel:c,target:T,accountId:U,threadId:r??this.parseThreadIdFromSessionKey(t.originSessionKey)}}}let o=this.getOriginSessionKey(t);if(!o)return;let i=o.match(/^agent:[^:]+:telegram:(?:direct|dm|group|channel):([^:]+)(?::topic:(\d+))?$/i);if(i?.[1])return{channel:"telegram",target:i[1],threadId:r??i[2]}}parseThreadIdFromSessionKey(t){return t?t.match(/:topic:(\d+)$/)?.[1]:void 0}retryDelayMs(t){let n=Math.max(0,t-1),r=zl*2**n;return Math.min(r,Yl)}executeWithRetries(t,n,r=1){let o=Date.now();console.info(`[WakeDispatcher] ${n.target} ${n.phase} started attempt ${r}/${zn} for ${n.label} session=${n.sessionId}`),Wl("openclaw",t,{timeout:ma},i=>{let s=Date.now()-o;if(!i){console.info(`[WakeDispatcher] ${n.target} ${n.phase} completed attempt ${r}/${zn} for ${n.label} session=${n.sessionId} in ${s}ms`);return}let c=`[WakeDispatcher] ${n.target} ${n.phase} failed`;if(r>=zn){console.error(`${c} after ${r} attempts for ${n.label} session=${n.sessionId} in ${s}ms: ${i.message}`),n.onFinalFailure?.();return}let p=this.retryDelayMs(r);console.error(`${c} attempt ${r}/${zn} for ${n.label} session=${n.sessionId} in ${s}ms: ${i.message}. Retrying in ${p}ms`);let f=setTimeout(()=>{this.pendingRetryTimers.delete(f),this.executeWithRetries(t,n,r+1)},p);this.pendingRetryTimers.add(f)})}fireChatSendWithRetry(t,n,r,o,i,s=!1,c){let p=["gateway","call","chat.send","--expect-final","--timeout",String(ma),"--params",JSON.stringify({sessionKey:t,message:n,deliver:s,idempotencyKey:ql()})];this.executeWithRetries(p,{label:r,sessionId:o,target:"chat.send",phase:i,onFinalFailure:c})}fireDirectNotificationWithRetry(t,n,r,o,i){let s=["message","send","--channel",t.channel,"--target",t.target,"--message",n];t.accountId&&s.push("--account",t.accountId),t.threadId&&s.push("--thread-id",t.threadId),this.executeWithRetries(s,{label:r,sessionId:o,target:"message.send",phase:"notify",onFinalFailure:i})}fireSystemEventWithRetry(t,n,r,o){let i=["system","event","--text",t,"--mode","now"];this.executeWithRetries(i,{label:n,sessionId:r,target:"system.event",phase:o})}sendUserNotification(t,n,r,o){let i=this.parseNotificationRoute(t);if(!i){this.fireSystemEventWithRetry(n,`${r}-notify-system`,o,"notify");return}this.fireDirectNotificationWithRetry(i,n,`${r}-notify`,o,()=>{this.fireSystemEventWithRetry(n,`${r}-notify-fallback`,o,"notify")})}dispatchSessionNotification(t,n){let r=this.getOriginSessionKey(t),o=n.notifyUser??(n.wakeMessage?"on-wake-fallback":"always"),i=n.userMessage?.trim(),s=n.wakeMessage?.trim();if(o==="always"&&i&&this.sendUserNotification(t,i,n.label,t.id),!!s){if(!r){o==="on-wake-fallback"&&i&&this.sendUserNotification(t,i,n.label,t.id),this.fireSystemEventWithRetry(s,`${n.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(r,s,`${n.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(s,`${n.label}-wake-fallback`,t.id,"wake")})}}};function Ql(){let e=process.env.OPENCLAW_CODE_AGENT_PLAN_WORKFLOW_PATH?.trim();if(e)return e;let t=Xl(la(import.meta.url)),n=[zr(process.cwd(),"workflows","plan-approval.lobster"),zr(t,"..","workflows","plan-approval.lobster"),zr(t,"..","..","workflows","plan-approval.lobster")];for(let r of n)if(Jl(r))return r;return la(new URL("../workflows/plan-approval.lobster",import.meta.url))}var Zl=Ql(),Yr=new Set(["completed","failed","killed"]),Jn=new Set(["starting","running"]),ef=5e3,tf=3e4;function nf(e){let t=e.trim();if(!t)return;let n=i=>typeof i=="string"&&i.trim().length>0&&/^[A-Za-z0-9._:-]+$/.test(i.trim()),r=[t];for(let i of t.split(/\r?\n/)){let s=i.trim();s.startsWith("{")&&s.endsWith("}")&&r.push(s)}for(let i of r)try{let s=JSON.parse(i),c=s?.resumeToken??s?.requiresApproval?.resumeToken??s?.details?.requiresApproval?.resumeToken;if(n(c))return c.trim()}catch{}let o=t.match(/"resumeToken"\s*:\s*"([^"]+)"/);if(o&&n(o[1]))return o[1].trim()}var Xn=class{sessions=new Map;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;store;metrics;wakeDispatcher;constructor(t=20,n=50){this.maxSessions=t,this.maxPersistedSessions=n,this.store=new Wn,this.metrics=new qn,this.wakeDispatcher=new Yn}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(t){let n=new Set([...this.sessions.values()].filter(o=>Jn.has(o.status)).map(o=>o.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}-${r}`);)r++;return`${t}-${r}`}spawn(t,n={}){if([...this.sessions.values()].filter(c=>Jn.has(c.status)).length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);let o=t.name||Ri(t.prompt),i=this.uniqueName(o);i!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${i}" (active session with same name exists)`);let s=new Vn(t,i);if(this.sessions.set(s.id,s),this.metrics.incrementLaunched(),s.on("statusChange",(c,p)=>{p==="running"&&s.harnessSessionId?this.store.markRunning(s):Yr.has(p)&&this.onSessionTerminal(s)}),s.on("turnEnd",(c,p)=>{this.onTurnEnd(s,p)}),s.start(),n.notifyLaunch!==!1){let c=`\u{1F680} [${s.name}] Launched | ${s.workdir} | ${s.model??"default"}`;this.notifySession(s,c,"launch")}return s}async spawnAndAwaitRunning(t,n={}){let r=this.spawn(t,n);return await this.waitForRunningSession(r),r}async waitForRunningSession(t){if(t.status==="running")return;if(Yr.has(t.status))throw new Error(this.describeLaunchFailure(t));let n=t.on?.bind(t),r=t.off?.bind(t)??t.removeListener?.bind(t);if(!n||!r)throw new Error(`Session ${t.name} [${t.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(p,f)=>{if(f==="running"){c(),o();return}Yr.has(f)&&(c(),i(new Error(this.describeLaunchFailure(t))))},c=()=>{r("statusChange",s)};n("statusChange",s)})}describeLaunchFailure(t){let n=t.killReason?` (reason: ${t.killReason})`:"",r=t.error||t.result?.result||`status=${t.status}${n}`;return`Session ${t.name} [${t.id}] failed to start: ${r}`}onSessionTerminal(t){if(this.persistSession(t),this.lastWaitingEventTimestamps.delete(t.id),t.killReason==="done")return;if(t.status==="completed"){if(!this.shouldEmitTerminalWake(t))return;this.triggerAgentEvent(t);return}if(t.status==="failed"){if(!this.shouldEmitTerminalWake(t))return;let c=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`,p=ot(c,200);this.triggerFailedEvent(t,p);return}let n=`$${(t.costUsd??0).toFixed(2)}`,r=Le(t.duration),i={user:"by agent/user","idle-timeout":`idle ${E.idleTimeoutMinutes??15}min`,shutdown:"gateway shutdown",unknown:""}[t.killReason]||"",s=`Killed${i?` (${i})`:""}`;this.notifySession(t,`\u26D4 [${t.name}] ${s} | ${n} | ${r}`)}persistSession(t){this.store.hasRecordedSession(t.id)||this.metrics.recordSession(t),this.store.persistTerminal(t)}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(t){this.metrics.recordSession(t)}notifySession(t,n,r="notification"){this.dispatchSessionNotification(t,{label:r,userMessage:n,notifyUser:"always"})}dispatchSessionNotification(t,n){this.wakeDispatcher.dispatchSessionNotification(t,n)}runLobsterApproval(t,n){let r=JSON.stringify({session_id:t.id,session_name:t.name,plan_summary:n}),o=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"run",pipeline:Zl,argsJson:r,timeoutMs:0})];pa("openclaw",o,{timeout:tf},(i,s,c)=>{if(i){console.error(`[SessionManager] Lobster launch failed for session=${t.id}: ${i.message}`),this.notifySession(t,`\u{1F4CB} [${t.name}] Plan ready \u2014 Lobster gate failed, please review manually:
89
+ ${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved){let n=this.harness.planApprovalToolNames;if(r=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below,${n.length>0?` then call ${n.join(" or ")} again to re-submit for approval.`:" then re-submit your revised plan for approval."} Do NOT start implementing yet.]
50
90
 
51
- ${ot(n,800)}`);return}let p=typeof s=="string"?s:String(s??""),f=typeof c=="string"?c:String(c??""),T=nf(`${p}
52
- ${f}`);if(!T){let te=`${p}
53
- ${f}`.trim().substring(0,200);console.warn(`[SessionManager] Lobster response missing resume token for session=${t.id}: ${te}`)}T&&(t.lobsterResumeToken=T);let U=[`\u{1F4CB} [${t.name}] Plan ready for approval`,"",ot(n,1200),"",`Session: ${t.name} (${t.id})`,"",'To approve: reply "approve"',"To reject: reply with feedback"];this.notifySession(t,U.join(`
54
- `))})}resumeLobsterApproval(t,n){let r=n?3e4:1e4;return new Promise((o,i)=>{let s=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"resume",token:t,approve:n})];pa("openclaw",s,{timeout:r},c=>{c?(console.error(`[SessionManager] Lobster resume failed (approve=${n}): ${c.message}`),i(c)):o()})})}debounceWaitingEvent(t){let n=Date.now(),r=this.lastWaitingEventTimestamps.get(t);return r&&n-r<ef?!1:(this.lastWaitingEventTimestamps.set(t,n),!0)}originThreadLine(t){return t.originThreadId!=null?`Session origin thread: ${t.originThreadId}`:""}extractLastOutputLine(t){return t.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(t,n=1e3){let r=t.getOutput(20).join(`
55
- `);return r.length>n?Ci(r,n):r}triggerAgentEvent(t){let n=this.getOutputPreview(t),r=["Coding agent session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Output preview:",n,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${t.id}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.","3. Notify the user with a summary of what was done."].join(`
56
- `),o=`$${(t.costUsd??0).toFixed(2)}`,i=Le(t.duration),s=`\u2705 [${t.name}] Completed | ${o} | ${i}`;this.dispatchSessionNotification(t,{label:"completed",userMessage:s,wakeMessage:r,notifyUser:"always"})}triggerFailedEvent(t,n){let r=this.getOutputPreview(t),o=r.trim()?["","Output preview:",r]:[],i=["Coding agent session failed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Failure summary:",n,...o,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${t.id}', full=true) to inspect the full failure context.`,"2. If the failure is a launch/config issue or other recoverable error, relaunch the task now or continue it yourself.","3. Notify the user with the failure cause and the next action you are taking."].join(`
57
- `),s=`$${(t.costUsd??0).toFixed(2)}`,c=Le(t.duration),p=[`\u274C [${t.name}] Failed | ${s} | ${c}`,` \u26A0\uFE0F ${n}`].join(`
58
- `);this.dispatchSessionNotification(t,{label:"failed",userMessage:p,wakeMessage:i,notifyUser:"always"})}triggerWaitingForInputEvent(t){if(!this.debounceWaitingEvent(t.id))return;let n=this.getOutputPreview(t),r=t.pendingPlanApproval,o=r?`\u{1F4CB} [${t.name}] Plan ready for review:
91
+ ${t}`,this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan"}catch(s){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${gn(s)}`)}}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(r,this.harnessSessionId??""));else if(this.harnessHandle?.streamInput){let n=this.harness.buildUserMessage(r,this.harnessSessionId??"");async function*o(){yield n}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){return!this.turnInProgress||!this.harnessHandle?.interrupt?!1:(await this.harnessHandle.interrupt(),!0)}switchPermissionMode(t){this.pendingModeSwitch=t}get isActive(){return this._status==="starting"||this._status==="running"}kill(t){this.transitionToTerminal("killed",{reason:t})}complete(t="done"){this.transitionToTerminal("completed",{reason:t})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}resetIdleTimer(){if(!this.multiTurn)return;let t=(N.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",t,()=>{this._status==="running"&&this.kill("idle-timeout")})}teardown(){this.clearAllTimers(),this.completedAt||(this.completedAt=Date.now()),this.messageStream&&this.messageStream.end(),this.harnessHandle?.interrupt&&this.harnessHandle.interrupt().catch(t=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${gn(t)}`)}),this.abortController.abort()}transitionToTerminal(t,r={}){this.isActive&&(this.turnInProgress=!1,r.reason&&(this.killReason=r.reason),r.error!==void 0&&(this.error=r.error),this.completedAt=Date.now(),this.transition(t),this.teardown())}async consumeMessages(t){for await(let r of t){if(!this.isActive)break;if(this.resetIdleTimer(),r.type==="init")this.clearTimer("startup"),this.harnessSessionId=r.session_id,this._status==="starting"&&this.transition("running");else if(r.type==="text"){this.waitingForInputFired=!1,this.pendingPlanApproval||(this.lastTurnHadQuestion=!1),this.outputBuffer.push(r.text),this.outputBuffer.length>za&&this.outputBuffer.splice(0,this.outputBuffer.length-za);try{Mf(Ef(Of(),`openclaw-agent-${this.id}.txt`),r.text+`
92
+ `,"utf-8")}catch{}this.emit("output",this,r.text)}else if(r.type==="tool_use"){if(r.name==="Write"){let n=r.input;typeof n?.file_path=="string"&&n.file_path.includes("/.claude/plans/")&&(this.planFilePath=n.file_path)}this.harness.questionToolNames.includes(r.name)?(this.lastTurnHadQuestion=!0,this.currentPermissionMode==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0)):this.harness.planApprovalToolNames.includes(r.name)&&!this.planModeApproved&&(this.lastTurnHadQuestion=!0,this.pendingPlanApproval=!0),this.emit("toolUse",this,r.name,r.input)}else if(r.type==="permission_mode_change"){let n=this.currentPermissionMode;this.currentPermissionMode=r.mode,r.mode!=="plan"&&n==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0,this.lastTurnHadQuestion=!0)}else if(r.type==="result"){if(this.result={subtype:r.data.success?"success":"error",duration_ms:r.data.duration_ms,total_cost_usd:r.data.total_cost_usd,num_turns:r.data.num_turns,result:r.data.result,is_error:!r.data.success,session_id:r.data.session_id},this.costUsd=r.data.total_cost_usd,this.multiTurn&&this.messageStream&&r.data.success){this.resetIdleTimer(),this.currentPermissionMode==="plan"&&!this.pendingPlanApproval&&!this.planModeApproved&&(this.pendingPlanApproval=!0);let o=this.pendingPlanApproval||this.lastTurnHadQuestion,s=this.messageStream?.hasPending()===!0;this.turnInProgress=s,o&&!this.waitingForInputFired?(this.waitingForInputFired=!0,this.emit("turnEnd",this,!0)):s||o||(this.emit("turnEnd",this,!1),this.complete("done"))}else this.turnInProgress=!1,this.transitionToTerminal(r.data.success?"completed":"failed");this.lastTurnHadQuestion=!1}else r.type}}};import{existsSync as Ff,mkdirSync as Nf,readFileSync as Uf,readdirSync as Df,renameSync as Lf,statSync as Kf,unlinkSync as jf,writeFileSync as Qa}from"fs";import{homedir as Bf,tmpdir as Ya}from"os";import{dirname as Wf,join as In}from"path";function Gf(e){let t=e.OPENCLAW_HOME?.trim();return t||In(Bf(),".openclaw")}function Hf(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||In(Gf(e),"code-agent-sessions.json")}var Vf=new Set(["completed","failed","killed"]),qf=new Set(["running","completed","failed","killed"]),zf=1440*60*1e3;function Ja(e){return e instanceof Error?e.message:String(e)}function Qf(e){return!!e&&typeof e=="object"}function yn(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function Be(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function To(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Yf(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function Jf(e){return e==="default"||e==="plan"||e==="bypassPermissions"?e:void 0}function Xf(e){return e==="never"||e==="on-request"?e:void 0}function Zf(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function eg(e){if(typeof e=="string"&&qf.has(e))return e==="running"?"killed":e}function tg(e){if(!Qf(e))return;let t=yn(e.harnessSessionId);if(!t)return;let r=eg(e.status);if(r)return{sessionId:Be(e.sessionId),harnessSessionId:t,name:yn(e.name,t),prompt:yn(e.prompt),workdir:yn(e.workdir,"(unknown)"),model:Be(e.model),reasoningEffort:Yf(e.reasoningEffort),createdAt:To(e.createdAt),completedAt:To(e.completedAt),status:r,killReason:Zf(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:Be(e.originAgentId),originChannel:Be(e.originChannel),originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originSessionKey:Be(e.originSessionKey),outputPath:Be(e.outputPath),harness:Be(e.harness),currentPermissionMode:Jf(e.currentPermissionMode),codexApprovalPolicy:Xf(e.codexApprovalPolicy),worktreePath:Be(e.worktreePath),worktreeBranch:Be(e.worktreeBranch),worktreeStrategy:e.worktreeStrategy==="off"||e.worktreeStrategy==="manual"||e.worktreeStrategy==="ask"||e.worktreeStrategy==="auto-merge"||e.worktreeStrategy==="auto-pr"?e.worktreeStrategy:void 0,worktreeMerged:typeof e.worktreeMerged=="boolean"?e.worktreeMerged:void 0,worktreeMergedAt:Be(e.worktreeMergedAt),worktreePrUrl:Be(e.worktreePrUrl),worktreePrNumber:To(e.worktreePrNumber)}}var wn=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;indexPath;constructor(t={}){let r=t.env??process.env;this.indexPath=t.indexPath??Hf(r),r.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){try{let t=Uf(this.indexPath,"utf-8"),r=JSON.parse(t);if(!Array.isArray(r))return;let n=!1;for(let o of r){let s=tg(o);if(!s){n=!0;continue}this.persisted.set(s.harnessSessionId,s),s.sessionId&&this.idIndex.set(s.sessionId,s.harnessSessionId),s.name&&this.nameIndex.set(s.name,s.harnessSessionId)}n&&this.saveIndex()}catch{}}saveIndex(){try{Nf(Wf(this.indexPath),{recursive:!0});let t=this.indexPath+".tmp";Qa(t,JSON.stringify([...this.persisted.values()],null,2),"utf-8"),Lf(t,this.indexPath)}catch(t){console.warn(`[SessionStore] Failed to save session index: ${Ja(t)}`)}}markRunning(t){if(!t.harnessSessionId)return;let r={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.originalWorkdir??t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch??(t.worktreePath?se(t.worktreePath):void 0),worktreeStrategy:t.worktreeStrategy};this.persisted.set(r.harnessSessionId,r),this.idIndex.set(t.id,r.harnessSessionId),this.nameIndex.set(t.name,r.harnessSessionId),this.saveIndex()}hasRecordedSession(t){return this.idIndex.has(t)}persistTerminal(t){if(!t.harnessSessionId)return;let r;try{let o=In(Ya(),`openclaw-agent-${t.id}.txt`);if(Ff(o))r=o;else{let s=t.getOutput().join(`
93
+ `);s.length>0&&(Qa(o,s,"utf-8"),r=o)}}catch(o){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${Ja(o)}`)}let n={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.originalWorkdir??t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,completedAt:t.completedAt,status:t.status,killReason:t.killReason,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,outputPath:r,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch??(t.worktreePath?se(t.worktreePath):void 0),worktreeStrategy:t.worktreeStrategy};this.persisted.set(t.harnessSessionId,n),this.idIndex.set(t.id,t.harnessSessionId),this.nameIndex.set(t.name,t.harnessSessionId),this.saveIndex()}getLatestPersistedByName(t){let r,n=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=0;for(let a of this.persisted.values()){if(a.name!==t){i++;continue}let d=a.createdAt??Number.NEGATIVE_INFINITY,m=a.completedAt??Number.NEGATIVE_INFINITY;(d>n||d===n&&m>o||d===n&&m===o&&i>s)&&(r=a,n=d,o=m,s=i),i++}return r}resolveHarnessSessionId(t,r){if(r)return r;let n=this.idIndex.get(t);if(n&&this.persisted.has(n))return n;let o=this.getLatestPersistedByName(t);if(o)return o.harnessSessionId;if(this.persisted.has(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return t}getPersistedSession(t){let r=this.persisted.get(t);if(r)return r;let n=this.idIndex.get(t);return n?this.persisted.get(n):this.getLatestPersistedByName(t)}listPersistedSessions(){return[...this.persisted.values()].sort((t,r)=>(r.completedAt??0)-(t.completedAt??0))}cleanupTmpOutputFiles(t){try{let r=Ya(),n=Df(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let s=In(r,o),i=Kf(s).mtimeMs;t-i>zf&&jf(s)}catch{}}catch{}}evictOldestPersisted(t){let r=this.listPersistedSessions();if(r.length<=t)return;let n=r.slice(t);for(let o of n){this.persisted.delete(o.harnessSessionId);for(let[s,i]of this.idIndex)i===o.harnessSessionId&&this.idIndex.delete(s);for(let[s,i]of this.nameIndex)i===o.harnessSessionId&&this.nameIndex.delete(s)}this.saveIndex()}shouldGcActiveSession(t,r,n){return!t.completedAt||!Vf.has(t.status)?!1:r-t.completedAt>n}};var rg=new Set(["completed","failed","killed"]),Sn=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(t){let r=t.costUsd??0,n=t.status;this.metrics.totalCostUsd+=r;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+r),rg.has(n)&&this.metrics.sessionsByStatus[n]++,t.completedAt){let s=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=s,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||r>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:r,prompt:Rt(t.prompt,80)})}getMetrics(){return{totalCostUsd:this.metrics.totalCostUsd,costPerDay:new Map(this.metrics.costPerDay),sessionsByStatus:{...this.metrics.sessionsByStatus},totalLaunched:this.metrics.totalLaunched,totalDurationMs:this.metrics.totalDurationMs,sessionsWithDuration:this.metrics.sessionsWithDuration,mostExpensive:this.metrics.mostExpensive?{...this.metrics.mostExpensive}:null}}};import{execFile as ng}from"child_process";import{randomUUID as og}from"crypto";var Xa=3e4,sg=2e3,ig=2e4,xn=4,bn=class{pendingRetryTimers=new Map;constructor(){process.on("beforeExit",()=>{this.pendingRetryTimers.size>0&&console.warn(`[WakeDispatcher] beforeExit: ${this.pendingRetryTimers.size} pending retry timer(s) still active \u2014 event loop should stay alive, investigate if process exits prematurely.`)});let t=r=>{this.pendingRetryTimers.size!==0&&console.warn(`[WakeDispatcher] ${r}: ${this.pendingRetryTimers.size} pending retry timer(s) will be abandoned on hard exit.`)};process.once("SIGTERM",()=>t("SIGTERM")),process.once("SIGINT",()=>t("SIGINT"))}clearPendingRetries(){for(let t of this.pendingRetryTimers.values())for(let r of t)clearTimeout(r);this.pendingRetryTimers.clear()}clearRetryTimersForSession(t){let r=this.pendingRetryTimers.get(t);if(r){for(let n of r)clearTimeout(n);this.pendingRetryTimers.delete(t)}}getOriginSessionKey(t){let r=t.originSessionKey?.trim();return r||void 0}getOriginThreadId(t){let r=t.originThreadId;return r==null?void 0:String(r).trim()||void 0}parseNotificationRoute(t){let r=t.originChannel?.trim(),n=this.getOriginThreadId(t);if(r){let a=r.split("|").map(d=>d.trim()).filter(Boolean);if(a.length>=2){let[d,m,y]=a,f=y??m,c=y?m:void 0;if(d&&f){let w=f;if(d==="discord"&&/^\d+$/.test(f)){let k=(t.originSessionKey??"").match(/^agent:[^:]+:discord:(channel|user):/i);k?.[1]&&(w=`${k[1]}:${f}`)}return{channel:d,target:w,accountId:c,threadId:n??this.parseThreadIdFromSessionKey(t.originSessionKey)}}}}let o=this.getOriginSessionKey(t);if(!o)return;let s=o.match(/^agent:[^:]+:telegram:(?:direct|dm|group|channel):([^:]+)(?::topic:(\d+))?$/i);if(s?.[1])return{channel:"telegram",target:s[1],threadId:n??s[2]};let i=o.match(/^agent:[^:]+:discord:(direct|dm|channel|group):(\d+)$/i);if(i?.[2]){let a=i[1].toLowerCase(),d=i[2];return{channel:"discord",target:a==="direct"||a==="dm"?`user:${d}`:`channel:${d}`,threadId:n}}}parseThreadIdFromSessionKey(t){return t?t.match(/:topic:(\d+)$/)?.[1]:void 0}retryDelayMs(t){let r=Math.max(0,t-1),n=sg*2**r;return Math.min(n,ig)}executeWithRetries(t,r,n=1){let o=Date.now();console.info(`[WakeDispatcher] ${r.target} ${r.phase} started attempt ${n}/${xn} for ${r.label} session=${r.sessionId}`),console.info(`[WakeDispatcher] dispatching notification: label=${r.label} session=${r.sessionId}`),ng("openclaw",t,{timeout:Xa},(s,i,a)=>{let d=Date.now()-o;if(!s){console.info(`[WakeDispatcher] ${r.target} ${r.phase} completed attempt ${n}/${xn} for ${r.label} session=${r.sessionId} in ${d}ms`),r.onSuccess?.();return}let m=a?.trim()?` | stderr: ${a.trim()}`:"",y=`[WakeDispatcher] ${r.target} ${r.phase} failed`;if(n>=xn){console.error(`${y} after ${n} attempts for ${r.label} session=${r.sessionId} in ${d}ms: ${s.message}${m}`),r.onFinalFailure?.();return}let f=this.retryDelayMs(n);console.error(`${y} attempt ${n}/${xn} for ${r.label} session=${r.sessionId} in ${d}ms: ${s.message}${m}. Retrying in ${f}ms`);let c=setTimeout(()=>{let w=this.pendingRetryTimers.get(r.sessionId);w&&(w.delete(c),w.size===0&&this.pendingRetryTimers.delete(r.sessionId)),this.executeWithRetries(t,r,n+1)},f);this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(c)})}fireChatSendWithRetry(t,r,n,o,s,i=!1,a){let d=["gateway","call","chat.send","--expect-final","--timeout",String(Xa),"--params",JSON.stringify({sessionKey:t,message:r,deliver:i,idempotencyKey:og()})];this.executeWithRetries(d,{label:n,sessionId:o,target:"chat.send",phase:s,onFinalFailure:a})}fireDirectNotificationWithRetry(t,r,n,o,s,i,a){let d=["message","send","--channel",t.channel,"--target",t.target,"--message",r];if(t.accountId&&d.push("--account",t.accountId),t.threadId&&d.push("--thread-id",t.threadId),s&&t.channel==="telegram"){let m=s.map(y=>y.map(f=>({text:f.label,callback_data:f.callbackData})));d.push("--buttons",JSON.stringify(m))}this.executeWithRetries(d,{label:n,sessionId:o,target:"message.send",phase:"notify",onSuccess:a,onFinalFailure:i})}fireSystemEventWithRetry(t,r,n,o,s,i){let a=["system","event","--text",t,"--mode","now"];this.executeWithRetries(a,{label:r,sessionId:n,target:"system.event",phase:o,onSuccess:i,onFinalFailure:s})}sendUserNotification(t,r,n,o,s,i,a){let d=this.parseNotificationRoute(t);if(!d){this.fireSystemEventWithRetry(r,`${n}-notify-system`,o,"notify",i,a);return}this.fireDirectNotificationWithRetry(d,r,`${n}-notify`,o,s,()=>{this.fireSystemEventWithRetry(r,`${n}-notify-fallback`,o,"notify",i,a)},a)}dispatchSessionNotification(t,r){let n=this.getOriginSessionKey(t),o=r.wakeMessageOnNotifySuccess!=null||r.wakeMessageOnNotifyFailed!=null,s=r.notifyUser??(r.wakeMessage?"on-wake-fallback":"always"),i=r.userMessage?.trim(),a=r.wakeMessage?.trim(),d=r.buttons;if(o){let m=r.wakeMessageOnNotifySuccess?.trim(),y=r.wakeMessageOnNotifyFailed?.trim(),f=S=>{if(S){if(!n){this.fireSystemEventWithRetry(S,`${r.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(n,S,`${r.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(S,`${r.label}-wake-fallback`,t.id,"wake")})}},c=m?()=>f(m):void 0,w=y?()=>{r.onUserNotifyFailed?.(),f(y)}:r.onUserNotifyFailed;i?this.sendUserNotification(t,i,r.label,t.id,d,w,c):w&&w();return}if(s==="always"&&i&&this.sendUserNotification(t,i,r.label,t.id,d,r.onUserNotifyFailed),!!a){if(!n){s==="on-wake-fallback"&&i&&this.sendUserNotification(t,i,r.label,t.id,d,r.onUserNotifyFailed),this.fireSystemEventWithRetry(a,`${r.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(n,a,`${r.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(a,`${r.label}-wake-fallback`,t.id,"wake")})}}};var Ao=new Set(["completed","failed","killed"]),kn=new Set(["starting","running"]),ug=5e3;var Pn=class{sessions=new Map;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueues=new Map;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;constructor(t=20,r=50){this.maxSessions=t,this.maxPersistedSessions=r,this.store=new wn,this.metrics=new Sn,this.wakeDispatcher=new bn}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(t){let r=new Set([...this.sessions.values()].filter(o=>kn.has(o.status)).map(o=>o.name));if(!r.has(t))return t;let n=2;for(;r.has(`${t}-${n}`);)n++;return`${t}-${n}`}spawn(t,r={}){if([...this.sessions.values()].filter(A=>kn.has(A.status)).length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);let o=t.name||ra(t.prompt),s=this.uniqueName(o);s!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${s}" (active session with same name exists)`);let i,a,d=t.resumeSessionId??t.resumeWorktreeFrom;if(d){let A=this.store.getPersistedSession(d);if(A&&(!t.worktreeStrategy&&A.worktreeStrategy&&(t.worktreeStrategy=A.worktreeStrategy),A.worktreePath))if(ag(A.worktreePath))console.info(`[SessionManager] Resuming with existing worktree: ${A.worktreePath}`),t.workdir=A.worktreePath,i=A.worktreePath,a=A.worktreeBranch??se(A.worktreePath);else if(A.worktreeBranch&&A.workdir)try{let ke=A.workdir;rn(ke);let ht=So(ke,A.worktreeBranch.replace(/^agent\//,""));console.info(`[SessionManager] Recreated worktree from branch ${A.worktreeBranch}: ${ht}`),t.workdir=ht,i=ht,a=A.worktreeBranch}catch(ke){console.warn(`[SessionManager] Failed to recreate worktree for resume: ${ke instanceof Error?ke.message:String(ke)}, using original workdir`),t.workdir=A.workdir}else console.warn(`[SessionManager] Worktree ${A.worktreePath} no longer exists and cannot be recreated, using original workdir`),t.workdir=A.workdir}let m=t.workdir,y=!1,f=!1,w=!!!(t.resumeSessionId??t.resumeWorktreeFrom)&&N.defaultWorktreeStrategy&&N.defaultWorktreeStrategy!=="delegate"?N.defaultWorktreeStrategy:t.worktreeStrategy??N.defaultWorktreeStrategy;w&&!t.worktreeStrategy&&(t.worktreeStrategy=w);let S=!t.resumeSessionId&&!i&&w&&w!=="off";if(S&&ha(t.workdir))if(!ya())console.warn("[SessionManager] Insufficient space for worktree (< 100MB), skipping worktree creation"),y=!0;else try{i=So(t.workdir,s),m=i,a=se(i),console.log(`[SessionManager] Created worktree at ${i}`)}catch(A){y=!0,console.warn(`[SessionManager] Failed to create worktree: ${A instanceof Error?A.message:String(A)}, using original workdir`)}else S&&(f=!0,console.info(`[SessionManager] Worktree creation skipped for "${s}" \u2014 workdir is not a git repo`));let k=t.systemPrompt;if(i&&a){let A=["","You are working in a git worktree.",`Worktree path: ${i}`,`Branch: ${a}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${i}.`,`Do NOT edit files directly in ${t.workdir} (the original workspace).`,`If your task references files by absolute path under ${t.workdir}, rewrite those`,"paths relative to your current working directory. For example:",` "${t.workdir}/src/file.py" \u2192 use relative path "src/file.py"`,"","Commit all your file changes to this branch before finishing.","Use `git add` and `git commit`. Do NOT run `git checkout`, `git switch`, or `git reset --hard` as these will detach or corrupt the worktree HEAD."].join(`
94
+ `);k=(t.systemPrompt??"")+A}let x=t.harness??"claude-code",T=this,b,E=x==="claude-code"&&!t.canUseTool?async(A,de)=>{if(!b)throw new Error("canUseTool called before session ID was set");return T.handleAskUserQuestion(b,de)}:t.canUseTool,P=new hn({...t,workdir:m,systemPrompt:k,canUseTool:E},s);if(b=P.id,i&&(P.worktreePath=i,P.originalWorkdir=t.workdir,P.worktreeBranch=a),this.sessions.set(P.id,P),this.metrics.incrementLaunched(),P.on("statusChange",(A,de)=>{de==="running"&&P.harnessSessionId?this.store.markRunning(P):Ao.has(de)&&this.onSessionTerminal(P).catch(ke=>{console.error(`[SessionManager] onSessionTerminal threw for session ${P.id}:`,ke)})}),P.on("turnEnd",(A,de)=>{this.onTurnEnd(P,de)}),P.start(),r.notifyLaunch!==!1){let A=P.worktreePath?`${P.worktreePath} (worktree of ${P.originalWorkdir})`:P.workdir,de=`\u{1F680} [${P.name}] Launched | ${A} | ${P.model??"default"}`;this.notifySession(P,de,"launch")}if(y){let A=`\u26A0\uFE0F [${P.name}] Worktree creation failed \u2014 session running in original workdir`;this.wakeDispatcher.dispatchSessionNotification(P,{label:"worktree-creation-failed",userMessage:A})}return f&&this.wakeDispatcher.dispatchSessionNotification(P,{label:"worktree-skipped-not-git-remote",userMessage:`\u26A0\uFE0F [${P.name}] Worktree creation skipped \u2014 workdir is not a git repo with a remote. Running in original workdir.`}),P}async spawnAndAwaitRunning(t,r={}){let n=this.spawn(t,r);return await this.waitForRunningSession(n),n}async waitForRunningSession(t){if(t.status==="running")return;if(Ao.has(t.status))throw new Error(this.describeLaunchFailure(t));let r=t.on?.bind(t),n=t.off?.bind(t)??t.removeListener?.bind(t);if(!r||!n)throw new Error(`Session ${t.name} [${t.id}] did not expose lifecycle events during startup.`);await new Promise((o,s)=>{let i=(d,m)=>{if(m==="running"){a(),o();return}Ao.has(m)&&(a(),s(new Error(this.describeLaunchFailure(t))))},a=()=>{n("statusChange",i)};r("statusChange",i)})}describeLaunchFailure(t){let r=t.killReason?` (reason: ${t.killReason})`:"",n=t.error||t.result?.result||`status=${t.status}${r}`;return`Session ${t.name} [${t.id}] failed to start: ${n}`}async handleWorktreeStrategy(t){if(this.isAlreadyMerged(t.harnessSessionId))return console.info(`[SessionManager] handleWorktreeStrategy: session "${t.name}" already merged \u2014 skipping strategy handling`),!0;if(t.status!=="completed")return!1;let r=t.worktreeStrategy;if(!r||r==="off"||r==="manual")return!1;let n=t.originalWorkdir,o=t.worktreePath,s=se(o)??t.worktreeBranch;if(!s)return this.dispatchSessionNotification(t,{label:"worktree-no-branch-name",userMessage:`\u26A0\uFE0F [${t.name}] Cannot determine branch name for worktree ${o}. The worktree may have been removed or is in detached HEAD state. Manual cleanup may be needed.`}),!0;let i=t.worktreeBaseBranch??Ke(n);if(!nn(n,s,i))return this.dispatchSessionNotification(t,{label:"worktree-no-commits-ahead",userMessage:`\u26A0\uFE0F [${t.name}] Auto-merge: branch '${s}' has no commits ahead of '${i}'.
95
+ Changes may be uncommitted. Check worktree directory: ${o}`}),!0;let a=Ct(n,s,i);if(!a)return console.warn(`[SessionManager] Failed to get diff summary for ${s}, skipping merge-back`),!1;let d=a.commitMessages.slice(0,5).map(f=>`\u2022 ${f.hash} ${f.message} (${f.author})`).join(`
96
+ `),m=a.commits>5?`
97
+ ...and ${a.commits-5} more`:"",y=[`\u{1F500} Session ${t.name} completed with changes`,"",`Branch: ${s} \u2192 ${i}`,`Commits: ${a.commits} | Files: ${a.filesChanged} | +${a.insertions} / -${a.deletions}`,"",d+m].join(`
98
+ `);if(r==="ask"){gt(n,s);let f=a.commitMessages.slice(0,5).map(x=>`\u2022 ${x.hash} ${x.message} (${x.author})`),c=a.commits>5?`...and ${a.commits-5} more`:"",w=[`\u{1F500} Session \`${t.name}\` completed with changes \u2014 decision required`,"",`Branch: \`${s}\` \u2192 \`${i}\``,`Commits: ${a.commits} | Files: ${a.filesChanged} | +${a.insertions} / -${a.deletions}`,"",...f,...c?[c]:[]].join(`
99
+ `),S=[`[WORKTREE DECISION REQUIRED] Session "${t.name}" completed with changes.`,"",`Branch: ${s} \u2192 ${i}`,`Commits: ${a.commits} | Files: ${a.filesChanged} | +${a.insertions} / -${a.deletions}`,"",...f,...c?[c]:[],"","Present this to the user and wait for their choice:",` 1. Merge: agent_merge(session="${t.name}", base_branch="${i}")`,` 2. Open PR: agent_pr(session="${t.name}")`,"","Wait for user reply before acting."].join(`
100
+ `),k=[[{label:"\u2B07\uFE0F Merge locally",callbackData:`code-agent:merge:${t.id}`},{label:"\u{1F500} Create PR",callbackData:`code-agent:pr:${t.id}`}]];return this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-ask",userMessage:w,notifyUser:"always",buttons:k,wakeMessageOnNotifySuccess:"Worktree strategy buttons delivered to user. Wait for their button callback \u2014 do NOT act on this worktree yourself. The user has already received the full diff summary and decision buttons. Do NOT send a duplicate completion message.",wakeMessageOnNotifyFailed:S}),t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{pendingWorktreeDecisionSince:new Date().toISOString()}),!0}if(r==="delegate"){gt(n,s);let f=a.commitMessages.slice(0,5).map(x=>`\u2022 ${x.hash} ${x.message} (${x.author})`),c=a.commits>5?`...and ${a.commits-5} more`:"",w=`\u{1F916} Delegating merge decision for \`${s}\` to orchestrator`,S=t.prompt?t.prompt.slice(0,500):"(no prompt)",k=[`[DELEGATED WORKTREE DECISION] Session "${t.name}" completed with changes.`,"",`Branch: ${s} \u2192 ${i}`,`Commits: ${a.commits} | Files: ${a.filesChanged} | +${a.insertions} / -${a.deletions}`,"",...f,...c?[c]:[],"","Original task prompt (first 500 chars):",S,"","\u2501\u2501\u2501 DECISION REQUIRED \u2501\u2501\u2501","You are the delegated decision-maker for this worktree branch.","","MERGE if:"," - Changes match the original task scope"," - No breaking changes or architectural concerns",` \u2192 agent_merge(session="${t.name}", base_branch="${i}")`,"","OPEN PR if:"," - Changes are non-trivial and benefit from review"," - User has previously requested PRs for this kind of work"," - You are unsure \u2014 PRs are the safer default",` \u2192 agent_pr(session="${t.name}")`,"","ESCALATE to user if:"," - Scope is ambiguous or changes are risky"," - User has standing preferences that apply here","","Always notify the user briefly with what you decided and why."].join(`
101
+ `);return this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-delegate",userMessage:w,wakeMessage:k,notifyUser:"always"}),t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{pendingWorktreeDecisionSince:new Date().toISOString()}),!0}if(r==="auto-merge")return this.isAlreadyMerged(t.harnessSessionId)||await this.enqueueMerge(n,async()=>{if(this.isAlreadyMerged(t.harnessSessionId))return;let f=on(n,s,i);if(f.success){Mt(n,s),t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString()});let c=`\u2705 [${t.name}] Merged ${s} \u2192 ${i} locally. Branch cleaned up.`;f.stashPopConflict?c+=`
102
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${f.stashRef??"stash@{0}"}\` in ${n} to review stashed changes.`:f.stashed&&(c+=`
103
+ (Pre-existing changes on ${i} were auto-stashed and restored.)`),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-success",userMessage:c})}else if(f.conflictFiles&&f.conflictFiles.length>0){let c=["Resolve merge conflicts in the following files and commit the resolution:","",...f.conflictFiles.map(w=>`- ${w}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${s}"`].join(`
104
+ `);try{this.spawn({prompt:c,workdir:n,name:`${t.name}-conflict-resolver`,harness:"claude-code",permissionMode:"bypassPermissions",multiTurn:!0}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-conflict",userMessage:`\u26A0\uFE0F [${t.name}] Merge conflicts in ${f.conflictFiles.length} file(s) \u2014 spawned conflict resolver session`,buttons:[[{label:"\u{1F500} Open PR instead",callbackData:`code-agent:open-pr:${t.id}`}]]})}catch(w){this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-conflict-spawn-failed",userMessage:`\u274C [${t.name}] Merge conflicts detected, but failed to spawn resolver: ${w instanceof Error?w.message:String(w)}`})}}else{let c=f.dirtyError?`\u274C [${t.name}] Merge blocked: ${f.error}`:`\u274C [${t.name}] Merge failed: ${f.error??"unknown error"}`;this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-error",userMessage:c})}},()=>{this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-merge-queued",userMessage:`\u{1F550} [${t.name}] Merge queued \u2014 another merge for this repo is in progress. Will notify when complete.`})}),!0;if(r==="auto-pr"){if(!et()){console.warn("[SessionManager] GitHub CLI not available, falling back to 'ask' strategy");let c=[y,"","(GitHub CLI not available for auto-PR)","","Reply with one of the following:",`1. Merge to ${i}`].join(`
105
+ `);return this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-fallback-ask",userMessage:c,buttons:[[{label:"\u2705 Merge instead",callbackData:`code-agent:merge:${t.id}`}]]}),!0}if(!gt(n,s))return this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-push-failed",userMessage:`\u274C [${t.name}] Failed to push ${s} \u2014 cannot create/update PR`}),!0;let f=er(n,s);if(f.exists&&f.state==="open"){if(a&&a.commits>0){let c=["\u{1F504} **New commits pushed**","",`${a.commits} commits (+${a.insertions} / -${a.deletions})`,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
106
+ `),w=an(n,f.number,c);t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:f.url,worktreePrNumber:f.number}),w?this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-updated",userMessage:`\u2705 [${t.name}] PR updated: ${f.url} (+${a.commits} commits)`}):this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-updated-no-comment",userMessage:`\u26A0\uFE0F [${t.name}] Pushed to ${f.url} (comment failed)`})}else t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:f.url,worktreePrNumber:f.number}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-up-to-date",userMessage:`\u2139\uFE0F [${t.name}] PR up to date: ${f.url}`});return!0}else{if(f.exists&&f.state==="merged")return t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:f.url,worktreePrNumber:f.number}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-merged",userMessage:`\u2705 [${t.name}] PR already merged: ${f.url}`}),!0;if(f.exists&&f.state==="closed")return t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:f.url,worktreePrNumber:f.number}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-closed",userMessage:`\u26A0\uFE0F [${t.name}] PR was closed without merging: ${f.url}`,buttons:[[{label:"\u{1F195} New PR",callbackData:`code-agent:new-pr:${t.id}`},{label:"\u2705 Merge locally",callbackData:`code-agent:merge-locally:${t.id}`}]]}),!0;{let c=`[openclaw-code-agent] ${t.name}`,w=[`Automated changes from OpenClaw Code Agent session: ${t.name}`,"","## Summary",`${a.commits} commits, ${a.filesChanged} files changed (+${a.insertions} / -${a.deletions})`,"","## Commits",d+m,"","---","\u{1F916} Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
107
+ `),S=sn(n,s,i,c,w);if(S.success&&S.prUrl){let k=er(n,s);t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePrUrl:S.prUrl,worktreePrNumber:k.number}),this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-success",userMessage:`\u{1F500} [${t.name}] PR created: ${S.prUrl}`})}else this.wakeDispatcher.dispatchSessionNotification(t,{label:"worktree-pr-error",userMessage:`\u274C [${t.name}] Failed to create PR: ${S.error??"unknown error"}`});return!0}}}return!1}async onSessionTerminal(t){this.persistSession(t),this.lastWaitingEventTimestamps.delete(t.id);let r=!1;t.worktreePath&&t.originalWorkdir&&(r=await this.handleWorktreeStrategy(t));let n=!1;if(t.worktreePath&&t.originalWorkdir&&t.status==="failed"&&t.costUsd===0&&t.duration<3e4){let d=t.originalWorkdir,m=se(t.worktreePath);console.info(`[SessionManager] Early startup failure for "${t.name}" \u2014 auto-cleaning worktree (cost=$${t.costUsd.toFixed(2)}, duration=${t.duration}ms)`),br(d,t.worktreePath),m&&Mt(d,m),t.harnessSessionId&&this.updatePersistedSession(t.harnessSessionId,{worktreePath:void 0,worktreeBranch:void 0}),n=!0}let o=!!t.harnessSessionId&&!!this.store.getPersistedSession(t.harnessSessionId)?.pendingWorktreeDecisionSince;if(!n&&t.worktreePath&&t.originalWorkdir&&(o?console.info(`[SessionManager] Skipping worktree directory removal for "${t.name}" \u2014 pendingWorktreeDecision is set (ask-strategy button callback may still fire).`):br(t.originalWorkdir,t.worktreePath)),t.killReason==="done"){if(r||this.lastTurnCompleteMarkers.has(t.id)||!this.shouldEmitTerminalWake(t))return;this.triggerAgentEvent(t);return}if(t.status==="completed"){if(!this.shouldEmitTerminalWake(t))return;this.triggerAgentEvent(t);return}if(t.status==="failed"){if(!this.shouldEmitTerminalWake(t))return;let d=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`,m=Rt(d,200);this.triggerFailedEvent(t,m,n);return}let s=`$${(t.costUsd??0).toFixed(2)}`,i=qe(t.duration);if(t.killReason==="idle-timeout"){this.notifySession(t,`\u{1F4A4} [${t.name}] Idle timeout | ${s} | ${i}`),this.wakeDispatcher.clearRetryTimersForSession(t.id);return}let a=this.getStoppedStatusLabel(t.killReason);this.notifySession(t,`\u26D4 [${t.name}] ${a} | ${s} | ${i}`),this.wakeDispatcher.clearRetryTimersForSession(t.id)}getStoppedStatusLabel(t){switch(t){case"user":return"Stopped by user";case"shutdown":return"Stopped by shutdown";case"startup-timeout":return"Stopped by startup timeout";case"unknown":case void 0:return"Stopped unexpectedly";default:return"Stopped"}}persistSession(t){this.store.hasRecordedSession(t.id)||this.metrics.recordSession(t),this.store.persistTerminal(t)}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(t){this.metrics.recordSession(t)}notifySession(t,r,n="notification"){this.dispatchSessionNotification(t,{label:n,userMessage:r,notifyUser:"always"})}dispatchSessionNotification(t,r){this.wakeDispatcher.dispatchSessionNotification(t,r)}debounceWaitingEvent(t){let r=Date.now(),n=this.lastWaitingEventTimestamps.get(t);return n&&r-n<ug?!1:(this.lastWaitingEventTimestamps.set(t,r),!0)}originThreadLine(t){return t.originThreadId!=null?`Session origin thread: ${t.originThreadId}`:""}extractLastOutputLine(t){return t.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(t,r=1e3){let n=t.getOutput(20).join(`
108
+ `);return n.length>r?oa(n,r):n}triggerAgentEvent(t){let r=this.getOutputPreview(t),n=["Coding agent session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","(Note: a turn-complete wake may have already been sent for this session. If you already acted on it, treat this as confirmation \u2014 do not repeat actions.)","","Output preview:",r,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${t.id}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.","3. Notify the user with a summary of what was done."].join(`
109
+ `),o=`$${(t.costUsd??0).toFixed(2)}`,s=qe(t.duration),i=t.outputMode==="deliverable"?`\u{1F4C4} [${t.name}] Deliverable ready | ${o} | ${s}`:`\u2705 [${t.name}] Completed | ${o} | ${s}`;this.dispatchSessionNotification(t,{label:"completed",userMessage:i,wakeMessage:n,notifyUser:"always"})}triggerFailedEvent(t,r,n=!1){let o=this.getOutputPreview(t),s=o.trim()?["","Output preview:",o]:[],i=n?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[],a=["Coding agent session failed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),`Harness session ID: ${t.harnessSessionId??"unknown"}`,"","Failure summary:",r,...s,...i,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${t.id}', full=true) to inspect the full failure context.`,"2. If the failure is a runtime error (usage limit, API error, crash), resume with a different harness:",` agent_launch(resume_session_id='${t.harnessSessionId??"unknown"}', harness='claude-code', ...)`," Note: agent_respond also resumes, but uses the same harness (may hit the same error)."," If the failure is a launch/config issue, relaunch fresh with agent_launch(prompt=...).","3. Notify the user with the failure cause and the next action you are taking."].join(`
110
+ `),d=`$${(t.costUsd??0).toFixed(2)}`,m=qe(t.duration),y=[`\u274C [${t.name}] Failed | ${d} | ${m}`,` \u26A0\uFE0F ${r}`].join(`
111
+ `),f=[[{label:"\u{1F504} Retry",callbackData:`code-agent:retry:${t.id}`},{label:"\u{1F4CB} View output",callbackData:`code-agent:view-output:${t.id}`}]];this.dispatchSessionNotification(t,{label:"failed",userMessage:y,wakeMessage:a,notifyUser:"always",buttons:f})}triggerWaitingForInputEvent(t){if(!this.debounceWaitingEvent(t.id))return;let r=this.getOutputPreview(t),n=t.pendingPlanApproval,o=n?`\u{1F4CB} [${t.name}] Plan ready for review:
59
112
 
60
- ${n}
113
+ ${r}
61
114
 
62
- Reply to approve or provide feedback.`:`\u{1F514} [${t.name}] Waiting for input`,i;if(r){let s=E.planApproval??"delegate";if(s==="ask"){this.runLobsterApproval(t,n);return}else s==="delegate"?i=["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"Permission mode: plan \u2192 will switch to bypassPermissions on approval","","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${t.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",n,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Notify the user \u2501\u2501\u2501","After reading the full plan, use the message tool to send the user a summary that includes:","- What files/components will be changed","- Risk level (low/medium/high) and why","- Scope: does this match the original task or has it expanded?","- Any concerns or assumptions the plan makes","This message creates accountability \u2014 you cannot approve blindly.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","You are the delegated decision-maker. Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- You have sent the user the summary message","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,"If escalating: tell the user you need their decision and WAIT for his explicit response.",`To request changes: agent_respond(session='${t.id}', message='<your feedback>') \u2014 do NOT set approve=true. The agent will revise the plan.`].join(`
115
+ Reply to approve or provide feedback.`:`\u2753 [${t.name}] Waiting for input`,s=n?N.planApproval??"delegate":void 0,i;if(n){let d=s??"delegate";d==="delegate"?i=["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"Permission mode: plan \u2192 will switch to bypassPermissions on approval","","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${t.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",r,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Notify the user \u2501\u2501\u2501","After reading the full plan, use the message tool to send the user a summary that includes:","- What files/components will be changed","- Risk level (low/medium/high) and why","- Scope: does this match the original task or has it expanded?","- Any concerns or assumptions the plan makes","This message creates accountability \u2014 you cannot approve blindly.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","You are the delegated decision-maker. Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- You have sent the user the summary message","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,"If escalating: tell the user you need their decision and WAIT for his explicit response.",`To request changes: agent_respond(session='${t.id}', message='<your feedback>') \u2014 do NOT set approve=true. The agent will revise the plan.`].join(`
116
+ `):d==="ask"?i=["[USER APPROVAL REQUESTED] Coding agent session has finished its plan. The user has been notified via Telegram and must approve directly.",`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"","DO NOT approve this plan yourself. Wait for the user's explicit approval or rejection.","Once the user responds, forward their decision:",` To approve: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,` To request changes: agent_respond(session='${t.id}', message='<user feedback>')`,"","Preview (truncated):",r].join(`
63
117
  `):i=["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`].join(`
64
- `)}else i=[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 forward the agent's EXACT question to the user. Do NOT add your own analysis, commentary, or interpretation. Do NOT "nudge" or "poke" the session.]`,"",`${t.multiTurn?"Multi-turn session":"Session"} is waiting for input.`,`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"","Last output:",n,"",`Use agent_respond(session='${t.id}', message='...') to send a reply, or agent_output(session='${t.id}', full: true) to see full context before deciding.`].join(`
65
- `);this.dispatchSessionNotification(t,{label:r?"plan-approval":"waiting",userMessage:o,wakeMessage:i,notifyUser:r?"always":"on-wake-fallback"})}onTurnEnd(t,n){if(n||t.pendingPlanApproval){this.triggerWaitingForInputEvent(t);return}this.shouldEmitTurnCompleteWake(t)&&this.triggerTurnCompleteEventWithSignal(t)}shouldEmitTurnCompleteWake(t){let n=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===n?!1:(this.lastTurnCompleteMarkers.set(t.id,n),!0)}shouldEmitTerminalWake(t){let n=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===n?!1:(this.lastTerminalWakeMarkers.set(t.id,n),!0)}triggerTurnCompleteEventWithSignal(t){let n=this.getOutputPreview(t),r=Dn(n),o=`$${(t.costUsd??0).toFixed(2)}`,i=r?"yes":"no",s=`\u{1F504} [${t.name}] Turn done | ${o} | Waiting input: ${i}`,c=["Coding agent session turn ended.",`Name: ${t.name}`,`ID: ${t.id}`,`Status: ${t.status}`,"",`Looks like waiting for user input: ${i}`,"","Last output (~20 lines):",n,...this.originThreadLine(t)?["",this.originThreadLine(t)]:[]].join(`
66
- `);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:s,wakeMessage:c,notifyUser:"always"})}resolve(t){let n=this.sessions.get(t);if(n)return n;let r=[...this.sessions.values()].filter(i=>i.name===t);if(r.length===0)return;let o=r.filter(i=>Jn.has(i.status));return o.length>0?o.sort((i,s)=>s.startedAt-i.startedAt)[0]:r.sort((i,s)=>s.startedAt-i.startedAt)[0]}get(t){return this.sessions.get(t)}list(t){let n=[...this.sessions.values()];return t&&t!=="all"&&(n=n.filter(r=>r.status===t)),n.sort((r,o)=>o.startedAt-r.startedAt)}kill(t,n){let r=this.sessions.get(t);return r?(r.kill(n??"user"),!0):!1}killAll(t="user"){for(let n of this.sessions.values())Jn.has(n.status)&&this.kill(n.id,t);this.wakeDispatcher.clearPendingRetries()}resolveHarnessSessionId(t){let n=this.resolve(t);return this.store.resolveHarnessSessionId(t,n?.harnessSessionId)}getPersistedSession(t){return this.store.getPersistedSession(t)}listPersistedSessions(){return this.store.listPersistedSessions()}cleanup(){let t=Date.now(),n=(E.sessionGcAgeMinutes??1440)*6e4;for(let[r,o]of this.sessions)this.store.shouldGcActiveSession(o,t,n)&&(this.persistSession(o),this.sessions.delete(r),this.lastWaitingEventTimestamps.delete(r),this.lastTurnCompleteMarkers.delete(r),this.lastTerminalWakeMarkers.delete(r));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}};function rO(e){let t=null,n=null;e.registerTool(r=>Pi(r),{optional:!1}),e.registerTool(r=>Mi(r),{optional:!1}),e.registerTool(r=>Ei(r),{optional:!1}),e.registerTool(r=>ki(r),{optional:!1}),e.registerTool(r=>$i(r),{optional:!1}),e.registerTool(r=>vi(r),{optional:!1}),Ni(e),Ui(e),_i(e),Li(e),Ki(e),Di(e),ji(e),e.registerService({id:"openclaw-code-agent",start:r=>{let o=e.pluginConfig??e.getConfig?.()??{};Ti(o),t=new Xn(E.maxSessions,E.maxPersistedSessions),Gr(t),n=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{t&&t.killAll("shutdown"),n&&clearInterval(n),n=null,t=null,Gr(null)}})}export{rO as register};
118
+ `)}else i=[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 forward the agent's EXACT question to the user. Do NOT add your own analysis, commentary, or interpretation. Do NOT "nudge" or "poke" the session.]`,"",`${t.multiTurn?"Multi-turn session":"Session"} is waiting for input.`,`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"","Last output:",r,"",`Use agent_respond(session='${t.id}', message='...') to send a reply, or agent_output(session='${t.id}', full: true) to see full context before deciding.`].join(`
119
+ `);let a=n&&s==="ask"?[[{label:"\u2705 Approve",callbackData:`code-agent:approve:${t.id}`},{label:"\u274C Reject",callbackData:`code-agent:reject:${t.id}`},{label:"\u270F\uFE0F Revise",callbackData:`code-agent:revise:${t.id}`}]]:n?void 0:[[{label:"\u{1F4AC} Reply",callbackData:`code-agent:reply:${t.id}`}]];n&&s==="ask"?this.dispatchSessionNotification(t,{label:"plan-approval",userMessage:o,notifyUser:"always",buttons:a,wakeMessageOnNotifySuccess:"Plan approval buttons delivered to user. Wait for their button callback \u2014 do NOT approve or reject this plan yourself.",wakeMessageOnNotifyFailed:i}):this.dispatchSessionNotification(t,{label:n?"plan-approval":"waiting",userMessage:o,wakeMessage:i,notifyUser:"always",buttons:a})}onTurnEnd(t,r){if(r||t.pendingPlanApproval){this.triggerWaitingForInputEvent(t);return}if(t.worktreeStrategy==="ask"||t.worktreeStrategy==="delegate"){console.info(`[SessionManager] Suppressing turn-complete wake for session ${t.id} (worktreeStrategy=${t.worktreeStrategy}) \u2014 worktree notification will follow.`);return}this.shouldEmitTurnCompleteWake(t)&&this.triggerTurnCompleteEventWithSignal(t)}shouldEmitTurnCompleteWake(t){let r=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===r?(console.info(`[SessionManager] shouldEmitTurnCompleteWake: debounced for session ${t.id} (marker unchanged: ${r})`),!1):(this.lastTurnCompleteMarkers.set(t.id,r),!0)}shouldEmitTerminalWake(t){let r=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===r?!1:(this.lastTerminalWakeMarkers.set(t.id,r),!0)}triggerTurnCompleteEventWithSignal(t){console.info(`[SessionManager] turn-complete wake dispatching for session ${t.id} (turns=${t.result?.num_turns??0}, strategy=${t.worktreeStrategy??"none"})`);let r=this.getOutputPreview(t),n=mn(r),o=`$${(t.costUsd??0).toFixed(2)}`,s=n?"yes":"no",i=`\u23F8\uFE0F [${t.name}] Paused after turn | Auto-resumable | ${o} | Waiting input: ${s}`,a=["Coding agent session turn ended.",`Name: ${t.name}`,`ID: ${t.id}`,`Status: ${t.status}`,"",`Looks like waiting for user input: ${s}`,"","Last output (~20 lines):",r,...this.originThreadLine(t)?["",this.originThreadLine(t)]:[]].join(`
120
+ `);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:i,wakeMessage:a,notifyUser:"always",onUserNotifyFailed:()=>{console.warn(`[SessionManager] turn-complete delivery failed for session ${t.id} \u2014 firing terminal notification as fallback`),this.shouldEmitTerminalWake(t)&&this.triggerAgentEvent(t)}})}resolve(t){let r=this.sessions.get(t);if(r)return r;let n=[...this.sessions.values()].filter(s=>s.name===t);if(n.length===0)return;let o=n.filter(s=>kn.has(s.status));return o.length>0?o.sort((s,i)=>i.startedAt-s.startedAt)[0]:n.sort((s,i)=>i.startedAt-s.startedAt)[0]}get(t){return this.sessions.get(t)}list(t){let r=[...this.sessions.values()];return t&&t!=="all"&&(r=r.filter(n=>n.status===t)),r.sort((n,o)=>o.startedAt-n.startedAt)}kill(t,r){let n=this.sessions.get(t);return n?(n.kill(r??"user"),!0):!1}killAll(t="user"){for(let r of this.sessions.values())kn.has(r.status)&&this.kill(r.id,t)}resolveHarnessSessionId(t){let r=this.resolve(t);return this.store.resolveHarnessSessionId(t,r?.harnessSessionId)}getPersistedSession(t){return this.store.getPersistedSession(t)}isAlreadyMerged(t){return t?this.store.getPersistedSession(t)?.worktreeMerged===!0:!1}async enqueueMerge(t,r,n){let o=this.mergeQueues.get(t);o!==void 0&&n&&n();let s=(o??Promise.resolve()).catch(()=>{}).then(()=>r()),i=s.catch(()=>{});return this.mergeQueues.set(t,i),i.finally(()=>{this.mergeQueues.get(t)===i&&this.mergeQueues.delete(t)}),s}updatePersistedSession(t,r){let n=this.store.getPersistedSession(t);return n?(Object.assign(n,r),this.store.saveIndex(),!0):!1}listPersistedSessions(){return this.store.listPersistedSessions()}remindStaleDecisions(){let r=Date.now();for(let n of this.store.listPersistedSessions()){if(!n.pendingWorktreeDecisionSince||n.worktreeMerged||n.worktreePrUrl)continue;let o=r-new Date(n.pendingWorktreeDecisionSince).getTime();if(o<36e5||n.lastWorktreeReminderAt&&r-new Date(n.lastWorktreeReminderAt).getTime()<36e5)continue;let s=Math.floor(o/(3600*1e3)),i=[`\u23F0 Reminder: branch \`${n.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${n.name} | Pending: ${s}h`,"",`agent_merge(session="${n.name}") or agent_pr(session="${n.name}") or agent_worktree_cleanup() to resolve.`].join(`
121
+ `);try{this.sendReminderNotification(n,i)}catch(a){console.warn(`[SessionManager] Failed to send stale-decision reminder for session ${n.name}: ${a instanceof Error?a.message:String(a)}`)}this.updatePersistedSession(n.harnessSessionId,{lastWorktreeReminderAt:new Date().toISOString()})}}sendReminderNotification(t,r){let n={id:t.harnessSessionId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey};this.wakeDispatcher.dispatchSessionNotification(n,{label:`worktree-stale-reminder-${t.name}`,userMessage:r,notifyUser:"always",buttons:[[{label:"\u2B07\uFE0F Merge locally",callbackData:`code-agent:merge:${t.harnessSessionId}`},{label:"\u{1F500} Create PR",callbackData:`code-agent:open-pr:${t.harnessSessionId}`}]]})}async handleAskUserQuestion(t,r){let o=this.sessions.get(t);if(!o)throw new Error(`Session "${t}" not found for AskUserQuestion intercept`);let i=r?.questions??[];if(i.length===0)throw new Error("AskUserQuestion: no questions in input");let a=i[0],d=a.options??[],m=[`[ASK USER QUESTION] Session "${o.name}" has a question requiring user input.`,"",`Question: ${a.question}`,...d.length>0?["Options:",...d.map((c,w)=>` ${w+1}. ${c.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${o.id}", message="<answer>") with their answer.`].join(`
122
+ `),y;d.length>0&&(y=[d.map((c,w)=>({label:c.label,callbackData:`code-agent:question-answer:${o.id}:${w}`}))]);let f=[`\u2753 [${o.name}] ${a.question}`].join(`
123
+ `);return new Promise((c,w)=>{let S=setTimeout(()=>{this.pendingAskUserQuestions.delete(t),w(new Error(`AskUserQuestion timed out after 600s for session "${o.name}"`))},6e5);this.pendingAskUserQuestions.set(t,{resolve:c,reject:w,questions:i,timeoutHandle:S}),this.wakeDispatcher.dispatchSessionNotification(o,{label:"ask-user-question",userMessage:f,notifyUser:"always",buttons:y,wakeMessageOnNotifySuccess:"AskUserQuestion buttons delivered to user. Await their selection \u2014 do NOT answer this question yourself.",wakeMessageOnNotifyFailed:m})})}resolveAskUserQuestion(t,r){let n=this.pendingAskUserQuestions.get(t);if(!n){console.warn(`[SessionManager] resolveAskUserQuestion: no pending question for session "${t}"`);return}clearTimeout(n.timeoutHandle),this.pendingAskUserQuestions.delete(t);let o=n.questions[0],s=o.options??[],i=s[r];if(!i){n.reject(new Error(`AskUserQuestion: invalid option index ${r} (${s.length} options available)`));return}n.resolve({behavior:"allow",updatedInput:{questions:n.questions,answers:{[o.question]:i.label}}})}cleanup(){let t=Date.now();this.remindStaleDecisions();let r=(N.sessionGcAgeMinutes??1440)*6e4;for(let[n,o]of this.sessions)this.store.shouldGcActiveSession(o,t,r)&&(this.persistSession(o),this.sessions.delete(n),this.lastWaitingEventTimestamps.delete(n),this.lastTurnCompleteMarkers.delete(n),this.lastTerminalWakeMarkers.delete(n));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}};function mg(e){let t=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"1",10)||1,r=t*60*60*1e3,n=Date.now()-r,o=new Set,s=process.env.OPENCLAW_WORKTREE_DIR??N.worktreeDir;if(s)o.add(s);else for(let a of e.listPersistedSessions())if(a.workdir)try{let d=pg("git",["rev-parse","--show-toplevel"],{cwd:a.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();d&&o.add(Za(d,".worktrees"))}catch{}if(o.size===0)return;let i=0;for(let a of o)try{let d=cg(a);for(let m of d){if(!m.startsWith("openclaw-worktree-"))continue;let y=Za(a,m);try{let f=dg(y);if(!f.isDirectory()||f.mtimeMs>n)continue;lg(y,{recursive:!0,force:!0}),i++}catch(f){console.warn(`[index] Failed to clean up orphaned worktree ${y}: ${f instanceof Error?f.message:String(f)}`)}}}catch{}i>0&&console.info(`[index] Cleaned up ${i} orphaned worktree(s) at startup (age > ${t}h)`)}function oC(e){let t=null,r=null;e.registerTool(n=>ea(n),{optional:!1}),e.registerTool(n=>aa(n),{optional:!1}),e.registerTool(n=>ua(n),{optional:!1}),e.registerTool(n=>Zr(n),{optional:!1}),e.registerTool(n=>da(n),{optional:!1}),e.registerTool(n=>la(n),{optional:!1}),e.registerTool(n=>cn(n),{optional:!1}),e.registerTool(n=>kr(n),{optional:!1}),e.registerTool(n=>Ia(n),{optional:!1}),e.registerTool(n=>wa(n),{optional:!1}),e.registerInteractiveHandler(Sa()),xa(e),ba(e),ka(e),Pa(e),Ta(e),Aa(e),$a(e),e.registerService({id:"openclaw-code-agent",start:n=>{let o=e.pluginConfig??e.getConfig?.()??{};Yi(o),t=new Pn(N.maxSessions,N.maxPersistedSessions),ho(t),mg(t),r=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{t&&t.killAll("shutdown"),r&&clearInterval(r),r=null,t=null,ho(null)}})}export{oC as register};