openclaw-code-agent 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,59 +1,27 @@
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
- (no output yet)
12
- ${t.join(`
13
- `)}`:`
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:
1
+ var Fg=Object.defineProperty;var u=(t,e)=>()=>(t&&(e=t(t=0)),e);var lo=(t,e)=>{for(var r in e)Fg(t,r,{get:e[r],enumerable:!0})};var Me={};lo(Me,{HasPropertyKey:()=>uo,IsArray:()=>pe,IsAsyncIterator:()=>$s,IsBigInt:()=>un,IsBoolean:()=>Ot,IsDate:()=>pr,IsFunction:()=>Es,IsIterator:()=>Os,IsNull:()=>Ds,IsNumber:()=>Ge,IsObject:()=>j,IsRegExp:()=>pn,IsString:()=>Q,IsSymbol:()=>Ns,IsUint8Array:()=>Dt,IsUndefined:()=>ce});function uo(t,e){return e in t}function $s(t){return j(t)&&!pe(t)&&!Dt(t)&&Symbol.asyncIterator in t}function pe(t){return Array.isArray(t)}function un(t){return typeof t=="bigint"}function Ot(t){return typeof t=="boolean"}function pr(t){return t instanceof globalThis.Date}function Es(t){return typeof t=="function"}function Os(t){return j(t)&&!pe(t)&&!Dt(t)&&Symbol.iterator in t}function Ds(t){return t===null}function Ge(t){return typeof t=="number"}function j(t){return typeof t=="object"&&t!==null}function pn(t){return t instanceof globalThis.RegExp}function Q(t){return typeof t=="string"}function Ns(t){return typeof t=="symbol"}function Dt(t){return t instanceof globalThis.Uint8Array}function ce(t){return t===void 0}var De=u(()=>{});function Lg(t){return t.map(e=>po(e))}function Wg(t){return new Date(t.getTime())}function Bg(t){return new Uint8Array(t)}function Ug(t){return new RegExp(t.source,t.flags)}function Kg(t){let e={};for(let r of Object.getOwnPropertyNames(t))e[r]=po(t[r]);for(let r of Object.getOwnPropertySymbols(t))e[r]=po(t[r]);return e}function po(t){return pe(t)?Lg(t):pr(t)?Wg(t):Dt(t)?Bg(t):pn(t)?Ug(t):j(t)?Kg(t):t}function ee(t){return po(t)}var We=u(()=>{De()});function Er(t,e){return e===void 0?ee(t):ee({...e,...t})}var co=u(()=>{We()});var Fs=u(()=>{co();We()});function ml(t){return t!==null&&typeof t=="object"}function fl(t){return globalThis.Array.isArray(t)&&!globalThis.ArrayBuffer.isView(t)}function gl(t){return t===void 0}function hl(t){return typeof t=="number"}var Sl=u(()=>{});var yl=u(()=>{Sl()});var mo,kl=u(()=>{yl();(function(t){t.InstanceMode="default",t.ExactOptionalPropertyTypes=!1,t.AllowArrayObject=!1,t.AllowNaN=!1,t.AllowNullVoid=!1;function e(s,a){return t.ExactOptionalPropertyTypes?a in s:s[a]!==void 0}t.IsExactOptionalProperty=e;function r(s){let a=ml(s);return t.AllowArrayObject?a:a&&!fl(s)}t.IsObjectLike=r;function n(s){return r(s)&&!(s instanceof Date)&&!(s instanceof Uint8Array)}t.IsRecordLike=n;function o(s){return t.AllowNaN?hl(s):Number.isFinite(s)}t.IsNumberLike=o;function i(s){let a=gl(s);return t.AllowNullVoid?a||s===null:a}t.IsVoidLike=i})(mo||(mo={}))});function Vg(t){return globalThis.Object.freeze(t).map(e=>cn(e))}function qg(t){let e={};for(let r of Object.getOwnPropertyNames(t))e[r]=cn(t[r]);for(let r of Object.getOwnPropertySymbols(t))e[r]=cn(t[r]);return globalThis.Object.freeze(e)}function cn(t){return pe(t)?Vg(t):pr(t)?t:Dt(t)?t:pn(t)?t:j(t)?qg(t):t}var vl=u(()=>{De()});function g(t,e){let r=e!==void 0?{...e,...t}:t;switch(mo.InstanceMode){case"freeze":return cn(r);case"clone":return ee(r);default:return r}}var R=u(()=>{kl();vl();We()});var Nt=u(()=>{R()});var we,Pl=u(()=>{we=class extends Error{constructor(e){super(e)}}});var xt=u(()=>{Pl()});var ge,mt,xe,rt,P,mn=u(()=>{ge=Symbol.for("TypeBox.Transform"),mt=Symbol.for("TypeBox.Readonly"),xe=Symbol.for("TypeBox.Optional"),rt=Symbol.for("TypeBox.Hint"),P=Symbol.for("TypeBox.Kind")});var T=u(()=>{mn()});function Or(t){return j(t)&&t[mt]==="Readonly"}function Be(t){return j(t)&&t[xe]==="Optional"}function Ls(t){return N(t,"Any")}function Ws(t){return N(t,"Argument")}function ft(t){return N(t,"Array")}function cr(t){return N(t,"AsyncIterator")}function mr(t){return N(t,"BigInt")}function Ft(t){return N(t,"Boolean")}function gt(t){return N(t,"Computed")}function ht(t){return N(t,"Constructor")}function jg(t){return N(t,"Date")}function St(t){return N(t,"Function")}function yt(t){return N(t,"Integer")}function ie(t){return N(t,"Intersect")}function fr(t){return N(t,"Iterator")}function N(t,e){return j(t)&&P in t&&t[P]===e}function fo(t){return Ot(t)||Ge(t)||Q(t)}function He(t){return N(t,"Literal")}function ze(t){return N(t,"MappedKey")}function te(t){return N(t,"MappedResult")}function Gt(t){return N(t,"Never")}function Gg(t){return N(t,"Not")}function fn(t){return N(t,"Null")}function kt(t){return N(t,"Number")}function me(t){return N(t,"Object")}function gr(t){return N(t,"Promise")}function hr(t){return N(t,"Record")}function de(t){return N(t,"Ref")}function Bs(t){return N(t,"RegExp")}function Lt(t){return N(t,"String")}function gn(t){return N(t,"Symbol")}function Qe(t){return N(t,"TemplateLiteral")}function Hg(t){return N(t,"This")}function Ht(t){return j(t)&&ge in t}function Je(t){return N(t,"Tuple")}function hn(t){return N(t,"Undefined")}function L(t){return N(t,"Union")}function zg(t){return N(t,"Uint8Array")}function Qg(t){return N(t,"Unknown")}function Jg(t){return N(t,"Unsafe")}function Yg(t){return N(t,"Void")}function Xg(t){return j(t)&&P in t&&Q(t[P])}function Ye(t){return Ls(t)||Ws(t)||ft(t)||Ft(t)||mr(t)||cr(t)||gt(t)||ht(t)||jg(t)||St(t)||yt(t)||ie(t)||fr(t)||He(t)||ze(t)||te(t)||Gt(t)||Gg(t)||fn(t)||kt(t)||me(t)||gr(t)||hr(t)||de(t)||Bs(t)||Lt(t)||gn(t)||Qe(t)||Hg(t)||Je(t)||hn(t)||L(t)||zg(t)||Qg(t)||Jg(t)||Yg(t)||Xg(t)}var B=u(()=>{De();T()});var c={};lo(c,{IsAny:()=>xl,IsArgument:()=>Al,IsArray:()=>Rl,IsAsyncIterator:()=>Tl,IsBigInt:()=>Ml,IsBoolean:()=>Cl,IsComputed:()=>_l,IsConstructor:()=>$l,IsDate:()=>El,IsFunction:()=>Ol,IsImport:()=>oh,IsInteger:()=>Dl,IsIntersect:()=>Nl,IsIterator:()=>Fl,IsKind:()=>lu,IsKindOf:()=>E,IsLiteral:()=>yn,IsLiteralBoolean:()=>ih,IsLiteralNumber:()=>Wl,IsLiteralString:()=>Ll,IsLiteralValue:()=>Bl,IsMappedKey:()=>Ul,IsMappedResult:()=>Kl,IsNever:()=>Vl,IsNot:()=>ql,IsNull:()=>jl,IsNumber:()=>Gl,IsObject:()=>Hl,IsOptional:()=>nh,IsPromise:()=>zl,IsProperties:()=>go,IsReadonly:()=>rh,IsRecord:()=>Ql,IsRecursive:()=>sh,IsRef:()=>Jl,IsRegExp:()=>Yl,IsSchema:()=>Ie,IsString:()=>Xl,IsSymbol:()=>Zl,IsTemplateLiteral:()=>eu,IsThis:()=>tu,IsTransform:()=>ru,IsTuple:()=>nu,IsUint8Array:()=>iu,IsUndefined:()=>ou,IsUnion:()=>qs,IsUnionLiteral:()=>ah,IsUnknown:()=>su,IsUnsafe:()=>au,IsVoid:()=>du,TypeGuardUnknownTypeError:()=>Us});function wl(t){try{return new RegExp(t),!0}catch{return!1}}function Ks(t){if(!Q(t))return!1;for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(r>=7&&r<=13||r===27||r===127)return!1}return!0}function Il(t){return Vs(t)||Ie(t)}function Sn(t){return ce(t)||un(t)}function J(t){return ce(t)||Ge(t)}function Vs(t){return ce(t)||Ot(t)}function G(t){return ce(t)||Q(t)}function eh(t){return ce(t)||Q(t)&&Ks(t)&&wl(t)}function th(t){return ce(t)||Q(t)&&Ks(t)}function bl(t){return ce(t)||Ie(t)}function rh(t){return j(t)&&t[mt]==="Readonly"}function nh(t){return j(t)&&t[xe]==="Optional"}function xl(t){return E(t,"Any")&&G(t.$id)}function Al(t){return E(t,"Argument")&&Ge(t.index)}function Rl(t){return E(t,"Array")&&t.type==="array"&&G(t.$id)&&Ie(t.items)&&J(t.minItems)&&J(t.maxItems)&&Vs(t.uniqueItems)&&bl(t.contains)&&J(t.minContains)&&J(t.maxContains)}function Tl(t){return E(t,"AsyncIterator")&&t.type==="AsyncIterator"&&G(t.$id)&&Ie(t.items)}function Ml(t){return E(t,"BigInt")&&t.type==="bigint"&&G(t.$id)&&Sn(t.exclusiveMaximum)&&Sn(t.exclusiveMinimum)&&Sn(t.maximum)&&Sn(t.minimum)&&Sn(t.multipleOf)}function Cl(t){return E(t,"Boolean")&&t.type==="boolean"&&G(t.$id)}function _l(t){return E(t,"Computed")&&Q(t.target)&&pe(t.parameters)&&t.parameters.every(e=>Ie(e))}function $l(t){return E(t,"Constructor")&&t.type==="Constructor"&&G(t.$id)&&pe(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function El(t){return E(t,"Date")&&t.type==="Date"&&G(t.$id)&&J(t.exclusiveMaximumTimestamp)&&J(t.exclusiveMinimumTimestamp)&&J(t.maximumTimestamp)&&J(t.minimumTimestamp)&&J(t.multipleOfTimestamp)}function Ol(t){return E(t,"Function")&&t.type==="Function"&&G(t.$id)&&pe(t.parameters)&&t.parameters.every(e=>Ie(e))&&Ie(t.returns)}function oh(t){return E(t,"Import")&&uo(t,"$defs")&&j(t.$defs)&&go(t.$defs)&&uo(t,"$ref")&&Q(t.$ref)&&t.$ref in t.$defs}function Dl(t){return E(t,"Integer")&&t.type==="integer"&&G(t.$id)&&J(t.exclusiveMaximum)&&J(t.exclusiveMinimum)&&J(t.maximum)&&J(t.minimum)&&J(t.multipleOf)}function go(t){return j(t)&&Object.entries(t).every(([e,r])=>Ks(e)&&Ie(r))}function Nl(t){return E(t,"Intersect")&&!(Q(t.type)&&t.type!=="object")&&pe(t.allOf)&&t.allOf.every(e=>Ie(e)&&!ru(e))&&G(t.type)&&(Vs(t.unevaluatedProperties)||bl(t.unevaluatedProperties))&&G(t.$id)}function Fl(t){return E(t,"Iterator")&&t.type==="Iterator"&&G(t.$id)&&Ie(t.items)}function E(t,e){return j(t)&&P in t&&t[P]===e}function Ll(t){return yn(t)&&Q(t.const)}function Wl(t){return yn(t)&&Ge(t.const)}function ih(t){return yn(t)&&Ot(t.const)}function yn(t){return E(t,"Literal")&&G(t.$id)&&Bl(t.const)}function Bl(t){return Ot(t)||Ge(t)||Q(t)}function Ul(t){return E(t,"MappedKey")&&pe(t.keys)&&t.keys.every(e=>Ge(e)||Q(e))}function Kl(t){return E(t,"MappedResult")&&go(t.properties)}function Vl(t){return E(t,"Never")&&j(t.not)&&Object.getOwnPropertyNames(t.not).length===0}function ql(t){return E(t,"Not")&&Ie(t.not)}function jl(t){return E(t,"Null")&&t.type==="null"&&G(t.$id)}function Gl(t){return E(t,"Number")&&t.type==="number"&&G(t.$id)&&J(t.exclusiveMaximum)&&J(t.exclusiveMinimum)&&J(t.maximum)&&J(t.minimum)&&J(t.multipleOf)}function Hl(t){return E(t,"Object")&&t.type==="object"&&G(t.$id)&&go(t.properties)&&Il(t.additionalProperties)&&J(t.minProperties)&&J(t.maxProperties)}function zl(t){return E(t,"Promise")&&t.type==="Promise"&&G(t.$id)&&Ie(t.item)}function Ql(t){return E(t,"Record")&&t.type==="object"&&G(t.$id)&&Il(t.additionalProperties)&&j(t.patternProperties)&&(e=>{let r=Object.getOwnPropertyNames(e.patternProperties);return r.length===1&&wl(r[0])&&j(e.patternProperties)&&Ie(e.patternProperties[r[0]])})(t)}function sh(t){return j(t)&&rt in t&&t[rt]==="Recursive"}function Jl(t){return E(t,"Ref")&&G(t.$id)&&Q(t.$ref)}function Yl(t){return E(t,"RegExp")&&G(t.$id)&&Q(t.source)&&Q(t.flags)&&J(t.maxLength)&&J(t.minLength)}function Xl(t){return E(t,"String")&&t.type==="string"&&G(t.$id)&&J(t.minLength)&&J(t.maxLength)&&eh(t.pattern)&&th(t.format)}function Zl(t){return E(t,"Symbol")&&t.type==="symbol"&&G(t.$id)}function eu(t){return E(t,"TemplateLiteral")&&t.type==="string"&&Q(t.pattern)&&t.pattern[0]==="^"&&t.pattern[t.pattern.length-1]==="$"}function tu(t){return E(t,"This")&&G(t.$id)&&Q(t.$ref)}function ru(t){return j(t)&&ge in t}function nu(t){return E(t,"Tuple")&&t.type==="array"&&G(t.$id)&&Ge(t.minItems)&&Ge(t.maxItems)&&t.minItems===t.maxItems&&(ce(t.items)&&ce(t.additionalItems)&&t.minItems===0||pe(t.items)&&t.items.every(e=>Ie(e)))}function ou(t){return E(t,"Undefined")&&t.type==="undefined"&&G(t.$id)}function ah(t){return qs(t)&&t.anyOf.every(e=>Ll(e)||Wl(e))}function qs(t){return E(t,"Union")&&G(t.$id)&&j(t)&&pe(t.anyOf)&&t.anyOf.every(e=>Ie(e))}function iu(t){return E(t,"Uint8Array")&&t.type==="Uint8Array"&&G(t.$id)&&J(t.minByteLength)&&J(t.maxByteLength)}function su(t){return E(t,"Unknown")&&G(t.$id)}function au(t){return E(t,"Unsafe")}function du(t){return E(t,"Void")&&t.type==="void"&&G(t.$id)}function lu(t){return j(t)&&P in t&&Q(t[P])&&!Zg.includes(t[P])}function Ie(t){return j(t)&&(xl(t)||Al(t)||Rl(t)||Cl(t)||Ml(t)||Tl(t)||_l(t)||$l(t)||El(t)||Ol(t)||Dl(t)||Nl(t)||Fl(t)||yn(t)||Ul(t)||Kl(t)||Vl(t)||ql(t)||jl(t)||Gl(t)||Hl(t)||zl(t)||Ql(t)||Jl(t)||Yl(t)||Xl(t)||Zl(t)||eu(t)||tu(t)||nu(t)||ou(t)||qs(t)||iu(t)||su(t)||au(t)||du(t)||lu(t))}var Us,Zg,uu=u(()=>{De();T();xt();Us=class extends we{},Zg=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"]});var js=u(()=>{B();uu();De()});var pu=u(()=>{});var cu=u(()=>{pu()});var Gs,kn,Hs,dh,nx,zt,Qt,mu,fu=u(()=>{Gs="(true|false)",kn="(0|[1-9][0-9]*)",Hs="(.*)",dh="(?!.*)",nx=`^${Gs}$`,zt=`^${kn}$`,Qt=`^${Hs}$`,mu=`^${dh}$`});var vn=u(()=>{fu()});var gu=u(()=>{});var hu=u(()=>{});var Su=u(()=>{gu();hu()});function yu(t,e){return t.includes(e)}function ku(t){return[...new Set(t)]}function ph(t,e){return t.filter(r=>e.includes(r))}function ch(t,e){return t.reduce((r,n)=>ph(r,n),e)}function vu(t){return t.length===1?t[0]:t.length>1?ch(t.slice(1),t[0]):[]}function Pu(t){let e=[];for(let r of t)e.push(...r);return e}var wu=u(()=>{});var Pn=u(()=>{wu()});function Jt(t){return g({[P]:"Any"},t)}var Iu=u(()=>{Nt();T()});var wn=u(()=>{Iu()});function Dr(t,e){return g({[P]:"Array",type:"array",items:t},e)}var bu=u(()=>{R();T()});var In=u(()=>{bu()});function xu(t){return g({[P]:"Argument",index:t})}var Au=u(()=>{R();T()});var zs=u(()=>{Au()});function Nr(t,e){return g({[P]:"AsyncIterator",type:"AsyncIterator",items:t},e)}var Ru=u(()=>{T();R()});var bn=u(()=>{Ru()});function Z(t,e,r){return g({[P]:"Computed",target:t,parameters:e},r)}var Tu=u(()=>{Nt();mn()});var Yt=u(()=>{Tu()});function mh(t,e){let{[e]:r,...n}=t;return n}function se(t,e){return e.reduce((r,n)=>mh(r,n),t)}var ho=u(()=>{});var Bt=u(()=>{ho()});function W(t){return g({[P]:"Never",not:{}},t)}var Mu=u(()=>{R();T()});var Ae=u(()=>{Mu()});var Cu=u(()=>{});function U(t){return g({[P]:"MappedResult",properties:t})}var Qs=u(()=>{R();T()});function Fr(t,e,r){return g({[P]:"Constructor",type:"Constructor",parameters:t,returns:e},r)}var _u=u(()=>{R();T()});var xn=u(()=>{_u()});function At(t,e,r){return g({[P]:"Function",type:"Function",parameters:t,returns:e},r)}var $u=u(()=>{R();T()});var Sr=u(()=>{$u()});function An(t,e){return g({[P]:"Union",anyOf:t},e)}var Js=u(()=>{R();T()});function fh(t){return t.some(e=>Be(e))}function Eu(t){return t.map(e=>Be(e)?gh(e):e)}function gh(t){return se(t,[xe])}function hh(t,e){return fh(t)?Ce(An(Eu(t),e)):An(Eu(t),e)}function Rt(t,e){return t.length===1?g(t[0],e):t.length===0?W(e):hh(t,e)}var Ou=u(()=>{R();T();Bt();Ae();Ut();Js();B()});var Du=u(()=>{});function q(t,e){return t.length===0?W(e):t.length===1?g(t[0],e):An(t,e)}var Nu=u(()=>{Ae();R();Js()});var he=u(()=>{Ou();Du();Nu()});function Sh(t){return t.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Ys(t,e,r){return t[e]===r&&t.charCodeAt(e-1)!==92}function Kt(t,e){return Ys(t,e,"(")}function Rn(t,e){return Ys(t,e,")")}function Fu(t,e){return Ys(t,e,"|")}function yh(t){if(!(Kt(t,0)&&Rn(t,t.length-1)))return!1;let e=0;for(let r=0;r<t.length;r++)if(Kt(t,r)&&(e+=1),Rn(t,r)&&(e-=1),e===0&&r!==t.length-1)return!1;return!0}function kh(t){return t.slice(1,t.length-1)}function vh(t){let e=0;for(let r=0;r<t.length;r++)if(Kt(t,r)&&(e+=1),Rn(t,r)&&(e-=1),Fu(t,r)&&e===0)return!0;return!1}function Ph(t){for(let e=0;e<t.length;e++)if(Kt(t,e))return!0;return!1}function wh(t){let[e,r]=[0,0],n=[];for(let i=0;i<t.length;i++)if(Kt(t,i)&&(e+=1),Rn(t,i)&&(e-=1),Fu(t,i)&&e===0){let s=t.slice(r,i);s.length>0&&n.push(Lr(s)),r=i+1}let o=t.slice(r);return o.length>0&&n.push(Lr(o)),n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"or",expr:n}}function Ih(t){function e(o,i){if(!Kt(o,i))throw new So("TemplateLiteralParser: Index must point to open parens");let s=0;for(let a=i;a<o.length;a++)if(Kt(o,a)&&(s+=1),Rn(o,a)&&(s-=1),s===0)return[i,a];throw new So("TemplateLiteralParser: Unclosed group parens in expression")}function r(o,i){for(let s=i;s<o.length;s++)if(Kt(o,s))return[i,s];return[i,o.length]}let n=[];for(let o=0;o<t.length;o++)if(Kt(t,o)){let[i,s]=e(t,o),a=t.slice(i,s+1);n.push(Lr(a)),o=s}else{let[i,s]=r(t,o),a=t.slice(i,s);a.length>0&&n.push(Lr(a)),o=s-1}return n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"and",expr:n}}function Lr(t){return yh(t)?Lr(kh(t)):vh(t)?wh(t):Ph(t)?Ih(t):{type:"const",const:Sh(t)}}function Wr(t){return Lr(t.slice(1,t.length-1))}var So,yo=u(()=>{xt();So=class extends we{}});function bh(t){return t.type==="or"&&t.expr.length===2&&t.expr[0].type==="const"&&t.expr[0].const==="0"&&t.expr[1].type==="const"&&t.expr[1].const==="[1-9][0-9]*"}function xh(t){return t.type==="or"&&t.expr.length===2&&t.expr[0].type==="const"&&t.expr[0].const==="true"&&t.expr[1].type==="const"&&t.expr[1].const==="false"}function Ah(t){return t.type==="const"&&t.const===".*"}function yr(t){return bh(t)||Ah(t)?!1:xh(t)?!0:t.type==="and"?t.expr.every(e=>yr(e)):t.type==="or"?t.expr.every(e=>yr(e)):t.type==="const"?!0:(()=>{throw new Xs("Unknown expression type")})()}function Lu(t){let e=Wr(t.pattern);return yr(e)}var Xs,Zs=u(()=>{yo();xt();Xs=class extends we{}});function*Wu(t){if(t.length===1)return yield*t[0];for(let e of t[0])for(let r of Wu(t.slice(1)))yield`${e}${r}`}function*Rh(t){return yield*Wu(t.expr.map(e=>[...Tn(e)]))}function*Th(t){for(let e of t.expr)yield*Tn(e)}function*Mh(t){return yield t.const}function*Tn(t){return t.type==="and"?yield*Rh(t):t.type==="or"?yield*Th(t):t.type==="const"?yield*Mh(t):(()=>{throw new ea("Unknown expression")})()}function ko(t){let e=Wr(t.pattern);return yr(e)?[...Tn(e)]:[]}var ea,ta=u(()=>{Zs();yo();xt();ea=class extends we{}});function V(t,e){return g({[P]:"Literal",const:t,type:typeof t},e)}var Bu=u(()=>{R();T()});var Ue=u(()=>{Bu()});function vo(t){return g({[P]:"Boolean",type:"boolean"},t)}var Uu=u(()=>{T();Nt()});var Po=u(()=>{Uu()});function Br(t){return g({[P]:"BigInt",type:"bigint"},t)}var Ku=u(()=>{T();Nt()});var Mn=u(()=>{Ku()});function nt(t){return g({[P]:"Number",type:"number"},t)}var Vu=u(()=>{R();T()});var kr=u(()=>{Vu()});function vt(t){return g({[P]:"String",type:"string"},t)}var qu=u(()=>{R();T()});var Ur=u(()=>{qu()});function*Ch(t){let e=t.trim().replace(/"|'/g,"");return e==="boolean"?yield vo():e==="number"?yield nt():e==="bigint"?yield Br():e==="string"?yield vt():yield(()=>{let r=e.split("|").map(n=>V(n.trim()));return r.length===0?W():r.length===1?r[0]:Rt(r)})()}function*_h(t){if(t[1]!=="{"){let e=V("$"),r=ra(t.slice(1));return yield*[e,...r]}for(let e=2;e<t.length;e++)if(t[e]==="}"){let r=Ch(t.slice(2,e)),n=ra(t.slice(e+1));return yield*[...r,...n]}yield V(t)}function*ra(t){for(let e=0;e<t.length;e++)if(t[e]==="$"){let r=V(t.slice(0,e)),n=_h(t.slice(e));return yield*[r,...n]}yield V(t)}function ju(t){return[...ra(t)]}var na=u(()=>{Ue();Po();Mn();kr();Ur();he();Ae()});function $h(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gu(t,e){return Qe(t)?t.pattern.slice(1,t.pattern.length-1):L(t)?`(${t.anyOf.map(r=>Gu(r,e)).join("|")})`:kt(t)?`${e}${kn}`:yt(t)?`${e}${kn}`:mr(t)?`${e}${kn}`:Lt(t)?`${e}${Hs}`:He(t)?`${e}${$h(t.const.toString())}`:Ft(t)?`${e}${Gs}`:(()=>{throw new oa(`Unexpected Kind '${t[P]}'`)})()}function ia(t){return`^${t.map(e=>Gu(e,"")).join("")}$`}var oa,sa=u(()=>{vn();T();xt();B();oa=class extends we{}});function vr(t){let r=ko(t).map(n=>V(n));return Rt(r)}var Hu=u(()=>{he();Ue();ta()});function wo(t,e){let r=Q(t)?ia(ju(t)):ia(t);return g({[P]:"TemplateLiteral",type:"string",pattern:r},e)}var zu=u(()=>{R();na();sa();De();T()});var Vt=u(()=>{Zs();ta();na();yo();sa();Hu();zu()});function Eh(t){return ko(t).map(r=>r.toString())}function Oh(t){let e=[];for(let r of t)e.push(...Ke(r));return e}function Dh(t){return[t.toString()]}function Ke(t){return[...new Set(Qe(t)?Eh(t):L(t)?Oh(t.anyOf):He(t)?Dh(t.const):kt(t)?["[number]"]:yt(t)?["[number]"]:[])]}var Io=u(()=>{Vt();B()});function Nh(t,e,r){let n={};for(let o of Object.getOwnPropertyNames(e))n[o]=Xt(t,Ke(e[o]),r);return n}function Fh(t,e,r){return Nh(t,e.properties,r)}function Qu(t,e,r){let n=Fh(t,e,r);return U(n)}var aa=u(()=>{ve();Io();Tt()});function Yu(t,e){return t.map(r=>Xu(r,e))}function Lh(t){return t.filter(e=>!Gt(e))}function Wh(t,e){return bo(Lh(Yu(t,e)))}function Bh(t){return t.some(e=>Gt(e))?[]:t}function Uh(t,e){return Rt(Bh(Yu(t,e)))}function Kh(t,e){return e in t?t[e]:e==="[number]"?Rt(t):W()}function Vh(t,e){return e==="[number]"?t:W()}function qh(t,e){return e in t?t[e]:W()}function Xu(t,e){return ie(t)?Wh(t.allOf,e):L(t)?Uh(t.anyOf,e):Je(t)?Kh(t.items??[],e):ft(t)?Vh(t.items,e):me(t)?qh(t.properties,e):W()}function da(t,e){return e.map(r=>Xu(t,r))}function Ju(t,e){return Rt(da(t,e))}function Xt(t,e,r){if(de(t)||de(e)){let n="Index types using Ref parameters require both Type and Key to be of TSchema";if(!Ye(t)||!Ye(e))throw new we(n);return Z("Index",[t,e])}return te(e)?Qu(t,e,r):ze(e)?Zu(t,e,r):g(Ye(e)?Ju(t,Ke(e)):Ju(t,e),r)}var la=u(()=>{R();xt();Yt();Ae();ot();he();Io();ua();aa();B()});function jh(t,e,r){return{[e]:Xt(t,[e],ee(r))}}function Gh(t,e,r){return e.reduce((n,o)=>({...n,...jh(t,o,r)}),{})}function Hh(t,e,r){return Gh(t,e.keys,r)}function Zu(t,e,r){let n=Hh(t,e,r);return U(n)}var ua=u(()=>{la();ve();We()});var Tt=u(()=>{ua();aa();Io();la()});function Kr(t,e){return g({[P]:"Iterator",type:"Iterator",items:t},e)}var ep=u(()=>{R();T()});var Cn=u(()=>{ep()});function zh(t){return globalThis.Object.keys(t).filter(e=>!Be(t[e]))}function Qh(t,e){let r=zh(t),n=r.length>0?{[P]:"Object",type:"object",required:r,properties:t}:{[P]:"Object",type:"object",properties:t};return g(n,e)}var H,tp=u(()=>{R();T();B();H=Qh});var Xe=u(()=>{tp()});function xo(t,e){return g({[P]:"Promise",type:"Promise",item:t},e)}var rp=u(()=>{R();T()});var Ao=u(()=>{rp()});function Jh(t){return g(se(t,[mt]))}function Yh(t){return g({...t,[mt]:"Readonly"})}function Xh(t,e){return e===!1?Jh(t):Yh(t)}function Ve(t,e){let r=e??!0;return te(t)?np(t,r):Xh(t,r)}var pa=u(()=>{R();T();Bt();ca();B()});function Zh(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Ve(t[n],e);return r}function eS(t,e){return Zh(t.properties,e)}function np(t,e){let r=eS(t,e);return U(r)}var ca=u(()=>{ve();pa()});var Pr=u(()=>{ca();pa()});function it(t,e){return g(t.length>0?{[P]:"Tuple",type:"array",items:t,additionalItems:!1,minItems:t.length,maxItems:t.length}:{[P]:"Tuple",type:"array",minItems:t.length,maxItems:t.length},e)}var op=u(()=>{R();T()});var Zt=u(()=>{op()});function ip(t,e){return t in e?st(t,e[t]):U(e)}function tS(t){return{[t]:V(t)}}function rS(t){let e={};for(let r of t)e[r]=V(r);return e}function nS(t,e){return yu(e,t)?tS(t):rS(e)}function oS(t,e){let r=nS(t,e);return ip(t,r)}function _n(t,e){return e.map(r=>st(t,r))}function iS(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=st(t,e[n]);return r}function st(t,e){let r={...e};return Be(e)?Ce(st(t,se(e,[xe]))):Or(e)?Ve(st(t,se(e,[mt]))):te(e)?ip(t,e.properties):ze(e)?oS(t,e.keys):ht(e)?Fr(_n(t,e.parameters),st(t,e.returns),r):St(e)?At(_n(t,e.parameters),st(t,e.returns),r):cr(e)?Nr(st(t,e.items),r):fr(e)?Kr(st(t,e.items),r):ie(e)?_e(_n(t,e.allOf),r):L(e)?q(_n(t,e.anyOf),r):Je(e)?it(_n(t,e.items??[]),r):me(e)?H(iS(t,e.properties),r):ft(e)?Dr(st(t,e.items),r):gr(e)?xo(st(t,e.item),r):e}function sS(t,e){let r={};for(let n of t)r[n]=st(n,e);return r}function sp(t,e,r){let n=Ye(t)?Ke(t):t,o=e({[P]:"MappedKey",keys:n}),i=sS(n,o);return H(i,r)}var ap=u(()=>{T();Bt();In();bn();xn();Sr();Tt();ot();Cn();Ue();Xe();Ut();Ao();Pr();Zt();he();Pn();Qs();B()});var ve=u(()=>{Cu();Qs();ap()});function aS(t){return g(se(t,[xe]))}function dS(t){return g({...t,[xe]:"Optional"})}function lS(t,e){return e===!1?aS(t):dS(t)}function Ce(t,e){let r=e??!0;return te(t)?dp(t,r):lS(t,r)}var ma=u(()=>{R();T();Bt();fa();B()});function uS(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Ce(t[n],e);return r}function pS(t,e){return uS(t.properties,e)}function dp(t,e){let r=pS(t,e);return U(r)}var fa=u(()=>{ve();ma()});var Ut=u(()=>{fa();ma()});function $n(t,e={}){let r=t.every(o=>me(o)),n=Ye(e.unevaluatedProperties)?{unevaluatedProperties:e.unevaluatedProperties}:{};return g(e.unevaluatedProperties===!1||Ye(e.unevaluatedProperties)||r?{...n,[P]:"Intersect",type:"object",allOf:t}:{...n,[P]:"Intersect",allOf:t},e)}var ga=u(()=>{R();T();B()});function cS(t){return t.every(e=>Be(e))}function mS(t){return se(t,[xe])}function lp(t){return t.map(e=>Be(e)?mS(e):e)}function fS(t,e){return cS(t)?Ce($n(lp(t),e)):$n(lp(t),e)}function bo(t,e={}){if(t.length===1)return g(t[0],e);if(t.length===0)return W(e);if(t.some(r=>Ht(r)))throw new Error("Cannot intersect transform types");return fS(t,e)}var up=u(()=>{T();R();Bt();Ae();Ut();ga();B()});var pp=u(()=>{});function _e(t,e){if(t.length===1)return g(t[0],e);if(t.length===0)return W(e);if(t.some(r=>Ht(r)))throw new Error("Cannot intersect transform types");return $n(t,e)}var cp=u(()=>{R();Ae();ga();B()});var ot=u(()=>{up();pp();cp()});function Mt(...t){let[e,r]=typeof t[0]=="string"?[t[0],t[1]]:[t[0].$id,t[1]];if(typeof e!="string")throw new we("Ref: $ref must be a string");return g({[P]:"Ref",$ref:e},r)}var mp=u(()=>{xt();R();T()});var wr=u(()=>{mp()});function gS(t,e){return Z("Awaited",[Z(t,e)])}function hS(t){return Z("Awaited",[Mt(t)])}function SS(t){return _e(fp(t))}function yS(t){return q(fp(t))}function kS(t){return Vr(t)}function fp(t){return t.map(e=>Vr(e))}function Vr(t,e){return g(gt(t)?gS(t.target,t.parameters):ie(t)?SS(t.allOf):L(t)?yS(t.anyOf):gr(t)?kS(t.item):de(t)?hS(t.$ref):t,e)}var gp=u(()=>{R();Yt();ot();he();wr();B()});var Ro=u(()=>{gp()});function hp(t){let e=[];for(let r of t)e.push(En(r));return e}function vS(t){let e=hp(t);return Pu(e)}function PS(t){let e=hp(t);return vu(e)}function wS(t){return t.map((e,r)=>r.toString())}function IS(t){return["[number]"]}function bS(t){return globalThis.Object.getOwnPropertyNames(t)}function xS(t){return AS?globalThis.Object.getOwnPropertyNames(t).map(r=>r[0]==="^"&&r[r.length-1]==="$"?r.slice(1,r.length-1):r):[]}function En(t){return ie(t)?vS(t.allOf):L(t)?PS(t.anyOf):Je(t)?wS(t.items??[]):ft(t)?IS(t.items):me(t)?bS(t.properties):hr(t)?xS(t.patternProperties):[]}var AS,ha=u(()=>{Pn();B();AS=!1});function RS(t,e){return Z("KeyOf",[Z(t,e)])}function TS(t){return Z("KeyOf",[Mt(t)])}function MS(t,e){let r=En(t),n=CS(r),o=Rt(n);return g(o,e)}function CS(t){return t.map(e=>e==="[number]"?nt():V(e))}function qr(t,e){return gt(t)?RS(t.target,t.parameters):de(t)?TS(t.$ref):te(t)?Sp(t,e):MS(t,e)}var Sa=u(()=>{R();Ue();kr();Yt();wr();ha();he();ya();B()});function _S(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=qr(t[n],ee(e));return r}function $S(t,e){return _S(t.properties,e)}function Sp(t,e){let r=$S(t,e);return U(r)}var ya=u(()=>{ve();Sa();We()});var yp=u(()=>{});var On=u(()=>{ya();yp();ha();Sa()});function ES(t){let e=[];for(let r of t)e.push(...En(r));return ku(e)}function OS(t){return t.filter(e=>!Gt(e))}function DS(t,e){let r=[];for(let n of t)r.push(...da(n,[e]));return OS(r)}function NS(t,e){let r={};for(let n of e)r[n]=bo(DS(t,n));return r}function kp(t,e){let r=ES(t),n=NS(t,r);return H(n,e)}var vp=u(()=>{ot();Tt();On();Xe();Pn();B()});var ka=u(()=>{vp()});function To(t){return g({[P]:"Date",type:"Date"},t)}var Pp=u(()=>{T();R()});var Mo=u(()=>{Pp()});function Co(t){return g({[P]:"Null",type:"null"},t)}var wp=u(()=>{R();T()});var _o=u(()=>{wp()});function $o(t){return g({[P]:"Symbol",type:"symbol"},t)}var Ip=u(()=>{R();T()});var Eo=u(()=>{Ip()});function Oo(t){return g({[P]:"Undefined",type:"undefined"},t)}var bp=u(()=>{R();T()});var Do=u(()=>{bp()});function No(t){return g({[P]:"Uint8Array",type:"Uint8Array"},t)}var xp=u(()=>{R();T()});var Fo=u(()=>{xp()});function er(t){return g({[P]:"Unknown"},t)}var Ap=u(()=>{R();T()});var jr=u(()=>{Ap()});function FS(t){return t.map(e=>va(e,!1))}function LS(t){let e={};for(let r of globalThis.Object.getOwnPropertyNames(t))e[r]=Ve(va(t[r],!1));return e}function Lo(t,e){return e===!0?t:Ve(t)}function va(t,e){return $s(t)?Lo(Jt(),e):Os(t)?Lo(Jt(),e):pe(t)?Ve(it(FS(t))):Dt(t)?No():pr(t)?To():j(t)?Lo(H(LS(t)),e):Es(t)?Lo(At([],er()),e):ce(t)?Oo():Ds(t)?Co():Ns(t)?$o():un(t)?Br():Ge(t)?V(t):Ot(t)?V(t):Q(t)?V(t):H({})}function Rp(t,e){return g(va(t,!0),e)}var Tp=u(()=>{wn();Mn();Mo();Sr();Ue();_o();Xe();Eo();Zt();Pr();Do();Fo();jr();Nt();De()});var Pa=u(()=>{Tp()});function Mp(t,e){return ht(t)?it(t.parameters,e):W(e)}var Cp=u(()=>{Zt();Ae();B()});var wa=u(()=>{Cp()});function _p(t,e){if(ce(t))throw new Error("Enum undefined or empty");let r=globalThis.Object.getOwnPropertyNames(t).filter(i=>isNaN(i)).map(i=>t[i]),o=[...new Set(r)].map(i=>V(i));return q(o,{...e,[rt]:"Enum"})}var $p=u(()=>{Ue();T();he();De()});var Ia=u(()=>{$p()});function at(t){return t===h.False?t:h.True}function Gr(t){throw new xa(t)}function Se(t){return c.IsNever(t)||c.IsIntersect(t)||c.IsUnion(t)||c.IsUnknown(t)||c.IsAny(t)}function ye(t,e){return c.IsNever(e)?Wp(t,e):c.IsIntersect(e)?Wo(t,e):c.IsUnion(e)?Ma(t,e):c.IsUnknown(e)?Vp(t,e):c.IsAny(e)?Ta(t,e):Gr("StructuralRight")}function Ta(t,e){return h.True}function WS(t,e){return c.IsIntersect(e)?Wo(t,e):c.IsUnion(e)&&e.anyOf.some(r=>c.IsAny(r)||c.IsUnknown(r))?h.True:c.IsUnion(e)?h.Union:c.IsUnknown(e)||c.IsAny(e)?h.True:h.Union}function BS(t,e){return c.IsUnknown(t)?h.False:c.IsAny(t)?h.Union:c.IsNever(t)?h.True:h.False}function US(t,e){return c.IsObject(e)&&Bo(e)?h.True:Se(e)?ye(t,e):c.IsArray(e)?at(z(t.items,e.items)):h.False}function KS(t,e){return Se(e)?ye(t,e):c.IsAsyncIterator(e)?at(z(t.items,e.items)):h.False}function VS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsBigInt(e)?h.True:h.False}function Fp(t,e){return c.IsLiteralBoolean(t)||c.IsBoolean(t)?h.True:h.False}function qS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsBoolean(e)?h.True:h.False}function jS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsConstructor(e)?t.parameters.length>e.parameters.length?h.False:t.parameters.every((r,n)=>at(z(e.parameters[n],r))===h.True)?at(z(t.returns,e.returns)):h.False:h.False}function GS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsDate(e)?h.True:h.False}function HS(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsFunction(e)?t.parameters.length>e.parameters.length?h.False:t.parameters.every((r,n)=>at(z(e.parameters[n],r))===h.True)?at(z(t.returns,e.returns)):h.False:h.False}function Lp(t,e){return c.IsLiteral(t)&&Me.IsNumber(t.const)||c.IsNumber(t)||c.IsInteger(t)?h.True:h.False}function zS(t,e){return c.IsInteger(e)||c.IsNumber(e)?h.True:Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):h.False}function Wo(t,e){return e.allOf.every(r=>z(t,r)===h.True)?h.True:h.False}function QS(t,e){return t.allOf.some(r=>z(r,e)===h.True)?h.True:h.False}function JS(t,e){return Se(e)?ye(t,e):c.IsIterator(e)?at(z(t.items,e.items)):h.False}function YS(t,e){return c.IsLiteral(e)&&e.const===t.const?h.True:Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsString(e)?Kp(t,e):c.IsNumber(e)?Bp(t,e):c.IsInteger(e)?Lp(t,e):c.IsBoolean(e)?Fp(t,e):h.False}function Wp(t,e){return h.False}function XS(t,e){return h.True}function Ep(t){let[e,r]=[t,0];for(;c.IsNot(e);)e=e.not,r+=1;return r%2===0?e:er()}function ZS(t,e){return c.IsNot(t)?z(Ep(t),e):c.IsNot(e)?z(t,Ep(e)):Gr("Invalid fallthrough for Not")}function ey(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsNull(e)?h.True:h.False}function Bp(t,e){return c.IsLiteralNumber(t)||c.IsNumber(t)||c.IsInteger(t)?h.True:h.False}function ty(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsInteger(e)||c.IsNumber(e)?h.True:h.False}function qe(t,e){return Object.getOwnPropertyNames(t.properties).length===e}function Op(t){return Bo(t)}function Dp(t){return qe(t,0)||qe(t,1)&&"description"in t.properties&&c.IsUnion(t.properties.description)&&t.properties.description.anyOf.length===2&&(c.IsString(t.properties.description.anyOf[0])&&c.IsUndefined(t.properties.description.anyOf[1])||c.IsString(t.properties.description.anyOf[1])&&c.IsUndefined(t.properties.description.anyOf[0]))}function ba(t){return qe(t,0)}function Np(t){return qe(t,0)}function ry(t){return qe(t,0)}function ny(t){return qe(t,0)}function oy(t){return Bo(t)}function iy(t){let e=nt();return qe(t,0)||qe(t,1)&&"length"in t.properties&&at(z(t.properties.length,e))===h.True}function sy(t){return qe(t,0)}function Bo(t){let e=nt();return qe(t,0)||qe(t,1)&&"length"in t.properties&&at(z(t.properties.length,e))===h.True}function ay(t){let e=At([Jt()],Jt());return qe(t,0)||qe(t,1)&&"then"in t.properties&&at(z(t.properties.then,e))===h.True}function Up(t,e){return z(t,e)===h.False||c.IsOptional(t)&&!c.IsOptional(e)?h.False:h.True}function $e(t,e){return c.IsUnknown(t)?h.False:c.IsAny(t)?h.Union:c.IsNever(t)||c.IsLiteralString(t)&&Op(e)||c.IsLiteralNumber(t)&&ba(e)||c.IsLiteralBoolean(t)&&Np(e)||c.IsSymbol(t)&&Dp(e)||c.IsBigInt(t)&&ry(e)||c.IsString(t)&&Op(e)||c.IsSymbol(t)&&Dp(e)||c.IsNumber(t)&&ba(e)||c.IsInteger(t)&&ba(e)||c.IsBoolean(t)&&Np(e)||c.IsUint8Array(t)&&oy(e)||c.IsDate(t)&&ny(e)||c.IsConstructor(t)&&sy(e)||c.IsFunction(t)&&iy(e)?h.True:c.IsRecord(t)&&c.IsString(Aa(t))?e[rt]==="Record"?h.True:h.False:c.IsRecord(t)&&c.IsNumber(Aa(t))&&qe(e,0)?h.True:h.False}function dy(t,e){return Se(e)?ye(t,e):c.IsRecord(e)?dt(t,e):c.IsObject(e)?(()=>{for(let r of Object.getOwnPropertyNames(e.properties)){if(!(r in t.properties)&&!c.IsOptional(e.properties[r]))return h.False;if(c.IsOptional(e.properties[r]))return h.True;if(Up(t.properties[r],e.properties[r])===h.False)return h.False}return h.True})():h.False}function ly(t,e){return Se(e)?ye(t,e):c.IsObject(e)&&ay(e)?h.True:c.IsPromise(e)?at(z(t.item,e.item)):h.False}function Aa(t){return zt in t.patternProperties?nt():Qt in t.patternProperties?vt():Gr("Unknown record key pattern")}function Ra(t){return zt in t.patternProperties?t.patternProperties[zt]:Qt in t.patternProperties?t.patternProperties[Qt]:Gr("Unable to get record value schema")}function dt(t,e){let[r,n]=[Aa(e),Ra(e)];return c.IsLiteralString(t)&&c.IsNumber(r)&&at(z(t,n))===h.True?h.True:c.IsUint8Array(t)&&c.IsNumber(r)||c.IsString(t)&&c.IsNumber(r)||c.IsArray(t)&&c.IsNumber(r)?z(t,n):c.IsObject(t)?(()=>{for(let o of Object.getOwnPropertyNames(t.properties))if(Up(n,t.properties[o])===h.False)return h.False;return h.True})():h.False}function uy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?z(Ra(t),Ra(e)):h.False}function py(t,e){let r=c.IsRegExp(t)?vt():t,n=c.IsRegExp(e)?vt():e;return z(r,n)}function Kp(t,e){return c.IsLiteral(t)&&Me.IsString(t.const)||c.IsString(t)?h.True:h.False}function cy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsString(e)?h.True:h.False}function my(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsSymbol(e)?h.True:h.False}function fy(t,e){return c.IsTemplateLiteral(t)?z(vr(t),e):c.IsTemplateLiteral(e)?z(t,vr(e)):Gr("Invalid fallthrough for TemplateLiteral")}function gy(t,e){return c.IsArray(e)&&t.items!==void 0&&t.items.every(r=>z(r,e.items)===h.True)}function hy(t,e){return c.IsNever(t)?h.True:c.IsUnknown(t)?h.False:c.IsAny(t)?h.Union:h.False}function Sy(t,e){return Se(e)?ye(t,e):c.IsObject(e)&&Bo(e)||c.IsArray(e)&&gy(t,e)?h.True:c.IsTuple(e)?Me.IsUndefined(t.items)&&!Me.IsUndefined(e.items)||!Me.IsUndefined(t.items)&&Me.IsUndefined(e.items)?h.False:Me.IsUndefined(t.items)&&!Me.IsUndefined(e.items)||t.items.every((r,n)=>z(r,e.items[n])===h.True)?h.True:h.False:h.False}function yy(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsUint8Array(e)?h.True:h.False}function ky(t,e){return Se(e)?ye(t,e):c.IsObject(e)?$e(t,e):c.IsRecord(e)?dt(t,e):c.IsVoid(e)?wy(t,e):c.IsUndefined(e)?h.True:h.False}function Ma(t,e){return e.anyOf.some(r=>z(t,r)===h.True)?h.True:h.False}function vy(t,e){return t.anyOf.every(r=>z(r,e)===h.True)?h.True:h.False}function Vp(t,e){return h.True}function Py(t,e){return c.IsNever(e)?Wp(t,e):c.IsIntersect(e)?Wo(t,e):c.IsUnion(e)?Ma(t,e):c.IsAny(e)?Ta(t,e):c.IsString(e)?Kp(t,e):c.IsNumber(e)?Bp(t,e):c.IsInteger(e)?Lp(t,e):c.IsBoolean(e)?Fp(t,e):c.IsArray(e)?BS(t,e):c.IsTuple(e)?hy(t,e):c.IsObject(e)?$e(t,e):c.IsUnknown(e)?h.True:h.False}function wy(t,e){return c.IsUndefined(t)||c.IsUndefined(t)?h.True:h.False}function Iy(t,e){return c.IsIntersect(e)?Wo(t,e):c.IsUnion(e)?Ma(t,e):c.IsUnknown(e)?Vp(t,e):c.IsAny(e)?Ta(t,e):c.IsObject(e)?$e(t,e):c.IsVoid(e)?h.True:h.False}function z(t,e){return c.IsTemplateLiteral(t)||c.IsTemplateLiteral(e)?fy(t,e):c.IsRegExp(t)||c.IsRegExp(e)?py(t,e):c.IsNot(t)||c.IsNot(e)?ZS(t,e):c.IsAny(t)?WS(t,e):c.IsArray(t)?US(t,e):c.IsBigInt(t)?VS(t,e):c.IsBoolean(t)?qS(t,e):c.IsAsyncIterator(t)?KS(t,e):c.IsConstructor(t)?jS(t,e):c.IsDate(t)?GS(t,e):c.IsFunction(t)?HS(t,e):c.IsInteger(t)?zS(t,e):c.IsIntersect(t)?QS(t,e):c.IsIterator(t)?JS(t,e):c.IsLiteral(t)?YS(t,e):c.IsNever(t)?XS(t,e):c.IsNull(t)?ey(t,e):c.IsNumber(t)?ty(t,e):c.IsObject(t)?dy(t,e):c.IsRecord(t)?uy(t,e):c.IsString(t)?cy(t,e):c.IsSymbol(t)?my(t,e):c.IsTuple(t)?Sy(t,e):c.IsPromise(t)?ly(t,e):c.IsUint8Array(t)?yy(t,e):c.IsUndefined(t)?ky(t,e):c.IsUnion(t)?vy(t,e):c.IsUnknown(t)?Py(t,e):c.IsVoid(t)?Iy(t,e):Gr(`Unknown left type operand '${t[P]}'`)}function tr(t,e){return z(t,e)}var xa,h,Ca=u(()=>{wn();Sr();kr();Ur();jr();Vt();vn();T();xt();js();xa=class extends we{};(function(t){t[t.Union=0]="Union",t[t.True=1]="True",t[t.False=2]="False"})(h||(h={}))});function by(t,e,r,n,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(t))i[s]=Hr(t[s],e,r,n,ee(o));return i}function xy(t,e,r,n,o){return by(t.properties,e,r,n,o)}function qp(t,e,r,n,o){let i=xy(t,e,r,n,o);return U(i)}var _a=u(()=>{ve();Uo();We()});function Ay(t,e,r,n){let o=tr(t,e);return o===h.Union?q([r,n]):o===h.True?r:n}function Hr(t,e,r,n,o){return te(t)?qp(t,e,r,n,o):ze(t)?g(jp(t,e,r,n,o)):g(Ay(t,e,r,n),o)}var Uo=u(()=>{R();he();Ca();$a();_a();B()});function Ry(t,e,r,n,o){return{[t]:Hr(V(t),e,r,n,ee(o))}}function Ty(t,e,r,n,o){return t.reduce((i,s)=>({...i,...Ry(s,e,r,n,o)}),{})}function My(t,e,r,n,o){return Ty(t.keys,e,r,n,o)}function jp(t,e,r,n,o){let i=My(t,e,r,n,o);return U(i)}var $a=u(()=>{ve();Ue();Uo();We()});var Gp=u(()=>{});var Dn=u(()=>{Ca();$a();_a();Gp();Uo()});function Hp(t,e){return zr(vr(t),e)}var Ea=u(()=>{Ko();Vt()});function Cy(t,e){let r=t.filter(n=>tr(n,e)===h.False);return r.length===1?r[0]:q(r)}function zr(t,e,r={}){return Qe(t)?g(Hp(t,e),r):te(t)?g(zp(t,e),r):g(L(t)?Cy(t.anyOf,e):tr(t,e)!==h.False?W():t,r)}var Ko=u(()=>{R();he();Ae();Dn();Oa();Ea();B()});function _y(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=zr(t[n],e);return r}function $y(t,e){return _y(t.properties,e)}function zp(t,e){let r=$y(t,e);return U(r)}var Oa=u(()=>{ve();Ko()});var Da=u(()=>{Oa();Ea();Ko()});function Qp(t,e){return Qr(vr(t),e)}var Na=u(()=>{Vo();Vt()});function Ey(t,e){let r=t.filter(n=>tr(n,e)!==h.False);return r.length===1?r[0]:q(r)}function Qr(t,e,r){return Qe(t)?g(Qp(t,e),r):te(t)?g(Jp(t,e),r):g(L(t)?Ey(t.anyOf,e):tr(t,e)!==h.False?t:W(),r)}var Vo=u(()=>{R();he();Ae();Dn();Fa();Na();B()});function Oy(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Qr(t[n],e);return r}function Dy(t,e){return Oy(t.properties,e)}function Jp(t,e){let r=Dy(t,e);return U(r)}var Fa=u(()=>{ve();Vo()});var La=u(()=>{Fa();Na();Vo()});function Yp(t,e){return ht(t)?g(t.returns,e):W(e)}var Xp=u(()=>{R();Ae();B()});var Wa=u(()=>{Xp()});function qo(t){return Ve(Ce(t))}var Zp=u(()=>{Pr();Ut()});var jo=u(()=>{Zp()});function Ir(t,e,r){return g({[P]:"Record",type:"object",patternProperties:{[t]:e}},r)}function Ba(t,e,r){let n={};for(let o of t)n[o]=e;return H(n,{...r,[rt]:"Record"})}function Ny(t,e,r){return Lu(t)?Ba(Ke(t),e,r):Ir(t.pattern,e,r)}function Fy(t,e,r){return Ba(Ke(q(t)),e,r)}function Ly(t,e,r){return Ba([t.toString()],e,r)}function Wy(t,e,r){return Ir(t.source,e,r)}function By(t,e,r){let n=ce(t.pattern)?Qt:t.pattern;return Ir(n,e,r)}function Uy(t,e,r){return Ir(Qt,e,r)}function Ky(t,e,r){return Ir(mu,e,r)}function Vy(t,e,r){return H({true:e,false:e},r)}function qy(t,e,r){return Ir(zt,e,r)}function jy(t,e,r){return Ir(zt,e,r)}function Go(t,e,r={}){return L(t)?Fy(t.anyOf,e,r):Qe(t)?Ny(t,e,r):He(t)?Ly(t.const,e,r):Ft(t)?Vy(t,e,r):yt(t)?qy(t,e,r):kt(t)?jy(t,e,r):Bs(t)?Wy(t,e,r):Lt(t)?By(t,e,r):Ls(t)?Uy(t,e,r):Gt(t)?Ky(t,e,r):W(r)}function Ho(t){return globalThis.Object.getOwnPropertyNames(t.patternProperties)[0]}function ec(t){let e=Ho(t);return e===Qt?vt():e===zt?nt():vt({pattern:e})}function zo(t){return t.patternProperties[Ho(t)]}var tc=u(()=>{R();T();Ae();kr();Xe();Ur();he();Vt();vn();Tt();De();B()});var Nn=u(()=>{tc()});function Gy(t,e){return e.parameters=Fn(t,e.parameters),e.returns=Pt(t,e.returns),e}function Hy(t,e){return e.parameters=Fn(t,e.parameters),e.returns=Pt(t,e.returns),e}function zy(t,e){return e.allOf=Fn(t,e.allOf),e}function Qy(t,e){return e.anyOf=Fn(t,e.anyOf),e}function Jy(t,e){return ce(e.items)||(e.items=Fn(t,e.items)),e}function Yy(t,e){return e.items=Pt(t,e.items),e}function Xy(t,e){return e.items=Pt(t,e.items),e}function Zy(t,e){return e.items=Pt(t,e.items),e}function ek(t,e){return e.item=Pt(t,e.item),e}function tk(t,e){let r=ik(t,e.properties);return{...e,...H(r)}}function rk(t,e){let r=Pt(t,ec(e)),n=Pt(t,zo(e)),o=Go(r,n);return{...e,...o}}function nk(t,e){return e.index in t?t[e.index]:er()}function ok(t,e){let r=Or(e),n=Be(e),o=Pt(t,e);return r&&n?qo(o):r&&!n?Ve(o):!r&&n?Ce(o):o}function ik(t,e){return globalThis.Object.getOwnPropertyNames(e).reduce((r,n)=>({...r,[n]:ok(t,e[n])}),{})}function Fn(t,e){return e.map(r=>Pt(t,r))}function Pt(t,e){return ht(e)?Gy(t,e):St(e)?Hy(t,e):ie(e)?zy(t,e):L(e)?Qy(t,e):Je(e)?Jy(t,e):ft(e)?Yy(t,e):cr(e)?Xy(t,e):fr(e)?Zy(t,e):gr(e)?ek(t,e):me(e)?tk(t,e):hr(e)?rk(t,e):Ws(e)?nk(t,e):e}function rc(t,e){return Pt(e,Er(t))}var nc=u(()=>{co();jr();jo();Pr();Ut();Xe();Nn();De();B()});var Ua=u(()=>{nc()});function oc(t){return g({[P]:"Integer",type:"integer"},t)}var ic=u(()=>{R();T()});var Ka=u(()=>{ic()});function sk(t,e,r){return{[t]:wt(V(t),e,ee(r))}}function ak(t,e,r){return t.reduce((o,i)=>({...o,...sk(i,e,r)}),{})}function dk(t,e,r){return ak(t.keys,e,r)}function sc(t,e,r){let n=dk(t,e,r);return U(n)}var Va=u(()=>{ve();br();Ue();We()});function lk(t){let[e,r]=[t.slice(0,1),t.slice(1)];return[e.toLowerCase(),r].join("")}function uk(t){let[e,r]=[t.slice(0,1),t.slice(1)];return[e.toUpperCase(),r].join("")}function pk(t){return t.toUpperCase()}function ck(t){return t.toLowerCase()}function mk(t,e,r){let n=Wr(t.pattern);if(!yr(n))return{...t,pattern:ac(t.pattern,e)};let s=[...Tn(n)].map(l=>V(l)),a=dc(s,e),d=q(a);return wo([d],r)}function ac(t,e){return typeof t=="string"?e==="Uncapitalize"?lk(t):e==="Capitalize"?uk(t):e==="Uppercase"?pk(t):e==="Lowercase"?ck(t):t:t.toString()}function dc(t,e){return t.map(r=>wt(r,e))}function wt(t,e,r={}){return ze(t)?sc(t,e,r):Qe(t)?mk(t,e,r):L(t)?q(dc(t.anyOf,e),r):He(t)?V(ac(t.const,e),r):g(t,r)}var br=u(()=>{R();Vt();Va();Ue();he();B()});function lc(t,e={}){return wt(t,"Capitalize",e)}var uc=u(()=>{br()});function pc(t,e={}){return wt(t,"Lowercase",e)}var cc=u(()=>{br()});function mc(t,e={}){return wt(t,"Uncapitalize",e)}var fc=u(()=>{br()});function gc(t,e={}){return wt(t,"Uppercase",e)}var hc=u(()=>{br()});var qa=u(()=>{uc();Va();br();cc();fc();hc()});function fk(t,e,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(t))n[o]=rr(t[o],e,ee(r));return n}function gk(t,e,r){return fk(t.properties,e,r)}function Sc(t,e,r){let n=gk(t,e,r);return U(n)}var ja=u(()=>{ve();Qo();We()});function hk(t,e){return t.map(r=>Ga(r,e))}function Sk(t,e){return t.map(r=>Ga(r,e))}function yk(t,e){let{[e]:r,...n}=t;return n}function kk(t,e){return e.reduce((r,n)=>yk(r,n),t)}function vk(t,e,r){let n=se(t,[ge,"$id","required","properties"]),o=kk(r,e);return H(o,n)}function Pk(t){let e=t.reduce((r,n)=>fo(n)?[...r,V(n)]:r,[]);return q(e)}function Ga(t,e){return ie(t)?_e(hk(t.allOf,e)):L(t)?q(Sk(t.anyOf,e)):me(t)?vk(t,e,t.properties):H({})}function rr(t,e,r){let n=pe(e)?Pk(e):e,o=Ye(e)?Ke(e):e,i=de(t),s=de(e);return te(t)?Sc(t,o,r):ze(e)?yc(t,e,r):i&&s?Z("Omit",[t,n],r):!i&&s?Z("Omit",[t,n],r):i&&!s?Z("Omit",[t,n],r):g({...Ga(t,o),...r})}var Qo=u(()=>{R();ho();mn();Yt();Ue();Tt();ot();he();Xe();Ha();ja();B();De()});function wk(t,e,r){return{[e]:rr(t,[e],ee(r))}}function Ik(t,e,r){return e.reduce((n,o)=>({...n,...wk(t,o,r)}),{})}function bk(t,e,r){return Ik(t,e.keys,r)}function yc(t,e,r){let n=bk(t,e,r);return U(n)}var Ha=u(()=>{ve();Qo();We()});var Jo=u(()=>{Ha();ja();Qo()});function xk(t,e,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(t))n[o]=nr(t[o],e,ee(r));return n}function Ak(t,e,r){return xk(t.properties,e,r)}function kc(t,e,r){let n=Ak(t,e,r);return U(n)}var za=u(()=>{ve();Yo();We()});function Rk(t,e){return t.map(r=>Qa(r,e))}function Tk(t,e){return t.map(r=>Qa(r,e))}function Mk(t,e){let r={};for(let n of e)n in t&&(r[n]=t[n]);return r}function Ck(t,e,r){let n=se(t,[ge,"$id","required","properties"]),o=Mk(r,e);return H(o,n)}function _k(t){let e=t.reduce((r,n)=>fo(n)?[...r,V(n)]:r,[]);return q(e)}function Qa(t,e){return ie(t)?_e(Rk(t.allOf,e)):L(t)?q(Tk(t.anyOf,e)):me(t)?Ck(t,e,t.properties):H({})}function nr(t,e,r){let n=pe(e)?_k(e):e,o=Ye(e)?Ke(e):e,i=de(t),s=de(e);return te(t)?kc(t,o,r):ze(e)?vc(t,e,r):i&&s?Z("Pick",[t,n],r):!i&&s?Z("Pick",[t,n],r):i&&!s?Z("Pick",[t,n],r):g({...Qa(t,o),...r})}var Yo=u(()=>{R();ho();Yt();ot();Ue();Xe();he();Tt();mn();B();De();Ja();za()});function $k(t,e,r){return{[e]:nr(t,[e],ee(r))}}function Ek(t,e,r){return e.reduce((n,o)=>({...n,...$k(t,o,r)}),{})}function Ok(t,e,r){return Ek(t,e.keys,r)}function vc(t,e,r){let n=Ok(t,e,r);return U(n)}var Ja=u(()=>{ve();Yo();We()});var Xo=u(()=>{Ja();za();Yo()});function Dk(t,e){return Z("Partial",[Z(t,e)])}function Nk(t){return Z("Partial",[Mt(t)])}function Fk(t){let e={};for(let r of globalThis.Object.getOwnPropertyNames(t))e[r]=Ce(t[r]);return e}function Lk(t,e){let r=se(t,[ge,"$id","required","properties"]),n=Fk(e);return H(n,r)}function Pc(t){return t.map(e=>wc(e))}function wc(t){return gt(t)?Dk(t.target,t.parameters):de(t)?Nk(t.$ref):ie(t)?_e(Pc(t.allOf)):L(t)?q(Pc(t.anyOf)):me(t)?Lk(t,t.properties):mr(t)||Ft(t)||yt(t)||He(t)||fn(t)||kt(t)||Lt(t)||gn(t)||hn(t)?t:H({})}function Jr(t,e){return te(t)?Ic(t,e):g({...wc(t),...e})}var Ya=u(()=>{R();Yt();Ut();Xe();ot();he();wr();Bt();T();Xa();B()});function Wk(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Jr(t[n],ee(e));return r}function Bk(t,e){return Wk(t.properties,e)}function Ic(t,e){let r=Bk(t,e);return U(r)}var Xa=u(()=>{ve();Ya();We()});var Zo=u(()=>{Xa();Ya()});function Uk(t,e){return Z("Required",[Z(t,e)])}function Kk(t){return Z("Required",[Mt(t)])}function Vk(t){let e={};for(let r of globalThis.Object.getOwnPropertyNames(t))e[r]=se(t[r],[xe]);return e}function qk(t,e){let r=se(t,[ge,"$id","required","properties"]),n=Vk(e);return H(n,r)}function bc(t){return t.map(e=>xc(e))}function xc(t){return gt(t)?Uk(t.target,t.parameters):de(t)?Kk(t.$ref):ie(t)?_e(bc(t.allOf)):L(t)?q(bc(t.anyOf)):me(t)?qk(t,t.properties):mr(t)||Ft(t)||yt(t)||He(t)||fn(t)||kt(t)||Lt(t)||gn(t)||hn(t)?t:H({})}function Yr(t,e){return te(t)?Ac(t,e):g({...xc(t),...e})}var Za=u(()=>{R();Yt();Xe();ot();he();wr();T();Bt();ed();B()});function jk(t,e){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=Yr(t[n],e);return r}function Gk(t,e){return jk(t.properties,e)}function Ac(t,e){let r=Gk(t,e);return U(r)}var ed=u(()=>{ve();Za()});var ei=u(()=>{ed();Za()});function Hk(t,e){return e.map(r=>de(r)?td(t,r.$ref):Ze(t,r))}function td(t,e){return e in t?de(t[e])?td(t,t[e].$ref):Ze(t,t[e]):W()}function zk(t){return Vr(t[0])}function Qk(t){return Xt(t[0],t[1])}function Jk(t){return qr(t[0])}function Yk(t){return Jr(t[0])}function Xk(t){return rr(t[0],t[1])}function Zk(t){return nr(t[0],t[1])}function ev(t){return Yr(t[0])}function tv(t,e,r){let n=Hk(t,r);return e==="Awaited"?zk(n):e==="Index"?Qk(n):e==="KeyOf"?Jk(n):e==="Partial"?Yk(n):e==="Omit"?Xk(n):e==="Pick"?Zk(n):e==="Required"?ev(n):W()}function rv(t,e){return Dr(Ze(t,e))}function nv(t,e){return Nr(Ze(t,e))}function ov(t,e,r){return Fr(Ln(t,e),Ze(t,r))}function iv(t,e,r){return At(Ln(t,e),Ze(t,r))}function sv(t,e){return _e(Ln(t,e))}function av(t,e){return Kr(Ze(t,e))}function dv(t,e){return H(globalThis.Object.keys(e).reduce((r,n)=>({...r,[n]:Ze(t,e[n])}),{}))}function lv(t,e){let[r,n]=[Ze(t,zo(e)),Ho(e)],o=Er(e);return o.patternProperties[n]=r,o}function uv(t,e){return de(e)?{...td(t,e.$ref),[ge]:e[ge]}:e}function pv(t,e){return it(Ln(t,e))}function cv(t,e){return q(Ln(t,e))}function Ln(t,e){return e.map(r=>Ze(t,r))}function Ze(t,e){return Be(e)?g(Ze(t,se(e,[xe])),e):Or(e)?g(Ze(t,se(e,[mt])),e):Ht(e)?g(uv(t,e),e):ft(e)?g(rv(t,e.items),e):cr(e)?g(nv(t,e.items),e):gt(e)?g(tv(t,e.target,e.parameters)):ht(e)?g(ov(t,e.parameters,e.returns),e):St(e)?g(iv(t,e.parameters,e.returns),e):ie(e)?g(sv(t,e.allOf),e):fr(e)?g(av(t,e.items),e):me(e)?g(dv(t,e.properties),e):hr(e)?g(lv(t,e)):Je(e)?g(pv(t,e.items||[]),e):L(e)?g(cv(t,e.anyOf),e):e}function mv(t,e){return e in t?Ze(t,t[e]):W()}function Rc(t){return globalThis.Object.getOwnPropertyNames(t).reduce((e,r)=>({...e,[r]:mv(t,r)}),{})}var Tc=u(()=>{Nt();Fs();Bt();In();Ro();bn();xn();Tt();Sr();ot();Cn();On();Xe();Jo();Xo();Ae();Zo();Nn();ei();Zt();he();T();B()});function Mc(t){return new rd(t)}var rd,Cc=u(()=>{Nt();T();Tc();rd=class{constructor(e){let r=Rc(e),n=this.WithIdentifiers(r);this.$defs=n}Import(e,r){let n={...this.$defs,[e]:g(this.$defs[e],r)};return g({[P]:"Import",$defs:n,$ref:e})}WithIdentifiers(e){return globalThis.Object.getOwnPropertyNames(e).reduce((r,n)=>({...r,[n]:{...e[n],$id:n}}),{})}}});var nd=u(()=>{Cc()});function _c(t,e){return g({[P]:"Not",not:t},e)}var $c=u(()=>{R();T()});var od=u(()=>{$c()});function Ec(t,e){return St(t)?it(t.parameters,e):W()}var Oc=u(()=>{Zt();Ae();B()});var id=u(()=>{Oc()});function Dc(t,e={}){ce(e.$id)&&(e.$id=`T${fv++}`);let r=Er(t({[P]:"This",$ref:`${e.$id}`}));return r.$id=e.$id,g({[rt]:"Recursive",...r},e)}var fv,Nc=u(()=>{co();R();De();T();fv=0});var sd=u(()=>{Nc()});function Fc(t,e){let r=Q(t)?new globalThis.RegExp(t):t;return g({[P]:"RegExp",type:"RegExp",source:r.source,flags:r.flags},e)}var Lc=u(()=>{R();De();T()});var ad=u(()=>{Lc()});function gv(t){return ie(t)?t.allOf:L(t)?t.anyOf:Je(t)?t.items??[]:[]}function Wc(t){return gv(t)}var Bc=u(()=>{B()});var dd=u(()=>{Bc()});function Uc(t,e){return St(t)?g(t.returns,e):W(e)}var Kc=u(()=>{R();Ae();B()});var ld=u(()=>{Kc()});var Vc=u(()=>{});var qc=u(()=>{});var jc=u(()=>{Vc();qc()});var Gc=u(()=>{});var Hc=u(()=>{Gc()});function zc(t){return new ud(t)}var ud,pd,Qc=u(()=>{T();B();ud=class{constructor(e){this.schema=e}Decode(e){return new pd(this.schema,e)}},pd=class{constructor(e,r){this.schema=e,this.decode=r}EncodeTransform(e,r){let i={Encode:s=>r[ge].Encode(e(s)),Decode:s=>this.decode(r[ge].Decode(s))};return{...r,[ge]:i}}EncodeSchema(e,r){let n={Decode:this.decode,Encode:e};return{...r,[ge]:n}}Encode(e){return Ht(this.schema)?this.EncodeTransform(e,this.schema):this.EncodeSchema(e,this.schema)}}});var cd=u(()=>{Qc()});function Jc(t={}){return g({[P]:t[P]??"Unsafe"},t)}var Yc=u(()=>{R();T()});var md=u(()=>{Yc()});function Xc(t){return g({[P]:"Void",type:"void"},t)}var Zc=u(()=>{R();T()});var fd=u(()=>{Zc()});var gd={};lo(gd,{Any:()=>Jt,Argument:()=>xu,Array:()=>Dr,AsyncIterator:()=>Nr,Awaited:()=>Vr,BigInt:()=>Br,Boolean:()=>vo,Capitalize:()=>lc,Composite:()=>kp,Const:()=>Rp,Constructor:()=>Fr,ConstructorParameters:()=>Mp,Date:()=>To,Enum:()=>_p,Exclude:()=>zr,Extends:()=>Hr,Extract:()=>Qr,Function:()=>At,Index:()=>Xt,InstanceType:()=>Yp,Instantiate:()=>rc,Integer:()=>oc,Intersect:()=>_e,Iterator:()=>Kr,KeyOf:()=>qr,Literal:()=>V,Lowercase:()=>pc,Mapped:()=>sp,Module:()=>Mc,Never:()=>W,Not:()=>_c,Null:()=>Co,Number:()=>nt,Object:()=>H,Omit:()=>rr,Optional:()=>Ce,Parameters:()=>Ec,Partial:()=>Jr,Pick:()=>nr,Promise:()=>xo,Readonly:()=>Ve,ReadonlyOptional:()=>qo,Record:()=>Go,Recursive:()=>Dc,Ref:()=>Mt,RegExp:()=>Fc,Required:()=>Yr,Rest:()=>Wc,ReturnType:()=>Uc,String:()=>vt,Symbol:()=>$o,TemplateLiteral:()=>wo,Transform:()=>zc,Tuple:()=>it,Uint8Array:()=>No,Uncapitalize:()=>mc,Undefined:()=>Oo,Union:()=>q,Unknown:()=>er,Unsafe:()=>Jc,Uppercase:()=>gc,Void:()=>Xc});var em=u(()=>{wn();zs();In();bn();Ro();Mn();Po();ka();Pa();xn();wa();Mo();Ia();Da();Dn();La();Sr();Tt();Wa();Ua();Ka();ot();qa();Cn();On();Ue();ve();nd();Ae();od();_o();kr();Xe();Jo();Ut();id();Zo();Xo();Ao();Pr();jo();Nn();sd();wr();ad();ei();dd();ld();Ur();Eo();Vt();cd();Zt();Fo();Do();he();jr();md();fd()});var p,tm=u(()=>{em();p=gd});var Ee=u(()=>{Fs();Nt();xt();js();cu();vn();Su();Pn();T();wn();In();zs();bn();Ro();Mn();Po();ka();Pa();xn();wa();Mo();Ia();Da();Dn();La();Sr();Tt();Wa();Ua();Ka();ot();Cn();qa();On();Ue();nd();ve();Ae();od();_o();kr();Xe();Jo();Ut();id();Zo();Xo();Ao();Pr();jo();Nn();sd();wr();ad();ei();dd();ld();jc();Hc();Ur();Eo();Vt();cd();Zt();Fo();Do();he();jr();md();fd();tm()});function hd(t){k=t}function Sd(t){fe=t}var k,fe,Y=u(()=>{k=null,fe=null});function rm(t){let e=t.chatId.trim(),r=t.topicId.trim();return!/^-?\d+$/.test(e)||!/^\d+$/.test(r)?null:`${e}:topic:${r}`}function vv(t){let e=t.conversationId.trim(),r=e.match(/^(-?\d+):topic:(\d+)$/i);if(r?.[1]&&r[2]){let i=rm({chatId:r[1],topicId:r[2]});return i?{chatId:r[1],topicId:r[2],canonicalConversationId:i}:null}if(!/^\d+$/.test(e))return null;let n=t.parentConversationId?.trim();if(!n||!/^-?\d+$/.test(n))return null;let o=rm({chatId:n,topicId:e});return o?{chatId:n,topicId:e,canonicalConversationId:o}:null}function Pv(t){if(!t)return;let e=t.match(/^agent:[^:]+:discord:(direct|dm|channel|group):/i);if(!e?.[1])return;let r=e[1].toLowerCase();return r==="direct"||r==="dm"?"user":"channel"}function wv(t,e){if(!/^\d+$/.test(t))return t;let r=Pv(e);return r?`${r}:${t}`:`channel:${t}`}function Iv(t){if(!(!t?.provider||!t.target)&&!(t.provider==="system"||t.target==="system"))return t.accountId?`${t.provider}|${t.accountId}|${t.target}`:`${t.provider}|${t.target}`}function bv(t){let e=t.toLowerCase(),r=[":thread:",":topic:"];for(let n of r){let o=e.lastIndexOf(n);if(o===-1)continue;let i=t.slice(0,o).trim(),s=t.slice(o+n.length).trim()||void 0;return{id:i||t,threadId:s}}return{id:t}}function xv(t){let e=t?.trim();if(!e)return;let r=e.split(":").filter(Boolean);if(r[0]?.trim().toLowerCase()==="agent")for(let n=2;n<=r.length-3;n+=1){let o=r[n]?.trim().toLowerCase();if(!o||!kv.has(o))continue;let i=r[n+1]?.trim().toLowerCase(),s=r.slice(n+2).join(":").trim();if(!(!i||!s))return{provider:o,kind:i,rawId:s}}}function Av(t,e=vv){try{return e({conversationId:t})}catch{return null}}function yd(t){return{provider:"system",target:"system",sessionKey:t?.trim()||void 0}}function kd(t,e){return{...t,threadId:e??t.threadId}}function Tv(t,e,r){return t==="telegram"&&r?.provider==="telegram"&&!!r.target&&e!==r.target}function Mv(t){let e=t?.trim();if(!e)return;let r=xv(e);if(!r)return;let{provider:n,kind:o,rawId:i}=r,s=bv(i),a=null;if(n==="telegram")try{a=Rv.safeParseTelegramTopicConversation(i)}catch{a=null}let d=a?.chatId??s.id,l=a?.topicId??s.threadId,m=n==="discord"?o==="direct"||o==="dm"?`user:${d}`:`channel:${d}`:d;return{provider:n,target:m,threadId:l,sessionKey:e}}function vd(t){let e=t?.match(/:topic:(\d+)$/);return e?parseInt(e[1],10):void 0}function Cv(t){return!!(t?.provider&&t.target&&t.provider!=="system"&&t.target!=="system")}function Wn(t,e,r){let n=Mv(r),o=e!=null?String(e):void 0,i=t?.trim();if(!i||i.toLowerCase()==="unknown")return n?kd(n,o):yd(r);let s=i.split("|").map(v=>v.trim());if(s.length<2)return n?kd(n,o):yd(r);let[a,d,l]=s,m=s.length>=3?l:d,S=s.length>=3?d:void 0,y=a?.toLowerCase();if(!y||!m)return n?kd(n,o):yd(r);let f=y==="discord"?wv(m,r):m;return Tv(y,f,n)?{provider:y,accountId:S,target:n.target,threadId:o??n.threadId,sessionKey:r?.trim()||void 0}:{provider:y,accountId:S,target:f,threadId:o??(n?.provider===y?n.threadId:void 0),sessionKey:r?.trim()||void 0}}function Xr(t){return Wn(Iv(t.route)??t.originChannel,t.route?.threadId??t.originThreadId,t.route?.sessionKey??t.originSessionKey)??t.route}function nm(t){let e=Xr(t);return Cv(e)?e:void 0}var kv,Rv,Zr=u(()=>{kv=new Set(["telegram","discord","slack","system","mattermost","feishu","line","whatsapp","signal","matrix","googlechat","bluebubbles","imessage","msteams"]);Rv={safeParseTelegramTopicConversation:Av}});import{readFileSync as _v}from"fs";import{homedir as $v}from"os";import{join as Ev}from"path";function im(){if(Bn!==void 0)return Bn;try{let t=_v(Ev($v(),".claude.json"),"utf-8");Bn=JSON.parse(t).mcpServers??{}}catch{Bn={}}return Bn}function sm(t){let e=t.defaultHarness??om,r={};for(let[n,o]of Object.entries(ri))r[n]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[n,o]of Object.entries(t.harnesses??{})){let i=r[n]??{},s={...i,defaultModel:o.defaultModel??i.defaultModel,reasoningEffort:o.reasoningEffort??i.reasoningEffort};o.allowedModels!==void 0?s.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(s.allowedModels=void 0),r[n]=s}if(t.defaultModel!==void 0){let n=r[e]??{};r[e]={...n,defaultModel:t.harnesses?.[e]?.defaultModel??t.defaultModel,allowedModels:t.harnesses?.[e]?.allowedModels!==void 0?n.allowedModels:t.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${e}.defaultModel instead.`)}if(t.model!==void 0){let n=r.codex??{};r.codex={...n,defaultModel:t.harnesses?.codex?.defaultModel??t.model,allowedModels:t.harnesses?.codex?.allowedModels!==void 0?n.allowedModels:t.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(t.reasoningEffort!==void 0){let n=r.codex??{};r.codex={...n,reasoningEffort:t.harnesses?.codex?.reasoningEffort??t.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(t.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[n,o]of Object.entries(r))t.harnesses?.[n]?.allowedModels===void 0&&(r[n]={...o,allowedModels:void 0})}_={maxSessions:t.maxSessions??20,defaultWorkdir:t.defaultWorkdir,idleTimeoutMinutes:t.idleTimeoutMinutes??15,sessionGcAgeMinutes:t.sessionGcAgeMinutes??1440,maxPersistedSessions:t.maxPersistedSessions??1e4,fallbackChannel:t.fallbackChannel,agentChannels:t.agentChannels,maxAutoResponds:t.maxAutoResponds??10,permissionMode:t.permissionMode??"plan",planApproval:t.planApproval??"ask",defaultHarness:e,harnesses:r,allowedModels:t.allowedModels,defaultWorktreeStrategy:t.defaultWorktreeStrategy??"off",worktreeDir:t.worktreeDir}}function Pe(){return _.defaultHarness??om}function am(t){let e=ri[t],r=_.harnesses[t];return{...e,...r,allowedModels:r?.allowedModels??e?.allowedModels}}function Ct(t){return am(t).defaultModel}function en(t){return _.harnesses[t]?.allowedModels??_.allowedModels}function lt(t){return am(t).reasoningEffort}function Pd(t){return(t.messageChannel??t.channel)?.toLowerCase()!=="telegram"?!1:!!vd(t.sessionKey)}function ni(t){if(t.messageChannel){let e=t.messageChannel.split("|");if(e.length>=3)return t.messageChannel;if(t.agentAccountId&&e.length>=2)return`${e[0]}|${t.agentAccountId}|${e.slice(1).join("|")}`;if(e.length===1&&t.chatId)return`${e[0]}|${t.chatId}`;if(e.length===1&&t.senderId&&!Pd(t))return`${e[0]}|${t.senderId}`}if(t.workspaceDir){let e=Kn(t.workspaceDir);if(e)return e}if(t.messageChannel&&t.messageChannel.includes("|"))return t.messageChannel}function qt(t,e){if(e&&String(e).includes("|"))return String(e);if(t?.channelId&&String(t.channelId).includes("|"))return String(t.channelId);if(t?.messageChannel){let r=String(t.messageChannel);if(r.includes("|"))return r;if(t.chatId)return`${r}|${t.chatId}`;if(t.senderId&&!Pd(t))return`${r}|${t.senderId}`}return t?.channel&&t?.chatId?`${t.channel}|${t.chatId}`:t?.channel&&t?.senderId&&!Pd(t)?`${t.channel}|${t.senderId}`:t?.id&&/^-?\d+$/.test(String(t.id))?`telegram|${t.id}`:_.fallbackChannel??"unknown"}function Un(t){return t?.messageThreadId??void 0}function _t(t,e,r){return Wn(qt(t,e),Un(t),r??t?.sessionKey)}function Kn(t){let e=_.agentChannels;if(!e)return;let r=i=>i.replace(/\/+$/,""),n=r(t),o=Object.entries(e).sort((i,s)=>s[0].length-i[0].length);for(let[i,s]of o)if(n===r(i)||n.startsWith(r(i)+"/"))return s}function dm(t){return vd(t)}var Bn,om,ri,_,Re=u(()=>{Zr();om="claude-code",ri={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium"}};_={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"ask",harnesses:{"claude-code":{...ri["claude-code"]},codex:{...ri.codex}}}});function oi(t){return{type:"backend_ref",ref:t}}function ii(t){return{type:"run_started",...t?{runId:t}:{}}}function Vn(t){return{type:"text_delta",text:t}}function lm(t,e){return{type:"tool_call",name:t,input:e}}function si(t){return{type:"pending_input",state:t}}function nn(t){return t?{type:"pending_input_resolved",requestId:t}:{type:"pending_input_resolved"}}function ai(t,e){return{type:"plan_artifact",artifact:t,finalized:e}}function di(t){return t?{type:"settings_changed",permissionMode:t}:{type:"settings_changed"}}function xr(t){return{type:"run_completed",data:t}}var rn,wd=u(()=>{rn=class{queue=[];resolvePending=null;done=!1;enqueue(e){this.queue.push(e),this.flush()}close(){this.done=!0,this.flush()}flush(){this.resolvePending&&(this.resolvePending(),this.resolvePending=null)}messages(){let e=this;return(async function*(){for(;;){for(;e.queue.length>0;)yield e.queue.shift();if(e.done)return;await new Promise(r=>{e.resolvePending=r})}})()}}});import*as ui from"@anthropic-ai/claude-agent-sdk";import{dirname as um,join as pm}from"path";import{fileURLToPath as Ov}from"url";import{createRequire as Dv}from"module";function Nv(t){if(typeof t.result=="string"&&t.result.length>0)return t.result;if(Array.isArray(t.errors)){let e=t.errors.filter(r=>typeof r=="string"&&r.length>0);if(e.length>0)return e.join(`
2
+ `)}}function Fv(t,e,r){let o=(Array.isArray(r.questions)?r.questions:[])[0]??{},i=typeof o.question=="string"?o.question:void 0,s=Array.isArray(o.options)?o.options.map(a=>{if(!a||typeof a!="object")return"";let d=a.label;return typeof d=="string"?d:""}).filter(Boolean):[];return{requestId:`${t||"claude"}-ask-${e}`,kind:"question",promptText:i,options:s,allowsFreeText:s.length===0||o.multiSelect===!0}}var li,cm=u(()=>{wd();li=class{constructor(e={}){this.deps=e}deps;name="claude-code";backendKind="claude-code";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!1,nativePlanArtifacts:!1,worktrees:"plugin-managed"};launch(e){let r=new rn,n=!1,o="",i=!1,s=0,a=e.resumeSessionId??"",d=e.canUseTool,l={cwd:e.cwd,model:e.model,permissionMode:e.permissionMode,allowDangerouslySkipPermissions:!0,pathToClaudeCodeExecutable:(()=>{try{let A=Dv(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return pm(um(A),"cli.js")}catch{let v=um(Ov(import.meta.url));return pm(v,"..","node_modules","@anthropic-ai","claude-agent-sdk","cli.js")}})(),allowedTools:e.allowedTools,systemPrompt:e.systemPrompt,includePartialMessages:!0,abortController:e.abortController,mcpServers:e.mcpServers,...d?{canUseTool:async(v,A)=>{if(v!=="AskUserQuestion")return{behavior:"allow"};let x=Fv(a,++s,A);r.enqueue(si(x));try{let w=await d(v,A);return r.enqueue(nn(x.requestId)),w}catch(w){throw r.enqueue(nn(x.requestId)),w}}}:{}};e.resumeSessionId&&(l.resume=e.resumeSessionId,l.forkSession=e.forkSession??!1);let m=e.prompt,S=this.deps.query??ui.query,y=this.deps.startup??ui.startup,f=(async()=>{if(typeof y!="function")return S({prompt:m,options:l});let v=await y({options:l});try{return v.query(m)}catch(A){throw await v.close?.(),A}})();return(async()=>{try{let v=await f;for await(let A of v){let x=A;if(x.type==="system"&&x.subtype==="init"){a=x.session_id??a,r.enqueue(oi({kind:"claude-code",conversationId:a}));continue}if(x.type==="system"&&x.subtype==="status"&&x.permissionMode){r.enqueue(di(x.permissionMode));continue}if(x.type==="assistant"){n||(n=!0,r.enqueue(ii()));for(let w of x.message?.content??[]){if(w.type==="text"){o+=o?`
3
+ ${w.text}`:w.text,r.enqueue(Vn(w.text));continue}w.type==="tool_use"&&((w.name==="ExitPlanMode"||w.name==="set_permission_mode")&&(i=!0),w.name!=="AskUserQuestion"&&r.enqueue(lm(w.name,w.input)))}continue}if(x.type==="result"){let w=o.trim();if(w&&(e.permissionMode==="plan"||i)){let C={explanation:void 0,steps:[],markdown:w};r.enqueue(ai(C,!0))}r.enqueue(xr({success:x.subtype==="success",duration_ms:x.duration_ms??0,total_cost_usd:x.total_cost_usd??0,num_turns:x.num_turns??0,result:Nv(x),session_id:x.session_id??a})),o="",i=!1,n=!1}}}finally{r.close()}})().catch(v=>{r.enqueue(xr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,result:v instanceof Error?v.message:String(v),session_id:a})),r.close()}),{messages:r.messages(),async setPermissionMode(v){let A=await f;typeof A.setPermissionMode=="function"&&await A.setPermissionMode(v)},async streamInput(v){let A=await f;typeof A.streamInput=="function"&&await A.streamInput(v)},async interrupt(){let v=await f;typeof v.interrupt=="function"&&await v.interrupt()}}}buildUserMessage(e,r){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:r}}}});import{spawn as Lv}from"node:child_process";import Wv from"node:readline";function Bv(t){return t instanceof Error?t.message:String(t)}function Uv(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}async function Kv(t,e){if(t.id!=null&&(Object.hasOwn(t,"result")||Object.hasOwn(t,"error"))){let n=String(t.id),o=e.pending.get(n);if(!o)return;if(clearTimeout(o.timer),e.pending.delete(n),t.error){o.reject(new Error(`codex app server rpc error (${t.error.code??"unknown"}): ${t.error.message??"unknown error"}`));return}o.resolve(t.result);return}let r=t.method?.trim();if(r){if(t.id==null){await e.onNotification(r,t.params);return}try{let n=await e.onRequest(r,t.params);e.respond({jsonrpc:"2.0",id:t.id,result:n??{}})}catch(n){e.respond({jsonrpc:"2.0",id:t.id,error:{code:-32603,message:Bv(n)}})}}}var pi,mm=u(()=>{pi=class{constructor(e,r,n){this.command=e;this.args=r;this.requestTimeoutMs=n}command;args;requestTimeoutMs;process=null;pending=new Map;counter=0;onNotification=()=>{};onRequest=async()=>({});setNotificationHandler(e){this.onNotification=e}setRequestHandler(e){this.onRequest=e}async connect(){if(this.process)return;let e=Lv(this.command,["app-server",...this.args],{stdio:["pipe","pipe","pipe"],env:process.env});if(!e.stdin||!e.stdout||!e.stderr)throw new Error("codex app server stdio pipes unavailable");this.process=e,Wv.createInterface({input:e.stdout}).on("line",n=>{this.handleLine(n)}),e.stderr.on("data",()=>{}),e.on("close",()=>{this.flushPending(new Error("codex app server stdio closed")),this.process=null})}async close(){this.flushPending(new Error("codex app server stdio closed"));let e=this.process;this.process=null,e&&e.kill()}async notify(e,r){this.write({jsonrpc:"2.0",method:e,params:r??{}})}async request(e,r,n){let o=`rpc-${++this.counter}`,i=new Promise((s,a)=>{let d=setTimeout(()=>{this.pending.delete(o),a(new Error(`codex app server timeout: ${e}`))},Math.max(100,n??this.requestTimeoutMs));d.unref?.(),this.pending.set(o,{resolve:s,reject:a,timer:d})});return this.write({jsonrpc:"2.0",id:o,method:e,params:r??{}}),await i}write(e){if(!this.process?.stdin)throw new Error("codex app server stdio not connected");this.process.stdin.write(`${JSON.stringify(e)}
4
+ `)}async handleLine(e){let r=Uv(e);r&&await Kv(r,{pending:this.pending,onNotification:this.onNotification,onRequest:this.onRequest,respond:n=>this.write(n)})}flushPending(e){for(let[r,n]of this.pending)clearTimeout(n.timer),n.reject(e),this.pending.delete(r)}}});function X(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function le(t,e,r){for(let n of e){let o=t?.[n];if(typeof o!="string")continue;let i=r?.trim===!1?o:o.trim();if(i)return i}}function Vv(t){return t instanceof Error?t.message:String(t)}function fm(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function or(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>or(r)).join("");let e=X(t);if(!e)return"";for(let r of["delta","text","content","message","input","output","parts"]){let n=or(e[r]);if(n)return n}for(let r of["item","turn","thread","response","result","data"]){let n=or(e[r]);if(n)return n}return""}function qn(t){let e=X(t);if(!e)return{};let r=X(e.thread)??X(e.session),n=X(e.turn)??X(e.run),o=X(e.item),i=X(e.serverRequest);return{threadId:le(e,["threadId","thread_id","conversationId","conversation_id"])??le(r,["id","threadId","thread_id","conversationId"]),runId:le(e,["turnId","turn_id","runId","run_id"])??le(n,["id","turnId","turn_id","runId","run_id"]),requestId:le(e,["requestId","request_id","serverRequestId"])??le(i,["id","requestId","request_id"]),itemId:le(e,["itemId","item_id"])??le(o,["id","itemId","item_id"])}}function ci(t,e,r=0){if(r>6)return;if(Array.isArray(t)){for(let i of t){let s=ci(i,e,r+1);if(s)return s}return}let n=X(t);if(!n)return;let o=le(n,e);if(o)return o;for(let i of Object.values(n)){let s=ci(i,e,r+1);if(s)return s}}function jn(t){return{threadId:qn(t).threadId,cwd:ci(t,["cwd","workdir","directory"])}}function gm(t){let e=t?.trim();return!!(e&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(e))}function hm(t){let e=t?.trim();if(!e)return;let r=e.split(/[/\\]+/).filter(Boolean),n=r.lastIndexOf("worktrees");if(!(n<0||n+1>=r.length))return r[n+1]}function mi(t){let e=X(t);if(!e)return;let r=X(e.item)??e;return le(r,["id","itemId","item_id","messageId","message_id"])}function qv(t,e=!1){let r=X(t);if(!r)return"";let n=X(r.item)??r;return le(n,["type"])?.toLowerCase()!=="agentmessage"?"":e?or(n):le(n,["text"],{trim:!1})??or(n)}function Sm(t,e){let r=t.trim().toLowerCase();return r==="item/agentmessage/delta"?{mode:"delta",text:or(e),itemId:mi(e)}:r==="item/completed"?{mode:"snapshot",text:qv(e),itemId:mi(e)}:{mode:"ignore",text:""}}function ym(t){return{itemId:mi(t),delta:or(t)}}function km(t){let e=X(t),r=X(e?.plan),o=(Array.isArray(e?.plan)?e.plan:Array.isArray(r?.steps)?r.steps:[]).map(i=>{let s=X(i),a=le(s,["step","title","text"]);if(!a)return null;let d=le(s,["status"])?.toLowerCase()??"pending";return{step:a,status:d==="inprogress"||d==="in_progress"?"inProgress":d==="completed"?"completed":"pending"}}).filter(Boolean);return{explanation:le(r,["explanation"])??le(e,["explanation"]),steps:o}}function vm(t){let e=X(t);if(!e)return{};let r=X(e.item)??e;return le(r,["type"])?.toLowerCase()!=="plan"?{}:{itemId:mi(r),text:le(r,["text"],{trim:!1})??or(r)}}function Pm(t,e){let r=t.trim().toLowerCase();if(r==="turn/failed")return"failed";if(r==="turn/cancelled")return"interrupted";let n=X(e)??{},o=X(n.turn)??n,i=le(o,["status"])?.toLowerCase();return i==="failed"?"failed":i==="interrupted"||i==="cancelled"?"interrupted":"completed"}function wm(t,e){let r=X(e)??{},n=X(r.turn)??r,o=X(n.error)??X(r.error);if(o)return le(o,["message","text","summary","reason"])}function jv(t,e){let r=Vv(t).toLowerCase();return r.includes("method not found")||r.includes("unknown method")?!0:r.includes("unknown variant")?e?r.includes(`unknown variant \`${e.toLowerCase()}\``):!0:!1}function Hv(t){return Gv.has(t.trim().toLowerCase())}function zv(t){let e=X(t);return e?!!le(e,["threadId","thread_id"]):!1}async function Gn(t){if(t.payloads.length===0)throw new Error(`codex app server request skipped: no payloads for ${t.methods.join(", ")||"<none>"}`);let e;for(let r of t.methods)for(let n of t.payloads){if(Hv(r)&&!zv(n))throw new Error(`codex app server request missing threadId: ${r}`);try{return await t.client.request(r,n,t.timeoutMs)}catch(o){if(e=o,!jv(o,r))continue}}throw e instanceof Error?e:new Error(String(e))}function Im(t){let e={cwd:t.cwd};t.model?.trim()&&(e.model=t.model.trim()),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim());let r={cwd:t.cwd};return t.approvalPolicy?.trim()&&(r.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(r.sandbox=t.sandbox.trim()),[e,r,{}]}function bm(t){let e={threadId:t.threadId,persistExtendedHistory:!1};return t.model?.trim()&&(e.model=t.model.trim()),t.reasoningEffort?.trim()&&(e.reasoningEffort=t.reasoningEffort.trim()),t.cwd?.trim()&&(e.cwd=t.cwd.trim()),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim()),[e]}function Qv(t){return[{type:"text",text:t}]}function Jv(t,e,r,n){let o=e?.trim(),i=n?.trim();if(t!=="plan")return o||i?{mode:"default",settings:{...o?{model:o}:{},...r?.trim()?{reasoningEffort:r.trim()}:{},developerInstructions:i??null}}:void 0;if(!(!o&&!i))return{mode:"plan",settings:{...o?{model:o}:{},...r?.trim()?{reasoningEffort:r.trim()}:{},developerInstructions:i??null}}}function xm(t){let e={threadId:t.threadId,input:Qv(t.prompt)};t.model?.trim()&&(e.model=t.model.trim()),t.approvalPolicy?.trim()&&(e.approvalPolicy=t.approvalPolicy.trim()),t.sandbox?.trim()&&(e.sandbox=t.sandbox.trim());let r=Jv(t.permissionMode??"default",t.model,t.reasoningEffort,t.systemPrompt);return r?[{...e,collaborationMode:r},{...e,collaboration_mode:{mode:r.mode,settings:{...typeof r.settings.model=="string"?{model:r.settings.model}:{},...typeof r.settings.reasoningEffort=="string"?{reasoning_effort:r.settings.reasoningEffort}:{},developer_instructions:r.settings.developerInstructions??null}}},e]:[e]}function Am(t){return[{threadId:t.threadId,turnId:t.turnId}]}function Yv(t){let e=X(t);if(!e)return[];let r=e.options??e.choices??e.availableDecisions??e.decisions;return Array.isArray(r)?r.map(n=>typeof n=="string"?n.trim():le(X(n),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function Xv(t){let e=t.trim().toLowerCase();return e.includes("session")?"acceptForSession":/cancel|abort|stop/.test(e)?"cancel":/deny|decline|reject|block|no/.test(e)?"decline":/approve|allow|accept|yes/.test(e)?"accept":t.trim()}function Rm(t,e,r){let n=t.trim().toLowerCase(),o=Yv(r),i=ci(r,["question","prompt","message","text","summary","reason"])??void 0,s=n.includes("requestapproval"),a=s?o.map(d=>({kind:"approval",label:d,decision:Xv(d),responseDecision:d})):o.map(d=>({kind:"option",label:d,value:d}));return{requestId:e,kind:s?"approval":"question",promptText:i,options:o,actions:a,allowsFreeText:!0}}function Tm(t){let e=t.trim().toLowerCase();return e.includes("requestuserinput")||e.includes("requestapproval")}function Id(t,e){let r=t==="bypassPermissions"?"never":e?.trim()||"never";return{approvalPolicy:r,sandbox:r==="never"?"danger-full-access":void 0}}var Gv,Mm=u(()=>{Gv=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function Cm(t){return t instanceof Error?t.message:String(t)}function nP(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return String(t);let e=t;return typeof e.message?.content=="string"?e.message.content:typeof e.text=="string"?e.text:String(t)}var Zv,Ar,eP,tP,rP,fi,_m=u(()=>{mm();wd();Mm();Zv="1.0",Ar=6e4,eP="OPENCLAW_CODEX_APP_SERVER_COMMAND",tP="OPENCLAW_CODEX_APP_SERVER_ARGS",rP="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";fi=class{constructor(e={}){this.deps=e}deps;name="codex";backendKind="codex-app-server";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!0,nativePlanArtifacts:!0,worktrees:"native-restore"};launch(e){let r={command:process.env[eP]?.trim()||"codex",args:fm(process.env[tP]),requestTimeoutMs:Number.parseInt(process.env[rP]??String(Ar),10)||Ar},n=this.deps.createClient?.(r)??new pi(r.command,r.args,r.requestTimeoutMs),o=new rn,i=e.resumeSessionId,s,a=e.backendRef?.worktreePath,d=e.backendRef?.worktreeId,l=e.permissionMode??"default",m,S=0,y="",f=[],v,A=new Map,x=new Set,w=O=>{let D=O?.trim();if(!D)return;let K=e.originalWorkdir?.trim()||e.cwd.trim();e.worktreeStrategy&&e.worktreeStrategy!=="off"&&D!==K&&gm(D)&&(a=D,d=hm(D))},C=()=>{i&&o.enqueue(oi({kind:"codex-app-server",conversationId:i,...s?{runId:s}:{},...d?{worktreeId:d}:{},...a?{worktreePath:a}:{}}))};n.setNotificationHandler(async(O,D)=>{let K=O.trim().toLowerCase(),ue=qn(D),ct=jn(D);if(ue.threadId&&i&&ue.threadId!==i)return;if(ue.threadId&&(i=ue.threadId),ue.runId&&(s=ue.runId),w(ct.cwd),(ue.threadId||ue.runId||ct.cwd)&&C(),K==="serverrequest/resolved"){m&&(o.enqueue(nn(m.requestId)),m=void 0);return}if(K==="turn/plan/updated"){let Te=km(D);y=Te.explanation??y,Te.steps.length>0&&(f=Te.steps);return}if(K==="item/plan/delta"){let Te=ym(D);if(Te.itemId&&Te.delta){let jt=A.get(Te.itemId)??"";A.set(Te.itemId,`${jt}${Te.delta}`)}return}if(K==="item/completed"){let Te=vm(D);if(Te.text?.trim()){let jt={explanation:y||void 0,steps:f,markdown:Te.text.trim()};o.enqueue(ai(jt,!0));return}}let ae=Sm(K,D);if(ae.mode==="delta"&&ae.text){ae.itemId&&x.add(ae.itemId),o.enqueue(Vn(ae.text));return}ae.mode==="snapshot"&&ae.text&&(!ae.itemId||!x.has(ae.itemId))&&o.enqueue(Vn(ae.text)),(K==="turn/completed"||K==="turn/failed"||K==="turn/cancelled")&&v&&(v.method=O,v.params=D,v.resolve())}),n.setRequestHandler(async(O,D)=>{if(!Tm(O))return{};let K=qn(D),ue=jn(D);if(K.threadId&&i&&K.threadId!==i)return{};K.threadId&&(i=K.threadId),K.runId&&(s=K.runId),w(ue.cwd),(K.threadId||K.runId||ue.cwd)&&C();let ct=K.requestId??`${i??"codex"}-${Date.now().toString(36)}`,ae=Rm(O,ct,D),Te=O.trim().toLowerCase(),jt=ae.options,ao=ae.actions??[],Dg=await new Promise(Ng=>{m={requestId:ct,methodLower:Te,state:ae,options:jt,actions:ao,resolveResponse:Ng},o.enqueue(si(ae))});return m=void 0,o.enqueue(nn(ct)),Dg});let b=async()=>{await n.connect(),await n.request("initialize",{protocolVersion:Zv,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},Ar),await n.notify("initialized",{})},M=async()=>{let O=Id(l,e.codexApprovalPolicy);if(i){let ue=await Gn({client:n,methods:["thread/resume"],payloads:bm({threadId:i,model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:O.approvalPolicy,sandbox:O.sandbox}),timeoutMs:Ar}),ct=jn(ue);i=ct.threadId??i,w(ct.cwd),C();return}let D=await Gn({client:n,methods:["thread/start","thread/new"],payloads:Im({cwd:e.originalWorkdir?.trim()||e.cwd,model:e.model,approvalPolicy:O.approvalPolicy,sandbox:O.sandbox}),timeoutMs:Ar}),K=jn(D);if(i=K.threadId,!i)throw new Error("Codex App Server did not return a thread id.");w(K.cwd),C()},F=async O=>{await M(),o.enqueue(ii()),S+=1,y="",f=[],A.clear(),x.clear();let D="",K,ue,ct=new Promise(ae=>{ue=ae});v={resolve:ue};try{let ae=Id(l,e.codexApprovalPolicy),Te=await Gn({client:n,methods:["turn/start"],payloads:xm({threadId:i,prompt:O,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,permissionMode:l,approvalPolicy:ae.approvalPolicy,sandbox:ae.sandbox}),timeoutMs:Ar}),jt=qn(Te);jt.runId&&(s=jt.runId,C()),await ct,D=v?.method??"turn/failed",K=v?.params;let ao=Pm(D,K);o.enqueue(xr({success:ao==="completed",outcome:ao,duration_ms:0,total_cost_usd:0,num_turns:S,result:wm(D,K),session_id:i}))}catch(ae){o.enqueue(xr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:S,result:Cm(ae),session_id:i??""}))}finally{v=void 0}},Le=async O=>m?(m.methodLower.includes("requestapproval")?m.resolveResponse({decision:O.trim()||"decline"}):m.resolveResponse({text:O.trim()}),!0):!1,pl=async O=>{let D=m;if(!D)return!1;let K=D.actions[O];if(K?.kind==="approval")return D.resolveResponse({decision:K.responseDecision,...K.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:K.proposedExecpolicyAmendment}:{}}),!0;let ue=D.options[O];return ue?(D.methodLower.includes("requestapproval")?D.resolveResponse({decision:ue}):D.resolveResponse({option:ue,index:O}),!0):!1},cl=typeof e.prompt=="string"?(async function*(){yield{type:"user",text:e.prompt,session_id:e.resumeSessionId??""}})():e.prompt;return(async()=>{try{await b();for await(let O of cl){let D=nP(O).trim();!D||await Le(D)||await F(D)}}catch(O){o.enqueue(xr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:S,result:Cm(O),session_id:i??e.resumeSessionId??""}))}finally{await n.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(O){l=O,o.enqueue(di(O))},async submitPendingInputOption(O){return pl(O)},async submitPendingInputText(O){return Le(O)},async interrupt(){!i||!s||await Gn({client:n,methods:["turn/interrupt"],payloads:Am({threadId:i,turnId:s}),timeoutMs:Ar}).catch(()=>{})}}}buildUserMessage(e,r){return{type:"user",text:e,session_id:r}}}});function $m(t){bd.set(t.name,t)}function Hn(t){let e=bd.get(t);if(!e)throw new Error(`Unknown agent harness: "${t}". Available: ${[...bd.keys()].join(", ")}`);return e}function Em(){return Hn(Pe())}var bd,xd=u(()=>{cm();_m();Re();bd=new Map;$m(new li);$m(new fi)});function $(t){return t.backendRef?.conversationId??t.harnessSessionId}function re(t){return t.id??t.sessionId??t.name??$(t)??t.harnessSessionId}function oP(t){return t.harnessSessionId}function et(t){let e=[re(t),$(t),oP(t)].filter(r=>!!r);return[...new Set(e)]}function Ad(t){return t.harnessName??t.persistedHarness??Pe()}function gi(t){if(t.backendRef?.kind==="codex-app-server")return"native-restore";try{return Hn(Ad(t)).capabilities.worktrees}catch{return"plugin-managed"}}function Rd(t){return t==="native-execution"||t==="native-restore"}function Om(t){return t==="native-restore"}function iP(t){return!!(t.backendRef?.worktreePath||t.backendRef?.worktreeId)}function Ne(t){return Rd(gi(t))&&iP(t)}var ke=u(()=>{Re();xd()});import{execFileSync as be}from"child_process";import*as Ii from"fs";import{tmpdir as wP}from"os";import{dirname as Qm,join as IP}from"path";function bP(t){try{return be("git",["rev-parse","--show-toplevel"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function bi(t){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(_.worktreeDir)return _.worktreeDir;if(t){let e=bP(t);if(e)return IP(e,".worktrees")}return wP()}function Jm(t){return t.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function xi(t){try{let e=be("git",["-C",t,"rev-parse","--git-common-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e&&e.endsWith("/.git")?Qm(e):void 0}catch{return}}function xP(){if(Pi!==void 0)return Pi;try{return be("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),Pi=!0,!0}catch{return Pi=!1,!1}}function ir(){if(wi!==void 0)return wi;try{return be("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),wi=!0,!0}catch{return wi=!1,!1}}function Cd(t){if(!xP())return!1;try{return be("git",["rev-parse","--git-dir"],{cwd:t,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Ym(t){try{let e=RP(t);if(!e)return console.warn(`[worktree] Failed to resolve free-space probe path for ${bi(t)}`),!0;let r=Ii.statfsSync(e),n=r.bavail*r.bsize;return TP(n)}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function Ai(t,e){try{return be("git",["-C",t,"rev-parse","--verify",e],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function AP(t){let e=t;for(;;){if(Ii.existsSync(e))return e;let r=Qm(e);if(r===e)return;e=r}}function RP(t){return AP(bi(t))}function TP(t){return t>=104857600}function sr(t){let e=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(e)return e;try{let n=be("git",["-C",t,"rev-parse","--abbrev-ref","origin/HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().replace(/^origin\//,"");if(n)return n}catch{}try{return be("git",["-C",t,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return be("git",["-C",t,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function Ri(t){try{let r=be("git",["-C",t,"rev-parse","--abbrev-ref","HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r==="HEAD"){console.warn(`[worktree] Worktree ${t} is in detached HEAD state \u2014 cannot determine branch name`);return}return r||void 0}catch{return}}function _d(t,e,r){try{let n=be("git",["-C",t,"rev-list","--count",`${r}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(n.trim(),10)>0}catch{return!1}}function Xm(t,e,r){try{let n=be("git",["-C",t,"rev-list","--left-right","--count",`${e}...${r}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),[o,i]=n.split(/\s+/);return{ahead:parseInt(o??"0",10)||0,behind:parseInt(i??"0",10)||0}}catch{return}}function Zm(t,e,r){try{return be("git",["-C",t,"merge-base","--is-ancestor",e,r],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function ef(t,e,r){try{let n=be("git",["-C",t,"merge-tree","--write-tree",r,e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=be("git",["-C",t,"rev-parse",`${r}^{tree}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return!!n&&n===o}catch{return!1}}function $t(t,e){try{return be("git",["-C",t,"branch","-D",e],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){return console.warn(`[worktree] Failed to delete branch ${e}: ${r instanceof Error?r.message:String(r)}`),!1}}function tf(t,e){if(e)return e;let r;try{r=be("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}try{let n=be("git",["-C",t,"remote","get-url","upstream"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n&&n!==r){let o=n.match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/);if(o)return o[1]}}catch{}}var Pi,wi,Jn=u(()=>{Re()});import{execFileSync as Yn}from"child_process";import{existsSync as MP,mkdirSync as rf,rmSync as nf}from"fs";function $d(t,e){let r=Jm(e),n=bi(t);rf(n,{recursive:!0});let o,i,s=10;for(let d=0;d<s;d++){let l=d===0?"":`-${Math.random().toString(16).slice(2,6)}`,m=`${n}/openclaw-worktree-${r}${l}`,S=`agent/${r}${l}`;try{rf(m,{recursive:!1}),o=m,i=S;break}catch(y){if(y&&typeof y=="object"&&"code"in y&&y.code==="EEXIST")continue;throw y}}if(!o||!i)throw new Error(`Failed to create unique worktree directory after ${s} attempts`);let a=Ai(t,i);try{a?Yn("git",["-C",t,"worktree","add",o,i],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):Yn("git",["-C",t,"worktree","add","-b",i,o],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(d){try{nf(o,{recursive:!0,force:!0})}catch{}throw d}return o}function CP(t){if(!MP(t))return[];try{let e=Yn("git",["-C",t,"status","--porcelain","--untracked-files=all"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return e?e.split(`
5
+ `).map(r=>r.trim()).filter(Boolean):[]}catch{return[]}}function tt(t,e,r={}){let n=r.destructive===!0,o=CP(e);if(o.length>0&&!n)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${e}: ${o[0]}`),!1;try{return Yn("git",["-C",t,"worktree","remove",...n?["--force"]:[],e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(i){if(console.warn(`[worktree] git worktree remove failed for ${e}: ${i instanceof Error?i.message:String(i)}`),!n)return!1;try{return nf(e,{recursive:!0,force:!0}),console.info(`[worktree] Fallback rmSync succeeded for ${e}`),!0}catch(s){return console.error(`[worktree] Both git worktree remove and rmSync failed for ${e}: ${s instanceof Error?s.message:String(s)}`),!1}}}function Ti(t){try{Yn("git",["-C",t,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var of=u(()=>{Jn()});import{execFileSync as ne}from"child_process";import{existsSync as _P}from"fs";function Tr(t,e,r){try{let n=ne("git",["-C",t,"rev-list","--count",`${r}..${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(n.trim(),10),s=ne("git",["-C",t,"diff","--shortstat",`${r}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,l=0,m=s.match(/(\d+)\s+files?\s+changed/);m&&(a=parseInt(m[1],10));let S=s.match(/(\d+)\s+insertions?\(/);S&&(d=parseInt(S[1],10));let y=s.match(/(\d+)\s+deletions?\(/);y&&(l=parseInt(y[1],10));let v=ne("git",["-C",t,"diff","--name-only","--diff-filter=ACMR",`${r}...${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
6
+ `).map(w=>w.trim()).filter(Boolean),x=ne("git",["-C",t,"log",`${r}..${e}`,"--format=%h|%s|%an","-n","5"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
7
+ `).filter(Boolean).map(w=>{let[C,b,M]=w.split("|");return{hash:C||"",message:b||"",author:M||""}});return{commits:o,filesChanged:a,insertions:d,deletions:l,changedFiles:v,commitMessages:x}}catch(n){console.warn(`[worktree] Failed to get diff summary: ${n instanceof Error?n.message:String(n)}`);return}}function Mi(t,e,r="origin"){try{return ne("git",["-C",t,"push",r,e],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to push branch ${e}: ${n instanceof Error?n.message:String(n)}`),!1}}function an(t){try{return ne("git",["-C",t,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
8
+ `).some(r=>r.length>0&&!r.startsWith("??")&&!r.startsWith("!!"))}catch{return!1}}function Ci(t,e,r,n="merge",o){let i=!1,s,a=d=>{if(i)try{ne("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(n==="squash"){if(ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),an(t)){let y;try{y=ne("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(f){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${f instanceof Error?f.message:String(f)}. Commit or stash changes manually, then retry.`}}if(!y.includes("No local changes to save")){i=!0;try{s=ne("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}ne("git",["-C",t,"merge","--squash",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ne("git",["-C",t,"commit","-m",`Squash merge ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let S=!1;if(i)try{ne("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{S=!0}return{success:!0,stashed:i||void 0,stashRef:s,stashPopConflict:S||void 0}}let d=o&&_P(o),l=d?o:t;if(d||ne("git",["-C",t,"checkout",e],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),an(t)){let S;try{S=ne("git",["-C",t,"stash","push","-m",`pre-merge stash before ${e}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(y){try{ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${y instanceof Error?y.message:String(y)}. Commit or stash changes manually, then retry.`}}if(!S.includes("No local changes to save")){i=!0;try{s=ne("git",["-C",t,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{ne("git",["-C",l,"rebase",r],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{ne("git",["-C",l,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(t),{success:!1,rebaseConflict:!0,stashed:i||void 0,stashRef:s,error:[`Rebase of ${e} onto ${r} hit conflicts.`,"To resolve manually:",` cd ${l}`,` git rebase ${r}`," # resolve conflicts in each file, then:"," git add <file>"," git rebase --continue"," # repeat until rebase finishes, then re-run agent_merge."].join(`
9
+ `)}}ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ne("git",["-C",t,"merge","--ff-only",e],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let m=!1;if(i)try{ne("git",["-C",t,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{m=!0}return{success:!0,fastForward:!0,stashed:i||void 0,stashRef:s,stashPopConflict:m||void 0}}catch(d){try{ne("git",["-C",t,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(t),{success:!1,error:d instanceof Error?d.message:String(d),stashed:i||void 0,stashRef:s}}}var Ed=u(()=>{});import{execFileSync as _i}from"child_process";function sf(t,e,r,n,o,i){if(!ir())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s;if(i)try{let S=_i("git",["-C",t,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[:/]([^/]+)\/[^/]+(?:\.git)?$/);S&&(s=S[1])}catch{}let a=["pr","create","--base",r];return i&&a.push("--repo",i),s?a.push("--head",`${s}:${e}`):a.push("--head",e),n&&o?a.push("--title",n,"--body",o):a.push("--fill-verbose"),{success:!0,prUrl:_i("gh",a,{cwd:t,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}function Xn(t,e,r){if(!ir())return{exists:!1,state:"none"};try{let n=["pr","list","--head",e,"--state","all","--json","url,number,title,state","--jq",".[0]"];r&&n.push("--repo",r);let i=_i("gh",n,{cwd:t,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!i)return{exists:!1,state:"none"};let s=JSON.parse(i),a=s.state.toLowerCase();return{exists:!0,state:a==="open"?"open":a==="merged"?"merged":a==="closed"?"closed":"none",url:s.url,number:s.number,title:s.title}}catch(n){return console.warn(`[worktree] Failed to sync PR status for ${e}: ${n instanceof Error?n.message:String(n)}`),{exists:!1,state:"none"}}}function af(t,e,r,n){if(!ir())return!1;try{let o=["pr","comment",String(e),"--body",r];return n&&o.push("--repo",n),_i("gh",o,{cwd:t,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(o){return console.warn(`[worktree] Failed to comment on PR #${e}: ${o instanceof Error?o.message:String(o)}`),!1}}function Mr(t){if(t.kind==="merge"){let e=t.filesChanged!==void 0?` (${t.filesChanged} files, +${t.insertions??0}/-${t.deletions??0})`:"";return`\u2705 Merged: ${t.branch} \u2192 ${t.base??"main"}${e}`}return t.kind==="pr-updated"?`\u2705 PR updated: ${t.prUrl??""}`:t.targetRepo?`\u2705 PR opened against ${t.targetRepo}: ${t.prUrl??""}`:`\u2705 PR opened: ${t.prUrl??""}`}var Od=u(()=>{Jn()});import{existsSync as Dd}from"fs";function df(){return new Date().toISOString()}function $P(t){return t.worktreeLifecycle??{state:t.worktreePath||t.worktreeBranch?"provisioned":"none",updatedAt:df(),baseBranch:t.worktreeBaseBranch,targetRepo:t.worktreePrTargetRepo,pushRemote:t.worktreePushRemote}}function EP(t){return t.worktreeLifecycle?.baseBranch??t.worktreeBaseBranch??(Dd(t.workdir)?sr(t.workdir):void 0)}function Zn(t,e={}){let r=$P(t),n=df(),o=new Set,i=Dd(t.workdir),s=!!(t.worktreePath&&Dd(t.worktreePath)),a=t.worktreeBranch,d=EP(t),l=!1,m=!1,S=!1,y=!1,f,v,A=t.worktreePrUrl?"open":"none",x=t.worktreePrUrl,w=t.worktreePrNumber;if(i||o.add("repo_missing"),a||o.add("branch_missing"),!s&&t.worktreePath&&o.add("worktree_missing"),e.activeSession&&o.add("active_session"),r.state==="pending_decision"&&o.add("pending_decision"),r.state==="merge_conflict_resolving"&&o.add("merge_conflict_resolving"),i&&a&&(l=Ai(t.workdir,a),l||o.add("branch_missing")),s&&t.worktreePath&&(m=an(t.worktreePath),m&&o.add("dirty_tracked_changes")),i&&l&&d){let Le=Xm(t.workdir,a,d);f=Le?.ahead,v=Le?.behind,S=Zm(t.workdir,a,d),S?o.add("topology_merged"):(y=ef(t.workdir,a,d),y&&o.add("merge_noop_content_already_on_base"),!y&&(f??0)>0&&o.add("unique_content"))}else d||o.add("base_branch_missing");if(e.includePrSync&&i&&a){let Le=Xn(t.workdir,a,t.worktreePrTargetRepo??r.targetRepo);A=Le.state,x=Le.url??x,w=Le.number??w}A==="open"&&o.add("pr_open"),A==="merged"&&!S&&!y&&o.add("pr_merged_not_reflected_locally");let C=r.state;S?C="merged":y?C="released":!l&&r.state==="pending_decision"&&(C="cleanup_failed");let b=e.activeSession||m||r.state==="pending_decision"||r.state==="merge_conflict_resolving"||r.state==="pr_open"||A==="open"||o.has("pr_merged_not_reflected_locally"),M=!b&&(C==="merged"||C==="released"||r.state==="dismissed"||r.state==="no_change"),F={checkedAt:n,repoExists:i,branchExists:l,worktreeExists:s,activeSession:e.activeSession===!0,dirtyTracked:m,topologyMerged:S,releaseNoopMerge:y,branchAheadCount:f,baseAheadCount:v,prState:A,prUrl:x,prNumber:w,reasons:[...o]};return{lifecycle:r,evidence:F,derivedState:C,cleanupSafe:M,preserve:b,reasons:[...o]}}var $i=u(()=>{Jn();Od();Ed()});var ut=u(()=>{Jn();of();Ed();Od();$i()});function dn(t,e){let r=t.resolve(e),n=t.getPersistedSession(e),o=r?re(r):n?re(n):void 0;return{activeSession:r,persistedSession:n,persistedRef:o,sessionName:r?.name??n?.name??e,worktreePath:r?.worktreePath??n?.worktreePath,originalWorkdir:r?.originalWorkdir??n?.workdir,branchName:r?.worktreeBranch??n?.worktreeBranch,notificationTarget:r??(n?{id:o??e,harnessSessionId:n.harnessSessionId,backendRef:n.backendRef,route:n.route}:void 0)}}function Af(t){return t.persistedSession?et(t.persistedSession):[]}function aw(t,e){let r=[e.id,e.backendConversationId,e.harnessSessionId,e.name],n,o;for(let i of r)if(i&&(n??=t.resolve(i),o??=t.getPersistedSession(i),n&&o))break;return{activeSession:n,persistedSession:o}}function Ui(t,e,r={}){let{activeSession:n,persistedSession:o}=aw(t,e),i=Zn({workdir:e.workdir,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeBaseBranch:r.baseBranch??o?.worktreeBaseBranch,worktreePrTargetRepo:o?.worktreePrTargetRepo,worktreePushRemote:o?.worktreePushRemote,worktreePrUrl:o?.worktreePrUrl,worktreePrNumber:o?.worktreePrNumber,worktreeLifecycle:o?.worktreeLifecycle},{activeSession:!!(n&&(n.status==="starting"||n.status==="running")),includePrSync:!!(o?.worktreeLifecycle?.state==="pr_open"||o?.worktreePrUrl)});return{activeSession:n,persistedSession:o,resolvedLifecycle:i}}function Ki(t){let e=t.list("all").filter(o=>o.worktreePath),r=t.listPersistedSessions().filter(o=>o.worktreePath),n=new Map;for(let o of r){if(!o.worktreePath)continue;let i=$(o),s=o.sessionId??i??o.harnessSessionId;s&&n.set(s,{id:o.sessionId??i??o.harnessSessionId,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.workdir,worktreeMerged:o.worktreeMerged,worktreeMergedAt:o.worktreeMergedAt,worktreePrUrl:o.worktreePrUrl,backendConversationId:i,harnessSessionId:o.harnessSessionId})}for(let o of e)o.worktreePath&&n.set(o.id,{id:o.id,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.originalWorkdir??o.workdir,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0,backendConversationId:$(o),harnessSessionId:o.harnessSessionId});return Array.from(n.values())}function Vi(t,e){return t.id===e||t.name===e||t.backendConversationId===e||t.harnessSessionId===e}function _r(t){switch(t){case"none":return"none";case"provisioned":return"active";case"pending_decision":return"needs decision";case"merge_conflict_resolving":return"conflict resolving";case"pr_open":return"pr open";case"merged":return"merged";case"released":return"released";case"dismissed":return"dismissed";case"no_change":return"no change";case"cleanup_failed":return"cleanup failed";default:return t}}function qi(t){switch(t){case"active_session":return"active session";case"pending_decision":return"pending decision";case"merge_conflict_resolving":return"conflict resolving";case"dirty_tracked_changes":return"dirty worktree";case"unique_content":return"still has unique content";case"topology_merged":return"merged by ancestry";case"merge_noop_content_already_on_base":return"content already on base";case"pr_open":return"PR open";case"pr_merged_not_reflected_locally":return"merged PR not reflected locally";case"repo_missing":return"repo missing";case"branch_missing":return"branch missing";case"worktree_missing":return"worktree missing";case"base_branch_missing":return"base branch missing";default:return t.replaceAll("_"," ")}}var to=u(()=>{ke();$i()});var Rf={};lo(Rf,{makeAgentPrTool:()=>ro});import{existsSync as lw}from"fs";function uw(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ro(t){return{name:"agent_pr",description:"Create or update a GitHub PR for a worktree branch. Handles full PR lifecycle: creates new PRs, updates existing open PRs with comments, and handles merged/closed PRs. Pushes the branch, syncs PR state, and persists metadata.",parameters:p.Object({session:p.String({description:"Session name or ID to create/update PR for"}),title:p.Optional(p.String({description:"PR title (default: auto-generated from session name)"})),body:p.Optional(p.String({description:"PR body (default: auto-generated from commit summary)"})),base_branch:p.Optional(p.String({description:"Base branch for the PR (default: detected from repo)"})),force_new:p.Optional(p.Boolean({description:"Force creation of a new PR even if one exists (default: false)"})),target_repo:p.Optional(p.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex'). Auto-detected from 'upstream' remote if not set."}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}],meta:{success:!1,state:"error"}};if(!uw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!ir())return{content:[{type:"text",text:"Error: GitHub CLI (gh) is not available. Install it and authenticate to create PRs."}],meta:{success:!1,state:"error"}};let n=dn(k,r.session),o=n.activeSession,i=n.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}],meta:{success:!1,state:"error"}};let{worktreePath:s,originalWorkdir:a,sessionName:d,branchName:l}=n;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}],meta:{success:!1,state:"error"}};if(!l)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree ${s}. The worktree may have been removed and no persisted branch name is available.`}],meta:{success:!1,state:"error"}};lw(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${l}" via originalWorkdir (${a})`);let m=r.base_branch??sr(a),S=n.persistedRef,y=tf(a,r.target_repo??i?.worktreePrTargetRepo);if(!Mi(a,l))return{content:[{type:"text",text:`\u274C Failed to push ${l} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let f=Xn(a,l,y);if(r.force_new&&f.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${l} (${f.state}).
39
10
 
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}).
11
+ Existing PR: ${f.url}
42
12
 
43
- Existing PR: ${c.url}
13
+ To create a new PR, you must first close/merge the existing PR manually or use a different branch.`}],meta:{success:!1,state:"error"}};if(f.exists&&f.state==="open"){let v=Tr(a,l,m);if(v&&v.commits>0){let A=v.commitMessages.slice(0,5).map(b=>`\u2022 ${b.hash} ${b.message} (${b.author})`).join(`
14
+ `),x=v.commits>5?`
15
+ ...and ${v.commits-5} more commits`:"",w=["\u{1F504} **New commits pushed**","",`${v.commits} new commits (+${v.insertions} / -${v.deletions})`,"","### Latest commits:",A+x,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
16
+ `);if(af(a,f.number,w,y)){S&&k.updatePersistedSession(S,{worktreePrUrl:f.url,worktreePrNumber:f.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:m,targetRepo:y,pushRemote:i?.worktreePushRemote}});let b=Mr({kind:"pr-updated",branch:l,prUrl:f.url});return k.notifyWorktreeOutcome(n.notificationTarget,b),{content:[{type:"text",text:`${b}
44
17
 
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}
18
+ \u{1F4DD} Added comment detailing ${v.commits} new commits (+${v.insertions} / -${v.deletions})`}],meta:{success:!0,state:"pr_updated"}}}else return{content:[{type:"text",text:`\u26A0\uFE0F Pushed to ${f.url} but failed to add comment.
49
19
 
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.
20
+ ${v.commits} new commits (+${v.insertions} / -${v.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return S&&k.updatePersistedSession(S,{worktreePrUrl:f.url,worktreePrNumber:f.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:m,targetRepo:y,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${f.url}
51
21
 
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}
22
+ No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else{if(f.exists&&f.state==="merged")return S&&k.updatePersistedSession(S,{worktreePrUrl:f.url,worktreePrNumber:f.number,worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDisposition:"merged",worktreeLifecycle:{state:"merged",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"agent_pr",baseBranch:m,targetRepo:y,pushRemote:i?.worktreePushRemote}}),{content:[{type:"text",text:`\u2705 PR was already merged: ${f.url}
53
23
 
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}
24
+ The worktree branch ${l} can be cleaned up with agent_merge(delete_branch=true).`}],meta:{success:!0,state:"merged"}};if(f.exists&&f.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${f.url}
57
25
 
58
26
  What would you like to do?
59
27
 
@@ -61,63 +29,185 @@ What would you like to do?
61
29
  2. Close and delete the branch with agent_merge(delete_branch=true), then start a new session/worktree
62
30
  3. Manually delete the closed PR on GitHub, then call agent_pr(force_new=true) to create a fresh PR
63
31
 
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]
74
- /agent_resume --list \u2014 list 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:
76
-
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(`
78
- `)}).join(`
79
-
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")?"":`
83
-
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.]
88
-
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.]
90
-
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:
112
-
113
- ${r}
114
-
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(`
117
- `):i=["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`].join(`
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};
32
+ (This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let v=r.title??`[openclaw-code-agent] ${d}`,A=r.body;if(!A){let w=Tr(a,l,m);if(w){let C=w.commitMessages.slice(0,5).map(M=>`\u2022 ${M.hash} ${M.message} (${M.author})`).join(`
33
+ `),b=w.commits>5?`
34
+ ...and ${w.commits-5} more`:"";A=[`Automated changes from OpenClaw Code Agent session: ${d}`,"","## Summary",`${w.commits} commits, ${w.filesChanged} files changed (+${w.insertions} / -${w.deletions})`,"","## Commits",C+b,"","---","\u{1F916} Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
35
+ `)}else A=`Automated changes from OpenClaw Code Agent session: ${d}`}let x=sf(a,l,m,v,A,y);if(x.success&&x.prUrl){let w=Xn(a,l,y);S&&k.updatePersistedSession(S,{worktreePrUrl:x.prUrl,worktreePrNumber:w.number,lifecycle:"terminal",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeState:"pr_open",worktreeDisposition:"pr-opened",worktreeLifecycle:{state:"pr_open",updatedAt:new Date().toISOString(),baseBranch:m,targetRepo:y,pushRemote:i?.worktreePushRemote}});let C=Mr({kind:"pr-opened",branch:l,targetRepo:y,prUrl:x.prUrl});return k.notifyWorktreeOutcome(n.notificationTarget,C),{content:[{type:"text",text:C}],meta:{success:!0,state:"created"}}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${x.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var Gi=u(()=>{Ee();Y();ut();to()});import{readdirSync as kb,statSync as vb,rmSync as Pb}from"fs";import{execFileSync as wb}from"child_process";import{join as Og}from"path";Ee();Y();function hv(t){return t.length>80?`${t.slice(0,80)}...`:t}function Sv(t){return t.worktreePath?!t.originalWorkdir||t.originalWorkdir===t.worktreePath?`${t.worktreePath} (worktree)`:`${t.worktreePath} (worktree of ${t.originalWorkdir})`:t.workdir}function yv(t){let e=["Session launched successfully.",` Name: ${t.sessionName}`,` ID: ${t.sessionId}`,` Harness: ${t.harness}`,` Permission mode: ${t.permissionMode}`,` Plan approval: ${t.planApproval}`,` Worktree strategy: ${t.worktreeStrategy??"off"}`,` Resolved workdir: ${Sv(t)}`,` Model: ${t.model??"default"}`,` Prompt: "${hv(t.prompt)}"`];return t.reasoningEffort&&e.push(` Reasoning effort: ${t.reasoningEffort}`),t.resumeSessionId?e.push(` Resume: ${t.resumeSessionId}${t.forkSession?" (forked)":""}`):t.forceNewSession&&e.push(" Force new session: true"),t.clearedPersistedCodexResume&&e.push(" Thread state: historical Codex state cleared; starting a fresh thread."),e.push(" Mode: multi-turn (use agent_respond to send follow-up messages)"),e.push("","Use agent_sessions to check status, agent_output to see output."),e.join(`
36
+ `)}function ti(t,e){return yv({...t,sessionId:e.id,sessionName:e.name,model:e.model,reasoningEffort:e.reasoningEffort,worktreeStrategy:e.worktreeStrategy??"off",worktreePath:e.worktreePath,originalWorkdir:e.originalWorkdir})}Re();function tn(t){let{requestedResumeSessionId:e,activeSession:r,persistedSession:n}=t;return e?r?{resumeSessionId:e,clearedPersistedCodexResume:!1}:n?.harness==="codex"&&n.backendRef?.kind!=="codex-app-server"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:e,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}ke();function Td(t){return"id"in t?t.id:t.sessionId}function zn(t){return t.status==="completed"||t.killReason==="done"}function sP(t){return zn(t)&&t.backendRef?.kind==="codex-app-server"&&!!$(t)}function aP(t){return(t.killReason==="shutdown"||t.killReason==="startup-timeout")&&!$(t)}function Qn(t){if(t.status==="running")return{kind:"direct",reason:"already_running"};let e=Td(t);if(zn(t)&&!sP(t))return{kind:"unavailable",reason:"completed",stableSessionId:e};let r=$(t);if(r){let n="harnessName"in t?void 0:t,{resumeSessionId:o,clearedPersistedCodexResume:i}=tn({requestedResumeSessionId:r,activeSession:"harnessName"in t?{harnessSessionId:r}:void 0,persistedSession:n?{harness:n.harness,backendRef:n.backendRef}:void 0});return o?{kind:"resume",resumeSessionId:o,stableSessionId:e,clearedPersistedCodexResume:i}:{kind:"unavailable",reason:"legacy_non_resumable",stableSessionId:e,clearedPersistedCodexResume:i}}return aP(t)?{kind:"relaunch",stableSessionId:e}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:e}}Re();import{existsSync as Lm}from"fs";ke();function Dm(t){return t==null?void 0:String(t).trim()||void 0}function dP(t){return t.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function lP(t){let e=t.split(/\n\s*\n/,1)[0]?.split(`
37
+ `).map(r=>r.trim()).filter(Boolean)??[];if(e.length!==0)for(let r of e){let n=r.match(/^(Workdir|Repo):\s*(.+)$/),o=dP(n?.[2]??"");if(o.startsWith("/")&&Lm(o))return o}}function Nm(t,e){return t.workdir!==e.workdir?!1:e.originSessionKey&&t.originSessionKey?t.originSessionKey===e.originSessionKey:!e.originChannel||!t.originChannel?!1:t.originChannel===e.originChannel&&Dm(t.originThreadId)===Dm(e.originThreadId)}function Fm(t){return t.slice(0,3).map(e=>` - ${e.name} [${e.ref}] | status=${e.status}${e.lifecycle?` | lifecycle=${e.lifecycle}`:""}`).join(`
38
+ `)}function uP(t,e){let r=[],n=[],o=new Set;for(let i of t.list?.("all")??[]){if(!Nm(i,e))continue;let s=i.id;if(!o.has(s)){if(o.add(s),i.isExplicitlyResumable){r.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0});continue}(i.status==="starting"||i.status==="running")&&n.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!1})}}for(let i of t.listPersistedSessions?.()??[]){if(!i.resumable||!Nm(i,e))continue;let s=re(i)??i.harnessSessionId,a=i.sessionId??$(i)??i.harnessSessionId;!s||!a||o.has(a)||(o.add(a),r.push({ref:s,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0}))}return{resumable:r,active:n}}function pP(t,e){if(!e||e.length===0)return!0;if(!t)return!1;let r=t.toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function Wm(t,e,r){let n=t.workdir||lP(t.prompt)||e.workspaceDir||_.defaultWorkdir||process.cwd();if(!Lm(n))return{kind:"error",text:`Error: Working directory does not exist: ${n}`};let o=t.harness??Pe(),i=Ct(o),s=t.model??i,a=t.model!==void 0;if(!s)return{kind:"error",text:`Error: No default model configured for harness "${o}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${o}.defaultModel or pass model explicitly.`};let d=en(o);if(d&&d.length>0&&!pP(s,d))return{kind:"error",text:a?`Error: Model "${s}" is not allowed. Permitted models: ${d.join(", ")}`:`Error: Default model "${s||"undefined"}" is not in allowedModels (${d.join(", ")}). Update your plugin config to set a compatible defaultModel.`};let l=ni(e),m=qt(e,l||Kn(n)),S=e.sessionKey||void 0,y=dm(S)??Un(e);if(!t.resume_session_id&&!t.force_new_session){let M=uP(r,{workdir:n,originSessionKey:S,originChannel:m,originThreadId:y});if(M.resumable.length>0||M.active.length>0){let F=M.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",Fm(M.resumable),"","Resume the latest one with:",` agent_respond(session='${M.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${M.resumable[0].ref}', fork_session=true)`].join(`
39
+ `):"",Le=M.active.length>0?[M.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",Fm(M.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${M.active[0].ref}', message='<next instruction>')`].join(`
40
+ `):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",F,Le,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
41
+ `)].filter(Boolean).join(`
42
+
43
+ `)}}}let f=t.resume_session_id,v=f?r.resolve?.(f):void 0,A=f?r.getPersistedSession?.(f):void 0;if(f){let M=r.resolveBackendConversationId?.(f)??r.resolveHarnessSessionId?.(f);if(!M)return{kind:"error",text:`Error: Could not resolve resume_session_id "${f}" to a session ID. Use agent_sessions to list available sessions.`};f=M}let{resumeSessionId:x,clearedPersistedCodexResume:w}=tn({requestedResumeSessionId:f,activeSession:v?{harnessSessionId:v.backendConversationId??v.harnessSessionId}:void 0,persistedSession:A?{harness:A.harness,backendRef:A.backendRef}:void 0}),C=t.permission_mode??_.permissionMode,b=t.plan_approval??_.planApproval;return{kind:"resolved",workdir:n,harness:o,resolvedModel:s,permissionMode:C,planApproval:b,originChannel:m,originThreadId:y,originSessionKey:S,route:_t(e,m,S),resumeSessionId:x,resolvedResumeId:f,clearedPersistedCodexResume:w,reasoningEffort:lt(o)}}function cP(t){return t instanceof Error?t.message:String(t)}function Bm(t,e){return t?("id"in t?t.id:t.sessionId)??e??"unknown-session":e??"unknown-session"}function mP(t){return!t||typeof t!="object"?!1:typeof t.prompt=="string"}function fP(t){return!!t&&typeof t=="object"&&typeof t.formatLaunchResult=="function"}function Um(t){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn \u2014 they stay open for follow-up messages via agent_respond. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:p.Object({prompt:p.String({description:"The task prompt to execute"}),name:p.Optional(p.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:p.Optional(p.String({description:"Working directory (defaults to cwd)"})),model:p.Optional(p.String({description:"Model name to use"})),system_prompt:p.Optional(p.String({description:"Additional system prompt"})),allowed_tools:p.Optional(p.Array(p.String(),{description:"List of allowed tools"})),resume_session_id:p.Optional(p.String({description:"Session reference to continue or fork from. Prefer the plugin session ID shown by agent_launch or agent_sessions; persisted backend conversation IDs also resolve when available."})),fork_session:p.Optional(p.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),force_new_session:p.Optional(p.Boolean({description:"Bypass resume-first protection and start a brand-new linked session even when a resumable or active linked session already exists."})),permission_mode:p.Optional(p.Union([p.Literal("default"),p.Literal("plan"),p.Literal("bypassPermissions")],{description:"Permission mode: 'default' (plugin-managed interactive execution), 'plan' (present the plan first and block implementation until approval), 'bypassPermissions' (fully autonomous execution). Defaults to plugin config ('plan' by default)."})),plan_approval:p.Optional(p.Union([p.Literal("ask"),p.Literal("delegate"),p.Literal("approve")],{description:"Plan approval policy for this session: 'ask' (send the full plan to the user with Approve/Revise/Reject buttons), 'delegate' (orchestrator must review the full plan, then either approve directly or escalate back to the user with the same buttons), 'approve' (auto-approve after verification). Overrides the plugin-level planApproval setting."})),harness:p.Optional(p.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."})),worktree_strategy:p.Optional(p.Union([p.Literal("off"),p.Literal("manual"),p.Literal("ask"),p.Literal("delegate"),p.Literal("auto-merge"),p.Literal("auto-pr")],{description:"Worktree strategy: 'off' (no worktree), 'manual' (create worktree but no auto merge-back), 'ask' (prompt user with Merge/PR/Decide later/Dismiss buttons), 'delegate' (orchestrator decides), 'auto-merge' (merge automatically), 'auto-pr' (open/update a PR automatically). Defaults to the plugin config when unset."})),worktree_base_branch:p.Optional(p.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),worktree_pr_target_repo:p.Optional(p.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex' for fork-to-upstream workflow). If not set, auto-detected from 'upstream' remote or defaults to 'origin'."}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!mP(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};r.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${r.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${t.agentId}" will be used for origin routing instead.`);try{let n=Wm(r,t,k);if(n.kind!=="resolved")return{content:[{type:"text",text:n.text}]};let{workdir:o,harness:i,resolvedModel:s,permissionMode:a,planApproval:d,originChannel:l,originThreadId:m,originSessionKey:S,route:y,resumeSessionId:f,resolvedResumeId:v,clearedPersistedCodexResume:A,reasoningEffort:x}=n,w=r.resume_session_id?k.resolve(r.resume_session_id)??k.getPersistedSession(r.resume_session_id):void 0,C=!r.fork_session&&w?Qn(w):void 0;if(C?.kind==="direct")return{content:[{type:"text",text:`Session ${w.name} [${Bm(w,r.resume_session_id)}] is already running. Use agent_respond(session='${r.resume_session_id}', message='<next instruction>') instead of agent_launch(resume_session_id=...).`}]};if(C?.kind==="unavailable")return{content:[{type:"text",text:`Resume unavailable for session ${w.name} [${Bm(w,r.resume_session_id)}] (${C.reason}). Use agent_launch(prompt='<new task>') for a fresh session or set fork_session=true to fork from prior context.`}]};let b=k.spawn({prompt:r.prompt,sessionIdOverride:r.fork_session?void 0:C?.kind==="resume"||C?.kind==="relaunch"?C.stableSessionId:void 0,name:r.name,workdir:o,model:s,reasoningEffort:x,systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,resumeSessionId:C?.kind==="resume"?C.resumeSessionId:f,resumeWorktreeFrom:v,forkSession:f?r.fork_session:!1,multiTurn:!0,permissionMode:a,planApproval:d,codexApprovalPolicy:i==="codex"?"never":void 0,originChannel:l,originThreadId:m,originAgentId:t.agentId||void 0,originSessionKey:S,route:y,harness:i,worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,worktreePrTargetRepo:r.worktree_pr_target_repo});return{content:[{type:"text",text:fP(k)?k.formatLaunchResult({prompt:r.prompt,workdir:o,harness:i,permissionMode:a??_.permissionMode,planApproval:d,forceNewSession:r.force_new_session,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,clearedPersistedCodexResume:A},b):ti({prompt:r.prompt,workdir:o,harness:i,permissionMode:a??_.permissionMode,planApproval:d,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,forceNewSession:r.force_new_session,clearedPersistedCodexResume:A},{id:b.id,name:b.name,model:b.model,reasoningEffort:b.reasoningEffort??lt(i),worktreeStrategy:b.worktreeStrategy??r.worktree_strategy??_.defaultWorktreeStrategy??"off",worktreePath:b.worktreePath,originalWorkdir:b.originalWorkdir})}]}}catch(n){let o=cP(n),i=o.includes("Max sessions")?"":`
44
+
45
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}Ee();Y();Re();import{existsSync as Nd,readFileSync as ff}from"fs";import{EventEmitter as OP}from"events";import{webcrypto as Vm}from"node:crypto";var Km="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var gP=128,Rr,on;function hP(t){!Rr||Rr.length<t?(Rr=Buffer.allocUnsafe(t*gP),Vm.getRandomValues(Rr),on=0):on+t>Rr.length&&(Vm.getRandomValues(Rr),on=0),on+=t}function hi(t=21){hP(t|=0);let e="";for(let r=on-t;r<on;r++)e+=Km[Rr[r]&63];return e}xd();Re();ke();var qm={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},jm=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function SP(t){return t.requestedPermissionMode!=="plan"?"not_plan_gated":t.pendingPlanApproval?"awaiting_approval":t.planModeApproved?"approved_then_implemented":t.currentPermissionMode!=="plan"?"implemented_without_required_approval":"awaiting_plan_output"}function Oe(t){return{...t,approvalExecutionState:SP(t)}}function Md(t,e){switch(e.type){case"initialize":return Oe({...t,worktreeState:e.hasWorktree&&t.worktreeState==="none"?"provisioned":t.worktreeState,lifecycle:t.status==="starting"?"starting":t.lifecycle,runtimeState:t.status==="starting"?"live":t.runtimeState});case"status.transition":return e.status==="starting"?Oe({...t,status:e.status,lifecycle:"starting",runtimeState:"live"}):e.status==="running"?Oe({...t,status:e.status,lifecycle:t.lifecycle==="starting"||t.lifecycle==="suspended"?"active":t.lifecycle,runtimeState:"live"}):Oe({...t,status:e.status,runtimeState:"stopped",lifecycle:t.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return Oe({...t,currentPermissionMode:e.currentPermissionMode});case"turn.started":return Oe({...t,lifecycle:"active",runtimeState:"live"});case"input.requested":return Oe({...t,lifecycle:t.pendingPlanApproval?"awaiting_plan_decision":"awaiting_user_input"});case"plan.requested":if(t.planModeApproved)return t;{let r=t.pendingPlanApproval&&t.approvalState==="pending"&&t.planApprovalContext===e.context,n=t.pendingPlanApproval&&t.approvalState==="changes_requested"&&t.planApprovalContext===e.context&&t.planDecisionVersion>0,o=!t.pendingPlanApproval&&t.approvalState==="changes_requested"&&t.planApprovalContext===e.context&&t.planDecisionVersion>0,i=r||n||o?t.planDecisionVersion:t.planDecisionVersion+1;return Oe({...t,pendingPlanApproval:!0,planApprovalContext:e.context,approvalState:"pending",planDecisionVersion:i,actionablePlanDecisionVersion:i,canonicalPlanPromptVersion:r?t.canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:r?t.approvalPromptRequiredVersion:void 0,approvalPromptVersion:r?t.approvalPromptVersion:void 0,approvalPromptStatus:r?t.approvalPromptStatus:"not_sent",approvalPromptTransport:r?t.approvalPromptTransport:"none",approvalPromptMessageKind:r?t.approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:r?t.approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:r?t.approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:r?t.approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"})}case"plan.cleared":return Oe({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,approvalState:t.approvalState==="pending"?"not_required":t.approvalState});case"plan.approved":return Oe({...t,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,planModeApproved:!0,approvalState:"approved",planDecisionVersion:t.planDecisionVersion+1,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",lifecycle:t.status==="running"?"active":t.lifecycle});case"plan.changes_requested":return Oe({...t,pendingPlanApproval:!0,approvalState:"changes_requested",planDecisionVersion:t.planDecisionVersion+1,actionablePlanDecisionVersion:void 0,canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:void 0,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",approvalPromptTransport:"none",approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"});case"terminal.entered":return Oe({...t,lifecycle:e.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return Oe({...t,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return Oe({...t,worktreeState:e.worktreeState,lifecycle:e.worktreeState==="pending_decision"?"awaiting_worktree_decision":jm.has(e.worktreeState)?"terminal":t.lifecycle});case"delivery.state_set":return Oe({...t,deliveryState:e.deliveryState})}}function Gm(t,e){let r={...t,...e.lifecycle!==void 0?{lifecycle:e.lifecycle}:{},...e.approvalState!==void 0?{approvalState:e.approvalState}:{},...e.approvalExecutionState!==void 0?{approvalExecutionState:e.approvalExecutionState}:{},...e.worktreeState!==void 0?{worktreeState:e.worktreeState}:{},...e.runtimeState!==void 0?{runtimeState:e.runtimeState}:{},...e.deliveryState!==void 0?{deliveryState:e.deliveryState}:{},...e.requestedPermissionMode!==void 0?{requestedPermissionMode:e.requestedPermissionMode}:{},...e.currentPermissionMode!==void 0?{currentPermissionMode:e.currentPermissionMode}:{},...e.pendingPlanApproval!==void 0?{pendingPlanApproval:e.pendingPlanApproval}:{},...e.planApprovalContext!==void 0?{planApprovalContext:e.planApprovalContext}:{},...e.planDecisionVersion!==void 0?{planDecisionVersion:e.planDecisionVersion}:{},...e.actionablePlanDecisionVersion!==void 0?{actionablePlanDecisionVersion:e.actionablePlanDecisionVersion}:{},...e.canonicalPlanPromptVersion!==void 0?{canonicalPlanPromptVersion:e.canonicalPlanPromptVersion}:{},...e.approvalPromptRequiredVersion!==void 0?{approvalPromptRequiredVersion:e.approvalPromptRequiredVersion}:{},...e.approvalPromptVersion!==void 0?{approvalPromptVersion:e.approvalPromptVersion}:{},...e.approvalPromptStatus!==void 0?{approvalPromptStatus:e.approvalPromptStatus}:{},...e.approvalPromptTransport!==void 0?{approvalPromptTransport:e.approvalPromptTransport}:{},...e.approvalPromptMessageKind!==void 0?{approvalPromptMessageKind:e.approvalPromptMessageKind}:{},...e.approvalPromptLastAttemptAt!==void 0?{approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt}:{},...e.approvalPromptDeliveredAt!==void 0?{approvalPromptDeliveredAt:e.approvalPromptDeliveredAt}:{},...e.approvalPromptFailedAt!==void 0?{approvalPromptFailedAt:e.approvalPromptFailedAt}:{},...e.planModeApproved!==void 0?{planModeApproved:e.planModeApproved}:{}};return e.approvalState==="changes_requested"&&e.pendingPlanApproval===void 0&&(r={...r,pendingPlanApproval:!1}),r.pendingPlanApproval?r={...r,approvalState:"pending",actionablePlanDecisionVersion:r.actionablePlanDecisionVersion??r.planDecisionVersion,lifecycle:"awaiting_plan_decision"}:r.approvalState==="changes_requested"&&(r={...r,actionablePlanDecisionVersion:void 0,lifecycle:"awaiting_user_input"}),e.pendingWorktreeDecisionSince!==void 0||r.worktreeState==="pending_decision"?r=Md(r,{type:"worktree.decision_requested"}):jm.has(r.worktreeState)&&(r={...r,lifecycle:"terminal"}),Oe(r)}var Si=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(e){this.queue.push(e),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(e=>{this.resolve=e})}}};import{appendFileSync as yP}from"fs";import{tmpdir as kP}from"os";import{join as vP}from"path";var Hm=2e3;function sn(t){return vP(kP(),`openclaw-agent-${t}.txt`)}function PP(t,e){if(!e)return;let r=e.split(`
46
+ `),[n="",...o]=r;t.length===0?t.push(n):t[t.length-1]+=n;for(let i of o)t.push(i)}function zm(t,e,r){PP(t,r),t.length>Hm&&t.splice(0,t.length-Hm);try{yP(sn(e),r,"utf-8")}catch{}return t}var yi=class{timers=new Map;get size(){return this.timers.size}set(e,r,n){this.clear(e);let o=setTimeout(n,r);o.unref?.(),this.timers.set(e,o)}clear(e){let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var ki=class{constructor(e){this.deps=e}deps;waitingForInputFired=!1;lastTurnHadQuestion=!1;turnInProgress=!0;currentTurnText="";currentTurnPlanArtifact;beginUserTurn(){this.waitingForInputFired=!1,this.turnInProgress=!0,this.currentTurnText="",this.currentTurnPlanArtifact=void 0,this.lastTurnHadQuestion=!1}noteTextDelta(e,r){this.waitingForInputFired=!1,r||(this.lastTurnHadQuestion=!1),this.deps.appendOutput(e),this.currentTurnText+=this.currentTurnText?`
47
+ ${e}`:e,this.deps.emitOutput(e)}noteToolCall(e){let{name:r,input:n,currentPermissionMode:o,permissionMode:i,planModeApproved:s}=e;if(r==="Write"){let a=n;typeof a?.file_path=="string"&&a.file_path.includes("/.claude/plans/")&&this.deps.setPlanFilePath(a.file_path)}r==="AskUserQuestion"?(this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),(o==="plan"||i==="plan")&&!s&&this.deps.markPendingPlanApproval("plan-mode")):(r==="ExitPlanMode"||r==="set_permission_mode")&&!s&&(this.lastTurnHadQuestion=!0,this.deps.markPendingPlanApproval("plan-mode")),this.deps.emitToolUse(r,n)}notePendingInput(){this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),this.waitingForInputFired||(this.waitingForInputFired=!0,this.deps.emitTurnEnd(!0))}clearResolvedPendingInput(e,r){if(!(!e||r?.requestId===e))return r}notePlanArtifact(e,r){if(this.currentTurnPlanArtifact=e,this.deps.setLatestPlanArtifact(e),!r)return;let n=e.markdown.trim();!n||this.currentTurnText.trim()===n||(this.deps.appendOutput(n),this.currentTurnText=n,this.deps.emitOutput(n))}noteSettingsChanged(e){let{oldMode:r,permissionMode:n,planModeApproved:o}=e;if(n)return n!=="plan"&&r==="plan"&&!o&&(this.deps.markPendingPlanApproval("plan-mode"),this.lastTurnHadQuestion=!0),n}finishSuccessfulTurn(e){let{currentPermissionMode:r,permissionMode:n,pendingPlanApproval:o,planModeApproved:i,pendingInputState:s,hasPendingMessages:a}=e,d=o;(r==="plan"||n==="plan")&&!d&&!i&&(this.deps.markPendingPlanApproval("plan-mode"),d=!0);let l=d||this.lastTurnHadQuestion||!!s;this.turnInProgress=a,l&&!this.waitingForInputFired?(this.waitingForInputFired=!0,d||this.deps.markAwaitingUserInput(),this.deps.emitTurnEnd(!0)):!a&&!l&&(this.deps.completeTurn(),this.deps.emitTurnEnd(!1))}finishTerminalTurn(){this.turnInProgress=!1}finishInterruptedTurn(e){this.turnInProgress=e,this.waitingForInputFired=!1,this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}resetAfterRun(){this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}};var vi=class{constructor(e){this.deps=e}deps;applyMessage(e,r){if(e.type==="backend_ref"){this.deps.clearStartupTimer(),this.deps.assignBackendRef({...e.ref}),this.deps.transitionRunning();return}if(e.type==="run_started"){e.runId&&this.deps.noteRunStarted(e.runId);return}if(e.type==="text_delta"){this.deps.noteTextDelta(e.text,r.pendingPlanApproval);return}if(e.type==="tool_call"){this.deps.noteToolCall({name:e.name,input:e.input,currentPermissionMode:r.currentPermissionMode,permissionMode:r.permissionMode,planModeApproved:r.planModeApproved});return}if(e.type==="pending_input"){this.deps.setPendingInputState(e.state),this.deps.notePendingInput();return}if(e.type==="pending_input_resolved"){this.deps.setPendingInputState(this.deps.clearResolvedPendingInput(e.requestId,r.pendingInputState));return}if(e.type==="plan_artifact"){this.deps.notePlanArtifact(e);return}if(e.type==="settings_changed"){let n=this.deps.noteSettingsChanged({oldMode:r.currentPermissionMode,permissionMode:e.permissionMode,planModeApproved:r.planModeApproved});n&&this.deps.setCurrentPermissionMode(n);return}if(e.type==="run_completed"){this.deps.handleRunCompleted(e.data);return}e.type}};ut();var DP=120*1e3;function Ei(t){return t instanceof Error?t.message:String(t)}var Oi=class extends OP{id;name;harnessSessionId;backendRef;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;requestedPermissionMode;planApproval;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;worktreePath;originalWorkdir;worktreeBranch;worktreeStrategy;worktreeBaseBranch;worktreePrTargetRepo;autoMergeParentSessionId;autoMergeConflictResolutionAttemptCount;autoMergeResolverSessionId;worktreePushRemote;worktreeDisposition;worktreePrUrl;worktreePrNumber;worktreeMerged;worktreeMergedAt;worktreeLifecycle;worktreeState="none";multiTurn;goalTaskId;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;route;pendingInputState;pendingPlanApproval=!1;planApprovalContext;planDecisionVersion=0;actionablePlanDecisionVersion;canonicalPlanPromptVersion;approvalPromptRequiredVersion;approvalPromptVersion;approvalPromptStatus="not_sent";approvalPromptTransport="none";approvalPromptMessageKind="none";approvalPromptLastAttemptAt;approvalPromptDeliveredAt;approvalPromptFailedAt;planFilePath;killReason="unknown";planModeApproved=!1;turnRuntime;harnessEvents;lifecycle="starting";approvalState="not_required";approvalExecutionState="not_plan_gated";approvalRationale;latestPlanArtifact;latestPlanArtifactVersion;runtimeState="live";deliveryState="idle";canUseTool;autoRespondCount=0;timers=new yi;constructor(e,r){super(),this.id=e.sessionIdOverride??hi(8),this.name=r,this.harness=e.harness?Hn(e.harness):Em(),this.prompt=e.prompt,this.workdir=e.workdir,this.model=e.model??Ct(this.harness.name),this.reasoningEffort=e.reasoningEffort??lt(this.harness.name),this.systemPrompt=e.systemPrompt,this.allowedTools=e.allowedTools,this.permissionMode=e.permissionMode??_.permissionMode,this.requestedPermissionMode=e.requestedPermissionMode??this.permissionMode,this.planApproval=e.planApproval??_.planApproval,this.codexApprovalPolicy=this.harness.name==="codex"?"never":void 0,this.currentPermissionMode=this.permissionMode,this.originChannel=e.originChannel,this.originThreadId=e.originThreadId,this.originAgentId=e.originAgentId,this.originSessionKey=e.originSessionKey,this.route=e.route?{...e.route}:void 0,this.backendRef=e.backendRef?{...e.backendRef}:void 0,this.resumeSessionId=e.resumeSessionId,this.forkSession=e.forkSession,this.multiTurn=e.multiTurn??!0,this.goalTaskId=e.goalTaskId,this.worktreeStrategy=e.worktreeStrategy,this.worktreeBaseBranch=e.worktreeBaseBranch,e.worktreePrTargetRepo&&(this.worktreePrTargetRepo=e.worktreePrTargetRepo),e.autoMergeParentSessionId&&(this.autoMergeParentSessionId=e.autoMergeParentSessionId),e.autoMergeConflictResolutionAttemptCount!==void 0&&(this.autoMergeConflictResolutionAttemptCount=e.autoMergeConflictResolutionAttemptCount),e.autoMergeResolverSessionId&&(this.autoMergeResolverSessionId=e.autoMergeResolverSessionId),this.canUseTool=e.canUseTool,this.startedAt=Date.now(),this.abortController=new AbortController,this.turnRuntime=new ki({appendOutput:n=>zm(this.outputBuffer,this.id,n),emitOutput:n=>this.emit("output",this,n),emitToolUse:(n,o)=>this.emit("toolUse",this,n,o),emitTurnEnd:n=>this.emit("turnEnd",this,n),markPendingPlanApproval:n=>this.markPendingPlanApproval(n),markAwaitingUserInput:()=>this.markAwaitingUserInput(),applyInputRequested:()=>this.applyControlEvent({type:"input.requested"}),completeTurn:()=>{this.applyControlEvent({type:"terminal.entered"}),this.complete("done")},setPlanFilePath:n=>{this.planFilePath=n},setLatestPlanArtifact:n=>{this.latestPlanArtifact=n;let o=this.pendingPlanApproval?this.actionablePlanDecisionVersion??this.planDecisionVersion:void 0;this.latestPlanArtifactVersion=o&&o>0?o:void 0}}),this.harnessEvents=new vi({clearStartupTimer:()=>this.clearTimer("startup"),assignBackendRef:n=>{this.backendRef=n,this.harnessSessionId=n.conversationId,n.worktreePath&&(this.worktreePath=n.worktreePath,this.originalWorkdir??=this.workdir,this.worktreeBranch??=Ri(n.worktreePath),this.worktreeStrategy&&this.worktreeStrategy!=="off"&&this.applyControlEvent({type:"worktree.state_set",worktreeState:"provisioned"}))},noteRunStarted:n=>{this.backendRef&&(this.backendRef={...this.backendRef,runId:n})},transitionRunning:()=>{this._status==="starting"&&this.transition("running")},noteTextDelta:(n,o)=>this.turnRuntime.noteTextDelta(n,o),noteToolCall:n=>this.turnRuntime.noteToolCall(n),setPendingInputState:n=>{this.pendingInputState=n},notePendingInput:()=>this.turnRuntime.notePendingInput(),clearResolvedPendingInput:(n,o)=>this.turnRuntime.clearResolvedPendingInput(n,o),notePlanArtifact:n=>this.turnRuntime.notePlanArtifact(n.artifact,n.finalized),noteSettingsChanged:n=>this.turnRuntime.noteSettingsChanged(n),setCurrentPermissionMode:n=>{this.currentPermissionMode=n,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:n})},handleRunCompleted:n=>{let o=n.outcome??(n.success?"completed":"failed");this.result={subtype:o==="interrupted"?"interrupted":n.success?"success":"error",duration_ms:n.duration_ms,total_cost_usd:n.total_cost_usd,num_turns:n.num_turns,result:n.result,is_error:o==="failed",session_id:n.session_id},this.costUsd=n.total_cost_usd;let i=this.multiTurn&&this.messageStream&&o==="interrupted",s=this.multiTurn&&this.messageStream&&o==="completed";i?(this.resetIdleTimer(),this.turnRuntime.finishInterruptedTurn(this.messageStream?.hasPending()===!0)):s?(this.resetIdleTimer(),this.turnRuntime.finishSuccessfulTurn({currentPermissionMode:this.currentPermissionMode,permissionMode:this.permissionMode,pendingPlanApproval:this.pendingPlanApproval,planModeApproved:this.planModeApproved,pendingInputState:this.pendingInputState,hasPendingMessages:this.messageStream?.hasPending()===!0})):(this.turnRuntime.finishTerminalTurn(),this.transitionToTerminal(o==="completed"?"completed":"failed")),this.turnRuntime.resetAfterRun(),this.pendingInputState=void 0}}),this.applyControlEvent({type:"initialize",hasWorktree:!!(this.worktreeStrategy&&this.worktreeStrategy!=="off")}),(e.planModeApproved!==void 0||e.approvalState!==void 0||e.approvalExecutionState!==void 0||e.approvalRationale!==void 0||e.pendingPlanApproval!==void 0||e.planApprovalContext!==void 0||e.planDecisionVersion!==void 0||e.actionablePlanDecisionVersion!==void 0||e.canonicalPlanPromptVersion!==void 0||e.approvalPromptRequiredVersion!==void 0||e.approvalPromptVersion!==void 0||e.approvalPromptStatus!==void 0||e.approvalPromptTransport!==void 0||e.approvalPromptMessageKind!==void 0||e.approvalPromptLastAttemptAt!==void 0||e.approvalPromptDeliveredAt!==void 0||e.approvalPromptFailedAt!==void 0)&&this.applyControlPatch({...e.planModeApproved!==void 0?{planModeApproved:e.planModeApproved}:{},...e.approvalState!==void 0?{approvalState:e.approvalState}:{},...e.approvalExecutionState!==void 0?{approvalExecutionState:e.approvalExecutionState}:{},...e.pendingPlanApproval!==void 0?{pendingPlanApproval:e.pendingPlanApproval}:{},...e.planApprovalContext!==void 0?{planApprovalContext:e.planApprovalContext}:{},...e.planDecisionVersion!==void 0?{planDecisionVersion:e.planDecisionVersion}:{},...e.actionablePlanDecisionVersion!==void 0?{actionablePlanDecisionVersion:e.actionablePlanDecisionVersion}:{},...e.canonicalPlanPromptVersion!==void 0?{canonicalPlanPromptVersion:e.canonicalPlanPromptVersion}:{},...e.approvalPromptRequiredVersion!==void 0?{approvalPromptRequiredVersion:e.approvalPromptRequiredVersion}:{},...e.approvalPromptVersion!==void 0?{approvalPromptVersion:e.approvalPromptVersion}:{},...e.approvalPromptStatus!==void 0?{approvalPromptStatus:e.approvalPromptStatus}:{},...e.approvalPromptTransport!==void 0?{approvalPromptTransport:e.approvalPromptTransport}:{},...e.approvalPromptMessageKind!==void 0?{approvalPromptMessageKind:e.approvalPromptMessageKind}:{},...e.approvalPromptLastAttemptAt!==void 0?{approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt}:{},...e.approvalPromptDeliveredAt!==void 0?{approvalPromptDeliveredAt:e.approvalPromptDeliveredAt}:{},...e.approvalPromptFailedAt!==void 0?{approvalPromptFailedAt:e.approvalPromptFailedAt}:{}}),this.approvalRationale=e.approvalRationale}get status(){return this._status}get harnessName(){return this.harness.name}get backendKind(){return this.harness.backendKind}get backendCapabilities(){return this.harness.capabilities}get backendConversationId(){return $(this)}get waitingForInputFired(){return this.turnRuntime.waitingForInputFired}set waitingForInputFired(e){this.turnRuntime.waitingForInputFired=e}get lastTurnHadQuestion(){return this.turnRuntime.lastTurnHadQuestion}set lastTurnHadQuestion(e){this.turnRuntime.lastTurnHadQuestion=e}get turnInProgress(){return this.turnRuntime.turnInProgress}set turnInProgress(e){this.turnRuntime.turnInProgress=e}get currentTurnText(){return this.turnRuntime.currentTurnText}set currentTurnText(e){this.turnRuntime.currentTurnText=e}get currentTurnPlanArtifact(){return this.turnRuntime.currentTurnPlanArtifact}set currentTurnPlanArtifact(e){this.turnRuntime.currentTurnPlanArtifact=e}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this.lifecycle}get isExplicitlyResumable(){return this.status!=="running"&&this.status!=="completed"&&this.killReason!=="done"&&!!this.backendConversationId}transition(e){if(!qm[this._status].includes(e))throw new Error(`Session state error: cannot transition from ${this._status} to ${e}. This is an internal error \u2014 please report it.`);let r=this._status;this._status=e,this.applyControlEvent({type:"status.transition",status:e}),this.emit("statusChange",this,e,r)}setTimer(e,r,n){this.timers.set(e,r,n)}clearTimer(e){this.timers.clear(e)}clearAllTimers(){this.timers.clearAll()}markPendingPlanApproval(e){let r=this.latestPlanArtifactVersion;this.approvalRationale=void 0,this.applyControlEvent({type:"plan.requested",context:e});let n=this.actionablePlanDecisionVersion??this.planDecisionVersion;this.currentTurnPlanArtifact&&n>0?(this.latestPlanArtifact=this.currentTurnPlanArtifact,this.latestPlanArtifactVersion=n):r!==n&&(this.latestPlanArtifact=void 0,this.latestPlanArtifactVersion=void 0)}clearPendingPlanApproval(){this.applyControlEvent({type:"plan.cleared"})}markAwaitingUserInput(){this.applyControlEvent({type:"input.requested"})}async start(){try{let e;this.multiTurn?(this.messageStream=new Si,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),e=this.messageStream):e=this.prompt;let r=this.harness.launch({prompt:e,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,backendRef:this.backendRef,worktreeStrategy:this.worktreeStrategy,originalWorkdir:this.originalWorkdir??this.workdir,abortController:this.abortController,mcpServers:im(),canUseTool:this.canUseTool});this.harnessHandle=r,this.setTimer("startup",DP,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(e){let r=e instanceof Error?e.message:String(e);this.transitionToTerminal("failed",{error:r});return}this.consumeMessages(this.harnessHandle.messages).catch(e=>{let r=e instanceof Error?e.message:String(e),n=e instanceof Error?e.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${r}`,n),this.isActive&&this.transitionToTerminal("failed",{error:r})})}async sendMessage(e){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.turnRuntime.beginUserTurn(),this.applyControlEvent({type:"turn.started"});let r=e;if(this.pendingModeSwitch){let n=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(n),this.currentPermissionMode=n,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:n}),this.pendingModeSwitch=void 0,i=!0,o=!0}catch(s){throw console.error(`[Session ${this.id}] setPermissionMode(${n}) FAILED: ${Ei(s)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${n}: ${Ei(s)}`)}else this.pendingModeSwitch=void 0,i=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);i&&(this.clearPendingPlanApproval(),n!=="plan"&&this.applyControlEvent({type:"plan.approved"})),o&&(r=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
48
+
49
+ ${e}`)}else if((this.pendingPlanApproval||this.approvalState==="changes_requested")&&!this.planModeApproved&&(this.approvalState!=="changes_requested"&&this.applyControlEvent({type:"plan.changes_requested"}),r=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below, then re-submit your revised plan for approval. Do NOT start implementing yet.]
50
+
51
+ ${e}`,this.harnessHandle?.setPermissionMode))try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan",this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:"plan"})}catch(n){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${Ei(n)}`)}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(r,this.backendConversationId??""));else if(this.harnessHandle?.streamInput){let n=this.harness.buildUserMessage(r,this.backendConversationId??"");async function*o(){yield n}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){return!this.turnInProgress||!this.harnessHandle?.interrupt?!1:(await this.harnessHandle.interrupt(),!0)}async submitPendingInputOption(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputOption)return!1;let r=await this.harnessHandle.submitPendingInputOption(e);return r&&(this.waitingForInputFired=!1),r}async submitPendingInputText(e){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputText)return!1;let r=await this.harnessHandle.submitPendingInputText(e);return r&&(this.waitingForInputFired=!1),r}switchPermissionMode(e){this.pendingModeSwitch=e}get isActive(){return this._status==="starting"||this._status==="running"}kill(e){this.transitionToTerminal("killed",{reason:e})}complete(e="done"){this.transitionToTerminal("completed",{reason:e})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(e){return e===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-e)}resetIdleTimer(){if(!this.multiTurn)return;let e=(_.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",e,()=>{this._status==="running"&&(this.applyControlEvent({type:"terminal.entered",suspended:!0}),this.kill("idle-timeout"))})}teardown(){this.clearAllTimers(),this.completedAt||(this.completedAt=Date.now()),this.messageStream&&this.messageStream.end(),this.harnessHandle?.interrupt&&this.harnessHandle.interrupt().catch(e=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${Ei(e)}`)}),this.abortController.abort(),this.applyControlEvent({type:"terminal.entered",suspended:this.lifecycle==="suspended"})}transitionToTerminal(e,r={}){this.isActive&&(this.turnInProgress=!1,r.reason&&(this.killReason=r.reason),r.error!==void 0&&(this.error=r.error),this.completedAt=Date.now(),this.applyControlEvent({type:"terminal.entered",suspended:e==="killed"&&r.reason==="idle-timeout"}),this.transition(e),this.teardown())}async consumeMessages(e){for await(let r of e){if(!this.isActive)break;this.resetIdleTimer(),this.harnessEvents.applyMessage(r,{pendingPlanApproval:this.pendingPlanApproval,currentPermissionMode:this.currentPermissionMode,permissionMode:this.permissionMode,planModeApproved:this.planModeApproved,pendingInputState:this.pendingInputState})}}controlStateSnapshot(){return{status:this._status,lifecycle:this.lifecycle,approvalState:this.approvalState,approvalExecutionState:this.approvalExecutionState,worktreeState:this.worktreeState,runtimeState:this.runtimeState,deliveryState:this.deliveryState,requestedPermissionMode:this.requestedPermissionMode,currentPermissionMode:this.currentPermissionMode,pendingPlanApproval:this.pendingPlanApproval,planApprovalContext:this.planApprovalContext,planDecisionVersion:this.planDecisionVersion,actionablePlanDecisionVersion:this.actionablePlanDecisionVersion,canonicalPlanPromptVersion:this.canonicalPlanPromptVersion,approvalPromptRequiredVersion:this.approvalPromptRequiredVersion,approvalPromptVersion:this.approvalPromptVersion,approvalPromptStatus:this.approvalPromptStatus,approvalPromptTransport:this.approvalPromptTransport,approvalPromptMessageKind:this.approvalPromptMessageKind,approvalPromptLastAttemptAt:this.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:this.approvalPromptDeliveredAt,approvalPromptFailedAt:this.approvalPromptFailedAt,planModeApproved:this.planModeApproved}}applyControlEvent(e){let r=Md(this.controlStateSnapshot(),e);this.applyControlState(r)}applyControlPatch(e){let r=Gm(this.controlStateSnapshot(),e);this.applyControlState(r)}applyControlState(e){this.lifecycle=e.lifecycle,this.approvalState=e.approvalState,this.approvalExecutionState=e.approvalExecutionState,this.worktreeState=e.worktreeState,this.runtimeState=e.runtimeState,this.deliveryState=e.deliveryState,this.pendingPlanApproval=e.pendingPlanApproval,this.planApprovalContext=e.planApprovalContext,this.planDecisionVersion=e.planDecisionVersion,this.actionablePlanDecisionVersion=e.actionablePlanDecisionVersion,this.canonicalPlanPromptVersion=e.canonicalPlanPromptVersion,this.approvalPromptRequiredVersion=e.approvalPromptRequiredVersion,this.approvalPromptVersion=e.approvalPromptVersion,this.approvalPromptStatus=e.approvalPromptStatus,this.approvalPromptTransport=e.approvalPromptTransport,this.approvalPromptMessageKind=e.approvalPromptMessageKind,this.approvalPromptLastAttemptAt=e.approvalPromptLastAttemptAt,this.approvalPromptDeliveredAt=e.approvalPromptDeliveredAt,this.approvalPromptFailedAt=e.approvalPromptFailedAt,this.planModeApproved=e.planModeApproved}};ke();function It(t){let e=Math.floor(t/1e3),r=Math.floor(e/60),n=e%60;return r>0?`${r}m${n}s`:`${n}s`}var NP=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","i","me","my","we","our","you","your","it","its","he","she","to","of","in","for","on","with","at","by","from","as","into","through","about","that","this","these","those","and","or","but","if","then","so","not","no","please","just","also","very","all","some","any","each","make","write","create","build","implement","add","update"]);function uf(t){let r=t.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!NP.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var lf={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4",awaiting_plan_decision:"\u{1F4CB}",awaiting_user_input:"\u2753",awaiting_worktree_decision:"\u{1F33F}",suspended:"\u23F8\uFE0F",terminal:"\u{1F3C1}"};function pf(t){let e=lf[t.phase]??lf[t.status]??"\u2753",r=It(t.duration),n=t.multiTurn?"multi-turn":"single",o=t.prompt.length>80?t.prompt.slice(0,80)+"...":t.prompt,i=t.costUsd>0?` | $${t.costUsd.toFixed(2)}`:"",s=[`${e} ${t.name} [${t.id}] (${r}${i}) \u2014 ${n}`,` \u{1F4C1} ${t.workdir}`,` \u{1F4DD} "${o}"`];if(t.worktreePath&&t.worktreeBranch){let d=` \u{1F33F} Worktree: ${t.worktreeBranch}`;t.worktreeMerged?d+=" [merged \u2713]":t.worktreePrUrl?d+=` [PR: ${t.worktreePrUrl}]`:d+=" [not merged]",s.push(d)}t.phase!==t.status&&s.push(` \u2699\uFE0F Phase: ${t.phase}`),t.lifecycle&&t.lifecycle!==t.phase&&s.push(` \u{1F504} Lifecycle: ${t.lifecycle}`),(t.requestedPermissionMode||t.currentPermissionMode||t.approvalExecutionState)&&s.push(` \u{1F510} Approval: ${t.approvalExecutionState??"unknown"} (requested=${t.requestedPermissionMode??"unknown"}, effective=${t.currentPermissionMode??"unknown"})`),t.resumable&&s.push(" \u21A9\uFE0F Resumable: yes"),t.harness&&s.push(` \u{1F9F0} Harness: ${t.harness}`);let a=$(t);return a&&s.push(` \u{1F517} Backend ID: ${a}`),t.resumeSessionId&&s.push(` \u21A9\uFE0F Resumed from: ${t.resumeSessionId}${t.forkSession?" (forked)":""}`),s.join(`
52
+ `)}function Di(t,e){let r=t.sessionsWithDuration>0?t.totalDurationMs/t.sessionsWithDuration:0,{completed:n,failed:o,killed:i}=t.sessionsByStatus,s=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${t.totalLaunched}`,` Running: ${e}`,` Completed: ${n}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${r>0?It(r):"n/a"}`];if(t.mostExpensive){let a=t.mostExpensive;s.push("","\u{1F3C6} Notable session",` ${a.name} [${a.id}]`,` \u{1F4DD} "${a.prompt}"`)}return s.join(`
53
+ `)}function Fe(t,e){return e<=0?"":t.length<=e?t:e<=3?".".repeat(e):t.slice(0,e-3)+"..."}function cf(t,e){let r=t.split(`
54
+ `),n=[],o=0;for(let i=r.length-1;i>=0;i--){let s=r[i].length+(n.length>0?1:0);if(o+s>e&&n.length>0)break;n.unshift(r[i]),o+=s}return n.join(`
55
+ `)}function mf(t,e){let r=t.split(`
56
+ `),n=[],o=0;for(let i=0;i<r.length;i++){let s=r[i].length+(n.length>0?1:0);if(o+s>e&&n.length>0)break;n.push(r[i]),o+=s}return n.join(`
57
+ `)}var FP=50,LP=1,WP=new Set(["starting","running","completed","failed","killed"]),BP=5,UP=1440*60*1e3;function KP(t){let e=Number(t);return!Number.isFinite(e)||e<LP?FP:Math.floor(e)}function VP(t){return typeof t=="string"&&WP.has(t)}function qP(t){let e=t.split(`
58
+ `);return e.at(-1)===""&&e.pop(),e}function gf(t){return t.backendRef?.conversationId??t.harnessSessionId}function hf(t,e,r){let n=ff(t,"utf-8"),o=qP(n);return e.full?o:o.slice(-r)}function jP(t,e,r){if(t.status!=="starting"&&t.status!=="running")return null;let n=sn(t.id);if(!Nd(n))return null;try{return hf(n,e,r)}catch{return null}}function GP(t){let e=It(t.duration),r=` | Cost: $${t.costUsd.toFixed(4)}`,n=t.phase?` | Phase: ${t.phase}`:"",o=t.lifecycle&&t.lifecycle!==t.phase?` | Lifecycle: ${t.lifecycle}`:"";return[`Session: ${t.name} [${t.id}] | Status: ${t.status.toUpperCase()}${n}${o}${r} | Duration: ${e}`,`${"\u2500".repeat(60)}`].join(`
59
+ `)}function HP(t){return[`Session: ${t.name||t.sessionId||gf(t)||"unknown"} | Status: ${t.status.toUpperCase()} | Cost: $${t.costUsd.toFixed(4)}`,`(retrieved from ${t.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`,`${"\u2500".repeat(60)}`].join(`
60
+ `)}function zP(t){let e=[];return t.error&&e.push(`Error: ${t.error}`),t.result?.result&&e.push(`Result: ${t.result.result}`),t.result&&e.push(`Result status: ${t.result.subtype}`),e.length>0?`
61
+ (no output yet)
62
+ ${e.join(`
63
+ `)}`:`
64
+ (no output yet)`}function Ni(t,e,r={}){let n=KP(r.lines),o=t.resolve(e);if(!o){let l=t.getPersistedSession(e);if(l?.outputPath&&Nd(l.outputPath))try{let m=hf(l.outputPath,r,n).join(`
65
+ `),S=HP(l);return m?`${S}
66
+ ${m}`:`${S}
67
+ (output file was empty)`}catch(m){let S=m instanceof Error?m.message:String(m);return`Error: Session "${e}" was cleaned up (expired) and output file could not be read: ${S}`}return`Error: Session "${e}" not found.`}let i=jP(o,r,n),s=i&&i.length>0?i:r.full?o.getOutput():o.getOutput(n),a=GP(o),d=s.length===0?`${a}${zP(o)}`:`${a}
68
+ ${s.join(`
69
+ `)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(Nd(o.planFilePath)){let l=ff(o.planFilePath,"utf-8"),m="\u2500".repeat(60);return`${d}
70
+ ${m}
71
+ Plan file: ${o.planFilePath}
72
+ ${m}
73
+ ${l}`}}catch{}return d}function Fi(t,e="all",r,n={}){let o=t.listPersistedSessions()??[],s=QP(t.list("all"),o);if(e!=="all"&&(s=s.filter(a=>a.status===e)),r&&(s=s.filter(a=>a.originChannel===r)),n.full){let a=Date.now()-UP;s=s.filter(d=>(d.startedAt??0)>=a)}else s=s.slice(0,BP);return s.length===0?"No sessions found.":s.map(a=>pf(a)).join(`
74
+
75
+ `)}function QP(t,e){let r=new Map;for(let n of e){if(!VP(n.status))continue;let o=n.completedAt??Date.now(),i=n.createdAt??o,s=gf(n),a=n.sessionId??`persisted:${s??n.harnessSessionId}`;r.set(a,{id:n.sessionId??s??n.harnessSessionId,name:n.name||n.sessionId||s||n.harnessSessionId,status:n.status,startedAt:n.createdAt??0,completedAt:n.completedAt,duration:Math.max(0,o-i),prompt:n.prompt??"",workdir:n.workdir??"(unknown)",costUsd:n.costUsd??0,multiTurn:!0,phase:n.lifecycle??n.status,lifecycle:n.lifecycle,resumable:n.resumable,harness:n.harness,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeMerged:n.worktreeMerged,worktreeMergedAt:n.worktreeMergedAt,worktreePrUrl:n.worktreePrUrl})}for(let n of t)r.set(n.id,{id:n.id,name:n.name,status:n.status,startedAt:n.startedAt,completedAt:n.completedAt,duration:n.duration,prompt:n.prompt,workdir:n.originalWorkdir??n.workdir,costUsd:n.costUsd,multiTurn:n.multiTurn,phase:n.phase,lifecycle:n.lifecycle,resumable:n.isExplicitlyResumable,harness:n.harnessName,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0});return[...r.values()].sort((n,o)=>(o.startedAt??0)-(n.startedAt??0))}function JP(t){if(!t||typeof t!="object")return"all";let e=t.status;switch(e){case"running":case"completed":case"failed":case"killed":case"all":return e;default:return"all"}}function Sf(t){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:p.Object({status:p.Optional(p.Union([p.Literal("all"),p.Literal("running"),p.Literal("completed"),p.Literal("failed"),p.Literal("killed")],{description:'Filter by status (default "all")'})),full:p.Optional(p.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=JP(r),o=t?.workspaceDir?Kn(t.workspaceDir):void 0,i=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:Fi(k,n,o,{full:i})}]}}}}Ee();Y();function Li(t,e,r){let n=t.resolve(e);return n?n.status==="completed"||n.status==="failed"||n.status==="killed"?`Session ${n.name} [${n.id}] is already ${n.status}. No action needed.`:r==="completed"?(n.complete(),`Session ${n.name} [${n.id}] marked as completed.`):(t.kill(n.id),`Session ${n.name} [${n.id}] has been terminated.`):`Error: Session "${e}" not found.`}function YP(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session!="string"?!1:e.reason===void 0?!0:e.reason==="completed"||e.reason==="killed"}function yf(t){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:p.Object({session:p.String({description:"Session name or ID to terminate"}),reason:p.Optional(p.Union([p.Literal("completed"),p.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(e,r){return k?YP(r)?{content:[{type:"text",text:Li(k,r.session,r.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}Ee();Y();function XP(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function Wi(t){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:p.Object({session:p.String({description:"Session name or ID to get output from"}),lines:p.Optional(p.Number({description:"Number of recent lines to show (default 50)"})),full:p.Optional(p.Boolean({description:"Show all available output"}))}),async execute(e,r){return k?XP(r)?{content:[{type:"text",text:Ni(k,r.session,{full:r.full,lines:r.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}Ee();Y();Re();ke();var ZP=10;function Ld(t){return t instanceof Error?t.message:String(t)}function Cr(t){return re(t)??t.harnessSessionId??"unknown-session"}function kf(t){return t.status!=="running"&&!!t.pendingPlanApproval&&!!$(t)}function eo(t,e,r){let n=e==="completed"?`This session is closed by default. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Cr(t)}', fork_session=true, prompt='<new task>').`:e==="legacy_non_resumable"?`Persisted historical backend state is intentionally non-resumable here. Launch fresh, or fork with agent_launch(resume_session_id='${Cr(t)}', fork_session=true, prompt='<new task>').`:e==="missing_backend_state"?`No resumable backend state is available. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Cr(t)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${Cr(t)}', message='<next instruction>') to continue the running session.`,o=r?` ${r}`:"";return{text:`Resume unavailable for session ${t.name} [${Cr(t)}] (${e}).${o} ${n}`,isError:!0}}async function vf(t,e,r){try{let n={prompt:e.prompt,sessionIdOverride:Td(e),workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,worktreeStrategy:e.worktreeStrategy,multiTurn:!0,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,permissionMode:e.currentPermissionMode,requestedPermissionMode:e.requestedPermissionMode??e.currentPermissionMode,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,harness:"harnessName"in e?e.harnessName:e.harness},o=await t.spawnAndAwaitRunning(n,{notifyLaunch:!1});return t.notifySession(o,`\u25B6\uFE0F [${o.name}] Relaunched fresh`),{text:`Session ${e.name} was relaunched fresh \u2014 it was killed during startup before the harness initialized. New session: ${o.name} [${o.id}].`}}catch(n){return{text:`Error relaunching session ${e.name} [${Cr(e)}]: ${Ld(n)}`,isError:!0}}}var ew=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
76
+
77
+ `;function Pf(t){let e=t?.replace(/\s+/g," ").trim();if(e)return Fe(e,240)}function Fd(t){if(t.approvalState==="changes_requested"&&!Bi(t))return`Plan changes were already requested for session ${t.name}. Wait for the revised plan before approving.`;if(t.approvalState==="rejected")return`Plan for session ${t.name} was already rejected.`}function Bi(t){return t.pendingPlanApproval?(t.approvalState==="changes_requested"?t.actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion)>0:!1}function tw(t){return Fd(t)?!1:Bi(t)||t.currentPermissionMode==="plan"}async function rw(t,e,r,n={}){let o=Qn(e);if(!(o.kind==="resume"||kf(e)))return;let s=!!(n.approve&&tw(e)),a=s?Pf(n.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?vf(t,e,r):eo(e,o.reason);let d={prompt:s?ew+r:r,sessionIdOverride:o.stableSessionId,workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,resumeSessionId:o.resumeSessionId,multiTurn:!0,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,permissionMode:s?"bypassPermissions":e.currentPermissionMode,requestedPermissionMode:e.requestedPermissionMode??e.currentPermissionMode,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,pendingPlanApproval:s?!1:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:s?void 0:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,...s?{approvalState:"approved",approvalExecutionState:"approved_then_implemented",approvalRationale:a,planModeApproved:!0}:{},harness:"harnessName"in e?e.harnessName:e.harness},l=await t.spawnAndAwaitRunning(d,{notifyLaunch:!1});return s?(t.notifySession(l,`\u{1F44D} [${l.name}] Plan approved (resumed)`,"plan-approved"),{text:`Plan approved for session ${l.name} [${l.id}]. Session resumed in bypassPermissions mode. Use agent_output to see the response.`}):(t.notifySession(l,`\u25B6\uFE0F [${l.name}] Auto-resumed`),{text:`Auto-resumed session ${l.name} [${l.id}]. Use agent_output to see the response.`})}catch(d){return eo(e,"missing_backend_state",`Backend resume failed: ${Ld(d)}`)}}async function bt(t,e){let r=t.resolve(e.session),n=r?void 0:t.getPersistedSession(e.session);if(!r&&!n)return{text:`Error: Session "${e.session}" not found.`,isError:!0};let o=r??n,i=o.status==="running"?{kind:"direct"}:Qn(o);if(e.approve){let a=Fd(o);if(a)return{text:a,isError:!0}}if(i.kind==="resume"||kf(o)){let a=await rw(t,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(a)return a}else{if(i.kind==="relaunch")return vf(t,o,e.message);if(i.kind==="unavailable")return eo(o,i.reason)}if(!r)return zn(n)?eo(n,"completed"):{text:`Error: Session ${n.name} [${Cr(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return zn(r)?eo(r,"completed"):{text:`Error: Session ${r.name} [${r.id}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};let s=_.maxAutoResponds??ZP;if(e.userInitiated)r.resetAutoRespond();else if(r.autoRespondCount>=s)return{text:`\u26A0\uFE0F Auto-respond limit reached (${r.autoRespondCount}/${s}). Ask the user to provide the answer for session ${r.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{if(e.approve){let f=Fd(r);if(f)return{text:f,isError:!0}}if(!e.approve&&r.pendingInputState?.allowsFreeText&&await r.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let v=Fe(e.message,100);t.notifySession(r,`\u21AA\uFE0F [${r.name}] "${v}"`,"agent-respond")}e.userInitiated||r.incrementAutoRespond();let f=Fe(e.message,80);return{text:[`Pending input answered for session ${r.name} [${r.id}].`,` Message: "${f}"`,"Use agent_output to see the response."].join(`
78
+ `)}}let d=!1;e.interrupt&&(d=await r.interrupt());let l=!!(e.approve&&Bi(r)),m=l?Pf(e.approvalRationale):void 0,S="";if(e.approve&&Bi(r)?(r.switchPermissionMode("bypassPermissions"),r.approvalRationale=m):e.approve&&r.currentPermissionMode==="default"?r.switchPermissionMode("bypassPermissions"):e.approve&&r.currentPermissionMode==="bypassPermissions"?S=`
79
+ \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:e.approve?S=`
80
+ \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:(r.pendingPlanApproval||r.approvalState==="changes_requested")&&(S=`
81
+ \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`),await r.sendMessage(e.message),l)t.notifySession(r,`\u{1F44D} [${r.name}] Plan approved`,"plan-approved");else if(e.userInitiated){let f=Fe(e.message,100);t.notifySession(r,`\u21AA\uFE0F [${r.name}] "${f}"`,"agent-respond")}e.userInitiated||r.incrementAutoRespond();let y=Fe(e.message,80);return l?{text:`Plan approved for session ${r.name} [${r.id}]. Use agent_output to see the response.`}:{text:[`Message sent to session ${r.name} [${r.id}].`,d?" (redirected active turn first)":e.interrupt?" (no active turn to interrupt)":"",` Message: "${y}"`,S,"Use agent_output to see the response."].filter(Boolean).join(`
82
+ `)}}catch(a){return{text:`Error sending message to session ${r.name} [${r.id}]: ${Ld(a)}`,isError:!0}}}function nw(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.message=="string"&&(e.approval_rationale===void 0||typeof e.approval_rationale=="string")}function wf(t){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent session. The session must be running. All sessions are multi-turn.",parameters:p.Object({session:p.String({description:"Session name or ID to respond to"}),message:p.String({description:"The message to send to the session"}),interrupt:p.Optional(p.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:p.Optional(p.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:p.Optional(p.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode, or (2) escalate a default-mode session to skip remaining OpenClaw approval checkpoints. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."})),approval_rationale:p.Optional(p.String({description:"Optional structured rationale for a direct delegated plan approval. Use this instead of embedding the rationale in message text when approve=true for a pending plan."}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!nw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve?, approval_rationale? }."}]};let n=await bt(k,{session:r.session,message:r.message,interrupt:r.interrupt,userInitiated:r.userInitiated,approve:r.approve,approvalRationale:r.approval_rationale});return{isError:n.isError??!1,content:[{type:"text",text:n.text}]}}}}Ee();Y();function ow(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.session=="string"&&typeof e.summary=="string"}function If(t){return{name:"agent_request_plan_approval",description:"Send a plan-approval decision prompt to the user for a session that is already waiting on plan approval. Reuses the plugin's Approve/Revise/Reject buttons so the user can decide directly from the message.",parameters:p.Object({session:p.String({description:"Session name or ID awaiting plan approval"}),summary:p.String({description:"Concise user-facing summary of scope, risk, and any concerns that should accompany the approval buttons"})}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!ow(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, summary }."}]};let n=k.requestPlanApprovalFromUser(r.session,r.summary);return{isError:n.startsWith("Error:"),content:[{type:"text",text:n}]}}}}Ee();Y();Re();function iw(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.report_id=="string"&&typeof e.report_text=="string"&&typeof e.plan_prompt=="string"&&typeof e.plan_workdir=="string"&&(e.plan_name==null||typeof e.plan_name=="string")&&(e.target_channel==null||typeof e.target_channel=="string")&&(e.target_thread_id==null||typeof e.target_thread_id=="string"||typeof e.target_thread_id=="number")&&(e.target_session_key==null||typeof e.target_session_key=="string")}function sw(t,e){let r=_t(t,e.target_channel,e.target_session_key);if(r)return e.target_thread_id!=null&&(r.threadId=String(e.target_thread_id)),r}function bf(t){return{name:"agent_send_monitor_report",description:"Post a monitor report to the current or explicit chat route with human-gated inline buttons. Use this for release reports that should offer a Start Plan action directly in Telegram.",parameters:p.Object({report_id:p.String({description:"Stable report identifier, for example 'openclaw-release-v2026.3.31'."}),report_text:p.String({description:"Final user-facing report text to deliver."}),plan_prompt:p.String({description:"Prompt to seed into the plan-only session when the user clicks Start Plan."}),plan_workdir:p.String({description:"Working directory for the planning session."}),plan_name:p.Optional(p.String({description:"Optional explicit session name for the planning session."})),target_channel:p.Optional(p.String({description:"Optional explicit route like 'telegram|-1003863755361'."})),target_thread_id:p.Optional(p.Union([p.String(),p.Number()],{description:"Optional explicit topic/thread id."})),target_session_key:p.Optional(p.String({description:"Optional explicit session key for wake routing."}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!iw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { report_id, report_text, plan_prompt, plan_workdir }."}]};let n=sw(t,r);return!n?.provider||!n.target?{content:[{type:"text",text:"Error: Could not resolve a direct delivery route for the monitor report."}]}:(k.sendMonitorReport({reportId:r.report_id,route:n,text:r.report_text,planName:r.plan_name??r.report_id,planPrompt:r.plan_prompt,planWorkdir:r.plan_workdir}),{content:[{type:"text",text:`Interactive monitor report queued for ${n.provider}|${n.target}${n.threadId?`#${n.threadId}`:""}.`}]})}}}Ee();Y();function xf(t){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:p.Object({}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=k.getMetrics(),o=k.list("running").length;return{content:[{type:"text",text:Di(n,o)}]}}}}Ee();Re();Y();ut();to();import{existsSync as Wd}from"fs";function dw(t){return!t||typeof t!="object"?!1:typeof t.session=="string"}function ji(t){return{name:"agent_merge",description:"Merge a worktree branch back to the base branch. Resolves session (active or persisted), gets worktree path, and performs the merge. On conflict, spawns a conflict-resolver session using the configured default harness.",parameters:p.Object({session:p.String({description:"Session name or ID to merge"}),base_branch:p.Optional(p.String({description:"Base branch to merge into (default: main)"})),strategy:p.Optional(p.Union([p.Literal("merge"),p.Literal("squash")],{description:"Merge strategy: 'merge' (default, fast-forward if possible; merge commit if branches have diverged) or 'squash' (squashes all commits into one)"})),push:p.Optional(p.Boolean({description:"Push the base branch after successful merge (default: false)"})),delete_branch:p.Optional(p.Boolean({description:"Delete the worktree branch after successful merge (default: true)"}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!dw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=dn(k,r.session),o=n.activeSession,i=n.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let{worktreePath:s,originalWorkdir:a,branchName:d}=n;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}]};if(!d)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree at ${s}. The worktree may have been removed and no persisted branch name is available.`}]};Wd(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${a})`);let l=a;if(!Wd(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let m=r.base_branch??sr(l),S=m,y=r.strategy??"merge",f=r.push===!0,v=r.delete_branch!==!1;if(i?.worktreeLifecycle?.state==="merged"||i?.worktreeMerged)return{content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" is already merged.`}]};let A={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]},x=n.persistedRef;return await k.enqueueMerge(l,async()=>{let w=k.getPersistedSession(r.session);if(w?.worktreeLifecycle?.state==="merged"||w?.worktreeMerged){A={content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" was already merged while waiting in queue.`}]};return}let C=Tr(l,d,m),b=Ci(l,d,S,y,s);if(b.success){if(f&&!Mi(l,S)){A={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${S} locally, but failed to push ${S}`}]};return}v&&$t(l,d);let M=!1;if(Wd(s)&&(M=tt(l,s),Ti(l)),w)for(let D of Af({...n,persistedSession:w}))k.updatePersistedSession(D,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDisposition:"merged",worktreeLifecycle:{state:"merged",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"agent_merge",baseBranch:m,targetRepo:w.worktreePrTargetRepo,pushRemote:w.worktreePushRemote}});let F=Mr({kind:"merge",branch:d,base:m,filesChanged:C?.filesChanged,insertions:C?.insertions,deletions:C?.deletions});k.notifyWorktreeOutcome(n.notificationTarget,F);let O=`\u2705 ${b.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${S}.${f?" Pushed.":""}${v?M?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;b.stashPopConflict?O+=`
83
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${b.stashRef??"stash@{0}"}\` in ${l} to review stashed changes.`:b.stashed&&(O+=`
84
+ (Pre-existing changes on ${S} were auto-stashed and restored.)`),A={content:[{type:"text",text:O}]}}else if(b.rebaseConflict)A={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
85
+
86
+ ${b.error}`}]};else if(b.conflictFiles&&b.conflictFiles.length>0){let M=["Resolve merge conflicts in the following files and commit the resolution:","",...b.conflictFiles.map(F=>`- ${F}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${d}"`].join(`
87
+ `);try{let F=k.spawn({prompt:M,workdir:l,name:`${r.session}-conflict-resolver`,harness:Pe(),permissionMode:"bypassPermissions",multiTurn:!0,route:o?.route??i?.route,originChannel:o?.originChannel??i?.originChannel,originThreadId:o?.originThreadId??i?.originThreadId,originAgentId:o?.originAgentId??i?.originAgentId,originSessionKey:o?.originSessionKey??i?.originSessionKey});A={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${b.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${F.name}`}]}}catch(F){A={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${F instanceof Error?F.message:String(F)}`}]}}}else A={content:[{type:"text",text:b.dirtyError?`\u274C Merge blocked: ${b.error}`:`\u274C Merge failed: ${b.error??"unknown error"}`}]}}),A}}}Gi();Ee();Y();ke();ut();to();function pw(t){return!!t&&typeof t=="object"}function Tf(t){return{name:"agent_worktree_cleanup",description:"Manage worktree cleanup with lifecycle-aware safety rules. Use preview_safe to list what Clean all safe would remove, clean_safe to execute it, or preview_all to see both safe and retained sandboxes with kept reasons.",parameters:p.Object({workdir:p.Optional(p.String({description:"Restrict cleanup to sessions rooted in this repository"})),base_branch:p.Optional(p.String({description:"Override base branch for lifecycle resolution"})),mode:p.Optional(p.Union([p.Literal("preview_safe"),p.Literal("clean_safe"),p.Literal("preview_all")],{description:"Cleanup mode. preview_safe shows what Clean all safe would remove, clean_safe performs that cleanup, preview_all shows both safe and retained worktrees. Defaults to preview_safe when dry_run=true, otherwise clean_safe."})),skip_session_check:p.Optional(p.Boolean({description:"Deprecated. Safe cleanup never removes live sessions."})),force:p.Optional(p.Boolean({description:"Deprecated alias for skip_session_check."})),dry_run:p.Optional(p.Boolean({description:"Show what would be cleaned without deleting anything."})),session:p.Optional(p.String({description:"Session name or ID to clean or dismiss."})),dismiss_session:p.Optional(p.Boolean({description:"When true and session is provided, permanently dismiss the worktree."}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!pw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, mode?, dry_run?, session?, dismiss_session? }."}]};let n=r.session,o=r.mode??(r.dry_run===!0?"preview_safe":"clean_safe"),i=o!=="clean_safe",s=o==="preview_all"||o==="clean_safe";if(n&&r.dismiss_session===!0)return{content:[{type:"text",text:await k.dismissWorktree(n)}]};let a=Ki(k);if(n&&(a=a.filter(f=>Vi(f,n)),a.length===0)){let f=dn(k,n);if(!f.persistedSession&&!f.activeSession)return{content:[{type:"text",text:`Error: Session "${n}" not found.`}]}}if(r.workdir&&(a=a.filter(f=>f.workdir===r.workdir)),a.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let d=[],l=[],m=[],S=[];for(let f of a){let{persistedSession:v,activeSession:A,resolvedLifecycle:x}=Ui(k,f,{baseBranch:r.base_branch});if(!x.cleanupSafe){if(s){let w=x.reasons.length>0?x.reasons.map(qi).join(", "):_r(x.derivedState);l.push(`${f.name} [kept: ${w}]`)}continue}if(d.push(`${f.name} (${_r(x.derivedState)})`),!i)try{let w=f.workdir;if(!((v??A)&&Ne(v??A))&&f.worktreePath&&tt(w,f.worktreePath,{destructive:!1}),f.worktreeBranch&&$t(w,f.worktreeBranch),v){let b=x.derivedState==="merged"||x.derivedState==="released"?x.derivedState:x.lifecycle.state;k.updatePersistedSession(f.id,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeMerged:b==="merged"?!0:v.worktreeMerged,worktreeMergedAt:b==="merged"?v.worktreeMergedAt??new Date().toISOString():v.worktreeMergedAt,worktreeLifecycle:{...v.worktreeLifecycle??x.lifecycle,state:b,updatedAt:new Date().toISOString(),resolvedAt:v.worktreeLifecycle?.resolvedAt??new Date().toISOString(),resolutionSource:v.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:r.base_branch??x.lifecycle.baseBranch??v.worktreeBaseBranch,targetRepo:v.worktreePrTargetRepo,pushRemote:v.worktreePushRemote,notes:x.reasons}})}m.push(`${f.name} (${_r(x.derivedState)})`)}catch(w){S.push(`${f.name}: ${w instanceof Error?w.message:String(w)}`)}}let y=[o==="clean_safe"?"Clean all safe:":o==="preview_all"?"Worktree lifecycle review:":"Clean all safe preview:"];return y.push(` SAFE ${i?"NOW":"FOUND"} (${d.length}): ${d.join(", ")||"(none)"}`),s&&y.push(` KEPT (${l.length}): ${l.join(", ")||"(none)"}`),i||(y.push(` CLEANED (${m.length}): ${m.join(", ")||"(none)"}`),y.push(` FAILURES (${S.length}): ${S.join(", ")||"(none)"}`)),{content:[{type:"text",text:y.join(`
88
+ `)}]}}}}Ee();Y();to();function cw(t){return!0}function Mf(t){return{name:"agent_worktree_status",description:"Show lifecycle-first worktree status for coding agent sessions. Displays product-facing lifecycle state, released handling, cleanup safety, and retained reasons.",parameters:p.Object({session:p.Optional(p.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(e,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!cw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let n=r.session,o=Ki(k);if(n&&(o=o.filter(s=>Vi(s,n)),o.length===0))return{content:[{type:"text",text:`Error: Session "${n}" not found or has no worktree.`}]};if(o.length===0)return{content:[{type:"text",text:"No sessions with worktrees found."}]};let i=[];for(let s of o){let{persistedSession:a,resolvedLifecycle:d}=Ui(k,s),l=d.cleanupSafe?"safe now":d.preserve?"preserve":"blocked";i.push(`Session: ${s.name} [${s.id}]`),i.push(` Branch: ${s.worktreeBranch??"(unknown)"} \u2192 ${d.lifecycle.baseBranch??a?.worktreeBaseBranch??"main"}`),i.push(` Repo: ${s.workdir}`),i.push(` Lifecycle:${_r(d.lifecycle.state)}`),d.derivedState!==d.lifecycle.state&&i.push(` Derived: ${_r(d.derivedState)}`),i.push(` Cleanup: ${l}`),d.evidence.prUrl&&i.push(` PR: ${d.evidence.prUrl} (${d.evidence.prState??"unknown"})`),(d.evidence.branchAheadCount!=null||d.evidence.baseAheadCount!=null)&&i.push(` Ahead: ${d.evidence.branchAheadCount??0} ahead / ${d.evidence.baseAheadCount??0} behind`),i.push(` Reasons: ${d.reasons.length>0?d.reasons.map(qi).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
89
+ `).trim()}]}}}}Ee();Y();Re();import{existsSync as mw}from"fs";function Hi(t,e){if(!e||e.length===0)return!0;if(!t)return!1;let r=t.toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function fw(t){return!t||typeof t!="object"?!1:typeof t.goal=="string"}function Cf(t){return{name:"goal_launch",description:"Launch an explicit goal loop. Use this only when the user specifically asks for a goal task, Ralph-style autonomous loop, iterative loop, autonomous repair loop, or keep-going-until-checks-pass workflow. This is not the default session path.",parameters:p.Object({goal:p.String({description:"End goal for the autonomous task"}),verifier_commands:p.Optional(p.Array(p.String({description:"Shell command that must pass for the goal to be considered complete"}),{minItems:1,description:"Verifier commands run after each coding turn"})),name:p.Optional(p.String({description:"Short task name (kebab-case preferred)"})),workdir:p.Optional(p.String({description:"Working directory (defaults to cwd / configured workspace)"})),model:p.Optional(p.String({description:"Model name to use"})),system_prompt:p.Optional(p.String({description:"Additional system prompt"})),allowed_tools:p.Optional(p.Array(p.String(),{description:"Allowed tools for the underlying agent session"})),max_iterations:p.Optional(p.Number({description:"Maximum verifier-driven repair iterations",minimum:1})),goal_mode:p.Optional(p.Union([p.Literal("ralph"),p.Literal("verifier")],{description:"Loop strategy. 'ralph' repeats until a completion promise appears. 'verifier' repeats until verifier commands pass. Defaults to 'ralph' when no verifiers are provided, otherwise 'verifier'."})),completion_promise:p.Optional(p.String({description:"Exact completion promise for Ralph-mode loops. Defaults to 'DONE'."})),permission_mode:p.Optional(p.Union([p.Literal("default"),p.Literal("plan"),p.Literal("bypassPermissions")],{description:"Permission mode for the underlying agent session. Defaults to bypassPermissions for autonomous goal loops."})),harness:p.Optional(p.String({description:"Agent harness to use (e.g. 'codex' or 'claude-code')."}))}),async execute(e,r){if(!fe)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!fw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let n=r.workdir||t.workspaceDir||_.defaultWorkdir||process.cwd();if(!mw(n))return{content:[{type:"text",text:`Error: Working directory does not exist: ${n}`}]};let o=(r.verifier_commands??[]).map((f,v)=>({label:`check-${v+1}`,command:f.trim()})).filter(f=>f.command.length>0),i=r.goal_mode??(o.length>0?"verifier":"ralph");if(i==="verifier"&&o.length===0)return{content:[{type:"text",text:"Error: verifier_commands must contain at least one non-empty command for verifier goal mode."}]};let s=r.harness??Pe(),a=r.model??Ct(s);if(!a)return{content:[{type:"text",text:`Error: No default model configured for harness "${s}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${s}.defaultModel or pass model explicitly.`}]};let d=en(s);if(!Hi(a,d))return{content:[{type:"text",text:`Error: Model "${a}" is not allowed. Permitted models: ${d?.join(", ")}`}]};let l=t.sessionKey||void 0,m=ni(t),S=qt(t,m),y=_t(t,S,l);try{let f=await fe.launchTask({goal:r.goal,name:r.name,workdir:n,model:a,reasoningEffort:lt(s),systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,maxIterations:r.max_iterations,permissionMode:r.permission_mode??"bypassPermissions",loopMode:i,completionPromise:r.completion_promise,originChannel:S,originThreadId:y?.threadId,originAgentId:t.agentId||void 0,originSessionKey:l,route:y,harness:s,verifierCommands:o});return{content:[{type:"text",text:["Goal task launched successfully.",` Name: ${f.name}`,` ID: ${f.id}`,` Dir: ${f.workdir}`,` Session: ${f.sessionName} [${f.sessionId}]`,` Harness: ${s}`,` Model: ${a}`,` Loop mode: ${f.loopMode}`,` Max iterations: ${f.maxIterations}`,` Goal: "${r.goal.length>100?`${r.goal.slice(0,100)}...`:r.goal}"`,...f.loopMode==="ralph"?[` Completion promise: ${f.completionPromise}`]:[" Verifiers:",...o.map(A=>` - ${A.command}`)],"","Use goal_status to follow progress or goal_stop to terminate the task."].join(`
90
+ `)}]}}catch(f){return{content:[{type:"text",text:`Error launching goal task: ${f instanceof Error?f.message:String(f)}`}]}}}}}Ee();function _f(t,e){return t.split(`
91
+ `).map(r=>`${e}${r}`)}function gw(t,e=8,r=600){let n=t.map(i=>i.trimEnd()).filter(i=>i.trim().length>0);if(n.length===0)return;let o=n.slice(-e).join(`
92
+ `);return o.length<=r?o:`...${o.slice(-(r-3))}`}function ar(t){if(t)return{phase:t.phase,awaitingInput:t.isAwaitingInput??!!t.pendingInputState,latestOutput:gw(t.getOutput(20))}}function dr(t,e){let r=t.loopMode??"verifier",n=[`${t.name} [${t.id}]`,` Status: ${t.status}`,...r==="ralph"?[" Loop mode: ralph",` Iteration: ${t.iteration}/${t.maxIterations}`]:[` Repair iteration: ${t.iteration}/${t.maxIterations}`],` Workdir: ${t.workdir}`];return r==="ralph"&&t.completionPromise&&n.push(` Completion promise: ${t.completionPromise}`),t.sessionId&&n.push(` Session: ${t.sessionName??"(unknown)"} [${t.sessionId}]`),e?.phase&&n.push(` Phase: ${e.phase}`),e?.awaitingInput!==void 0&&n.push(` Awaiting input: ${e.awaitingInput?"yes":"no"}`),t.lastVerifierSummary&&(n.push(" Last verifier:"),n.push(..._f(t.lastVerifierSummary," "))),e?.latestOutput&&(n.push(" Latest activity:"),n.push(..._f(e.latestOutput," "))),t.waitingForUserReason&&n.push(` Waiting on user: ${t.waitingForUserReason}`),t.failureReason&&n.push(` Failure: ${t.failureReason}`),n.join(`
93
+ `)}Y();function $f(t){return{name:"goal_status",description:"Show status for explicit goal tasks managed by the goal controller. Use this to inspect one goal task or list all goal tasks.",parameters:p.Object({task:p.Optional(p.String({description:"Task name or ID. Omit to list all tasks."}))}),async execute(e,r){if(!fe)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};let n=r&&typeof r=="object"&&typeof r.task=="string"?r.task:void 0;if(n){let i=fe.getTask(n);if(!i)return{content:[{type:"text",text:`Error: Goal task "${n}" not found.`}]};let s=i.sessionId?k?.resolve(i.sessionId):void 0;return{content:[{type:"text",text:dr(i,ar(s))}]}}let o=fe.listTasks();return o.length===0?{content:[{type:"text",text:"No goal tasks found."}]}:{content:[{type:"text",text:o.map(i=>{let s=i.sessionId?k?.resolve(i.sessionId):void 0;return dr(i,ar(s))}).join(`
94
+
95
+ `)}]}}}}Ee();Y();function hw(t){return!!t&&typeof t=="object"&&typeof t.task=="string"}function Ef(t){return{name:"goal_stop",description:"Stop an explicit goal task and kill its underlying agent session.",parameters:p.Object({task:p.String({description:"Goal task name or ID"})}),async execute(e,r){if(!fe)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!hw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let n=fe.stopTask(r.task);return n?{content:[{type:"text",text:n.action==="already_terminal"?`Task is already ${n.task.status}.`:`Task "${n.task.name}" (${n.task.id}) stopped.`}]}:{content:[{type:"text",text:`Error: Goal task "${r.task}" not found.`}]}}}}Y();Gi();var lr="code-agent";function Sw(t){let e=t.trim().replace(new RegExp(`^${lr}:`),"");return e||null}async function zi(t,e){try{await pt(t,{text:e})}catch(r){let n=r instanceof Error?r.message:String(r);console.warn(`[callback-handler] Failed to resolve worktree prompt: ${n}`)}}function Bd(t){if(t&&typeof t=="object"&&"content"in t&&Array.isArray(t.content)){let e=t.content[0];return typeof e?.text=="string"?e.text:"(done)"}return"(done)"}function yw(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}function kw(t,e){if(yw(t.kind)){if(!e)return"This plan decision is stale because the session is no longer available.";if(t.planDecisionVersion!=null&&(e.actionablePlanDecisionVersion??e.planDecisionVersion)!=null&&t.planDecisionVersion!==(e.actionablePlanDecisionVersion??e.planDecisionVersion))return"This plan decision is stale because a newer plan review state already exists.";if(!e.pendingPlanApproval)return"This plan is no longer awaiting approval.";if(t.kind==="plan-approve"&&e.approvalState==="changes_requested"&&!e.pendingPlanApproval)return"Changes were already requested for this plan. Wait for the revised plan before approving.";if(t.kind==="plan-request-changes"&&e.approvalState==="changes_requested")return"Changes were already requested for this plan. Send your feedback to the agent instead."}}function vw(t){let e="callback"in t?t.callback?.payload:void 0,r="interaction"in t?t.interaction?.payload:void 0;return e??r??""}function Ud(t){let e=t instanceof Error?t.message:String(t);return/message is not modified/i.test(e)}function Pw(t){let e=t instanceof Error?t.message:String(t);return/empty message/i.test(e)}async function pt(t,e={}){let r=t.respond,{text:n}=e;if(t.channel==="telegram"){if(typeof n=="string"&&typeof r.editMessage=="function")try{await r.editMessage({text:n,buttons:[]});return}catch(o){if(Ud(o))return;let i=o instanceof Error?o.message:String(o);console.warn(`[callback-handler] Failed to edit Telegram worktree prompt before clearing buttons: ${i}`)}typeof r.clearButtons=="function"&&await r.clearButtons();return}if(typeof r.clearComponents=="function")try{await r.clearComponents(typeof n=="string"?{text:n}:void 0);return}catch(o){if(Ud(o))return;if(Pw(o)){if(typeof n!="string"&&typeof r.acknowledge=="function"){await r.acknowledge();return}typeof n!="string"&&typeof r.acknowledge!="function"&&console.warn("[callback-handler] clearComponents failed with empty-message error and no acknowledge fallback available")}else{if(typeof n!="string")throw o;{let i=o instanceof Error?o.message:String(o);console.warn(`[callback-handler] clearComponents failed before text fallback: ${i}`)}}}if(typeof n=="string"&&typeof r.editMessage=="function")try{await r.editMessage({text:n})}catch(o){if(!Ud(o)){let i=o instanceof Error?o.message:String(o);console.warn(`[callback-handler] Failed to edit worktree prompt before clearing interactive state: ${i}`)}}typeof r.clearButtons=="function"&&await r.clearButtons()}async function oe(t,e){if(t.channel==="telegram"){await t.respond.reply({text:e});return}await t.respond.reply({text:e,ephemeral:!0})}function Kd(t="telegram"){return{channel:t,namespace:lr,handler:async e=>{if(!e.auth.isAuthorizedSender)return await oe(e,"\u26D4 Unauthorized."),{handled:!0};let r=vw(e),n=Sw(r);if(!n)return await oe(e,`\u26A0\uFE0F Unrecognized callback payload: "${r}".`),{handled:!0};if(!k)return await oe(e,"\u26A0\uFE0F Code agent service not running."),{handled:!0};let o=k.getActionToken(n);if(!o)return await oe(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};let i=o.sessionId,s=k.resolve?.(i)??k.getPersistedSession?.(i),a=s?.name??i,d=kw(o,s);if(d)return await pt(e),await oe(e,`\u26A0\uFE0F ${d}`),{handled:!0};let l=k.consumeActionToken(n);if(!l)return await oe(e,"\u26A0\uFE0F This action is stale or has already been used."),{handled:!0};switch(l.kind){case"worktree-merge":{await zi(e,`\u2705 Merge selected for [${a}]`);let m=await ji().execute("callback",{session:i});await oe(e,Bd(m));break}case"worktree-decide-later":{await zi(e,`\u23ED\uFE0F Deferred for [${a}]`);let m=k.snoozeWorktreeDecision(i);await oe(e,m.startsWith("Error")?m:"\u23ED\uFE0F Snoozed 24h");break}case"worktree-dismiss":{await zi(e,`\u{1F5D1}\uFE0F Discarded for [${a}]`);let m=await k.dismissWorktree(i);await oe(e,(m.startsWith("Error"),m));break}case"worktree-create-pr":case"worktree-update-pr":{await zi(e,o.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${a}]`:`\u{1F4EC} PR selected for [${a}]`);let m=await ro().execute("callback",{session:i});await oe(e,Bd(m));break}case"worktree-view-pr":{await pt(e);let m=k.getPersistedSession?.(i),S=o.targetUrl??m?.worktreePrUrl;await oe(e,S?`PR: ${S}`:"\u26A0\uFE0F PR URL is no longer available.");break}case"plan-approve":{await pt(e),k.clearPlanDecisionTokens(i);let m=await bt(k,{session:i,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});m.isError&&await oe(e,`\u26A0\uFE0F ${m.text}`);break}case"plan-reject":{await pt(e),k.clearPlanDecisionTokens(i);let m=k.resolve(i);if(m)m.approvalState="rejected",k.kill(m.id,"user"),await oe(e,`\u274C Plan rejected for [${m.name}]. Session stopped.`);else{let S=k.getPersistedSession?.(i);S?(k.updatePersistedSession?.(i,{approvalState:"rejected",lifecycle:"terminal",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:(S.planDecisionVersion??0)+1}),await oe(e,`\u274C Plan rejected for [${S.name??a}]. Session remains stopped.`)):await oe(e,"\u274C Plan rejected.")}break}case"plan-request-changes":{await pt(e);let m=k.resolve?.(i),S=k.getPersistedSession?.(i),y=m?.name??S?.name??i,f=(m?.planDecisionVersion??S?.planDecisionVersion??0)+1;k.clearPlanDecisionTokens(i),k.updatePersistedSession(i,{approvalState:"changes_requested",lifecycle:"awaiting_user_input",pendingPlanApproval:!1,planDecisionVersion:f,actionablePlanDecisionVersion:void 0,canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:void 0,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",approvalPromptTransport:"none",approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:void 0}),await oe(e,`\u270F\uFE0F Type your revision feedback for [${y}] and I'll forward it to the agent.`);break}case"monitor-start-plan":{if(await pt(e),!l.launchPrompt||!l.launchWorkdir){await oe(e,"\u26A0\uFE0F This release action is missing the plan launch context.");break}let m=k.launchMonitorPlan({route:l.route,prompt:l.launchPrompt,workdir:l.launchWorkdir,name:l.launchName});await oe(e,`\u25B6\uFE0F Planning session started: ${m.name} [${m.id}]`);break}case"monitor-dismiss":{await pt(e),await oe(e,"\u2705 Dismissed.");break}case"session-restart":case"session-resume":{await pt(e);let m=await bt(k,{session:i,message:"Continue where you left off.",userInitiated:!0});await oe(e,m.isError?`\u26A0\uFE0F ${m.text}`:`\u25B6\uFE0F ${m.text}`);break}case"view-output":{await pt(e);let m=await Wi().execute("callback",{session:i,lines:50});await oe(e,Bd(m));break}case"question-answer":{if(await pt(e),o.optionIndex==null){await oe(e,"\u26A0\uFE0F Invalid question-answer action.");break}await k.resolvePendingInputOption(i,o.optionIndex),await oe(e,"\u2705 Answer submitted.");break}default:{await pt(e),await oe(e,"\u26A0\uFE0F Unknown callback action.");break}}return{handled:!0}}}}Y();Re();function ww(t){return t instanceof Error?t.message:String(t)}function Of(t){t.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /agent [--name <name>] <prompt>"};let n,o=r.match(/^--name\s+(\S+)\s+/);o&&(n=o[1],r=r.slice(o[0].length).trim());let i=r;if(!i)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let s=Pe(),a=Ct(s);if(!a)return{text:`Error: No default model configured for harness "${s}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${s}.defaultModel or pass model explicitly via agent_launch.`};let d=k.spawn({prompt:i,name:n,workdir:_.defaultWorkdir||process.cwd(),model:a,reasoningEffort:lt(s),codexApprovalPolicy:s==="codex"?"never":void 0,originChannel:qt(e),originThreadId:Un(e),route:_t(e),harness:s}),l=i.length>80?i.slice(0,80)+"...":i;return{text:["Session launched.",` Name: ${d.name}`,` ID: ${d.id}`,` Prompt: "${l}"`,` Status: ${d.status}`].join(`
96
+ `)}}catch(s){let a=ww(s),d=a.includes("Max sessions")?"":`
97
+
98
+ Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${d}`}}}})}Y();function Df(t){t.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").split(/\s+/).includes("--full");return{text:Fi(k,"all",void 0,{full:r})}}})}Y();function Nf(t){t.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=e.args?.trim();return r?{text:Li(k,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}Y();function Ff(t){t.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:`Usage: /agent_respond <id-or-name> <message>
99
+ /agent_respond --interrupt <id-or-name> <message>`};let n=!1,o=r;o.startsWith("--interrupt ")&&(n=!0,o=o.slice(12).trim());let i=o.indexOf(" ");if(i===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let s=o.slice(0,i),a=o.slice(i+1).trim();return a?{text:(await bt(k,{session:s,message:a,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}Y();function Lf(t){t.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let e=k.getMetrics(),r=k.list("running").length;return{text:Di(e,r)}}})}Y();var Iw=50;function Wf(t){t.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let n=r.split(/\s+/),o="",i=!1,s=Iw;for(let d=0;d<n.length;d++)if(n[d]==="--full")i=!0;else if(n[d]==="--lines"&&d+1<n.length){let l=parseInt(n[d+1],10);!isNaN(l)&&l>0&&(s=l),d++}else o||(o=n[d]);return o?{text:Ni(k,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}Y();Re();import{existsSync as bw}from"fs";function xw(t){let e=t.match(/"[^"]*"|'[^']*'|\S+/g);return e?e.map(r=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r):[]}function Bf(t){t.registerCommand({name:"goal",description:"Launch an explicit goal task (Ralph-style completion loop or verifier-driven loop)",acceptsArgs:!0,requireAuth:!0,handler:async e=>{if(!fe)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>"};let n=xw(r),o,i=_.defaultWorkdir||process.cwd(),s,a,d="bypassPermissions",l,m,S,y=[],f=[];for(let b=0;b<n.length;b++){let M=n[b];if(M==="--name"&&b+1<n.length)o=n[++b];else if(M==="--workdir"&&b+1<n.length)i=n[++b];else if(M==="--model"&&b+1<n.length)s=n[++b];else if(M==="--max-iterations"&&b+1<n.length){let F=parseInt(n[++b],10);!Number.isNaN(F)&&F>0&&(a=F)}else if(M==="--permission-mode"&&b+1<n.length){let F=n[++b];if(F==="default"||F==="plan"||F==="bypassPermissions")d=F;else return{text:`Error: Invalid permission mode "${F}".`}}else if(M==="--harness"&&b+1<n.length)l=n[++b];else if(M==="--mode"&&b+1<n.length){let F=n[++b];if(F==="ralph"||F==="verifier")m=F;else return{text:`Error: Invalid goal mode "${F}". Use ralph or verifier.`}}else if(M==="--completion-promise"&&b+1<n.length)S=n[++b];else if(M==="--verify"&&b+1<n.length){let F=n[++b].trim();if(!F)return{text:"Error: --verify commands must not be empty."};y.push(F)}else f.push(M)}let v=f.join(" ").trim();if(!v)return{text:"Usage: /goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>"};if(!bw(i))return{text:`Error: Working directory does not exist: ${i}`};let A=m??(y.length>0?"verifier":"ralph");if(A==="verifier"&&y.length===0)return{text:"Error: verifier mode requires at least one --verify command."};let x=l??Pe(),w=s??Ct(x);if(!w)return{text:`Error: No default model configured for harness "${x}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${x}.defaultModel or pass model explicitly.`};let C=en(x);if(!Hi(w,C))return{text:`Error: Model "${w}" is not allowed. Permitted models: ${C?.join(", ")}`};try{let b=_t(e),M=await fe.launchTask({goal:v,name:o,workdir:i,model:w,reasoningEffort:lt(x),maxIterations:a,permissionMode:d,harness:x,loopMode:A,completionPromise:S,originChannel:qt(e),originThreadId:b?.threadId,originSessionKey:e.sessionKey,route:b,verifierCommands:y.map((F,Le)=>({label:`check-${Le+1}`,command:F}))});return{text:["Goal task launched.",` Name: ${M.name}`,` ID: ${M.id}`,` Session: ${M.sessionName} [${M.sessionId}]`,` Harness: ${x}`,` Loop mode: ${M.loopMode}`,...M.loopMode==="ralph"?[` Completion promise: ${M.completionPromise}`]:[],` Max iterations: ${M.maxIterations}`,` Goal: "${v.length>100?`${v.slice(0,100)}...`:v}"`].join(`
100
+ `)}}catch(b){return{text:`Error launching goal task: ${b.message}`}}}})}Y();function Uf(t){t.registerCommand({name:"goal_status",description:"Show one goal task or list all explicit goal tasks. Usage: /goal_status [<task-id-or-name>]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!fe)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(r){let o=fe.getTask(r);if(!o)return{text:`Error: Goal task "${r}" not found.`};let i=o.sessionId?k?.resolve(o.sessionId):void 0;return{text:dr(o,ar(i))}}let n=fe.listTasks();return n.length===0?{text:"No goal tasks found."}:{text:n.map(o=>{let i=o.sessionId?k?.resolve(o.sessionId):void 0;return dr(o,ar(i))}).join(`
101
+
102
+ `)}}})}Y();function Kf(t){t.registerCommand({name:"goal_stop",description:"Stop a goal task. Usage: /goal_stop <task-id-or-name>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!fe)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let r=(e.args??"").trim();if(!r)return{text:"Usage: /goal_stop <task-id-or-name>"};let n=fe.stopTask(r);return n?n.action==="already_terminal"?{text:`Task is already ${n.task.status}.`}:{text:`Task "${n.task.name}" (${n.task.id}) stopped.`}:{text:`Error: Goal task "${r}" not found.`}}})}import{execFile as Lw}from"child_process";import{createHash as Yf}from"crypto";import{existsSync as Aw,mkdirSync as Rw,readFileSync as Tw,renameSync as Mw,writeFileSync as Cw}from"fs";import{homedir as _w}from"os";import{dirname as $w,join as Vf}from"path";function Ew(t){let e=t.OPENCLAW_HOME?.trim();return e||Vf(_w(),".openclaw")}function Ow(t){let e=t.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||Vf(Ew(t),"code-agent-goal-tasks.json")}function Dw(t){return t instanceof Error?t.message:String(t)}function Nw(t){if(!t||typeof t!="object")return;let e=t;if(!(typeof e.provider!="string"||typeof e.target!="string"))return{provider:e.provider,target:e.target,accountId:typeof e.accountId=="string"?e.accountId:void 0,threadId:typeof e.threadId=="string"?e.threadId:void 0,sessionKey:typeof e.sessionKey=="string"?e.sessionKey:void 0}}function Fw(t){if(!t||typeof t!="object")return;let e=t;if(typeof e.id!="string"||typeof e.name!="string"||typeof e.goal!="string"||typeof e.workdir!="string"||typeof e.status!="string")return;let r=e.status,n=r==="running"||r==="waiting_for_session"?"waiting_for_session":r;return{id:e.id,name:e.name,goal:e.goal,workdir:e.workdir,status:n,createdAt:typeof e.createdAt=="number"?e.createdAt:Date.now(),updatedAt:typeof e.updatedAt=="number"?e.updatedAt:Date.now(),iteration:typeof e.iteration=="number"?e.iteration:0,maxIterations:typeof e.maxIterations=="number"?e.maxIterations:8,sessionId:typeof e.sessionId=="string"?e.sessionId:void 0,sessionName:typeof e.sessionName=="string"?e.sessionName:void 0,harnessSessionId:typeof e.harnessSessionId=="string"?e.harnessSessionId:void 0,model:typeof e.model=="string"?e.model:void 0,reasoningEffort:typeof e.reasoningEffort=="string"?e.reasoningEffort:void 0,systemPrompt:typeof e.systemPrompt=="string"?e.systemPrompt:void 0,allowedTools:Array.isArray(e.allowedTools)?e.allowedTools.filter(o=>typeof o=="string"):void 0,originChannel:typeof e.originChannel=="string"?e.originChannel:void 0,originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originAgentId:typeof e.originAgentId=="string"?e.originAgentId:void 0,originSessionKey:typeof e.originSessionKey=="string"?e.originSessionKey:void 0,route:Nw(e.route),harness:typeof e.harness=="string"?e.harness:void 0,permissionMode:typeof e.permissionMode=="string"?e.permissionMode:void 0,loopMode:e.loopMode==="ralph"?"ralph":"verifier",completionPromise:typeof e.completionPromise=="string"?e.completionPromise:void 0,verifierCommands:Array.isArray(e.verifierCommands)?e.verifierCommands.filter(o=>!!o&&typeof o=="object"&&typeof o.label=="string"&&typeof o.command=="string"):[],lastVerifierSummary:typeof e.lastVerifierSummary=="string"?e.lastVerifierSummary:void 0,lastVerifierFingerprint:typeof e.lastVerifierFingerprint=="string"?e.lastVerifierFingerprint:void 0,repeatedFailureCount:typeof e.repeatedFailureCount=="number"?e.repeatedFailureCount:0,waitingForUserReason:typeof e.waitingForUserReason=="string"?e.waitingForUserReason:void 0,failureReason:typeof e.failureReason=="string"?e.failureReason:void 0}}var Qi=class{path;tasks=new Map;constructor(e=process.env){this.path=Ow(e),this.load()}load(){try{if(!Aw(this.path))return;let e=Tw(this.path,"utf8"),r=JSON.parse(e);if(!Array.isArray(r))return;for(let n of r){let o=Fw(n);o&&this.tasks.set(o.id,o)}this.save()}catch{}}save(){try{Rw($w(this.path),{recursive:!0});let e=`${this.path}.tmp`;Cw(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),Mw(e,this.path)}catch(e){console.warn(`[GoalTaskStore] Failed to save ${this.path}: ${Dw(e)}`)}}upsert(e){this.tasks.set(e.id,e),this.save()}get(e){let r=this.tasks.get(e);return r||[...this.tasks.values()].find(n=>n.name===e)}list(){return[...this.tasks.values()].sort((e,r)=>r.createdAt-e.createdAt)}};Zr();var Ww=8,Xf=600*1e3,Bw=4e3,Vd=1200,Uw="DONE";function Kw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function no(t,e){return t.length<=e?t:`${t.slice(0,e-3)}...`}function ur(t,e=20){let r=t.split(/\r?\n/).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);return r.length<=e?r.join(`
103
+ `):r.slice(-e).join(`
104
+ `)}function qf(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jf(t){let e=t?.trim();return e&&e.length>0?e:Uw}function Vw(t){return t.route??Wn(t.originChannel,t.originThreadId,t.originSessionKey)}function qd(t){return t.map((e,r)=>({label:e.label.trim()||`check-${r+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??Xf})).filter(e=>e.command.length>0)}function qw(t){return t.loopMode==="verifier"}function jw(t){return qd(t.verifierCommands).length>0}function Gf(t){return qw(t)&&!jw(t)}function Ji(){return"Verifier-mode goal tasks require at least one verifier command."}function Hf(t){let e=t.steps.filter(r=>!r.ok).map(r=>`${r.label}:${r.exitCode}:${ur(r.output,12)}`).join(`
105
+ `);return Yf("sha1").update(e).digest("hex")}function Gw(t){return Yf("sha1").update(ur(t,24)).digest("hex")}function zf(t){let e=t.toLowerCase().replace(/\s+/g," ").trim();if(!e)return;if(/\b(can i|may i|should i|do you want me to|would you like me to)\b/.test(e)&&/\b(read|write|edit|modify|change|inspect|search|run|execute|install|delete|move|rename|open)\b/.test(e))return"Yes, proceed.";if(/\b(should i continue|shall i continue|want me to continue|should i proceed|shall i proceed|can i proceed|go ahead)\b/.test(e))return"Yes, continue."}function Hw(t){if(t.loopMode==="ralph")return["You are working inside a Ralph Wiggum-style autonomous loop.","","Goal:",t.goal,"","Loop rules:","- Keep making concrete progress toward the goal in this repository.","- An external controller will continue looping until you emit the completion promise or the iteration budget is exhausted.",`- When the goal is truly complete, output this exact marker on its own line: <promise>${t.completionPromise}</promise>`,"- Do not output that completion marker early, approximately, or with altered spelling.","- If you are not done yet, do not emit the completion marker.","- Do not ask to stop or wait for confirmation unless blocked by a real product, architecture, credential, or approval decision.","- Re-run useful local checks before ending each turn.",t.verifierCommands.length>0?"- External verifier commands will also be run after you claim completion.":"- There may not be external verifiers, so your completion promise is the success gate."].join(`
106
+ `);let e=t.verifierCommands.map(r=>`- ${r.label}: ${r.command}`).join(`
107
+ `);return["You are working on an autonomous goal-driven task.","","Goal:",t.goal,"","Working rules:","- Make concrete progress toward the goal in this repository.","- An external controller will run these verifier commands after your turn:",e,"- If any verifier fails, you will receive the exact failures and must continue fixing the remaining gaps.","- Do not stop early just because you think the task is probably done.","- Do not ask for confirmation unless you are blocked by a real product, architecture, or credential decision.","- Before ending a turn, run any local checks you think are useful."].join(`
108
+ `)}function Qf(t){return t.loopMode==="ralph"?["The OpenClaw gateway restarted while this Ralph-style goal task was running.","Resume from the prior session context and continue immediately.","","Goal:",t.goal,"","Instructions:","- Continue from the current repo state and prior session context without restarting from scratch.",`- Only emit <promise>${t.completionPromise}</promise> when the goal is actually complete.`,"- The external controller will keep looping until that marker appears or the iteration budget is exhausted.","- Do not ask for confirmation just because the gateway restarted."].join(`
109
+ `):["The OpenClaw gateway restarted while this autonomous goal task was running.","Resume from the prior session context and continue toward the same goal immediately.","","Goal:",t.goal,"","Instructions:","- Re-orient yourself from the existing repo state and prior session context.","- Continue the task without restarting from scratch unless the prior approach is clearly invalid.","- The external controller will continue running verifier commands after your turns.","- Do not ask for confirmation just because the gateway restarted."].join(`
110
+ `)}function zw(t,e){let r=e.steps.filter(o=>!o.ok).map(o=>[`- ${o.label} failed (exit ${o.exitCode})`,ur(o.output,18)].join(`
111
+ `)).join(`
112
+
113
+ `);return["The external verifier did not pass.",t.repeatedFailureCount>=2?"The same verifier fingerprint has repeated. Use a different debugging strategy than your previous attempt.":"Fix only the remaining issues from the verifier output below.","","Goal:",t.goal,"","Verifier failures:",r,"","Instructions:","- Continue from the current code state and prior session context.","- Make the minimum necessary changes to satisfy the remaining verifier failures.","- Re-run relevant checks yourself before ending the turn.","- Do not ask for confirmation unless you are truly blocked on a human decision."].join(`
114
+ `)}function Qw(t,e){let r=ur(e,18)||"(no meaningful output)",n=t.repeatedFailureCount>=2?"The loop has repeated without converging. Use a different strategy than the previous attempt.":"Continue from the current repo state and prior session context.";return["Continue the same Ralph-style goal task.","","Goal:",t.goal,"","Status:",`- The last turn ended without the completion promise <promise>${t.completionPromise}</promise>.`,`- Current iteration: ${t.iteration}/${t.maxIterations}.`,`- ${n}`,"","Latest output / blockers:",r,"","Instructions:","- Keep working until the goal is actually complete.",`- Only emit <promise>${t.completionPromise}</promise> when all requested work is done.`,"- If you are not done, do not emit the completion promise.",t.verifierCommands.length>0?"- If you believe you are done, make sure the expected verifiers are likely to pass before emitting the completion promise.":"- There may not be external verifiers, so your completion promise is the success signal."].join(`
115
+ `)}function Jw(t,e){let r=e.steps.filter(n=>!n.ok).map(n=>[`- ${n.label} failed (exit ${n.exitCode})`,ur(n.output,18)].join(`
116
+ `)).join(`
117
+
118
+ `);return["You emitted the completion promise, but the external verifiers did not pass.","","Goal:",t.goal,"","Verifier failures:",r,"","Instructions:","- Continue from the current repo state and fix only the remaining gaps.",`- Do not emit <promise>${t.completionPromise}</promise> again until the goal is fully complete and the failing checks are addressed.`,"- Re-run relevant checks yourself before ending the turn."].join(`
119
+ `)}function Yw(t,e){let r=e.trim();if(!r)return!1;let n=new RegExp(`(^|\\n)\\s*${qf(r)}\\s*(\\n|$)`,"i"),o=new RegExp(`<promise>\\s*${qf(r)}\\s*<\\/promise>`,"i");return n.test(t)||o.test(t)}function Jf(t){return t.steps.map(e=>`${e.ok?"PASS":"FAIL"} ${e.label} (exit ${e.exitCode}, ${Math.round(e.durationMs)}ms)`).join(`
120
+ `)}function $r(t){return t instanceof Error?t.message:String(t)}function Xw(t){return t==="succeeded"||t==="failed"||t==="stopped"}function Zw(t){return no(t.error?.trim()||"Underlying session failed.",Vd)}function eI(t,e){return new Promise(r=>{let n=Date.now();Lw("bash",["-lc",e.command],{cwd:t,timeout:e.timeoutMs??Xf,maxBuffer:1024*1024},(o,i,s)=>{let a=Date.now()-n,d=typeof o?.code=="number"?o.code:o?1:0,l=`${i??""}${s?`
121
+ ${s}`:""}`.trim();r({label:e.label,command:e.command,ok:!o,exitCode:d,durationMs:a,output:no(l||"(no output)",Bw)})})})}var Yi=class{store;sessionManager;restorePromise=null;inFlight=new Set;observerDisposers=new Map;scheduledEvaluations=new Map;dirtyEvaluations=new Set;dirtyEvaluationSessionIds=new Map;started=!1;constructor(e){this.sessionManager=e,this.store=new Qi}start(){this.started||(this.started=!0,!this.restorePromise&&(this.restorePromise=this.restoreRecoverableTasks().catch(e=>{console.warn(`[GoalController] Failed to restore recoverable tasks: ${$r(e)}`)}).finally(()=>{this.restorePromise=null})))}stop(){this.started=!1,this.clearScheduledEvaluations(),this.detachSessionObservers(),this.captureRecoverableTasks(),this.store.save()}listTasks(){return this.store.list()}getTask(e){return this.store.get(e)}async launchTask(e){let r=e.loopMode??"verifier",n=qd(e.verifierCommands);if(r==="verifier"&&n.length===0)throw new Error(Ji());let i={id:hi(8),name:Kw(e.name??e.goal),goal:e.goal.trim(),workdir:e.workdir,status:"waiting_for_session",createdAt:Date.now(),updatedAt:Date.now(),iteration:0,maxIterations:e.maxIterations??Ww,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,allowedTools:e.allowedTools,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,harness:e.harness,permissionMode:e.permissionMode??"bypassPermissions",loopMode:r,completionPromise:jf(e.completionPromise),verifierCommands:n,repeatedFailureCount:0},s=await this.spawnTaskSession(i,Hw(i));return this.attachSessionObservers(i,s),i.sessionId=s.id,i.sessionName=s.name,i.harnessSessionId=s.harnessSessionId,i.status="running",i.updatedAt=Date.now(),this.store.upsert(i),this.scheduleTaskEvaluation(i.id,"launch",s.id),this.notify(i,`\u{1F3AF} [${i.name}] Goal task started
122
+
123
+ Goal:
124
+ ${no(i.goal,500)}`,"goal-task-started"),i}stopTask(e){let r=this.store.get(e);if(r)return Xw(r.status)?{task:r,action:"already_terminal"}:(r.sessionId&&this.sessionManager.kill(r.sessionId,"user"),this.markTaskStopped(r,"Stopped by user."),{task:r,action:"stopped"})}async spawnTaskSession(e,r){return this.spawnManagedTaskSession(e,r)}async spawnManagedTaskSession(e,r,n){let o=n?this.sessionManager.resolveHarnessSessionId(n)??n:void 0,i=n?this.sessionManager.resolve(n):void 0,s=o?this.sessionManager.getPersistedSession(o)??this.sessionManager.getPersistedSession(n??o):void 0,{resumeSessionId:a}=tn({requestedResumeSessionId:o,activeSession:i?{harnessSessionId:i.harnessSessionId}:void 0,persistedSession:s?{harness:s.harness,backendRef:s.backendRef}:void 0}),d={prompt:r,name:e.name,workdir:e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,systemPrompt:e.systemPrompt,allowedTools:e.allowedTools,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:Vw(e),permissionMode:e.permissionMode,multiTurn:!0,goalTaskId:e.id,harness:e.harness,resumeSessionId:a,resumeWorktreeFrom:o,worktreeStrategy:"off"};return this.sessionManager.spawnAndAwaitRunning(d,{notifyLaunch:!1})}async resumeTaskSession(e,r,n){if(!n.harnessSessionId){let i=await this.spawnTaskSession(e,["The previous session ended without a resumable harness session id.","Continue working on the same goal.","",r].join(`
125
+ `));return this.attachSessionObservers(e,i),i}let o=await this.spawnManagedTaskSession(e,r,n.harnessSessionId);return this.attachSessionObservers(e,o),o}resolveResumeSessionId(e){if(e.harnessSessionId)return e.harnessSessionId;if(e.sessionId){let n=this.sessionManager.resolveHarnessSessionId(e.sessionId);if(n)return n}let r=this.sessionManager.resolveHarnessSessionId(e.name);if(r)return r}captureRecoverableTasks(){for(let e of this.store.list()){if(e.status!=="running"&&e.status!=="waiting_for_session")continue;let r=e.sessionId?this.sessionManager.resolve(e.sessionId):void 0;r&&(e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId??e.harnessSessionId,e.route=r.route??e.route,e.updatedAt=Date.now(),e.status="waiting_for_session",this.store.upsert(e))}}async restoreRecoverableTasks(){for(let e of this.store.list()){if(!this.started)break;if(e.status==="waiting_for_user"){this.markTaskFailed(e,"Goal task was waiting for user input and cannot continue autonomously");continue}if(e.status!=="waiting_for_session"&&e.status!=="running")continue;if(Gf(e)){this.markTaskFailed(e,Ji());continue}if(e.sessionId){let n=this.sessionManager.resolve(e.sessionId);if(n&&(n.status==="starting"||n.status==="running"))continue}let r=this.resolveResumeSessionId(e);if(!r){this.markTaskFailed(e,"Goal task could not be resumed after gateway restart because no resumable session id was available.");continue}try{let n=await this.spawnManagedTaskSession(e,Qf(e),r);if(!this.started){e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??r,e.route=n.route??e.route,e.status="waiting_for_session",e.updatedAt=Date.now(),this.store.upsert(e),this.sessionManager.kill(n.id,"shutdown");break}this.attachSessionObservers(e,n),e.sessionId=n.id,e.sessionName=n.name,e.harnessSessionId=n.harnessSessionId??r,e.route=n.route??e.route,e.status="running",e.updatedAt=Date.now(),this.store.upsert(e),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after gateway restart`,n),this.scheduleTaskEvaluation(e.id,"restore",n.id)}catch(n){this.markTaskFailed(e,`Failed to resume the goal task after gateway restart: ${$r(n)}`)}}}async runVerifiers(e){let r=qd(e.verifierCommands);if(r.length===0){let s={status:"fail",steps:[{label:"verifier-config",command:"(none configured)",ok:!1,exitCode:1,durationMs:0,output:Ji()}],summary:"",fingerprint:""};return s.fingerprint=Hf(s),s.summary=Jf(s),s}let n=[];for(let s of r)n.push(await eI(e.workdir,s));let i={status:n.every(s=>s.ok)?"pass":"fail",steps:n,summary:"",fingerprint:""};return i.fingerprint=Hf(i),i.summary=Jf(i),i}notify(e,r,n){this.sessionManager.emitGoalTaskUpdate(e,r,n)}notifyIterationStatus(e,r,n){let o=ar(n??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0)),i=`${r}
126
+
127
+ ${dr(e,o)}`;this.notify(e,i,"goal-task-progress")}setTaskRunningWithSession(e,r){e.sessionId=r.id,e.sessionName=r.name,e.harnessSessionId=r.harnessSessionId,e.route=r.route??e.route,e.status="running",e.waitingForUserReason=void 0,e.updatedAt=Date.now(),this.store.upsert(e)}attachSessionObservers(e,r){if(this.observerDisposers.has(r.id))return;let n=(i,s)=>{(s==="completed"||s==="failed"||s==="killed")&&(this.removeSessionObserver(r.id),this.scheduleTaskEvaluation(e.id,`status:${s}`,r.id))},o=()=>{let i=this.store.get(e.id);i&&(i.sessionId=r.id,i.sessionName=r.name,i.harnessSessionId=r.harnessSessionId,i.route=r.route??i.route,i.updatedAt=Date.now(),i.status==="waiting_for_session"&&(i.status="running"),this.store.upsert(i),this.notifyIterationStatus(i,`\u{1F504} [${i.name}] Coding turn complete`,r),this.scheduleTaskEvaluation(e.id,"turnEnd",r.id))};r.on("statusChange",n),r.on("turnEnd",o),this.observerDisposers.set(r.id,()=>{r.off?.("statusChange",n),r.off?.("turnEnd",o),r.removeListener?.("statusChange",n),r.removeListener?.("turnEnd",o)})}scheduleTaskEvaluation(e,r,n){if(!this.started)return;let o=this.scheduledEvaluations.get(e);if(o){!o.sessionId&&n&&(o.sessionId=n);return}let i={timer:setTimeout(()=>{this.scheduledEvaluations.delete(e),this.evaluateTask(e,r,i.sessionId).catch(s=>{console.warn(`[GoalController] evaluateTask error (${r}): ${$r(s)}`)})},0),sessionId:n};i.timer.unref?.(),this.scheduledEvaluations.set(e,i)}clearScheduledEvaluations(){for(let e of this.scheduledEvaluations.values())clearTimeout(e.timer);this.scheduledEvaluations.clear(),this.dirtyEvaluations.clear(),this.dirtyEvaluationSessionIds.clear()}detachSessionObservers(){for(let e of[...this.observerDisposers.keys()])this.removeSessionObserver(e)}removeSessionObserver(e){let r=this.observerDisposers.get(e);r&&(this.observerDisposers.delete(e),r())}markTaskFailed(e,r){e.status="failed",e.failureReason=no(r,Vd),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u274C [${e.name}] Goal task failed
128
+
129
+ ${e.failureReason}`,"goal-task-failed")}markTaskFailedWaitingForUser(e,r){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${r}`)}markTaskSucceeded(e,r){e.status="succeeded",e.lastVerifierSummary=r,e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u2705 [${e.name}] Goal task succeeded
130
+
131
+ ${r}`,"goal-task-succeeded")}markTaskStopped(e,r){e.status="stopped",e.failureReason=no(r,Vd),e.updatedAt=Date.now(),this.store.upsert(e),this.notify(e,`\u26D4 [${e.name}] Goal task stopped
132
+
133
+ ${e.failureReason}`,"goal-task-stopped")}async handleRunningSession(e,r){if(r.pendingPlanApproval){let s=await bt(this.sessionManager,{session:r.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});s.isError&&this.markTaskFailed(e,s.text);return}if(!r.pendingInputState){this.setTaskRunningWithSession(e,r);return}let n=r.getOutput(30).join(`
134
+ `),o=zf(n);if(!o){this.markTaskFailedWaitingForUser(e,ur(n,24)||"The session is waiting for user input.");return}let i=await bt(this.sessionManager,{session:r.id,message:o,userInitiated:!1});if(i.isError||i.text.includes("Auto-respond limit reached")){this.markTaskFailedWaitingForUser(e,i.text);return}e.status="running",e.waitingForUserReason=void 0,e.updatedAt=Date.now(),this.store.upsert(e)}async resumeAfterIdleTimeout(e,r,n){try{let o=await this.resumeTaskSession(e,n,r);this.setTaskRunningWithSession(e,o),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after idle timeout`,o),this.scheduleTaskEvaluation(e.id,"idle-timeout-resume",o.id)}catch(o){this.markTaskFailed(e,`Failed to resume the goal task after idle timeout: ${$r(o)}`)}}async handleTerminalSession(e,r){if(r.status==="failed"){this.markTaskFailed(e,Zw(r));return}if(r.status==="killed"&&r.killReason==="user"){this.markTaskStopped(e,"Stopped by user.");return}if(r.status==="killed"&&r.killReason==="idle-timeout"){let i=r.getOutput(60).join(`
135
+ `);if(r.pendingPlanApproval){let s=await bt(this.sessionManager,{session:r.id,message:"Approved. Implement the plan.",approve:!0,userInitiated:!1});if(s.isError){this.markTaskFailed(e,s.text);return}let a=this.sessionManager.resolve(r.id);if(!a){this.markTaskFailed(e,"Failed to resolve the resumed goal task session after idle timeout plan approval.");return}this.attachSessionObservers(e,a),this.setTaskRunningWithSession(e,a),this.notifyIterationStatus(e,`\u{1F504} [${e.name}] Goal task resumed after idle timeout`,a),this.scheduleTaskEvaluation(e.id,"idle-timeout-plan-resume",a.id);return}if(r.pendingInputState){let s=zf(i);if(!s){this.markTaskFailed(e,`Goal task was waiting for user input and cannot continue autonomously: ${ur(i,24)||"The goal task hit idle timeout while waiting for user input."}`);return}await this.resumeAfterIdleTimeout(e,r,["The previous session hit idle timeout while waiting for a response.",`Use this response and continue the goal: ${s}`].join(`
136
+
137
+ `));return}await this.resumeAfterIdleTimeout(e,r,Qf(e));return}if(r.status==="killed"&&r.killReason!=="done"){this.markTaskFailed(e,`Underlying session was killed (${r.killReason}).`);return}if(e.loopMode==="ralph"){let i=r.getOutput(200).join(`
138
+ `),s=jf(e.completionPromise);if(Yw(i,s)){if(e.verifierCommands.length===0){this.markTaskSucceeded(e,`Completion promise "${s}" detected in agent output.`);return}let m=await this.runVerifiers(e);if(e.lastVerifierSummary=m.summary,e.updatedAt=Date.now(),m.status==="pass"){this.markTaskSucceeded(e,[`Completion promise "${s}" detected.`,m.summary].join(`
139
+ `));return}if(e.lastVerifierFingerprint===m.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=m.fingerprint,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Goal task emitted completion promise but verifiers still failed before hitting the iteration budget (${e.maxIterations}).`,m.summary].join(`
140
+ `));return}e.iteration+=1;let S=Jw(e,m);try{let y=await this.resumeTaskSession(e,S,r);this.setTaskRunningWithSession(e,y),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Completion claimed but verifiers still failed`),this.scheduleTaskEvaluation(e.id,"ralph-verifier-resume",y.id)}catch(y){this.markTaskFailed(e,`Failed to resume the Ralph goal task after verifier failure: ${$r(y)}`)}return}let d=Gw(i);if(e.lastVerifierFingerprint===d?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=d,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Completion promise "${s}" was not emitted before hitting the iteration budget (${e.maxIterations}).`,"Latest output:",ur(i,20)||"(no output)"].join(`
141
+ `));return}e.iteration+=1;let l=Qw(e,i);try{let m=await this.resumeTaskSession(e,l,r);this.setTaskRunningWithSession(e,m),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Ralph iteration continued`),this.scheduleTaskEvaluation(e.id,"ralph-continue",m.id)}catch(m){this.markTaskFailed(e,`Failed to continue the Ralph goal task: ${$r(m)}`)}return}let n=await this.runVerifiers(e);if(e.lastVerifierSummary=n.summary,e.updatedAt=Date.now(),n.status==="pass"){this.markTaskSucceeded(e,n.summary);return}if(e.lastVerifierFingerprint===n.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=n.fingerprint,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Verifier did not pass before hitting the iteration budget (${e.maxIterations}).`,n.summary].join(`
142
+ `));return}e.iteration+=1;let o=zw(e,n);try{let i=await this.resumeTaskSession(e,o,r);this.setTaskRunningWithSession(e,i),this.notifyIterationStatus(e,`\u{1F501} [${e.name}] Repair iteration started after verifier failure`),this.scheduleTaskEvaluation(e.id,"repair-resume",i.id)}catch(i){this.markTaskFailed(e,`Failed to resume the goal task: ${$r(i)}`)}}async evaluateTask(e,r,n){this.restorePromise&&await this.restorePromise;let o=this.store.get(e);o&&await this.reconcileTask(o,r,n)}async reconcileTask(e,r="manual",n){if(!(e.status==="succeeded"||e.status==="failed"||e.status==="stopped")){if(this.inFlight.has(e.id)){this.dirtyEvaluations.add(e.id),!this.dirtyEvaluationSessionIds.get(e.id)&&n?this.dirtyEvaluationSessionIds.set(e.id,n):this.dirtyEvaluationSessionIds.has(e.id)||this.dirtyEvaluationSessionIds.set(e.id,n);return}this.inFlight.add(e.id);try{if(n&&e.sessionId&&e.sessionId!==n){let i=this.sessionManager.resolve(n);if(i&&(i.status==="completed"||i.status==="failed"||i.status==="killed"))return}let o=n?this.sessionManager.resolve(n)??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0):e.sessionId?this.sessionManager.resolve(e.sessionId):void 0;if(e.status==="waiting_for_user"){this.markTaskFailed(e,"Goal task was waiting for user input and cannot continue autonomously");return}if(Gf(e)){this.markTaskFailed(e,Ji());return}if(!o){this.markTaskFailed(e,"Underlying session could not be found.");return}if(e.sessionName=o.name,e.harnessSessionId=o.harnessSessionId,e.route=o.route??e.route,e.updatedAt=Date.now(),this.store.upsert(e),o.status==="starting"||o.status==="running"){await this.handleRunningSession(e,o);return}await this.handleTerminalSession(e,o)}finally{if(this.inFlight.delete(e.id),this.dirtyEvaluations.has(e.id)){this.dirtyEvaluations.delete(e.id);let o=this.dirtyEvaluationSessionIds.get(e.id);this.dirtyEvaluationSessionIds.delete(e.id),this.scheduleTaskEvaluation(e.id,`${r}:dirty`,o)}}}}};Re();import{existsSync as tI,realpathSync as rI}from"fs";import{resolve as nI}from"path";function Zf(t){if(!t)return;let e=nI(t);try{if(tI(e))return rI.native(e)}catch{}return e}function Xi(t,e){return!t||!e?!1:Zf(t)===Zf(e)}ke();Re();import{existsSync as oI}from"fs";ke();ut();function eg(t){return t instanceof Error?t.message:String(t)}function iI(t){let e=t.worktreeStrategy??_.defaultWorktreeStrategy;return!!e&&e!=="off"&&Rd(gi({harnessName:t.harness??Pe(),backendRef:t.backendRef}))}function sI(t,e,r,n){let o=["","You are working in a git worktree.",`Worktree path: ${r}`,`Branch: ${n}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${r}.`,`Do NOT edit files directly in ${e} (the original workspace).`,`If your task references files by absolute path under ${e}, rewrite those`,"paths relative to your current working directory. For example:",` "${e}/src/file.py" \u2192 use relative path "src/file.py"`,"","Commit all your file changes to this branch before finishing.","Use `git add` and `git commit`. Do NOT run `git checkout`, `git switch`, or `git reset --hard` as these will detach or corrupt the worktree HEAD.","","When making changes, please note:","- Do NOT commit planning documents, investigation notes, or analysis artifacts to this branch","- Only commit actual code, configuration, tests, and documentation changes that were explicitly requested as part of the task"].join(`
143
+ `);return(t??"")+o}function aI(t,e){let r=t.resumeSessionId??t.resumeWorktreeFrom;if(!r)return{};let n=e(r);if(!n)return{};let o=(()=>{if(n.workdir&&n.workdir!==n.worktreePath)return n.workdir;if(n.worktreePath){let s=xi(n.worktreePath);return n.workdir&&s&&Xi(n.workdir,s)?n.workdir:s??n.workdir}return n.workdir})();if(!t.worktreeStrategy&&n.worktreeStrategy&&(t.worktreeStrategy=n.worktreeStrategy),!t.planApproval&&n.planApproval&&(t.planApproval=n.planApproval),!n.worktreePath)return{};if(!n.worktreeBranch)throw new Error(`Cannot resume session "${r}": persisted worktree metadata is missing worktreeBranch.`);let i=Om(gi({persistedHarness:n.harness,backendRef:n.backendRef}))&&!!n.backendRef?.worktreePath;if(oI(n.worktreePath))return console.info(`[SessionManager] Resuming with existing worktree: ${n.worktreePath}`),{actualWorkdir:n.worktreePath,originalWorkdir:o??n.worktreePath,worktreePath:n.worktreePath,worktreeBranchName:n.worktreeBranch};if(!o)return console.warn(`[SessionManager] Worktree ${n.worktreePath} no longer exists and cannot be recreated, using original workdir`),{clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom};if(i)return console.info(`[SessionManager] Native Codex worktree ${n.worktreePath} is missing; resuming from original workdir and letting the backend restore thread state.`),{actualWorkdir:o,originalWorkdir:o,worktreeBranchName:n.worktreeBranch,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom};try{Ti(o);let s=$d(o,n.worktreeBranch.replace(/^agent\//,""));return console.info(`[SessionManager] Recreated worktree from branch ${n.worktreeBranch}: ${s}`),{actualWorkdir:s,originalWorkdir:o,worktreePath:s,worktreeBranchName:n.worktreeBranch}}catch(s){return console.warn(`[SessionManager] Failed to recreate worktree for resume: ${eg(s)}, using original workdir`),{actualWorkdir:o,originalWorkdir:o,clearedResumeSessionId:!!t.resumeSessionId,clearedResumeWorktreeFrom:!!t.resumeWorktreeFrom}}}function tg(t,e,r){let{actualWorkdir:n,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}=aI(t,r);a&&(t.resumeSessionId=void 0),d&&(t.resumeWorktreeFrom=void 0),n??=t.workdir,o??=t.workdir;let l=!!(t.resumeSessionId??t.resumeWorktreeFrom),m=t.worktreeStrategy??_.defaultWorktreeStrategy;m&&(t.worktreeStrategy=m);let S=iI(t),y=!t.resumeSessionId&&!i&&m&&m!=="off"&&!S;if(S&&!Cd(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${m}" requires a git worktree, but "${o}" is not a git repository.`);if(y&&Cd(o)){if(!Ym(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=$d(o,e),n=i,s=Ri(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);console.log(`[SessionManager] Created worktree at ${i}`)}catch(f){throw new Error(`Cannot launch session "${e}": worktree creation failed: ${eg(f)}`)}}else if(y)throw new Error(`Cannot launch session "${e}": worktree strategy "${m}" requires a git worktree, but "${o}" is not a git repository.`);return l&&i&&(n=i),{actualWorkdir:n,originalWorkdir:o,effectiveSystemPrompt:i&&s?sI(t.systemPrompt,o,i,s):t.systemPrompt,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}}var Zi=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,r){return tg(e,r,this.getPersistedSession)}hydrateSpawnedSession(e,r,n){n.worktreeStrategy&&n.worktreeStrategy!=="off"&&(e.originalWorkdir=r.originalWorkdir),r.worktreePath&&(e.worktreePath=r.worktreePath,e.worktreeBranch=r.worktreeBranchName,e.worktreeState="provisioned"),n.worktreePrTargetRepo&&(e.worktreePrTargetRepo=n.worktreePrTargetRepo)}};ke();var es=class{constructor(e){this.deps=e}deps;applySessionPatch(e,r){let n=this.deps.store.getPersistedSession(e);n&&(Object.assign(n,r),this.deps.store.assertPersistedEntry(n));let o=this.findActiveSessionForRef(e,n);return o&&this.applyPatchToActiveSession(o,r),!n&&!o?!1:(n&&this.deps.store.saveIndex(),!0)}matchesExistingSession(e,r){if(!r)return!1;let n=$(e),o=$(r);return!!(r.sessionId&&e.id===r.sessionId||o&&o===n||r?.harnessSessionId&&e.harnessSessionId===r.harnessSessionId||r?.name&&e.name===r.name)}findActiveSessionForRef(e,r){let n=this.deps.resolveSession(e);if(n)return n;for(let o of this.deps.sessions.values())if(re(o)===e||$(o)===e||o.harnessSessionId===e||this.matchesExistingSession(o,r))return o}applyPatchToActiveSession(e,r){this.applyControlStatePatch(e,r),this.applySessionMetadataPatch(e,r),this.applyWorktreeMetadataPatch(e,r)}applyControlStatePatch(e,r){let n={lifecycle:r.lifecycle,approvalState:r.approvalState,worktreeState:r.worktreeState,runtimeState:r.runtimeState,deliveryState:r.deliveryState,pendingPlanApproval:r.pendingPlanApproval,planApprovalContext:r.planApprovalContext,planDecisionVersion:r.planDecisionVersion,actionablePlanDecisionVersion:r.actionablePlanDecisionVersion,canonicalPlanPromptVersion:r.canonicalPlanPromptVersion,approvalPromptRequiredVersion:r.approvalPromptRequiredVersion,approvalPromptVersion:r.approvalPromptVersion,approvalPromptStatus:r.approvalPromptStatus,approvalPromptTransport:r.approvalPromptTransport,approvalPromptMessageKind:r.approvalPromptMessageKind,approvalPromptLastAttemptAt:r.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:r.approvalPromptDeliveredAt,approvalPromptFailedAt:r.approvalPromptFailedAt,pendingWorktreeDecisionSince:r.pendingWorktreeDecisionSince};if(typeof e.applyControlPatch=="function"){e.applyControlPatch(n);return}this.assignIfDefined(e,"lifecycle",r.lifecycle),this.assignIfDefined(e,"approvalState",r.approvalState),this.assignIfDefined(e,"worktreeState",r.worktreeState),this.assignIfDefined(e,"runtimeState",r.runtimeState),this.assignIfDefined(e,"deliveryState",r.deliveryState),this.assignIfDefined(e,"pendingPlanApproval",r.pendingPlanApproval),this.assignIfDefined(e,"planApprovalContext",r.planApprovalContext),this.assignIfDefined(e,"planDecisionVersion",r.planDecisionVersion),this.assignIfDefined(e,"actionablePlanDecisionVersion",r.actionablePlanDecisionVersion),this.assignIfDefined(e,"canonicalPlanPromptVersion",r.canonicalPlanPromptVersion),this.assignIfDefined(e,"approvalPromptRequiredVersion",r.approvalPromptRequiredVersion),this.assignIfDefined(e,"approvalPromptVersion",r.approvalPromptVersion),this.assignIfDefined(e,"approvalPromptStatus",r.approvalPromptStatus),this.assignIfDefined(e,"approvalPromptTransport",r.approvalPromptTransport),this.assignIfDefined(e,"approvalPromptMessageKind",r.approvalPromptMessageKind),this.assignIfDefined(e,"approvalPromptLastAttemptAt",r.approvalPromptLastAttemptAt),this.assignIfDefined(e,"approvalPromptDeliveredAt",r.approvalPromptDeliveredAt),this.assignIfDefined(e,"approvalPromptFailedAt",r.approvalPromptFailedAt)}applySessionMetadataPatch(e,r){this.assignIfDefined(e,"approvalRationale",r.approvalRationale)}applyWorktreeMetadataPatch(e,r){this.assignIfDefined(e,"worktreePath",r.worktreePath),this.assignIfDefined(e,"worktreeBranch",r.worktreeBranch),this.assignIfDefined(e,"worktreePrUrl",r.worktreePrUrl),this.assignIfDefined(e,"worktreePrNumber",r.worktreePrNumber),this.assignIfDefined(e,"worktreeMerged",r.worktreeMerged),this.assignIfDefined(e,"worktreeMergedAt",r.worktreeMergedAt),this.assignIfDefined(e,"worktreeDisposition",r.worktreeDisposition),this.assignIfDefined(e,"worktreePrTargetRepo",r.worktreePrTargetRepo),this.assignIfDefined(e,"worktreePushRemote",r.worktreePushRemote),this.assignIfDefined(e,"worktreeLifecycle",r.worktreeLifecycle),"autoMergeParentSessionId"in r&&(e.autoMergeParentSessionId=r.autoMergeParentSessionId),"autoMergeConflictResolutionAttemptCount"in r&&(e.autoMergeConflictResolutionAttemptCount=r.autoMergeConflictResolutionAttemptCount),"autoMergeResolverSessionId"in r&&(e.autoMergeResolverSessionId=r.autoMergeResolverSessionId)}assignIfDefined(e,r,n){n!==void 0&&(e[r]=n)}};ke();var dI=new Set(["starting","running"]),ts=class{constructor(e,r){this.sessions=e;this.store=r}sessions;store;resolveActive(e){let r=this.sessions.get(e);return r||(this.findPreferredMatch(e,n=>n.name===e)??this.findPreferredMatch(e,n=>$(n)===e)??this.findPreferredMatch(e,n=>n.harnessSessionId===e))}getPersistedSession(e){return this.store.getPersistedSession(e)}resolveBackendConversationId(e){let r=this.resolveActive(e);return this.store.resolveBackendConversationId(e,r?$(r)??r.harnessSessionId:void 0)}findPreferredMatch(e,r){let n,o;for(let i of this.sessions.values())r(i,e)&&((!o||i.startedAt>o.startedAt)&&(o=i),dI.has(i.status)&&(!n||i.startedAt>n.startedAt)&&(n=i));return n??o}};ke();ke();ut();var rs=class{constructor(e){this.deps=e}deps;async plan(e){let r=re(e)??e.harnessSessionId;if(this.deps.isAlreadyMerged(r))return console.info(`[SessionManager] handleWorktreeStrategy: session "${e.name}" already merged \u2014 skipping strategy handling`),{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};if(e.status!=="completed")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};if(!this.deps.shouldRunWorktreeStrategy(e))return console.info(`[SessionManager] handleWorktreeStrategy: skipping \u2014 session "${e.name}" is in phase "${e.phase}"`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let n=e.worktreeStrategy;if(!n||n==="off"||n==="manual")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let o=e.worktreePath,i=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,o),s=e.worktreeBranch;if(!i)return{kind:"notify",label:"worktree-missing-repo-dir",message:`\u26A0\uFE0F [${e.name}] Cannot determine the original repo for worktree ${o}. Manual inspection is required.`};if(!s)return{kind:"notify",label:"worktree-no-branch-name",message:`\u26A0\uFE0F [${e.name}] Cannot determine branch name for worktree ${o}. The worktree may have been removed or is in detached HEAD state. Manual cleanup may be needed.`};let a=e.worktreeBaseBranch??sr(i),d=this.deps.getWorktreeCompletionState(i,o,s,a);if(d==="no-change")return{kind:"no-change",repoDir:i,worktreePath:o,nativeBackendWorktree:Ne(e)};if(d==="base-advanced")return{kind:"notify",label:"worktree-no-commits-ahead",message:`\u26A0\uFE0F [${e.name}] Auto-merge: branch '${s}' has no commits ahead of '${a}', but '${a}' has new commits \u2014 commits likely landed outside the worktree branch. Verify that commits were not made directly to '${a}' instead of the worktree branch. Worktree: ${o}`};if(d==="dirty-uncommitted")return{kind:"notify",label:"worktree-dirty-uncommitted",message:`\u26A0\uFE0F [${e.name}] Session completed with uncommitted changes. The branch has no commits ahead of '${a}' but there are modified tracked files in the worktree. Check: ${o}`};let l=Tr(i,s,a);return l?{kind:"decision",strategy:n,repoDir:i,worktreePath:o,branchName:s,baseBranch:a,diffSummary:l,sessionRef:r??void 0}:(console.warn(`[SessionManager] Failed to get diff summary for ${s}, skipping merge-back`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}})}};function jd(t,e){return{...e,baseBranch:e.baseBranch??t.worktreeBaseBranch,targetRepo:e.targetRepo??t.worktreePrTargetRepo,pushRemote:e.pushRemote??t.worktreePushRemote}}function ns(t,e={}){let r=e.updatedAt??new Date().toISOString(),n={pendingWorktreeDecisionSince:e.pendingSince??r,lastWorktreeReminderAt:void 0,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision",worktreeLifecycle:jd(t,{state:"pending_decision",updatedAt:r,notes:e.notes})};return e.clearResolverSessionId&&(n.autoMergeResolverSessionId=void 0),n}function rg(t,e,r,n={}){let o=n.updatedAt??new Date().toISOString();return{autoMergeConflictResolutionAttemptCount:r,autoMergeResolverSessionId:e,pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,lifecycle:"terminal",worktreeState:"merge_conflict_resolving",worktreeLifecycle:jd(t,{state:"merge_conflict_resolving",updatedAt:o,notes:n.notes})}}function ng(t,e={}){let r=e.updatedAt??new Date().toISOString(),n=e.resolvedAt??r,o={worktreeMerged:!0,worktreeMergedAt:e.mergedAt??n,lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeLifecycle:jd(t,{state:"merged",updatedAt:r,resolvedAt:n,resolutionSource:e.resolutionSource??"agent_merge"})};return e.clearResolverSessionId&&(o.autoMergeResolverSessionId=void 0),o}ut();var os=class{constructor(e){this.deps=e;this.actions=new rs({shouldRunWorktreeStrategy:e.shouldRunWorktreeStrategy,isAlreadyMerged:e.isAlreadyMerged,resolveWorktreeRepoDir:e.resolveWorktreeRepoDir,getWorktreeCompletionState:e.getWorktreeCompletionState})}deps;actions;buildConflictResolverPrompt(e){return["Resolve the git rebase conflict for the auto-merge worktree and finish the rebase cleanly.","",`Original session: ${e.session.name} [${e.session.id}]`,`Repository root: ${e.repoDir}`,`Conflicted worktree: ${e.worktreePath}`,`Branch: ${e.branchName}`,`Base branch: ${e.baseBranch}`,"","Requirements:","- Work only inside the conflicted worktree.","- Inspect the current rebase state and resolve only the necessary conflict hunks.","- Make only minimal follow-up edits needed to keep the rebased branch correct.","- Continue the rebase until it completes successfully.","- Run relevant local verification before you finish.","- Do not broaden scope or start unrelated refactors.",`- Stop only when the branch is cleanly rebased onto ${e.baseBranch}.`,e.mergeError?"":void 0,e.mergeError?"Rebase failure details:":void 0,e.mergeError].filter(r=>typeof r=="string").join(`
144
+ `)}notifyAutoMergeConflictEscalation(e,r,n){this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-escalated",userMessage:[`\u26A0\uFE0F [${e.name}] Auto-merge could not finish after one conflict-resolution attempt.`,`Branch \`${r}\` was preserved for manual follow-up.`,"",n].join(`
145
+ `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}updatePersistedSessionFor(e,r){for(let n of et(e))this.deps.updatePersistedSession(n,r)}markPendingDecision(e,r={}){this.updatePersistedSessionFor(e,ns(e,r))}markAutoMergeConflictResolving(e,r,n){this.updatePersistedSessionFor(e,rg(e,r,n,{notes:[`resolver_session:${r}`]}))}markMerged(e){this.updatePersistedSessionFor(e,ng(e,{clearResolverSessionId:!0}))}async handleWorktreeStrategy(e){let r=await this.actions.plan(e);return r.kind==="skip"?r.result:r.kind==="notify"?(this.deps.dispatchSessionNotification(e,{label:r.label,userMessage:r.message}),{notificationSent:!0,worktreeRemoved:!1}):r.kind==="no-change"?this.handleNoChange(e,r.repoDir,r.worktreePath,r.nativeBackendWorktree):r.strategy==="ask"?this.handleAskStrategy(e,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="delegate"?this.handleDelegateStrategy(e,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="auto-merge"?(await this.handleAutoMergeStrategy(e,r.repoDir,r.worktreePath,r.branchName,r.baseBranch,r.diffSummary,r.sessionRef),{notificationSent:!0,worktreeRemoved:!1}):r.strategy==="auto-pr"?this.handleAutoPrStrategy(e,r.baseBranch):{notificationSent:!1,worktreeRemoved:!1}}async handleNoChange(e,r,n,o=Ne(e)){let i=o?!0:tt(r,n);return i?(e.worktreePath=void 0,this.updatePersistedSessionFor(e,{worktreePath:void 0,worktreeDisposition:"no-change-cleaned",worktreeState:"none",worktreeLifecycle:{state:"no_change",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"strategy_no_change",baseBranch:e.worktreeBaseBranch,targetRepo:e.worktreePrTargetRepo,pushRemote:e.worktreePushRemote}}),this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildNoChangeNotification({session:e,nativeBackendWorktree:o,cleanupSucceeded:!0,worktreePath:n,preview:this.deps.getOutputPreview(e),originThreadLine:this.deps.originThreadLine(e)}))):this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildNoChangeNotification({session:e,nativeBackendWorktree:o,cleanupSucceeded:!1,worktreePath:n,preview:this.deps.getOutputPreview(e),originThreadLine:this.deps.originThreadLine(e)})),{notificationSent:!0,worktreeRemoved:i}}handleAskStrategy(e,r,n,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildAskNotification({session:e,branchName:r,baseBranch:n,diffSummary:o,buttons:this.deps.getWorktreeDecisionButtons(e.id)})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleDelegateStrategy(e,r,n,o){return this.deps.dispatchSessionNotification(e,this.deps.worktreeMessages.buildDelegateNotification({session:e,branchName:r,baseBranch:n,diffSummary:o})),this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}handleAutoMergeSuccess(e,r,n,o,i,s){$t(r,n),this.markMerged(e);let d=Mr({kind:"merge",branch:n,base:o,filesChanged:i.filesChanged,insertions:i.insertions,deletions:i.deletions});s.stashPopConflict?d+=`
146
+ \u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${s.stashRef??"stash@{0}"}\` in ${r} to review stashed changes.`:s.stashed&&(d+=`
147
+ (Pre-existing changes on ${o} were auto-stashed and restored.)`),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-success",userMessage:d})}async handleInitialAutoMergeConflict(e,r,n,o,i,s){let a=e.autoMergeConflictResolutionAttemptCount??0;if(a>=1){this.markPendingDecision(e,{notes:["auto_merge_conflict_retry_exhausted"],clearResolverSessionId:!0}),this.notifyAutoMergeConflictEscalation(e,o,`The rebased branch still conflicts with \`${i}\`. Open a PR or resolve manually in ${n}.`);return}let d=this.buildConflictResolverPrompt({session:e,repoDir:r,worktreePath:n,branchName:o,baseBranch:i,mergeError:s});try{let l=await this.deps.spawnConflictResolver({session:e,repoDir:r,worktreePath:n,branchName:o,baseBranch:i,prompt:d});this.markAutoMergeConflictResolving(e,l.id,a+1),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-resolving",userMessage:`\u26A0\uFE0F [${e.name}] Auto-merge hit a rebase conflict. Started resolver session ${l.name} and will retry automatically if it succeeds.`})}catch(l){this.markPendingDecision(e,{notes:["auto_merge_conflict_resolver_spawn_failed"]}),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-spawn-failed",userMessage:`\u274C [${e.name}] Auto-merge hit a rebase conflict and failed to start the resolver: ${l instanceof Error?l.message:String(l)}`,buttons:[[this.deps.makeOpenPrButton(e.id)]]})}}handleAutoMergeRetryFailure(e,r,n,o){this.markPendingDecision(e,{notes:["auto_merge_conflict_retry_failed"],clearResolverSessionId:!0}),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",userMessage:[o,"","Auto-merge retry did not complete after conflict resolution.",`Branch \`${r}\` was preserved for manual follow-up in ${n}.`].join(`
148
+ `),buttons:[[this.deps.makeOpenPrButton(e.id)]]})}async handleAutoMergeStrategy(e,r,n,o,i,s,a=re(e)??e.harnessSessionId){this.deps.isAlreadyMerged(a)||e.autoMergeResolverSessionId||await this.deps.enqueueMerge(r,async()=>{if(this.deps.isAlreadyMerged(a))return;let d=this.deps.mergeBranch(r,o,i,"merge",n);if(d.success){this.handleAutoMergeSuccess(e,r,o,i,s,d);return}if(d.rebaseConflict){await this.handleInitialAutoMergeConflict(e,r,n,o,i,d.error);return}let l=d.dirtyError?`\u274C [${e.name}] Merge blocked: ${d.error}`:`\u274C [${e.name}] Merge failed: ${d.error??"unknown error"}`;if(e.worktreeState==="merge_conflict_resolving"||e.worktreeLifecycle?.state==="merge_conflict_resolving"){this.handleAutoMergeRetryFailure(e,o,n,l);return}this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",userMessage:l})},()=>{this.deps.dispatchSessionNotification(e,{label:"worktree-merge-queued",userMessage:`\u{1F550} [${e.name}] Merge queued \u2014 another merge for this repo is in progress. Will notify when complete.`})})}async handleAutoPrStrategy(e,r){return this.updatePersistedSessionFor(e,{lifecycle:"terminal",worktreeState:"pr_in_progress"}),(await this.deps.runAutoPr(e,r)).success||this.markPendingDecision(e),{notificationSent:!0,worktreeRemoved:!1}}};import{existsSync as LI,writeFileSync as WI}from"fs";Zr();import{randomUUID as lI}from"crypto";function uI(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"}var is=class{constructor(e,r){this.onChange=e;this.retentionMs=r}onChange;retentionMs;tokens=new Map;afterChange;replaceAll(e){this.tokens.clear();for(let r of e)this.tokens.set(r.id,r)}clear(){this.tokens.clear(),this.notifyChanged()}listForPersistence(){return[...this.tokens.values()]}createActionToken(e,r,n={}){let o={id:lI(),sessionId:e,kind:r,createdAt:Date.now(),...n};return this.tokens.set(o.id,o),this.notifyChanged(),o}getActionToken(e){let r=this.tokens.get(e);if(r){if(r.expiresAt!=null&&r.expiresAt<=Date.now()){this.tokens.delete(e),this.notifyChanged();return}return r}}consumeActionToken(e){let r=this.getActionToken(e);if(!(!r||r.consumedAt!=null))return r.consumedAt=Date.now(),this.notifyChanged(),r}deleteActionTokensForSession(e){let r=!1;for(let[n,o]of this.tokens)o.sessionId===e&&(this.tokens.delete(n),r=!0);r&&this.notifyChanged()}deletePlanDecisionTokensForSession(e,r){let n=!1;for(let[o,i]of this.tokens)i.sessionId!==e||!uI(i.kind)||r!=null&&i.planDecisionVersion===r||(this.tokens.delete(o),n=!0);n&&this.notifyChanged()}purgeExpiredActionTokens(e=Date.now()){let r=!1;for(let[n,o]of this.tokens){let i=o.expiresAt!=null&&o.expiresAt<=e,s=o.consumedAt!=null&&e-o.consumedAt>this.retentionMs;(i||s)&&(this.tokens.delete(n),r=!0)}r&&this.notifyChanged()}nextExpiryAt(){let e;for(let r of this.tokens.values()){let n=[r.expiresAt,r.consumedAt!=null?r.consumedAt+this.retentionMs:void 0].filter(o=>o!=null&&Number.isFinite(o));for(let o of n)(e==null||o<e)&&(e=o)}return e}setAfterChangeListener(e){this.afterChange=e}notifyChanged(){this.onChange(),this.afterChange?.()}};ke();ke();var ss=class{constructor(e){this.indexes=e}indexes;hasRecordedSession(e){return this.indexes.idIndex.has(e)}getLatestPersistedByName(e){let r,n=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=0;for(let a of this.indexes.persisted.values()){if(a.name!==e){s++;continue}let d=a.createdAt??Number.NEGATIVE_INFINITY,l=a.completedAt??Number.NEGATIVE_INFINITY;(d>n||d===n&&l>o||d===n&&l===o&&s>i)&&(r=a,n=d,o=l,i=s),s++}return r}resolveBackendConversationId(e,r){if(r)return r;let n=this.indexes.idIndex.get(e);if(n){let s=this.indexes.persisted.get(n);return(s?$(s):void 0)??n}let o=this.getLatestPersistedByName(e);if(o)return $(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(e);if(i){let s=this.indexes.persisted.get(i);return(s?$(s):void 0)??i}if(this.indexes.persisted.has(e)){let s=this.indexes.persisted.get(e);return s?$(s)??e:e}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))return e}resolveHarnessSessionId(e,r){return this.resolveBackendConversationId(e,r)}getPersistedSession(e){let r=this.indexes.idIndex.get(e);if(r)return this.indexes.persisted.get(r);let n=this.getLatestPersistedByName(e);if(n)return n;let o=this.indexes.backendIdIndex.get(e);return o?this.indexes.persisted.get(o):this.indexes.persisted.get(e)}listPersistedSessions(){return[...this.indexes.persisted.values()].sort((e,r)=>(r.completedAt??0)-(e.completedAt??0))}};import{existsSync as EI,mkdirSync as OI,readFileSync as DI,readdirSync as Hd,renameSync as ug,statSync as pg,unlinkSync as cg,writeFileSync as mg}from"fs";import{tmpdir as zd}from"os";import{dirname as NI,join as us}from"path";import{homedir as pI}from"node:os";import{join as cI}from"node:path";function og(t){let e=t.OPENCLAW_HOME?.trim();if(e)return e;let r=t.HOME?.trim()||pI();return cI(r,".openclaw")}Zr();var as=6,mI=new Set(["running","completed","failed","killed"]);function oo(t){return!!t&&typeof t=="object"}function ln(t,e=""){return typeof t=="string"&&t.trim().length>0?t:e}function I(t){return typeof t=="string"&&t.trim().length>0?t:void 0}function je(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function fI(t){return t==="low"||t==="medium"||t==="high"?t:void 0}function ig(t){return t==="default"||t==="plan"||t==="bypassPermissions"?t:void 0}function gI(t){return t==="never"||t==="on-request"?"never":void 0}function hI(t){return t==="approve"||t==="ask"||t==="delegate"?t:void 0}function SI(t){if(t==="plan-mode"||t==="codex-first-turn-plan"||t==="soft-plan")return"plan-mode"}function yI(t){return t==="user"||t==="idle-timeout"||t==="startup-timeout"||t==="shutdown"||t==="done"||t==="unknown"?t:void 0}function sg(t){return t==="starting"||t==="active"||t==="awaiting_plan_decision"||t==="awaiting_user_input"||t==="awaiting_worktree_decision"||t==="suspended"||t==="terminal"?t:void 0}function kI(t){return t==="not_required"||t==="pending"||t==="approved"||t==="changes_requested"||t==="rejected"?t:void 0}function vI(t){return t==="none"||t==="provisioned"||t==="pending_decision"||t==="merge_conflict_resolving"||t==="merge_in_progress"||t==="pr_in_progress"||t==="merged"||t==="released"||t==="pr_open"||t==="dismissed"||t==="cleanup_failed"?t:void 0}function PI(t){return t==="none"||t==="provisioned"||t==="pending_decision"||t==="merge_conflict_resolving"||t==="pr_open"||t==="merged"||t==="released"||t==="dismissed"||t==="no_change"||t==="cleanup_failed"?t:void 0}function wI(t){return t==="live"||t==="stopped"?t:void 0}function II(t){return t==="not_sent"||t==="sending"||t==="delivered"||t==="fallback_delivered"||t==="failed"?t:void 0}function bI(t){return t==="none"||t==="direct-telegram"||t==="wake-only"?t:void 0}function xI(t){return t==="none"||t==="canonical_buttons"||t==="explicit_fallback_text"?t:void 0}function AI(t){return t==="idle"||t==="notifying"||t==="wake_pending"||t==="failed"?t:void 0}function RI(t){return t==="awaiting_plan_output"||t==="awaiting_approval"||t==="approved_then_implemented"||t==="implemented_without_required_approval"||t==="not_plan_gated"?t:void 0}function TI(t){return t==="plan-approve"||t==="plan-request-changes"||t==="plan-reject"||t==="monitor-start-plan"||t==="monitor-dismiss"||t==="worktree-merge"||t==="worktree-create-pr"||t==="worktree-update-pr"||t==="worktree-view-pr"||t==="worktree-decide-later"||t==="worktree-dismiss"||t==="session-resume"||t==="session-restart"||t==="view-output"||t==="question-answer"?t:void 0}function ag(t){if(!oo(t))return;let e=I(t.provider),r=I(t.accountId),n=I(t.target),o=I(t.threadId),i=I(t.sessionKey);if(!(!e||!n))return{provider:e,accountId:r,target:n,threadId:o,sessionKey:i}}function MI(t,e,r){if(oo(t)){let n=I(t.kind),o=I(t.conversationId);if(o&&(n==="claude-code"||n==="codex-app-server"))return{kind:n,conversationId:o,runId:I(t.runId),worktreeId:I(t.worktreeId),worktreePath:I(t.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:r}}function CI(t){if(!oo(t))return;let e=PI(t.state),r=I(t.updatedAt);if(!e||!r)return;let n=I(t.resolutionSource);return{state:e,updatedAt:r,resolvedAt:I(t.resolvedAt),resolutionSource:n==="agent_merge"||n==="agent_pr"||n==="strategy_no_change"||n==="lifecycle_resolver"||n==="dismiss"||n==="maintenance"?n:void 0,baseBranch:I(t.baseBranch),targetRepo:I(t.targetRepo),pushRemote:I(t.pushRemote),notes:Array.isArray(t.notes)?t.notes.filter(o=>typeof o=="string"&&o.length>0):void 0}}function _I(t){let e=new Date(0).toISOString(),r=I(t.worktreeMergedAt)??I(t.worktreeDismissedAt)??I(t.pendingWorktreeDecisionSince)??e;if(t.worktreeMerged===!0)return{state:"merged",updatedAt:r,resolvedAt:I(t.worktreeMergedAt)??r,resolutionSource:"agent_merge",baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:r,resolvedAt:I(t.worktreeDismissedAt)??r,resolutionSource:"dismiss",baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.worktreeDisposition==="no-change-cleaned")return{state:"no_change",updatedAt:r,resolvedAt:r,resolutionSource:"strategy_no_change",baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.worktreeDisposition==="pr-opened"||t.worktreeState==="pr_open")return{state:"pr_open",updatedAt:r,baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:r,baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(t.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:r,baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)};if(I(t.worktreePath)||I(t.worktreeBranch))return{state:"provisioned",updatedAt:r,baseBranch:I(t.worktreeBaseBranch),targetRepo:I(t.worktreePrTargetRepo),pushRemote:I(t.worktreePushRemote)}}function $I(t){if(typeof t=="string"&&mI.has(t))return t==="running"?"killed":t}function dg(t){if(!oo(t))return;let e=ln(t.harnessSessionId);if(!e)return;let r=$I(t.status);if(!r)return;let n=t.status==="running",o=I(t.worktreePath),i=I(t.worktreeBranch),s=I(t.originChannel),a=typeof t.originThreadId=="string"||typeof t.originThreadId=="number"?t.originThreadId:void 0,d=I(t.originSessionKey),l=ag(t.route);if(!l)return;let m=Xr({route:l,originChannel:s,originThreadId:a,originSessionKey:d});if(!m||o&&!i)return;let S=I(t.harness),y=MI(t.backendRef,S,e),f=CI(t.worktreeLifecycle)??_I(t);return{sessionId:I(t.sessionId),harnessSessionId:e,backendRef:y,name:ln(t.name,e),prompt:ln(t.prompt),workdir:ln(t.workdir,"(unknown)"),model:I(t.model),reasoningEffort:fI(t.reasoningEffort),createdAt:je(t.createdAt),completedAt:je(t.completedAt),status:r,lifecycle:n?sg(t.lifecycle)??"suspended":sg(t.lifecycle),approvalState:kI(t.approvalState),worktreeState:vI(t.worktreeState),runtimeState:n?"stopped":wI(t.runtimeState),deliveryState:AI(t.deliveryState),completionWakeIssuedAt:I(t.completionWakeIssuedAt),completionWakeSucceededAt:I(t.completionWakeSucceededAt),completionWakeFailedAt:I(t.completionWakeFailedAt),completionWakeSummaryRequired:t.completionWakeSummaryRequired===!0?!0:void 0,killReason:yI(t.killReason),costUsd:typeof t.costUsd=="number"&&Number.isFinite(t.costUsd)?t.costUsd:0,originAgentId:I(t.originAgentId),originChannel:s,originThreadId:a,originSessionKey:d,route:m,outputPath:I(t.outputPath),harness:S,requestedPermissionMode:ig(t.requestedPermissionMode),currentPermissionMode:ig(t.currentPermissionMode),approvalExecutionState:RI(t.approvalExecutionState),approvalRationale:I(t.approvalRationale),planModeApproved:t.planModeApproved===!0,pendingPlanApproval:t.pendingPlanApproval===!0,planApprovalContext:SI(t.planApprovalContext),planDecisionVersion:je(t.planDecisionVersion),actionablePlanDecisionVersion:je(t.actionablePlanDecisionVersion),canonicalPlanPromptVersion:je(t.canonicalPlanPromptVersion),approvalPromptRequiredVersion:je(t.approvalPromptRequiredVersion),approvalPromptVersion:je(t.approvalPromptVersion),approvalPromptStatus:II(t.approvalPromptStatus),approvalPromptTransport:bI(t.approvalPromptTransport),approvalPromptMessageKind:xI(t.approvalPromptMessageKind),approvalPromptLastAttemptAt:I(t.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:I(t.approvalPromptDeliveredAt),approvalPromptFailedAt:I(t.approvalPromptFailedAt),planApproval:hI(t.planApproval),codexApprovalPolicy:gI(t.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:t.worktreeStrategy==="off"||t.worktreeStrategy==="manual"||t.worktreeStrategy==="ask"||t.worktreeStrategy==="delegate"||t.worktreeStrategy==="auto-merge"||t.worktreeStrategy==="auto-pr"?t.worktreeStrategy:void 0,worktreeMerged:typeof t.worktreeMerged=="boolean"?t.worktreeMerged:void 0,worktreeMergedAt:I(t.worktreeMergedAt),worktreePrUrl:I(t.worktreePrUrl),worktreePrNumber:je(t.worktreePrNumber),pendingWorktreeDecisionSince:I(t.pendingWorktreeDecisionSince),lastWorktreeReminderAt:I(t.lastWorktreeReminderAt),worktreeBaseBranch:I(t.worktreeBaseBranch),worktreePrTargetRepo:I(t.worktreePrTargetRepo),autoMergeParentSessionId:I(t.autoMergeParentSessionId),autoMergeConflictResolutionAttemptCount:je(t.autoMergeConflictResolutionAttemptCount),autoMergeResolverSessionId:I(t.autoMergeResolverSessionId),worktreePushRemote:I(t.worktreePushRemote),worktreeDecisionSnoozedUntil:I(t.worktreeDecisionSnoozedUntil),worktreeDisposition:t.worktreeDisposition==="active"||t.worktreeDisposition==="pr-opened"||t.worktreeDisposition==="merged"||t.worktreeDisposition==="dismissed"||t.worktreeDisposition==="no-change-cleaned"?t.worktreeDisposition:void 0,worktreeDismissedAt:I(t.worktreeDismissedAt),worktreeLifecycle:f,resumable:n?!0:t.resumable===!0}}function lg(t){if(!oo(t))return;let e=TI(t.kind),r=ln(t.id),n=ln(t.sessionId),o=je(t.createdAt);if(!(!r||!n||!e||o==null))return{id:r,sessionId:n,kind:e,createdAt:o,planDecisionVersion:je(t.planDecisionVersion),expiresAt:je(t.expiresAt),consumedAt:je(t.consumedAt),optionIndex:je(t.optionIndex),label:I(t.label),targetUrl:I(t.targetUrl),route:ag(t.route),launchName:I(t.launchName),launchPrompt:I(t.launchPrompt),launchWorkdir:I(t.launchWorkdir)}}function ds(t){if(!t.backendRef?.kind||!t.backendRef.conversationId)throw new Error(`Persisted session ${t.harnessSessionId} is missing required backend ref metadata.`);if(!t.route?.provider||!t.route.target)throw new Error(`Persisted session ${t.harnessSessionId} is missing required route metadata.`);if(t.worktreePath&&!t.worktreeBranch)throw new Error(`Persisted session ${t.harnessSessionId} is missing required worktreeBranch metadata.`)}function Gd(t){return!!t&&typeof t=="object"}function Qd(t){return t instanceof Error?t.message:String(t)}function fg(t){let e=t.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||us(og(t),"code-agent-sessions.json")}function gg(t,e,r){try{OI(NI(t),{recursive:!0});let n=t+".tmp";mg(n,JSON.stringify({schemaVersion:as,sessions:e,actionTokens:r},null,2),"utf-8"),ug(n,t)}catch(n){console.warn(`[SessionStore] Failed to save session index: ${Qd(n)}`)}}function ls(t,e){try{if(!EI(t))return;let r=`${t}.legacy-${Date.now()}.json`;ug(t,r),console.warn(`[SessionStore] Breaking upgrade: archived ${e} session store to ${r}. Legacy sessions are not loaded by this release.`)}catch(r){console.warn(`[SessionStore] Failed to archive legacy session store: ${Qd(r)}`)}}function FI(t,e){try{if(e.length===0)return;let r=`${t}.codex-sdk-legacy-${Date.now()}.json`;mg(r,JSON.stringify(e,null,2),"utf-8"),console.warn(`[SessionStore] Breaking Codex transport upgrade: archived ${e.length} legacy Codex SDK session(s) to ${r}. They are not loaded by the App Server backend.`)}catch(r){console.warn(`[SessionStore] Failed to archive legacy Codex SDK sessions: ${Qd(r)}`)}}function hg(t,e){try{let r=zd(),n=Hd(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let i=us(r,o),s=pg(i).mtimeMs;t-s>e&&cg(i)}catch{}}catch{}}function Sg(t,e){try{let r=zd(),n=Hd(r).filter(i=>i.startsWith("openclaw-agent-")&&i.endsWith(".txt")),o;for(let i of n)try{let s=us(r,i),a=pg(s).mtimeMs+e;if(a<=t)return t;o=o==null?a:Math.min(o,a)}catch{}return o}catch{return}}function yg(t){try{let e=new Set(t),r=zd(),n=Hd(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n){let i=us(r,o);if(!e.has(i))try{cg(i)}catch{}}}catch{}}function kg(t){let{indexPath:e,clearAll:r,indexPersistedEntry:n,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:s}=t;try{let a=DI(e,"utf-8"),d=JSON.parse(a);if(Array.isArray(d)){ls(e,"legacy array store"),s();return}if(!Gd(d)||d.schemaVersion!==as&&d.schemaVersion!==4){ls(e,`schema mismatch (expected v${as})`),s();return}let l=Array.isArray(d.sessions)?d.sessions:[],m=[];for(let y of l){if(Gd(y)&&y.harness==="codex"){let v=Gd(y.backendRef)?y.backendRef:void 0;if((typeof v?.kind=="string"?v.kind:void 0)!=="codex-app-server"){m.push(y);continue}}let f=dg(y);if(!f){r(),ls(e,"invalid v4 session entry"),s();return}n(f)}m.length>0&&(FI(e,m),s());let S=Array.isArray(d.actionTokens)?d.actionTokens:[];for(let y of S){let f=lg(y);if(!f){r(),ls(e,"invalid v4 action token"),s();return}o(f)}i()}catch{}}var BI=new Set(["completed","failed","killed"]),Jd=1440*60*1e3;function UI(t){return t instanceof Error?t.message:String(t)}var ps=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;backendIdIndex=new Map;actionTokens;actionTokenStore;indexPath;queries;constructor(e={}){let r=e.env??process.env;this.indexPath=e.indexPath??fg(r),this.actionTokenStore=new is(()=>this.saveIndex(),Jd),this.actionTokens=this.actionTokenStore.tokens,this.queries=new ss({persisted:this.persisted,idIndex:this.idIndex,nameIndex:this.nameIndex,backendIdIndex:this.backendIdIndex}),r.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){kg({indexPath:this.indexPath,clearAll:()=>{this.persisted.clear(),this.idIndex.clear(),this.nameIndex.clear(),this.backendIdIndex.clear(),this.actionTokenStore.clear()},indexPersistedEntry:e=>this.indexPersistedEntry(e),setActionToken:e=>{this.actionTokens.set(e.id,e)},purgeExpiredActionTokens:()=>this.actionTokenStore.purgeExpiredActionTokens(),saveIndex:()=>this.saveIndex()})}saveIndex(){gg(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(e){ds(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){return e.backendRef??{kind:Ad(e)==="codex"?"codex-app-server":"claude-code",conversationId:e.harnessSessionId}}indexPersistedEntry(e){let r=this.getEntryStorageKey(e);this.persisted.set(r,e),e.sessionId&&this.idIndex.set(e.sessionId,r),e.name&&this.nameIndex.set(e.name,r);let n=$(e);n&&this.backendIdIndex.set(n,r)}removePersistedIndexes(e){let r=this.getEntryStorageKey(e);this.persisted.delete(r);for(let[n,o]of this.idIndex)o===r&&this.idIndex.delete(n);for(let[n,o]of this.nameIndex)o===r&&this.nameIndex.delete(n);for(let[n,o]of this.backendIdIndex)o===r&&this.backendIdIndex.delete(n)}markRunning(e){if(!e.harnessSessionId)return;let r=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1},n=Xr({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!n)return;let o={sessionId:e.id,harnessSessionId:e.harnessSessionId,backendRef:this.buildPersistedBackendRef(e),name:e.name,prompt:e.prompt,workdir:e.originalWorkdir??e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,createdAt:e.startedAt,status:"running",lifecycle:e.lifecycle,approvalState:e.approvalState,worktreeState:e.worktreeState,runtimeState:e.runtimeState,deliveryState:e.deliveryState,costUsd:0,originAgentId:e.originAgentId,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey,route:n,harness:e.harnessName,requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:r.planModeApproved,pendingPlanApproval:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeStrategy:e.worktreeStrategy,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,autoMergeParentSessionId:e.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:e.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:e.autoMergeResolverSessionId,worktreeLifecycle:e.worktreeLifecycle,resumable:e.isExplicitlyResumable};ds(o),this.indexPersistedEntry(o),this.saveIndex()}hasRecordedSession(e){return this.queries.hasRecordedSession(e)}persistTerminal(e){if(!e.harnessSessionId)return;let r=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1},n=Xr({route:e.route,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey});if(!n)return;let o;try{let s=sn(e.id);if(LI(s))o=s;else{let a=e.getOutput().join(`
149
+ `);a.length>0&&(WI(s,a,"utf-8"),o=s)}}catch(s){console.warn(`[SessionStore] Failed to write output file for session ${e.id}: ${UI(s)}`)}let i={sessionId:e.id,harnessSessionId:e.harnessSessionId,backendRef:this.buildPersistedBackendRef(e),name:e.name,prompt:e.prompt,workdir:e.originalWorkdir??e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,createdAt:e.startedAt,completedAt:e.completedAt,status:e.status,lifecycle:e.lifecycle,approvalState:e.approvalState,worktreeState:e.worktreeState,runtimeState:e.runtimeState,deliveryState:e.deliveryState,killReason:e.killReason,costUsd:e.costUsd,originAgentId:e.originAgentId,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey,route:n,outputPath:o,harness:e.harnessName,requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:r.planModeApproved,pendingPlanApproval:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeStrategy:e.worktreeStrategy,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,autoMergeParentSessionId:e.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:e.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:e.autoMergeResolverSessionId,worktreeLifecycle:e.worktreeLifecycle,resumable:e.isExplicitlyResumable};ds(i),this.indexPersistedEntry(i),this.saveIndex()}getLatestPersistedByName(e){return this.queries.getLatestPersistedByName(e)}resolveBackendConversationId(e,r){return this.queries.resolveBackendConversationId(e,r)}resolveHarnessSessionId(e,r){return this.queries.resolveHarnessSessionId(e,r)}getPersistedSession(e){return this.queries.getPersistedSession(e)}listPersistedSessions(){return this.queries.listPersistedSessions()}cleanupTmpOutputFiles(e){this.actionTokenStore.purgeExpiredActionTokens(e),hg(e,Jd)}getNextTmpOutputCleanupAt(e){return Sg(e,Jd)}evictOldestPersisted(e){let r=this.listPersistedSessions();if(r.length<=e)return[];let n=r.slice(e);for(let o of n)this.removePersistedIndexes(o);return this.saveIndex(),n}shouldGcActiveSession(e,r,n){return!e.completedAt||!BI.has(e.status)?!1:r-e.completedAt>n}getActionToken(e){return this.actionTokenStore.getActionToken(e)}consumeActionToken(e){return this.actionTokenStore.consumeActionToken(e)}deleteActionTokensForSession(e){this.actionTokenStore.deleteActionTokensForSession(e)}purgeExpiredActionTokens(e=Date.now()){this.actionTokenStore.purgeExpiredActionTokens(e)}getNextActionTokenExpiry(){return this.actionTokenStore.nextExpiryAt()}onActionTokensChanged(e){this.actionTokenStore.setAfterChangeListener(e)}hasOutputPathReference(e){for(let r of this.persisted.values())if(r.outputPath===e)return!0;return!1}getReferencedOutputPaths(){return[...new Set([...this.persisted.values()].map(e=>e.outputPath).filter(e=>typeof e=="string"&&e.length>0))]}cleanupOrphanOutputFiles(){yg(this.getReferencedOutputPaths())}};var KI=new Set(["completed","failed","killed"]),cs=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(e){let r=e.costUsd??0,n=e.status;this.metrics.totalCostUsd+=r;let o=new Date(e.completedAt??e.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+r),KI.has(n)&&this.metrics.sessionsByStatus[n]++,e.completedAt){let i=e.completedAt-e.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||r>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:e.id,name:e.name,costUsd:r,prompt:Fe(e.prompt,80)})}getMetrics(){return{totalCostUsd:this.metrics.totalCostUsd,costPerDay:new Map(this.metrics.costPerDay),sessionsByStatus:{...this.metrics.sessionsByStatus},totalLaunched:this.metrics.totalLaunched,totalDurationMs:this.metrics.totalDurationMs,sessionsWithDuration:this.metrics.sessionsWithDuration,mostExpensive:this.metrics.mostExpensive?{...this.metrics.mostExpensive}:null}}};import{execFile as VI}from"child_process";var Yd=3e4,qI=2e3,jI=2e4,Et=4;function ms(t){return t instanceof Error?t.message:String(t)}function GI(){return new Error(`Dispatch timed out after ${Yd}ms`)}var fs=class{pendingRetryTimers=new Map;orderedDispatchTails=new Map;disposed=!1;clearPendingRetries(){for(let e of this.pendingRetryTimers.values())for(let r of e)clearTimeout(r.timer),r.onCleared?.();this.pendingRetryTimers.clear()}clearRetryTimersForSession(e){let r=this.pendingRetryTimers.get(e);if(r){for(let n of r)clearTimeout(n.timer),n.onCleared?.();this.pendingRetryTimers.delete(e)}}dispose(){this.disposed=!0,this.clearPendingRetries(),this.orderedDispatchTails.clear()}execute(e,r,n=1){if(!this.disposed){if(n===1&&r.orderingKey){this.enqueueOrderedDispatch(r.orderingKey,o=>this.executeNow(e,r,o,n));return}this.executeNow(e,r,void 0,n)}}executePromise(e,r,n=1){if(!this.disposed){if(n===1&&r.orderingKey){this.enqueueOrderedDispatch(r.orderingKey,o=>this.executePromiseNow(e,r,o,n));return}this.executePromiseNow(e,r,void 0,n)}}executeNow(e,r,n,o=1){if(this.disposed){n?.();return}let i=Date.now();o===1&&r.onStarted?.(),this.log("info","dispatch_started",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et}),VI("openclaw",e,{timeout:Yd},(s,a,d)=>{if(this.disposed){n?.();return}let l=Date.now()-i;if(!s){this.log("info","dispatch_succeeded",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et,elapsedMs:l}),r.onSuccess?.(),n?.();return}let m=d?.trim()?` | stderr: ${d.trim()}`:"";if(o>=Et){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et,elapsedMs:l,error:`${ms(s)}${m}`,terminal:!0}),r.onFinalFailure?.(),n?.();return}let S=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et,elapsedMs:l,retryDelayMs:S,error:`${ms(s)}${m}`});let y={timer:setTimeout(()=>{let f=this.pendingRetryTimers.get(r.sessionId);f&&(f.delete(y),f.size===0&&this.pendingRetryTimers.delete(r.sessionId)),this.executeNow(e,r,n,o+1)},S),onCleared:n};y.timer.unref?.(),this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(y)})}executePromiseNow(e,r,n,o=1){if(this.disposed){n?.();return}let i=Date.now();o===1&&r.onStarted?.(),this.log("info","dispatch_started",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et}),this.executePromiseWithTimeout(e).then(()=>{if(this.disposed){n?.();return}let s=Date.now()-i;this.log("info","dispatch_succeeded",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et,elapsedMs:s}),r.onSuccess?.(),n?.()}).catch(s=>{if(this.disposed){n?.();return}let a=Date.now()-i;if(o>=Et){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et,elapsedMs:a,error:ms(s),terminal:!0}),r.onFinalFailure?.(),n?.();return}let d=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:o,maxAttempts:Et,elapsedMs:a,retryDelayMs:d,error:ms(s)});let l={timer:setTimeout(()=>{let m=this.pendingRetryTimers.get(r.sessionId);m&&(m.delete(l),m.size===0&&this.pendingRetryTimers.delete(r.sessionId)),this.executePromiseNow(e,r,n,o+1)},d),onCleared:n};l.timer.unref?.(),this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(l)})}executePromiseWithTimeout(e){return new Promise((r,n)=>{let o=!1,i=setTimeout(()=>{o||(o=!0,n(GI()))},Yd);i.unref?.(),Promise.resolve().then(e).then(()=>{o||(o=!0,clearTimeout(i),r())}).catch(s=>{o||(o=!0,clearTimeout(i),n(s))})})}retryDelayMs(e){let r=Math.max(0,e-1),n=qI*2**r;return Math.min(n,jI)}enqueueOrderedDispatch(e,r){let o=(this.orderedDispatchTails.get(e)??Promise.resolve()).catch(()=>{}).then(()=>{if(!this.disposed)return new Promise(i=>{let s=!1;r(()=>{s||(s=!0,i())})})});this.orderedDispatchTails.set(e,o),o.finally(()=>{this.orderedDispatchTails.get(e)===o&&this.orderedDispatchTails.delete(e)})}log(e,r,n){let o=`[WakeDispatcher] ${JSON.stringify({event:r,...n})}`;if(e==="error"){console.error(o);return}console.info(o)}};Zr();var gs=class{resolve(e){let r=nm(e);if(!(!r?.provider||!r.target))return{channel:r.provider,target:r.target,accountId:r.accountId,threadId:r.threadId,sessionKey:r.sessionKey}}summary(e){if(!e)return"system";let r=e.accountId?`|${e.accountId}`:"",n=e.threadId?`#${e.threadId}`:"";return`${e.channel}${r}|${e.target}${n}`}};import{randomUUID as HI}from"crypto";function zI(){return process.env.OPENCLAW_CODE_AGENT_DISCORD_SDK_MODULE_URL??"openclaw/plugin-sdk/discord"}var hs=class{discordComponentSenderPromise=null;buildChatSendArgs(e,r,n){return["gateway","call","chat.send","--expect-final","--timeout","30000","--params",JSON.stringify({sessionKey:e,message:r,deliver:n,idempotencyKey:HI()})]}buildDirectNotificationArgs(e,r,n){let o=["message","send","--channel",e.channel,"--target",e.target,"--message",r];return e.accountId&&o.push("--account",e.accountId),e.threadId&&o.push("--thread-id",e.threadId),n&&e.channel==="telegram"&&o.push("--buttons",JSON.stringify(n.map(i=>i.map(s=>({text:s.label,callback_data:s.callbackData.startsWith(`${lr}:`)?s.callbackData:`${lr}:${s.callbackData}`}))))),o}prefixCallbackData(e){return e.startsWith(`${lr}:`)?e:`${lr}:${e}`}resolveDiscordButtonStyle(e){let r=e.trim().toLowerCase();return r==="approve"||r==="open pr"?"primary":r==="merge"||r==="resume"?"success":r==="reject"||r==="discard"?"danger":"secondary"}buildDiscordComponentSpec(e){let r=[];for(let n of e)if(!(!Array.isArray(n)||n.length===0))for(let o=0;o<n.length;o+=5){let i=n.slice(o,o+5);r.push({type:"actions",buttons:i.map(s=>({label:s.label,callbackData:this.prefixCallbackData(s.callbackData),style:this.resolveDiscordButtonStyle(s.label)}))})}return{blocks:r}}resolveDiscordComponentTarget(e){let r=e.threadId?.trim();return r?`channel:${r}`:e.target}async loadDiscordComponentSender(){return this.discordComponentSenderPromise||(this.discordComponentSenderPromise=import(zI()).then(e=>{if(typeof e.sendDiscordComponentMessage!="function")throw new Error("OpenClaw Discord component sender export is unavailable");return e.sendDiscordComponentMessage}).catch(e=>{throw this.discordComponentSenderPromise=null,e})),this.discordComponentSenderPromise}async sendDiscordComponents(e,r){await(await this.loadDiscordComponentSender())(this.resolveDiscordComponentTarget(e),this.buildDiscordComponentSpec(r),e.accountId?{accountId:e.accountId}:void 0)}buildSystemEventArgs(e){return["system","event","--text",e,"--mode","now"]}};var Ss=class{routes=new gs;transport=new hs;executor=new fs;clearPendingRetries(){this.executor.clearPendingRetries()}clearRetryTimersForSession(e){this.executor.clearRetryTimersForSession(e)}dispose(){this.executor.dispose()}sendWake(e,r,n,o,i,s){let d=this.routes.resolve(e)?.sessionKey?.trim();if(!d){this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-system`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",onSuccess:s,onFinalFailure:i});return}this.executor.execute(this.transport.buildChatSendArgs(d,r,!0),{label:n,sessionId:e.id,target:"chat.send",phase:o,routeSummary:`session:${d}`,messageKind:"wake",onSuccess:s,onFinalFailure:()=>{this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-fallback`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",onSuccess:s,onFinalFailure:i})}})}sendUserNotification(e,r,n,o,i,s){let a=!!(o&&o.length>0),d=this.routes.resolve(e),l=d?`notify:${d.channel}|${d.accountId??""}|${d.target}|${d.threadId??""}`:`notify:system:${e.id}`;if(!d){if(a){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${e.id} has no direct route; refusing text-only fallback because buttons would be lost.`),i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-notify-system`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",orderingKey:l,onSuccess:s,onFinalFailure:i});return}if(a&&d.channel==="discord"){let m=()=>{this.executor.executePromise(()=>this.transport.sendDiscordComponents(d,o),{label:`${n}-notify-components`,sessionId:e.id,target:"discord.components",phase:"notify",routeSummary:this.routes.summary(d),messageKind:"notify",onSuccess:s,onFinalFailure:()=>{console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${e.id} failed Discord component delivery.`),i?.()}})};if(r){this.executor.execute(this.transport.buildDirectNotificationArgs(d,r),{label:`${n}-notify-text`,sessionId:e.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(d),messageKind:"notify",orderingKey:l,onSuccess:m,onFinalFailure:i});return}m();return}this.executor.execute(this.transport.buildDirectNotificationArgs(d,r,o),{label:`${n}-notify`,sessionId:e.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(d),messageKind:"notify",orderingKey:l,onSuccess:s,onFinalFailure:()=>{if(a){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${e.id} failed direct delivery; refusing text-only fallback because buttons would be lost.`),i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-notify-fallback`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",orderingKey:l,onSuccess:s,onFinalFailure:i})}})}sendUserNotificationSequence(e,r,n,o,i){let s=r.map(d=>({text:d.text.trim(),buttons:d.buttons})).filter(d=>d.text.length>0);if(s.length===0){o?.();return}let a=d=>{let l=s[d];if(!l){i?.();return}let m=d===0?o:i;this.sendUserNotification(e,l.text,`${n}-part-${d+1}`,l.buttons,m,()=>a(d+1))};a(0)}dispatchSessionNotification(e,r){let n=r.hooks,o=r.wakeMessageOnNotifySuccess!=null||r.wakeMessageOnNotifyFailed!=null,i=r.notifyUser??(r.wakeMessage?"on-wake-fallback":"always"),s=(r.userMessages?.length?r.userMessages:r.userMessage?.trim()?[{text:r.userMessage.trim(),buttons:r.buttons}]:[]).map(l=>({text:l.text.trim(),buttons:l.buttons})).filter(l=>l.text.length>0),a=s[0]?.text,d=r.wakeMessage?.trim();if(o){let l=r.wakeMessageOnNotifySuccess?.trim(),m=r.wakeMessageOnNotifyFailed?.trim(),S=v=>{v&&(n?.onWakeStarted?.(),this.sendWake(e,v,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded))},y=()=>{n?.onNotifySucceeded?.(),l&&S(l)},f=m?()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.(),S(m)}:()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()};s.length>0?(n?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,r.label,f,y)):f();return}i==="always"&&s.length>0&&(n?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,r.label,()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()},()=>n?.onNotifySucceeded?.())),d&&(n?.onWakeStarted?.(),i==="on-wake-fallback"&&s.length>0&&!this.routes.resolve(e)?.sessionKey&&(n?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,r.label,()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()},()=>n?.onNotifySucceeded?.())),this.sendWake(e,d,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded))}};var ys=class{constructor(e,r){this.actionTokens=e;this.isGitHubCliAvailable=r}actionTokens;isGitHubCliAvailable;createActionToken(e,r,n={}){return this.actionTokens.createActionToken(e,r,{expiresAt:Date.now()+10080*60*1e3,...n})}consumeActionToken(e){return this.actionTokens.consumeActionToken(e)}getActionToken(e){return this.actionTokens.getActionToken(e)}clearPlanDecisionTokens(e,r){this.actionTokens.deletePlanDecisionTokensForSession(e,r)}makeActionButton(e,r,n,o={}){let i=this.createActionToken(e,r,{label:n,...o});return{label:n,callbackData:i.id}}getWorktreeDecisionButtons(e,r){if(!r)return[];let n=[],o=[this.makeActionButton(e,"worktree-merge","Merge")];if(this.isGitHubCliAvailable())r.worktreePrUrl?(o.push(this.makeActionButton(e,"worktree-view-pr","View PR",{targetUrl:r.worktreePrUrl})),n.push(o),n.push([this.makeActionButton(e,"worktree-update-pr","Sync PR"),this.makeActionButton(e,"worktree-decide-later","Later")])):(o.push(this.makeActionButton(e,"worktree-create-pr","Open PR")),n.push(o),n.push([this.makeActionButton(e,"worktree-decide-later","Later"),this.makeActionButton(e,"worktree-dismiss","Discard")]));else return n.push([...o,this.makeActionButton(e,"worktree-decide-later","Later")]),n.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),n;return r.worktreePrUrl&&n.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),n}getPlanApprovalButtons(e,r){return[[this.makeActionButton(e,"plan-approve","Approve",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(e,"plan-request-changes","Revise",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(e,"plan-reject","Reject",{planDecisionVersion:r?.planDecisionVersion})]]}getResumeButtons(e,r){let n=[];return r.isExplicitlyResumable&&n.push(this.makeActionButton(e,"session-resume","Resume")),n.push(this.makeActionButton(e,"view-output","View output")),[n]}getQuestionButtons(e,r){if(r.length!==0)return[r.map((n,o)=>this.makeActionButton(e,"question-answer",n.label,{optionIndex:o}))]}getMonitorReportButtons(e){let{reportId:r,route:n,planName:o,planPrompt:i,planWorkdir:s}=e;return[[this.makeActionButton(r,"monitor-start-plan","Start Plan",{route:n,launchName:o,launchPrompt:i,launchWorkdir:s}),this.makeActionButton(r,"monitor-dismiss","Dismiss",{route:n})]]}};ke();var ks=class{constructor(e,r){this.wakeDispatcher=e;this.applyPersistedPatch=r}wakeDispatcher;applyPersistedPatch;dispatch(e,r){let n=this.getDeliveryRef(e),o=this.buildCompletionWakePatch(r),i=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifySuccess?.trim()),s=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifyFailed?.trim()),a={onNotifyStarted:()=>{this.applyDeliveryState(n,"notifying"),r.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{this.applyDeliveryState(n,i?"wake_pending":"idle"),r.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{this.applyDeliveryState(n,s?"wake_pending":"failed"),r.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyPersistedPatchWithCompletionWake(n,"wake_pending",o,{completionWakeIssuedAt:new Date().toISOString(),completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0}),r.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{this.applyPersistedPatchWithCompletionWake(n,"idle",o,{completionWakeSucceededAt:new Date().toISOString(),completionWakeFailedAt:void 0}),r.hooks?.onWakeSucceeded?.()},onWakeFailed:()=>{this.applyPersistedPatchWithCompletionWake(n,"failed",o,{completionWakeFailedAt:new Date().toISOString()}),r.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(e,{...r,hooks:a})}notifyWorktreeOutcome(e,r){this.dispatch(e,{label:"worktree-outcome",userMessage:r,notifyUser:"always"})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(e){return re(e)??$(e)??""}applyDeliveryState(e,r){!e||!r||this.applyPersistedPatch(e,{deliveryState:r})}applyPersistedPatchWithCompletionWake(e,r,n,o){!e||!r||this.applyPersistedPatch(e,n?{deliveryState:r,...n,...o}:{deliveryState:r})}buildCompletionWakePatch(e){if(e.label==="completed")return{completionWakeSummaryRequired:!0}}};ut();import{existsSync as QI}from"fs";var vs=class{getCompletionState(e,r,n,o){return _d(e,n,o)?"has-commits":_d(e,o,n)?"base-advanced":an(r)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(e,r,n){if(!e.worktreePath||!e.workdir||!QI(e.worktreePath)||e.pendingWorktreeDecisionSince||e.worktreeState==="pending_decision")return!1;let o=e.worktreeMergedAt??e.worktreeDismissedAt??e.completedAt??e.createdAt,i=typeof o=="string"?new Date(o).getTime():Number(o??0);return!!i&&r-i>=n}};var Ps=class{constructor(e,r,n,o){this.pendingQuestions=e;this.dispatchSessionNotification=r;this.clearWaitingTimestamp=n;this.getQuestionButtons=o}pendingQuestions;dispatchSessionNotification;clearWaitingTimestamp;getQuestionButtons;async handleAskUserQuestion(e,r){let i=r?.questions??[];if(i.length===0)throw new Error("AskUserQuestion: no questions in input");let s=i[0],a=s.options??[],d=this.getQuestionButtons(e.id,a),l=`\u2753 [${e.name}] ${s.question}`,m=[`[ASK USER QUESTION] Session "${e.name}" has a question requiring user input.`,"",`Question: ${s.question}`,...a.length>0?["Options:",...a.map((S,y)=>` ${y+1}. ${S.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
150
+ `);return new Promise((S,y)=>{let f=setTimeout(()=>{this.pendingQuestions.delete(e.id),y(new Error(`AskUserQuestion timed out after 600s for session "${e.name}"`))},6e5);f.unref?.(),this.pendingQuestions.set(e.id,{resolve:S,reject:y,questions:i,timeoutHandle:f}),this.dispatchSessionNotification(e,{label:"ask-user-question",userMessage:l,notifyUser:"always",buttons:d,wakeMessageOnNotifySuccess:["AskUserQuestion delivered to the user.",`Session: ${e.name} | ID: ${e.id}`,`Question: ${s.question}`,"Await their selection \u2014 do NOT answer this question yourself."].join(`
151
+ `),wakeMessageOnNotifyFailed:m})})}resolveAskUserQuestion(e,r){let n=this.pendingQuestions.get(e);if(!n){console.warn(`[SessionQuestionService] resolveAskUserQuestion: no pending question for session "${e}"`);return}clearTimeout(n.timeoutHandle),this.pendingQuestions.delete(e);let o=n.questions[0],i=o.options??[],s=i[r];if(!s){n.reject(new Error(`AskUserQuestion: invalid option index ${r} (${i.length} options available)`));return}this.clearWaitingTimestamp(e),n.resolve({behavior:"allow",updatedInput:{questions:n.questions,answers:{[o.question]:s.label}}})}dispose(){for(let e of this.pendingQuestions.values())clearTimeout(e.timeoutHandle),e.reject(new Error("SessionManager disposed before AskUserQuestion resolved."));this.pendingQuestions.clear()}};function JI(t){if(t.requestedPermissionMode==="plan"){if(t.approvalExecutionState==="approved_then_implemented"){if(t.planApproval==="ask"&&t.approvalPromptStatus==="delivered"&&t.approvalPromptMessageKind==="canonical_buttons"&&t.approvalPromptDeliveredAt)return"Approval interpretation: canonical Approve/Revise/Reject buttons were delivered, and implementation after approval was expected.";if(t.approvalState==="approved")return"Approval interpretation: explicit plan approval was recorded before implementation, so leaving plan-only mode was expected."}if(t.approvalExecutionState==="implemented_without_required_approval")return"Approval interpretation: implementation left plan-only mode without a recorded approval."}}function ws(t){let e=JI(t);return[`Requested permission mode: ${t.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${t.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${t.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function io(t){switch(t){case"user":return"Stopped by user";case"shutdown":return"Stopped by shutdown";case"startup-timeout":return"Stopped by startup timeout";case"unknown":case void 0:return"Stopped unexpectedly";default:return"Stopped"}}function YI(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function Xd(t){let{sessionId:e,canonicalStatusDetail:r,canonicalStatusDelivered:n=!0}=t;return["[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${e}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.",`3. ${r??(n?"The plugin already sent the canonical completion status to the user.":"The plugin did not confirm delivery of the canonical completion status to the user.")}`,"4. Unless you are silently continuing an internal multi-phase pipeline or there is still no meaningful confirmed outcome to report, you must send the user a short factual completion summary for this completed session.","5. This requirement applies to ordinary terminal/manual completions too, not just delegated worktree decisions.","6. That follow-up belongs to you alone; keep it brief, concrete, and grounded in reliable result data.",...n?["7. Do NOT repeat the plugin's status line, and do NOT rely on the plugin to summarize the completed work for you."]:["7. Because canonical status delivery was not confirmed, account for that gap yourself when you follow up; do NOT assume the plugin already reached the user."]]}function XI(t){let{contract:e,canonicalStatusDelivered:r}=t;return["Completion diagnostics:",`- Canonical completion status delivered to user: ${r?"yes":"no"}`,`- Plugin requested short factual follow-up summary: ${e.requiresShortFactualSummary?"yes":"no"}`,`- Contract applies to ordinary terminal/manual completions: ${e.appliesToOrdinaryTerminalCompletions?"yes":"no"}`]}function Zd(t){let{session:e,originThreadLine:r,preview:n}=t,o=`$${(e.costUsd??0).toFixed(2)}`,i=It(e.duration),s=YI(),a=d=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,r,...ws(e),"","Output preview:",n,"",...XI({contract:s,canonicalStatusDelivered:d}),"",...Xd({sessionId:e.id,canonicalStatusDelivered:d})].join(`
152
+ `);return{userMessage:`\u2705 [${e.name}] Completed | ${o} | ${i}`,wakeMessageOnNotifySuccess:a(!0),wakeMessageOnNotifyFailed:a(!1),followupContract:s}}function el(t){let{session:e,originThreadLine:r,errorSummary:n,preview:o,worktreeAutoCleaned:i,failedButtons:s}=t,a=o.trim()?["","Output preview:",o]:[],d=i?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[],l=`$${(e.costUsd??0).toFixed(2)}`,m=It(e.duration);return{userMessage:[`\u274C [${e.name}] Failed | ${l} | ${m}`,` \u26A0\uFE0F ${n}`].join(`
153
+ `),wakeMessage:["Coding agent session failed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,r,...ws(e),...e.harnessSessionId?[`Backend conversation ID: ${e.harnessSessionId}`]:[],"","Failure summary:",n,...a,...d,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${e.id}', full=true) to inspect the full failure context.`,`2. Continue the same session with agent_respond(session='${e.id}', message='<next instruction>').`,` If you intentionally want to fork or switch harnesses, launch a new session with agent_launch(resume_session_id='${e.id}', fork_session=true, ...)`," If the failure is a launch/config issue, relaunch fresh with agent_launch(prompt=...).","3. Notify the user with the failure cause and the next action you are taking."].join(`
154
+ `),buttons:s}}function tl(t){let{session:e,originThreadLine:r,preview:n}=t,o=`$${(e.costUsd??0).toFixed(2)}`;return{userMessage:`\u23F8\uFE0F [${e.name}] Turn completed | ${o}`,wakeMessage:["Coding agent session turn ended.",`Name: ${e.name}`,`ID: ${e.id}`,`Status: ${e.status}`,`Lifecycle: ${e.lifecycle}`,"","Last output (~20 lines):",n,...r?["",r]:[]].join(`
155
+ `)}}function rl(t){let{sessionName:e,sessionId:r,branchName:n,baseBranch:o,promptSnippet:i,commitLines:s,moreNote:a,diffSummary:d}=t;return[`[DELEGATED WORKTREE DECISION] Session "${e}" completed with changes.`,"",`Session ID: ${r}`,`Branch: ${n} \u2192 ${o}`,`Commits: ${d.commits} | Files: ${d.filesChanged} | +${d.insertions} / -${d.deletions}`,"",...s,...a?[a]:[],"","Original task prompt (first 500 chars):",i,"","You own the next step for this worktree.",`- Merge immediately with agent_merge(session="${e}", base_branch="${o}") if the changes are clearly in-scope and low-risk.`,"- If a PR is safer, message the user with the summary and ask for confirmation before calling agent_pr().","- If scope or risk is unclear, message the user and ask for guidance.","- Never call agent_pr() autonomously in delegate mode.","- After deciding, notify the user briefly with what you did and why."].join(`
156
+ `)}function nl(t,e){return[`[DELEGATED WORKTREE DECISION REMINDER] Session "${t.name}" still has an unresolved worktree decision.`,"",`Session ID: ${t.sessionId??t.harnessSessionId}`,`Branch: ${t.worktreeBranch??"unknown"}`,`Pending: ${e}h`,"","Resolve it now:",`- agent_merge(session="${t.name}") if the diff is clearly safe and in scope`,"- If a PR is safer, ask the user before agent_pr()","- If scope or risk is unclear, ask the user for guidance","- Never call agent_pr() autonomously in delegate mode"].join(`
157
+ `)}function ol(t){let{sessionName:e,sessionId:r,cleanupSummary:n,preview:o,originThreadLine:i,requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:m,approvalPromptStatus:S,approvalPromptMessageKind:y,approvalPromptDeliveredAt:f}=t,v=o.trim()?["","Output preview:",o]:[];return["Coding agent session completed with no repository changes.",`Name: ${e} | ID: ${r}`,`Worktree outcome: ${n}`,...i?[i]:[],...ws({requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d,approvalState:l,planApproval:m,approvalPromptStatus:S,approvalPromptMessageKind:y,approvalPromptDeliveredAt:f}),...v,"",...Xd({sessionId:r,canonicalStatusDetail:"The plugin already sent the canonical completion status to the user, including that no repo changes were kept."})].join(`
158
+ `)}function il(t){let e=[],r=t.changedFiles.slice(0,3).map(o=>`\`${o}\``);if(r.length>0){let o=t.changedFiles.length-r.length;e.push(o>0?`Touches ${r.join(", ")} and ${o} more file${o===1?"":"s"}`:`Touches ${r.join(", ")}`)}let n=[...new Set(t.commitMessages.map(o=>o.message.trim()).filter(Boolean))].slice(0,2);return n.length>0&&e.push(`Recent work: ${n.join("; ")}`),e}var wg=3200,sl=3e3,ZI=2400,eb=120,tb=5,rb=280,vg=1400,Pg="- Additional plan details omitted for brevity.";function Ig(t){return t.replace(/^#{1,6}\s+/,"").replace(/^[-*+]\s+/,"").replace(/^\d+[.)]\s+/,"").replace(/^`([^`]+)`$/,"$1").trim()}function nb(t){return t.split(`
159
+ `).map(e=>e.trim()).filter(Boolean).map(Ig).map(e=>Fe(e,220)).filter(e=>e.length>0).filter(e=>!/^(plan|proposed plan|implementation plan|review summary|full plan)[:]?$/i.test(e)).filter(e=>!/^(should|can|could|would|will)\b.*\?$/i.test(e)).filter(e=>!/^(thinking|checking|considering|analyzing)\b/i.test(e))}function ob(t){return t.split(`
160
+ `).map(e=>e.trim()).filter(Boolean).map(Ig).filter(e=>e.length>0).filter(e=>!/^(plan|proposed plan|implementation plan|review summary|summary|why this was escalated|full plan)[:]?$/i.test(e)).filter(e=>!/^(should|can|could|would|will)\b.*\?$/i.test(e)).filter(e=>!/^(thinking|checking|considering|analyzing)\b/i.test(e))}function al(t){let e=nb(t);return e.length===0?`Review summary:
161
+ - Plan details are available in the full session output.`:["Review summary:",...e.slice(0,6).map(r=>`- ${r}`)].join(`
162
+ `)}function ib(t){let e=[],r=!1;for(let o of t){let i=o.replace(/\s+/g," ").trim();if(!i)continue;let s=Fe(i,rb);s.length<i.length&&(r=!0);let a=`- ${s}`;if(e.length>=tb||[...e,a].join(`
163
+ `).length>vg){r=!0;break}e.push(a)}if(e.length===0)return["- Plan details are available in the full session output."];if(!r)return e;let n=[...e];for(;n.length>0&&[...n,Pg].join(`
164
+ `).length>vg;)n.pop();return[...n,Pg]}function dl(t){return ib(ob(t)).join(`
165
+ `)}function sb(t,e){let r=[],n=t.trim();for(;n.length>e;){let o=n.lastIndexOf(" ",e);o<Math.floor(e*.6)&&(o=e),r.push(n.slice(0,o).trimEnd()),n=n.slice(o).trimStart()}return n.length>0&&r.push(n),r}function ab(t,e){let r=t.split(`
166
+ `),n=[],o="",i=()=>{o.trim().length>0&&(n.push(o.trimEnd()),o="")};for(let s of r){if(s.length>e){i();for(let d of sb(s,e))n.push(d);continue}let a=o.length>0?`${o}
167
+ ${s}`:s;if(a.length>e){i(),o=s;continue}o=a}return i(),n}function bg(t){return Fe(t.trim(),eb)}function xg(t,e){return e?t?`
168
+
169
+ Choose Approve, Revise, or Reject below.`:`
170
+
171
+ Approval is still pending for this plan version.`:`
172
+
173
+ Continued in next message.`}function db(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=`\u{1F4CB} [${e}] Plan v${r??"?"} ready for approval:`,s=`
174
+
175
+ Full plan (truncated):
176
+ `,a=xg(o,!0),d=Math.max(0,sl-i.length-s.length-a.length);return`${i}${s}${Fe(n,d)}${a}`}function lb(t){let{sessionName:e,actionableVersion:r,fullPlanText:n,hasButtons:o}=t,i=bg(e),s=ZI;for(;s>0;){let a=ab(n,s),d=a.map((S,y)=>{let f=a.length,v=[`\u{1F4CB} [${i}] Plan v${r??"?"} ready for approval (${y+1}/${f}):`,"",y===0?"Full plan:":""].filter(Boolean).join(`
177
+ `),A=xg(o,y===f-1);return`${v}
178
+ ${S}${A}`}),l=d.reduce((S,y)=>Math.max(S,y.length),0);if(l<=sl)return d;let m=l-sl;s-=Math.max(m,50)}return[db({sessionName:i,actionableVersion:r,fullPlanText:n,hasButtons:o})]}function ll(t){let{preview:e,artifact:r}=t,n=r?.markdown?.trim();return n&&n.length<=wg?`Full plan:
179
+ ${n}`:al(n||e)}function Ag(t){let{sessionName:e,actionableVersion:r,preview:n,artifact:o,hasButtons:i}=t,s=o?.markdown?.trim(),a=bg(e);if(s){let l=`\u{1F4CB} [${a}] Plan v${r??"?"} ready for approval:
180
+
181
+ Full plan:
182
+ ${s}
183
+
184
+ ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`;return l.length<=wg?{displayMode:"single-full-plan",userMessages:[l],reviewSummary:`Full plan:
185
+ ${s}`}:{displayMode:"chunked-full-plan",userMessages:lb({sessionName:e,actionableVersion:r,fullPlanText:s,hasButtons:i}),reviewSummary:al(s)}}let d=al(n);return{displayMode:"summary",userMessages:[`\u{1F4CB} [${a}] Plan v${r??"?"} ready for approval:
186
+
187
+ ${d}
188
+
189
+ ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for this plan version."}`],reviewSummary:d}}function ub(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function so(t){let{session:e,summary:r}=t,n=e.actionablePlanDecisionVersion??e.planDecisionVersion;return[`\u{1F4CB} [${e.name}] Plan v${n??"?"} needs your decision.`,"","Interactive Approve / Revise / Reject buttons could not be delivered, so reply here instead:",'- Reply "approve" to approve and start implementation','- Reply "reject" to reject and stop the session',"- Any other reply will be sent back as revision feedback","","Why this was escalated:","",r].join(`
190
+ `)}function ul(t){let{session:e,preview:r,planArtifact:n,originThreadLine:o,planApprovalMode:i,planApprovalButtons:s,questionButtons:a}=t,d=e.pendingPlanApproval,l=e.actionablePlanDecisionVersion??e.planDecisionVersion,m=ub(e,l),S=i??"delegate",y=d&&S==="ask"&&!m?Ag({sessionName:e.name,actionableVersion:l,preview:r,artifact:n,hasButtons:!!s}):void 0,f=d?y?.reviewSummary??ll({preview:r,artifact:n}):void 0,v=d?y&&y.userMessages.length===1?y.userMessages[0]:void 0:`\u2753 [${e.name}] Question waiting for reply:
191
+
192
+ ${r}`,A=d&&y&&y.userMessages.length>1?y.userMessages.map((w,C,b)=>({text:w,buttons:C===b.length-1?s:void 0})):void 0;if(d){let w=S,C="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return w==="delegate"?{label:"plan-approval",userMessage:v,userMessages:A,planReviewSummary:f,wakeMessage:["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${e.name} | ID: ${e.id} | Plan v${l??"?"}`,o,C,"","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${e.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",r,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Review privately \u2501\u2501\u2501","You are the delegated decision-maker. Review the plan yourself before involving the user.","If you approve directly, you own the user-facing explanation of what was approved and why.","Keep it short and user-facing: one sentence is usually enough.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: call agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true, approval_rationale='<brief reason>').`,"That rationale should say why approval was safe: for example scope match, low risk, or no meaningful ambiguity.","After approving directly, send the user a short plain-text follow-up explaining what was approved and why.","The plugin's thumbs-up line is only the minimal approval acknowledgment, not the explanation.",`If escalating: call agent_request_plan_approval(session='${e.id}', summary='...') exactly once so the plugin posts the single canonical Approve / Revise / Reject prompt.`,"That summary must concisely explain why this was escalated, plus changed files/components, risk level and why, scope match/expansion, and any concerns or assumptions.","After the canonical prompt exists, WAIT for the user's button click or explicit response and do NOT send a second plain-text recap.",`To request changes without user escalation: call agent_respond(session='${e.id}', message='<your feedback>') and do NOT set approve=true. The agent will revise the plan.`].join(`
193
+ `)}:w==="ask"?{label:"plan-approval",userMessage:v,userMessages:A,planReviewSummary:f,wakeMessage:["[USER APPROVAL REQUESTED] Coding agent session has finished its plan. The user has been notified via Telegram and must approve directly.",`Name: ${e.name} | ID: ${e.id} | Plan v${l??"?"}`,o,C,"","DO NOT approve this plan yourself. Wait for the user's explicit approval or rejection.","Once the user responds, forward their decision:",` To approve: agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`,` To request changes: agent_respond(session='${e.id}', message='<user feedback>')`,"","Preview (truncated):",r].join(`
194
+ `),buttons:A?void 0:s}:{label:"plan-approval",userMessage:v,planReviewSummary:f,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`].join(`
195
+ `)}}let x=e.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:v,wakeMessage:[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 forward the agent's EXACT question to the user. Do NOT add your own analysis, commentary, or interpretation. Do NOT "nudge" or "poke" the session.]`,"",`${x} is waiting for a genuine user reply.`,`Name: ${e.name} | ID: ${e.id}`,o,"","Last output:",r,"",`Use agent_respond(session='${e.id}', message='...') to send a reply, or agent_output(session='${e.id}', full: true) to see full context before deciding.`].join(`
196
+ `),buttons:a}}ke();var Is=class t{constructor(e,r,n,o){this.buildRoutingProxy=e;this.dispatchNotification=r;this.updatePersistedSession=n;this.getWorktreeDecisionButtons=o}buildRoutingProxy;dispatchNotification;updatePersistedSession;getWorktreeDecisionButtons;static REMINDER_THRESHOLD_MS=10800*1e3;static REMINDER_INTERVAL_MS=10800*1e3;getNextReminderAt(e){if(!e.pendingWorktreeDecisionSince)return;let r=e.worktreeState==="pending_decision"||e.lifecycle==="awaiting_worktree_decision",n=e.worktreeState==null&&e.lifecycle==null&&!e.worktreeMerged&&!e.worktreePrUrl;if(!r&&!n)return;let o=new Date(e.pendingWorktreeDecisionSince).getTime();if(!Number.isFinite(o))return;let i=[o+t.REMINDER_THRESHOLD_MS];if(e.worktreeDecisionSnoozedUntil){let s=new Date(e.worktreeDecisionSnoozedUntil).getTime();Number.isFinite(s)&&i.push(s)}if(e.lastWorktreeReminderAt){let s=new Date(e.lastWorktreeReminderAt).getTime();Number.isFinite(s)&&i.push(s+t.REMINDER_INTERVAL_MS)}return Math.max(...i)}sendReminderIfDue(e,r=Date.now()){let n=this.getNextReminderAt(e);if(n==null||n>r)return!1;let o=r-new Date(e.pendingWorktreeDecisionSince).getTime(),i=Math.floor(Math.max(0,o)/(3600*1e3));try{this.sendReminderNotification(e,i)}catch(s){return console.warn(`[SessionReminderService] Failed to send stale-decision reminder for session ${e.name}: ${s instanceof Error?s.message:String(s)}`),!1}for(let s of et(e))this.updatePersistedSession(s,{lastWorktreeReminderAt:new Date(r).toISOString()});return!0}sendReminderNotification(e,r){let n=this.buildRoutingProxy({id:e.sessionId??e.name??$(e)??e.harnessSessionId,sessionId:e.sessionId,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef,route:e.route});if(e.worktreeStrategy==="delegate"){this.dispatchNotification(n,{label:`worktree-stale-reminder-${e.name}`,wakeMessage:nl(e,r),notifyUser:"never"});return}let o=[`\u23F0 Reminder: branch \`${e.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${e.name} | Pending: ${r}h`,"",`agent_merge(session="${e.name}") or agent_pr(session="${e.name}") or agent_worktree_cleanup() to resolve.`].join(`
197
+ `);this.dispatchNotification(n,{label:`worktree-stale-reminder-${e.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(re(e)??e.harnessSessionId)})}};ut();ke();import{existsSync as pb,readFileSync as cb}from"fs";function Rg(t,e){return e!=null&&t.approvalPromptRequiredVersion===e&&(t.approvalPromptStatus==="delivered"||t.approvalPromptStatus==="fallback_delivered")}function mb(t,e){if(t.latestPlanArtifactVersion===e&&t.latestPlanArtifact)return t.latestPlanArtifact;let r=t.planFilePath?.trim();if(!(!r||!pb(r)))try{let n=cb(r,"utf-8").trim();return n?{markdown:n,steps:[]}:void 0}catch{return}}var bs=class{constructor(e){this.deps=e}deps;buildPlanApprovalWakeText(e,r,n=!1){return[n?"Plan review fallback text delivered to the user because interactive buttons could not be delivered.":"Plan approval buttons delivered to the user.",`Session: ${e.name} | ID: ${e.id} | Plan v${r??"?"}`,`Wait for their ${n?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
198
+ `)}buildPlanApprovalDeliveryFailureWake(e,r){return["[PLAN APPROVAL DELIVERY FAILED] The plugin could not deliver the canonical plan review buttons or the explicit fallback text to the user.",`Name: ${e.name} | ID: ${e.id} | Plan v${r??"?"}`,this.deps.originThreadLine(e),"","No user-visible actionable review prompt is confirmed for this plan version.","Intervene manually before assuming the user saw the plan review request."].join(`
199
+ `)}dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",userMessage:so({session:e,summary:n}),notifyUser:"always",hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"failed",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,r,!0),wakeMessageOnNotifyFailed:this.buildPlanApprovalDeliveryFailureWake(e,r)})}logCompletionWakeDiagnostic(e){console.info(JSON.stringify({event:e.event,sessionId:e.session.id,sessionName:e.session.name,canonicalStatusDelivered:e.canonicalStatusDelivered,requestedShortFactualSummary:e.followupSummaryRequired,completionKind:"terminal"}))}handleTurnEnd(e,r){if(e.status!=="running"){console.info(`[SessionManager] Suppressing turn-end wake for session ${e.id} (status=${e.status}) \u2014 terminal notification owns the completion path.`);return}if(!e.goalTaskId){if(r||e.pendingPlanApproval){this.emitWaitingForInput(e);return}if(e.worktreeStrategy==="ask"||e.worktreeStrategy==="delegate"){console.info(`[SessionManager] Suppressing turn-complete wake for session ${e.id} (worktreeStrategy=${e.worktreeStrategy}) \u2014 worktree notification will follow.`);return}this.deps.shouldEmitTurnCompleteWake(e)&&this.emitTurnComplete(e)}}async handleSessionTerminal(e){if(this.deps.persistSession(e),this.deps.clearWaitingTimestamp(e.id),e.goalTaskId){this.deps.clearRetryTimersForSession(e.id);return}let r={notificationSent:!1,worktreeRemoved:!1};e.worktreePath&&e.originalWorkdir&&(r=await this.deps.handleWorktreeStrategy(e));let n=!1;if(e.worktreePath&&e.originalWorkdir&&e.status==="failed"&&e.costUsd===0&&e.duration<3e4){let a=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),d=e.worktreeBranch,l=Ne(e);console.info(`[SessionManager] Early startup failure for "${e.name}" \u2014 auto-cleaning worktree (cost=$${e.costUsd.toFixed(2)}, duration=${e.duration}ms)`);let m=!1;if(a&&!l&&(m=tt(a,e.worktreePath)),a&&d&&!l&&m&&$t(a,d),m){for(let S of et(e))this.deps.updatePersistedSession(S,{worktreePath:void 0,worktreeBranch:void 0});n=!0}}let o=e.worktreeStrategy&&e.worktreeStrategy!=="off"&&e.worktreeStrategy!=="manual";if(!n&&e.worktreePath&&e.originalWorkdir){let a=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),d=Ne(e);r.worktreeRemoved?console.info(`[SessionManager] Worktree already removed for "${e.name}" during strategy handling.`):o?console.info(`[SessionManager] Keeping worktree alive for "${e.name}" (strategy=${e.worktreeStrategy}) \u2014 will be cleaned up on explicit resolution.`):a&&!d&&tt(a,e.worktreePath)}if(e.killReason==="done"){if(r.notificationSent||this.deps.hasTurnCompleteWakeMarker(e.id)||!this.deps.shouldEmitTerminalWake(e))return;this.emitCompleted(e);return}if(e.status==="completed"){if(!this.deps.shouldEmitTerminalWake(e))return;this.emitCompleted(e);return}if(e.status==="failed"){if(!this.deps.shouldEmitTerminalWake(e))return;let a=e.error||e.result?.is_error&&e.result.result||e.result?.result||this.deps.extractLastOutputLine(e)||`Session failed with no error details (session=${e.id}, subtype=${e.result?.subtype??"none"}, turns=${e.result?.num_turns??0})`;this.emitFailed(e,Fe(a,200),n);return}let i=`$${(e.costUsd??0).toFixed(2)}`,s=e.duration;if(e.killReason==="idle-timeout"){let a=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0;if(e.pendingPlanApproval){let d=e.actionablePlanDecisionVersion??e.planDecisionVersion,l=Rg(e,d);if(a==="delegate"){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",wakeMessage:["[DELEGATED PLAN APPROVAL REMINDER] Plan review is still pending after the session hit idle timeout.",`Name: ${e.name} | ID: ${e.id}`,this.deps.originThreadLine(e),"The agent already produced a plan and is waiting for a delegated decision.","Review privately first. Approve directly with agent_respond(..., approve=true, approval_rationale='...') if the plan is clearly within scope and low risk.","Escalate only if needed via agent_request_plan_approval(summary='...').","If you approve directly, follow up with a short user-facing explanation; the plugin's thumbs-up line is only the minimal approval acknowledgment.","If a canonical approval prompt was already posted for this plan version, do not restate it in plain text."].join(`
200
+ `),notifyUser:"never"}),this.deps.clearRetryTimersForSession(e.id);return}if(a==="ask"&&l){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",notifyUser:"never",wakeMessage:["[PLAN APPROVAL REMINDER] The user already has an actionable plan review prompt for this plan version.",`Name: ${e.name} | ID: ${e.id} | Plan v${d??"?"}`,this.deps.originThreadLine(e),"Do NOT post another approval summary unless canonical delivery is known to be missing."].join(`
201
+ `)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",userMessage:[`\u{1F4CB} [${e.name}] Plan v${d??"?"} still awaiting approval after idle timeout | ${i} | ${It(s)}`,"","The agent already produced a plan and is waiting for your decision.","Approve resumes the session and starts implementation.","Revise resumes it in plan mode so it can update the plan first.","Reject keeps the session stopped."].join(`
202
+ `),notifyUser:"always",buttons:a==="ask"&&!l?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:d}):void 0}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.dispatchSessionNotification(e,{label:"suspended",userMessage:`\u{1F4A4} [${e.name}] Suspended after idle timeout | ${i} | ${It(s)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(e.id,e)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.notifySession(e,`\u26D4 [${e.name}] ${io(e.killReason)} | ${i} | ${It(s)}`),this.deps.clearRetryTimersForSession(e.id)}emitWaitingForInput(e){if(!this.deps.debounceWaitingEvent(e.id))return;let r=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0,n=e.actionablePlanDecisionVersion??e.planDecisionVersion,o=e.pendingPlanApproval&&r==="ask"&&Rg(e,n),i=!e.pendingPlanApproval&&e.pendingInputState?.promptText?e.pendingInputState.promptText:this.deps.getOutputPreview(e,e.pendingPlanApproval&&r!=="delegate"?Number.POSITIVE_INFINITY:void 0),s=e.pendingPlanApproval&&r==="ask"&&!o?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:n}):!e.pendingPlanApproval&&e.pendingInputState?.options.length?this.deps.getQuestionButtons(e.id,e.pendingInputState.options.map(m=>({label:m}))):void 0,a=mb(e,n),d=ul({session:e,preview:i,planArtifact:a,originThreadLine:this.deps.originThreadLine(e),planApprovalMode:r,planApprovalButtons:s,questionButtons:e.pendingPlanApproval?void 0:s}),l=d.planReviewSummary??i;if(d.label==="plan-approval"&&r==="ask"&&o){this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,userMessages:d.userMessages,notifyUser:"never",buttons:d.buttons,wakeMessage:d.wakeMessage});return}if(d.label==="plan-approval"&&r==="ask"){this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,userMessages:d.userMessages,notifyUser:"always",buttons:d.buttons,hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"sending",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{canonicalPlanPromptVersion:n,approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:n,approvalPromptVersion:n,approvalPromptStatus:"failed",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,n,l),wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,n)});return}if(d.label==="plan-approval"){this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,wakeMessage:d.wakeMessage,notifyUser:"never",buttons:d.buttons});return}this.deps.dispatchSessionNotification(e,{label:d.label,userMessage:d.userMessage,notifyUser:"always",buttons:d.buttons,wakeMessageOnNotifyFailed:d.wakeMessage})}emitTurnComplete(e){console.info(`[SessionManager] turn-complete wake dispatching for session ${e.id} (turns=${e.result?.num_turns??0}, strategy=${e.worktreeStrategy??"none"})`);let r=tl({session:e,originThreadLine:this.deps.originThreadLine(e),preview:this.deps.getOutputPreview(e)});this.deps.dispatchSessionNotification(e,{label:"turn-complete",userMessage:r.userMessage,wakeMessage:r.wakeMessage,notifyUser:"always",onUserNotifyFailed:()=>{console.warn(`[SessionManager] turn-complete delivery failed for session ${e.id} \u2014 firing terminal notification as fallback`),this.deps.shouldEmitTerminalWake(e)&&this.emitCompleted(e)}})}emitCompleted(e){let r=this.deps.getOutputPreview(e),n=Zd({session:e,originThreadLine:this.deps.originThreadLine(e),preview:r}),o;this.deps.dispatchSessionNotification(e,{label:"completed",userMessage:n.userMessage,notifyUser:"always",wakeMessageOnNotifySuccess:n.wakeMessageOnNotifySuccess,wakeMessageOnNotifyFailed:n.wakeMessageOnNotifyFailed,hooks:{onNotifySucceeded:()=>{o=!0,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_succeeded",canonicalStatusDelivered:o,followupSummaryRequired:n.followupContract.requiresShortFactualSummary})},onNotifyFailed:()=>{o=!1,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_failed",canonicalStatusDelivered:o,followupSummaryRequired:n.followupContract.requiresShortFactualSummary})},onWakeSucceeded:()=>{this.logCompletionWakeDiagnostic({session:e,event:"completion_wake_succeeded",canonicalStatusDelivered:o,followupSummaryRequired:n.followupContract.requiresShortFactualSummary})}}})}emitFailed(e,r,n){let o=el({session:e,originThreadLine:this.deps.originThreadLine(e),errorSummary:r,preview:this.deps.getOutputPreview(e),worktreeAutoCleaned:n,failedButtons:this.deps.getResumeButtons(e.id,e)});this.deps.dispatchSessionNotification(e,{label:"failed",userMessage:o.userMessage,wakeMessage:o.wakeMessage,notifyUser:"always",buttons:o.buttons})}};ke();ut();import{existsSync as fb}from"fs";var xs=class{constructor(e){this.deps=e}deps;async dismissWorktree(e){let r=this.deps.getPersistedSession(e),n=this.deps.resolveActiveSession(e),o=n??r;if(!o)return`Error: Session "${e}" not found.`;let i=n?.worktreePath??r?.worktreePath,s=this.deps.resolveWorktreeRepoDir(n?.originalWorkdir??r?.workdir,i),a=n?.worktreeBranch??r?.worktreeBranch,d=n?.name??r?.name??e;if(!s)return`Error: No workdir found for session "${e}".`;let l=Ne(o);!l&&i&&fb(i)&&tt(s,i,{destructive:!0}),a&&$t(s,a);for(let S of et(n??r))this.deps.updatePersistedSession(S,{worktreeDisposition:"dismissed",worktreeDismissedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,worktreeState:"dismissed",lifecycle:"terminal",worktreePath:void 0,worktreeBranch:void 0,worktreeLifecycle:{state:"dismissed",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"dismiss",baseBranch:r?.worktreeLifecycle?.baseBranch,targetRepo:r?.worktreePrTargetRepo,pushRemote:r?.worktreePushRemote}});let m=l?`\u{1F5D1}\uFE0F [${d}] Branch \`${a??"unknown"}\` dismissed. Native backend worktree released for backend cleanup.`:`\u{1F5D1}\uFE0F [${d}] Branch \`${a??"unknown"}\` dismissed and permanently deleted.`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:re(n??r??{id:e})??e,sessionId:r?.sessionId,harnessSessionId:n?.harnessSessionId??r?.harnessSessionId,backendRef:n?.backendRef??r?.backendRef,route:n?.route??r?.route}),{label:"worktree-dismissed",userMessage:m,notifyUser:"always"}),m}snoozeWorktreeDecision(e){let r=this.deps.getPersistedSession(e);if(!r)return`Error: Session "${e}" not found.`;let n=new Date(Date.now()+1440*60*1e3).toISOString();for(let s of et(r))this.deps.updatePersistedSession(s,{worktreeDecisionSnoozedUntil:n,lastWorktreeReminderAt:new Date().toISOString()});let i=`\u23ED\uFE0F Reminder snoozed 24h for \`${r.worktreeBranch??"unknown"}\` (session: ${r.name})`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:re(r)??$(r)??r.harnessSessionId,sessionId:r.sessionId,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route}),{label:"worktree-snoozed",userMessage:i,notifyUser:"always"}),i}};var Tg=new Set(["starting","running"]),As=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>Tg.has(e.status)).length}uniqueName(e){let r=new Set([...this.sessions.values()].filter(o=>Tg.has(o.status)).map(o=>o.name));if(!r.has(e))return e;let n=2;for(;r.has(`${e}-${n}`);)n+=1;return`${e}-${n}`}add(e){this.sessions.set(e.id,e)}remove(e){this.sessions.delete(e)}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()]}};var Rs=class{constructor(e){this.deps=e}deps;initializeSession(e,r,n,o={}){if(this.deps.hydrateSpawnedSession(e,r,n),e.on("statusChange",(i,s)=>{s==="running"&&e.harnessSessionId?this.deps.markRunning(e):(s==="completed"||s==="failed"||s==="killed")&&this.deps.handleTerminal(e).catch(a=>{console.error(`[SessionRuntimeBootstrap] handleTerminal threw for session ${e.id}:`,a)})}),e.on("turnEnd",(i,s)=>{this.deps.handleTurnEnd(e,s)}),e.start(),o.notifyLaunch!==!1){let i=this.deps.formatLaunchWorkdirLabel(e),s=`\u{1F680} [${e.name}] Launched | ${i} | ${e.model??"default"}`;this.deps.notifySession(e,s,"launch")}return e}};var Ts=class{buildNoChangeNotification(e){let{session:r,nativeBackendWorktree:n,cleanupSucceeded:o,worktreePath:i,preview:s,originThreadLine:a}=e,d=o?n?"native backend worktree released for backend cleanup":"worktree cleaned up":`cleanup failed; worktree still exists at ${i}`;return{label:o?"worktree-no-changes":"worktree-no-changes-cleanup-failed",userMessage:o?n?`\u2139\uFE0F [${r.name}] Session completed with no changes \u2014 native backend worktree released for backend cleanup`:`\u2139\uFE0F [${r.name}] Session completed with no changes \u2014 worktree cleaned up`:`\u26A0\uFE0F [${r.name}] Session completed with no changes, but worktree cleanup failed. Worktree still exists at ${i}`,wakeMessage:ol({sessionName:r.name,sessionId:r.id,cleanupSummary:d,preview:s,originThreadLine:a,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,approvalExecutionState:r.approvalExecutionState,approvalState:r.approvalState,planApproval:r.planApproval,approvalPromptStatus:r.approvalPromptStatus,approvalPromptMessageKind:r.approvalPromptMessageKind,approvalPromptDeliveredAt:r.approvalPromptDeliveredAt}),notifyUser:"always"}}buildAskNotification(e){let{session:r,branchName:n,baseBranch:o,diffSummary:i,buttons:s}=e,a=il(i),d=i.commitMessages.slice(0,5).map(S=>`\u2022 ${S.hash} ${S.message} (${S.author})`),l=i.commits>5?`...and ${i.commits-5} more`:"",m=r.worktreePrTargetRepo?`Branch: \`${n}\` \u2192 \`${o}\` | PR target: ${r.worktreePrTargetRepo}`:`Branch: \`${n}\` \u2192 \`${o}\``;return{label:"worktree-merge-ask",userMessage:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",m,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"",...a.length>0?["Summary:",...a.map(S=>`- ${S}`),""]:[],"Recent commits:",...d,...l?[l]:[],"",`\u26A0\uFE0F Discard will permanently delete branch \`${n}\` and all local changes. This cannot be undone.`].join(`
203
+ `),notifyUser:"always",buttons:s,wakeMessageOnNotifySuccess:["Worktree decision buttons delivered to the user.",`Session: ${r.name} | ID: ${r.id}`,m,"Wait for their button callback \u2014 do NOT act on this worktree yourself."].join(`
204
+ `),wakeMessageOnNotifyFailed:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",m,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
205
+ `)}}buildDelegateNotification(e){let{session:r,branchName:n,baseBranch:o,diffSummary:i}=e,s=i.commitMessages.slice(0,5).map(l=>`\u2022 ${l.hash} ${l.message} (${l.author})`),a=i.commits>5?`...and ${i.commits-5} more`:void 0,d=r.prompt?r.prompt.slice(0,500):"(no prompt)";return{label:"worktree-delegate",wakeMessage:rl({sessionName:r.name,sessionId:r.id,branchName:n,baseBranch:o,promptSnippet:d,commitLines:s,moreNote:a,diffSummary:i}),notifyUser:"never"}}};$i();ut();var Ms=class t{timers=new Map;disposed=!1;static MAX_DELAY_MS=2147483647;schedule(e,r,n){if(this.disposed)return;this.cancel(e);let o=Math.max(0,r-Date.now()),i=setTimeout(()=>{if(this.timers.delete(e),!this.disposed){if(r-Date.now()>0){this.schedule(e,r,n);return}n()}},Math.min(o,t.MAX_DELAY_MS));i.unref?.(),this.timers.set(e,i)}cancel(e){let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}cancelPrefix(e){for(let r of this.timers.keys())r.startsWith(e)&&this.cancel(r)}dispose(){this.disposed=!0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};import{unlinkSync as gb}from"fs";var Mg=new Set(["completed","failed","killed"]),hb=new Set(["starting","running"]),Sb=5e3,Cg=10080*60*1e3,yb=300*1e3,_g="tmp-output:cleanup",Cs=class{registry;sessions;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueues=new Map;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;interactions;notifications;worktrees;questions;reminders;lifecycle;restore;stateSync;references;worktreeStrategy;worktreeDecisions;runtimeBootstrap;worktreeMessages;maintenance=new Ms;constructor(e=20,r=50,n={}){this.maxSessions=e,this.maxPersistedSessions=r,this.registry=new As,this.sessions=this.registry.sessions,this.store=new ps(n.store),this.metrics=new cs,this.wakeDispatcher=new Ss,this.interactions=new ys(this.store.actionTokenStore,ir),this.references=new ts(this.sessions,this.store),this.stateSync=new es({store:this.store,sessions:this.sessions,resolveSession:o=>this.references.resolveActive(o)}),this.notifications=new ks(this.wakeDispatcher,(o,i)=>this.stateSync.applySessionPatch(o,i)),this.store.onActionTokensChanged(()=>this.syncActionTokenExpiryDeadline()),this.worktrees=new vs,this.restore=new Zi(o=>this.store.getPersistedSession(o)),this.worktreeMessages=new Ts,this.worktreeStrategy=new os({shouldRunWorktreeStrategy:o=>this.shouldRunWorktreeStrategy(o),isAlreadyMerged:o=>this.isAlreadyMerged(o),resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),getWorktreeCompletionState:(o,i,s,a)=>this.getWorktreeCompletionState(o,i,s,a),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),dispatchSessionNotification:(o,i)=>this.dispatchSessionNotification(o,i),getOutputPreview:(o,i)=>this.getOutputPreview(o,i),originThreadLine:o=>this.originThreadLine(o),getWorktreeDecisionButtons:o=>this.getWorktreeDecisionButtons(o),makeOpenPrButton:o=>this.makeActionButton(o,"worktree-create-pr","Open PR"),worktreeMessages:this.worktreeMessages,enqueueMerge:(o,i,s)=>this.enqueueMerge(o,i,s),mergeBranch:Ci,spawnConflictResolver:async({session:o,worktreePath:i,prompt:s})=>this.spawn({prompt:s,workdir:i,name:`${o.name}-conflict-resolver`,harness:o.harnessName||Pe(),model:o.model,reasoningEffort:o.reasoningEffort,permissionMode:"bypassPermissions",multiTurn:!0,worktreeStrategy:"off",autoMergeParentSessionId:o.id,route:o.route,originChannel:o.originChannel,originThreadId:o.originThreadId,originAgentId:o.originAgentId,originSessionKey:o.originSessionKey},{notifyLaunch:!1}),runAutoPr:async(o,i)=>{let{makeAgentPrTool:s}=await Promise.resolve().then(()=>(Gi(),Rf));return{success:(await s().execute("auto-pr",{session:o.id,base_branch:i}))?.meta?.success===!0}}}),this.questions=new Ps(this.pendingAskUserQuestions,(o,i)=>this.dispatchSessionNotification(o,i),o=>{this.lastWaitingEventTimestamps.delete(o)},(o,i)=>this.interactions.getQuestionButtons(o,i)),this.reminders=new Is(o=>this.buildRoutingProxy(o),(o,i)=>this.notifications.dispatch(o,i),(o,i)=>this.updatePersistedSession(o,i),o=>this.getWorktreeDecisionButtons(o)),this.lifecycle=new bs({persistSession:o=>this.persistSession(o),clearWaitingTimestamp:o=>{this.lastWaitingEventTimestamps.delete(o)},handleWorktreeStrategy:o=>this.handleWorktreeStrategy(o),resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),dispatchSessionNotification:(o,i)=>this.dispatchSessionNotification(o,i),notifySession:(o,i,s)=>this.notifySession(o,i,s),clearRetryTimersForSession:o=>this.wakeDispatcher.clearRetryTimersForSession(o),hasTurnCompleteWakeMarker:o=>this.lastTurnCompleteMarkers.has(o),shouldEmitTurnCompleteWake:o=>this.shouldEmitTurnCompleteWake(o),shouldEmitTerminalWake:o=>this.shouldEmitTerminalWake(o),resolvePlanApprovalMode:o=>this.resolvePlanApprovalMode(o),getPlanApprovalButtons:(o,i)=>this.interactions.getPlanApprovalButtons(o,i),getResumeButtons:(o,i)=>this.interactions.getResumeButtons(o,i),getQuestionButtons:(o,i)=>this.interactions.getQuestionButtons(o,i),extractLastOutputLine:o=>this.extractLastOutputLine(o),getOutputPreview:(o,i)=>this.getOutputPreview(o,i),originThreadLine:o=>this.originThreadLine(o),debounceWaitingEvent:o=>this.debounceWaitingEvent(o),isAlreadyMerged:o=>this.isAlreadyMerged(o)}),this.worktreeDecisions=new xs({getPersistedSession:o=>this.store.getPersistedSession(o),resolveActiveSession:o=>this.references.resolveActive(o),resolveWorktreeRepoDir:(o,i)=>this.resolveWorktreeRepoDir(o,i),updatePersistedSession:(o,i)=>this.updatePersistedSession(o,i),dispatchNotification:(o,i)=>this.notifications.dispatch(o,i),buildRoutingProxy:o=>this.buildRoutingProxy(o)}),this.runtimeBootstrap=new Rs({hydrateSpawnedSession:(o,i,s)=>{this.restore.hydrateSpawnedSession(o,i,s)},markRunning:o=>{this.store.markRunning(o),this.onPersistedSessionChanged(this.store.getPersistedSession(o.id))},handleTerminal:async o=>this.onSessionTerminal(o),handleTurnEnd:(o,i)=>this.onTurnEnd(o,i),formatLaunchWorkdirLabel:o=>this.formatLaunchWorkdirLabel(o),notifySession:(o,i,s)=>this.notifySession(o,i,s)})}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(e){return this.registry.uniqueName(e)}persistedMaintenanceRef(e){return e.sessionId??$(e)??e.harnessSessionId}runtimeGcKey(e){return`runtime-gc:${e}`}persistedMaintenanceKey(e,r){return`persisted:${e}:${r}`}runtimeGcMaxAgeMs(){return(_.sessionGcAgeMinutes??1440)*6e4}syncRuntimeGcDeadline(e){if(!e.completedAt)return;let r=this.runtimeGcKey(e.id);this.maintenance.schedule(r,e.completedAt+this.runtimeGcMaxAgeMs(),()=>{let n=this.sessions.get(e.id);if(!n||!n.completedAt)return;let o=this.runtimeGcMaxAgeMs();if(!this.store.shouldGcActiveSession(n,Date.now(),o)){this.syncRuntimeGcDeadline(n);return}this.registry.remove(e.id),this.persistSession(n,{scheduleRuntimeGc:!1}),this.lastWaitingEventTimestamps.delete(e.id),this.lastTurnCompleteMarkers.delete(e.id),this.lastTerminalWakeMarkers.delete(e.id)})}cancelPersistedMaintenance(e){let r=this.persistedMaintenanceRef(e);r&&this.maintenance.cancelPrefix(`persisted:${r}:`)}onPersistedSessionChanged(e){e&&(this.syncPersistedSessionMaintenance(e),this.enforcePersistedRetention())}isLegacyResolvedWorktree(e){return e.worktreeMerged===!0||e.worktreeDisposition==="dismissed"||e.worktreeDisposition==="no-change-cleaned"||e.worktreeState==="merged"||e.worktreeState==="dismissed"}syncPersistedSessionMaintenance(e){let r=this.persistedMaintenanceRef(e);if(!r)return;this.maintenance.cancel(this.persistedMaintenanceKey(r,"worktree-reminder"));let n=this.reminders.getNextReminderAt(e);n!=null&&this.schedulePersistedWorktreeReminder(r,n),this.maintenance.cancel(this.persistedMaintenanceKey(r,"worktree-retention"));let o=Zn(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),i=e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0),s=this.isLegacyResolvedWorktree(e);if((o.cleanupSafe||s)&&typeof i=="string"){let a=new Date(i).getTime();Number.isFinite(a)&&this.maintenance.schedule(this.persistedMaintenanceKey(r,"worktree-retention"),a+Cg,()=>{let d=this.store.getPersistedSession(r);d&&this.reconcileResolvedWorktreeRetention(d,Date.now())})}}schedulePersistedWorktreeReminder(e,r){let n=this.persistedMaintenanceKey(e,"worktree-reminder");this.maintenance.schedule(n,r,()=>{let o=this.store.getPersistedSession(e);if(!o||this.reminders.sendReminderIfDue(o,Date.now()))return;let s=this.reminders.getNextReminderAt(o);s!=null&&this.schedulePersistedWorktreeReminder(e,Math.max(s,Date.now()+yb))})}reconcileResolvedWorktreeRetention(e,r){let n=Zn(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),o=e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0),i=o?new Date(o).getTime():0,s=this.isLegacyResolvedWorktree(e);if(!(!n.cleanupSafe&&!s||!i||r-i<Cg))try{if(!e.worktreePath&&!Ne(e))return;let a=this.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!a)return;let d=Ne(e)?!1:tt(a,e.worktreePath);if(!Ne(e)&&!d)return;for(let l of et(e))this.updatePersistedSession(l,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",worktreeLifecycle:{...e.worktreeLifecycle??n.lifecycle,state:n.derivedState,updatedAt:new Date(r).toISOString(),resolvedAt:e.worktreeLifecycle?.resolvedAt??new Date(r).toISOString(),resolutionSource:e.worktreeLifecycle?.resolutionSource??"maintenance",notes:n.reasons}})}catch(a){console.warn(`[SessionManager] Failed maintenance cleanup for worktree ${e.worktreePath}: ${a instanceof Error?a.message:String(a)}`)}}syncActionTokenExpiryDeadline(){let e="tokens:expiry";this.maintenance.cancel(e);let r=this.store.getNextActionTokenExpiry();r!=null&&this.maintenance.schedule(e,r,()=>{this.store.purgeExpiredActionTokens(Date.now())})}syncTmpOutputCleanupDeadline(e=Date.now()){this.maintenance.cancel(_g);let r=this.store.getNextTmpOutputCleanupAt(e);r!=null&&this.maintenance.schedule(_g,r,()=>{let n=Date.now();this.store.cleanupTmpOutputFiles(n),this.syncTmpOutputCleanupDeadline(n)})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.store.hasOutputPathReference(e)))try{gb(e)}catch{}}enforcePersistedRetention(){let e=this.store.evictOldestPersisted(this.maxPersistedSessions);for(let r of e)this.cancelPersistedMaintenance(r),r.sessionId&&this.maintenance.cancel(this.runtimeGcKey(r.sessionId)),this.cleanupOutputPathIfUnreferenced(r.outputPath)}bootstrapMaintenanceSchedules(){let e=Date.now();this.store.cleanupTmpOutputFiles(e);for(let r of this.store.listPersistedSessions())this.syncPersistedSessionMaintenance(r);this.syncActionTokenExpiryDeadline(),this.store.cleanupOrphanOutputFiles(),this.syncTmpOutputCleanupDeadline(e)}disposeMaintenance(){this.maintenance.dispose()}spawn(e,r={}){if(this.registry.activeSessionCount()>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);if(e.sessionIdOverride){let y=this.registry.get(e.sessionIdOverride);if(y?.status==="starting"||y?.status==="running")throw new Error(`Cannot reuse session ID ${e.sessionIdOverride}: that session is still ${y.status}.`);y&&this.registry.remove(y.id),this.lastWaitingEventTimestamps.delete(e.sessionIdOverride),this.lastTurnCompleteMarkers.delete(e.sessionIdOverride),this.lastTerminalWakeMarkers.delete(e.sessionIdOverride),this.maintenance.cancel(this.runtimeGcKey(e.sessionIdOverride))}let o=e.name||uf(e.prompt),i=this.uniqueName(o);if(i!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${i}" (active session with same name exists)`),!e.route?.provider||!e.route.target)throw new Error(`Cannot launch session "${i}": missing explicit route metadata.`);let s=this.restore.prepareSpawn(e,i),a=e.harness??"claude-code",d=this,l,m=a==="claude-code"&&!e.canUseTool?async(y,f)=>{if(!l)throw new Error("canUseTool called before session ID was set");return d.handleAskUserQuestion(l,f)}:e.canUseTool,S=new Oi({...e,workdir:s.actualWorkdir,systemPrompt:s.effectiveSystemPrompt,canUseTool:m},i);return l=S.id,this.registry.add(S),this.metrics.incrementLaunched(),this.runtimeBootstrap.initializeSession(S,s,e,r)}async spawnAndAwaitRunning(e,r={}){let n=this.spawn(e,r);return await this.waitForRunningSession(n),n}async waitForRunningSession(e){if(e.status==="running")return;if(Mg.has(e.status))throw new Error(this.describeLaunchFailure(e));let r=e.on?.bind(e),n=e.off?.bind(e)??e.removeListener?.bind(e);if(!r||!n)throw new Error(`Session ${e.name} [${e.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(d,l)=>{if(l==="running"){a(),o();return}Mg.has(l)&&(a(),i(new Error(this.describeLaunchFailure(e))))},a=()=>{n("statusChange",s)};r("statusChange",s)})}describeLaunchFailure(e){let r=e.killReason?` (reason: ${e.killReason})`:"",n=e.error||e.result?.result||`status=${e.status}${r}`;return`Session ${e.name} [${e.id}] failed to start: ${n}`}formatLaunchResult(e,r){return ti({prompt:e.prompt,workdir:e.workdir,harness:e.harness,permissionMode:e.permissionMode??_.permissionMode,planApproval:e.planApproval,resumeSessionId:e.resumeSessionId,forkSession:e.forkSession,forceNewSession:e.forceNewSession,clearedPersistedCodexResume:e.clearedPersistedCodexResume},r)}shouldRunWorktreeStrategy(e){let r=e.lifecycle;return!(r==="starting"||r==="awaiting_plan_decision"||r==="awaiting_user_input"||e.pendingPlanApproval)}makeActionButton(e,r,n,o={}){return this.interactions.makeActionButton(e,r,n,o)}consumeActionToken(e){return this.interactions.consumeActionToken(e)}getActionToken(e){return this.interactions.getActionToken(e)}clearPlanDecisionTokens(e,r){this.interactions.clearPlanDecisionTokens(e,r)}hasProvablePlanReviewPrompt(e,r){return r!=null&&e.approvalPromptRequiredVersion===r&&(e.approvalPromptStatus==="delivered"||e.approvalPromptStatus==="fallback_delivered")}buildPlanApprovalWakeText(e,r,n=!1){return[n?"Plan review fallback text delivered to the user because interactive buttons could not be delivered.":"Plan approval buttons delivered to the user.",`Session: ${e.name} | ID: ${e.id} | Plan v${r??"?"}`,`Wait for their ${n?"explicit reply":"button callback"} \u2014 do NOT approve or reject this plan yourself.`].join(`
206
+ `)}buildPlanApprovalDeliveryFailureWake(e,r){return["[PLAN APPROVAL DELIVERY FAILED] The plugin could not deliver the canonical plan review buttons or the explicit fallback text to the user.",`Name: ${e.name} | ID: ${e.id} | Plan v${r??"?"}`,e.originThreadId!=null?`Origin thread: ${e.originThreadId}`:"","","No user-visible actionable review prompt is confirmed for this plan version.","Intervene manually before assuming the user saw the plan review request."].filter(Boolean).join(`
207
+ `)}dispatchPlanApprovalFallback(e,r,n){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",userMessage:so({session:e,summary:n}),notifyUser:"always",hooks:{onNotifyStarted:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"sending",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:r,approvalPromptVersion:r,approvalPromptStatus:"failed",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText(e,r,!0),wakeMessageOnNotifyFailed:this.buildPlanApprovalDeliveryFailureWake(e,r)})}getWorktreeDecisionButtons(e){let r=this.resolve(e)??this.getPersistedSession(e);if(!(!r||r.worktreeStrategy==="delegate"))return this.interactions.getWorktreeDecisionButtons(e,r)}getWorktreeCompletionState(e,r,n,o){return this.worktrees.getCompletionState(e,r,n,o)}notifyWorktreeOutcome(e,r){this.notifications.notifyWorktreeOutcome(e,r)}requestPlanApprovalFromUser(e,r){let n=r.trim();if(!n)return"Error: summary must not be empty.";let o=dl(n),i=this.resolve(e),s=i?void 0:this.getPersistedSession(e),a=i??s;if(!a)return`Error: Session "${e}" not found.`;if(!a.pendingPlanApproval)return`Error: Session "${e}" is not awaiting plan approval.`;let d=re(i??s??{id:e})??e;if(this.resolvePlanApprovalMode(a)!=="delegate")return`Error: Session "${e}" already uses direct user plan approval. Do not send a duplicate approval prompt.`;let l=a.actionablePlanDecisionVersion??a.planDecisionVersion;if(this.hasProvablePlanReviewPrompt(a,l))return[`An actionable plan review prompt already exists for session ${a.name} [${d}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ");if(a.deliveryState==="notifying")return[`A plan approval prompt is already being delivered for session ${a.name} [${d}].`,"Wait for delivery to finish before retrying."].join(" ");let m=this.interactions.getPlanApprovalButtons(d,{...a,planDecisionVersion:l}),S=[`\u{1F4CB} [${a.name}] Plan v${l??"?"} needs your decision:`,"","Why this was escalated:","",o,"","Choose Approve, Revise, or Reject below."].join(`
208
+ `);return this.notifications.dispatch(this.buildRoutingProxy({id:d,name:a.name,sessionId:s?.sessionId,harnessSessionId:i?.harnessSessionId??s?.harnessSessionId,backendRef:i?.backendRef??s?.backendRef,route:i?.route??s?.route}),{label:"plan-approval",userMessage:S,notifyUser:"always",buttons:m,hooks:{onNotifyStarted:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptStatus:"sending",approvalPromptVersion:l,approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.updatePersistedSession(d,{canonicalPlanPromptVersion:l,approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(d,{approvalPromptRequiredVersion:l,approvalPromptVersion:l,approvalPromptStatus:"failed",approvalPromptTransport:"direct-telegram",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(this.buildRoutingProxy({id:d,name:a.name,sessionId:s?.sessionId,harnessSessionId:i?.harnessSessionId??s?.harnessSessionId,backendRef:i?.backendRef??s?.backendRef,route:i?.route??s?.route}),l,o),wakeMessageOnNotifySuccess:this.buildPlanApprovalWakeText({id:d,name:a.name},l)}),[`Canonical plan approval prompt sent for session ${a.name} [${d}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ")}buildRoutingProxy(e){return{id:re(e)??$(e)??e.harnessSessionId??"unknown-session",name:e.name,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef?{...e.backendRef}:void 0,route:e.route}}resolveWorktreeRepoDir(e,r){return e&&(!r||!Xi(e,r))||!r?e:xi(r)??e}formatLaunchWorkdirLabel(e){if(!e.worktreePath)return e.workdir;let r=this.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath);return!r||r===e.worktreePath?e.worktreePath:`${e.worktreePath} (worktree of ${r})`}async dismissWorktree(e){return this.worktreeDecisions.dismissWorktree(e)}snoozeWorktreeDecision(e){return this.worktreeDecisions.snoozeWorktreeDecision(e)}async handleWorktreeStrategy(e){return this.worktreeStrategy.handleWorktreeStrategy(e)}async onSessionTerminal(e){if(e.autoMergeParentSessionId){await this.handleAutoMergeResolverTerminal(e);return}return this.lifecycle.handleSessionTerminal(e)}async handleAutoMergeResolverTerminal(e){this.persistSession(e),this.lastWaitingEventTimestamps.delete(e.id),this.wakeDispatcher.clearRetryTimersForSession(e.id);let r=e.autoMergeParentSessionId;if(!r)return;let n=this.resolve(r),o=this.getPersistedSession(r),i=n??(o?this.buildRoutingProxy({id:o.sessionId,name:o.name,sessionId:o.sessionId,harnessSessionId:o.harnessSessionId,backendRef:o.backendRef,route:o.route}):void 0);if(!i){console.warn(`[SessionManager] Auto-merge resolver ${e.id} completed, but original session ${r} could not be found.`);return}if(e.status==="completed"&&n){this.updatePersistedSession(r,{autoMergeResolverSessionId:void 0}),await this.handleWorktreeStrategy(n);return}let s=n?.worktreeBranch??o?.worktreeBranch??"unknown",a=n?.worktreePath??o?.worktreePath??"(unknown worktree)",d=n?.worktreeBaseBranch??o?.worktreeBaseBranch,l=n?.worktreePrTargetRepo??o?.worktreePrTargetRepo,m=n?.worktreePushRemote??o?.worktreePushRemote;this.updatePersistedSession(r,ns({worktreeBaseBranch:d,worktreePrTargetRepo:l,worktreePushRemote:m},{clearResolverSessionId:!0,notes:[e.status==="completed"?"auto_merge_conflict_resolver_completed_without_retry_target":"auto_merge_conflict_resolver_failed"]})),this.dispatchSessionNotification(i,{label:"worktree-merge-conflict-resolver-failed",userMessage:[`\u26A0\uFE0F [${i.name}] Auto-merge conflict resolution did not complete successfully.`,`Branch \`${s}\` was preserved for manual follow-up in ${a}.`,e.status==="completed"?"The resolver finished, but the original session could not be resumed for the merge retry.":`Resolver session ${e.name} ended with status=${e.status}.`].join(`
209
+ `),buttons:[[this.makeActionButton(r,"worktree-create-pr","Open PR")]]})}getStoppedStatusLabel(e){return io(e)}persistSession(e,r={}){let n=r.scheduleRuntimeGc??!0;this.store.hasRecordedSession(e.id)||this.metrics.recordSession(e),this.store.persistTerminal(e),n&&this.syncRuntimeGcDeadline(e),this.onPersistedSessionChanged(this.store.getPersistedSession(e.id)),this.syncTmpOutputCleanupDeadline()}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(e){this.metrics.recordSession(e)}notifySession(e,r,n="notification"){this.dispatchSessionNotification(e,{label:n,userMessage:r,notifyUser:"always"})}sendMonitorReport(e){let r=this.interactions.getMonitorReportButtons({reportId:e.reportId,route:e.route,planName:e.planName,planPrompt:e.planPrompt,planWorkdir:e.planWorkdir});this.dispatchSessionNotification(this.buildRoutingProxy({id:e.reportId,route:e.route}),{label:"monitor-report",userMessage:e.text,notifyUser:"always",buttons:r})}emitGoalTaskUpdate(e,r,n="goal-task"){let o=this.buildRoutingProxy({id:e.sessionId??e.id,route:e.route});o.originChannel=e.originChannel,o.originThreadId=e.originThreadId,o.originSessionKey=e.originSessionKey,this.dispatchSessionNotification(o,{label:n,userMessage:r,notifyUser:"always"})}launchMonitorPlan(e){let r=e.route??{provider:"system",target:"system"};return this.spawn({prompt:e.prompt,workdir:e.workdir,name:e.name,harness:Pe(),permissionMode:"plan",planApproval:"ask",worktreeStrategy:"off",multiTurn:!0,route:r,originChannel:this.originChannelFromRoute(r),originThreadId:r.threadId,originSessionKey:r.sessionKey})}dispatchSessionNotification(e,r){this.notifications.dispatch(e,r)}originChannelFromRoute(e){return e.accountId?`${e.provider}|${e.accountId}|${e.target}`:`${e.provider}|${e.target}`}debounceWaitingEvent(e){let r=Date.now(),n=this.lastWaitingEventTimestamps.get(e);return n&&r-n<Sb?!1:(this.lastWaitingEventTimestamps.set(e,r),!0)}originThreadLine(e){return e.originThreadId!=null?`Session origin thread: ${e.originThreadId}`:""}extractLastOutputLine(e){return e.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(e,r=1e3){let n=!Number.isFinite(r),o=typeof e.getOutput=="function"?e.getOutput():[],i=n?o.join(`
210
+ `):this.selectCompletionPreviewSource(e);return n?i:i.length>r?this.shouldPreferTailPreview(e)?cf(i,r):mf(i,r):i}selectCompletionPreviewSource(e){let r=typeof e.getOutput=="function"?e.getOutput():[],n=r.join(`
211
+ `).trim();return n?this.shouldPreferTailPreview(e)?this.extractLastSubstantiveBlock(n)??n:r.slice(-20).join(`
212
+ `):""}shouldPreferTailPreview(e){if(e.status==="completed"||e.killReason==="done")return!0;let r=e;return r.approvalState==="approved"||r.planModeApproved===!0||(r.planDecisionVersion??0)>0}extractLastSubstantiveBlock(e){let n=e.split(/\n\s*\n+/).map(o=>o.trim()).filter(o=>/[A-Za-z0-9]/.test(o)).at(-1);if(n)return n.length>=120||n.includes(`
213
+ `)?n:void 0}triggerAgentEvent(e){this.lifecycle.emitCompleted(e)}triggerFailedEvent(e,r,n=!1){this.lifecycle.emitFailed(e,r,n)}triggerWaitingForInputEvent(e){this.lifecycle.emitWaitingForInput(e)}resolvePlanApprovalMode(e){return e.planApproval??_.planApproval??"delegate"}onTurnEnd(e,r){this.lifecycle.handleTurnEnd(e,r)}shouldEmitTurnCompleteWake(e){let r=`${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(e.id)===r?(console.info(`[SessionManager] shouldEmitTurnCompleteWake: debounced for session ${e.id} (marker unchanged: ${r})`),!1):(this.lastTurnCompleteMarkers.set(e.id,r),!0)}shouldEmitTerminalWake(e){let r=`${e.status}|${e.completedAt??0}|${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.killReason}`;return this.lastTerminalWakeMarkers.get(e.id)===r?!1:(this.lastTerminalWakeMarkers.set(e.id,r),!0)}triggerTurnCompleteEventWithSignal(e){this.lifecycle.emitTurnComplete(e)}resolve(e){return this.references.resolveActive(e)}get(e){return this.registry.get(e)}list(e){let r=this.registry.list();return e&&e!=="all"&&(r=r.filter(n=>n.status===e)),r.sort((n,o)=>o.startedAt-n.startedAt)}kill(e,r){let n=this.registry.get(e);return n?(n.kill(r??"user"),!0):!1}killAll(e="user"){for(let r of this.sessions.values())hb.has(r.status)&&this.kill(r.id,e)}resolveBackendConversationId(e){return this.references.resolveBackendConversationId(e)}resolveHarnessSessionId(e){return this.resolveBackendConversationId(e)}getPersistedSession(e){return this.references.getPersistedSession(e)}isAlreadyMerged(e){if(!e)return!1;let r=this.store.getPersistedSession(e);return r?.worktreeMerged===!0||r?.worktreeLifecycle?.state==="merged"||r?.worktreeLifecycle?.state==="released"}async enqueueMerge(e,r,n){let o=this.mergeQueues.get(e);o!==void 0&&n&&n();let i=(o??Promise.resolve()).catch(()=>{}).then(()=>r()),s=i.catch(()=>{});return this.mergeQueues.set(e,s),s.finally(()=>{this.mergeQueues.get(e)===s&&this.mergeQueues.delete(e)}),i}updatePersistedSession(e,r){let n=this.stateSync.applySessionPatch(e,r);return n&&this.onPersistedSessionChanged(this.store.getPersistedSession(e)),n}listPersistedSessions(){return this.store.listPersistedSessions()}async handleAskUserQuestion(e,r){let n=this.sessions.get(e);if(!n)throw new Error(`Session "${e}" not found for AskUserQuestion intercept`);return this.questions.handleAskUserQuestion(n,r)}resolveAskUserQuestion(e,r){this.questions.resolveAskUserQuestion(e,r)}async resolvePendingInputOption(e,r){let n=this.sessions.get(e);return n&&await n.submitPendingInputOption(r)?(this.lastWaitingEventTimestamps.delete(e),!0):(this.questions.resolveAskUserQuestion(e,r),!0)}dispose(){this.disposeMaintenance(),this.questions.dispose(),this.notifications.dispose()}};Y();var $g;function _s(t){if(t&&typeof t=="object"){$g=t;return}$g=void 0}Re();import{definePluginEntry as Eg}from"openclaw/plugin-sdk/core";function Ib(t){let e=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"168",10)||168,r=e*60*60*1e3,n=Date.now()-r,o=new Set(t.listPersistedSessions().map(d=>d.worktreePath).filter(d=>typeof d=="string"&&d.length>0)),i=new Set,s=process.env.OPENCLAW_WORKTREE_DIR??_.worktreeDir;if(s)i.add(s);else for(let d of t.listPersistedSessions())if(d.workdir)try{let l=wb("git",["rev-parse","--show-toplevel"],{cwd:d.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();l&&i.add(Og(l,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let d of i)try{let l=kb(d);for(let m of l){if(!m.startsWith("openclaw-worktree-"))continue;let S=Og(d,m);try{let y=vb(S);if(!y.isDirectory()||y.mtimeMs>n||o.has(S))continue;Pb(S,{recursive:!0,force:!0}),a++}catch(y){console.warn(`[index] Failed to clean up orphaned worktree ${S}: ${y instanceof Error?y.message:String(y)}`)}}}catch{}a>0&&console.info(`[index] Cleaned up ${a} orphaned worktree(s) at startup (age > ${e}h)`)}function bb(t){let e=null,r=null,n=t.registerTool;_s(t.runtime),n(o=>Um(o),{optional:!1}),n(o=>Sf(o),{optional:!1}),n(o=>yf(o),{optional:!1}),n(o=>Wi(o),{optional:!1}),n(o=>wf(o),{optional:!1}),n(o=>If(o),{optional:!1}),n(o=>bf(o),{optional:!1}),n(o=>xf(o),{optional:!1}),n(o=>ji(o),{optional:!1}),n(o=>ro(o),{optional:!1}),n(o=>Tf(o),{optional:!1}),n(o=>Mf(o),{optional:!1}),n(o=>Cf(o),{optional:!1}),n(o=>$f(o),{optional:!1}),n(o=>Ef(o),{optional:!1}),t.registerInteractiveHandler(Kd("telegram")),t.registerInteractiveHandler(Kd("discord")),Of(t),Df(t),Nf(t),Ff(t),Lf(t),Wf(t),Bf(t),Uf(t),Kf(t),t.registerService({id:"openclaw-code-agent",start:o=>{let i=t.pluginConfig??{};sm(i),_s(t.runtime),e=new Cs(_.maxSessions,_.maxPersistedSessions),r=new Yi(e),hd(e),Sd(r),r.start(),Ib(e),e.bootstrapMaintenanceSchedules()},stop:()=>{r&&r.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),r=null,e=null,_s(void 0),Sd(null),hd(null)}})}var yG=Eg({id:"openclaw-code-agent",name:"OpenClaw Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:bb});export{yG as default,bb as register};