openclaw-code-agent 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,26 @@
1
1
  # OpenClaw Code Agent
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/openclaw-code-agent.svg)](https://www.npmjs.com/package/openclaw-code-agent)
4
+ [![npm downloads](https://img.shields.io/npm/dm/openclaw-code-agent.svg)](https://www.npmjs.com/package/openclaw-code-agent)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
+
3
7
  An [OpenClaw](https://openclaw.com) plugin that lets AI agents orchestrate coding agent sessions as managed background processes. Launch, monitor, and interact with multiple concurrent coding sessions directly from Telegram, Discord, or any OpenClaw-supported messaging platform — without leaving your chat interface.
4
8
 
9
+ ## Why?
10
+
11
+ Built-in ACP is useful as a relay bridge for simple one-shot tasks, but it stops short of full orchestration. `openclaw-code-agent` adds an async control layer around coding sessions so you can review plans before execution, persist and resume work later, and run multiple sessions concurrently. It also supports multiple harnesses instead of binding you to a single agent integration. The result is closer to background job orchestration for coding agents than a direct chat-to-agent relay.
12
+
13
+ ## Demo
14
+ <img src="assets/ask-readme.gif" alt="Ask mode demo showing plan review and approval before execution">
15
+
16
+ *Plan review and approval in ask mode: the agent pauses for your decision before executing.*
17
+
18
+ ### Autonomous mode (delegate)
19
+
20
+ <img src="assets/delegate-readme.gif" alt="Delegate mode demo showing autonomous execution with selective escalation">
21
+
22
+ *In delegate mode, the orchestrator auto-approves low-risk plans and only escalates when needed.*
23
+
5
24
  ## Supported Agents
6
25
 
7
26
  | Agent | Status | Notes |
@@ -41,6 +60,7 @@ An [OpenClaw](https://openclaw.com) plugin that lets AI agents orchestrate codin
41
60
 
42
61
  ```bash
43
62
  openclaw plugins install openclaw-code-agent
63
+ openclaw plugins enable openclaw-code-agent
44
64
  openclaw gateway restart
45
65
  ```
46
66
 
@@ -80,7 +100,7 @@ Replace `my-bot` with your Telegram bot account name and `123456789` with your T
80
100
 
81
101
  | Tool | Description | Key Parameters |
82
102
  |------|-------------|----------------|
83
- | `agent_launch` | Start a new coding agent session in background | `prompt`, `name`, `workdir`, `model`, `resume_session_id`, `fork_session`, `permission_mode`, `harness`, `notify_on_turn_end` |
103
+ | `agent_launch` | Start a new coding agent session in background | `prompt`, `name`, `workdir`, `model`, `resume_session_id`, `fork_session`, `permission_mode`, `harness` |
84
104
  | `agent_respond` | Send a follow-up message to a running session | `session`, `message`, `interrupt`, `approve`, `userInitiated` |
85
105
  | `agent_kill` | Terminate or complete a running session | `session`, `reason` |
86
106
  | `agent_output` | Read buffered output from a session | `session`, `lines`, `full` |
@@ -178,7 +198,7 @@ Set values in `~/.openclaw/openclaw.json` under `plugins.entries["openclaw-code-
178
198
  | `permissionMode` | `string` | `"plan"` | `"default"` / `"plan"` / `"acceptEdits"` / `"bypassPermissions"` |
179
199
  | `idleTimeoutMinutes` | `number` | `15` | Idle timeout before auto-kill |
180
200
  | `sessionGcAgeMinutes` | `number` | `1440` | TTL for completed/failed/killed runtime sessions before GC eviction |
181
- | `maxPersistedSessions` | `number` | `50` | Max completed sessions kept for resume |
201
+ | `maxPersistedSessions` | `number` | `10000` | Max completed sessions kept for resume; the 24h GC TTL (`sessionGcAgeMinutes`) is the primary retention control |
182
202
  | `planApproval` | `string` | `"delegate"` | `"approve"` (orchestrator can auto-approve) / `"ask"` (always forward to user) / `"delegate"` (orchestrator decides) |
183
203
  | `defaultHarness` | `string` | `"claude-code"` | Default harness for new sessions (`"claude-code"` / `"codex"`) |
184
204
  | `model` | `string` | — | Codex-only model override for new sessions (for example `"gpt-5.3-codex"`). Used when no explicit `model` is passed to `agent_launch`; falls back to `defaultModel` if unset |
@@ -206,11 +226,6 @@ Permission modes are shared at the plugin API, but each harness maps them differ
206
226
  - `OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS` — comma-separated extra directories for Codex bypass mode
207
227
  - `OPENCLAW_CODEX_HEARTBEAT_MS` — Codex activity heartbeat interval in milliseconds (default `10000`)
208
228
 
209
- ### `notify_on_turn_end` (`notifyOnTurnEnd`)
210
-
211
- `agent_launch` accepts `notify_on_turn_end` (default `true`). When `false`, turn-end wake notifications are suppressed for that session.
212
- Internal config field: `notifyOnTurnEnd`.
213
-
214
229
  ### Session Lifecycle + GC
215
230
 
216
231
  - Active sessions live in runtime memory (`SessionManager.sessions`)
@@ -357,6 +372,13 @@ openclaw-code-agent/
357
372
 
358
373
  ---
359
374
 
375
+ ## Troubleshooting
376
+
377
+ - Plugin installed but the gateway does not see it yet: run `openclaw gateway restart`.
378
+ - Notifications are not arriving: verify `fallbackChannel` uses the exact format `"telegram|bot-name|chat-id"` in `~/.openclaw/openclaw.json`.
379
+
380
+ ---
381
+
360
382
  ## Contributing
361
383
 
362
384
  Contributions are welcome! Please:
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
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 Rp}from"fs";var z={};zn(z,{HasPropertyKey:()=>tn,IsArray:()=>K,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:()=>L});function tn(e,t){return t in e}function Yn(e){return w(e)&&!K(e)&&!Ne(e)&&Symbol.asyncIterator in e}function K(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)&&!K(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 L(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 K(e)?qi(e):et(e)?zi(e):Ne(e)?Yi(e):Ut(e)?Xi(e):w(e)?Ji(e):e}function E(e){return nn(e)}function ct(e,t){return t===void 0?E(e):E({...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,d){return e.ExactOptionalPropertyTypes?d in a:a[d]!==void 0}e.IsExactOptionalProperty=t;function n(a){let d=Dr(a);return e.AllowArrayObject?d:d&&!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 d=Vr(a);return e.AllowNullVoid?d||a===null:d}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 K(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 E(n);default:return n}}var V=class extends Error{constructor(t){super(t)}};var j=Symbol.for("TypeBox.Transform"),xe=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[xe]==="Readonly"}function ee(e){return w(e)&&e[W]==="Optional"}function er(e){return h(e,"Any")}function tr(e){return h(e,"Argument")}function Te(e){return h(e,"Array")}function tt(e){return h(e,"AsyncIterator")}function nt(e){return h(e,"BigInt")}function Ke(e){return h(e,"Boolean")}function be(e){return h(e,"Computed")}function Ae(e){return h(e,"Constructor")}function ea(e){return h(e,"Date")}function we(e){return h(e,"Function")}function Oe(e){return h(e,"Integer")}function U(e){return h(e,"Intersect")}function rt(e){return h(e,"Iterator")}function h(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 h(e,"Literal")}function ue(e){return h(e,"MappedKey")}function k(e){return h(e,"MappedResult")}function De(e){return h(e,"Never")}function ta(e){return h(e,"Not")}function Nt(e){return h(e,"Null")}function Re(e){return h(e,"Number")}function v(e){return h(e,"Object")}function ot(e){return h(e,"Promise")}function st(e){return h(e,"Record")}function N(e){return h(e,"Ref")}function nr(e){return h(e,"RegExp")}function Le(e){return h(e,"String")}function Kt(e){return h(e,"Symbol")}function me(e){return h(e,"TemplateLiteral")}function na(e){return h(e,"This")}function Ge(e){return w(e)&&j in e}function de(e){return h(e,"Tuple")}function Lt(e){return h(e,"Undefined")}function y(e){return h(e,"Union")}function ra(e){return h(e,"Uint8Array")}function oa(e){return h(e,"Unknown")}function sa(e){return h(e,"Unsafe")}function ia(e){return h(e,"Void")}function aa(e){return w(e)&&p in e&&C(e[p])}function pe(e){return er(e)||tr(e)||Te(e)||Ke(e)||nt(e)||tt(e)||be(e)||Ae(e)||ea(e)||we(e)||Oe(e)||U(e)||rt(e)||ae(e)||ue(e)||k(e)||De(e)||ta(e)||Nt(e)||Re(e)||v(e)||ot(e)||st(e)||N(e)||nr(e)||Le(e)||Kt(e)||me(e)||na(e)||de(e)||Lt(e)||y(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:()=>So,IsRecursive:()=>ga,IsRef:()=>xo,IsRegExp:()=>To,IsSchema:()=>B,IsString:()=>bo,IsSymbol:()=>Ao,IsTemplateLiteral:()=>wo,IsThis:()=>Oo,IsTransform:()=>Ro,IsTuple:()=>Po,IsUint8Array:()=>Mo,IsUndefined:()=>Co,IsUnion:()=>ir,IsUnionLiteral:()=>Ia,IsUnknown:()=>Fo,IsUnsafe:()=>Eo,IsVoid:()=>ko,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 vt(e){return L(e)||$t(e)}function M(e){return L(e)||ie(e)}function sr(e){return L(e)||_e(e)}function O(e){return L(e)||C(e)}function ma(e){return L(e)||C(e)&&or(e)&&Hr(e)}function da(e){return L(e)||C(e)&&or(e)}function qr(e){return L(e)||B(e)}function pa(e){return w(e)&&e[xe]==="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)&&vt(e.exclusiveMaximum)&&vt(e.exclusiveMinimum)&&vt(e.maximum)&&vt(e.minimum)&&vt(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)&&K(e.parameters)&&e.parameters.every(t=>B(t))}function to(e){return I(e,"Constructor")&&e.type==="Constructor"&&O(e.$id)&&K(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)&&K(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")&&K(e.allOf)&&e.allOf.every(t=>B(t)&&!Ro(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")&&K(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 So(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 xo(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)&&ma(e.pattern)&&da(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 Ro(e){return w(e)&&j in e}function Po(e){return I(e,"Tuple")&&e.type==="array"&&O(e.$id)&&ie(e.minItems)&&ie(e.maxItems)&&e.minItems===e.maxItems&&(L(e.items)&&L(e.additionalItems)&&e.minItems===0||K(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)&&K(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 Eo(e){return I(e,"Unsafe")}function ko(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)||So(e)||xo(e)||To(e)||bo(e)||Ao(e)||wo(e)||Oo(e)||Po(e)||Co(e)||ir(e)||Mo(e)||Fo(e)||Eo(e)||ko(e)||$o(e))}var ar="(true|false)",Dt="(0|[1-9][0-9]*)",ur="(.*)",ha="(?!.*)",Fl=`^${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 Sa(e,t){return e.reduce((n,r)=>ya(n,r),t)}function Ko(e){return e.length===1?e[0]:e.length>1?Sa(e.slice(1),e[0]):[]}function Lo(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 vo(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 xa(e,t){let{[t]:n,...r}=e;return r}function _(e,t){return t.reduce((n,r)=>xa(n,r),e)}function S(e){return u({[p]:"Never",not:{}},e)}function x(e){return u({[p]:"MappedResult",properties:e})}function It(e,t,n){return u({[p]:"Constructor",type:"Constructor",parameters:e,returns:t},n)}function Ee(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 ke(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 mr(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function je(e,t){return mr(e,t,"(")}function Vt(e,t){return mr(e,t,")")}function Do(e,t){return mr(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 Ra(e){return e.slice(1,e.length-1)}function Pa(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 d=s;d<o.length;d++)if(je(o,d)&&(a+=1),Vt(o,d)&&(a-=1),a===0)return[s,d];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),d=e.slice(s,a+1);r.push(ht(d)),o=a}else{let[s,a]=n(e,o),d=e.slice(s,a);d.length>0&&r.push(ht(d)),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(Ra(e)):Pa(e)?Ma(e):Ca(e)?Fa(e):{type:"const",const:wa(e)}}function yt(e){return ht(e.slice(1,e.length-1))}var dr=class extends V{};function Ea(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 ka(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 Ea(e)||$a(e)?!1:ka(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 dr("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 mn(e){return u({[p]:"Boolean",type:"boolean"},e)}function St(e){return u({[p]:"BigInt",type:"bigint"},e)}function ge(e){return u({[p]:"Number",type:"number"},e)}function Pe(e){return u({[p]:"String",type:"string"},e)}function*Ka(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield mn():t==="number"?yield ge():t==="bigint"?yield St():t==="string"?yield Pe():yield(()=>{let n=t.split("|").map(r=>b(r.trim()));return n.length===0?S():n.length===1?n[0]:ke(n)})()}function*La(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=Ka(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=La(e.slice(t));return yield*[n,...r]}yield b(e)}function Bo(e){return[...cr(e)]}var lr=class extends V{};function va(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ho(e,t){return me(e)?e.pattern.slice(1,e.pattern.length-1):y(e)?`(${e.anyOf.map(n=>Ho(n,t)).join("|")})`:Re(e)?`${t}${Dt}`:Oe(e)?`${t}${Dt}`:nt(e)?`${t}${Dt}`:Le(e)?`${t}${ur}`:ae(e)?`${t}${va(e.const.toString())}`:Ke(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 ke(n)}function dn(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(me(e)?ja(e):y(e)?Da(e.anyOf):ae(e)?Ga(e.const):Re(e)?["[number]"]:Oe(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 x(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 ke(qa(zo(e,t)))}function Ya(e,t){return t in e?e[t]:t==="[number]"?ke(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):y(e)?za(e.anyOf,t):de(e)?Ya(e.items??[],t):Te(e)?Xa(e.items,t):v(e)?Ja(e.properties,t):S()}function gr(e,t){return t.map(n=>Yo(e,n))}function qo(e,t){return ke(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 k(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],E(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 x(r)}function xt(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 R=nu;function cn(e,t){return u({[p]:"Promise",type:"Promise",item:e},t)}function ru(e){return u(_(e,[xe]))}function ou(e){return u({...e,[xe]:"Readonly"})}function su(e,t){return t===!1?ru(e):ou(e)}function ne(e,t){let n=t??!0;return k(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 x(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]):x(t)}function uu(e){return{[e]:b(e)}}function mu(e){let t={};for(let n of e)t[n]=b(n);return t}function du(e,t){return _o(t,e)?uu(e):mu(t)}function pu(e,t){let n=du(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,[xe]))):k(t)?Qo(e,t.properties):ue(t)?pu(e,t.keys):Ae(t)?It(Ht(e,t.parameters),he(e,t.returns),n):we(t)?Ee(Ht(e,t.parameters),he(e,t.returns),n):tt(t)?gt(he(e,t.items),n):rt(t)?xt(he(e,t.items),n):U(t)?X(Ht(e,t.allOf),n):y(t)?A(Ht(e,t.anyOf),n):de(t)?Ie(Ht(e,t.items??[]),n):v(t)?R(cu(e,t.properties),n):Te(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 R(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 k(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 x(n)}function Wt(e,t={}){let n=e.every(o=>v(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 Su(e){return e.every(t=>ee(t))}function xu(e){return _(e,[W])}function ts(e){return e.map(t=>ee(t)?xu(t):t)}function Tu(e,t){return Su(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 Ru(e){return Tt(e)}function ns(e){return e.map(t=>Tt(t))}function Tt(e,t){return u(be(e)?bu(e.target,e.parameters):U(e)?wu(e.allOf):y(e)?Ou(e.anyOf):ot(e)?Ru(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 Pu(e){let t=rs(e);return Lo(t)}function Cu(e){let t=rs(e);return Ko(t)}function Mu(e){return e.map((t,n)=>n.toString())}function Fu(e){return["[number]"]}function Eu(e){return globalThis.Object.getOwnPropertyNames(e)}function ku(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)?Pu(e.allOf):y(e)?Cu(e.anyOf):de(e)?Mu(e.items??[]):Te(e)?Fu(e.items):v(e)?Eu(e.properties):st(e)?ku(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=Ku(n),o=ke(r);return u(o,t)}function Ku(e){return e.map(t=>t==="[number]"?ge():b(t))}function bt(e,t){return be(e)?Uu(e.target,e.parameters):N(e)?_u(e.$ref):k(e)?os(e,t):Nu(e,t)}function Lu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=bt(e[r],E(t));return n}function vu(e,t){return Lu(e.properties,t)}function os(e,t){let n=vu(e,t);return x(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 R(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):K(e)?ne(Ie(Bu(e))):Ne(e)?hn():et(e)?ln():w(e)?yn(R(Hu(e)),t):Xn(e)?yn(Ee([],qe()),t):L(e)?In():Qn(e)?fn():Zn(e)?gn():$t(e)?St():ie(e)?b(e):_e(e)?b(e):C(e)?b(e):R({})}function is(e,t){return u(Ir(e,!0),t)}function as(e,t){return Ae(e)?Ie(e.parameters,t):S(t)}function us(e,t){if(L(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{},m;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(m||(m={}));function ye(e){return e===m.False?e:m.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)?Sn(e,t):i.IsUnion(t)?br(e,t):i.IsUnknown(t)?Ss(e,t):i.IsAny(t)?Tr(e,t):At("StructuralRight")}function Tr(e,t){return m.True}function Wu(e,t){return i.IsIntersect(t)?Sn(e,t):i.IsUnion(t)&&t.anyOf.some(n=>i.IsAny(n)||i.IsUnknown(n))?m.True:i.IsUnion(t)?m.Union:i.IsUnknown(t)||i.IsAny(t)?m.True:m.Union}function qu(e,t){return i.IsUnknown(e)?m.False:i.IsAny(e)?m.Union:i.IsNever(e)?m.True:m.False}function zu(e,t){return i.IsObject(t)&&xn(t)?m.True:D(t)?G(e,t):i.IsArray(t)?ye(P(e.items,t.items)):m.False}function Yu(e,t){return D(t)?G(e,t):i.IsAsyncIterator(t)?ye(P(e.items,t.items)):m.False}function Xu(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsBigInt(t)?m.True:m.False}function ls(e,t){return i.IsLiteralBoolean(e)||i.IsBoolean(e)?m.True:m.False}function Ju(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsBoolean(t)?m.True:m.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?m.False:e.parameters.every((n,r)=>ye(P(t.parameters[r],n))===m.True)?ye(P(e.returns,t.returns)):m.False:m.False}function Zu(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsDate(t)?m.True:m.False}function em(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsFunction(t)?e.parameters.length>t.parameters.length?m.False:e.parameters.every((n,r)=>ye(P(t.parameters[r],n))===m.True)?ye(P(e.returns,t.returns)):m.False:m.False}function fs(e,t){return i.IsLiteral(e)&&z.IsNumber(e.const)||i.IsNumber(e)||i.IsInteger(e)?m.True:m.False}function tm(e,t){return i.IsInteger(t)||i.IsNumber(t)?m.True:D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):m.False}function Sn(e,t){return t.allOf.every(n=>P(e,n)===m.True)?m.True:m.False}function nm(e,t){return e.allOf.some(n=>P(n,t)===m.True)?m.True:m.False}function rm(e,t){return D(t)?G(e,t):i.IsIterator(t)?ye(P(e.items,t.items)):m.False}function om(e,t){return i.IsLiteral(t)&&t.const===e.const?m.True:D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(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):m.False}function gs(e,t){return m.False}function sm(e,t){return m.True}function ms(e){let[t,n]=[e,0];for(;i.IsNot(t);)t=t.not,n+=1;return n%2===0?t:qe()}function im(e,t){return i.IsNot(e)?P(ms(e),t):i.IsNot(t)?P(e,ms(t)):At("Invalid fallthrough for Not")}function am(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsNull(t)?m.True:m.False}function Is(e,t){return i.IsLiteralNumber(e)||i.IsNumber(e)||i.IsInteger(e)?m.True:m.False}function um(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsInteger(t)||i.IsNumber(t)?m.True:m.False}function re(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function ds(e){return xn(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 mm(e){return re(e,0)}function dm(e){return re(e,0)}function pm(e){return xn(e)}function cm(e){let t=ge();return re(e,0)||re(e,1)&&"length"in e.properties&&ye(P(e.properties.length,t))===m.True}function lm(e){return re(e,0)}function xn(e){let t=ge();return re(e,0)||re(e,1)&&"length"in e.properties&&ye(P(e.properties.length,t))===m.True}function fm(e){let t=Ee([He()],He());return re(e,0)||re(e,1)&&"then"in e.properties&&ye(P(e.properties.then,t))===m.True}function hs(e,t){return P(e,t)===m.False||i.IsOptional(e)&&!i.IsOptional(t)?m.False:m.True}function J(e,t){return i.IsUnknown(e)?m.False:i.IsAny(e)?m.Union:i.IsNever(e)||i.IsLiteralString(e)&&ds(t)||i.IsLiteralNumber(e)&&hr(t)||i.IsLiteralBoolean(e)&&cs(t)||i.IsSymbol(e)&&ps(t)||i.IsBigInt(e)&&mm(t)||i.IsString(e)&&ds(t)||i.IsSymbol(e)&&ps(t)||i.IsNumber(e)&&hr(t)||i.IsInteger(e)&&hr(t)||i.IsBoolean(e)&&cs(t)||i.IsUint8Array(e)&&pm(t)||i.IsDate(e)&&dm(t)||i.IsConstructor(e)&&lm(t)||i.IsFunction(e)&&cm(t)?m.True:i.IsRecord(e)&&i.IsString(Sr(e))?t[fe]==="Record"?m.True:m.False:i.IsRecord(e)&&i.IsNumber(Sr(e))&&re(t,0)?m.True:m.False}function gm(e,t){return D(t)?G(e,t):i.IsRecord(t)?Se(e,t):i.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!i.IsOptional(t.properties[n]))return m.False;if(i.IsOptional(t.properties[n]))return m.True;if(hs(e.properties[n],t.properties[n])===m.False)return m.False}return m.True})():m.False}function Im(e,t){return D(t)?G(e,t):i.IsObject(t)&&fm(t)?m.True:i.IsPromise(t)?ye(P(e.item,t.item)):m.False}function Sr(e){return Ve in e.patternProperties?ge():Be in e.patternProperties?Pe():At("Unknown record key pattern")}function xr(e){return Ve in e.patternProperties?e.patternProperties[Ve]:Be in e.patternProperties?e.patternProperties[Be]:At("Unable to get record value schema")}function Se(e,t){let[n,r]=[Sr(t),xr(t)];return i.IsLiteralString(e)&&i.IsNumber(n)&&ye(P(e,r))===m.True?m.True:i.IsUint8Array(e)&&i.IsNumber(n)||i.IsString(e)&&i.IsNumber(n)||i.IsArray(e)&&i.IsNumber(n)?P(e,r):i.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(hs(r,e.properties[o])===m.False)return m.False;return m.True})():m.False}function hm(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?P(xr(e),xr(t)):m.False}function ym(e,t){let n=i.IsRegExp(e)?Pe():e,r=i.IsRegExp(t)?Pe():t;return P(n,r)}function ys(e,t){return i.IsLiteral(e)&&z.IsString(e.const)||i.IsString(e)?m.True:m.False}function Sm(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsString(t)?m.True:m.False}function xm(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsSymbol(t)?m.True:m.False}function Tm(e,t){return i.IsTemplateLiteral(e)?P(at(e),t):i.IsTemplateLiteral(t)?P(e,at(t)):At("Invalid fallthrough for TemplateLiteral")}function bm(e,t){return i.IsArray(t)&&e.items!==void 0&&e.items.every(n=>P(n,t.items)===m.True)}function Am(e,t){return i.IsNever(e)?m.True:i.IsUnknown(e)?m.False:i.IsAny(e)?m.Union:m.False}function wm(e,t){return D(t)?G(e,t):i.IsObject(t)&&xn(t)||i.IsArray(t)&&bm(e,t)?m.True:i.IsTuple(t)?z.IsUndefined(e.items)&&!z.IsUndefined(t.items)||!z.IsUndefined(e.items)&&z.IsUndefined(t.items)?m.False:z.IsUndefined(e.items)&&!z.IsUndefined(t.items)||e.items.every((n,r)=>P(n,t.items[r])===m.True)?m.True:m.False:m.False}function Om(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsUint8Array(t)?m.True:m.False}function Rm(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsVoid(t)?Mm(e,t):i.IsUndefined(t)?m.True:m.False}function br(e,t){return t.anyOf.some(n=>P(e,n)===m.True)?m.True:m.False}function Pm(e,t){return e.anyOf.every(n=>P(n,t)===m.True)?m.True:m.False}function Ss(e,t){return m.True}function Cm(e,t){return i.IsNever(t)?gs(e,t):i.IsIntersect(t)?Sn(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)?Am(e,t):i.IsObject(t)?J(e,t):i.IsUnknown(t)?m.True:m.False}function Mm(e,t){return i.IsUndefined(e)||i.IsUndefined(e)?m.True:m.False}function Fm(e,t){return i.IsIntersect(t)?Sn(e,t):i.IsUnion(t)?br(e,t):i.IsUnknown(t)?Ss(e,t):i.IsAny(t)?Tr(e,t):i.IsObject(t)?J(e,t):i.IsVoid(t)?m.True:m.False}function P(e,t){return i.IsTemplateLiteral(e)||i.IsTemplateLiteral(t)?Tm(e,t):i.IsRegExp(e)||i.IsRegExp(t)?ym(e,t):i.IsNot(e)||i.IsNot(t)?im(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)?em(e,t):i.IsInteger(e)?tm(e,t):i.IsIntersect(e)?nm(e,t):i.IsIterator(e)?rm(e,t):i.IsLiteral(e)?om(e,t):i.IsNever(e)?sm(e,t):i.IsNull(e)?am(e,t):i.IsNumber(e)?um(e,t):i.IsObject(e)?gm(e,t):i.IsRecord(e)?hm(e,t):i.IsString(e)?Sm(e,t):i.IsSymbol(e)?xm(e,t):i.IsTuple(e)?wm(e,t):i.IsPromise(e)?Im(e,t):i.IsUint8Array(e)?Om(e,t):i.IsUndefined(e)?Rm(e,t):i.IsUnion(e)?Pm(e,t):i.IsUnknown(e)?Cm(e,t):i.IsVoid(e)?Fm(e,t):At(`Unknown left type operand '${e[p]}'`)}function ze(e,t){return P(e,t)}function Em(e,t,n,r,o){let s={};for(let a of globalThis.Object.getOwnPropertyNames(e))s[a]=wt(e[a],t,n,r,E(o));return s}function km(e,t,n,r,o){return Em(e.properties,t,n,r,o)}function xs(e,t,n,r,o){let s=km(e,t,n,r,o);return x(s)}function $m(e,t,n,r){let o=ze(e,t);return o===m.Union?A([n,r]):o===m.True?n:r}function wt(e,t,n,r,o){return k(e)?xs(e,t,n,r,o):ue(e)?u(Ts(e,t,n,r,o)):u($m(e,t,n,r),o)}function Um(e,t,n,r,o){return{[e]:wt(b(e),t,n,r,E(o))}}function _m(e,t,n,r,o){return e.reduce((s,a)=>({...s,...Um(a,t,n,r,o)}),{})}function Nm(e,t,n,r,o){return _m(e.keys,t,n,r,o)}function Ts(e,t,n,r,o){let s=Nm(e,t,n,r,o);return x(s)}function bs(e,t){return Ot(at(e),t)}function Km(e,t){let n=e.filter(r=>ze(r,t)===m.False);return n.length===1?n[0]:A(n)}function Ot(e,t,n={}){return me(e)?u(bs(e,t),n):k(e)?u(As(e,t),n):u(y(e)?Km(e.anyOf,t):ze(e,t)!==m.False?S():e,n)}function Lm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ot(e[r],t);return n}function vm(e,t){return Lm(e.properties,t)}function As(e,t){let n=vm(e,t);return x(n)}function ws(e,t){return Rt(at(e),t)}function jm(e,t){let n=e.filter(r=>ze(r,t)!==m.False);return n.length===1?n[0]:A(n)}function Rt(e,t,n){return me(e)?u(ws(e,t),n):k(e)?u(Os(e,t),n):u(y(e)?jm(e.anyOf,t):ze(e,t)!==m.False?e:S(),n)}function Dm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Rt(e[r],t);return n}function Gm(e,t){return Dm(e.properties,t)}function Os(e,t){let n=Gm(e,t);return x(n)}function Rs(e,t){return Ae(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 R(r,{...n,[fe]:"Record"})}function Vm(e,t,n){return Go(e)?Ar(te(e),t,n):ut(e.pattern,t,n)}function Bm(e,t,n){return Ar(te(A(e)),t,n)}function Hm(e,t,n){return Ar([e.toString()],t,n)}function Wm(e,t,n){return ut(e.source,t,n)}function qm(e,t,n){let r=L(e.pattern)?Be:e.pattern;return ut(r,t,n)}function zm(e,t,n){return ut(Be,t,n)}function Ym(e,t,n){return ut(Uo,t,n)}function Xm(e,t,n){return R({true:t,false:t},n)}function Jm(e,t,n){return ut(Ve,t,n)}function Qm(e,t,n){return ut(Ve,t,n)}function bn(e,t,n={}){return y(e)?Bm(e.anyOf,t,n):me(e)?Vm(e,t,n):ae(e)?Hm(e.const,t,n):Ke(e)?Xm(e,t,n):Oe(e)?Jm(e,t,n):Re(e)?Qm(e,t,n):nr(e)?Wm(e,t,n):Le(e)?qm(e,t,n):er(e)?zm(e,t,n):De(e)?Ym(e,t,n):S(n)}function An(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function Ps(e){let t=An(e);return t===Be?Pe():t===Ve?ge():Pe({pattern:t})}function wn(e){return e.patternProperties[An(e)]}function Zm(e,t){return t.parameters=zt(e,t.parameters),t.returns=Ce(e,t.returns),t}function ed(e,t){return t.parameters=zt(e,t.parameters),t.returns=Ce(e,t.returns),t}function td(e,t){return t.allOf=zt(e,t.allOf),t}function nd(e,t){return t.anyOf=zt(e,t.anyOf),t}function rd(e,t){return L(t.items)||(t.items=zt(e,t.items)),t}function od(e,t){return t.items=Ce(e,t.items),t}function sd(e,t){return t.items=Ce(e,t.items),t}function id(e,t){return t.items=Ce(e,t.items),t}function ad(e,t){return t.item=Ce(e,t.item),t}function ud(e,t){let n=cd(e,t.properties);return{...t,...R(n)}}function md(e,t){let n=Ce(e,Ps(t)),r=Ce(e,wn(t)),o=bn(n,r);return{...t,...o}}function dd(e,t){return t.index in e?e[t.index]:qe()}function pd(e,t){let n=lt(t),r=ee(t),o=Ce(e,t);return n&&r?Tn(o):n&&!r?ne(o):!n&&r?Y(o):o}function cd(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:pd(e,t[r])}),{})}function zt(e,t){return t.map(n=>Ce(e,n))}function Ce(e,t){return Ae(t)?Zm(e,t):we(t)?ed(e,t):U(t)?td(e,t):y(t)?nd(e,t):de(t)?rd(e,t):Te(t)?od(e,t):tt(t)?sd(e,t):rt(t)?id(e,t):ot(t)?ad(e,t):v(t)?ud(e,t):st(t)?md(e,t):tr(t)?dd(e,t):t}function Cs(e,t){return Ce(t,ct(e))}function Ms(e){return u({[p]:"Integer",type:"integer"},e)}function ld(e,t,n){return{[e]:Me(b(e),t,E(n))}}function fd(e,t,n){return e.reduce((o,s)=>({...o,...ld(s,t,n)}),{})}function gd(e,t,n){return fd(e.keys,t,n)}function Fs(e,t,n){let r=gd(e,t,n);return x(r)}function Id(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function hd(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function yd(e){return e.toUpperCase()}function Sd(e){return e.toLowerCase()}function xd(e,t,n){let r=yt(e.pattern);if(!it(r))return{...e,pattern:Es(e.pattern,t)};let a=[...Bt(r)].map(f=>b(f)),d=ks(a,t),c=A(d);return dn([c],n)}function Es(e,t){return typeof e=="string"?t==="Uncapitalize"?Id(e):t==="Capitalize"?hd(e):t==="Uppercase"?yd(e):t==="Lowercase"?Sd(e):e:e.toString()}function ks(e,t){return e.map(n=>Me(n,t))}function Me(e,t,n={}){return ue(e)?Fs(e,t,n):me(e)?xd(e,t,n):y(e)?A(ks(e.anyOf,t),n):ae(e)?b(Es(e.const,t),n):u(e,n)}function $s(e,t={}){return Me(e,"Capitalize",t)}function Us(e,t={}){return Me(e,"Lowercase",t)}function _s(e,t={}){return Me(e,"Uncapitalize",t)}function Ns(e,t={}){return Me(e,"Uppercase",t)}function Td(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ye(e[o],t,E(n));return r}function bd(e,t,n){return Td(e.properties,t,n)}function Ks(e,t,n){let r=bd(e,t,n);return x(r)}function Ad(e,t){return e.map(n=>wr(n,t))}function wd(e,t){return e.map(n=>wr(n,t))}function Od(e,t){let{[t]:n,...r}=e;return r}function Rd(e,t){return t.reduce((n,r)=>Od(n,r),e)}function Pd(e,t,n){let r=_(e,[j,"$id","required","properties"]),o=Rd(n,t);return R(o,r)}function Cd(e){let t=e.reduce((n,r)=>on(r)?[...n,b(r)]:n,[]);return A(t)}function wr(e,t){return U(e)?X(Ad(e.allOf,t)):y(e)?A(wd(e.anyOf,t)):v(e)?Pd(e,t,e.properties):R({})}function Ye(e,t,n){let r=K(t)?Cd(t):t,o=pe(t)?te(t):t,s=N(e),a=N(t);return k(e)?Ks(e,o,n):ue(t)?Ls(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 Md(e,t,n){return{[t]:Ye(e,[t],E(n))}}function Fd(e,t,n){return t.reduce((r,o)=>({...r,...Md(e,o,n)}),{})}function Ed(e,t,n){return Fd(e,t.keys,n)}function Ls(e,t,n){let r=Ed(e,t,n);return x(r)}function kd(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Xe(e[o],t,E(n));return r}function $d(e,t,n){return kd(e.properties,t,n)}function vs(e,t,n){let r=$d(e,t,n);return x(r)}function Ud(e,t){return e.map(n=>Or(n,t))}function _d(e,t){return e.map(n=>Or(n,t))}function Nd(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function Kd(e,t,n){let r=_(e,[j,"$id","required","properties"]),o=Nd(n,t);return R(o,r)}function Ld(e){let t=e.reduce((n,r)=>on(r)?[...n,b(r)]:n,[]);return A(t)}function Or(e,t){return U(e)?X(Ud(e.allOf,t)):y(e)?A(_d(e.anyOf,t)):v(e)?Kd(e,t,e.properties):R({})}function Xe(e,t,n){let r=K(t)?Ld(t):t,o=pe(t)?te(t):t,s=N(e),a=N(t);return k(e)?vs(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 vd(e,t,n){return{[t]:Xe(e,[t],E(n))}}function jd(e,t,n){return t.reduce((r,o)=>({...r,...vd(e,o,n)}),{})}function Dd(e,t,n){return jd(e,t.keys,n)}function js(e,t,n){let r=Dd(e,t,n);return x(r)}function Gd(e,t){return F("Partial",[F(e,t)])}function Vd(e){return F("Partial",[$e(e)])}function Bd(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=Y(e[n]);return t}function Hd(e,t){let n=_(e,[j,"$id","required","properties"]),r=Bd(t);return R(r,n)}function Ds(e){return e.map(t=>Gs(t))}function Gs(e){return be(e)?Gd(e.target,e.parameters):N(e)?Vd(e.$ref):U(e)?X(Ds(e.allOf)):y(e)?A(Ds(e.anyOf)):v(e)?Hd(e,e.properties):nt(e)||Ke(e)||Oe(e)||ae(e)||Nt(e)||Re(e)||Le(e)||Kt(e)||Lt(e)?e:R({})}function Pt(e,t){return k(e)?Vs(e,t):u({...Gs(e),...t})}function Wd(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Pt(e[r],E(t));return n}function qd(e,t){return Wd(e.properties,t)}function Vs(e,t){let n=qd(e,t);return x(n)}function zd(e,t){return F("Required",[F(e,t)])}function Yd(e){return F("Required",[$e(e)])}function Xd(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=_(e[n],[W]);return t}function Jd(e,t){let n=_(e,[j,"$id","required","properties"]),r=Xd(t);return R(r,n)}function Bs(e){return e.map(t=>Hs(t))}function Hs(e){return be(e)?zd(e.target,e.parameters):N(e)?Yd(e.$ref):U(e)?X(Bs(e.allOf)):y(e)?A(Bs(e.anyOf)):v(e)?Jd(e,e.properties):nt(e)||Ke(e)||Oe(e)||ae(e)||Nt(e)||Re(e)||Le(e)||Kt(e)||Lt(e)?e:R({})}function Ct(e,t){return k(e)?Ws(e,t):u({...Hs(e),...t})}function Qd(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ct(e[r],t);return n}function Zd(e,t){return Qd(e.properties,t)}function Ws(e,t){let n=Zd(e,t);return x(n)}function ep(e,t){return t.map(n=>N(n)?Rr(e,n.$ref):ce(e,n))}function Rr(e,t){return t in e?N(e[t])?Rr(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 Pt(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 mp(e,t){return ft(ce(e,t))}function dp(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 Ee(Yt(e,t),ce(e,n))}function lp(e,t){return X(Yt(e,t))}function fp(e,t){return xt(ce(e,t))}function gp(e,t){return R(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)?{...Rr(e,t.$ref),[j]:t[j]}:t}function yp(e,t){return Ie(Yt(e,t))}function Sp(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,[xe])),t):Ge(t)?u(hp(e,t),t):Te(t)?u(mp(e,t.items),t):tt(t)?u(dp(e,t.items),t):be(t)?u(up(e,t.target,t.parameters)):Ae(t)?u(pp(e,t.parameters,t.returns),t):we(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):v(t)?u(gp(e,t.properties),t):st(t)?u(Ip(e,t)):de(t)?u(yp(e,t.items||[]),t):y(t)?u(Sp(e,t.anyOf),t):t}function xp(e,t){return t in e?ce(e,e[t]):S()}function qs(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:xp(e,n)}),{})}var Pr=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 Pr(e)}function Ys(e,t){return u({[p]:"Not",not:e},t)}function Xs(e,t){return we(e)?Ie(e.parameters,t):S()}var Tp=0;function Js(e,t={}){L(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:y(e)?e.anyOf:de(e)?e.items??[]:[]}function Zs(e){return bp(e)}function ei(e,t){return we(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:()=>vo,Array:()=>ft,AsyncIterator:()=>gt,Awaited:()=>Tt,BigInt:()=>St,Boolean:()=>mn,Capitalize:()=>$s,Composite:()=>ss,Const:()=>is,Constructor:()=>It,ConstructorParameters:()=>as,Date:()=>ln,Enum:()=>us,Exclude:()=>Ot,Extends:()=>wt,Extract:()=>Rt,Function:()=>Ee,Index:()=>We,InstanceType:()=>Rs,Instantiate:()=>Cs,Integer:()=>Ms,Intersect:()=>X,Iterator:()=>xt,KeyOf:()=>bt,Literal:()=>b,Lowercase:()=>Us,Mapped:()=>Zo,Module:()=>zs,Never:()=>S,Not:()=>Ys,Null:()=>fn,Number:()=>ge,Object:()=>R,Omit:()=>Ye,Optional:()=>Y,Parameters:()=>Xs,Partial:()=>Pt,Pick:()=>Xe,Promise:()=>cn,Readonly:()=>ne,ReadonlyOptional:()=>Tn,Record:()=>bn,Recursive:()=>Js,Ref:()=>$e,RegExp:()=>Qs,Required:()=>Ct,Rest:()=>Zs,ReturnType:()=>ei,String:()=>Pe,Symbol:()=>gn,TemplateLiteral:()=>dn,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 Er(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 T={maxSessions:5,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:50,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",reasoningEffort:"medium"};function si(e){T={maxSessions:e.maxSessions??5,defaultModel:e.defaultModel,model:e.model,reasoningEffort:e.reasoningEffort??"medium",defaultWorkdir:e.defaultWorkdir,idleTimeoutMinutes:e.idleTimeoutMinutes??15,sessionGcAgeMinutes:e.sessionGcAgeMinutes??1440,maxPersistedSessions:e.maxPersistedSessions??50,fallbackChannel:e.fallbackChannel,agentChannels:e.agentChannels,maxAutoResponds:e.maxAutoResponds??10,permissionMode:e.permissionMode??"plan",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}`:T.fallbackChannel??"unknown"}function Ft(e){return e?.messageThreadId??void 0}function Jt(e){let t=T.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 Et(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 Pp(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."})),notify_on_turn_end:l.Optional(l.Boolean({description:"Send wake notifications at every turn end. Defaults to true."})),permission_mode:l.Optional(l.Union([l.Literal("default"),l.Literal("plan"),l.Literal("acceptEdits"),l.Literal("bypassPermissions")],{description:"Permission mode for the session. 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||T.defaultWorkdir||process.cwd();if(!Rp(r))return{content:[{type:"text",text:`Error: Working directory does not exist: ${r}`}]};try{let o=n.harness??T.defaultHarness,s=o==="codex"?T.model??T.defaultModel:T.defaultModel,a=n.resume_session_id,d=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:$}=Et({requestedResumeSessionId:a,activeSession:d?{harnessSessionId:d.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:T.reasoningEffort,systemPrompt:n.system_prompt,allowedTools:n.allowed_tools,resumeSessionId:f,forkSession:f?n.fork_session:!1,multiTurn:!n.multi_turn_disabled,notifyOnTurnEnd:n.notify_on_turn_end??!0,permissionMode:n.permission_mode,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,Fe=["Session launched successfully.",` Name: ${Z.name}`,` ID: ${Z.id}`,` Dir: ${r}`,` Model: ${Z.model??"default"}`,` Prompt: "${q}"`];return n.resume_session_id&&(Fe.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),$&&Fe.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),Fe.push(n.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),Fe.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:Fe.join(`
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 Rp}from"fs";var z={};zn(z,{HasPropertyKey:()=>tn,IsArray:()=>K,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:()=>L});function tn(e,t){return t in e}function Yn(e){return w(e)&&!K(e)&&!Ne(e)&&Symbol.asyncIterator in e}function K(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)&&!K(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 L(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 K(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,d){return e.ExactOptionalPropertyTypes?d in a:a[d]!==void 0}e.IsExactOptionalProperty=t;function n(a){let d=Dr(a);return e.AllowArrayObject?d:d&&!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 d=Vr(a);return e.AllowNullVoid?d||a===null:d}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 K(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"),xe=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[xe]==="Readonly"}function ee(e){return w(e)&&e[W]==="Optional"}function er(e){return h(e,"Any")}function tr(e){return h(e,"Argument")}function Te(e){return h(e,"Array")}function tt(e){return h(e,"AsyncIterator")}function nt(e){return h(e,"BigInt")}function Ke(e){return h(e,"Boolean")}function be(e){return h(e,"Computed")}function Ae(e){return h(e,"Constructor")}function ea(e){return h(e,"Date")}function we(e){return h(e,"Function")}function Oe(e){return h(e,"Integer")}function U(e){return h(e,"Intersect")}function rt(e){return h(e,"Iterator")}function h(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 h(e,"Literal")}function ue(e){return h(e,"MappedKey")}function E(e){return h(e,"MappedResult")}function De(e){return h(e,"Never")}function ta(e){return h(e,"Not")}function Nt(e){return h(e,"Null")}function Re(e){return h(e,"Number")}function v(e){return h(e,"Object")}function ot(e){return h(e,"Promise")}function st(e){return h(e,"Record")}function N(e){return h(e,"Ref")}function nr(e){return h(e,"RegExp")}function Le(e){return h(e,"String")}function Kt(e){return h(e,"Symbol")}function me(e){return h(e,"TemplateLiteral")}function na(e){return h(e,"This")}function Ge(e){return w(e)&&j in e}function de(e){return h(e,"Tuple")}function Lt(e){return h(e,"Undefined")}function y(e){return h(e,"Union")}function ra(e){return h(e,"Uint8Array")}function oa(e){return h(e,"Unknown")}function sa(e){return h(e,"Unsafe")}function ia(e){return h(e,"Void")}function aa(e){return w(e)&&p in e&&C(e[p])}function pe(e){return er(e)||tr(e)||Te(e)||Ke(e)||nt(e)||tt(e)||be(e)||Ae(e)||ea(e)||we(e)||Oe(e)||U(e)||rt(e)||ae(e)||ue(e)||E(e)||De(e)||ta(e)||Nt(e)||Re(e)||v(e)||ot(e)||st(e)||N(e)||nr(e)||Le(e)||Kt(e)||me(e)||na(e)||de(e)||Lt(e)||y(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:()=>So,IsRecursive:()=>ga,IsRef:()=>xo,IsRegExp:()=>To,IsSchema:()=>B,IsString:()=>bo,IsSymbol:()=>Ao,IsTemplateLiteral:()=>wo,IsThis:()=>Oo,IsTransform:()=>Ro,IsTuple:()=>Po,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 vt(e){return L(e)||$t(e)}function M(e){return L(e)||ie(e)}function sr(e){return L(e)||_e(e)}function O(e){return L(e)||C(e)}function ma(e){return L(e)||C(e)&&or(e)&&Hr(e)}function da(e){return L(e)||C(e)&&or(e)}function qr(e){return L(e)||B(e)}function pa(e){return w(e)&&e[xe]==="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)&&vt(e.exclusiveMaximum)&&vt(e.exclusiveMinimum)&&vt(e.maximum)&&vt(e.minimum)&&vt(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)&&K(e.parameters)&&e.parameters.every(t=>B(t))}function to(e){return I(e,"Constructor")&&e.type==="Constructor"&&O(e.$id)&&K(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)&&K(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")&&K(e.allOf)&&e.allOf.every(t=>B(t)&&!Ro(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")&&K(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 So(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 xo(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)&&ma(e.pattern)&&da(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 Ro(e){return w(e)&&j in e}function Po(e){return I(e,"Tuple")&&e.type==="array"&&O(e.$id)&&ie(e.minItems)&&ie(e.maxItems)&&e.minItems===e.maxItems&&(L(e.items)&&L(e.additionalItems)&&e.minItems===0||K(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)&&K(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)||So(e)||xo(e)||To(e)||bo(e)||Ao(e)||wo(e)||Oo(e)||Po(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="(?!.*)",Fl=`^${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 Sa(e,t){return e.reduce((n,r)=>ya(n,r),t)}function Ko(e){return e.length===1?e[0]:e.length>1?Sa(e.slice(1),e[0]):[]}function Lo(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 vo(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 xa(e,t){let{[t]:n,...r}=e;return r}function _(e,t){return t.reduce((n,r)=>xa(n,r),e)}function S(e){return u({[p]:"Never",not:{}},e)}function x(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 mr(e,t,n){return e[t]===n&&e.charCodeAt(t-1)!==92}function je(e,t){return mr(e,t,"(")}function Vt(e,t){return mr(e,t,")")}function Do(e,t){return mr(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 Ra(e){return e.slice(1,e.length-1)}function Pa(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 d=s;d<o.length;d++)if(je(o,d)&&(a+=1),Vt(o,d)&&(a-=1),a===0)return[s,d];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),d=e.slice(s,a+1);r.push(ht(d)),o=a}else{let[s,a]=n(e,o),d=e.slice(s,a);d.length>0&&r.push(ht(d)),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(Ra(e)):Pa(e)?Ma(e):Ca(e)?Fa(e):{type:"const",const:wa(e)}}function yt(e){return ht(e.slice(1,e.length-1))}var dr=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 dr("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 mn(e){return u({[p]:"Boolean",type:"boolean"},e)}function St(e){return u({[p]:"BigInt",type:"bigint"},e)}function ge(e){return u({[p]:"Number",type:"number"},e)}function Pe(e){return u({[p]:"String",type:"string"},e)}function*Ka(e){let t=e.trim().replace(/"|'/g,"");return t==="boolean"?yield mn():t==="number"?yield ge():t==="bigint"?yield St():t==="string"?yield Pe():yield(()=>{let n=t.split("|").map(r=>b(r.trim()));return n.length===0?S():n.length===1?n[0]:Ee(n)})()}function*La(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=Ka(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=La(e.slice(t));return yield*[n,...r]}yield b(e)}function Bo(e){return[...cr(e)]}var lr=class extends V{};function va(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ho(e,t){return me(e)?e.pattern.slice(1,e.pattern.length-1):y(e)?`(${e.anyOf.map(n=>Ho(n,t)).join("|")})`:Re(e)?`${t}${Dt}`:Oe(e)?`${t}${Dt}`:nt(e)?`${t}${Dt}`:Le(e)?`${t}${ur}`:ae(e)?`${t}${va(e.const.toString())}`:Ke(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 dn(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(me(e)?ja(e):y(e)?Da(e.anyOf):ae(e)?Ga(e.const):Re(e)?["[number]"]:Oe(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 x(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):y(e)?za(e.anyOf,t):de(e)?Ya(e.items??[],t):Te(e)?Xa(e.items,t):v(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 x(r)}function xt(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 R=nu;function cn(e,t){return u({[p]:"Promise",type:"Promise",item:e},t)}function ru(e){return u(_(e,[xe]))}function ou(e){return u({...e,[xe]:"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 x(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]):x(t)}function uu(e){return{[e]:b(e)}}function mu(e){let t={};for(let n of e)t[n]=b(n);return t}function du(e,t){return _o(t,e)?uu(e):mu(t)}function pu(e,t){let n=du(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,[xe]))):E(t)?Qo(e,t.properties):ue(t)?pu(e,t.keys):Ae(t)?It(Ht(e,t.parameters),he(e,t.returns),n):we(t)?ke(Ht(e,t.parameters),he(e,t.returns),n):tt(t)?gt(he(e,t.items),n):rt(t)?xt(he(e,t.items),n):U(t)?X(Ht(e,t.allOf),n):y(t)?A(Ht(e,t.anyOf),n):de(t)?Ie(Ht(e,t.items??[]),n):v(t)?R(cu(e,t.properties),n):Te(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 R(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 x(n)}function Wt(e,t={}){let n=e.every(o=>v(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 Su(e){return e.every(t=>ee(t))}function xu(e){return _(e,[W])}function ts(e){return e.map(t=>ee(t)?xu(t):t)}function Tu(e,t){return Su(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 Ru(e){return Tt(e)}function ns(e){return e.map(t=>Tt(t))}function Tt(e,t){return u(be(e)?bu(e.target,e.parameters):U(e)?wu(e.allOf):y(e)?Ou(e.anyOf):ot(e)?Ru(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 Pu(e){let t=rs(e);return Lo(t)}function Cu(e){let t=rs(e);return Ko(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)?Pu(e.allOf):y(e)?Cu(e.anyOf):de(e)?Mu(e.items??[]):Te(e)?Fu(e.items):v(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=Ku(n),o=Ee(r);return u(o,t)}function Ku(e){return e.map(t=>t==="[number]"?ge():b(t))}function bt(e,t){return be(e)?Uu(e.target,e.parameters):N(e)?_u(e.$ref):E(e)?os(e,t):Nu(e,t)}function Lu(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=bt(e[r],k(t));return n}function vu(e,t){return Lu(e.properties,t)}function os(e,t){let n=vu(e,t);return x(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 R(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):K(e)?ne(Ie(Bu(e))):Ne(e)?hn():et(e)?ln():w(e)?yn(R(Hu(e)),t):Xn(e)?yn(ke([],qe()),t):L(e)?In():Qn(e)?fn():Zn(e)?gn():$t(e)?St():ie(e)?b(e):_e(e)?b(e):C(e)?b(e):R({})}function is(e,t){return u(Ir(e,!0),t)}function as(e,t){return Ae(e)?Ie(e.parameters,t):S(t)}function us(e,t){if(L(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{},m;(function(e){e[e.Union=0]="Union",e[e.True=1]="True",e[e.False=2]="False"})(m||(m={}));function ye(e){return e===m.False?e:m.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)?Sn(e,t):i.IsUnion(t)?br(e,t):i.IsUnknown(t)?Ss(e,t):i.IsAny(t)?Tr(e,t):At("StructuralRight")}function Tr(e,t){return m.True}function Wu(e,t){return i.IsIntersect(t)?Sn(e,t):i.IsUnion(t)&&t.anyOf.some(n=>i.IsAny(n)||i.IsUnknown(n))?m.True:i.IsUnion(t)?m.Union:i.IsUnknown(t)||i.IsAny(t)?m.True:m.Union}function qu(e,t){return i.IsUnknown(e)?m.False:i.IsAny(e)?m.Union:i.IsNever(e)?m.True:m.False}function zu(e,t){return i.IsObject(t)&&xn(t)?m.True:D(t)?G(e,t):i.IsArray(t)?ye(P(e.items,t.items)):m.False}function Yu(e,t){return D(t)?G(e,t):i.IsAsyncIterator(t)?ye(P(e.items,t.items)):m.False}function Xu(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsBigInt(t)?m.True:m.False}function ls(e,t){return i.IsLiteralBoolean(e)||i.IsBoolean(e)?m.True:m.False}function Ju(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsBoolean(t)?m.True:m.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?m.False:e.parameters.every((n,r)=>ye(P(t.parameters[r],n))===m.True)?ye(P(e.returns,t.returns)):m.False:m.False}function Zu(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsDate(t)?m.True:m.False}function em(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsFunction(t)?e.parameters.length>t.parameters.length?m.False:e.parameters.every((n,r)=>ye(P(t.parameters[r],n))===m.True)?ye(P(e.returns,t.returns)):m.False:m.False}function fs(e,t){return i.IsLiteral(e)&&z.IsNumber(e.const)||i.IsNumber(e)||i.IsInteger(e)?m.True:m.False}function tm(e,t){return i.IsInteger(t)||i.IsNumber(t)?m.True:D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):m.False}function Sn(e,t){return t.allOf.every(n=>P(e,n)===m.True)?m.True:m.False}function nm(e,t){return e.allOf.some(n=>P(n,t)===m.True)?m.True:m.False}function rm(e,t){return D(t)?G(e,t):i.IsIterator(t)?ye(P(e.items,t.items)):m.False}function om(e,t){return i.IsLiteral(t)&&t.const===e.const?m.True:D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(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):m.False}function gs(e,t){return m.False}function sm(e,t){return m.True}function ms(e){let[t,n]=[e,0];for(;i.IsNot(t);)t=t.not,n+=1;return n%2===0?t:qe()}function im(e,t){return i.IsNot(e)?P(ms(e),t):i.IsNot(t)?P(e,ms(t)):At("Invalid fallthrough for Not")}function am(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsNull(t)?m.True:m.False}function Is(e,t){return i.IsLiteralNumber(e)||i.IsNumber(e)||i.IsInteger(e)?m.True:m.False}function um(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsInteger(t)||i.IsNumber(t)?m.True:m.False}function re(e,t){return Object.getOwnPropertyNames(e.properties).length===t}function ds(e){return xn(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 mm(e){return re(e,0)}function dm(e){return re(e,0)}function pm(e){return xn(e)}function cm(e){let t=ge();return re(e,0)||re(e,1)&&"length"in e.properties&&ye(P(e.properties.length,t))===m.True}function lm(e){return re(e,0)}function xn(e){let t=ge();return re(e,0)||re(e,1)&&"length"in e.properties&&ye(P(e.properties.length,t))===m.True}function fm(e){let t=ke([He()],He());return re(e,0)||re(e,1)&&"then"in e.properties&&ye(P(e.properties.then,t))===m.True}function hs(e,t){return P(e,t)===m.False||i.IsOptional(e)&&!i.IsOptional(t)?m.False:m.True}function J(e,t){return i.IsUnknown(e)?m.False:i.IsAny(e)?m.Union:i.IsNever(e)||i.IsLiteralString(e)&&ds(t)||i.IsLiteralNumber(e)&&hr(t)||i.IsLiteralBoolean(e)&&cs(t)||i.IsSymbol(e)&&ps(t)||i.IsBigInt(e)&&mm(t)||i.IsString(e)&&ds(t)||i.IsSymbol(e)&&ps(t)||i.IsNumber(e)&&hr(t)||i.IsInteger(e)&&hr(t)||i.IsBoolean(e)&&cs(t)||i.IsUint8Array(e)&&pm(t)||i.IsDate(e)&&dm(t)||i.IsConstructor(e)&&lm(t)||i.IsFunction(e)&&cm(t)?m.True:i.IsRecord(e)&&i.IsString(Sr(e))?t[fe]==="Record"?m.True:m.False:i.IsRecord(e)&&i.IsNumber(Sr(e))&&re(t,0)?m.True:m.False}function gm(e,t){return D(t)?G(e,t):i.IsRecord(t)?Se(e,t):i.IsObject(t)?(()=>{for(let n of Object.getOwnPropertyNames(t.properties)){if(!(n in e.properties)&&!i.IsOptional(t.properties[n]))return m.False;if(i.IsOptional(t.properties[n]))return m.True;if(hs(e.properties[n],t.properties[n])===m.False)return m.False}return m.True})():m.False}function Im(e,t){return D(t)?G(e,t):i.IsObject(t)&&fm(t)?m.True:i.IsPromise(t)?ye(P(e.item,t.item)):m.False}function Sr(e){return Ve in e.patternProperties?ge():Be in e.patternProperties?Pe():At("Unknown record key pattern")}function xr(e){return Ve in e.patternProperties?e.patternProperties[Ve]:Be in e.patternProperties?e.patternProperties[Be]:At("Unable to get record value schema")}function Se(e,t){let[n,r]=[Sr(t),xr(t)];return i.IsLiteralString(e)&&i.IsNumber(n)&&ye(P(e,r))===m.True?m.True:i.IsUint8Array(e)&&i.IsNumber(n)||i.IsString(e)&&i.IsNumber(n)||i.IsArray(e)&&i.IsNumber(n)?P(e,r):i.IsObject(e)?(()=>{for(let o of Object.getOwnPropertyNames(e.properties))if(hs(r,e.properties[o])===m.False)return m.False;return m.True})():m.False}function hm(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?P(xr(e),xr(t)):m.False}function ym(e,t){let n=i.IsRegExp(e)?Pe():e,r=i.IsRegExp(t)?Pe():t;return P(n,r)}function ys(e,t){return i.IsLiteral(e)&&z.IsString(e.const)||i.IsString(e)?m.True:m.False}function Sm(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsString(t)?m.True:m.False}function xm(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsSymbol(t)?m.True:m.False}function Tm(e,t){return i.IsTemplateLiteral(e)?P(at(e),t):i.IsTemplateLiteral(t)?P(e,at(t)):At("Invalid fallthrough for TemplateLiteral")}function bm(e,t){return i.IsArray(t)&&e.items!==void 0&&e.items.every(n=>P(n,t.items)===m.True)}function Am(e,t){return i.IsNever(e)?m.True:i.IsUnknown(e)?m.False:i.IsAny(e)?m.Union:m.False}function wm(e,t){return D(t)?G(e,t):i.IsObject(t)&&xn(t)||i.IsArray(t)&&bm(e,t)?m.True:i.IsTuple(t)?z.IsUndefined(e.items)&&!z.IsUndefined(t.items)||!z.IsUndefined(e.items)&&z.IsUndefined(t.items)?m.False:z.IsUndefined(e.items)&&!z.IsUndefined(t.items)||e.items.every((n,r)=>P(n,t.items[r])===m.True)?m.True:m.False:m.False}function Om(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsUint8Array(t)?m.True:m.False}function Rm(e,t){return D(t)?G(e,t):i.IsObject(t)?J(e,t):i.IsRecord(t)?Se(e,t):i.IsVoid(t)?Mm(e,t):i.IsUndefined(t)?m.True:m.False}function br(e,t){return t.anyOf.some(n=>P(e,n)===m.True)?m.True:m.False}function Pm(e,t){return e.anyOf.every(n=>P(n,t)===m.True)?m.True:m.False}function Ss(e,t){return m.True}function Cm(e,t){return i.IsNever(t)?gs(e,t):i.IsIntersect(t)?Sn(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)?Am(e,t):i.IsObject(t)?J(e,t):i.IsUnknown(t)?m.True:m.False}function Mm(e,t){return i.IsUndefined(e)||i.IsUndefined(e)?m.True:m.False}function Fm(e,t){return i.IsIntersect(t)?Sn(e,t):i.IsUnion(t)?br(e,t):i.IsUnknown(t)?Ss(e,t):i.IsAny(t)?Tr(e,t):i.IsObject(t)?J(e,t):i.IsVoid(t)?m.True:m.False}function P(e,t){return i.IsTemplateLiteral(e)||i.IsTemplateLiteral(t)?Tm(e,t):i.IsRegExp(e)||i.IsRegExp(t)?ym(e,t):i.IsNot(e)||i.IsNot(t)?im(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)?em(e,t):i.IsInteger(e)?tm(e,t):i.IsIntersect(e)?nm(e,t):i.IsIterator(e)?rm(e,t):i.IsLiteral(e)?om(e,t):i.IsNever(e)?sm(e,t):i.IsNull(e)?am(e,t):i.IsNumber(e)?um(e,t):i.IsObject(e)?gm(e,t):i.IsRecord(e)?hm(e,t):i.IsString(e)?Sm(e,t):i.IsSymbol(e)?xm(e,t):i.IsTuple(e)?wm(e,t):i.IsPromise(e)?Im(e,t):i.IsUint8Array(e)?Om(e,t):i.IsUndefined(e)?Rm(e,t):i.IsUnion(e)?Pm(e,t):i.IsUnknown(e)?Cm(e,t):i.IsVoid(e)?Fm(e,t):At(`Unknown left type operand '${e[p]}'`)}function ze(e,t){return P(e,t)}function km(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 Em(e,t,n,r,o){return km(e.properties,t,n,r,o)}function xs(e,t,n,r,o){let s=Em(e,t,n,r,o);return x(s)}function $m(e,t,n,r){let o=ze(e,t);return o===m.Union?A([n,r]):o===m.True?n:r}function wt(e,t,n,r,o){return E(e)?xs(e,t,n,r,o):ue(e)?u(Ts(e,t,n,r,o)):u($m(e,t,n,r),o)}function Um(e,t,n,r,o){return{[e]:wt(b(e),t,n,r,k(o))}}function _m(e,t,n,r,o){return e.reduce((s,a)=>({...s,...Um(a,t,n,r,o)}),{})}function Nm(e,t,n,r,o){return _m(e.keys,t,n,r,o)}function Ts(e,t,n,r,o){let s=Nm(e,t,n,r,o);return x(s)}function bs(e,t){return Ot(at(e),t)}function Km(e,t){let n=e.filter(r=>ze(r,t)===m.False);return n.length===1?n[0]:A(n)}function Ot(e,t,n={}){return me(e)?u(bs(e,t),n):E(e)?u(As(e,t),n):u(y(e)?Km(e.anyOf,t):ze(e,t)!==m.False?S():e,n)}function Lm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ot(e[r],t);return n}function vm(e,t){return Lm(e.properties,t)}function As(e,t){let n=vm(e,t);return x(n)}function ws(e,t){return Rt(at(e),t)}function jm(e,t){let n=e.filter(r=>ze(r,t)!==m.False);return n.length===1?n[0]:A(n)}function Rt(e,t,n){return me(e)?u(ws(e,t),n):E(e)?u(Os(e,t),n):u(y(e)?jm(e.anyOf,t):ze(e,t)!==m.False?e:S(),n)}function Dm(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Rt(e[r],t);return n}function Gm(e,t){return Dm(e.properties,t)}function Os(e,t){let n=Gm(e,t);return x(n)}function Rs(e,t){return Ae(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 R(r,{...n,[fe]:"Record"})}function Vm(e,t,n){return Go(e)?Ar(te(e),t,n):ut(e.pattern,t,n)}function Bm(e,t,n){return Ar(te(A(e)),t,n)}function Hm(e,t,n){return Ar([e.toString()],t,n)}function Wm(e,t,n){return ut(e.source,t,n)}function qm(e,t,n){let r=L(e.pattern)?Be:e.pattern;return ut(r,t,n)}function zm(e,t,n){return ut(Be,t,n)}function Ym(e,t,n){return ut(Uo,t,n)}function Xm(e,t,n){return R({true:t,false:t},n)}function Jm(e,t,n){return ut(Ve,t,n)}function Qm(e,t,n){return ut(Ve,t,n)}function bn(e,t,n={}){return y(e)?Bm(e.anyOf,t,n):me(e)?Vm(e,t,n):ae(e)?Hm(e.const,t,n):Ke(e)?Xm(e,t,n):Oe(e)?Jm(e,t,n):Re(e)?Qm(e,t,n):nr(e)?Wm(e,t,n):Le(e)?qm(e,t,n):er(e)?zm(e,t,n):De(e)?Ym(e,t,n):S(n)}function An(e){return globalThis.Object.getOwnPropertyNames(e.patternProperties)[0]}function Ps(e){let t=An(e);return t===Be?Pe():t===Ve?ge():Pe({pattern:t})}function wn(e){return e.patternProperties[An(e)]}function Zm(e,t){return t.parameters=zt(e,t.parameters),t.returns=Ce(e,t.returns),t}function ed(e,t){return t.parameters=zt(e,t.parameters),t.returns=Ce(e,t.returns),t}function td(e,t){return t.allOf=zt(e,t.allOf),t}function nd(e,t){return t.anyOf=zt(e,t.anyOf),t}function rd(e,t){return L(t.items)||(t.items=zt(e,t.items)),t}function od(e,t){return t.items=Ce(e,t.items),t}function sd(e,t){return t.items=Ce(e,t.items),t}function id(e,t){return t.items=Ce(e,t.items),t}function ad(e,t){return t.item=Ce(e,t.item),t}function ud(e,t){let n=cd(e,t.properties);return{...t,...R(n)}}function md(e,t){let n=Ce(e,Ps(t)),r=Ce(e,wn(t)),o=bn(n,r);return{...t,...o}}function dd(e,t){return t.index in e?e[t.index]:qe()}function pd(e,t){let n=lt(t),r=ee(t),o=Ce(e,t);return n&&r?Tn(o):n&&!r?ne(o):!n&&r?Y(o):o}function cd(e,t){return globalThis.Object.getOwnPropertyNames(t).reduce((n,r)=>({...n,[r]:pd(e,t[r])}),{})}function zt(e,t){return t.map(n=>Ce(e,n))}function Ce(e,t){return Ae(t)?Zm(e,t):we(t)?ed(e,t):U(t)?td(e,t):y(t)?nd(e,t):de(t)?rd(e,t):Te(t)?od(e,t):tt(t)?sd(e,t):rt(t)?id(e,t):ot(t)?ad(e,t):v(t)?ud(e,t):st(t)?md(e,t):tr(t)?dd(e,t):t}function Cs(e,t){return Ce(t,ct(e))}function Ms(e){return u({[p]:"Integer",type:"integer"},e)}function ld(e,t,n){return{[e]:Me(b(e),t,k(n))}}function fd(e,t,n){return e.reduce((o,s)=>({...o,...ld(s,t,n)}),{})}function gd(e,t,n){return fd(e.keys,t,n)}function Fs(e,t,n){let r=gd(e,t,n);return x(r)}function Id(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toLowerCase(),n].join("")}function hd(e){let[t,n]=[e.slice(0,1),e.slice(1)];return[t.toUpperCase(),n].join("")}function yd(e){return e.toUpperCase()}function Sd(e){return e.toLowerCase()}function xd(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)),d=Es(a,t),c=A(d);return dn([c],n)}function ks(e,t){return typeof e=="string"?t==="Uncapitalize"?Id(e):t==="Capitalize"?hd(e):t==="Uppercase"?yd(e):t==="Lowercase"?Sd(e):e:e.toString()}function Es(e,t){return e.map(n=>Me(n,t))}function Me(e,t,n={}){return ue(e)?Fs(e,t,n):me(e)?xd(e,t,n):y(e)?A(Es(e.anyOf,t),n):ae(e)?b(ks(e.const,t),n):u(e,n)}function $s(e,t={}){return Me(e,"Capitalize",t)}function Us(e,t={}){return Me(e,"Lowercase",t)}function _s(e,t={}){return Me(e,"Uncapitalize",t)}function Ns(e,t={}){return Me(e,"Uppercase",t)}function Td(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Ye(e[o],t,k(n));return r}function bd(e,t,n){return Td(e.properties,t,n)}function Ks(e,t,n){let r=bd(e,t,n);return x(r)}function Ad(e,t){return e.map(n=>wr(n,t))}function wd(e,t){return e.map(n=>wr(n,t))}function Od(e,t){let{[t]:n,...r}=e;return r}function Rd(e,t){return t.reduce((n,r)=>Od(n,r),e)}function Pd(e,t,n){let r=_(e,[j,"$id","required","properties"]),o=Rd(n,t);return R(o,r)}function Cd(e){let t=e.reduce((n,r)=>on(r)?[...n,b(r)]:n,[]);return A(t)}function wr(e,t){return U(e)?X(Ad(e.allOf,t)):y(e)?A(wd(e.anyOf,t)):v(e)?Pd(e,t,e.properties):R({})}function Ye(e,t,n){let r=K(t)?Cd(t):t,o=pe(t)?te(t):t,s=N(e),a=N(t);return E(e)?Ks(e,o,n):ue(t)?Ls(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 Md(e,t,n){return{[t]:Ye(e,[t],k(n))}}function Fd(e,t,n){return t.reduce((r,o)=>({...r,...Md(e,o,n)}),{})}function kd(e,t,n){return Fd(e,t.keys,n)}function Ls(e,t,n){let r=kd(e,t,n);return x(r)}function Ed(e,t,n){let r={};for(let o of globalThis.Object.getOwnPropertyNames(e))r[o]=Xe(e[o],t,k(n));return r}function $d(e,t,n){return Ed(e.properties,t,n)}function vs(e,t,n){let r=$d(e,t,n);return x(r)}function Ud(e,t){return e.map(n=>Or(n,t))}function _d(e,t){return e.map(n=>Or(n,t))}function Nd(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function Kd(e,t,n){let r=_(e,[j,"$id","required","properties"]),o=Nd(n,t);return R(o,r)}function Ld(e){let t=e.reduce((n,r)=>on(r)?[...n,b(r)]:n,[]);return A(t)}function Or(e,t){return U(e)?X(Ud(e.allOf,t)):y(e)?A(_d(e.anyOf,t)):v(e)?Kd(e,t,e.properties):R({})}function Xe(e,t,n){let r=K(t)?Ld(t):t,o=pe(t)?te(t):t,s=N(e),a=N(t);return E(e)?vs(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 vd(e,t,n){return{[t]:Xe(e,[t],k(n))}}function jd(e,t,n){return t.reduce((r,o)=>({...r,...vd(e,o,n)}),{})}function Dd(e,t,n){return jd(e,t.keys,n)}function js(e,t,n){let r=Dd(e,t,n);return x(r)}function Gd(e,t){return F("Partial",[F(e,t)])}function Vd(e){return F("Partial",[$e(e)])}function Bd(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=Y(e[n]);return t}function Hd(e,t){let n=_(e,[j,"$id","required","properties"]),r=Bd(t);return R(r,n)}function Ds(e){return e.map(t=>Gs(t))}function Gs(e){return be(e)?Gd(e.target,e.parameters):N(e)?Vd(e.$ref):U(e)?X(Ds(e.allOf)):y(e)?A(Ds(e.anyOf)):v(e)?Hd(e,e.properties):nt(e)||Ke(e)||Oe(e)||ae(e)||Nt(e)||Re(e)||Le(e)||Kt(e)||Lt(e)?e:R({})}function Pt(e,t){return E(e)?Vs(e,t):u({...Gs(e),...t})}function Wd(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Pt(e[r],k(t));return n}function qd(e,t){return Wd(e.properties,t)}function Vs(e,t){let n=qd(e,t);return x(n)}function zd(e,t){return F("Required",[F(e,t)])}function Yd(e){return F("Required",[$e(e)])}function Xd(e){let t={};for(let n of globalThis.Object.getOwnPropertyNames(e))t[n]=_(e[n],[W]);return t}function Jd(e,t){let n=_(e,[j,"$id","required","properties"]),r=Xd(t);return R(r,n)}function Bs(e){return e.map(t=>Hs(t))}function Hs(e){return be(e)?zd(e.target,e.parameters):N(e)?Yd(e.$ref):U(e)?X(Bs(e.allOf)):y(e)?A(Bs(e.anyOf)):v(e)?Jd(e,e.properties):nt(e)||Ke(e)||Oe(e)||ae(e)||Nt(e)||Re(e)||Le(e)||Kt(e)||Lt(e)?e:R({})}function Ct(e,t){return E(e)?Ws(e,t):u({...Hs(e),...t})}function Qd(e,t){let n={};for(let r of globalThis.Object.getOwnPropertyNames(e))n[r]=Ct(e[r],t);return n}function Zd(e,t){return Qd(e.properties,t)}function Ws(e,t){let n=Zd(e,t);return x(n)}function ep(e,t){return t.map(n=>N(n)?Rr(e,n.$ref):ce(e,n))}function Rr(e,t){return t in e?N(e[t])?Rr(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 Pt(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 mp(e,t){return ft(ce(e,t))}function dp(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 xt(ce(e,t))}function gp(e,t){return R(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)?{...Rr(e,t.$ref),[j]:t[j]}:t}function yp(e,t){return Ie(Yt(e,t))}function Sp(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,[xe])),t):Ge(t)?u(hp(e,t),t):Te(t)?u(mp(e,t.items),t):tt(t)?u(dp(e,t.items),t):be(t)?u(up(e,t.target,t.parameters)):Ae(t)?u(pp(e,t.parameters,t.returns),t):we(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):v(t)?u(gp(e,t.properties),t):st(t)?u(Ip(e,t)):de(t)?u(yp(e,t.items||[]),t):y(t)?u(Sp(e,t.anyOf),t):t}function xp(e,t){return t in e?ce(e,e[t]):S()}function qs(e){return globalThis.Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:xp(e,n)}),{})}var Pr=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 Pr(e)}function Ys(e,t){return u({[p]:"Not",not:e},t)}function Xs(e,t){return we(e)?Ie(e.parameters,t):S()}var Tp=0;function Js(e,t={}){L(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:y(e)?e.anyOf:de(e)?e.items??[]:[]}function Zs(e){return bp(e)}function ei(e,t){return we(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:()=>vo,Array:()=>ft,AsyncIterator:()=>gt,Awaited:()=>Tt,BigInt:()=>St,Boolean:()=>mn,Capitalize:()=>$s,Composite:()=>ss,Const:()=>is,Constructor:()=>It,ConstructorParameters:()=>as,Date:()=>ln,Enum:()=>us,Exclude:()=>Ot,Extends:()=>wt,Extract:()=>Rt,Function:()=>ke,Index:()=>We,InstanceType:()=>Rs,Instantiate:()=>Cs,Integer:()=>Ms,Intersect:()=>X,Iterator:()=>xt,KeyOf:()=>bt,Literal:()=>b,Lowercase:()=>Us,Mapped:()=>Zo,Module:()=>zs,Never:()=>S,Not:()=>Ys,Null:()=>fn,Number:()=>ge,Object:()=>R,Omit:()=>Ye,Optional:()=>Y,Parameters:()=>Xs,Partial:()=>Pt,Pick:()=>Xe,Promise:()=>cn,Readonly:()=>ne,ReadonlyOptional:()=>Tn,Record:()=>bn,Recursive:()=>Js,Ref:()=>$e,RegExp:()=>Qs,Required:()=>Ct,Rest:()=>Zs,ReturnType:()=>ei,String:()=>Pe,Symbol:()=>gn,TemplateLiteral:()=>dn,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 T={maxSessions:5,idleTimeoutMinutes:15,sessionGcAgeMinutes:1440,maxPersistedSessions:1e4,maxAutoResponds:10,permissionMode:"plan",planApproval:"delegate",reasoningEffort:"medium"};function si(e){T={maxSessions:e.maxSessions??5,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",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}`:T.fallbackChannel??"unknown"}function Ft(e){return e?.messageThreadId??void 0}function Jt(e){let t=T.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 Pp(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. 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||T.defaultWorkdir||process.cwd();if(!Rp(r))return{content:[{type:"text",text:`Error: Working directory does not exist: ${r}`}]};try{let o=n.harness??T.defaultHarness,s=o==="codex"?T.model??T.defaultModel:T.defaultModel,a=n.resume_session_id,d=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:d?{harnessSessionId:d.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:T.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,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,Fe=["Session launched successfully.",` Name: ${Z.name}`,` ID: ${Z.id}`,` Dir: ${r}`,` Model: ${Z.model??"default"}`,` Prompt: "${q}"`];return n.resume_session_id&&(Fe.push(` Resume: ${n.resume_session_id}${n.fork_session?" (forked)":""}`),$&&Fe.push(" Thread state: historical Codex state cleared; starting a fresh thread.")),Fe.push(n.multi_turn_disabled?" Mode: single-turn (fire-and-forget)":" Mode: multi-turn (use agent_respond to send follow-up messages)"),Fe.push("","Use agent_sessions to check status, agent_output to see output."),{content:[{type:"text",text:Fe.join(`
2
2
  `)}]}}catch(o){let s=Pp(o),a=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}${a}`}]}}}}}import{existsSync as Ep,readFileSync as kp}from"fs";function Ue(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m${r}s`:`${r}s`}var Mp=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 mi(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!Mp.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var Fp={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function di(e){let t=Fp[e.status]??"\u2753",n=Ue(e.duration),r=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)}`:"",a=[`${t} ${e.name} [${e.id}] (${n}${s}) \u2014 ${r}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];return e.phase!==e.status&&a.push(` \u2699\uFE0F Phase: ${e.phase}`),e.harness&&a.push(` \u{1F9F0} Harness: ${e.harness}`),e.harnessSessionId&&a.push(` \u{1F517} Session ID: ${e.harnessSessionId}`),e.resumeSessionId&&a.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),a.join(`
4
+ Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${s}${a}`}]}}}}}import{existsSync as kp,readFileSync as Ep}from"fs";function Ue(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m${r}s`:`${r}s`}var Mp=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 mi(e){let n=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!Mp.has(r)).slice(0,3);return n.length===0?"session":n.join("-")}var Fp={starting:"\u{1F7E1}",running:"\u{1F7E2}",completed:"\u2705",failed:"\u274C",killed:"\u26D4"};function di(e){let t=Fp[e.status]??"\u2753",n=Ue(e.duration),r=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)}`:"",a=[`${t} ${e.name} [${e.id}] (${n}${s}) \u2014 ${r}`,` \u{1F4C1} ${e.workdir}`,` \u{1F4DD} "${o}"`];return e.phase!==e.status&&a.push(` \u2699\uFE0F Phase: ${e.phase}`),e.harness&&a.push(` \u{1F9F0} Harness: ${e.harness}`),e.harnessSessionId&&a.push(` \u{1F517} Session ID: ${e.harnessSessionId}`),e.resumeSessionId&&a.push(` \u21A9\uFE0F Resumed from: ${e.resumeSessionId}${e.forkSession?" (forked)":""}`),a.join(`
5
5
  `)}function On(e,t){let n=e.sessionsWithDuration>0?e.totalDurationMs/e.sessionsWithDuration:0,{completed:r,failed:o,killed:s}=e.sessionsByStatus,a=["\u{1F4CA} OpenClaw Code Agent Stats","","\u{1F4CB} Sessions",` Launched: ${e.totalLaunched}`,` Running: ${t}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${s}`,"",`\u23F1\uFE0F Average duration: ${n>0?Ue(n):"n/a"}`];if(e.mostExpensive){let d=e.mostExpensive;a.push("","\u{1F3C6} Notable session",` ${d.name} [${d.id}]`,` \u{1F4DD} "${d.prompt}"`)}return a.join(`
6
6
  `)}function Je(e,t){return t<=0?"":e.length<=t?e:t<=3?".".repeat(t):e.slice(0,t-3)+"..."}function pi(e,t){let n=e.split(`
7
7
  `),r=[],o=0;for(let s=n.length-1;s>=0;s--){let a=n[s].length+(r.length>0?1:0);if(o+a>t&&r.length>0)break;r.unshift(n[s]),o+=a}return r.join(`
@@ -11,7 +11,7 @@ Use agent_sessions to see active sessions and their status.`;return{content:[{ty
11
11
  (no output yet)
12
12
  ${t.join(`
13
13
  `)}`:`
14
- (no output yet)`}function Rn(e,t,n={}){let r=Lp(n.lines),o=e.resolve(t);if(!o){let d=e.getPersistedSession(t);if(d?.outputPath&&Ep(d.outputPath))try{let c=kp(d.outputPath,"utf-8"),f=c;!n.full&&c&&(f=c.split(`
14
+ (no output yet)`}function Rn(e,t,n={}){let r=Lp(n.lines),o=e.resolve(t);if(!o){let d=e.getPersistedSession(t);if(d?.outputPath&&kp(d.outputPath))try{let c=Ep(d.outputPath,"utf-8"),f=c;!n.full&&c&&(f=c.split(`
15
15
  `).slice(-r).join(`
16
16
  `));let $=Dp(d);return f?`${$}
17
17
  ${f}`:`${$}
@@ -20,7 +20,7 @@ ${s.join(`
20
20
  `)}`}function Pn(e,t="all",n,r={}){let o=e.listPersistedSessions()??[],a=Vp(e.list("all"),o);if(t!=="all"&&(a=a.filter(d=>d.status===t)),n&&(a=a.filter(d=>d.originChannel===n)),r.full){let d=Date.now()-Kp;a=a.filter(c=>(c.startedAt??0)>=d)}else a=a.slice(0,Np);return a.length===0?"No sessions found.":a.map(d=>di(d)).join(`
21
21
 
22
22
  `)}function Vp(e,t){let n=new Map;for(let r of t){if(!vp(r.status))continue;let o=r.completedAt??Date.now(),s=r.createdAt??o,a=r.sessionId??`persisted:${r.harnessSessionId}`;n.set(a,{id:r.sessionId??r.harnessSessionId,name:r.name||r.harnessSessionId,status:r.status,startedAt:r.createdAt??0,completedAt:r.completedAt,duration:Math.max(0,o-s),prompt:r.prompt??"",workdir:r.workdir??"(unknown)",costUsd:r.costUsd??0,multiTurn:!0,phase:r.status,harness:r.harness,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId})}for(let r of e)n.set(r.id,{id:r.id,name:r.name,status:r.status,startedAt:r.startedAt,completedAt:r.completedAt,duration:r.duration,prompt:r.prompt,workdir:r.workdir,costUsd:r.costUsd,multiTurn:r.multiTurn,phase:r.phase,harness:r.harnessName,harnessSessionId:r.harnessSessionId,originChannel:r.originChannel,originThreadId:r.originThreadId});return[...n.values()].sort((r,o)=>(o.startedAt??0)-(r.startedAt??0))}function Bp(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 ci(e){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:l.Object({status:l.Optional(l.Union([l.Literal("all"),l.Literal("running"),l.Literal("completed"),l.Literal("failed"),l.Literal("killed")],{description:'Filter by status (default "all")'})),full:l.Optional(l.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=Bp(n),o=e?.workspaceDir?Jt(e.workspaceDir):void 0,s=!!(n&&typeof n=="object"&&n.full===!0);return{content:[{type:"text",text:Pn(g,r,o,{full:s})}]}}}}function Cn(e,t,n){let r=e.resolve(t);return r?r.status==="completed"||r.status==="failed"||r.status==="killed"?`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`:n==="completed"?(r.complete(),`Session ${r.name} [${r.id}] marked as completed.`):(e.kill(r.id),`Session ${r.name} [${r.id}] has been terminated.`):`Error: Session "${t}" not found.`}function Hp(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 li(e){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:l.Object({session:l.String({description:"Session name or ID to terminate"}),reason:l.Optional(l.Union([l.Literal("completed"),l.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends \u2705 notification). 'killed' (default) terminates it."}))}),async execute(t,n){return g?Hp(n)?{content:[{type:"text",text:Cn(g,n.session,n.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}function Wp(e){return!e||typeof e!="object"?!1:typeof e.session=="string"}function fi(e){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:l.Object({session:l.String({description:"Session name or ID to get output from"}),lines:l.Optional(l.Number({description:"Number of recent lines to show (default 50)"})),full:l.Optional(l.Boolean({description:"Show all available output"}))}),async execute(t,n){return g?Wp(n)?{content:[{type:"text",text:Rn(g,n.session,{full:n.full,lines:n.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}var qp=new Set(["killed","completed","failed"]),zp=new Set(["idle-timeout","shutdown","done"]),Yp=10,Xp=100,Jp=/\b(change|swap|replace|remove|add|update|instead|don't|revise|modify)\b/i;function Qt(e){return e instanceof Error?e.message:String(e)}function Qp(e){switch(e){case"completed":return"completed";case"failed":return"failed";default:return"idle-kill"}}function gi(e){return"id"in e?e.id:e.sessionId??e.harnessSessionId}function Zp(e){return e.status==="killed"&&e.completedAt==null}function ec(e,t){return qp.has(e.status)&&!!e.harnessSessionId&&(e.status==="failed"||e.status==="completed"&&e.killReason==="done"||e.status==="killed"&&(zp.has(e.killReason??"")||t&&Zp(e)))}function tc(e,t){if(!(t.trim().length<Xp&&!Jp.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 nc(e,t,n,r={}){if(ec(t,r.allowRecoveredRunningStub===!0))try{let o="harnessName"in t?t:void 0,s="harnessName"in t?void 0:t,{resumeSessionId:a}=Et({requestedResumeSessionId:t.harnessSessionId,activeSession:o?{harnessSessionId:o.harnessSessionId}:void 0,persistedSession:s?{harness:s.harness}:void 0}),d={prompt:n,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:a,multiTurn:!0,notifyOnTurnEnd:t.notifyOnTurnEnd,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:t.currentPermissionMode,harness:"harnessName"in t?t.harnessName:t.harness},c=e.spawn(d),f=Qp(t.status);return e.notifySession(c,`\u{1F504} [${c.name}] Auto-resumed from ${f}`),{text:`Auto-resumed ${f} session ${c.name} [${c.id}]. Use agent_output to see the response.`}}catch(o){return{text:`Error auto-resuming session ${t.name} [${gi(t)}]: ${Qt(o)}`,isError:!0}}}function rc(e,t,n){let r=t.lobsterResumeToken;if(r){if(t.lobsterResumeToken=void 0,n.approve&&t.pendingPlanApproval)return e.resumeLobsterApproval(r,!0).catch(o=>{console.error(`[Respond] Lobster resume failed, falling back to direct mode switch: ${Qt(o)}`),t.switchPermissionMode("bypassPermissions"),t.sendMessage(n.message).catch(s=>{console.error(`[Respond] Fallback sendMessage also failed: ${Qt(s)}`)})}),{text:`Plan approved. Lobster workflow resuming for session ${t.name} [${t.id}].`};e.resumeLobsterApproval(r,!1).catch(o=>{console.error(`[Respond] Lobster cancel failed (non-critical): ${Qt(o)}`)})}}async function Mn(e,t){let n=e.resolve(t.session),r=n?void 0:e.getPersistedSession(t.session);if(!n&&!r)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let s=await nc(e,n??r,t.message,{allowRecoveredRunningStub:!n});if(s)return s;if(!n)return{text:`Error: Session ${r.name} [${gi(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return{text:`Error: Session ${n.name} [${n.id}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};let a=T.maxAutoResponds??Yp;if(t.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=a)return{text:`\u26A0\uFE0F Auto-respond limit reached (${n.autoRespondCount}/${a}). Ask the user to provide the answer for session ${n.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};let d=rc(e,n,t);if(d)return d;try{t.interrupt&&await n.interrupt();let c="";if(t.approve&&n.pendingPlanApproval){let $=tc(n.name,t.message);if($)return $;n.switchPermissionMode("bypassPermissions")}else t.approve?c=`
23
+ `),isError:!0}}async function nc(e,t,n,r={}){if(ec(t,r.allowRecoveredRunningStub===!0))try{let o="harnessName"in t?t:void 0,s="harnessName"in t?void 0:t,{resumeSessionId:a}=kt({requestedResumeSessionId:t.harnessSessionId,activeSession:o?{harnessSessionId:o.harnessSessionId}:void 0,persistedSession:s?{harness:s.harness}:void 0}),d={prompt:n,workdir:t.workdir,name:t.name,model:t.model,reasoningEffort:t.reasoningEffort,resumeSessionId:a,multiTurn:!0,originChannel:t.originChannel,originThreadId:t.originThreadId,originAgentId:t.originAgentId,originSessionKey:t.originSessionKey,permissionMode:t.currentPermissionMode,harness:"harnessName"in t?t.harnessName:t.harness},c=e.spawn(d),f=Qp(t.status);return e.notifySession(c,`\u{1F504} [${c.name}] Auto-resumed from ${f}`),{text:`Auto-resumed ${f} session ${c.name} [${c.id}]. Use agent_output to see the response.`}}catch(o){return{text:`Error auto-resuming session ${t.name} [${gi(t)}]: ${Qt(o)}`,isError:!0}}}function rc(e,t,n){let r=t.lobsterResumeToken;if(r){if(t.lobsterResumeToken=void 0,n.approve&&t.pendingPlanApproval)return e.resumeLobsterApproval(r,!0).catch(o=>{console.error(`[Respond] Lobster resume failed, falling back to direct mode switch: ${Qt(o)}`),t.switchPermissionMode("bypassPermissions"),t.sendMessage(n.message).catch(s=>{console.error(`[Respond] Fallback sendMessage also failed: ${Qt(s)}`)})}),{text:`Plan approved. Lobster workflow resuming for session ${t.name} [${t.id}].`};e.resumeLobsterApproval(r,!1).catch(o=>{console.error(`[Respond] Lobster cancel failed (non-critical): ${Qt(o)}`)})}}async function Mn(e,t){let n=e.resolve(t.session),r=n?void 0:e.getPersistedSession(t.session);if(!n&&!r)return{text:`Error: Session "${t.session}" not found.`,isError:!0};let s=await nc(e,n??r,t.message,{allowRecoveredRunningStub:!n});if(s)return s;if(!n)return{text:`Error: Session ${r.name} [${gi(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(n.status!=="running")return{text:`Error: Session ${n.name} [${n.id}] is not running (status: ${n.status}). Cannot send a message to a non-running session.`,isError:!0};let a=T.maxAutoResponds??Yp;if(t.userInitiated)n.resetAutoRespond();else if(n.autoRespondCount>=a)return{text:`\u26A0\uFE0F Auto-respond limit reached (${n.autoRespondCount}/${a}). Ask the user to provide the answer for session ${n.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};let d=rc(e,n,t);if(d)return d;try{t.interrupt&&await n.interrupt();let c="";if(t.approve&&n.pendingPlanApproval){let $=tc(n.name,t.message);if($)return $;n.switchPermissionMode("bypassPermissions")}else t.approve?c=`
24
24
  \u26A0\uFE0F approve=true was set but session has no pending plan approval.`:n.pendingPlanApproval&&(c=`
25
25
  \u2139\uFE0F Session has a pending plan \u2014 sending as revision feedback. The agent will revise and re-submit. Set approve=true to approve instead.`);await n.sendMessage(t.message),t.userInitiated||n.incrementAutoRespond();let f=Je(t.message,80);return{text:[`Message sent to session ${n.name} [${n.id}].`,t.interrupt?" (interrupted current turn first)":"",` Message: "${f}"`,c,"Use agent_output to see the response."].filter(Boolean).join(`
26
26
  `)}}catch(c){return{text:`Error sending message to session ${n.name} [${n.id}]: ${Qt(c)}`,isError:!0}}}function oc(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.session=="string"&&typeof t.message=="string"}function Ii(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 approve a pending plan and switch the session from plan mode to bypassPermissions. Only works when the session has a pending plan approval (after ExitPlanMode / set_permission_mode). To request changes instead, omit this flag \u2014 the message will be sent as revision feedback and the agent will revise the plan."}))}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!oc(n))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, message, interrupt?, userInitiated?, approve? }."}]};let r=await Mn(g,n);return{isError:r.isError??!1,content:[{type:"text",text:r.text}]}}}}function hi(e){return{name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics: session counts by status, average duration, and notable sessions.",parameters:l.Object({}),async execute(t,n){if(!g)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=g.getMetrics(),o=g.list("running").length;return{content:[{type:"text",text:On(r,o)}]}}}}function sc(e){return e instanceof Error?e.message:String(e)}function yi(e){e.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent [--name <name>] <prompt>"};let r,o=n.match(/^--name\s+(\S+)\s+/);o&&(r=o[1],n=n.slice(o[0].length).trim());let s=n;if(!s)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let a=T.defaultHarness,d=a==="codex"?T.model??T.defaultModel:T.defaultModel,c=g.spawn({prompt:s,name:r,workdir:T.defaultWorkdir||process.cwd(),model:d,reasoningEffort:T.reasoningEffort,originChannel:Mt(t),originThreadId:Ft(t),harness:a}),f=s.length>80?s.slice(0,80)+"...":s;return{text:["Session launched.",` Name: ${c.name}`,` ID: ${c.id}`,` Prompt: "${f}"`,` Status: ${c.status}`].join(`
@@ -34,18 +34,18 @@ ${Q.map(q=>{let Fe=q.prompt.length>60?q.prompt.slice(0,60)+"...":q.prompt,Qe=q.c
34
34
  `)}).join(`
35
35
 
36
36
  `)}`}}let r=!1;n.startsWith("--fork ")&&(r=!0,n=n.slice(7).trim());let o=n.indexOf(" "),s,a;o===-1?(s=n,a="Continue where you left off."):(s=n.slice(0,o),a=n.slice(o+1).trim()||"Continue where you left off.");let d=g.resolveHarnessSessionId(s);if(!d)return{text:`Error: Could not find a session ID for "${s}".
37
- Use /agent_resume --list to see available sessions.`};let c=g.resolve(s),f=g.getPersistedSession(s),{resumeSessionId:$,clearedPersistedCodexResume:le}=Et({requestedResumeSessionId:d,activeSession:c?{harnessSessionId:c.harnessSessionId}:void 0,persistedSession:f?{harness:f.harness}:void 0}),oe=f?.workdir??process.cwd();try{let Q=g.spawn({prompt:a,workdir:oe,name:f?.name,model:f?.model,resumeSessionId:$,forkSession:$?r:!1,originChannel:Mt(t),originThreadId:Ft(t)??f?.originThreadId,originAgentId:t?.agentId??f?.originAgentId,originSessionKey:t?.sessionKey??f?.originSessionKey,harness:f?.harness}),Z=a.length>80?a.slice(0,80)+"...":a;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${Q.name}`,` ID: ${Q.id}`,$?` Resume from: ${d}`:" Resume from: fresh thread",` Dir: ${oe}`,` Prompt: "${Z}"`,le?" Note: cleared persisted Codex thread state after restart to avoid org-mismatch resume failures.":""].join(`
37
+ Use /agent_resume --list to see available sessions.`};let c=g.resolve(s),f=g.getPersistedSession(s),{resumeSessionId:$,clearedPersistedCodexResume:le}=kt({requestedResumeSessionId:d,activeSession:c?{harnessSessionId:c.harnessSessionId}:void 0,persistedSession:f?{harness:f.harness}:void 0}),oe=f?.workdir??process.cwd();try{let Q=g.spawn({prompt:a,workdir:oe,name:f?.name,model:f?.model,resumeSessionId:$,forkSession:$?r:!1,originChannel:Mt(t),originThreadId:Ft(t)??f?.originThreadId,originAgentId:t?.agentId??f?.originAgentId,originSessionKey:t?.sessionKey??f?.originSessionKey,harness:f?.harness}),Z=a.length>80?a.slice(0,80)+"...":a;return{text:[`Session resumed${r?" (forked)":""}.`,` Name: ${Q.name}`,` ID: ${Q.id}`,$?` Resume from: ${d}`:" Resume from: fresh thread",` Dir: ${oe}`,` Prompt: "${Z}"`,le?" Note: cleared persisted Codex thread state after restart to avoid org-mismatch resume failures.":""].join(`
38
38
  `)}}catch(Q){let Z=ic(Q),q=Z.includes("Max sessions")?"":`
39
39
 
40
40
  Use /agent_sessions to see active sessions or /agent_resume --list to see resumable sessions.`;return{text:`Error resuming session: ${Z}${q}`}}}})}function bi(e){e.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:`Usage: /agent_respond <id-or-name> <message>
41
- /agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!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 a=o.slice(0,s),d=o.slice(s+1).trim();return d?{text:(await Mn(g,{session:a,message:d,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}function Ai(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=g.getMetrics(),n=g.list("running").length;return{text:On(t,n)}}})}var ac=50;function wi(e){e.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=n.split(/\s+/),o="",s=!1,a=ac;for(let c=0;c<r.length;c++)if(r[c]==="--full")s=!0;else if(r[c]==="--lines"&&c+1<r.length){let f=parseInt(r[c+1],10);!isNaN(f)&&f>0&&(a=f),c++}else o||(o=r[c]);return o?{text:Rn(g,o,{full:s,lines:a})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}import{execFile as ji}from"child_process";import{existsSync as rl}from"fs";import{fileURLToPath as Di}from"url";import{dirname as ol,join as _r}from"path";import{EventEmitter as Fc}from"events";import Ri from"crypto";var Oi="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var uc=128,mt,kt,mc=e=>{!mt||mt.length<e?(mt=Buffer.allocUnsafe(e*uc),Ri.randomFillSync(mt),kt=0):kt+e>mt.length&&(Ri.randomFillSync(mt),kt=0),kt+=e};var Pi=(e=21)=>{mc(e|=0);let t="";for(let n=kt-e;n<kt;n++)t+=Oi[mt[n]&63];return t};import{query as dc}from"@anthropic-ai/claude-agent-sdk";var Fn=class{name="claude-code";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=["AskUserQuestion"];planApprovalToolNames=["ExitPlanMode","set_permission_mode"];launch(t){let n={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers};t.resumeSessionId&&(n.resume=t.resumeSessionId,n.forkSession=t.forkSession??!1);let r=dc({prompt:t.prompt,options:n});return{messages:this.adaptMessages(r),async setPermissionMode(o){typeof r.setPermissionMode=="function"&&await r.setPermissionMode(o)},async streamInput(o){typeof r.streamInput=="function"&&await r.streamInput(o)},async interrupt(){typeof r.interrupt=="function"&&await r.interrupt()}}}buildUserMessage(t,n){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n}}async*adaptMessages(t){for await(let n of t){let r=n;if(r.type==="system"&&r.subtype==="init")yield{type:"init",session_id:r.session_id??""};else if(r.type==="system"&&r.subtype==="status"&&r.permissionMode)yield{type:"permission_mode_change",mode:r.permissionMode};else if(r.type==="assistant")for(let o of r.message?.content??[])o.type==="text"?yield{type:"text",text:o.text}:o.type==="tool_use"&&(yield{type:"tool_use",name:o.name,input:o.input});else r.type==="result"&&(yield{type:"result",data:{success:r.subtype==="success",duration_ms:r.duration_ms??0,total_cost_usd:r.total_cost_usd??0,num_turns:r.num_turns??0,result:r.result,session_id:r.session_id??""}})}}};import{parse as gc,resolve as Ic}from"path";import{Codex as hc}from"@openai/codex-sdk";var pc=["proceed","continue","implement","apply","run","merge","deploy","commit"],cc=["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"],lc=["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 fc(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function En(e){let t=fc(e);if(!t||lc.some(r=>t.includes(r)))return!1;let n=pc.some(r=>t.includes(r));return cc.some(r=>t.includes(r))?n||t.includes("confirm"):t.endsWith("?")?n:!1}var Ci=1e4,Mi="codex:waiting-for-user",yc=1.1/1e6,Sc=.275/1e6,xc=4.4/1e6,Tc="OPENCLAW_CODEX_HEARTBEAT_MS",bc="OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS";function Ac(e){if(!e)return 0;let t=e.cached_input_tokens??0,n=Math.max(0,(e.input_tokens??0)-t),r=e.output_tokens??0;return n*yc+t*Sc+r*xc}function Fi(e,t={}){return{success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,session_id:e,...t}}function wc(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 Oc(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(`
42
- `)}function Ei(e){return e instanceof Error?e.message:String(e)}function Rc(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Pc(e){return gc(Ic(e)).root||"/"}function Cc(e){let n=[Pc(e)];return n.push(...Rc(process.env[bc])),[...new Set(n)]}function Mc(e,t){let r=(t??e.permissionMode)==="bypassPermissions"?Cc(e.cwd):void 0;return{model:e.model,modelReasoningEffort:e.reasoningEffort,workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0,additionalDirectories:r}}var kn=class{constructor(t={}){this.deps=t}name="codex";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=[Mi];planApprovalToolNames=[];activityHeartbeatMs(){let t=Number.parseInt(process.env[Tc]??String(Ci),10);return!Number.isFinite(t)||t<=0?Ci:t}createCodexClient(){return this.deps.createCodex?.()??new hc}launch(t){let n=t.permissionMode==="plan",r=t.permissionMode==="plan"?"default":t.permissionMode,o=t.resumeSessionId,s=0,a=0,d=this.activityHeartbeatMs(),c,f,$=!1,le=!0,oe,Q=[],Z=null,q=!1,Fe=!1;function Qe(){Z&&(Z(),Z=null)}function Ze(H){Q.push(H),Qe()}function Nr(){q=!0,Qe()}function Vn(H){!H||Fe||(Fe=!0,Ze({type:"init",session_id:H}))}async function*Gi(){for(;;){for(;Q.length>0;)yield Q.shift();if(q)return;await new Promise(H=>{Z=H})}}let Zt=()=>Mc(t,r),Vi=()=>(c||(c=this.createCodexClient()),f||(le&&t.resumeSessionId?f=c.resumeThread(t.resumeSessionId,Zt()):o?f=c.resumeThread(o,Zt()):f=c.startThread(Zt())),$&&o&&(f=c.resumeThread(o,Zt()),$=!1),Vn(f.id??o??void 0),f),Kr=async H=>{let Hn=Date.now();a+=1;let Lr="",Wn=!1,qn,Bi=le&&n?Oc(H):H,en=pt=>{Wn||(Wn=!0,Ze({type:"result",data:Fi(o??"",{duration_ms:Date.now()-Hn,total_cost_usd:s,num_turns:a,...pt,session_id:o??""})}))};try{let pt=Vi(),vr=pt.id??o??void 0;vr&&(o=vr,Vn(o)),oe=new AbortController,t.abortController?.signal.aborted&&oe.abort(t.abortController.signal.reason),qn=setInterval(()=>{Ze({type:"activity"})},d);let Hi=await pt.runStreamed(Bi,{signal:oe.signal});for await(let se of Hi.events){if(se.type==="thread.started"){o=se.thread_id,Vn(o);continue}if(se.type==="item.completed"){(se.item.type==="agent_message"||se.item.type==="reasoning")&&(Lr+=`${se.item.text}
43
- `,Ze({type:"text",text:se.item.text}));continue}if(se.type==="error"){Ze({type:"text",text:`[codex:error] ${se.message}`});continue}if(se.type==="turn.failed"){en({success:!1,result:se.error.message,session_id:o??""});continue}if(se.type==="turn.completed"){s+=Ac(se.usage);let jr=Lr.slice(-500);En(jr)&&Ze({type:"tool_use",name:Mi,input:{text:jr}}),en({success:!0,session_id:o??""})}}Wn||en({success:!1,result:"Codex turn ended without terminal event",session_id:o??""})}catch(pt){en({success:!1,result:Ei(pt),session_id:o??""})}finally{qn&&clearInterval(qn),oe=void 0,le=!1}},Bn=()=>{oe?.abort(t.abortController?.signal.reason??"interrupted")};return t.abortController?.signal&&t.abortController.signal.addEventListener("abort",Bn),(async()=>{try{let H=t.prompt;if(typeof H=="string"){await Kr(H);return}for await(let Hn of H)if(t.abortController?.signal.aborted||(await Kr(wc(Hn)),t.abortController?.signal.aborted))break}finally{t.abortController?.signal.removeEventListener("abort",Bn),Nr()}})().catch(H=>{Ze({type:"result",data:Fi(o??"",{success:!1,result:Ei(H),total_cost_usd:s,num_turns:a,session_id:o??""})}),t.abortController?.signal.removeEventListener("abort",Bn),Nr()}),{messages:Gi(),async setPermissionMode(H){r=H,$=!0},async interrupt(){oe?.abort("interrupted")}}}buildUserMessage(t,n){return{type:"user",text:t,session_id:n}}};var kr=new Map;function ki(e){kr.set(e.name,e)}function $r(e){let t=kr.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...kr.keys()].join(", ")}`);return t}function $i(){let e=T.defaultHarness??"claude-code";return $r(e)}ki(new Fn);ki(new kn);var Ui=200,Ec=120*1e3;function $n(e){return e instanceof Error?e.message:String(e)}var kc={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},Ur=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})}}},Un=class extends Fc{id;name;harnessSessionId;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;multiTurn;notifyOnTurnEnd;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;pendingPlanApproval=!1;lobsterResumeToken;killReason="unknown";waitingForInputFired=!1;lastTurnHadQuestion=!1;planModeApproved=!1;autoRespondCount=0;timers=new Map;constructor(t,n){super(),this.id=Pi(8),this.name=n,this.harness=t.harness?$r(t.harness):$i();let r=this.harness.name==="codex";this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??(r?T.model:void 0)??T.defaultModel,this.reasoningEffort=t.reasoningEffort??(r?T.reasoningEffort:void 0),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??T.permissionMode,this.currentPermissionMode=r&&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.notifyOnTurnEnd=t.notifyOnTurnEnd??!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(!kc[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let n=this._status;this._status=t,this.emit("statusChange",this,t,n)}setTimer(t,n,r){this.clearTimer(t),this.timers.set(t,setTimeout(r,n))}clearTimer(t){let n=this.timers.get(t);n&&(clearTimeout(n),this.timers.delete(t))}clearAllTimers(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}async start(){try{let t;this.multiTurn?(this.messageStream=new Ur,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let n=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,abortController:this.abortController,mcpServers:oi()});this.harnessHandle=n,this.setTimer("startup",Ec,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let n=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:n});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let n=t instanceof Error?t.message:String(t),r=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${n}`,r),this.isActive&&this.transitionToTerminal("failed",{error:n})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.waitingForInputFired=!1;let n=t;if(this.pendingModeSwitch){let r=this.pendingModeSwitch,o=!1,s=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(r),this.currentPermissionMode=r,this.pendingModeSwitch=void 0,s=!0,o=!0}catch(a){throw console.error(`[Session ${this.id}] setPermissionMode(${r}) FAILED: ${$n(a)}`),this.pendingPlanApproval=!0,new Error(`Failed to switch permission mode to ${r}: ${$n(a)}`)}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,r!=="plan"&&(this.planModeApproved=!0)),o&&(n=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
41
+ /agent_respond --interrupt <id-or-name> <message>`};let r=!1,o=n;o.startsWith("--interrupt ")&&(r=!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 a=o.slice(0,s),d=o.slice(s+1).trim();return d?{text:(await Mn(g,{session:a,message:d,interrupt:r,userInitiated:!0})).text}:{text:"Error: Empty message. Usage: /agent_respond <id-or-name> <message>"}}})}function Ai(e){e.registerCommand({name:"agent_stats",description:"Show OpenClaw Code Agent usage metrics",acceptsArgs:!1,requireAuth:!0,handler:()=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=g.getMetrics(),n=g.list("running").length;return{text:On(t,n)}}})}var ac=50;function wi(e){e.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:t=>{if(!g)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let n=(t.args??"").trim();if(!n)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=n.split(/\s+/),o="",s=!1,a=ac;for(let c=0;c<r.length;c++)if(r[c]==="--full")s=!0;else if(r[c]==="--lines"&&c+1<r.length){let f=parseInt(r[c+1],10);!isNaN(f)&&f>0&&(a=f),c++}else o||(o=r[c]);return o?{text:Rn(g,o,{full:s,lines:a})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}import{execFile as ji}from"child_process";import{existsSync as rl}from"fs";import{fileURLToPath as Di}from"url";import{dirname as ol,join as _r}from"path";import{EventEmitter as Fc}from"events";import Ri from"crypto";var Oi="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var uc=128,mt,Et,mc=e=>{!mt||mt.length<e?(mt=Buffer.allocUnsafe(e*uc),Ri.randomFillSync(mt),Et=0):Et+e>mt.length&&(Ri.randomFillSync(mt),Et=0),Et+=e};var Pi=(e=21)=>{mc(e|=0);let t="";for(let n=Et-e;n<Et;n++)t+=Oi[mt[n]&63];return t};import{query as dc}from"@anthropic-ai/claude-agent-sdk";var Fn=class{name="claude-code";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=["AskUserQuestion"];planApprovalToolNames=["ExitPlanMode","set_permission_mode"];launch(t){let n={cwd:t.cwd,model:t.model,permissionMode:t.permissionMode,allowDangerouslySkipPermissions:!0,allowedTools:t.allowedTools,systemPrompt:t.systemPrompt,includePartialMessages:!0,abortController:t.abortController,mcpServers:t.mcpServers};t.resumeSessionId&&(n.resume=t.resumeSessionId,n.forkSession=t.forkSession??!1);let r=dc({prompt:t.prompt,options:n});return{messages:this.adaptMessages(r),async setPermissionMode(o){typeof r.setPermissionMode=="function"&&await r.setPermissionMode(o)},async streamInput(o){typeof r.streamInput=="function"&&await r.streamInput(o)},async interrupt(){typeof r.interrupt=="function"&&await r.interrupt()}}}buildUserMessage(t,n){return{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:n}}async*adaptMessages(t){for await(let n of t){let r=n;if(r.type==="system"&&r.subtype==="init")yield{type:"init",session_id:r.session_id??""};else if(r.type==="system"&&r.subtype==="status"&&r.permissionMode)yield{type:"permission_mode_change",mode:r.permissionMode};else if(r.type==="assistant")for(let o of r.message?.content??[])o.type==="text"?yield{type:"text",text:o.text}:o.type==="tool_use"&&(yield{type:"tool_use",name:o.name,input:o.input});else r.type==="result"&&(yield{type:"result",data:{success:r.subtype==="success",duration_ms:r.duration_ms??0,total_cost_usd:r.total_cost_usd??0,num_turns:r.num_turns??0,result:r.result,session_id:r.session_id??""}})}}};import{parse as gc,resolve as Ic}from"path";import{Codex as hc}from"@openai/codex-sdk";var pc=["proceed","continue","implement","apply","run","merge","deploy","commit"],cc=["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"],lc=["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 fc(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function kn(e){let t=fc(e);if(!t||lc.some(r=>t.includes(r)))return!1;let n=pc.some(r=>t.includes(r));return cc.some(r=>t.includes(r))?n||t.includes("confirm"):t.endsWith("?")?n:!1}var Ci=1e4,Mi="codex:waiting-for-user",yc=1.1/1e6,Sc=.275/1e6,xc=4.4/1e6,Tc="OPENCLAW_CODEX_HEARTBEAT_MS",bc="OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS";function Ac(e){if(!e)return 0;let t=e.cached_input_tokens??0,n=Math.max(0,(e.input_tokens??0)-t),r=e.output_tokens??0;return n*yc+t*Sc+r*xc}function Fi(e,t={}){return{success:!1,duration_ms:0,total_cost_usd:0,num_turns:0,session_id:e,...t}}function wc(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 Oc(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(`
42
+ `)}function ki(e){return e instanceof Error?e.message:String(e)}function Rc(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Pc(e){return gc(Ic(e)).root||"/"}function Cc(e){let n=[Pc(e)];return n.push(...Rc(process.env[bc])),[...new Set(n)]}function Mc(e,t){let r=(t??e.permissionMode)==="bypassPermissions"?Cc(e.cwd):void 0;return{model:e.model,modelReasoningEffort:e.reasoningEffort,workingDirectory:e.cwd,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0,additionalDirectories:r}}var En=class{constructor(t={}){this.deps=t}name="codex";supportedPermissionModes=["default","plan","acceptEdits","bypassPermissions"];questionToolNames=[Mi];planApprovalToolNames=[];activityHeartbeatMs(){let t=Number.parseInt(process.env[Tc]??String(Ci),10);return!Number.isFinite(t)||t<=0?Ci:t}createCodexClient(){return this.deps.createCodex?.()??new hc}launch(t){let n=t.permissionMode==="plan",r=t.permissionMode==="plan"?"default":t.permissionMode,o=t.resumeSessionId,s=0,a=0,d=this.activityHeartbeatMs(),c,f,$=!1,le=!0,oe,Q=[],Z=null,q=!1,Fe=!1;function Qe(){Z&&(Z(),Z=null)}function Ze(H){Q.push(H),Qe()}function Nr(){q=!0,Qe()}function Vn(H){!H||Fe||(Fe=!0,Ze({type:"init",session_id:H}))}async function*Gi(){for(;;){for(;Q.length>0;)yield Q.shift();if(q)return;await new Promise(H=>{Z=H})}}let Zt=()=>Mc(t,r),Vi=()=>(c||(c=this.createCodexClient()),f||(le&&t.resumeSessionId?f=c.resumeThread(t.resumeSessionId,Zt()):o?f=c.resumeThread(o,Zt()):f=c.startThread(Zt())),$&&o&&(f=c.resumeThread(o,Zt()),$=!1),Vn(f.id??o??void 0),f),Kr=async H=>{let Hn=Date.now();a+=1;let Lr="",Wn=!1,qn,Bi=le&&n?Oc(H):H,en=pt=>{Wn||(Wn=!0,Ze({type:"result",data:Fi(o??"",{duration_ms:Date.now()-Hn,total_cost_usd:s,num_turns:a,...pt,session_id:o??""})}))};try{let pt=Vi(),vr=pt.id??o??void 0;vr&&(o=vr,Vn(o)),oe=new AbortController,t.abortController?.signal.aborted&&oe.abort(t.abortController.signal.reason),qn=setInterval(()=>{Ze({type:"activity"})},d);let Hi=await pt.runStreamed(Bi,{signal:oe.signal});for await(let se of Hi.events){if(se.type==="thread.started"){o=se.thread_id,Vn(o);continue}if(se.type==="item.completed"){(se.item.type==="agent_message"||se.item.type==="reasoning")&&(Lr+=`${se.item.text}
43
+ `,Ze({type:"text",text:se.item.text}));continue}if(se.type==="error"){Ze({type:"text",text:`[codex:error] ${se.message}`});continue}if(se.type==="turn.failed"){en({success:!1,result:se.error.message,session_id:o??""});continue}if(se.type==="turn.completed"){s+=Ac(se.usage);let jr=Lr.slice(-500);kn(jr)&&Ze({type:"tool_use",name:Mi,input:{text:jr}}),en({success:!0,session_id:o??""})}}Wn||en({success:!1,result:"Codex turn ended without terminal event",session_id:o??""})}catch(pt){en({success:!1,result:ki(pt),session_id:o??""})}finally{qn&&clearInterval(qn),oe=void 0,le=!1}},Bn=()=>{oe?.abort(t.abortController?.signal.reason??"interrupted")};return t.abortController?.signal&&t.abortController.signal.addEventListener("abort",Bn),(async()=>{try{let H=t.prompt;if(typeof H=="string"){await Kr(H);return}for await(let Hn of H)if(t.abortController?.signal.aborted||(await Kr(wc(Hn)),t.abortController?.signal.aborted))break}finally{t.abortController?.signal.removeEventListener("abort",Bn),Nr()}})().catch(H=>{Ze({type:"result",data:Fi(o??"",{success:!1,result:ki(H),total_cost_usd:s,num_turns:a,session_id:o??""})}),t.abortController?.signal.removeEventListener("abort",Bn),Nr()}),{messages:Gi(),async setPermissionMode(H){r=H,$=!0},async interrupt(){oe?.abort("interrupted")}}}buildUserMessage(t,n){return{type:"user",text:t,session_id:n}}};var Er=new Map;function Ei(e){Er.set(e.name,e)}function $r(e){let t=Er.get(e);if(!t)throw new Error(`Unknown agent harness: "${e}". Available: ${[...Er.keys()].join(", ")}`);return t}function $i(){let e=T.defaultHarness??"claude-code";return $r(e)}Ei(new Fn);Ei(new En);var Ui=200,kc=120*1e3;function $n(e){return e instanceof Error?e.message:String(e)}var Ec={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]},Ur=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})}}},Un=class extends Fc{id;name;harnessSessionId;harness;harnessHandle;prompt;workdir;model;reasoningEffort;systemPrompt;allowedTools;permissionMode;currentPermissionMode;pendingModeSwitch;resumeSessionId;forkSession;multiTurn;messageStream;_status="starting";error;startedAt;completedAt;abortController;outputBuffer=[];result;costUsd=0;originChannel;originThreadId;originAgentId;originSessionKey;pendingPlanApproval=!1;lobsterResumeToken;killReason="unknown";waitingForInputFired=!1;lastTurnHadQuestion=!1;planModeApproved=!1;autoRespondCount=0;timers=new Map;constructor(t,n){super(),this.id=Pi(8),this.name=n,this.harness=t.harness?$r(t.harness):$i();let r=this.harness.name==="codex";this.prompt=t.prompt,this.workdir=t.workdir,this.model=t.model??(r?T.model:void 0)??T.defaultModel,this.reasoningEffort=t.reasoningEffort??(r?T.reasoningEffort:void 0),this.systemPrompt=t.systemPrompt,this.allowedTools=t.allowedTools,this.permissionMode=t.permissionMode??T.permissionMode,this.currentPermissionMode=r&&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(!Ec[this._status].includes(t))throw new Error(`Session state error: cannot transition from ${this._status} to ${t}. This is an internal error \u2014 please report it.`);let n=this._status;this._status=t,this.emit("statusChange",this,t,n)}setTimer(t,n,r){this.clearTimer(t),this.timers.set(t,setTimeout(r,n))}clearTimer(t){let n=this.timers.get(t);n&&(clearTimeout(n),this.timers.delete(t))}clearAllTimers(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear()}async start(){try{let t;this.multiTurn?(this.messageStream=new Ur,this.messageStream.push(this.harness.buildUserMessage(this.prompt,"")),t=this.messageStream):t=this.prompt;let n=this.harness.launch({prompt:t,cwd:this.workdir,model:this.model,reasoningEffort:this.reasoningEffort,permissionMode:this.permissionMode,systemPrompt:this.systemPrompt,allowedTools:this.allowedTools,resumeSessionId:this.resumeSessionId,forkSession:this.forkSession,abortController:this.abortController,mcpServers:oi()});this.harnessHandle=n,this.setTimer("startup",kc,()=>{this._status==="starting"&&this.kill("startup-timeout")})}catch(t){let n=t instanceof Error?t.message:String(t);this.transitionToTerminal("failed",{error:n});return}this.consumeMessages(this.harnessHandle.messages).catch(t=>{let n=t instanceof Error?t.message:String(t),r=t instanceof Error?t.stack:void 0;console.error(`[Session ${this.id}] consumeMessages error: ${n}`,r),this.isActive&&this.transitionToTerminal("failed",{error:n})})}async sendMessage(t){if(this._status!=="running")throw new Error(`Session is not running (status: ${this._status})`);this.resetIdleTimer(),this.waitingForInputFired=!1;let n=t;if(this.pendingModeSwitch){let r=this.pendingModeSwitch,o=!1,s=!1;if(this.harnessHandle?.setPermissionMode)try{await this.harnessHandle.setPermissionMode(r),this.currentPermissionMode=r,this.pendingModeSwitch=void 0,s=!0,o=!0}catch(a){throw console.error(`[Session ${this.id}] setPermissionMode(${r}) FAILED: ${$n(a)}`),this.pendingPlanApproval=!0,new Error(`Failed to switch permission mode to ${r}: ${$n(a)}`)}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,r!=="plan"&&(this.planModeApproved=!0)),o&&(n=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
44
44
 
45
45
  ${t}`)}else if(this.pendingPlanApproval&&!this.planModeApproved){let r=this.harness.planApprovalToolNames;if(n=`[SYSTEM: The user wants changes to your plan. Revise the plan based on their feedback below,${r.length>0?` then call ${r.join(" or ")} again to re-submit for approval.`:" then re-submit your revised plan for approval."} Do NOT start implementing yet.]
46
46
 
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: ${$n(s)}`)}}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(n,this.harnessSessionId??""));else if(this.harnessHandle?.streamInput){let r=this.harness.buildUserMessage(n,this.harnessSessionId??"");async function*o(){yield r}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){this.harnessHandle?.interrupt&&await this.harnessHandle.interrupt()}switchPermissionMode(t){this.pendingModeSwitch=t}get isActive(){return this._status==="starting"||this._status==="running"}kill(t){this.transitionToTerminal("killed",{reason:t})}complete(t="done"){this.transitionToTerminal("completed",{reason:t})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}resetIdleTimer(){if(!this.multiTurn)return;let t=(T.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: ${$n(t)}`)}),this.abortController.abort()}transitionToTerminal(t,n={}){this.isActive&&(n.reason&&(this.killReason=n.reason),n.error!==void 0&&(this.error=n.error),this.completedAt=Date.now(),this.transition(t),this.teardown())}async consumeMessages(t){for await(let n of t){if(!this.isActive)break;if(this.resetIdleTimer(),n.type==="init")this.clearTimer("startup"),this.harnessSessionId=n.session_id,this._status==="starting"&&this.transition("running");else if(n.type==="text")this.waitingForInputFired=!1,this.pendingPlanApproval||(this.lastTurnHadQuestion=!1),this.outputBuffer.push(n.text),this.outputBuffer.length>Ui&&this.outputBuffer.splice(0,this.outputBuffer.length-Ui),this.emit("output",this,n.text);else if(n.type==="tool_use")this.harness.questionToolNames.includes(n.name)?(this.lastTurnHadQuestion=!0,this.currentPermissionMode==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0)):this.harness.planApprovalToolNames.includes(n.name)&&!this.planModeApproved&&(this.lastTurnHadQuestion=!0,this.pendingPlanApproval=!0),this.emit("toolUse",this,n.name,n.input);else if(n.type==="permission_mode_change"){let r=this.currentPermissionMode;this.currentPermissionMode=n.mode,n.mode!=="plan"&&r==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0,this.lastTurnHadQuestion=!0)}else if(n.type==="result"){if(this.result={subtype:n.data.success?"success":"error",duration_ms:n.data.duration_ms,total_cost_usd:n.data.total_cost_usd,num_turns:n.data.num_turns,result:n.data.result,is_error:!n.data.success,session_id:n.data.session_id},this.costUsd=n.data.total_cost_usd,this.multiTurn&&this.messageStream&&n.data.success){this.resetIdleTimer(),this.currentPermissionMode==="plan"&&!this.pendingPlanApproval&&!this.planModeApproved&&(this.pendingPlanApproval=!0);let o=this.pendingPlanApproval||this.lastTurnHadQuestion,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(n.data.success?"completed":"failed");this.lastTurnHadQuestion=!1}else n.type}}};import{mkdirSync as $c,readFileSync as Uc,readdirSync as _c,renameSync as Nc,statSync as Kc,unlinkSync as Lc,writeFileSync as _i}from"fs";import{homedir as vc,tmpdir as Ni}from"os";import{dirname as jc,join as Nn}from"path";function Dc(e){let t=e.OPENCLAW_HOME?.trim();return t||Nn(vc(),".openclaw")}function Gc(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||Nn(Dc(e),"code-agent-sessions.json")}var Vc=new Set(["completed","failed","killed"]),Bc=new Set(["running","completed","failed","killed"]),Hc=1440*60*1e3;function Ki(e){return e instanceof Error?e.message:String(e)}function Wc(e){return!!e&&typeof e=="object"}function _n(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function dt(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Li(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function qc(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function zc(e){return e==="default"||e==="plan"||e==="acceptEdits"||e==="bypassPermissions"?e:void 0}function Yc(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function Xc(e){if(typeof e=="string"&&Bc.has(e))return e==="running"?"killed":e}function Jc(e){if(!Wc(e))return;let t=_n(e.harnessSessionId);if(!t)return;let n=Xc(e.status);if(n)return{sessionId:dt(e.sessionId),harnessSessionId:t,name:_n(e.name,t),prompt:_n(e.prompt),workdir:_n(e.workdir,"(unknown)"),model:dt(e.model),reasoningEffort:qc(e.reasoningEffort),createdAt:Li(e.createdAt),completedAt:Li(e.completedAt),status:n,killReason:Yc(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:dt(e.originAgentId),originChannel:dt(e.originChannel),originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originSessionKey:dt(e.originSessionKey),outputPath:dt(e.outputPath),harness:dt(e.harness),notifyOnTurnEnd:typeof e.notifyOnTurnEnd=="boolean"?e.notifyOnTurnEnd:void 0,currentPermissionMode:zc(e.currentPermissionMode)}}var Kn=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;indexPath;constructor(t={}){let n=t.env??process.env;this.indexPath=t.indexPath??Gc(n),n.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){try{let t=Uc(this.indexPath,"utf-8"),n=JSON.parse(t);if(!Array.isArray(n))return;let r=!1;for(let o of n){let s=Jc(o);if(!s){r=!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)}r&&this.saveIndex()}catch{}}saveIndex(){try{$c(jc(this.indexPath),{recursive:!0});let t=this.indexPath+".tmp";_i(t,JSON.stringify([...this.persisted.values()],null,2),"utf-8"),Nc(t,this.indexPath)}catch(t){console.warn(`[SessionStore] Failed to save session index: ${Ki(t)}`)}}markRunning(t){if(!t.harnessSessionId)return;let n={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,harness:t.harnessName,notifyOnTurnEnd:t.notifyOnTurnEnd,currentPermissionMode:t.currentPermissionMode};this.persisted.set(n.harnessSessionId,n),this.idIndex.set(t.id,n.harnessSessionId),this.nameIndex.set(t.name,n.harnessSessionId),this.saveIndex()}hasRecordedSession(t){return this.idIndex.has(t)}persistTerminal(t){if(!t.harnessSessionId)return;let n;try{let o=Nn(Ni(),`openclaw-agent-${t.id}.txt`),s=t.getOutput().join(`
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}: ${Ki(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,notifyOnTurnEnd:t.notifyOnTurnEnd,currentPermissionMode:t.currentPermissionMode};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 d of this.persisted.values()){if(d.name!==t){a++;continue}let c=d.createdAt??Number.NEGATIVE_INFINITY,f=d.completedAt??Number.NEGATIVE_INFINITY;(c>r||c===r&&f>o||c===r&&f===o&&a>s)&&(n=d,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=Kc(s).mtimeMs;t-a>Hc&&Lc(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 Qc=new Set(["completed","failed","killed"]),Ln=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),Qc.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 Zc}from"child_process";import{randomUUID as el}from"crypto";var vi=3e4,tl=2e3,nl=2e4,vn=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(d=>d.trim()).filter(Boolean);if(a.length>=2){let[d,c,f]=a,$=f??c,le=f?c:void 0;if(d&&$)return{channel:d,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=tl*2**n;return Math.min(r,nl)}executeWithRetries(t,n,r=1){let o=Date.now();console.info(`[WakeDispatcher] ${n.target} ${n.phase} started attempt ${r}/${vn} for ${n.label} session=${n.sessionId}`),Zc("openclaw",t,{timeout:vi},s=>{let a=Date.now()-o;if(!s){console.info(`[WakeDispatcher] ${n.target} ${n.phase} completed attempt ${r}/${vn} for ${n.label} session=${n.sessionId} in ${a}ms`);return}let d=`[WakeDispatcher] ${n.target} ${n.phase} failed`;if(r>=vn){console.error(`${d} after ${r} attempts for ${n.label} session=${n.sessionId} in ${a}ms: ${s.message}`),n.onFinalFailure?.();return}let c=this.retryDelayMs(r);console.error(`${d} attempt ${r}/${vn} 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,d){let c=["gateway","call","chat.send","--expect-final","--timeout",String(vi),"--params",JSON.stringify({sessionKey:t,message:n,deliver:a,idempotencyKey:el()})];this.executeWithRetries(c,{label:r,sessionId:o,target:"chat.send",phase:s,onFinalFailure:d})}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 sl(){let e=process.env.OPENCLAW_CODE_AGENT_PLAN_WORKFLOW_PATH?.trim();if(e)return e;let t=ol(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(rl(r))return r;return Di(new URL("../workflows/plan-approval.lobster",import.meta.url))}var il=sl(),al=new Set(["completed","failed","killed"]),Dn=new Set(["starting","running"]),ul=5e3,ml=3e4;function dl(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),d=a?.resumeToken??a?.requiresApproval?.resumeToken??a?.details?.requiresApproval?.resumeToken;if(n(d))return d.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=5,n=50){this.maxSessions=t,this.maxPersistedSessions=n,this.store=new Kn,this.metrics=new Ln,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(d=>Dn.has(d.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||mi(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",(d,c)=>{c==="running"&&s.harnessSessionId?this.store.markRunning(s):al.has(c)&&this.onSessionTerminal(s)}),s.on("turnEnd",(d,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 d=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`,c=Je(d,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 ${T.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:il,argsJson:r,timeoutMs:0})];ji("openclaw",o,{timeout:ml},(s,a,d)=>{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:
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: ${$n(s)}`)}}if(this.multiTurn&&this.messageStream)this.messageStream.push(this.harness.buildUserMessage(n,this.harnessSessionId??""));else if(this.harnessHandle?.streamInput){let r=this.harness.buildUserMessage(n,this.harnessSessionId??"");async function*o(){yield r}await this.harnessHandle.streamInput(o())}else throw new Error("Session does not support follow-up messages (launched in single-turn mode).")}async interrupt(){this.harnessHandle?.interrupt&&await this.harnessHandle.interrupt()}switchPermissionMode(t){this.pendingModeSwitch=t}get isActive(){return this._status==="starting"||this._status==="running"}kill(t){this.transitionToTerminal("killed",{reason:t})}complete(t="done"){this.transitionToTerminal("completed",{reason:t})}incrementAutoRespond(){this.autoRespondCount++}resetAutoRespond(){this.autoRespondCount=0}getOutput(t){return t===void 0?this.outputBuffer.slice():this.outputBuffer.slice(-t)}resetIdleTimer(){if(!this.multiTurn)return;let t=(T.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: ${$n(t)}`)}),this.abortController.abort()}transitionToTerminal(t,n={}){this.isActive&&(n.reason&&(this.killReason=n.reason),n.error!==void 0&&(this.error=n.error),this.completedAt=Date.now(),this.transition(t),this.teardown())}async consumeMessages(t){for await(let n of t){if(!this.isActive)break;if(this.resetIdleTimer(),n.type==="init")this.clearTimer("startup"),this.harnessSessionId=n.session_id,this._status==="starting"&&this.transition("running");else if(n.type==="text")this.waitingForInputFired=!1,this.pendingPlanApproval||(this.lastTurnHadQuestion=!1),this.outputBuffer.push(n.text),this.outputBuffer.length>Ui&&this.outputBuffer.splice(0,this.outputBuffer.length-Ui),this.emit("output",this,n.text);else if(n.type==="tool_use")this.harness.questionToolNames.includes(n.name)?(this.lastTurnHadQuestion=!0,this.currentPermissionMode==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0)):this.harness.planApprovalToolNames.includes(n.name)&&!this.planModeApproved&&(this.lastTurnHadQuestion=!0,this.pendingPlanApproval=!0),this.emit("toolUse",this,n.name,n.input);else if(n.type==="permission_mode_change"){let r=this.currentPermissionMode;this.currentPermissionMode=n.mode,n.mode!=="plan"&&r==="plan"&&!this.planModeApproved&&(this.pendingPlanApproval=!0,this.lastTurnHadQuestion=!0)}else if(n.type==="result"){if(this.result={subtype:n.data.success?"success":"error",duration_ms:n.data.duration_ms,total_cost_usd:n.data.total_cost_usd,num_turns:n.data.num_turns,result:n.data.result,is_error:!n.data.success,session_id:n.data.session_id},this.costUsd=n.data.total_cost_usd,this.multiTurn&&this.messageStream&&n.data.success){this.resetIdleTimer(),this.currentPermissionMode==="plan"&&!this.pendingPlanApproval&&!this.planModeApproved&&(this.pendingPlanApproval=!0);let o=this.pendingPlanApproval||this.lastTurnHadQuestion,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(n.data.success?"completed":"failed");this.lastTurnHadQuestion=!1}else n.type}}};import{mkdirSync as $c,readFileSync as Uc,readdirSync as _c,renameSync as Nc,statSync as Kc,unlinkSync as Lc,writeFileSync as _i}from"fs";import{homedir as vc,tmpdir as Ni}from"os";import{dirname as jc,join as Nn}from"path";function Dc(e){let t=e.OPENCLAW_HOME?.trim();return t||Nn(vc(),".openclaw")}function Gc(e){let t=e.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return t||Nn(Dc(e),"code-agent-sessions.json")}var Vc=new Set(["completed","failed","killed"]),Bc=new Set(["running","completed","failed","killed"]),Hc=1440*60*1e3;function Ki(e){return e instanceof Error?e.message:String(e)}function Wc(e){return!!e&&typeof e=="object"}function _n(e,t=""){return typeof e=="string"&&e.trim().length>0?e:t}function dt(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Li(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function qc(e){return e==="low"||e==="medium"||e==="high"?e:void 0}function zc(e){return e==="default"||e==="plan"||e==="acceptEdits"||e==="bypassPermissions"?e:void 0}function Yc(e){return e==="user"||e==="idle-timeout"||e==="startup-timeout"||e==="shutdown"||e==="done"||e==="unknown"?e:void 0}function Xc(e){if(typeof e=="string"&&Bc.has(e))return e==="running"?"killed":e}function Jc(e){if(!Wc(e))return;let t=_n(e.harnessSessionId);if(!t)return;let n=Xc(e.status);if(n)return{sessionId:dt(e.sessionId),harnessSessionId:t,name:_n(e.name,t),prompt:_n(e.prompt),workdir:_n(e.workdir,"(unknown)"),model:dt(e.model),reasoningEffort:qc(e.reasoningEffort),createdAt:Li(e.createdAt),completedAt:Li(e.completedAt),status:n,killReason:Yc(e.killReason),costUsd:typeof e.costUsd=="number"&&Number.isFinite(e.costUsd)?e.costUsd:0,originAgentId:dt(e.originAgentId),originChannel:dt(e.originChannel),originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originSessionKey:dt(e.originSessionKey),outputPath:dt(e.outputPath),harness:dt(e.harness),currentPermissionMode:zc(e.currentPermissionMode)}}var Kn=class{persisted=new Map;idIndex=new Map;nameIndex=new Map;indexPath;constructor(t={}){let n=t.env??process.env;this.indexPath=t.indexPath??Gc(n),n.OPENCLAW_DEBUG_SESSION_STORE==="1"&&console.warn(`[SessionStore] index path: ${this.indexPath}`),this.loadIndex()}loadIndex(){try{let t=Uc(this.indexPath,"utf-8"),n=JSON.parse(t);if(!Array.isArray(n))return;let r=!1;for(let o of n){let s=Jc(o);if(!s){r=!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)}r&&this.saveIndex()}catch{}}saveIndex(){try{$c(jc(this.indexPath),{recursive:!0});let t=this.indexPath+".tmp";_i(t,JSON.stringify([...this.persisted.values()],null,2),"utf-8"),Nc(t,this.indexPath)}catch(t){console.warn(`[SessionStore] Failed to save session index: ${Ki(t)}`)}}markRunning(t){if(!t.harnessSessionId)return;let n={sessionId:t.id,harnessSessionId:t.harnessSessionId,name:t.name,prompt:t.prompt,workdir:t.workdir,model:t.model,reasoningEffort:t.reasoningEffort,createdAt:t.startedAt,status:"running",costUsd:0,originAgentId:t.originAgentId,originChannel:t.originChannel,originThreadId:t.originThreadId,originSessionKey:t.originSessionKey,harness:t.harnessName,currentPermissionMode:t.currentPermissionMode};this.persisted.set(n.harnessSessionId,n),this.idIndex.set(t.id,n.harnessSessionId),this.nameIndex.set(t.name,n.harnessSessionId),this.saveIndex()}hasRecordedSession(t){return this.idIndex.has(t)}persistTerminal(t){if(!t.harnessSessionId)return;let n;try{let o=Nn(Ni(),`openclaw-agent-${t.id}.txt`),s=t.getOutput().join(`
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}: ${Ki(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};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 d of this.persisted.values()){if(d.name!==t){a++;continue}let c=d.createdAt??Number.NEGATIVE_INFINITY,f=d.completedAt??Number.NEGATIVE_INFINITY;(c>r||c===r&&f>o||c===r&&f===o&&a>s)&&(n=d,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=Kc(s).mtimeMs;t-a>Hc&&Lc(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 Qc=new Set(["completed","failed","killed"]),Ln=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),Qc.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 Zc}from"child_process";import{randomUUID as el}from"crypto";var vi=3e4,tl=2e3,nl=2e4,vn=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(d=>d.trim()).filter(Boolean);if(a.length>=2){let[d,c,f]=a,$=f??c,le=f?c:void 0;if(d&&$)return{channel:d,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=tl*2**n;return Math.min(r,nl)}executeWithRetries(t,n,r=1){let o=Date.now();console.info(`[WakeDispatcher] ${n.target} ${n.phase} started attempt ${r}/${vn} for ${n.label} session=${n.sessionId}`),Zc("openclaw",t,{timeout:vi},s=>{let a=Date.now()-o;if(!s){console.info(`[WakeDispatcher] ${n.target} ${n.phase} completed attempt ${r}/${vn} for ${n.label} session=${n.sessionId} in ${a}ms`);return}let d=`[WakeDispatcher] ${n.target} ${n.phase} failed`;if(r>=vn){console.error(`${d} after ${r} attempts for ${n.label} session=${n.sessionId} in ${a}ms: ${s.message}`),n.onFinalFailure?.();return}let c=this.retryDelayMs(r);console.error(`${d} attempt ${r}/${vn} 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,d){let c=["gateway","call","chat.send","--expect-final","--timeout",String(vi),"--params",JSON.stringify({sessionKey:t,message:n,deliver:a,idempotencyKey:el()})];this.executeWithRetries(c,{label:r,sessionId:o,target:"chat.send",phase:s,onFinalFailure:d})}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 sl(){let e=process.env.OPENCLAW_CODE_AGENT_PLAN_WORKFLOW_PATH?.trim();if(e)return e;let t=ol(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(rl(r))return r;return Di(new URL("../workflows/plan-approval.lobster",import.meta.url))}var il=sl(),al=new Set(["completed","failed","killed"]),Dn=new Set(["starting","running"]),ul=5e3,ml=3e4;function dl(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),d=a?.resumeToken??a?.requiresApproval?.resumeToken??a?.details?.requiresApproval?.resumeToken;if(n(d))return d.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=5,n=50){this.maxSessions=t,this.maxPersistedSessions=n,this.store=new Kn,this.metrics=new Ln,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(d=>Dn.has(d.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||mi(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",(d,c)=>{c==="running"&&s.harnessSessionId?this.store.markRunning(s):al.has(c)&&this.onSessionTerminal(s)}),s.on("turnEnd",(d,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 d=t.error||t.result?.is_error&&t.result.result||t.result?.result||this.extractLastOutputLine(t)||`Session failed with no error details (session=${t.id}, subtype=${t.result?.subtype??"none"}, turns=${t.result?.num_turns??0})`,c=Je(d,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 ${T.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:il,argsJson:r,timeoutMs:0})];ji("openclaw",o,{timeout:ml},(s,a,d)=>{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
49
 
50
50
  ${Je(n,800)}`);return}let c=typeof a=="string"?a:String(a??""),f=typeof d=="string"?d:String(d??""),$=dl(`${c}
51
51
  ${f}`);if(!$){let oe=`${c}
@@ -61,5 +61,5 @@ ${n}
61
61
  Reply to approve or provide feedback.`:`\u{1F514} [${t.name}] Waiting for input`,s;if(r){let a=T.planApproval??"delegate";if(a==="ask"){this.runLobsterApproval(t,n);return}else a==="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):",n,"","\u2501\u2501\u2501 STEP 2 (MANDATORY): Notify the user \u2501\u2501\u2501","After reading the full plan, use the message tool to send the user a summary that includes:","- What files/components will be changed","- Risk level (low/medium/high) and why","- Scope: does this match the original task or has it expanded?","- Any concerns or assumptions the plan makes","This message creates accountability \u2014 you cannot approve blindly.","","\u2501\u2501\u2501 STEP 3 (ONLY AFTER steps 1 and 2): Decide \u2501\u2501\u2501","You are the delegated decision-maker. Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- You have sent the user the summary message","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure \u2014 when in doubt, always escalate","",`If approving: agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`,"If escalating: tell the user you need their decision and WAIT for his explicit response.",`To request changes: agent_respond(session='${t.id}', message='<your feedback>') \u2014 do NOT set approve=true. The agent will revise the plan.`].join(`
62
62
  `):s=["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${t.id}', message='Approved. Go ahead.', approve=true)`].join(`
63
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:",n,"",`Use agent_respond(session='${t.id}', message='...') to send a reply, or agent_output(session='${t.id}', full: true) to see full context before deciding.`].join(`
64
- `);this.dispatchSessionNotification(t,{label:r?"plan-approval":"waiting",userMessage:o,wakeMessage:s,notifyUser:r?"always":"on-wake-fallback"})}onTurnEnd(t,n){if(t.notifyOnTurnEnd!==!1){if(n||t.pendingPlanApproval){this.triggerWaitingForInputEvent(t);return}this.shouldEmitTurnCompleteWake(t)&&this.triggerTurnCompleteEventWithSignal(t)}}shouldEmitTurnCompleteWake(t){let n=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===n?!1:(this.lastTurnCompleteMarkers.set(t.id,n),!0)}shouldEmitTerminalWake(t){let n=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===n?!1:(this.lastTerminalWakeMarkers.set(t.id,n),!0)}triggerTurnCompleteEventWithSignal(t){let n=this.getOutputPreview(t),r=En(n),o=`$${(t.costUsd??0).toFixed(2)}`,s=r?"yes":"no",a=`\u{1F504} [${t.name}] Turn done | ${o} | Waiting input: ${s}`,d=["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):",n,...this.originThreadLine(t)?["",this.originThreadLine(t)]:[]].join(`
65
- `);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:a,wakeMessage:d,notifyUser:"always"})}resolve(t){let n=this.sessions.get(t);if(n)return n;let r=[...this.sessions.values()].filter(s=>s.name===t);if(r.length===0)return;let o=r.filter(s=>Dn.has(s.status));return o.length>0?o.sort((s,a)=>a.startedAt-s.startedAt)[0]:r.sort((s,a)=>a.startedAt-s.startedAt)[0]}get(t){return this.sessions.get(t)}list(t){let n=[...this.sessions.values()];return t&&t!=="all"&&(n=n.filter(r=>r.status===t)),n.sort((r,o)=>o.startedAt-r.startedAt)}kill(t,n){let r=this.sessions.get(t);return r?(r.kill(n??"user"),!0):!1}killAll(t="user"){for(let n of this.sessions.values())Dn.has(n.status)&&this.kill(n.id,t);this.wakeDispatcher.clearPendingRetries()}resolveHarnessSessionId(t){let n=this.resolve(t);return this.store.resolveHarnessSessionId(t,n?.harnessSessionId)}getPersistedSession(t){return this.store.getPersistedSession(t)}listPersistedSessions(){return this.store.listPersistedSessions()}cleanup(){let t=Date.now(),n=(T.sessionGcAgeMinutes??1440)*6e4;for(let[r,o]of this.sessions)this.store.shouldGcActiveSession(o,t,n)&&(this.persistSession(o),this.sessions.delete(r),this.lastWaitingEventTimestamps.delete(r),this.lastTurnCompleteMarkers.delete(r),this.lastTerminalWakeMarkers.delete(r));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}};function sR(e){let t=null,n=null;e.registerTool(r=>ui(r),{optional:!1}),e.registerTool(r=>ci(r),{optional:!1}),e.registerTool(r=>li(r),{optional:!1}),e.registerTool(r=>fi(r),{optional:!1}),e.registerTool(r=>Ii(r),{optional:!1}),e.registerTool(r=>hi(r),{optional:!1}),yi(e),Si(e),xi(e),Ti(e),bi(e),Ai(e),wi(e),e.registerService({id:"openclaw-code-agent",start:r=>{let o=e.pluginConfig??e.getConfig?.()??{};si(o),t=new Gn(T.maxSessions,T.maxPersistedSessions),Er(t),n=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{t&&t.killAll("shutdown"),n&&clearInterval(n),n=null,t=null,Er(null)}})}export{sR as register};
64
+ `);this.dispatchSessionNotification(t,{label:r?"plan-approval":"waiting",userMessage:o,wakeMessage:s,notifyUser:r?"always":"on-wake-fallback"})}onTurnEnd(t,n){if(n||t.pendingPlanApproval){this.triggerWaitingForInputEvent(t);return}this.shouldEmitTurnCompleteWake(t)&&this.triggerTurnCompleteEventWithSignal(t)}shouldEmitTurnCompleteWake(t){let n=`${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.result?.duration_ms??0}`;return this.lastTurnCompleteMarkers.get(t.id)===n?!1:(this.lastTurnCompleteMarkers.set(t.id,n),!0)}shouldEmitTerminalWake(t){let n=`${t.status}|${t.completedAt??0}|${t.result?.session_id??""}|${t.result?.num_turns??0}|${t.killReason}`;return this.lastTerminalWakeMarkers.get(t.id)===n?!1:(this.lastTerminalWakeMarkers.set(t.id,n),!0)}triggerTurnCompleteEventWithSignal(t){let n=this.getOutputPreview(t),r=kn(n),o=`$${(t.costUsd??0).toFixed(2)}`,s=r?"yes":"no",a=`\u{1F504} [${t.name}] Turn done | ${o} | Waiting input: ${s}`,d=["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):",n,...this.originThreadLine(t)?["",this.originThreadLine(t)]:[]].join(`
65
+ `);this.dispatchSessionNotification(t,{label:"turn-complete",userMessage:a,wakeMessage:d,notifyUser:"always"})}resolve(t){let n=this.sessions.get(t);if(n)return n;let r=[...this.sessions.values()].filter(s=>s.name===t);if(r.length===0)return;let o=r.filter(s=>Dn.has(s.status));return o.length>0?o.sort((s,a)=>a.startedAt-s.startedAt)[0]:r.sort((s,a)=>a.startedAt-s.startedAt)[0]}get(t){return this.sessions.get(t)}list(t){let n=[...this.sessions.values()];return t&&t!=="all"&&(n=n.filter(r=>r.status===t)),n.sort((r,o)=>o.startedAt-r.startedAt)}kill(t,n){let r=this.sessions.get(t);return r?(r.kill(n??"user"),!0):!1}killAll(t="user"){for(let n of this.sessions.values())Dn.has(n.status)&&this.kill(n.id,t);this.wakeDispatcher.clearPendingRetries()}resolveHarnessSessionId(t){let n=this.resolve(t);return this.store.resolveHarnessSessionId(t,n?.harnessSessionId)}getPersistedSession(t){return this.store.getPersistedSession(t)}listPersistedSessions(){return this.store.listPersistedSessions()}cleanup(){let t=Date.now(),n=(T.sessionGcAgeMinutes??1440)*6e4;for(let[r,o]of this.sessions)this.store.shouldGcActiveSession(o,t,n)&&(this.persistSession(o),this.sessions.delete(r),this.lastWaitingEventTimestamps.delete(r),this.lastTurnCompleteMarkers.delete(r),this.lastTerminalWakeMarkers.delete(r));this.store.cleanupTmpOutputFiles(t),this.store.evictOldestPersisted(this.maxPersistedSessions)}};function sR(e){let t=null,n=null;e.registerTool(r=>ui(r),{optional:!1}),e.registerTool(r=>ci(r),{optional:!1}),e.registerTool(r=>li(r),{optional:!1}),e.registerTool(r=>fi(r),{optional:!1}),e.registerTool(r=>Ii(r),{optional:!1}),e.registerTool(r=>hi(r),{optional:!1}),yi(e),Si(e),xi(e),Ti(e),bi(e),Ai(e),wi(e),e.registerService({id:"openclaw-code-agent",start:r=>{let o=e.pluginConfig??e.getConfig?.()??{};si(o),t=new Gn(T.maxSessions,T.maxPersistedSessions),kr(t),n=setInterval(()=>t.cleanup(),300*1e3)},stop:()=>{t&&t.killAll("shutdown"),n&&clearInterval(n),n=null,t=null,kr(null)}})}export{sR as register};
@@ -2,7 +2,7 @@
2
2
  "id": "openclaw-code-agent",
3
3
  "name": "OpenClaw Code Agent",
4
4
  "description": "Orchestrate coding agent sessions from OpenClaw",
5
- "version": "2.0.0",
5
+ "version": "2.0.2",
6
6
  "configSchema": {
7
7
  "type": "object",
8
8
  "additionalProperties": false,
@@ -40,8 +40,8 @@
40
40
  },
41
41
  "maxPersistedSessions": {
42
42
  "type": "number",
43
- "default": 50,
44
- "description": "Maximum number of completed sessions to keep in memory for resume"
43
+ "default": 10000,
44
+ "description": "Maximum number of completed sessions to keep in memory for resume. In practice, the 24h GC TTL (`sessionGcAgeMinutes`) is the primary retention control."
45
45
  },
46
46
  "fallbackChannel": {
47
47
  "type": "string",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openclaw-code-agent",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {