openclaw-code-agent 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +48 -47
- package/package.json +1 -1
- package/skills/code-agent-orchestration/SKILL.md +16 -2
package/dist/index.js
CHANGED
|
@@ -1,65 +1,66 @@
|
|
|
1
|
-
var Wi=Object.defineProperty;var zn=(e,t)=>{for(var n in t)Wi(e,n,{get:t[n],enumerable:!0})};import{existsSync as Pp}from"fs";var z={};zn(z,{HasPropertyKey:()=>tn,IsArray:()=>v,IsAsyncIterator:()=>Yn,IsBigInt:()=>$t,IsBoolean:()=>_e,IsDate:()=>et,IsFunction:()=>Xn,IsIterator:()=>Jn,IsNull:()=>Qn,IsNumber:()=>ie,IsObject:()=>w,IsRegExp:()=>Ut,IsString:()=>C,IsSymbol:()=>Zn,IsUint8Array:()=>Ne,IsUndefined:()=>K});function tn(e,t){return t in e}function Yn(e){return w(e)&&!v(e)&&!Ne(e)&&Symbol.asyncIterator in e}function v(e){return Array.isArray(e)}function $t(e){return typeof e=="bigint"}function _e(e){return typeof e=="boolean"}function et(e){return e instanceof globalThis.Date}function Xn(e){return typeof e=="function"}function Jn(e){return w(e)&&!v(e)&&!Ne(e)&&Symbol.iterator in e}function Qn(e){return e===null}function ie(e){return typeof e=="number"}function w(e){return typeof e=="object"&&e!==null}function Ut(e){return e instanceof globalThis.RegExp}function C(e){return typeof e=="string"}function Zn(e){return typeof e=="symbol"}function Ne(e){return e instanceof globalThis.Uint8Array}function K(e){return e===void 0}function qi(e){return e.map(t=>nn(t))}function zi(e){return new Date(e.getTime())}function Yi(e){return new Uint8Array(e)}function Xi(e){return new RegExp(e.source,e.flags)}function Ji(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=nn(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=nn(e[n]);return t}function nn(e){return v(e)?qi(e):et(e)?zi(e):Ne(e)?Yi(e):Ut(e)?Xi(e):w(e)?Ji(e):e}function k(e){return nn(e)}function ct(e,t){return t===void 0?k(e):k({...t,...e})}function Dr(e){return e!==null&&typeof e=="object"}function Gr(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function Vr(e){return e===void 0}function Br(e){return typeof e=="number"}var rn;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(a,m){return e.ExactOptionalPropertyTypes?m in a:a[m]!==void 0}e.IsExactOptionalProperty=t;function n(a){let m=Dr(a);return e.AllowArrayObject?m:m&&!Gr(a)}e.IsObjectLike=n;function r(a){return n(a)&&!(a instanceof Date)&&!(a instanceof Uint8Array)}e.IsRecordLike=r;function o(a){return e.AllowNaN?Br(a):Number.isFinite(a)}e.IsNumberLike=o;function s(a){let m=Vr(a);return e.AllowNullVoid?m||a===null:m}e.IsVoidLike=s})(rn||(rn={}));function Qi(e){return globalThis.Object.freeze(e).map(t=>_t(t))}function Zi(e){let t={};for(let n of Object.getOwnPropertyNames(e))t[n]=_t(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=_t(e[n]);return globalThis.Object.freeze(t)}function _t(e){return v(e)?Qi(e):et(e)?e:Ne(e)?e:Ut(e)?e:w(e)?Zi(e):e}function u(e,t){let n=t!==void 0?{...t,...e}:e;switch(rn.InstanceMode){case"freeze":return _t(n);case"clone":return k(n);default:return n}}var V=class extends Error{constructor(t){super(t)}};var j=Symbol.for("TypeBox.Transform"),Te=Symbol.for("TypeBox.Readonly"),W=Symbol.for("TypeBox.Optional"),fe=Symbol.for("TypeBox.Hint"),p=Symbol.for("TypeBox.Kind");function lt(e){return w(e)&&e[Te]==="Readonly"}function ee(e){return w(e)&&e[W]==="Optional"}function er(e){return y(e,"Any")}function tr(e){return y(e,"Argument")}function be(e){return y(e,"Array")}function tt(e){return y(e,"AsyncIterator")}function nt(e){return y(e,"BigInt")}function ve(e){return y(e,"Boolean")}function Ae(e){return y(e,"Computed")}function we(e){return y(e,"Constructor")}function ea(e){return y(e,"Date")}function Oe(e){return y(e,"Function")}function Pe(e){return y(e,"Integer")}function U(e){return y(e,"Intersect")}function rt(e){return y(e,"Iterator")}function y(e,t){return w(e)&&p in e&&e[p]===t}function on(e){return _e(e)||ie(e)||C(e)}function ae(e){return y(e,"Literal")}function ue(e){return y(e,"MappedKey")}function E(e){return y(e,"MappedResult")}function De(e){return y(e,"Never")}function ta(e){return y(e,"Not")}function Nt(e){return y(e,"Null")}function Re(e){return y(e,"Number")}function L(e){return y(e,"Object")}function ot(e){return y(e,"Promise")}function st(e){return y(e,"Record")}function N(e){return y(e,"Ref")}function nr(e){return y(e,"RegExp")}function Ke(e){return y(e,"String")}function vt(e){return y(e,"Symbol")}function de(e){return y(e,"TemplateLiteral")}function na(e){return y(e,"This")}function Ge(e){return w(e)&&j in e}function me(e){return y(e,"Tuple")}function Kt(e){return y(e,"Undefined")}function x(e){return y(e,"Union")}function ra(e){return y(e,"Uint8Array")}function oa(e){return y(e,"Unknown")}function sa(e){return y(e,"Unsafe")}function ia(e){return y(e,"Void")}function aa(e){return w(e)&&p in e&&C(e[p])}function pe(e){return er(e)||tr(e)||be(e)||ve(e)||nt(e)||tt(e)||Ae(e)||we(e)||ea(e)||Oe(e)||Pe(e)||U(e)||rt(e)||ae(e)||ue(e)||E(e)||De(e)||ta(e)||Nt(e)||Re(e)||L(e)||ot(e)||st(e)||N(e)||nr(e)||Ke(e)||vt(e)||de(e)||na(e)||me(e)||Kt(e)||x(e)||ra(e)||oa(e)||sa(e)||ia(e)||aa(e)}var i={};zn(i,{IsAny:()=>zr,IsArgument:()=>Yr,IsArray:()=>Xr,IsAsyncIterator:()=>Jr,IsBigInt:()=>Qr,IsBoolean:()=>Zr,IsComputed:()=>eo,IsConstructor:()=>to,IsDate:()=>no,IsFunction:()=>ro,IsImport:()=>la,IsInteger:()=>oo,IsIntersect:()=>so,IsIterator:()=>io,IsKind:()=>$o,IsKindOf:()=>I,IsLiteral:()=>jt,IsLiteralBoolean:()=>fa,IsLiteralNumber:()=>uo,IsLiteralString:()=>ao,IsLiteralValue:()=>mo,IsMappedKey:()=>po,IsMappedResult:()=>co,IsNever:()=>lo,IsNot:()=>fo,IsNull:()=>go,IsNumber:()=>Io,IsObject:()=>ho,IsOptional:()=>ca,IsPromise:()=>yo,IsProperties:()=>sn,IsReadonly:()=>pa,IsRecord:()=>xo,IsRecursive:()=>ga,IsRef:()=>So,IsRegExp:()=>To,IsSchema:()=>B,IsString:()=>bo,IsSymbol:()=>Ao,IsTemplateLiteral:()=>wo,IsThis:()=>Oo,IsTransform:()=>Po,IsTuple:()=>Ro,IsUint8Array:()=>Mo,IsUndefined:()=>Co,IsUnion:()=>ir,IsUnionLiteral:()=>Ia,IsUnknown:()=>Fo,IsUnsafe:()=>ko,IsVoid:()=>Eo,TypeGuardUnknownTypeError:()=>rr});var rr=class extends V{},ua=["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 Hr(e){try{return new RegExp(e),!0}catch{return!1}}function or(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 Wr(e){return sr(e)||B(e)}function Lt(e){return K(e)||$t(e)}function M(e){return K(e)||ie(e)}function sr(e){return K(e)||_e(e)}function O(e){return K(e)||C(e)}function da(e){return K(e)||C(e)&&or(e)&&Hr(e)}function ma(e){return K(e)||C(e)&&or(e)}function qr(e){return K(e)||B(e)}function pa(e){return w(e)&&e[Te]==="Readonly"}function ca(e){return w(e)&&e[W]==="Optional"}function zr(e){return I(e,"Any")&&O(e.$id)}function Yr(e){return I(e,"Argument")&&ie(e.index)}function Xr(e){return I(e,"Array")&&e.type==="array"&&O(e.$id)&&B(e.items)&&M(e.minItems)&&M(e.maxItems)&&sr(e.uniqueItems)&&qr(e.contains)&&M(e.minContains)&&M(e.maxContains)}function Jr(e){return I(e,"AsyncIterator")&&e.type==="AsyncIterator"&&O(e.$id)&&B(e.items)}function Qr(e){return I(e,"BigInt")&&e.type==="bigint"&&O(e.$id)&&Lt(e.exclusiveMaximum)&&Lt(e.exclusiveMinimum)&&Lt(e.maximum)&&Lt(e.minimum)&&Lt(e.multipleOf)}function Zr(e){return I(e,"Boolean")&&e.type==="boolean"&&O(e.$id)}function eo(e){return I(e,"Computed")&&C(e.target)&&v(e.parameters)&&e.parameters.every(t=>B(t))}function to(e){return I(e,"Constructor")&&e.type==="Constructor"&&O(e.$id)&&v(e.parameters)&&e.parameters.every(t=>B(t))&&B(e.returns)}function no(e){return I(e,"Date")&&e.type==="Date"&&O(e.$id)&&M(e.exclusiveMaximumTimestamp)&&M(e.exclusiveMinimumTimestamp)&&M(e.maximumTimestamp)&&M(e.minimumTimestamp)&&M(e.multipleOfTimestamp)}function ro(e){return I(e,"Function")&&e.type==="Function"&&O(e.$id)&&v(e.parameters)&&e.parameters.every(t=>B(t))&&B(e.returns)}function la(e){return I(e,"Import")&&tn(e,"$defs")&&w(e.$defs)&&sn(e.$defs)&&tn(e,"$ref")&&C(e.$ref)&&e.$ref in e.$defs}function oo(e){return I(e,"Integer")&&e.type==="integer"&&O(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function sn(e){return w(e)&&Object.entries(e).every(([t,n])=>or(t)&&B(n))}function so(e){return I(e,"Intersect")&&!(C(e.type)&&e.type!=="object")&&v(e.allOf)&&e.allOf.every(t=>B(t)&&!Po(t))&&O(e.type)&&(sr(e.unevaluatedProperties)||qr(e.unevaluatedProperties))&&O(e.$id)}function io(e){return I(e,"Iterator")&&e.type==="Iterator"&&O(e.$id)&&B(e.items)}function I(e,t){return w(e)&&p in e&&e[p]===t}function ao(e){return jt(e)&&C(e.const)}function uo(e){return jt(e)&&ie(e.const)}function fa(e){return jt(e)&&_e(e.const)}function jt(e){return I(e,"Literal")&&O(e.$id)&&mo(e.const)}function mo(e){return _e(e)||ie(e)||C(e)}function po(e){return I(e,"MappedKey")&&v(e.keys)&&e.keys.every(t=>ie(t)||C(t))}function co(e){return I(e,"MappedResult")&&sn(e.properties)}function lo(e){return I(e,"Never")&&w(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function fo(e){return I(e,"Not")&&B(e.not)}function go(e){return I(e,"Null")&&e.type==="null"&&O(e.$id)}function Io(e){return I(e,"Number")&&e.type==="number"&&O(e.$id)&&M(e.exclusiveMaximum)&&M(e.exclusiveMinimum)&&M(e.maximum)&&M(e.minimum)&&M(e.multipleOf)}function ho(e){return I(e,"Object")&&e.type==="object"&&O(e.$id)&&sn(e.properties)&&Wr(e.additionalProperties)&&M(e.minProperties)&&M(e.maxProperties)}function yo(e){return I(e,"Promise")&&e.type==="Promise"&&O(e.$id)&&B(e.item)}function xo(e){return I(e,"Record")&&e.type==="object"&&O(e.$id)&&Wr(e.additionalProperties)&&w(e.patternProperties)&&(t=>{let n=Object.getOwnPropertyNames(t.patternProperties);return n.length===1&&Hr(n[0])&&w(t.patternProperties)&&B(t.patternProperties[n[0]])})(e)}function ga(e){return w(e)&&fe in e&&e[fe]==="Recursive"}function So(e){return I(e,"Ref")&&O(e.$id)&&C(e.$ref)}function To(e){return I(e,"RegExp")&&O(e.$id)&&C(e.source)&&C(e.flags)&&M(e.maxLength)&&M(e.minLength)}function bo(e){return I(e,"String")&&e.type==="string"&&O(e.$id)&&M(e.minLength)&&M(e.maxLength)&&da(e.pattern)&&ma(e.format)}function Ao(e){return I(e,"Symbol")&&e.type==="symbol"&&O(e.$id)}function wo(e){return I(e,"TemplateLiteral")&&e.type==="string"&&C(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Oo(e){return I(e,"This")&&O(e.$id)&&C(e.$ref)}function Po(e){return w(e)&&j in e}function Ro(e){return I(e,"Tuple")&&e.type==="array"&&O(e.$id)&&ie(e.minItems)&&ie(e.maxItems)&&e.minItems===e.maxItems&&(K(e.items)&&K(e.additionalItems)&&e.minItems===0||v(e.items)&&e.items.every(t=>B(t)))}function Co(e){return I(e,"Undefined")&&e.type==="undefined"&&O(e.$id)}function Ia(e){return ir(e)&&e.anyOf.every(t=>ao(t)||uo(t))}function ir(e){return I(e,"Union")&&O(e.$id)&&w(e)&&v(e.anyOf)&&e.anyOf.every(t=>B(t))}function Mo(e){return I(e,"Uint8Array")&&e.type==="Uint8Array"&&O(e.$id)&&M(e.minByteLength)&&M(e.maxByteLength)}function Fo(e){return I(e,"Unknown")&&O(e.$id)}function ko(e){return I(e,"Unsafe")}function Eo(e){return I(e,"Void")&&e.type==="void"&&O(e.$id)}function $o(e){return w(e)&&p in e&&C(e[p])&&!ua.includes(e[p])}function B(e){return w(e)&&(zr(e)||Yr(e)||Xr(e)||Zr(e)||Qr(e)||Jr(e)||eo(e)||to(e)||no(e)||ro(e)||oo(e)||so(e)||io(e)||jt(e)||po(e)||co(e)||lo(e)||fo(e)||go(e)||Io(e)||ho(e)||yo(e)||xo(e)||So(e)||To(e)||bo(e)||Ao(e)||wo(e)||Oo(e)||Ro(e)||Co(e)||ir(e)||Mo(e)||Fo(e)||ko(e)||Eo(e)||$o(e))}var ar="(true|false)",Dt="(0|[1-9][0-9]*)",ur="(.*)",ha="(?!.*)",kl=`^${ar}$`,Ve=`^${Dt}$`,Be=`^${ur}$`,Uo=`^${ha}$`;function _o(e,t){return e.includes(t)}function No(e){return[...new Set(e)]}function ya(e,t){return e.filter(n=>t.includes(n))}function xa(e,t){return e.reduce((n,r)=>ya(n,r),t)}function vo(e){return e.length===1?e[0]:e.length>1?xa(e.slice(1),e[0]):[]}function Ko(e){let t=[];for(let n of e)t.push(...n);return t}function He(e){return u({[p]:"Any"},e)}function ft(e,t){return u({[p]:"Array",type:"array",items:e},t)}function Lo(e){return u({[p]:"Argument",index:e})}function gt(e,t){return u({[p]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function F(e,t,n){return u({[p]:"Computed",target:e,parameters:t},n)}function Sa(e,t){let{[t]:n,...r}=e;return r}function _(e,t){return t.reduce((n,r)=>Sa(n,r),e)}function S(e){return u({[p]:"Never",not:{}},e)}function T(e){return u({[p]:"MappedResult",properties:e})}function It(e,t,n){return u({[p]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function ke(e,t,n){return u({[p]:"Function",type:"Function",parameters:e,returns:t},n)}function Gt(e,t){return u({[p]:"Union",anyOf:e},t)}function Ta(e){return e.some(t=>ee(t))}function jo(e){return e.map(t=>ee(t)?ba(t):t)}function ba(e){return _(e,[W])}function Aa(e,t){return Ta(e)?Y(Gt(jo(e),t)):Gt(jo(e),t)}function Ee(e,t){return e.length===1?u(e[0],t):e.length===0?S(t):Aa(e,t)}function A(e,t){return e.length===0?S(t):e.length===1?u(e[0],t):Gt(e,t)}var an=class extends V{};function wa(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function dr(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function je(e,t){return dr(e,t,"(")}function Vt(e,t){return dr(e,t,")")}function Do(e,t){return dr(e,t,"|")}function Oa(e){if(!(je(e,0)&&Vt(e,e.length-1)))return!1;let t=0;for(let n=0;n<e.length;n++)if(je(e,n)&&(t+=1),Vt(e,n)&&(t-=1),t===0&&n!==e.length-1)return!1;return!0}function Pa(e){return e.slice(1,e.length-1)}function Ra(e){let t=0;for(let n=0;n<e.length;n++)if(je(e,n)&&(t+=1),Vt(e,n)&&(t-=1),Do(e,n)&&t===0)return!0;return!1}function Ca(e){for(let t=0;t<e.length;t++)if(je(e,t))return!0;return!1}function Ma(e){let[t,n]=[0,0],r=[];for(let s=0;s<e.length;s++)if(je(e,s)&&(t+=1),Vt(e,s)&&(t-=1),Do(e,s)&&t===0){let a=e.slice(n,s);a.length>0&&r.push(ht(a)),n=s+1}let o=e.slice(n);return o.length>0&&r.push(ht(o)),r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"or",expr:r}}function Fa(e){function t(o,s){if(!je(o,s))throw new an("TemplateLiteralParser: Index must point to open parens");let a=0;for(let m=s;m<o.length;m++)if(je(o,m)&&(a+=1),Vt(o,m)&&(a-=1),a===0)return[s,m];throw new an("TemplateLiteralParser: Unclosed group parens in expression")}function n(o,s){for(let a=s;a<o.length;a++)if(je(o,a))return[s,a];return[s,o.length]}let r=[];for(let o=0;o<e.length;o++)if(je(e,o)){let[s,a]=t(e,o),m=e.slice(s,a+1);r.push(ht(m)),o=a}else{let[s,a]=n(e,o),m=e.slice(s,a);m.length>0&&r.push(ht(m)),o=a-1}return r.length===0?{type:"const",const:""}:r.length===1?r[0]:{type:"and",expr:r}}function ht(e){return Oa(e)?ht(Pa(e)):Ra(e)?Ma(e):Ca(e)?Fa(e):{type:"const",const:wa(e)}}function yt(e){return ht(e.slice(1,e.length-1))}var mr=class extends V{};function ka(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 Ea(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 $a(e){return e.type==="const"&&e.const===".*"}function it(e){return ka(e)||$a(e)?!1:Ea(e)?!0:e.type==="and"?e.expr.every(t=>it(t)):e.type==="or"?e.expr.every(t=>it(t)):e.type==="const"?!0:(()=>{throw new mr("Unknown expression type")})()}function Go(e){let t=yt(e.pattern);return it(t)}var pr=class extends V{};function*Vo(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let n of Vo(e.slice(1)))yield`${t}${n}`}function*Ua(e){return yield*Vo(e.expr.map(t=>[...Bt(t)]))}function*_a(e){for(let t of e.expr)yield*Bt(t)}function*Na(e){return yield e.const}function*Bt(e){return e.type==="and"?yield*Ua(e):e.type==="or"?yield*_a(e):e.type==="const"?yield*Na(e):(()=>{throw new pr("Unknown expression")})()}function un(e){let t=yt(e.pattern);return it(t)?[...Bt(t)]:[]}function b(e,t){return u({[p]:"Literal",const:e,type:typeof e},t)}function dn(e){return u({[p]:"Boolean",type:"boolean"},e)}function xt(e){return u({[p]:"BigInt",type:"bigint"},e)}function ge(e){return u({[p]:"Number",type:"number"},e)}function Ce(e){return u({[p]:"String",type:"string"},e)}function*va(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield dn():t==="number"?yield ge():t==="bigint"?yield xt():t==="string"?yield Ce():yield(()=>{let n=t.split("|").map(r=>b(r.trim()));return n.length===0?S():n.length===1?n[0]:Ee(n)})()}function*Ka(e){if(e[1]!=="{"){let t=b("$"),n=cr(e.slice(1));return yield*[t,...n]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let n=va(e.slice(2,t)),r=cr(e.slice(t+1));return yield*[...n,...r]}yield b(e)}function*cr(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let n=b(e.slice(0,t)),r=Ka(e.slice(t));return yield*[n,...r]}yield b(e)}function Bo(e){return[...cr(e)]}var lr=class extends V{};function La(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ho(e,t){return de(e)?e.pattern.slice(1,e.pattern.length-1):x(e)?`(${e.anyOf.map(n=>Ho(n,t)).join("|")})`:Re(e)?`${t}${Dt}`:Pe(e)?`${t}${Dt}`:nt(e)?`${t}${Dt}`:Ke(e)?`${t}${ur}`:ae(e)?`${t}${La(e.const.toString())}`:ve(e)?`${t}${ar}`:(()=>{throw new lr(`Unexpected Kind '${e[p]}'`)})()}function fr(e){return`^${e.map(t=>Ho(t,"")).join("")}$`}function at(e){let n=un(e).map(r=>b(r));return Ee(n)}function mn(e,t){let n=C(e)?fr(Bo(e)):fr(e);return u({[p]:"TemplateLiteral",type:"string",pattern:n},t)}function ja(e){return un(e).map(n=>n.toString())}function Da(e){let t=[];for(let n of e)t.push(...te(n));return t}function Ga(e){return[e.toString()]}function te(e){return[...new Set(de(e)?ja(e):x(e)?Da(e.anyOf):ae(e)?Ga(e.const):Re(e)?["[number]"]:Pe(e)?["[number]"]:[])]}function Va(e,t,n){let r={};for(let o of Object.getOwnPropertyNames(t))r[o]=We(e,te(t[o]),n);return r}function Ba(e,t,n){return Va(e,t.properties,n)}function Wo(e,t,n){let r=Ba(e,t,n);return T(r)}function zo(e,t){return e.map(n=>Yo(n,t))}function Ha(e){return e.filter(t=>!De(t))}function Wa(e,t){return pn(Ha(zo(e,t)))}function qa(e){return e.some(t=>De(t))?[]:e}function za(e,t){return Ee(qa(zo(e,t)))}function Ya(e,t){return t in e?e[t]:t==="[number]"?Ee(e):S()}function Xa(e,t){return t==="[number]"?e:S()}function Ja(e,t){return t in e?e[t]:S()}function Yo(e,t){return U(e)?Wa(e.allOf,t):x(e)?za(e.anyOf,t):me(e)?Ya(e.items??[],t):be(e)?Xa(e.items,t):L(e)?Ja(e.properties,t):S()}function gr(e,t){return t.map(n=>Yo(e,n))}function qo(e,t){return Ee(gr(e,t))}function We(e,t,n){if(N(e)||N(t)){let r="Index types using Ref parameters require both Type and Key to be of TSchema";if(!pe(e)||!pe(t))throw new V(r);return F("Index",[e,t])}return E(t)?Wo(e,t,n):ue(t)?Xo(e,t,n):u(pe(t)?qo(e,te(t)):qo(e,t),n)}function Qa(e,t,n){return{[t]:We(e,[t],k(n))}}function Za(e,t,n){return t.reduce((r,o)=>({...r,...Qa(e,o,n)}),{})}function eu(e,t,n){return Za(e,t.keys,n)}function Xo(e,t,n){let r=eu(e,t,n);return T(r)}function St(e,t){return u({[p]:"Iterator",type:"Iterator",items:e},t)}function tu(e){return globalThis.Object.keys(e).filter(t=>!ee(e[t]))}function nu(e,t){let n=tu(e),r=n.length>0?{[p]:"Object",type:"object",required:n,properties:e}:{[p]:"Object",type:"object",properties:e};return u(r,t)}var P=nu;function cn(e,t){return u({[p]:"Promise",type:"Promise",item:e},t)}function ru(e){return u(_(e,[Te]))}function ou(e){return u({...e,[Te]:"Readonly"})}function su(e,t){return t===!1?ru(e):ou(e)}function ne(e,t){let n=t??!0;return E(e)?Jo(e,n):su(e,n)}function iu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=ne(e[r],t);return n}function au(e,t){return iu(e.properties,t)}function Jo(e,t){let n=au(e,t);return T(n)}function Ie(e,t){return u(e.length>0?{[p]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[p]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function Qo(e,t){return e in t?he(e,t[e]):T(t)}function uu(e){return{[e]:b(e)}}function du(e){let t={};for(let n of e)t[n]=b(n);return t}function mu(e,t){return _o(t,e)?uu(e):du(t)}function pu(e,t){let n=mu(e,t);return Qo(e,n)}function Ht(e,t){return t.map(n=>he(e,n))}function cu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(t))n[r]=he(e,t[r]);return n}function he(e,t){let n={...t};return ee(t)?Y(he(e,_(t,[W]))):lt(t)?ne(he(e,_(t,[Te]))):E(t)?Qo(e,t.properties):ue(t)?pu(e,t.keys):we(t)?It(Ht(e,t.parameters),he(e,t.returns),n):Oe(t)?ke(Ht(e,t.parameters),he(e,t.returns),n):tt(t)?gt(he(e,t.items),n):rt(t)?St(he(e,t.items),n):U(t)?X(Ht(e,t.allOf),n):x(t)?A(Ht(e,t.anyOf),n):me(t)?Ie(Ht(e,t.items??[]),n):L(t)?P(cu(e,t.properties),n):be(t)?ft(he(e,t.items),n):ot(t)?cn(he(e,t.item),n):t}function lu(e,t){let n={};for(let r of e)n[r]=he(r,t);return n}function Zo(e,t,n){let r=pe(e)?te(e):e,o=t({[p]:"MappedKey",keys:r}),s=lu(r,o);return P(s,n)}function fu(e){return u(_(e,[W]))}function gu(e){return u({...e,[W]:"Optional"})}function Iu(e,t){return t===!1?fu(e):gu(e)}function Y(e,t){let n=t??!0;return E(e)?es(e,n):Iu(e,n)}function hu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Y(e[r],t);return n}function yu(e,t){return hu(e.properties,t)}function es(e,t){let n=yu(e,t);return T(n)}function Wt(e,t={}){let n=e.every(o=>L(o)),r=pe(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||pe(t.unevaluatedProperties)||n?{...r,[p]:"Intersect",type:"object",allOf:e}:{...r,[p]:"Intersect",allOf:e},t)}function xu(e){return e.every(t=>ee(t))}function Su(e){return _(e,[W])}function ts(e){return e.map(t=>ee(t)?Su(t):t)}function Tu(e,t){return xu(e)?Y(Wt(ts(e),t)):Wt(ts(e),t)}function pn(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return S(t);if(e.some(n=>Ge(n)))throw new Error("Cannot intersect transform types");return Tu(e,t)}function X(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return S(t);if(e.some(n=>Ge(n)))throw new Error("Cannot intersect transform types");return Wt(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 V("Ref: $ref must be a string");return u({[p]:"Ref",$ref:t},n)}function bu(e,t){return F("Awaited",[F(e,t)])}function Au(e){return F("Awaited",[$e(e)])}function wu(e){return X(ns(e))}function Ou(e){return A(ns(e))}function Pu(e){return Tt(e)}function ns(e){return e.map(t=>Tt(t))}function Tt(e,t){return u(Ae(e)?bu(e.target,e.parameters):U(e)?wu(e.allOf):x(e)?Ou(e.anyOf):ot(e)?Pu(e.item):N(e)?Au(e.$ref):e,t)}function rs(e){let t=[];for(let n of e)t.push(qt(n));return t}function Ru(e){let t=rs(e);return Ko(t)}function Cu(e){let t=rs(e);return vo(t)}function Mu(e){return e.map((t,n)=>n.toString())}function Fu(e){return["[number]"]}function ku(e){return globalThis.Object.getOwnPropertyNames(e)}function Eu(e){return $u?globalThis.Object.getOwnPropertyNames(e).map(n=>n[0]==="^"&&n[n.length-1]==="$"?n.slice(1,n.length-1):n):[]}function qt(e){return U(e)?Ru(e.allOf):x(e)?Cu(e.anyOf):me(e)?Mu(e.items??[]):be(e)?Fu(e.items):L(e)?ku(e.properties):st(e)?Eu(e.patternProperties):[]}var $u=!1;function Uu(e,t){return F("KeyOf",[F(e,t)])}function _u(e){return F("KeyOf",[$e(e)])}function Nu(e,t){let n=qt(e),r=vu(n),o=Ee(r);return u(o,t)}function vu(e){return e.map(t=>t==="[number]"?ge():b(t))}function bt(e,t){return Ae(e)?Uu(e.target,e.parameters):N(e)?_u(e.$ref):E(e)?os(e,t):Nu(e,t)}function Ku(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=bt(e[r],k(t));return n}function Lu(e,t){return Ku(e.properties,t)}function os(e,t){let n=Lu(e,t);return T(n)}function ju(e){let t=[];for(let n of e)t.push(...qt(n));return No(t)}function Du(e){return e.filter(t=>!De(t))}function Gu(e,t){let n=[];for(let r of e)n.push(...gr(r,[t]));return Du(n)}function Vu(e,t){let n={};for(let r of t)n[r]=pn(Gu(e,r));return n}function ss(e,t){let n=ju(e),r=Vu(e,n);return P(r,t)}function ln(e){return u({[p]:"Date",type:"Date"},e)}function fn(e){return u({[p]:"Null",type:"null"},e)}function gn(e){return u({[p]:"Symbol",type:"symbol"},e)}function In(e){return u({[p]:"Undefined",type:"undefined"},e)}function hn(e){return u({[p]:"Uint8Array",type:"Uint8Array"},e)}function qe(e){return u({[p]:"Unknown"},e)}function Bu(e){return e.map(t=>Ir(t,!1))}function Hu(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=ne(Ir(e[n],!1));return t}function yn(e,t){return t===!0?e:ne(e)}function Ir(e,t){return Yn(e)?yn(He(),t):Jn(e)?yn(He(),t):v(e)?ne(Ie(Bu(e))):Ne(e)?hn():et(e)?ln():w(e)?yn(P(Hu(e)),t):Xn(e)?yn(ke([],qe()),t):K(e)?In():Qn(e)?fn():Zn(e)?gn():$t(e)?xt():ie(e)?b(e):_e(e)?b(e):C(e)?b(e):P({})}function is(e,t){return u(Ir(e,!0),t)}function as(e,t){return we(e)?Ie(e.parameters,t):S(t)}function us(e,t){if(K(e))throw new Error("Enum undefined or empty");let n=globalThis.Object.getOwnPropertyNames(e).filter(s=>isNaN(s)).map(s=>e[s]),o=[...new Set(n)].map(s=>b(s));return A(o,{...t,[fe]:"Enum"})}var yr=class extends V{},d;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(d||(d={}));function ye(e){return e===d.False?e:d.True}function At(e){throw new yr(e)}function D(e){return i.IsNever(e)||i.IsIntersect(e)||i.IsUnion(e)||i.IsUnknown(e)||i.IsAny(e)}function G(e,t){return i.IsNever(t)?gs(e,t):i.IsIntersect(t)?xn(e,t):i.IsUnion(t)?br(e,t):i.IsUnknown(t)?xs(e,t):i.IsAny(t)?Tr(e,t):At("StructuralRight")}function Tr(e,t){return d.True}function Wu(e,t){return i.IsIntersect(t)?xn(e,t):i.IsUnion(t)&&t.anyOf.some(n=>i.IsAny(n)||i.IsUnknown(n))?d.True:i.IsUnion(t)?d.Union:i.IsUnknown(t)||i.IsAny(t)?d.True:d.Union}function qu(e,t){return i.IsUnknown(e)?d.False:i.IsAny(e)?d.Union:i.IsNever(e)?d.True:d.False}function zu(e,t){return i.IsObject(t)&&Sn(t)?d.True:D(t)?G(e,t):i.IsArray(t)?ye(R(e.items,t.items)):d.False}function Yu(e,t){return D(t)?G(e,t):i.IsAsyncIterator(t)?ye(R(e.items,t.items)):d.False}function Xu(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsBigInt(t)?d.True:d.False}function ls(e,t){return i.IsLiteralBoolean(e)||i.IsBoolean(e)?d.True:d.False}function Ju(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsBoolean(t)?d.True:d.False}function Qu(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsConstructor(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>ye(R(t.parameters[r],n))===d.True)?ye(R(e.returns,t.returns)):d.False:d.False}function Zu(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsDate(t)?d.True:d.False}function ed(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsFunction(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((n,r)=>ye(R(t.parameters[r],n))===d.True)?ye(R(e.returns,t.returns)):d.False:d.False}function fs(e,t){return i.IsLiteral(e)&&z.IsNumber(e.const)||i.IsNumber(e)||i.IsInteger(e)?d.True:d.False}function td(e,t){return i.IsInteger(t)||i.IsNumber(t)?d.True:D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):d.False}function xn(e,t){return t.allOf.every(n=>R(e,n)===d.True)?d.True:d.False}function nd(e,t){return e.allOf.some(n=>R(n,t)===d.True)?d.True:d.False}function rd(e,t){return D(t)?G(e,t):i.IsIterator(t)?ye(R(e.items,t.items)):d.False}function od(e,t){return i.IsLiteral(t)&&t.const===e.const?d.True:D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsString(t)?ys(e,t):i.IsNumber(t)?Is(e,t):i.IsInteger(t)?fs(e,t):i.IsBoolean(t)?ls(e,t):d.False}function gs(e,t){return d.False}function sd(e,t){return d.True}function ds(e){let[t,n]=[e,0];for(;i.IsNot(t);)t=t.not,n+=1;return n%2===0?t:qe()}function id(e,t){return i.IsNot(e)?R(ds(e),t):i.IsNot(t)?R(e,ds(t)):At("Invalid fallthrough for Not")}function ad(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsNull(t)?d.True:d.False}function Is(e,t){return i.IsLiteralNumber(e)||i.IsNumber(e)||i.IsInteger(e)?d.True:d.False}function ud(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsInteger(t)||i.IsNumber(t)?d.True:d.False}function re(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function ms(e){return Sn(e)}function ps(e){return re(e,0)||re(e,1)&&"description"in e.properties&&i.IsUnion(e.properties.description)&&e.properties.description.anyOf.length===2&&(i.IsString(e.properties.description.anyOf[0])&&i.IsUndefined(e.properties.description.anyOf[1])||i.IsString(e.properties.description.anyOf[1])&&i.IsUndefined(e.properties.description.anyOf[0]))}function hr(e){return re(e,0)}function cs(e){return re(e,0)}function dd(e){return re(e,0)}function md(e){return re(e,0)}function pd(e){return Sn(e)}function cd(e){let t=ge();return re(e,0)||re(e,1)&&"length"in e.properties&&ye(R(e.properties.length,t))===d.True}function ld(e){return re(e,0)}function Sn(e){let t=ge();return re(e,0)||re(e,1)&&"length"in e.properties&&ye(R(e.properties.length,t))===d.True}function fd(e){let t=ke([He()],He());return re(e,0)||re(e,1)&&"then"in e.properties&&ye(R(e.properties.then,t))===d.True}function hs(e,t){return R(e,t)===d.False||i.IsOptional(e)&&!i.IsOptional(t)?d.False:d.True}function J(e,t){return i.IsUnknown(e)?d.False:i.IsAny(e)?d.Union:i.IsNever(e)||i.IsLiteralString(e)&&ms(t)||i.IsLiteralNumber(e)&&hr(t)||i.IsLiteralBoolean(e)&&cs(t)||i.IsSymbol(e)&&ps(t)||i.IsBigInt(e)&&dd(t)||i.IsString(e)&&ms(t)||i.IsSymbol(e)&&ps(t)||i.IsNumber(e)&&hr(t)||i.IsInteger(e)&&hr(t)||i.IsBoolean(e)&&cs(t)||i.IsUint8Array(e)&&pd(t)||i.IsDate(e)&&md(t)||i.IsConstructor(e)&&ld(t)||i.IsFunction(e)&&cd(t)?d.True:i.IsRecord(e)&&i.IsString(xr(e))?t[fe]==="Record"?d.True:d.False:i.IsRecord(e)&&i.IsNumber(xr(e))&&re(t,0)?d.True:d.False}function gd(e,t){return D(t)?G(e,t):i.IsRecord(t)?xe(e,t):i.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!i.IsOptional(t.properties[n]))return d.False;if(i.IsOptional(t.properties[n]))return d.True;if(hs(e.properties[n],t.properties[n])===d.False)return d.False}return d.True})():d.False}function Id(e,t){return D(t)?G(e,t):i.IsObject(t)&&fd(t)?d.True:i.IsPromise(t)?ye(R(e.item,t.item)):d.False}function xr(e){return Ve in e.patternProperties?ge():Be in e.patternProperties?Ce():At("Unknown record key pattern")}function Sr(e){return Ve in e.patternProperties?e.patternProperties[Ve]:Be in e.patternProperties?e.patternProperties[Be]:At("Unable to get record value schema")}function xe(e,t){let[n,r]=[xr(t),Sr(t)];return i.IsLiteralString(e)&&i.IsNumber(n)&&ye(R(e,r))===d.True?d.True:i.IsUint8Array(e)&&i.IsNumber(n)||i.IsString(e)&&i.IsNumber(n)||i.IsArray(e)&&i.IsNumber(n)?R(e,r):i.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(hs(r,e.properties[o])===d.False)return d.False;return d.True})():d.False}function hd(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?R(Sr(e),Sr(t)):d.False}function yd(e,t){let n=i.IsRegExp(e)?Ce():e,r=i.IsRegExp(t)?Ce():t;return R(n,r)}function ys(e,t){return i.IsLiteral(e)&&z.IsString(e.const)||i.IsString(e)?d.True:d.False}function xd(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsString(t)?d.True:d.False}function Sd(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsSymbol(t)?d.True:d.False}function Td(e,t){return i.IsTemplateLiteral(e)?R(at(e),t):i.IsTemplateLiteral(t)?R(e,at(t)):At("Invalid fallthrough for TemplateLiteral")}function bd(e,t){return i.IsArray(t)&&e.items!==void 0&&e.items.every(n=>R(n,t.items)===d.True)}function Ad(e,t){return i.IsNever(e)?d.True:i.IsUnknown(e)?d.False:i.IsAny(e)?d.Union:d.False}function wd(e,t){return D(t)?G(e,t):i.IsObject(t)&&Sn(t)||i.IsArray(t)&&bd(e,t)?d.True:i.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)=>R(n,t.items[r])===d.True)?d.True:d.False:d.False}function Od(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsUint8Array(t)?d.True:d.False}function Pd(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?xe(e,t):i.IsVoid(t)?Md(e,t):i.IsUndefined(t)?d.True:d.False}function br(e,t){return t.anyOf.some(n=>R(e,n)===d.True)?d.True:d.False}function Rd(e,t){return e.anyOf.every(n=>R(n,t)===d.True)?d.True:d.False}function xs(e,t){return d.True}function Cd(e,t){return i.IsNever(t)?gs(e,t):i.IsIntersect(t)?xn(e,t):i.IsUnion(t)?br(e,t):i.IsAny(t)?Tr(e,t):i.IsString(t)?ys(e,t):i.IsNumber(t)?Is(e,t):i.IsInteger(t)?fs(e,t):i.IsBoolean(t)?ls(e,t):i.IsArray(t)?qu(e,t):i.IsTuple(t)?Ad(e,t):i.IsObject(t)?J(e,t):i.IsUnknown(t)?d.True:d.False}function Md(e,t){return i.IsUndefined(e)||i.IsUndefined(e)?d.True:d.False}function Fd(e,t){return i.IsIntersect(t)?xn(e,t):i.IsUnion(t)?br(e,t):i.IsUnknown(t)?xs(e,t):i.IsAny(t)?Tr(e,t):i.IsObject(t)?J(e,t):i.IsVoid(t)?d.True:d.False}function R(e,t){return i.IsTemplateLiteral(e)||i.IsTemplateLiteral(t)?Td(e,t):i.IsRegExp(e)||i.IsRegExp(t)?yd(e,t):i.IsNot(e)||i.IsNot(t)?id(e,t):i.IsAny(e)?Wu(e,t):i.IsArray(e)?zu(e,t):i.IsBigInt(e)?Xu(e,t):i.IsBoolean(e)?Ju(e,t):i.IsAsyncIterator(e)?Yu(e,t):i.IsConstructor(e)?Qu(e,t):i.IsDate(e)?Zu(e,t):i.IsFunction(e)?ed(e,t):i.IsInteger(e)?td(e,t):i.IsIntersect(e)?nd(e,t):i.IsIterator(e)?rd(e,t):i.IsLiteral(e)?od(e,t):i.IsNever(e)?sd(e,t):i.IsNull(e)?ad(e,t):i.IsNumber(e)?ud(e,t):i.IsObject(e)?gd(e,t):i.IsRecord(e)?hd(e,t):i.IsString(e)?xd(e,t):i.IsSymbol(e)?Sd(e,t):i.IsTuple(e)?wd(e,t):i.IsPromise(e)?Id(e,t):i.IsUint8Array(e)?Od(e,t):i.IsUndefined(e)?Pd(e,t):i.IsUnion(e)?Rd(e,t):i.IsUnknown(e)?Cd(e,t):i.IsVoid(e)?Fd(e,t):At(`Unknown left type operand '${e[p]}'`)}function ze(e,t){return R(e,t)}function kd(e,t,n,r,o){let s={};for(let a of globalThis.Object.getOwnPropertyNames(e))s[a]=wt(e[a],t,n,r,k(o));return s}function Ed(e,t,n,r,o){return kd(e.properties,t,n,r,o)}function Ss(e,t,n,r,o){let s=Ed(e,t,n,r,o);return T(s)}function $d(e,t,n,r){let o=ze(e,t);return o===d.Union?A([n,r]):o===d.True?n:r}function wt(e,t,n,r,o){return E(e)?Ss(e,t,n,r,o):ue(e)?u(Ts(e,t,n,r,o)):u($d(e,t,n,r),o)}function Ud(e,t,n,r,o){return{[e]:wt(b(e),t,n,r,k(o))}}function _d(e,t,n,r,o){return e.reduce((s,a)=>({...s,...Ud(a,t,n,r,o)}),{})}function Nd(e,t,n,r,o){return _d(e.keys,t,n,r,o)}function Ts(e,t,n,r,o){let s=Nd(e,t,n,r,o);return T(s)}function bs(e,t){return Ot(at(e),t)}function vd(e,t){let n=e.filter(r=>ze(r,t)===d.False);return n.length===1?n[0]:A(n)}function Ot(e,t,n={}){return de(e)?u(bs(e,t),n):E(e)?u(As(e,t),n):u(x(e)?vd(e.anyOf,t):ze(e,t)!==d.False?S():e,n)}function Kd(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ot(e[r],t);return n}function Ld(e,t){return Kd(e.properties,t)}function As(e,t){let n=Ld(e,t);return T(n)}function ws(e,t){return Pt(at(e),t)}function jd(e,t){let n=e.filter(r=>ze(r,t)!==d.False);return n.length===1?n[0]:A(n)}function Pt(e,t,n){return de(e)?u(ws(e,t),n):E(e)?u(Os(e,t),n):u(x(e)?jd(e.anyOf,t):ze(e,t)!==d.False?e:S(),n)}function Dd(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Pt(e[r],t);return n}function Gd(e,t){return Dd(e.properties,t)}function Os(e,t){let n=Gd(e,t);return T(n)}function Ps(e,t){return we(e)?u(e.returns,t):S(t)}function Tn(e){return ne(Y(e))}function ut(e,t,n){return u({[p]:"Record",type:"object",patternProperties:{[e]:t}},n)}function Ar(e,t,n){let r={};for(let o of e)r[o]=t;return P(r,{...n,[fe]:"Record"})}function Vd(e,t,n){return Go(e)?Ar(te(e),t,n):ut(e.pattern,t,n)}function Bd(e,t,n){return Ar(te(A(e)),t,n)}function Hd(e,t,n){return Ar([e.toString()],t,n)}function Wd(e,t,n){return ut(e.source,t,n)}function qd(e,t,n){let r=K(e.pattern)?Be:e.pattern;return ut(r,t,n)}function zd(e,t,n){return ut(Be,t,n)}function Yd(e,t,n){return ut(Uo,t,n)}function Xd(e,t,n){return P({true:t,false:t},n)}function Jd(e,t,n){return ut(Ve,t,n)}function Qd(e,t,n){return ut(Ve,t,n)}function bn(e,t,n={}){return x(e)?Bd(e.anyOf,t,n):de(e)?Vd(e,t,n):ae(e)?Hd(e.const,t,n):ve(e)?Xd(e,t,n):Pe(e)?Jd(e,t,n):Re(e)?Qd(e,t,n):nr(e)?Wd(e,t,n):Ke(e)?qd(e,t,n):er(e)?zd(e,t,n):De(e)?Yd(e,t,n):S(n)}function An(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function Rs(e){let t=An(e);return t===Be?Ce():t===Ve?ge():Ce({pattern:t})}function wn(e){return e.patternProperties[An(e)]}function Zd(e,t){return t.parameters=zt(e,t.parameters),t.returns=Me(e,t.returns),t}function em(e,t){return t.parameters=zt(e,t.parameters),t.returns=Me(e,t.returns),t}function tm(e,t){return t.allOf=zt(e,t.allOf),t}function nm(e,t){return t.anyOf=zt(e,t.anyOf),t}function rm(e,t){return K(t.items)||(t.items=zt(e,t.items)),t}function om(e,t){return t.items=Me(e,t.items),t}function sm(e,t){return t.items=Me(e,t.items),t}function im(e,t){return t.items=Me(e,t.items),t}function am(e,t){return t.item=Me(e,t.item),t}function um(e,t){let n=cm(e,t.properties);return{...t,...P(n)}}function dm(e,t){let n=Me(e,Rs(t)),r=Me(e,wn(t)),o=bn(n,r);return{...t,...o}}function mm(e,t){return t.index in e?e[t.index]:qe()}function pm(e,t){let n=lt(t),r=ee(t),o=Me(e,t);return n&&r?Tn(o):n&&!r?ne(o):!n&&r?Y(o):o}function cm(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:pm(e,t[r])}),{})}function zt(e,t){return t.map(n=>Me(e,n))}function Me(e,t){return we(t)?Zd(e,t):Oe(t)?em(e,t):U(t)?tm(e,t):x(t)?nm(e,t):me(t)?rm(e,t):be(t)?om(e,t):tt(t)?sm(e,t):rt(t)?im(e,t):ot(t)?am(e,t):L(t)?um(e,t):st(t)?dm(e,t):tr(t)?mm(e,t):t}function Cs(e,t){return Me(t,ct(e))}function Ms(e){return u({[p]:"Integer",type:"integer"},e)}function lm(e,t,n){return{[e]:Fe(b(e),t,k(n))}}function fm(e,t,n){return e.reduce((o,s)=>({...o,...lm(s,t,n)}),{})}function gm(e,t,n){return fm(e.keys,t,n)}function Fs(e,t,n){let r=gm(e,t,n);return T(r)}function Im(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function hm(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function ym(e){return e.toUpperCase()}function xm(e){return e.toLowerCase()}function Sm(e,t,n){let r=yt(e.pattern);if(!it(r))return{...e,pattern:ks(e.pattern,t)};let a=[...Bt(r)].map(f=>b(f)),m=Es(a,t),c=A(m);return mn([c],n)}function ks(e,t){return typeof e=="string"?t==="Uncapitalize"?Im(e):t==="Capitalize"?hm(e):t==="Uppercase"?ym(e):t==="Lowercase"?xm(e):e:e.toString()}function Es(e,t){return e.map(n=>Fe(n,t))}function Fe(e,t,n={}){return ue(e)?Fs(e,t,n):de(e)?Sm(e,t,n):x(e)?A(Es(e.anyOf,t),n):ae(e)?b(ks(e.const,t),n):u(e,n)}function $s(e,t={}){return Fe(e,"Capitalize",t)}function Us(e,t={}){return Fe(e,"Lowercase",t)}function _s(e,t={}){return Fe(e,"Uncapitalize",t)}function Ns(e,t={}){return Fe(e,"Uppercase",t)}function Tm(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ye(e[o],t,k(n));return r}function bm(e,t,n){return Tm(e.properties,t,n)}function vs(e,t,n){let r=bm(e,t,n);return T(r)}function Am(e,t){return e.map(n=>wr(n,t))}function wm(e,t){return e.map(n=>wr(n,t))}function Om(e,t){let{[t]:n,...r}=e;return r}function Pm(e,t){return t.reduce((n,r)=>Om(n,r),e)}function Rm(e,t,n){let r=_(e,[j,"$id","required","properties"]),o=Pm(n,t);return P(o,r)}function Cm(e){let t=e.reduce((n,r)=>on(r)?[...n,b(r)]:n,[]);return A(t)}function wr(e,t){return U(e)?X(Am(e.allOf,t)):x(e)?A(wm(e.anyOf,t)):L(e)?Rm(e,t,e.properties):P({})}function Ye(e,t,n){let r=v(t)?Cm(t):t,o=pe(t)?te(t):t,s=N(e),a=N(t);return E(e)?vs(e,o,n):ue(t)?Ks(e,t,n):s&&a?F("Omit",[e,r],n):!s&&a?F("Omit",[e,r],n):s&&!a?F("Omit",[e,r],n):u({...wr(e,o),...n})}function Mm(e,t,n){return{[t]:Ye(e,[t],k(n))}}function Fm(e,t,n){return t.reduce((r,o)=>({...r,...Mm(e,o,n)}),{})}function km(e,t,n){return Fm(e,t.keys,n)}function Ks(e,t,n){let r=km(e,t,n);return T(r)}function Em(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Xe(e[o],t,k(n));return r}function $m(e,t,n){return Em(e.properties,t,n)}function Ls(e,t,n){let r=$m(e,t,n);return T(r)}function Um(e,t){return e.map(n=>Or(n,t))}function _m(e,t){return e.map(n=>Or(n,t))}function Nm(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function vm(e,t,n){let r=_(e,[j,"$id","required","properties"]),o=Nm(n,t);return P(o,r)}function Km(e){let t=e.reduce((n,r)=>on(r)?[...n,b(r)]:n,[]);return A(t)}function Or(e,t){return U(e)?X(Um(e.allOf,t)):x(e)?A(_m(e.anyOf,t)):L(e)?vm(e,t,e.properties):P({})}function Xe(e,t,n){let r=v(t)?Km(t):t,o=pe(t)?te(t):t,s=N(e),a=N(t);return E(e)?Ls(e,o,n):ue(t)?js(e,t,n):s&&a?F("Pick",[e,r],n):!s&&a?F("Pick",[e,r],n):s&&!a?F("Pick",[e,r],n):u({...Or(e,o),...n})}function Lm(e,t,n){return{[t]:Xe(e,[t],k(n))}}function jm(e,t,n){return t.reduce((r,o)=>({...r,...Lm(e,o,n)}),{})}function Dm(e,t,n){return jm(e,t.keys,n)}function js(e,t,n){let r=Dm(e,t,n);return T(r)}function Gm(e,t){return F("Partial",[F(e,t)])}function Vm(e){return F("Partial",[$e(e)])}function Bm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=Y(e[n]);return t}function Hm(e,t){let n=_(e,[j,"$id","required","properties"]),r=Bm(t);return P(r,n)}function Ds(e){return e.map(t=>Gs(t))}function Gs(e){return Ae(e)?Gm(e.target,e.parameters):N(e)?Vm(e.$ref):U(e)?X(Ds(e.allOf)):x(e)?A(Ds(e.anyOf)):L(e)?Hm(e,e.properties):nt(e)||ve(e)||Pe(e)||ae(e)||Nt(e)||Re(e)||Ke(e)||vt(e)||Kt(e)?e:P({})}function Rt(e,t){return E(e)?Vs(e,t):u({...Gs(e),...t})}function Wm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Rt(e[r],k(t));return n}function qm(e,t){return Wm(e.properties,t)}function Vs(e,t){let n=qm(e,t);return T(n)}function zm(e,t){return F("Required",[F(e,t)])}function Ym(e){return F("Required",[$e(e)])}function Xm(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=_(e[n],[W]);return t}function Jm(e,t){let n=_(e,[j,"$id","required","properties"]),r=Xm(t);return P(r,n)}function Bs(e){return e.map(t=>Hs(t))}function Hs(e){return Ae(e)?zm(e.target,e.parameters):N(e)?Ym(e.$ref):U(e)?X(Bs(e.allOf)):x(e)?A(Bs(e.anyOf)):L(e)?Jm(e,e.properties):nt(e)||ve(e)||Pe(e)||ae(e)||Nt(e)||Re(e)||Ke(e)||vt(e)||Kt(e)?e:P({})}function Ct(e,t){return E(e)?Ws(e,t):u({...Hs(e),...t})}function Qm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ct(e[r],t);return n}function Zm(e,t){return Qm(e.properties,t)}function Ws(e,t){let n=Zm(e,t);return T(n)}function ep(e,t){return t.map(n=>N(n)?Pr(e,n.$ref):ce(e,n))}function Pr(e,t){return t in e?N(e[t])?Pr(e,e[t].$ref):ce(e,e[t]):S()}function tp(e){return Tt(e[0])}function np(e){return We(e[0],e[1])}function rp(e){return bt(e[0])}function op(e){return Rt(e[0])}function sp(e){return Ye(e[0],e[1])}function ip(e){return Xe(e[0],e[1])}function ap(e){return Ct(e[0])}function up(e,t,n){let r=ep(e,n);return t==="Awaited"?tp(r):t==="Index"?np(r):t==="KeyOf"?rp(r):t==="Partial"?op(r):t==="Omit"?sp(r):t==="Pick"?ip(r):t==="Required"?ap(r):S()}function dp(e,t){return ft(ce(e,t))}function mp(e,t){return gt(ce(e,t))}function pp(e,t,n){return It(Yt(e,t),ce(e,n))}function cp(e,t,n){return ke(Yt(e,t),ce(e,n))}function lp(e,t){return X(Yt(e,t))}function fp(e,t){return St(ce(e,t))}function gp(e,t){return P(globalThis.Object.keys(t).reduce((n,r)=>({...n,[r]:ce(e,t[r])}),{}))}function Ip(e,t){let[n,r]=[ce(e,wn(t)),An(t)],o=ct(t);return o.patternProperties[r]=n,o}function hp(e,t){return N(t)?{...Pr(e,t.$ref),[j]:t[j]}:t}function yp(e,t){return Ie(Yt(e,t))}function xp(e,t){return A(Yt(e,t))}function Yt(e,t){return t.map(n=>ce(e,n))}function ce(e,t){return ee(t)?u(ce(e,_(t,[W])),t):lt(t)?u(ce(e,_(t,[Te])),t):Ge(t)?u(hp(e,t),t):be(t)?u(dp(e,t.items),t):tt(t)?u(mp(e,t.items),t):Ae(t)?u(up(e,t.target,t.parameters)):we(t)?u(pp(e,t.parameters,t.returns),t):Oe(t)?u(cp(e,t.parameters,t.returns),t):U(t)?u(lp(e,t.allOf),t):rt(t)?u(fp(e,t.items),t):L(t)?u(gp(e,t.properties),t):st(t)?u(Ip(e,t)):me(t)?u(yp(e,t.items||[]),t):x(t)?u(xp(e,t.anyOf),t):t}function Sp(e,t){return t in e?ce(e,e[t]):S()}function qs(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:Sp(e,n)}),{})}var Rr=class{constructor(t){let n=qs(t),r=this.WithIdentifiers(n);this.$defs=r}Import(t,n){let r={...this.$defs,[t]:u(this.$defs[t],n)};return u({[p]:"Import",$defs:r,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:{...t[r],$id:r}}),{})}};function zs(e){return new Rr(e)}function Ys(e,t){return u({[p]:"Not",not:e},t)}function Xs(e,t){return Oe(e)?Ie(e.parameters,t):S()}var Tp=0;function Js(e,t={}){K(t.$id)&&(t.$id=`T${Tp++}`);let n=ct(e({[p]:"This",$ref:`${t.$id}`}));return n.$id=t.$id,u({[fe]:"Recursive",...n},t)}function Qs(e,t){let n=C(e)?new globalThis.RegExp(e):e;return u({[p]:"RegExp",type:"RegExp",source:n.source,flags:n.flags},t)}function bp(e){return U(e)?e.allOf:x(e)?e.anyOf:me(e)?e.items??[]:[]}function Zs(e){return bp(e)}function ei(e,t){return Oe(e)?u(e.returns,t):S(t)}var Cr=class{constructor(t){this.schema=t}Decode(t){return new Mr(this.schema,t)}},Mr=class{constructor(t,n){this.schema=t,this.decode=n}EncodeTransform(t,n){let s={Encode:a=>n[j].Encode(t(a)),Decode:a=>this.decode(n[j].Decode(a))};return{...n,[j]:s}}EncodeSchema(t,n){let r={Decode:this.decode,Encode:t};return{...n,[j]:r}}Encode(t){return Ge(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function ti(e){return new Cr(e)}function ni(e={}){return u({[p]:e[p]??"Unsafe"},e)}function ri(e){return u({[p]:"Void",type:"void"},e)}var Fr={};zn(Fr,{Any:()=>He,Argument:()=>Lo,Array:()=>ft,AsyncIterator:()=>gt,Awaited:()=>Tt,BigInt:()=>xt,Boolean:()=>dn,Capitalize:()=>$s,Composite:()=>ss,Const:()=>is,Constructor:()=>It,ConstructorParameters:()=>as,Date:()=>ln,Enum:()=>us,Exclude:()=>Ot,Extends:()=>wt,Extract:()=>Pt,Function:()=>ke,Index:()=>We,InstanceType:()=>Ps,Instantiate:()=>Cs,Integer:()=>Ms,Intersect:()=>X,Iterator:()=>St,KeyOf:()=>bt,Literal:()=>b,Lowercase:()=>Us,Mapped:()=>Zo,Module:()=>zs,Never:()=>S,Not:()=>Ys,Null:()=>fn,Number:()=>ge,Object:()=>P,Omit:()=>Ye,Optional:()=>Y,Parameters:()=>Xs,Partial:()=>Rt,Pick:()=>Xe,Promise:()=>cn,Readonly:()=>ne,ReadonlyOptional:()=>Tn,Record:()=>bn,Recursive:()=>Js,Ref:()=>$e,RegExp:()=>Qs,Required:()=>Ct,Rest:()=>Zs,ReturnType:()=>ei,String:()=>Ce,Symbol:()=>gn,TemplateLiteral:()=>mn,Transform:()=>ti,Tuple:()=>Ie,Uint8Array:()=>hn,Uncapitalize:()=>_s,Undefined:()=>In,Union:()=>A,Unknown:()=>qe,Unsafe:()=>ni,Uppercase:()=>Ns,Void:()=>ri});var l=Fr;var g=null;function kr(e){g=e}import{readFileSync as Ap}from"fs";import{homedir as wp}from"os";import{join as Op}from"path";var Xt;function oi(){if(Xt!==void 0)return Xt;try{let e=Ap(Op(wp(),".claude.json"),"utf-8");Xt=JSON.parse(e).mcpServers??{}}catch{Xt={}}return Xt}var h={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",codexApprovalPolicy:"on-request",planApproval:"delegate",reasoningEffort:"medium"};function si(e){h={maxSessions:e.maxSessions??20,defaultModel:e.defaultModel,model:e.model,reasoningEffort:e.reasoningEffort??"medium",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:e.defaultHarness}}function ii(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=Jt(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function Mt(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}`:h.fallbackChannel??"unknown"}function Ft(e){return e?.messageThreadId??void 0}function Jt(e){let t=h.agentChannels;if(!t)return;let n=s=>s.replace(/\/+$/,""),r=n(e),o=Object.entries(t).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of o)if(r===n(s)||r.startsWith(n(s)+"/"))return a}function ai(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 Rp(e){return e instanceof Error?e.message:String(e)}function Cp(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function ui(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(!Cp(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||h.defaultWorkdir||process.cwd();if(!Pp(r))return{content:[{type:"text",text:`Error: Working directory does not exist: ${r}`}]};try{let o=n.harness??h.defaultHarness,s=o==="codex"?h.model??h.defaultModel:h.defaultModel,a=n.resume_session_id,m=a?g.resolve(a):void 0,c=a?g.getPersistedSession(a):void 0;if(a){let Qe=g.resolveHarnessSessionId(a);if(!Qe)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${a}" to a session ID. Use agent_sessions to list available sessions.`}]};a=Qe}let{resumeSessionId:f,clearedPersistedCodexResume:$}=kt({requestedResumeSessionId:a,activeSession:m?{harnessSessionId:m.harnessSessionId}:void 0,persistedSession:c?{harness:c.harness}:void 0}),le=ii(e),oe=Mt(e,le||Jt(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 Z=g.spawn({prompt:n.prompt,name:n.name,workdir:r,model:n.model??s,reasoningEffort:h.reasoningEffort,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:f,forkSession:f?n.fork_session:!1,multiTurn:!n.multi_turn_disabled,permissionMode:n.permission_mode,codexApprovalPolicy:o==="codex"?h.codexApprovalPolicy:void 0,originChannel:oe,originThreadId:ai(Q)??Ft(e),originAgentId:e.agentId||void 0,originSessionKey:Q,harness:o}),q=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,Se=["Session launched successfully.",` Name: ${Z.name}`,` ID: ${Z.id}`,` Dir: ${r}`,` Model: ${Z.model??"default"}`,` Prompt: "${q}"`];return o==="codex"&&Se.push(` Codex approval policy: ${Z.codexApprovalPolicy??h.codexApprovalPolicy}`),n.resume_session_id&&(Se.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),$&&Se.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),Se.push(n.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),Se.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:Se.join(`
|
|
2
|
-
`)}]}}catch(o){let s=
|
|
1
|
+
var ma=Object.defineProperty;var Qr=(e,t)=>{for(var r in t)ma(e,r,{get:t[r],enumerable:!0})};import{existsSync as Bc}from"fs";var Q={};Qr(Q,{HasPropertyKey:()=>nr,IsArray:()=>K,IsAsyncIterator:()=>Zr,IsBigInt:()=>Ut,IsBoolean:()=>ve,IsDate:()=>rt,IsFunction:()=>en,IsIterator:()=>tn,IsNull:()=>rn,IsNumber:()=>ue,IsObject:()=>P,IsRegExp:()=>Nt,IsString:()=>M,IsSymbol:()=>nn,IsUint8Array:()=>Ke,IsUndefined:()=>L});function nr(e,t){return t in e}function Zr(e){return P(e)&&!K(e)&&!Ke(e)&&Symbol.asyncIterator in e}function K(e){return Array.isArray(e)}function Ut(e){return typeof e=="bigint"}function ve(e){return typeof e=="boolean"}function rt(e){return e instanceof globalThis.Date}function en(e){return typeof e=="function"}function tn(e){return P(e)&&!K(e)&&!Ke(e)&&Symbol.iterator in e}function rn(e){return e===null}function ue(e){return typeof e=="number"}function P(e){return typeof e=="object"&&e!==null}function Nt(e){return e instanceof globalThis.RegExp}function M(e){return typeof e=="string"}function nn(e){return typeof e=="symbol"}function Ke(e){return e instanceof globalThis.Uint8Array}function L(e){return e===void 0}function ca(e){return e.map(t=>or(t))}function pa(e){return new Date(e.getTime())}function la(e){return new Uint8Array(e)}function fa(e){return new RegExp(e.source,e.flags)}function ga(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=or(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=or(e[r]);return t}function or(e){return K(e)?ca(e):rt(e)?pa(e):Ke(e)?la(e):Nt(e)?fa(e):P(e)?ga(e):e}function F(e){return or(e)}function lt(e,t){return t===void 0?F(e):F({...t,...e})}function Jn(e){return e!==null&&typeof e=="object"}function Xn(e){return globalThis.Array.isArray(e)&&!globalThis.ArrayBuffer.isView(e)}function Qn(e){return e===void 0}function Zn(e){return typeof e=="number"}var sr;(function(e){e.InstanceMode="default",e.ExactOptionalPropertyTypes=!1,e.AllowArrayObject=!1,e.AllowNaN=!1,e.AllowNullVoid=!1;function t(i,m){return e.ExactOptionalPropertyTypes?m in i:i[m]!==void 0}e.IsExactOptionalProperty=t;function r(i){let m=Jn(i);return e.AllowArrayObject?m:m&&!Xn(i)}e.IsObjectLike=r;function n(i){return r(i)&&!(i instanceof Date)&&!(i instanceof Uint8Array)}e.IsRecordLike=n;function o(i){return e.AllowNaN?Zn(i):Number.isFinite(i)}e.IsNumberLike=o;function s(i){let m=Qn(i);return e.AllowNullVoid?m||i===null:m}e.IsVoidLike=s})(sr||(sr={}));function Ia(e){return globalThis.Object.freeze(e).map(t=>_t(t))}function ha(e){let t={};for(let r of Object.getOwnPropertyNames(e))t[r]=_t(e[r]);for(let r of Object.getOwnPropertySymbols(e))t[r]=_t(e[r]);return globalThis.Object.freeze(t)}function _t(e){return K(e)?Ia(e):rt(e)?e:Ke(e)?e:Nt(e)?e:P(e)?ha(e):e}function u(e,t){let r=t!==void 0?{...t,...e}:e;switch(sr.InstanceMode){case"freeze":return _t(r);case"clone":return F(r);default:return r}}var q=class extends Error{constructor(t){super(t)}};var G=Symbol.for("TypeBox.Transform"),Te=Symbol.for("TypeBox.Readonly"),J=Symbol.for("TypeBox.Optional"),ge=Symbol.for("TypeBox.Hint"),c=Symbol.for("TypeBox.Kind");function ft(e){return P(e)&&e[Te]==="Readonly"}function re(e){return P(e)&&e[J]==="Optional"}function on(e){return y(e,"Any")}function sn(e){return y(e,"Argument")}function be(e){return y(e,"Array")}function nt(e){return y(e,"AsyncIterator")}function ot(e){return y(e,"BigInt")}function Le(e){return y(e,"Boolean")}function Ae(e){return y(e,"Computed")}function we(e){return y(e,"Constructor")}function ya(e){return y(e,"Date")}function Pe(e){return y(e,"Function")}function Oe(e){return y(e,"Integer")}function U(e){return y(e,"Intersect")}function st(e){return y(e,"Iterator")}function y(e,t){return P(e)&&c in e&&e[c]===t}function ir(e){return ve(e)||ue(e)||M(e)}function de(e){return y(e,"Literal")}function me(e){return y(e,"MappedKey")}function $(e){return y(e,"MappedResult")}function Ve(e){return y(e,"Never")}function xa(e){return y(e,"Not")}function vt(e){return y(e,"Null")}function Re(e){return y(e,"Number")}function j(e){return y(e,"Object")}function it(e){return y(e,"Promise")}function at(e){return y(e,"Record")}function v(e){return y(e,"Ref")}function an(e){return y(e,"RegExp")}function je(e){return y(e,"String")}function Kt(e){return y(e,"Symbol")}function ce(e){return y(e,"TemplateLiteral")}function Sa(e){return y(e,"This")}function Be(e){return P(e)&&G in e}function pe(e){return y(e,"Tuple")}function Lt(e){return y(e,"Undefined")}function x(e){return y(e,"Union")}function Ta(e){return y(e,"Uint8Array")}function ba(e){return y(e,"Unknown")}function Aa(e){return y(e,"Unsafe")}function wa(e){return y(e,"Void")}function Pa(e){return P(e)&&c in e&&M(e[c])}function le(e){return on(e)||sn(e)||be(e)||Le(e)||ot(e)||nt(e)||Ae(e)||we(e)||ya(e)||Pe(e)||Oe(e)||U(e)||st(e)||de(e)||me(e)||$(e)||Ve(e)||xa(e)||vt(e)||Re(e)||j(e)||it(e)||at(e)||v(e)||an(e)||je(e)||Kt(e)||ce(e)||Sa(e)||pe(e)||Lt(e)||x(e)||Ta(e)||ba(e)||Aa(e)||wa(e)||Pa(e)}var a={};Qr(a,{IsAny:()=>no,IsArgument:()=>oo,IsArray:()=>so,IsAsyncIterator:()=>io,IsBigInt:()=>ao,IsBoolean:()=>uo,IsComputed:()=>mo,IsConstructor:()=>co,IsDate:()=>po,IsFunction:()=>lo,IsImport:()=>Ea,IsInteger:()=>fo,IsIntersect:()=>go,IsIterator:()=>Io,IsKind:()=>Go,IsKindOf:()=>I,IsLiteral:()=>Dt,IsLiteralBoolean:()=>Fa,IsLiteralNumber:()=>yo,IsLiteralString:()=>ho,IsLiteralValue:()=>xo,IsMappedKey:()=>So,IsMappedResult:()=>To,IsNever:()=>bo,IsNot:()=>Ao,IsNull:()=>wo,IsNumber:()=>Po,IsObject:()=>Oo,IsOptional:()=>ka,IsPromise:()=>Ro,IsProperties:()=>ar,IsReadonly:()=>Ma,IsRecord:()=>Co,IsRecursive:()=>$a,IsRef:()=>Mo,IsRegExp:()=>ko,IsSchema:()=>z,IsString:()=>Eo,IsSymbol:()=>Fo,IsTemplateLiteral:()=>$o,IsThis:()=>Uo,IsTransform:()=>No,IsTuple:()=>_o,IsUint8Array:()=>Ko,IsUndefined:()=>vo,IsUnion:()=>cn,IsUnionLiteral:()=>Ua,IsUnknown:()=>Lo,IsUnsafe:()=>jo,IsVoid:()=>Do,TypeGuardUnknownTypeError:()=>un});var un=class extends q{},Oa=["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 eo(e){try{return new RegExp(e),!0}catch{return!1}}function dn(e){if(!M(e))return!1;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=7&&r<=13||r===27||r===127)return!1}return!0}function to(e){return mn(e)||z(e)}function jt(e){return L(e)||Ut(e)}function k(e){return L(e)||ue(e)}function mn(e){return L(e)||ve(e)}function O(e){return L(e)||M(e)}function Ra(e){return L(e)||M(e)&&dn(e)&&eo(e)}function Ca(e){return L(e)||M(e)&&dn(e)}function ro(e){return L(e)||z(e)}function Ma(e){return P(e)&&e[Te]==="Readonly"}function ka(e){return P(e)&&e[J]==="Optional"}function no(e){return I(e,"Any")&&O(e.$id)}function oo(e){return I(e,"Argument")&&ue(e.index)}function so(e){return I(e,"Array")&&e.type==="array"&&O(e.$id)&&z(e.items)&&k(e.minItems)&&k(e.maxItems)&&mn(e.uniqueItems)&&ro(e.contains)&&k(e.minContains)&&k(e.maxContains)}function io(e){return I(e,"AsyncIterator")&&e.type==="AsyncIterator"&&O(e.$id)&&z(e.items)}function ao(e){return I(e,"BigInt")&&e.type==="bigint"&&O(e.$id)&&jt(e.exclusiveMaximum)&&jt(e.exclusiveMinimum)&&jt(e.maximum)&&jt(e.minimum)&&jt(e.multipleOf)}function uo(e){return I(e,"Boolean")&&e.type==="boolean"&&O(e.$id)}function mo(e){return I(e,"Computed")&&M(e.target)&&K(e.parameters)&&e.parameters.every(t=>z(t))}function co(e){return I(e,"Constructor")&&e.type==="Constructor"&&O(e.$id)&&K(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function po(e){return I(e,"Date")&&e.type==="Date"&&O(e.$id)&&k(e.exclusiveMaximumTimestamp)&&k(e.exclusiveMinimumTimestamp)&&k(e.maximumTimestamp)&&k(e.minimumTimestamp)&&k(e.multipleOfTimestamp)}function lo(e){return I(e,"Function")&&e.type==="Function"&&O(e.$id)&&K(e.parameters)&&e.parameters.every(t=>z(t))&&z(e.returns)}function Ea(e){return I(e,"Import")&&nr(e,"$defs")&&P(e.$defs)&&ar(e.$defs)&&nr(e,"$ref")&&M(e.$ref)&&e.$ref in e.$defs}function fo(e){return I(e,"Integer")&&e.type==="integer"&&O(e.$id)&&k(e.exclusiveMaximum)&&k(e.exclusiveMinimum)&&k(e.maximum)&&k(e.minimum)&&k(e.multipleOf)}function ar(e){return P(e)&&Object.entries(e).every(([t,r])=>dn(t)&&z(r))}function go(e){return I(e,"Intersect")&&!(M(e.type)&&e.type!=="object")&&K(e.allOf)&&e.allOf.every(t=>z(t)&&!No(t))&&O(e.type)&&(mn(e.unevaluatedProperties)||ro(e.unevaluatedProperties))&&O(e.$id)}function Io(e){return I(e,"Iterator")&&e.type==="Iterator"&&O(e.$id)&&z(e.items)}function I(e,t){return P(e)&&c in e&&e[c]===t}function ho(e){return Dt(e)&&M(e.const)}function yo(e){return Dt(e)&&ue(e.const)}function Fa(e){return Dt(e)&&ve(e.const)}function Dt(e){return I(e,"Literal")&&O(e.$id)&&xo(e.const)}function xo(e){return ve(e)||ue(e)||M(e)}function So(e){return I(e,"MappedKey")&&K(e.keys)&&e.keys.every(t=>ue(t)||M(t))}function To(e){return I(e,"MappedResult")&&ar(e.properties)}function bo(e){return I(e,"Never")&&P(e.not)&&Object.getOwnPropertyNames(e.not).length===0}function Ao(e){return I(e,"Not")&&z(e.not)}function wo(e){return I(e,"Null")&&e.type==="null"&&O(e.$id)}function Po(e){return I(e,"Number")&&e.type==="number"&&O(e.$id)&&k(e.exclusiveMaximum)&&k(e.exclusiveMinimum)&&k(e.maximum)&&k(e.minimum)&&k(e.multipleOf)}function Oo(e){return I(e,"Object")&&e.type==="object"&&O(e.$id)&&ar(e.properties)&&to(e.additionalProperties)&&k(e.minProperties)&&k(e.maxProperties)}function Ro(e){return I(e,"Promise")&&e.type==="Promise"&&O(e.$id)&&z(e.item)}function Co(e){return I(e,"Record")&&e.type==="object"&&O(e.$id)&&to(e.additionalProperties)&&P(e.patternProperties)&&(t=>{let r=Object.getOwnPropertyNames(t.patternProperties);return r.length===1&&eo(r[0])&&P(t.patternProperties)&&z(t.patternProperties[r[0]])})(e)}function $a(e){return P(e)&&ge in e&&e[ge]==="Recursive"}function Mo(e){return I(e,"Ref")&&O(e.$id)&&M(e.$ref)}function ko(e){return I(e,"RegExp")&&O(e.$id)&&M(e.source)&&M(e.flags)&&k(e.maxLength)&&k(e.minLength)}function Eo(e){return I(e,"String")&&e.type==="string"&&O(e.$id)&&k(e.minLength)&&k(e.maxLength)&&Ra(e.pattern)&&Ca(e.format)}function Fo(e){return I(e,"Symbol")&&e.type==="symbol"&&O(e.$id)}function $o(e){return I(e,"TemplateLiteral")&&e.type==="string"&&M(e.pattern)&&e.pattern[0]==="^"&&e.pattern[e.pattern.length-1]==="$"}function Uo(e){return I(e,"This")&&O(e.$id)&&M(e.$ref)}function No(e){return P(e)&&G in e}function _o(e){return I(e,"Tuple")&&e.type==="array"&&O(e.$id)&&ue(e.minItems)&&ue(e.maxItems)&&e.minItems===e.maxItems&&(L(e.items)&&L(e.additionalItems)&&e.minItems===0||K(e.items)&&e.items.every(t=>z(t)))}function vo(e){return I(e,"Undefined")&&e.type==="undefined"&&O(e.$id)}function Ua(e){return cn(e)&&e.anyOf.every(t=>ho(t)||yo(t))}function cn(e){return I(e,"Union")&&O(e.$id)&&P(e)&&K(e.anyOf)&&e.anyOf.every(t=>z(t))}function Ko(e){return I(e,"Uint8Array")&&e.type==="Uint8Array"&&O(e.$id)&&k(e.minByteLength)&&k(e.maxByteLength)}function Lo(e){return I(e,"Unknown")&&O(e.$id)}function jo(e){return I(e,"Unsafe")}function Do(e){return I(e,"Void")&&e.type==="void"&&O(e.$id)}function Go(e){return P(e)&&c in e&&M(e[c])&&!Oa.includes(e[c])}function z(e){return P(e)&&(no(e)||oo(e)||so(e)||uo(e)||ao(e)||io(e)||mo(e)||co(e)||po(e)||lo(e)||fo(e)||go(e)||Io(e)||Dt(e)||So(e)||To(e)||bo(e)||Ao(e)||wo(e)||Po(e)||Oo(e)||Ro(e)||Co(e)||Mo(e)||ko(e)||Eo(e)||Fo(e)||$o(e)||Uo(e)||_o(e)||vo(e)||cn(e)||Ko(e)||Lo(e)||jo(e)||Do(e)||Go(e))}var pn="(true|false)",Gt="(0|[1-9][0-9]*)",ln="(.*)",Na="(?!.*)",ff=`^${pn}$`,He=`^${Gt}$`,We=`^${ln}$`,Vo=`^${Na}$`;function Bo(e,t){return e.includes(t)}function Ho(e){return[...new Set(e)]}function _a(e,t){return e.filter(r=>t.includes(r))}function va(e,t){return e.reduce((r,n)=>_a(r,n),t)}function Wo(e){return e.length===1?e[0]:e.length>1?va(e.slice(1),e[0]):[]}function qo(e){let t=[];for(let r of e)t.push(...r);return t}function qe(e){return u({[c]:"Any"},e)}function gt(e,t){return u({[c]:"Array",type:"array",items:e},t)}function zo(e){return u({[c]:"Argument",index:e})}function It(e,t){return u({[c]:"AsyncIterator",type:"AsyncIterator",items:e},t)}function E(e,t,r){return u({[c]:"Computed",target:e,parameters:t},r)}function Ka(e,t){let{[t]:r,...n}=e;return n}function N(e,t){return t.reduce((r,n)=>Ka(r,n),e)}function S(e){return u({[c]:"Never",not:{}},e)}function T(e){return u({[c]:"MappedResult",properties:e})}function ht(e,t,r){return u({[c]:"Constructor",type:"Constructor",parameters:e,returns:t},r)}function $e(e,t,r){return u({[c]:"Function",type:"Function",parameters:e,returns:t},r)}function Vt(e,t){return u({[c]:"Union",anyOf:e},t)}function La(e){return e.some(t=>re(t))}function Yo(e){return e.map(t=>re(t)?ja(t):t)}function ja(e){return N(e,[J])}function Da(e,t){return La(e)?Z(Vt(Yo(e),t)):Vt(Yo(e),t)}function Ue(e,t){return e.length===1?u(e[0],t):e.length===0?S(t):Da(e,t)}function w(e,t){return e.length===0?S(t):e.length===1?u(e[0],t):Vt(e,t)}var ur=class extends q{};function Ga(e){return e.replace(/\\\$/g,"$").replace(/\\\*/g,"*").replace(/\\\^/g,"^").replace(/\\\|/g,"|").replace(/\\\(/g,"(").replace(/\\\)/g,")")}function fn(e,t,r){return e[t]===r&&e.charCodeAt(t-1)!==92}function Ge(e,t){return fn(e,t,"(")}function Bt(e,t){return fn(e,t,")")}function Jo(e,t){return fn(e,t,"|")}function Va(e){if(!(Ge(e,0)&&Bt(e,e.length-1)))return!1;let t=0;for(let r=0;r<e.length;r++)if(Ge(e,r)&&(t+=1),Bt(e,r)&&(t-=1),t===0&&r!==e.length-1)return!1;return!0}function Ba(e){return e.slice(1,e.length-1)}function Ha(e){let t=0;for(let r=0;r<e.length;r++)if(Ge(e,r)&&(t+=1),Bt(e,r)&&(t-=1),Jo(e,r)&&t===0)return!0;return!1}function Wa(e){for(let t=0;t<e.length;t++)if(Ge(e,t))return!0;return!1}function qa(e){let[t,r]=[0,0],n=[];for(let s=0;s<e.length;s++)if(Ge(e,s)&&(t+=1),Bt(e,s)&&(t-=1),Jo(e,s)&&t===0){let i=e.slice(r,s);i.length>0&&n.push(yt(i)),r=s+1}let o=e.slice(r);return o.length>0&&n.push(yt(o)),n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"or",expr:n}}function za(e){function t(o,s){if(!Ge(o,s))throw new ur("TemplateLiteralParser: Index must point to open parens");let i=0;for(let m=s;m<o.length;m++)if(Ge(o,m)&&(i+=1),Bt(o,m)&&(i-=1),i===0)return[s,m];throw new ur("TemplateLiteralParser: Unclosed group parens in expression")}function r(o,s){for(let i=s;i<o.length;i++)if(Ge(o,i))return[s,i];return[s,o.length]}let n=[];for(let o=0;o<e.length;o++)if(Ge(e,o)){let[s,i]=t(e,o),m=e.slice(s,i+1);n.push(yt(m)),o=i}else{let[s,i]=r(e,o),m=e.slice(s,i);m.length>0&&n.push(yt(m)),o=i-1}return n.length===0?{type:"const",const:""}:n.length===1?n[0]:{type:"and",expr:n}}function yt(e){return Va(e)?yt(Ba(e)):Ha(e)?qa(e):Wa(e)?za(e):{type:"const",const:Ga(e)}}function xt(e){return yt(e.slice(1,e.length-1))}var gn=class extends q{};function Ya(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 Ja(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 Xa(e){return e.type==="const"&&e.const===".*"}function ut(e){return Ya(e)||Xa(e)?!1:Ja(e)?!0:e.type==="and"?e.expr.every(t=>ut(t)):e.type==="or"?e.expr.every(t=>ut(t)):e.type==="const"?!0:(()=>{throw new gn("Unknown expression type")})()}function Xo(e){let t=xt(e.pattern);return ut(t)}var In=class extends q{};function*Qo(e){if(e.length===1)return yield*e[0];for(let t of e[0])for(let r of Qo(e.slice(1)))yield`${t}${r}`}function*Qa(e){return yield*Qo(e.expr.map(t=>[...Ht(t)]))}function*Za(e){for(let t of e.expr)yield*Ht(t)}function*eu(e){return yield e.const}function*Ht(e){return e.type==="and"?yield*Qa(e):e.type==="or"?yield*Za(e):e.type==="const"?yield*eu(e):(()=>{throw new In("Unknown expression")})()}function dr(e){let t=xt(e.pattern);return ut(t)?[...Ht(t)]:[]}function b(e,t){return u({[c]:"Literal",const:e,type:typeof e},t)}function mr(e){return u({[c]:"Boolean",type:"boolean"},e)}function St(e){return u({[c]:"BigInt",type:"bigint"},e)}function Ie(e){return u({[c]:"Number",type:"number"},e)}function Ce(e){return u({[c]:"String",type:"string"},e)}function*tu(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield mr():t==="number"?yield Ie():t==="bigint"?yield St():t==="string"?yield Ce():yield(()=>{let r=t.split("|").map(n=>b(n.trim()));return r.length===0?S():r.length===1?r[0]:Ue(r)})()}function*ru(e){if(e[1]!=="{"){let t=b("$"),r=hn(e.slice(1));return yield*[t,...r]}for(let t=2;t<e.length;t++)if(e[t]==="}"){let r=tu(e.slice(2,t)),n=hn(e.slice(t+1));return yield*[...r,...n]}yield b(e)}function*hn(e){for(let t=0;t<e.length;t++)if(e[t]==="$"){let r=b(e.slice(0,t)),n=ru(e.slice(t));return yield*[r,...n]}yield b(e)}function Zo(e){return[...hn(e)]}var yn=class extends q{};function nu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function es(e,t){return ce(e)?e.pattern.slice(1,e.pattern.length-1):x(e)?`(${e.anyOf.map(r=>es(r,t)).join("|")})`:Re(e)?`${t}${Gt}`:Oe(e)?`${t}${Gt}`:ot(e)?`${t}${Gt}`:je(e)?`${t}${ln}`:de(e)?`${t}${nu(e.const.toString())}`:Le(e)?`${t}${pn}`:(()=>{throw new yn(`Unexpected Kind '${e[c]}'`)})()}function xn(e){return`^${e.map(t=>es(t,"")).join("")}$`}function dt(e){let r=dr(e).map(n=>b(n));return Ue(r)}function cr(e,t){let r=M(e)?xn(Zo(e)):xn(e);return u({[c]:"TemplateLiteral",type:"string",pattern:r},t)}function ou(e){return dr(e).map(r=>r.toString())}function su(e){let t=[];for(let r of e)t.push(...ne(r));return t}function iu(e){return[e.toString()]}function ne(e){return[...new Set(ce(e)?ou(e):x(e)?su(e.anyOf):de(e)?iu(e.const):Re(e)?["[number]"]:Oe(e)?["[number]"]:[])]}function au(e,t,r){let n={};for(let o of Object.getOwnPropertyNames(t))n[o]=ze(e,ne(t[o]),r);return n}function uu(e,t,r){return au(e,t.properties,r)}function ts(e,t,r){let n=uu(e,t,r);return T(n)}function ns(e,t){return e.map(r=>os(r,t))}function du(e){return e.filter(t=>!Ve(t))}function mu(e,t){return pr(du(ns(e,t)))}function cu(e){return e.some(t=>Ve(t))?[]:e}function pu(e,t){return Ue(cu(ns(e,t)))}function lu(e,t){return t in e?e[t]:t==="[number]"?Ue(e):S()}function fu(e,t){return t==="[number]"?e:S()}function gu(e,t){return t in e?e[t]:S()}function os(e,t){return U(e)?mu(e.allOf,t):x(e)?pu(e.anyOf,t):pe(e)?lu(e.items??[],t):be(e)?fu(e.items,t):j(e)?gu(e.properties,t):S()}function Sn(e,t){return t.map(r=>os(e,r))}function rs(e,t){return Ue(Sn(e,t))}function ze(e,t,r){if(v(e)||v(t)){let n="Index types using Ref parameters require both Type and Key to be of TSchema";if(!le(e)||!le(t))throw new q(n);return E("Index",[e,t])}return $(t)?ts(e,t,r):me(t)?ss(e,t,r):u(le(t)?rs(e,ne(t)):rs(e,t),r)}function Iu(e,t,r){return{[t]:ze(e,[t],F(r))}}function hu(e,t,r){return t.reduce((n,o)=>({...n,...Iu(e,o,r)}),{})}function yu(e,t,r){return hu(e,t.keys,r)}function ss(e,t,r){let n=yu(e,t,r);return T(n)}function Tt(e,t){return u({[c]:"Iterator",type:"Iterator",items:e},t)}function xu(e){return globalThis.Object.keys(e).filter(t=>!re(e[t]))}function Su(e,t){let r=xu(e),n=r.length>0?{[c]:"Object",type:"object",required:r,properties:e}:{[c]:"Object",type:"object",properties:e};return u(n,t)}var R=Su;function lr(e,t){return u({[c]:"Promise",type:"Promise",item:e},t)}function Tu(e){return u(N(e,[Te]))}function bu(e){return u({...e,[Te]:"Readonly"})}function Au(e,t){return t===!1?Tu(e):bu(e)}function oe(e,t){let r=t??!0;return $(e)?is(e,r):Au(e,r)}function wu(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=oe(e[n],t);return r}function Pu(e,t){return wu(e.properties,t)}function is(e,t){let r=Pu(e,t);return T(r)}function he(e,t){return u(e.length>0?{[c]:"Tuple",type:"array",items:e,additionalItems:!1,minItems:e.length,maxItems:e.length}:{[c]:"Tuple",type:"array",minItems:e.length,maxItems:e.length},t)}function as(e,t){return e in t?ye(e,t[e]):T(t)}function Ou(e){return{[e]:b(e)}}function Ru(e){let t={};for(let r of e)t[r]=b(r);return t}function Cu(e,t){return Bo(t,e)?Ou(e):Ru(t)}function Mu(e,t){let r=Cu(e,t);return as(e,r)}function Wt(e,t){return t.map(r=>ye(e,r))}function ku(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(t))r[n]=ye(e,t[n]);return r}function ye(e,t){let r={...t};return re(t)?Z(ye(e,N(t,[J]))):ft(t)?oe(ye(e,N(t,[Te]))):$(t)?as(e,t.properties):me(t)?Mu(e,t.keys):we(t)?ht(Wt(e,t.parameters),ye(e,t.returns),r):Pe(t)?$e(Wt(e,t.parameters),ye(e,t.returns),r):nt(t)?It(ye(e,t.items),r):st(t)?Tt(ye(e,t.items),r):U(t)?ee(Wt(e,t.allOf),r):x(t)?w(Wt(e,t.anyOf),r):pe(t)?he(Wt(e,t.items??[]),r):j(t)?R(ku(e,t.properties),r):be(t)?gt(ye(e,t.items),r):it(t)?lr(ye(e,t.item),r):t}function Eu(e,t){let r={};for(let n of e)r[n]=ye(n,t);return r}function us(e,t,r){let n=le(e)?ne(e):e,o=t({[c]:"MappedKey",keys:n}),s=Eu(n,o);return R(s,r)}function Fu(e){return u(N(e,[J]))}function $u(e){return u({...e,[J]:"Optional"})}function Uu(e,t){return t===!1?Fu(e):$u(e)}function Z(e,t){let r=t??!0;return $(e)?ds(e,r):Uu(e,r)}function Nu(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Z(e[n],t);return r}function _u(e,t){return Nu(e.properties,t)}function ds(e,t){let r=_u(e,t);return T(r)}function qt(e,t={}){let r=e.every(o=>j(o)),n=le(t.unevaluatedProperties)?{unevaluatedProperties:t.unevaluatedProperties}:{};return u(t.unevaluatedProperties===!1||le(t.unevaluatedProperties)||r?{...n,[c]:"Intersect",type:"object",allOf:e}:{...n,[c]:"Intersect",allOf:e},t)}function vu(e){return e.every(t=>re(t))}function Ku(e){return N(e,[J])}function ms(e){return e.map(t=>re(t)?Ku(t):t)}function Lu(e,t){return vu(e)?Z(qt(ms(e),t)):qt(ms(e),t)}function pr(e,t={}){if(e.length===1)return u(e[0],t);if(e.length===0)return S(t);if(e.some(r=>Be(r)))throw new Error("Cannot intersect transform types");return Lu(e,t)}function ee(e,t){if(e.length===1)return u(e[0],t);if(e.length===0)return S(t);if(e.some(r=>Be(r)))throw new Error("Cannot intersect transform types");return qt(e,t)}function Ne(...e){let[t,r]=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({[c]:"Ref",$ref:t},r)}function ju(e,t){return E("Awaited",[E(e,t)])}function Du(e){return E("Awaited",[Ne(e)])}function Gu(e){return ee(cs(e))}function Vu(e){return w(cs(e))}function Bu(e){return bt(e)}function cs(e){return e.map(t=>bt(t))}function bt(e,t){return u(Ae(e)?ju(e.target,e.parameters):U(e)?Gu(e.allOf):x(e)?Vu(e.anyOf):it(e)?Bu(e.item):v(e)?Du(e.$ref):e,t)}function ps(e){let t=[];for(let r of e)t.push(zt(r));return t}function Hu(e){let t=ps(e);return qo(t)}function Wu(e){let t=ps(e);return Wo(t)}function qu(e){return e.map((t,r)=>r.toString())}function zu(e){return["[number]"]}function Yu(e){return globalThis.Object.getOwnPropertyNames(e)}function Ju(e){return Xu?globalThis.Object.getOwnPropertyNames(e).map(r=>r[0]==="^"&&r[r.length-1]==="$"?r.slice(1,r.length-1):r):[]}function zt(e){return U(e)?Hu(e.allOf):x(e)?Wu(e.anyOf):pe(e)?qu(e.items??[]):be(e)?zu(e.items):j(e)?Yu(e.properties):at(e)?Ju(e.patternProperties):[]}var Xu=!1;function Qu(e,t){return E("KeyOf",[E(e,t)])}function Zu(e){return E("KeyOf",[Ne(e)])}function ed(e,t){let r=zt(e),n=td(r),o=Ue(n);return u(o,t)}function td(e){return e.map(t=>t==="[number]"?Ie():b(t))}function At(e,t){return Ae(e)?Qu(e.target,e.parameters):v(e)?Zu(e.$ref):$(e)?ls(e,t):ed(e,t)}function rd(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=At(e[n],F(t));return r}function nd(e,t){return rd(e.properties,t)}function ls(e,t){let r=nd(e,t);return T(r)}function od(e){let t=[];for(let r of e)t.push(...zt(r));return Ho(t)}function sd(e){return e.filter(t=>!Ve(t))}function id(e,t){let r=[];for(let n of e)r.push(...Sn(n,[t]));return sd(r)}function ad(e,t){let r={};for(let n of t)r[n]=pr(id(e,n));return r}function fs(e,t){let r=od(e),n=ad(e,r);return R(n,t)}function fr(e){return u({[c]:"Date",type:"Date"},e)}function gr(e){return u({[c]:"Null",type:"null"},e)}function Ir(e){return u({[c]:"Symbol",type:"symbol"},e)}function hr(e){return u({[c]:"Undefined",type:"undefined"},e)}function yr(e){return u({[c]:"Uint8Array",type:"Uint8Array"},e)}function Ye(e){return u({[c]:"Unknown"},e)}function ud(e){return e.map(t=>Tn(t,!1))}function dd(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=oe(Tn(e[r],!1));return t}function xr(e,t){return t===!0?e:oe(e)}function Tn(e,t){return Zr(e)?xr(qe(),t):tn(e)?xr(qe(),t):K(e)?oe(he(ud(e))):Ke(e)?yr():rt(e)?fr():P(e)?xr(R(dd(e)),t):en(e)?xr($e([],Ye()),t):L(e)?hr():rn(e)?gr():nn(e)?Ir():Ut(e)?St():ue(e)?b(e):ve(e)?b(e):M(e)?b(e):R({})}function gs(e,t){return u(Tn(e,!0),t)}function Is(e,t){return we(e)?he(e.parameters,t):S(t)}function hs(e,t){if(L(e))throw new Error("Enum undefined or empty");let r=globalThis.Object.getOwnPropertyNames(e).filter(s=>isNaN(s)).map(s=>e[s]),o=[...new Set(r)].map(s=>b(s));return w(o,{...t,[ge]:"Enum"})}var An=class extends q{},d;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(d||(d={}));function xe(e){return e===d.False?e:d.True}function wt(e){throw new An(e)}function V(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)?ws(e,t):a.IsIntersect(t)?Sr(e,t):a.IsUnion(t)?Rn(e,t):a.IsUnknown(t)?Cs(e,t):a.IsAny(t)?On(e,t):wt("StructuralRight")}function On(e,t){return d.True}function md(e,t){return a.IsIntersect(t)?Sr(e,t):a.IsUnion(t)&&t.anyOf.some(r=>a.IsAny(r)||a.IsUnknown(r))?d.True:a.IsUnion(t)?d.Union:a.IsUnknown(t)||a.IsAny(t)?d.True:d.Union}function cd(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)?d.True:d.False}function pd(e,t){return a.IsObject(t)&&Tr(t)?d.True:V(t)?B(e,t):a.IsArray(t)?xe(C(e.items,t.items)):d.False}function ld(e,t){return V(t)?B(e,t):a.IsAsyncIterator(t)?xe(C(e.items,t.items)):d.False}function fd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsBigInt(t)?d.True:d.False}function bs(e,t){return a.IsLiteralBoolean(e)||a.IsBoolean(e)?d.True:d.False}function gd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsBoolean(t)?d.True:d.False}function Id(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsConstructor(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((r,n)=>xe(C(t.parameters[n],r))===d.True)?xe(C(e.returns,t.returns)):d.False:d.False}function hd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsDate(t)?d.True:d.False}function yd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsFunction(t)?e.parameters.length>t.parameters.length?d.False:e.parameters.every((r,n)=>xe(C(t.parameters[n],r))===d.True)?xe(C(e.returns,t.returns)):d.False:d.False}function As(e,t){return a.IsLiteral(e)&&Q.IsNumber(e.const)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function xd(e,t){return a.IsInteger(t)||a.IsNumber(t)?d.True:V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):d.False}function Sr(e,t){return t.allOf.every(r=>C(e,r)===d.True)?d.True:d.False}function Sd(e,t){return e.allOf.some(r=>C(r,t)===d.True)?d.True:d.False}function Td(e,t){return V(t)?B(e,t):a.IsIterator(t)?xe(C(e.items,t.items)):d.False}function bd(e,t){return a.IsLiteral(t)&&t.const===e.const?d.True:V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsString(t)?Rs(e,t):a.IsNumber(t)?Ps(e,t):a.IsInteger(t)?As(e,t):a.IsBoolean(t)?bs(e,t):d.False}function ws(e,t){return d.False}function Ad(e,t){return d.True}function ys(e){let[t,r]=[e,0];for(;a.IsNot(t);)t=t.not,r+=1;return r%2===0?t:Ye()}function wd(e,t){return a.IsNot(e)?C(ys(e),t):a.IsNot(t)?C(e,ys(t)):wt("Invalid fallthrough for Not")}function Pd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsNull(t)?d.True:d.False}function Ps(e,t){return a.IsLiteralNumber(e)||a.IsNumber(e)||a.IsInteger(e)?d.True:d.False}function Od(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsInteger(t)||a.IsNumber(t)?d.True:d.False}function se(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function xs(e){return Tr(e)}function Ss(e){return se(e,0)||se(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 bn(e){return se(e,0)}function Ts(e){return se(e,0)}function Rd(e){return se(e,0)}function Cd(e){return se(e,0)}function Md(e){return Tr(e)}function kd(e){let t=Ie();return se(e,0)||se(e,1)&&"length"in e.properties&&xe(C(e.properties.length,t))===d.True}function Ed(e){return se(e,0)}function Tr(e){let t=Ie();return se(e,0)||se(e,1)&&"length"in e.properties&&xe(C(e.properties.length,t))===d.True}function Fd(e){let t=$e([qe()],qe());return se(e,0)||se(e,1)&&"then"in e.properties&&xe(C(e.properties.then,t))===d.True}function Os(e,t){return C(e,t)===d.False||a.IsOptional(e)&&!a.IsOptional(t)?d.False:d.True}function te(e,t){return a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:a.IsNever(e)||a.IsLiteralString(e)&&xs(t)||a.IsLiteralNumber(e)&&bn(t)||a.IsLiteralBoolean(e)&&Ts(t)||a.IsSymbol(e)&&Ss(t)||a.IsBigInt(e)&&Rd(t)||a.IsString(e)&&xs(t)||a.IsSymbol(e)&&Ss(t)||a.IsNumber(e)&&bn(t)||a.IsInteger(e)&&bn(t)||a.IsBoolean(e)&&Ts(t)||a.IsUint8Array(e)&&Md(t)||a.IsDate(e)&&Cd(t)||a.IsConstructor(e)&&Ed(t)||a.IsFunction(e)&&kd(t)?d.True:a.IsRecord(e)&&a.IsString(wn(e))?t[ge]==="Record"?d.True:d.False:a.IsRecord(e)&&a.IsNumber(wn(e))&&se(t,0)?d.True:d.False}function $d(e,t){return V(t)?B(e,t):a.IsRecord(t)?Se(e,t):a.IsObject(t)?(()=>{for(let r of Object.getOwnPropertyNames(t.properties)){if(!(r in e.properties)&&!a.IsOptional(t.properties[r]))return d.False;if(a.IsOptional(t.properties[r]))return d.True;if(Os(e.properties[r],t.properties[r])===d.False)return d.False}return d.True})():d.False}function Ud(e,t){return V(t)?B(e,t):a.IsObject(t)&&Fd(t)?d.True:a.IsPromise(t)?xe(C(e.item,t.item)):d.False}function wn(e){return He in e.patternProperties?Ie():We in e.patternProperties?Ce():wt("Unknown record key pattern")}function Pn(e){return He in e.patternProperties?e.patternProperties[He]:We in e.patternProperties?e.patternProperties[We]:wt("Unable to get record value schema")}function Se(e,t){let[r,n]=[wn(t),Pn(t)];return a.IsLiteralString(e)&&a.IsNumber(r)&&xe(C(e,n))===d.True?d.True:a.IsUint8Array(e)&&a.IsNumber(r)||a.IsString(e)&&a.IsNumber(r)||a.IsArray(e)&&a.IsNumber(r)?C(e,n):a.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(Os(n,e.properties[o])===d.False)return d.False;return d.True})():d.False}function Nd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?C(Pn(e),Pn(t)):d.False}function _d(e,t){let r=a.IsRegExp(e)?Ce():e,n=a.IsRegExp(t)?Ce():t;return C(r,n)}function Rs(e,t){return a.IsLiteral(e)&&Q.IsString(e.const)||a.IsString(e)?d.True:d.False}function vd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsString(t)?d.True:d.False}function Kd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsSymbol(t)?d.True:d.False}function Ld(e,t){return a.IsTemplateLiteral(e)?C(dt(e),t):a.IsTemplateLiteral(t)?C(e,dt(t)):wt("Invalid fallthrough for TemplateLiteral")}function jd(e,t){return a.IsArray(t)&&e.items!==void 0&&e.items.every(r=>C(r,t.items)===d.True)}function Dd(e,t){return a.IsNever(e)?d.True:a.IsUnknown(e)?d.False:a.IsAny(e)?d.Union:d.False}function Gd(e,t){return V(t)?B(e,t):a.IsObject(t)&&Tr(t)||a.IsArray(t)&&jd(e,t)?d.True:a.IsTuple(t)?Q.IsUndefined(e.items)&&!Q.IsUndefined(t.items)||!Q.IsUndefined(e.items)&&Q.IsUndefined(t.items)?d.False:Q.IsUndefined(e.items)&&!Q.IsUndefined(t.items)||e.items.every((r,n)=>C(r,t.items[n])===d.True)?d.True:d.False:d.False}function Vd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsUint8Array(t)?d.True:d.False}function Bd(e,t){return V(t)?B(e,t):a.IsObject(t)?te(e,t):a.IsRecord(t)?Se(e,t):a.IsVoid(t)?qd(e,t):a.IsUndefined(t)?d.True:d.False}function Rn(e,t){return t.anyOf.some(r=>C(e,r)===d.True)?d.True:d.False}function Hd(e,t){return e.anyOf.every(r=>C(r,t)===d.True)?d.True:d.False}function Cs(e,t){return d.True}function Wd(e,t){return a.IsNever(t)?ws(e,t):a.IsIntersect(t)?Sr(e,t):a.IsUnion(t)?Rn(e,t):a.IsAny(t)?On(e,t):a.IsString(t)?Rs(e,t):a.IsNumber(t)?Ps(e,t):a.IsInteger(t)?As(e,t):a.IsBoolean(t)?bs(e,t):a.IsArray(t)?cd(e,t):a.IsTuple(t)?Dd(e,t):a.IsObject(t)?te(e,t):a.IsUnknown(t)?d.True:d.False}function qd(e,t){return a.IsUndefined(e)||a.IsUndefined(e)?d.True:d.False}function zd(e,t){return a.IsIntersect(t)?Sr(e,t):a.IsUnion(t)?Rn(e,t):a.IsUnknown(t)?Cs(e,t):a.IsAny(t)?On(e,t):a.IsObject(t)?te(e,t):a.IsVoid(t)?d.True:d.False}function C(e,t){return a.IsTemplateLiteral(e)||a.IsTemplateLiteral(t)?Ld(e,t):a.IsRegExp(e)||a.IsRegExp(t)?_d(e,t):a.IsNot(e)||a.IsNot(t)?wd(e,t):a.IsAny(e)?md(e,t):a.IsArray(e)?pd(e,t):a.IsBigInt(e)?fd(e,t):a.IsBoolean(e)?gd(e,t):a.IsAsyncIterator(e)?ld(e,t):a.IsConstructor(e)?Id(e,t):a.IsDate(e)?hd(e,t):a.IsFunction(e)?yd(e,t):a.IsInteger(e)?xd(e,t):a.IsIntersect(e)?Sd(e,t):a.IsIterator(e)?Td(e,t):a.IsLiteral(e)?bd(e,t):a.IsNever(e)?Ad(e,t):a.IsNull(e)?Pd(e,t):a.IsNumber(e)?Od(e,t):a.IsObject(e)?$d(e,t):a.IsRecord(e)?Nd(e,t):a.IsString(e)?vd(e,t):a.IsSymbol(e)?Kd(e,t):a.IsTuple(e)?Gd(e,t):a.IsPromise(e)?Ud(e,t):a.IsUint8Array(e)?Vd(e,t):a.IsUndefined(e)?Bd(e,t):a.IsUnion(e)?Hd(e,t):a.IsUnknown(e)?Wd(e,t):a.IsVoid(e)?zd(e,t):wt(`Unknown left type operand '${e[c]}'`)}function Je(e,t){return C(e,t)}function Yd(e,t,r,n,o){let s={};for(let i of globalThis.Object.getOwnPropertyNames(e))s[i]=Pt(e[i],t,r,n,F(o));return s}function Jd(e,t,r,n,o){return Yd(e.properties,t,r,n,o)}function Ms(e,t,r,n,o){let s=Jd(e,t,r,n,o);return T(s)}function Xd(e,t,r,n){let o=Je(e,t);return o===d.Union?w([r,n]):o===d.True?r:n}function Pt(e,t,r,n,o){return $(e)?Ms(e,t,r,n,o):me(e)?u(ks(e,t,r,n,o)):u(Xd(e,t,r,n),o)}function Qd(e,t,r,n,o){return{[e]:Pt(b(e),t,r,n,F(o))}}function Zd(e,t,r,n,o){return e.reduce((s,i)=>({...s,...Qd(i,t,r,n,o)}),{})}function em(e,t,r,n,o){return Zd(e.keys,t,r,n,o)}function ks(e,t,r,n,o){let s=em(e,t,r,n,o);return T(s)}function Es(e,t){return Ot(dt(e),t)}function tm(e,t){let r=e.filter(n=>Je(n,t)===d.False);return r.length===1?r[0]:w(r)}function Ot(e,t,r={}){return ce(e)?u(Es(e,t),r):$(e)?u(Fs(e,t),r):u(x(e)?tm(e.anyOf,t):Je(e,t)!==d.False?S():e,r)}function rm(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Ot(e[n],t);return r}function nm(e,t){return rm(e.properties,t)}function Fs(e,t){let r=nm(e,t);return T(r)}function $s(e,t){return Rt(dt(e),t)}function om(e,t){let r=e.filter(n=>Je(n,t)!==d.False);return r.length===1?r[0]:w(r)}function Rt(e,t,r){return ce(e)?u($s(e,t),r):$(e)?u(Us(e,t),r):u(x(e)?om(e.anyOf,t):Je(e,t)!==d.False?e:S(),r)}function sm(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Rt(e[n],t);return r}function im(e,t){return sm(e.properties,t)}function Us(e,t){let r=im(e,t);return T(r)}function Ns(e,t){return we(e)?u(e.returns,t):S(t)}function br(e){return oe(Z(e))}function mt(e,t,r){return u({[c]:"Record",type:"object",patternProperties:{[e]:t}},r)}function Cn(e,t,r){let n={};for(let o of e)n[o]=t;return R(n,{...r,[ge]:"Record"})}function am(e,t,r){return Xo(e)?Cn(ne(e),t,r):mt(e.pattern,t,r)}function um(e,t,r){return Cn(ne(w(e)),t,r)}function dm(e,t,r){return Cn([e.toString()],t,r)}function mm(e,t,r){return mt(e.source,t,r)}function cm(e,t,r){let n=L(e.pattern)?We:e.pattern;return mt(n,t,r)}function pm(e,t,r){return mt(We,t,r)}function lm(e,t,r){return mt(Vo,t,r)}function fm(e,t,r){return R({true:t,false:t},r)}function gm(e,t,r){return mt(He,t,r)}function Im(e,t,r){return mt(He,t,r)}function Ar(e,t,r={}){return x(e)?um(e.anyOf,t,r):ce(e)?am(e,t,r):de(e)?dm(e.const,t,r):Le(e)?fm(e,t,r):Oe(e)?gm(e,t,r):Re(e)?Im(e,t,r):an(e)?mm(e,t,r):je(e)?cm(e,t,r):on(e)?pm(e,t,r):Ve(e)?lm(e,t,r):S(r)}function wr(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function _s(e){let t=wr(e);return t===We?Ce():t===He?Ie():Ce({pattern:t})}function Pr(e){return e.patternProperties[wr(e)]}function hm(e,t){return t.parameters=Yt(e,t.parameters),t.returns=Me(e,t.returns),t}function ym(e,t){return t.parameters=Yt(e,t.parameters),t.returns=Me(e,t.returns),t}function xm(e,t){return t.allOf=Yt(e,t.allOf),t}function Sm(e,t){return t.anyOf=Yt(e,t.anyOf),t}function Tm(e,t){return L(t.items)||(t.items=Yt(e,t.items)),t}function bm(e,t){return t.items=Me(e,t.items),t}function Am(e,t){return t.items=Me(e,t.items),t}function wm(e,t){return t.items=Me(e,t.items),t}function Pm(e,t){return t.item=Me(e,t.item),t}function Om(e,t){let r=km(e,t.properties);return{...t,...R(r)}}function Rm(e,t){let r=Me(e,_s(t)),n=Me(e,Pr(t)),o=Ar(r,n);return{...t,...o}}function Cm(e,t){return t.index in e?e[t.index]:Ye()}function Mm(e,t){let r=ft(t),n=re(t),o=Me(e,t);return r&&n?br(o):r&&!n?oe(o):!r&&n?Z(o):o}function km(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:Mm(e,t[n])}),{})}function Yt(e,t){return t.map(r=>Me(e,r))}function Me(e,t){return we(t)?hm(e,t):Pe(t)?ym(e,t):U(t)?xm(e,t):x(t)?Sm(e,t):pe(t)?Tm(e,t):be(t)?bm(e,t):nt(t)?Am(e,t):st(t)?wm(e,t):it(t)?Pm(e,t):j(t)?Om(e,t):at(t)?Rm(e,t):sn(t)?Cm(e,t):t}function vs(e,t){return Me(t,lt(e))}function Ks(e){return u({[c]:"Integer",type:"integer"},e)}function Em(e,t,r){return{[e]:ke(b(e),t,F(r))}}function Fm(e,t,r){return e.reduce((o,s)=>({...o,...Em(s,t,r)}),{})}function $m(e,t,r){return Fm(e.keys,t,r)}function Ls(e,t,r){let n=$m(e,t,r);return T(n)}function Um(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),r].join("")}function Nm(e){let[t,r]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),r].join("")}function _m(e){return e.toUpperCase()}function vm(e){return e.toLowerCase()}function Km(e,t,r){let n=xt(e.pattern);if(!ut(n))return{...e,pattern:js(e.pattern,t)};let i=[...Ht(n)].map(f=>b(f)),m=Ds(i,t),p=w(m);return cr([p],r)}function js(e,t){return typeof e=="string"?t==="Uncapitalize"?Um(e):t==="Capitalize"?Nm(e):t==="Uppercase"?_m(e):t==="Lowercase"?vm(e):e:e.toString()}function Ds(e,t){return e.map(r=>ke(r,t))}function ke(e,t,r={}){return me(e)?Ls(e,t,r):ce(e)?Km(e,t,r):x(e)?w(Ds(e.anyOf,t),r):de(e)?b(js(e.const,t),r):u(e,r)}function Gs(e,t={}){return ke(e,"Capitalize",t)}function Vs(e,t={}){return ke(e,"Lowercase",t)}function Bs(e,t={}){return ke(e,"Uncapitalize",t)}function Hs(e,t={}){return ke(e,"Uppercase",t)}function Lm(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=Xe(e[o],t,F(r));return n}function jm(e,t,r){return Lm(e.properties,t,r)}function Ws(e,t,r){let n=jm(e,t,r);return T(n)}function Dm(e,t){return e.map(r=>Mn(r,t))}function Gm(e,t){return e.map(r=>Mn(r,t))}function Vm(e,t){let{[t]:r,...n}=e;return n}function Bm(e,t){return t.reduce((r,n)=>Vm(r,n),e)}function Hm(e,t,r){let n=N(e,[G,"$id","required","properties"]),o=Bm(r,t);return R(o,n)}function Wm(e){let t=e.reduce((r,n)=>ir(n)?[...r,b(n)]:r,[]);return w(t)}function Mn(e,t){return U(e)?ee(Dm(e.allOf,t)):x(e)?w(Gm(e.anyOf,t)):j(e)?Hm(e,t,e.properties):R({})}function Xe(e,t,r){let n=K(t)?Wm(t):t,o=le(t)?ne(t):t,s=v(e),i=v(t);return $(e)?Ws(e,o,r):me(t)?qs(e,t,r):s&&i?E("Omit",[e,n],r):!s&&i?E("Omit",[e,n],r):s&&!i?E("Omit",[e,n],r):u({...Mn(e,o),...r})}function qm(e,t,r){return{[t]:Xe(e,[t],F(r))}}function zm(e,t,r){return t.reduce((n,o)=>({...n,...qm(e,o,r)}),{})}function Ym(e,t,r){return zm(e,t.keys,r)}function qs(e,t,r){let n=Ym(e,t,r);return T(n)}function Jm(e,t,r){let n={};for(let o of globalThis.Object.getOwnPropertyNames(e))n[o]=Qe(e[o],t,F(r));return n}function Xm(e,t,r){return Jm(e.properties,t,r)}function zs(e,t,r){let n=Xm(e,t,r);return T(n)}function Qm(e,t){return e.map(r=>kn(r,t))}function Zm(e,t){return e.map(r=>kn(r,t))}function ec(e,t){let r={};for(let n of t)n in e&&(r[n]=e[n]);return r}function tc(e,t,r){let n=N(e,[G,"$id","required","properties"]),o=ec(r,t);return R(o,n)}function rc(e){let t=e.reduce((r,n)=>ir(n)?[...r,b(n)]:r,[]);return w(t)}function kn(e,t){return U(e)?ee(Qm(e.allOf,t)):x(e)?w(Zm(e.anyOf,t)):j(e)?tc(e,t,e.properties):R({})}function Qe(e,t,r){let n=K(t)?rc(t):t,o=le(t)?ne(t):t,s=v(e),i=v(t);return $(e)?zs(e,o,r):me(t)?Ys(e,t,r):s&&i?E("Pick",[e,n],r):!s&&i?E("Pick",[e,n],r):s&&!i?E("Pick",[e,n],r):u({...kn(e,o),...r})}function nc(e,t,r){return{[t]:Qe(e,[t],F(r))}}function oc(e,t,r){return t.reduce((n,o)=>({...n,...nc(e,o,r)}),{})}function sc(e,t,r){return oc(e,t.keys,r)}function Ys(e,t,r){let n=sc(e,t,r);return T(n)}function ic(e,t){return E("Partial",[E(e,t)])}function ac(e){return E("Partial",[Ne(e)])}function uc(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=Z(e[r]);return t}function dc(e,t){let r=N(e,[G,"$id","required","properties"]),n=uc(t);return R(n,r)}function Js(e){return e.map(t=>Xs(t))}function Xs(e){return Ae(e)?ic(e.target,e.parameters):v(e)?ac(e.$ref):U(e)?ee(Js(e.allOf)):x(e)?w(Js(e.anyOf)):j(e)?dc(e,e.properties):ot(e)||Le(e)||Oe(e)||de(e)||vt(e)||Re(e)||je(e)||Kt(e)||Lt(e)?e:R({})}function Ct(e,t){return $(e)?Qs(e,t):u({...Xs(e),...t})}function mc(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Ct(e[n],F(t));return r}function cc(e,t){return mc(e.properties,t)}function Qs(e,t){let r=cc(e,t);return T(r)}function pc(e,t){return E("Required",[E(e,t)])}function lc(e){return E("Required",[Ne(e)])}function fc(e){let t={};for(let r of globalThis.Object.getOwnPropertyNames(e))t[r]=N(e[r],[J]);return t}function gc(e,t){let r=N(e,[G,"$id","required","properties"]),n=fc(t);return R(n,r)}function Zs(e){return e.map(t=>ei(t))}function ei(e){return Ae(e)?pc(e.target,e.parameters):v(e)?lc(e.$ref):U(e)?ee(Zs(e.allOf)):x(e)?w(Zs(e.anyOf)):j(e)?gc(e,e.properties):ot(e)||Le(e)||Oe(e)||de(e)||vt(e)||Re(e)||je(e)||Kt(e)||Lt(e)?e:R({})}function Mt(e,t){return $(e)?ti(e,t):u({...ei(e),...t})}function Ic(e,t){let r={};for(let n of globalThis.Object.getOwnPropertyNames(e))r[n]=Mt(e[n],t);return r}function hc(e,t){return Ic(e.properties,t)}function ti(e,t){let r=hc(e,t);return T(r)}function yc(e,t){return t.map(r=>v(r)?En(e,r.$ref):fe(e,r))}function En(e,t){return t in e?v(e[t])?En(e,e[t].$ref):fe(e,e[t]):S()}function xc(e){return bt(e[0])}function Sc(e){return ze(e[0],e[1])}function Tc(e){return At(e[0])}function bc(e){return Ct(e[0])}function Ac(e){return Xe(e[0],e[1])}function wc(e){return Qe(e[0],e[1])}function Pc(e){return Mt(e[0])}function Oc(e,t,r){let n=yc(e,r);return t==="Awaited"?xc(n):t==="Index"?Sc(n):t==="KeyOf"?Tc(n):t==="Partial"?bc(n):t==="Omit"?Ac(n):t==="Pick"?wc(n):t==="Required"?Pc(n):S()}function Rc(e,t){return gt(fe(e,t))}function Cc(e,t){return It(fe(e,t))}function Mc(e,t,r){return ht(Jt(e,t),fe(e,r))}function kc(e,t,r){return $e(Jt(e,t),fe(e,r))}function Ec(e,t){return ee(Jt(e,t))}function Fc(e,t){return Tt(fe(e,t))}function $c(e,t){return R(globalThis.Object.keys(t).reduce((r,n)=>({...r,[n]:fe(e,t[n])}),{}))}function Uc(e,t){let[r,n]=[fe(e,Pr(t)),wr(t)],o=lt(t);return o.patternProperties[n]=r,o}function Nc(e,t){return v(t)?{...En(e,t.$ref),[G]:t[G]}:t}function _c(e,t){return he(Jt(e,t))}function vc(e,t){return w(Jt(e,t))}function Jt(e,t){return t.map(r=>fe(e,r))}function fe(e,t){return re(t)?u(fe(e,N(t,[J])),t):ft(t)?u(fe(e,N(t,[Te])),t):Be(t)?u(Nc(e,t),t):be(t)?u(Rc(e,t.items),t):nt(t)?u(Cc(e,t.items),t):Ae(t)?u(Oc(e,t.target,t.parameters)):we(t)?u(Mc(e,t.parameters,t.returns),t):Pe(t)?u(kc(e,t.parameters,t.returns),t):U(t)?u(Ec(e,t.allOf),t):st(t)?u(Fc(e,t.items),t):j(t)?u($c(e,t.properties),t):at(t)?u(Uc(e,t)):pe(t)?u(_c(e,t.items||[]),t):x(t)?u(vc(e,t.anyOf),t):t}function Kc(e,t){return t in e?fe(e,e[t]):S()}function ri(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,r)=>({...t,[r]:Kc(e,r)}),{})}var Fn=class{constructor(t){let r=ri(t),n=this.WithIdentifiers(r);this.$defs=n}Import(t,r){let n={...this.$defs,[t]:u(this.$defs[t],r)};return u({[c]:"Import",$defs:n,$ref:t})}WithIdentifiers(t){return globalThis.Object.getOwnPropertyNames(t).reduce((r,n)=>({...r,[n]:{...t[n],$id:n}}),{})}};function ni(e){return new Fn(e)}function oi(e,t){return u({[c]:"Not",not:e},t)}function si(e,t){return Pe(e)?he(e.parameters,t):S()}var Lc=0;function ii(e,t={}){L(t.$id)&&(t.$id=`T${Lc++}`);let r=lt(e({[c]:"This",$ref:`${t.$id}`}));return r.$id=t.$id,u({[ge]:"Recursive",...r},t)}function ai(e,t){let r=M(e)?new globalThis.RegExp(e):e;return u({[c]:"RegExp",type:"RegExp",source:r.source,flags:r.flags},t)}function jc(e){return U(e)?e.allOf:x(e)?e.anyOf:pe(e)?e.items??[]:[]}function ui(e){return jc(e)}function di(e,t){return Pe(e)?u(e.returns,t):S(t)}var $n=class{constructor(t){this.schema=t}Decode(t){return new Un(this.schema,t)}},Un=class{constructor(t,r){this.schema=t,this.decode=r}EncodeTransform(t,r){let s={Encode:i=>r[G].Encode(t(i)),Decode:i=>this.decode(r[G].Decode(i))};return{...r,[G]:s}}EncodeSchema(t,r){let n={Decode:this.decode,Encode:t};return{...r,[G]:n}}Encode(t){return Be(this.schema)?this.EncodeTransform(t,this.schema):this.EncodeSchema(t,this.schema)}};function mi(e){return new $n(e)}function ci(e={}){return u({[c]:e[c]??"Unsafe"},e)}function pi(e){return u({[c]:"Void",type:"void"},e)}var Nn={};Qr(Nn,{Any:()=>qe,Argument:()=>zo,Array:()=>gt,AsyncIterator:()=>It,Awaited:()=>bt,BigInt:()=>St,Boolean:()=>mr,Capitalize:()=>Gs,Composite:()=>fs,Const:()=>gs,Constructor:()=>ht,ConstructorParameters:()=>Is,Date:()=>fr,Enum:()=>hs,Exclude:()=>Ot,Extends:()=>Pt,Extract:()=>Rt,Function:()=>$e,Index:()=>ze,InstanceType:()=>Ns,Instantiate:()=>vs,Integer:()=>Ks,Intersect:()=>ee,Iterator:()=>Tt,KeyOf:()=>At,Literal:()=>b,Lowercase:()=>Vs,Mapped:()=>us,Module:()=>ni,Never:()=>S,Not:()=>oi,Null:()=>gr,Number:()=>Ie,Object:()=>R,Omit:()=>Xe,Optional:()=>Z,Parameters:()=>si,Partial:()=>Ct,Pick:()=>Qe,Promise:()=>lr,Readonly:()=>oe,ReadonlyOptional:()=>br,Record:()=>Ar,Recursive:()=>ii,Ref:()=>Ne,RegExp:()=>ai,Required:()=>Mt,Rest:()=>ui,ReturnType:()=>di,String:()=>Ce,Symbol:()=>Ir,TemplateLiteral:()=>cr,Transform:()=>mi,Tuple:()=>he,Uint8Array:()=>yr,Uncapitalize:()=>Bs,Undefined:()=>hr,Union:()=>w,Unknown:()=>Ye,Unsafe:()=>ci,Uppercase:()=>Hs,Void:()=>pi});var l=Nn;var g=null;function _n(e){g=e}import{readFileSync as Dc}from"fs";import{homedir as Gc}from"os";import{join as Vc}from"path";var Xt;function li(){if(Xt!==void 0)return Xt;try{let e=Dc(Vc(Gc(),".claude.json"),"utf-8");Xt=JSON.parse(e).mcpServers??{}}catch{Xt={}}return Xt}var h={maxSessions:20,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",codexApprovalPolicy:"on-request",planApproval:"delegate",reasoningEffort:"medium"};function fi(e){h={maxSessions:e.maxSessions??20,defaultModel:e.defaultModel,model:e.model,reasoningEffort:e.reasoningEffort??"medium",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:e.defaultHarness}}function gi(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=Qt(e.workspaceDir);if(t)return t}if(e.messageChannel&&e.messageChannel.includes("|"))return e.messageChannel}function kt(e,t){if(t&&String(t).includes("|"))return String(t);if(e?.channelId&&String(e.channelId).includes("|"))return String(e.channelId);if(e?.messageChannel){let r=String(e.messageChannel);if(r.includes("|"))return r;if(e.chatId)return`${r}|${e.chatId}`;if(e.senderId)return`${r}|${e.senderId}`}return e?.channel&&e?.chatId?`${e.channel}|${e.chatId}`:e?.channel&&e?.senderId?`${e.channel}|${e.senderId}`:e?.id&&/^-?\d+$/.test(String(e.id))?`telegram|${e.id}`:h.fallbackChannel??"unknown"}function Et(e){return e?.messageThreadId??void 0}function Qt(e){let t=h.agentChannels;if(!t)return;let r=s=>s.replace(/\/+$/,""),n=r(e),o=Object.entries(t).sort((s,i)=>i[0].length-s[0].length);for(let[s,i]of o)if(n===r(s)||n.startsWith(r(s)+"/"))return i}function Ii(e){if(!e)return;let t=e.match(/:topic:(\d+)$/);return t?parseInt(t[1],10):void 0}function Ft(e){let{requestedResumeSessionId:t,activeSession:r,persistedSession:n}=e;return t?r?{resumeSessionId:t,clearedPersistedCodexResume:!1}:n?.harness==="codex"?{resumeSessionId:void 0,clearedPersistedCodexResume:!0}:{resumeSessionId:t,clearedPersistedCodexResume:!1}:{resumeSessionId:void 0,clearedPersistedCodexResume:!1}}function Hc(e){return e instanceof Error?e.message:String(e)}function Wc(e){return!e||typeof e!="object"?!1:typeof e.prompt=="string"}function hi(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,r){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Wc(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};r.agentId&&console.warn(`[agent_launch] \u26A0\uFE0F agentId="${r.agentId}" was passed as a parameter \u2014 this is WRONG. agentId is only for sessions_spawn (OpenClaw sub-agents), not agent_launch (CC sessions). The field is being ignored. ctx.agentId="${e.agentId}" will be used for origin routing instead.`);let n=r.workdir||e.workspaceDir||h.defaultWorkdir||process.cwd();if(!Bc(n))return{content:[{type:"text",text:`Error: Working directory does not exist: ${n}`}]};try{let o=r.harness??h.defaultHarness,s=o==="codex"?h.model??h.defaultModel:h.defaultModel,i=r.resume_session_id,m=i?g.resolve(i):void 0,p=i?g.getPersistedSession(i):void 0;if(i){let Fe=g.resolveHarnessSessionId(i);if(!Fe)return{content:[{type:"text",text:`Error: Could not resolve resume_session_id "${i}" to a session ID. Use agent_sessions to list available sessions.`}]};i=Fe}let{resumeSessionId:f,clearedPersistedCodexResume:A}=Ft({requestedResumeSessionId:i,activeSession:m?{harnessSessionId:m.harnessSessionId}:void 0,persistedSession:p?{harness:p.harness}:void 0}),_=gi(e),ie=kt(e,_||Qt(n)),Y=e.sessionKey||void 0;!Y&&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 H=g.spawn({prompt:r.prompt,name:r.name,workdir:n,model:r.model??s,reasoningEffort:h.reasoningEffort,systemPrompt:r.system_prompt,allowedTools:r.allowed_tools,resumeSessionId:f,forkSession:f?r.fork_session:!1,multiTurn:!r.multi_turn_disabled,permissionMode:r.permission_mode,codexApprovalPolicy:o==="codex"?h.codexApprovalPolicy:void 0,originChannel:ie,originThreadId:Ii(Y)??Et(e),originAgentId:e.agentId||void 0,originSessionKey:Y,harness:o}),W=r.prompt.length>80?r.prompt.slice(0,80)+"...":r.prompt,X=["Session launched successfully.",` Name: ${H.name}`,` ID: ${H.id}`,` Dir: ${n}`,` Model: ${H.model??"default"}`,` Prompt: "${W}"`];return o==="codex"&&X.push(` Codex approval policy: ${H.codexApprovalPolicy??h.codexApprovalPolicy}`),r.resume_session_id&&(X.push(` Resume: ${r.resume_session_id}${r.fork_session?" (forked)":""}`),A&&X.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),X.push(r.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),X.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:X.join(`
|
|
2
|
+
`)}]}}catch(o){let s=Hc(o),i=s.includes("Max sessions")?"":`
|
|
3
3
|
|
|
4
|
-
Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${s}${
|
|
5
|
-
`)}function
|
|
6
|
-
`)}function
|
|
7
|
-
`),
|
|
8
|
-
`)}var
|
|
9
|
-
`)}function
|
|
10
|
-
`)}function
|
|
4
|
+
Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${s}${i}`}]}}}}}import{existsSync as Yc,readFileSync as Jc}from"fs";function _e(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),n=t%60;return r>0?`${r}m${n}s`:`${n}s`}var qc=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 yi(e){let r=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(n=>n.length>1&&!qc.has(n)).slice(0,3);return r.length===0?"session":r.join("-")}var zc={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function xi(e){let t=zc[e.status]??"\u2753",r=_e(e.duration),n=e.multiTurn?"multi-turn":"single",o=e.prompt.length>80?e.prompt.slice(0,80)+"...":e.prompt,s=e.costUsd>0?` | $${e.costUsd.toFixed(2)}`:"",i=[`${t} ${e.name} [${e.id}] (${r}${s}) \u2014 ${n}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];return e.phase!==e.status&&i.push(` \u2699\uFE0F Phase: ${e.phase}`),e.harness&&i.push(` \u{1F9F0} Harness: ${e.harness}`),e.harnessSessionId&&i.push(` \u{1F517} Session ID: ${e.harnessSessionId}`),e.resumeSessionId&&i.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),i.join(`
|
|
5
|
+
`)}function Or(e,t){let r=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:n,failed:o,killed:s}=e.sessionsByStatus,i=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${n}`,` Failed: ${o}`,` Killed: ${s}`,"",`\u23F1\uFE0F Average duration: ${r>0?_e(r):"n/a"}`];if(e.mostExpensive){let m=e.mostExpensive;i.push("","\u{1F3C6} Notable session",` ${m.name} [${m.id}]`,` \u{1F4DD} "${m.prompt}"`)}return i.join(`
|
|
6
|
+
`)}function Ze(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function Si(e,t){let r=e.split(`
|
|
7
|
+
`),n=[],o=0;for(let s=r.length-1;s>=0;s--){let i=r[s].length+(n.length>0?1:0);if(o+i>t&&n.length>0)break;n.unshift(r[s]),o+=i}return n.join(`
|
|
8
|
+
`)}var Xc=50,Qc=1,Zc=new Set(["starting","running","completed","failed","killed"]),ep=5,tp=1440*60*1e3;function rp(e){let t=Number(e);return!Number.isFinite(t)||t<Qc?Xc:Math.floor(t)}function np(e){return typeof e=="string"&&Zc.has(e)}function op(e){let t=_e(e.duration),r=` | Cost: $${e.costUsd.toFixed(4)}`,n=e.status==="running"?` | Phase: ${e.phase}`:"";return[`Session: ${e.name} [${e.id}] | Status: ${e.status.toUpperCase()}${n}${r} | Duration: ${t}`,`${"\u2500".repeat(60)}`].join(`
|
|
9
|
+
`)}function sp(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?`
|
|
11
11
|
(no output yet)
|
|
12
12
|
${t.join(`
|
|
13
13
|
`)}`:`
|
|
14
|
-
(no output yet)`}function
|
|
15
|
-
`).slice(-
|
|
16
|
-
`));let
|
|
17
|
-
${f}`:`${
|
|
18
|
-
(output file was empty)`}catch(
|
|
14
|
+
(no output yet)`}function Rr(e,t,r={}){let n=rp(r.lines),o=e.resolve(t);if(!o){let m=e.getPersistedSession(t);if(m?.outputPath&&Yc(m.outputPath))try{let p=Jc(m.outputPath,"utf-8"),f=p;!r.full&&p&&(f=p.split(`
|
|
15
|
+
`).slice(-n).join(`
|
|
16
|
+
`));let A=sp(m);return f?`${A}
|
|
17
|
+
${f}`:`${A}
|
|
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 s=r.full?o.getOutput():o.getOutput(n),i=op(o);return s.length===0?`${i}${ip(o)}`:`${i}
|
|
19
19
|
${s.join(`
|
|
20
|
-
`)}`}function
|
|
20
|
+
`)}`}function Cr(e,t="all",r,n={}){let o=e.listPersistedSessions()??[],i=ap(e.list("all"),o);if(t!=="all"&&(i=i.filter(m=>m.status===t)),r&&(i=i.filter(m=>m.originChannel===r)),n.full){let m=Date.now()-tp;i=i.filter(p=>(p.startedAt??0)>=m)}else i=i.slice(0,ep);return i.length===0?"No sessions found.":i.map(m=>xi(m)).join(`
|
|
21
21
|
|
|
22
|
-
`)}function
|
|
23
|
-
`),isError:!0}}async function
|
|
24
|
-
\
|
|
25
|
-
\
|
|
26
|
-
|
|
27
|
-
`)}}catch(
|
|
22
|
+
`)}function ap(e,t){let r=new Map;for(let n of t){if(!np(n.status))continue;let o=n.completedAt??Date.now(),s=n.createdAt??o,i=n.sessionId??`persisted:${n.harnessSessionId}`;r.set(i,{id:n.sessionId??n.harnessSessionId,name:n.name||n.harnessSessionId,status:n.status,startedAt:n.createdAt??0,completedAt:n.completedAt,duration:Math.max(0,o-s),prompt:n.prompt??"",workdir:n.workdir??"(unknown)",costUsd:n.costUsd??0,multiTurn:!0,phase:n.status,harness:n.harness,harnessSessionId:n.harnessSessionId,originChannel:n.originChannel,originThreadId:n.originThreadId})}for(let n of e)r.set(n.id,{id:n.id,name:n.name,status:n.status,startedAt:n.startedAt,completedAt:n.completedAt,duration:n.duration,prompt:n.prompt,workdir:n.workdir,costUsd:n.costUsd,multiTurn:n.multiTurn,phase:n.phase,harness:n.harnessName,harnessSessionId:n.harnessSessionId,originChannel:n.originChannel,originThreadId:n.originThreadId});return[...r.values()].sort((n,o)=>(o.startedAt??0)-(n.startedAt??0))}function up(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 Ti(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,r){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=up(r),o=e?.workspaceDir?Qt(e.workspaceDir):void 0,s=!!(r&&typeof r=="object"&&r.full===!0);return{content:[{type:"text",text:Cr(g,n,o,{full:s})}]}}}}function Mr(e,t,r){let n=e.resolve(t);return n?n.status==="completed"||n.status==="failed"||n.status==="killed"?`Session ${n.name} [${n.id}] is already ${n.status}. No action needed.`:r==="completed"?(n.complete(),`Session ${n.name} [${n.id}] marked as completed.`):(e.kill(n.id),`Session ${n.name} [${n.id}] has been terminated.`):`Error: Session "${t}" not found.`}function dp(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 bi(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,r){return g?dp(r)?{content:[{type:"text",text:Mr(g,r.session,r.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}function mp(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function Ai(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,r){return g?mp(r)?{content:[{type:"text",text:Rr(g,r.session,{full:r.full,lines:r.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}var cp=new Set(["killed","completed","failed"]),pp=new Set(["startup-timeout"]),lp=10,fp=100,gp=/\b(change|swap|replace|remove|add|update|instead|don't|revise|modify)\b/i;function Zt(e){return e instanceof Error?e.message:String(e)}function Ip(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 wi(e){return"id"in e?e.id:e.sessionId??e.harnessSessionId}function hp(e){return e.status==="killed"&&e.completedAt==null}function yp(e,t){return cp.has(e.status)&&!!e.harnessSessionId&&(e.status==="failed"||e.status==="completed"&&e.killReason==="done"||e.status==="killed"&&(!pp.has(e.killReason??"")||t&&hp(e)))}function xp(e,t){if(!(t.trim().length<fp&&!gp.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 Sp(e,t,r,n={}){if(yp(t,n.allowRecoveredRunningStub===!0))try{let o="harnessName"in t?t:void 0,s="harnessName"in t?void 0:t,{resumeSessionId:i}=Ft({requestedResumeSessionId:t.harnessSessionId,activeSession:o?{harnessSessionId:o.harnessSessionId}:void 0,persistedSession:s?{harness:s.harness}:void 0}),m={prompt:r,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:i,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=e.spawn(m),f=Ip(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} [${wi(t)}]: ${Zt(o)}`,isError:!0}}}function Tp(e,t,r){let n=t.lobsterResumeToken;if(!n)return;t.lobsterResumeToken=void 0;let o=t.pendingPlanApproval||t.currentPermissionMode==="acceptEdits"||t.currentPermissionMode==="default";if(r.approve&&o)return e.resumeLobsterApproval(n,!0).catch(s=>{console.error(`[Respond] Lobster resume failed, falling back to direct mode switch: ${Zt(s)}`),t.switchPermissionMode("bypassPermissions"),t.sendMessage(r.message).catch(i=>{console.error(`[Respond] Fallback sendMessage also failed: ${Zt(i)}`)})}),{text:`Plan approved. Lobster workflow resuming for session ${t.name} [${t.id}].`};e.resumeLobsterApproval(n,!1).catch(s=>{console.error(`[Respond] Lobster cancel failed (non-critical): ${Zt(s)}`)})}async function kr(e,t){let r=e.resolve(t.session),n=r?void 0:e.getPersistedSession(t.session);if(!r&&!n)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let s=await Sp(e,r??n,t.message,{allowRecoveredRunningStub:!r});if(s)return s;if(!r)return{text:`Error: Session ${n.name} [${wi(n)}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};if(r.status!=="running")return{text:`Error: Session ${r.name} [${r.id}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};let i=h.maxAutoResponds??lp;if(t.userInitiated)r.resetAutoRespond();else if(r.autoRespondCount>=i)return{text:`\u26A0\uFE0F Auto-respond limit reached (${r.autoRespondCount}/${i}). Ask the user to provide the answer for session ${r.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};let m=Tp(e,r,t);if(m)return m;try{t.interrupt&&await r.interrupt();let p="";if(t.approve&&r.pendingPlanApproval){let A=xp(r.name,t.message);if(A)return A;r.switchPermissionMode("bypassPermissions")}else t.approve&&(r.currentPermissionMode==="acceptEdits"||r.currentPermissionMode==="default")?r.switchPermissionMode("bypassPermissions"):t.approve&&r.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.`:r.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 r.sendMessage(t.message),t.userInitiated||r.incrementAutoRespond();let f=Ze(t.message,80);return{text:[`Message sent to session ${r.name} [${r.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 ${r.name} [${r.id}]: ${Zt(p)}`,isError:!0}}}function bp(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function Pi(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,r){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!bp(r))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let n=await kr(g,r);return{isError:n.isError??!1,content:[{type:"text",text:n.text}]}}}}function Oi(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,r){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let n=g.getMetrics(),o=g.list("running").length;return{content:[{type:"text",text:Or(n,o)}]}}}}function Ap(e){return e instanceof Error?e.message:String(e)}function Ri(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 r=(t.args??"").trim();if(!r)return{text:"Usage: /agent [--name <name>] <prompt>"};let n,o=r.match(/^--name\s+(\S+)\s+/);o&&(n=o[1],r=r.slice(o[0].length).trim());let s=r;if(!s)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=h.defaultHarness,m=i==="codex"?h.model??h.defaultModel:h.defaultModel,p=g.spawn({prompt:s,name:n,workdir:h.defaultWorkdir||process.cwd(),model:m,reasoningEffort:h.reasoningEffort,codexApprovalPolicy:h.codexApprovalPolicy,originChannel:kt(t),originThreadId:Et(t),harness:i}),f=s.length>80?s.slice(0,80)+"...":s;return{text:["Session launched.",` Name: ${p.name}`,` ID: ${p.id}`,` Prompt: "${f}"`,` Status: ${p.status}`].join(`
|
|
28
|
+
`)}}catch(i){let m=Ap(i),p=m.includes("Max sessions")?"":`
|
|
28
29
|
|
|
29
|
-
Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${m}${
|
|
30
|
+
Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${m}${p}`}}}})}function Ci(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 r=(t.args??"").split(/\s+/).includes("--full");return{text:Cr(g,"all",void 0,{full:r})}}})}function Mi(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 r=t.args?.trim();return r?{text:Mr(g,r,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}function wp(e){return e instanceof Error?e.message:String(e)}function ki(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 r=(t.args??"").trim();if(!r)return{text:`Usage: /agent_resume <id-or-name> [prompt]
|
|
30
31
|
/agent_resume --list \u2014 list resumable sessions
|
|
31
|
-
/agent_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(
|
|
32
|
+
/agent_resume --fork <id-or-name> [prompt] \u2014 fork instead of continuing`};if(r==="--list"){let Y=g.listPersistedSessions();return Y.length===0?{text:"No resumable sessions found. Sessions are persisted after completion."}:{text:`Resumable sessions:
|
|
32
33
|
|
|
33
|
-
${
|
|
34
|
+
${Y.map(W=>{let X=W.prompt.length>60?W.prompt.slice(0,60)+"...":W.prompt,Fe=W.completedAt?`completed ${_e(Date.now()-W.completedAt)} ago`:W.status;return[` ${W.name} \u2014 ${Fe}`,` Session ID: ${W.harnessSessionId}`,` \u{1F4C1} ${W.workdir}`,` \u{1F4DD} "${X}"`].join(`
|
|
34
35
|
`)}).join(`
|
|
35
36
|
|
|
36
|
-
`)}`}}let
|
|
37
|
-
Use /agent_resume --list to see available sessions.`};let
|
|
38
|
-
`)}}catch(
|
|
37
|
+
`)}`}}let n=!1;r.startsWith("--fork ")&&(n=!0,r=r.slice(7).trim());let o=r.indexOf(" "),s,i;o===-1?(s=r,i="Continue where you left off."):(s=r.slice(0,o),i=r.slice(o+1).trim()||"Continue where you left off.");let m=g.resolveHarnessSessionId(s);if(!m)return{text:`Error: Could not find a session ID for "${s}".
|
|
38
|
+
Use /agent_resume --list to see available sessions.`};let p=g.resolve(s),f=g.getPersistedSession(s),{resumeSessionId:A,clearedPersistedCodexResume:_}=Ft({requestedResumeSessionId:m,activeSession:p?{harnessSessionId:p.harnessSessionId}:void 0,persistedSession:f?{harness:f.harness}:void 0}),ie=f?.workdir??process.cwd();try{let Y=g.spawn({prompt:i,workdir:ie,name:f?.name,model:f?.model,codexApprovalPolicy:p?.codexApprovalPolicy??f?.codexApprovalPolicy,resumeSessionId:A,forkSession:A?n:!1,originChannel:kt(t),originThreadId:Et(t)??f?.originThreadId,originAgentId:t?.agentId??f?.originAgentId,originSessionKey:t?.sessionKey??f?.originSessionKey,harness:f?.harness}),H=i.length>80?i.slice(0,80)+"...":i;return{text:[`Session resumed${n?" (forked)":""}.`,` Name: ${Y.name}`,` ID: ${Y.id}`,A?` Resume from: ${m}`:" Resume from: fresh thread",` Dir: ${ie}`,` Prompt: "${H}"`,_?" Note: cleared persisted Codex thread state after restart to avoid org-mismatch resume failures.":""].join(`
|
|
39
|
+
`)}}catch(Y){let H=wp(Y),W=H.includes("Max sessions")?"":`
|
|
39
40
|
|
|
40
|
-
Use /agent_sessions to see active sessions or /agent_resume --list to see resumable sessions.`;return{text:`Error resuming session: ${
|
|
41
|
-
/agent_respond --interrupt <id-or-name> <message>`};let
|
|
42
|
-
`)}function
|
|
43
|
-
`,
|
|
41
|
+
Use /agent_sessions to see active sessions or /agent_resume --list to see resumable sessions.`;return{text:`Error resuming session: ${H}${W}`}}}})}function Ei(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 r=(t.args??"").trim();if(!r)return{text:`Usage: /agent_respond <id-or-name> <message>
|
|
42
|
+
/agent_respond --interrupt <id-or-name> <message>`};let n=!1,o=r;o.startsWith("--interrupt ")&&(n=!0,o=o.slice(12).trim());let s=o.indexOf(" ");if(s===-1)return{text:"Error: Missing message. Usage: /agent_respond <id-or-name> <message>"};let i=o.slice(0,s),m=o.slice(s+1).trim();return m?{text:(await kr(g,{session:i,message:m,interrupt:n,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}function Fi(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(),r=g.list("running").length;return{text:Or(t,r)}}})}var Pp=50;function $i(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 r=(t.args??"").trim();if(!r)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let n=r.split(/\s+/),o="",s=!1,i=Pp;for(let p=0;p<n.length;p++)if(n[p]==="--full")s=!0;else if(n[p]==="--lines"&&p+1<n.length){let f=parseInt(n[p+1],10);!isNaN(f)&&f>0&&(i=f),p++}else o||(o=n[p]);return o?{text:Rr(g,o,{full:s,lines:i})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}import{execFile as oa}from"child_process";import{existsSync as jl}from"fs";import{fileURLToPath as sa}from"url";import{dirname as Dl,join as Dn}from"path";import{EventEmitter as pl}from"events";import Ni from"crypto";var Ui="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Op=128,ct,$t,Rp=e=>{!ct||ct.length<e?(ct=Buffer.allocUnsafe(e*Op),Ni.randomFillSync(ct),$t=0):$t+e>ct.length&&(Ni.randomFillSync(ct),$t=0),$t+=e};var _i=(e=21)=>{Rp(e|=0);let t="";for(let r=$t-e;r<$t;r++)t+=Ui[ct[r]&63];return t};import{query as Cp}from"@anthropic-ai/claude-agent-sdk";var Er=class{name="claude-code";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=["AskUserQuestion"];planApprovalToolNames=["ExitPlanMode","set_permission_mode"];launch(t){let r={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&&(r.resume=t.resumeSessionId,r.forkSession=t.forkSession??!1);let n=Cp({prompt:t.prompt,options:r});return{messages:this.adaptMessages(n),async setPermissionMode(o){typeof n.setPermissionMode=="function"&&await n.setPermissionMode(o)},async streamInput(o){typeof n.streamInput=="function"&&await n.streamInput(o)},async interrupt(){typeof n.interrupt=="function"&&await n.interrupt()}}}buildUserMessage(t,r){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:r}}async*adaptMessages(t){for await(let r of t){let n=r;if(n.type==="system"&&n.subtype==="init")yield{type:"init",session_id:n.session_id??""};else if(n.type==="system"&&n.subtype==="status"&&n.permissionMode)yield{type:"permission_mode_change",mode:n.permissionMode};else if(n.type==="assistant")for(let o of n.message?.content??[])o.type==="text"?yield{type:"text",text:o.text}:o.type==="tool_use"&&(yield{type:"tool_use",name:o.name,input:o.input});else n.type==="result"&&(yield{type:"result",data:{success:n.subtype==="success",duration_ms:n.duration_ms??0,total_cost_usd:n.total_cost_usd??0,num_turns:n.num_turns??0,result:n.result,session_id:n.session_id??""}})}}};import{parse as Xp,resolve as Qp}from"path";import{Codex as Hi}from"@openai/codex-sdk";import{randomUUID as Mp}from"node:crypto";import{lstat as kp,mkdir as vn,readFile as Li,readlink as Ep,realpath as Fp,rename as $p,rm as Fr,symlink as Up,writeFile as ji}from"node:fs/promises";import{homedir as Np,tmpdir as Di}from"node:os";import{dirname as _p,join as Ee,resolve as vp}from"node:path";var Kp=50,Lp=3e4,jp=Ee(Di(),"openclaw-codex-auth.lock");function Dp(e,t){let r={};for(let[n,o]of Object.entries(e))typeof o=="string"&&(r[n]=o);return r.HOME=t,r}function Gp(e){return new Promise(t=>setTimeout(t,e))}async function Gi(e){try{return await kp(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function vi(e,t){if(await Gi(t)){if(await Ep(t)===e)return;await Fr(t,{recursive:!0,force:!0})}await Up(e,t)}function Vp(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return null;let r=Number(t);if(Number.isFinite(r))return r;let n=Date.parse(t);if(Number.isFinite(n))return n}return null}async function Ki(e){let t;try{t=await Li(e,"utf8")}catch(r){return r.code==="ENOENT",null}try{let r=JSON.parse(t);if(!r||typeof r!="object")return null;let n=Vp(r.last_refresh);return n===null?null:{lastRefresh:n,raw:t}}catch{return null}}async function Vi(e,t){await vn(_p(e),{recursive:!0});let r=`${e}.tmp`;await ji(r,t,"utf8"),await $p(r,e)}async function Bp(e,t){try{let r=await Li(e,"utf8");await Vi(t,r)}catch(r){if(r.code!=="ENOENT")throw r;await Fr(t,{force:!0})}}async function Hp(e,t){let r=await Ki(e);if(!r)return;let n=await Ki(t);n&&r.lastRefresh<=n.lastRefresh||await Vi(t,r.raw)}async function Wp(e,t,r){let n=Date.now()+t;for(;;)try{await vn(e);break}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=n)throw new Error(`Timed out waiting for Codex auth lock at ${e}`);await Gp(r)}try{await ji(Ee(e,"holder.json"),JSON.stringify({pid:process.pid,acquired_at:new Date().toISOString()}),"utf8")}catch{}let o=!1;return async()=>{o||(o=!0,await Fr(e,{recursive:!0,force:!0}))}}async function Bi(e=process.env,t={}){let r=e.HOME??Np(),n=await Fp(r).catch(()=>vp(r)),o=Ee(n,".codex"),s=Ee(o,"auth.json"),i=Ee(o,"sessions"),m=Ee(o,"config.toml"),p=await Gi(m)?m:void 0,f=t.tempRootDir??Di(),A=Ee(f,`openclaw-codex-auth-${Mp()}`),_=Ee(A,".codex"),ie=Ee(_,"auth.json"),Y=t.lockDir??jp,H=t.lockTimeoutMs??Lp,W=t.lockRetryMs??Kp;return await vn(_,{recursive:!0}),await vi(i,Ee(_,"sessions")),p&&await vi(p,Ee(_,"config.toml")),{tempHome:A,tempCodexDir:_,canonicalHome:n,canonicalCodexDir:o,canonicalAuthPath:s,canonicalSessionsPath:i,canonicalConfigPath:p,env:Dp(e,A),async prepareForTurn(){let X=await Wp(Y,H,W);try{await Bp(s,ie)}catch(er){throw await X(),er}let Fe=!1;return async()=>{if(!Fe){Fe=!0;try{await Hp(ie,s)}finally{await X()}}}},async cleanup(){await Fr(A,{recursive:!0,force:!0})}}}var qp=["proceed","continue","implement","apply","run","merge","deploy","commit"],zp=["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"],Yp=["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 Jp(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function $r(e){let t=Jp(e);if(!t||Yp.some(n=>t.includes(n)))return!1;let r=qp.some(n=>t.includes(n));return zp.some(n=>t.includes(n))?r||t.includes("confirm"):t.endsWith("?")?r:!1}var Wi=1e4,qi="codex:waiting-for-user",Zp=1.1/1e6,el=.275/1e6,tl=4.4/1e6,rl="OPENCLAW_CODEX_HEARTBEAT_MS",nl="OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS",ol="OPENCLAW_CODEX_AUTH_STRATEGY";function sl(e){if(!e)return 0;let t=e.cached_input_tokens??0,r=Math.max(0,(e.input_tokens??0)-t),n=e.output_tokens??0;return r*Zp+t*el+n*tl}function zi(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 al(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 Yi(e){return e instanceof Error?e.message:String(e)}function ul(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function dl(e){return Xp(Qp(e)).root||"/"}function ml(e){let r=[dl(e)];return r.push(...ul(process.env[nl])),[...new Set(r)]}function cl(e,t){let n=(t??e.permissionMode)==="bypassPermissions"?ml(e.cwd):void 0;return{model:e.model,modelReasoningEffort:e.reasoningEffort,workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:e.codexApprovalPolicy??"on-request",skipGitRepoCheck:!0,additionalDirectories:n}}var Ur=class{constructor(t={}){this.deps=t}name="codex";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=[qi];planApprovalToolNames=[];activityHeartbeatMs(){let t=Number.parseInt(process.env[rl]??String(Wi),10);return!Number.isFinite(t)||t<=0?Wi:t}createCodexClient(t){return this.deps.createCodex?.({env:t})??(t?new Hi({env:t}):new Hi)}launch(t){let n=process.env[ol]==="legacy"?void 0:this.deps.createAuthWorkspace?.(process.env)??Bi(process.env),o=t.permissionMode==="plan",s=t.permissionMode==="plan"?"default":t.permissionMode,i=t.resumeSessionId,m=0,p=0,f=this.activityHeartbeatMs(),A,_,ie=!1,Y=!0,H,W=[],X=null,Fe=!1,er=!1;function Gn(){X&&(X(),X=null)}function et(D){W.push(D),Gn()}function Vn(){Fe=!0,Gn()}function Hr(D){!D||er||(er=!0,et({type:"init",session_id:D}))}async function*ia(){for(;;){for(;W.length>0;)yield W.shift();if(Fe)return;await new Promise(D=>{X=D})}}let tr=()=>cl(t,s),aa=D=>(A||(A=this.createCodexClient(D)),_||(Y&&t.resumeSessionId?_=A.resumeThread(t.resumeSessionId,tr()):i?_=A.resumeThread(i,tr()):_=A.startThread(tr())),ie&&i&&(_=A.resumeThread(i,tr()),ie=!1),Hr(_.id??i??void 0),_),Bn=async D=>{let qr=Date.now();p+=1;let Hn="",zr=!1,Yr,Jr,Wn=!1,ua=Y&&o?al(D):D,rr=tt=>{zr||(zr=!0,et({type:"result",data:zi(i??"",{duration_ms:Date.now()-qr,total_cost_usd:m,num_turns:p,...tt,session_id:i??""})}))},Xr=async()=>{!Jr||Wn||(Wn=!0,await Jr())};try{let tt=n?await n:void 0;tt&&(Jr=await tt.prepareForTurn());let qn=aa(tt?.env),zn=qn.id??i??void 0;zn&&(i=zn,Hr(i)),H=new AbortController,t.abortController?.signal.aborted&&H.abort(t.abortController.signal.reason),Yr=setInterval(()=>{et({type:"activity"})},f);let da=await qn.runStreamed(ua,{signal:H.signal});for await(let ae of da.events){if(await Xr(),ae.type==="thread.started"){i=ae.thread_id,Hr(i);continue}if(ae.type==="item.completed"){(ae.item.type==="agent_message"||ae.item.type==="reasoning")&&(Hn+=`${ae.item.text}
|
|
44
|
+
`,et({type:"text",text:ae.item.text}));continue}if(ae.type==="error"){et({type:"text",text:`[codex:error] ${ae.message}`});continue}if(ae.type==="turn.failed"){rr({success:!1,result:ae.error.message,session_id:i??""});continue}if(ae.type==="turn.completed"){m+=sl(ae.usage);let Yn=Hn.slice(-500);$r(Yn)&&et({type:"tool_use",name:qi,input:{text:Yn}}),rr({success:!0,session_id:i??""})}}await Xr(),zr||rr({success:!1,result:"Codex turn ended without terminal event",session_id:i??""})}catch(tt){await Xr(),rr({success:!1,result:Yi(tt),session_id:i??""})}finally{Yr&&clearInterval(Yr),H=void 0,Y=!1}},Wr=()=>{H?.abort(t.abortController?.signal.reason??"interrupted")};return t.abortController?.signal&&t.abortController.signal.addEventListener("abort",Wr),(async()=>{try{let D=t.prompt;if(typeof D=="string"){await Bn(D);return}for await(let qr of D)if(t.abortController?.signal.aborted||(await Bn(il(qr)),t.abortController?.signal.aborted))break}finally{if(t.abortController?.signal.removeEventListener("abort",Wr),n)try{await(await n).cleanup()}catch{}Vn()}})().catch(D=>{et({type:"result",data:zi(i??"",{success:!1,result:Yi(D),total_cost_usd:m,num_turns:p,session_id:i??""})}),t.abortController?.signal.removeEventListener("abort",Wr),Vn()}),{messages:ia(),async setPermissionMode(D){s=D,ie=!0},async interrupt(){H?.abort("interrupted")}}}buildUserMessage(t,r){return{type:"user",text:t,session_id:r}}};var Kn=new Map;function Ji(e){Kn.set(e.name,e)}function Ln(e){let t=Kn.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...Kn.keys()].join(", ")}`);return t}function Xi(){let e=h.defaultHarness??"claude-code";return Ln(e)}Ji(new Er);Ji(new Ur);var Qi=200,ll=120*1e3;function Nr(e){return e instanceof Error?e.message:String(e)}var fl={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},jn=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})}}},_r=class extends pl{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,r){super(),this.id=_i(8),this.name=r,this.harness=t.harness?Ln(t.harness):Xi();let n=this.harness.name==="codex";this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??(n?h.model:void 0)??h.defaultModel,this.reasoningEffort=t.reasoningEffort??(n?h.reasoningEffort:void 0),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??h.permissionMode,this.codexApprovalPolicy=n?t.codexApprovalPolicy??h.codexApprovalPolicy:void 0,this.currentPermissionMode=n&&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(!fl[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let r=this._status;this._status=t,this.emit("statusChange",this,t,r)}setTimer(t,r,n){this.clearTimer(t),this.timers.set(t,setTimeout(n,r))}clearTimer(t){let r=this.timers.get(t);r&&(clearTimeout(r),this.timers.delete(t))}clearAllTimers(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}async start(){try{let t;this.multiTurn?(this.messageStream=new jn,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let r=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,codexApprovalPolicy:this.codexApprovalPolicy,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,abortController:this.abortController,mcpServers:li()});this.harnessHandle=r,this.setTimer("startup",ll,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let r=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:r});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let r=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${r}`,n),this.isActive&&this.transitionToTerminal("failed",{error:r})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.waitingForInputFired=!1;let r=t;if(this.pendingModeSwitch){let n=this.pendingModeSwitch,o=!1,s=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(n),this.currentPermissionMode=n,this.pendingModeSwitch=void 0,s=!0,o=!0}catch(i){throw console.error(`[Session ${this.id}] setPermissionMode(${n}) FAILED: ${Nr(i)}`),this.pendingPlanApproval=!0,new Error(`Failed to switch permission mode to ${n}: ${Nr(i)}`)}else this.pendingModeSwitch=void 0,s=!0,o=!0,console.warn(`[Session ${this.id}] Cannot call setPermissionMode \u2014 falling back to text prefix only (currentPermissionMode remains ${this.currentPermissionMode})`);s&&(this.pendingPlanApproval=!1,n!=="plan"&&(this.planModeApproved=!0)),o&&(r=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
|
|
44
45
|
|
|
45
|
-
${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved){let
|
|
46
|
+
${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved){let n=this.harness.planApprovalToolNames;if(r=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below,${n.length>0?` then call ${n.join(" or ")} again to re-submit for approval.`:" then re-submit your revised plan for approval."} Do NOT start implementing yet.]
|
|
46
47
|
|
|
47
|
-
${t}`,this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode("plan"),this.currentPermissionMode="plan"}catch(s){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${
|
|
48
|
-
`);s.length>0&&(_i(o,s,"utf-8"),n=o)}catch(o){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${vi(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,s=Number.NEGATIVE_INFINITY,a=0;for(let m of this.persisted.values()){if(m.name!==t){a++;continue}let c=m.createdAt??Number.NEGATIVE_INFINITY,f=m.completedAt??Number.NEGATIVE_INFINITY;(c>r||c===r&&f>o||c===r&&f===o&&a>s)&&(n=m,r=c,o=f,s=a),a++}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=Ni(),r=_c(n).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of r)try{let s=Nn(n,o),a=vc(s).mtimeMs;t-a>Hc&&Kc(s)}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[s,a]of this.idIndex)a===o.harnessSessionId&&this.idIndex.delete(s);for(let[s,a]of this.nameIndex)a===o.harnessSessionId&&this.nameIndex.delete(s)}this.saveIndex()}shouldGcActiveSession(t,n,r){return!t.completedAt||!Vc.has(t.status)?!1:n-t.completedAt>r}};var Zc=new Set(["completed","failed","killed"]),Kn=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),Zc.has(r)&&this.metrics.sessionsByStatus[r]++,t.completedAt){let s=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=s,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||n>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:n,prompt:Je(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 el}from"child_process";import{randomUUID as tl}from"crypto";var Li=3e4,nl=2e3,rl=2e4,Ln=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 a=n.split("|").map(m=>m.trim()).filter(Boolean);if(a.length>=2){let[m,c,f]=a,$=f??c,le=f?c:void 0;if(m&&$)return{channel:m,target:$,accountId:le,threadId:r??this.parseThreadIdFromSessionKey(t.originSessionKey)}}}let o=this.getOriginSessionKey(t);if(!o)return;let s=o.match(/^agent:[^:]+:telegram:(?:direct|dm|group|channel):([^:]+)(?::topic:(\d+))?$/i);if(s?.[1])return{channel:"telegram",target:s[1],threadId:r??s[2]}}parseThreadIdFromSessionKey(t){return t?t.match(/:topic:(\d+)$/)?.[1]:void 0}retryDelayMs(t){let n=Math.max(0,t-1),r=nl*2**n;return Math.min(r,rl)}executeWithRetries(t,n,r=1){let o=Date.now();console.info(`[WakeDispatcher] ${n.target} ${n.phase} started attempt ${r}/${Ln} for ${n.label} session=${n.sessionId}`),el("openclaw",t,{timeout:Li},s=>{let a=Date.now()-o;if(!s){console.info(`[WakeDispatcher] ${n.target} ${n.phase} completed attempt ${r}/${Ln} for ${n.label} session=${n.sessionId} in ${a}ms`);return}let m=`[WakeDispatcher] ${n.target} ${n.phase} failed`;if(r>=Ln){console.error(`${m} after ${r} attempts for ${n.label} session=${n.sessionId} in ${a}ms: ${s.message}`),n.onFinalFailure?.();return}let c=this.retryDelayMs(r);console.error(`${m} attempt ${r}/${Ln} for ${n.label} session=${n.sessionId} in ${a}ms: ${s.message}. Retrying in ${c}ms`);let f=setTimeout(()=>{this.pendingRetryTimers.delete(f),this.executeWithRetries(t,n,r+1)},c);this.pendingRetryTimers.add(f)})}fireChatSendWithRetry(t,n,r,o,s,a=!1,m){let c=["gateway","call","chat.send","--expect-final","--timeout",String(Li),"--params",JSON.stringify({sessionKey:t,message:n,deliver:a,idempotencyKey:tl()})];this.executeWithRetries(c,{label:r,sessionId:o,target:"chat.send",phase:s,onFinalFailure:m})}fireDirectNotificationWithRetry(t,n,r,o,s){let a=["message","send","--channel",t.channel,"--target",t.target,"--message",n];t.accountId&&a.push("--account",t.accountId),t.threadId&&a.push("--thread-id",t.threadId),this.executeWithRetries(a,{label:r,sessionId:o,target:"message.send",phase:"notify",onFinalFailure:s})}fireSystemEventWithRetry(t,n,r,o){let s=["system","event","--text",t,"--mode","now"];this.executeWithRetries(s,{label:n,sessionId:r,target:"system.event",phase:o})}sendUserNotification(t,n,r,o){let s=this.parseNotificationRoute(t);if(!s){this.fireSystemEventWithRetry(n,`${r}-notify-system`,o,"notify");return}this.fireDirectNotificationWithRetry(s,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"),s=n.userMessage?.trim(),a=n.wakeMessage?.trim();if(o==="always"&&s&&this.sendUserNotification(t,s,n.label,t.id),!!a){if(!r){o==="on-wake-fallback"&&s&&this.sendUserNotification(t,s,n.label,t.id),this.fireSystemEventWithRetry(a,`${n.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(r,a,`${n.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(a,`${n.label}-wake-fallback`,t.id,"wake")})}}};function il(){let e=process.env.OPENCLAW_CODE_AGENT_PLAN_WORKFLOW_PATH?.trim();if(e)return e;let t=sl(Di(import.meta.url)),n=[_r(process.cwd(),"workflows","plan-approval.lobster"),_r(t,"..","workflows","plan-approval.lobster"),_r(t,"..","..","workflows","plan-approval.lobster")];for(let r of n)if(ol(r))return r;return Di(new URL("../workflows/plan-approval.lobster",import.meta.url))}var al=il(),ul=new Set(["completed","failed","killed"]),Dn=new Set(["starting","running"]),dl=5e3,ml=3e4;function pl(e){let t=e.trim();if(!t)return;let n=s=>typeof s=="string"&&s.trim().length>0&&/^[A-Za-z0-9._:-]+$/.test(s.trim()),r=[t];for(let s of t.split(/\r?\n/)){let a=s.trim();a.startsWith("{")&&a.endsWith("}")&&r.push(a)}for(let s of r)try{let a=JSON.parse(s),m=a?.resumeToken??a?.requiresApproval?.resumeToken??a?.details?.requiresApproval?.resumeToken;if(n(m))return m.trim()}catch{}let o=t.match(/"resumeToken"\s*:\s*"([^"]+)"/);if(o&&n(o[1]))return o[1].trim()}var Gn=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 vn,this.metrics=new Kn,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=>Dn.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){if([...this.sessions.values()].filter(m=>Dn.has(m.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 r=t.name||di(t.prompt),o=this.uniqueName(r);o!==r&&console.warn(`[SessionManager] Name conflict: "${r}" \u2192 "${o}" (active session with same name exists)`);let s=new Un(t,o);this.sessions.set(s.id,s),this.metrics.incrementLaunched(),s.on("statusChange",(m,c)=>{c==="running"&&s.harnessSessionId?this.store.markRunning(s):ul.has(c)&&this.onSessionTerminal(s)}),s.on("turnEnd",(m,c)=>{this.onTurnEnd(s,c)}),s.start();let a=`\u{1F680} [${s.name}] Launched | ${s.workdir} | ${s.model??"default"}`;return this.notifySession(s,a,"launch"),s}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 m=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})`,c=Je(m,200);this.triggerFailedEvent(t,c);return}let n=`$${(t.costUsd??0).toFixed(2)}`,r=Ue(t.duration),s={user:"by agent/user","idle-timeout":`idle ${h.idleTimeoutMinutes??15}min`,shutdown:"gateway shutdown",unknown:""}[t.killReason]||"",a=`Killed${s?` (${s})`:""}`;this.notifySession(t,`\u26D4 [${t.name}] ${a} | ${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:al,argsJson:r,timeoutMs:0})];ji("openclaw",o,{timeout:ml},(s,a,m)=>{if(s){console.error(`[SessionManager] Lobster launch failed for session=${t.id}: ${s.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(s){console.warn(`[Session ${this.id}] Failed to re-assert plan mode: ${Nr(s)}`)}}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(r,this.harnessSessionId??""));else if(this.harnessHandle?.streamInput){let n=this.harness.buildUserMessage(r,this.harnessSessionId??"");async function*o(){yield n}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){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=(h.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: ${Nr(t)}`)}),this.abortController.abort()}transitionToTerminal(t,r={}){this.isActive&&(r.reason&&(this.killReason=r.reason),r.error!==void 0&&(this.error=r.error),this.completedAt=Date.now(),this.transition(t),this.teardown())}async consumeMessages(t){for await(let r of t){if(!this.isActive)break;if(this.resetIdleTimer(),r.type==="init")this.clearTimer("startup"),this.harnessSessionId=r.session_id,this._status==="starting"&&this.transition("running");else if(r.type==="text")this.waitingForInputFired=!1,this.pendingPlanApproval||(this.lastTurnHadQuestion=!1),this.outputBuffer.push(r.text),this.outputBuffer.length>Qi&&this.outputBuffer.splice(0,this.outputBuffer.length-Qi),this.emit("output",this,r.text);else if(r.type==="tool_use")this.harness.questionToolNames.includes(r.name)?(this.lastTurnHadQuestion=!0,this.currentPermissionMode==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0)):this.harness.planApprovalToolNames.includes(r.name)&&!this.planModeApproved&&(this.lastTurnHadQuestion=!0,this.pendingPlanApproval=!0),this.emit("toolUse",this,r.name,r.input);else if(r.type==="permission_mode_change"){let n=this.currentPermissionMode;this.currentPermissionMode=r.mode,r.mode!=="plan"&&n==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0,this.lastTurnHadQuestion=!0)}else if(r.type==="result"){if(this.result={subtype:r.data.success?"success":"error",duration_ms:r.data.duration_ms,total_cost_usd:r.data.total_cost_usd,num_turns:r.data.num_turns,result:r.data.result,is_error:!r.data.success,session_id:r.data.session_id},this.costUsd=r.data.total_cost_usd,this.multiTurn&&this.messageStream&&r.data.success){this.resetIdleTimer(),this.currentPermissionMode==="plan"&&!this.pendingPlanApproval&&!this.planModeApproved&&(this.pendingPlanApproval=!0);let o=this.pendingPlanApproval||this.lastTurnHadQuestion,s=this.messageStream?.hasPending()===!0;o&&!this.waitingForInputFired?(this.waitingForInputFired=!0,this.emit("turnEnd",this,!0)):s||o||(this.emit("turnEnd",this,!1),this.complete("done"))}else this.transitionToTerminal(r.data.success?"completed":"failed");this.lastTurnHadQuestion=!1}else r.type}}};import{mkdirSync as gl,readFileSync as Il,readdirSync as hl,renameSync as yl,statSync as xl,unlinkSync as Sl,writeFileSync as Zi}from"fs";import{homedir as Tl,tmpdir as ea}from"os";import{dirname as bl,join as Kr}from"path";function Al(e){let t=e.OPENCLAW_HOME?.trim();return t||Kr(Tl(),".openclaw")}function wl(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||Kr(Al(e),"code-agent-sessions.json")}var Pl=new Set(["completed","failed","killed"]),Ol=new Set(["running","completed","failed","killed"]),Rl=1440*60*1e3;function ta(e){return e instanceof Error?e.message:String(e)}function Cl(e){return!!e&&typeof e=="object"}function vr(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function pt(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function ra(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Ml(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function kl(e){return e==="default"||e==="plan"||e==="acceptEdits"||e==="bypassPermissions"?e:void 0}function El(e){return e==="never"||e==="on-request"?e:void 0}function Fl(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function $l(e){if(typeof e=="string"&&Ol.has(e))return e==="running"?"killed":e}function Ul(e){if(!Cl(e))return;let t=vr(e.harnessSessionId);if(!t)return;let r=$l(e.status);if(r)return{sessionId:pt(e.sessionId),harnessSessionId:t,name:vr(e.name,t),prompt:vr(e.prompt),workdir:vr(e.workdir,"(unknown)"),model:pt(e.model),reasoningEffort:Ml(e.reasoningEffort),createdAt:ra(e.createdAt),completedAt:ra(e.completedAt),status:r,killReason:Fl(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:pt(e.originAgentId),originChannel:pt(e.originChannel),originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originSessionKey:pt(e.originSessionKey),outputPath:pt(e.outputPath),harness:pt(e.harness),currentPermissionMode:kl(e.currentPermissionMode),codexApprovalPolicy:El(e.codexApprovalPolicy)}}var Lr=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;indexPath;constructor(t={}){let r=t.env??process.env;this.indexPath=t.indexPath??wl(r),r.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){try{let t=Il(this.indexPath,"utf-8"),r=JSON.parse(t);if(!Array.isArray(r))return;let n=!1;for(let o of r){let s=Ul(o);if(!s){n=!0;continue}this.persisted.set(s.harnessSessionId,s),s.sessionId&&this.idIndex.set(s.sessionId,s.harnessSessionId),s.name&&this.nameIndex.set(s.name,s.harnessSessionId)}n&&this.saveIndex()}catch{}}saveIndex(){try{gl(bl(this.indexPath),{recursive:!0});let t=this.indexPath+".tmp";Zi(t,JSON.stringify([...this.persisted.values()],null,2),"utf-8"),yl(t,this.indexPath)}catch(t){console.warn(`[SessionStore] Failed to save session index: ${ta(t)}`)}}markRunning(t){if(!t.harnessSessionId)return;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,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(r.harnessSessionId,r),this.idIndex.set(t.id,r.harnessSessionId),this.nameIndex.set(t.name,r.harnessSessionId),this.saveIndex()}hasRecordedSession(t){return this.idIndex.has(t)}persistTerminal(t){if(!t.harnessSessionId)return;let r;try{let o=Kr(ea(),`openclaw-agent-${t.id}.txt`),s=t.getOutput().join(`
|
|
49
|
+
`);s.length>0&&(Zi(o,s,"utf-8"),r=o)}catch(o){console.warn(`[SessionStore] Failed to write output file for session ${t.id}: ${ta(o)}`)}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,completedAt:t.completedAt,status:t.status,killReason:t.killReason,costUsd:t.costUsd,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,outputPath:r,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode,codexApprovalPolicy:t.codexApprovalPolicy};this.persisted.set(t.harnessSessionId,n),this.idIndex.set(t.id,t.harnessSessionId),this.nameIndex.set(t.name,t.harnessSessionId),this.saveIndex()}getLatestPersistedByName(t){let r,n=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY,i=0;for(let m of this.persisted.values()){if(m.name!==t){i++;continue}let p=m.createdAt??Number.NEGATIVE_INFINITY,f=m.completedAt??Number.NEGATIVE_INFINITY;(p>n||p===n&&f>o||p===n&&f===o&&i>s)&&(r=m,n=p,o=f,s=i),i++}return r}resolveHarnessSessionId(t,r){if(r)return r;let n=this.idIndex.get(t);if(n&&this.persisted.has(n))return n;let o=this.getLatestPersistedByName(t);if(o)return o.harnessSessionId;if(this.persisted.has(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return t}getPersistedSession(t){let r=this.persisted.get(t);if(r)return r;let n=this.idIndex.get(t);return n?this.persisted.get(n):this.getLatestPersistedByName(t)}listPersistedSessions(){return[...this.persisted.values()].sort((t,r)=>(r.completedAt??0)-(t.completedAt??0))}cleanupTmpOutputFiles(t){try{let r=ea(),n=hl(r).filter(o=>o.startsWith("openclaw-agent-")&&o.endsWith(".txt"));for(let o of n)try{let s=Kr(r,o),i=xl(s).mtimeMs;t-i>Rl&&Sl(s)}catch{}}catch{}}evictOldestPersisted(t){let r=this.listPersistedSessions();if(r.length<=t)return;let n=r.slice(t);for(let o of n){this.persisted.delete(o.harnessSessionId);for(let[s,i]of this.idIndex)i===o.harnessSessionId&&this.idIndex.delete(s);for(let[s,i]of this.nameIndex)i===o.harnessSessionId&&this.nameIndex.delete(s)}this.saveIndex()}shouldGcActiveSession(t,r,n){return!t.completedAt||!Pl.has(t.status)?!1:r-t.completedAt>n}};var Nl=new Set(["completed","failed","killed"]),jr=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(t){let r=t.costUsd??0,n=t.status;this.metrics.totalCostUsd+=r;let o=new Date(t.completedAt??t.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+r),Nl.has(n)&&this.metrics.sessionsByStatus[n]++,t.completedAt){let s=t.completedAt-t.startedAt;this.metrics.totalDurationMs+=s,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||r>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:t.id,name:t.name,costUsd:r,prompt:Ze(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 _l}from"child_process";import{randomUUID as vl}from"crypto";var na=3e4,Kl=2e3,Ll=2e4,Dr=4,Gr=class{pendingRetryTimers=new Set;clearPendingRetries(){for(let t of this.pendingRetryTimers)clearTimeout(t);this.pendingRetryTimers.clear()}getOriginSessionKey(t){let r=t.originSessionKey?.trim();return r||void 0}getOriginThreadId(t){let r=t.originThreadId;return r==null?void 0:String(r).trim()||void 0}parseNotificationRoute(t){let r=t.originChannel?.trim(),n=this.getOriginThreadId(t);if(r){let i=r.split("|").map(m=>m.trim()).filter(Boolean);if(i.length>=2){let[m,p,f]=i,A=f??p,_=f?p:void 0;if(m&&A)return{channel:m,target:A,accountId:_,threadId:n??this.parseThreadIdFromSessionKey(t.originSessionKey)}}}let o=this.getOriginSessionKey(t);if(!o)return;let s=o.match(/^agent:[^:]+:telegram:(?:direct|dm|group|channel):([^:]+)(?::topic:(\d+))?$/i);if(s?.[1])return{channel:"telegram",target:s[1],threadId:n??s[2]}}parseThreadIdFromSessionKey(t){return t?t.match(/:topic:(\d+)$/)?.[1]:void 0}retryDelayMs(t){let r=Math.max(0,t-1),n=Kl*2**r;return Math.min(n,Ll)}executeWithRetries(t,r,n=1){let o=Date.now();console.info(`[WakeDispatcher] ${r.target} ${r.phase} started attempt ${n}/${Dr} for ${r.label} session=${r.sessionId}`),_l("openclaw",t,{timeout:na},s=>{let i=Date.now()-o;if(!s){console.info(`[WakeDispatcher] ${r.target} ${r.phase} completed attempt ${n}/${Dr} for ${r.label} session=${r.sessionId} in ${i}ms`);return}let m=`[WakeDispatcher] ${r.target} ${r.phase} failed`;if(n>=Dr){console.error(`${m} after ${n} attempts for ${r.label} session=${r.sessionId} in ${i}ms: ${s.message}`),r.onFinalFailure?.();return}let p=this.retryDelayMs(n);console.error(`${m} attempt ${n}/${Dr} for ${r.label} session=${r.sessionId} in ${i}ms: ${s.message}. Retrying in ${p}ms`);let f=setTimeout(()=>{this.pendingRetryTimers.delete(f),this.executeWithRetries(t,r,n+1)},p);this.pendingRetryTimers.add(f)})}fireChatSendWithRetry(t,r,n,o,s,i=!1,m){let p=["gateway","call","chat.send","--expect-final","--timeout",String(na),"--params",JSON.stringify({sessionKey:t,message:r,deliver:i,idempotencyKey:vl()})];this.executeWithRetries(p,{label:n,sessionId:o,target:"chat.send",phase:s,onFinalFailure:m})}fireDirectNotificationWithRetry(t,r,n,o,s){let i=["message","send","--channel",t.channel,"--target",t.target,"--message",r];t.accountId&&i.push("--account",t.accountId),t.threadId&&i.push("--thread-id",t.threadId),this.executeWithRetries(i,{label:n,sessionId:o,target:"message.send",phase:"notify",onFinalFailure:s})}fireSystemEventWithRetry(t,r,n,o){let s=["system","event","--text",t,"--mode","now"];this.executeWithRetries(s,{label:r,sessionId:n,target:"system.event",phase:o})}sendUserNotification(t,r,n,o){let s=this.parseNotificationRoute(t);if(!s){this.fireSystemEventWithRetry(r,`${n}-notify-system`,o,"notify");return}this.fireDirectNotificationWithRetry(s,r,`${n}-notify`,o,()=>{this.fireSystemEventWithRetry(r,`${n}-notify-fallback`,o,"notify")})}dispatchSessionNotification(t,r){let n=this.getOriginSessionKey(t),o=r.notifyUser??(r.wakeMessage?"on-wake-fallback":"always"),s=r.userMessage?.trim(),i=r.wakeMessage?.trim();if(o==="always"&&s&&this.sendUserNotification(t,s,r.label,t.id),!!i){if(!n){o==="on-wake-fallback"&&s&&this.sendUserNotification(t,s,r.label,t.id),this.fireSystemEventWithRetry(i,`${r.label}-wake-system`,t.id,"wake");return}this.fireChatSendWithRetry(n,i,`${r.label}-wake`,t.id,"wake",!0,()=>{this.fireSystemEventWithRetry(i,`${r.label}-wake-fallback`,t.id,"wake")})}}};function Gl(){let e=process.env.OPENCLAW_CODE_AGENT_PLAN_WORKFLOW_PATH?.trim();if(e)return e;let t=Dl(sa(import.meta.url)),r=[Dn(process.cwd(),"workflows","plan-approval.lobster"),Dn(t,"..","workflows","plan-approval.lobster"),Dn(t,"..","..","workflows","plan-approval.lobster")];for(let n of r)if(jl(n))return n;return sa(new URL("../workflows/plan-approval.lobster",import.meta.url))}var Vl=Gl(),Bl=new Set(["completed","failed","killed"]),Vr=new Set(["starting","running"]),Hl=5e3,Wl=3e4;function ql(e){let t=e.trim();if(!t)return;let r=s=>typeof s=="string"&&s.trim().length>0&&/^[A-Za-z0-9._:-]+$/.test(s.trim()),n=[t];for(let s of t.split(/\r?\n/)){let i=s.trim();i.startsWith("{")&&i.endsWith("}")&&n.push(i)}for(let s of n)try{let i=JSON.parse(s),m=i?.resumeToken??i?.requiresApproval?.resumeToken??i?.details?.requiresApproval?.resumeToken;if(r(m))return m.trim()}catch{}let o=t.match(/"resumeToken"\s*:\s*"([^"]+)"/);if(o&&r(o[1]))return o[1].trim()}var Br=class{sessions=new Map;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;store;metrics;wakeDispatcher;constructor(t=20,r=50){this.maxSessions=t,this.maxPersistedSessions=r,this.store=new Lr,this.metrics=new jr,this.wakeDispatcher=new Gr}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(t){let r=new Set([...this.sessions.values()].filter(o=>Vr.has(o.status)).map(o=>o.name));if(!r.has(t))return t;let n=2;for(;r.has(`${t}-${n}`);)n++;return`${t}-${n}`}spawn(t){if([...this.sessions.values()].filter(m=>Vr.has(m.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 n=t.name||yi(t.prompt),o=this.uniqueName(n);o!==n&&console.warn(`[SessionManager] Name conflict: "${n}" \u2192 "${o}" (active session with same name exists)`);let s=new _r(t,o);this.sessions.set(s.id,s),this.metrics.incrementLaunched(),s.on("statusChange",(m,p)=>{p==="running"&&s.harnessSessionId?this.store.markRunning(s):Bl.has(p)&&this.onSessionTerminal(s)}),s.on("turnEnd",(m,p)=>{this.onTurnEnd(s,p)}),s.start();let i=`\u{1F680} [${s.name}] Launched | ${s.workdir} | ${s.model??"default"}`;return this.notifySession(s,i,"launch"),s}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 m=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=Ze(m,200);this.triggerFailedEvent(t,p);return}let r=`$${(t.costUsd??0).toFixed(2)}`,n=_e(t.duration),s={user:"by agent/user","idle-timeout":`idle ${h.idleTimeoutMinutes??15}min`,shutdown:"gateway shutdown",unknown:""}[t.killReason]||"",i=`Killed${s?` (${s})`:""}`;this.notifySession(t,`\u26D4 [${t.name}] ${i} | ${r} | ${n}`)}persistSession(t){this.store.hasRecordedSession(t.id)||this.metrics.recordSession(t),this.store.persistTerminal(t)}getMetrics(){return this.metrics.getMetrics()}recordSessionMetrics(t){this.metrics.recordSession(t)}notifySession(t,r,n="notification"){this.dispatchSessionNotification(t,{label:n,userMessage:r,notifyUser:"always"})}dispatchSessionNotification(t,r){this.wakeDispatcher.dispatchSessionNotification(t,r)}runLobsterApproval(t,r){let n=JSON.stringify({session_id:t.id,session_name:t.name,plan_summary:r}),o=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"run",pipeline:Vl,argsJson:n,timeoutMs:0})];oa("openclaw",o,{timeout:Wl},(s,i,m)=>{if(s){console.error(`[SessionManager] Lobster launch failed for session=${t.id}: ${s.message}`),this.notifySession(t,`\u{1F4CB} [${t.name}] Plan ready \u2014 Lobster gate failed, please review manually:
|
|
49
50
|
|
|
50
|
-
${
|
|
51
|
-
${f}`);if(
|
|
52
|
-
${f}`.trim().substring(0,200);console.warn(`[SessionManager] Lobster response missing resume token for session=${t.id}: ${
|
|
53
|
-
`))})}resumeLobsterApproval(t,
|
|
54
|
-
`);return
|
|
55
|
-
`),o=`$${(t.costUsd??0).toFixed(2)}`,s=
|
|
56
|
-
`),
|
|
57
|
-
`);this.dispatchSessionNotification(t,{label:"failed",userMessage:
|
|
51
|
+
${Ze(r,800)}`);return}let p=typeof i=="string"?i:String(i??""),f=typeof m=="string"?m:String(m??""),A=ql(`${p}
|
|
52
|
+
${f}`);if(!A){let ie=`${p}
|
|
53
|
+
${f}`.trim().substring(0,200);console.warn(`[SessionManager] Lobster response missing resume token for session=${t.id}: ${ie}`)}A&&(t.lobsterResumeToken=A);let _=[`\u{1F4CB} [${t.name}] Plan ready for approval`,"",Ze(r,1200),"",`Session: ${t.name} (${t.id})`,"",'To approve: reply "approve"',"To reject: reply with feedback"];this.notifySession(t,_.join(`
|
|
54
|
+
`))})}resumeLobsterApproval(t,r){let n=r?3e4:1e4;return new Promise((o,s)=>{let i=["--json","invoke","--tool","lobster","--args-json",JSON.stringify({action:"resume",token:t,approve:r})];oa("openclaw",i,{timeout:n},m=>{m?(console.error(`[SessionManager] Lobster resume failed (approve=${r}): ${m.message}`),s(m)):o()})})}debounceWaitingEvent(t){let r=Date.now(),n=this.lastWaitingEventTimestamps.get(t);return n&&r-n<Hl?!1:(this.lastWaitingEventTimestamps.set(t,r),!0)}originThreadLine(t){return t.originThreadId!=null?`Session origin thread: ${t.originThreadId}`:""}extractLastOutputLine(t){return t.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(t,r=1e3){let n=t.getOutput(20).join(`
|
|
55
|
+
`);return n.length>r?Si(n,r):n}triggerAgentEvent(t){let r=this.getOutputPreview(t),n=["Coding agent session completed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Output preview:",r,"","[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${t.id}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW \u2014 do not wait for user input.","3. Notify the user with a summary of what was done."].join(`
|
|
56
|
+
`),o=`$${(t.costUsd??0).toFixed(2)}`,s=_e(t.duration),i=`\u2705 [${t.name}] Completed | ${o} | ${s}`;this.dispatchSessionNotification(t,{label:"completed",userMessage:i,wakeMessage:n,notifyUser:"always"})}triggerFailedEvent(t,r){let n=this.getOutputPreview(t),o=n.trim()?["","Output preview:",n]:[],s=["Coding agent session failed.",`Name: ${t.name} | ID: ${t.id}`,`Status: ${t.status}`,this.originThreadLine(t),"","Failure summary:",r,...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
|
+
`),i=`$${(t.costUsd??0).toFixed(2)}`,m=_e(t.duration),p=[`\u274C [${t.name}] Failed | ${i} | ${m}`,` \u26A0\uFE0F ${r}`].join(`
|
|
58
|
+
`);this.dispatchSessionNotification(t,{label:"failed",userMessage:p,wakeMessage:s,notifyUser:"always"})}triggerWaitingForInputEvent(t){if(!this.debounceWaitingEvent(t.id))return;let r=this.getOutputPreview(t),n=t.pendingPlanApproval,o=n?`\u{1F4CB} [${t.name}] Plan ready for review:
|
|
58
59
|
|
|
59
|
-
${
|
|
60
|
+
${r}
|
|
60
61
|
|
|
61
|
-
Reply to approve or provide feedback.`:`\u{1F514} [${t.name}] Waiting for input`,s;if(
|
|
62
|
+
Reply to approve or provide feedback.`:`\u{1F514} [${t.name}] Waiting for input`,s;if(n){let i=h.planApproval??"delegate";if(i==="ask"){this.runLobsterApproval(t,r);return}else i==="delegate"?s=["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"Permission mode: plan \u2192 will switch to bypassPermissions on approval","","\u26A0\uFE0F YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","\u2501\u2501\u2501 STEP 1 (MANDATORY): Read the full plan \u2501\u2501\u2501",`Call agent_output(session='${t.id}', full=true) to read the FULL plan output.`,"The preview below is truncated \u2014 you MUST read the full output before making any decision.","","Preview (truncated):",r,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Notify the user \u2501\u2501\u2501","After reading the full plan, use the message tool to send the user a summary that includes:","- What files/components will be changed","- Risk level (low/medium/high) and why","- Scope: does this match the original task or has it expanded?","- Any concerns or assumptions the plan makes","This message creates accountability \u2014 you cannot approve blindly.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","You are the delegated decision-maker. Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- You have sent the user the summary message","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,"If escalating: tell the user you need their decision and WAIT for his explicit response.",`To request changes: agent_respond(session='${t.id}', message='<your feedback>') \u2014 do NOT set approve=true. The agent will revise the plan.`].join(`
|
|
62
63
|
`):s=["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`].join(`
|
|
63
|
-
`)}else s=[`[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:",
|
|
64
|
-
`);this.dispatchSessionNotification(t,{label:
|
|
65
|
-
`);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:
|
|
64
|
+
`)}else s=[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" \u2192 auto-respond. For ALL other questions \u2192 forward the agent's EXACT question to the user. Do NOT add your own analysis, commentary, or interpretation. Do NOT "nudge" or "poke" the session.]`,"",`${t.multiTurn?"Multi-turn session":"Session"} is waiting for input.`,`Name: ${t.name} | ID: ${t.id}`,this.originThreadLine(t),"","Last output:",r,"",`Use agent_respond(session='${t.id}', message='...') to send a reply, or agent_output(session='${t.id}', full: true) to see full context before deciding.`].join(`
|
|
65
|
+
`);this.dispatchSessionNotification(t,{label:n?"plan-approval":"waiting",userMessage:o,wakeMessage:s,notifyUser:n?"always":"on-wake-fallback"})}onTurnEnd(t,r){if(r||t.pendingPlanApproval){this.triggerWaitingForInputEvent(t);return}this.shouldEmitTurnCompleteWake(t)&&this.triggerTurnCompleteEventWithSignal(t)}shouldEmitTurnCompleteWake(t){let r=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===r?!1:(this.lastTurnCompleteMarkers.set(t.id,r),!0)}shouldEmitTerminalWake(t){let r=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===r?!1:(this.lastTerminalWakeMarkers.set(t.id,r),!0)}triggerTurnCompleteEventWithSignal(t){let r=this.getOutputPreview(t),n=$r(r),o=`$${(t.costUsd??0).toFixed(2)}`,s=n?"yes":"no",i=`\u{1F504} [${t.name}] Turn done | ${o} | Waiting input: ${s}`,m=["Coding agent session turn ended.",`Name: ${t.name}`,`ID: ${t.id}`,`Status: ${t.status}`,"",`Looks like waiting for user input: ${s}`,"","Last output (~20 lines):",r,...this.originThreadLine(t)?["",this.originThreadLine(t)]:[]].join(`
|
|
66
|
+
`);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:i,wakeMessage:m,notifyUser:"always"})}resolve(t){let r=this.sessions.get(t);if(r)return r;let n=[...this.sessions.values()].filter(s=>s.name===t);if(n.length===0)return;let o=n.filter(s=>Vr.has(s.status));return o.length>0?o.sort((s,i)=>i.startedAt-s.startedAt)[0]:n.sort((s,i)=>i.startedAt-s.startedAt)[0]}get(t){return this.sessions.get(t)}list(t){let r=[...this.sessions.values()];return t&&t!=="all"&&(r=r.filter(n=>n.status===t)),r.sort((n,o)=>o.startedAt-n.startedAt)}kill(t,r){let n=this.sessions.get(t);return n?(n.kill(r??"user"),!0):!1}killAll(t="user"){for(let r of this.sessions.values())Vr.has(r.status)&&this.kill(r.id,t);this.wakeDispatcher.clearPendingRetries()}resolveHarnessSessionId(t){let r=this.resolve(t);return this.store.resolveHarnessSessionId(t,r?.harnessSessionId)}getPersistedSession(t){return this.store.getPersistedSession(t)}listPersistedSessions(){return this.store.listPersistedSessions()}cleanup(){let t=Date.now(),r=(h.sessionGcAgeMinutes??1440)*6e4;for(let[n,o]of this.sessions)this.store.shouldGcActiveSession(o,t,r)&&(this.persistSession(o),this.sessions.delete(n),this.lastWaitingEventTimestamps.delete(n),this.lastTurnCompleteMarkers.delete(n),this.lastTerminalWakeMarkers.delete(n));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}};function zO(e){let t=null,r=null;e.registerTool(n=>hi(n),{optional:!1}),e.registerTool(n=>Ti(n),{optional:!1}),e.registerTool(n=>bi(n),{optional:!1}),e.registerTool(n=>Ai(n),{optional:!1}),e.registerTool(n=>Pi(n),{optional:!1}),e.registerTool(n=>Oi(n),{optional:!1}),Ri(e),Ci(e),Mi(e),ki(e),Ei(e),Fi(e),$i(e),e.registerService({id:"openclaw-code-agent",start:n=>{let o=e.pluginConfig??e.getConfig?.()??{};fi(o),t=new Br(h.maxSessions,h.maxPersistedSessions),_n(t),r=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{t&&t.killAll("shutdown"),r&&clearInterval(r),r=null,t=null,_n(null)}})}export{zO as register};
|
package/package.json
CHANGED
|
@@ -209,7 +209,7 @@ Use `agent_kill(reason: "completed")` when:
|
|
|
209
209
|
- After a turn completes without a question, the session is immediately **paused** (killed with reason `done`, auto-resumable).
|
|
210
210
|
- On the next `agent_respond` to a completed or idle-killed session, the plugin **auto-resumes** by spawning a new session with the same session ID — conversation context is preserved.
|
|
211
211
|
- Sessions idle for `idleTimeoutMinutes` (default: 15 min) are killed with reason `idle-timeout` and also auto-resume on next respond.
|
|
212
|
-
- Sessions killed
|
|
212
|
+
- Sessions killed for any reason except `startup-timeout` auto-resume on next `agent_respond`. This includes user-killed sessions (`agent_kill`), shutdown-killed sessions (gateway restart), and idle-timeout sessions.
|
|
213
213
|
|
|
214
214
|
### Timeouts
|
|
215
215
|
|
|
@@ -246,6 +246,20 @@ Notifications are routed to the Telegram thread/topic where the session was laun
|
|
|
246
246
|
|
|
247
247
|
Sessions start in `plan` mode by default. When you reply with **only** an approval keyword as the **entire message** (`"go ahead"`, `"implement"`, `"looks good"`, `"approved"`, `"lgtm"`, `"do it"`, `"proceed"`, `"execute"`, `"ship it"`), the plugin switches the session to `bypassPermissions` mode. The message must contain **only** the keyword — extra text will prevent the switch. To approve and also give instructions, send the approval keyword first, then send implementation details as a separate follow-up message.
|
|
248
248
|
|
|
249
|
+
### Permission escalation with `approve: true`
|
|
250
|
+
|
|
251
|
+
The `approve` parameter on `agent_respond` escalates session permissions to `bypassPermissions`. It works in two scenarios:
|
|
252
|
+
|
|
253
|
+
1. **Plan mode approval**: When a session has a pending plan approval (after `ExitPlanMode` / `set_permission_mode`), `approve: true` approves the plan and switches to `bypassPermissions`.
|
|
254
|
+
2. **`acceptEdits` / `default` mode escalation**: When a session is in `acceptEdits` or `default` mode and keeps prompting for shell/exec command permissions, `approve: true` escalates to `bypassPermissions` to skip all remaining prompts.
|
|
255
|
+
|
|
256
|
+
If the session is already in `bypassPermissions` mode, `approve: true` is a no-op. In `plan` mode without a pending plan, it is ignored.
|
|
257
|
+
|
|
258
|
+
```
|
|
259
|
+
# Escalate an acceptEdits session that keeps prompting for bash permissions
|
|
260
|
+
agent_respond(session: "fix-auth", message: "proceed", approve: true)
|
|
261
|
+
```
|
|
262
|
+
|
|
249
263
|
### Plan approval modes
|
|
250
264
|
|
|
251
265
|
The `planApproval` config controls how the orchestrator handles plan-approval events:
|
|
@@ -324,5 +338,5 @@ When a session completes, keep summaries brief:
|
|
|
324
338
|
| `agent_sessions` | List sessions | `status` (all/running/completed/failed/killed) |
|
|
325
339
|
| `agent_output` | Read the output | `session`, `full`, `lines` |
|
|
326
340
|
| `agent_kill` | Kill or complete a session | `session`, `reason` (`"completed"` or omit) |
|
|
327
|
-
| `agent_respond` | Send a follow-up | `session`, `message`, `interrupt` |
|
|
341
|
+
| `agent_respond` | Send a follow-up | `session`, `message`, `interrupt`, `approve` |
|
|
328
342
|
| `agent_stats` | Usage metrics | none |
|