openclaw-code-agent 3.0.0 → 3.1.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/README.md +80 -515
- package/dist/index.js +112 -107
- package/openclaw.plugin.json +12 -35
- package/package.json +13 -6
- package/skills/code-agent-orchestration/SKILL.md +146 -435
package/dist/index.js
CHANGED
|
@@ -1,59 +1,26 @@
|
|
|
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
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
`)
|
|
6
|
-
`)}function
|
|
7
|
-
`),n=[],
|
|
8
|
-
`)}
|
|
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 uf=Object.defineProperty;var u=(e,t)=>()=>(e&&(t=e(e=0)),t);var Hn=(e,t)=>{for(var r in t)uf(e,r,{get:t[r],enumerable:!0})};var ve={};Hn(ve,{HasPropertyKey:()=>Gn,IsArray:()=>ue,IsAsyncIterator:()=>rs,IsBigInt:()=>Qr,IsBoolean:()=>Rt,IsDate:()=>Xt,IsFunction:()=>ns,IsIterator:()=>os,IsNull:()=>is,IsNumber:()=>We,IsObject:()=>j,IsRegExp:()=>Jr,IsString:()=>z,IsSymbol:()=>ss,IsUint8Array:()=>At,IsUndefined:()=>pe});function Gn(e,t){return t in e}function rs(e){return j(e)&&!ue(e)&&!At(e)&&Symbol.asyncIterator in e}function ue(e){return Array.isArray(e)}function Qr(e){return typeof e=="bigint"}function Rt(e){return typeof e=="boolean"}function Xt(e){return e instanceof globalThis.Date}function ns(e){return typeof e=="function"}function os(e){return j(e)&&!ue(e)&&!At(e)&&Symbol.iterator in e}function is(e){return e===null}function We(e){return typeof e=="number"}function j(e){return typeof e=="object"&&e!==null}function Jr(e){return e instanceof globalThis.RegExp}function z(e){return typeof e=="string"}function ss(e){return typeof e=="symbol"}function At(e){return e instanceof globalThis.Uint8Array}function pe(e){return e===void 0}var Ce=u(()=>{});function pf(e){return e.map(t=>zn(t))}function cf(e){return new Date(e.getTime())}function lf(e){return new Uint8Array(e)}function mf(e){return new RegExp(e.source,e.flags)}function ff(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=zn(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=zn(e[r]);return t}function zn(e){return ue(e)?pf(e):Xt(e)?cf(e):At(e)?lf(e):Jr(e)?mf(e):j(e)?ff(e):e}function X(e){return zn(e)}var Ee=u(()=>{Ce()});function wr(e,t){return t===void 0?X(e):X({...t,...e})}var Qn=u(()=>{Ee()});var as=u(()=>{Qn();Ee()});function Sd(e){return e!==null&&typeof e=="object"}function kd(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function yd(e){return e===void 0}function wd(e){return typeof e=="number"}var Id=u(()=>{});var xd=u(()=>{Id()});var Jn,Pd=u(()=>{xd();(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(s,a){return e.ExactOptionalPropertyTypes?a in s:s[a]!==void 0}e.IsExactOptionalProperty=t;function r(s){let a=Sd(s);return e.AllowArrayObject?a:a&&!kd(s)}e.IsObjectLike=r;function n(s){return r(s)&&!(s instanceof Date)&&!(s instanceof Uint8Array)}e.IsRecordLike=n;function o(s){return e.AllowNaN?wd(s):Number.isFinite(s)}e.IsNumberLike=o;function i(s){let a=yd(s);return e.AllowNullVoid?a||s===null:a}e.IsVoidLike=i})(Jn||(Jn={}))});function gf(e){return globalThis.Object.freeze(e).map(t=>Yr(t))}function hf(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=Yr(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=Yr(e[r]);return globalThis.Object.freeze(t)}function Yr(e){return ue(e)?gf(e):Xt(e)?e:At(e)?e:Jr(e)?e:j(e)?hf(e):e}var bd=u(()=>{Ce()});function l(e,t){let r=t!==void 0?{...t,...e}:e;switch(Jn.InstanceMode){case"freeze":return Yr(r);case"clone":return X(r);default:return r}}var P=u(()=>{Pd();bd();Ee()});var Tt=u(()=>{P()});var we,vd=u(()=>{we=class extends Error{constructor(t){super(t)}}});var kt=u(()=>{vd()});var le,it,xe,Je,w,Xr=u(()=>{le=Symbol.for("TypeBox.Transform"),it=Symbol.for("TypeBox.Readonly"),xe=Symbol.for("TypeBox.Optional"),Je=Symbol.for("TypeBox.Hint"),w=Symbol.for("TypeBox.Kind")});var b=u(()=>{Xr()});function Ir(e){return j(e)&&e[it]==="Readonly"}function $e(e){return j(e)&&e[xe]==="Optional"}function ds(e){return O(e,"Any")}function us(e){return O(e,"Argument")}function st(e){return O(e,"Array")}function Zt(e){return O(e,"AsyncIterator")}function er(e){return O(e,"BigInt")}function Mt(e){return O(e,"Boolean")}function at(e){return O(e,"Computed")}function dt(e){return O(e,"Constructor")}function Sf(e){return O(e,"Date")}function ut(e){return O(e,"Function")}function pt(e){return O(e,"Integer")}function oe(e){return O(e,"Intersect")}function tr(e){return O(e,"Iterator")}function O(e,t){return j(e)&&w in e&&e[w]===t}function Yn(e){return Rt(e)||We(e)||z(e)}function Be(e){return O(e,"Literal")}function Ke(e){return O(e,"MappedKey")}function Z(e){return O(e,"MappedResult")}function Lt(e){return O(e,"Never")}function kf(e){return O(e,"Not")}function Zr(e){return O(e,"Null")}function ct(e){return O(e,"Number")}function ce(e){return O(e,"Object")}function rr(e){return O(e,"Promise")}function nr(e){return O(e,"Record")}function se(e){return O(e,"Ref")}function ps(e){return O(e,"RegExp")}function Ct(e){return O(e,"String")}function en(e){return O(e,"Symbol")}function je(e){return O(e,"TemplateLiteral")}function yf(e){return O(e,"This")}function Ut(e){return j(e)&&le in e}function qe(e){return O(e,"Tuple")}function tn(e){return O(e,"Undefined")}function N(e){return O(e,"Union")}function wf(e){return O(e,"Uint8Array")}function If(e){return O(e,"Unknown")}function xf(e){return O(e,"Unsafe")}function Pf(e){return O(e,"Void")}function bf(e){return j(e)&&w in e&&z(e[w])}function Ve(e){return ds(e)||us(e)||st(e)||Mt(e)||er(e)||Zt(e)||at(e)||dt(e)||Sf(e)||ut(e)||pt(e)||oe(e)||tr(e)||Be(e)||Ke(e)||Z(e)||Lt(e)||kf(e)||Zr(e)||ct(e)||ce(e)||rr(e)||nr(e)||se(e)||ps(e)||Ct(e)||en(e)||je(e)||yf(e)||qe(e)||tn(e)||N(e)||wf(e)||If(e)||xf(e)||Pf(e)||bf(e)}var D=u(()=>{Ce();b()});var p={};Hn(p,{IsAny:()=>Md,IsArgument:()=>Cd,IsArray:()=>Ed,IsAsyncIterator:()=>$d,IsBigInt:()=>Od,IsBoolean:()=>_d,IsComputed:()=>Nd,IsConstructor:()=>Fd,IsDate:()=>Dd,IsFunction:()=>Ld,IsImport:()=>Cf,IsInteger:()=>Ud,IsIntersect:()=>Wd,IsIterator:()=>Bd,IsKind:()=>mu,IsKindOf:()=>M,IsLiteral:()=>nn,IsLiteralBoolean:()=>Ef,IsLiteralNumber:()=>jd,IsLiteralString:()=>Kd,IsLiteralValue:()=>qd,IsMappedKey:()=>Vd,IsMappedResult:()=>Hd,IsNever:()=>Gd,IsNot:()=>zd,IsNull:()=>Qd,IsNumber:()=>Jd,IsObject:()=>Yd,IsOptional:()=>Mf,IsPromise:()=>Xd,IsProperties:()=>Xn,IsReadonly:()=>Tf,IsRecord:()=>Zd,IsRecursive:()=>$f,IsRef:()=>eu,IsRegExp:()=>tu,IsSchema:()=>Ie,IsString:()=>ru,IsSymbol:()=>nu,IsTemplateLiteral:()=>ou,IsThis:()=>iu,IsTransform:()=>su,IsTuple:()=>au,IsUint8Array:()=>uu,IsUndefined:()=>du,IsUnion:()=>fs,IsUnionLiteral:()=>Of,IsUnknown:()=>pu,IsUnsafe:()=>cu,IsVoid:()=>lu,TypeGuardUnknownTypeError:()=>cs});function Rd(e){try{return new RegExp(e),!0}catch{return!1}}function ls(e){if(!z(e))return!1;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=7&&r<=13||r===27||r===127)return!1}return!0}function Ad(e){return ms(e)||Ie(e)}function rn(e){return pe(e)||Qr(e)}function Q(e){return pe(e)||We(e)}function ms(e){return pe(e)||Rt(e)}function q(e){return pe(e)||z(e)}function Rf(e){return pe(e)||z(e)&&ls(e)&&Rd(e)}function Af(e){return pe(e)||z(e)&&ls(e)}function Td(e){return pe(e)||Ie(e)}function Tf(e){return j(e)&&e[it]==="Readonly"}function Mf(e){return j(e)&&e[xe]==="Optional"}function Md(e){return M(e,"Any")&&q(e.$id)}function Cd(e){return M(e,"Argument")&&We(e.index)}function Ed(e){return M(e,"Array")&&e.type==="array"&&q(e.$id)&&Ie(e.items)&&Q(e.minItems)&&Q(e.maxItems)&&ms(e.uniqueItems)&&Td(e.contains)&&Q(e.minContains)&&Q(e.maxContains)}function $d(e){return M(e,"AsyncIterator")&&e.type==="AsyncIterator"&&q(e.$id)&&Ie(e.items)}function Od(e){return M(e,"BigInt")&&e.type==="bigint"&&q(e.$id)&&rn(e.exclusiveMaximum)&&rn(e.exclusiveMinimum)&&rn(e.maximum)&&rn(e.minimum)&&rn(e.multipleOf)}function _d(e){return M(e,"Boolean")&&e.type==="boolean"&&q(e.$id)}function Nd(e){return M(e,"Computed")&&z(e.target)&&ue(e.parameters)&&e.parameters.every(t=>Ie(t))}function Fd(e){return M(e,"Constructor")&&e.type==="Constructor"&&q(e.$id)&&ue(e.parameters)&&e.parameters.every(t=>Ie(t))&&Ie(e.returns)}function Dd(e){return M(e,"Date")&&e.type==="Date"&&q(e.$id)&&Q(e.exclusiveMaximumTimestamp)&&Q(e.exclusiveMinimumTimestamp)&&Q(e.maximumTimestamp)&&Q(e.minimumTimestamp)&&Q(e.multipleOfTimestamp)}function Ld(e){return M(e,"Function")&&e.type==="Function"&&q(e.$id)&&ue(e.parameters)&&e.parameters.every(t=>Ie(t))&&Ie(e.returns)}function Cf(e){return M(e,"Import")&&Gn(e,"$defs")&&j(e.$defs)&&Xn(e.$defs)&&Gn(e,"$ref")&&z(e.$ref)&&e.$ref in e.$defs}function Ud(e){return M(e,"Integer")&&e.type==="integer"&&q(e.$id)&&Q(e.exclusiveMaximum)&&Q(e.exclusiveMinimum)&&Q(e.maximum)&&Q(e.minimum)&&Q(e.multipleOf)}function Xn(e){return j(e)&&Object.entries(e).every(([t,r])=>ls(t)&&Ie(r))}function Wd(e){return M(e,"Intersect")&&!(z(e.type)&&e.type!=="object")&&ue(e.allOf)&&e.allOf.every(t=>Ie(t)&&!su(t))&&q(e.type)&&(ms(e.unevaluatedProperties)||Td(e.unevaluatedProperties))&&q(e.$id)}function Bd(e){return M(e,"Iterator")&&e.type==="Iterator"&&q(e.$id)&&Ie(e.items)}function M(e,t){return j(e)&&w in e&&e[w]===t}function Kd(e){return nn(e)&&z(e.const)}function jd(e){return nn(e)&&We(e.const)}function Ef(e){return nn(e)&&Rt(e.const)}function nn(e){return M(e,"Literal")&&q(e.$id)&&qd(e.const)}function qd(e){return Rt(e)||We(e)||z(e)}function Vd(e){return M(e,"MappedKey")&&ue(e.keys)&&e.keys.every(t=>We(t)||z(t))}function Hd(e){return M(e,"MappedResult")&&Xn(e.properties)}function Gd(e){return M(e,"Never")&&j(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function zd(e){return M(e,"Not")&&Ie(e.not)}function Qd(e){return M(e,"Null")&&e.type==="null"&&q(e.$id)}function Jd(e){return M(e,"Number")&&e.type==="number"&&q(e.$id)&&Q(e.exclusiveMaximum)&&Q(e.exclusiveMinimum)&&Q(e.maximum)&&Q(e.minimum)&&Q(e.multipleOf)}function Yd(e){return M(e,"Object")&&e.type==="object"&&q(e.$id)&&Xn(e.properties)&&Ad(e.additionalProperties)&&Q(e.minProperties)&&Q(e.maxProperties)}function Xd(e){return M(e,"Promise")&&e.type==="Promise"&&q(e.$id)&&Ie(e.item)}function Zd(e){return M(e,"Record")&&e.type==="object"&&q(e.$id)&&Ad(e.additionalProperties)&&j(e.patternProperties)&&(t=>{let r=Object.getOwnPropertyNames(t.patternProperties);return r.length===1&&Rd(r[0])&&j(t.patternProperties)&&Ie(t.patternProperties[r[0]])})(e)}function $f(e){return j(e)&&Je in e&&e[Je]==="Recursive"}function eu(e){return M(e,"Ref")&&q(e.$id)&&z(e.$ref)}function tu(e){return M(e,"RegExp")&&q(e.$id)&&z(e.source)&&z(e.flags)&&Q(e.maxLength)&&Q(e.minLength)}function ru(e){return M(e,"String")&&e.type==="string"&&q(e.$id)&&Q(e.minLength)&&Q(e.maxLength)&&Rf(e.pattern)&&Af(e.format)}function nu(e){return M(e,"Symbol")&&e.type==="symbol"&&q(e.$id)}function ou(e){return M(e,"TemplateLiteral")&&e.type==="string"&&z(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function iu(e){return M(e,"This")&&q(e.$id)&&z(e.$ref)}function su(e){return j(e)&&le in e}function au(e){return M(e,"Tuple")&&e.type==="array"&&q(e.$id)&&We(e.minItems)&&We(e.maxItems)&&e.minItems===e.maxItems&&(pe(e.items)&&pe(e.additionalItems)&&e.minItems===0||ue(e.items)&&e.items.every(t=>Ie(t)))}function du(e){return M(e,"Undefined")&&e.type==="undefined"&&q(e.$id)}function Of(e){return fs(e)&&e.anyOf.every(t=>Kd(t)||jd(t))}function fs(e){return M(e,"Union")&&q(e.$id)&&j(e)&&ue(e.anyOf)&&e.anyOf.every(t=>Ie(t))}function uu(e){return M(e,"Uint8Array")&&e.type==="Uint8Array"&&q(e.$id)&&Q(e.minByteLength)&&Q(e.maxByteLength)}function pu(e){return M(e,"Unknown")&&q(e.$id)}function cu(e){return M(e,"Unsafe")}function lu(e){return M(e,"Void")&&e.type==="void"&&q(e.$id)}function mu(e){return j(e)&&w in e&&z(e[w])&&!vf.includes(e[w])}function Ie(e){return j(e)&&(Md(e)||Cd(e)||Ed(e)||_d(e)||Od(e)||$d(e)||Nd(e)||Fd(e)||Dd(e)||Ld(e)||Ud(e)||Wd(e)||Bd(e)||nn(e)||Vd(e)||Hd(e)||Gd(e)||zd(e)||Qd(e)||Jd(e)||Yd(e)||Xd(e)||Zd(e)||eu(e)||tu(e)||ru(e)||nu(e)||ou(e)||iu(e)||au(e)||du(e)||fs(e)||uu(e)||pu(e)||cu(e)||lu(e)||mu(e))}var cs,vf,fu=u(()=>{Ce();b();kt();cs=class extends we{},vf=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"]});var gs=u(()=>{D();fu();Ce()});var gu=u(()=>{});var hu=u(()=>{gu()});var hs,on,Ss,_f,gx,Wt,Bt,Su,ku=u(()=>{hs="(true|false)",on="(0|[1-9][0-9]*)",Ss="(.*)",_f="(?!.*)",gx=`^${hs}$`,Wt=`^${on}$`,Bt=`^${Ss}$`,Su=`^${_f}$`});var sn=u(()=>{ku()});var yu=u(()=>{});var wu=u(()=>{});var Iu=u(()=>{yu();wu()});function xu(e,t){return e.includes(t)}function Pu(e){return[...new Set(e)]}function Df(e,t){return e.filter(r=>t.includes(r))}function Lf(e,t){return e.reduce((r,n)=>Df(r,n),t)}function bu(e){return e.length===1?e[0]:e.length>1?Lf(e.slice(1),e[0]):[]}function vu(e){let t=[];for(let r of e)t.push(...r);return t}var Ru=u(()=>{});var an=u(()=>{Ru()});function Kt(e){return l({[w]:"Any"},e)}var Au=u(()=>{Tt();b()});var dn=u(()=>{Au()});function xr(e,t){return l({[w]:"Array",type:"array",items:e},t)}var Tu=u(()=>{P();b()});var un=u(()=>{Tu()});function Mu(e){return l({[w]:"Argument",index:e})}var Cu=u(()=>{P();b()});var ks=u(()=>{Cu()});function Pr(e,t){return l({[w]:"AsyncIterator",type:"AsyncIterator",items:e},t)}var Eu=u(()=>{b();P()});var pn=u(()=>{Eu()});function Y(e,t,r){return l({[w]:"Computed",target:e,parameters:t},r)}var $u=u(()=>{Tt();Xr()});var jt=u(()=>{$u()});function Uf(e,t){let{[t]:r,...n}=e;return n}function ie(e,t){return t.reduce((r,n)=>Uf(r,n),e)}var Zn=u(()=>{});var $t=u(()=>{Zn()});function F(e){return l({[w]:"Never",not:{}},e)}var Ou=u(()=>{P();b()});var Pe=u(()=>{Ou()});var _u=u(()=>{});function L(e){return l({[w]:"MappedResult",properties:e})}var ys=u(()=>{P();b()});function br(e,t,r){return l({[w]:"Constructor",type:"Constructor",parameters:e,returns:t},r)}var Nu=u(()=>{P();b()});var cn=u(()=>{Nu()});function yt(e,t,r){return l({[w]:"Function",type:"Function",parameters:e,returns:t},r)}var Fu=u(()=>{P();b()});var or=u(()=>{Fu()});function ln(e,t){return l({[w]:"Union",anyOf:e},t)}var ws=u(()=>{P();b()});function Wf(e){return e.some(t=>$e(t))}function Du(e){return e.map(t=>$e(t)?Bf(t):t)}function Bf(e){return ie(e,[xe])}function Kf(e,t){return Wf(e)?Re(ln(Du(e),t)):ln(Du(e),t)}function wt(e,t){return e.length===1?l(e[0],t):e.length===0?F(t):Kf(e,t)}var Lu=u(()=>{P();b();$t();Pe();Ot();ws();D()});var Uu=u(()=>{});function B(e,t){return e.length===0?F(t):e.length===1?l(e[0],t):ln(e,t)}var Wu=u(()=>{Pe();P();ws()});var me=u(()=>{Lu();Uu();Wu()});function jf(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Is(e,t,r){return e[t]===r&&e.charCodeAt(t-1)!==92}function _t(e,t){return Is(e,t,"(")}function mn(e,t){return Is(e,t,")")}function Bu(e,t){return Is(e,t,"|")}function qf(e){if(!(_t(e,0)&&mn(e,e.length-1)))return!1;let t=0;for(let r=0;r<e.length;r++)if(_t(e,r)&&(t+=1),mn(e,r)&&(t-=1),t===0&&r!==e.length-1)return!1;return!0}function Vf(e){return e.slice(1,e.length-1)}function Hf(e){let t=0;for(let r=0;r<e.length;r++)if(_t(e,r)&&(t+=1),mn(e,r)&&(t-=1),Bu(e,r)&&t===0)return!0;return!1}function Gf(e){for(let t=0;t<e.length;t++)if(_t(e,t))return!0;return!1}function zf(e){let[t,r]=[0,0],n=[];for(let i=0;i<e.length;i++)if(_t(e,i)&&(t+=1),mn(e,i)&&(t-=1),Bu(e,i)&&t===0){let s=e.slice(r,i);s.length>0&&n.push(vr(s)),r=i+1}let o=e.slice(r);return o.length>0&&n.push(vr(o)),n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"or",expr:n}}function Qf(e){function t(o,i){if(!_t(o,i))throw new eo("TemplateLiteralParser: Index must point to open parens");let s=0;for(let a=i;a<o.length;a++)if(_t(o,a)&&(s+=1),mn(o,a)&&(s-=1),s===0)return[i,a];throw new eo("TemplateLiteralParser: Unclosed group parens in expression")}function r(o,i){for(let s=i;s<o.length;s++)if(_t(o,s))return[i,s];return[i,o.length]}let n=[];for(let o=0;o<e.length;o++)if(_t(e,o)){let[i,s]=t(e,o),a=e.slice(i,s+1);n.push(vr(a)),o=s}else{let[i,s]=r(e,o),a=e.slice(i,s);a.length>0&&n.push(vr(a)),o=s-1}return n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"and",expr:n}}function vr(e){return qf(e)?vr(Vf(e)):Hf(e)?zf(e):Gf(e)?Qf(e):{type:"const",const:jf(e)}}function Rr(e){return vr(e.slice(1,e.length-1))}var eo,to=u(()=>{kt();eo=class extends we{}});function Jf(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="0"&&e.expr[1].type==="const"&&e.expr[1].const==="[1-9][0-9]*"}function Yf(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="true"&&e.expr[1].type==="const"&&e.expr[1].const==="false"}function Xf(e){return e.type==="const"&&e.const===".*"}function ir(e){return Jf(e)||Xf(e)?!1:Yf(e)?!0:e.type==="and"?e.expr.every(t=>ir(t)):e.type==="or"?e.expr.every(t=>ir(t)):e.type==="const"?!0:(()=>{throw new xs("Unknown expression type")})()}function Ku(e){let t=Rr(e.pattern);return ir(t)}var xs,Ps=u(()=>{to();kt();xs=class extends we{}});function*ju(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let r of ju(e.slice(1)))yield`${t}${r}`}function*Zf(e){return yield*ju(e.expr.map(t=>[...fn(t)]))}function*eg(e){for(let t of e.expr)yield*fn(t)}function*tg(e){return yield e.const}function*fn(e){return e.type==="and"?yield*Zf(e):e.type==="or"?yield*eg(e):e.type==="const"?yield*tg(e):(()=>{throw new bs("Unknown expression")})()}function ro(e){let t=Rr(e.pattern);return ir(t)?[...fn(t)]:[]}var bs,vs=u(()=>{Ps();to();kt();bs=class extends we{}});function U(e,t){return l({[w]:"Literal",const:e,type:typeof e},t)}var qu=u(()=>{P();b()});var Oe=u(()=>{qu()});function no(e){return l({[w]:"Boolean",type:"boolean"},e)}var Vu=u(()=>{b();Tt()});var oo=u(()=>{Vu()});function Ar(e){return l({[w]:"BigInt",type:"bigint"},e)}var Hu=u(()=>{b();Tt()});var gn=u(()=>{Hu()});function Ye(e){return l({[w]:"Number",type:"number"},e)}var Gu=u(()=>{P();b()});var sr=u(()=>{Gu()});function lt(e){return l({[w]:"String",type:"string"},e)}var zu=u(()=>{P();b()});var Tr=u(()=>{zu()});function*rg(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield no():t==="number"?yield Ye():t==="bigint"?yield Ar():t==="string"?yield lt():yield(()=>{let r=t.split("|").map(n=>U(n.trim()));return r.length===0?F():r.length===1?r[0]:wt(r)})()}function*ng(e){if(e[1]!=="{"){let t=U("$"),r=Rs(e.slice(1));return yield*[t,...r]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let r=rg(e.slice(2,t)),n=Rs(e.slice(t+1));return yield*[...r,...n]}yield U(e)}function*Rs(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let r=U(e.slice(0,t)),n=ng(e.slice(t));return yield*[r,...n]}yield U(e)}function Qu(e){return[...Rs(e)]}var As=u(()=>{Oe();oo();gn();sr();Tr();me();Pe()});function og(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ju(e,t){return je(e)?e.pattern.slice(1,e.pattern.length-1):N(e)?`(${e.anyOf.map(r=>Ju(r,t)).join("|")})`:ct(e)?`${t}${on}`:pt(e)?`${t}${on}`:er(e)?`${t}${on}`:Ct(e)?`${t}${Ss}`:Be(e)?`${t}${og(e.const.toString())}`:Mt(e)?`${t}${hs}`:(()=>{throw new Ts(`Unexpected Kind '${e[w]}'`)})()}function Ms(e){return`^${e.map(t=>Ju(t,"")).join("")}$`}var Ts,Cs=u(()=>{sn();b();kt();D();Ts=class extends we{}});function ar(e){let r=ro(e).map(n=>U(n));return wt(r)}var Yu=u(()=>{me();Oe();vs()});function io(e,t){let r=z(e)?Ms(Qu(e)):Ms(e);return l({[w]:"TemplateLiteral",type:"string",pattern:r},t)}var Xu=u(()=>{P();As();Cs();Ce();b()});var Nt=u(()=>{Ps();vs();As();to();Cs();Yu();Xu()});function ig(e){return ro(e).map(r=>r.toString())}function sg(e){let t=[];for(let r of e)t.push(..._e(r));return t}function ag(e){return[e.toString()]}function _e(e){return[...new Set(je(e)?ig(e):N(e)?sg(e.anyOf):Be(e)?ag(e.const):ct(e)?["[number]"]:pt(e)?["[number]"]:[])]}var so=u(()=>{Nt();D()});function dg(e,t,r){let n={};for(let o of Object.getOwnPropertyNames(t))n[o]=qt(e,_e(t[o]),r);return n}function ug(e,t,r){return dg(e,t.properties,r)}function Zu(e,t,r){let n=ug(e,t,r);return L(n)}var Es=u(()=>{Se();so();It()});function tp(e,t){return e.map(r=>rp(r,t))}function pg(e){return e.filter(t=>!Lt(t))}function cg(e,t){return ao(pg(tp(e,t)))}function lg(e){return e.some(t=>Lt(t))?[]:e}function mg(e,t){return wt(lg(tp(e,t)))}function fg(e,t){return t in e?e[t]:t==="[number]"?wt(e):F()}function gg(e,t){return t==="[number]"?e:F()}function hg(e,t){return t in e?e[t]:F()}function rp(e,t){return oe(e)?cg(e.allOf,t):N(e)?mg(e.anyOf,t):qe(e)?fg(e.items??[],t):st(e)?gg(e.items,t):ce(e)?hg(e.properties,t):F()}function $s(e,t){return t.map(r=>rp(e,r))}function ep(e,t){return wt($s(e,t))}function qt(e,t,r){if(se(e)||se(t)){let n="Index types using Ref parameters require both Type and Key to be of TSchema";if(!Ve(e)||!Ve(t))throw new we(n);return Y("Index",[e,t])}return Z(t)?Zu(e,t,r):Ke(t)?np(e,t,r):l(Ve(t)?ep(e,_e(t)):ep(e,t),r)}var Os=u(()=>{P();kt();jt();Pe();Xe();me();so();_s();Es();D()});function Sg(e,t,r){return{[t]:qt(e,[t],X(r))}}function kg(e,t,r){return t.reduce((n,o)=>({...n,...Sg(e,o,r)}),{})}function yg(e,t,r){return kg(e,t.keys,r)}function np(e,t,r){let n=yg(e,t,r);return L(n)}var _s=u(()=>{Os();Se();Ee()});var It=u(()=>{_s();Es();so();Os()});function Mr(e,t){return l({[w]:"Iterator",type:"Iterator",items:e},t)}var op=u(()=>{P();b()});var hn=u(()=>{op()});function wg(e){return globalThis.Object.keys(e).filter(t=>!$e(e[t]))}function Ig(e,t){let r=wg(e),n=r.length>0?{[w]:"Object",type:"object",required:r,properties:e}:{[w]:"Object",type:"object",properties:e};return l(n,t)}var V,ip=u(()=>{P();b();D();V=Ig});var He=u(()=>{ip()});function uo(e,t){return l({[w]:"Promise",type:"Promise",item:e},t)}var sp=u(()=>{P();b()});var po=u(()=>{sp()});function xg(e){return l(ie(e,[it]))}function Pg(e){return l({...e,[it]:"Readonly"})}function bg(e,t){return t===!1?xg(e):Pg(e)}function Ne(e,t){let r=t??!0;return Z(e)?ap(e,r):bg(e,r)}var Ns=u(()=>{P();b();$t();Fs();D()});function vg(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Ne(e[n],t);return r}function Rg(e,t){return vg(e.properties,t)}function ap(e,t){let r=Rg(e,t);return L(r)}var Fs=u(()=>{Se();Ns()});var dr=u(()=>{Fs();Ns()});function Ze(e,t){return l(e.length>0?{[w]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[w]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}var dp=u(()=>{P();b()});var Vt=u(()=>{dp()});function up(e,t){return e in t?et(e,t[e]):L(t)}function Ag(e){return{[e]:U(e)}}function Tg(e){let t={};for(let r of e)t[r]=U(r);return t}function Mg(e,t){return xu(t,e)?Ag(e):Tg(t)}function Cg(e,t){let r=Mg(e,t);return up(e,r)}function Sn(e,t){return t.map(r=>et(e,r))}function Eg(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=et(e,t[n]);return r}function et(e,t){let r={...t};return $e(t)?Re(et(e,ie(t,[xe]))):Ir(t)?Ne(et(e,ie(t,[it]))):Z(t)?up(e,t.properties):Ke(t)?Cg(e,t.keys):dt(t)?br(Sn(e,t.parameters),et(e,t.returns),r):ut(t)?yt(Sn(e,t.parameters),et(e,t.returns),r):Zt(t)?Pr(et(e,t.items),r):tr(t)?Mr(et(e,t.items),r):oe(t)?Ae(Sn(e,t.allOf),r):N(t)?B(Sn(e,t.anyOf),r):qe(t)?Ze(Sn(e,t.items??[]),r):ce(t)?V(Eg(e,t.properties),r):st(t)?xr(et(e,t.items),r):rr(t)?uo(et(e,t.item),r):t}function $g(e,t){let r={};for(let n of e)r[n]=et(n,t);return r}function pp(e,t,r){let n=Ve(e)?_e(e):e,o=t({[w]:"MappedKey",keys:n}),i=$g(n,o);return V(i,r)}var cp=u(()=>{b();$t();un();pn();cn();or();It();Xe();hn();Oe();He();Ot();po();dr();Vt();me();an();ys();D()});var Se=u(()=>{_u();ys();cp()});function Og(e){return l(ie(e,[xe]))}function _g(e){return l({...e,[xe]:"Optional"})}function Ng(e,t){return t===!1?Og(e):_g(e)}function Re(e,t){let r=t??!0;return Z(e)?lp(e,r):Ng(e,r)}var Ds=u(()=>{P();b();$t();Ls();D()});function Fg(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Re(e[n],t);return r}function Dg(e,t){return Fg(e.properties,t)}function lp(e,t){let r=Dg(e,t);return L(r)}var Ls=u(()=>{Se();Ds()});var Ot=u(()=>{Ls();Ds()});function kn(e,t={}){let r=e.every(o=>ce(o)),n=Ve(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return l(t.unevaluatedProperties===!1||Ve(t.unevaluatedProperties)||r?{...n,[w]:"Intersect",type:"object",allOf:e}:{...n,[w]:"Intersect",allOf:e},t)}var Us=u(()=>{P();b();D()});function Lg(e){return e.every(t=>$e(t))}function Ug(e){return ie(e,[xe])}function mp(e){return e.map(t=>$e(t)?Ug(t):t)}function Wg(e,t){return Lg(e)?Re(kn(mp(e),t)):kn(mp(e),t)}function ao(e,t={}){if(e.length===1)return l(e[0],t);if(e.length===0)return F(t);if(e.some(r=>Ut(r)))throw new Error("Cannot intersect transform types");return Wg(e,t)}var fp=u(()=>{b();P();$t();Pe();Ot();Us();D()});var gp=u(()=>{});function Ae(e,t){if(e.length===1)return l(e[0],t);if(e.length===0)return F(t);if(e.some(r=>Ut(r)))throw new Error("Cannot intersect transform types");return kn(e,t)}var hp=u(()=>{P();Pe();Us();D()});var Xe=u(()=>{fp();gp();hp()});function xt(...e){let[t,r]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new we("Ref: $ref must be a string");return l({[w]:"Ref",$ref:t},r)}var Sp=u(()=>{kt();P();b()});var ur=u(()=>{Sp()});function Bg(e,t){return Y("Awaited",[Y(e,t)])}function Kg(e){return Y("Awaited",[xt(e)])}function jg(e){return Ae(kp(e))}function qg(e){return B(kp(e))}function Vg(e){return Cr(e)}function kp(e){return e.map(t=>Cr(t))}function Cr(e,t){return l(at(e)?Bg(e.target,e.parameters):oe(e)?jg(e.allOf):N(e)?qg(e.anyOf):rr(e)?Vg(e.item):se(e)?Kg(e.$ref):e,t)}var yp=u(()=>{P();jt();Xe();me();ur();D()});var co=u(()=>{yp()});function wp(e){let t=[];for(let r of e)t.push(yn(r));return t}function Hg(e){let t=wp(e);return vu(t)}function Gg(e){let t=wp(e);return bu(t)}function zg(e){return e.map((t,r)=>r.toString())}function Qg(e){return["[number]"]}function Jg(e){return globalThis.Object.getOwnPropertyNames(e)}function Yg(e){return Xg?globalThis.Object.getOwnPropertyNames(e).map(r=>r[0]==="^"&&r[r.length-1]==="$"?r.slice(1,r.length-1):r):[]}function yn(e){return oe(e)?Hg(e.allOf):N(e)?Gg(e.anyOf):qe(e)?zg(e.items??[]):st(e)?Qg(e.items):ce(e)?Jg(e.properties):nr(e)?Yg(e.patternProperties):[]}var Xg,Ws=u(()=>{an();D();Xg=!1});function Zg(e,t){return Y("KeyOf",[Y(e,t)])}function eh(e){return Y("KeyOf",[xt(e)])}function th(e,t){let r=yn(e),n=rh(r),o=wt(n);return l(o,t)}function rh(e){return e.map(t=>t==="[number]"?Ye():U(t))}function Er(e,t){return at(e)?Zg(e.target,e.parameters):se(e)?eh(e.$ref):Z(e)?Ip(e,t):th(e,t)}var Bs=u(()=>{P();Oe();sr();jt();ur();Ws();me();Ks();D()});function nh(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Er(e[n],X(t));return r}function oh(e,t){return nh(e.properties,t)}function Ip(e,t){let r=oh(e,t);return L(r)}var Ks=u(()=>{Se();Bs();Ee()});var xp=u(()=>{});var wn=u(()=>{Ks();xp();Ws();Bs()});function ih(e){let t=[];for(let r of e)t.push(...yn(r));return Pu(t)}function sh(e){return e.filter(t=>!Lt(t))}function ah(e,t){let r=[];for(let n of e)r.push(...$s(n,[t]));return sh(r)}function dh(e,t){let r={};for(let n of t)r[n]=ao(ah(e,n));return r}function Pp(e,t){let r=ih(e),n=dh(e,r);return V(n,t)}var bp=u(()=>{Xe();It();wn();He();an();D()});var js=u(()=>{bp()});function lo(e){return l({[w]:"Date",type:"Date"},e)}var vp=u(()=>{b();P()});var mo=u(()=>{vp()});function fo(e){return l({[w]:"Null",type:"null"},e)}var Rp=u(()=>{P();b()});var go=u(()=>{Rp()});function ho(e){return l({[w]:"Symbol",type:"symbol"},e)}var Ap=u(()=>{P();b()});var So=u(()=>{Ap()});function ko(e){return l({[w]:"Undefined",type:"undefined"},e)}var Tp=u(()=>{P();b()});var yo=u(()=>{Tp()});function wo(e){return l({[w]:"Uint8Array",type:"Uint8Array"},e)}var Mp=u(()=>{P();b()});var Io=u(()=>{Mp()});function Ht(e){return l({[w]:"Unknown"},e)}var Cp=u(()=>{P();b()});var $r=u(()=>{Cp()});function uh(e){return e.map(t=>qs(t,!1))}function ph(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=Ne(qs(e[r],!1));return t}function xo(e,t){return t===!0?e:Ne(e)}function qs(e,t){return rs(e)?xo(Kt(),t):os(e)?xo(Kt(),t):ue(e)?Ne(Ze(uh(e))):At(e)?wo():Xt(e)?lo():j(e)?xo(V(ph(e)),t):ns(e)?xo(yt([],Ht()),t):pe(e)?ko():is(e)?fo():ss(e)?ho():Qr(e)?Ar():We(e)?U(e):Rt(e)?U(e):z(e)?U(e):V({})}function Ep(e,t){return l(qs(e,!0),t)}var $p=u(()=>{dn();gn();mo();or();Oe();go();He();So();Vt();dr();yo();Io();$r();Tt();Ce()});var Vs=u(()=>{$p()});function Op(e,t){return dt(e)?Ze(e.parameters,t):F(t)}var _p=u(()=>{Vt();Pe();D()});var Hs=u(()=>{_p()});function Np(e,t){if(pe(e))throw new Error("Enum undefined or empty");let r=globalThis.Object.getOwnPropertyNames(e).filter(i=>isNaN(i)).map(i=>e[i]),o=[...new Set(r)].map(i=>U(i));return B(o,{...t,[Je]:"Enum"})}var Fp=u(()=>{Oe();b();me();Ce()});var Gs=u(()=>{Fp()});function tt(e){return e===f.False?e:f.True}function Or(e){throw new Qs(e)}function fe(e){return p.IsNever(e)||p.IsIntersect(e)||p.IsUnion(e)||p.IsUnknown(e)||p.IsAny(e)}function ge(e,t){return p.IsNever(t)?jp(e,t):p.IsIntersect(t)?Po(e,t):p.IsUnion(t)?Zs(e,t):p.IsUnknown(t)?Gp(e,t):p.IsAny(t)?Xs(e,t):Or("StructuralRight")}function Xs(e,t){return f.True}function ch(e,t){return p.IsIntersect(t)?Po(e,t):p.IsUnion(t)&&t.anyOf.some(r=>p.IsAny(r)||p.IsUnknown(r))?f.True:p.IsUnion(t)?f.Union:p.IsUnknown(t)||p.IsAny(t)?f.True:f.Union}function lh(e,t){return p.IsUnknown(e)?f.False:p.IsAny(e)?f.Union:p.IsNever(e)?f.True:f.False}function mh(e,t){return p.IsObject(t)&&bo(t)?f.True:fe(t)?ge(e,t):p.IsArray(t)?tt(H(e.items,t.items)):f.False}function fh(e,t){return fe(t)?ge(e,t):p.IsAsyncIterator(t)?tt(H(e.items,t.items)):f.False}function gh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsBigInt(t)?f.True:f.False}function Bp(e,t){return p.IsLiteralBoolean(e)||p.IsBoolean(e)?f.True:f.False}function hh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsBoolean(t)?f.True:f.False}function Sh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsConstructor(t)?e.parameters.length>t.parameters.length?f.False:e.parameters.every((r,n)=>tt(H(t.parameters[n],r))===f.True)?tt(H(e.returns,t.returns)):f.False:f.False}function kh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsDate(t)?f.True:f.False}function yh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsFunction(t)?e.parameters.length>t.parameters.length?f.False:e.parameters.every((r,n)=>tt(H(t.parameters[n],r))===f.True)?tt(H(e.returns,t.returns)):f.False:f.False}function Kp(e,t){return p.IsLiteral(e)&&ve.IsNumber(e.const)||p.IsNumber(e)||p.IsInteger(e)?f.True:f.False}function wh(e,t){return p.IsInteger(t)||p.IsNumber(t)?f.True:fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):f.False}function Po(e,t){return t.allOf.every(r=>H(e,r)===f.True)?f.True:f.False}function Ih(e,t){return e.allOf.some(r=>H(r,t)===f.True)?f.True:f.False}function xh(e,t){return fe(t)?ge(e,t):p.IsIterator(t)?tt(H(e.items,t.items)):f.False}function Ph(e,t){return p.IsLiteral(t)&&t.const===e.const?f.True:fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsString(t)?Hp(e,t):p.IsNumber(t)?qp(e,t):p.IsInteger(t)?Kp(e,t):p.IsBoolean(t)?Bp(e,t):f.False}function jp(e,t){return f.False}function bh(e,t){return f.True}function Dp(e){let[t,r]=[e,0];for(;p.IsNot(t);)t=t.not,r+=1;return r%2===0?t:Ht()}function vh(e,t){return p.IsNot(e)?H(Dp(e),t):p.IsNot(t)?H(e,Dp(t)):Or("Invalid fallthrough for Not")}function Rh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsNull(t)?f.True:f.False}function qp(e,t){return p.IsLiteralNumber(e)||p.IsNumber(e)||p.IsInteger(e)?f.True:f.False}function Ah(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsInteger(t)||p.IsNumber(t)?f.True:f.False}function Fe(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Lp(e){return bo(e)}function Up(e){return Fe(e,0)||Fe(e,1)&&"description"in e.properties&&p.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(p.IsString(e.properties.description.anyOf[0])&&p.IsUndefined(e.properties.description.anyOf[1])||p.IsString(e.properties.description.anyOf[1])&&p.IsUndefined(e.properties.description.anyOf[0]))}function zs(e){return Fe(e,0)}function Wp(e){return Fe(e,0)}function Th(e){return Fe(e,0)}function Mh(e){return Fe(e,0)}function Ch(e){return bo(e)}function Eh(e){let t=Ye();return Fe(e,0)||Fe(e,1)&&"length"in e.properties&&tt(H(e.properties.length,t))===f.True}function $h(e){return Fe(e,0)}function bo(e){let t=Ye();return Fe(e,0)||Fe(e,1)&&"length"in e.properties&&tt(H(e.properties.length,t))===f.True}function Oh(e){let t=yt([Kt()],Kt());return Fe(e,0)||Fe(e,1)&&"then"in e.properties&&tt(H(e.properties.then,t))===f.True}function Vp(e,t){return H(e,t)===f.False||p.IsOptional(e)&&!p.IsOptional(t)?f.False:f.True}function Te(e,t){return p.IsUnknown(e)?f.False:p.IsAny(e)?f.Union:p.IsNever(e)||p.IsLiteralString(e)&&Lp(t)||p.IsLiteralNumber(e)&&zs(t)||p.IsLiteralBoolean(e)&&Wp(t)||p.IsSymbol(e)&&Up(t)||p.IsBigInt(e)&&Th(t)||p.IsString(e)&&Lp(t)||p.IsSymbol(e)&&Up(t)||p.IsNumber(e)&&zs(t)||p.IsInteger(e)&&zs(t)||p.IsBoolean(e)&&Wp(t)||p.IsUint8Array(e)&&Ch(t)||p.IsDate(e)&&Mh(t)||p.IsConstructor(e)&&$h(t)||p.IsFunction(e)&&Eh(t)?f.True:p.IsRecord(e)&&p.IsString(Js(e))?t[Je]==="Record"?f.True:f.False:p.IsRecord(e)&&p.IsNumber(Js(e))&&Fe(t,0)?f.True:f.False}function _h(e,t){return fe(t)?ge(e,t):p.IsRecord(t)?rt(e,t):p.IsObject(t)?(()=>{for(let r of Object.getOwnPropertyNames(t.properties)){if(!(r in e.properties)&&!p.IsOptional(t.properties[r]))return f.False;if(p.IsOptional(t.properties[r]))return f.True;if(Vp(e.properties[r],t.properties[r])===f.False)return f.False}return f.True})():f.False}function Nh(e,t){return fe(t)?ge(e,t):p.IsObject(t)&&Oh(t)?f.True:p.IsPromise(t)?tt(H(e.item,t.item)):f.False}function Js(e){return Wt in e.patternProperties?Ye():Bt in e.patternProperties?lt():Or("Unknown record key pattern")}function Ys(e){return Wt in e.patternProperties?e.patternProperties[Wt]:Bt in e.patternProperties?e.patternProperties[Bt]:Or("Unable to get record value schema")}function rt(e,t){let[r,n]=[Js(t),Ys(t)];return p.IsLiteralString(e)&&p.IsNumber(r)&&tt(H(e,n))===f.True?f.True:p.IsUint8Array(e)&&p.IsNumber(r)||p.IsString(e)&&p.IsNumber(r)||p.IsArray(e)&&p.IsNumber(r)?H(e,n):p.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(Vp(n,e.properties[o])===f.False)return f.False;return f.True})():f.False}function Fh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?H(Ys(e),Ys(t)):f.False}function Dh(e,t){let r=p.IsRegExp(e)?lt():e,n=p.IsRegExp(t)?lt():t;return H(r,n)}function Hp(e,t){return p.IsLiteral(e)&&ve.IsString(e.const)||p.IsString(e)?f.True:f.False}function Lh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsString(t)?f.True:f.False}function Uh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsSymbol(t)?f.True:f.False}function Wh(e,t){return p.IsTemplateLiteral(e)?H(ar(e),t):p.IsTemplateLiteral(t)?H(e,ar(t)):Or("Invalid fallthrough for TemplateLiteral")}function Bh(e,t){return p.IsArray(t)&&e.items!==void 0&&e.items.every(r=>H(r,t.items)===f.True)}function Kh(e,t){return p.IsNever(e)?f.True:p.IsUnknown(e)?f.False:p.IsAny(e)?f.Union:f.False}function jh(e,t){return fe(t)?ge(e,t):p.IsObject(t)&&bo(t)||p.IsArray(t)&&Bh(e,t)?f.True:p.IsTuple(t)?ve.IsUndefined(e.items)&&!ve.IsUndefined(t.items)||!ve.IsUndefined(e.items)&&ve.IsUndefined(t.items)?f.False:ve.IsUndefined(e.items)&&!ve.IsUndefined(t.items)||e.items.every((r,n)=>H(r,t.items[n])===f.True)?f.True:f.False:f.False}function qh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsUint8Array(t)?f.True:f.False}function Vh(e,t){return fe(t)?ge(e,t):p.IsObject(t)?Te(e,t):p.IsRecord(t)?rt(e,t):p.IsVoid(t)?zh(e,t):p.IsUndefined(t)?f.True:f.False}function Zs(e,t){return t.anyOf.some(r=>H(e,r)===f.True)?f.True:f.False}function Hh(e,t){return e.anyOf.every(r=>H(r,t)===f.True)?f.True:f.False}function Gp(e,t){return f.True}function Gh(e,t){return p.IsNever(t)?jp(e,t):p.IsIntersect(t)?Po(e,t):p.IsUnion(t)?Zs(e,t):p.IsAny(t)?Xs(e,t):p.IsString(t)?Hp(e,t):p.IsNumber(t)?qp(e,t):p.IsInteger(t)?Kp(e,t):p.IsBoolean(t)?Bp(e,t):p.IsArray(t)?lh(e,t):p.IsTuple(t)?Kh(e,t):p.IsObject(t)?Te(e,t):p.IsUnknown(t)?f.True:f.False}function zh(e,t){return p.IsUndefined(e)||p.IsUndefined(e)?f.True:f.False}function Qh(e,t){return p.IsIntersect(t)?Po(e,t):p.IsUnion(t)?Zs(e,t):p.IsUnknown(t)?Gp(e,t):p.IsAny(t)?Xs(e,t):p.IsObject(t)?Te(e,t):p.IsVoid(t)?f.True:f.False}function H(e,t){return p.IsTemplateLiteral(e)||p.IsTemplateLiteral(t)?Wh(e,t):p.IsRegExp(e)||p.IsRegExp(t)?Dh(e,t):p.IsNot(e)||p.IsNot(t)?vh(e,t):p.IsAny(e)?ch(e,t):p.IsArray(e)?mh(e,t):p.IsBigInt(e)?gh(e,t):p.IsBoolean(e)?hh(e,t):p.IsAsyncIterator(e)?fh(e,t):p.IsConstructor(e)?Sh(e,t):p.IsDate(e)?kh(e,t):p.IsFunction(e)?yh(e,t):p.IsInteger(e)?wh(e,t):p.IsIntersect(e)?Ih(e,t):p.IsIterator(e)?xh(e,t):p.IsLiteral(e)?Ph(e,t):p.IsNever(e)?bh(e,t):p.IsNull(e)?Rh(e,t):p.IsNumber(e)?Ah(e,t):p.IsObject(e)?_h(e,t):p.IsRecord(e)?Fh(e,t):p.IsString(e)?Lh(e,t):p.IsSymbol(e)?Uh(e,t):p.IsTuple(e)?jh(e,t):p.IsPromise(e)?Nh(e,t):p.IsUint8Array(e)?qh(e,t):p.IsUndefined(e)?Vh(e,t):p.IsUnion(e)?Hh(e,t):p.IsUnknown(e)?Gh(e,t):p.IsVoid(e)?Qh(e,t):Or(`Unknown left type operand '${e[w]}'`)}function Gt(e,t){return H(e,t)}var Qs,f,ea=u(()=>{dn();or();sr();Tr();$r();Nt();sn();b();kt();gs();Qs=class extends we{};(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(f||(f={}))});function Jh(e,t,r,n,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(e))i[s]=_r(e[s],t,r,n,X(o));return i}function Yh(e,t,r,n,o){return Jh(e.properties,t,r,n,o)}function zp(e,t,r,n,o){let i=Yh(e,t,r,n,o);return L(i)}var ta=u(()=>{Se();vo();Ee()});function Xh(e,t,r,n){let o=Gt(e,t);return o===f.Union?B([r,n]):o===f.True?r:n}function _r(e,t,r,n,o){return Z(e)?zp(e,t,r,n,o):Ke(e)?l(Qp(e,t,r,n,o)):l(Xh(e,t,r,n),o)}var vo=u(()=>{P();me();ea();ra();ta();D()});function Zh(e,t,r,n,o){return{[e]:_r(U(e),t,r,n,X(o))}}function eS(e,t,r,n,o){return e.reduce((i,s)=>({...i,...Zh(s,t,r,n,o)}),{})}function tS(e,t,r,n,o){return eS(e.keys,t,r,n,o)}function Qp(e,t,r,n,o){let i=tS(e,t,r,n,o);return L(i)}var ra=u(()=>{Se();Oe();vo();Ee()});var Jp=u(()=>{});var In=u(()=>{ea();ra();ta();Jp();vo()});function Yp(e,t){return Nr(ar(e),t)}var na=u(()=>{Ro();Nt()});function rS(e,t){let r=e.filter(n=>Gt(n,t)===f.False);return r.length===1?r[0]:B(r)}function Nr(e,t,r={}){return je(e)?l(Yp(e,t),r):Z(e)?l(Xp(e,t),r):l(N(e)?rS(e.anyOf,t):Gt(e,t)!==f.False?F():e,r)}var Ro=u(()=>{P();me();Pe();In();oa();na();D()});function nS(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Nr(e[n],t);return r}function oS(e,t){return nS(e.properties,t)}function Xp(e,t){let r=oS(e,t);return L(r)}var oa=u(()=>{Se();Ro()});var ia=u(()=>{oa();na();Ro()});function Zp(e,t){return Fr(ar(e),t)}var sa=u(()=>{Ao();Nt()});function iS(e,t){let r=e.filter(n=>Gt(n,t)!==f.False);return r.length===1?r[0]:B(r)}function Fr(e,t,r){return je(e)?l(Zp(e,t),r):Z(e)?l(ec(e,t),r):l(N(e)?iS(e.anyOf,t):Gt(e,t)!==f.False?e:F(),r)}var Ao=u(()=>{P();me();Pe();In();aa();sa();D()});function sS(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Fr(e[n],t);return r}function aS(e,t){return sS(e.properties,t)}function ec(e,t){let r=aS(e,t);return L(r)}var aa=u(()=>{Se();Ao()});var da=u(()=>{aa();sa();Ao()});function tc(e,t){return dt(e)?l(e.returns,t):F(t)}var rc=u(()=>{P();Pe();D()});var ua=u(()=>{rc()});function To(e){return Ne(Re(e))}var nc=u(()=>{dr();Ot()});var Mo=u(()=>{nc()});function pr(e,t,r){return l({[w]:"Record",type:"object",patternProperties:{[e]:t}},r)}function pa(e,t,r){let n={};for(let o of e)n[o]=t;return V(n,{...r,[Je]:"Record"})}function dS(e,t,r){return Ku(e)?pa(_e(e),t,r):pr(e.pattern,t,r)}function uS(e,t,r){return pa(_e(B(e)),t,r)}function pS(e,t,r){return pa([e.toString()],t,r)}function cS(e,t,r){return pr(e.source,t,r)}function lS(e,t,r){let n=pe(e.pattern)?Bt:e.pattern;return pr(n,t,r)}function mS(e,t,r){return pr(Bt,t,r)}function fS(e,t,r){return pr(Su,t,r)}function gS(e,t,r){return V({true:t,false:t},r)}function hS(e,t,r){return pr(Wt,t,r)}function SS(e,t,r){return pr(Wt,t,r)}function Co(e,t,r={}){return N(e)?uS(e.anyOf,t,r):je(e)?dS(e,t,r):Be(e)?pS(e.const,t,r):Mt(e)?gS(e,t,r):pt(e)?hS(e,t,r):ct(e)?SS(e,t,r):ps(e)?cS(e,t,r):Ct(e)?lS(e,t,r):ds(e)?mS(e,t,r):Lt(e)?fS(e,t,r):F(r)}function Eo(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function oc(e){let t=Eo(e);return t===Bt?lt():t===Wt?Ye():lt({pattern:t})}function $o(e){return e.patternProperties[Eo(e)]}var ic=u(()=>{P();b();Pe();sr();He();Tr();me();Nt();sn();It();Ce();D()});var xn=u(()=>{ic()});function kS(e,t){return t.parameters=Pn(e,t.parameters),t.returns=mt(e,t.returns),t}function yS(e,t){return t.parameters=Pn(e,t.parameters),t.returns=mt(e,t.returns),t}function wS(e,t){return t.allOf=Pn(e,t.allOf),t}function IS(e,t){return t.anyOf=Pn(e,t.anyOf),t}function xS(e,t){return pe(t.items)||(t.items=Pn(e,t.items)),t}function PS(e,t){return t.items=mt(e,t.items),t}function bS(e,t){return t.items=mt(e,t.items),t}function vS(e,t){return t.items=mt(e,t.items),t}function RS(e,t){return t.item=mt(e,t.item),t}function AS(e,t){let r=ES(e,t.properties);return{...t,...V(r)}}function TS(e,t){let r=mt(e,oc(t)),n=mt(e,$o(t)),o=Co(r,n);return{...t,...o}}function MS(e,t){return t.index in e?e[t.index]:Ht()}function CS(e,t){let r=Ir(t),n=$e(t),o=mt(e,t);return r&&n?To(o):r&&!n?Ne(o):!r&&n?Re(o):o}function ES(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:CS(e,t[n])}),{})}function Pn(e,t){return t.map(r=>mt(e,r))}function mt(e,t){return dt(t)?kS(e,t):ut(t)?yS(e,t):oe(t)?wS(e,t):N(t)?IS(e,t):qe(t)?xS(e,t):st(t)?PS(e,t):Zt(t)?bS(e,t):tr(t)?vS(e,t):rr(t)?RS(e,t):ce(t)?AS(e,t):nr(t)?TS(e,t):us(t)?MS(e,t):t}function sc(e,t){return mt(t,wr(e))}var ac=u(()=>{Qn();$r();Mo();dr();Ot();He();xn();Ce();D()});var ca=u(()=>{ac()});function dc(e){return l({[w]:"Integer",type:"integer"},e)}var uc=u(()=>{P();b()});var la=u(()=>{uc()});function $S(e,t,r){return{[e]:ft(U(e),t,X(r))}}function OS(e,t,r){return e.reduce((o,i)=>({...o,...$S(i,t,r)}),{})}function _S(e,t,r){return OS(e.keys,t,r)}function pc(e,t,r){let n=_S(e,t,r);return L(n)}var ma=u(()=>{Se();cr();Oe();Ee()});function NS(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),r].join("")}function FS(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),r].join("")}function DS(e){return e.toUpperCase()}function LS(e){return e.toLowerCase()}function US(e,t,r){let n=Rr(e.pattern);if(!ir(n))return{...e,pattern:cc(e.pattern,t)};let s=[...fn(n)].map(c=>U(c)),a=lc(s,t),d=B(a);return io([d],r)}function cc(e,t){return typeof e=="string"?t==="Uncapitalize"?NS(e):t==="Capitalize"?FS(e):t==="Uppercase"?DS(e):t==="Lowercase"?LS(e):e:e.toString()}function lc(e,t){return e.map(r=>ft(r,t))}function ft(e,t,r={}){return Ke(e)?pc(e,t,r):je(e)?US(e,t,r):N(e)?B(lc(e.anyOf,t),r):Be(e)?U(cc(e.const,t),r):l(e,r)}var cr=u(()=>{P();Nt();ma();Oe();me();D()});function mc(e,t={}){return ft(e,"Capitalize",t)}var fc=u(()=>{cr()});function gc(e,t={}){return ft(e,"Lowercase",t)}var hc=u(()=>{cr()});function Sc(e,t={}){return ft(e,"Uncapitalize",t)}var kc=u(()=>{cr()});function yc(e,t={}){return ft(e,"Uppercase",t)}var wc=u(()=>{cr()});var fa=u(()=>{fc();ma();cr();hc();kc();wc()});function WS(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=zt(e[o],t,X(r));return n}function BS(e,t,r){return WS(e.properties,t,r)}function Ic(e,t,r){let n=BS(e,t,r);return L(n)}var ga=u(()=>{Se();Oo();Ee()});function KS(e,t){return e.map(r=>ha(r,t))}function jS(e,t){return e.map(r=>ha(r,t))}function qS(e,t){let{[t]:r,...n}=e;return n}function VS(e,t){return t.reduce((r,n)=>qS(r,n),e)}function HS(e,t,r){let n=ie(e,[le,"$id","required","properties"]),o=VS(r,t);return V(o,n)}function GS(e){let t=e.reduce((r,n)=>Yn(n)?[...r,U(n)]:r,[]);return B(t)}function ha(e,t){return oe(e)?Ae(KS(e.allOf,t)):N(e)?B(jS(e.anyOf,t)):ce(e)?HS(e,t,e.properties):V({})}function zt(e,t,r){let n=ue(t)?GS(t):t,o=Ve(t)?_e(t):t,i=se(e),s=se(t);return Z(e)?Ic(e,o,r):Ke(t)?xc(e,t,r):i&&s?Y("Omit",[e,n],r):!i&&s?Y("Omit",[e,n],r):i&&!s?Y("Omit",[e,n],r):l({...ha(e,o),...r})}var Oo=u(()=>{P();Zn();Xr();jt();Oe();It();Xe();me();He();Sa();ga();D();Ce()});function zS(e,t,r){return{[t]:zt(e,[t],X(r))}}function QS(e,t,r){return t.reduce((n,o)=>({...n,...zS(e,o,r)}),{})}function JS(e,t,r){return QS(e,t.keys,r)}function xc(e,t,r){let n=JS(e,t,r);return L(n)}var Sa=u(()=>{Se();Oo();Ee()});var _o=u(()=>{Sa();ga();Oo()});function YS(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=Qt(e[o],t,X(r));return n}function XS(e,t,r){return YS(e.properties,t,r)}function Pc(e,t,r){let n=XS(e,t,r);return L(n)}var ka=u(()=>{Se();No();Ee()});function ZS(e,t){return e.map(r=>ya(r,t))}function ek(e,t){return e.map(r=>ya(r,t))}function tk(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function rk(e,t,r){let n=ie(e,[le,"$id","required","properties"]),o=tk(r,t);return V(o,n)}function nk(e){let t=e.reduce((r,n)=>Yn(n)?[...r,U(n)]:r,[]);return B(t)}function ya(e,t){return oe(e)?Ae(ZS(e.allOf,t)):N(e)?B(ek(e.anyOf,t)):ce(e)?rk(e,t,e.properties):V({})}function Qt(e,t,r){let n=ue(t)?nk(t):t,o=Ve(t)?_e(t):t,i=se(e),s=se(t);return Z(e)?Pc(e,o,r):Ke(t)?bc(e,t,r):i&&s?Y("Pick",[e,n],r):!i&&s?Y("Pick",[e,n],r):i&&!s?Y("Pick",[e,n],r):l({...ya(e,o),...r})}var No=u(()=>{P();Zn();jt();Xe();Oe();He();me();It();Xr();D();Ce();wa();ka()});function ok(e,t,r){return{[t]:Qt(e,[t],X(r))}}function ik(e,t,r){return t.reduce((n,o)=>({...n,...ok(e,o,r)}),{})}function sk(e,t,r){return ik(e,t.keys,r)}function bc(e,t,r){let n=sk(e,t,r);return L(n)}var wa=u(()=>{Se();No();Ee()});var Fo=u(()=>{wa();ka();No()});function ak(e,t){return Y("Partial",[Y(e,t)])}function dk(e){return Y("Partial",[xt(e)])}function uk(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=Re(e[r]);return t}function pk(e,t){let r=ie(e,[le,"$id","required","properties"]),n=uk(t);return V(n,r)}function vc(e){return e.map(t=>Rc(t))}function Rc(e){return at(e)?ak(e.target,e.parameters):se(e)?dk(e.$ref):oe(e)?Ae(vc(e.allOf)):N(e)?B(vc(e.anyOf)):ce(e)?pk(e,e.properties):er(e)||Mt(e)||pt(e)||Be(e)||Zr(e)||ct(e)||Ct(e)||en(e)||tn(e)?e:V({})}function Dr(e,t){return Z(e)?Ac(e,t):l({...Rc(e),...t})}var Ia=u(()=>{P();jt();Ot();He();Xe();me();ur();$t();b();xa();D()});function ck(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Dr(e[n],X(t));return r}function lk(e,t){return ck(e.properties,t)}function Ac(e,t){let r=lk(e,t);return L(r)}var xa=u(()=>{Se();Ia();Ee()});var Do=u(()=>{xa();Ia()});function mk(e,t){return Y("Required",[Y(e,t)])}function fk(e){return Y("Required",[xt(e)])}function gk(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=ie(e[r],[xe]);return t}function hk(e,t){let r=ie(e,[le,"$id","required","properties"]),n=gk(t);return V(n,r)}function Tc(e){return e.map(t=>Mc(t))}function Mc(e){return at(e)?mk(e.target,e.parameters):se(e)?fk(e.$ref):oe(e)?Ae(Tc(e.allOf)):N(e)?B(Tc(e.anyOf)):ce(e)?hk(e,e.properties):er(e)||Mt(e)||pt(e)||Be(e)||Zr(e)||ct(e)||Ct(e)||en(e)||tn(e)?e:V({})}function Lr(e,t){return Z(e)?Cc(e,t):l({...Mc(e),...t})}var Pa=u(()=>{P();jt();He();Xe();me();ur();b();$t();ba();D()});function Sk(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Lr(e[n],t);return r}function kk(e,t){return Sk(e.properties,t)}function Cc(e,t){let r=kk(e,t);return L(r)}var ba=u(()=>{Se();Pa()});var Lo=u(()=>{ba();Pa()});function yk(e,t){return t.map(r=>se(r)?va(e,r.$ref):Ge(e,r))}function va(e,t){return t in e?se(e[t])?va(e,e[t].$ref):Ge(e,e[t]):F()}function wk(e){return Cr(e[0])}function Ik(e){return qt(e[0],e[1])}function xk(e){return Er(e[0])}function Pk(e){return Dr(e[0])}function bk(e){return zt(e[0],e[1])}function vk(e){return Qt(e[0],e[1])}function Rk(e){return Lr(e[0])}function Ak(e,t,r){let n=yk(e,r);return t==="Awaited"?wk(n):t==="Index"?Ik(n):t==="KeyOf"?xk(n):t==="Partial"?Pk(n):t==="Omit"?bk(n):t==="Pick"?vk(n):t==="Required"?Rk(n):F()}function Tk(e,t){return xr(Ge(e,t))}function Mk(e,t){return Pr(Ge(e,t))}function Ck(e,t,r){return br(bn(e,t),Ge(e,r))}function Ek(e,t,r){return yt(bn(e,t),Ge(e,r))}function $k(e,t){return Ae(bn(e,t))}function Ok(e,t){return Mr(Ge(e,t))}function _k(e,t){return V(globalThis.Object.keys(t).reduce((r,n)=>({...r,[n]:Ge(e,t[n])}),{}))}function Nk(e,t){let[r,n]=[Ge(e,$o(t)),Eo(t)],o=wr(t);return o.patternProperties[n]=r,o}function Fk(e,t){return se(t)?{...va(e,t.$ref),[le]:t[le]}:t}function Dk(e,t){return Ze(bn(e,t))}function Lk(e,t){return B(bn(e,t))}function bn(e,t){return t.map(r=>Ge(e,r))}function Ge(e,t){return $e(t)?l(Ge(e,ie(t,[xe])),t):Ir(t)?l(Ge(e,ie(t,[it])),t):Ut(t)?l(Fk(e,t),t):st(t)?l(Tk(e,t.items),t):Zt(t)?l(Mk(e,t.items),t):at(t)?l(Ak(e,t.target,t.parameters)):dt(t)?l(Ck(e,t.parameters,t.returns),t):ut(t)?l(Ek(e,t.parameters,t.returns),t):oe(t)?l($k(e,t.allOf),t):tr(t)?l(Ok(e,t.items),t):ce(t)?l(_k(e,t.properties),t):nr(t)?l(Nk(e,t)):qe(t)?l(Dk(e,t.items||[]),t):N(t)?l(Lk(e,t.anyOf),t):t}function Uk(e,t){return t in e?Ge(e,e[t]):F()}function Ec(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,r)=>({...t,[r]:Uk(e,r)}),{})}var $c=u(()=>{Tt();as();$t();un();co();pn();cn();It();or();Xe();hn();wn();He();_o();Fo();Pe();Do();xn();Lo();Vt();me();b();D()});function Oc(e){return new Ra(e)}var Ra,_c=u(()=>{Tt();b();$c();Ra=class{constructor(t){let r=Ec(t),n=this.WithIdentifiers(r);this.$defs=n}Import(t,r){let n={...this.$defs,[t]:l(this.$defs[t],r)};return l({[w]:"Import",$defs:n,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:{...t[n],$id:n}}),{})}}});var Aa=u(()=>{_c()});function Nc(e,t){return l({[w]:"Not",not:e},t)}var Fc=u(()=>{P();b()});var Ta=u(()=>{Fc()});function Dc(e,t){return ut(e)?Ze(e.parameters,t):F()}var Lc=u(()=>{Vt();Pe();D()});var Ma=u(()=>{Lc()});function Uc(e,t={}){pe(t.$id)&&(t.$id=`T${Wk++}`);let r=wr(e({[w]:"This",$ref:`${t.$id}`}));return r.$id=t.$id,l({[Je]:"Recursive",...r},t)}var Wk,Wc=u(()=>{Qn();P();Ce();b();Wk=0});var Ca=u(()=>{Wc()});function Bc(e,t){let r=z(e)?new globalThis.RegExp(e):e;return l({[w]:"RegExp",type:"RegExp",source:r.source,flags:r.flags},t)}var Kc=u(()=>{P();Ce();b()});var Ea=u(()=>{Kc()});function Bk(e){return oe(e)?e.allOf:N(e)?e.anyOf:qe(e)?e.items??[]:[]}function jc(e){return Bk(e)}var qc=u(()=>{D()});var $a=u(()=>{qc()});function Vc(e,t){return ut(e)?l(e.returns,t):F(t)}var Hc=u(()=>{P();Pe();D()});var Oa=u(()=>{Hc()});var Gc=u(()=>{});var zc=u(()=>{});var Qc=u(()=>{Gc();zc()});var Jc=u(()=>{});var Yc=u(()=>{Jc()});function Xc(e){return new _a(e)}var _a,Na,Zc=u(()=>{b();D();_a=class{constructor(t){this.schema=t}Decode(t){return new Na(this.schema,t)}},Na=class{constructor(t,r){this.schema=t,this.decode=r}EncodeTransform(t,r){let i={Encode:s=>r[le].Encode(t(s)),Decode:s=>this.decode(r[le].Decode(s))};return{...r,[le]:i}}EncodeSchema(t,r){let n={Decode:this.decode,Encode:t};return{...r,[le]:n}}Encode(t){return Ut(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}}});var Fa=u(()=>{Zc()});function el(e={}){return l({[w]:e[w]??"Unsafe"},e)}var tl=u(()=>{P();b()});var Da=u(()=>{tl()});function rl(e){return l({[w]:"Void",type:"void"},e)}var nl=u(()=>{P();b()});var La=u(()=>{nl()});var Ua={};Hn(Ua,{Any:()=>Kt,Argument:()=>Mu,Array:()=>xr,AsyncIterator:()=>Pr,Awaited:()=>Cr,BigInt:()=>Ar,Boolean:()=>no,Capitalize:()=>mc,Composite:()=>Pp,Const:()=>Ep,Constructor:()=>br,ConstructorParameters:()=>Op,Date:()=>lo,Enum:()=>Np,Exclude:()=>Nr,Extends:()=>_r,Extract:()=>Fr,Function:()=>yt,Index:()=>qt,InstanceType:()=>tc,Instantiate:()=>sc,Integer:()=>dc,Intersect:()=>Ae,Iterator:()=>Mr,KeyOf:()=>Er,Literal:()=>U,Lowercase:()=>gc,Mapped:()=>pp,Module:()=>Oc,Never:()=>F,Not:()=>Nc,Null:()=>fo,Number:()=>Ye,Object:()=>V,Omit:()=>zt,Optional:()=>Re,Parameters:()=>Dc,Partial:()=>Dr,Pick:()=>Qt,Promise:()=>uo,Readonly:()=>Ne,ReadonlyOptional:()=>To,Record:()=>Co,Recursive:()=>Uc,Ref:()=>xt,RegExp:()=>Bc,Required:()=>Lr,Rest:()=>jc,ReturnType:()=>Vc,String:()=>lt,Symbol:()=>ho,TemplateLiteral:()=>io,Transform:()=>Xc,Tuple:()=>Ze,Uint8Array:()=>wo,Uncapitalize:()=>Sc,Undefined:()=>ko,Union:()=>B,Unknown:()=>Ht,Unsafe:()=>el,Uppercase:()=>yc,Void:()=>rl});var ol=u(()=>{dn();ks();un();pn();co();gn();oo();js();Vs();cn();Hs();mo();Gs();ia();In();da();or();It();ua();ca();la();Xe();fa();hn();wn();Oe();Se();Aa();Pe();Ta();go();sr();He();_o();Ot();Ma();Do();Fo();po();dr();Mo();xn();Ca();ur();Ea();Lo();$a();Oa();Tr();So();Nt();Fa();Vt();Io();yo();me();$r();Da();La()});var g,il=u(()=>{ol();g=Ua});var nt=u(()=>{as();Tt();kt();gs();hu();sn();Iu();an();b();dn();un();ks();pn();co();gn();oo();js();Vs();cn();Hs();mo();Gs();ia();In();da();or();It();ua();ca();la();Xe();hn();fa();wn();Oe();Aa();Se();Pe();Ta();go();sr();He();_o();Ot();Ma();Do();Fo();po();dr();Mo();xn();Ca();ur();Ea();Lo();$a();Oa();Qc();Yc();Tr();So();Nt();Fa();Vt();Io();yo();me();$r();Da();La();il()});function Wa(e){k=e}var k,he=u(()=>{k=null});function Vk(e){if(!e)return;let t=e.match(/^agent:[^:]+:discord:(direct|dm|channel|group):/i);if(!t?.[1])return;let r=t[1].toLowerCase();return r==="direct"||r==="dm"?"user":"channel"}function Hk(e,t){if(!/^\d+$/.test(e))return e;let r=Vk(t);return r?`${r}:${e}`:`channel:${e}`}function Gk(e){if(!(!e?.provider||!e.target)&&!(e.provider==="system"||e.target==="system"))return e.accountId?`${e.provider}|${e.accountId}|${e.target}`:`${e.provider}|${e.target}`}function zk(e){let t=e?.trim();if(!t)return;let r=t.match(/^agent:[^:]+:([^:]+):([^:]+):([^:]+)(?::topic:([^:]+))?$/i);if(!r)return;let[,n,o,i,s]=r,a=n.toLowerCase(),d=o.toLowerCase(),c=a==="discord"?d==="direct"||d==="dm"?`user:${i}`:`channel:${i}`:i;return{provider:a,target:c,threadId:s,sessionKey:t}}function sl(e){let t=e?.match(/:topic:(\d+)$/);return t?parseInt(t[1],10):void 0}function Qk(e){return!!(e?.provider&&e.target&&e.provider!=="system"&&e.target!=="system")}function Ba(e,t,r){let n=zk(r),o=t!=null?String(t):void 0,i=e?.trim();if(!i||i==="unknown")return n?{...n,threadId:o??n.threadId}:{provider:"system",target:"system",sessionKey:r?.trim()||void 0};let s=i.split("|").map(y=>y.trim()).filter(Boolean);if(s.length<2)return n?{...n,threadId:o??n.threadId}:{provider:"system",target:"system",sessionKey:r?.trim()||void 0};let[a,d,c]=s,h=c??d,m=c?d:void 0;if(!a||!h)return;let S=a==="discord"?Hk(h,r):h;return{provider:a,accountId:m,target:S,threadId:o??(n?.provider===a?n.threadId:void 0),sessionKey:r?.trim()||void 0}}function Ur(e){return Ba(Gk(e.route)??e.originChannel,e.route?.threadId??e.originThreadId,e.route?.sessionKey??e.originSessionKey)??e.route}function al(e){let t=Ur(e);return Qk(t)?t:void 0}var vn=u(()=>{});import{readFileSync as Jk}from"fs";import{homedir as Yk}from"os";import{join as Xk}from"path";function ul(){if(Rn!==void 0)return Rn;try{let e=Jk(Xk(Yk(),".claude.json"),"utf-8");Rn=JSON.parse(e).mcpServers??{}}catch{Rn={}}return Rn}function pl(e){let t=e.defaultHarness??dl,r={};for(let[n,o]of Object.entries(Wo))r[n]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[n,o]of Object.entries(e.harnesses??{})){let i=r[n]??{},s={...i,defaultModel:o.defaultModel??i.defaultModel,reasoningEffort:o.reasoningEffort??i.reasoningEffort};o.allowedModels!==void 0?s.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(s.allowedModels=void 0),r[n]=s}if(e.defaultModel!==void 0){let n=r[t]??{};r[t]={...n,defaultModel:e.harnesses?.[t]?.defaultModel??e.defaultModel,allowedModels:e.harnesses?.[t]?.allowedModels!==void 0?n.allowedModels:e.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${t}.defaultModel instead.`)}if(e.model!==void 0){let n=r.codex??{};r.codex={...n,defaultModel:e.harnesses?.codex?.defaultModel??e.model,allowedModels:e.harnesses?.codex?.allowedModels!==void 0?n.allowedModels:e.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(e.reasoningEffort!==void 0){let n=r.codex??{};r.codex={...n,reasoningEffort:e.harnesses?.codex?.reasoningEffort??e.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(e.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[n,o]of Object.entries(r))e.harnesses?.[n]?.allowedModels===void 0&&(r[n]={...o,allowedModels:void 0})}E={maxSessions:e.maxSessions??20,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??15,sessionGcAgeMinutes:e.sessionGcAgeMinutes??1440,maxPersistedSessions:e.maxPersistedSessions??1e4,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10,permissionMode:e.permissionMode??"plan",planApproval:e.planApproval??"ask",defaultHarness:t,harnesses:r,allowedModels:e.allowedModels,defaultWorktreeStrategy:e.defaultWorktreeStrategy??"off",worktreeDir:e.worktreeDir}}function De(){return E.defaultHarness??dl}function cl(e){let t=Wo[e],r=E.harnesses[e];return{...t,...r,allowedModels:r?.allowedModels??t?.allowedModels}}function Wr(e){return cl(e).defaultModel}function ll(e){return E.harnesses[e]?.allowedModels??E.allowedModels}function Jt(e){return cl(e).reasoningEffort}function ml(e){if(e.messageChannel){let t=e.messageChannel.split("|");if(t.length>=3)return e.messageChannel;if(e.agentAccountId&&t.length>=2)return`${t[0]}|${e.agentAccountId}|${t.slice(1).join("|")}`;if(t.length===1&&e.chatId)return`${t[0]}|${e.chatId}`;if(t.length===1&&e.senderId)return`${t[0]}|${e.senderId}`}if(e.workspaceDir){let t=Mn(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function An(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);if(e?.messageChannel){let r=String(e.messageChannel);if(r.includes("|"))return r;if(e.chatId)return`${r}|${e.chatId}`;if(e.senderId)return`${r}|${e.senderId}`}return e?.channel&&e?.chatId?`${e.channel}|${e.chatId}`:e?.channel&&e?.senderId?`${e.channel}|${e.senderId}`:e?.id&&/^-?\d+$/.test(String(e.id))?`telegram|${e.id}`:E.fallbackChannel??"unknown"}function Tn(e){return e?.messageThreadId??void 0}function Bo(e,t,r){return Ba(An(e,t),Tn(e),r??e?.sessionKey)}function Mn(e){let t=E.agentChannels;if(!t)return;let r=i=>i.replace(/\/+$/,""),n=r(e),o=Object.entries(t).sort((i,s)=>s[0].length-i[0].length);for(let[i,s]of o)if(n===r(i)||n.startsWith(r(i)+"/"))return s}function fl(e){return sl(e)}var Rn,dl,Wo,E,Le=u(()=>{vn();dl="claude-code",Wo={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium"}};E={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"ask",harnesses:{"claude-code":{...Wo["claude-code"]},codex:{...Wo.codex}}}});function jo(e){return{type:"backend_ref",ref:e}}function qo(e){return{type:"run_started",...e?{runId:e}:{}}}function Cn(e){return{type:"text_delta",text:e}}function gl(e,t){return{type:"tool_call",name:e,input:t}}function Vo(e){return{type:"pending_input",state:e}}function Kr(e){return e?{type:"pending_input_resolved",requestId:e}:{type:"pending_input_resolved"}}function Ho(e,t){return{type:"plan_artifact",artifact:e,finalized:t}}function Go(e){return e?{type:"settings_changed",permissionMode:e}:{type:"settings_changed"}}function lr(e){return{type:"run_completed",data:e}}var Br,Ka=u(()=>{Br=class{queue=[];resolvePending=null;done=!1;enqueue(t){this.queue.push(t),this.flush()}close(){this.done=!0,this.flush()}flush(){this.resolvePending&&(this.resolvePending(),this.resolvePending=null)}messages(){let t=this;return(async function*(){for(;;){for(;t.queue.length>0;)yield t.queue.shift();if(t.done)return;await new Promise(r=>{t.resolvePending=r})}})()}}});import{query as Zk}from"@anthropic-ai/claude-agent-sdk";import{dirname as hl,join as Sl}from"path";import{fileURLToPath as ey}from"url";import{createRequire as ty}from"module";function ry(e,t,r){let o=(Array.isArray(r.questions)?r.questions:[])[0]??{},i=typeof o.question=="string"?o.question:void 0,s=Array.isArray(o.options)?o.options.map(a=>{if(!a||typeof a!="object")return"";let d=a.label;return typeof d=="string"?d:""}).filter(Boolean):[];return{requestId:`${e||"claude"}-ask-${t}`,kind:"question",promptText:i,options:s,allowsFreeText:s.length===0||o.multiSelect===!0}}var zo,kl=u(()=>{Ka();zo=class{name="claude-code";backendKind="claude-code";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!1,nativePlanArtifacts:!1,worktrees:"plugin-managed"};launch(t){let r=new Br,n=!1,o="",i=!1,s=0,a=t.resumeSessionId??"",d=t.canUseTool,c={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,pathToClaudeCodeExecutable:(()=>{try{let S=ty(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return Sl(hl(S),"cli.js")}catch{let m=hl(ey(import.meta.url));return Sl(m,"..","node_modules","@anthropic-ai","claude-agent-sdk","cli.js")}})(),allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers,...d?{canUseTool:async(m,S)=>{if(m!=="AskUserQuestion")return{behavior:"allow"};let y=ry(a,++s,S);r.enqueue(Vo(y));try{let x=await d(m,S);return r.enqueue(Kr(y.requestId)),x}catch(x){throw r.enqueue(Kr(y.requestId)),x}}}:{}};t.resumeSessionId&&(c.resume=t.resumeSessionId,c.forkSession=t.forkSession??!1);let h=Zk({prompt:t.prompt,options:c});return(async()=>{try{for await(let m of h){let S=m;if(S.type==="system"&&S.subtype==="init"){a=S.session_id??a,r.enqueue(jo({kind:"claude-code",conversationId:a}));continue}if(S.type==="system"&&S.subtype==="status"&&S.permissionMode){r.enqueue(Go(S.permissionMode));continue}if(S.type==="assistant"){n||(n=!0,r.enqueue(qo()));for(let y of S.message?.content??[]){if(y.type==="text"){o+=o?`
|
|
2
|
+
${y.text}`:y.text,r.enqueue(Cn(y.text));continue}y.type==="tool_use"&&((y.name==="ExitPlanMode"||y.name==="set_permission_mode")&&(i=!0),y.name!=="AskUserQuestion"&&r.enqueue(gl(y.name,y.input)))}continue}if(S.type==="result"){let y=o.trim();if(y&&(t.permissionMode==="plan"||i)){let x={explanation:void 0,steps:[],markdown:y};r.enqueue(Ho(x,!0))}r.enqueue(lr({success:S.subtype==="success",duration_ms:S.duration_ms??0,total_cost_usd:S.total_cost_usd??0,num_turns:S.num_turns??0,result:S.result,session_id:S.session_id??a})),o="",i=!1,n=!1}}}finally{r.close()}})().catch(m=>{r.enqueue(lr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,result:m instanceof Error?m.message:String(m),session_id:a})),r.close()}),{messages:r.messages(),async setPermissionMode(m){typeof h.setPermissionMode=="function"&&await h.setPermissionMode(m)},async streamInput(m){typeof h.streamInput=="function"&&await h.streamInput(m)},async interrupt(){typeof h.interrupt=="function"&&await h.interrupt()}}}buildUserMessage(t,r){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:r}}}});import{spawn as ny}from"node:child_process";import oy from"node:readline";function iy(e){return e instanceof Error?e.message:String(e)}function sy(e){try{let t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}async function ay(e,t){if(e.id!=null&&(Object.hasOwn(e,"result")||Object.hasOwn(e,"error"))){let n=String(e.id),o=t.pending.get(n);if(!o)return;if(clearTimeout(o.timer),t.pending.delete(n),e.error){o.reject(new Error(`codex app server rpc error (${e.error.code??"unknown"}): ${e.error.message??"unknown error"}`));return}o.resolve(e.result);return}let r=e.method?.trim();if(r){if(e.id==null){await t.onNotification(r,e.params);return}try{let n=await t.onRequest(r,e.params);t.respond({jsonrpc:"2.0",id:e.id,result:n??{}})}catch(n){t.respond({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:iy(n)}})}}}var Qo,yl=u(()=>{Qo=class{constructor(t,r,n){this.command=t;this.args=r;this.requestTimeoutMs=n}process=null;pending=new Map;counter=0;onNotification=()=>{};onRequest=async()=>({});setNotificationHandler(t){this.onNotification=t}setRequestHandler(t){this.onRequest=t}async connect(){if(this.process)return;let t=ny(this.command,["app-server",...this.args],{stdio:["pipe","pipe","pipe"],env:process.env});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("codex app server stdio pipes unavailable");this.process=t,oy.createInterface({input:t.stdout}).on("line",n=>{this.handleLine(n)}),t.stderr.on("data",()=>{}),t.on("close",()=>{this.flushPending(new Error("codex app server stdio closed")),this.process=null})}async close(){this.flushPending(new Error("codex app server stdio closed"));let t=this.process;this.process=null,t&&t.kill()}async notify(t,r){this.write({jsonrpc:"2.0",method:t,params:r??{}})}async request(t,r,n){let o=`rpc-${++this.counter}`,i=new Promise((s,a)=>{let d=setTimeout(()=>{this.pending.delete(o),a(new Error(`codex app server timeout: ${t}`))},Math.max(100,n??this.requestTimeoutMs));d.unref?.(),this.pending.set(o,{resolve:s,reject:a,timer:d})});return this.write({jsonrpc:"2.0",id:o,method:t,params:r??{}}),await i}write(t){if(!this.process?.stdin)throw new Error("codex app server stdio not connected");this.process.stdin.write(`${JSON.stringify(t)}
|
|
3
|
+
`)}async handleLine(t){let r=sy(t);r&&await ay(r,{pending:this.pending,onNotification:this.onNotification,onRequest:this.onRequest,respond:n=>this.write(n)})}flushPending(t){for(let[r,n]of this.pending)clearTimeout(n.timer),n.reject(t),this.pending.delete(r)}}});function J(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ae(e,t,r){for(let n of t){let o=e?.[n];if(typeof o!="string")continue;let i=r?.trim===!1?o:o.trim();if(i)return i}}function dy(e){return e instanceof Error?e.message:String(e)}function wl(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Yt(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(r=>Yt(r)).join("");let t=J(e);if(!t)return"";for(let r of["delta","text","content","message","input","output","parts"]){let n=Yt(t[r]);if(n)return n}for(let r of["item","turn","thread","response","result","data"]){let n=Yt(t[r]);if(n)return n}return""}function En(e){let t=J(e);if(!t)return{};let r=J(t.thread)??J(t.session),n=J(t.turn)??J(t.run),o=J(t.item),i=J(t.serverRequest);return{threadId:ae(t,["threadId","thread_id","conversationId","conversation_id"])??ae(r,["id","threadId","thread_id","conversationId"]),runId:ae(t,["turnId","turn_id","runId","run_id"])??ae(n,["id","turnId","turn_id","runId","run_id"]),requestId:ae(t,["requestId","request_id","serverRequestId"])??ae(i,["id","requestId","request_id"]),itemId:ae(t,["itemId","item_id"])??ae(o,["id","itemId","item_id"])}}function Jo(e,t,r=0){if(r>6)return;if(Array.isArray(e)){for(let i of e){let s=Jo(i,t,r+1);if(s)return s}return}let n=J(e);if(!n)return;let o=ae(n,t);if(o)return o;for(let i of Object.values(n)){let s=Jo(i,t,r+1);if(s)return s}}function $n(e){return{threadId:En(e).threadId,cwd:Jo(e,["cwd","workdir","directory"])}}function Il(e){let t=e?.trim();return!!(t&&/[/\\]worktrees[/\\][^/\\]+[/\\][^/\\]+/.test(t))}function xl(e){let t=e?.trim();if(!t)return;let r=t.split(/[/\\]+/).filter(Boolean),n=r.lastIndexOf("worktrees");if(!(n<0||n+1>=r.length))return r[n+1]}function Yo(e){let t=J(e);if(!t)return;let r=J(t.item)??t;return ae(r,["id","itemId","item_id","messageId","message_id"])}function uy(e,t=!1){let r=J(e);if(!r)return"";let n=J(r.item)??r;return ae(n,["type"])?.toLowerCase()!=="agentmessage"?"":t?Yt(n):ae(n,["text"],{trim:!1})??Yt(n)}function Pl(e,t){let r=e.trim().toLowerCase();return r==="item/agentmessage/delta"?{mode:"delta",text:Yt(t),itemId:Yo(t)}:r==="item/completed"?{mode:"snapshot",text:uy(t),itemId:Yo(t)}:{mode:"ignore",text:""}}function bl(e){return{itemId:Yo(e),delta:Yt(e)}}function vl(e){let t=J(e),r=J(t?.plan),o=(Array.isArray(t?.plan)?t.plan:Array.isArray(r?.steps)?r.steps:[]).map(i=>{let s=J(i),a=ae(s,["step","title","text"]);if(!a)return null;let d=ae(s,["status"])?.toLowerCase()??"pending";return{step:a,status:d==="inprogress"||d==="in_progress"?"inProgress":d==="completed"?"completed":"pending"}}).filter(Boolean);return{explanation:ae(r,["explanation"])??ae(t,["explanation"]),steps:o}}function Rl(e){let t=J(e);if(!t)return{};let r=J(t.item)??t;return ae(r,["type"])?.toLowerCase()!=="plan"?{}:{itemId:Yo(r),text:ae(r,["text"],{trim:!1})??Yt(r)}}function Al(e,t){let r=e.trim().toLowerCase();if(r==="turn/failed"||r==="turn/cancelled")return!1;let n=J(t)??{},o=J(n.turn)??n,i=ae(o,["status"])?.toLowerCase();return i!=="failed"&&i!=="interrupted"&&i!=="cancelled"}function Tl(e,t){let r=J(t)??{},n=J(r.turn)??r,o=J(n.error)??J(r.error);if(o)return ae(o,["message","text","summary","reason"])}function py(e,t){let r=dy(e).toLowerCase();return r.includes("method not found")||r.includes("unknown method")?!0:r.includes("unknown variant")?t?r.includes(`unknown variant \`${t.toLowerCase()}\``):!0:!1}function ly(e){return cy.has(e.trim().toLowerCase())}function my(e){let t=J(e);return t?!!ae(t,["threadId","thread_id"]):!1}async function On(e){if(e.payloads.length===0)throw new Error(`codex app server request skipped: no payloads for ${e.methods.join(", ")||"<none>"}`);let t;for(let r of e.methods)for(let n of e.payloads){if(ly(r)&&!my(n))throw new Error(`codex app server request missing threadId: ${r}`);try{return await e.client.request(r,n,e.timeoutMs)}catch(o){if(t=o,!py(o,r))continue}}throw t instanceof Error?t:new Error(String(t))}function Ml(e){let t={cwd:e.cwd};e.model?.trim()&&(t.model=e.model.trim()),e.approvalPolicy?.trim()&&(t.approvalPolicy=e.approvalPolicy.trim()),e.sandbox?.trim()&&(t.sandbox=e.sandbox.trim());let r={cwd:e.cwd};return e.approvalPolicy?.trim()&&(r.approvalPolicy=e.approvalPolicy.trim()),e.sandbox?.trim()&&(r.sandbox=e.sandbox.trim()),[t,r,{}]}function Cl(e){let t={threadId:e.threadId,persistExtendedHistory:!1};return e.model?.trim()&&(t.model=e.model.trim()),e.reasoningEffort?.trim()&&(t.reasoningEffort=e.reasoningEffort.trim()),e.cwd?.trim()&&(t.cwd=e.cwd.trim()),e.approvalPolicy?.trim()&&(t.approvalPolicy=e.approvalPolicy.trim()),e.sandbox?.trim()&&(t.sandbox=e.sandbox.trim()),[t]}function fy(e){return[{type:"text",text:e}]}function gy(e,t,r){let n=t?.trim();if(e!=="plan")return n?{mode:"default",settings:{model:n,...r?.trim()?{reasoningEffort:r.trim()}:{},developerInstructions:null}}:void 0;if(n)return{mode:"plan",settings:{model:n,...r?.trim()?{reasoningEffort:r.trim()}:{},developerInstructions:null}}}function El(e){let t={threadId:e.threadId,input:fy(e.prompt)};e.model?.trim()&&(t.model=e.model.trim()),e.approvalPolicy?.trim()&&(t.approvalPolicy=e.approvalPolicy.trim()),e.sandbox?.trim()&&(t.sandbox=e.sandbox.trim());let r=gy(e.permissionMode??"default",e.model,e.reasoningEffort);return r?[{...t,collaborationMode:r},{...t,collaboration_mode:{mode:r.mode,settings:{model:r.settings.model,...typeof r.settings.reasoningEffort=="string"?{reasoning_effort:r.settings.reasoningEffort}:{},developer_instructions:null}}},t]:[t]}function $l(e){return[{threadId:e.threadId,turnId:e.turnId}]}function hy(e){let t=J(e);if(!t)return[];let r=t.options??t.choices??t.availableDecisions??t.decisions;return Array.isArray(r)?r.map(n=>typeof n=="string"?n.trim():ae(J(n),["label","title","text","value","name","id"])??"").filter(Boolean):[]}function Sy(e){let t=e.trim().toLowerCase();return t.includes("session")?"acceptForSession":/cancel|abort|stop/.test(t)?"cancel":/deny|decline|reject|block|no/.test(t)?"decline":/approve|allow|accept|yes/.test(t)?"accept":e.trim()}function Ol(e,t,r){let n=e.trim().toLowerCase(),o=hy(r),i=Jo(r,["question","prompt","message","text","summary","reason"])??void 0,s=n.includes("requestapproval"),a=s?o.map(d=>({kind:"approval",label:d,decision:Sy(d),responseDecision:d})):o.map(d=>({kind:"option",label:d,value:d}));return{requestId:t,kind:s?"approval":"question",promptText:i,options:o,actions:a,allowsFreeText:!0}}function _l(e){let t=e.trim().toLowerCase();return t.includes("requestuserinput")||t.includes("requestapproval")}function ja(e,t){let r=e==="bypassPermissions"?"never":t?.trim()||"never";return{approvalPolicy:r,sandbox:r==="never"?"danger-full-access":void 0}}var cy,Nl=u(()=>{cy=new Set(["thread/resume","turn/start","turn/steer","turn/interrupt"])});function Fl(e){return e instanceof Error?e.message:String(e)}function xy(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return String(e);let t=e;return typeof t.message?.content=="string"?t.message.content:typeof t.text=="string"?t.text:String(e)}var ky,mr,yy,wy,Iy,Xo,Dl=u(()=>{yl();Ka();Nl();ky="1.0",mr=6e4,yy="OPENCLAW_CODEX_APP_SERVER_COMMAND",wy="OPENCLAW_CODEX_APP_SERVER_ARGS",Iy="OPENCLAW_CODEX_APP_SERVER_TIMEOUT_MS";Xo=class{constructor(t={}){this.deps=t}name="codex";backendKind="codex-app-server";supportedPermissionModes=["default","plan","bypassPermissions"];capabilities={nativePendingInput:!0,nativePlanArtifacts:!0,worktrees:"native-restore"};launch(t){let r={command:process.env[yy]?.trim()||"codex",args:wl(process.env[wy]),requestTimeoutMs:Number.parseInt(process.env[Iy]??String(mr),10)||mr},n=this.deps.createClient?.(r)??new Qo(r.command,r.args,r.requestTimeoutMs),o=new Br,i=t.resumeSessionId,s,a=t.backendRef?.worktreePath,d=t.backendRef?.worktreeId,c=t.permissionMode??"default",h,m=0,S="",y=[],x,$=new Map,re=new Set,R=C=>{let A=C?.trim();if(!A)return;let _=t.originalWorkdir?.trim()||t.cwd.trim();t.worktreeStrategy&&t.worktreeStrategy!=="off"&&A!==_&&Il(A)&&(a=A,d=xl(A))},W=()=>{i&&o.enqueue(jo({kind:"codex-app-server",conversationId:i,...s?{runId:s}:{},...d?{worktreeId:d}:{},...a?{worktreePath:a}:{}}))};n.setNotificationHandler(async(C,A)=>{let _=C.trim().toLowerCase(),G=En(A),ye=$n(A);if(G.threadId&&i&&G.threadId!==i)return;if(G.threadId&&(i=G.threadId),G.runId&&(s=G.runId),R(ye.cwd),(G.threadId||G.runId||ye.cwd)&&W(),_==="serverrequest/resolved"){h&&(o.enqueue(Kr(h.requestId)),h=void 0);return}if(_==="turn/plan/updated"){let be=vl(A);S=be.explanation??S,be.steps.length>0&&(y=be.steps);return}if(_==="item/plan/delta"){let be=bl(A);if(be.itemId&&be.delta){let Dt=$.get(be.itemId)??"";$.set(be.itemId,`${Dt}${be.delta}`)}return}if(_==="item/completed"){let be=Rl(A);if(be.text?.trim()){let Dt={explanation:S||void 0,steps:y,markdown:be.text.trim()};o.enqueue(Ho(Dt,!0));return}}let ne=Pl(_,A);if(ne.mode==="delta"&&ne.text){ne.itemId&&re.add(ne.itemId),o.enqueue(Cn(ne.text));return}ne.mode==="snapshot"&&ne.text&&(!ne.itemId||!re.has(ne.itemId))&&o.enqueue(Cn(ne.text)),(_==="turn/completed"||_==="turn/failed"||_==="turn/cancelled")&&x&&(x.method=C,x.params=A,x.resolve())}),n.setRequestHandler(async(C,A)=>{if(!_l(C))return{};let _=En(A),G=$n(A);if(_.threadId&&i&&_.threadId!==i)return{};_.threadId&&(i=_.threadId),_.runId&&(s=_.runId),R(G.cwd),(_.threadId||_.runId||G.cwd)&&W();let ye=_.requestId??`${i??"codex"}-${Date.now().toString(36)}`,ne=Ol(C,ye,A),be=C.trim().toLowerCase(),Dt=ne.options,sf=ne.actions??[],af=await new Promise(df=>{h={requestId:ye,methodLower:be,state:ne,options:Dt,actions:sf,resolveResponse:df},o.enqueue(Vo(ne))});return h=void 0,o.enqueue(Kr(ye)),af});let I=async()=>{await n.connect(),await n.request("initialize",{protocolVersion:ky,clientInfo:{name:"openclaw-code-agent",version:"3.1.0"},capabilities:{experimentalApi:!0}},mr),await n.notify("initialized",{})},v=async()=>{let C=ja(c,t.codexApprovalPolicy);if(i){let G=await On({client:n,methods:["thread/resume"],payloads:Cl({threadId:i,model:t.model,reasoningEffort:t.reasoningEffort,approvalPolicy:C.approvalPolicy,sandbox:C.sandbox}),timeoutMs:mr}),ye=$n(G);i=ye.threadId??i,R(ye.cwd),W();return}let A=await On({client:n,methods:["thread/start","thread/new"],payloads:Ml({cwd:t.originalWorkdir?.trim()||t.cwd,model:t.model,approvalPolicy:C.approvalPolicy,sandbox:C.sandbox}),timeoutMs:mr}),_=$n(A);if(i=_.threadId,!i)throw new Error("Codex App Server did not return a thread id.");R(_.cwd),W()},de=async C=>{await v(),o.enqueue(qo()),m+=1,S="",y=[],$.clear(),re.clear();let A="",_,G,ye=new Promise(ne=>{G=ne});x={resolve:G};try{let ne=ja(c,t.codexApprovalPolicy),be=await On({client:n,methods:["turn/start"],payloads:El({threadId:i,prompt:C,model:t.model,reasoningEffort:t.reasoningEffort,permissionMode:c,approvalPolicy:ne.approvalPolicy,sandbox:ne.sandbox}),timeoutMs:mr}),Dt=En(be);Dt.runId&&(s=Dt.runId,W()),await ye,A=x?.method??"turn/failed",_=x?.params,o.enqueue(lr({success:Al(A,_),duration_ms:0,total_cost_usd:0,num_turns:m,result:Tl(A,_),session_id:i}))}catch(ne){o.enqueue(lr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:Fl(ne),session_id:i??""}))}finally{x=void 0}},yr=async C=>h?(h.methodLower.includes("requestapproval")?h.resolveResponse({decision:C.trim()||"decline"}):h.resolveResponse({text:C.trim()}),!0):!1,qn=async C=>{let A=h;if(!A)return!1;let _=A.actions[C];if(_?.kind==="approval")return A.resolveResponse({decision:_.responseDecision,..._.proposedExecpolicyAmendment?{proposedExecpolicyAmendment:_.proposedExecpolicyAmendment}:{}}),!0;let G=A.options[C];return G?(A.methodLower.includes("requestapproval")?A.resolveResponse({decision:G}):A.resolveResponse({option:G,index:C}),!0):!1},Vn=typeof t.prompt=="string"?(async function*(){yield{type:"user",text:t.prompt,session_id:t.resumeSessionId??""}})():t.prompt;return(async()=>{try{await I();for await(let C of Vn){let A=xy(C).trim();!A||await yr(A)||await de(A)}}catch(C){o.enqueue(lr({success:!1,duration_ms:0,total_cost_usd:0,num_turns:m,result:Fl(C),session_id:i??t.resumeSessionId??""}))}finally{await n.close().catch(()=>{}),o.close()}})(),{messages:o.messages(),async setPermissionMode(C){c=C,o.enqueue(Go(C))},async submitPendingInputOption(C){return qn(C)},async interrupt(){!i||!s||await On({client:n,methods:["turn/interrupt"],payloads:$l({threadId:i,turnId:s}),timeoutMs:mr}).catch(()=>{})}}}buildUserMessage(t,r){return{type:"user",text:t,session_id:r}}}});function Ll(e){qa.set(e.name,e)}function _n(e){let t=qa.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...qa.keys()].join(", ")}`);return t}function Ul(){return _n(De())}var qa,Va=u(()=>{kl();Dl();Le();qa=new Map;Ll(new zo);Ll(new Xo)});function T(e){return e.backendRef?.conversationId??e.harnessSessionId}function ee(e){return e.id??e.sessionId??e.name??T(e)??e.harnessSessionId}function Py(e){return e.harnessSessionId}function ze(e){let t=[ee(e),T(e),Py(e)].filter(r=>!!r);return[...new Set(t)]}function Ha(e){return e.harnessName??e.persistedHarness??De()}function Zo(e){if(e.backendRef?.kind==="codex-app-server")return"native-restore";try{return _n(Ha(e)).capabilities.worktrees}catch{return"plugin-managed"}}function Ga(e){return e==="native-execution"||e==="native-restore"}function Wl(e){return e==="native-restore"}function by(e){return!!(e.backendRef?.worktreePath||e.backendRef?.worktreeId)}function ot(e){return Ga(Zo(e))&&by(e)}var ke=u(()=>{Le();Va()});import{execFileSync as Ue}from"child_process";import{statfsSync as By}from"fs";import{tmpdir as Ky}from"os";import{dirname as jy,join as qy}from"path";function Vy(e){try{return Ue("git",["rev-parse","--show-toplevel"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{return}}function Ja(e){if(process.env.OPENCLAW_WORKTREE_DIR)return process.env.OPENCLAW_WORKTREE_DIR;if(E.worktreeDir)return E.worktreeDir;if(e){let t=Vy(e);if(t)return qy(t,".worktrees")}return Ky()}function rm(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").replace(/\.{2,}/g,"-").replace(/^[-.]|[-.]$/g,"").slice(0,100)||"session"}function si(e){try{let t=Ue("git",["-C",e,"rev-parse","--git-common-dir"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return t&&t.endsWith("/.git")?jy(t):void 0}catch{return}}function Hy(){if(oi!==void 0)return oi;try{return Ue("git",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),oi=!0,!0}catch{return oi=!1,!1}}function Pt(){if(ii!==void 0)return ii;try{return Ue("gh",["--version"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),ii=!0,!0}catch{return ii=!1,!1}}function Ya(e){if(!Hy())return!1;try{return Ue("git",["rev-parse","--git-dir"],{cwd:e,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function nm(){try{let e=Ja(),t=By(e),r=t.bavail*t.bsize,n=100*1024*1024;return r>=n}catch(e){return console.warn(`[worktree] Failed to check free space: ${e instanceof Error?e.message:String(e)}`),!0}}function om(e,t){try{return Ue("git",["-C",e,"rev-parse","--verify",t],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function gt(e){let t=process.env.OPENCLAW_WORKTREE_BASE_BRANCH?.trim();if(t)return t;try{let n=Ue("git",["-C",e,"rev-parse","--abbrev-ref","origin/HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().replace(/^origin\//,"");if(n)return n}catch{}try{return Ue("git",["-C",e,"rev-parse","--verify","main"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"main"}catch{}try{return Ue("git",["-C",e,"rev-parse","--verify","master"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),"master"}catch{return"main"}}function ai(e){try{let r=Ue("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r==="HEAD"){console.warn(`[worktree] Worktree ${e} is in detached HEAD state \u2014 cannot determine branch name`);return}return r||void 0}catch{return}}function Dn(e,t,r){try{let n=Ue("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(n.trim(),10)>0}catch{return!1}}function bt(e,t){try{return Ue("git",["-C",e,"branch","-D",t],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(r){return console.warn(`[worktree] Failed to delete branch ${t}: ${r instanceof Error?r.message:String(r)}`),!1}}function im(e,t){if(t)return t;try{let r=Ue("git",["-C",e,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),n=Ue("git",["-C",e,"remote","get-url","upstream"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n&&n!==r){let o=n.match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/);if(o)return o[1]}}catch{}}var oi,ii,di=u(()=>{Le()});import{execFileSync as Ln}from"child_process";import{existsSync as Gy,mkdirSync as sm,rmSync as am}from"fs";function Xa(e,t){let r=rm(t),n=Ja(e);sm(n,{recursive:!0});let o,i,s=10;for(let d=0;d<s;d++){let c=d===0?"":`-${Math.random().toString(16).slice(2,6)}`,h=`${n}/openclaw-worktree-${r}${c}`,m=`agent/${r}${c}`;try{sm(h,{recursive:!1}),o=h,i=m;break}catch(S){if(S&&typeof S=="object"&&"code"in S&&S.code==="EEXIST")continue;throw S}}if(!o||!i)throw new Error(`Failed to create unique worktree directory after ${s} attempts`);let a=om(e,i);try{a?Ln("git",["-C",e,"worktree","add",o,i],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):Ln("git",["-C",e,"worktree","add","-b",i,o],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(d){try{am(o,{recursive:!0,force:!0})}catch{}throw d}return o}function zy(e){if(!Gy(e))return[];try{let t=Ln("git",["-C",e,"status","--porcelain","--untracked-files=all"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return t?t.split(`
|
|
4
|
+
`).map(r=>r.trim()).filter(Boolean):[]}catch{return[]}}function ht(e,t,r={}){let n=r.destructive===!0,o=zy(t);if(o.length>0&&!n)return console.warn(`[worktree] Refusing implicit cleanup for dirty worktree ${t}: ${o[0]}`),!1;try{return Ln("git",["-C",e,"worktree","remove",...n?["--force"]:[],t],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(i){if(console.warn(`[worktree] git worktree remove failed for ${t}: ${i instanceof Error?i.message:String(i)}`),!n)return!1;try{return am(t,{recursive:!0,force:!0}),console.info(`[worktree] Fallback rmSync succeeded for ${t}`),!0}catch(s){return console.error(`[worktree] Both git worktree remove and rmSync failed for ${t}: ${s instanceof Error?s.message:String(s)}`),!1}}}function ui(e){try{Ln("git",["-C",e,"worktree","prune"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}}var dm=u(()=>{di()});import{execFileSync as te}from"child_process";import{existsSync as Qy}from"fs";function Ft(e,t,r){try{let n=te("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),o=parseInt(n.trim(),10),s=te("git",["-C",e,"diff","--shortstat",`${r}...${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),a=0,d=0,c=0,h=s.match(/(\d+)\s+files?\s+changed/);h&&(a=parseInt(h[1],10));let m=s.match(/(\d+)\s+insertions?\(/);m&&(d=parseInt(m[1],10));let S=s.match(/(\d+)\s+deletions?\(/);S&&(c=parseInt(S[1],10));let x=te("git",["-C",e,"diff","--name-only","--diff-filter=ACMR",`${r}...${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
5
|
+
`).map(R=>R.trim()).filter(Boolean),re=te("git",["-C",e,"log",`${r}..${t}`,"--format=%h|%s|%an","-n","5"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
6
|
+
`).filter(Boolean).map(R=>{let[W,I,v]=R.split("|");return{hash:W||"",message:I||"",author:v||""}});return{commits:o,filesChanged:a,insertions:d,deletions:c,changedFiles:x,commitMessages:re}}catch(n){console.warn(`[worktree] Failed to get diff summary: ${n instanceof Error?n.message:String(n)}`);return}}function ci(e,t,r="origin"){try{return te("git",["-C",e,"push",r,t],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(n){return console.warn(`[worktree] Failed to push branch ${t}: ${n instanceof Error?n.message:String(n)}`),!1}}function pi(e){try{return te("git",["-C",e,"status","--porcelain"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).split(`
|
|
7
|
+
`).some(r=>r.length>0&&!r.startsWith("??")&&!r.startsWith("!!"))}catch{return!1}}function li(e,t,r,n="merge",o){let i=!1,s,a=d=>{if(i)try{te("git",["-C",d,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}};try{if(n==="squash"){if(te("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),pi(e)){let S;try{S=te("git",["-C",e,"stash","push","-m",`pre-merge stash before ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(y){return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${y instanceof Error?y.message:String(y)}. Commit or stash changes manually, then retry.`}}if(!S.includes("No local changes to save")){i=!0;try{s=te("git",["-C",e,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}te("git",["-C",e,"merge","--squash",t],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),te("git",["-C",e,"commit","-m",`Squash merge ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let m=!1;if(i)try{te("git",["-C",e,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{m=!0}return{success:!0,stashed:i||void 0,stashRef:s,stashPopConflict:m||void 0}}let d=o&&Qy(o),c=d?o:e;if(d||te("git",["-C",e,"checkout",t],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),pi(e)){let m;try{m=te("git",["-C",e,"stash","push","-m",`pre-merge stash before ${t}`],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(S){try{te("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return{success:!1,dirtyError:!0,error:`Auto-stash failed: ${S instanceof Error?S.message:String(S)}. Commit or stash changes manually, then retry.`}}if(!m.includes("No local changes to save")){i=!0;try{s=te("git",["-C",e,"stash","list","--format=%gd","-n","1"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||void 0}catch{}}}try{te("git",["-C",c,"rebase",r],{timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{try{te("git",["-C",c,"rebase","--abort"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}try{te("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(e),{success:!1,rebaseConflict:!0,stashed:i||void 0,stashRef:s,error:[`Rebase of ${t} onto ${r} hit conflicts.`,"To resolve manually:",` cd ${c}`,` git rebase ${r}`," # resolve conflicts in each file, then:"," git add <file>"," git rebase --continue"," # repeat until rebase finishes, then re-run agent_merge."].join(`
|
|
8
|
+
`)}}te("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),te("git",["-C",e,"merge","--ff-only",t],{timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let h=!1;if(i)try{te("git",["-C",e,"stash","pop"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{h=!0}return{success:!0,fastForward:!0,stashed:i||void 0,stashRef:s,stashPopConflict:h||void 0}}catch(d){try{te("git",["-C",e,"checkout",r],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{}return a(e),{success:!1,error:d instanceof Error?d.message:String(d),stashed:i||void 0,stashRef:s}}}var um=u(()=>{});import{execFileSync as mi}from"child_process";function pm(e,t,r,n,o,i){if(!Pt())return{success:!1,error:"GitHub CLI (gh) is not available"};try{let s;if(i)try{let m=mi("git",["-C",e,"remote","get-url","origin"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[:/]([^/]+)\/[^/]+(?:\.git)?$/);m&&(s=m[1])}catch{}let a=["pr","create","--base",r];return i&&a.push("--repo",i),s?a.push("--head",`${s}:${t}`):a.push("--head",t),n&&o?a.push("--title",n,"--body",o):a.push("--fill-verbose"),{success:!0,prUrl:mi("gh",a,{cwd:e,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}function Za(e,t,r){if(!Pt())return{exists:!1,state:"none"};try{let n=["pr","list","--head",t,"--state","all","--json","url,number,title,state","--jq",".[0]"];r&&n.push("--repo",r);let i=mi("gh",n,{cwd:e,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!i)return{exists:!1,state:"none"};let s=JSON.parse(i),a=s.state.toLowerCase();return{exists:!0,state:a==="open"?"open":a==="merged"?"merged":a==="closed"?"closed":"none",url:s.url,number:s.number,title:s.title}}catch(n){return console.warn(`[worktree] Failed to sync PR status for ${t}: ${n instanceof Error?n.message:String(n)}`),{exists:!1,state:"none"}}}function cm(e,t,r,n){if(!Pt())return!1;try{let o=["pr","comment",String(t),"--body",r];return n&&o.push("--repo",n),mi("gh",o,{cwd:e,timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch(o){return console.warn(`[worktree] Failed to comment on PR #${t}: ${o instanceof Error?o.message:String(o)}`),!1}}function gr(e){if(e.kind==="merge"){let t=e.filesChanged!==void 0?` (${e.filesChanged} files, +${e.insertions??0}/-${e.deletions??0})`:"";return`\u2705 Merged: ${e.branch} \u2192 ${e.base??"main"}${t}`}return e.kind==="pr-updated"?`\u2705 PR updated: ${e.prUrl??""}`:e.targetRepo?`\u2705 PR opened against ${e.targetRepo}: ${e.prUrl??""}`:`\u2705 PR opened: ${e.prUrl??""}`}var lm=u(()=>{di()});var Qe=u(()=>{di();dm();um();lm()});function Vr(e,t){let r=e.resolve(t),n=e.getPersistedSession(t),o=r?ee(r):n?ee(n):void 0;return{activeSession:r,persistedSession:n,persistedRef:o,sessionName:r?.name??n?.name??t,worktreePath:r?.worktreePath??n?.worktreePath,originalWorkdir:r?.originalWorkdir??n?.workdir,branchName:r?.worktreeBranch??n?.worktreeBranch,notificationTarget:r??(n?{id:o??t,harnessSessionId:n.harnessSessionId,backendRef:n.backendRef,route:n.route}:void 0)}}function Ii(e){return e.persistedSession?ze(e.persistedSession):[]}function Tm(e){let t=e.list("all").filter(o=>o.worktreePath),r=e.listPersistedSessions().filter(o=>o.worktreePath),n=new Map;for(let o of r){if(!o.worktreePath)continue;let i=T(o),s=o.sessionId??i??o.harnessSessionId;s&&n.set(s,{id:o.sessionId??i??o.harnessSessionId,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.workdir,worktreeMerged:o.worktreeMerged,worktreeMergedAt:o.worktreeMergedAt,worktreePrUrl:o.worktreePrUrl,backendConversationId:i,harnessSessionId:o.harnessSessionId})}for(let o of t)o.worktreePath&&n.set(o.id,{id:o.id,name:o.name,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,workdir:o.originalWorkdir??o.workdir,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0,backendConversationId:T(o),harnessSessionId:o.harnessSessionId});return Array.from(n.values())}function nd(e,t){return e.id===t||e.name===t||e.backendConversationId===t||e.harnessSessionId===t}var Wn=u(()=>{ke()});var Mm={};Hn(Mm,{makeAgentPrTool:()=>Bn});import{existsSync as xw}from"fs";function Pw(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function Bn(e){return{name:"agent_pr",description:"Create or update a GitHub PR for a worktree branch. Handles full PR lifecycle: creates new PRs, updates existing open PRs with comments, and handles merged/closed PRs. Pushes the branch, syncs PR state, and persists metadata.",parameters:g.Object({session:g.String({description:"Session name or ID to create/update PR for"}),title:g.Optional(g.String({description:"PR title (default: auto-generated from session name)"})),body:g.Optional(g.String({description:"PR body (default: auto-generated from commit summary)"})),base_branch:g.Optional(g.String({description:"Base branch for the PR (default: detected from repo)"})),force_new:g.Optional(g.Boolean({description:"Force creation of a new PR even if one exists (default: false)"})),target_repo:g.Optional(g.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex'). Auto-detected from 'upstream' remote if not set."}))}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}],meta:{success:!1,state:"error"}};if(!Pw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, title?, body?, base_branch?, force_new? }."}],meta:{success:!1,state:"error"}};if(!Pt())return{content:[{type:"text",text:"Error: GitHub CLI (gh) is not available. Install it and authenticate to create PRs."}],meta:{success:!1,state:"error"}};let n=Vr(k,r.session),o=n.activeSession,i=n.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}],meta:{success:!1,state:"error"}};let{worktreePath:s,originalWorkdir:a,sessionName:d,branchName:c}=n;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}],meta:{success:!1,state:"error"}};if(!c)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree ${s}. The worktree may have been removed and no persisted branch name is available.`}],meta:{success:!1,state:"error"}};xw(s)||console.info(`[agent_pr] Worktree directory ${s} no longer exists; proceeding with branch "${c}" via originalWorkdir (${a})`);let h=r.base_branch??gt(a),m=n.persistedRef,S=im(a,r.target_repo??i?.worktreePrTargetRepo);if(!ci(a,c))return{content:[{type:"text",text:`\u274C Failed to push ${c} \u2014 cannot create/update PR`}],meta:{success:!1,state:"error"}};let y=Za(a,c,S);if(r.force_new&&y.exists)return{content:[{type:"text",text:`\u26A0\uFE0F Cannot create new PR: A PR already exists for ${c} (${y.state}).
|
|
39
9
|
|
|
40
|
-
|
|
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}).
|
|
10
|
+
Existing PR: ${y.url}
|
|
42
11
|
|
|
43
|
-
|
|
12
|
+
To create a new PR, you must first close/merge the existing PR manually or use a different branch.`}],meta:{success:!1,state:"error"}};if(y.exists&&y.state==="open"){let x=Ft(a,c,h);if(x&&x.commits>0){let $=x.commitMessages.slice(0,5).map(I=>`\u2022 ${I.hash} ${I.message} (${I.author})`).join(`
|
|
13
|
+
`),re=x.commits>5?`
|
|
14
|
+
...and ${x.commits-5} more commits`:"",R=["\u{1F504} **New commits pushed**","",`${x.commits} new commits (+${x.insertions} / -${x.deletions})`,"","### Latest commits:",$+re,"","---","\u{1F916} [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
|
|
15
|
+
`);if(cm(a,y.number,R,S)){m&&k.updatePersistedSession(m,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0});let I=gr({kind:"pr-updated",branch:c,prUrl:y.url});return k.notifyWorktreeOutcome(n.notificationTarget,I),{content:[{type:"text",text:`${I}
|
|
44
16
|
|
|
45
|
-
|
|
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}
|
|
17
|
+
\u{1F4DD} Added comment detailing ${x.commits} new commits (+${x.insertions} / -${x.deletions})`}],meta:{success:!0,state:"pr_updated"}}}else return{content:[{type:"text",text:`\u26A0\uFE0F Pushed to ${y.url} but failed to add comment.
|
|
49
18
|
|
|
50
|
-
|
|
19
|
+
${x.commits} new commits (+${x.insertions} / -${x.deletions})`}],meta:{success:!0,state:"pr_open"}}}else return m&&k.updatePersistedSession(m,{worktreePrUrl:y.url,worktreePrNumber:y.number,lifecycle:"terminal",worktreeState:"pr_open",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0}),{content:[{type:"text",text:`\u2139\uFE0F PR already exists and is up to date: ${y.url}
|
|
51
20
|
|
|
52
|
-
|
|
21
|
+
No new commits to push.`}],meta:{success:!0,state:"pr_open"}}}else{if(y.exists&&y.state==="merged")return m&&k.updatePersistedSession(m,{worktreePrUrl:y.url,worktreePrNumber:y.number,worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDisposition:"merged"}),{content:[{type:"text",text:`\u2705 PR was already merged: ${y.url}
|
|
53
22
|
|
|
54
|
-
|
|
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}
|
|
23
|
+
The worktree branch ${c} can be cleaned up with agent_merge(delete_branch=true).`}],meta:{success:!0,state:"merged"}};if(y.exists&&y.state==="closed")return{content:[{type:"text",text:`\u26A0\uFE0F A PR exists but was closed without merging: ${y.url}
|
|
57
24
|
|
|
58
25
|
What would you like to do?
|
|
59
26
|
|
|
@@ -61,63 +28,101 @@ What would you like to do?
|
|
|
61
28
|
2. Close and delete the branch with agent_merge(delete_branch=true), then start a new session/worktree
|
|
62
29
|
3. Manually delete the closed PR on GitHub, then call agent_pr(force_new=true) to create a fresh PR
|
|
63
30
|
|
|
64
|
-
(This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}]};{let
|
|
65
|
-
`),
|
|
66
|
-
...and ${
|
|
67
|
-
`)}else
|
|
68
|
-
`)
|
|
69
|
-
`)
|
|
70
|
-
`)
|
|
71
|
-
`)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
${
|
|
78
|
-
`)}).
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
`)
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
95
|
-
|
|
96
|
-
`),
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
`)
|
|
100
|
-
|
|
101
|
-
`)
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
`),
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
31
|
+
(This tool cannot automatically reopen or recreate PRs to avoid unintended actions.)`}],meta:{success:!1,state:"closed"}};{let x=r.title??`[openclaw-code-agent] ${d}`,$=r.body;if(!$){let R=Ft(a,c,h);if(R){let W=R.commitMessages.slice(0,5).map(v=>`\u2022 ${v.hash} ${v.message} (${v.author})`).join(`
|
|
32
|
+
`),I=R.commits>5?`
|
|
33
|
+
...and ${R.commits-5} more`:"";$=[`Automated changes from OpenClaw Code Agent session: ${d}`,"","## Summary",`${R.commits} commits, ${R.filesChanged} files changed (+${R.insertions} / -${R.deletions})`,"","## Commits",W+I,"","---","\u{1F916} Generated with [openclaw-code-agent](https://github.com/goldmar/openclaw-code-agent)"].join(`
|
|
34
|
+
`)}else $=`Automated changes from OpenClaw Code Agent session: ${d}`}let re=pm(a,c,h,x,$,S);if(re.success&&re.prUrl){let R=Za(a,c,S);m&&k.updatePersistedSession(m,{worktreePrUrl:re.prUrl,worktreePrNumber:R.number,lifecycle:"terminal",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeState:"pr_open",worktreeDisposition:"pr-opened"});let W=gr({kind:"pr-opened",branch:c,targetRepo:S,prUrl:re.prUrl});return k.notifyWorktreeOutcome(n.notificationTarget,W),{content:[{type:"text",text:W}],meta:{success:!0,state:"created"}}}else return{content:[{type:"text",text:`\u274C Failed to create PR: ${re.error??"unknown error"}`}],meta:{success:!1,state:"error"}}}}}}}var Pi=u(()=>{nt();he();Qe();Wn()});import{readdirSync as $I,statSync as OI,rmSync as _I}from"fs";import{execFileSync as NI}from"child_process";import{join as of}from"path";nt();he();function Kk(e){return e.length>80?`${e.slice(0,80)}...`:e}function jk(e){return e.worktreePath?!e.originalWorkdir||e.originalWorkdir===e.worktreePath?`${e.worktreePath} (worktree)`:`${e.worktreePath} (worktree of ${e.originalWorkdir})`:e.workdir}function qk(e){let t=["Session launched successfully.",` Name: ${e.sessionName}`,` ID: ${e.sessionId}`,` Harness: ${e.harness}`,` Permission mode: ${e.permissionMode}`,` Plan approval: ${e.planApproval}`,` Worktree strategy: ${e.worktreeStrategy??"off"}`,` Resolved workdir: ${jk(e)}`,` Model: ${e.model??"default"}`,` Prompt: "${Kk(e.prompt)}"`];return e.reasoningEffort&&t.push(` Reasoning effort: ${e.reasoningEffort}`),e.resumeSessionId?t.push(` Resume: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`):e.forceNewSession&&t.push(" Force new session: true"),e.clearedPersistedCodexResume&&t.push(" Thread state: historical Codex state cleared; starting a fresh thread."),t.push(" Mode: multi-turn (use agent_respond to send follow-up messages)"),t.push("","Use agent_sessions to check status, agent_output to see output."),t.join(`
|
|
35
|
+
`)}function Uo(e,t){return qk({...e,sessionId:t.id,sessionName:t.name,model:t.model,reasoningEffort:t.reasoningEffort,worktreeStrategy:t.worktreeStrategy??"off",worktreePath:t.worktreePath,originalWorkdir:t.originalWorkdir})}Le();function Ko(e){let{requestedResumeSessionId:t,activeSession:r,persistedSession:n}=e;return t?r?{resumeSessionId:t,clearedPersistedCodexResume:!1}:n?.harness==="codex"&&n.backendRef?.kind!=="codex-app-server"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:t,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}ke();function za(e){return"id"in e?e.id:e.sessionId}function Nn(e){return e.status==="completed"||e.killReason==="done"}function vy(e){return Nn(e)&&e.backendRef?.kind==="codex-app-server"&&!!T(e)}function Ry(e){return(e.killReason==="shutdown"||e.killReason==="startup-timeout")&&!T(e)}function Fn(e){if(e.status==="running")return{kind:"direct",reason:"already_running"};let t=za(e);if(Nn(e)&&!vy(e))return{kind:"unavailable",reason:"completed",stableSessionId:t};let r=T(e);if(r){let n="harnessName"in e?void 0:e,{resumeSessionId:o,clearedPersistedCodexResume:i}=Ko({requestedResumeSessionId:r,activeSession:"harnessName"in e?{harnessSessionId:r}:void 0,persistedSession:n?{harness:n.harness,backendRef:n.backendRef}:void 0});return o?{kind:"resume",resumeSessionId:o,stableSessionId:t,clearedPersistedCodexResume:i}:{kind:"unavailable",reason:"legacy_non_resumable",stableSessionId:t,clearedPersistedCodexResume:i}}return Ry(e)?{kind:"relaunch",stableSessionId:t}:{kind:"unavailable",reason:"missing_backend_state",stableSessionId:t}}Le();import{existsSync as ql}from"fs";ke();function Bl(e){return e==null?void 0:String(e).trim()||void 0}function Ay(e){return e.trim().replace(/^['"`](.*)['"`]$/s,"$1").trim()}function Ty(e){let t=e.split(/\n\s*\n/,1)[0]?.split(`
|
|
36
|
+
`).map(r=>r.trim()).filter(Boolean)??[];if(t.length!==0)for(let r of t){let n=r.match(/^(Workdir|Repo):\s*(.+)$/),o=Ay(n?.[2]??"");if(o.startsWith("/")&&ql(o))return o}}function Kl(e,t){return e.workdir!==t.workdir?!1:t.originSessionKey&&e.originSessionKey?e.originSessionKey===t.originSessionKey:!t.originChannel||!e.originChannel?!1:e.originChannel===t.originChannel&&Bl(e.originThreadId)===Bl(t.originThreadId)}function jl(e){return e.slice(0,3).map(t=>` - ${t.name} [${t.ref}] | status=${t.status}${t.lifecycle?` | lifecycle=${t.lifecycle}`:""}`).join(`
|
|
37
|
+
`)}function My(e,t){let r=[],n=[],o=new Set;for(let i of e.list?.("all")??[]){if(!Kl(i,t))continue;let s=i.id;if(!o.has(s)){if(o.add(s),i.isExplicitlyResumable){r.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0});continue}(i.status==="starting"||i.status==="running")&&n.push({ref:i.id,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!1})}}for(let i of e.listPersistedSessions?.()??[]){if(!i.resumable||!Kl(i,t))continue;let s=ee(i)??i.harnessSessionId,a=i.sessionId??T(i)??i.harnessSessionId;!s||!a||o.has(a)||(o.add(a),r.push({ref:s,name:i.name,status:i.status,lifecycle:i.lifecycle,resumable:!0}))}return{resumable:r,active:n}}function Cy(e,t){if(!t||t.length===0)return!0;if(!e)return!1;let r=e.toLowerCase();return t.some(n=>r.includes(n.toLowerCase()))}function Vl(e,t,r){let n=e.workdir||Ty(e.prompt)||t.workspaceDir||E.defaultWorkdir||process.cwd();if(!ql(n))return{kind:"error",text:`Error: Working directory does not exist: ${n}`};let o=e.harness??De(),i=Wr(o),s=e.model??i,a=e.model!==void 0;if(!s)return{kind:"error",text:`Error: No default model configured for harness "${o}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${o}.defaultModel or pass model explicitly.`};let d=ll(o);if(d&&d.length>0&&!Cy(s,d))return{kind:"error",text:a?`Error: Model "${s}" is not allowed. Permitted models: ${d.join(", ")}`:`Error: Default model "${s||"undefined"}" is not in allowedModels (${d.join(", ")}). Update your plugin config to set a compatible defaultModel.`};let c=ml(t),h=An(t,c||Mn(n)),m=t.sessionKey||void 0,S=fl(m)??Tn(t);if(!e.resume_session_id&&!e.force_new_session){let v=My(r,{workdir:n,originSessionKey:m,originChannel:h,originThreadId:S});if(v.resumable.length>0||v.active.length>0){let de=v.resumable.length>0?["Linked resumable session(s) already exist for this thread/workdir:",jl(v.resumable),"","Resume the latest one with:",` agent_respond(session='${v.resumable[0].ref}', message='<next instruction>')`,"Fork from it with:",` agent_launch(prompt='<new task>', resume_session_id='${v.resumable[0].ref}', fork_session=true)`].join(`
|
|
38
|
+
`):"",yr=v.active.length>0?[v.resumable.length>0?"Linked active session(s):":"Linked active session(s) already exist for this thread/workdir:",jl(v.active),"","Send a follow-up instead of launching a duplicate:",` agent_respond(session='${v.active[0].ref}', message='<next instruction>')`].join(`
|
|
39
|
+
`):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",de,yr,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
|
|
40
|
+
`)].filter(Boolean).join(`
|
|
41
|
+
|
|
42
|
+
`)}}}let y=e.resume_session_id,x=y?r.resolve?.(y):void 0,$=y?r.getPersistedSession?.(y):void 0;if(y){let v=r.resolveBackendConversationId?.(y)??r.resolveHarnessSessionId?.(y);if(!v)return{kind:"error",text:`Error: Could not resolve resume_session_id "${y}" to a session ID. Use agent_sessions to list available sessions.`};y=v}let{resumeSessionId:re,clearedPersistedCodexResume:R}=Ko({requestedResumeSessionId:y,activeSession:x?{harnessSessionId:x.backendConversationId??x.harnessSessionId}:void 0,persistedSession:$?{harness:$.harness,backendRef:$.backendRef}:void 0}),W=e.permission_mode??E.permissionMode,I=e.plan_approval??E.planApproval;return{kind:"resolved",workdir:n,harness:o,resolvedModel:s,permissionMode:W,planApproval:I,originChannel:h,originThreadId:S,originSessionKey:m,route:Bo(t,h,m),resumeSessionId:re,resolvedResumeId:y,clearedPersistedCodexResume:R,reasoningEffort:Jt(o)}}function Ey(e){return e instanceof Error?e.message:String(e)}function Hl(e,t){return e?("id"in e?e.id:e.sessionId)??t??"unknown-session":t??"unknown-session"}function $y(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function Oy(e){return!!e&&typeof e=="object"&&typeof e.formatLaunchResult=="function"}function Gl(e){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn \u2014 they stay open for follow-up messages via agent_respond. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:g.Object({prompt:g.String({description:"The task prompt to execute"}),name:g.Optional(g.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:g.Optional(g.String({description:"Working directory (defaults to cwd)"})),model:g.Optional(g.String({description:"Model name to use"})),system_prompt:g.Optional(g.String({description:"Additional system prompt"})),allowed_tools:g.Optional(g.Array(g.String(),{description:"List of allowed tools"})),resume_session_id:g.Optional(g.String({description:"Session reference to continue or fork from. Prefer the plugin session ID shown by agent_launch or agent_sessions; persisted backend conversation IDs also resolve when available."})),fork_session:g.Optional(g.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),force_new_session:g.Optional(g.Boolean({description:"Bypass resume-first protection and start a brand-new linked session even when a resumable or active linked session already exists."})),permission_mode:g.Optional(g.Union([g.Literal("default"),g.Literal("plan"),g.Literal("bypassPermissions")],{description:"Permission mode: 'default' (plugin-managed interactive execution), 'plan' (present the plan first and block implementation until approval), 'bypassPermissions' (fully autonomous execution). Defaults to plugin config ('plan' by default)."})),plan_approval:g.Optional(g.Union([g.Literal("ask"),g.Literal("delegate"),g.Literal("approve")],{description:"Plan approval policy for this session: 'ask' (send the full plan to the user with Approve/Revise/Reject buttons), 'delegate' (orchestrator must review the full plan, then either approve directly or escalate back to the user with the same buttons), 'approve' (auto-approve after verification). Overrides the plugin-level planApproval setting."})),harness:g.Optional(g.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."})),worktree_strategy:g.Optional(g.Union([g.Literal("off"),g.Literal("manual"),g.Literal("ask"),g.Literal("delegate"),g.Literal("auto-merge"),g.Literal("auto-pr")],{description:"Worktree strategy: 'off' (no worktree), 'manual' (create worktree but no auto merge-back), 'ask' (prompt user with Merge/PR/Decide later/Dismiss buttons), 'delegate' (orchestrator decides), 'auto-merge' (merge automatically), 'auto-pr' (open/update a PR automatically). Defaults to the plugin config when unset."})),worktree_base_branch:g.Optional(g.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),worktree_pr_target_repo:g.Optional(g.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex' for fork-to-upstream workflow). If not set, auto-detected from 'upstream' remote or defaults to 'origin'."}))}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!$y(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};r.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${r.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${e.agentId}" will be used for origin routing instead.`);try{let n=Vl(r,e,k);if(n.kind!=="resolved")return{content:[{type:"text",text:n.text}]};let{workdir:o,harness:i,resolvedModel:s,permissionMode:a,planApproval:d,originChannel:c,originThreadId:h,originSessionKey:m,route:S,resumeSessionId:y,resolvedResumeId:x,clearedPersistedCodexResume:$,reasoningEffort:re}=n,R=r.resume_session_id?k.resolve(r.resume_session_id)??k.getPersistedSession(r.resume_session_id):void 0,W=!r.fork_session&&R?Fn(R):void 0;if(W?.kind==="direct")return{content:[{type:"text",text:`Session ${R.name} [${Hl(R,r.resume_session_id)}] is already running. Use agent_respond(session='${r.resume_session_id}', message='<next instruction>') instead of agent_launch(resume_session_id=...).`}]};if(W?.kind==="unavailable")return{content:[{type:"text",text:`Resume unavailable for session ${R.name} [${Hl(R,r.resume_session_id)}] (${W.reason}). Use agent_launch(prompt='<new task>') for a fresh session or set fork_session=true to fork from prior context.`}]};let I=k.spawn({prompt:r.prompt,sessionIdOverride:r.fork_session?void 0:W?.kind==="resume"||W?.kind==="relaunch"?W.stableSessionId:void 0,name:r.name,workdir:o,model:s,reasoningEffort:re,systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,resumeSessionId:W?.kind==="resume"?W.resumeSessionId:y,resumeWorktreeFrom:x,forkSession:y?r.fork_session:!1,multiTurn:!0,permissionMode:a,planApproval:d,codexApprovalPolicy:i==="codex"?"never":void 0,originChannel:c,originThreadId:h,originAgentId:e.agentId||void 0,originSessionKey:m,route:S,harness:i,worktreeStrategy:r.worktree_strategy,worktreeBaseBranch:r.worktree_base_branch,worktreePrTargetRepo:r.worktree_pr_target_repo});return{content:[{type:"text",text:Oy(k)?k.formatLaunchResult({prompt:r.prompt,workdir:o,harness:i,permissionMode:a??E.permissionMode,planApproval:d,forceNewSession:r.force_new_session,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,clearedPersistedCodexResume:$},I):Uo({prompt:r.prompt,workdir:o,harness:i,permissionMode:a??E.permissionMode,planApproval:d,resumeSessionId:r.resume_session_id,forkSession:r.fork_session,forceNewSession:r.force_new_session,clearedPersistedCodexResume:$},{id:I.id,name:I.name,model:I.model,reasoningEffort:I.reasoningEffort??Jt(i),worktreeStrategy:I.worktreeStrategy??r.worktree_strategy??E.defaultWorktreeStrategy??"off",worktreePath:I.worktreePath,originalWorkdir:I.originalWorkdir})}]}}catch(n){let o=Ey(n),i=o.includes("Max sessions")?"":`
|
|
43
|
+
|
|
44
|
+
Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}nt();he();Le();import{existsSync as ed,readFileSync as km}from"fs";import{EventEmitter as Jy}from"events";import{webcrypto as Ql}from"node:crypto";var zl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var _y=128,fr,jr;function Ny(e){!fr||fr.length<e?(fr=Buffer.allocUnsafe(e*_y),Ql.getRandomValues(fr),jr=0):jr+e>fr.length&&(Ql.getRandomValues(fr),jr=0),jr+=e}function Jl(e=21){Ny(e|=0);let t="";for(let r=jr-e;r<jr;r++)t+=zl[fr[r]&63];return t}Va();Le();ke();var Yl={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},Xl=new Set(["merged","pr_open","dismissed","cleanup_failed"]);function Fy(e){return e.requestedPermissionMode!=="plan"?"not_plan_gated":e.pendingPlanApproval?"awaiting_approval":e.planModeApproved?"approved_then_implemented":e.currentPermissionMode!=="plan"?"implemented_without_required_approval":"awaiting_approval"}function Me(e){return{...e,approvalExecutionState:Fy(e)}}function Qa(e,t){switch(t.type){case"initialize":return Me({...e,worktreeState:t.hasWorktree&&e.worktreeState==="none"?"provisioned":e.worktreeState,lifecycle:e.status==="starting"?"starting":e.lifecycle,runtimeState:e.status==="starting"?"live":e.runtimeState});case"status.transition":return t.status==="starting"?Me({...e,status:t.status,lifecycle:"starting",runtimeState:"live"}):t.status==="running"?Me({...e,status:t.status,lifecycle:e.lifecycle==="starting"||e.lifecycle==="suspended"?"active":e.lifecycle,runtimeState:"live"}):Me({...e,status:t.status,runtimeState:"stopped",lifecycle:e.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return Me({...e,currentPermissionMode:t.currentPermissionMode});case"turn.started":return Me({...e,lifecycle:"active",runtimeState:"live"});case"input.requested":return Me({...e,lifecycle:e.pendingPlanApproval?"awaiting_plan_decision":"awaiting_user_input"});case"plan.requested":if(e.planModeApproved)return e;{let r=e.pendingPlanApproval&&e.approvalState==="pending"&&e.planApprovalContext===t.context;return Me({...e,pendingPlanApproval:!0,planApprovalContext:t.context,approvalState:"pending",planDecisionVersion:r?e.planDecisionVersion:e.planDecisionVersion+1,lifecycle:"awaiting_plan_decision"})}case"plan.cleared":return Me({...e,pendingPlanApproval:!1,planApprovalContext:void 0,approvalState:e.approvalState==="pending"?"not_required":e.approvalState});case"plan.approved":return Me({...e,pendingPlanApproval:!1,planApprovalContext:void 0,planModeApproved:!0,approvalState:"approved",planDecisionVersion:e.planDecisionVersion+1,lifecycle:e.status==="running"?"active":e.lifecycle});case"plan.changes_requested":return Me({...e,pendingPlanApproval:!0,approvalState:"changes_requested",planDecisionVersion:e.planDecisionVersion+1,lifecycle:"awaiting_plan_decision"});case"terminal.entered":return Me({...e,lifecycle:t.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return Me({...e,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return Me({...e,worktreeState:t.worktreeState,lifecycle:t.worktreeState==="pending_decision"?"awaiting_worktree_decision":Xl.has(t.worktreeState)?"terminal":e.lifecycle});case"delivery.state_set":return Me({...e,deliveryState:t.deliveryState})}}function Zl(e,t){let r={...e,...t.lifecycle!==void 0?{lifecycle:t.lifecycle}:{},...t.approvalState!==void 0?{approvalState:t.approvalState}:{},...t.approvalExecutionState!==void 0?{approvalExecutionState:t.approvalExecutionState}:{},...t.worktreeState!==void 0?{worktreeState:t.worktreeState}:{},...t.runtimeState!==void 0?{runtimeState:t.runtimeState}:{},...t.deliveryState!==void 0?{deliveryState:t.deliveryState}:{},...t.requestedPermissionMode!==void 0?{requestedPermissionMode:t.requestedPermissionMode}:{},...t.currentPermissionMode!==void 0?{currentPermissionMode:t.currentPermissionMode}:{},...t.pendingPlanApproval!==void 0?{pendingPlanApproval:t.pendingPlanApproval}:{},...t.planApprovalContext!==void 0?{planApprovalContext:t.planApprovalContext}:{},...t.planDecisionVersion!==void 0?{planDecisionVersion:t.planDecisionVersion}:{},...t.canonicalPlanPromptVersion!==void 0?{canonicalPlanPromptVersion:t.canonicalPlanPromptVersion}:{},...t.planModeApproved!==void 0?{planModeApproved:t.planModeApproved}:{}};return r.pendingPlanApproval&&(r={...r,approvalState:r.approvalState==="changes_requested"?"changes_requested":"pending",lifecycle:"awaiting_plan_decision"}),t.pendingWorktreeDecisionSince!==void 0||r.worktreeState==="pending_decision"?r=Qa(r,{type:"worktree.decision_requested"}):Xl.has(r.worktreeState)&&(r={...r,lifecycle:"terminal"}),Me(r)}var ei=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(t){this.queue.push(t),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(t=>{this.resolve=t})}}};import{appendFileSync as Dy}from"fs";import{tmpdir as Ly}from"os";import{join as Uy}from"path";var em=2e3;function qr(e){return Uy(Ly(),`openclaw-agent-${e}.txt`)}function Wy(e,t){if(!t)return;let r=t.split(`
|
|
45
|
+
`),[n="",...o]=r;e.length===0?e.push(n):e[e.length-1]+=n;for(let i of o)e.push(i)}function tm(e,t,r){Wy(e,r),e.length>em&&e.splice(0,e.length-em);try{Dy(qr(t),r,"utf-8")}catch{}return e}var ti=class{timers=new Map;get size(){return this.timers.size}set(t,r,n){this.clear(t);let o=setTimeout(n,r);o.unref?.(),this.timers.set(t,o)}clear(t){let r=this.timers.get(t);r&&(clearTimeout(r),this.timers.delete(t))}clearAll(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}};var ri=class{constructor(t){this.deps=t}waitingForInputFired=!1;lastTurnHadQuestion=!1;turnInProgress=!0;currentTurnText="";currentTurnPlanArtifact;beginUserTurn(){this.waitingForInputFired=!1,this.turnInProgress=!0,this.currentTurnText="",this.currentTurnPlanArtifact=void 0,this.lastTurnHadQuestion=!1}noteTextDelta(t,r){this.waitingForInputFired=!1,r||(this.lastTurnHadQuestion=!1),this.deps.appendOutput(t),this.currentTurnText+=this.currentTurnText?`
|
|
46
|
+
${t}`:t,this.deps.emitOutput(t)}noteToolCall(t){let{name:r,input:n,currentPermissionMode:o,permissionMode:i,planModeApproved:s}=t;if(r==="Write"){let a=n;typeof a?.file_path=="string"&&a.file_path.includes("/.claude/plans/")&&this.deps.setPlanFilePath(a.file_path)}r==="AskUserQuestion"?(this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),(o==="plan"||i==="plan")&&!s&&this.deps.markPendingPlanApproval("plan-mode")):(r==="ExitPlanMode"||r==="set_permission_mode")&&!s&&(this.lastTurnHadQuestion=!0,this.deps.markPendingPlanApproval("plan-mode")),this.deps.emitToolUse(r,n)}notePendingInput(){this.lastTurnHadQuestion=!0,this.deps.applyInputRequested(),this.waitingForInputFired||(this.waitingForInputFired=!0,this.deps.emitTurnEnd(!0))}clearResolvedPendingInput(t,r){if(!(!t||r?.requestId===t))return r}notePlanArtifact(t,r){if(this.currentTurnPlanArtifact=t,!r)return;let n=t.markdown.trim();!n||this.currentTurnText.trim()===n||(this.deps.appendOutput(n),this.currentTurnText=n,this.deps.emitOutput(n))}noteSettingsChanged(t){let{oldMode:r,permissionMode:n,planModeApproved:o}=t;if(n)return n!=="plan"&&r==="plan"&&!o&&(this.deps.markPendingPlanApproval("plan-mode"),this.lastTurnHadQuestion=!0),n}finishSuccessfulTurn(t){let{currentPermissionMode:r,permissionMode:n,pendingPlanApproval:o,planModeApproved:i,pendingInputState:s,hasPendingMessages:a}=t,d=o;(r==="plan"||n==="plan")&&!d&&!i&&(this.deps.markPendingPlanApproval("plan-mode"),d=!0);let c=d||this.lastTurnHadQuestion||!!s;this.turnInProgress=a,c&&!this.waitingForInputFired?(this.waitingForInputFired=!0,d||this.deps.markAwaitingUserInput(),this.deps.emitTurnEnd(!0)):!a&&!c&&(this.deps.completeTurn(),this.deps.emitTurnEnd(!1))}finishTerminalTurn(){this.turnInProgress=!1}resetAfterRun(){this.lastTurnHadQuestion=!1,this.currentTurnText="",this.currentTurnPlanArtifact=void 0}};var ni=class{constructor(t){this.deps=t}applyMessage(t,r){if(t.type==="backend_ref"){this.deps.clearStartupTimer(),this.deps.assignBackendRef({...t.ref}),this.deps.transitionRunning();return}if(t.type==="run_started"){t.runId&&this.deps.noteRunStarted(t.runId);return}if(t.type==="text_delta"){this.deps.noteTextDelta(t.text,r.pendingPlanApproval);return}if(t.type==="tool_call"){this.deps.noteToolCall({name:t.name,input:t.input,currentPermissionMode:r.currentPermissionMode,permissionMode:r.permissionMode,planModeApproved:r.planModeApproved});return}if(t.type==="pending_input"){this.deps.setPendingInputState(t.state),this.deps.notePendingInput();return}if(t.type==="pending_input_resolved"){this.deps.setPendingInputState(this.deps.clearResolvedPendingInput(t.requestId,r.pendingInputState));return}if(t.type==="plan_artifact"){this.deps.notePlanArtifact(t);return}if(t.type==="settings_changed"){let n=this.deps.noteSettingsChanged({oldMode:r.currentPermissionMode,permissionMode:t.permissionMode,planModeApproved:r.planModeApproved});n&&this.deps.setCurrentPermissionMode(n);return}if(t.type==="run_completed"){this.deps.handleRunCompleted(t.data);return}t.type}};Qe();var Yy=120*1e3;function fi(e){return e instanceof Error?e.message:String(e)}var gi=class extends Jy{id;name;harnessSessionId;backendRef;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;requestedPermissionMode;planApproval;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;worktreePath;originalWorkdir;worktreeBranch;worktreeStrategy;worktreeBaseBranch;worktreePrTargetRepo;worktreePushRemote;worktreeDisposition;worktreePrUrl;worktreePrNumber;worktreeMerged;worktreeMergedAt;worktreeState="none";multiTurn;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;route;pendingInputState;pendingPlanApproval=!1;planApprovalContext;planDecisionVersion=0;canonicalPlanPromptVersion;planFilePath;killReason="unknown";planModeApproved=!1;turnRuntime;harnessEvents;lifecycle="starting";approvalState="not_required";approvalExecutionState="not_plan_gated";runtimeState="live";deliveryState="idle";canUseTool;autoRespondCount=0;timers=new ti;constructor(t,r){super(),this.id=t.sessionIdOverride??Jl(8),this.name=r,this.harness=t.harness?_n(t.harness):Ul(),this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??Wr(this.harness.name),this.reasoningEffort=t.reasoningEffort??Jt(this.harness.name),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??E.permissionMode,this.requestedPermissionMode=t.requestedPermissionMode??this.permissionMode,this.planApproval=t.planApproval??E.planApproval,this.codexApprovalPolicy=this.harness.name==="codex"?"never":void 0,this.currentPermissionMode=this.permissionMode,this.originChannel=t.originChannel,this.originThreadId=t.originThreadId,this.originAgentId=t.originAgentId,this.originSessionKey=t.originSessionKey,this.route=t.route?{...t.route}:void 0,this.backendRef=t.backendRef?{...t.backendRef}:void 0,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.worktreeStrategy=t.worktreeStrategy,this.worktreeBaseBranch=t.worktreeBaseBranch,t.worktreePrTargetRepo&&(this.worktreePrTargetRepo=t.worktreePrTargetRepo),this.canUseTool=t.canUseTool,this.startedAt=Date.now(),this.abortController=new AbortController,this.turnRuntime=new ri({appendOutput:n=>tm(this.outputBuffer,this.id,n),emitOutput:n=>this.emit("output",this,n),emitToolUse:(n,o)=>this.emit("toolUse",this,n,o),emitTurnEnd:n=>this.emit("turnEnd",this,n),markPendingPlanApproval:n=>this.markPendingPlanApproval(n),markAwaitingUserInput:()=>this.markAwaitingUserInput(),applyInputRequested:()=>this.applyControlEvent({type:"input.requested"}),completeTurn:()=>{this.applyControlEvent({type:"terminal.entered"}),this.complete("done")},setPlanFilePath:n=>{this.planFilePath=n}}),this.harnessEvents=new ni({clearStartupTimer:()=>this.clearTimer("startup"),assignBackendRef:n=>{this.backendRef=n,this.harnessSessionId=n.conversationId,n.worktreePath&&(this.worktreePath=n.worktreePath,this.originalWorkdir??=this.workdir,this.worktreeBranch??=ai(n.worktreePath),this.worktreeStrategy&&this.worktreeStrategy!=="off"&&this.applyControlEvent({type:"worktree.state_set",worktreeState:"provisioned"}))},noteRunStarted:n=>{this.backendRef&&(this.backendRef={...this.backendRef,runId:n})},transitionRunning:()=>{this._status==="starting"&&this.transition("running")},noteTextDelta:(n,o)=>this.turnRuntime.noteTextDelta(n,o),noteToolCall:n=>this.turnRuntime.noteToolCall(n),setPendingInputState:n=>{this.pendingInputState=n},notePendingInput:()=>this.turnRuntime.notePendingInput(),clearResolvedPendingInput:(n,o)=>this.turnRuntime.clearResolvedPendingInput(n,o),notePlanArtifact:n=>this.turnRuntime.notePlanArtifact(n.artifact,n.finalized),noteSettingsChanged:n=>this.turnRuntime.noteSettingsChanged(n),setCurrentPermissionMode:n=>{this.currentPermissionMode=n,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:n})},handleRunCompleted:n=>{this.result={subtype:n.success?"success":"error",duration_ms:n.duration_ms,total_cost_usd:n.total_cost_usd,num_turns:n.num_turns,result:n.result,is_error:!n.success,session_id:n.session_id},this.costUsd=n.total_cost_usd,this.multiTurn&&this.messageStream&&n.success?(this.resetIdleTimer(),this.turnRuntime.finishSuccessfulTurn({currentPermissionMode:this.currentPermissionMode,permissionMode:this.permissionMode,pendingPlanApproval:this.pendingPlanApproval,planModeApproved:this.planModeApproved,pendingInputState:this.pendingInputState,hasPendingMessages:this.messageStream?.hasPending()===!0})):(this.turnRuntime.finishTerminalTurn(),this.transitionToTerminal(n.success?"completed":"failed")),this.turnRuntime.resetAfterRun(),this.pendingInputState=void 0}}),this.applyControlEvent({type:"initialize",hasWorktree:!!(this.worktreeStrategy&&this.worktreeStrategy!=="off")}),(t.planModeApproved!==void 0||t.approvalState!==void 0||t.approvalExecutionState!==void 0)&&this.applyControlPatch({...t.planModeApproved!==void 0?{planModeApproved:t.planModeApproved}:{},...t.approvalState!==void 0?{approvalState:t.approvalState}:{},...t.approvalExecutionState!==void 0?{approvalExecutionState:t.approvalExecutionState}:{}})}get status(){return this._status}get harnessName(){return this.harness.name}get backendKind(){return this.harness.backendKind}get backendCapabilities(){return this.harness.capabilities}get backendConversationId(){return T(this)}get waitingForInputFired(){return this.turnRuntime.waitingForInputFired}set waitingForInputFired(t){this.turnRuntime.waitingForInputFired=t}get lastTurnHadQuestion(){return this.turnRuntime.lastTurnHadQuestion}set lastTurnHadQuestion(t){this.turnRuntime.lastTurnHadQuestion=t}get turnInProgress(){return this.turnRuntime.turnInProgress}set turnInProgress(t){this.turnRuntime.turnInProgress=t}get currentTurnText(){return this.turnRuntime.currentTurnText}set currentTurnText(t){this.turnRuntime.currentTurnText=t}get currentTurnPlanArtifact(){return this.turnRuntime.currentTurnPlanArtifact}set currentTurnPlanArtifact(t){this.turnRuntime.currentTurnPlanArtifact=t}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this.lifecycle}get isExplicitlyResumable(){return this.status!=="running"&&this.status!=="completed"&&this.killReason!=="done"&&!!this.backendConversationId}transition(t){if(!Yl[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let r=this._status;this._status=t,this.applyControlEvent({type:"status.transition",status:t}),this.emit("statusChange",this,t,r)}setTimer(t,r,n){this.timers.set(t,r,n)}clearTimer(t){this.timers.clear(t)}clearAllTimers(){this.timers.clearAll()}markPendingPlanApproval(t){this.applyControlEvent({type:"plan.requested",context:t})}clearPendingPlanApproval(){this.applyControlEvent({type:"plan.cleared"})}markAwaitingUserInput(){this.applyControlEvent({type:"input.requested"})}async start(){try{let t;this.multiTurn?(this.messageStream=new ei,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let r=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,backendRef:this.backendRef,worktreeStrategy:this.worktreeStrategy,originalWorkdir:this.originalWorkdir??this.workdir,abortController:this.abortController,mcpServers:ul(),canUseTool:this.canUseTool});this.harnessHandle=r,this.setTimer("startup",Yy,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let r=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:r});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let r=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${r}`,n),this.isActive&&this.transitionToTerminal("failed",{error:r})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.turnRuntime.beginUserTurn(),this.applyControlEvent({type:"turn.started"});let r=t;if(this.pendingModeSwitch){let n=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(n),this.currentPermissionMode=n,this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:n}),this.pendingModeSwitch=void 0,i=!0,o=!0}catch(s){throw console.error(`[Session ${this.id}] setPermissionMode(${n}) FAILED: ${fi(s)}`),this.markPendingPlanApproval(this.planApprovalContext??"plan-mode"),new Error(`Failed to switch permission mode to ${n}: ${fi(s)}`)}else this.pendingModeSwitch=void 0,i=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);i&&(this.clearPendingPlanApproval(),n!=="plan"&&this.applyControlEvent({type:"plan.approved"})),o&&(r=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
|
|
47
|
+
|
|
48
|
+
${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved&&(this.applyControlEvent({type:"plan.changes_requested"}),r=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below, then re-submit your revised plan for approval. Do NOT start implementing yet.]
|
|
49
|
+
|
|
50
|
+
${t}`,this.harnessHandle?.setPermissionMode))try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan",this.applyControlEvent({type:"permission.mode_changed",currentPermissionMode:"plan"})}catch(n){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${fi(n)}`)}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(r,this.backendConversationId??""));else if(this.harnessHandle?.streamInput){let n=this.harness.buildUserMessage(r,this.backendConversationId??"");async function*o(){yield n}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){return!this.turnInProgress||!this.harnessHandle?.interrupt?!1:(await this.harnessHandle.interrupt(),!0)}async submitPendingInputOption(t){if(!this.pendingInputState||!this.harnessHandle?.submitPendingInputOption)return!1;let r=await this.harnessHandle.submitPendingInputOption(t);return r&&(this.waitingForInputFired=!1),r}switchPermissionMode(t){this.pendingModeSwitch=t}get isActive(){return this._status==="starting"||this._status==="running"}kill(t){this.transitionToTerminal("killed",{reason:t})}complete(t="done"){this.transitionToTerminal("completed",{reason:t})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}resetIdleTimer(){if(!this.multiTurn)return;let t=(E.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",t,()=>{this._status==="running"&&(this.applyControlEvent({type:"terminal.entered",suspended:!0}),this.kill("idle-timeout"))})}teardown(){this.clearAllTimers(),this.completedAt||(this.completedAt=Date.now()),this.messageStream&&this.messageStream.end(),this.harnessHandle?.interrupt&&this.harnessHandle.interrupt().catch(t=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${fi(t)}`)}),this.abortController.abort(),this.applyControlEvent({type:"terminal.entered",suspended:this.lifecycle==="suspended"})}transitionToTerminal(t,r={}){this.isActive&&(this.turnInProgress=!1,r.reason&&(this.killReason=r.reason),r.error!==void 0&&(this.error=r.error),this.completedAt=Date.now(),this.applyControlEvent({type:"terminal.entered",suspended:t==="killed"&&r.reason==="idle-timeout"}),this.transition(t),this.teardown())}async consumeMessages(t){for await(let r of t){if(!this.isActive)break;this.resetIdleTimer(),this.harnessEvents.applyMessage(r,{pendingPlanApproval:this.pendingPlanApproval,currentPermissionMode:this.currentPermissionMode,permissionMode:this.permissionMode,planModeApproved:this.planModeApproved,pendingInputState:this.pendingInputState})}}controlStateSnapshot(){return{status:this._status,lifecycle:this.lifecycle,approvalState:this.approvalState,approvalExecutionState:this.approvalExecutionState,worktreeState:this.worktreeState,runtimeState:this.runtimeState,deliveryState:this.deliveryState,requestedPermissionMode:this.requestedPermissionMode,currentPermissionMode:this.currentPermissionMode,pendingPlanApproval:this.pendingPlanApproval,planApprovalContext:this.planApprovalContext,planDecisionVersion:this.planDecisionVersion,canonicalPlanPromptVersion:this.canonicalPlanPromptVersion,planModeApproved:this.planModeApproved}}applyControlEvent(t){let r=Qa(this.controlStateSnapshot(),t);this.applyControlState(r)}applyControlPatch(t){let r=Zl(this.controlStateSnapshot(),t);this.applyControlState(r)}applyControlState(t){this.lifecycle=t.lifecycle,this.approvalState=t.approvalState,this.approvalExecutionState=t.approvalExecutionState,this.worktreeState=t.worktreeState,this.runtimeState=t.runtimeState,this.deliveryState=t.deliveryState,this.pendingPlanApproval=t.pendingPlanApproval,this.planApprovalContext=t.planApprovalContext,this.planDecisionVersion=t.planDecisionVersion,this.canonicalPlanPromptVersion=t.canonicalPlanPromptVersion,this.planModeApproved=t.planModeApproved}};ke();function St(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),n=t%60;return r>0?`${r}m${n}s`:`${n}s`}var Xy=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","i","me","my","we","our","you","your","it","its","he","she","to","of","in","for","on","with","at","by","from","as","into","through","about","that","this","these","those","and","or","but","if","then","so","not","no","please","just","also","very","all","some","any","each","make","write","create","build","implement","add","update"]);function fm(e){let r=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!Xy.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var mm={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4",awaiting_plan_decision:"\u{1F4CB}",awaiting_user_input:"\u2753",awaiting_worktree_decision:"\u{1F33F}",suspended:"\u23F8\uFE0F",terminal:"\u{1F3C1}"};function gm(e){let t=mm[e.phase]??mm[e.status]??"\u2753",r=St(e.duration),n=e.multiTurn?"multi-turn":"single",o=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,i=e.costUsd>0?` | $${e.costUsd.toFixed(2)}`:"",s=[`${t} ${e.name} [${e.id}] (${r}${i}) \u2014 ${n}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];if(e.worktreePath&&e.worktreeBranch){let d=` \u{1F33F} Worktree: ${e.worktreeBranch}`;e.worktreeMerged?d+=" [merged \u2713]":e.worktreePrUrl?d+=` [PR: ${e.worktreePrUrl}]`:d+=" [not merged]",s.push(d)}e.phase!==e.status&&s.push(` \u2699\uFE0F Phase: ${e.phase}`),e.lifecycle&&e.lifecycle!==e.phase&&s.push(` \u{1F504} Lifecycle: ${e.lifecycle}`),(e.requestedPermissionMode||e.currentPermissionMode||e.approvalExecutionState)&&s.push(` \u{1F510} Approval: ${e.approvalExecutionState??"unknown"} (requested=${e.requestedPermissionMode??"unknown"}, effective=${e.currentPermissionMode??"unknown"})`),e.resumable&&s.push(" \u21A9\uFE0F Resumable: yes"),e.harness&&s.push(` \u{1F9F0} Harness: ${e.harness}`);let a=T(e);return a&&s.push(` \u{1F517} Backend ID: ${a}`),e.resumeSessionId&&s.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),s.join(`
|
|
51
|
+
`)}function hi(e,t){let r=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:n,failed:o,killed:i}=e.sessionsByStatus,s=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${n}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${r>0?St(r):"n/a"}`];if(e.mostExpensive){let a=e.mostExpensive;s.push("","\u{1F3C6} Notable session",` ${a.name} [${a.id}]`,` \u{1F4DD} "${a.prompt}"`)}return s.join(`
|
|
52
|
+
`)}function hr(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function hm(e,t){let r=e.split(`
|
|
53
|
+
`),n=[],o=0;for(let i=r.length-1;i>=0;i--){let s=r[i].length+(n.length>0?1:0);if(o+s>t&&n.length>0)break;n.unshift(r[i]),o+=s}return n.join(`
|
|
54
|
+
`)}function Sm(e,t){let r=e.split(`
|
|
55
|
+
`),n=[],o=0;for(let i=0;i<r.length;i++){let s=r[i].length+(n.length>0?1:0);if(o+s>t&&n.length>0)break;n.push(r[i]),o+=s}return n.join(`
|
|
56
|
+
`)}var Zy=50,ew=1,tw=new Set(["starting","running","completed","failed","killed"]),rw=5,nw=1440*60*1e3;function ow(e){let t=Number(e);return!Number.isFinite(t)||t<ew?Zy:Math.floor(t)}function iw(e){return typeof e=="string"&&tw.has(e)}function sw(e){let t=e.split(`
|
|
57
|
+
`);return t.at(-1)===""&&t.pop(),t}function ym(e){return e.backendRef?.conversationId??e.harnessSessionId}function wm(e,t,r){let n=km(e,"utf-8"),o=sw(n);return t.full?o:o.slice(-r)}function aw(e,t,r){if(e.status!=="starting"&&e.status!=="running")return null;let n=qr(e.id);if(!ed(n))return null;try{return wm(n,t,r)}catch{return null}}function dw(e){let t=St(e.duration),r=` | Cost: $${e.costUsd.toFixed(4)}`,n=e.phase?` | Phase: ${e.phase}`:"",o=e.lifecycle&&e.lifecycle!==e.phase?` | Lifecycle: ${e.lifecycle}`:"";return[`Session: ${e.name} [${e.id}] | Status: ${e.status.toUpperCase()}${n}${o}${r} | Duration: ${t}`,`${"\u2500".repeat(60)}`].join(`
|
|
58
|
+
`)}function uw(e){return[`Session: ${e.name||e.sessionId||ym(e)||"unknown"} | Status: ${e.status.toUpperCase()} | Cost: $${e.costUsd.toFixed(4)}`,`(retrieved from ${e.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`,`${"\u2500".repeat(60)}`].join(`
|
|
59
|
+
`)}function pw(e){let t=[];return e.error&&t.push(`Error: ${e.error}`),e.result?.result&&t.push(`Result: ${e.result.result}`),e.result&&t.push(`Result status: ${e.result.subtype}`),t.length>0?`
|
|
60
|
+
(no output yet)
|
|
61
|
+
${t.join(`
|
|
62
|
+
`)}`:`
|
|
63
|
+
(no output yet)`}function Si(e,t,r={}){let n=ow(r.lines),o=e.resolve(t);if(!o){let c=e.getPersistedSession(t);if(c?.outputPath&&ed(c.outputPath))try{let h=wm(c.outputPath,r,n).join(`
|
|
64
|
+
`),m=uw(c);return h?`${m}
|
|
65
|
+
${h}`:`${m}
|
|
66
|
+
(output file was empty)`}catch(h){let m=h instanceof Error?h.message:String(h);return`Error: Session "${t}" was cleaned up (expired) and output file could not be read: ${m}`}return`Error: Session "${t}" not found.`}let i=aw(o,r,n),s=i&&i.length>0?i:r.full?o.getOutput():o.getOutput(n),a=dw(o),d=s.length===0?`${a}${pw(o)}`:`${a}
|
|
67
|
+
${s.join(`
|
|
68
|
+
`)}`;if(o.pendingPlanApproval&&o.planFilePath)try{if(ed(o.planFilePath)){let c=km(o.planFilePath,"utf-8"),h="\u2500".repeat(60);return`${d}
|
|
69
|
+
${h}
|
|
70
|
+
Plan file: ${o.planFilePath}
|
|
71
|
+
${h}
|
|
72
|
+
${c}`}}catch{}return d}function ki(e,t="all",r,n={}){let o=e.listPersistedSessions()??[],s=cw(e.list("all"),o);if(t!=="all"&&(s=s.filter(a=>a.status===t)),r&&(s=s.filter(a=>a.originChannel===r)),n.full){let a=Date.now()-nw;s=s.filter(d=>(d.startedAt??0)>=a)}else s=s.slice(0,rw);return s.length===0?"No sessions found.":s.map(a=>gm(a)).join(`
|
|
73
|
+
|
|
74
|
+
`)}function cw(e,t){let r=new Map;for(let n of t){if(!iw(n.status))continue;let o=n.completedAt??Date.now(),i=n.createdAt??o,s=ym(n),a=n.sessionId??`persisted:${s??n.harnessSessionId}`;r.set(a,{id:n.sessionId??s??n.harnessSessionId,name:n.name||n.sessionId||s||n.harnessSessionId,status:n.status,startedAt:n.createdAt??0,completedAt:n.completedAt,duration:Math.max(0,o-i),prompt:n.prompt??"",workdir:n.workdir??"(unknown)",costUsd:n.costUsd??0,multiTurn:!0,phase:n.lifecycle??n.status,lifecycle:n.lifecycle,resumable:n.resumable,harness:n.harness,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeMerged:n.worktreeMerged,worktreeMergedAt:n.worktreeMergedAt,worktreePrUrl:n.worktreePrUrl})}for(let n of e)r.set(n.id,{id:n.id,name:n.name,status:n.status,startedAt:n.startedAt,completedAt:n.completedAt,duration:n.duration,prompt:n.prompt,workdir:n.originalWorkdir??n.workdir,costUsd:n.costUsd,multiTurn:n.multiTurn,phase:n.phase,lifecycle:n.lifecycle,resumable:n.isExplicitlyResumable,harness:n.harnessName,backendRef:n.backendRef,harnessSessionId:n.harnessSessionId,requestedPermissionMode:n.requestedPermissionMode,currentPermissionMode:n.currentPermissionMode,approvalExecutionState:n.approvalExecutionState,originChannel:n.originChannel,originThreadId:n.originThreadId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,worktreeStrategy:n.worktreeStrategy,worktreeMerged:void 0,worktreeMergedAt:void 0,worktreePrUrl:void 0});return[...r.values()].sort((n,o)=>(o.startedAt??0)-(n.startedAt??0))}function lw(e){if(!e||typeof e!="object")return"all";let t=e.status;switch(t){case"running":case"completed":case"failed":case"killed":case"all":return t;default:return"all"}}function Im(e){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:g.Object({status:g.Optional(g.Union([g.Literal("all"),g.Literal("running"),g.Literal("completed"),g.Literal("failed"),g.Literal("killed")],{description:'Filter by status (default "all")'})),full:g.Optional(g.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=lw(r),o=e?.workspaceDir?Mn(e.workspaceDir):void 0,i=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:ki(k,n,o,{full:i})}]}}}}nt();he();function yi(e,t,r){let n=e.resolve(t);return n?n.status==="completed"||n.status==="failed"||n.status==="killed"?`Session ${n.name} [${n.id}] is already ${n.status}. No action needed.`:r==="completed"?(n.complete(),`Session ${n.name} [${n.id}] marked as completed.`):(e.kill(n.id),`Session ${n.name} [${n.id}] has been terminated.`):`Error: Session "${t}" not found.`}function mw(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session!="string"?!1:t.reason===void 0?!0:t.reason==="completed"||t.reason==="killed"}function xm(e){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:g.Object({session:g.String({description:"Session name or ID to terminate"}),reason:g.Optional(g.Union([g.Literal("completed"),g.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(t,r){return k?mw(r)?{content:[{type:"text",text:yi(k,r.session,r.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}nt();he();function fw(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function wi(e){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:g.Object({session:g.String({description:"Session name or ID to get output from"}),lines:g.Optional(g.Number({description:"Number of recent lines to show (default 50)"})),full:g.Optional(g.Boolean({description:"Show all available output"}))}),async execute(t,r){return k?fw(r)?{content:[{type:"text",text:Si(k,r.session,{full:r.full,lines:r.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}nt();he();Le();ke();var gw=10;function rd(e){return e instanceof Error?e.message:String(e)}function Sr(e){return ee(e)??e.harnessSessionId??"unknown-session"}function Pm(e){return e.status!=="running"&&!!e.pendingPlanApproval&&!!T(e)}function Un(e,t,r){let n=t==="completed"?`This session is closed by default. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Sr(e)}', fork_session=true, prompt='<new task>').`:t==="legacy_non_resumable"?`Persisted historical backend state is intentionally non-resumable here. Launch fresh, or fork with agent_launch(resume_session_id='${Sr(e)}', fork_session=true, prompt='<new task>').`:t==="missing_backend_state"?`No resumable backend state is available. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Sr(e)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${Sr(e)}', message='<next instruction>') to continue the running session.`,o=r?` ${r}`:"";return{text:`Resume unavailable for session ${e.name} [${Sr(e)}] (${t}).${o} ${n}`,isError:!0}}async function bm(e,t,r){try{let n={prompt:t.prompt,sessionIdOverride:za(t),workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,worktreeStrategy:t.worktreeStrategy,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,route:t.route,permissionMode:t.currentPermissionMode,requestedPermissionMode:t.requestedPermissionMode??t.currentPermissionMode,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,harness:"harnessName"in t?t.harnessName:t.harness},o=await e.spawnAndAwaitRunning(n,{notifyLaunch:!1});return e.notifySession(o,`\u25B6\uFE0F [${o.name}] Relaunched fresh`),{text:`Session ${t.name} was relaunched fresh \u2014 it was killed during startup before the harness initialized. New session: ${o.name} [${o.id}].`}}catch(n){return{text:`Error relaunching session ${t.name} [${Sr(t)}]: ${rd(n)}`,isError:!0}}}var hw=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
|
|
75
|
+
|
|
76
|
+
`;function td(e){if(e.approvalState==="changes_requested")return`Plan changes were already requested for session ${e.name}. Wait for the revised plan before approving.`;if(e.approvalState==="rejected")return`Plan for session ${e.name} was already rejected.`}function Sw(e){return td(e)?!1:!!(e.pendingPlanApproval||e.currentPermissionMode==="plan")}async function kw(e,t,r,n={}){let o=Fn(t);if(!(o.kind==="resume"||Pm(t)))return;let s=!!(n.approve&&Sw(t));try{if(o.kind!=="resume")return o.kind==="relaunch"?bm(e,t,r):Un(t,o.reason);let a={prompt:s?hw+r:r,sessionIdOverride:o.stableSessionId,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:o.resumeSessionId,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,route:t.route,permissionMode:s?"bypassPermissions":t.currentPermissionMode,requestedPermissionMode:t.requestedPermissionMode??t.currentPermissionMode,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,...s?{approvalState:"approved",approvalExecutionState:"approved_then_implemented",planModeApproved:!0}:{},harness:"harnessName"in t?t.harnessName:t.harness},d=await e.spawnAndAwaitRunning(a,{notifyLaunch:!1});return s?(e.notifySession(d,`\u{1F44D} [${d.name}] Plan approved (resumed)`,"plan-approved"),{text:`Plan approved for session ${d.name} [${d.id}]. Session resumed in bypassPermissions mode. Use agent_output to see the response.`}):(e.notifySession(d,`\u25B6\uFE0F [${d.name}] Auto-resumed`),{text:`Auto-resumed session ${d.name} [${d.id}]. Use agent_output to see the response.`})}catch(a){return Un(t,"missing_backend_state",`Backend resume failed: ${rd(a)}`)}}async function kr(e,t){let r=e.resolve(t.session),n=r?void 0:e.getPersistedSession(t.session);if(!r&&!n)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let o=r??n,i=o.status==="running"?{kind:"direct"}:Fn(o);if(t.approve){let a=td(o);if(a)return{text:a,isError:!0}}if(i.kind==="resume"||Pm(o)){let a=await kw(e,o,t.message,{approve:t.approve});if(a)return a}else{if(i.kind==="relaunch")return bm(e,o,t.message);if(i.kind==="unavailable")return Un(o,i.reason)}if(!r)return Nn(n)?Un(n,"completed"):{text:`Error: Session ${n.name} [${Sr(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return Nn(r)?Un(r,"completed"):{text:`Error: Session ${r.name} [${r.id}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};let s=E.maxAutoResponds??gw;if(t.userInitiated)r.resetAutoRespond();else if(r.autoRespondCount>=s)return{text:`\u26A0\uFE0F Auto-respond limit reached (${r.autoRespondCount}/${s}). Ask the user to provide the answer for session ${r.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{if(t.approve){let m=td(r);if(m)return{text:m,isError:!0}}let a=!1;t.interrupt&&(a=await r.interrupt());let d=!!(t.approve&&r.pendingPlanApproval),c="";if(t.approve&&r.pendingPlanApproval||t.approve&&r.currentPermissionMode==="default"?r.switchPermissionMode("bypassPermissions"):t.approve&&r.currentPermissionMode==="bypassPermissions"?c=`
|
|
77
|
+
\u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:t.approve?c=`
|
|
78
|
+
\u26A0\uFE0F approve=true was set but session has no pending plan approval.`:r.pendingPlanApproval&&(c=`
|
|
79
|
+
\u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`),await r.sendMessage(t.message),d)e.notifySession(r,`\u{1F44D} [${r.name}] Plan approved`,"plan-approved");else if(t.userInitiated){let m=hr(t.message,100);e.notifySession(r,`\u21AA\uFE0F [${r.name}] "${m}"`,"agent-respond")}t.userInitiated||r.incrementAutoRespond();let h=hr(t.message,80);return d?{text:`Plan approved for session ${r.name} [${r.id}]. Use agent_output to see the response.`}:{text:[`Message sent to session ${r.name} [${r.id}].`,a?" (redirected active turn first)":t.interrupt?" (no active turn to interrupt)":"",` Message: "${h}"`,c,"Use agent_output to see the response."].filter(Boolean).join(`
|
|
80
|
+
`)}}catch(a){return{text:`Error sending message to session ${r.name} [${r.id}]: ${rd(a)}`,isError:!0}}}function yw(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function vm(e){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent session. The session must be running. All sessions are multi-turn.",parameters:g.Object({session:g.String({description:"Session name or ID to respond to"}),message:g.String({description:"The message to send to the session"}),interrupt:g.Optional(g.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:g.Optional(g.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:g.Optional(g.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode, or (2) escalate a default-mode session to skip remaining OpenClaw approval checkpoints. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."}))}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!yw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let n=await kr(k,r);return{isError:n.isError??!1,content:[{type:"text",text:n.text}]}}}}nt();he();function ww(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.summary=="string"}function Rm(e){return{name:"agent_request_plan_approval",description:"Send a plan-approval decision prompt to the user for a session that is already waiting on plan approval. Reuses the plugin's Approve/Revise/Reject buttons so the user can decide directly from the message.",parameters:g.Object({session:g.String({description:"Session name or ID awaiting plan approval"}),summary:g.String({description:"Concise user-facing summary of scope, risk, and any concerns that should accompany the approval buttons"})}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!ww(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, summary }."}]};let n=k.requestPlanApprovalFromUser(r.session,r.summary);return{isError:n.startsWith("Error:"),content:[{type:"text",text:n}]}}}}nt();he();function Am(e){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:g.Object({}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=k.getMetrics(),o=k.list("running").length;return{content:[{type:"text",text:hi(n,o)}]}}}}nt();Le();he();Qe();Wn();import{existsSync as od}from"fs";function Iw(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function xi(e){return{name:"agent_merge",description:"Merge a worktree branch back to the base branch. Resolves session (active or persisted), gets worktree path, and performs the merge. On conflict, spawns a conflict-resolver session using the configured default harness.",parameters:g.Object({session:g.String({description:"Session name or ID to merge"}),base_branch:g.Optional(g.String({description:"Base branch to merge into (default: main)"})),strategy:g.Optional(g.Union([g.Literal("merge"),g.Literal("squash")],{description:"Merge strategy: 'merge' (default, fast-forward if possible; merge commit if branches have diverged) or 'squash' (squashes all commits into one)"})),push:g.Optional(g.Boolean({description:"Push the base branch after successful merge (default: false)"})),delete_branch:g.Optional(g.Boolean({description:"Delete the worktree branch after successful merge (default: true)"}))}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Iw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let n=Vr(k,r.session),o=n.activeSession,i=n.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${r.session}" not found.`}]};let{worktreePath:s,originalWorkdir:a,branchName:d}=n;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${r.session}" does not have a worktree.`}]};if(!d)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree at ${s}. The worktree may have been removed and no persisted branch name is available.`}]};od(s)||console.info(`[agent_merge] Worktree directory ${s} no longer exists; proceeding with merge via originalWorkdir (${a})`);let c=a;if(!od(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let h=r.base_branch??gt(c),m=h,S=r.strategy??"merge",y=r.push===!0,x=r.delete_branch!==!1;if(i?.worktreeMerged)return{content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" is already merged.`}]};let $={content:[{type:"text",text:"\u274C Merge did not run (internal error)"}]},re=n.persistedRef;return await k.enqueueMerge(c,async()=>{let R=k.getPersistedSession(r.session);if(R?.worktreeMerged){$={content:[{type:"text",text:`\u2139\uFE0F Session "${r.session}" was already merged while waiting in queue.`}]};return}let W=Ft(c,d,h),I=li(c,d,m,S,s);if(I.success){if(y&&!ci(c,m)){$={content:[{type:"text",text:`\u26A0\uFE0F Merged ${d} \u2192 ${m} locally, but failed to push ${m}`}]};return}x&&bt(c,d);let v=!1;if(od(s)&&(v=ht(c,s),ui(c)),R)for(let A of Ii({...n,persistedSession:R}))k.updatePersistedSession(A,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDisposition:"merged"});let de=gr({kind:"merge",branch:d,base:h,filesChanged:W?.filesChanged,insertions:W?.insertions,deletions:W?.deletions});k.notifyWorktreeOutcome(n.notificationTarget,de);let C=`\u2705 ${I.fastForward?"\u26A1 Fast-forward":"\u{1F500} Merge commit"}: ${d} \u2192 ${m}.${y?" Pushed.":""}${x?v?" Branch and worktree cleaned up.":" Branch deleted; worktree cleanup skipped.":""}`;I.stashPopConflict?C+=`
|
|
81
|
+
\u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${I.stashRef??"stash@{0}"}\` in ${c} to review stashed changes.`:I.stashed&&(C+=`
|
|
82
|
+
(Pre-existing changes on ${m} were auto-stashed and restored.)`),$={content:[{type:"text",text:C}]}}else if(I.rebaseConflict)$={content:[{type:"text",text:`\u26A0\uFE0F Rebase conflicts \u2014 manual resolution required:
|
|
83
|
+
|
|
84
|
+
${I.error}`}]};else if(I.conflictFiles&&I.conflictFiles.length>0){let v=["Resolve merge conflicts in the following files and commit the resolution:","",...I.conflictFiles.map(de=>`- ${de}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${d}"`].join(`
|
|
85
|
+
`);try{let de=k.spawn({prompt:v,workdir:c,name:`${r.session}-conflict-resolver`,harness:De(),permissionMode:"bypassPermissions",multiTurn:!0,route:o?.route??i?.route,originChannel:o?.originChannel??i?.originChannel,originThreadId:o?.originThreadId??i?.originThreadId,originAgentId:o?.originAgentId??i?.originAgentId,originSessionKey:o?.originSessionKey??i?.originSessionKey});$={content:[{type:"text",text:`\u26A0\uFE0F Merge conflicts in ${I.conflictFiles.length} file(s) \u2014 spawned conflict resolver session: ${de.name}`}]}}catch(de){$={content:[{type:"text",text:`\u274C Merge conflicts detected, but failed to spawn resolver: ${de instanceof Error?de.message:String(de)}`}]}}}else $={content:[{type:"text",text:I.dirtyError?`\u274C Merge blocked: ${I.error}`:`\u274C Merge failed: ${I.error??"unknown error"}`}]}}),$}}}Pi();nt();Qe();he();Wn();import{execFileSync as Hr}from"child_process";import{existsSync as bw}from"fs";function vw(e){return!(!e||typeof e!="object")}function Rw(e){try{return Hr("git",["-C",e,"branch","--list","agent/*"],{timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
86
|
+
`).map(r=>r.replace(/^\*?\s+/,"").trim()).filter(Boolean)}catch{return[]}}function Aw(e,t,r){try{let n=Hr("git",["-C",e,"merge-base",t,r],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=Hr("git",["-C",e,"rev-parse",t],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return n===o}catch{return!1}}function Tw(e,t,r){try{let n=Hr("git",["-C",e,"rev-list","--count",`${r}..${t}`],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return parseInt(n.trim(),10)||0}catch{return 0}}function Mw(e,t){if(k){for(let r of k.listPersistedSessions())if(r.worktreeBranch===t&&r.worktreePrUrl&&r.worktreeMerged!==!0)return{number:r.worktreePrNumber??0,url:r.worktreePrUrl}}if(Pt())try{let r=Hr("gh",["pr","list","--head",t,"--state","open","--json","number,url"],{timeout:15e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"],cwd:e}),n=JSON.parse(r.trim());if(Array.isArray(n)&&n.length>0)return{number:n[0].number,url:n[0].url}}catch{}return null}function Cm(e){return{name:"agent_worktree_cleanup",description:"Clean up agent/* branches. Three categories are always protected from deletion: (1) branches with active running/starting sessions, (2) branches with unmerged commits ahead of the base branch, (3) branches with open GitHub PRs. Only fully merged branches with no active session or open PR are eligible for deletion. Use skip_session_check (alias: force) to bypass the active-session check only \u2014 useful when a session crashed and left a stale branch. Use session to dismiss a pending worktree decision without merging.",parameters:g.Object({workdir:g.Optional(g.String({description:"Working directory (defaults to cwd)"})),base_branch:g.Optional(g.String({description:"Base branch to check merge status against (default: main)"})),skip_session_check:g.Optional(g.Boolean({description:"Skip the check for running sessions (use only when a session crashed and left a stale branch). Does NOT override unmerged commit or open PR protection. (default: false)"})),force:g.Optional(g.Boolean({description:"Deprecated alias for skip_session_check. See skip_session_check for details."})),dry_run:g.Optional(g.Boolean({description:"Show what would be deleted without actually deleting (default: false)"})),session:g.Optional(g.String({description:"Session name or ID to dismiss/clear pending worktree decision for (optional)"})),dismiss_session:g.Optional(g.Boolean({description:"When true and session is provided, permanently dismiss the worktree \u2014 deletes the branch and worktree directory. Irreversible. (default: false)"}))}),async execute(t,r){if(!vw(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, skip_session_check?, force?, dry_run?, session? }."}]};let n=r.session,o=r.dismiss_session===!0;if(n&&o&&k)return{content:[{type:"text",text:await k.dismissWorktree(n)}]};if(n&&k){let I=Vr(k,n);if(I.persistedSession)for(let v of Ii(I))k.updatePersistedSession(v,{pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0})}let i=r.workdir||process.cwd(),s=r.base_branch??gt(i),a=r.skip_session_check===!0||r.force===!0,d=r.dry_run===!0;if(!bw(i))return{content:[{type:"text",text:`Error: Working directory does not exist: ${i}`}]};try{Hr("git",["-C",i,"rev-parse","--git-dir"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{return{content:[{type:"text",text:`Error: ${i} is not a git repository`}]}}let c=Rw(i);if(c.length===0)return{content:[{type:"text",text:"No agent/* branches found."}]};let h=new Set,m=new Map;if(k){for(let I of k.list())if(I.status==="starting"||I.status==="running"){let v=I.worktreeBranch;v&&(h.add(v),m.set(v,`${I.name} is ${I.status}`))}}let S=[],y=[],x=[],$=[];for(let I of c){if(!a&&h.has(I)){let v=m.get(I)??"unknown";x.push(`${I} (session: ${v})`);continue}if(Aw(i,I,s))S.push(I);else{let v=Mw(i,I);if(v)$.push({branch:I,prNumber:v.number,prUrl:v.url});else{let de=Tw(i,I,s);y.push({branch:I,commitsAhead:de})}}}let re=(I,v)=>{let de=["agent/* branch status:"],yr=d?"WOULD DELETE":"DELETED",qn=(d?S:I).join(", ")||"(none)",Vn=v.length>0?`; ${v.length} failed: ${v.join(", ")}`:"";de.push(` ${yr} (${d?S.length:I.length}): ${qn}${Vn}`);let C=y.length>0?y.map(({branch:G,commitsAhead:ye})=>ye>0?`${G} [${ye} commit${ye!==1?"s":""} ahead]`:G).join(", "):"(none)";de.push(` KEPT \u2013 unmerged (${y.length}): ${C}`);let A=x.length>0?x.join(", "):"(none)";de.push(` KEPT \u2013 active session (${x.length}): ${A}`);let _=$.length>0?$.map(({branch:G,prNumber:ye,prUrl:ne})=>ye>0?`${G} [PR #${ye}]`:`${G} [open PR]`).join(", "):"(none)";return de.push(` KEPT \u2013 open PR (${$.length}): ${_}`),de.join(`
|
|
87
|
+
`)};if(d)return{content:[{type:"text",text:re([],[])}]};let R=[],W=[];for(let I of S)bt(i,I)?R.push(I):W.push(I);return{content:[{type:"text",text:re(R,W)}]}}}}nt();he();Qe();Wn();import{existsSync as Cw}from"fs";function Ew(e){return!0}function Em(e){return{name:"agent_worktree_status",description:"Show worktree status for coding agent sessions. If session parameter is provided, shows status for that session only. Otherwise, shows all sessions with worktrees. Displays branch name, repository, strategy, commits ahead, merge status, and PR URLs.",parameters:g.Object({session:g.Optional(g.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(t,r){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Ew(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let n=r.session,o=[],i=Tm(k);if(n&&(i=i.filter(c=>nd(c,n)),i.length===0))return{content:[{type:"text",text:`Error: Session "${n}" not found or has no worktree.`}]};if(i.length===0)return{content:[{type:"text",text:"No sessions with worktrees found."}]};let a=k.listPersistedSessions().filter(c=>c.pendingWorktreeDecisionSince&&!c.worktreeMerged&&!c.worktreePrUrl),d=n?a.filter(c=>nd({id:c.sessionId??c.name??c.harnessSessionId,name:c.name,backendConversationId:c.backendRef?.conversationId,harnessSessionId:c.harnessSessionId},n)):a;if(d.length>0){o.push(`\u23F3 Pending decisions (${d.length}):`),o.push("");for(let c of d){let h=new Date(c.pendingWorktreeDecisionSince),m=Date.now()-h.getTime(),S=Math.floor(m/(3600*1e3)),y=Math.floor(S/24),x=S%24,$=Math.floor(m%(3600*1e3)/6e4),re=y>0?`${y}d ${x}h`:S>0?`${S}h ${$}m`:`${$}m`,R=gt(c.workdir);o.push(`\u2022 ${c.name.padEnd(14)} ${(c.worktreeBranch??"?").padEnd(30)} \u2192 ${R.padEnd(10)} pending ${re}`)}if(o.push(""),d.length===1){let c=d[0];o.push(`Use agent_merge(session="${c.name}") or agent_pr(session="${c.name}") to resolve.`)}else o.push('Use agent_merge(session="<name>") or agent_pr(session="<name>") to resolve.');o.push(""),o.push("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),o.push("All worktrees:"),o.push("")}for(let c of i){let h=c.worktreeBranch;if(!h){o.push(`Session: ${c.name} [${c.id}]`),o.push(` Worktree: ${c.worktreePath}`),o.push(" Status: Cannot determine branch (detached HEAD or worktree removed)"),o.push("");continue}let m=gt(c.workdir),S=Cw(c.workdir);if(o.push(`Session: ${c.name} [${c.id}]`),o.push(` Branch: ${h} \u2192 ${m}`),o.push(` Repo: ${c.workdir}`),c.worktreeStrategy&&o.push(` Strategy: ${c.worktreeStrategy}`),S)try{if(Dn(c.workdir,h,m)){let x=Ft(c.workdir,h,m);x?o.push(` Commits: ${x.commits} ahead of ${m} (+${x.insertions} / -${x.deletions})`):o.push(` Commits: ahead of ${m}`)}else o.push(` Commits: even with ${m}`)}catch{o.push(" Commits: (unable to check)")}else o.push(" Commits: (repo no longer exists)");if(c.worktreeMerged){let y=c.worktreeMergedAt?new Date(c.worktreeMergedAt).toLocaleString():"unknown";o.push(` Merged: Yes (${y})`)}else c.worktreePrUrl?o.push(` PR: ${c.worktreePrUrl}`):o.push(" Merged: No");o.push("")}return{content:[{type:"text",text:o.join(`
|
|
88
|
+
`).trim()}]}}}}he();Pi();var Gr="code-agent";function $w(e){let t=e.trim().replace(new RegExp(`^${Gr}:`),"");return t||null}async function bi(e,t){if(typeof e.respond.editMessage=="function")try{await e.respond.editMessage({text:t,buttons:[]});return}catch(r){let n=r instanceof Error?r.message:String(r);/message is not modified/i.test(n)||console.warn(`[callback-handler] Failed to edit worktree prompt: ${n}`)}await e.respond.clearButtons()}function id(e){if(e&&typeof e=="object"&&"content"in e&&Array.isArray(e.content)){let t=e.content[0];return typeof t?.text=="string"?t.text:"(done)"}return"(done)"}function Ow(e){return e==="plan-approve"||e==="plan-request-changes"||e==="plan-reject"}function _w(e,t){if(Ow(e.kind)){if(!t)return"This plan decision is stale because the session is no longer available.";if(e.planDecisionVersion!=null&&t.planDecisionVersion!=null&&e.planDecisionVersion!==t.planDecisionVersion)return"This plan decision is stale because a newer plan review state already exists.";if(!t.pendingPlanApproval)return"This plan is no longer awaiting approval.";if(e.kind==="plan-approve"&&t.approvalState==="changes_requested")return"Changes were already requested for this plan. Wait for the revised plan before approving.";if(e.kind==="plan-request-changes"&&t.approvalState==="changes_requested")return"Changes were already requested for this plan. Send your feedback to the agent instead."}}function sd(e="telegram"){return{channel:e,namespace:Gr,handler:async t=>{if(!t.auth.isAuthorizedSender)return await t.respond.reply({text:"\u26D4 Unauthorized."}),{handled:!0};let r=$w(t.callback.payload);if(!r)return await t.respond.reply({text:`\u26A0\uFE0F Unrecognized callback payload: "${t.callback.payload}".`}),{handled:!0};if(!k)return await t.respond.reply({text:"\u26A0\uFE0F Code agent service not running."}),{handled:!0};let n=k.consumeActionToken(r);if(!n)return await t.respond.reply({text:"\u26A0\uFE0F This action is stale or has already been used."}),{handled:!0};let o=n.sessionId,i=k.resolve?.(o)??k.getPersistedSession?.(o),s=i?.name??o,a=_w(n,i);if(a)return await t.respond.clearButtons(),await t.respond.reply({text:`\u26A0\uFE0F ${a}`}),{handled:!0};switch(n.kind){case"worktree-merge":{await bi(t,`\u2705 Merge selected for [${s}]`);let d=await xi().execute("callback",{session:o});await t.respond.reply({text:id(d)});break}case"worktree-decide-later":{await bi(t,`\u23ED\uFE0F Deferred for [${s}]`);let d=k.snoozeWorktreeDecision(o);await t.respond.reply({text:d.startsWith("Error")?d:"\u23ED\uFE0F Snoozed 24h"});break}case"worktree-dismiss":{await bi(t,`\u{1F5D1}\uFE0F Discarded for [${s}]`);let d=await k.dismissWorktree(o);await t.respond.reply({text:(d.startsWith("Error"),d)});break}case"worktree-create-pr":case"worktree-update-pr":{await bi(t,n.kind==="worktree-update-pr"?`\u{1F4EC} PR update selected for [${s}]`:`\u{1F4EC} PR selected for [${s}]`);let d=await Bn().execute("callback",{session:o});await t.respond.reply({text:id(d)});break}case"worktree-view-pr":{await t.respond.clearButtons();let d=k.getPersistedSession?.(o),c=n.targetUrl??d?.worktreePrUrl;await t.respond.reply({text:c?`PR: ${c}`:"\u26A0\uFE0F PR URL is no longer available."});break}case"plan-approve":{await t.respond.clearButtons();let d=await kr(k,{session:o,message:"Approved. Go ahead.",approve:!0,userInitiated:!0});d.isError&&await t.respond.reply({text:`\u26A0\uFE0F ${d.text}`});break}case"plan-reject":{await t.respond.clearButtons();let d=k.resolve(o);if(d)d.approvalState="rejected",k.kill(d.id,"user"),await t.respond.reply({text:`\u274C Plan rejected for [${d.name}]. Session stopped.`});else{let c=k.getPersistedSession?.(o);c?(k.updatePersistedSession?.(o,{approvalState:"rejected",lifecycle:"terminal",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:(c.planDecisionVersion??0)+1}),await t.respond.reply({text:`\u274C Plan rejected for [${c.name??s}]. Session remains stopped.`})):await t.respond.reply({text:"\u274C Plan rejected."})}break}case"plan-request-changes":{await t.respond.clearButtons();let d=k.resolve?.(o),c=k.getPersistedSession?.(o),h=d?.name??c?.name??o,m=(d?.planDecisionVersion??c?.planDecisionVersion??0)+1;k.updatePersistedSession(o,{approvalState:"changes_requested",lifecycle:"awaiting_plan_decision",pendingPlanApproval:!0,planDecisionVersion:m}),await t.respond.reply({text:`\u270F\uFE0F Type your revision feedback for [${h}] and I'll forward it to the agent.`});break}case"session-restart":case"session-resume":{await t.respond.clearButtons();let d=await kr(k,{session:o,message:"Continue where you left off.",userInitiated:!0});await t.respond.reply({text:d.isError?`\u26A0\uFE0F ${d.text}`:`\u25B6\uFE0F ${d.text}`});break}case"view-output":{await t.respond.clearButtons();let d=await wi().execute("callback",{session:o,lines:50});await t.respond.reply({text:id(d)});break}case"question-answer":{if(await t.respond.clearButtons(),n.optionIndex==null){await t.respond.reply({text:"\u26A0\uFE0F Invalid question-answer action."});break}await k.resolvePendingInputOption(o,n.optionIndex),await t.respond.reply({text:"\u2705 Answer submitted."});break}default:{await t.respond.clearButtons(),await t.respond.reply({text:"\u26A0\uFE0F Unknown callback action."});break}}return{handled:!0}}}}he();Le();function Nw(e){return e instanceof Error?e.message:String(e)}function $m(e){e.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:"Usage: /agent [--name <name>] <prompt>"};let n,o=r.match(/^--name\s+(\S+)\s+/);o&&(n=o[1],r=r.slice(o[0].length).trim());let i=r;if(!i)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let s=De(),a=Wr(s);if(!a)return{text:`Error: No default model configured for harness "${s}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${s}.defaultModel or pass model explicitly via agent_launch.`};let d=k.spawn({prompt:i,name:n,workdir:E.defaultWorkdir||process.cwd(),model:a,reasoningEffort:Jt(s),codexApprovalPolicy:s==="codex"?"never":void 0,originChannel:An(t),originThreadId:Tn(t),route:Bo(t),harness:s}),c=i.length>80?i.slice(0,80)+"...":i;return{text:["Session launched.",` Name: ${d.name}`,` ID: ${d.id}`,` Prompt: "${c}"`,` Status: ${d.status}`].join(`
|
|
89
|
+
`)}}catch(s){let a=Nw(s),d=a.includes("Max sessions")?"":`
|
|
90
|
+
|
|
91
|
+
Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${a}${d}`}}}})}he();function Om(e){e.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").split(/\s+/).includes("--full");return{text:ki(k,"all",void 0,{full:r})}}})}he();function _m(e){e.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=t.args?.trim();return r?{text:yi(k,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}he();function Nm(e){e.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:`Usage: /agent_respond <id-or-name> <message>
|
|
92
|
+
/agent_respond --interrupt <id-or-name> <message>`};let n=!1,o=r;o.startsWith("--interrupt ")&&(n=!0,o=o.slice(12).trim());let i=o.indexOf(" ");if(i===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let s=o.slice(0,i),a=o.slice(i+1).trim();return a?{text:(await kr(k,{session:s,message:a,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}he();function Fm(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=k.getMetrics(),r=k.list("running").length;return{text:hi(t,r)}}})}he();var Fw=50;function Dm(e){e.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let r=(t.args??"").trim();if(!r)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let n=r.split(/\s+/),o="",i=!1,s=Fw;for(let d=0;d<n.length;d++)if(n[d]==="--full")i=!0;else if(n[d]==="--lines"&&d+1<n.length){let c=parseInt(n[d+1],10);!isNaN(c)&&c>0&&(s=c),d++}else o||(o=n[d]);return o?{text:Si(k,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}Le();import{existsSync as Dw,realpathSync as Lw}from"fs";import{resolve as Uw}from"path";function Lm(e){if(!e)return;let t=Uw(e);try{if(Dw(t))return Lw.native(t)}catch{}return t}function vi(e,t){return!e||!t?!1:Lm(e)===Lm(t)}ke();Le();import{existsSync as Ww}from"fs";ke();Qe();function Um(e){return e instanceof Error?e.message:String(e)}function Bw(e){let t=e.worktreeStrategy??E.defaultWorktreeStrategy;return!!t&&t!=="off"&&Ga(Zo({harnessName:e.harness??De(),backendRef:e.backendRef}))}function Kw(e,t,r,n){let o=["","You are working in a git worktree.",`Worktree path: ${r}`,`Branch: ${n}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${r}.`,`Do NOT edit files directly in ${t} (the original workspace).`,`If your task references files by absolute path under ${t}, rewrite those`,"paths relative to your current working directory. For example:",` "${t}/src/file.py" \u2192 use relative path "src/file.py"`,"","Commit all your file changes to this branch before finishing.","Use `git add` and `git commit`. Do NOT run `git checkout`, `git switch`, or `git reset --hard` as these will detach or corrupt the worktree HEAD.","","When making changes, please note:","- Do NOT commit planning documents, investigation notes, or analysis artifacts to this branch","- Only commit actual code, configuration, tests, and documentation changes that were explicitly requested as part of the task"].join(`
|
|
93
|
+
`);return(e??"")+o}function jw(e,t){let r=e.resumeSessionId??e.resumeWorktreeFrom;if(!r)return{};let n=t(r);if(!n)return{};let o=(()=>{if(n.workdir&&n.workdir!==n.worktreePath)return n.workdir;if(n.worktreePath){let s=si(n.worktreePath);return n.workdir&&s&&vi(n.workdir,s)?n.workdir:s??n.workdir}return n.workdir})();if(!e.worktreeStrategy&&n.worktreeStrategy&&(e.worktreeStrategy=n.worktreeStrategy),!e.planApproval&&n.planApproval&&(e.planApproval=n.planApproval),!n.worktreePath)return{};if(!n.worktreeBranch)throw new Error(`Cannot resume session "${r}": persisted worktree metadata is missing worktreeBranch.`);let i=Wl(Zo({persistedHarness:n.harness,backendRef:n.backendRef}))&&!!n.backendRef?.worktreePath;if(Ww(n.worktreePath))return console.info(`[SessionManager] Resuming with existing worktree: ${n.worktreePath}`),{actualWorkdir:n.worktreePath,originalWorkdir:o??n.worktreePath,worktreePath:n.worktreePath,worktreeBranchName:n.worktreeBranch};if(!o)return console.warn(`[SessionManager] Worktree ${n.worktreePath} no longer exists and cannot be recreated, using original workdir`),{clearedResumeSessionId:!!e.resumeSessionId,clearedResumeWorktreeFrom:!!e.resumeWorktreeFrom};if(i)return console.info(`[SessionManager] Native Codex worktree ${n.worktreePath} is missing; resuming from original workdir and letting the backend restore thread state.`),{actualWorkdir:o,originalWorkdir:o,worktreeBranchName:n.worktreeBranch,clearedResumeWorktreeFrom:!!e.resumeWorktreeFrom};try{ui(o);let s=Xa(o,n.worktreeBranch.replace(/^agent\//,""));return console.info(`[SessionManager] Recreated worktree from branch ${n.worktreeBranch}: ${s}`),{actualWorkdir:s,originalWorkdir:o,worktreePath:s,worktreeBranchName:n.worktreeBranch}}catch(s){return console.warn(`[SessionManager] Failed to recreate worktree for resume: ${Um(s)}, using original workdir`),{actualWorkdir:o,originalWorkdir:o,clearedResumeSessionId:!!e.resumeSessionId,clearedResumeWorktreeFrom:!!e.resumeWorktreeFrom}}}function Wm(e,t,r){let{actualWorkdir:n,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}=jw(e,r);a&&(e.resumeSessionId=void 0),d&&(e.resumeWorktreeFrom=void 0),n??=e.workdir,o??=e.workdir;let c=!!(e.resumeSessionId??e.resumeWorktreeFrom),h=e.worktreeStrategy??E.defaultWorktreeStrategy;h&&(e.worktreeStrategy=h);let m=Bw(e),S=!e.resumeSessionId&&!i&&h&&h!=="off"&&!m;if(m&&!Ya(o))throw new Error(`Cannot launch session "${t}": worktree strategy "${h}" requires a git worktree, but "${o}" is not a git repository.`);if(S&&Ya(o)){if(!nm())throw new Error(`Cannot launch session "${t}": insufficient space for worktree creation.`);try{if(i=Xa(o,t),n=i,s=ai(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);console.log(`[SessionManager] Created worktree at ${i}`)}catch(y){throw new Error(`Cannot launch session "${t}": worktree creation failed: ${Um(y)}`)}}else if(S)throw new Error(`Cannot launch session "${t}": worktree strategy "${h}" requires a git worktree, but "${o}" is not a git repository.`);return c&&i&&(n=i),{actualWorkdir:n,originalWorkdir:o,effectiveSystemPrompt:i&&s?Kw(e.systemPrompt,o,i,s):e.systemPrompt,worktreePath:i,worktreeBranchName:s,clearedResumeSessionId:a,clearedResumeWorktreeFrom:d}}var Ri=class{constructor(t){this.getPersistedSession=t}prepareSpawn(t,r){return Wm(t,r,this.getPersistedSession)}hydrateSpawnedSession(t,r,n){n.worktreeStrategy&&n.worktreeStrategy!=="off"&&(t.originalWorkdir=r.originalWorkdir),r.worktreePath&&(t.worktreePath=r.worktreePath,t.worktreeBranch=r.worktreeBranchName,t.worktreeState="provisioned"),n.worktreePrTargetRepo&&(t.worktreePrTargetRepo=n.worktreePrTargetRepo)}};ke();var Ai=class{constructor(t){this.deps=t}applySessionPatch(t,r){let n=this.deps.store.getPersistedSession(t);n&&(Object.assign(n,r),this.deps.store.assertPersistedEntry(n));let o=this.findActiveSessionForRef(t,n);return o&&this.applyPatchToActiveSession(o,r),!n&&!o?!1:(n&&this.deps.store.saveIndex(),!0)}matchesExistingSession(t,r){if(!r)return!1;let n=T(t),o=T(r);return!!(r.sessionId&&t.id===r.sessionId||o&&o===n||r?.harnessSessionId&&t.harnessSessionId===r.harnessSessionId||r?.name&&t.name===r.name)}findActiveSessionForRef(t,r){let n=this.deps.resolveSession(t);if(n)return n;for(let o of this.deps.sessions.values())if(ee(o)===t||T(o)===t||o.harnessSessionId===t||this.matchesExistingSession(o,r))return o}applyPatchToActiveSession(t,r){typeof t.applyControlPatch=="function"?t.applyControlPatch({lifecycle:r.lifecycle,approvalState:r.approvalState,worktreeState:r.worktreeState,runtimeState:r.runtimeState,deliveryState:r.deliveryState,pendingPlanApproval:r.pendingPlanApproval,planApprovalContext:r.planApprovalContext,planDecisionVersion:r.planDecisionVersion,canonicalPlanPromptVersion:r.canonicalPlanPromptVersion,pendingWorktreeDecisionSince:r.pendingWorktreeDecisionSince}):(r.lifecycle!==void 0&&(t.lifecycle=r.lifecycle),r.approvalState!==void 0&&(t.approvalState=r.approvalState),r.worktreeState!==void 0&&(t.worktreeState=r.worktreeState),r.runtimeState!==void 0&&(t.runtimeState=r.runtimeState),r.deliveryState!==void 0&&(t.deliveryState=r.deliveryState),r.pendingPlanApproval!==void 0&&(t.pendingPlanApproval=r.pendingPlanApproval),r.planApprovalContext!==void 0&&(t.planApprovalContext=r.planApprovalContext),r.planDecisionVersion!==void 0&&(t.planDecisionVersion=r.planDecisionVersion),r.canonicalPlanPromptVersion!==void 0&&(t.canonicalPlanPromptVersion=r.canonicalPlanPromptVersion)),r.worktreePath!==void 0&&(t.worktreePath=r.worktreePath),r.worktreeBranch!==void 0&&(t.worktreeBranch=r.worktreeBranch),r.worktreePrUrl!==void 0&&(t.worktreePrUrl=r.worktreePrUrl),r.worktreePrNumber!==void 0&&(t.worktreePrNumber=r.worktreePrNumber),r.worktreeMerged!==void 0&&(t.worktreeMerged=r.worktreeMerged),r.worktreeMergedAt!==void 0&&(t.worktreeMergedAt=r.worktreeMergedAt),r.worktreeDisposition!==void 0&&(t.worktreeDisposition=r.worktreeDisposition),r.worktreePrTargetRepo!==void 0&&(t.worktreePrTargetRepo=r.worktreePrTargetRepo),r.worktreePushRemote!==void 0&&(t.worktreePushRemote=r.worktreePushRemote)}};ke();var qw=new Set(["starting","running"]),Ti=class{constructor(t,r){this.sessions=t;this.store=r}resolveActive(t){let r=this.sessions.get(t);if(r)return r;let n=[...this.sessions.values()],o=n.filter(a=>a.name===t);if(o.length>0)return this.pickPreferredSession(o);let i=n.filter(a=>T(a)===t);if(i.length>0)return this.pickPreferredSession(i);let s=n.filter(a=>a.harnessSessionId===t);if(s.length>0)return this.pickPreferredSession(s)}getPersistedSession(t){return this.store.getPersistedSession(t)}resolveBackendConversationId(t){let r=this.resolveActive(t);return this.store.resolveBackendConversationId(t,r?T(r)??r.harnessSessionId:void 0)}pickPreferredSession(t){let r=t.filter(o=>qw.has(o.status));return(r.length>0?r:t).sort((o,i)=>i.startedAt-o.startedAt)[0]}};ke();ke();Qe();var Mi=class{constructor(t){this.deps=t}async plan(t){let r=ee(t)??t.harnessSessionId;if(this.deps.isAlreadyMerged(r))return console.info(`[SessionManager] handleWorktreeStrategy: session "${t.name}" already merged \u2014 skipping strategy handling`),{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};if(t.status!=="completed")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};if(!this.deps.shouldRunWorktreeStrategy(t))return console.info(`[SessionManager] handleWorktreeStrategy: skipping \u2014 session "${t.name}" is in phase "${t.phase}"`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let n=t.worktreeStrategy;if(!n||n==="off"||n==="manual")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let o=t.worktreePath,i=this.deps.resolveWorktreeRepoDir(t.originalWorkdir,o),s=t.worktreeBranch;if(!i)return{kind:"notify",label:"worktree-missing-repo-dir",message:`\u26A0\uFE0F [${t.name}] Cannot determine the original repo for worktree ${o}. Manual inspection is required.`};if(!s)return{kind:"notify",label:"worktree-no-branch-name",message:`\u26A0\uFE0F [${t.name}] Cannot determine branch name for worktree ${o}. The worktree may have been removed or is in detached HEAD state. Manual cleanup may be needed.`};let a=t.worktreeBaseBranch??gt(i),d=this.deps.getWorktreeCompletionState(i,o,s,a);if(d==="no-change")return{kind:"no-change",repoDir:i,worktreePath:o,nativeBackendWorktree:ot(t)};if(d==="base-advanced")return{kind:"notify",label:"worktree-no-commits-ahead",message:`\u26A0\uFE0F [${t.name}] Auto-merge: branch '${s}' has no commits ahead of '${a}', but '${a}' has new commits \u2014 commits likely landed outside the worktree branch. Verify that commits were not made directly to '${a}' instead of the worktree branch. Worktree: ${o}`};if(d==="dirty-uncommitted")return{kind:"notify",label:"worktree-dirty-uncommitted",message:`\u26A0\uFE0F [${t.name}] Session completed with uncommitted changes. The branch has no commits ahead of '${a}' but there are modified tracked files in the worktree. Check: ${o}`};let c=Ft(i,s,a);return c?{kind:"decision",strategy:n,repoDir:i,worktreePath:o,branchName:s,baseBranch:a,diffSummary:c,sessionRef:r??void 0}:(console.warn(`[SessionManager] Failed to get diff summary for ${s}, skipping merge-back`),{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}})}};Qe();var Ci=class{constructor(t){this.deps=t;this.actions=new Mi({shouldRunWorktreeStrategy:t.shouldRunWorktreeStrategy,isAlreadyMerged:t.isAlreadyMerged,resolveWorktreeRepoDir:t.resolveWorktreeRepoDir,getWorktreeCompletionState:t.getWorktreeCompletionState})}actions;updatePersistedSessionFor(t,r){for(let n of ze(t))this.deps.updatePersistedSession(n,r)}async handleWorktreeStrategy(t){let r=await this.actions.plan(t);return r.kind==="skip"?r.result:r.kind==="notify"?(this.deps.dispatchSessionNotification(t,{label:r.label,userMessage:r.message}),{notificationSent:!0,worktreeRemoved:!1}):r.kind==="no-change"?this.handleNoChange(t,r.repoDir,r.worktreePath,r.nativeBackendWorktree):r.strategy==="ask"?this.handleAskStrategy(t,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="delegate"?this.handleDelegateStrategy(t,r.branchName,r.baseBranch,r.diffSummary):r.strategy==="auto-merge"?(await this.handleAutoMergeStrategy(t,r.repoDir,r.worktreePath,r.branchName,r.baseBranch,r.diffSummary,r.sessionRef),{notificationSent:!0,worktreeRemoved:!1}):r.strategy==="auto-pr"?this.handleAutoPrStrategy(t,r.baseBranch):{notificationSent:!1,worktreeRemoved:!1}}async handleNoChange(t,r,n,o=ot(t)){let i=o?!0:ht(r,n);return i?(t.worktreePath=void 0,this.updatePersistedSessionFor(t,{worktreePath:void 0,worktreeDisposition:"no-change-cleaned",worktreeState:"none"}),this.deps.dispatchSessionNotification(t,this.deps.worktreeMessages.buildNoChangeNotification({session:t,nativeBackendWorktree:o,cleanupSucceeded:!0,worktreePath:n,preview:this.deps.getOutputPreview(t),originThreadLine:this.deps.originThreadLine(t)}))):this.deps.dispatchSessionNotification(t,this.deps.worktreeMessages.buildNoChangeNotification({session:t,nativeBackendWorktree:o,cleanupSucceeded:!1,worktreePath:n,preview:this.deps.getOutputPreview(t),originThreadLine:this.deps.originThreadLine(t)})),{notificationSent:!0,worktreeRemoved:i}}handleAskStrategy(t,r,n,o){return this.deps.dispatchSessionNotification(t,this.deps.worktreeMessages.buildAskNotification({session:t,branchName:r,baseBranch:n,diffSummary:o,buttons:this.deps.getWorktreeDecisionButtons(t.id)})),this.updatePersistedSessionFor(t,{pendingWorktreeDecisionSince:new Date().toISOString(),lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"}),{notificationSent:!0,worktreeRemoved:!1}}handleDelegateStrategy(t,r,n,o){return this.deps.dispatchSessionNotification(t,this.deps.worktreeMessages.buildDelegateNotification({session:t,branchName:r,baseBranch:n,diffSummary:o})),this.updatePersistedSessionFor(t,{pendingWorktreeDecisionSince:new Date().toISOString(),lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"}),{notificationSent:!0,worktreeRemoved:!1}}async handleAutoMergeStrategy(t,r,n,o,i,s,a=ee(t)??t.harnessSessionId){this.deps.isAlreadyMerged(a)||await this.deps.enqueueMerge(r,async()=>{if(this.deps.isAlreadyMerged(a))return;let d=li(r,o,i,"merge",n);if(d.success){bt(r,o),this.updatePersistedSessionFor(t,{worktreeMerged:!0,worktreeMergedAt:new Date().toISOString(),lifecycle:"terminal",worktreeState:"merged",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0});let m=gr({kind:"merge",branch:o,base:i,filesChanged:s.filesChanged,insertions:s.insertions,deletions:s.deletions});d.stashPopConflict?m+=`
|
|
94
|
+
\u26A0\uFE0F Pre-merge stash pop conflicted \u2014 run \`git stash show ${d.stashRef??"stash@{0}"}\` in ${r} to review stashed changes.`:d.stashed&&(m+=`
|
|
95
|
+
(Pre-existing changes on ${i} were auto-stashed and restored.)`),this.deps.dispatchSessionNotification(t,{label:"worktree-merge-success",userMessage:m});return}if(d.conflictFiles&&d.conflictFiles.length>0){let h=["Resolve merge conflicts in the following files and commit the resolution:","",...d.conflictFiles.map(m=>`- ${m}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${o}"`].join(`
|
|
96
|
+
`);try{await this.deps.spawnConflictResolver(t,r,h),this.deps.dispatchSessionNotification(t,{label:"worktree-merge-conflict",userMessage:`\u26A0\uFE0F [${t.name}] Merge conflicts in ${d.conflictFiles.length} file(s) \u2014 spawned conflict resolver session`,buttons:[[this.deps.makeOpenPrButton(t.id)]]})}catch(m){this.deps.dispatchSessionNotification(t,{label:"worktree-merge-conflict-spawn-failed",userMessage:`\u274C [${t.name}] Merge conflicts detected, but failed to spawn resolver: ${m instanceof Error?m.message:String(m)}`})}return}let c=d.dirtyError?`\u274C [${t.name}] Merge blocked: ${d.error}`:`\u274C [${t.name}] Merge failed: ${d.error??"unknown error"}`;this.deps.dispatchSessionNotification(t,{label:"worktree-merge-error",userMessage:c})},()=>{this.deps.dispatchSessionNotification(t,{label:"worktree-merge-queued",userMessage:`\u{1F550} [${t.name}] Merge queued \u2014 another merge for this repo is in progress. Will notify when complete.`})})}async handleAutoPrStrategy(t,r){return this.updatePersistedSessionFor(t,{lifecycle:"terminal",worktreeState:"pr_in_progress"}),(await this.deps.runAutoPr(t,r)).success||this.updatePersistedSessionFor(t,{pendingWorktreeDecisionSince:new Date().toISOString(),lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"}),{notificationSent:!0,worktreeRemoved:!1}}};import{existsSync as kI,writeFileSync as yI}from"fs";vn();import{randomUUID as Vw}from"crypto";var Ei=class{constructor(t,r){this.onChange=t;this.retentionMs=r}tokens=new Map;replaceAll(t){this.tokens.clear();for(let r of t)this.tokens.set(r.id,r)}clear(){this.tokens.clear()}listForPersistence(){return[...this.tokens.values()]}createActionToken(t,r,n={}){let o={id:Vw(),sessionId:t,kind:r,createdAt:Date.now(),...n};return this.tokens.set(o.id,o),this.onChange(),o}getActionToken(t){let r=this.tokens.get(t);if(r){if(r.expiresAt!=null&&r.expiresAt<=Date.now()){this.tokens.delete(t),this.onChange();return}return r}}consumeActionToken(t){let r=this.getActionToken(t);if(!(!r||r.consumedAt!=null))return r.consumedAt=Date.now(),this.onChange(),r}deleteActionTokensForSession(t){let r=!1;for(let[n,o]of this.tokens)o.sessionId===t&&(this.tokens.delete(n),r=!0);r&&this.onChange()}purgeExpiredActionTokens(t=Date.now()){let r=!1;for(let[n,o]of this.tokens){let i=o.expiresAt!=null&&o.expiresAt<=t,s=o.consumedAt!=null&&t-o.consumedAt>this.retentionMs;(i||s)&&(this.tokens.delete(n),r=!0)}r&&this.onChange()}};ke();ke();var $i=class{constructor(t){this.indexes=t}hasRecordedSession(t){return this.indexes.idIndex.has(t)}getLatestPersistedByName(t){let r,n=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=0;for(let a of this.indexes.persisted.values()){if(a.name!==t){s++;continue}let d=a.createdAt??Number.NEGATIVE_INFINITY,c=a.completedAt??Number.NEGATIVE_INFINITY;(d>n||d===n&&c>o||d===n&&c===o&&s>i)&&(r=a,n=d,o=c,i=s),s++}return r}resolveBackendConversationId(t,r){if(r)return r;let n=this.indexes.idIndex.get(t);if(n){let s=this.indexes.persisted.get(n);return(s?T(s):void 0)??n}let o=this.getLatestPersistedByName(t);if(o)return T(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(t);if(i){let s=this.indexes.persisted.get(i);return(s?T(s):void 0)??i}if(this.indexes.persisted.has(t)){let s=this.indexes.persisted.get(t);return s?T(s)??t:t}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return t}resolveHarnessSessionId(t,r){return this.resolveBackendConversationId(t,r)}getPersistedSession(t){let r=this.indexes.idIndex.get(t);if(r)return this.indexes.persisted.get(r);let n=this.getLatestPersistedByName(t);if(n)return n;let o=this.indexes.backendIdIndex.get(t);return o?this.indexes.persisted.get(o):this.indexes.persisted.get(t)}listPersistedSessions(){return[...this.indexes.persisted.values()].sort((t,r)=>(r.completedAt??0)-(t.completedAt??0))}};import{existsSync as uI,mkdirSync as pI,readFileSync as cI,readdirSync as lI,renameSync as Hm,statSync as mI,unlinkSync as fI,writeFileSync as Gm}from"fs";import{tmpdir as gI}from"os";import{dirname as hI,join as zm}from"path";import{homedir as Hw}from"node:os";import{join as Gw}from"node:path";function Bm(e){let t=e.OPENCLAW_HOME?.trim();if(t)return t;let r=e.HOME?.trim()||Hw();return Gw(r,".openclaw")}vn();var Oi=6,zw=new Set(["running","completed","failed","killed"]);function _i(e){return!!e&&typeof e=="object"}function zr(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function K(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function vt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Qw(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function Km(e){return e==="default"||e==="plan"||e==="bypassPermissions"?e:void 0}function Jw(e){return e==="never"||e==="on-request"?"never":void 0}function Yw(e){return e==="approve"||e==="ask"||e==="delegate"?e:void 0}function Xw(e){if(e==="plan-mode"||e==="codex-first-turn-plan"||e==="soft-plan")return"plan-mode"}function Zw(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function jm(e){return e==="starting"||e==="active"||e==="awaiting_plan_decision"||e==="awaiting_user_input"||e==="awaiting_worktree_decision"||e==="suspended"||e==="terminal"?e:void 0}function eI(e){return e==="not_required"||e==="pending"||e==="approved"||e==="changes_requested"||e==="rejected"?e:void 0}function tI(e){return e==="none"||e==="provisioned"||e==="pending_decision"||e==="merge_in_progress"||e==="pr_in_progress"||e==="merged"||e==="pr_open"||e==="dismissed"||e==="cleanup_failed"?e:void 0}function rI(e){return e==="live"||e==="stopped"?e:void 0}function nI(e){return e==="idle"||e==="notifying"||e==="wake_pending"||e==="failed"?e:void 0}function oI(e){return e==="awaiting_approval"||e==="approved_then_implemented"||e==="implemented_without_required_approval"||e==="not_plan_gated"?e:void 0}function iI(e){return e==="plan-approve"||e==="plan-request-changes"||e==="plan-reject"||e==="worktree-merge"||e==="worktree-create-pr"||e==="worktree-update-pr"||e==="worktree-view-pr"||e==="worktree-decide-later"||e==="worktree-dismiss"||e==="session-resume"||e==="session-restart"||e==="view-output"||e==="question-answer"?e:void 0}function sI(e){if(!_i(e))return;let t=K(e.provider),r=K(e.accountId),n=K(e.target),o=K(e.threadId),i=K(e.sessionKey);if(!(!t||!n))return{provider:t,accountId:r,target:n,threadId:o,sessionKey:i}}function aI(e,t,r){if(_i(e)){let n=K(e.kind),o=K(e.conversationId);if(o&&(n==="claude-code"||n==="codex-app-server"))return{kind:n,conversationId:o,runId:K(e.runId),worktreeId:K(e.worktreeId),worktreePath:K(e.worktreePath)}}if(t==="claude-code")return{kind:"claude-code",conversationId:r}}function dI(e){if(typeof e=="string"&&zw.has(e))return e==="running"?"killed":e}function qm(e){if(!_i(e))return;let t=zr(e.harnessSessionId);if(!t)return;let r=dI(e.status);if(!r)return;let n=e.status==="running",o=K(e.worktreePath),i=K(e.worktreeBranch),s=K(e.originChannel),a=typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,d=K(e.originSessionKey),c=sI(e.route);if(!c)return;let h=Ur({route:c,originChannel:s,originThreadId:a,originSessionKey:d});if(!h||o&&!i)return;let m=K(e.harness),S=aI(e.backendRef,m,t);return{sessionId:K(e.sessionId),harnessSessionId:t,backendRef:S,name:zr(e.name,t),prompt:zr(e.prompt),workdir:zr(e.workdir,"(unknown)"),model:K(e.model),reasoningEffort:Qw(e.reasoningEffort),createdAt:vt(e.createdAt),completedAt:vt(e.completedAt),status:r,lifecycle:n?jm(e.lifecycle)??"suspended":jm(e.lifecycle),approvalState:eI(e.approvalState),worktreeState:tI(e.worktreeState),runtimeState:n?"stopped":rI(e.runtimeState),deliveryState:nI(e.deliveryState),killReason:Zw(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:K(e.originAgentId),originChannel:s,originThreadId:a,originSessionKey:d,route:h,outputPath:K(e.outputPath),harness:m,requestedPermissionMode:Km(e.requestedPermissionMode),currentPermissionMode:Km(e.currentPermissionMode),approvalExecutionState:oI(e.approvalExecutionState),planModeApproved:e.planModeApproved===!0,pendingPlanApproval:e.pendingPlanApproval===!0,planApprovalContext:Xw(e.planApprovalContext),planDecisionVersion:vt(e.planDecisionVersion),canonicalPlanPromptVersion:vt(e.canonicalPlanPromptVersion),planApproval:Yw(e.planApproval),codexApprovalPolicy:Jw(e.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:e.worktreeStrategy==="off"||e.worktreeStrategy==="manual"||e.worktreeStrategy==="ask"||e.worktreeStrategy==="delegate"||e.worktreeStrategy==="auto-merge"||e.worktreeStrategy==="auto-pr"?e.worktreeStrategy:void 0,worktreeMerged:typeof e.worktreeMerged=="boolean"?e.worktreeMerged:void 0,worktreeMergedAt:K(e.worktreeMergedAt),worktreePrUrl:K(e.worktreePrUrl),worktreePrNumber:vt(e.worktreePrNumber),pendingWorktreeDecisionSince:K(e.pendingWorktreeDecisionSince),lastWorktreeReminderAt:K(e.lastWorktreeReminderAt),worktreeBaseBranch:K(e.worktreeBaseBranch),worktreePrTargetRepo:K(e.worktreePrTargetRepo),worktreePushRemote:K(e.worktreePushRemote),worktreeDecisionSnoozedUntil:K(e.worktreeDecisionSnoozedUntil),worktreeDisposition:e.worktreeDisposition==="active"||e.worktreeDisposition==="pr-opened"||e.worktreeDisposition==="merged"||e.worktreeDisposition==="dismissed"||e.worktreeDisposition==="no-change-cleaned"?e.worktreeDisposition:void 0,worktreeDismissedAt:K(e.worktreeDismissedAt),resumable:n?!0:e.resumable===!0}}function Vm(e){if(!_i(e))return;let t=iI(e.kind),r=zr(e.id),n=zr(e.sessionId),o=vt(e.createdAt);if(!(!r||!n||!t||o==null))return{id:r,sessionId:n,kind:t,createdAt:o,planDecisionVersion:vt(e.planDecisionVersion),expiresAt:vt(e.expiresAt),consumedAt:vt(e.consumedAt),optionIndex:vt(e.optionIndex),label:K(e.label),targetUrl:K(e.targetUrl)}}function Ni(e){if(!e.backendRef?.kind||!e.backendRef.conversationId)throw new Error(`Persisted session ${e.harnessSessionId} is missing required backend ref metadata.`);if(!e.route?.provider||!e.route.target)throw new Error(`Persisted session ${e.harnessSessionId} is missing required route metadata.`);if(e.worktreePath&&!e.worktreeBranch)throw new Error(`Persisted session ${e.harnessSessionId} is missing required worktreeBranch metadata.`)}function ad(e){return!!e&&typeof e=="object"}function dd(e){return e instanceof Error?e.message:String(e)}function Qm(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||zm(Bm(e),"code-agent-sessions.json")}function Jm(e,t,r){try{pI(hI(e),{recursive:!0});let n=e+".tmp";Gm(n,JSON.stringify({schemaVersion:Oi,sessions:t,actionTokens:r},null,2),"utf-8"),Hm(n,e)}catch(n){console.warn(`[SessionStore] Failed to save session index: ${dd(n)}`)}}function Fi(e,t){try{if(!uI(e))return;let r=`${e}.legacy-${Date.now()}.json`;Hm(e,r),console.warn(`[SessionStore] Breaking upgrade: archived ${t} session store to ${r}. Legacy sessions are not loaded by this release.`)}catch(r){console.warn(`[SessionStore] Failed to archive legacy session store: ${dd(r)}`)}}function SI(e,t){try{if(t.length===0)return;let r=`${e}.codex-sdk-legacy-${Date.now()}.json`;Gm(r,JSON.stringify(t,null,2),"utf-8"),console.warn(`[SessionStore] Breaking Codex transport upgrade: archived ${t.length} legacy Codex SDK session(s) to ${r}. They are not loaded by the App Server backend.`)}catch(r){console.warn(`[SessionStore] Failed to archive legacy Codex SDK sessions: ${dd(r)}`)}}function Ym(e,t){try{let r=gI(),n=lI(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let i=zm(r,o),s=mI(i).mtimeMs;e-s>t&&fI(i)}catch{}}catch{}}function Xm(e){let{indexPath:t,clearAll:r,indexPersistedEntry:n,setActionToken:o,purgeExpiredActionTokens:i,saveIndex:s}=e;try{let a=cI(t,"utf-8"),d=JSON.parse(a);if(Array.isArray(d)){Fi(t,"legacy array store"),s();return}if(!ad(d)||d.schemaVersion!==Oi&&d.schemaVersion!==4){Fi(t,`schema mismatch (expected v${Oi})`),s();return}let c=Array.isArray(d.sessions)?d.sessions:[],h=[];for(let S of c){if(ad(S)&&S.harness==="codex"){let x=ad(S.backendRef)?S.backendRef:void 0;if((typeof x?.kind=="string"?x.kind:void 0)!=="codex-app-server"){h.push(S);continue}}let y=qm(S);if(!y){r(),Fi(t,"invalid v4 session entry"),s();return}n(y)}h.length>0&&(SI(t,h),s());let m=Array.isArray(d.actionTokens)?d.actionTokens:[];for(let S of m){let y=Vm(S);if(!y){r(),Fi(t,"invalid v4 action token"),s();return}o(y)}i()}catch{}}var wI=new Set(["completed","failed","killed"]),Zm=1440*60*1e3;function II(e){return e instanceof Error?e.message:String(e)}var Di=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;backendIdIndex=new Map;actionTokens;actionTokenStore;indexPath;queries;constructor(t={}){let r=t.env??process.env;this.indexPath=t.indexPath??Qm(r),this.actionTokenStore=new Ei(()=>this.saveIndex(),Zm),this.actionTokens=this.actionTokenStore.tokens,this.queries=new $i({persisted:this.persisted,idIndex:this.idIndex,nameIndex:this.nameIndex,backendIdIndex:this.backendIdIndex}),r.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){Xm({indexPath:this.indexPath,clearAll:()=>{this.persisted.clear(),this.idIndex.clear(),this.nameIndex.clear(),this.backendIdIndex.clear(),this.actionTokenStore.clear()},indexPersistedEntry:t=>this.indexPersistedEntry(t),setActionToken:t=>{this.actionTokens.set(t.id,t)},purgeExpiredActionTokens:()=>this.actionTokenStore.purgeExpiredActionTokens(),saveIndex:()=>this.saveIndex()})}saveIndex(){Jm(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence())}assertPersistedEntry(t){Ni(t)}getEntryStorageKey(t){return t.harnessSessionId}buildPersistedBackendRef(t){return t.backendRef??{kind:Ha(t)==="codex"?"codex-app-server":"claude-code",conversationId:t.harnessSessionId}}indexPersistedEntry(t){let r=this.getEntryStorageKey(t);this.persisted.set(r,t),t.sessionId&&this.idIndex.set(t.sessionId,r),t.name&&this.nameIndex.set(t.name,r);let n=T(t);n&&this.backendIdIndex.set(n,r)}removePersistedIndexes(t){let r=this.getEntryStorageKey(t);this.persisted.delete(r);for(let[n,o]of this.idIndex)o===r&&this.idIndex.delete(n);for(let[n,o]of this.nameIndex)o===r&&this.nameIndex.delete(n);for(let[n,o]of this.backendIdIndex)o===r&&this.backendIdIndex.delete(n)}markRunning(t){if(!t.harnessSessionId)return;let r=typeof t.controlStateSnapshot=="function"?t.controlStateSnapshot():{planModeApproved:!1},n=Ur({route:t.route,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey});if(!n)return;let o={sessionId:t.id,harnessSessionId:t.harnessSessionId,backendRef:this.buildPersistedBackendRef(t),name:t.name,prompt:t.prompt,workdir:t.originalWorkdir??t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",lifecycle:t.lifecycle,approvalState:t.approvalState,worktreeState:t.worktreeState,runtimeState:t.runtimeState,deliveryState:t.deliveryState,costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,route:n,harness:t.harnessName,requestedPermissionMode:t.requestedPermissionMode,currentPermissionMode:t.currentPermissionMode,approvalExecutionState:t.approvalExecutionState,planModeApproved:r.planModeApproved,pendingPlanApproval:t.pendingPlanApproval,planApprovalContext:t.planApprovalContext,planDecisionVersion:t.planDecisionVersion,canonicalPlanPromptVersion:t.canonicalPlanPromptVersion,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch,worktreeStrategy:t.worktreeStrategy,worktreeBaseBranch:t.worktreeBaseBranch,worktreePrTargetRepo:t.worktreePrTargetRepo,resumable:t.isExplicitlyResumable};Ni(o),this.indexPersistedEntry(o),this.saveIndex()}hasRecordedSession(t){return this.queries.hasRecordedSession(t)}persistTerminal(t){if(!t.harnessSessionId)return;let r=typeof t.controlStateSnapshot=="function"?t.controlStateSnapshot():{planModeApproved:!1},n=Ur({route:t.route,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey});if(!n)return;let o;try{let s=qr(t.id);if(kI(s))o=s;else{let a=t.getOutput().join(`
|
|
97
|
+
`);a.length>0&&(yI(s,a,"utf-8"),o=s)}}catch(s){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${II(s)}`)}let i={sessionId:t.id,harnessSessionId:t.harnessSessionId,backendRef:this.buildPersistedBackendRef(t),name:t.name,prompt:t.prompt,workdir:t.originalWorkdir??t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,completedAt:t.completedAt,status:t.status,lifecycle:t.lifecycle,approvalState:t.approvalState,worktreeState:t.worktreeState,runtimeState:t.runtimeState,deliveryState:t.deliveryState,killReason:t.killReason,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,route:n,outputPath:o,harness:t.harnessName,requestedPermissionMode:t.requestedPermissionMode,currentPermissionMode:t.currentPermissionMode,approvalExecutionState:t.approvalExecutionState,planModeApproved:r.planModeApproved,pendingPlanApproval:t.pendingPlanApproval,planApprovalContext:t.planApprovalContext,planDecisionVersion:t.planDecisionVersion,canonicalPlanPromptVersion:t.canonicalPlanPromptVersion,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:t.worktreePath,worktreeBranch:t.worktreeBranch,worktreeStrategy:t.worktreeStrategy,worktreeBaseBranch:t.worktreeBaseBranch,worktreePrTargetRepo:t.worktreePrTargetRepo,resumable:t.isExplicitlyResumable};Ni(i),this.indexPersistedEntry(i),this.saveIndex()}getLatestPersistedByName(t){return this.queries.getLatestPersistedByName(t)}resolveBackendConversationId(t,r){return this.queries.resolveBackendConversationId(t,r)}resolveHarnessSessionId(t,r){return this.queries.resolveHarnessSessionId(t,r)}getPersistedSession(t){return this.queries.getPersistedSession(t)}listPersistedSessions(){return this.queries.listPersistedSessions()}cleanupTmpOutputFiles(t){this.actionTokenStore.purgeExpiredActionTokens(t),Ym(t,Zm)}evictOldestPersisted(t){let r=this.listPersistedSessions();if(r.length<=t)return;let n=r.slice(t);for(let o of n)this.removePersistedIndexes(o);this.saveIndex()}shouldGcActiveSession(t,r,n){return!t.completedAt||!wI.has(t.status)?!1:r-t.completedAt>n}getActionToken(t){return this.actionTokenStore.getActionToken(t)}consumeActionToken(t){return this.actionTokenStore.consumeActionToken(t)}deleteActionTokensForSession(t){this.actionTokenStore.deleteActionTokensForSession(t)}purgeExpiredActionTokens(t=Date.now()){this.actionTokenStore.purgeExpiredActionTokens(t)}};var xI=new Set(["completed","failed","killed"]),Li=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(t){let r=t.costUsd??0,n=t.status;this.metrics.totalCostUsd+=r;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+r),xI.has(n)&&this.metrics.sessionsByStatus[n]++,t.completedAt){let i=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||r>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:r,prompt:hr(t.prompt,80)})}getMetrics(){return{totalCostUsd:this.metrics.totalCostUsd,costPerDay:new Map(this.metrics.costPerDay),sessionsByStatus:{...this.metrics.sessionsByStatus},totalLaunched:this.metrics.totalLaunched,totalDurationMs:this.metrics.totalDurationMs,sessionsWithDuration:this.metrics.sessionsWithDuration,mostExpensive:this.metrics.mostExpensive?{...this.metrics.mostExpensive}:null}}};import{execFile as PI}from"child_process";var bI=3e4,vI=2e3,RI=2e4,Kn=4;function ef(e){return e instanceof Error?e.message:String(e)}var Ui=class{pendingRetryTimers=new Map;clearPendingRetries(){for(let t of this.pendingRetryTimers.values())for(let r of t)clearTimeout(r);this.pendingRetryTimers.clear()}clearRetryTimersForSession(t){let r=this.pendingRetryTimers.get(t);if(r){for(let n of r)clearTimeout(n);this.pendingRetryTimers.delete(t)}}dispose(){this.clearPendingRetries()}execute(t,r,n=1){let o=Date.now();n===1&&r.onStarted?.(),this.log("info","dispatch_started",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:n,maxAttempts:Kn}),PI("openclaw",t,{timeout:bI},(i,s,a)=>{let d=Date.now()-o;if(!i){this.log("info","dispatch_succeeded",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:n,maxAttempts:Kn,elapsedMs:d}),r.onSuccess?.();return}let c=a?.trim()?` | stderr: ${a.trim()}`:"";if(n>=Kn){this.log("error","dispatch_failed",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:n,maxAttempts:Kn,elapsedMs:d,error:`${ef(i)}${c}`,terminal:!0}),r.onFinalFailure?.();return}let h=this.retryDelayMs(n);this.log("error","dispatch_retry_scheduled",{label:r.label,sessionId:r.sessionId,target:r.target,phase:r.phase,messageKind:r.messageKind,route:r.routeSummary,attempt:n,maxAttempts:Kn,elapsedMs:d,retryDelayMs:h,error:`${ef(i)}${c}`});let m=setTimeout(()=>{let S=this.pendingRetryTimers.get(r.sessionId);S&&(S.delete(m),S.size===0&&this.pendingRetryTimers.delete(r.sessionId)),this.execute(t,r,n+1)},h);m.unref?.(),this.pendingRetryTimers.has(r.sessionId)||this.pendingRetryTimers.set(r.sessionId,new Set),this.pendingRetryTimers.get(r.sessionId).add(m)})}retryDelayMs(t){let r=Math.max(0,t-1),n=vI*2**r;return Math.min(n,RI)}log(t,r,n){let o=`[WakeDispatcher] ${JSON.stringify({event:r,...n})}`;if(t==="error"){console.error(o);return}console.info(o)}};vn();var Wi=class{resolve(t){let r=al(t);if(!(!r?.provider||!r.target))return{channel:r.provider,target:r.target,accountId:r.accountId,threadId:r.threadId,sessionKey:r.sessionKey}}summary(t){if(!t)return"system";let r=t.accountId?`|${t.accountId}`:"",n=t.threadId?`#${t.threadId}`:"";return`${t.channel}${r}|${t.target}${n}`}};import{randomUUID as AI}from"crypto";var Bi=class{buildChatSendArgs(t,r,n){return["gateway","call","chat.send","--expect-final","--timeout","30000","--params",JSON.stringify({sessionKey:t,message:r,deliver:n,idempotencyKey:AI()})]}buildDirectNotificationArgs(t,r,n){let o=["message","send","--channel",t.channel,"--target",t.target,"--message",r];return t.accountId&&o.push("--account",t.accountId),t.threadId&&o.push("--thread-id",t.threadId),n&&t.channel==="telegram"&&o.push("--buttons",JSON.stringify(n.map(i=>i.map(s=>({text:s.label,callback_data:s.callbackData.startsWith(`${Gr}:`)?s.callbackData:`${Gr}:${s.callbackData}`}))))),o}buildSystemEventArgs(t){return["system","event","--text",t,"--mode","now"]}};var Ki=class{routes=new Wi;transport=new Bi;executor=new Ui;clearPendingRetries(){this.executor.clearPendingRetries()}clearRetryTimersForSession(t){this.executor.clearRetryTimersForSession(t)}dispose(){this.executor.dispose()}sendWake(t,r,n,o,i,s){let d=this.routes.resolve(t)?.sessionKey?.trim();if(!d){this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-system`,sessionId:t.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",onSuccess:s,onFinalFailure:i});return}this.executor.execute(this.transport.buildChatSendArgs(d,r,!0),{label:n,sessionId:t.id,target:"chat.send",phase:o,routeSummary:`session:${d}`,messageKind:"wake",onSuccess:s,onFinalFailure:()=>{this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-fallback`,sessionId:t.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",onSuccess:s,onFinalFailure:i})}})}sendUserNotification(t,r,n,o,i,s){let a=!!(o&&o.length>0),d=this.routes.resolve(t);if(!d){if(a){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${t.id} has no direct route; refusing text-only fallback because buttons would be lost.`),i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-notify-system`,sessionId:t.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",onSuccess:s,onFinalFailure:i});return}this.executor.execute(this.transport.buildDirectNotificationArgs(d,r,o),{label:`${n}-notify`,sessionId:t.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(d),messageKind:"notify",onSuccess:s,onFinalFailure:()=>{if(a){console.warn(`[WakeDispatcher] Interactive notification "${n}" for session ${t.id} failed direct delivery; refusing text-only fallback because buttons would be lost.`),i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(r),{label:`${n}-notify-fallback`,sessionId:t.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",onSuccess:s,onFinalFailure:i})}})}dispatchSessionNotification(t,r){let n=r.hooks,o=r.wakeMessageOnNotifySuccess!=null||r.wakeMessageOnNotifyFailed!=null,i=r.notifyUser??(r.wakeMessage?"on-wake-fallback":"always"),s=r.userMessage?.trim(),a=r.wakeMessage?.trim();if(o){let d=r.wakeMessageOnNotifySuccess?.trim(),c=r.wakeMessageOnNotifyFailed?.trim(),h=y=>{y&&(n?.onWakeStarted?.(),this.sendWake(t,y,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded))},m=()=>{n?.onNotifySucceeded?.(),d&&h(d)},S=c?()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.(),h(c)}:()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()};s?(n?.onNotifyStarted?.(),this.sendUserNotification(t,s,r.label,r.buttons,S,m)):S();return}i==="always"&&s&&(n?.onNotifyStarted?.(),this.sendUserNotification(t,s,r.label,r.buttons,()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()},()=>n?.onNotifySucceeded?.())),a&&(n?.onWakeStarted?.(),i==="on-wake-fallback"&&s&&!this.routes.resolve(t)?.sessionKey&&(n?.onNotifyStarted?.(),this.sendUserNotification(t,s,r.label,r.buttons,()=>{n?.onNotifyFailed?.(),r.onUserNotifyFailed?.()},()=>n?.onNotifySucceeded?.())),this.sendWake(t,a,`${r.label}-wake`,"wake",n?.onWakeFailed,n?.onWakeSucceeded))}};var ji=class{constructor(t,r){this.actionTokens=t;this.isGitHubCliAvailable=r}createActionToken(t,r,n={}){return this.actionTokens.createActionToken(t,r,{expiresAt:Date.now()+10080*60*1e3,...n})}consumeActionToken(t){return this.actionTokens.consumeActionToken(t)}makeActionButton(t,r,n,o={}){let i=this.createActionToken(t,r,{label:n,...o});return{label:n,callbackData:i.id}}getWorktreeDecisionButtons(t,r){if(!r)return[];let n=[],o=[this.makeActionButton(t,"worktree-merge","Merge")];if(this.isGitHubCliAvailable())r.worktreePrUrl?(o.push(this.makeActionButton(t,"worktree-view-pr","View PR",{targetUrl:r.worktreePrUrl})),n.push(o),n.push([this.makeActionButton(t,"worktree-update-pr","Sync PR"),this.makeActionButton(t,"worktree-decide-later","Later")])):(o.push(this.makeActionButton(t,"worktree-create-pr","Open PR")),n.push(o),n.push([this.makeActionButton(t,"worktree-decide-later","Later"),this.makeActionButton(t,"worktree-dismiss","Discard")]));else return n.push([...o,this.makeActionButton(t,"worktree-decide-later","Later")]),n.push([this.makeActionButton(t,"worktree-dismiss","Discard")]),n;return r.worktreePrUrl&&n.push([this.makeActionButton(t,"worktree-dismiss","Discard")]),n}getPlanApprovalButtons(t,r){return[[this.makeActionButton(t,"plan-approve","Approve",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(t,"plan-request-changes","Revise",{planDecisionVersion:r?.planDecisionVersion}),this.makeActionButton(t,"plan-reject","Reject",{planDecisionVersion:r?.planDecisionVersion})]]}getResumeButtons(t,r){let n=[];return r.isExplicitlyResumable&&n.push(this.makeActionButton(t,"session-resume","Resume")),n.push(this.makeActionButton(t,"view-output","View output")),[n]}getQuestionButtons(t,r){if(r.length!==0)return[r.map((n,o)=>this.makeActionButton(t,"question-answer",n.label,{optionIndex:o}))]}};ke();var qi=class{constructor(t,r){this.wakeDispatcher=t;this.applyPersistedPatch=r}dispatch(t,r){let n=this.getDeliveryRef(t),o=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifySuccess?.trim()),i=!!(r.wakeMessage?.trim()||r.wakeMessageOnNotifyFailed?.trim()),s={onNotifyStarted:()=>{this.applyDeliveryState(n,"notifying"),r.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{this.applyDeliveryState(n,o?"wake_pending":"idle"),r.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{this.applyDeliveryState(n,i?"wake_pending":"failed"),r.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyDeliveryState(n,"wake_pending"),r.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{this.applyDeliveryState(n,"idle"),r.hooks?.onWakeSucceeded?.()},onWakeFailed:()=>{this.applyDeliveryState(n,"failed"),r.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(t,{...r,hooks:s})}notifyWorktreeOutcome(t,r){this.dispatch(t,{label:"worktree-outcome",userMessage:r,notifyUser:"always"})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(t){return ee(t)??T(t)??""}applyDeliveryState(t,r){!t||!r||this.applyPersistedPatch(t,{deliveryState:r})}};Qe();import{existsSync as TI}from"fs";var Vi=class{getCompletionState(t,r,n,o){return Dn(t,n,o)?"has-commits":Dn(t,o,n)?"base-advanced":pi(r)?"dirty-uncommitted":"no-change"}isResolvedWorktreeEligibleForCleanup(t,r,n){if(!t.worktreePath||!t.workdir||!TI(t.worktreePath)||t.pendingWorktreeDecisionSince||t.worktreeState==="pending_decision")return!1;let o=t.worktreeMergedAt??t.worktreeDismissedAt??t.completedAt??t.createdAt,i=typeof o=="string"?new Date(o).getTime():Number(o??0);return!!i&&r-i>=n}};var Hi=class{constructor(t,r,n,o){this.pendingQuestions=t;this.dispatchSessionNotification=r;this.clearWaitingTimestamp=n;this.getQuestionButtons=o}async handleAskUserQuestion(t,r){let i=r?.questions??[];if(i.length===0)throw new Error("AskUserQuestion: no questions in input");let s=i[0],a=s.options??[],d=this.getQuestionButtons(t.id,a),c=`\u2753 [${t.name}] ${s.question}`,h=[`[ASK USER QUESTION] Session "${t.name}" has a question requiring user input.`,"",`Question: ${s.question}`,...a.length>0?["Options:",...a.map((m,S)=>` ${S+1}. ${m.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${t.id}", message="<answer>") with their answer.`].join(`
|
|
98
|
+
`);return new Promise((m,S)=>{let y=setTimeout(()=>{this.pendingQuestions.delete(t.id),S(new Error(`AskUserQuestion timed out after 600s for session "${t.name}"`))},6e5);y.unref?.(),this.pendingQuestions.set(t.id,{resolve:m,reject:S,questions:i,timeoutHandle:y}),this.dispatchSessionNotification(t,{label:"ask-user-question",userMessage:c,notifyUser:"always",buttons:d,wakeMessageOnNotifySuccess:["AskUserQuestion delivered to the user.",`Session: ${t.name} | ID: ${t.id}`,`Question: ${s.question}`,"Await their selection \u2014 do NOT answer this question yourself."].join(`
|
|
99
|
+
`),wakeMessageOnNotifyFailed:h})})}resolveAskUserQuestion(t,r){let n=this.pendingQuestions.get(t);if(!n){console.warn(`[SessionQuestionService] resolveAskUserQuestion: no pending question for session "${t}"`);return}clearTimeout(n.timeoutHandle),this.pendingQuestions.delete(t);let o=n.questions[0],i=o.options??[],s=i[r];if(!s){n.reject(new Error(`AskUserQuestion: invalid option index ${r} (${i.length} options available)`));return}this.clearWaitingTimestamp(t),n.resolve({behavior:"allow",updatedInput:{questions:n.questions,answers:{[o.question]:s.label}}})}dispose(){for(let t of this.pendingQuestions.values())clearTimeout(t.timeoutHandle),t.reject(new Error("SessionManager disposed before AskUserQuestion resolved."));this.pendingQuestions.clear()}};function Gi(e){return[`Requested permission mode: ${e.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${e.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${e.approvalExecutionState??"unknown"}`]}function jn(e){switch(e){case"user":return"Stopped by user";case"shutdown":return"Stopped by shutdown";case"startup-timeout":return"Stopped by startup timeout";case"unknown":case void 0:return"Stopped unexpectedly";default:return"Stopped"}}function ud(e){let{session:t,originThreadLine:r,preview:n}=e,o=`$${(t.costUsd??0).toFixed(2)}`,i=St(t.duration);return{userMessage:`\u2705 [${t.name}] Completed | ${o} | ${i}`,wakeMessage:["Coding agent session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,r,...Gi(t),"","Output preview:",n,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${t.id}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.","3. The plugin already sent the canonical completion notification to the user.","4. Do NOT send a duplicate plain-text recap unless you need real synthesis, a concrete risk callout, or next-step guidance beyond that canonical message."].join(`
|
|
100
|
+
`)}}function pd(e){let{session:t,originThreadLine:r,errorSummary:n,preview:o,worktreeAutoCleaned:i,failedButtons:s}=e,a=o.trim()?["","Output preview:",o]:[],d=i?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[],c=`$${(t.costUsd??0).toFixed(2)}`,h=St(t.duration);return{userMessage:[`\u274C [${t.name}] Failed | ${c} | ${h}`,` \u26A0\uFE0F ${n}`].join(`
|
|
101
|
+
`),wakeMessage:["Coding agent session failed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,r,...Gi(t),...t.harnessSessionId?[`Backend conversation ID: ${t.harnessSessionId}`]:[],"","Failure summary:",n,...a,...d,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${t.id}', full=true) to inspect the full failure context.`,`2. Continue the same session with agent_respond(session='${t.id}', message='<next instruction>').`,` If you intentionally want to fork or switch harnesses, launch a new session with agent_launch(resume_session_id='${t.id}', fork_session=true, ...)`," If the failure is a launch/config issue, relaunch fresh with agent_launch(prompt=...).","3. Notify the user with the failure cause and the next action you are taking."].join(`
|
|
102
|
+
`),buttons:s}}function cd(e){let{session:t,originThreadLine:r,preview:n}=e,o=`$${(t.costUsd??0).toFixed(2)}`;return{userMessage:`\u23F8\uFE0F [${t.name}] Turn completed | ${o}`,wakeMessage:["Coding agent session turn ended.",`Name: ${t.name}`,`ID: ${t.id}`,`Status: ${t.status}`,`Lifecycle: ${t.lifecycle}`,"","Last output (~20 lines):",n,...r?["",r]:[]].join(`
|
|
103
|
+
`)}}function ld(e){let{sessionName:t,sessionId:r,branchName:n,baseBranch:o,promptSnippet:i,commitLines:s,moreNote:a,diffSummary:d}=e;return[`[DELEGATED WORKTREE DECISION] Session "${t}" completed with changes.`,"",`Session ID: ${r}`,`Branch: ${n} \u2192 ${o}`,`Commits: ${d.commits} | Files: ${d.filesChanged} | +${d.insertions} / -${d.deletions}`,"",...s,...a?[a]:[],"","Original task prompt (first 500 chars):",i,"","You own the next step for this worktree.",`- Merge immediately with agent_merge(session="${t}", base_branch="${o}") if the changes are clearly in-scope and low-risk.`,"- If a PR is safer, message the user with the summary and ask for confirmation before calling agent_pr().","- If scope or risk is unclear, message the user and ask for guidance.","- Never call agent_pr() autonomously in delegate mode.","- After deciding, notify the user briefly with what you did and why."].join(`
|
|
104
|
+
`)}function md(e,t){return[`[DELEGATED WORKTREE DECISION REMINDER] Session "${e.name}" still has an unresolved worktree decision.`,"",`Session ID: ${e.sessionId??e.harnessSessionId}`,`Branch: ${e.worktreeBranch??"unknown"}`,`Pending: ${t}h`,"","Resolve it now:",`- agent_merge(session="${e.name}") if the diff is clearly safe and in scope`,"- If a PR is safer, ask the user before agent_pr()","- If scope or risk is unclear, ask the user for guidance","- Never call agent_pr() autonomously in delegate mode"].join(`
|
|
105
|
+
`)}function fd(e){let{sessionName:t,sessionId:r,cleanupSummary:n,preview:o,originThreadLine:i,requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d}=e,c=o.trim()?["","Output preview:",o]:[];return["Coding agent session completed with no repository changes.",`Name: ${t} | ID: ${r}`,`Worktree outcome: ${n}`,...i?[i]:[],...Gi({requestedPermissionMode:s,currentPermissionMode:a,approvalExecutionState:d}),...c,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${r}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.","3. The plugin already sent the canonical completion notification to the user, including that no repo changes were kept.","4. Do NOT send a duplicate plain-text recap unless you need real synthesis, a concrete risk callout, or next-step guidance beyond that canonical message."].join(`
|
|
106
|
+
`)}function gd(e){let t=[],r=e.changedFiles.slice(0,3).map(o=>`\`${o}\``);if(r.length>0){let o=e.changedFiles.length-r.length;t.push(o>0?`Touches ${r.join(", ")} and ${o} more file${o===1?"":"s"}`:`Touches ${r.join(", ")}`)}let n=[...new Set(e.commitMessages.map(o=>o.message.trim()).filter(Boolean))].slice(0,2);return n.length>0&&t.push(`Recent work: ${n.join("; ")}`),t}function hd(e){let{session:t,preview:r,originThreadLine:n,planApprovalMode:o,planApprovalButtons:i,questionButtons:s}=e,a=t.pendingPlanApproval,d=a?o==="ask"?`\u{1F4CB} [${t.name}] Plan ready for approval:
|
|
112
107
|
|
|
113
108
|
${r}
|
|
114
109
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
`)}
|
|
119
|
-
`)
|
|
120
|
-
`);
|
|
121
|
-
`);try{this.sendReminderNotification(
|
|
122
|
-
`),
|
|
123
|
-
`)
|
|
110
|
+
Choose Approve, Revise, or Reject below.`:void 0:`\u2753 [${t.name}] Question waiting for reply:
|
|
111
|
+
|
|
112
|
+
${r}`;if(a){let h=o??"delegate",m="Permission mode: plan \u2192 will switch to bypassPermissions on approval";return h==="delegate"?{label:"plan-approval",userMessage:d,wakeMessage:["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${t.name} | ID: ${t.id}`,n,m,"","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${t.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",r,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Review privately \u2501\u2501\u2501","You are the delegated decision-maker. Review the plan yourself before involving the user.","Do NOT post any user-facing approval summary unless you decide escalation is required.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: call agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true) and do NOT show the user an approval prompt.`,`If escalating: call agent_request_plan_approval(session='${t.id}', summary='...') exactly once so the plugin posts the single canonical Approve / Revise / Reject prompt.`,"That summary must include changed files/components, risk level and why, scope match/expansion, and any concerns or assumptions.","After the canonical prompt exists, WAIT for the user's button click or explicit response and do NOT send a second plain-text recap.",`To request changes without user escalation: call agent_respond(session='${t.id}', message='<your feedback>') and do NOT set approve=true. The agent will revise the plan.`].join(`
|
|
113
|
+
`)}:h==="ask"?{label:"plan-approval",userMessage:d,wakeMessage:["[USER APPROVAL REQUESTED] Coding agent session has finished its plan. The user has been notified via Telegram and must approve directly.",`Name: ${t.name} | ID: ${t.id}`,n,m,"","DO NOT approve this plan yourself. Wait for the user's explicit approval or rejection.","Once the user responds, forward their decision:",` To approve: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,` To request changes: agent_respond(session='${t.id}', message='<user feedback>')`,"","Preview (truncated):",r].join(`
|
|
114
|
+
`),buttons:i}:{label:"plan-approval",userMessage:d,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`].join(`
|
|
115
|
+
`)}}let c=t.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:d,wakeMessage:[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 forward the agent's EXACT question to the user. Do NOT add your own analysis, commentary, or interpretation. Do NOT "nudge" or "poke" the session.]`,"",`${c} is waiting for a genuine user reply.`,`Name: ${t.name} | ID: ${t.id}`,n,"","Last output:",r,"",`Use agent_respond(session='${t.id}', message='...') to send a reply, or agent_output(session='${t.id}', full: true) to see full context before deciding.`].join(`
|
|
116
|
+
`),buttons:s}}ke();var zi=class{constructor(t,r,n,o){this.buildRoutingProxy=t;this.dispatchNotification=r;this.updatePersistedSession=n;this.getWorktreeDecisionButtons=o}remindStaleDecisions(t,r=Date.now()){for(let i of t){if(!i.pendingWorktreeDecisionSince)continue;let s=i.worktreeState==="pending_decision"||i.lifecycle==="awaiting_worktree_decision",a=i.worktreeState==null&&i.lifecycle==null&&!i.worktreeMerged&&!i.worktreePrUrl;if(!s&&!a)continue;if(i.worktreeDecisionSnoozedUntil){let h=new Date(i.worktreeDecisionSnoozedUntil).getTime();if(Number.isFinite(h)&&h>r)continue}let d=r-new Date(i.pendingWorktreeDecisionSince).getTime();if(!Number.isFinite(d)||d<108e5||i.lastWorktreeReminderAt&&r-new Date(i.lastWorktreeReminderAt).getTime()<108e5)continue;let c=Math.floor(d/(3600*1e3));try{this.sendReminderNotification(i,c)}catch(h){console.warn(`[SessionReminderService] Failed to send stale-decision reminder for session ${i.name}: ${h instanceof Error?h.message:String(h)}`)}for(let h of ze(i))this.updatePersistedSession(h,{lastWorktreeReminderAt:new Date(r).toISOString()})}}sendReminderNotification(t,r){let n=this.buildRoutingProxy({id:t.sessionId??t.name??T(t)??t.harnessSessionId,sessionId:t.sessionId,harnessSessionId:t.harnessSessionId,backendRef:t.backendRef,route:t.route});if(t.worktreeStrategy==="delegate"){this.dispatchNotification(n,{label:`worktree-stale-reminder-${t.name}`,wakeMessage:md(t,r),notifyUser:"never"});return}let o=[`\u23F0 Reminder: branch \`${t.worktreeBranch??"unknown"}\` is still waiting for a merge decision.`,`Session: ${t.name} | Pending: ${r}h`,"",`agent_merge(session="${t.name}") or agent_pr(session="${t.name}") or agent_worktree_cleanup() to resolve.`].join(`
|
|
117
|
+
`);this.dispatchNotification(n,{label:`worktree-stale-reminder-${t.name}`,userMessage:o,notifyUser:"always",buttons:this.getWorktreeDecisionButtons(ee(t)??t.harnessSessionId)})}};Qe();ke();var Qi=class{constructor(t){this.deps=t}handleTurnEnd(t,r){if(t.status!=="running"){console.info(`[SessionManager] Suppressing turn-end wake for session ${t.id} (status=${t.status}) \u2014 terminal notification owns the completion path.`);return}if(r||t.pendingPlanApproval){this.emitWaitingForInput(t);return}if(t.worktreeStrategy==="ask"||t.worktreeStrategy==="delegate"){console.info(`[SessionManager] Suppressing turn-complete wake for session ${t.id} (worktreeStrategy=${t.worktreeStrategy}) \u2014 worktree notification will follow.`);return}this.deps.shouldEmitTurnCompleteWake(t)&&this.emitTurnComplete(t)}async handleSessionTerminal(t){this.deps.persistSession(t),this.deps.clearWaitingTimestamp(t.id);let r={notificationSent:!1,worktreeRemoved:!1};t.worktreePath&&t.originalWorkdir&&(r=await this.deps.handleWorktreeStrategy(t));let n=!1;if(t.worktreePath&&t.originalWorkdir&&t.status==="failed"&&t.costUsd===0&&t.duration<3e4){let a=this.deps.resolveWorktreeRepoDir(t.originalWorkdir,t.worktreePath),d=t.worktreeBranch,c=ot(t);console.info(`[SessionManager] Early startup failure for "${t.name}" \u2014 auto-cleaning worktree (cost=$${t.costUsd.toFixed(2)}, duration=${t.duration}ms)`);let h=!1;if(a&&!c&&(h=ht(a,t.worktreePath)),a&&d&&!c&&h&&bt(a,d),h){for(let m of ze(t))this.deps.updatePersistedSession(m,{worktreePath:void 0,worktreeBranch:void 0});n=!0}}let o=t.worktreeStrategy&&t.worktreeStrategy!=="off"&&t.worktreeStrategy!=="manual";if(!n&&t.worktreePath&&t.originalWorkdir){let a=this.deps.resolveWorktreeRepoDir(t.originalWorkdir,t.worktreePath),d=ot(t);r.worktreeRemoved?console.info(`[SessionManager] Worktree already removed for "${t.name}" during strategy handling.`):o?console.info(`[SessionManager] Keeping worktree alive for "${t.name}" (strategy=${t.worktreeStrategy}) \u2014 will be cleaned up on explicit resolution.`):a&&!d&&ht(a,t.worktreePath)}if(t.killReason==="done"){if(r.notificationSent||this.deps.hasTurnCompleteWakeMarker(t.id)||!this.deps.shouldEmitTerminalWake(t))return;this.emitCompleted(t);return}if(t.status==="completed"){if(!this.deps.shouldEmitTerminalWake(t))return;this.emitCompleted(t);return}if(t.status==="failed"){if(!this.deps.shouldEmitTerminalWake(t))return;let a=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.deps.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`;this.emitFailed(t,hr(a,200),n);return}let i=`$${(t.costUsd??0).toFixed(2)}`,s=t.duration;if(t.killReason==="idle-timeout"){let a=t.pendingPlanApproval?this.deps.resolvePlanApprovalMode(t):void 0;if(t.pendingPlanApproval){if(a==="delegate"){this.deps.dispatchSessionNotification(t,{label:"plan-approval-timeout",wakeMessage:["[DELEGATED PLAN APPROVAL REMINDER] Plan review is still pending after the session hit idle timeout.",`Name: ${t.name} | ID: ${t.id}`,this.deps.originThreadLine(t),"The agent already produced a plan and is waiting for a delegated decision.","Review privately first. Approve directly with agent_respond(..., approve=true) if the plan is clearly within scope and low risk.","Escalate only if needed via agent_request_plan_approval(summary='...').","If a canonical approval prompt was already posted for this plan version, do not restate it in plain text."].join(`
|
|
118
|
+
`),notifyUser:"never"}),this.deps.clearRetryTimersForSession(t.id);return}this.deps.dispatchSessionNotification(t,{label:"plan-approval-timeout",userMessage:[`\u{1F4CB} [${t.name}] Plan still awaiting approval after idle timeout | ${i} | ${St(s)}`,"","The agent already produced a plan and is waiting for your decision.","Approve resumes the session and starts implementation.","Revise resumes it in plan mode so it can update the plan first.","Reject keeps the session stopped."].join(`
|
|
119
|
+
`),notifyUser:"always",buttons:a==="ask"?this.deps.getPlanApprovalButtons(t.id,t):void 0}),this.deps.clearRetryTimersForSession(t.id);return}this.deps.dispatchSessionNotification(t,{label:"suspended",userMessage:`\u{1F4A4} [${t.name}] Suspended after idle timeout | ${i} | ${St(s)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(t.id,t)}),this.deps.clearRetryTimersForSession(t.id);return}this.deps.notifySession(t,`\u26D4 [${t.name}] ${jn(t.killReason)} | ${i} | ${St(s)}`),this.deps.clearRetryTimersForSession(t.id)}emitWaitingForInput(t){if(!this.deps.debounceWaitingEvent(t.id))return;let r=t.pendingPlanApproval?this.deps.resolvePlanApprovalMode(t):void 0,n=t.planDecisionVersion,o=!t.pendingPlanApproval&&t.pendingInputState?.promptText?t.pendingInputState.promptText:this.deps.getOutputPreview(t,t.pendingPlanApproval&&r!=="delegate"?Number.POSITIVE_INFINITY:void 0),i=t.pendingPlanApproval&&r==="ask"?this.deps.getPlanApprovalButtons(t.id,t):!t.pendingPlanApproval&&t.pendingInputState?.options.length?this.deps.getQuestionButtons(t.id,t.pendingInputState.options.map(a=>({label:a}))):void 0,s=hd({session:t,preview:o,originThreadLine:this.deps.originThreadLine(t),planApprovalMode:r,planApprovalButtons:i,questionButtons:t.pendingPlanApproval?void 0:i});if(s.label==="plan-approval"&&r==="ask"){this.deps.dispatchSessionNotification(t,{label:s.label,userMessage:s.userMessage,notifyUser:"always",buttons:s.buttons,hooks:{onNotifySucceeded:()=>{this.deps.updatePersistedSession(t.id,{canonicalPlanPromptVersion:n})}},wakeMessageOnNotifySuccess:["Plan approval buttons delivered to the user.",`Session: ${t.name} | ID: ${t.id}`,"Wait for their button callback \u2014 do NOT approve or reject this plan yourself."].join(`
|
|
120
|
+
`),wakeMessageOnNotifyFailed:s.wakeMessage});return}if(s.label==="plan-approval"){this.deps.dispatchSessionNotification(t,{label:s.label,userMessage:s.userMessage,wakeMessage:s.wakeMessage,notifyUser:"never",buttons:s.buttons});return}this.deps.dispatchSessionNotification(t,{label:s.label,userMessage:s.userMessage,notifyUser:"always",buttons:s.buttons,wakeMessageOnNotifyFailed:s.wakeMessage})}emitTurnComplete(t){console.info(`[SessionManager] turn-complete wake dispatching for session ${t.id} (turns=${t.result?.num_turns??0}, strategy=${t.worktreeStrategy??"none"})`);let r=cd({session:t,originThreadLine:this.deps.originThreadLine(t),preview:this.deps.getOutputPreview(t)});this.deps.dispatchSessionNotification(t,{label:"turn-complete",userMessage:r.userMessage,wakeMessage:r.wakeMessage,notifyUser:"always",onUserNotifyFailed:()=>{console.warn(`[SessionManager] turn-complete delivery failed for session ${t.id} \u2014 firing terminal notification as fallback`),this.deps.shouldEmitTerminalWake(t)&&this.emitCompleted(t)}})}emitCompleted(t){let r=this.deps.getOutputPreview(t),n=ud({session:t,originThreadLine:this.deps.originThreadLine(t),preview:r});this.deps.dispatchSessionNotification(t,{label:"completed",userMessage:n.userMessage,wakeMessage:n.wakeMessage,notifyUser:"always"})}emitFailed(t,r,n){let o=pd({session:t,originThreadLine:this.deps.originThreadLine(t),errorSummary:r,preview:this.deps.getOutputPreview(t),worktreeAutoCleaned:n,failedButtons:this.deps.getResumeButtons(t.id,t)});this.deps.dispatchSessionNotification(t,{label:"failed",userMessage:o.userMessage,wakeMessage:o.wakeMessage,notifyUser:"always",buttons:o.buttons})}};ke();Qe();import{existsSync as MI}from"fs";var Ji=class{constructor(t){this.deps=t}async dismissWorktree(t){let r=this.deps.getPersistedSession(t),n=this.deps.resolveActiveSession(t),o=n??r;if(!o)return`Error: Session "${t}" not found.`;let i=n?.worktreePath??r?.worktreePath,s=this.deps.resolveWorktreeRepoDir(n?.originalWorkdir??r?.workdir,i),a=n?.worktreeBranch??r?.worktreeBranch,d=n?.name??r?.name??t;if(!s)return`Error: No workdir found for session "${t}".`;let c=ot(o);!c&&i&&MI(i)&&ht(s,i,{destructive:!0}),a&&bt(s,a);for(let m of ze(n??r))this.deps.updatePersistedSession(m,{worktreeDisposition:"dismissed",worktreeDismissedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,worktreeState:"dismissed",lifecycle:"terminal",worktreePath:void 0,worktreeBranch:void 0});let h=c?`\u{1F5D1}\uFE0F [${d}] Branch \`${a??"unknown"}\` dismissed. Native backend worktree released for backend cleanup.`:`\u{1F5D1}\uFE0F [${d}] Branch \`${a??"unknown"}\` dismissed and permanently deleted.`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:ee(n??r??{id:t})??t,sessionId:r?.sessionId,harnessSessionId:n?.harnessSessionId??r?.harnessSessionId,backendRef:n?.backendRef??r?.backendRef,route:n?.route??r?.route}),{label:"worktree-dismissed",userMessage:h,notifyUser:"always"}),h}snoozeWorktreeDecision(t){let r=this.deps.getPersistedSession(t);if(!r)return`Error: Session "${t}" not found.`;let n=new Date(Date.now()+1440*60*1e3).toISOString();for(let s of ze(r))this.deps.updatePersistedSession(s,{worktreeDecisionSnoozedUntil:n,lastWorktreeReminderAt:new Date().toISOString()});let i=`\u23ED\uFE0F Reminder snoozed 24h for \`${r.worktreeBranch??"unknown"}\` (session: ${r.name})`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:ee(r)??T(r)??r.harnessSessionId,sessionId:r.sessionId,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route}),{label:"worktree-snoozed",userMessage:i,notifyUser:"always"}),i}};var tf=new Set(["starting","running"]),Yi=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(t=>tf.has(t.status)).length}uniqueName(t){let r=new Set([...this.sessions.values()].filter(o=>tf.has(o.status)).map(o=>o.name));if(!r.has(t))return t;let n=2;for(;r.has(`${t}-${n}`);)n+=1;return`${t}-${n}`}add(t){this.sessions.set(t.id,t)}remove(t){this.sessions.delete(t)}get(t){return this.sessions.get(t)}list(){return[...this.sessions.values()]}};var Xi=class{constructor(t){this.deps=t}initializeSession(t,r,n,o={}){if(this.deps.hydrateSpawnedSession(t,r,n),t.on("statusChange",(i,s)=>{s==="running"&&t.harnessSessionId?this.deps.markRunning(t):(s==="completed"||s==="failed"||s==="killed")&&this.deps.handleTerminal(t).catch(a=>{console.error(`[SessionRuntimeBootstrap] handleTerminal threw for session ${t.id}:`,a)})}),t.on("turnEnd",(i,s)=>{this.deps.handleTurnEnd(t,s)}),t.start(),o.notifyLaunch!==!1){let i=this.deps.formatLaunchWorkdirLabel(t),s=`\u{1F680} [${t.name}] Launched | ${i} | ${t.model??"default"}`;this.deps.notifySession(t,s,"launch")}return t}};var Zi=class{buildNoChangeNotification(t){let{session:r,nativeBackendWorktree:n,cleanupSucceeded:o,worktreePath:i,preview:s,originThreadLine:a}=t,d=o?n?"native backend worktree released for backend cleanup":"worktree cleaned up":`cleanup failed; worktree still exists at ${i}`;return{label:o?"worktree-no-changes":"worktree-no-changes-cleanup-failed",userMessage:o?n?`\u2139\uFE0F [${r.name}] Session completed with no changes \u2014 native backend worktree released for backend cleanup`:`\u2139\uFE0F [${r.name}] Session completed with no changes \u2014 worktree cleaned up`:`\u26A0\uFE0F [${r.name}] Session completed with no changes, but worktree cleanup failed. Worktree still exists at ${i}`,wakeMessage:fd({sessionName:r.name,sessionId:r.id,cleanupSummary:d,preview:s,originThreadLine:a,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,approvalExecutionState:r.approvalExecutionState}),notifyUser:"always"}}buildAskNotification(t){let{session:r,branchName:n,baseBranch:o,diffSummary:i,buttons:s}=t,a=gd(i),d=i.commitMessages.slice(0,5).map(m=>`\u2022 ${m.hash} ${m.message} (${m.author})`),c=i.commits>5?`...and ${i.commits-5} more`:"",h=r.worktreePrTargetRepo?`Branch: \`${n}\` \u2192 \`${o}\` | PR target: ${r.worktreePrTargetRepo}`:`Branch: \`${n}\` \u2192 \`${o}\``;return{label:"worktree-merge-ask",userMessage:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",h,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"",...a.length>0?["Summary:",...a.map(m=>`- ${m}`),""]:[],"Recent commits:",...d,...c?[c]:[],"",`\u26A0\uFE0F Discard will permanently delete branch \`${n}\` and all local changes. This cannot be undone.`].join(`
|
|
121
|
+
`),notifyUser:"always",buttons:s,wakeMessageOnNotifySuccess:["Worktree decision buttons delivered to the user.",`Session: ${r.name} | ID: ${r.id}`,h,"Wait for their button callback \u2014 do NOT act on this worktree yourself."].join(`
|
|
122
|
+
`),wakeMessageOnNotifyFailed:[`\u{1F500} Worktree decision required for session \`${r.name}\``,"",h,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
|
|
123
|
+
`)}}buildDelegateNotification(t){let{session:r,branchName:n,baseBranch:o,diffSummary:i}=t,s=i.commitMessages.slice(0,5).map(c=>`\u2022 ${c.hash} ${c.message} (${c.author})`),a=i.commits>5?`...and ${i.commits-5} more`:void 0,d=r.prompt?r.prompt.slice(0,500):"(no prompt)";return{label:"worktree-delegate",wakeMessage:ld({sessionName:r.name,sessionId:r.id,branchName:n,baseBranch:o,promptSnippet:d,commitLines:s,moreNote:a,diffSummary:i}),notifyUser:"never"}}};Qe();var rf=new Set(["completed","failed","killed"]),CI=new Set(["starting","running"]),EI=5e3,es=class{registry;sessions;maxSessions;maxPersistedSessions;lastDailyMaintenanceAt=0;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueues=new Map;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;interactions;notifications;worktrees;questions;reminders;lifecycle;restore;stateSync;references;worktreeStrategy;worktreeDecisions;runtimeBootstrap;worktreeMessages;constructor(t=20,r=50){this.maxSessions=t,this.maxPersistedSessions=r,this.registry=new Yi,this.sessions=this.registry.sessions,this.store=new Di,this.metrics=new Li,this.wakeDispatcher=new Ki,this.interactions=new ji(this.store.actionTokenStore,Pt),this.references=new Ti(this.sessions,this.store),this.stateSync=new Ai({store:this.store,sessions:this.sessions,resolveSession:n=>this.references.resolveActive(n)}),this.notifications=new qi(this.wakeDispatcher,(n,o)=>this.stateSync.applySessionPatch(n,o)),this.worktrees=new Vi,this.restore=new Ri(n=>this.store.getPersistedSession(n)),this.worktreeMessages=new Zi,this.worktreeStrategy=new Ci({shouldRunWorktreeStrategy:n=>this.shouldRunWorktreeStrategy(n),isAlreadyMerged:n=>this.isAlreadyMerged(n),resolveWorktreeRepoDir:(n,o)=>this.resolveWorktreeRepoDir(n,o),getWorktreeCompletionState:(n,o,i,s)=>this.getWorktreeCompletionState(n,o,i,s),updatePersistedSession:(n,o)=>this.updatePersistedSession(n,o),dispatchSessionNotification:(n,o)=>this.dispatchSessionNotification(n,o),getOutputPreview:(n,o)=>this.getOutputPreview(n,o),originThreadLine:n=>this.originThreadLine(n),getWorktreeDecisionButtons:n=>this.getWorktreeDecisionButtons(n),makeOpenPrButton:n=>this.makeActionButton(n,"worktree-create-pr","Open PR"),worktreeMessages:this.worktreeMessages,enqueueMerge:(n,o,i)=>this.enqueueMerge(n,o,i),spawnConflictResolver:async(n,o,i)=>{this.spawn({prompt:i,workdir:o,name:`${n.name}-conflict-resolver`,harness:De(),permissionMode:"bypassPermissions",multiTurn:!0,route:n.route,originChannel:n.originChannel,originThreadId:n.originThreadId,originAgentId:n.originAgentId,originSessionKey:n.originSessionKey})},runAutoPr:async(n,o)=>{let{makeAgentPrTool:i}=await Promise.resolve().then(()=>(Pi(),Mm));return{success:(await i().execute("auto-pr",{session:n.id,base_branch:o}))?.meta?.success===!0}}}),this.questions=new Hi(this.pendingAskUserQuestions,(n,o)=>this.dispatchSessionNotification(n,o),n=>{this.lastWaitingEventTimestamps.delete(n)},(n,o)=>this.interactions.getQuestionButtons(n,o)),this.reminders=new zi(n=>this.buildRoutingProxy(n),(n,o)=>this.notifications.dispatch(n,o),(n,o)=>this.updatePersistedSession(n,o),n=>this.getWorktreeDecisionButtons(n)),this.lifecycle=new Qi({persistSession:n=>this.persistSession(n),clearWaitingTimestamp:n=>{this.lastWaitingEventTimestamps.delete(n)},handleWorktreeStrategy:n=>this.handleWorktreeStrategy(n),resolveWorktreeRepoDir:(n,o)=>this.resolveWorktreeRepoDir(n,o),updatePersistedSession:(n,o)=>this.updatePersistedSession(n,o),dispatchSessionNotification:(n,o)=>this.dispatchSessionNotification(n,o),notifySession:(n,o,i)=>this.notifySession(n,o,i),clearRetryTimersForSession:n=>this.wakeDispatcher.clearRetryTimersForSession(n),hasTurnCompleteWakeMarker:n=>this.lastTurnCompleteMarkers.has(n),shouldEmitTurnCompleteWake:n=>this.shouldEmitTurnCompleteWake(n),shouldEmitTerminalWake:n=>this.shouldEmitTerminalWake(n),resolvePlanApprovalMode:n=>this.resolvePlanApprovalMode(n),getPlanApprovalButtons:(n,o)=>this.interactions.getPlanApprovalButtons(n,o),getResumeButtons:(n,o)=>this.interactions.getResumeButtons(n,o),getQuestionButtons:(n,o)=>this.interactions.getQuestionButtons(n,o),extractLastOutputLine:n=>this.extractLastOutputLine(n),getOutputPreview:(n,o)=>this.getOutputPreview(n,o),originThreadLine:n=>this.originThreadLine(n),debounceWaitingEvent:n=>this.debounceWaitingEvent(n),isAlreadyMerged:n=>this.isAlreadyMerged(n)}),this.worktreeDecisions=new Ji({getPersistedSession:n=>this.store.getPersistedSession(n),resolveActiveSession:n=>this.references.resolveActive(n),resolveWorktreeRepoDir:(n,o)=>this.resolveWorktreeRepoDir(n,o),updatePersistedSession:(n,o)=>this.updatePersistedSession(n,o),dispatchNotification:(n,o)=>this.notifications.dispatch(n,o),buildRoutingProxy:n=>this.buildRoutingProxy(n)}),this.runtimeBootstrap=new Xi({hydrateSpawnedSession:(n,o,i)=>{this.restore.hydrateSpawnedSession(n,o,i)},markRunning:n=>this.store.markRunning(n),handleTerminal:async n=>this.onSessionTerminal(n),handleTurnEnd:(n,o)=>this.onTurnEnd(n,o),formatLaunchWorkdirLabel:n=>this.formatLaunchWorkdirLabel(n),notifySession:(n,o,i)=>this.notifySession(n,o,i)})}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(t){return this.registry.uniqueName(t)}spawn(t,r={}){if(this.registry.activeSessionCount()>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);if(t.sessionIdOverride){let S=this.registry.get(t.sessionIdOverride);if(S?.status==="starting"||S?.status==="running")throw new Error(`Cannot reuse session ID ${t.sessionIdOverride}: that session is still ${S.status}.`);S&&this.registry.remove(S.id),this.lastWaitingEventTimestamps.delete(t.sessionIdOverride),this.lastTurnCompleteMarkers.delete(t.sessionIdOverride),this.lastTerminalWakeMarkers.delete(t.sessionIdOverride)}let o=t.name||fm(t.prompt),i=this.uniqueName(o);if(i!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${i}" (active session with same name exists)`),!t.route?.provider||!t.route.target)throw new Error(`Cannot launch session "${i}": missing explicit route metadata.`);let s=this.restore.prepareSpawn(t,i),a=t.harness??"claude-code",d=this,c,h=a==="claude-code"&&!t.canUseTool?async(S,y)=>{if(!c)throw new Error("canUseTool called before session ID was set");return d.handleAskUserQuestion(c,y)}:t.canUseTool,m=new gi({...t,workdir:s.actualWorkdir,systemPrompt:s.effectiveSystemPrompt,canUseTool:h},i);return c=m.id,this.registry.add(m),this.metrics.incrementLaunched(),this.runtimeBootstrap.initializeSession(m,s,t,r)}async spawnAndAwaitRunning(t,r={}){let n=this.spawn(t,r);return await this.waitForRunningSession(n),n}async waitForRunningSession(t){if(t.status==="running")return;if(rf.has(t.status))throw new Error(this.describeLaunchFailure(t));let r=t.on?.bind(t),n=t.off?.bind(t)??t.removeListener?.bind(t);if(!r||!n)throw new Error(`Session ${t.name} [${t.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(d,c)=>{if(c==="running"){a(),o();return}rf.has(c)&&(a(),i(new Error(this.describeLaunchFailure(t))))},a=()=>{n("statusChange",s)};r("statusChange",s)})}describeLaunchFailure(t){let r=t.killReason?` (reason: ${t.killReason})`:"",n=t.error||t.result?.result||`status=${t.status}${r}`;return`Session ${t.name} [${t.id}] failed to start: ${n}`}formatLaunchResult(t,r){return Uo({prompt:t.prompt,workdir:t.workdir,harness:t.harness,permissionMode:t.permissionMode??E.permissionMode,planApproval:t.planApproval,resumeSessionId:t.resumeSessionId,forkSession:t.forkSession,forceNewSession:t.forceNewSession,clearedPersistedCodexResume:t.clearedPersistedCodexResume},r)}shouldRunWorktreeStrategy(t){let r=t.lifecycle;return!(r==="starting"||r==="awaiting_plan_decision"||r==="awaiting_user_input"||t.pendingPlanApproval)}makeActionButton(t,r,n,o={}){return this.interactions.makeActionButton(t,r,n,o)}consumeActionToken(t){return this.interactions.consumeActionToken(t)}getWorktreeDecisionButtons(t){let r=this.resolve(t)??this.getPersistedSession(t);if(!(!r||r.worktreeStrategy==="delegate"))return this.interactions.getWorktreeDecisionButtons(t,r)}getWorktreeCompletionState(t,r,n,o){return this.worktrees.getCompletionState(t,r,n,o)}notifyWorktreeOutcome(t,r){this.notifications.notifyWorktreeOutcome(t,r)}requestPlanApprovalFromUser(t,r){let n=r.trim();if(!n)return"Error: summary must not be empty.";let o=this.resolve(t),i=o?void 0:this.getPersistedSession(t),s=o??i;if(!s)return`Error: Session "${t}" not found.`;if(!s.pendingPlanApproval)return`Error: Session "${t}" is not awaiting plan approval.`;let a=ee(o??i??{id:t})??t;if(this.resolvePlanApprovalMode(s)!=="delegate")return`Error: Session "${t}" already uses direct user plan approval. Do not send a duplicate approval prompt.`;if(s.canonicalPlanPromptVersion===s.planDecisionVersion)return[`Canonical plan approval prompt already exists for session ${s.name} [${a}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ");if(s.deliveryState==="notifying")return[`A plan approval prompt is already being delivered for session ${s.name} [${a}].`,"Wait for delivery to finish before retrying."].join(" ");let d=this.interactions.getPlanApprovalButtons(a,s),c=[`\u{1F4CB} [${s.name}] Plan needs your decision:`,"",n,"","Choose Approve, Revise, or Reject below."].join(`
|
|
124
|
+
`);return this.notifications.dispatch(this.buildRoutingProxy({id:a,sessionId:i?.sessionId,harnessSessionId:o?.harnessSessionId??i?.harnessSessionId,backendRef:o?.backendRef??i?.backendRef,route:o?.route??i?.route}),{label:"plan-approval",userMessage:c,notifyUser:"always",buttons:d,hooks:{onNotifySucceeded:()=>{this.updatePersistedSession(a,{canonicalPlanPromptVersion:s.planDecisionVersion})}}}),[`Canonical plan approval prompt sent for session ${s.name} [${a}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ")}buildRoutingProxy(t){return{id:ee(t)??T(t)??t.harnessSessionId??"unknown-session",harnessSessionId:t.harnessSessionId,backendRef:t.backendRef?{...t.backendRef}:void 0,route:t.route}}resolveWorktreeRepoDir(t,r){return t&&(!r||!vi(t,r))||!r?t:si(r)??t}formatLaunchWorkdirLabel(t){if(!t.worktreePath)return t.workdir;let r=this.resolveWorktreeRepoDir(t.originalWorkdir,t.worktreePath);return!r||r===t.worktreePath?t.worktreePath:`${t.worktreePath} (worktree of ${r})`}async dismissWorktree(t){return this.worktreeDecisions.dismissWorktree(t)}snoozeWorktreeDecision(t){return this.worktreeDecisions.snoozeWorktreeDecision(t)}async handleWorktreeStrategy(t){return this.worktreeStrategy.handleWorktreeStrategy(t)}async onSessionTerminal(t){return this.lifecycle.handleSessionTerminal(t)}getStoppedStatusLabel(t){return jn(t)}persistSession(t){this.store.hasRecordedSession(t.id)||this.metrics.recordSession(t),this.store.persistTerminal(t)}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(t){this.metrics.recordSession(t)}notifySession(t,r,n="notification"){this.dispatchSessionNotification(t,{label:n,userMessage:r,notifyUser:"always"})}dispatchSessionNotification(t,r){this.notifications.dispatch(t,r)}debounceWaitingEvent(t){let r=Date.now(),n=this.lastWaitingEventTimestamps.get(t);return n&&r-n<EI?!1:(this.lastWaitingEventTimestamps.set(t,r),!0)}originThreadLine(t){return t.originThreadId!=null?`Session origin thread: ${t.originThreadId}`:""}extractLastOutputLine(t){return t.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(t,r=1e3){let n=!Number.isFinite(r),o=typeof t.getOutput=="function"?t.getOutput():[],i=n?o.join(`
|
|
125
|
+
`):this.selectCompletionPreviewSource(t);return n?i:i.length>r?this.shouldPreferTailPreview(t)?hm(i,r):Sm(i,r):i}selectCompletionPreviewSource(t){let r=typeof t.getOutput=="function"?t.getOutput():[],n=r.join(`
|
|
126
|
+
`).trim();return n?this.shouldPreferTailPreview(t)?this.extractLastSubstantiveBlock(n)??n:r.slice(-20).join(`
|
|
127
|
+
`):""}shouldPreferTailPreview(t){if(t.status==="completed"||t.killReason==="done")return!0;let r=t;return r.approvalState==="approved"||r.planModeApproved===!0||(r.planDecisionVersion??0)>0}extractLastSubstantiveBlock(t){let n=t.split(/\n\s*\n+/).map(o=>o.trim()).filter(o=>/[A-Za-z0-9]/.test(o)).at(-1);if(n)return n.length>=120||n.includes(`
|
|
128
|
+
`)?n:void 0}triggerAgentEvent(t){this.lifecycle.emitCompleted(t)}triggerFailedEvent(t,r,n=!1){this.lifecycle.emitFailed(t,r,n)}triggerWaitingForInputEvent(t){this.lifecycle.emitWaitingForInput(t)}resolvePlanApprovalMode(t){return t.planApproval??E.planApproval??"delegate"}onTurnEnd(t,r){this.lifecycle.handleTurnEnd(t,r)}shouldEmitTurnCompleteWake(t){let r=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===r?(console.info(`[SessionManager] shouldEmitTurnCompleteWake: debounced for session ${t.id} (marker unchanged: ${r})`),!1):(this.lastTurnCompleteMarkers.set(t.id,r),!0)}shouldEmitTerminalWake(t){let r=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===r?!1:(this.lastTerminalWakeMarkers.set(t.id,r),!0)}triggerTurnCompleteEventWithSignal(t){this.lifecycle.emitTurnComplete(t)}resolve(t){return this.references.resolveActive(t)}get(t){return this.registry.get(t)}list(t){let r=this.registry.list();return t&&t!=="all"&&(r=r.filter(n=>n.status===t)),r.sort((n,o)=>o.startedAt-n.startedAt)}kill(t,r){let n=this.registry.get(t);return n?(n.kill(r??"user"),!0):!1}killAll(t="user"){for(let r of this.sessions.values())CI.has(r.status)&&this.kill(r.id,t)}resolveBackendConversationId(t){return this.references.resolveBackendConversationId(t)}resolveHarnessSessionId(t){return this.resolveBackendConversationId(t)}getPersistedSession(t){return this.references.getPersistedSession(t)}isAlreadyMerged(t){return t?this.store.getPersistedSession(t)?.worktreeMerged===!0:!1}async enqueueMerge(t,r,n){let o=this.mergeQueues.get(t);o!==void 0&&n&&n();let i=(o??Promise.resolve()).catch(()=>{}).then(()=>r()),s=i.catch(()=>{});return this.mergeQueues.set(t,s),s.finally(()=>{this.mergeQueues.get(t)===s&&this.mergeQueues.delete(t)}),i}updatePersistedSession(t,r){return this.stateSync.applySessionPatch(t,r)}listPersistedSessions(){return this.store.listPersistedSessions()}remindStaleDecisions(){this.reminders.remindStaleDecisions(this.store.listPersistedSessions())}sendReminderNotification(t,r){let n=Date.now(),o=t.pendingWorktreeDecisionSince?new Date(t.pendingWorktreeDecisionSince).getTime():n-14400*1e3;this.reminders.remindStaleDecisions([{...t,pendingWorktreeDecisionSince:new Date(o).toISOString(),lastWorktreeReminderAt:void 0}],n)}async handleAskUserQuestion(t,r){let n=this.sessions.get(t);if(!n)throw new Error(`Session "${t}" not found for AskUserQuestion intercept`);return this.questions.handleAskUserQuestion(n,r)}resolveAskUserQuestion(t,r){this.questions.resolveAskUserQuestion(t,r)}async resolvePendingInputOption(t,r){let n=this.sessions.get(t);return n&&await n.submitPendingInputOption(r)?(this.lastWaitingEventTimestamps.delete(t),!0):(this.questions.resolveAskUserQuestion(t,r),!0)}cleanup(){let t=Date.now();this.remindStaleDecisions(),this.runDailyWorktreeMaintenance(t);let r=(E.sessionGcAgeMinutes??1440)*6e4;for(let[n,o]of this.sessions)this.store.shouldGcActiveSession(o,t,r)&&(this.persistSession(o),this.registry.remove(n),this.lastWaitingEventTimestamps.delete(n),this.lastTurnCompleteMarkers.delete(n),this.lastTerminalWakeMarkers.delete(n));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}runDailyWorktreeMaintenance(t){if(!(t-this.lastDailyMaintenanceAt<864e5)){this.lastDailyMaintenanceAt=t;for(let o of this.store.listPersistedSessions())if(this.worktrees.isResolvedWorktreeEligibleForCleanup(o,t,6048e5))try{let i=this.resolveWorktreeRepoDir(o.workdir,o.worktreePath);if(!i)continue;let s=ot(o)?!1:ht(i,o.worktreePath);if(!ot(o)&&!s)continue;for(let a of ze(o))this.updatePersistedSession(a,{worktreePath:void 0,worktreeState:"none"})}catch(i){console.warn(`[SessionManager] Failed daily cleanup for worktree ${o.worktreePath}: ${i instanceof Error?i.message:String(i)}`)}}}dispose(){this.questions.dispose(),this.notifications.dispose()}};he();var nf;function ts(e){if(e&&typeof e=="object"){nf=e;return}nf=void 0}Le();function FI(e){let t=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"168",10)||168,r=t*60*60*1e3,n=Date.now()-r,o=new Set(e.listPersistedSessions().map(d=>d.worktreePath).filter(d=>typeof d=="string"&&d.length>0)),i=new Set,s=process.env.OPENCLAW_WORKTREE_DIR??E.worktreeDir;if(s)i.add(s);else for(let d of e.listPersistedSessions())if(d.workdir)try{let c=NI("git",["rev-parse","--show-toplevel"],{cwd:d.workdir,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();c&&i.add(of(c,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let d of i)try{let c=$I(d);for(let h of c){if(!h.startsWith("openclaw-worktree-"))continue;let m=of(d,h);try{let S=OI(m);if(!S.isDirectory()||S.mtimeMs>n||o.has(m))continue;_I(m,{recursive:!0,force:!0}),a++}catch(S){console.warn(`[index] Failed to clean up orphaned worktree ${m}: ${S instanceof Error?S.message:String(S)}`)}}}catch{}a>0&&console.info(`[index] Cleaned up ${a} orphaned worktree(s) at startup (age > ${t}h)`)}function gK(e){let t=null,r=null;ts(e.runtime),e.registerTool(n=>Gl(n),{optional:!1}),e.registerTool(n=>Im(n),{optional:!1}),e.registerTool(n=>xm(n),{optional:!1}),e.registerTool(n=>wi(n),{optional:!1}),e.registerTool(n=>vm(n),{optional:!1}),e.registerTool(n=>Rm(n),{optional:!1}),e.registerTool(n=>Am(n),{optional:!1}),e.registerTool(n=>xi(n),{optional:!1}),e.registerTool(n=>Bn(n),{optional:!1}),e.registerTool(n=>Cm(n),{optional:!1}),e.registerTool(n=>Em(n),{optional:!1}),e.registerInteractiveHandler(sd("telegram")),e.registerInteractiveHandler(sd("discord")),$m(e),Om(e),_m(e),Nm(e),Fm(e),Dm(e),e.registerService({id:"openclaw-code-agent",start:n=>{let o=e.pluginConfig??e.getConfig?.()??{};pl(o),ts(e.runtime),t=new es(E.maxSessions,E.maxPersistedSessions),Wa(t),FI(t),r=setInterval(()=>t.cleanup(),300*1e3),r.unref?.()},stop:()=>{t&&t.killAll("shutdown"),r&&clearInterval(r),t&&t.dispose(),r=null,t=null,ts(void 0),Wa(null)}})}export{gK as register};
|