openclaw-code-agent 2.3.0 β†’ 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -179,6 +179,7 @@ The plugin sends targeted notifications to the originating Telegram thread:
179
179
  | ❓ | Waiting for input | Session is waiting for user input |
180
180
  | πŸ“‹ | Plan ready | Plan approval requested β€” reply "go" to approve |
181
181
  | ⏸️ | Paused after turn | Turn completed, session paused (auto-resumable) |
182
+ | β†ͺ️ | Redirected | Active work was intentionally interrupted and redirected in-place |
182
183
  | ▢️ | Auto-resumed | Session resumed on the next `agent_respond` |
183
184
  | βœ… | Completed | Completion summary with cost and duration |
184
185
  | ❌ | Failed | Error notification with hint |
package/dist/index.js CHANGED
@@ -1,66 +1,66 @@
1
- var xa=Object.defineProperty;var sr=(e,t)=>{for(var n in t)xa(e,n,{get:t[n],enumerable:!0})};import{existsSync as Zm}from"fs";var J={};sr(J,{HasPropertyKey:()=>dn,IsArray:()=>K,IsAsyncIterator:()=>ir,IsBigInt:()=>Dt,IsBoolean:()=>Ke,IsDate:()=>it,IsFunction:()=>ar,IsIterator:()=>ur,IsNull:()=>dr,IsNumber:()=>ue,IsObject:()=>A,IsRegExp:()=>jt,IsString:()=>C,IsSymbol:()=>cr,IsUint8Array:()=>De,IsUndefined:()=>D});function dn(e,t){return t in e}function ir(e){return A(e)&&!K(e)&&!De(e)&&Symbol.asyncIterator in e}function K(e){return Array.isArray(e)}function Dt(e){return typeof e=="bigint"}function Ke(e){return typeof e=="boolean"}function it(e){return e instanceof globalThis.Date}function ar(e){return typeof e=="function"}function ur(e){return A(e)&&!K(e)&&!De(e)&&Symbol.iterator in e}function dr(e){return e===null}function ue(e){return typeof e=="number"}function A(e){return typeof e=="object"&&e!==null}function jt(e){return e instanceof globalThis.RegExp}function C(e){return typeof e=="string"}function cr(e){return typeof e=="symbol"}function De(e){return e instanceof globalThis.Uint8Array}function D(e){return e===void 0}function Sa(e){return e.map(t=>cn(t))}function Ta(e){return new Date(e.getTime())}function ba(e){return new Uint8Array(e)}function wa(e){return new RegExp(e.source,e.flags)}function Aa(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=cn(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=cn(e[n]);return t}function cn(e){return K(e)?Sa(e):it(e)?Ta(e):De(e)?ba(e):jt(e)?wa(e):A(e)?Aa(e):e}function F(e){return cn(e)}function yt(e,t){return t===void 0?F(e):F({...t,...e})}function no(e){return e!==null&&typeof e=="object"}function ro(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function oo(e){return e===void 0}function so(e){return typeof e=="number"}var mn;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(s,c){return e.ExactOptionalPropertyTypes?c in s:s[c]!==void 0}e.IsExactOptionalProperty=t;function n(s){let c=no(s);return e.AllowArrayObject?c:c&&!ro(s)}e.IsObjectLike=n;function r(s){return n(s)&&!(s instanceof Date)&&!(s instanceof Uint8Array)}e.IsRecordLike=r;function o(s){return e.AllowNaN?so(s):Number.isFinite(s)}e.IsNumberLike=o;function i(s){let c=oo(s);return e.AllowNullVoid?c||s===null:c}e.IsVoidLike=i})(mn||(mn={}));function Pa(e){return globalThis.Object.freeze(e).map(t=>Gt(t))}function Ra(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Gt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Gt(e[n]);return globalThis.Object.freeze(t)}function Gt(e){return K(e)?Pa(e):it(e)?e:De(e)?e:jt(e)?e:A(e)?Ra(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(mn.InstanceMode){case"freeze":return Gt(n);case"clone":return F(n);default:return n}}var W=class extends Error{constructor(t){super(t)}};var V=Symbol.for("TypeBox.Transform"),Ae=Symbol.for("TypeBox.Readonly"),Y=Symbol.for("TypeBox.Optional"),Ie=Symbol.for("TypeBox.Hint"),m=Symbol.for("TypeBox.Kind");function xt(e){return A(e)&&e[Ae]==="Readonly"}function re(e){return A(e)&&e[Y]==="Optional"}function mr(e){return h(e,"Any")}function pr(e){return h(e,"Argument")}function Pe(e){return h(e,"Array")}function at(e){return h(e,"AsyncIterator")}function ut(e){return h(e,"BigInt")}function je(e){return h(e,"Boolean")}function Re(e){return h(e,"Computed")}function Oe(e){return h(e,"Constructor")}function Oa(e){return h(e,"Date")}function Ce(e){return h(e,"Function")}function Me(e){return h(e,"Integer")}function v(e){return h(e,"Intersect")}function dt(e){return h(e,"Iterator")}function h(e,t){return A(e)&&m in e&&e[m]===t}function pn(e){return Ke(e)||ue(e)||C(e)}function de(e){return h(e,"Literal")}function ce(e){return h(e,"MappedKey")}function $(e){return h(e,"MappedResult")}function We(e){return h(e,"Never")}function Ca(e){return h(e,"Not")}function Vt(e){return h(e,"Null")}function Ee(e){return h(e,"Number")}function j(e){return h(e,"Object")}function ct(e){return h(e,"Promise")}function mt(e){return h(e,"Record")}function L(e){return h(e,"Ref")}function lr(e){return h(e,"RegExp")}function Ge(e){return h(e,"String")}function Ht(e){return h(e,"Symbol")}function me(e){return h(e,"TemplateLiteral")}function Ma(e){return h(e,"This")}function qe(e){return A(e)&&V in e}function pe(e){return h(e,"Tuple")}function Bt(e){return h(e,"Undefined")}function y(e){return h(e,"Union")}function Ea(e){return h(e,"Uint8Array")}function ka(e){return h(e,"Unknown")}function Fa(e){return h(e,"Unsafe")}function $a(e){return h(e,"Void")}function va(e){return A(e)&&m in e&&C(e[m])}function le(e){return mr(e)||pr(e)||Pe(e)||je(e)||ut(e)||at(e)||Re(e)||Oe(e)||Oa(e)||Ce(e)||Me(e)||v(e)||dt(e)||de(e)||ce(e)||$(e)||We(e)||Ca(e)||Vt(e)||Ee(e)||j(e)||ct(e)||mt(e)||L(e)||lr(e)||Ge(e)||Ht(e)||me(e)||Ma(e)||pe(e)||Bt(e)||y(e)||Ea(e)||ka(e)||Fa(e)||$a(e)||va(e)}var a={};sr(a,{IsAny:()=>co,IsArgument:()=>mo,IsArray:()=>po,IsAsyncIterator:()=>lo,IsBigInt:()=>fo,IsBoolean:()=>go,IsComputed:()=>Io,IsConstructor:()=>ho,IsDate:()=>yo,IsFunction:()=>xo,IsImport:()=>Da,IsInteger:()=>So,IsIntersect:()=>To,IsIterator:()=>bo,IsKind:()=>zo,IsKindOf:()=>I,IsLiteral:()=>qt,IsLiteralBoolean:()=>ja,IsLiteralNumber:()=>Ao,IsLiteralString:()=>wo,IsLiteralValue:()=>Po,IsMappedKey:()=>Ro,IsMappedResult:()=>Oo,IsNever:()=>Co,IsNot:()=>Mo,IsNull:()=>Eo,IsNumber:()=>ko,IsObject:()=>Fo,IsOptional:()=>Ka,IsPromise:()=>$o,IsProperties:()=>ln,IsReadonly:()=>La,IsRecord:()=>vo,IsRecursive:()=>Ga,IsRef:()=>No,IsRegExp:()=>Uo,IsSchema:()=>q,IsString:()=>_o,IsSymbol:()=>Lo,IsTemplateLiteral:()=>Ko,IsThis:()=>Do,IsTransform:()=>jo,IsTuple:()=>Go,IsUint8Array:()=>Ho,IsUndefined:()=>Vo,IsUnion:()=>hr,IsUnionLiteral:()=>Va,IsUnknown:()=>Bo,IsUnsafe:()=>Wo,IsVoid:()=>qo,TypeGuardUnknownTypeError:()=>fr});var fr=class extends W{},Na=["Argument","Any","Array","AsyncIterator","BigInt","Boolean","Computed","Constructor","Date","Enum","Function","Integer","Intersect","Iterator","Literal","MappedKey","MappedResult","Not","Null","Number","Object","Promise","Record","Ref","RegExp","String","Symbol","TemplateLiteral","This","Tuple","Undefined","Union","Uint8Array","Unknown","Void"];function io(e){try{return new RegExp(e),!0}catch{return!1}}function gr(e){if(!C(e))return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function ao(e){return Ir(e)||q(e)}function Wt(e){return D(e)||Dt(e)}function M(e){return D(e)||ue(e)}function Ir(e){return D(e)||Ke(e)}function P(e){return D(e)||C(e)}function Ua(e){return D(e)||C(e)&&gr(e)&&io(e)}function _a(e){return D(e)||C(e)&&gr(e)}function uo(e){return D(e)||q(e)}function La(e){return A(e)&&e[Ae]==="Readonly"}function Ka(e){return A(e)&&e[Y]==="Optional"}function co(e){return I(e,"Any")&&P(e.$id)}function mo(e){return I(e,"Argument")&&ue(e.index)}function po(e){return I(e,"Array")&&e.type==="array"&&P(e.$id)&&q(e.items)&&M(e.minItems)&&M(e.maxItems)&&Ir(e.uniqueItems)&&uo(e.contains)&&M(e.minContains)&&M(e.maxContains)}function lo(e){return I(e,"AsyncIterator")&&e.type==="AsyncIterator"&&P(e.$id)&&q(e.items)}function fo(e){return I(e,"BigInt")&&e.type==="bigint"&&P(e.$id)&&Wt(e.exclusiveMaximum)&&Wt(e.exclusiveMinimum)&&Wt(e.maximum)&&Wt(e.minimum)&&Wt(e.multipleOf)}function go(e){return I(e,"Boolean")&&e.type==="boolean"&&P(e.$id)}function Io(e){return I(e,"Computed")&&C(e.target)&&K(e.parameters)&&e.parameters.every(t=>q(t))}function ho(e){return I(e,"Constructor")&&e.type==="Constructor"&&P(e.$id)&&K(e.parameters)&&e.parameters.every(t=>q(t))&&q(e.returns)}function yo(e){return I(e,"Date")&&e.type==="Date"&&P(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function xo(e){return I(e,"Function")&&e.type==="Function"&&P(e.$id)&&K(e.parameters)&&e.parameters.every(t=>q(t))&&q(e.returns)}function Da(e){return I(e,"Import")&&dn(e,"$defs")&&A(e.$defs)&&ln(e.$defs)&&dn(e,"$ref")&&C(e.$ref)&&e.$ref in e.$defs}function So(e){return I(e,"Integer")&&e.type==="integer"&&P(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function ln(e){return A(e)&&Object.entries(e).every(([t,n])=>gr(t)&&q(n))}function To(e){return I(e,"Intersect")&&!(C(e.type)&&e.type!=="object")&&K(e.allOf)&&e.allOf.every(t=>q(t)&&!jo(t))&&P(e.type)&&(Ir(e.unevaluatedProperties)||uo(e.unevaluatedProperties))&&P(e.$id)}function bo(e){return I(e,"Iterator")&&e.type==="Iterator"&&P(e.$id)&&q(e.items)}function I(e,t){return A(e)&&m in e&&e[m]===t}function wo(e){return qt(e)&&C(e.const)}function Ao(e){return qt(e)&&ue(e.const)}function ja(e){return qt(e)&&Ke(e.const)}function qt(e){return I(e,"Literal")&&P(e.$id)&&Po(e.const)}function Po(e){return Ke(e)||ue(e)||C(e)}function Ro(e){return I(e,"MappedKey")&&K(e.keys)&&e.keys.every(t=>ue(t)||C(t))}function Oo(e){return I(e,"MappedResult")&&ln(e.properties)}function Co(e){return I(e,"Never")&&A(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Mo(e){return I(e,"Not")&&q(e.not)}function Eo(e){return I(e,"Null")&&e.type==="null"&&P(e.$id)}function ko(e){return I(e,"Number")&&e.type==="number"&&P(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function Fo(e){return I(e,"Object")&&e.type==="object"&&P(e.$id)&&ln(e.properties)&&ao(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function $o(e){return I(e,"Promise")&&e.type==="Promise"&&P(e.$id)&&q(e.item)}function vo(e){return I(e,"Record")&&e.type==="object"&&P(e.$id)&&ao(e.additionalProperties)&&A(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&io(n[0])&&A(t.patternProperties)&&q(t.patternProperties[n[0]])})(e)}function Ga(e){return A(e)&&Ie in e&&e[Ie]==="Recursive"}function No(e){return I(e,"Ref")&&P(e.$id)&&C(e.$ref)}function Uo(e){return I(e,"RegExp")&&P(e.$id)&&C(e.source)&&C(e.flags)&&M(e.maxLength)&&M(e.minLength)}function _o(e){return I(e,"String")&&e.type==="string"&&P(e.$id)&&M(e.minLength)&&M(e.maxLength)&&Ua(e.pattern)&&_a(e.format)}function Lo(e){return I(e,"Symbol")&&e.type==="symbol"&&P(e.$id)}function Ko(e){return I(e,"TemplateLiteral")&&e.type==="string"&&C(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Do(e){return I(e,"This")&&P(e.$id)&&C(e.$ref)}function jo(e){return A(e)&&V in e}function Go(e){return I(e,"Tuple")&&e.type==="array"&&P(e.$id)&&ue(e.minItems)&&ue(e.maxItems)&&e.minItems===e.maxItems&&(D(e.items)&&D(e.additionalItems)&&e.minItems===0||K(e.items)&&e.items.every(t=>q(t)))}function Vo(e){return I(e,"Undefined")&&e.type==="undefined"&&P(e.$id)}function Va(e){return hr(e)&&e.anyOf.every(t=>wo(t)||Ao(t))}function hr(e){return I(e,"Union")&&P(e.$id)&&A(e)&&K(e.anyOf)&&e.anyOf.every(t=>q(t))}function Ho(e){return I(e,"Uint8Array")&&e.type==="Uint8Array"&&P(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function Bo(e){return I(e,"Unknown")&&P(e.$id)}function Wo(e){return I(e,"Unsafe")}function qo(e){return I(e,"Void")&&e.type==="void"&&P(e.$id)}function zo(e){return A(e)&&m in e&&C(e[m])&&!Na.includes(e[m])}function q(e){return A(e)&&(co(e)||mo(e)||po(e)||go(e)||fo(e)||lo(e)||Io(e)||ho(e)||yo(e)||xo(e)||So(e)||To(e)||bo(e)||qt(e)||Ro(e)||Oo(e)||Co(e)||Mo(e)||Eo(e)||ko(e)||Fo(e)||$o(e)||vo(e)||No(e)||Uo(e)||_o(e)||Lo(e)||Ko(e)||Do(e)||Go(e)||Vo(e)||hr(e)||Ho(e)||Bo(e)||Wo(e)||qo(e)||zo(e))}var yr="(true|false)",zt="(0|[1-9][0-9]*)",xr="(.*)",Ha="(?!.*)",wf=`^${yr}$`,ze=`^${zt}$`,Ye=`^${xr}$`,Yo=`^${Ha}$`;function Jo(e,t){return e.includes(t)}function Xo(e){return[...new Set(e)]}function Ba(e,t){return e.filter(n=>t.includes(n))}function Wa(e,t){return e.reduce((n,r)=>Ba(n,r),t)}function Qo(e){return e.length===1?e[0]:e.length>1?Wa(e.slice(1),e[0]):[]}function Zo(e){let t=[];for(let n of e)t.push(...n);return t}function Je(e){return u({[m]:"Any"},e)}function St(e,t){return u({[m]:"Array",type:"array",items:e},t)}function es(e){return u({[m]:"Argument",index:e})}function Tt(e,t){return u({[m]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function k(e,t,n){return u({[m]:"Computed",target:e,parameters:t},n)}function qa(e,t){let{[t]:n,...r}=e;return r}function N(e,t){return t.reduce((n,r)=>qa(n,r),e)}function x(e){return u({[m]:"Never",not:{}},e)}function S(e){return u({[m]:"MappedResult",properties:e})}function bt(e,t,n){return u({[m]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function Ne(e,t,n){return u({[m]:"Function",type:"Function",parameters:e,returns:t},n)}function Yt(e,t){return u({[m]:"Union",anyOf:e},t)}function za(e){return e.some(t=>re(t))}function ts(e){return e.map(t=>re(t)?Ya(t):t)}function Ya(e){return N(e,[Y])}function Ja(e,t){return za(e)?X(Yt(ts(e),t)):Yt(ts(e),t)}function Ue(e,t){return e.length===1?u(e[0],t):e.length===0?x(t):Ja(e,t)}function w(e,t){return e.length===0?x(t):e.length===1?u(e[0],t):Yt(e,t)}var fn=class extends W{};function Xa(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Sr(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function He(e,t){return Sr(e,t,"(")}function Jt(e,t){return Sr(e,t,")")}function ns(e,t){return Sr(e,t,"|")}function Qa(e){if(!(He(e,0)&&Jt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(He(e,n)&&(t+=1),Jt(e,n)&&(t-=1),t===0&&n!==e.length-1)return!1;return!0}function Za(e){return e.slice(1,e.length-1)}function eu(e){let t=0;for(let n=0;n<e.length;n++)if(He(e,n)&&(t+=1),Jt(e,n)&&(t-=1),ns(e,n)&&t===0)return!0;return!1}function tu(e){for(let t=0;t<e.length;t++)if(He(e,t))return!0;return!1}function nu(e){let[t,n]=[0,0],r=[];for(let i=0;i<e.length;i++)if(He(e,i)&&(t+=1),Jt(e,i)&&(t-=1),ns(e,i)&&t===0){let s=e.slice(n,i);s.length>0&&r.push(wt(s)),n=i+1}let o=e.slice(n);return o.length>0&&r.push(wt(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function ru(e){function t(o,i){if(!He(o,i))throw new fn("TemplateLiteralParser: Index must point to open parens");let s=0;for(let c=i;c<o.length;c++)if(He(o,c)&&(s+=1),Jt(o,c)&&(s-=1),s===0)return[i,c];throw new fn("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,i){for(let s=i;s<o.length;s++)if(He(o,s))return[i,s];return[i,o.length]}let r=[];for(let o=0;o<e.length;o++)if(He(e,o)){let[i,s]=t(e,o),c=e.slice(i,s+1);r.push(wt(c)),o=s}else{let[i,s]=n(e,o),c=e.slice(i,s);c.length>0&&r.push(wt(c)),o=s-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function wt(e){return Qa(e)?wt(Za(e)):eu(e)?nu(e):tu(e)?ru(e):{type:"const",const:Xa(e)}}function At(e){return wt(e.slice(1,e.length-1))}var Tr=class extends W{};function ou(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="0"&&e.expr[1].type==="const"&&e.expr[1].const==="[1-9][0-9]*"}function su(e){return e.type==="or"&&e.expr.length===2&&e.expr[0].type==="const"&&e.expr[0].const==="true"&&e.expr[1].type==="const"&&e.expr[1].const==="false"}function iu(e){return e.type==="const"&&e.const===".*"}function pt(e){return ou(e)||iu(e)?!1:su(e)?!0:e.type==="and"?e.expr.every(t=>pt(t)):e.type==="or"?e.expr.every(t=>pt(t)):e.type==="const"?!0:(()=>{throw new Tr("Unknown expression type")})()}function rs(e){let t=At(e.pattern);return pt(t)}var br=class extends W{};function*os(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let n of os(e.slice(1)))yield`${t}${n}`}function*au(e){return yield*os(e.expr.map(t=>[...Xt(t)]))}function*uu(e){for(let t of e.expr)yield*Xt(t)}function*du(e){return yield e.const}function*Xt(e){return e.type==="and"?yield*au(e):e.type==="or"?yield*uu(e):e.type==="const"?yield*du(e):(()=>{throw new br("Unknown expression")})()}function gn(e){let t=At(e.pattern);return pt(t)?[...Xt(t)]:[]}function b(e,t){return u({[m]:"Literal",const:e,type:typeof e},t)}function In(e){return u({[m]:"Boolean",type:"boolean"},e)}function Pt(e){return u({[m]:"BigInt",type:"bigint"},e)}function he(e){return u({[m]:"Number",type:"number"},e)}function ke(e){return u({[m]:"String",type:"string"},e)}function*cu(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield In():t==="number"?yield he():t==="bigint"?yield Pt():t==="string"?yield ke():yield(()=>{let n=t.split("|").map(r=>b(r.trim()));return n.length===0?x():n.length===1?n[0]:Ue(n)})()}function*mu(e){if(e[1]!=="{"){let t=b("$"),n=wr(e.slice(1));return yield*[t,...n]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let n=cu(e.slice(2,t)),r=wr(e.slice(t+1));return yield*[...n,...r]}yield b(e)}function*wr(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=b(e.slice(0,t)),r=mu(e.slice(t));return yield*[n,...r]}yield b(e)}function ss(e){return[...wr(e)]}var Ar=class extends W{};function pu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function is(e,t){return me(e)?e.pattern.slice(1,e.pattern.length-1):y(e)?`(${e.anyOf.map(n=>is(n,t)).join("|")})`:Ee(e)?`${t}${zt}`:Me(e)?`${t}${zt}`:ut(e)?`${t}${zt}`:Ge(e)?`${t}${xr}`:de(e)?`${t}${pu(e.const.toString())}`:je(e)?`${t}${yr}`:(()=>{throw new Ar(`Unexpected Kind '${e[m]}'`)})()}function Pr(e){return`^${e.map(t=>is(t,"")).join("")}$`}function lt(e){let n=gn(e).map(r=>b(r));return Ue(n)}function hn(e,t){let n=C(e)?Pr(ss(e)):Pr(e);return u({[m]:"TemplateLiteral",type:"string",pattern:n},t)}function lu(e){return gn(e).map(n=>n.toString())}function fu(e){let t=[];for(let n of e)t.push(...oe(n));return t}function gu(e){return[e.toString()]}function oe(e){return[...new Set(me(e)?lu(e):y(e)?fu(e.anyOf):de(e)?gu(e.const):Ee(e)?["[number]"]:Me(e)?["[number]"]:[])]}function Iu(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=Xe(e,oe(t[o]),n);return r}function hu(e,t,n){return Iu(e,t.properties,n)}function as(e,t,n){let r=hu(e,t,n);return S(r)}function ds(e,t){return e.map(n=>cs(n,t))}function yu(e){return e.filter(t=>!We(t))}function xu(e,t){return yn(yu(ds(e,t)))}function Su(e){return e.some(t=>We(t))?[]:e}function Tu(e,t){return Ue(Su(ds(e,t)))}function bu(e,t){return t in e?e[t]:t==="[number]"?Ue(e):x()}function wu(e,t){return t==="[number]"?e:x()}function Au(e,t){return t in e?e[t]:x()}function cs(e,t){return v(e)?xu(e.allOf,t):y(e)?Tu(e.anyOf,t):pe(e)?bu(e.items??[],t):Pe(e)?wu(e.items,t):j(e)?Au(e.properties,t):x()}function Rr(e,t){return t.map(n=>cs(e,n))}function us(e,t){return Ue(Rr(e,t))}function Xe(e,t,n){if(L(e)||L(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!le(e)||!le(t))throw new W(r);return k("Index",[e,t])}return $(t)?as(e,t,n):ce(t)?ms(e,t,n):u(le(t)?us(e,oe(t)):us(e,t),n)}function Pu(e,t,n){return{[t]:Xe(e,[t],F(n))}}function Ru(e,t,n){return t.reduce((r,o)=>({...r,...Pu(e,o,n)}),{})}function Ou(e,t,n){return Ru(e,t.keys,n)}function ms(e,t,n){let r=Ou(e,t,n);return S(r)}function Rt(e,t){return u({[m]:"Iterator",type:"Iterator",items:e},t)}function Cu(e){return globalThis.Object.keys(e).filter(t=>!re(e[t]))}function Mu(e,t){let n=Cu(e),r=n.length>0?{[m]:"Object",type:"object",required:n,properties:e}:{[m]:"Object",type:"object",properties:e};return u(r,t)}var R=Mu;function xn(e,t){return u({[m]:"Promise",type:"Promise",item:e},t)}function Eu(e){return u(N(e,[Ae]))}function ku(e){return u({...e,[Ae]:"Readonly"})}function Fu(e,t){return t===!1?Eu(e):ku(e)}function se(e,t){let n=t??!0;return $(e)?ps(e,n):Fu(e,n)}function $u(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=se(e[r],t);return n}function vu(e,t){return $u(e.properties,t)}function ps(e,t){let n=vu(e,t);return S(n)}function ye(e,t){return u(e.length>0?{[m]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[m]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function ls(e,t){return e in t?xe(e,t[e]):S(t)}function Nu(e){return{[e]:b(e)}}function Uu(e){let t={};for(let n of e)t[n]=b(n);return t}function _u(e,t){return Jo(t,e)?Nu(e):Uu(t)}function Lu(e,t){let n=_u(e,t);return ls(e,n)}function Qt(e,t){return t.map(n=>xe(e,n))}function Ku(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=xe(e,t[r]);return n}function xe(e,t){let n={...t};return re(t)?X(xe(e,N(t,[Y]))):xt(t)?se(xe(e,N(t,[Ae]))):$(t)?ls(e,t.properties):ce(t)?Lu(e,t.keys):Oe(t)?bt(Qt(e,t.parameters),xe(e,t.returns),n):Ce(t)?Ne(Qt(e,t.parameters),xe(e,t.returns),n):at(t)?Tt(xe(e,t.items),n):dt(t)?Rt(xe(e,t.items),n):v(t)?Q(Qt(e,t.allOf),n):y(t)?w(Qt(e,t.anyOf),n):pe(t)?ye(Qt(e,t.items??[]),n):j(t)?R(Ku(e,t.properties),n):Pe(t)?St(xe(e,t.items),n):ct(t)?xn(xe(e,t.item),n):t}function Du(e,t){let n={};for(let r of e)n[r]=xe(r,t);return n}function fs(e,t,n){let r=le(e)?oe(e):e,o=t({[m]:"MappedKey",keys:r}),i=Du(r,o);return R(i,n)}function ju(e){return u(N(e,[Y]))}function Gu(e){return u({...e,[Y]:"Optional"})}function Vu(e,t){return t===!1?ju(e):Gu(e)}function X(e,t){let n=t??!0;return $(e)?gs(e,n):Vu(e,n)}function Hu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=X(e[r],t);return n}function Bu(e,t){return Hu(e.properties,t)}function gs(e,t){let n=Bu(e,t);return S(n)}function Zt(e,t={}){let n=e.every(o=>j(o)),r=le(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||le(t.unevaluatedProperties)||n?{...r,[m]:"Intersect",type:"object",allOf:e}:{...r,[m]:"Intersect",allOf:e},t)}function Wu(e){return e.every(t=>re(t))}function qu(e){return N(e,[Y])}function Is(e){return e.map(t=>re(t)?qu(t):t)}function zu(e,t){return Wu(e)?X(Zt(Is(e),t)):Zt(Is(e),t)}function yn(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>qe(n)))throw new Error("Cannot intersect transform types");return zu(e,t)}function Q(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>qe(n)))throw new Error("Cannot intersect transform types");return Zt(e,t)}function _e(...e){let[t,n]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new W("Ref: $ref must be a string");return u({[m]:"Ref",$ref:t},n)}function Yu(e,t){return k("Awaited",[k(e,t)])}function Ju(e){return k("Awaited",[_e(e)])}function Xu(e){return Q(hs(e))}function Qu(e){return w(hs(e))}function Zu(e){return Ot(e)}function hs(e){return e.map(t=>Ot(t))}function Ot(e,t){return u(Re(e)?Yu(e.target,e.parameters):v(e)?Xu(e.allOf):y(e)?Qu(e.anyOf):ct(e)?Zu(e.item):L(e)?Ju(e.$ref):e,t)}function ys(e){let t=[];for(let n of e)t.push(en(n));return t}function ed(e){let t=ys(e);return Zo(t)}function td(e){let t=ys(e);return Qo(t)}function nd(e){return e.map((t,n)=>n.toString())}function rd(e){return["[number]"]}function od(e){return globalThis.Object.getOwnPropertyNames(e)}function sd(e){return id?globalThis.Object.getOwnPropertyNames(e).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function en(e){return v(e)?ed(e.allOf):y(e)?td(e.anyOf):pe(e)?nd(e.items??[]):Pe(e)?rd(e.items):j(e)?od(e.properties):mt(e)?sd(e.patternProperties):[]}var id=!1;function ad(e,t){return k("KeyOf",[k(e,t)])}function ud(e){return k("KeyOf",[_e(e)])}function dd(e,t){let n=en(e),r=cd(n),o=Ue(r);return u(o,t)}function cd(e){return e.map(t=>t==="[number]"?he():b(t))}function Ct(e,t){return Re(e)?ad(e.target,e.parameters):L(e)?ud(e.$ref):$(e)?xs(e,t):dd(e,t)}function md(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ct(e[r],F(t));return n}function pd(e,t){return md(e.properties,t)}function xs(e,t){let n=pd(e,t);return S(n)}function ld(e){let t=[];for(let n of e)t.push(...en(n));return Xo(t)}function fd(e){return e.filter(t=>!We(t))}function gd(e,t){let n=[];for(let r of e)n.push(...Rr(r,[t]));return fd(n)}function Id(e,t){let n={};for(let r of t)n[r]=yn(gd(e,r));return n}function Ss(e,t){let n=ld(e),r=Id(e,n);return R(r,t)}function Sn(e){return u({[m]:"Date",type:"Date"},e)}function Tn(e){return u({[m]:"Null",type:"null"},e)}function bn(e){return u({[m]:"Symbol",type:"symbol"},e)}function wn(e){return u({[m]:"Undefined",type:"undefined"},e)}function An(e){return u({[m]:"Uint8Array",type:"Uint8Array"},e)}function Qe(e){return u({[m]:"Unknown"},e)}function hd(e){return e.map(t=>Or(t,!1))}function yd(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=se(Or(e[n],!1));return t}function Pn(e,t){return t===!0?e:se(e)}function Or(e,t){return ir(e)?Pn(Je(),t):ur(e)?Pn(Je(),t):K(e)?se(ye(hd(e))):De(e)?An():it(e)?Sn():A(e)?Pn(R(yd(e)),t):ar(e)?Pn(Ne([],Qe()),t):D(e)?wn():dr(e)?Tn():cr(e)?bn():Dt(e)?Pt():ue(e)?b(e):Ke(e)?b(e):C(e)?b(e):R({})}function Ts(e,t){return u(Or(e,!0),t)}function bs(e,t){return Oe(e)?ye(e.parameters,t):x(t)}function ws(e,t){if(D(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(i=>isNaN(i)).map(i=>e[i]),o=[...new Set(n)].map(i=>b(i));return w(o,{...t,[Ie]:"Enum"})}var Mr=class extends W{},d;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(d||(d={}));function Se(e){return e===d.False?e:d.True}function Mt(e){throw new Mr(e)}function H(e){return a.IsNever(e)||a.IsIntersect(e)||a.IsUnion(e)||a.IsUnknown(e)||a.IsAny(e)}function B(e,t){return a.IsNever(t)?Es(e,t):a.IsIntersect(t)?Rn(e,t):a.IsUnion(t)?$r(e,t):a.IsUnknown(t)?vs(e,t):a.IsAny(t)?Fr(e,t):Mt("StructuralRight")}function Fr(e,t){return d.True}function xd(e,t){return a.IsIntersect(t)?Rn(e,t):a.IsUnion(t)&&t.anyOf.some(n=>a.IsAny(n)||a.IsUnknown(n))?d.True:a.IsUnion(t)?d.Union:a.IsUnknown(t)||a.IsAny(t)?d.True:d.Union}function Sd(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)?d.True:d.False}function Td(e,t){return a.IsObject(t)&&On(t)?d.True:H(t)?B(e,t):a.IsArray(t)?Se(O(e.items,t.items)):d.False}function bd(e,t){return H(t)?B(e,t):a.IsAsyncIterator(t)?Se(O(e.items,t.items)):d.False}function wd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsBigInt(t)?d.True:d.False}function Cs(e,t){return a.IsLiteralBoolean(e)||a.IsBoolean(e)?d.True:d.False}function Ad(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsBoolean(t)?d.True:d.False}function Pd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsConstructor(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>Se(O(t.parameters[r],n))===d.True)?Se(O(e.returns,t.returns)):d.False:d.False}function Rd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsDate(t)?d.True:d.False}function Od(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsFunction(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>Se(O(t.parameters[r],n))===d.True)?Se(O(e.returns,t.returns)):d.False:d.False}function Ms(e,t){return a.IsLiteral(e)&&J.IsNumber(e.const)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function Cd(e,t){return a.IsInteger(t)||a.IsNumber(t)?d.True:H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):d.False}function Rn(e,t){return t.allOf.every(n=>O(e,n)===d.True)?d.True:d.False}function Md(e,t){return e.allOf.some(n=>O(n,t)===d.True)?d.True:d.False}function Ed(e,t){return H(t)?B(e,t):a.IsIterator(t)?Se(O(e.items,t.items)):d.False}function kd(e,t){return a.IsLiteral(t)&&t.const===e.const?d.True:H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsString(t)?$s(e,t):a.IsNumber(t)?ks(e,t):a.IsInteger(t)?Ms(e,t):a.IsBoolean(t)?Cs(e,t):d.False}function Es(e,t){return d.False}function Fd(e,t){return d.True}function As(e){let[t,n]=[e,0];for(;a.IsNot(t);)t=t.not,n+=1;return n%2===0?t:Qe()}function $d(e,t){return a.IsNot(e)?O(As(e),t):a.IsNot(t)?O(e,As(t)):Mt("Invalid fallthrough for Not")}function vd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsNull(t)?d.True:d.False}function ks(e,t){return a.IsLiteralNumber(e)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function Nd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsInteger(t)||a.IsNumber(t)?d.True:d.False}function ie(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Ps(e){return On(e)}function Rs(e){return ie(e,0)||ie(e,1)&&"description"in e.properties&&a.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(a.IsString(e.properties.description.anyOf[0])&&a.IsUndefined(e.properties.description.anyOf[1])||a.IsString(e.properties.description.anyOf[1])&&a.IsUndefined(e.properties.description.anyOf[0]))}function Cr(e){return ie(e,0)}function Os(e){return ie(e,0)}function Ud(e){return ie(e,0)}function _d(e){return ie(e,0)}function Ld(e){return On(e)}function Kd(e){let t=he();return ie(e,0)||ie(e,1)&&"length"in e.properties&&Se(O(e.properties.length,t))===d.True}function Dd(e){return ie(e,0)}function On(e){let t=he();return ie(e,0)||ie(e,1)&&"length"in e.properties&&Se(O(e.properties.length,t))===d.True}function jd(e){let t=Ne([Je()],Je());return ie(e,0)||ie(e,1)&&"then"in e.properties&&Se(O(e.properties.then,t))===d.True}function Fs(e,t){return O(e,t)===d.False||a.IsOptional(e)&&!a.IsOptional(t)?d.False:d.True}function Z(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)||a.IsLiteralString(e)&&Ps(t)||a.IsLiteralNumber(e)&&Cr(t)||a.IsLiteralBoolean(e)&&Os(t)||a.IsSymbol(e)&&Rs(t)||a.IsBigInt(e)&&Ud(t)||a.IsString(e)&&Ps(t)||a.IsSymbol(e)&&Rs(t)||a.IsNumber(e)&&Cr(t)||a.IsInteger(e)&&Cr(t)||a.IsBoolean(e)&&Os(t)||a.IsUint8Array(e)&&Ld(t)||a.IsDate(e)&&_d(t)||a.IsConstructor(e)&&Dd(t)||a.IsFunction(e)&&Kd(t)?d.True:a.IsRecord(e)&&a.IsString(Er(e))?t[Ie]==="Record"?d.True:d.False:a.IsRecord(e)&&a.IsNumber(Er(e))&&ie(t,0)?d.True:d.False}function Gd(e,t){return H(t)?B(e,t):a.IsRecord(t)?Te(e,t):a.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!a.IsOptional(t.properties[n]))return d.False;if(a.IsOptional(t.properties[n]))return d.True;if(Fs(e.properties[n],t.properties[n])===d.False)return d.False}return d.True})():d.False}function Vd(e,t){return H(t)?B(e,t):a.IsObject(t)&&jd(t)?d.True:a.IsPromise(t)?Se(O(e.item,t.item)):d.False}function Er(e){return ze in e.patternProperties?he():Ye in e.patternProperties?ke():Mt("Unknown record key pattern")}function kr(e){return ze in e.patternProperties?e.patternProperties[ze]:Ye in e.patternProperties?e.patternProperties[Ye]:Mt("Unable to get record value schema")}function Te(e,t){let[n,r]=[Er(t),kr(t)];return a.IsLiteralString(e)&&a.IsNumber(n)&&Se(O(e,r))===d.True?d.True:a.IsUint8Array(e)&&a.IsNumber(n)||a.IsString(e)&&a.IsNumber(n)||a.IsArray(e)&&a.IsNumber(n)?O(e,r):a.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(Fs(r,e.properties[o])===d.False)return d.False;return d.True})():d.False}function Hd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?O(kr(e),kr(t)):d.False}function Bd(e,t){let n=a.IsRegExp(e)?ke():e,r=a.IsRegExp(t)?ke():t;return O(n,r)}function $s(e,t){return a.IsLiteral(e)&&J.IsString(e.const)||a.IsString(e)?d.True:d.False}function Wd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsString(t)?d.True:d.False}function qd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsSymbol(t)?d.True:d.False}function zd(e,t){return a.IsTemplateLiteral(e)?O(lt(e),t):a.IsTemplateLiteral(t)?O(e,lt(t)):Mt("Invalid fallthrough for TemplateLiteral")}function Yd(e,t){return a.IsArray(t)&&e.items!==void 0&&e.items.every(n=>O(n,t.items)===d.True)}function Jd(e,t){return a.IsNever(e)?d.True:a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:d.False}function Xd(e,t){return H(t)?B(e,t):a.IsObject(t)&&On(t)||a.IsArray(t)&&Yd(e,t)?d.True:a.IsTuple(t)?J.IsUndefined(e.items)&&!J.IsUndefined(t.items)||!J.IsUndefined(e.items)&&J.IsUndefined(t.items)?d.False:J.IsUndefined(e.items)&&!J.IsUndefined(t.items)||e.items.every((n,r)=>O(n,t.items[r])===d.True)?d.True:d.False:d.False}function Qd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsUint8Array(t)?d.True:d.False}function Zd(e,t){return H(t)?B(e,t):a.IsObject(t)?Z(e,t):a.IsRecord(t)?Te(e,t):a.IsVoid(t)?nc(e,t):a.IsUndefined(t)?d.True:d.False}function $r(e,t){return t.anyOf.some(n=>O(e,n)===d.True)?d.True:d.False}function ec(e,t){return e.anyOf.every(n=>O(n,t)===d.True)?d.True:d.False}function vs(e,t){return d.True}function tc(e,t){return a.IsNever(t)?Es(e,t):a.IsIntersect(t)?Rn(e,t):a.IsUnion(t)?$r(e,t):a.IsAny(t)?Fr(e,t):a.IsString(t)?$s(e,t):a.IsNumber(t)?ks(e,t):a.IsInteger(t)?Ms(e,t):a.IsBoolean(t)?Cs(e,t):a.IsArray(t)?Sd(e,t):a.IsTuple(t)?Jd(e,t):a.IsObject(t)?Z(e,t):a.IsUnknown(t)?d.True:d.False}function nc(e,t){return a.IsUndefined(e)||a.IsUndefined(e)?d.True:d.False}function rc(e,t){return a.IsIntersect(t)?Rn(e,t):a.IsUnion(t)?$r(e,t):a.IsUnknown(t)?vs(e,t):a.IsAny(t)?Fr(e,t):a.IsObject(t)?Z(e,t):a.IsVoid(t)?d.True:d.False}function O(e,t){return a.IsTemplateLiteral(e)||a.IsTemplateLiteral(t)?zd(e,t):a.IsRegExp(e)||a.IsRegExp(t)?Bd(e,t):a.IsNot(e)||a.IsNot(t)?$d(e,t):a.IsAny(e)?xd(e,t):a.IsArray(e)?Td(e,t):a.IsBigInt(e)?wd(e,t):a.IsBoolean(e)?Ad(e,t):a.IsAsyncIterator(e)?bd(e,t):a.IsConstructor(e)?Pd(e,t):a.IsDate(e)?Rd(e,t):a.IsFunction(e)?Od(e,t):a.IsInteger(e)?Cd(e,t):a.IsIntersect(e)?Md(e,t):a.IsIterator(e)?Ed(e,t):a.IsLiteral(e)?kd(e,t):a.IsNever(e)?Fd(e,t):a.IsNull(e)?vd(e,t):a.IsNumber(e)?Nd(e,t):a.IsObject(e)?Gd(e,t):a.IsRecord(e)?Hd(e,t):a.IsString(e)?Wd(e,t):a.IsSymbol(e)?qd(e,t):a.IsTuple(e)?Xd(e,t):a.IsPromise(e)?Vd(e,t):a.IsUint8Array(e)?Qd(e,t):a.IsUndefined(e)?Zd(e,t):a.IsUnion(e)?ec(e,t):a.IsUnknown(e)?tc(e,t):a.IsVoid(e)?rc(e,t):Mt(`Unknown left type operand '${e[m]}'`)}function Ze(e,t){return O(e,t)}function oc(e,t,n,r,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(e))i[s]=Et(e[s],t,n,r,F(o));return i}function sc(e,t,n,r,o){return oc(e.properties,t,n,r,o)}function Ns(e,t,n,r,o){let i=sc(e,t,n,r,o);return S(i)}function ic(e,t,n,r){let o=Ze(e,t);return o===d.Union?w([n,r]):o===d.True?n:r}function Et(e,t,n,r,o){return $(e)?Ns(e,t,n,r,o):ce(e)?u(Us(e,t,n,r,o)):u(ic(e,t,n,r),o)}function ac(e,t,n,r,o){return{[e]:Et(b(e),t,n,r,F(o))}}function uc(e,t,n,r,o){return e.reduce((i,s)=>({...i,...ac(s,t,n,r,o)}),{})}function dc(e,t,n,r,o){return uc(e.keys,t,n,r,o)}function Us(e,t,n,r,o){let i=dc(e,t,n,r,o);return S(i)}function _s(e,t){return kt(lt(e),t)}function cc(e,t){let n=e.filter(r=>Ze(r,t)===d.False);return n.length===1?n[0]:w(n)}function kt(e,t,n={}){return me(e)?u(_s(e,t),n):$(e)?u(Ls(e,t),n):u(y(e)?cc(e.anyOf,t):Ze(e,t)!==d.False?x():e,n)}function mc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=kt(e[r],t);return n}function pc(e,t){return mc(e.properties,t)}function Ls(e,t){let n=pc(e,t);return S(n)}function Ks(e,t){return Ft(lt(e),t)}function lc(e,t){let n=e.filter(r=>Ze(r,t)!==d.False);return n.length===1?n[0]:w(n)}function Ft(e,t,n){return me(e)?u(Ks(e,t),n):$(e)?u(Ds(e,t),n):u(y(e)?lc(e.anyOf,t):Ze(e,t)!==d.False?e:x(),n)}function fc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ft(e[r],t);return n}function gc(e,t){return fc(e.properties,t)}function Ds(e,t){let n=gc(e,t);return S(n)}function js(e,t){return Oe(e)?u(e.returns,t):x(t)}function Cn(e){return se(X(e))}function ft(e,t,n){return u({[m]:"Record",type:"object",patternProperties:{[e]:t}},n)}function vr(e,t,n){let r={};for(let o of e)r[o]=t;return R(r,{...n,[Ie]:"Record"})}function Ic(e,t,n){return rs(e)?vr(oe(e),t,n):ft(e.pattern,t,n)}function hc(e,t,n){return vr(oe(w(e)),t,n)}function yc(e,t,n){return vr([e.toString()],t,n)}function xc(e,t,n){return ft(e.source,t,n)}function Sc(e,t,n){let r=D(e.pattern)?Ye:e.pattern;return ft(r,t,n)}function Tc(e,t,n){return ft(Ye,t,n)}function bc(e,t,n){return ft(Yo,t,n)}function wc(e,t,n){return R({true:t,false:t},n)}function Ac(e,t,n){return ft(ze,t,n)}function Pc(e,t,n){return ft(ze,t,n)}function Mn(e,t,n={}){return y(e)?hc(e.anyOf,t,n):me(e)?Ic(e,t,n):de(e)?yc(e.const,t,n):je(e)?wc(e,t,n):Me(e)?Ac(e,t,n):Ee(e)?Pc(e,t,n):lr(e)?xc(e,t,n):Ge(e)?Sc(e,t,n):mr(e)?Tc(e,t,n):We(e)?bc(e,t,n):x(n)}function En(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function Gs(e){let t=En(e);return t===Ye?ke():t===ze?he():ke({pattern:t})}function kn(e){return e.patternProperties[En(e)]}function Rc(e,t){return t.parameters=tn(e,t.parameters),t.returns=Fe(e,t.returns),t}function Oc(e,t){return t.parameters=tn(e,t.parameters),t.returns=Fe(e,t.returns),t}function Cc(e,t){return t.allOf=tn(e,t.allOf),t}function Mc(e,t){return t.anyOf=tn(e,t.anyOf),t}function Ec(e,t){return D(t.items)||(t.items=tn(e,t.items)),t}function kc(e,t){return t.items=Fe(e,t.items),t}function Fc(e,t){return t.items=Fe(e,t.items),t}function $c(e,t){return t.items=Fe(e,t.items),t}function vc(e,t){return t.item=Fe(e,t.item),t}function Nc(e,t){let n=Kc(e,t.properties);return{...t,...R(n)}}function Uc(e,t){let n=Fe(e,Gs(t)),r=Fe(e,kn(t)),o=Mn(n,r);return{...t,...o}}function _c(e,t){return t.index in e?e[t.index]:Qe()}function Lc(e,t){let n=xt(t),r=re(t),o=Fe(e,t);return n&&r?Cn(o):n&&!r?se(o):!n&&r?X(o):o}function Kc(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:Lc(e,t[r])}),{})}function tn(e,t){return t.map(n=>Fe(e,n))}function Fe(e,t){return Oe(t)?Rc(e,t):Ce(t)?Oc(e,t):v(t)?Cc(e,t):y(t)?Mc(e,t):pe(t)?Ec(e,t):Pe(t)?kc(e,t):at(t)?Fc(e,t):dt(t)?$c(e,t):ct(t)?vc(e,t):j(t)?Nc(e,t):mt(t)?Uc(e,t):pr(t)?_c(e,t):t}function Vs(e,t){return Fe(t,yt(e))}function Hs(e){return u({[m]:"Integer",type:"integer"},e)}function Dc(e,t,n){return{[e]:$e(b(e),t,F(n))}}function jc(e,t,n){return e.reduce((o,i)=>({...o,...Dc(i,t,n)}),{})}function Gc(e,t,n){return jc(e.keys,t,n)}function Bs(e,t,n){let r=Gc(e,t,n);return S(r)}function Vc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function Hc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function Bc(e){return e.toUpperCase()}function Wc(e){return e.toLowerCase()}function qc(e,t,n){let r=At(e.pattern);if(!pt(r))return{...e,pattern:Ws(e.pattern,t)};let s=[...Xt(r)].map(f=>b(f)),c=qs(s,t),p=w(c);return hn([p],n)}function Ws(e,t){return typeof e=="string"?t==="Uncapitalize"?Vc(e):t==="Capitalize"?Hc(e):t==="Uppercase"?Bc(e):t==="Lowercase"?Wc(e):e:e.toString()}function qs(e,t){return e.map(n=>$e(n,t))}function $e(e,t,n={}){return ce(e)?Bs(e,t,n):me(e)?qc(e,t,n):y(e)?w(qs(e.anyOf,t),n):de(e)?b(Ws(e.const,t),n):u(e,n)}function zs(e,t={}){return $e(e,"Capitalize",t)}function Ys(e,t={}){return $e(e,"Lowercase",t)}function Js(e,t={}){return $e(e,"Uncapitalize",t)}function Xs(e,t={}){return $e(e,"Uppercase",t)}function zc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=et(e[o],t,F(n));return r}function Yc(e,t,n){return zc(e.properties,t,n)}function Qs(e,t,n){let r=Yc(e,t,n);return S(r)}function Jc(e,t){return e.map(n=>Nr(n,t))}function Xc(e,t){return e.map(n=>Nr(n,t))}function Qc(e,t){let{[t]:n,...r}=e;return r}function Zc(e,t){return t.reduce((n,r)=>Qc(n,r),e)}function em(e,t,n){let r=N(e,[V,"$id","required","properties"]),o=Zc(n,t);return R(o,r)}function tm(e){let t=e.reduce((n,r)=>pn(r)?[...n,b(r)]:n,[]);return w(t)}function Nr(e,t){return v(e)?Q(Jc(e.allOf,t)):y(e)?w(Xc(e.anyOf,t)):j(e)?em(e,t,e.properties):R({})}function et(e,t,n){let r=K(t)?tm(t):t,o=le(t)?oe(t):t,i=L(e),s=L(t);return $(e)?Qs(e,o,n):ce(t)?Zs(e,t,n):i&&s?k("Omit",[e,r],n):!i&&s?k("Omit",[e,r],n):i&&!s?k("Omit",[e,r],n):u({...Nr(e,o),...n})}function nm(e,t,n){return{[t]:et(e,[t],F(n))}}function rm(e,t,n){return t.reduce((r,o)=>({...r,...nm(e,o,n)}),{})}function om(e,t,n){return rm(e,t.keys,n)}function Zs(e,t,n){let r=om(e,t,n);return S(r)}function sm(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=tt(e[o],t,F(n));return r}function im(e,t,n){return sm(e.properties,t,n)}function ei(e,t,n){let r=im(e,t,n);return S(r)}function am(e,t){return e.map(n=>Ur(n,t))}function um(e,t){return e.map(n=>Ur(n,t))}function dm(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function cm(e,t,n){let r=N(e,[V,"$id","required","properties"]),o=dm(n,t);return R(o,r)}function mm(e){let t=e.reduce((n,r)=>pn(r)?[...n,b(r)]:n,[]);return w(t)}function Ur(e,t){return v(e)?Q(am(e.allOf,t)):y(e)?w(um(e.anyOf,t)):j(e)?cm(e,t,e.properties):R({})}function tt(e,t,n){let r=K(t)?mm(t):t,o=le(t)?oe(t):t,i=L(e),s=L(t);return $(e)?ei(e,o,n):ce(t)?ti(e,t,n):i&&s?k("Pick",[e,r],n):!i&&s?k("Pick",[e,r],n):i&&!s?k("Pick",[e,r],n):u({...Ur(e,o),...n})}function pm(e,t,n){return{[t]:tt(e,[t],F(n))}}function lm(e,t,n){return t.reduce((r,o)=>({...r,...pm(e,o,n)}),{})}function fm(e,t,n){return lm(e,t.keys,n)}function ti(e,t,n){let r=fm(e,t,n);return S(r)}function gm(e,t){return k("Partial",[k(e,t)])}function Im(e){return k("Partial",[_e(e)])}function hm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=X(e[n]);return t}function ym(e,t){let n=N(e,[V,"$id","required","properties"]),r=hm(t);return R(r,n)}function ni(e){return e.map(t=>ri(t))}function ri(e){return Re(e)?gm(e.target,e.parameters):L(e)?Im(e.$ref):v(e)?Q(ni(e.allOf)):y(e)?w(ni(e.anyOf)):j(e)?ym(e,e.properties):ut(e)||je(e)||Me(e)||de(e)||Vt(e)||Ee(e)||Ge(e)||Ht(e)||Bt(e)?e:R({})}function $t(e,t){return $(e)?oi(e,t):u({...ri(e),...t})}function xm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=$t(e[r],F(t));return n}function Sm(e,t){return xm(e.properties,t)}function oi(e,t){let n=Sm(e,t);return S(n)}function Tm(e,t){return k("Required",[k(e,t)])}function bm(e){return k("Required",[_e(e)])}function wm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=N(e[n],[Y]);return t}function Am(e,t){let n=N(e,[V,"$id","required","properties"]),r=wm(t);return R(r,n)}function si(e){return e.map(t=>ii(t))}function ii(e){return Re(e)?Tm(e.target,e.parameters):L(e)?bm(e.$ref):v(e)?Q(si(e.allOf)):y(e)?w(si(e.anyOf)):j(e)?Am(e,e.properties):ut(e)||je(e)||Me(e)||de(e)||Vt(e)||Ee(e)||Ge(e)||Ht(e)||Bt(e)?e:R({})}function vt(e,t){return $(e)?ai(e,t):u({...ii(e),...t})}function Pm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=vt(e[r],t);return n}function Rm(e,t){return Pm(e.properties,t)}function ai(e,t){let n=Rm(e,t);return S(n)}function Om(e,t){return t.map(n=>L(n)?_r(e,n.$ref):fe(e,n))}function _r(e,t){return t in e?L(e[t])?_r(e,e[t].$ref):fe(e,e[t]):x()}function Cm(e){return Ot(e[0])}function Mm(e){return Xe(e[0],e[1])}function Em(e){return Ct(e[0])}function km(e){return $t(e[0])}function Fm(e){return et(e[0],e[1])}function $m(e){return tt(e[0],e[1])}function vm(e){return vt(e[0])}function Nm(e,t,n){let r=Om(e,n);return t==="Awaited"?Cm(r):t==="Index"?Mm(r):t==="KeyOf"?Em(r):t==="Partial"?km(r):t==="Omit"?Fm(r):t==="Pick"?$m(r):t==="Required"?vm(r):x()}function Um(e,t){return St(fe(e,t))}function _m(e,t){return Tt(fe(e,t))}function Lm(e,t,n){return bt(nn(e,t),fe(e,n))}function Km(e,t,n){return Ne(nn(e,t),fe(e,n))}function Dm(e,t){return Q(nn(e,t))}function jm(e,t){return Rt(fe(e,t))}function Gm(e,t){return R(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:fe(e,t[r])}),{}))}function Vm(e,t){let[n,r]=[fe(e,kn(t)),En(t)],o=yt(t);return o.patternProperties[r]=n,o}function Hm(e,t){return L(t)?{..._r(e,t.$ref),[V]:t[V]}:t}function Bm(e,t){return ye(nn(e,t))}function Wm(e,t){return w(nn(e,t))}function nn(e,t){return t.map(n=>fe(e,n))}function fe(e,t){return re(t)?u(fe(e,N(t,[Y])),t):xt(t)?u(fe(e,N(t,[Ae])),t):qe(t)?u(Hm(e,t),t):Pe(t)?u(Um(e,t.items),t):at(t)?u(_m(e,t.items),t):Re(t)?u(Nm(e,t.target,t.parameters)):Oe(t)?u(Lm(e,t.parameters,t.returns),t):Ce(t)?u(Km(e,t.parameters,t.returns),t):v(t)?u(Dm(e,t.allOf),t):dt(t)?u(jm(e,t.items),t):j(t)?u(Gm(e,t.properties),t):mt(t)?u(Vm(e,t)):pe(t)?u(Bm(e,t.items||[]),t):y(t)?u(Wm(e,t.anyOf),t):t}function qm(e,t){return t in e?fe(e,e[t]):x()}function ui(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:qm(e,n)}),{})}var Lr=class{constructor(t){let n=ui(t),r=this.WithIdentifiers(n);this.$defs=r}Import(t,n){let r={...this.$defs,[t]:u(this.$defs[t],n)};return u({[m]:"Import",$defs:r,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:{...t[r],$id:r}}),{})}};function di(e){return new Lr(e)}function ci(e,t){return u({[m]:"Not",not:e},t)}function mi(e,t){return Ce(e)?ye(e.parameters,t):x()}var zm=0;function pi(e,t={}){D(t.$id)&&(t.$id=`T${zm++}`);let n=yt(e({[m]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[Ie]:"Recursive",...n},t)}function li(e,t){let n=C(e)?new globalThis.RegExp(e):e;return u({[m]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},t)}function Ym(e){return v(e)?e.allOf:y(e)?e.anyOf:pe(e)?e.items??[]:[]}function fi(e){return Ym(e)}function gi(e,t){return Ce(e)?u(e.returns,t):x(t)}var Kr=class{constructor(t){this.schema=t}Decode(t){return new Dr(this.schema,t)}},Dr=class{constructor(t,n){this.schema=t,this.decode=n}EncodeTransform(t,n){let i={Encode:s=>n[V].Encode(t(s)),Decode:s=>this.decode(n[V].Decode(s))};return{...n,[V]:i}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[V]:r}}Encode(t){return qe(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function Ii(e){return new Kr(e)}function hi(e={}){return u({[m]:e[m]??"Unsafe"},e)}function yi(e){return u({[m]:"Void",type:"void"},e)}var jr={};sr(jr,{Any:()=>Je,Argument:()=>es,Array:()=>St,AsyncIterator:()=>Tt,Awaited:()=>Ot,BigInt:()=>Pt,Boolean:()=>In,Capitalize:()=>zs,Composite:()=>Ss,Const:()=>Ts,Constructor:()=>bt,ConstructorParameters:()=>bs,Date:()=>Sn,Enum:()=>ws,Exclude:()=>kt,Extends:()=>Et,Extract:()=>Ft,Function:()=>Ne,Index:()=>Xe,InstanceType:()=>js,Instantiate:()=>Vs,Integer:()=>Hs,Intersect:()=>Q,Iterator:()=>Rt,KeyOf:()=>Ct,Literal:()=>b,Lowercase:()=>Ys,Mapped:()=>fs,Module:()=>di,Never:()=>x,Not:()=>ci,Null:()=>Tn,Number:()=>he,Object:()=>R,Omit:()=>et,Optional:()=>X,Parameters:()=>mi,Partial:()=>$t,Pick:()=>tt,Promise:()=>xn,Readonly:()=>se,ReadonlyOptional:()=>Cn,Record:()=>Mn,Recursive:()=>pi,Ref:()=>_e,RegExp:()=>li,Required:()=>vt,Rest:()=>fi,ReturnType:()=>gi,String:()=>ke,Symbol:()=>bn,TemplateLiteral:()=>hn,Transform:()=>Ii,Tuple:()=>ye,Uint8Array:()=>An,Uncapitalize:()=>Js,Undefined:()=>wn,Union:()=>w,Unknown:()=>Qe,Unsafe:()=>hi,Uppercase:()=>Xs,Void:()=>yi});var l=jr;var g=null;function Gr(e){g=e}import{readFileSync as Jm}from"fs";import{homedir as Xm}from"os";import{join as Qm}from"path";var rn,xi="claude-code",Fn={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium",approvalPolicy:"on-request"}};function Si(){if(rn!==void 0)return rn;try{let e=Jm(Qm(Xm(),".claude.json"),"utf-8");rn=JSON.parse(e).mcpServers??{}}catch{rn={}}return rn}var E={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",codexApprovalPolicy:"on-request",harnesses:{"claude-code":{...Fn["claude-code"]},codex:{...Fn.codex}}};function Ti(e){let t=e.defaultHarness??xi,n={};for(let[r,o]of Object.entries(Fn))n[r]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[r,o]of Object.entries(e.harnesses??{})){let s={...n[r]??{},...o};o.allowedModels!==void 0?s.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(s.allowedModels=void 0),n[r]=s}if(e.defaultModel!==void 0){let r=n[t]??{};n[t]={...r,defaultModel:e.harnesses?.[t]?.defaultModel??e.defaultModel,allowedModels:e.harnesses?.[t]?.allowedModels!==void 0?r.allowedModels:e.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${t}.defaultModel instead.`)}if(e.model!==void 0){let r=n.codex??{};n.codex={...r,defaultModel:e.harnesses?.codex?.defaultModel??e.model,allowedModels:e.harnesses?.codex?.allowedModels!==void 0?r.allowedModels:e.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(e.reasoningEffort!==void 0){let r=n.codex??{};n.codex={...r,reasoningEffort:e.harnesses?.codex?.reasoningEffort??e.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(e.codexApprovalPolicy!==void 0){let r=n.codex??{};n.codex={...r,approvalPolicy:e.harnesses?.codex?.approvalPolicy??e.codexApprovalPolicy},console.warn("[openclaw-code-agent] config.codexApprovalPolicy is deprecated; use harnesses.codex.approvalPolicy instead.")}if(e.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[r,o]of Object.entries(n))e.harnesses?.[r]?.allowedModels===void 0&&(n[r]={...o,allowedModels:void 0})}E={maxSessions:e.maxSessions??20,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??15,sessionGcAgeMinutes:e.sessionGcAgeMinutes??1440,maxPersistedSessions:e.maxPersistedSessions??1e4,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10,permissionMode:e.permissionMode??"plan",codexApprovalPolicy:e.codexApprovalPolicy??"on-request",planApproval:e.planApproval??"delegate",defaultHarness:t,harnesses:n,allowedModels:e.allowedModels}}function nt(){return E.defaultHarness??xi}function Vr(e){let t=Fn[e],n=E.harnesses[e];return{...t,...n,allowedModels:n?.allowedModels??t?.allowedModels}}function rt(e){return Vr(e).defaultModel}function bi(e){return E.harnesses[e]?.allowedModels??E.allowedModels}function Nt(e){return Vr(e).reasoningEffort}function gt(e){return Vr(e).approvalPolicy}function wi(e){if(e.messageChannel){let t=e.messageChannel.split("|");if(t.length>=3)return e.messageChannel;if(e.agentAccountId&&t.length>=2)return`${t[0]}|${e.agentAccountId}|${t.slice(1).join("|")}`;if(t.length===1&&e.chatId)return`${t[0]}|${e.chatId}`;if(t.length===1&&e.senderId)return`${t[0]}|${e.senderId}`}if(e.workspaceDir){let t=on(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function Ut(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);if(e?.messageChannel){let n=String(e.messageChannel);if(n.includes("|"))return n;if(e.chatId)return`${n}|${e.chatId}`;if(e.senderId)return`${n}|${e.senderId}`}return e?.channel&&e?.chatId?`${e.channel}|${e.chatId}`:e?.channel&&e?.senderId?`${e.channel}|${e.senderId}`:e?.id&&/^-?\d+$/.test(String(e.id))?`telegram|${e.id}`:E.fallbackChannel??"unknown"}function _t(e){return e?.messageThreadId??void 0}function on(e){let t=E.agentChannels;if(!t)return;let n=i=>i.replace(/\/+$/,""),r=n(e),o=Object.entries(t).sort((i,s)=>s[0].length-i[0].length);for(let[i,s]of o)if(r===n(i)||r.startsWith(n(i)+"/"))return s}function Ai(e){if(!e)return;let t=e.match(/:topic:(\d+)$/);return t?parseInt(t[1],10):void 0}function Lt(e){let{requestedResumeSessionId:t,activeSession:n,persistedSession:r}=e;return t?n?{resumeSessionId:t,clearedPersistedCodexResume:!1}:r?.harness==="codex"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:t,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}function ep(e){return e instanceof Error?e.message:String(e)}function tp(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function np(e,t){if(!t||t.length===0)return!0;if(!e)return!1;let n=e.toLowerCase();return t.some(r=>n.includes(r.toLowerCase()))}function Pi(e){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn by default \u2014 they stay open for follow-up messages via agent_respond. Set multi_turn_disabled: true for fire-and-forget sessions. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:l.Object({prompt:l.String({description:"The task prompt to execute"}),name:l.Optional(l.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:l.Optional(l.String({description:"Working directory (defaults to cwd)"})),model:l.Optional(l.String({description:"Model name to use"})),system_prompt:l.Optional(l.String({description:"Additional system prompt"})),allowed_tools:l.Optional(l.Array(l.String(),{description:"List of allowed tools"})),resume_session_id:l.Optional(l.String({description:"Session ID to resume (from a previous session's harnessSessionId). Continues the conversation from where it left off."})),fork_session:l.Optional(l.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),multi_turn_disabled:l.Optional(l.Boolean({description:"Disable multi-turn mode. By default sessions stay open for follow-up messages. Set to true for fire-and-forget sessions."})),permission_mode:l.Optional(l.Union([l.Literal("default"),l.Literal("plan"),l.Literal("acceptEdits"),l.Literal("bypassPermissions")],{description:"Permission mode for the session. This is the plugin's orchestration mode, not the Codex SDK approval policy. Defaults to plugin config (plan by default)."})),harness:l.Optional(l.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!tp(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};n.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${n.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${e.agentId}" will be used for origin routing instead.`);let r=n.workdir||e.workspaceDir||E.defaultWorkdir||process.cwd();if(!Zm(r))return{content:[{type:"text",text:`Error: Working directory does not exist: ${r}`}]};try{let o=n.harness??nt(),i=rt(o),s=n.model??i,c=n.model!==void 0;if(!s)return{content:[{type:"text",text:`Error: No default model configured for harness "${o}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${o}.defaultModel or pass model explicitly.`}]};let p=bi(o);if(p&&p.length>0&&!np(s,p))return{content:[{type:"text",text:c?`Error: Model "${s}" is not allowed. Permitted models: ${p.join(", ")}`:`Error: Default model "${s||"undefined"}" is not in allowedModels (${p.join(", ")}). Update your plugin config to set a compatible defaultModel.`}]};let f=n.resume_session_id,T=f?g.resolve(f):void 0,U=f?g.getPersistedSession(f):void 0;if(f){let we=g.resolveHarnessSessionId(f);if(!we)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${f}" to a session ID. Use agent_sessions to list available sessions.`}]};f=we}let{resumeSessionId:te,clearedPersistedCodexResume:ge}=Lt({requestedResumeSessionId:f,activeSession:T?{harnessSessionId:T.harnessSessionId}:void 0,persistedSession:U?{harness:U.harness}:void 0}),ae=wi(e),ee=Ut(e,ae||on(r)),z=e.sessionKey||void 0;!z&&e.agentId&&console.warn(`[agent_launch] ctx.sessionKey is not populated. ctx fields: agentId=${e.agentId}, messageChannel=${e.messageChannel}, agentAccountId=${e.agentAccountId}, workspaceDir=${e.workspaceDir}`);let _=g.spawn({prompt:n.prompt,name:n.name,workdir:r,model:s,reasoningEffort:Nt(o),systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:te,forkSession:te?n.fork_session:!1,multiTurn:!n.multi_turn_disabled,permissionMode:n.permission_mode,codexApprovalPolicy:o==="codex"?gt(o)??E.codexApprovalPolicy:void 0,originChannel:ee,originThreadId:Ai(z)??_t(e),originAgentId:e.agentId||void 0,originSessionKey:z,harness:o}),Be=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,be=["Session launched successfully.",` Name: ${_.name}`,` ID: ${_.id}`,` Dir: ${r}`,` Model: ${_.model??"default"}`,` Prompt: "${Be}"`];return o==="codex"&&be.push(` Codex approval policy: ${_.codexApprovalPolicy??gt(o)??E.codexApprovalPolicy}`),n.resume_session_id&&(be.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),ge&&be.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),be.push(n.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),be.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:be.join(`
2
- `)}]}}catch(o){let i=ep(o),s=i.includes("Max sessions")?"":`
1
+ var Ta=Object.defineProperty;var ir=(e,t)=>{for(var n in t)Ta(e,n,{get:t[n],enumerable:!0})};import{existsSync as tp}from"fs";var Z={};ir(Z,{HasPropertyKey:()=>cn,IsArray:()=>K,IsAsyncIterator:()=>ar,IsBigInt:()=>jt,IsBoolean:()=>Le,IsDate:()=>it,IsFunction:()=>ur,IsIterator:()=>dr,IsNull:()=>cr,IsNumber:()=>ue,IsObject:()=>A,IsRegExp:()=>Gt,IsString:()=>C,IsSymbol:()=>mr,IsUint8Array:()=>Ke,IsUndefined:()=>D});function cn(e,t){return t in e}function ar(e){return A(e)&&!K(e)&&!Ke(e)&&Symbol.asyncIterator in e}function K(e){return Array.isArray(e)}function jt(e){return typeof e=="bigint"}function Le(e){return typeof e=="boolean"}function it(e){return e instanceof globalThis.Date}function ur(e){return typeof e=="function"}function dr(e){return A(e)&&!K(e)&&!Ke(e)&&Symbol.iterator in e}function cr(e){return e===null}function ue(e){return typeof e=="number"}function A(e){return typeof e=="object"&&e!==null}function Gt(e){return e instanceof globalThis.RegExp}function C(e){return typeof e=="string"}function mr(e){return typeof e=="symbol"}function Ke(e){return e instanceof globalThis.Uint8Array}function D(e){return e===void 0}function ba(e){return e.map(t=>mn(t))}function wa(e){return new Date(e.getTime())}function Aa(e){return new Uint8Array(e)}function Pa(e){return new RegExp(e.source,e.flags)}function Ra(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=mn(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=mn(e[n]);return t}function mn(e){return K(e)?ba(e):it(e)?wa(e):Ke(e)?Aa(e):Gt(e)?Pa(e):A(e)?Ra(e):e}function $(e){return mn(e)}function xt(e,t){return t===void 0?$(e):$({...t,...e})}function oo(e){return e!==null&&typeof e=="object"}function so(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function io(e){return e===void 0}function ao(e){return typeof e=="number"}var pn;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(s,c){return e.ExactOptionalPropertyTypes?c in s:s[c]!==void 0}e.IsExactOptionalProperty=t;function n(s){let c=oo(s);return e.AllowArrayObject?c:c&&!so(s)}e.IsObjectLike=n;function r(s){return n(s)&&!(s instanceof Date)&&!(s instanceof Uint8Array)}e.IsRecordLike=r;function o(s){return e.AllowNaN?ao(s):Number.isFinite(s)}e.IsNumberLike=o;function i(s){let c=io(s);return e.AllowNullVoid?c||s===null:c}e.IsVoidLike=i})(pn||(pn={}));function Oa(e){return globalThis.Object.freeze(e).map(t=>Vt(t))}function Ca(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=Vt(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=Vt(e[n]);return globalThis.Object.freeze(t)}function Vt(e){return K(e)?Oa(e):it(e)?e:Ke(e)?e:Gt(e)?e:A(e)?Ca(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(pn.InstanceMode){case"freeze":return Vt(n);case"clone":return $(n);default:return n}}var q=class extends Error{constructor(t){super(t)}};var V=Symbol.for("TypeBox.Transform"),we=Symbol.for("TypeBox.Readonly"),J=Symbol.for("TypeBox.Optional"),Ie=Symbol.for("TypeBox.Hint"),m=Symbol.for("TypeBox.Kind");function St(e){return A(e)&&e[we]==="Readonly"}function oe(e){return A(e)&&e[J]==="Optional"}function pr(e){return h(e,"Any")}function lr(e){return h(e,"Argument")}function Ae(e){return h(e,"Array")}function at(e){return h(e,"AsyncIterator")}function ut(e){return h(e,"BigInt")}function De(e){return h(e,"Boolean")}function Pe(e){return h(e,"Computed")}function Re(e){return h(e,"Constructor")}function Ma(e){return h(e,"Date")}function Oe(e){return h(e,"Function")}function Ce(e){return h(e,"Integer")}function U(e){return h(e,"Intersect")}function dt(e){return h(e,"Iterator")}function h(e,t){return A(e)&&m in e&&e[m]===t}function ln(e){return Le(e)||ue(e)||C(e)}function de(e){return h(e,"Literal")}function ce(e){return h(e,"MappedKey")}function v(e){return h(e,"MappedResult")}function Be(e){return h(e,"Never")}function Ea(e){return h(e,"Not")}function Ht(e){return h(e,"Null")}function Me(e){return h(e,"Number")}function j(e){return h(e,"Object")}function ct(e){return h(e,"Promise")}function mt(e){return h(e,"Record")}function L(e){return h(e,"Ref")}function fr(e){return h(e,"RegExp")}function je(e){return h(e,"String")}function Bt(e){return h(e,"Symbol")}function me(e){return h(e,"TemplateLiteral")}function Fa(e){return h(e,"This")}function We(e){return A(e)&&V in e}function pe(e){return h(e,"Tuple")}function Wt(e){return h(e,"Undefined")}function y(e){return h(e,"Union")}function ka(e){return h(e,"Uint8Array")}function $a(e){return h(e,"Unknown")}function va(e){return h(e,"Unsafe")}function Na(e){return h(e,"Void")}function Ua(e){return A(e)&&m in e&&C(e[m])}function le(e){return pr(e)||lr(e)||Ae(e)||De(e)||ut(e)||at(e)||Pe(e)||Re(e)||Ma(e)||Oe(e)||Ce(e)||U(e)||dt(e)||de(e)||ce(e)||v(e)||Be(e)||Ea(e)||Ht(e)||Me(e)||j(e)||ct(e)||mt(e)||L(e)||fr(e)||je(e)||Bt(e)||me(e)||Fa(e)||pe(e)||Wt(e)||y(e)||ka(e)||$a(e)||va(e)||Na(e)||Ua(e)}var a={};ir(a,{IsAny:()=>po,IsArgument:()=>lo,IsArray:()=>fo,IsAsyncIterator:()=>go,IsBigInt:()=>Io,IsBoolean:()=>ho,IsComputed:()=>yo,IsConstructor:()=>xo,IsDate:()=>So,IsFunction:()=>To,IsImport:()=>Ga,IsInteger:()=>bo,IsIntersect:()=>wo,IsIterator:()=>Ao,IsKind:()=>Jo,IsKindOf:()=>I,IsLiteral:()=>zt,IsLiteralBoolean:()=>Va,IsLiteralNumber:()=>Ro,IsLiteralString:()=>Po,IsLiteralValue:()=>Oo,IsMappedKey:()=>Co,IsMappedResult:()=>Mo,IsNever:()=>Eo,IsNot:()=>Fo,IsNull:()=>ko,IsNumber:()=>$o,IsObject:()=>vo,IsOptional:()=>ja,IsPromise:()=>No,IsProperties:()=>fn,IsReadonly:()=>Da,IsRecord:()=>Uo,IsRecursive:()=>Ha,IsRef:()=>_o,IsRegExp:()=>Lo,IsSchema:()=>z,IsString:()=>Ko,IsSymbol:()=>Do,IsTemplateLiteral:()=>jo,IsThis:()=>Go,IsTransform:()=>Vo,IsTuple:()=>Ho,IsUint8Array:()=>Wo,IsUndefined:()=>Bo,IsUnion:()=>yr,IsUnionLiteral:()=>Ba,IsUnknown:()=>qo,IsUnsafe:()=>zo,IsVoid:()=>Yo,TypeGuardUnknownTypeError:()=>gr});var gr=class extends q{},_a=["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 uo(e){try{return new RegExp(e),!0}catch{return!1}}function Ir(e){if(!C(e))return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=7&&n<=13||n===27||n===127)return!1}return!0}function co(e){return hr(e)||z(e)}function qt(e){return D(e)||jt(e)}function M(e){return D(e)||ue(e)}function hr(e){return D(e)||Le(e)}function P(e){return D(e)||C(e)}function La(e){return D(e)||C(e)&&Ir(e)&&uo(e)}function Ka(e){return D(e)||C(e)&&Ir(e)}function mo(e){return D(e)||z(e)}function Da(e){return A(e)&&e[we]==="Readonly"}function ja(e){return A(e)&&e[J]==="Optional"}function po(e){return I(e,"Any")&&P(e.$id)}function lo(e){return I(e,"Argument")&&ue(e.index)}function fo(e){return I(e,"Array")&&e.type==="array"&&P(e.$id)&&z(e.items)&&M(e.minItems)&&M(e.maxItems)&&hr(e.uniqueItems)&&mo(e.contains)&&M(e.minContains)&&M(e.maxContains)}function go(e){return I(e,"AsyncIterator")&&e.type==="AsyncIterator"&&P(e.$id)&&z(e.items)}function Io(e){return I(e,"BigInt")&&e.type==="bigint"&&P(e.$id)&&qt(e.exclusiveMaximum)&&qt(e.exclusiveMinimum)&&qt(e.maximum)&&qt(e.minimum)&&qt(e.multipleOf)}function ho(e){return I(e,"Boolean")&&e.type==="boolean"&&P(e.$id)}function yo(e){return I(e,"Computed")&&C(e.target)&&K(e.parameters)&&e.parameters.every(t=>z(t))}function xo(e){return I(e,"Constructor")&&e.type==="Constructor"&&P(e.$id)&&K(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function So(e){return I(e,"Date")&&e.type==="Date"&&P(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function To(e){return I(e,"Function")&&e.type==="Function"&&P(e.$id)&&K(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function Ga(e){return I(e,"Import")&&cn(e,"$defs")&&A(e.$defs)&&fn(e.$defs)&&cn(e,"$ref")&&C(e.$ref)&&e.$ref in e.$defs}function bo(e){return I(e,"Integer")&&e.type==="integer"&&P(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function fn(e){return A(e)&&Object.entries(e).every(([t,n])=>Ir(t)&&z(n))}function wo(e){return I(e,"Intersect")&&!(C(e.type)&&e.type!=="object")&&K(e.allOf)&&e.allOf.every(t=>z(t)&&!Vo(t))&&P(e.type)&&(hr(e.unevaluatedProperties)||mo(e.unevaluatedProperties))&&P(e.$id)}function Ao(e){return I(e,"Iterator")&&e.type==="Iterator"&&P(e.$id)&&z(e.items)}function I(e,t){return A(e)&&m in e&&e[m]===t}function Po(e){return zt(e)&&C(e.const)}function Ro(e){return zt(e)&&ue(e.const)}function Va(e){return zt(e)&&Le(e.const)}function zt(e){return I(e,"Literal")&&P(e.$id)&&Oo(e.const)}function Oo(e){return Le(e)||ue(e)||C(e)}function Co(e){return I(e,"MappedKey")&&K(e.keys)&&e.keys.every(t=>ue(t)||C(t))}function Mo(e){return I(e,"MappedResult")&&fn(e.properties)}function Eo(e){return I(e,"Never")&&A(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Fo(e){return I(e,"Not")&&z(e.not)}function ko(e){return I(e,"Null")&&e.type==="null"&&P(e.$id)}function $o(e){return I(e,"Number")&&e.type==="number"&&P(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function vo(e){return I(e,"Object")&&e.type==="object"&&P(e.$id)&&fn(e.properties)&&co(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function No(e){return I(e,"Promise")&&e.type==="Promise"&&P(e.$id)&&z(e.item)}function Uo(e){return I(e,"Record")&&e.type==="object"&&P(e.$id)&&co(e.additionalProperties)&&A(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&uo(n[0])&&A(t.patternProperties)&&z(t.patternProperties[n[0]])})(e)}function Ha(e){return A(e)&&Ie in e&&e[Ie]==="Recursive"}function _o(e){return I(e,"Ref")&&P(e.$id)&&C(e.$ref)}function Lo(e){return I(e,"RegExp")&&P(e.$id)&&C(e.source)&&C(e.flags)&&M(e.maxLength)&&M(e.minLength)}function Ko(e){return I(e,"String")&&e.type==="string"&&P(e.$id)&&M(e.minLength)&&M(e.maxLength)&&La(e.pattern)&&Ka(e.format)}function Do(e){return I(e,"Symbol")&&e.type==="symbol"&&P(e.$id)}function jo(e){return I(e,"TemplateLiteral")&&e.type==="string"&&C(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Go(e){return I(e,"This")&&P(e.$id)&&C(e.$ref)}function Vo(e){return A(e)&&V in e}function Ho(e){return I(e,"Tuple")&&e.type==="array"&&P(e.$id)&&ue(e.minItems)&&ue(e.maxItems)&&e.minItems===e.maxItems&&(D(e.items)&&D(e.additionalItems)&&e.minItems===0||K(e.items)&&e.items.every(t=>z(t)))}function Bo(e){return I(e,"Undefined")&&e.type==="undefined"&&P(e.$id)}function Ba(e){return yr(e)&&e.anyOf.every(t=>Po(t)||Ro(t))}function yr(e){return I(e,"Union")&&P(e.$id)&&A(e)&&K(e.anyOf)&&e.anyOf.every(t=>z(t))}function Wo(e){return I(e,"Uint8Array")&&e.type==="Uint8Array"&&P(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function qo(e){return I(e,"Unknown")&&P(e.$id)}function zo(e){return I(e,"Unsafe")}function Yo(e){return I(e,"Void")&&e.type==="void"&&P(e.$id)}function Jo(e){return A(e)&&m in e&&C(e[m])&&!_a.includes(e[m])}function z(e){return A(e)&&(po(e)||lo(e)||fo(e)||ho(e)||Io(e)||go(e)||yo(e)||xo(e)||So(e)||To(e)||bo(e)||wo(e)||Ao(e)||zt(e)||Co(e)||Mo(e)||Eo(e)||Fo(e)||ko(e)||$o(e)||vo(e)||No(e)||Uo(e)||_o(e)||Lo(e)||Ko(e)||Do(e)||jo(e)||Go(e)||Ho(e)||Bo(e)||yr(e)||Wo(e)||qo(e)||zo(e)||Yo(e)||Jo(e))}var xr="(true|false)",Yt="(0|[1-9][0-9]*)",Sr="(.*)",Wa="(?!.*)",Af=`^${xr}$`,qe=`^${Yt}$`,ze=`^${Sr}$`,Xo=`^${Wa}$`;function Qo(e,t){return e.includes(t)}function Zo(e){return[...new Set(e)]}function qa(e,t){return e.filter(n=>t.includes(n))}function za(e,t){return e.reduce((n,r)=>qa(n,r),t)}function es(e){return e.length===1?e[0]:e.length>1?za(e.slice(1),e[0]):[]}function ts(e){let t=[];for(let n of e)t.push(...n);return t}function Ye(e){return u({[m]:"Any"},e)}function Tt(e,t){return u({[m]:"Array",type:"array",items:e},t)}function ns(e){return u({[m]:"Argument",index:e})}function bt(e,t){return u({[m]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function E(e,t,n){return u({[m]:"Computed",target:e,parameters:t},n)}function Ya(e,t){let{[t]:n,...r}=e;return r}function _(e,t){return t.reduce((n,r)=>Ya(n,r),e)}function x(e){return u({[m]:"Never",not:{}},e)}function S(e){return u({[m]:"MappedResult",properties:e})}function wt(e,t,n){return u({[m]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function ve(e,t,n){return u({[m]:"Function",type:"Function",parameters:e,returns:t},n)}function Jt(e,t){return u({[m]:"Union",anyOf:e},t)}function Ja(e){return e.some(t=>oe(t))}function rs(e){return e.map(t=>oe(t)?Xa(t):t)}function Xa(e){return _(e,[J])}function Qa(e,t){return Ja(e)?ee(Jt(rs(e),t)):Jt(rs(e),t)}function Ne(e,t){return e.length===1?u(e[0],t):e.length===0?x(t):Qa(e,t)}function w(e,t){return e.length===0?x(t):e.length===1?u(e[0],t):Jt(e,t)}var gn=class extends q{};function Za(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function Tr(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function Ve(e,t){return Tr(e,t,"(")}function Xt(e,t){return Tr(e,t,")")}function os(e,t){return Tr(e,t,"|")}function eu(e){if(!(Ve(e,0)&&Xt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(Ve(e,n)&&(t+=1),Xt(e,n)&&(t-=1),t===0&&n!==e.length-1)return!1;return!0}function tu(e){return e.slice(1,e.length-1)}function nu(e){let t=0;for(let n=0;n<e.length;n++)if(Ve(e,n)&&(t+=1),Xt(e,n)&&(t-=1),os(e,n)&&t===0)return!0;return!1}function ru(e){for(let t=0;t<e.length;t++)if(Ve(e,t))return!0;return!1}function ou(e){let[t,n]=[0,0],r=[];for(let i=0;i<e.length;i++)if(Ve(e,i)&&(t+=1),Xt(e,i)&&(t-=1),os(e,i)&&t===0){let s=e.slice(n,i);s.length>0&&r.push(At(s)),n=i+1}let o=e.slice(n);return o.length>0&&r.push(At(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function su(e){function t(o,i){if(!Ve(o,i))throw new gn("TemplateLiteralParser: Index must point to open parens");let s=0;for(let c=i;c<o.length;c++)if(Ve(o,c)&&(s+=1),Xt(o,c)&&(s-=1),s===0)return[i,c];throw new gn("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,i){for(let s=i;s<o.length;s++)if(Ve(o,s))return[i,s];return[i,o.length]}let r=[];for(let o=0;o<e.length;o++)if(Ve(e,o)){let[i,s]=t(e,o),c=e.slice(i,s+1);r.push(At(c)),o=s}else{let[i,s]=n(e,o),c=e.slice(i,s);c.length>0&&r.push(At(c)),o=s-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function At(e){return eu(e)?At(tu(e)):nu(e)?ou(e):ru(e)?su(e):{type:"const",const:Za(e)}}function Pt(e){return At(e.slice(1,e.length-1))}var br=class extends q{};function iu(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 au(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 uu(e){return e.type==="const"&&e.const===".*"}function pt(e){return iu(e)||uu(e)?!1:au(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 br("Unknown expression type")})()}function ss(e){let t=Pt(e.pattern);return pt(t)}var wr=class extends q{};function*is(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let n of is(e.slice(1)))yield`${t}${n}`}function*du(e){return yield*is(e.expr.map(t=>[...Qt(t)]))}function*cu(e){for(let t of e.expr)yield*Qt(t)}function*mu(e){return yield e.const}function*Qt(e){return e.type==="and"?yield*du(e):e.type==="or"?yield*cu(e):e.type==="const"?yield*mu(e):(()=>{throw new wr("Unknown expression")})()}function In(e){let t=Pt(e.pattern);return pt(t)?[...Qt(t)]:[]}function T(e,t){return u({[m]:"Literal",const:e,type:typeof e},t)}function hn(e){return u({[m]:"Boolean",type:"boolean"},e)}function Rt(e){return u({[m]:"BigInt",type:"bigint"},e)}function he(e){return u({[m]:"Number",type:"number"},e)}function Ee(e){return u({[m]:"String",type:"string"},e)}function*pu(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield hn():t==="number"?yield he():t==="bigint"?yield Rt():t==="string"?yield Ee():yield(()=>{let n=t.split("|").map(r=>T(r.trim()));return n.length===0?x():n.length===1?n[0]:Ne(n)})()}function*lu(e){if(e[1]!=="{"){let t=T("$"),n=Ar(e.slice(1));return yield*[t,...n]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let n=pu(e.slice(2,t)),r=Ar(e.slice(t+1));return yield*[...n,...r]}yield T(e)}function*Ar(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=T(e.slice(0,t)),r=lu(e.slice(t));return yield*[n,...r]}yield T(e)}function as(e){return[...Ar(e)]}var Pr=class extends q{};function fu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function us(e,t){return me(e)?e.pattern.slice(1,e.pattern.length-1):y(e)?`(${e.anyOf.map(n=>us(n,t)).join("|")})`:Me(e)?`${t}${Yt}`:Ce(e)?`${t}${Yt}`:ut(e)?`${t}${Yt}`:je(e)?`${t}${Sr}`:de(e)?`${t}${fu(e.const.toString())}`:De(e)?`${t}${xr}`:(()=>{throw new Pr(`Unexpected Kind '${e[m]}'`)})()}function Rr(e){return`^${e.map(t=>us(t,"")).join("")}$`}function lt(e){let n=In(e).map(r=>T(r));return Ne(n)}function yn(e,t){let n=C(e)?Rr(as(e)):Rr(e);return u({[m]:"TemplateLiteral",type:"string",pattern:n},t)}function gu(e){return In(e).map(n=>n.toString())}function Iu(e){let t=[];for(let n of e)t.push(...se(n));return t}function hu(e){return[e.toString()]}function se(e){return[...new Set(me(e)?gu(e):y(e)?Iu(e.anyOf):de(e)?hu(e.const):Me(e)?["[number]"]:Ce(e)?["[number]"]:[])]}function yu(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=Je(e,se(t[o]),n);return r}function xu(e,t,n){return yu(e,t.properties,n)}function ds(e,t,n){let r=xu(e,t,n);return S(r)}function ms(e,t){return e.map(n=>ps(n,t))}function Su(e){return e.filter(t=>!Be(t))}function Tu(e,t){return xn(Su(ms(e,t)))}function bu(e){return e.some(t=>Be(t))?[]:e}function wu(e,t){return Ne(bu(ms(e,t)))}function Au(e,t){return t in e?e[t]:t==="[number]"?Ne(e):x()}function Pu(e,t){return t==="[number]"?e:x()}function Ru(e,t){return t in e?e[t]:x()}function ps(e,t){return U(e)?Tu(e.allOf,t):y(e)?wu(e.anyOf,t):pe(e)?Au(e.items??[],t):Ae(e)?Pu(e.items,t):j(e)?Ru(e.properties,t):x()}function Or(e,t){return t.map(n=>ps(e,n))}function cs(e,t){return Ne(Or(e,t))}function Je(e,t,n){if(L(e)||L(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!le(e)||!le(t))throw new q(r);return E("Index",[e,t])}return v(t)?ds(e,t,n):ce(t)?ls(e,t,n):u(le(t)?cs(e,se(t)):cs(e,t),n)}function Ou(e,t,n){return{[t]:Je(e,[t],$(n))}}function Cu(e,t,n){return t.reduce((r,o)=>({...r,...Ou(e,o,n)}),{})}function Mu(e,t,n){return Cu(e,t.keys,n)}function ls(e,t,n){let r=Mu(e,t,n);return S(r)}function Ot(e,t){return u({[m]:"Iterator",type:"Iterator",items:e},t)}function Eu(e){return globalThis.Object.keys(e).filter(t=>!oe(e[t]))}function Fu(e,t){let n=Eu(e),r=n.length>0?{[m]:"Object",type:"object",required:n,properties:e}:{[m]:"Object",type:"object",properties:e};return u(r,t)}var R=Fu;function Sn(e,t){return u({[m]:"Promise",type:"Promise",item:e},t)}function ku(e){return u(_(e,[we]))}function $u(e){return u({...e,[we]:"Readonly"})}function vu(e,t){return t===!1?ku(e):$u(e)}function ie(e,t){let n=t??!0;return v(e)?fs(e,n):vu(e,n)}function Nu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ie(e[r],t);return n}function Uu(e,t){return Nu(e.properties,t)}function fs(e,t){let n=Uu(e,t);return S(n)}function ye(e,t){return u(e.length>0?{[m]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[m]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function gs(e,t){return e in t?xe(e,t[e]):S(t)}function _u(e){return{[e]:T(e)}}function Lu(e){let t={};for(let n of e)t[n]=T(n);return t}function Ku(e,t){return Qo(t,e)?_u(e):Lu(t)}function Du(e,t){let n=Ku(e,t);return gs(e,n)}function Zt(e,t){return t.map(n=>xe(e,n))}function ju(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=xe(e,t[r]);return n}function xe(e,t){let n={...t};return oe(t)?ee(xe(e,_(t,[J]))):St(t)?ie(xe(e,_(t,[we]))):v(t)?gs(e,t.properties):ce(t)?Du(e,t.keys):Re(t)?wt(Zt(e,t.parameters),xe(e,t.returns),n):Oe(t)?ve(Zt(e,t.parameters),xe(e,t.returns),n):at(t)?bt(xe(e,t.items),n):dt(t)?Ot(xe(e,t.items),n):U(t)?te(Zt(e,t.allOf),n):y(t)?w(Zt(e,t.anyOf),n):pe(t)?ye(Zt(e,t.items??[]),n):j(t)?R(ju(e,t.properties),n):Ae(t)?Tt(xe(e,t.items),n):ct(t)?Sn(xe(e,t.item),n):t}function Gu(e,t){let n={};for(let r of e)n[r]=xe(r,t);return n}function Is(e,t,n){let r=le(e)?se(e):e,o=t({[m]:"MappedKey",keys:r}),i=Gu(r,o);return R(i,n)}function Vu(e){return u(_(e,[J]))}function Hu(e){return u({...e,[J]:"Optional"})}function Bu(e,t){return t===!1?Vu(e):Hu(e)}function ee(e,t){let n=t??!0;return v(e)?hs(e,n):Bu(e,n)}function Wu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ee(e[r],t);return n}function qu(e,t){return Wu(e.properties,t)}function hs(e,t){let n=qu(e,t);return S(n)}function en(e,t={}){let n=e.every(o=>j(o)),r=le(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||le(t.unevaluatedProperties)||n?{...r,[m]:"Intersect",type:"object",allOf:e}:{...r,[m]:"Intersect",allOf:e},t)}function zu(e){return e.every(t=>oe(t))}function Yu(e){return _(e,[J])}function ys(e){return e.map(t=>oe(t)?Yu(t):t)}function Ju(e,t){return zu(e)?ee(en(ys(e),t)):en(ys(e),t)}function xn(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>We(n)))throw new Error("Cannot intersect transform types");return Ju(e,t)}function te(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return x(t);if(e.some(n=>We(n)))throw new Error("Cannot intersect transform types");return en(e,t)}function Ue(...e){let[t,n]=typeof e[0]=="string"?[e[0],e[1]]:[e[0].$id,e[1]];if(typeof t!="string")throw new q("Ref: $ref must be a string");return u({[m]:"Ref",$ref:t},n)}function Xu(e,t){return E("Awaited",[E(e,t)])}function Qu(e){return E("Awaited",[Ue(e)])}function Zu(e){return te(xs(e))}function ed(e){return w(xs(e))}function td(e){return Ct(e)}function xs(e){return e.map(t=>Ct(t))}function Ct(e,t){return u(Pe(e)?Xu(e.target,e.parameters):U(e)?Zu(e.allOf):y(e)?ed(e.anyOf):ct(e)?td(e.item):L(e)?Qu(e.$ref):e,t)}function Ss(e){let t=[];for(let n of e)t.push(tn(n));return t}function nd(e){let t=Ss(e);return ts(t)}function rd(e){let t=Ss(e);return es(t)}function od(e){return e.map((t,n)=>n.toString())}function sd(e){return["[number]"]}function id(e){return globalThis.Object.getOwnPropertyNames(e)}function ad(e){return ud?globalThis.Object.getOwnPropertyNames(e).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function tn(e){return U(e)?nd(e.allOf):y(e)?rd(e.anyOf):pe(e)?od(e.items??[]):Ae(e)?sd(e.items):j(e)?id(e.properties):mt(e)?ad(e.patternProperties):[]}var ud=!1;function dd(e,t){return E("KeyOf",[E(e,t)])}function cd(e){return E("KeyOf",[Ue(e)])}function md(e,t){let n=tn(e),r=pd(n),o=Ne(r);return u(o,t)}function pd(e){return e.map(t=>t==="[number]"?he():T(t))}function Mt(e,t){return Pe(e)?dd(e.target,e.parameters):L(e)?cd(e.$ref):v(e)?Ts(e,t):md(e,t)}function ld(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Mt(e[r],$(t));return n}function fd(e,t){return ld(e.properties,t)}function Ts(e,t){let n=fd(e,t);return S(n)}function gd(e){let t=[];for(let n of e)t.push(...tn(n));return Zo(t)}function Id(e){return e.filter(t=>!Be(t))}function hd(e,t){let n=[];for(let r of e)n.push(...Or(r,[t]));return Id(n)}function yd(e,t){let n={};for(let r of t)n[r]=xn(hd(e,r));return n}function bs(e,t){let n=gd(e),r=yd(e,n);return R(r,t)}function Tn(e){return u({[m]:"Date",type:"Date"},e)}function bn(e){return u({[m]:"Null",type:"null"},e)}function wn(e){return u({[m]:"Symbol",type:"symbol"},e)}function An(e){return u({[m]:"Undefined",type:"undefined"},e)}function Pn(e){return u({[m]:"Uint8Array",type:"Uint8Array"},e)}function Xe(e){return u({[m]:"Unknown"},e)}function xd(e){return e.map(t=>Cr(t,!1))}function Sd(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ie(Cr(e[n],!1));return t}function Rn(e,t){return t===!0?e:ie(e)}function Cr(e,t){return ar(e)?Rn(Ye(),t):dr(e)?Rn(Ye(),t):K(e)?ie(ye(xd(e))):Ke(e)?Pn():it(e)?Tn():A(e)?Rn(R(Sd(e)),t):ur(e)?Rn(ve([],Xe()),t):D(e)?An():cr(e)?bn():mr(e)?wn():jt(e)?Rt():ue(e)?T(e):Le(e)?T(e):C(e)?T(e):R({})}function ws(e,t){return u(Cr(e,!0),t)}function As(e,t){return Re(e)?ye(e.parameters,t):x(t)}function Ps(e,t){if(D(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(i=>isNaN(i)).map(i=>e[i]),o=[...new Set(n)].map(i=>T(i));return w(o,{...t,[Ie]:"Enum"})}var Er=class extends q{},d;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(d||(d={}));function Se(e){return e===d.False?e:d.True}function Et(e){throw new Er(e)}function H(e){return a.IsNever(e)||a.IsIntersect(e)||a.IsUnion(e)||a.IsUnknown(e)||a.IsAny(e)}function B(e,t){return a.IsNever(t)?ks(e,t):a.IsIntersect(t)?On(e,t):a.IsUnion(t)?vr(e,t):a.IsUnknown(t)?Us(e,t):a.IsAny(t)?$r(e,t):Et("StructuralRight")}function $r(e,t){return d.True}function Td(e,t){return a.IsIntersect(t)?On(e,t):a.IsUnion(t)&&t.anyOf.some(n=>a.IsAny(n)||a.IsUnknown(n))?d.True:a.IsUnion(t)?d.Union:a.IsUnknown(t)||a.IsAny(t)?d.True:d.Union}function bd(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)?d.True:d.False}function wd(e,t){return a.IsObject(t)&&Cn(t)?d.True:H(t)?B(e,t):a.IsArray(t)?Se(O(e.items,t.items)):d.False}function Ad(e,t){return H(t)?B(e,t):a.IsAsyncIterator(t)?Se(O(e.items,t.items)):d.False}function Pd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsBigInt(t)?d.True:d.False}function Es(e,t){return a.IsLiteralBoolean(e)||a.IsBoolean(e)?d.True:d.False}function Rd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsBoolean(t)?d.True:d.False}function Od(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsConstructor(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>Se(O(t.parameters[r],n))===d.True)?Se(O(e.returns,t.returns)):d.False:d.False}function Cd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsDate(t)?d.True:d.False}function Md(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsFunction(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>Se(O(t.parameters[r],n))===d.True)?Se(O(e.returns,t.returns)):d.False:d.False}function Fs(e,t){return a.IsLiteral(e)&&Z.IsNumber(e.const)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function Ed(e,t){return a.IsInteger(t)||a.IsNumber(t)?d.True:H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):d.False}function On(e,t){return t.allOf.every(n=>O(e,n)===d.True)?d.True:d.False}function Fd(e,t){return e.allOf.some(n=>O(n,t)===d.True)?d.True:d.False}function kd(e,t){return H(t)?B(e,t):a.IsIterator(t)?Se(O(e.items,t.items)):d.False}function $d(e,t){return a.IsLiteral(t)&&t.const===e.const?d.True:H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsString(t)?Ns(e,t):a.IsNumber(t)?$s(e,t):a.IsInteger(t)?Fs(e,t):a.IsBoolean(t)?Es(e,t):d.False}function ks(e,t){return d.False}function vd(e,t){return d.True}function Rs(e){let[t,n]=[e,0];for(;a.IsNot(t);)t=t.not,n+=1;return n%2===0?t:Xe()}function Nd(e,t){return a.IsNot(e)?O(Rs(e),t):a.IsNot(t)?O(e,Rs(t)):Et("Invalid fallthrough for Not")}function Ud(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsNull(t)?d.True:d.False}function $s(e,t){return a.IsLiteralNumber(e)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function _d(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsInteger(t)||a.IsNumber(t)?d.True:d.False}function ae(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function Os(e){return Cn(e)}function Cs(e){return ae(e,0)||ae(e,1)&&"description"in e.properties&&a.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(a.IsString(e.properties.description.anyOf[0])&&a.IsUndefined(e.properties.description.anyOf[1])||a.IsString(e.properties.description.anyOf[1])&&a.IsUndefined(e.properties.description.anyOf[0]))}function Mr(e){return ae(e,0)}function Ms(e){return ae(e,0)}function Ld(e){return ae(e,0)}function Kd(e){return ae(e,0)}function Dd(e){return Cn(e)}function jd(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&Se(O(e.properties.length,t))===d.True}function Gd(e){return ae(e,0)}function Cn(e){let t=he();return ae(e,0)||ae(e,1)&&"length"in e.properties&&Se(O(e.properties.length,t))===d.True}function Vd(e){let t=ve([Ye()],Ye());return ae(e,0)||ae(e,1)&&"then"in e.properties&&Se(O(e.properties.then,t))===d.True}function vs(e,t){return O(e,t)===d.False||a.IsOptional(e)&&!a.IsOptional(t)?d.False:d.True}function ne(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)||a.IsLiteralString(e)&&Os(t)||a.IsLiteralNumber(e)&&Mr(t)||a.IsLiteralBoolean(e)&&Ms(t)||a.IsSymbol(e)&&Cs(t)||a.IsBigInt(e)&&Ld(t)||a.IsString(e)&&Os(t)||a.IsSymbol(e)&&Cs(t)||a.IsNumber(e)&&Mr(t)||a.IsInteger(e)&&Mr(t)||a.IsBoolean(e)&&Ms(t)||a.IsUint8Array(e)&&Dd(t)||a.IsDate(e)&&Kd(t)||a.IsConstructor(e)&&Gd(t)||a.IsFunction(e)&&jd(t)?d.True:a.IsRecord(e)&&a.IsString(Fr(e))?t[Ie]==="Record"?d.True:d.False:a.IsRecord(e)&&a.IsNumber(Fr(e))&&ae(t,0)?d.True:d.False}function Hd(e,t){return H(t)?B(e,t):a.IsRecord(t)?Te(e,t):a.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!a.IsOptional(t.properties[n]))return d.False;if(a.IsOptional(t.properties[n]))return d.True;if(vs(e.properties[n],t.properties[n])===d.False)return d.False}return d.True})():d.False}function Bd(e,t){return H(t)?B(e,t):a.IsObject(t)&&Vd(t)?d.True:a.IsPromise(t)?Se(O(e.item,t.item)):d.False}function Fr(e){return qe in e.patternProperties?he():ze in e.patternProperties?Ee():Et("Unknown record key pattern")}function kr(e){return qe in e.patternProperties?e.patternProperties[qe]:ze in e.patternProperties?e.patternProperties[ze]:Et("Unable to get record value schema")}function Te(e,t){let[n,r]=[Fr(t),kr(t)];return a.IsLiteralString(e)&&a.IsNumber(n)&&Se(O(e,r))===d.True?d.True:a.IsUint8Array(e)&&a.IsNumber(n)||a.IsString(e)&&a.IsNumber(n)||a.IsArray(e)&&a.IsNumber(n)?O(e,r):a.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(vs(r,e.properties[o])===d.False)return d.False;return d.True})():d.False}function Wd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?O(kr(e),kr(t)):d.False}function qd(e,t){let n=a.IsRegExp(e)?Ee():e,r=a.IsRegExp(t)?Ee():t;return O(n,r)}function Ns(e,t){return a.IsLiteral(e)&&Z.IsString(e.const)||a.IsString(e)?d.True:d.False}function zd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsString(t)?d.True:d.False}function Yd(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsSymbol(t)?d.True:d.False}function Jd(e,t){return a.IsTemplateLiteral(e)?O(lt(e),t):a.IsTemplateLiteral(t)?O(e,lt(t)):Et("Invalid fallthrough for TemplateLiteral")}function Xd(e,t){return a.IsArray(t)&&e.items!==void 0&&e.items.every(n=>O(n,t.items)===d.True)}function Qd(e,t){return a.IsNever(e)?d.True:a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:d.False}function Zd(e,t){return H(t)?B(e,t):a.IsObject(t)&&Cn(t)||a.IsArray(t)&&Xd(e,t)?d.True:a.IsTuple(t)?Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||!Z.IsUndefined(e.items)&&Z.IsUndefined(t.items)?d.False:Z.IsUndefined(e.items)&&!Z.IsUndefined(t.items)||e.items.every((n,r)=>O(n,t.items[r])===d.True)?d.True:d.False:d.False}function ec(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsUint8Array(t)?d.True:d.False}function tc(e,t){return H(t)?B(e,t):a.IsObject(t)?ne(e,t):a.IsRecord(t)?Te(e,t):a.IsVoid(t)?oc(e,t):a.IsUndefined(t)?d.True:d.False}function vr(e,t){return t.anyOf.some(n=>O(e,n)===d.True)?d.True:d.False}function nc(e,t){return e.anyOf.every(n=>O(n,t)===d.True)?d.True:d.False}function Us(e,t){return d.True}function rc(e,t){return a.IsNever(t)?ks(e,t):a.IsIntersect(t)?On(e,t):a.IsUnion(t)?vr(e,t):a.IsAny(t)?$r(e,t):a.IsString(t)?Ns(e,t):a.IsNumber(t)?$s(e,t):a.IsInteger(t)?Fs(e,t):a.IsBoolean(t)?Es(e,t):a.IsArray(t)?bd(e,t):a.IsTuple(t)?Qd(e,t):a.IsObject(t)?ne(e,t):a.IsUnknown(t)?d.True:d.False}function oc(e,t){return a.IsUndefined(e)||a.IsUndefined(e)?d.True:d.False}function sc(e,t){return a.IsIntersect(t)?On(e,t):a.IsUnion(t)?vr(e,t):a.IsUnknown(t)?Us(e,t):a.IsAny(t)?$r(e,t):a.IsObject(t)?ne(e,t):a.IsVoid(t)?d.True:d.False}function O(e,t){return a.IsTemplateLiteral(e)||a.IsTemplateLiteral(t)?Jd(e,t):a.IsRegExp(e)||a.IsRegExp(t)?qd(e,t):a.IsNot(e)||a.IsNot(t)?Nd(e,t):a.IsAny(e)?Td(e,t):a.IsArray(e)?wd(e,t):a.IsBigInt(e)?Pd(e,t):a.IsBoolean(e)?Rd(e,t):a.IsAsyncIterator(e)?Ad(e,t):a.IsConstructor(e)?Od(e,t):a.IsDate(e)?Cd(e,t):a.IsFunction(e)?Md(e,t):a.IsInteger(e)?Ed(e,t):a.IsIntersect(e)?Fd(e,t):a.IsIterator(e)?kd(e,t):a.IsLiteral(e)?$d(e,t):a.IsNever(e)?vd(e,t):a.IsNull(e)?Ud(e,t):a.IsNumber(e)?_d(e,t):a.IsObject(e)?Hd(e,t):a.IsRecord(e)?Wd(e,t):a.IsString(e)?zd(e,t):a.IsSymbol(e)?Yd(e,t):a.IsTuple(e)?Zd(e,t):a.IsPromise(e)?Bd(e,t):a.IsUint8Array(e)?ec(e,t):a.IsUndefined(e)?tc(e,t):a.IsUnion(e)?nc(e,t):a.IsUnknown(e)?rc(e,t):a.IsVoid(e)?sc(e,t):Et(`Unknown left type operand '${e[m]}'`)}function Qe(e,t){return O(e,t)}function ic(e,t,n,r,o){let i={};for(let s of globalThis.Object.getOwnPropertyNames(e))i[s]=Ft(e[s],t,n,r,$(o));return i}function ac(e,t,n,r,o){return ic(e.properties,t,n,r,o)}function _s(e,t,n,r,o){let i=ac(e,t,n,r,o);return S(i)}function uc(e,t,n,r){let o=Qe(e,t);return o===d.Union?w([n,r]):o===d.True?n:r}function Ft(e,t,n,r,o){return v(e)?_s(e,t,n,r,o):ce(e)?u(Ls(e,t,n,r,o)):u(uc(e,t,n,r),o)}function dc(e,t,n,r,o){return{[e]:Ft(T(e),t,n,r,$(o))}}function cc(e,t,n,r,o){return e.reduce((i,s)=>({...i,...dc(s,t,n,r,o)}),{})}function mc(e,t,n,r,o){return cc(e.keys,t,n,r,o)}function Ls(e,t,n,r,o){let i=mc(e,t,n,r,o);return S(i)}function Ks(e,t){return kt(lt(e),t)}function pc(e,t){let n=e.filter(r=>Qe(r,t)===d.False);return n.length===1?n[0]:w(n)}function kt(e,t,n={}){return me(e)?u(Ks(e,t),n):v(e)?u(Ds(e,t),n):u(y(e)?pc(e.anyOf,t):Qe(e,t)!==d.False?x():e,n)}function lc(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=kt(e[r],t);return n}function fc(e,t){return lc(e.properties,t)}function Ds(e,t){let n=fc(e,t);return S(n)}function js(e,t){return $t(lt(e),t)}function gc(e,t){let n=e.filter(r=>Qe(r,t)!==d.False);return n.length===1?n[0]:w(n)}function $t(e,t,n){return me(e)?u(js(e,t),n):v(e)?u(Gs(e,t),n):u(y(e)?gc(e.anyOf,t):Qe(e,t)!==d.False?e:x(),n)}function Ic(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=$t(e[r],t);return n}function hc(e,t){return Ic(e.properties,t)}function Gs(e,t){let n=hc(e,t);return S(n)}function Vs(e,t){return Re(e)?u(e.returns,t):x(t)}function Mn(e){return ie(ee(e))}function ft(e,t,n){return u({[m]:"Record",type:"object",patternProperties:{[e]:t}},n)}function Nr(e,t,n){let r={};for(let o of e)r[o]=t;return R(r,{...n,[Ie]:"Record"})}function yc(e,t,n){return ss(e)?Nr(se(e),t,n):ft(e.pattern,t,n)}function xc(e,t,n){return Nr(se(w(e)),t,n)}function Sc(e,t,n){return Nr([e.toString()],t,n)}function Tc(e,t,n){return ft(e.source,t,n)}function bc(e,t,n){let r=D(e.pattern)?ze:e.pattern;return ft(r,t,n)}function wc(e,t,n){return ft(ze,t,n)}function Ac(e,t,n){return ft(Xo,t,n)}function Pc(e,t,n){return R({true:t,false:t},n)}function Rc(e,t,n){return ft(qe,t,n)}function Oc(e,t,n){return ft(qe,t,n)}function En(e,t,n={}){return y(e)?xc(e.anyOf,t,n):me(e)?yc(e,t,n):de(e)?Sc(e.const,t,n):De(e)?Pc(e,t,n):Ce(e)?Rc(e,t,n):Me(e)?Oc(e,t,n):fr(e)?Tc(e,t,n):je(e)?bc(e,t,n):pr(e)?wc(e,t,n):Be(e)?Ac(e,t,n):x(n)}function Fn(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function Hs(e){let t=Fn(e);return t===ze?Ee():t===qe?he():Ee({pattern:t})}function kn(e){return e.patternProperties[Fn(e)]}function Cc(e,t){return t.parameters=nn(e,t.parameters),t.returns=Fe(e,t.returns),t}function Mc(e,t){return t.parameters=nn(e,t.parameters),t.returns=Fe(e,t.returns),t}function Ec(e,t){return t.allOf=nn(e,t.allOf),t}function Fc(e,t){return t.anyOf=nn(e,t.anyOf),t}function kc(e,t){return D(t.items)||(t.items=nn(e,t.items)),t}function $c(e,t){return t.items=Fe(e,t.items),t}function vc(e,t){return t.items=Fe(e,t.items),t}function Nc(e,t){return t.items=Fe(e,t.items),t}function Uc(e,t){return t.item=Fe(e,t.item),t}function _c(e,t){let n=jc(e,t.properties);return{...t,...R(n)}}function Lc(e,t){let n=Fe(e,Hs(t)),r=Fe(e,kn(t)),o=En(n,r);return{...t,...o}}function Kc(e,t){return t.index in e?e[t.index]:Xe()}function Dc(e,t){let n=St(t),r=oe(t),o=Fe(e,t);return n&&r?Mn(o):n&&!r?ie(o):!n&&r?ee(o):o}function jc(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:Dc(e,t[r])}),{})}function nn(e,t){return t.map(n=>Fe(e,n))}function Fe(e,t){return Re(t)?Cc(e,t):Oe(t)?Mc(e,t):U(t)?Ec(e,t):y(t)?Fc(e,t):pe(t)?kc(e,t):Ae(t)?$c(e,t):at(t)?vc(e,t):dt(t)?Nc(e,t):ct(t)?Uc(e,t):j(t)?_c(e,t):mt(t)?Lc(e,t):lr(t)?Kc(e,t):t}function Bs(e,t){return Fe(t,xt(e))}function Ws(e){return u({[m]:"Integer",type:"integer"},e)}function Gc(e,t,n){return{[e]:ke(T(e),t,$(n))}}function Vc(e,t,n){return e.reduce((o,i)=>({...o,...Gc(i,t,n)}),{})}function Hc(e,t,n){return Vc(e.keys,t,n)}function qs(e,t,n){let r=Hc(e,t,n);return S(r)}function Bc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function Wc(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function qc(e){return e.toUpperCase()}function zc(e){return e.toLowerCase()}function Yc(e,t,n){let r=Pt(e.pattern);if(!pt(r))return{...e,pattern:zs(e.pattern,t)};let s=[...Qt(r)].map(f=>T(f)),c=Ys(s,t),p=w(c);return yn([p],n)}function zs(e,t){return typeof e=="string"?t==="Uncapitalize"?Bc(e):t==="Capitalize"?Wc(e):t==="Uppercase"?qc(e):t==="Lowercase"?zc(e):e:e.toString()}function Ys(e,t){return e.map(n=>ke(n,t))}function ke(e,t,n={}){return ce(e)?qs(e,t,n):me(e)?Yc(e,t,n):y(e)?w(Ys(e.anyOf,t),n):de(e)?T(zs(e.const,t),n):u(e,n)}function Js(e,t={}){return ke(e,"Capitalize",t)}function Xs(e,t={}){return ke(e,"Lowercase",t)}function Qs(e,t={}){return ke(e,"Uncapitalize",t)}function Zs(e,t={}){return ke(e,"Uppercase",t)}function Jc(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ze(e[o],t,$(n));return r}function Xc(e,t,n){return Jc(e.properties,t,n)}function ei(e,t,n){let r=Xc(e,t,n);return S(r)}function Qc(e,t){return e.map(n=>Ur(n,t))}function Zc(e,t){return e.map(n=>Ur(n,t))}function em(e,t){let{[t]:n,...r}=e;return r}function tm(e,t){return t.reduce((n,r)=>em(n,r),e)}function nm(e,t,n){let r=_(e,[V,"$id","required","properties"]),o=tm(n,t);return R(o,r)}function rm(e){let t=e.reduce((n,r)=>ln(r)?[...n,T(r)]:n,[]);return w(t)}function Ur(e,t){return U(e)?te(Qc(e.allOf,t)):y(e)?w(Zc(e.anyOf,t)):j(e)?nm(e,t,e.properties):R({})}function Ze(e,t,n){let r=K(t)?rm(t):t,o=le(t)?se(t):t,i=L(e),s=L(t);return v(e)?ei(e,o,n):ce(t)?ti(e,t,n):i&&s?E("Omit",[e,r],n):!i&&s?E("Omit",[e,r],n):i&&!s?E("Omit",[e,r],n):u({...Ur(e,o),...n})}function om(e,t,n){return{[t]:Ze(e,[t],$(n))}}function sm(e,t,n){return t.reduce((r,o)=>({...r,...om(e,o,n)}),{})}function im(e,t,n){return sm(e,t.keys,n)}function ti(e,t,n){let r=im(e,t,n);return S(r)}function am(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=et(e[o],t,$(n));return r}function um(e,t,n){return am(e.properties,t,n)}function ni(e,t,n){let r=um(e,t,n);return S(r)}function dm(e,t){return e.map(n=>_r(n,t))}function cm(e,t){return e.map(n=>_r(n,t))}function mm(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function pm(e,t,n){let r=_(e,[V,"$id","required","properties"]),o=mm(n,t);return R(o,r)}function lm(e){let t=e.reduce((n,r)=>ln(r)?[...n,T(r)]:n,[]);return w(t)}function _r(e,t){return U(e)?te(dm(e.allOf,t)):y(e)?w(cm(e.anyOf,t)):j(e)?pm(e,t,e.properties):R({})}function et(e,t,n){let r=K(t)?lm(t):t,o=le(t)?se(t):t,i=L(e),s=L(t);return v(e)?ni(e,o,n):ce(t)?ri(e,t,n):i&&s?E("Pick",[e,r],n):!i&&s?E("Pick",[e,r],n):i&&!s?E("Pick",[e,r],n):u({..._r(e,o),...n})}function fm(e,t,n){return{[t]:et(e,[t],$(n))}}function gm(e,t,n){return t.reduce((r,o)=>({...r,...fm(e,o,n)}),{})}function Im(e,t,n){return gm(e,t.keys,n)}function ri(e,t,n){let r=Im(e,t,n);return S(r)}function hm(e,t){return E("Partial",[E(e,t)])}function ym(e){return E("Partial",[Ue(e)])}function xm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ee(e[n]);return t}function Sm(e,t){let n=_(e,[V,"$id","required","properties"]),r=xm(t);return R(r,n)}function oi(e){return e.map(t=>si(t))}function si(e){return Pe(e)?hm(e.target,e.parameters):L(e)?ym(e.$ref):U(e)?te(oi(e.allOf)):y(e)?w(oi(e.anyOf)):j(e)?Sm(e,e.properties):ut(e)||De(e)||Ce(e)||de(e)||Ht(e)||Me(e)||je(e)||Bt(e)||Wt(e)?e:R({})}function vt(e,t){return v(e)?ii(e,t):u({...si(e),...t})}function Tm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=vt(e[r],$(t));return n}function bm(e,t){return Tm(e.properties,t)}function ii(e,t){let n=bm(e,t);return S(n)}function wm(e,t){return E("Required",[E(e,t)])}function Am(e){return E("Required",[Ue(e)])}function Pm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=_(e[n],[J]);return t}function Rm(e,t){let n=_(e,[V,"$id","required","properties"]),r=Pm(t);return R(r,n)}function ai(e){return e.map(t=>ui(t))}function ui(e){return Pe(e)?wm(e.target,e.parameters):L(e)?Am(e.$ref):U(e)?te(ai(e.allOf)):y(e)?w(ai(e.anyOf)):j(e)?Rm(e,e.properties):ut(e)||De(e)||Ce(e)||de(e)||Ht(e)||Me(e)||je(e)||Bt(e)||Wt(e)?e:R({})}function Nt(e,t){return v(e)?di(e,t):u({...ui(e),...t})}function Om(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Nt(e[r],t);return n}function Cm(e,t){return Om(e.properties,t)}function di(e,t){let n=Cm(e,t);return S(n)}function Mm(e,t){return t.map(n=>L(n)?Lr(e,n.$ref):fe(e,n))}function Lr(e,t){return t in e?L(e[t])?Lr(e,e[t].$ref):fe(e,e[t]):x()}function Em(e){return Ct(e[0])}function Fm(e){return Je(e[0],e[1])}function km(e){return Mt(e[0])}function $m(e){return vt(e[0])}function vm(e){return Ze(e[0],e[1])}function Nm(e){return et(e[0],e[1])}function Um(e){return Nt(e[0])}function _m(e,t,n){let r=Mm(e,n);return t==="Awaited"?Em(r):t==="Index"?Fm(r):t==="KeyOf"?km(r):t==="Partial"?$m(r):t==="Omit"?vm(r):t==="Pick"?Nm(r):t==="Required"?Um(r):x()}function Lm(e,t){return Tt(fe(e,t))}function Km(e,t){return bt(fe(e,t))}function Dm(e,t,n){return wt(rn(e,t),fe(e,n))}function jm(e,t,n){return ve(rn(e,t),fe(e,n))}function Gm(e,t){return te(rn(e,t))}function Vm(e,t){return Ot(fe(e,t))}function Hm(e,t){return R(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:fe(e,t[r])}),{}))}function Bm(e,t){let[n,r]=[fe(e,kn(t)),Fn(t)],o=xt(t);return o.patternProperties[r]=n,o}function Wm(e,t){return L(t)?{...Lr(e,t.$ref),[V]:t[V]}:t}function qm(e,t){return ye(rn(e,t))}function zm(e,t){return w(rn(e,t))}function rn(e,t){return t.map(n=>fe(e,n))}function fe(e,t){return oe(t)?u(fe(e,_(t,[J])),t):St(t)?u(fe(e,_(t,[we])),t):We(t)?u(Wm(e,t),t):Ae(t)?u(Lm(e,t.items),t):at(t)?u(Km(e,t.items),t):Pe(t)?u(_m(e,t.target,t.parameters)):Re(t)?u(Dm(e,t.parameters,t.returns),t):Oe(t)?u(jm(e,t.parameters,t.returns),t):U(t)?u(Gm(e,t.allOf),t):dt(t)?u(Vm(e,t.items),t):j(t)?u(Hm(e,t.properties),t):mt(t)?u(Bm(e,t)):pe(t)?u(qm(e,t.items||[]),t):y(t)?u(zm(e,t.anyOf),t):t}function Ym(e,t){return t in e?fe(e,e[t]):x()}function ci(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:Ym(e,n)}),{})}var Kr=class{constructor(t){let n=ci(t),r=this.WithIdentifiers(n);this.$defs=r}Import(t,n){let r={...this.$defs,[t]:u(this.$defs[t],n)};return u({[m]:"Import",$defs:r,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:{...t[r],$id:r}}),{})}};function mi(e){return new Kr(e)}function pi(e,t){return u({[m]:"Not",not:e},t)}function li(e,t){return Oe(e)?ye(e.parameters,t):x()}var Jm=0;function fi(e,t={}){D(t.$id)&&(t.$id=`T${Jm++}`);let n=xt(e({[m]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[Ie]:"Recursive",...n},t)}function gi(e,t){let n=C(e)?new globalThis.RegExp(e):e;return u({[m]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},t)}function Xm(e){return U(e)?e.allOf:y(e)?e.anyOf:pe(e)?e.items??[]:[]}function Ii(e){return Xm(e)}function hi(e,t){return Oe(e)?u(e.returns,t):x(t)}var Dr=class{constructor(t){this.schema=t}Decode(t){return new jr(this.schema,t)}},jr=class{constructor(t,n){this.schema=t,this.decode=n}EncodeTransform(t,n){let i={Encode:s=>n[V].Encode(t(s)),Decode:s=>this.decode(n[V].Decode(s))};return{...n,[V]:i}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[V]:r}}Encode(t){return We(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function yi(e){return new Dr(e)}function xi(e={}){return u({[m]:e[m]??"Unsafe"},e)}function Si(e){return u({[m]:"Void",type:"void"},e)}var Gr={};ir(Gr,{Any:()=>Ye,Argument:()=>ns,Array:()=>Tt,AsyncIterator:()=>bt,Awaited:()=>Ct,BigInt:()=>Rt,Boolean:()=>hn,Capitalize:()=>Js,Composite:()=>bs,Const:()=>ws,Constructor:()=>wt,ConstructorParameters:()=>As,Date:()=>Tn,Enum:()=>Ps,Exclude:()=>kt,Extends:()=>Ft,Extract:()=>$t,Function:()=>ve,Index:()=>Je,InstanceType:()=>Vs,Instantiate:()=>Bs,Integer:()=>Ws,Intersect:()=>te,Iterator:()=>Ot,KeyOf:()=>Mt,Literal:()=>T,Lowercase:()=>Xs,Mapped:()=>Is,Module:()=>mi,Never:()=>x,Not:()=>pi,Null:()=>bn,Number:()=>he,Object:()=>R,Omit:()=>Ze,Optional:()=>ee,Parameters:()=>li,Partial:()=>vt,Pick:()=>et,Promise:()=>Sn,Readonly:()=>ie,ReadonlyOptional:()=>Mn,Record:()=>En,Recursive:()=>fi,Ref:()=>Ue,RegExp:()=>gi,Required:()=>Nt,Rest:()=>Ii,ReturnType:()=>hi,String:()=>Ee,Symbol:()=>wn,TemplateLiteral:()=>yn,Transform:()=>yi,Tuple:()=>ye,Uint8Array:()=>Pn,Uncapitalize:()=>Qs,Undefined:()=>An,Union:()=>w,Unknown:()=>Xe,Unsafe:()=>xi,Uppercase:()=>Zs,Void:()=>Si});var l=Gr;var g=null;function Vr(e){g=e}import{readFileSync as Qm}from"fs";import{homedir as Zm}from"os";import{join as ep}from"path";var on,Ti="claude-code",$n={"claude-code":{defaultModel:"sonnet",allowedModels:["sonnet","opus"]},codex:{defaultModel:"gpt-5.4",allowedModels:["gpt-5.4"],reasoningEffort:"medium",approvalPolicy:"on-request"}};function bi(){if(on!==void 0)return on;try{let e=Qm(ep(Zm(),".claude.json"),"utf-8");on=JSON.parse(e).mcpServers??{}}catch{on={}}return on}var F={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",codexApprovalPolicy:"on-request",harnesses:{"claude-code":{...$n["claude-code"]},codex:{...$n.codex}}};function wi(e){let t=e.defaultHarness??Ti,n={};for(let[r,o]of Object.entries($n))n[r]={...o,allowedModels:o.allowedModels?[...o.allowedModels]:void 0};for(let[r,o]of Object.entries(e.harnesses??{})){let s={...n[r]??{},...o};o.allowedModels!==void 0?s.allowedModels=o.allowedModels?[...o.allowedModels]:o.allowedModels:o.defaultModel!==void 0&&(s.allowedModels=void 0),n[r]=s}if(e.defaultModel!==void 0){let r=n[t]??{};n[t]={...r,defaultModel:e.harnesses?.[t]?.defaultModel??e.defaultModel,allowedModels:e.harnesses?.[t]?.allowedModels!==void 0?r.allowedModels:e.allowedModels},console.warn(`[openclaw-code-agent] config.defaultModel is deprecated; use harnesses.${t}.defaultModel instead.`)}if(e.model!==void 0){let r=n.codex??{};n.codex={...r,defaultModel:e.harnesses?.codex?.defaultModel??e.model,allowedModels:e.harnesses?.codex?.allowedModels!==void 0?r.allowedModels:e.allowedModels},console.warn("[openclaw-code-agent] config.model is deprecated; use harnesses.codex.defaultModel instead.")}if(e.reasoningEffort!==void 0){let r=n.codex??{};n.codex={...r,reasoningEffort:e.harnesses?.codex?.reasoningEffort??e.reasoningEffort},console.warn("[openclaw-code-agent] config.reasoningEffort is deprecated; use harnesses.codex.reasoningEffort instead.")}if(e.codexApprovalPolicy!==void 0){let r=n.codex??{};n.codex={...r,approvalPolicy:e.harnesses?.codex?.approvalPolicy??e.codexApprovalPolicy},console.warn("[openclaw-code-agent] config.codexApprovalPolicy is deprecated; use harnesses.codex.approvalPolicy instead.")}if(e.allowedModels!==void 0){console.warn("[openclaw-code-agent] config.allowedModels is deprecated; use harnesses.<name>.allowedModels instead.");for(let[r,o]of Object.entries(n))e.harnesses?.[r]?.allowedModels===void 0&&(n[r]={...o,allowedModels:void 0})}F={maxSessions:e.maxSessions??20,defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??15,sessionGcAgeMinutes:e.sessionGcAgeMinutes??1440,maxPersistedSessions:e.maxPersistedSessions??1e4,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10,permissionMode:e.permissionMode??"plan",codexApprovalPolicy:e.codexApprovalPolicy??"on-request",planApproval:e.planApproval??"delegate",defaultHarness:t,harnesses:n,allowedModels:e.allowedModels}}function tt(){return F.defaultHarness??Ti}function Hr(e){let t=$n[e],n=F.harnesses[e];return{...t,...n,allowedModels:n?.allowedModels??t?.allowedModels}}function nt(e){return Hr(e).defaultModel}function Ai(e){return F.harnesses[e]?.allowedModels??F.allowedModels}function Ut(e){return Hr(e).reasoningEffort}function gt(e){return Hr(e).approvalPolicy}function Pi(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=sn(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function _t(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);if(e?.messageChannel){let n=String(e.messageChannel);if(n.includes("|"))return n;if(e.chatId)return`${n}|${e.chatId}`;if(e.senderId)return`${n}|${e.senderId}`}return e?.channel&&e?.chatId?`${e.channel}|${e.chatId}`:e?.channel&&e?.senderId?`${e.channel}|${e.senderId}`:e?.id&&/^-?\d+$/.test(String(e.id))?`telegram|${e.id}`:F.fallbackChannel??"unknown"}function Lt(e){return e?.messageThreadId??void 0}function sn(e){let t=F.agentChannels;if(!t)return;let n=i=>i.replace(/\/+$/,""),r=n(e),o=Object.entries(t).sort((i,s)=>s[0].length-i[0].length);for(let[i,s]of o)if(r===n(i)||r.startsWith(n(i)+"/"))return s}function Ri(e){if(!e)return;let t=e.match(/:topic:(\d+)$/);return t?parseInt(t[1],10):void 0}function Kt(e){let{requestedResumeSessionId:t,activeSession:n,persistedSession:r}=e;return t?n?{resumeSessionId:t,clearedPersistedCodexResume:!1}:r?.harness==="codex"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:t,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}function np(e){return e instanceof Error?e.message:String(e)}function rp(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function op(e,t){if(!t||t.length===0)return!0;if(!e)return!1;let n=e.toLowerCase();return t.some(r=>n.includes(r.toLowerCase()))}function Oi(e){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn by default \u2014 they stay open for follow-up messages via agent_respond. Set multi_turn_disabled: true for fire-and-forget sessions. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:l.Object({prompt:l.String({description:"The task prompt to execute"}),name:l.Optional(l.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:l.Optional(l.String({description:"Working directory (defaults to cwd)"})),model:l.Optional(l.String({description:"Model name to use"})),system_prompt:l.Optional(l.String({description:"Additional system prompt"})),allowed_tools:l.Optional(l.Array(l.String(),{description:"List of allowed tools"})),resume_session_id:l.Optional(l.String({description:"Session ID to resume (from a previous session's harnessSessionId). Continues the conversation from where it left off."})),fork_session:l.Optional(l.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),multi_turn_disabled:l.Optional(l.Boolean({description:"Disable multi-turn mode. By default sessions stay open for follow-up messages. Set to true for fire-and-forget sessions."})),permission_mode:l.Optional(l.Union([l.Literal("default"),l.Literal("plan"),l.Literal("acceptEdits"),l.Literal("bypassPermissions")],{description:"Permission mode for the session. This is the plugin's orchestration mode, not the Codex SDK approval policy. Defaults to plugin config (plan by default)."})),harness:l.Optional(l.String({description:"Agent harness to use (e.g. 'claude-code'). Defaults to 'claude-code'."}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!rp(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};n.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${n.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${e.agentId}" will be used for origin routing instead.`);let r=n.workdir||e.workspaceDir||F.defaultWorkdir||process.cwd();if(!tp(r))return{content:[{type:"text",text:`Error: Working directory does not exist: ${r}`}]};try{let o=n.harness??tt(),i=nt(o),s=n.model??i,c=n.model!==void 0;if(!s)return{content:[{type:"text",text:`Error: No default model configured for harness "${o}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${o}.defaultModel or pass model explicitly.`}]};let p=Ai(o);if(p&&p.length>0&&!op(s,p))return{content:[{type:"text",text:c?`Error: Model "${s}" is not allowed. Permitted models: ${p.join(", ")}`:`Error: Default model "${s||"undefined"}" is not in allowedModels (${p.join(", ")}). Update your plugin config to set a compatible defaultModel.`}]};let f=n.resume_session_id,b=f?g.resolve(f):void 0,k=f?g.getPersistedSession(f):void 0;if(f){let yt=g.resolveHarnessSessionId(f);if(!yt)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${f}" to a session ID. Use agent_sessions to list available sessions.`}]};f=yt}let{resumeSessionId:X,clearedPersistedCodexResume:ge}=Kt({requestedResumeSessionId:f,activeSession:b?{harnessSessionId:b.harnessSessionId}:void 0,persistedSession:k?{harness:k.harness}:void 0}),Y=Pi(e),W=_t(e,Y||sn(r)),Q=e.sessionKey||void 0;!Q&&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 N=g.spawn({prompt:n.prompt,name:n.name,workdir:r,model:s,reasoningEffort:Ut(o),systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:X,forkSession:X?n.fork_session:!1,multiTurn:!n.multi_turn_disabled,permissionMode:n.permission_mode,codexApprovalPolicy:o==="codex"?gt(o)??F.codexApprovalPolicy:void 0,originChannel:W,originThreadId:Ri(Q)??Lt(e),originAgentId:e.agentId||void 0,originSessionKey:Q,harness:o}),He=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,be=["Session launched successfully.",` Name: ${N.name}`,` ID: ${N.id}`,` Dir: ${r}`,` Model: ${N.model??"default"}`,` Prompt: "${He}"`];return o==="codex"&&be.push(` Codex approval policy: ${N.codexApprovalPolicy??gt(o)??F.codexApprovalPolicy}`),n.resume_session_id&&(be.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),ge&&be.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),be.push(n.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),be.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:be.join(`
2
+ `)}]}}catch(o){let i=np(o),s=i.includes("Max sessions")?"":`
3
3
 
4
- Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${i}${s}`}]}}}}}import{existsSync as sp,readFileSync as ip}from"fs";function Le(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m${r}s`:`${r}s`}var rp=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","i","me","my","we","our","you","your","it","its","he","she","to","of","in","for","on","with","at","by","from","as","into","through","about","that","this","these","those","and","or","but","if","then","so","not","no","please","just","also","very","all","some","any","each","make","write","create","build","implement","add","update"]);function Ri(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!rp.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var op={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function Oi(e){let t=op[e.status]??"\u2753",n=Le(e.duration),r=e.multiTurn?"multi-turn":"single",o=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,i=e.costUsd>0?` | $${e.costUsd.toFixed(2)}`:"",s=[`${t} ${e.name} [${e.id}] (${n}${i}) \u2014 ${r}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];return e.phase!==e.status&&s.push(` \u2699\uFE0F Phase: ${e.phase}`),e.harness&&s.push(` \u{1F9F0} Harness: ${e.harness}`),e.harnessSessionId&&s.push(` \u{1F517} Session ID: ${e.harnessSessionId}`),e.resumeSessionId&&s.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),s.join(`
5
- `)}function $n(e,t){let n=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:r,failed:o,killed:i}=e.sessionsByStatus,s=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${n>0?Le(n):"n/a"}`];if(e.mostExpensive){let c=e.mostExpensive;s.push("","\u{1F3C6} Notable session",` ${c.name} [${c.id}]`,` \u{1F4DD} "${c.prompt}"`)}return s.join(`
6
- `)}function ot(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function Ci(e,t){let n=e.split(`
4
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${i}${s}`}]}}}}}import{existsSync as ap,readFileSync as up}from"fs";function _e(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m${r}s`:`${r}s`}var sp=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 Ci(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!sp.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var ip={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function Mi(e){let t=ip[e.status]??"\u2753",n=_e(e.duration),r=e.multiTurn?"multi-turn":"single",o=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,i=e.costUsd>0?` | $${e.costUsd.toFixed(2)}`:"",s=[`${t} ${e.name} [${e.id}] (${n}${i}) \u2014 ${r}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];return e.phase!==e.status&&s.push(` \u2699\uFE0F Phase: ${e.phase}`),e.harness&&s.push(` \u{1F9F0} Harness: ${e.harness}`),e.harnessSessionId&&s.push(` \u{1F517} Session ID: ${e.harnessSessionId}`),e.resumeSessionId&&s.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),s.join(`
5
+ `)}function vn(e,t){let n=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:r,failed:o,killed:i}=e.sessionsByStatus,s=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${i}`,"",`\u23F1\uFE0F Average duration: ${n>0?_e(n):"n/a"}`];if(e.mostExpensive){let c=e.mostExpensive;s.push("","\u{1F3C6} Notable session",` ${c.name} [${c.id}]`,` \u{1F4DD} "${c.prompt}"`)}return s.join(`
6
+ `)}function rt(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function Ei(e,t){let n=e.split(`
7
7
  `),r=[],o=0;for(let i=n.length-1;i>=0;i--){let s=n[i].length+(r.length>0?1:0);if(o+s>t&&r.length>0)break;r.unshift(n[i]),o+=s}return r.join(`
8
- `)}var ap=50,up=1,dp=new Set(["starting","running","completed","failed","killed"]),cp=5,mp=1440*60*1e3;function pp(e){let t=Number(e);return!Number.isFinite(t)||t<up?ap:Math.floor(t)}function lp(e){return typeof e=="string"&&dp.has(e)}function fp(e){let t=Le(e.duration),n=` | Cost: $${e.costUsd.toFixed(4)}`,r=e.status==="running"?` | Phase: ${e.phase}`:"";return[`Session: ${e.name} [${e.id}] | Status: ${e.status.toUpperCase()}${r}${n} | Duration: ${t}`,`${"\u2500".repeat(60)}`].join(`
9
- `)}function gp(e){return[`Session: ${e.name||e.harnessSessionId} | Status: ${e.status.toUpperCase()} | Cost: $${e.costUsd.toFixed(4)}`,`(retrieved from ${e.outputPath} \u2014 evicted from runtime cache \u2014 showing persisted output)`,`${"\u2500".repeat(60)}`].join(`
10
- `)}function Ip(e){let t=[];return e.error&&t.push(`Error: ${e.error}`),e.result?.result&&t.push(`Result: ${e.result.result}`),e.result&&t.push(`Result status: ${e.result.subtype}`),t.length>0?`
8
+ `)}var dp=50,cp=1,mp=new Set(["starting","running","completed","failed","killed"]),pp=5,lp=1440*60*1e3;function fp(e){let t=Number(e);return!Number.isFinite(t)||t<cp?dp:Math.floor(t)}function gp(e){return typeof e=="string"&&mp.has(e)}function Ip(e){let t=_e(e.duration),n=` | Cost: $${e.costUsd.toFixed(4)}`,r=e.status==="running"?` | Phase: ${e.phase}`:"";return[`Session: ${e.name} [${e.id}] | Status: ${e.status.toUpperCase()}${r}${n} | Duration: ${t}`,`${"\u2500".repeat(60)}`].join(`
9
+ `)}function hp(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 yp(e){let t=[];return e.error&&t.push(`Error: ${e.error}`),e.result?.result&&t.push(`Result: ${e.result.result}`),e.result&&t.push(`Result status: ${e.result.subtype}`),t.length>0?`
11
11
  (no output yet)
12
12
  ${t.join(`
13
13
  `)}`:`
14
- (no output yet)`}function vn(e,t,n={}){let r=pp(n.lines),o=e.resolve(t);if(!o){let c=e.getPersistedSession(t);if(c?.outputPath&&sp(c.outputPath))try{let p=ip(c.outputPath,"utf-8"),f=p;!n.full&&p&&(f=p.split(`
14
+ (no output yet)`}function Nn(e,t,n={}){let r=fp(n.lines),o=e.resolve(t);if(!o){let c=e.getPersistedSession(t);if(c?.outputPath&&ap(c.outputPath))try{let p=up(c.outputPath,"utf-8"),f=p;!n.full&&p&&(f=p.split(`
15
15
  `).slice(-r).join(`
16
- `));let T=gp(c);return f?`${T}
17
- ${f}`:`${T}
18
- (output file was empty)`}catch(p){let f=p instanceof Error?p.message:String(p);return`Error: Session "${t}" was cleaned up (expired) and output file could not be read: ${f}`}return`Error: Session "${t}" not found.`}let i=n.full?o.getOutput():o.getOutput(r),s=fp(o);return i.length===0?`${s}${Ip(o)}`:`${s}
16
+ `));let b=hp(c);return f?`${b}
17
+ ${f}`:`${b}
18
+ (output file was empty)`}catch(p){let f=p instanceof Error?p.message:String(p);return`Error: Session "${t}" was cleaned up (expired) and output file could not be read: ${f}`}return`Error: Session "${t}" not found.`}let i=n.full?o.getOutput():o.getOutput(r),s=Ip(o);return i.length===0?`${s}${yp(o)}`:`${s}
19
19
  ${i.join(`
20
- `)}`}function Nn(e,t="all",n,r={}){let o=e.listPersistedSessions()??[],s=hp(e.list("all"),o);if(t!=="all"&&(s=s.filter(c=>c.status===t)),n&&(s=s.filter(c=>c.originChannel===n)),r.full){let c=Date.now()-mp;s=s.filter(p=>(p.startedAt??0)>=c)}else s=s.slice(0,cp);return s.length===0?"No sessions found.":s.map(c=>Oi(c)).join(`
20
+ `)}`}function Un(e,t="all",n,r={}){let o=e.listPersistedSessions()??[],s=xp(e.list("all"),o);if(t!=="all"&&(s=s.filter(c=>c.status===t)),n&&(s=s.filter(c=>c.originChannel===n)),r.full){let c=Date.now()-lp;s=s.filter(p=>(p.startedAt??0)>=c)}else s=s.slice(0,pp);return s.length===0?"No sessions found.":s.map(c=>Mi(c)).join(`
21
21
 
22
- `)}function hp(e,t){let n=new Map;for(let r of t){if(!lp(r.status))continue;let o=r.completedAt??Date.now(),i=r.createdAt??o,s=r.sessionId??`persisted:${r.harnessSessionId}`;n.set(s,{id:r.sessionId??r.harnessSessionId,name:r.name||r.harnessSessionId,status:r.status,startedAt:r.createdAt??0,completedAt:r.completedAt,duration:Math.max(0,o-i),prompt:r.prompt??"",workdir:r.workdir??"(unknown)",costUsd:r.costUsd??0,multiTurn:!0,phase:r.status,harness:r.harness,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId})}for(let r of e)n.set(r.id,{id:r.id,name:r.name,status:r.status,startedAt:r.startedAt,completedAt:r.completedAt,duration:r.duration,prompt:r.prompt,workdir:r.workdir,costUsd:r.costUsd,multiTurn:r.multiTurn,phase:r.phase,harness:r.harnessName,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId});return[...n.values()].sort((r,o)=>(o.startedAt??0)-(r.startedAt??0))}function yp(e){if(!e||typeof e!="object")return"all";let t=e.status;switch(t){case"running":case"completed":case"failed":case"killed":case"all":return t;default:return"all"}}function Mi(e){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:l.Object({status:l.Optional(l.Union([l.Literal("all"),l.Literal("running"),l.Literal("completed"),l.Literal("failed"),l.Literal("killed")],{description:'Filter by status (default "all")'})),full:l.Optional(l.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=yp(n),o=e?.workspaceDir?on(e.workspaceDir):void 0,i=!!(n&&typeof n=="object"&&n.full===!0);return{content:[{type:"text",text:Nn(g,r,o,{full:i})}]}}}}function Un(e,t,n){let r=e.resolve(t);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`:n==="completed"?(r.complete(),`Session ${r.name} [${r.id}] marked as completed.`):(e.kill(r.id),`Session ${r.name} [${r.id}] has been terminated.`):`Error: Session "${t}" not found.`}function xp(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session!="string"?!1:t.reason===void 0?!0:t.reason==="completed"||t.reason==="killed"}function Ei(e){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:l.Object({session:l.String({description:"Session name or ID to terminate"}),reason:l.Optional(l.Union([l.Literal("completed"),l.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(t,n){return g?xp(n)?{content:[{type:"text",text:Un(g,n.session,n.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}function Sp(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function ki(e){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:l.Object({session:l.String({description:"Session name or ID to get output from"}),lines:l.Optional(l.Number({description:"Number of recent lines to show (default 50)"})),full:l.Optional(l.Boolean({description:"Show all available output"}))}),async execute(t,n){return g?Sp(n)?{content:[{type:"text",text:vn(g,n.session,{full:n.full,lines:n.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}var Tp=new Set(["killed","completed","failed"]),bp=new Set(["startup-timeout"]),wp=10,Ap=100,Pp=/\b(change|swap|replace|remove|add|update|instead|don't|revise|modify)\b/i;function sn(e){return e instanceof Error?e.message:String(e)}function Rp(e,t){switch(e){case"completed":return"completed";case"failed":return"failed";default:return t==="user"?"user-killed":t==="shutdown"?"shutdown-killed":"idle-kill"}}function Fi(e){return"id"in e?e.id:e.sessionId??e.harnessSessionId}function Op(e){return e.status==="killed"&&e.completedAt==null}function Cp(e,t){return Tp.has(e.status)&&!!e.harnessSessionId&&(e.status==="failed"||e.status==="completed"&&e.killReason==="done"||e.status==="killed"&&(!bp.has(e.killReason??"")||t&&Op(e)))}function Mp(e,t){if(!(t.trim().length<Ap&&!Pp.test(t)))return{text:["Cannot approve and revise in the same call.","Your message appears to contain revision feedback. Send it first WITHOUT approve=true:",` agent_respond(session='${e}', message='<your feedback>')`,"The agent will revise the plan. Then approve the revised plan."].join(`
23
- `),isError:!0}}async function Ep(e,t,n,r={}){if(Cp(t,r.allowRecoveredRunningStub===!0))try{let o="harnessName"in t?t:void 0,i="harnessName"in t?void 0:t,{resumeSessionId:s}=Lt({requestedResumeSessionId:t.harnessSessionId,activeSession:o?{harnessSessionId:o.harnessSessionId}:void 0,persistedSession:i?{harness:i.harness}:void 0}),c={prompt:n,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:s,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,harness:"harnessName"in t?t.harnessName:t.harness},p=await e.spawnAndAwaitRunning(c,{notifyLaunch:!1}),f=Rp(t.status,t.killReason);return e.notifySession(p,`\u{1F504} [${p.name}] Auto-resumed from ${f}`),{text:`Auto-resumed ${f} session ${p.name} [${p.id}]. Use agent_output to see the response.`}}catch(o){return{text:`Error auto-resuming session ${t.name} [${Fi(t)}]: ${sn(o)}`,isError:!0}}}function kp(e,t,n){let r=t.lobsterResumeToken;if(!r)return;t.lobsterResumeToken=void 0;let o=t.pendingPlanApproval||t.currentPermissionMode==="acceptEdits"||t.currentPermissionMode==="default";if(n.approve&&o)return e.resumeLobsterApproval(r,!0).catch(i=>{console.error(`[Respond] Lobster resume failed, falling back to direct mode switch: ${sn(i)}`),t.switchPermissionMode("bypassPermissions"),t.sendMessage(n.message).catch(s=>{console.error(`[Respond] Fallback sendMessage also failed: ${sn(s)}`)})}),{text:`Plan approved. Lobster workflow resuming for session ${t.name} [${t.id}].`};e.resumeLobsterApproval(r,!1).catch(i=>{console.error(`[Respond] Lobster cancel failed (non-critical): ${sn(i)}`)})}async function _n(e,t){let n=e.resolve(t.session),r=n?void 0:e.getPersistedSession(t.session);if(!n&&!r)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let i=await Ep(e,n??r,t.message,{allowRecoveredRunningStub:!n});if(i)return i;if(!n)return{text:`Error: Session ${r.name} [${Fi(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return{text:`Error: Session ${n.name} [${n.id}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};let s=E.maxAutoResponds??wp;if(t.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=s)return{text:`\u26A0\uFE0F Auto-respond limit reached (${n.autoRespondCount}/${s}). Ask the user to provide the answer for session ${n.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};let c=kp(e,n,t);if(c)return c;try{t.interrupt&&await n.interrupt();let p="";if(t.approve&&n.pendingPlanApproval){let T=Mp(n.name,t.message);if(T)return T;n.switchPermissionMode("bypassPermissions")}else t.approve&&(n.currentPermissionMode==="acceptEdits"||n.currentPermissionMode==="default")?n.switchPermissionMode("bypassPermissions"):t.approve&&n.currentPermissionMode==="bypassPermissions"?p=`
24
- \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:t.approve?p=`
25
- \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:n.pendingPlanApproval&&(p=`
26
- \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`);await n.sendMessage(t.message),t.userInitiated||n.incrementAutoRespond();let f=ot(t.message,80);return{text:[`Message sent to session ${n.name} [${n.id}].`,t.interrupt?" (interrupted current turn first)":"",` Message: "${f}"`,p,"Use agent_output to see the response."].filter(Boolean).join(`
27
- `)}}catch(p){return{text:`Error sending message to session ${n.name} [${n.id}]: ${sn(p)}`,isError:!0}}}function Fp(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function $i(e){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent session. The session must be running. Sessions are multi-turn by default, so this works with any session unless it was launched with multi_turn_disabled: true.",parameters:l.Object({session:l.String({description:"Session name or ID to respond to"}),message:l.String({description:"The message to send to the session"}),interrupt:l.Optional(l.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:l.Optional(l.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:l.Optional(l.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode (after ExitPlanMode / set_permission_mode), or (2) escalate an acceptEdits or default mode session to skip all remaining permission prompts. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Fp(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let r=await _n(g,n);return{isError:r.isError??!1,content:[{type:"text",text:r.text}]}}}}function vi(e){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:l.Object({}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=g.getMetrics(),o=g.list("running").length;return{content:[{type:"text",text:$n(r,o)}]}}}}function $p(e){return e instanceof Error?e.message:String(e)}function Ni(e){e.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent [--name <name>] <prompt>"};let r,o=n.match(/^--name\s+(\S+)\s+/);o&&(r=o[1],n=n.slice(o[0].length).trim());let i=n;if(!i)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let s=nt(),c=rt(s);if(!c)return{text:`Error: No default model configured for harness "${s}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${s}.defaultModel or pass model explicitly via agent_launch.`};let p=g.spawn({prompt:i,name:r,workdir:E.defaultWorkdir||process.cwd(),model:c,reasoningEffort:Nt(s),codexApprovalPolicy:s==="codex"?gt(s)??E.codexApprovalPolicy:void 0,originChannel:Ut(t),originThreadId:_t(t),harness:s}),f=i.length>80?i.slice(0,80)+"...":i;return{text:["Session launched.",` Name: ${p.name}`,` ID: ${p.id}`,` Prompt: "${f}"`,` Status: ${p.status}`].join(`
28
- `)}}catch(s){let c=$p(s),p=c.includes("Max sessions")?"":`
22
+ `)}function xp(e,t){let n=new Map;for(let r of t){if(!gp(r.status))continue;let o=r.completedAt??Date.now(),i=r.createdAt??o,s=r.sessionId??`persisted:${r.harnessSessionId}`;n.set(s,{id:r.sessionId??r.harnessSessionId,name:r.name||r.harnessSessionId,status:r.status,startedAt:r.createdAt??0,completedAt:r.completedAt,duration:Math.max(0,o-i),prompt:r.prompt??"",workdir:r.workdir??"(unknown)",costUsd:r.costUsd??0,multiTurn:!0,phase:r.status,harness:r.harness,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId})}for(let r of e)n.set(r.id,{id:r.id,name:r.name,status:r.status,startedAt:r.startedAt,completedAt:r.completedAt,duration:r.duration,prompt:r.prompt,workdir:r.workdir,costUsd:r.costUsd,multiTurn:r.multiTurn,phase:r.phase,harness:r.harnessName,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId});return[...n.values()].sort((r,o)=>(o.startedAt??0)-(r.startedAt??0))}function Sp(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 Fi(e){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:l.Object({status:l.Optional(l.Union([l.Literal("all"),l.Literal("running"),l.Literal("completed"),l.Literal("failed"),l.Literal("killed")],{description:'Filter by status (default "all")'})),full:l.Optional(l.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=Sp(n),o=e?.workspaceDir?sn(e.workspaceDir):void 0,i=!!(n&&typeof n=="object"&&n.full===!0);return{content:[{type:"text",text:Un(g,r,o,{full:i})}]}}}}function _n(e,t,n){let r=e.resolve(t);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`:n==="completed"?(r.complete(),`Session ${r.name} [${r.id}] marked as completed.`):(e.kill(r.id),`Session ${r.name} [${r.id}] has been terminated.`):`Error: Session "${t}" not found.`}function Tp(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 ki(e){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:l.Object({session:l.String({description:"Session name or ID to terminate"}),reason:l.Optional(l.Union([l.Literal("completed"),l.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(t,n){return g?Tp(n)?{content:[{type:"text",text:_n(g,n.session,n.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}function bp(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function $i(e){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:l.Object({session:l.String({description:"Session name or ID to get output from"}),lines:l.Optional(l.Number({description:"Number of recent lines to show (default 50)"})),full:l.Optional(l.Boolean({description:"Show all available output"}))}),async execute(t,n){return g?bp(n)?{content:[{type:"text",text:Nn(g,n.session,{full:n.full,lines:n.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}var wp=new Set(["killed","completed","failed"]),Ap=new Set(["startup-timeout"]),Pp=10,Rp=100,Op=/\b(change|swap|replace|remove|add|update|instead|don't|revise|modify)\b/i;function an(e){return e instanceof Error?e.message:String(e)}function vi(e){return"id"in e?e.id:e.sessionId??e.harnessSessionId}function Cp(e){return e.status==="killed"&&e.completedAt==null}function Mp(e,t){return wp.has(e.status)&&!!e.harnessSessionId&&(e.status==="failed"||e.status==="completed"&&e.killReason==="done"||e.status==="killed"&&(!Ap.has(e.killReason??"")||t&&Cp(e)))}function Ep(e,t){if(!(t.trim().length<Rp&&!Op.test(t)))return{text:["Cannot approve and revise in the same call.","Your message appears to contain revision feedback. Send it first WITHOUT approve=true:",` agent_respond(session='${e}', message='<your feedback>')`,"The agent will revise the plan. Then approve the revised plan."].join(`
23
+ `),isError:!0}}async function Fp(e,t,n,r={}){if(Mp(t,r.allowRecoveredRunningStub===!0))try{let o="harnessName"in t?t:void 0,i="harnessName"in t?void 0:t,{resumeSessionId:s}=Kt({requestedResumeSessionId:t.harnessSessionId,activeSession:o?{harnessSessionId:o.harnessSessionId}:void 0,persistedSession:i?{harness:i.harness}:void 0}),c={prompt:n,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:s,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy,harness:"harnessName"in t?t.harnessName:t.harness},p=await e.spawnAndAwaitRunning(c,{notifyLaunch:!1});return e.notifySession(p,`\u25B6\uFE0F [${p.name}] Auto-resumed`),{text:`Auto-resumed session ${p.name} [${p.id}]. Use agent_output to see the response.`}}catch(o){return{text:`Error auto-resuming session ${t.name} [${vi(t)}]: ${an(o)}`,isError:!0}}}function kp(e,t,n){let r=t.lobsterResumeToken;if(!r)return;t.lobsterResumeToken=void 0;let o=t.pendingPlanApproval||t.currentPermissionMode==="acceptEdits"||t.currentPermissionMode==="default";if(n.approve&&o)return e.resumeLobsterApproval(r,!0).catch(i=>{console.error(`[Respond] Lobster resume failed, falling back to direct mode switch: ${an(i)}`),t.switchPermissionMode("bypassPermissions"),t.sendMessage(n.message).catch(s=>{console.error(`[Respond] Fallback sendMessage also failed: ${an(s)}`)})}),{text:`Plan approved. Lobster workflow resuming for session ${t.name} [${t.id}].`};e.resumeLobsterApproval(r,!1).catch(i=>{console.error(`[Respond] Lobster cancel failed (non-critical): ${an(i)}`)})}async function Ln(e,t){let n=e.resolve(t.session),r=n?void 0:e.getPersistedSession(t.session);if(!n&&!r)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let i=await Fp(e,n??r,t.message,{allowRecoveredRunningStub:!n});if(i)return i;if(!n)return{text:`Error: Session ${r.name} [${vi(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return{text:`Error: Session ${n.name} [${n.id}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};let s=F.maxAutoResponds??Pp;if(t.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=s)return{text:`\u26A0\uFE0F Auto-respond limit reached (${n.autoRespondCount}/${s}). Ask the user to provide the answer for session ${n.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};let c=kp(e,n,t);if(c)return c;try{let p=!1;t.interrupt&&(p=await n.interrupt());let f="";if(t.approve&&n.pendingPlanApproval){let k=Ep(n.name,t.message);if(k)return k;n.switchPermissionMode("bypassPermissions")}else t.approve&&(n.currentPermissionMode==="acceptEdits"||n.currentPermissionMode==="default")?n.switchPermissionMode("bypassPermissions"):t.approve&&n.currentPermissionMode==="bypassPermissions"?f=`
24
+ \u2139\uFE0F approve=true was set but session is already in bypassPermissions mode.`:t.approve?f=`
25
+ \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:n.pendingPlanApproval&&(f=`
26
+ \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`);await n.sendMessage(t.message),p&&e.notifySession(n,`\u21AA\uFE0F [${n.name}] Redirected`,"redirected"),t.userInitiated||n.incrementAutoRespond();let b=rt(t.message,80);return{text:[`Message sent to session ${n.name} [${n.id}].`,p?" (redirected active turn first)":t.interrupt?" (no active turn to interrupt)":"",` Message: "${b}"`,f,"Use agent_output to see the response."].filter(Boolean).join(`
27
+ `)}}catch(p){return{text:`Error sending message to session ${n.name} [${n.id}]: ${an(p)}`,isError:!0}}}function $p(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function Ni(e){return{name:"agent_respond",description:"Send a follow-up message to a running coding agent session. The session must be running. Sessions are multi-turn by default, so this works with any session unless it was launched with multi_turn_disabled: true.",parameters:l.Object({session:l.String({description:"Session name or ID to respond to"}),message:l.String({description:"The message to send to the session"}),interrupt:l.Optional(l.Boolean({description:"If true, interrupt the current turn before sending the message. Useful to redirect the session mid-response."})),userInitiated:l.Optional(l.Boolean({description:"Set to true when the message comes from the user (not auto-generated). Resets the auto-respond counter and bypasses the auto-respond limit."})),approve:l.Optional(l.Boolean({description:"Set to true to escalate session permissions to bypassPermissions. Works in two scenarios: (1) approve a pending plan in plan mode (after ExitPlanMode / set_permission_mode), or (2) escalate an acceptEdits or default mode session to skip all remaining permission prompts. No-op if already in bypassPermissions mode. In plan mode without a pending plan, this flag is ignored."}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!$p(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let r=await Ln(g,n);return{isError:r.isError??!1,content:[{type:"text",text:r.text}]}}}}function Ui(e){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:l.Object({}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=g.getMetrics(),o=g.list("running").length;return{content:[{type:"text",text:vn(r,o)}]}}}}function vp(e){return e instanceof Error?e.message:String(e)}function _i(e){e.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent [--name <name>] <prompt>"};let r,o=n.match(/^--name\s+(\S+)\s+/);o&&(r=o[1],n=n.slice(o[0].length).trim());let i=n;if(!i)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let s=tt(),c=nt(s);if(!c)return{text:`Error: No default model configured for harness "${s}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${s}.defaultModel or pass model explicitly via agent_launch.`};let p=g.spawn({prompt:i,name:r,workdir:F.defaultWorkdir||process.cwd(),model:c,reasoningEffort:Ut(s),codexApprovalPolicy:s==="codex"?gt(s)??F.codexApprovalPolicy:void 0,originChannel:_t(t),originThreadId:Lt(t),harness:s}),f=i.length>80?i.slice(0,80)+"...":i;return{text:["Session launched.",` Name: ${p.name}`,` ID: ${p.id}`,` Prompt: "${f}"`,` Status: ${p.status}`].join(`
28
+ `)}}catch(s){let c=vp(s),p=c.includes("Max sessions")?"":`
29
29
 
30
- Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${c}${p}`}}}})}function Ui(e){e.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").split(/\s+/).includes("--full");return{text:Nn(g,"all",void 0,{full:n})}}})}function _i(e){e.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=t.args?.trim();return n?{text:Un(g,n,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}function vp(e){return e instanceof Error?e.message:String(e)}function Li(e){e.registerCommand({name:"agent_resume",description:"Resume a previous coding agent session. Usage: /agent_resume <id-or-name> [prompt] or /agent_resume --list to see resumable sessions.",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /agent_resume <id-or-name> [prompt]
30
+ Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${c}${p}`}}}})}function Li(e){e.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").split(/\s+/).includes("--full");return{text:Un(g,"all",void 0,{full:n})}}})}function Ki(e){e.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=t.args?.trim();return n?{text:_n(g,n,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}function Np(e){return e instanceof Error?e.message:String(e)}function Di(e){e.registerCommand({name:"agent_resume",description:"Resume a previous coding agent session. Usage: /agent_resume <id-or-name> [prompt] or /agent_resume --list to see resumable sessions.",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /agent_resume <id-or-name> [prompt]
31
31
  /agent_resume --list \u2014 list resumable sessions
32
- /agent_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let ee=g.listPersistedSessions();return ee.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
32
+ /agent_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(n==="--list"){let W=g.listPersistedSessions();return W.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
33
33
 
34
- ${ee.map(_=>{let Be=_.prompt.length>60?_.prompt.slice(0,60)+"...":_.prompt,be=_.completedAt?`completed ${Le(Date.now()-_.completedAt)} ago`:_.status;return[` ${_.name} \u2014 ${be}`,` Session ID: ${_.harnessSessionId}`,` \u{1F4C1} ${_.workdir}`,` \u{1F4DD} "${Be}"`].join(`
34
+ ${W.map(N=>{let He=N.prompt.length>60?N.prompt.slice(0,60)+"...":N.prompt,be=N.completedAt?`completed ${_e(Date.now()-N.completedAt)} ago`:N.status;return[` ${N.name} \u2014 ${be}`,` Session ID: ${N.harnessSessionId}`,` \u{1F4C1} ${N.workdir}`,` \u{1F4DD} "${He}"`].join(`
35
35
  `)}).join(`
36
36
 
37
37
  `)}`}}let r=!1;n.startsWith("--fork ")&&(r=!0,n=n.slice(7).trim());let o=n.indexOf(" "),i,s;o===-1?(i=n,s="Continue where you left off."):(i=n.slice(0,o),s=n.slice(o+1).trim()||"Continue where you left off.");let c=g.resolveHarnessSessionId(i);if(!c)return{text:`Error: Could not find a session ID for "${i}".
38
- Use /agent_resume --list to see available sessions.`};let p=g.resolve(i),f=g.getPersistedSession(i),{resumeSessionId:T,clearedPersistedCodexResume:U}=Lt({requestedResumeSessionId:c,activeSession:p?{harnessSessionId:p.harnessSessionId}:void 0,persistedSession:f?{harness:f.harness}:void 0}),te=f?.workdir??process.cwd(),ge=f?.harness??nt(),ae=f?.model??rt(ge);try{if(!ae)return{text:`Error: No default model configured for harness "${ge}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${ge}.defaultModel or pass model explicitly when launching a fresh session.`};let ee=g.spawn({prompt:s,workdir:te,name:f?.name,model:ae,codexApprovalPolicy:p?.codexApprovalPolicy??f?.codexApprovalPolicy,resumeSessionId:T,forkSession:T?r:!1,originChannel:Ut(t),originThreadId:_t(t)??f?.originThreadId,originAgentId:t?.agentId??f?.originAgentId,originSessionKey:t?.sessionKey??f?.originSessionKey,harness:ge}),z=s.length>80?s.slice(0,80)+"...":s;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${ee.name}`,` ID: ${ee.id}`,T?` Resume from: ${c}`:" Resume from: fresh thread",` Dir: ${te}`,` Prompt: "${z}"`,U?" Note: cleared persisted Codex thread state after restart to avoid org-mismatch resume failures.":""].join(`
39
- `)}}catch(ee){let z=vp(ee),_=z.includes("Max sessions")?"":`
38
+ Use /agent_resume --list to see available sessions.`};let p=g.resolve(i),f=g.getPersistedSession(i),{resumeSessionId:b,clearedPersistedCodexResume:k}=Kt({requestedResumeSessionId:c,activeSession:p?{harnessSessionId:p.harnessSessionId}:void 0,persistedSession:f?{harness:f.harness}:void 0}),X=f?.workdir??process.cwd(),ge=f?.harness??tt(),Y=f?.model??nt(ge);try{if(!Y)return{text:`Error: No default model configured for harness "${ge}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${ge}.defaultModel or pass model explicitly when launching a fresh session.`};let W=g.spawn({prompt:s,workdir:X,name:f?.name,model:Y,codexApprovalPolicy:p?.codexApprovalPolicy??f?.codexApprovalPolicy,resumeSessionId:b,forkSession:b?r:!1,originChannel:_t(t),originThreadId:Lt(t)??f?.originThreadId,originAgentId:t?.agentId??f?.originAgentId,originSessionKey:t?.sessionKey??f?.originSessionKey,harness:ge}),Q=s.length>80?s.slice(0,80)+"...":s;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${W.name}`,` ID: ${W.id}`,b?` Resume from: ${c}`:" Resume from: fresh thread",` Dir: ${X}`,` Prompt: "${Q}"`,k?" Note: cleared persisted Codex thread state after restart to avoid org-mismatch resume failures.":""].join(`
39
+ `)}}catch(W){let Q=Np(W),N=Q.includes("Max sessions")?"":`
40
40
 
41
- Use /agent_sessions to see active sessions or /agent_resume --list to see resumable sessions.`;return{text:`Error resuming session: ${z}${_}`}}}})}function Ki(e){e.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /agent_respond <id-or-name> <message>
42
- /agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!0,o=o.slice(12).trim());let i=o.indexOf(" ");if(i===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let s=o.slice(0,i),c=o.slice(i+1).trim();return c?{text:(await _n(g,{session:s,message:c,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}function Di(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=g.getMetrics(),n=g.list("running").length;return{text:$n(t,n)}}})}var Np=50;function ji(e){e.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=n.split(/\s+/),o="",i=!1,s=Np;for(let p=0;p<r.length;p++)if(r[p]==="--full")i=!0;else if(r[p]==="--lines"&&p+1<r.length){let f=parseInt(r[p+1],10);!isNaN(f)&&f>0&&(s=f),p++}else o||(o=r[p]);return o?{text:vn(g,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}import{execFile as pa}from"child_process";import{existsSync as Jl}from"fs";import{fileURLToPath as la}from"url";import{dirname as Xl,join as zr}from"path";import{EventEmitter as bl}from"events";import Vi from"crypto";var Gi="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Up=128,It,Kt,_p=e=>{!It||It.length<e?(It=Buffer.allocUnsafe(e*Up),Vi.randomFillSync(It),Kt=0):Kt+e>It.length&&(Vi.randomFillSync(It),Kt=0),Kt+=e};var Hi=(e=21)=>{_p(e|=0);let t="";for(let n=Kt-e;n<Kt;n++)t+=Gi[It[n]&63];return t};import{query as Lp}from"@anthropic-ai/claude-agent-sdk";var Ln=class{name="claude-code";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=["AskUserQuestion"];planApprovalToolNames=["ExitPlanMode","set_permission_mode"];launch(t){let n={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers};t.resumeSessionId&&(n.resume=t.resumeSessionId,n.forkSession=t.forkSession??!1);let r=Lp({prompt:t.prompt,options:n});return{messages:this.adaptMessages(r),async setPermissionMode(o){typeof r.setPermissionMode=="function"&&await r.setPermissionMode(o)},async streamInput(o){typeof r.streamInput=="function"&&await r.streamInput(o)},async interrupt(){typeof r.interrupt=="function"&&await r.interrupt()}}}buildUserMessage(t,n){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n}}async*adaptMessages(t){for await(let n of t){let r=n;if(r.type==="system"&&r.subtype==="init")yield{type:"init",session_id:r.session_id??""};else if(r.type==="system"&&r.subtype==="status"&&r.permissionMode)yield{type:"permission_mode_change",mode:r.permissionMode};else if(r.type==="assistant")for(let o of r.message?.content??[])o.type==="text"?yield{type:"text",text:o.text}:o.type==="tool_use"&&(yield{type:"tool_use",name:o.name,input:o.input});else r.type==="result"&&(yield{type:"result",data:{success:r.subtype==="success",duration_ms:r.duration_ms??0,total_cost_usd:r.total_cost_usd??0,num_turns:r.num_turns??0,result:r.result,session_id:r.session_id??""}})}}};import{parse as al,resolve as ul}from"path";import{Codex as Zi}from"@openai/codex-sdk";import{randomUUID as Kp}from"node:crypto";import{lstat as Dp,mkdir as Hr,readFile as qi,readlink as jp,realpath as Gp,rename as Vp,rm as Kn,symlink as Hp,writeFile as zi}from"node:fs/promises";import{homedir as Bp,tmpdir as Yi}from"node:os";import{dirname as Wp,join as ve,resolve as qp}from"node:path";var zp=50,Yp=3e4,Jp=ve(Yi(),"openclaw-codex-auth.lock");function Xp(e,t){let n={};for(let[r,o]of Object.entries(e))typeof o=="string"&&(n[r]=o);return n.HOME=t,n}function Qp(e){return new Promise(t=>setTimeout(t,e))}async function Ji(e){try{return await Dp(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Bi(e,t){if(await Ji(t)){if(await jp(t)===e)return;await Kn(t,{recursive:!0,force:!0})}await Hp(e,t)}function Zp(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return null;let n=Number(t);if(Number.isFinite(n))return n;let r=Date.parse(t);if(Number.isFinite(r))return r}return null}async function Wi(e){let t;try{t=await qi(e,"utf8")}catch(n){return n.code==="ENOENT",null}try{let n=JSON.parse(t);if(!n||typeof n!="object")return null;let r=Zp(n.last_refresh);return r===null?null:{lastRefresh:r,raw:t}}catch{return null}}async function Xi(e,t){await Hr(Wp(e),{recursive:!0});let n=`${e}.tmp`;await zi(n,t,"utf8"),await Vp(n,e)}async function el(e,t){try{let n=await qi(e,"utf8");await Xi(t,n)}catch(n){if(n.code!=="ENOENT")throw n;await Kn(t,{force:!0})}}async function tl(e,t){let n=await Wi(e);if(!n)return;let r=await Wi(t);r&&n.lastRefresh<=r.lastRefresh||await Xi(t,n.raw)}async function nl(e,t,n){let r=Date.now()+t;for(;;)try{await Hr(e);break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()>=r)throw new Error(`Timed out waiting for Codex auth lock at ${e}`);await Qp(n)}try{await zi(ve(e,"holder.json"),JSON.stringify({pid:process.pid,acquired_at:new Date().toISOString()}),"utf8")}catch{}let o=!1;return async()=>{o||(o=!0,await Kn(e,{recursive:!0,force:!0}))}}async function Qi(e=process.env,t={}){let n=e.HOME??Bp(),r=await Gp(n).catch(()=>qp(n)),o=ve(r,".codex"),i=ve(o,"auth.json"),s=ve(o,"sessions"),c=ve(o,"config.toml"),p=await Ji(c)?c:void 0,f=t.tempRootDir??Yi(),T=ve(f,`openclaw-codex-auth-${Kp()}`),U=ve(T,".codex"),te=ve(U,"auth.json"),ge=t.lockDir??Jp,ae=t.lockTimeoutMs??Yp,ee=t.lockRetryMs??zp;return await Hr(U,{recursive:!0}),await Bi(s,ve(U,"sessions")),p&&await Bi(p,ve(U,"config.toml")),{tempHome:T,tempCodexDir:U,canonicalHome:r,canonicalCodexDir:o,canonicalAuthPath:i,canonicalSessionsPath:s,canonicalConfigPath:p,env:Xp(e,T),async prepareForTurn(){let z=await nl(ge,ae,ee);try{await el(i,te)}catch(Be){throw await z(),Be}let _=!1;return async()=>{if(!_){_=!0;try{await tl(te,i)}finally{await z()}}}},async cleanup(){await Kn(T,{recursive:!0,force:!0})}}}var rl=["proceed","continue","implement","apply","run","merge","deploy","commit"],ol=["shall i proceed","do you want me to","would you like me to","please confirm","should i continue","can i proceed","should i proceed","should i go ahead","want me to continue","approve and i'll","confirm and i'll"],sl=["why this failed was","why did this fail","what failed","what happened","how can i help","is this clear","any questions","anything else","let me know","would you like a summary"];function il(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Dn(e){let t=il(e);if(!t||sl.some(r=>t.includes(r)))return!1;let n=rl.some(r=>t.includes(r));return ol.some(r=>t.includes(r))?n||t.includes("confirm"):t.endsWith("?")?n:!1}var ea=1e4,ta="codex:waiting-for-user",dl=1.1/1e6,cl=.275/1e6,ml=4.4/1e6,pl="OPENCLAW_CODEX_HEARTBEAT_MS",ll="OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS",fl="OPENCLAW_CODEX_AUTH_STRATEGY";function gl(e){if(!e)return 0;let t=e.cached_input_tokens??0,n=Math.max(0,(e.input_tokens??0)-t),r=e.output_tokens??0;return n*dl+t*cl+r*ml}function na(e,t={}){return{success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,session_id:e,...t}}function Il(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return String(e);let t=e;return typeof t.message?.content=="string"?t.message.content:typeof t.text=="string"?t.text:String(e)}function hl(e){return["[SYSTEM: First turn only. Do not implement yet.]","Start by producing a concise implementation plan only.","Then end your response with an explicit question asking whether you should proceed with implementation.","",e].join(`
43
- `)}function ra(e){return e instanceof Error?e.message:String(e)}function yl(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function xl(e){return al(ul(e)).root||"/"}function Sl(e){let n=[xl(e)];return n.push(...yl(process.env[ll])),[...new Set(n)]}function Tl(e,t){let r=(t??e.permissionMode)==="bypassPermissions"?Sl(e.cwd):void 0;return{model:e.model,modelReasoningEffort:e.reasoningEffort,workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:e.codexApprovalPolicy??"on-request",skipGitRepoCheck:!0,additionalDirectories:r}}var jn=class{constructor(t={}){this.deps=t}name="codex";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=[ta];planApprovalToolNames=[];activityHeartbeatMs(){let t=Number.parseInt(process.env[pl]??String(ea),10);return!Number.isFinite(t)||t<=0?ea:t}createCodexClient(t){return this.deps.createCodex?.({env:t})??(t?new Zi({env:t}):new Zi)}launch(t){let r=process.env[fl]==="legacy"?void 0:this.deps.createAuthWorkspace?.(process.env)??Qi(process.env),o=t.permissionMode==="plan",i=t.permissionMode==="plan"?"default":t.permissionMode,s=t.resumeSessionId,c=0,p=0,f=this.activityHeartbeatMs(),T,U,te=!1,ge=!0,ae,ee=[],z=null,_=!1,Be=!1;function be(){z&&(z(),z=null)}function we(G){ee.push(G),be()}function Jr(){_=!0,be()}function fa(G){!G||Be||(Be=!0,we({type:"init",session_id:G}))}async function*ga(){for(;;){for(;ee.length>0;)yield ee.shift();if(_)return;await new Promise(G=>{z=G})}}let an=()=>Tl(t,i),Ia=G=>(T||(T=this.createCodexClient(G)),U||(ge&&t.resumeSessionId?U=T.resumeThread(t.resumeSessionId,an()):s?U=T.resumeThread(s,an()):U=T.startThread(an())),te&&s&&(U=T.resumeThread(s,an()),te=!1),U),Xr=async G=>{let Zn=Date.now();p+=1;let Qr="",er=!1,tr,nr,Zr=!1,ha=ge&&o?hl(G):G,un=st=>{er||(er=!0,we({type:"result",data:na(s??"",{duration_ms:Date.now()-Zn,total_cost_usd:c,num_turns:p,...st,session_id:s??""})}))},rr=async()=>{!nr||Zr||(Zr=!0,await nr())};try{let st=r?await r:void 0;st&&(nr=await st.prepareForTurn());let or=Ia(st?.env),eo=or.id??s??void 0;eo&&(s=eo),ae=new AbortController,t.abortController?.signal.aborted&&ae.abort(t.abortController.signal.reason),tr=setInterval(()=>{we({type:"activity"})},f);let ya=await or.runStreamed(ha,{signal:ae.signal});for await(let ne of ya.events)if(await rr(),ne.type==="thread.started"&&(s=ne.thread_id),fa(s??or.id??void 0),ne.type!=="thread.started"){if(ne.type==="item.completed"){(ne.item.type==="agent_message"||ne.item.type==="reasoning")&&(Qr+=`${ne.item.text}
44
- `,we({type:"text",text:ne.item.text}));continue}if(ne.type==="error"){we({type:"text",text:`[codex:error] ${ne.message}`});continue}if(ne.type==="turn.failed"){un({success:!1,result:ne.error.message,session_id:s??""});continue}if(ne.type==="turn.completed"){c+=gl(ne.usage);let to=Qr.slice(-500);Dn(to)&&we({type:"tool_use",name:ta,input:{text:to}}),un({success:!0,session_id:s??""})}}await rr(),er||un({success:!1,result:"Codex turn ended without terminal event",session_id:s??""})}catch(st){await rr(),un({success:!1,result:ra(st),session_id:s??""})}finally{tr&&clearInterval(tr),ae=void 0,ge=!1}},Qn=()=>{ae?.abort(t.abortController?.signal.reason??"interrupted")};return t.abortController?.signal&&t.abortController.signal.addEventListener("abort",Qn),(async()=>{try{let G=t.prompt;if(typeof G=="string"){await Xr(G);return}for await(let Zn of G)if(t.abortController?.signal.aborted||(await Xr(Il(Zn)),t.abortController?.signal.aborted))break}finally{if(t.abortController?.signal.removeEventListener("abort",Qn),r)try{await(await r).cleanup()}catch{}Jr()}})().catch(G=>{we({type:"result",data:na(s??"",{success:!1,result:ra(G),total_cost_usd:c,num_turns:p,session_id:s??""})}),t.abortController?.signal.removeEventListener("abort",Qn),Jr()}),{messages:ga(),async setPermissionMode(G){i=G,te=!0},async interrupt(){ae?.abort("interrupted")}}}buildUserMessage(t,n){return{type:"user",text:t,session_id:n}}};var Br=new Map;function oa(e){Br.set(e.name,e)}function Wr(e){let t=Br.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...Br.keys()].join(", ")}`);return t}function sa(){return Wr(nt())}oa(new Ln);oa(new jn);var ia=200,wl=120*1e3;function Gn(e){return e instanceof Error?e.message:String(e)}var Al={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},qr=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(t){this.queue.push(t),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(t=>{this.resolve=t})}}},Vn=class extends bl{id;name;harnessSessionId;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;multiTurn;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;pendingPlanApproval=!1;lobsterResumeToken;killReason="unknown";waitingForInputFired=!1;lastTurnHadQuestion=!1;planModeApproved=!1;autoRespondCount=0;timers=new Map;constructor(t,n){super(),this.id=Hi(8),this.name=n,this.harness=t.harness?Wr(t.harness):sa(),this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??rt(this.harness.name),this.reasoningEffort=t.reasoningEffort??Nt(this.harness.name),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??E.permissionMode,this.codexApprovalPolicy=this.harness.name==="codex"?t.codexApprovalPolicy??gt(this.harness.name)??E.codexApprovalPolicy:void 0,this.currentPermissionMode=this.harness.name==="codex"&&this.permissionMode==="plan"?"default":this.permissionMode,this.originChannel=t.originChannel,this.originThreadId=t.originThreadId,this.originAgentId=t.originAgentId,this.originSessionKey=t.originSessionKey,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.startedAt=Date.now(),this.abortController=new AbortController}get status(){return this._status}get harnessName(){return this.harness.name}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this._status!=="running"?this._status:this.harness.name==="codex"?"implementing":this.pendingPlanApproval?"awaiting-plan-approval":this.currentPermissionMode==="plan"?"planning":"implementing"}transition(t){if(!Al[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let n=this._status;this._status=t,this.emit("statusChange",this,t,n)}setTimer(t,n,r){this.clearTimer(t),this.timers.set(t,setTimeout(r,n))}clearTimer(t){let n=this.timers.get(t);n&&(clearTimeout(n),this.timers.delete(t))}clearAllTimers(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}async start(){try{let t;this.multiTurn?(this.messageStream=new qr,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let n=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,abortController:this.abortController,mcpServers:Si()});this.harnessHandle=n,this.setTimer("startup",wl,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let n=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:n});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let n=t instanceof Error?t.message:String(t),r=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${n}`,r),this.isActive&&this.transitionToTerminal("failed",{error:n})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.waitingForInputFired=!1;let n=t;if(this.pendingModeSwitch){let r=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(r),this.currentPermissionMode=r,this.pendingModeSwitch=void 0,i=!0,o=!0}catch(s){throw console.error(`[Session ${this.id}] setPermissionMode(${r}) FAILED: ${Gn(s)}`),this.pendingPlanApproval=!0,new Error(`Failed to switch permission mode to ${r}: ${Gn(s)}`)}else this.pendingModeSwitch=void 0,i=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);i&&(this.pendingPlanApproval=!1,r!=="plan"&&(this.planModeApproved=!0)),o&&(n=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
41
+ Use /agent_sessions to see active sessions or /agent_resume --list to see resumable sessions.`;return{text:`Error resuming session: ${Q}${N}`}}}})}function ji(e){e.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /agent_respond <id-or-name> <message>
42
+ /agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!0,o=o.slice(12).trim());let i=o.indexOf(" ");if(i===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let s=o.slice(0,i),c=o.slice(i+1).trim();return c?{text:(await Ln(g,{session:s,message:c,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}function Gi(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=g.getMetrics(),n=g.list("running").length;return{text:vn(t,n)}}})}var Up=50;function Vi(e){e.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=n.split(/\s+/),o="",i=!1,s=Up;for(let p=0;p<r.length;p++)if(r[p]==="--full")i=!0;else if(r[p]==="--lines"&&p+1<r.length){let f=parseInt(r[p+1],10);!isNaN(f)&&f>0&&(s=f),p++}else o||(o=r[p]);return o?{text:Nn(g,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}import{execFile as fa}from"child_process";import{existsSync as Xl}from"fs";import{fileURLToPath as ga}from"url";import{dirname as Ql,join as Yr}from"path";import{EventEmitter as wl}from"events";import Bi from"crypto";var Hi="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var _p=128,It,Dt,Lp=e=>{!It||It.length<e?(It=Buffer.allocUnsafe(e*_p),Bi.randomFillSync(It),Dt=0):Dt+e>It.length&&(Bi.randomFillSync(It),Dt=0),Dt+=e};var Wi=(e=21)=>{Lp(e|=0);let t="";for(let n=Dt-e;n<Dt;n++)t+=Hi[It[n]&63];return t};import{query as Kp}from"@anthropic-ai/claude-agent-sdk";var Kn=class{name="claude-code";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=["AskUserQuestion"];planApprovalToolNames=["ExitPlanMode","set_permission_mode"];launch(t){let n={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers};t.resumeSessionId&&(n.resume=t.resumeSessionId,n.forkSession=t.forkSession??!1);let r=Kp({prompt:t.prompt,options:n});return{messages:this.adaptMessages(r),async setPermissionMode(o){typeof r.setPermissionMode=="function"&&await r.setPermissionMode(o)},async streamInput(o){typeof r.streamInput=="function"&&await r.streamInput(o)},async interrupt(){typeof r.interrupt=="function"&&await r.interrupt()}}}buildUserMessage(t,n){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n}}async*adaptMessages(t){for await(let n of t){let r=n;if(r.type==="system"&&r.subtype==="init")yield{type:"init",session_id:r.session_id??""};else if(r.type==="system"&&r.subtype==="status"&&r.permissionMode)yield{type:"permission_mode_change",mode:r.permissionMode};else if(r.type==="assistant")for(let o of r.message?.content??[])o.type==="text"?yield{type:"text",text:o.text}:o.type==="tool_use"&&(yield{type:"tool_use",name:o.name,input:o.input});else r.type==="result"&&(yield{type:"result",data:{success:r.subtype==="success",duration_ms:r.duration_ms??0,total_cost_usd:r.total_cost_usd??0,num_turns:r.num_turns??0,result:r.result,session_id:r.session_id??""}})}}};import{parse as ul,resolve as dl}from"path";import{Codex as ta}from"@openai/codex-sdk";import{randomUUID as Dp}from"node:crypto";import{lstat as jp,mkdir as Br,readFile as Yi,readlink as Gp,realpath as Vp,rename as Hp,rm as Dn,symlink as Bp,writeFile as Ji}from"node:fs/promises";import{homedir as Wp,tmpdir as Xi}from"node:os";import{dirname as qp,join as $e,resolve as zp}from"node:path";var Yp=50,Jp=3e4,Xp=$e(Xi(),"openclaw-codex-auth.lock");function Qp(e,t){let n={};for(let[r,o]of Object.entries(e))typeof o=="string"&&(n[r]=o);return n.HOME=t,n}function Zp(e){return new Promise(t=>setTimeout(t,e))}async function Qi(e){try{return await jp(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function qi(e,t){if(await Qi(t)){if(await Gp(t)===e)return;await Dn(t,{recursive:!0,force:!0})}await Bp(e,t)}function el(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return null;let n=Number(t);if(Number.isFinite(n))return n;let r=Date.parse(t);if(Number.isFinite(r))return r}return null}async function zi(e){let t;try{t=await Yi(e,"utf8")}catch(n){return n.code==="ENOENT",null}try{let n=JSON.parse(t);if(!n||typeof n!="object")return null;let r=el(n.last_refresh);return r===null?null:{lastRefresh:r,raw:t}}catch{return null}}async function Zi(e,t){await Br(qp(e),{recursive:!0});let n=`${e}.tmp`;await Ji(n,t,"utf8"),await Hp(n,e)}async function tl(e,t){try{let n=await Yi(e,"utf8");await Zi(t,n)}catch(n){if(n.code!=="ENOENT")throw n;await Dn(t,{force:!0})}}async function nl(e,t){let n=await zi(e);if(!n)return;let r=await zi(t);r&&n.lastRefresh<=r.lastRefresh||await Zi(t,n.raw)}async function rl(e,t,n){let r=Date.now()+t;for(;;)try{await Br(e);break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()>=r)throw new Error(`Timed out waiting for Codex auth lock at ${e}`);await Zp(n)}try{await Ji($e(e,"holder.json"),JSON.stringify({pid:process.pid,acquired_at:new Date().toISOString()}),"utf8")}catch{}let o=!1;return async()=>{o||(o=!0,await Dn(e,{recursive:!0,force:!0}))}}async function ea(e=process.env,t={}){let n=e.HOME??Wp(),r=await Vp(n).catch(()=>zp(n)),o=$e(r,".codex"),i=$e(o,"auth.json"),s=$e(o,"sessions"),c=$e(o,"config.toml"),p=await Qi(c)?c:void 0,f=t.tempRootDir??Xi(),b=$e(f,`openclaw-codex-auth-${Dp()}`),k=$e(b,".codex"),X=$e(k,"auth.json"),ge=t.lockDir??Xp,Y=t.lockTimeoutMs??Jp,W=t.lockRetryMs??Yp;return await Br(k,{recursive:!0}),await qi(s,$e(k,"sessions")),p&&await qi(p,$e(k,"config.toml")),{tempHome:b,tempCodexDir:k,canonicalHome:r,canonicalCodexDir:o,canonicalAuthPath:i,canonicalSessionsPath:s,canonicalConfigPath:p,env:Qp(e,b),async prepareForTurn(){let Q=await rl(ge,Y,W);try{await tl(i,X)}catch(He){throw await Q(),He}let N=!1;return async()=>{if(!N){N=!0;try{await nl(X,i)}finally{await Q()}}}},async cleanup(){await Dn(b,{recursive:!0,force:!0})}}}var ol=["proceed","continue","implement","apply","run","merge","deploy","commit"],sl=["shall i proceed","do you want me to","would you like me to","please confirm","should i continue","can i proceed","should i proceed","should i go ahead","want me to continue","approve and i'll","confirm and i'll"],il=["why this failed was","why did this fail","what failed","what happened","how can i help","is this clear","any questions","anything else","let me know","would you like a summary"];function al(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function jn(e){let t=al(e);if(!t||il.some(r=>t.includes(r)))return!1;let n=ol.some(r=>t.includes(r));return sl.some(r=>t.includes(r))?n||t.includes("confirm"):t.endsWith("?")?n:!1}var na=1e4,ra="codex:waiting-for-user",cl=1.1/1e6,ml=.275/1e6,pl=4.4/1e6,ll="OPENCLAW_CODEX_HEARTBEAT_MS",fl="OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS",gl="OPENCLAW_CODEX_AUTH_STRATEGY";function Il(e){if(!e)return 0;let t=e.cached_input_tokens??0,n=Math.max(0,(e.input_tokens??0)-t),r=e.output_tokens??0;return n*cl+t*ml+r*pl}function oa(e,t={}){return{success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,session_id:e,...t}}function hl(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return String(e);let t=e;return typeof t.message?.content=="string"?t.message.content:typeof t.text=="string"?t.text:String(e)}function yl(e){return["[SYSTEM: First turn only. Do not implement yet.]","Start by producing a concise implementation plan only.","Then end your response with an explicit question asking whether you should proceed with implementation.","",e].join(`
43
+ `)}function sa(e){return e instanceof Error?e.message:String(e)}function xl(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Sl(e){return ul(dl(e)).root||"/"}function Tl(e){let n=[Sl(e)];return n.push(...xl(process.env[fl])),[...new Set(n)]}function bl(e,t){let r=(t??e.permissionMode)==="bypassPermissions"?Tl(e.cwd):void 0;return{model:e.model,modelReasoningEffort:e.reasoningEffort,workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:e.codexApprovalPolicy??"on-request",skipGitRepoCheck:!0,additionalDirectories:r}}var Gn=class{constructor(t={}){this.deps=t}name="codex";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=[ra];planApprovalToolNames=[];activityHeartbeatMs(){let t=Number.parseInt(process.env[ll]??String(na),10);return!Number.isFinite(t)||t<=0?na:t}createCodexClient(t){return this.deps.createCodex?.({env:t})??(t?new ta({env:t}):new ta)}launch(t){let r=process.env[gl]==="legacy"?void 0:this.deps.createAuthWorkspace?.(process.env)??ea(process.env),o=t.permissionMode==="plan",i=t.permissionMode==="plan"?"default":t.permissionMode,s=t.resumeSessionId,c=0,p=0,f=this.activityHeartbeatMs(),b,k,X=!1,ge=!0,Y,W=!1,Q=[],N=null,He=!1,be=!1;function yt(){N&&(N(),N=null)}function ot(G){Q.push(G),yt()}function Xr(){He=!0,yt()}function Ia(G){!G||be||(be=!0,ot({type:"init",session_id:G}))}async function*ha(){for(;;){for(;Q.length>0;)yield Q.shift();if(He)return;await new Promise(G=>{N=G})}}let un=()=>bl(t,i),ya=G=>(b||(b=this.createCodexClient(G)),k||(ge&&t.resumeSessionId?k=b.resumeThread(t.resumeSessionId,un()):s?k=b.resumeThread(s,un()):k=b.startThread(un())),X&&s&&(k=b.resumeThread(s,un()),X=!1),k),Qr=async G=>{let er=Date.now();p+=1;let Zr="",tr=!1,eo=!1,nr,rr,to=!1,xa=ge&&o?yl(G):G,dn=st=>{tr||(tr=!0,ot({type:"result",data:oa(s??"",{duration_ms:Date.now()-er,total_cost_usd:c,num_turns:p,...st,session_id:s??""})}))},or=async()=>{!rr||to||(to=!0,await rr())};try{let st=r?await r:void 0;st&&(rr=await st.prepareForTurn());let sr=ya(st?.env),no=sr.id??s??void 0;no&&(s=no),Y=new AbortController,t.abortController?.signal.aborted&&Y.abort(t.abortController.signal.reason),nr=setInterval(()=>{ot({type:"activity"})},f);let Sa=await sr.runStreamed(xa,{signal:Y.signal});for await(let re of Sa.events)if(await or(),re.type==="thread.started"&&(s=re.thread_id),Ia(s??sr.id??void 0),re.type!=="thread.started"){if(re.type==="item.completed"){(re.item.type==="agent_message"||re.item.type==="reasoning")&&(Zr+=`${re.item.text}
44
+ `,ot({type:"text",text:re.item.text}));continue}if(re.type==="error"){Y?.signal.aborted&&W||ot({type:"text",text:`[codex:error] ${re.message}`});continue}if(re.type==="turn.failed"){if(Y?.signal.aborted&&W){W=!1,eo=!0,X=!0;break}dn({success:!1,result:re.error.message,session_id:s??""});continue}if(re.type==="turn.completed"){c+=Il(re.usage);let ro=Zr.slice(-500);jn(ro)&&ot({type:"tool_use",name:ra,input:{text:ro}}),dn({success:!0,session_id:s??""})}}if(await or(),eo)return;tr||dn({success:!1,result:"Codex turn ended without terminal event",session_id:s??""})}catch(st){if(await or(),Y?.signal.aborted&&W){W=!1,X=!0;return}dn({success:!1,result:sa(st),session_id:s??""})}finally{nr&&clearInterval(nr),Y=void 0,ge=!1}},Zn=()=>{Y?.abort(t.abortController?.signal.reason??"interrupted")};return t.abortController?.signal&&t.abortController.signal.addEventListener("abort",Zn),(async()=>{try{let G=t.prompt;if(typeof G=="string"){await Qr(G);return}for await(let er of G)if(t.abortController?.signal.aborted||(await Qr(hl(er)),t.abortController?.signal.aborted))break}finally{if(t.abortController?.signal.removeEventListener("abort",Zn),r)try{await(await r).cleanup()}catch{}Xr()}})().catch(G=>{ot({type:"result",data:oa(s??"",{success:!1,result:sa(G),total_cost_usd:c,num_turns:p,session_id:s??""})}),t.abortController?.signal.removeEventListener("abort",Zn),Xr()}),{messages:ha(),async setPermissionMode(G){i=G,X=!0},async interrupt(){Y&&(W=!0,Y.abort("interrupted"))}}}buildUserMessage(t,n){return{type:"user",text:t,session_id:n}}};var Wr=new Map;function ia(e){Wr.set(e.name,e)}function qr(e){let t=Wr.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...Wr.keys()].join(", ")}`);return t}function aa(){return qr(tt())}ia(new Kn);ia(new Gn);var ua=200,Al=120*1e3;function Vn(e){return e instanceof Error?e.message:String(e)}var Pl={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},zr=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(t){this.queue.push(t),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(t=>{this.resolve=t})}}},Hn=class extends wl{id;name;harnessSessionId;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;codexApprovalPolicy;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;multiTurn;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;pendingPlanApproval=!1;lobsterResumeToken;killReason="unknown";waitingForInputFired=!1;lastTurnHadQuestion=!1;planModeApproved=!1;turnInProgress=!0;autoRespondCount=0;timers=new Map;constructor(t,n){super(),this.id=Wi(8),this.name=n,this.harness=t.harness?qr(t.harness):aa(),this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??nt(this.harness.name),this.reasoningEffort=t.reasoningEffort??Ut(this.harness.name),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??F.permissionMode,this.codexApprovalPolicy=this.harness.name==="codex"?t.codexApprovalPolicy??gt(this.harness.name)??F.codexApprovalPolicy:void 0,this.currentPermissionMode=this.harness.name==="codex"&&this.permissionMode==="plan"?"default":this.permissionMode,this.originChannel=t.originChannel,this.originThreadId=t.originThreadId,this.originAgentId=t.originAgentId,this.originSessionKey=t.originSessionKey,this.resumeSessionId=t.resumeSessionId,this.forkSession=t.forkSession,this.multiTurn=t.multiTurn??!0,this.startedAt=Date.now(),this.abortController=new AbortController}get status(){return this._status}get harnessName(){return this.harness.name}get duration(){return(this.completedAt??Date.now())-this.startedAt}get phase(){return this._status!=="running"?this._status:this.harness.name==="codex"?"implementing":this.pendingPlanApproval?"awaiting-plan-approval":this.currentPermissionMode==="plan"?"planning":"implementing"}transition(t){if(!Pl[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let n=this._status;this._status=t,this.emit("statusChange",this,t,n)}setTimer(t,n,r){this.clearTimer(t),this.timers.set(t,setTimeout(r,n))}clearTimer(t){let n=this.timers.get(t);n&&(clearTimeout(n),this.timers.delete(t))}clearAllTimers(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}async start(){try{let t;this.multiTurn?(this.messageStream=new zr,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let n=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,abortController:this.abortController,mcpServers:bi()});this.harnessHandle=n,this.setTimer("startup",Al,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let n=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:n});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let n=t instanceof Error?t.message:String(t),r=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${n}`,r),this.isActive&&this.transitionToTerminal("failed",{error:n})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.waitingForInputFired=!1,this.turnInProgress=!0;let n=t;if(this.pendingModeSwitch){let r=this.pendingModeSwitch,o=!1,i=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(r),this.currentPermissionMode=r,this.pendingModeSwitch=void 0,i=!0,o=!0}catch(s){throw console.error(`[Session ${this.id}] setPermissionMode(${r}) FAILED: ${Vn(s)}`),this.pendingPlanApproval=!0,new Error(`Failed to switch permission mode to ${r}: ${Vn(s)}`)}else this.pendingModeSwitch=void 0,i=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);i&&(this.pendingPlanApproval=!1,r!=="plan"&&(this.planModeApproved=!0)),o&&(n=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
45
45
 
46
46
  ${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved){let r=this.harness.planApprovalToolNames;if(n=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below,${r.length>0?` then call ${r.join(" or ")} again to re-submit for approval.`:" then re-submit your revised plan for approval."} Do NOT start implementing yet.]
47
47
 
48
- ${t}`,this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan"}catch(i){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${Gn(i)}`)}}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(n,this.harnessSessionId??""));else if(this.harnessHandle?.streamInput){let r=this.harness.buildUserMessage(n,this.harnessSessionId??"");async function*o(){yield r}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){this.harnessHandle?.interrupt&&await this.harnessHandle.interrupt()}switchPermissionMode(t){this.pendingModeSwitch=t}get isActive(){return this._status==="starting"||this._status==="running"}kill(t){this.transitionToTerminal("killed",{reason:t})}complete(t="done"){this.transitionToTerminal("completed",{reason:t})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}resetIdleTimer(){if(!this.multiTurn)return;let t=(E.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",t,()=>{this._status==="running"&&this.kill("idle-timeout")})}teardown(){this.clearAllTimers(),this.completedAt||(this.completedAt=Date.now()),this.messageStream&&this.messageStream.end(),this.harnessHandle?.interrupt&&this.harnessHandle.interrupt().catch(t=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${Gn(t)}`)}),this.abortController.abort()}transitionToTerminal(t,n={}){this.isActive&&(n.reason&&(this.killReason=n.reason),n.error!==void 0&&(this.error=n.error),this.completedAt=Date.now(),this.transition(t),this.teardown())}async consumeMessages(t){for await(let n of t){if(!this.isActive)break;if(this.resetIdleTimer(),n.type==="init")this.clearTimer("startup"),this.harnessSessionId=n.session_id,this._status==="starting"&&this.transition("running");else if(n.type==="text")this.waitingForInputFired=!1,this.pendingPlanApproval||(this.lastTurnHadQuestion=!1),this.outputBuffer.push(n.text),this.outputBuffer.length>ia&&this.outputBuffer.splice(0,this.outputBuffer.length-ia),this.emit("output",this,n.text);else if(n.type==="tool_use")this.harness.questionToolNames.includes(n.name)?(this.lastTurnHadQuestion=!0,this.currentPermissionMode==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0)):this.harness.planApprovalToolNames.includes(n.name)&&!this.planModeApproved&&(this.lastTurnHadQuestion=!0,this.pendingPlanApproval=!0),this.emit("toolUse",this,n.name,n.input);else if(n.type==="permission_mode_change"){let r=this.currentPermissionMode;this.currentPermissionMode=n.mode,n.mode!=="plan"&&r==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0,this.lastTurnHadQuestion=!0)}else if(n.type==="result"){if(this.result={subtype:n.data.success?"success":"error",duration_ms:n.data.duration_ms,total_cost_usd:n.data.total_cost_usd,num_turns:n.data.num_turns,result:n.data.result,is_error:!n.data.success,session_id:n.data.session_id},this.costUsd=n.data.total_cost_usd,this.multiTurn&&this.messageStream&&n.data.success){this.resetIdleTimer(),this.currentPermissionMode==="plan"&&!this.pendingPlanApproval&&!this.planModeApproved&&(this.pendingPlanApproval=!0);let o=this.pendingPlanApproval||this.lastTurnHadQuestion,i=this.messageStream?.hasPending()===!0;o&&!this.waitingForInputFired?(this.waitingForInputFired=!0,this.emit("turnEnd",this,!0)):i||o||(this.emit("turnEnd",this,!1),this.complete("done"))}else this.transitionToTerminal(n.data.success?"completed":"failed");this.lastTurnHadQuestion=!1}else n.type}}};import{mkdirSync as Pl,readFileSync as Rl,readdirSync as Ol,renameSync as Cl,statSync as Ml,unlinkSync as El,writeFileSync as aa}from"fs";import{homedir as kl,tmpdir as ua}from"os";import{dirname as Fl,join as Bn}from"path";function $l(e){let t=e.OPENCLAW_HOME?.trim();return t||Bn(kl(),".openclaw")}function vl(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||Bn($l(e),"code-agent-sessions.json")}var Nl=new Set(["completed","failed","killed"]),Ul=new Set(["running","completed","failed","killed"]),_l=1440*60*1e3;function da(e){return e instanceof Error?e.message:String(e)}function Ll(e){return!!e&&typeof e=="object"}function Hn(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function ht(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function ca(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Kl(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function Dl(e){return e==="default"||e==="plan"||e==="acceptEdits"||e==="bypassPermissions"?e:void 0}function jl(e){return e==="never"||e==="on-request"?e:void 0}function Gl(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function Vl(e){if(typeof e=="string"&&Ul.has(e))return e==="running"?"killed":e}function Hl(e){if(!Ll(e))return;let t=Hn(e.harnessSessionId);if(!t)return;let n=Vl(e.status);if(n)return{sessionId:ht(e.sessionId),harnessSessionId:t,name:Hn(e.name,t),prompt:Hn(e.prompt),workdir:Hn(e.workdir,"(unknown)"),model:ht(e.model),reasoningEffort:Kl(e.reasoningEffort),createdAt:ca(e.createdAt),completedAt:ca(e.completedAt),status:n,killReason:Gl(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:ht(e.originAgentId),originChannel:ht(e.originChannel),originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originSessionKey:ht(e.originSessionKey),outputPath:ht(e.outputPath),harness:ht(e.harness),currentPermissionMode:Dl(e.currentPermissionMode),codexApprovalPolicy:jl(e.codexApprovalPolicy)}}var Wn=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;indexPath;constructor(t={}){let n=t.env??process.env;this.indexPath=t.indexPath??vl(n),n.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){try{let t=Rl(this.indexPath,"utf-8"),n=JSON.parse(t);if(!Array.isArray(n))return;let r=!1;for(let o of n){let i=Hl(o);if(!i){r=!0;continue}this.persisted.set(i.harnessSessionId,i),i.sessionId&&this.idIndex.set(i.sessionId,i.harnessSessionId),i.name&&this.nameIndex.set(i.name,i.harnessSessionId)}r&&this.saveIndex()}catch{}}saveIndex(){try{Pl(Fl(this.indexPath),{recursive:!0});let t=this.indexPath+".tmp";aa(t,JSON.stringify([...this.persisted.values()],null,2),"utf-8"),Cl(t,this.indexPath)}catch(t){console.warn(`[SessionStore] Failed to save session index: ${da(t)}`)}}markRunning(t){if(!t.harnessSessionId)return;let n={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy};this.persisted.set(n.harnessSessionId,n),this.idIndex.set(t.id,n.harnessSessionId),this.nameIndex.set(t.name,n.harnessSessionId),this.saveIndex()}hasRecordedSession(t){return this.idIndex.has(t)}persistTerminal(t){if(!t.harnessSessionId)return;let n;try{let o=Bn(ua(),`openclaw-agent-${t.id}.txt`),i=t.getOutput().join(`
49
- `);i.length>0&&(aa(o,i,"utf-8"),n=o)}catch(o){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${da(o)}`)}let r={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,completedAt:t.completedAt,status:t.status,killReason:t.killReason,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,outputPath:n,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy};this.persisted.set(t.harnessSessionId,r),this.idIndex.set(t.id,t.harnessSessionId),this.nameIndex.set(t.name,t.harnessSessionId),this.saveIndex()}getLatestPersistedByName(t){let n,r=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=0;for(let c of this.persisted.values()){if(c.name!==t){s++;continue}let p=c.createdAt??Number.NEGATIVE_INFINITY,f=c.completedAt??Number.NEGATIVE_INFINITY;(p>r||p===r&&f>o||p===r&&f===o&&s>i)&&(n=c,r=p,o=f,i=s),s++}return n}resolveHarnessSessionId(t,n){if(n)return n;let r=this.idIndex.get(t);if(r&&this.persisted.has(r))return r;let o=this.getLatestPersistedByName(t);if(o)return o.harnessSessionId;if(this.persisted.has(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return t}getPersistedSession(t){let n=this.persisted.get(t);if(n)return n;let r=this.idIndex.get(t);return r?this.persisted.get(r):this.getLatestPersistedByName(t)}listPersistedSessions(){return[...this.persisted.values()].sort((t,n)=>(n.completedAt??0)-(t.completedAt??0))}cleanupTmpOutputFiles(t){try{let n=ua(),r=Ol(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r)try{let i=Bn(n,o),s=Ml(i).mtimeMs;t-s>_l&&El(i)}catch{}}catch{}}evictOldestPersisted(t){let n=this.listPersistedSessions();if(n.length<=t)return;let r=n.slice(t);for(let o of r){this.persisted.delete(o.harnessSessionId);for(let[i,s]of this.idIndex)s===o.harnessSessionId&&this.idIndex.delete(i);for(let[i,s]of this.nameIndex)s===o.harnessSessionId&&this.nameIndex.delete(i)}this.saveIndex()}shouldGcActiveSession(t,n,r){return!t.completedAt||!Nl.has(t.status)?!1:n-t.completedAt>r}};var Bl=new Set(["completed","failed","killed"]),qn=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(t){let n=t.costUsd??0,r=t.status;this.metrics.totalCostUsd+=n;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+n),Bl.has(r)&&this.metrics.sessionsByStatus[r]++,t.completedAt){let i=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||n>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:n,prompt:ot(t.prompt,80)})}getMetrics(){return{totalCostUsd:this.metrics.totalCostUsd,costPerDay:new Map(this.metrics.costPerDay),sessionsByStatus:{...this.metrics.sessionsByStatus},totalLaunched:this.metrics.totalLaunched,totalDurationMs:this.metrics.totalDurationMs,sessionsWithDuration:this.metrics.sessionsWithDuration,mostExpensive:this.metrics.mostExpensive?{...this.metrics.mostExpensive}:null}}};import{execFile as Wl}from"child_process";import{randomUUID as ql}from"crypto";var ma=3e4,zl=2e3,Yl=2e4,zn=4,Yn=class{pendingRetryTimers=new Set;clearPendingRetries(){for(let t of this.pendingRetryTimers)clearTimeout(t);this.pendingRetryTimers.clear()}getOriginSessionKey(t){let n=t.originSessionKey?.trim();return n||void 0}getOriginThreadId(t){let n=t.originThreadId;return n==null?void 0:String(n).trim()||void 0}parseNotificationRoute(t){let n=t.originChannel?.trim(),r=this.getOriginThreadId(t);if(n){let s=n.split("|").map(c=>c.trim()).filter(Boolean);if(s.length>=2){let[c,p,f]=s,T=f??p,U=f?p:void 0;if(c&&T)return{channel:c,target:T,accountId:U,threadId:r??this.parseThreadIdFromSessionKey(t.originSessionKey)}}}let o=this.getOriginSessionKey(t);if(!o)return;let i=o.match(/^agent:[^:]+:telegram:(?:direct|dm|group|channel):([^:]+)(?::topic:(\d+))?$/i);if(i?.[1])return{channel:"telegram",target:i[1],threadId:r??i[2]}}parseThreadIdFromSessionKey(t){return t?t.match(/:topic:(\d+)$/)?.[1]:void 0}retryDelayMs(t){let n=Math.max(0,t-1),r=zl*2**n;return Math.min(r,Yl)}executeWithRetries(t,n,r=1){let o=Date.now();console.info(`[WakeDispatcher] ${n.target} ${n.phase} started attempt ${r}/${zn} for ${n.label} session=${n.sessionId}`),Wl("openclaw",t,{timeout:ma},i=>{let s=Date.now()-o;if(!i){console.info(`[WakeDispatcher] ${n.target} ${n.phase} completed attempt ${r}/${zn} for ${n.label} session=${n.sessionId} in ${s}ms`);return}let c=`[WakeDispatcher] ${n.target} ${n.phase} failed`;if(r>=zn){console.error(`${c} after ${r} attempts for ${n.label} session=${n.sessionId} in ${s}ms: ${i.message}`),n.onFinalFailure?.();return}let p=this.retryDelayMs(r);console.error(`${c} attempt ${r}/${zn} for ${n.label} session=${n.sessionId} in ${s}ms: ${i.message}. Retrying in ${p}ms`);let f=setTimeout(()=>{this.pendingRetryTimers.delete(f),this.executeWithRetries(t,n,r+1)},p);this.pendingRetryTimers.add(f)})}fireChatSendWithRetry(t,n,r,o,i,s=!1,c){let p=["gateway","call","chat.send","--expect-final","--timeout",String(ma),"--params",JSON.stringify({sessionKey:t,message:n,deliver:s,idempotencyKey:ql()})];this.executeWithRetries(p,{label:r,sessionId:o,target:"chat.send",phase:i,onFinalFailure:c})}fireDirectNotificationWithRetry(t,n,r,o,i){let s=["message","send","--channel",t.channel,"--target",t.target,"--message",n];t.accountId&&s.push("--account",t.accountId),t.threadId&&s.push("--thread-id",t.threadId),this.executeWithRetries(s,{label:r,sessionId:o,target:"message.send",phase:"notify",onFinalFailure:i})}fireSystemEventWithRetry(t,n,r,o){let i=["system","event","--text",t,"--mode","now"];this.executeWithRetries(i,{label:n,sessionId:r,target:"system.event",phase:o})}sendUserNotification(t,n,r,o){let i=this.parseNotificationRoute(t);if(!i){this.fireSystemEventWithRetry(n,`${r}-notify-system`,o,"notify");return}this.fireDirectNotificationWithRetry(i,n,`${r}-notify`,o,()=>{this.fireSystemEventWithRetry(n,`${r}-notify-fallback`,o,"notify")})}dispatchSessionNotification(t,n){let r=this.getOriginSessionKey(t),o=n.notifyUser??(n.wakeMessage?"on-wake-fallback":"always"),i=n.userMessage?.trim(),s=n.wakeMessage?.trim();if(o==="always"&&i&&this.sendUserNotification(t,i,n.label,t.id),!!s){if(!r){o==="on-wake-fallback"&&i&&this.sendUserNotification(t,i,n.label,t.id),this.fireSystemEventWithRetry(s,`${n.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(r,s,`${n.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(s,`${n.label}-wake-fallback`,t.id,"wake")})}}};function Ql(){let e=process.env.OPENCLAW_CODE_AGENT_PLAN_WORKFLOW_PATH?.trim();if(e)return e;let t=Xl(la(import.meta.url)),n=[zr(process.cwd(),"workflows","plan-approval.lobster"),zr(t,"..","workflows","plan-approval.lobster"),zr(t,"..","..","workflows","plan-approval.lobster")];for(let r of n)if(Jl(r))return r;return la(new URL("../workflows/plan-approval.lobster",import.meta.url))}var Zl=Ql(),Yr=new Set(["completed","failed","killed"]),Jn=new Set(["starting","running"]),ef=5e3,tf=3e4;function nf(e){let t=e.trim();if(!t)return;let n=i=>typeof i=="string"&&i.trim().length>0&&/^[A-Za-z0-9._:-]+$/.test(i.trim()),r=[t];for(let i of t.split(/\r?\n/)){let s=i.trim();s.startsWith("{")&&s.endsWith("}")&&r.push(s)}for(let i of r)try{let s=JSON.parse(i),c=s?.resumeToken??s?.requiresApproval?.resumeToken??s?.details?.requiresApproval?.resumeToken;if(n(c))return c.trim()}catch{}let o=t.match(/"resumeToken"\s*:\s*"([^"]+)"/);if(o&&n(o[1]))return o[1].trim()}var Xn=class{sessions=new Map;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;store;metrics;wakeDispatcher;constructor(t=20,n=50){this.maxSessions=t,this.maxPersistedSessions=n,this.store=new Wn,this.metrics=new qn,this.wakeDispatcher=new Yn}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(t){let n=new Set([...this.sessions.values()].filter(o=>Jn.has(o.status)).map(o=>o.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}-${r}`);)r++;return`${t}-${r}`}spawn(t,n={}){if([...this.sessions.values()].filter(c=>Jn.has(c.status)).length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);let o=t.name||Ri(t.prompt),i=this.uniqueName(o);i!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${i}" (active session with same name exists)`);let s=new Vn(t,i);if(this.sessions.set(s.id,s),this.metrics.incrementLaunched(),s.on("statusChange",(c,p)=>{p==="running"&&s.harnessSessionId?this.store.markRunning(s):Yr.has(p)&&this.onSessionTerminal(s)}),s.on("turnEnd",(c,p)=>{this.onTurnEnd(s,p)}),s.start(),n.notifyLaunch!==!1){let c=`\u{1F680} [${s.name}] Launched | ${s.workdir} | ${s.model??"default"}`;this.notifySession(s,c,"launch")}return s}async spawnAndAwaitRunning(t,n={}){let r=this.spawn(t,n);return await this.waitForRunningSession(r),r}async waitForRunningSession(t){if(t.status==="running")return;if(Yr.has(t.status))throw new Error(this.describeLaunchFailure(t));let n=t.on?.bind(t),r=t.off?.bind(t)??t.removeListener?.bind(t);if(!n||!r)throw new Error(`Session ${t.name} [${t.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(p,f)=>{if(f==="running"){c(),o();return}Yr.has(f)&&(c(),i(new Error(this.describeLaunchFailure(t))))},c=()=>{r("statusChange",s)};n("statusChange",s)})}describeLaunchFailure(t){let n=t.killReason?` (reason: ${t.killReason})`:"",r=t.error||t.result?.result||`status=${t.status}${n}`;return`Session ${t.name} [${t.id}] failed to start: ${r}`}onSessionTerminal(t){if(this.persistSession(t),this.lastWaitingEventTimestamps.delete(t.id),t.killReason==="done")return;if(t.status==="completed"){if(!this.shouldEmitTerminalWake(t))return;this.triggerAgentEvent(t);return}if(t.status==="failed"){if(!this.shouldEmitTerminalWake(t))return;let c=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`,p=ot(c,200);this.triggerFailedEvent(t,p);return}let n=`$${(t.costUsd??0).toFixed(2)}`,r=Le(t.duration),i={user:"by agent/user","idle-timeout":`idle ${E.idleTimeoutMinutes??15}min`,shutdown:"gateway shutdown",unknown:""}[t.killReason]||"",s=`Killed${i?` (${i})`:""}`;this.notifySession(t,`\u26D4 [${t.name}] ${s} | ${n} | ${r}`)}persistSession(t){this.store.hasRecordedSession(t.id)||this.metrics.recordSession(t),this.store.persistTerminal(t)}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(t){this.metrics.recordSession(t)}notifySession(t,n,r="notification"){this.dispatchSessionNotification(t,{label:r,userMessage:n,notifyUser:"always"})}dispatchSessionNotification(t,n){this.wakeDispatcher.dispatchSessionNotification(t,n)}runLobsterApproval(t,n){let r=JSON.stringify({session_id:t.id,session_name:t.name,plan_summary:n}),o=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"run",pipeline:Zl,argsJson:r,timeoutMs:0})];pa("openclaw",o,{timeout:tf},(i,s,c)=>{if(i){console.error(`[SessionManager] Lobster launch failed for session=${t.id}: ${i.message}`),this.notifySession(t,`\u{1F4CB} [${t.name}] Plan ready \u2014 Lobster gate failed, please review manually:
48
+ ${t}`,this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan"}catch(i){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${Vn(i)}`)}}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(n,this.harnessSessionId??""));else if(this.harnessHandle?.streamInput){let r=this.harness.buildUserMessage(n,this.harnessSessionId??"");async function*o(){yield r}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){return!this.turnInProgress||!this.harnessHandle?.interrupt?!1:(await this.harnessHandle.interrupt(),!0)}switchPermissionMode(t){this.pendingModeSwitch=t}get isActive(){return this._status==="starting"||this._status==="running"}kill(t){this.transitionToTerminal("killed",{reason:t})}complete(t="done"){this.transitionToTerminal("completed",{reason:t})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}resetIdleTimer(){if(!this.multiTurn)return;let t=(F.idleTimeoutMinutes??15)*60*1e3;this.setTimer("idle",t,()=>{this._status==="running"&&this.kill("idle-timeout")})}teardown(){this.clearAllTimers(),this.completedAt||(this.completedAt=Date.now()),this.messageStream&&this.messageStream.end(),this.harnessHandle?.interrupt&&this.harnessHandle.interrupt().catch(t=>{console.warn(`[Session ${this.id}] interrupt during teardown failed: ${Vn(t)}`)}),this.abortController.abort()}transitionToTerminal(t,n={}){this.isActive&&(this.turnInProgress=!1,n.reason&&(this.killReason=n.reason),n.error!==void 0&&(this.error=n.error),this.completedAt=Date.now(),this.transition(t),this.teardown())}async consumeMessages(t){for await(let n of t){if(!this.isActive)break;if(this.resetIdleTimer(),n.type==="init")this.clearTimer("startup"),this.harnessSessionId=n.session_id,this._status==="starting"&&this.transition("running");else if(n.type==="text")this.waitingForInputFired=!1,this.pendingPlanApproval||(this.lastTurnHadQuestion=!1),this.outputBuffer.push(n.text),this.outputBuffer.length>ua&&this.outputBuffer.splice(0,this.outputBuffer.length-ua),this.emit("output",this,n.text);else if(n.type==="tool_use")this.harness.questionToolNames.includes(n.name)?(this.lastTurnHadQuestion=!0,this.currentPermissionMode==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0)):this.harness.planApprovalToolNames.includes(n.name)&&!this.planModeApproved&&(this.lastTurnHadQuestion=!0,this.pendingPlanApproval=!0),this.emit("toolUse",this,n.name,n.input);else if(n.type==="permission_mode_change"){let r=this.currentPermissionMode;this.currentPermissionMode=n.mode,n.mode!=="plan"&&r==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0,this.lastTurnHadQuestion=!0)}else if(n.type==="result"){if(this.result={subtype:n.data.success?"success":"error",duration_ms:n.data.duration_ms,total_cost_usd:n.data.total_cost_usd,num_turns:n.data.num_turns,result:n.data.result,is_error:!n.data.success,session_id:n.data.session_id},this.costUsd=n.data.total_cost_usd,this.multiTurn&&this.messageStream&&n.data.success){this.resetIdleTimer(),this.currentPermissionMode==="plan"&&!this.pendingPlanApproval&&!this.planModeApproved&&(this.pendingPlanApproval=!0);let o=this.pendingPlanApproval||this.lastTurnHadQuestion,i=this.messageStream?.hasPending()===!0;this.turnInProgress=i,o&&!this.waitingForInputFired?(this.waitingForInputFired=!0,this.emit("turnEnd",this,!0)):i||o||(this.emit("turnEnd",this,!1),this.complete("done"))}else this.turnInProgress=!1,this.transitionToTerminal(n.data.success?"completed":"failed");this.lastTurnHadQuestion=!1}else n.type}}};import{mkdirSync as Rl,readFileSync as Ol,readdirSync as Cl,renameSync as Ml,statSync as El,unlinkSync as Fl,writeFileSync as da}from"fs";import{homedir as kl,tmpdir as ca}from"os";import{dirname as $l,join as Wn}from"path";function vl(e){let t=e.OPENCLAW_HOME?.trim();return t||Wn(kl(),".openclaw")}function Nl(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||Wn(vl(e),"code-agent-sessions.json")}var Ul=new Set(["completed","failed","killed"]),_l=new Set(["running","completed","failed","killed"]),Ll=1440*60*1e3;function ma(e){return e instanceof Error?e.message:String(e)}function Kl(e){return!!e&&typeof e=="object"}function Bn(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function ht(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function pa(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Dl(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function jl(e){return e==="default"||e==="plan"||e==="acceptEdits"||e==="bypassPermissions"?e:void 0}function Gl(e){return e==="never"||e==="on-request"?e:void 0}function Vl(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function Hl(e){if(typeof e=="string"&&_l.has(e))return e==="running"?"killed":e}function Bl(e){if(!Kl(e))return;let t=Bn(e.harnessSessionId);if(!t)return;let n=Hl(e.status);if(n)return{sessionId:ht(e.sessionId),harnessSessionId:t,name:Bn(e.name,t),prompt:Bn(e.prompt),workdir:Bn(e.workdir,"(unknown)"),model:ht(e.model),reasoningEffort:Dl(e.reasoningEffort),createdAt:pa(e.createdAt),completedAt:pa(e.completedAt),status:n,killReason:Vl(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:ht(e.originAgentId),originChannel:ht(e.originChannel),originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originSessionKey:ht(e.originSessionKey),outputPath:ht(e.outputPath),harness:ht(e.harness),currentPermissionMode:jl(e.currentPermissionMode),codexApprovalPolicy:Gl(e.codexApprovalPolicy)}}var qn=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;indexPath;constructor(t={}){let n=t.env??process.env;this.indexPath=t.indexPath??Nl(n),n.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){try{let t=Ol(this.indexPath,"utf-8"),n=JSON.parse(t);if(!Array.isArray(n))return;let r=!1;for(let o of n){let i=Bl(o);if(!i){r=!0;continue}this.persisted.set(i.harnessSessionId,i),i.sessionId&&this.idIndex.set(i.sessionId,i.harnessSessionId),i.name&&this.nameIndex.set(i.name,i.harnessSessionId)}r&&this.saveIndex()}catch{}}saveIndex(){try{Rl($l(this.indexPath),{recursive:!0});let t=this.indexPath+".tmp";da(t,JSON.stringify([...this.persisted.values()],null,2),"utf-8"),Ml(t,this.indexPath)}catch(t){console.warn(`[SessionStore] Failed to save session index: ${ma(t)}`)}}markRunning(t){if(!t.harnessSessionId)return;let n={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy};this.persisted.set(n.harnessSessionId,n),this.idIndex.set(t.id,n.harnessSessionId),this.nameIndex.set(t.name,n.harnessSessionId),this.saveIndex()}hasRecordedSession(t){return this.idIndex.has(t)}persistTerminal(t){if(!t.harnessSessionId)return;let n;try{let o=Wn(ca(),`openclaw-agent-${t.id}.txt`),i=t.getOutput().join(`
49
+ `);i.length>0&&(da(o,i,"utf-8"),n=o)}catch(o){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${ma(o)}`)}let r={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,completedAt:t.completedAt,status:t.status,killReason:t.killReason,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,outputPath:n,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy};this.persisted.set(t.harnessSessionId,r),this.idIndex.set(t.id,t.harnessSessionId),this.nameIndex.set(t.name,t.harnessSessionId),this.saveIndex()}getLatestPersistedByName(t){let n,r=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=0;for(let c of this.persisted.values()){if(c.name!==t){s++;continue}let p=c.createdAt??Number.NEGATIVE_INFINITY,f=c.completedAt??Number.NEGATIVE_INFINITY;(p>r||p===r&&f>o||p===r&&f===o&&s>i)&&(n=c,r=p,o=f,i=s),s++}return n}resolveHarnessSessionId(t,n){if(n)return n;let r=this.idIndex.get(t);if(r&&this.persisted.has(r))return r;let o=this.getLatestPersistedByName(t);if(o)return o.harnessSessionId;if(this.persisted.has(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return t}getPersistedSession(t){let n=this.persisted.get(t);if(n)return n;let r=this.idIndex.get(t);return r?this.persisted.get(r):this.getLatestPersistedByName(t)}listPersistedSessions(){return[...this.persisted.values()].sort((t,n)=>(n.completedAt??0)-(t.completedAt??0))}cleanupTmpOutputFiles(t){try{let n=ca(),r=Cl(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r)try{let i=Wn(n,o),s=El(i).mtimeMs;t-s>Ll&&Fl(i)}catch{}}catch{}}evictOldestPersisted(t){let n=this.listPersistedSessions();if(n.length<=t)return;let r=n.slice(t);for(let o of r){this.persisted.delete(o.harnessSessionId);for(let[i,s]of this.idIndex)s===o.harnessSessionId&&this.idIndex.delete(i);for(let[i,s]of this.nameIndex)s===o.harnessSessionId&&this.nameIndex.delete(i)}this.saveIndex()}shouldGcActiveSession(t,n,r){return!t.completedAt||!Ul.has(t.status)?!1:n-t.completedAt>r}};var Wl=new Set(["completed","failed","killed"]),zn=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(t){let n=t.costUsd??0,r=t.status;this.metrics.totalCostUsd+=n;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+n),Wl.has(r)&&this.metrics.sessionsByStatus[r]++,t.completedAt){let i=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||n>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:n,prompt: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 ql}from"child_process";import{randomUUID as zl}from"crypto";var la=3e4,Yl=2e3,Jl=2e4,Yn=4,Jn=class{pendingRetryTimers=new Set;clearPendingRetries(){for(let t of this.pendingRetryTimers)clearTimeout(t);this.pendingRetryTimers.clear()}getOriginSessionKey(t){let n=t.originSessionKey?.trim();return n||void 0}getOriginThreadId(t){let n=t.originThreadId;return n==null?void 0:String(n).trim()||void 0}parseNotificationRoute(t){let n=t.originChannel?.trim(),r=this.getOriginThreadId(t);if(n){let s=n.split("|").map(c=>c.trim()).filter(Boolean);if(s.length>=2){let[c,p,f]=s,b=f??p,k=f?p:void 0;if(c&&b)return{channel:c,target:b,accountId:k,threadId:r??this.parseThreadIdFromSessionKey(t.originSessionKey)}}}let o=this.getOriginSessionKey(t);if(!o)return;let i=o.match(/^agent:[^:]+:telegram:(?:direct|dm|group|channel):([^:]+)(?::topic:(\d+))?$/i);if(i?.[1])return{channel:"telegram",target:i[1],threadId:r??i[2]}}parseThreadIdFromSessionKey(t){return t?t.match(/:topic:(\d+)$/)?.[1]:void 0}retryDelayMs(t){let n=Math.max(0,t-1),r=Yl*2**n;return Math.min(r,Jl)}executeWithRetries(t,n,r=1){let o=Date.now();console.info(`[WakeDispatcher] ${n.target} ${n.phase} started attempt ${r}/${Yn} for ${n.label} session=${n.sessionId}`),ql("openclaw",t,{timeout:la},i=>{let s=Date.now()-o;if(!i){console.info(`[WakeDispatcher] ${n.target} ${n.phase} completed attempt ${r}/${Yn} for ${n.label} session=${n.sessionId} in ${s}ms`);return}let c=`[WakeDispatcher] ${n.target} ${n.phase} failed`;if(r>=Yn){console.error(`${c} after ${r} attempts for ${n.label} session=${n.sessionId} in ${s}ms: ${i.message}`),n.onFinalFailure?.();return}let p=this.retryDelayMs(r);console.error(`${c} attempt ${r}/${Yn} for ${n.label} session=${n.sessionId} in ${s}ms: ${i.message}. Retrying in ${p}ms`);let f=setTimeout(()=>{this.pendingRetryTimers.delete(f),this.executeWithRetries(t,n,r+1)},p);this.pendingRetryTimers.add(f)})}fireChatSendWithRetry(t,n,r,o,i,s=!1,c){let p=["gateway","call","chat.send","--expect-final","--timeout",String(la),"--params",JSON.stringify({sessionKey:t,message:n,deliver:s,idempotencyKey:zl()})];this.executeWithRetries(p,{label:r,sessionId:o,target:"chat.send",phase:i,onFinalFailure:c})}fireDirectNotificationWithRetry(t,n,r,o,i){let s=["message","send","--channel",t.channel,"--target",t.target,"--message",n];t.accountId&&s.push("--account",t.accountId),t.threadId&&s.push("--thread-id",t.threadId),this.executeWithRetries(s,{label:r,sessionId:o,target:"message.send",phase:"notify",onFinalFailure:i})}fireSystemEventWithRetry(t,n,r,o){let i=["system","event","--text",t,"--mode","now"];this.executeWithRetries(i,{label:n,sessionId:r,target:"system.event",phase:o})}sendUserNotification(t,n,r,o){let i=this.parseNotificationRoute(t);if(!i){this.fireSystemEventWithRetry(n,`${r}-notify-system`,o,"notify");return}this.fireDirectNotificationWithRetry(i,n,`${r}-notify`,o,()=>{this.fireSystemEventWithRetry(n,`${r}-notify-fallback`,o,"notify")})}dispatchSessionNotification(t,n){let r=this.getOriginSessionKey(t),o=n.notifyUser??(n.wakeMessage?"on-wake-fallback":"always"),i=n.userMessage?.trim(),s=n.wakeMessage?.trim();if(o==="always"&&i&&this.sendUserNotification(t,i,n.label,t.id),!!s){if(!r){o==="on-wake-fallback"&&i&&this.sendUserNotification(t,i,n.label,t.id),this.fireSystemEventWithRetry(s,`${n.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(r,s,`${n.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(s,`${n.label}-wake-fallback`,t.id,"wake")})}}};function Zl(){let e=process.env.OPENCLAW_CODE_AGENT_PLAN_WORKFLOW_PATH?.trim();if(e)return e;let t=Ql(ga(import.meta.url)),n=[Yr(process.cwd(),"workflows","plan-approval.lobster"),Yr(t,"..","workflows","plan-approval.lobster"),Yr(t,"..","..","workflows","plan-approval.lobster")];for(let r of n)if(Xl(r))return r;return ga(new URL("../workflows/plan-approval.lobster",import.meta.url))}var ef=Zl(),Jr=new Set(["completed","failed","killed"]),Xn=new Set(["starting","running"]),tf=5e3,nf=3e4;function rf(e){let t=e.trim();if(!t)return;let n=i=>typeof i=="string"&&i.trim().length>0&&/^[A-Za-z0-9._:-]+$/.test(i.trim()),r=[t];for(let i of t.split(/\r?\n/)){let s=i.trim();s.startsWith("{")&&s.endsWith("}")&&r.push(s)}for(let i of r)try{let s=JSON.parse(i),c=s?.resumeToken??s?.requiresApproval?.resumeToken??s?.details?.requiresApproval?.resumeToken;if(n(c))return c.trim()}catch{}let o=t.match(/"resumeToken"\s*:\s*"([^"]+)"/);if(o&&n(o[1]))return o[1].trim()}var Qn=class{sessions=new Map;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;store;metrics;wakeDispatcher;constructor(t=20,n=50){this.maxSessions=t,this.maxPersistedSessions=n,this.store=new qn,this.metrics=new zn,this.wakeDispatcher=new Jn}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(t){let n=new Set([...this.sessions.values()].filter(o=>Xn.has(o.status)).map(o=>o.name));if(!n.has(t))return t;let r=2;for(;n.has(`${t}-${r}`);)r++;return`${t}-${r}`}spawn(t,n={}){if([...this.sessions.values()].filter(c=>Xn.has(c.status)).length>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);let o=t.name||Ci(t.prompt),i=this.uniqueName(o);i!==o&&console.warn(`[SessionManager] Name conflict: "${o}" \u2192 "${i}" (active session with same name exists)`);let s=new Hn(t,i);if(this.sessions.set(s.id,s),this.metrics.incrementLaunched(),s.on("statusChange",(c,p)=>{p==="running"&&s.harnessSessionId?this.store.markRunning(s):Jr.has(p)&&this.onSessionTerminal(s)}),s.on("turnEnd",(c,p)=>{this.onTurnEnd(s,p)}),s.start(),n.notifyLaunch!==!1){let c=`\u{1F680} [${s.name}] Launched | ${s.workdir} | ${s.model??"default"}`;this.notifySession(s,c,"launch")}return s}async spawnAndAwaitRunning(t,n={}){let r=this.spawn(t,n);return await this.waitForRunningSession(r),r}async waitForRunningSession(t){if(t.status==="running")return;if(Jr.has(t.status))throw new Error(this.describeLaunchFailure(t));let n=t.on?.bind(t),r=t.off?.bind(t)??t.removeListener?.bind(t);if(!n||!r)throw new Error(`Session ${t.name} [${t.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(p,f)=>{if(f==="running"){c(),o();return}Jr.has(f)&&(c(),i(new Error(this.describeLaunchFailure(t))))},c=()=>{r("statusChange",s)};n("statusChange",s)})}describeLaunchFailure(t){let n=t.killReason?` (reason: ${t.killReason})`:"",r=t.error||t.result?.result||`status=${t.status}${n}`;return`Session ${t.name} [${t.id}] failed to start: ${r}`}onSessionTerminal(t){if(this.persistSession(t),this.lastWaitingEventTimestamps.delete(t.id),t.killReason==="done")return;if(t.status==="completed"){if(!this.shouldEmitTerminalWake(t))return;this.triggerAgentEvent(t);return}if(t.status==="failed"){if(!this.shouldEmitTerminalWake(t))return;let i=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`,s=rt(i,200);this.triggerFailedEvent(t,s);return}let n=`$${(t.costUsd??0).toFixed(2)}`,r=_e(t.duration);if(t.killReason==="idle-timeout"){this.notifySession(t,`\u{1F4A4} [${t.name}] Idle timeout | ${n} | ${r}`);return}let o=this.getStoppedStatusLabel(t.killReason);this.notifySession(t,`\u26D4 [${t.name}] ${o} | ${n} | ${r}`)}getStoppedStatusLabel(t){switch(t){case"user":return"Stopped by user";case"shutdown":return"Stopped by shutdown";case"startup-timeout":return"Stopped by startup timeout";case"unknown":case void 0:return"Stopped unexpectedly";default:return"Stopped"}}persistSession(t){this.store.hasRecordedSession(t.id)||this.metrics.recordSession(t),this.store.persistTerminal(t)}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(t){this.metrics.recordSession(t)}notifySession(t,n,r="notification"){this.dispatchSessionNotification(t,{label:r,userMessage:n,notifyUser:"always"})}dispatchSessionNotification(t,n){this.wakeDispatcher.dispatchSessionNotification(t,n)}runLobsterApproval(t,n){let r=JSON.stringify({session_id:t.id,session_name:t.name,plan_summary:n}),o=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"run",pipeline:ef,argsJson:r,timeoutMs:0})];fa("openclaw",o,{timeout:nf},(i,s,c)=>{if(i){console.error(`[SessionManager] Lobster launch failed for session=${t.id}: ${i.message}`),this.notifySession(t,`\u{1F4CB} [${t.name}] Plan ready \u2014 Lobster gate failed, please review manually:
50
50
 
51
- ${ot(n,800)}`);return}let p=typeof s=="string"?s:String(s??""),f=typeof c=="string"?c:String(c??""),T=nf(`${p}
52
- ${f}`);if(!T){let te=`${p}
53
- ${f}`.trim().substring(0,200);console.warn(`[SessionManager] Lobster response missing resume token for session=${t.id}: ${te}`)}T&&(t.lobsterResumeToken=T);let U=[`\u{1F4CB} [${t.name}] Plan ready for approval`,"",ot(n,1200),"",`Session: ${t.name} (${t.id})`,"",'To approve: reply "approve"',"To reject: reply with feedback"];this.notifySession(t,U.join(`
54
- `))})}resumeLobsterApproval(t,n){let r=n?3e4:1e4;return new Promise((o,i)=>{let s=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"resume",token:t,approve:n})];pa("openclaw",s,{timeout:r},c=>{c?(console.error(`[SessionManager] Lobster resume failed (approve=${n}): ${c.message}`),i(c)):o()})})}debounceWaitingEvent(t){let n=Date.now(),r=this.lastWaitingEventTimestamps.get(t);return r&&n-r<ef?!1:(this.lastWaitingEventTimestamps.set(t,n),!0)}originThreadLine(t){return t.originThreadId!=null?`Session origin thread: ${t.originThreadId}`:""}extractLastOutputLine(t){return t.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(t,n=1e3){let r=t.getOutput(20).join(`
55
- `);return r.length>n?Ci(r,n):r}triggerAgentEvent(t){let n=this.getOutputPreview(t),r=["Coding agent session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Output preview:",n,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${t.id}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.","3. Notify the user with a summary of what was done."].join(`
56
- `),o=`$${(t.costUsd??0).toFixed(2)}`,i=Le(t.duration),s=`\u2705 [${t.name}] Completed | ${o} | ${i}`;this.dispatchSessionNotification(t,{label:"completed",userMessage:s,wakeMessage:r,notifyUser:"always"})}triggerFailedEvent(t,n){let r=this.getOutputPreview(t),o=r.trim()?["","Output preview:",r]:[],i=["Coding agent session failed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Failure summary:",n,...o,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${t.id}', full=true) to inspect the full failure context.`,"2. If the failure is a launch/config issue or other recoverable error, relaunch the task now or continue it yourself.","3. Notify the user with the failure cause and the next action you are taking."].join(`
57
- `),s=`$${(t.costUsd??0).toFixed(2)}`,c=Le(t.duration),p=[`\u274C [${t.name}] Failed | ${s} | ${c}`,` \u26A0\uFE0F ${n}`].join(`
51
+ ${rt(n,800)}`);return}let p=typeof s=="string"?s:String(s??""),f=typeof c=="string"?c:String(c??""),b=rf(`${p}
52
+ ${f}`);if(!b){let X=`${p}
53
+ ${f}`.trim().substring(0,200);console.warn(`[SessionManager] Lobster response missing resume token for session=${t.id}: ${X}`)}b&&(t.lobsterResumeToken=b);let k=[`\u{1F4CB} [${t.name}] Plan ready for approval`,"",rt(n,1200),"",`Session: ${t.name} (${t.id})`,"",'To approve: reply "approve"',"To reject: reply with feedback"];this.notifySession(t,k.join(`
54
+ `))})}resumeLobsterApproval(t,n){let r=n?3e4:1e4;return new Promise((o,i)=>{let s=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"resume",token:t,approve:n})];fa("openclaw",s,{timeout:r},c=>{c?(console.error(`[SessionManager] Lobster resume failed (approve=${n}): ${c.message}`),i(c)):o()})})}debounceWaitingEvent(t){let n=Date.now(),r=this.lastWaitingEventTimestamps.get(t);return r&&n-r<tf?!1:(this.lastWaitingEventTimestamps.set(t,n),!0)}originThreadLine(t){return t.originThreadId!=null?`Session origin thread: ${t.originThreadId}`:""}extractLastOutputLine(t){return t.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(t,n=1e3){let r=t.getOutput(20).join(`
55
+ `);return r.length>n?Ei(r,n):r}triggerAgentEvent(t){let n=this.getOutputPreview(t),r=["Coding agent session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Output preview:",n,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${t.id}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.","3. Notify the user with a summary of what was done."].join(`
56
+ `),o=`$${(t.costUsd??0).toFixed(2)}`,i=_e(t.duration),s=`\u2705 [${t.name}] Completed | ${o} | ${i}`;this.dispatchSessionNotification(t,{label:"completed",userMessage:s,wakeMessage:r,notifyUser:"always"})}triggerFailedEvent(t,n){let r=this.getOutputPreview(t),o=r.trim()?["","Output preview:",r]:[],i=["Coding agent session failed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Failure summary:",n,...o,"","[ACTION REQUIRED] Follow your autonomy rules for session failure:",`1. Use agent_output(session='${t.id}', full=true) to inspect the full failure context.`,"2. If the failure is a launch/config issue or other recoverable error, relaunch the task now or continue it yourself.","3. Notify the user with the failure cause and the next action you are taking."].join(`
57
+ `),s=`$${(t.costUsd??0).toFixed(2)}`,c=_e(t.duration),p=[`\u274C [${t.name}] Failed | ${s} | ${c}`,` \u26A0\uFE0F ${n}`].join(`
58
58
  `);this.dispatchSessionNotification(t,{label:"failed",userMessage:p,wakeMessage:i,notifyUser:"always"})}triggerWaitingForInputEvent(t){if(!this.debounceWaitingEvent(t.id))return;let n=this.getOutputPreview(t),r=t.pendingPlanApproval,o=r?`\u{1F4CB} [${t.name}] Plan ready for review:
59
59
 
60
60
  ${n}
61
61
 
62
- Reply to approve or provide feedback.`:`\u{1F514} [${t.name}] Waiting for input`,i;if(r){let s=E.planApproval??"delegate";if(s==="ask"){this.runLobsterApproval(t,n);return}else s==="delegate"?i=["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"Permission mode: plan \u2192 will switch to bypassPermissions on approval","","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${t.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",n,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Notify the user \u2501\u2501\u2501","After reading the full plan, use the message tool to send the user a summary that includes:","- What files/components will be changed","- Risk level (low/medium/high) and why","- Scope: does this match the original task or has it expanded?","- Any concerns or assumptions the plan makes","This message creates accountability \u2014 you cannot approve blindly.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","You are the delegated decision-maker. Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- You have sent the user the summary message","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,"If escalating: tell the user you need their decision and WAIT for his explicit response.",`To request changes: agent_respond(session='${t.id}', message='<your feedback>') \u2014 do NOT set approve=true. The agent will revise the plan.`].join(`
62
+ Reply to approve or provide feedback.`:`\u2753 [${t.name}] Waiting for input`,i;if(r){let s=F.planApproval??"delegate";if(s==="ask"){this.runLobsterApproval(t,n);return}else s==="delegate"?i=["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"Permission mode: plan \u2192 will switch to bypassPermissions on approval","","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${t.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",n,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Notify the user \u2501\u2501\u2501","After reading the full plan, use the message tool to send the user a summary that includes:","- What files/components will be changed","- Risk level (low/medium/high) and why","- Scope: does this match the original task or has it expanded?","- Any concerns or assumptions the plan makes","This message creates accountability \u2014 you cannot approve blindly.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","You are the delegated decision-maker. Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- You have sent the user the summary message","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,"If escalating: tell the user you need their decision and WAIT for his explicit response.",`To request changes: agent_respond(session='${t.id}', message='<your feedback>') \u2014 do NOT set approve=true. The agent will revise the plan.`].join(`
63
63
  `):i=["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`].join(`
64
64
  `)}else i=[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 forward the agent's EXACT question to the user. Do NOT add your own analysis, commentary, or interpretation. Do NOT "nudge" or "poke" the session.]`,"",`${t.multiTurn?"Multi-turn session":"Session"} is waiting for input.`,`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"","Last output:",n,"",`Use agent_respond(session='${t.id}', message='...') to send a reply, or agent_output(session='${t.id}', full: true) to see full context before deciding.`].join(`
65
- `);this.dispatchSessionNotification(t,{label:r?"plan-approval":"waiting",userMessage:o,wakeMessage:i,notifyUser:r?"always":"on-wake-fallback"})}onTurnEnd(t,n){if(n||t.pendingPlanApproval){this.triggerWaitingForInputEvent(t);return}this.shouldEmitTurnCompleteWake(t)&&this.triggerTurnCompleteEventWithSignal(t)}shouldEmitTurnCompleteWake(t){let n=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===n?!1:(this.lastTurnCompleteMarkers.set(t.id,n),!0)}shouldEmitTerminalWake(t){let n=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===n?!1:(this.lastTerminalWakeMarkers.set(t.id,n),!0)}triggerTurnCompleteEventWithSignal(t){let n=this.getOutputPreview(t),r=Dn(n),o=`$${(t.costUsd??0).toFixed(2)}`,i=r?"yes":"no",s=`\u{1F504} [${t.name}] Turn done | ${o} | Waiting input: ${i}`,c=["Coding agent session turn ended.",`Name: ${t.name}`,`ID: ${t.id}`,`Status: ${t.status}`,"",`Looks like waiting for user input: ${i}`,"","Last output (~20 lines):",n,...this.originThreadLine(t)?["",this.originThreadLine(t)]:[]].join(`
66
- `);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:s,wakeMessage:c,notifyUser:"always"})}resolve(t){let n=this.sessions.get(t);if(n)return n;let r=[...this.sessions.values()].filter(i=>i.name===t);if(r.length===0)return;let o=r.filter(i=>Jn.has(i.status));return o.length>0?o.sort((i,s)=>s.startedAt-i.startedAt)[0]:r.sort((i,s)=>s.startedAt-i.startedAt)[0]}get(t){return this.sessions.get(t)}list(t){let n=[...this.sessions.values()];return t&&t!=="all"&&(n=n.filter(r=>r.status===t)),n.sort((r,o)=>o.startedAt-r.startedAt)}kill(t,n){let r=this.sessions.get(t);return r?(r.kill(n??"user"),!0):!1}killAll(t="user"){for(let n of this.sessions.values())Jn.has(n.status)&&this.kill(n.id,t);this.wakeDispatcher.clearPendingRetries()}resolveHarnessSessionId(t){let n=this.resolve(t);return this.store.resolveHarnessSessionId(t,n?.harnessSessionId)}getPersistedSession(t){return this.store.getPersistedSession(t)}listPersistedSessions(){return this.store.listPersistedSessions()}cleanup(){let t=Date.now(),n=(E.sessionGcAgeMinutes??1440)*6e4;for(let[r,o]of this.sessions)this.store.shouldGcActiveSession(o,t,n)&&(this.persistSession(o),this.sessions.delete(r),this.lastWaitingEventTimestamps.delete(r),this.lastTurnCompleteMarkers.delete(r),this.lastTerminalWakeMarkers.delete(r));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}};function rO(e){let t=null,n=null;e.registerTool(r=>Pi(r),{optional:!1}),e.registerTool(r=>Mi(r),{optional:!1}),e.registerTool(r=>Ei(r),{optional:!1}),e.registerTool(r=>ki(r),{optional:!1}),e.registerTool(r=>$i(r),{optional:!1}),e.registerTool(r=>vi(r),{optional:!1}),Ni(e),Ui(e),_i(e),Li(e),Ki(e),Di(e),ji(e),e.registerService({id:"openclaw-code-agent",start:r=>{let o=e.pluginConfig??e.getConfig?.()??{};Ti(o),t=new Xn(E.maxSessions,E.maxPersistedSessions),Gr(t),n=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{t&&t.killAll("shutdown"),n&&clearInterval(n),n=null,t=null,Gr(null)}})}export{rO as register};
65
+ `);this.dispatchSessionNotification(t,{label:r?"plan-approval":"waiting",userMessage:o,wakeMessage:i,notifyUser:r?"always":"on-wake-fallback"})}onTurnEnd(t,n){if(n||t.pendingPlanApproval){this.triggerWaitingForInputEvent(t);return}this.shouldEmitTurnCompleteWake(t)&&this.triggerTurnCompleteEventWithSignal(t)}shouldEmitTurnCompleteWake(t){let n=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===n?!1:(this.lastTurnCompleteMarkers.set(t.id,n),!0)}shouldEmitTerminalWake(t){let n=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===n?!1:(this.lastTerminalWakeMarkers.set(t.id,n),!0)}triggerTurnCompleteEventWithSignal(t){let n=this.getOutputPreview(t),r=jn(n),o=`$${(t.costUsd??0).toFixed(2)}`,i=r?"yes":"no",s=`\u23F8\uFE0F [${t.name}] Paused after turn | Auto-resumable | ${o} | Waiting input: ${i}`,c=["Coding agent session turn ended.",`Name: ${t.name}`,`ID: ${t.id}`,`Status: ${t.status}`,"",`Looks like waiting for user input: ${i}`,"","Last output (~20 lines):",n,...this.originThreadLine(t)?["",this.originThreadLine(t)]:[]].join(`
66
+ `);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:s,wakeMessage:c,notifyUser:"always"})}resolve(t){let n=this.sessions.get(t);if(n)return n;let r=[...this.sessions.values()].filter(i=>i.name===t);if(r.length===0)return;let o=r.filter(i=>Xn.has(i.status));return o.length>0?o.sort((i,s)=>s.startedAt-i.startedAt)[0]:r.sort((i,s)=>s.startedAt-i.startedAt)[0]}get(t){return this.sessions.get(t)}list(t){let n=[...this.sessions.values()];return t&&t!=="all"&&(n=n.filter(r=>r.status===t)),n.sort((r,o)=>o.startedAt-r.startedAt)}kill(t,n){let r=this.sessions.get(t);return r?(r.kill(n??"user"),!0):!1}killAll(t="user"){for(let n of this.sessions.values())Xn.has(n.status)&&this.kill(n.id,t);this.wakeDispatcher.clearPendingRetries()}resolveHarnessSessionId(t){let n=this.resolve(t);return this.store.resolveHarnessSessionId(t,n?.harnessSessionId)}getPersistedSession(t){return this.store.getPersistedSession(t)}listPersistedSessions(){return this.store.listPersistedSessions()}cleanup(){let t=Date.now(),n=(F.sessionGcAgeMinutes??1440)*6e4;for(let[r,o]of this.sessions)this.store.shouldGcActiveSession(o,t,n)&&(this.persistSession(o),this.sessions.delete(r),this.lastWaitingEventTimestamps.delete(r),this.lastTurnCompleteMarkers.delete(r),this.lastTerminalWakeMarkers.delete(r));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}};function oO(e){let t=null,n=null;e.registerTool(r=>Oi(r),{optional:!1}),e.registerTool(r=>Fi(r),{optional:!1}),e.registerTool(r=>ki(r),{optional:!1}),e.registerTool(r=>$i(r),{optional:!1}),e.registerTool(r=>Ni(r),{optional:!1}),e.registerTool(r=>Ui(r),{optional:!1}),_i(e),Li(e),Ki(e),Di(e),ji(e),Gi(e),Vi(e),e.registerService({id:"openclaw-code-agent",start:r=>{let o=e.pluginConfig??e.getConfig?.()??{};wi(o),t=new Qn(F.maxSessions,F.maxPersistedSessions),Vr(t),n=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{t&&t.killAll("shutdown"),n&&clearInterval(n),n=null,t=null,Vr(null)}})}export{oO as register};
@@ -2,7 +2,7 @@
2
2
  "id": "openclaw-code-agent",
3
3
  "name": "OpenClaw Code Agent",
4
4
  "description": "Orchestrate coding agent sessions from OpenClaw",
5
- "version": "2.3.0",
5
+ "version": "2.3.1",
6
6
  "configSchema": {
7
7
  "type": "object",
8
8
  "additionalProperties": false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openclaw-code-agent",
3
- "version": "2.3.0",
3
+ "version": "2.3.1",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {