@linzumi/cli 1.0.237 → 1.0.239

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.
@@ -1,41 +1,274 @@
1
1
  import { createRequire as __linzumiBundleCreateRequire } from 'node:module';
2
2
  const require = __linzumiBundleCreateRequire(import.meta.url);
3
- var Io=Object.create;var _t=Object.defineProperty;var Po=Object.getOwnPropertyDescriptor;var Eo=Object.getOwnPropertyNames;var Ao=Object.getPrototypeOf,Mo=Object.prototype.hasOwnProperty;var M=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var N=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);var qo=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Eo(n))!Mo.call(e,o)&&o!==t&&_t(e,o,{get:()=>n[o],enumerable:!(r=Po(n,o))||r.enumerable});return e};var Ie=(e,n,t)=>(t=e!=null?Io(Ao(e)):{},qo(n||!e||!e.__esModule?_t(t,"default",{value:e,enumerable:!0}):t,e));var H=N((Su,vt)=>{"use strict";var St=["nodebuffer","arraybuffer","fragments"],bt=typeof Blob<"u";bt&&St.push("blob");vt.exports={BINARY_TYPES:St,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bt,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Pe=N((bu,Ve)=>{"use strict";var{EMPTY_BUFFER:Oo}=H(),Tn=Buffer[Symbol.species];function Fo(e,n){if(e.length===0)return Oo;if(e.length===1)return e[0];let t=Buffer.allocUnsafe(n),r=0;for(let o=0;o<e.length;o++){let i=e[o];t.set(i,r),r+=i.length}return r<n?new Tn(t.buffer,t.byteOffset,r):t}function xt(e,n,t,r,o){for(let i=0;i<o;i++)t[r+i]=e[i]^n[i&3]}function wt(e,n){for(let t=0;t<e.length;t++)e[t]^=n[t&3]}function Lo(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function Cn(e){if(Cn.readOnly=!0,Buffer.isBuffer(e))return e;let n;return e instanceof ArrayBuffer?n=new Tn(e):ArrayBuffer.isView(e)?n=new Tn(e.buffer,e.byteOffset,e.byteLength):(n=Buffer.from(e),Cn.readOnly=!1),n}Ve.exports={concat:Fo,mask:xt,toArrayBuffer:Lo,toBuffer:Cn,unmask:wt};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=M("bufferutil");Ve.exports.mask=function(n,t,r,o,i){i<48?xt(n,t,r,o,i):e.mask(n,t,r,o,i)},Ve.exports.unmask=function(n,t){n.length<32?wt(n,t):e.unmask(n,t)}}catch{}});var Ct=N((vu,Tt)=>{"use strict";var kt=Symbol("kDone"),Rn=Symbol("kRun"),In=class{constructor(n){this[kt]=()=>{this.pending--,this[Rn]()},this.concurrency=n||1/0,this.jobs=[],this.pending=0}add(n){this.jobs.push(n),this[Rn]()}[Rn](){if(this.pending!==this.concurrency&&this.jobs.length){let n=this.jobs.shift();this.pending++,n(this[kt])}}};Tt.exports=In});var Ae=N((xu,Et)=>{"use strict";var Ee=M("zlib"),Rt=Pe(),jo=Ct(),{kStatusCode:It}=H(),Do=Buffer[Symbol.species],No=Buffer.from([0,0,255,255]),Ze=Symbol("permessage-deflate"),V=Symbol("total-length"),ge=Symbol("callback"),ee=Symbol("buffers"),ye=Symbol("error"),Qe,Pn=class{constructor(n,t,r){if(this._maxPayload=r|0,this._options=n||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Qe){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Qe=new jo(o)}}static get extensionName(){return"permessage-deflate"}offer(){let n={};return this._options.serverNoContextTakeover&&(n.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(n.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(n.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?n.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(n.client_max_window_bits=!0),n}accept(n){return n=this.normalizeParams(n),this.params=this._isServer?this.acceptAsServer(n):this.acceptAsClient(n),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let n=this._deflate[ge];this._deflate.close(),this._deflate=null,n&&n(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(n){let t=this._options,r=n.find(o=>!(t.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>o.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(n){let t=n[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(n){return n.forEach(t=>{Object.keys(t).forEach(r=>{let o=t[r];if(o.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(o=o[0],r==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else if(r==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=o})}),n}decompress(n,t,r){Qe.add(o=>{this._decompress(n,t,(i,s)=>{o(),r(i,s)})})}compress(n,t,r){Qe.add(o=>{this._compress(n,t,(i,s)=>{o(),r(i,s)})})}_decompress(n,t,r){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Ee.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ee.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Ze]=this,this._inflate[V]=0,this._inflate[ee]=[],this._inflate.on("error",Jo),this._inflate.on("data",Pt)}this._inflate[ge]=r,this._inflate.write(n),t&&this._inflate.write(No),this._inflate.flush(()=>{let i=this._inflate[ye];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=Rt.concat(this._inflate[ee],this._inflate[V]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[V]=0,this._inflate[ee]=[],t&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(n,t,r){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Ee.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ee.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[V]=0,this._deflate[ee]=[],this._deflate.on("data",$o)}this._deflate[ge]=r,this._deflate.write(n),this._deflate.flush(Ee.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Rt.concat(this._deflate[ee],this._deflate[V]);t&&(i=new Do(i.buffer,i.byteOffset,i.length-4)),this._deflate[ge]=null,this._deflate[V]=0,this._deflate[ee]=[],t&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Et.exports=Pn;function $o(e){this[ee].push(e),this[V]+=e.length}function Pt(e){if(this[V]+=e.length,this[Ze]._maxPayload<1||this[V]<=this[Ze]._maxPayload){this[ee].push(e);return}this[ye]=new RangeError("Max payload size exceeded"),this[ye].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ye][It]=1009,this.removeListener("data",Pt),this.reset()}function Jo(e){if(this[Ze]._inflate=null,this[ye]){this[ge](this[ye]);return}e[It]=1007,this[ge](e)}});var _e=N((wu,Ye)=>{"use strict";var{isUtf8:At}=M("buffer"),{hasBlob:Uo}=H(),Ko=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function zo(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function En(e){let n=e.length,t=0;for(;t<n;)if((e[t]&128)===0)t++;else if((e[t]&224)===192){if(t+1===n||(e[t+1]&192)!==128||(e[t]&254)===192)return!1;t+=2}else if((e[t]&240)===224){if(t+2>=n||(e[t+1]&192)!==128||(e[t+2]&192)!==128||e[t]===224&&(e[t+1]&224)===128||e[t]===237&&(e[t+1]&224)===160)return!1;t+=3}else if((e[t]&248)===240){if(t+3>=n||(e[t+1]&192)!==128||(e[t+2]&192)!==128||(e[t+3]&192)!==128||e[t]===240&&(e[t+1]&240)===128||e[t]===244&&e[t+1]>143||e[t]>244)return!1;t+=4}else return!1;return!0}function Bo(e){return Uo&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}Ye.exports={isBlob:Bo,isValidStatusCode:zo,isValidUTF8:En,tokenChars:Ko};if(At)Ye.exports.isValidUTF8=function(e){return e.length<24?En(e):At(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=M("utf-8-validate");Ye.exports.isValidUTF8=function(n){return n.length<32?En(n):e(n)}}catch{}});var Fn=N((ku,Dt)=>{"use strict";var{Writable:Go}=M("stream"),Mt=Ae(),{BINARY_TYPES:Wo,EMPTY_BUFFER:qt,kStatusCode:Ho,kWebSocket:Vo}=H(),{concat:An,toArrayBuffer:Qo,unmask:Zo}=Pe(),{isValidStatusCode:Yo,isValidUTF8:Ot}=_e(),Xe=Buffer[Symbol.species],J=0,Ft=1,Lt=2,jt=3,Mn=4,qn=5,en=6,On=class extends Go{constructor(n={}){super(),this._allowSynchronousEvents=n.allowSynchronousEvents!==void 0?n.allowSynchronousEvents:!0,this._binaryType=n.binaryType||Wo[0],this._extensions=n.extensions||{},this._isServer=!!n.isServer,this._maxPayload=n.maxPayload|0,this._skipUTF8Validation=!!n.skipUTF8Validation,this[Vo]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=J}_write(n,t,r){if(this._opcode===8&&this._state==J)return r();this._bufferedBytes+=n.length,this._buffers.push(n),this.startLoop(r)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Xe(r.buffer,r.byteOffset+n,r.length-n),new Xe(r.buffer,r.byteOffset,n)}let t=Buffer.allocUnsafe(n);do{let r=this._buffers[0],o=t.length-n;n>=r.length?t.set(this._buffers.shift(),o):(t.set(new Uint8Array(r.buffer,r.byteOffset,n),o),this._buffers[0]=new Xe(r.buffer,r.byteOffset+n,r.length-n)),n-=r.length}while(n>0);return t}startLoop(n){this._loop=!0;do switch(this._state){case J:this.getInfo(n);break;case Ft:this.getPayloadLength16(n);break;case Lt:this.getPayloadLength64(n);break;case jt:this.getMask();break;case Mn:this.getData(n);break;case qn:case en:this._loop=!1;return}while(this._loop);this._errored||n()}getInfo(n){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");n(o);return}let r=(t[0]&64)===64;if(r&&!this._extensions[Mt.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");n(o);return}if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");n(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");n(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");n(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");n(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");n(o);return}this._payloadLength===126?this._state=Ft:this._payloadLength===127?this._state=Lt:this.haveLength(n)}getPayloadLength16(n){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(n)}getPayloadLength64(n){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");n(o);return}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(n)}haveLength(n){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(t);return}this._masked?this._state=jt:this._state=Mn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Mn}getData(n){let t=qt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Zo(t,this._mask)}if(this._opcode>7){this.controlMessage(t,n);return}if(this._compressed){this._state=qn,this.decompress(t,n);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(n)}decompress(n,t){this._extensions[Mt.extensionName].decompress(n,this._fin,(o,i)=>{if(o)return t(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(s);return}this._fragments.push(i)}this.dataMessage(t),this._state===J&&this.startLoop(t)})}dataMessage(n){if(!this._fin){this._state=J;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=An(r,t):this._binaryType==="arraybuffer"?o=Qo(An(r,t)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=J):(this._state=en,setImmediate(()=>{this.emit("message",o,!0),this._state=J,this.startLoop(n)}))}else{let o=An(r,t);if(!this._skipUTF8Validation&&!Ot(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._state===qn||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=J):(this._state=en,setImmediate(()=>{this.emit("message",o,!1),this._state=J,this.startLoop(n)}))}}controlMessage(n,t){if(this._opcode===8){if(n.length===0)this._loop=!1,this.emit("conclude",1005,qt),this.end();else{let r=n.readUInt16BE(0);if(!Yo(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let o=new Xe(n.buffer,n.byteOffset+2,n.length-2);if(!this._skipUTF8Validation&&!Ot(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",r,o),this.end()}this._state=J;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",n),this._state=J):(this._state=en,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",n),this._state=J,this.startLoop(t)}))}createError(n,t,r,o,i){this._loop=!1,this._errored=!0;let s=new n(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=i,s[Ho]=o,s}};Dt.exports=On});var Dn=N((Cu,Jt)=>{"use strict";var{Duplex:Tu}=M("stream"),{randomFillSync:Xo}=M("crypto"),Nt=Ae(),{EMPTY_BUFFER:ei,kWebSocket:ni,NOOP:ti}=H(),{isBlob:Se,isValidStatusCode:ri}=_e(),{mask:$t,toBuffer:oe}=Pe(),U=Symbol("kByteLength"),oi=Buffer.alloc(4),nn=8*1024,ie,be=nn,K=0,ii=1,si=2,Ln=class e{constructor(n,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=n,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=K,this.onerror=ti,this[ni]=void 0}static frame(n,t){let r,o=!1,i=2,s=!1;t.mask&&(r=t.maskBuffer||oi,t.generateMask?t.generateMask(r):(be===nn&&(ie===void 0&&(ie=Buffer.alloc(nn)),Xo(ie,0,nn),be=0),r[0]=ie[be++],r[1]=ie[be++],r[2]=ie[be++],r[3]=ie[be++]),s=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof n=="string"?(!t.mask||s)&&t[U]!==void 0?a=t[U]:(n=Buffer.from(n),a=n.length):(a=n.length,o=t.mask&&t.readOnly&&!s);let d=a;a>=65536?(i+=8,d=127):a>125&&(i+=2,d=126);let u=Buffer.allocUnsafe(o?a+i:i);return u[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(u[0]|=64),u[1]=d,d===126?u.writeUInt16BE(a,2):d===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),t.mask?(u[1]|=128,u[i-4]=r[0],u[i-3]=r[1],u[i-2]=r[2],u[i-1]=r[3],s?[u,n]:o?($t(n,r,u,i,a),[u]):($t(n,r,n,0,a),[u,n])):[u,n]}close(n,t,r,o){let i;if(n===void 0)i=ei;else{if(typeof n!="number"||!ri(n))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(n,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(n,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let s={[U]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==K?this.enqueue([this.dispatch,i,!1,s,o]):this.sendFrame(e.frame(i,s),o)}ping(n,t,r){let o,i;if(typeof n=="string"?(o=Buffer.byteLength(n),i=!1):Se(n)?(o=n.size,i=!1):(n=oe(n),o=n.length,i=oe.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[U]:o,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Se(n)?this._state!==K?this.enqueue([this.getBlobData,n,!1,s,r]):this.getBlobData(n,!1,s,r):this._state!==K?this.enqueue([this.dispatch,n,!1,s,r]):this.sendFrame(e.frame(n,s),r)}pong(n,t,r){let o,i;if(typeof n=="string"?(o=Buffer.byteLength(n),i=!1):Se(n)?(o=n.size,i=!1):(n=oe(n),o=n.length,i=oe.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[U]:o,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Se(n)?this._state!==K?this.enqueue([this.getBlobData,n,!1,s,r]):this.getBlobData(n,!1,s,r):this._state!==K?this.enqueue([this.dispatch,n,!1,s,r]):this.sendFrame(e.frame(n,s),r)}send(n,t,r){let o=this._extensions[Nt.extensionName],i=t.binary?2:1,s=t.compress,a,d;typeof n=="string"?(a=Buffer.byteLength(n),d=!1):Se(n)?(a=n.size,d=!1):(n=oe(n),a=n.length,d=oe.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=o._threshold),this._compress=s):(s=!1,i=0),t.fin&&(this._firstFragment=!0);let u={[U]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:d,rsv1:s};Se(n)?this._state!==K?this.enqueue([this.getBlobData,n,this._compress,u,r]):this.getBlobData(n,this._compress,u,r):this._state!==K?this.enqueue([this.dispatch,n,this._compress,u,r]):this.dispatch(n,this._compress,u,r)}getBlobData(n,t,r,o){this._bufferedBytes+=r[U],this._state=si,n.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(jn,this,a,o);return}this._bufferedBytes-=r[U];let s=oe(i);t?this.dispatch(s,t,r,o):(this._state=K,this.sendFrame(e.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(ai,this,i,o)})}dispatch(n,t,r,o){if(!t){this.sendFrame(e.frame(n,r),o);return}let i=this._extensions[Nt.extensionName];this._bufferedBytes+=r[U],this._state=ii,i.compress(n,r.fin,(s,a)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");jn(this,d,o);return}this._bufferedBytes-=r[U],this._state=K,r.readOnly=!1,this.sendFrame(e.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===K&&this._queue.length;){let n=this._queue.shift();this._bufferedBytes-=n[3][U],Reflect.apply(n[0],this,n.slice(1))}}enqueue(n){this._bufferedBytes+=n[3][U],this._queue.push(n)}sendFrame(n,t){n.length===2?(this._socket.cork(),this._socket.write(n[0]),this._socket.write(n[1],t),this._socket.uncork()):this._socket.write(n[0],t)}};Jt.exports=Ln;function jn(e,n,t){typeof t=="function"&&t(n);for(let r=0;r<e._queue.length;r++){let o=e._queue[r],i=o[o.length-1];typeof i=="function"&&i(n)}}function ai(e,n,t){jn(e,n,t),e.onerror(n)}});var Qt=N((Ru,Vt)=>{"use strict";var{kForOnEventAttribute:Me,kListener:Nn}=H(),Ut=Symbol("kCode"),Kt=Symbol("kData"),zt=Symbol("kError"),Bt=Symbol("kMessage"),Gt=Symbol("kReason"),ve=Symbol("kTarget"),Wt=Symbol("kType"),Ht=Symbol("kWasClean"),Q=class{constructor(n){this[ve]=null,this[Wt]=n}get target(){return this[ve]}get type(){return this[Wt]}};Object.defineProperty(Q.prototype,"target",{enumerable:!0});Object.defineProperty(Q.prototype,"type",{enumerable:!0});var se=class extends Q{constructor(n,t={}){super(n),this[Ut]=t.code===void 0?0:t.code,this[Gt]=t.reason===void 0?"":t.reason,this[Ht]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Ut]}get reason(){return this[Gt]}get wasClean(){return this[Ht]}};Object.defineProperty(se.prototype,"code",{enumerable:!0});Object.defineProperty(se.prototype,"reason",{enumerable:!0});Object.defineProperty(se.prototype,"wasClean",{enumerable:!0});var xe=class extends Q{constructor(n,t={}){super(n),this[zt]=t.error===void 0?null:t.error,this[Bt]=t.message===void 0?"":t.message}get error(){return this[zt]}get message(){return this[Bt]}};Object.defineProperty(xe.prototype,"error",{enumerable:!0});Object.defineProperty(xe.prototype,"message",{enumerable:!0});var qe=class extends Q{constructor(n,t={}){super(n),this[Kt]=t.data===void 0?null:t.data}get data(){return this[Kt]}};Object.defineProperty(qe.prototype,"data",{enumerable:!0});var di={addEventListener(e,n,t={}){for(let o of this.listeners(e))if(!t[Me]&&o[Nn]===n&&!o[Me])return;let r;if(e==="message")r=function(i,s){let a=new qe("message",{data:s?i:i.toString()});a[ve]=this,tn(n,this,a)};else if(e==="close")r=function(i,s){let a=new se("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ve]=this,tn(n,this,a)};else if(e==="error")r=function(i){let s=new xe("error",{error:i,message:i.message});s[ve]=this,tn(n,this,s)};else if(e==="open")r=function(){let i=new Q("open");i[ve]=this,tn(n,this,i)};else return;r[Me]=!!t[Me],r[Nn]=n,t.once?this.once(e,r):this.on(e,r)},removeEventListener(e,n){for(let t of this.listeners(e))if(t[Nn]===n&&!t[Me]){this.removeListener(e,t);break}}};Vt.exports={CloseEvent:se,ErrorEvent:xe,Event:Q,EventTarget:di,MessageEvent:qe};function tn(e,n,t){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,t):e.call(n,t)}});var $n=N((Iu,Zt)=>{"use strict";var{tokenChars:Oe}=_e();function B(e,n,t){e[n]===void 0?e[n]=[t]:e[n].push(t)}function ui(e){let n=Object.create(null),t=Object.create(null),r=!1,o=!1,i=!1,s,a,d=-1,u=-1,c=-1,f=0;for(;f<e.length;f++)if(u=e.charCodeAt(f),s===void 0)if(c===-1&&Oe[u]===1)d===-1&&(d=f);else if(f!==0&&(u===32||u===9))c===-1&&d!==-1&&(c=f);else if(u===59||u===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1&&(c=f);let v=e.slice(d,c);u===44?(B(n,v,t),t=Object.create(null)):s=v,d=c=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(a===void 0)if(c===-1&&Oe[u]===1)d===-1&&(d=f);else if(u===32||u===9)c===-1&&d!==-1&&(c=f);else if(u===59||u===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1&&(c=f),B(t,e.slice(d,c),!0),u===44&&(B(n,s,t),t=Object.create(null),s=void 0),d=c=-1}else if(u===61&&d!==-1&&c===-1)a=e.slice(d,f),d=c=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(o){if(Oe[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);d===-1?d=f:r||(r=!0),o=!1}else if(i)if(Oe[u]===1)d===-1&&(d=f);else if(u===34&&d!==-1)i=!1,c=f;else if(u===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&e.charCodeAt(f-1)===61)i=!0;else if(c===-1&&Oe[u]===1)d===-1&&(d=f);else if(d!==-1&&(u===32||u===9))c===-1&&(c=f);else if(u===59||u===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1&&(c=f);let v=e.slice(d,c);r&&(v=v.replace(/\\/g,""),r=!1),B(t,a,v),u===44&&(B(n,s,t),t=Object.create(null),s=void 0),a=void 0,d=c=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(d===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");c===-1&&(c=f);let y=e.slice(d,c);return s===void 0?B(n,y,t):(a===void 0?B(t,y,!0):r?B(t,a,y.replace(/\\/g,"")):B(t,a,y),B(n,s,t)),n}function ci(e){return Object.keys(e).map(n=>{let t=e[n];return Array.isArray(t)||(t=[t]),t.map(r=>[n].concat(Object.keys(r).map(o=>{let i=r[o];return Array.isArray(i)||(i=[i]),i.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Zt.exports={format:ci,parse:ui}});var an=N((Au,ur)=>{"use strict";var li=M("events"),pi=M("https"),fi=M("http"),er=M("net"),mi=M("tls"),{randomBytes:hi,createHash:gi}=M("crypto"),{Duplex:Pu,Readable:Eu}=M("stream"),{URL:Jn}=M("url"),ne=Ae(),yi=Fn(),_i=Dn(),{isBlob:Si}=_e(),{BINARY_TYPES:Yt,EMPTY_BUFFER:rn,GUID:bi,kForOnEventAttribute:Un,kListener:vi,kStatusCode:xi,kWebSocket:O,NOOP:nr}=H(),{EventTarget:{addEventListener:wi,removeEventListener:ki}}=Qt(),{format:Ti,parse:Ci}=$n(),{toBuffer:Ri}=Pe(),Ii=30*1e3,tr=Symbol("kAborted"),Kn=[8,13],Z=["CONNECTING","OPEN","CLOSING","CLOSED"],Pi=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,P=class e extends li{constructor(n,t,r){super(),this._binaryType=Yt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=rn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,n!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(r=t,t=[]):t=[t]),rr(this,n,t,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(n){Yt.includes(n)&&(this._binaryType=n,this._receiver&&(this._receiver._binaryType=n))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(n,t,r){let o=new yi({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new _i(n,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=n,o[O]=this,i[O]=this,n[O]=this,o.on("conclude",Mi),o.on("drain",qi),o.on("error",Oi),o.on("message",Fi),o.on("ping",Li),o.on("pong",ji),i.onerror=Di,n.setTimeout&&n.setTimeout(0),n.setNoDelay&&n.setNoDelay(),t.length>0&&n.unshift(t),n.on("close",sr),n.on("data",sn),n.on("end",ar),n.on("error",dr),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ne.extensionName]&&this._extensions[ne.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(n,t){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){$(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(n,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ir(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(n,t,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(r=n,n=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){zn(this,n,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(n||rn,t,r)}pong(n,t,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"?(r=n,n=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){zn(this,n,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(n||rn,t,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(n,t,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof n=="number"&&(n=n.toString()),this.readyState!==e.OPEN){zn(this,n,r);return}let o={binary:typeof n!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ne.extensionName]||(o.compress=!1),this._sender.send(n||rn,o,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){$(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:Z.indexOf("CONNECTING")});Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:Z.indexOf("CONNECTING")});Object.defineProperty(P,"OPEN",{enumerable:!0,value:Z.indexOf("OPEN")});Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:Z.indexOf("OPEN")});Object.defineProperty(P,"CLOSING",{enumerable:!0,value:Z.indexOf("CLOSING")});Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:Z.indexOf("CLOSING")});Object.defineProperty(P,"CLOSED",{enumerable:!0,value:Z.indexOf("CLOSED")});Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:Z.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let n of this.listeners(e))if(n[Un])return n[vi];return null},set(n){for(let t of this.listeners(e))if(t[Un]){this.removeListener(e,t);break}typeof n=="function"&&this.addEventListener(e,n,{[Un]:!0})}})});P.prototype.addEventListener=wi;P.prototype.removeEventListener=ki;ur.exports=P;function rr(e,n,t,r){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Kn[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!Kn.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Kn.join(", ")})`);let i;if(n instanceof Jn)i=n;else try{i=new Jn(n)}catch{throw new SyntaxError(`Invalid URL: ${n}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),e._url=i.href;let s=i.protocol==="wss:",a=i.protocol==="ws+unix:",d;if(i.protocol!=="ws:"&&!s&&!a?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?d="The URL's pathname is empty":i.hash&&(d="The URL contains a fragment identifier"),d){let p=new SyntaxError(d);if(e._redirects===0)throw p;on(e,p);return}let u=s?443:80,c=hi(16).toString("base64"),f=s?pi.request:fi.request,y=new Set,v;if(o.createConnection=o.createConnection||(s?Ai:Ei),o.defaultPort=o.defaultPort||u,o.port=i.port||u,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(v=new ne(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=Ti({[ne.extensionName]:v.offer()})),t.length){for(let p of t){if(typeof p!="string"||!Pi.test(p)||y.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(p)}o.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),a){let p=o.path.split(":");o.socketPath=p[0],o.path=p[1]}let h;if(o.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=s,e._originalHostOrSocketPath=a?o.socketPath:i.host;let p=r&&r.headers;if(r={...r,headers:{}},p)for(let[m,k]of Object.entries(p))r.headers[m.toLowerCase()]=k}else if(e.listenerCount("redirect")===0){let p=a?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:i.host===e._originalHostOrSocketPath;(!p||e._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,p||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),h=e._req=f(o),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=f(o);o.timeout&&h.on("timeout",()=>{$(e,h,"Opening handshake has timed out")}),h.on("error",p=>{h===null||h[tr]||(h=e._req=null,on(e,p))}),h.on("response",p=>{let m=p.headers.location,k=p.statusCode;if(m&&o.followRedirects&&k>=300&&k<400){if(++e._redirects>o.maxRedirects){$(e,h,"Maximum redirects exceeded");return}h.abort();let I;try{I=new Jn(m,n)}catch{let S=new SyntaxError(`Invalid URL: ${m}`);on(e,S);return}rr(e,I,t,r)}else e.emit("unexpected-response",h,p)||$(e,h,`Unexpected server response: ${p.statusCode}`)}),h.on("upgrade",(p,m,k)=>{if(e.emit("upgrade",p),e.readyState!==P.CONNECTING)return;h=e._req=null;let I=p.headers.upgrade;if(I===void 0||I.toLowerCase()!=="websocket"){$(e,m,"Invalid Upgrade header");return}let L=gi("sha1").update(c+bi).digest("base64");if(p.headers["sec-websocket-accept"]!==L){$(e,m,"Invalid Sec-WebSocket-Accept header");return}let S=p.headers["sec-websocket-protocol"],g;if(S!==void 0?y.size?y.has(S)||(g="Server sent an invalid subprotocol"):g="Server sent a subprotocol but none was requested":y.size&&(g="Server sent no subprotocol"),g){$(e,m,g);return}S&&(e._protocol=S);let x=p.headers["sec-websocket-extensions"];if(x!==void 0){if(!v){$(e,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let w;try{w=Ci(x)}catch{$(e,m,"Invalid Sec-WebSocket-Extensions header");return}let T=Object.keys(w);if(T.length!==1||T[0]!==ne.extensionName){$(e,m,"Server indicated an extension that was not requested");return}try{v.accept(w[ne.extensionName])}catch{$(e,m,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[ne.extensionName]=v}e.setSocket(m,k,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(h,e):h.end()}function on(e,n){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit("error",n),e.emitClose()}function Ei(e){return e.path=e.socketPath,er.connect(e)}function Ai(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=er.isIP(e.host)?"":e.host),mi.connect(e)}function $(e,n,t){e._readyState=P.CLOSING;let r=new Error(t);Error.captureStackTrace(r,$),n.setHeader?(n[tr]=!0,n.abort(),n.socket&&!n.socket.destroyed&&n.socket.destroy(),process.nextTick(on,e,r)):(n.destroy(r),n.once("error",e.emit.bind(e,"error")),n.once("close",e.emitClose.bind(e)))}function zn(e,n,t){if(n){let r=Si(n)?n.size:Ri(n).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${e.readyState} (${Z[e.readyState]})`);process.nextTick(t,r)}}function Mi(e,n){let t=this[O];t._closeFrameReceived=!0,t._closeMessage=n,t._closeCode=e,t._socket[O]!==void 0&&(t._socket.removeListener("data",sn),process.nextTick(or,t._socket),e===1005?t.close():t.close(e,n))}function qi(){let e=this[O];e.isPaused||e._socket.resume()}function Oi(e){let n=this[O];n._socket[O]!==void 0&&(n._socket.removeListener("data",sn),process.nextTick(or,n._socket),n.close(e[xi])),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e))}function Xt(){this[O].emitClose()}function Fi(e,n){this[O].emit("message",e,n)}function Li(e){let n=this[O];n._autoPong&&n.pong(e,!this._isServer,nr),n.emit("ping",e)}function ji(e){this[O].emit("pong",e)}function or(e){e.resume()}function Di(e){let n=this[O];n.readyState!==P.CLOSED&&(n.readyState===P.OPEN&&(n._readyState=P.CLOSING,ir(n)),this._socket.end(),n._errorEmitted||(n._errorEmitted=!0,n.emit("error",e)))}function ir(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),Ii)}function sr(){let e=this[O];this.removeListener("close",sr),this.removeListener("data",sn),this.removeListener("end",ar),e._readyState=P.CLOSING;let n;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(n=e._socket.read())!==null&&e._receiver.write(n),e._receiver.end(),this[O]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Xt),e._receiver.on("finish",Xt))}function sn(e){this[O]._receiver.write(e)||this.pause()}function ar(){let e=this[O];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function dr(){let e=this[O];this.removeListener("error",dr),this.on("error",nr),e&&(e._readyState=P.CLOSING,this.destroy())}});var fr=N((qu,pr)=>{"use strict";var Mu=an(),{Duplex:Ni}=M("stream");function cr(e){e.emit("close")}function $i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function lr(e){this.removeListener("error",lr),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function Ji(e,n){let t=!0,r=new Ni({...n,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(i,s){let a=!s&&r._readableState.objectMode?i.toString():i;r.push(a)||e.pause()}),e.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),e.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(o,i){if(e.readyState===e.CLOSED){i(o),process.nextTick(cr,r);return}let s=!1;e.once("error",function(d){s=!0,i(d)}),e.once("close",function(){s||i(o),process.nextTick(cr,r)}),t&&e.terminate()},r._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",function(){r._final(o)});return}e._socket!==null&&(e._socket._writableState.finished?(o(),r._readableState.endEmitted&&r.destroy()):(e._socket.once("finish",function(){o()}),e.close()))},r._read=function(){e.isPaused&&e.resume()},r._write=function(o,i,s){if(e.readyState===e.CONNECTING){e.once("open",function(){r._write(o,i,s)});return}e.send(o,s)},r.on("end",$i),r.on("error",lr),r}pr.exports=Ji});var hr=N((Ou,mr)=>{"use strict";var{tokenChars:Ui}=_e();function Ki(e){let n=new Set,t=-1,r=-1,o=0;for(o;o<e.length;o++){let s=e.charCodeAt(o);if(r===-1&&Ui[s]===1)t===-1&&(t=o);else if(o!==0&&(s===32||s===9))r===-1&&t!==-1&&(r=o);else if(s===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${o}`);r===-1&&(r=o);let a=e.slice(t,r);if(n.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);n.add(a),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=e.slice(t,o);if(n.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return n.add(i),n}mr.exports={parse:Ki}});var xr=N((Lu,vr)=>{"use strict";var zi=M("events"),dn=M("http"),{Duplex:Fu}=M("stream"),{createHash:Bi}=M("crypto"),gr=$n(),ae=Ae(),Gi=hr(),Wi=an(),{GUID:Hi,kWebSocket:Vi}=H(),Qi=/^[+/0-9A-Za-z]{22}==$/,yr=0,_r=1,br=2,Bn=class extends zi{constructor(n,t){if(super(),n={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wi,...n},n.port==null&&!n.server&&!n.noServer||n.port!=null&&(n.server||n.noServer)||n.server&&n.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(n.port!=null?(this._server=dn.createServer((r,o)=>{let i=dn.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(n.port,n.host,n.backlog,t)):n.server&&(this._server=n.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Zi(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,s)=>{this.handleUpgrade(o,i,s,r)}})}n.perMessageDeflate===!0&&(n.perMessageDeflate={}),n.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=n,this._state=yr}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(n){if(this._state===br){n&&this.once("close",()=>{n(new Error("The server is not running"))}),process.nextTick(Fe,this);return}if(n&&this.once("close",n),this._state!==_r)if(this._state=_r,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Fe,this):process.nextTick(Fe,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Fe(this)})}}shouldHandle(n){if(this.options.path){let t=n.url.indexOf("?");if((t!==-1?n.url.slice(0,t):n.url)!==this.options.path)return!1}return!0}handleUpgrade(n,t,r,o){t.on("error",Sr);let i=n.headers["sec-websocket-key"],s=n.headers.upgrade,a=+n.headers["sec-websocket-version"];if(n.method!=="GET"){de(this,n,t,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){de(this,n,t,400,"Invalid Upgrade header");return}if(i===void 0||!Qi.test(i)){de(this,n,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){de(this,n,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(n)){Le(t,400);return}let d=n.headers["sec-websocket-protocol"],u=new Set;if(d!==void 0)try{u=Gi.parse(d)}catch{de(this,n,t,400,"Invalid Sec-WebSocket-Protocol header");return}let c=n.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&c!==void 0){let y=new ae(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let v=gr.parse(c);v[ae.extensionName]&&(y.accept(v[ae.extensionName]),f[ae.extensionName]=y)}catch{de(this,n,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let y={origin:n.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(n.socket.authorized||n.socket.encrypted),req:n};if(this.options.verifyClient.length===2){this.options.verifyClient(y,(v,h,p,m)=>{if(!v)return Le(t,h||401,p,m);this.completeUpgrade(f,i,u,n,t,r,o)});return}if(!this.options.verifyClient(y))return Le(t,401)}this.completeUpgrade(f,i,u,n,t,r,o)}completeUpgrade(n,t,r,o,i,s,a){if(!i.readable||!i.writable)return i.destroy();if(i[Vi])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>yr)return Le(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Bi("sha1").update(t+Hi).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,o):r.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),c._protocol=f)}if(n[ae.extensionName]){let f=n[ae.extensionName].params,y=gr.format({[ae.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${y}`),c._extensions=n}this.emit("headers",u,o),i.write(u.concat(`\r
3
+ var FE=Object.create;var tc=Object.defineProperty;var zE=Object.getOwnPropertyDescriptor;var BE=Object.getOwnPropertyNames;var KE=Object.getPrototypeOf,JE=Object.prototype.hasOwnProperty;var dt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var WE=(e,t)=>()=>(e&&(t=e(e=0)),t);var Bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),HE=(e,t)=>{for(var n in t)tc(e,n,{get:t[n],enumerable:!0})},GE=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of BE(t))!JE.call(e,r)&&r!==n&&tc(e,r,{get:()=>t[r],enumerable:!(i=zE(t,r))||i.enumerable});return e};var Ro=(e,t,n)=>(n=e!=null?FE(KE(e)):{},GE(t||!e||!e.__esModule?tc(n,"default",{value:e,enumerable:!0}):n,e));var Jn=Bt((IQ,Ty)=>{"use strict";var xy=["nodebuffer","arraybuffer","fragments"],Cy=typeof Blob<"u";Cy&&xy.push("blob");Ty.exports={BINARY_TYPES:xy,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Cy,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Oo=Bt((PQ,qs)=>{"use strict";var{EMPTY_BUFFER:VE}=Jn(),nc=Buffer[Symbol.species];function ZE(e,t){if(e.length===0)return VE;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),i=0;for(let r=0;r<e.length;r++){let o=e[r];n.set(o,i),i+=o.length}return i<t?new nc(n.buffer,n.byteOffset,i):n}function Iy(e,t,n,i,r){for(let o=0;o<r;o++)n[i+o]=e[o]^t[o&3]}function Py(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function QE(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function rc(e){if(rc.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new nc(e):ArrayBuffer.isView(e)?t=new nc(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),rc.readOnly=!1),t}qs.exports={concat:ZE,mask:Iy,toArrayBuffer:QE,toBuffer:rc,unmask:Py};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=dt("bufferutil");qs.exports.mask=function(t,n,i,r,o){o<48?Iy(t,n,i,r,o):e.mask(t,n,i,r,o)},qs.exports.unmask=function(t,n){t.length<32?Py(t,n):e.unmask(t,n)}}catch{}});var Oy=Bt((EQ,Ry)=>{"use strict";var Ey=Symbol("kDone"),ic=Symbol("kRun"),oc=class{constructor(t){this[Ey]=()=>{this.pending--,this[ic]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[ic]()}[ic](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[Ey])}}};Ry.exports=oc});var $o=Bt((RQ,jy)=>{"use strict";var Ao=dt("zlib"),Ay=Oo(),YE=Oy(),{kStatusCode:$y}=Jn(),XE=Buffer[Symbol.species],eR=Buffer.from([0,0,255,255]),Ds=Symbol("permessage-deflate"),Wn=Symbol("total-length"),mi=Symbol("callback"),ar=Symbol("buffers"),hi=Symbol("error"),Ns,ac=class{constructor(t,n,i){if(this._maxPayload=i|0,this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Ns){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ns=new YE(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[mi];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let n=this._options,i=t.find(r=>!(n.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>r.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(i.server_no_context_takeover=!0),n.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(i.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?i.client_max_window_bits=n.clientMaxWindowBits:(i.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(t){let n=t[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(t){return t.forEach(n=>{Object.keys(n).forEach(i=>{let r=n[i];if(r.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(r=r[0],i==="client_max_window_bits"){if(r!==!0){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else if(i==="server_max_window_bits"){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else throw new Error(`Unknown parameter "${i}"`);n[i]=r})}),t}decompress(t,n,i){Ns.add(r=>{this._decompress(t,n,(o,a)=>{r(),i(o,a)})})}compress(t,n,i){Ns.add(r=>{this._compress(t,n,(o,a)=>{r(),i(o,a)})})}_decompress(t,n,i){let r=this._isServer?"client":"server";if(!this._inflate){let o=`${r}_max_window_bits`,a=typeof this.params[o]!="number"?Ao.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Ao.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Ds]=this,this._inflate[Wn]=0,this._inflate[ar]=[],this._inflate.on("error",nR),this._inflate.on("data",My)}this._inflate[mi]=i,this._inflate.write(t),n&&this._inflate.write(eR),this._inflate.flush(()=>{let o=this._inflate[hi];if(o){this._inflate.close(),this._inflate=null,i(o);return}let a=Ay.concat(this._inflate[ar],this._inflate[Wn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Wn]=0,this._inflate[ar]=[],n&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),i(null,a)})}_compress(t,n,i){let r=this._isServer?"server":"client";if(!this._deflate){let o=`${r}_max_window_bits`,a=typeof this.params[o]!="number"?Ao.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Ao.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[Wn]=0,this._deflate[ar]=[],this._deflate.on("data",tR)}this._deflate[mi]=i,this._deflate.write(t),this._deflate.flush(Ao.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Ay.concat(this._deflate[ar],this._deflate[Wn]);n&&(o=new XE(o.buffer,o.byteOffset,o.length-4)),this._deflate[mi]=null,this._deflate[Wn]=0,this._deflate[ar]=[],n&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),i(null,o)})}};jy.exports=ac;function tR(e){this[ar].push(e),this[Wn]+=e.length}function My(e){if(this[Wn]+=e.length,this[Ds]._maxPayload<1||this[Wn]<=this[Ds]._maxPayload){this[ar].push(e);return}this[hi]=new RangeError("Max payload size exceeded"),this[hi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[hi][$y]=1009,this.removeListener("data",My),this.reset()}function nR(e){if(this[Ds]._inflate=null,this[hi]){this[mi](this[hi]);return}e[$y]=1007,this[mi](e)}});var gi=Bt((OQ,Ls)=>{"use strict";var{isUtf8:qy}=dt("buffer"),{hasBlob:rR}=Jn(),iR=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function oR(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function sc(e){let t=e.length,n=0;for(;n<t;)if((e[n]&128)===0)n++;else if((e[n]&224)===192){if(n+1===t||(e[n+1]&192)!==128||(e[n]&254)===192)return!1;n+=2}else if((e[n]&240)===224){if(n+2>=t||(e[n+1]&192)!==128||(e[n+2]&192)!==128||e[n]===224&&(e[n+1]&224)===128||e[n]===237&&(e[n+1]&224)===160)return!1;n+=3}else if((e[n]&248)===240){if(n+3>=t||(e[n+1]&192)!==128||(e[n+2]&192)!==128||(e[n+3]&192)!==128||e[n]===240&&(e[n+1]&240)===128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function aR(e){return rR&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}Ls.exports={isBlob:aR,isValidStatusCode:oR,isValidUTF8:sc,tokenChars:iR};if(qy)Ls.exports.isValidUTF8=function(e){return e.length<24?sc(e):qy(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=dt("utf-8-validate");Ls.exports.isValidUTF8=function(t){return t.length<32?sc(t):e(t)}}catch{}});var pc=Bt((AQ,By)=>{"use strict";var{Writable:sR}=dt("stream"),Ny=$o(),{BINARY_TYPES:dR,EMPTY_BUFFER:Dy,kStatusCode:uR,kWebSocket:lR}=Jn(),{concat:dc,toArrayBuffer:cR,unmask:pR}=Oo(),{isValidStatusCode:fR,isValidUTF8:Ly}=gi(),Us=Buffer[Symbol.species],tn=0,Uy=1,Fy=2,zy=3,uc=4,lc=5,Fs=6,cc=class extends sR{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||dR[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[lR]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=tn}_write(t,n,i){if(this._opcode===8&&this._state==tn)return i();this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(i)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Us(i.buffer,i.byteOffset+t,i.length-t),new Us(i.buffer,i.byteOffset,t)}let n=Buffer.allocUnsafe(t);do{let i=this._buffers[0],r=n.length-t;t>=i.length?n.set(this._buffers.shift(),r):(n.set(new Uint8Array(i.buffer,i.byteOffset,t),r),this._buffers[0]=new Us(i.buffer,i.byteOffset+t,i.length-t)),t-=i.length}while(t>0);return n}startLoop(t){this._loop=!0;do switch(this._state){case tn:this.getInfo(t);break;case Uy:this.getPayloadLength16(t);break;case Fy:this.getPayloadLength64(t);break;case zy:this.getMask();break;case uc:this.getData(t);break;case lc:case Fs:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(r);return}let i=(n[0]&64)===64;if(i&&!this._extensions[Ny.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(r);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(r);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(r);return}if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(r);return}this._payloadLength===126?this._state=Uy:this._payloadLength===127?this._state=Fy:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),i=n.readUInt32BE(0);if(i>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(r);return}this._payloadLength=i*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(n);return}this._masked?this._state=zy:this._state=uc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=uc}getData(t){let n=Dy;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&pR(n,this._mask)}if(this._opcode>7){this.controlMessage(n,t);return}if(this._compressed){this._state=lc,this.decompress(n,t);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(t)}decompress(t,n){this._extensions[Ny.extensionName].decompress(t,this._fin,(r,o)=>{if(r)return n(r);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(a);return}this._fragments.push(o)}this.dataMessage(n),this._state===tn&&this.startLoop(n)})}dataMessage(t){if(!this._fin){this._state=tn;return}let n=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=dc(i,n):this._binaryType==="arraybuffer"?r=cR(dc(i,n)):this._binaryType==="blob"?r=new Blob(i):r=i,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=tn):(this._state=Fs,setImmediate(()=>{this.emit("message",r,!0),this._state=tn,this.startLoop(t)}))}else{let r=dc(i,n);if(!this._skipUTF8Validation&&!Ly(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(o);return}this._state===lc||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=tn):(this._state=Fs,setImmediate(()=>{this.emit("message",r,!1),this._state=tn,this.startLoop(t)}))}}controlMessage(t,n){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,Dy),this.end();else{let i=t.readUInt16BE(0);if(!fR(i)){let o=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let r=new Us(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Ly(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",i,r),this.end()}this._state=tn;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=tn):(this._state=Fs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=tn,this.startLoop(n)}))}createError(t,n,i,r,o){this._loop=!1,this._errored=!0;let a=new t(i?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(a,this.createError),a.code=o,a[uR]=r,a}};By.exports=cc});var hc=Bt((MQ,Wy)=>{"use strict";var{Duplex:$Q}=dt("stream"),{randomFillSync:mR}=dt("crypto"),Ky=$o(),{EMPTY_BUFFER:hR,kWebSocket:gR,NOOP:yR}=Jn(),{isBlob:yi,isValidStatusCode:_R}=gi(),{mask:Jy,toBuffer:Or}=Oo(),nn=Symbol("kByteLength"),vR=Buffer.alloc(4),zs=8*1024,Ar,_i=zs,_n=0,bR=1,wR=2,fc=class e{constructor(t,n,i){this._extensions=n||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=_n,this.onerror=yR,this[gR]=void 0}static frame(t,n){let i,r=!1,o=2,a=!1;n.mask&&(i=n.maskBuffer||vR,n.generateMask?n.generateMask(i):(_i===zs&&(Ar===void 0&&(Ar=Buffer.alloc(zs)),mR(Ar,0,zs),_i=0),i[0]=Ar[_i++],i[1]=Ar[_i++],i[2]=Ar[_i++],i[3]=Ar[_i++]),a=(i[0]|i[1]|i[2]|i[3])===0,o=6);let s;typeof t=="string"?(!n.mask||a)&&n[nn]!==void 0?s=n[nn]:(t=Buffer.from(t),s=t.length):(s=t.length,r=n.mask&&n.readOnly&&!a);let d=s;s>=65536?(o+=8,d=127):s>125&&(o+=2,d=126);let u=Buffer.allocUnsafe(r?s+o:o);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=d,d===126?u.writeUInt16BE(s,2):d===127&&(u[2]=u[3]=0,u.writeUIntBE(s,4,6)),n.mask?(u[1]|=128,u[o-4]=i[0],u[o-3]=i[1],u[o-2]=i[2],u[o-1]=i[3],a?[u,t]:r?(Jy(t,i,u,o,s),[u]):(Jy(t,i,t,0,s),[u,t])):[u,t]}close(t,n,i,r){let o;if(t===void 0)o=hR;else{if(typeof t!="number"||!_R(t))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let s=Buffer.byteLength(n);if(s>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+s),o.writeUInt16BE(t,0),typeof n=="string"?o.write(n,2):o.set(n,2)}}let a={[nn]:o.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==_n?this.enqueue([this.dispatch,o,!1,a,r]):this.sendFrame(e.frame(o,a),r)}ping(t,n,i){let r,o;if(typeof t=="string"?(r=Buffer.byteLength(t),o=!1):yi(t)?(r=t.size,o=!1):(t=Or(t),r=t.length,o=Or.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[nn]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};yi(t)?this._state!==_n?this.enqueue([this.getBlobData,t,!1,a,i]):this.getBlobData(t,!1,a,i):this._state!==_n?this.enqueue([this.dispatch,t,!1,a,i]):this.sendFrame(e.frame(t,a),i)}pong(t,n,i){let r,o;if(typeof t=="string"?(r=Buffer.byteLength(t),o=!1):yi(t)?(r=t.size,o=!1):(t=Or(t),r=t.length,o=Or.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[nn]:r,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};yi(t)?this._state!==_n?this.enqueue([this.getBlobData,t,!1,a,i]):this.getBlobData(t,!1,a,i):this._state!==_n?this.enqueue([this.dispatch,t,!1,a,i]):this.sendFrame(e.frame(t,a),i)}send(t,n,i){let r=this._extensions[Ky.extensionName],o=n.binary?2:1,a=n.compress,s,d;typeof t=="string"?(s=Buffer.byteLength(t),d=!1):yi(t)?(s=t.size,d=!1):(t=Or(t),s=t.length,d=Or.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=s>=r._threshold),this._compress=a):(a=!1,o=0),n.fin&&(this._firstFragment=!0);let u={[nn]:s,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:d,rsv1:a};yi(t)?this._state!==_n?this.enqueue([this.getBlobData,t,this._compress,u,i]):this.getBlobData(t,this._compress,u,i):this._state!==_n?this.enqueue([this.dispatch,t,this._compress,u,i]):this.dispatch(t,this._compress,u,i)}getBlobData(t,n,i,r){this._bufferedBytes+=i[nn],this._state=wR,t.arrayBuffer().then(o=>{if(this._socket.destroyed){let s=new Error("The socket was closed while the blob was being read");process.nextTick(mc,this,s,r);return}this._bufferedBytes-=i[nn];let a=Or(o);n?this.dispatch(a,n,i,r):(this._state=_n,this.sendFrame(e.frame(a,i),r),this.dequeue())}).catch(o=>{process.nextTick(SR,this,o,r)})}dispatch(t,n,i,r){if(!n){this.sendFrame(e.frame(t,i),r);return}let o=this._extensions[Ky.extensionName];this._bufferedBytes+=i[nn],this._state=bR,o.compress(t,i.fin,(a,s)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");mc(this,d,r);return}this._bufferedBytes-=i[nn],this._state=_n,i.readOnly=!1,this.sendFrame(e.frame(s,i),r),this.dequeue()})}dequeue(){for(;this._state===_n&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][nn],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][nn],this._queue.push(t)}sendFrame(t,n){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],n),this._socket.uncork()):this._socket.write(t[0],n)}};Wy.exports=fc;function mc(e,t,n){typeof n=="function"&&n(t);for(let i=0;i<e._queue.length;i++){let r=e._queue[i],o=r[r.length-1];typeof o=="function"&&o(t)}}function SR(e,t,n){mc(e,t,n),e.onerror(t)}});var t_=Bt((jQ,e_)=>{"use strict";var{kForOnEventAttribute:Mo,kListener:gc}=Jn(),Hy=Symbol("kCode"),Gy=Symbol("kData"),Vy=Symbol("kError"),Zy=Symbol("kMessage"),Qy=Symbol("kReason"),vi=Symbol("kTarget"),Yy=Symbol("kType"),Xy=Symbol("kWasClean"),Hn=class{constructor(t){this[vi]=null,this[Yy]=t}get target(){return this[vi]}get type(){return this[Yy]}};Object.defineProperty(Hn.prototype,"target",{enumerable:!0});Object.defineProperty(Hn.prototype,"type",{enumerable:!0});var $r=class extends Hn{constructor(t,n={}){super(t),this[Hy]=n.code===void 0?0:n.code,this[Qy]=n.reason===void 0?"":n.reason,this[Xy]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Hy]}get reason(){return this[Qy]}get wasClean(){return this[Xy]}};Object.defineProperty($r.prototype,"code",{enumerable:!0});Object.defineProperty($r.prototype,"reason",{enumerable:!0});Object.defineProperty($r.prototype,"wasClean",{enumerable:!0});var bi=class extends Hn{constructor(t,n={}){super(t),this[Vy]=n.error===void 0?null:n.error,this[Zy]=n.message===void 0?"":n.message}get error(){return this[Vy]}get message(){return this[Zy]}};Object.defineProperty(bi.prototype,"error",{enumerable:!0});Object.defineProperty(bi.prototype,"message",{enumerable:!0});var jo=class extends Hn{constructor(t,n={}){super(t),this[Gy]=n.data===void 0?null:n.data}get data(){return this[Gy]}};Object.defineProperty(jo.prototype,"data",{enumerable:!0});var kR={addEventListener(e,t,n={}){for(let r of this.listeners(e))if(!n[Mo]&&r[gc]===t&&!r[Mo])return;let i;if(e==="message")i=function(o,a){let s=new jo("message",{data:a?o:o.toString()});s[vi]=this,Bs(t,this,s)};else if(e==="close")i=function(o,a){let s=new $r("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});s[vi]=this,Bs(t,this,s)};else if(e==="error")i=function(o){let a=new bi("error",{error:o,message:o.message});a[vi]=this,Bs(t,this,a)};else if(e==="open")i=function(){let o=new Hn("open");o[vi]=this,Bs(t,this,o)};else return;i[Mo]=!!n[Mo],i[gc]=t,n.once?this.once(e,i):this.on(e,i)},removeEventListener(e,t){for(let n of this.listeners(e))if(n[gc]===t&&!n[Mo]){this.removeListener(e,n);break}}};e_.exports={CloseEvent:$r,ErrorEvent:bi,Event:Hn,EventTarget:kR,MessageEvent:jo};function Bs(e,t,n){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}});var yc=Bt((qQ,n_)=>{"use strict";var{tokenChars:qo}=gi();function $n(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function xR(e){let t=Object.create(null),n=Object.create(null),i=!1,r=!1,o=!1,a,s,d=-1,u=-1,l=-1,p=0;for(;p<e.length;p++)if(u=e.charCodeAt(p),a===void 0)if(l===-1&&qo[u]===1)d===-1&&(d=p);else if(p!==0&&(u===32||u===9))l===-1&&d!==-1&&(l=p);else if(u===59||u===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1&&(l=p);let f=e.slice(d,l);u===44?($n(t,f,n),n=Object.create(null)):a=f,d=l=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s===void 0)if(l===-1&&qo[u]===1)d===-1&&(d=p);else if(u===32||u===9)l===-1&&d!==-1&&(l=p);else if(u===59||u===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1&&(l=p),$n(n,e.slice(d,l),!0),u===44&&($n(t,a,n),n=Object.create(null),a=void 0),d=l=-1}else if(u===61&&d!==-1&&l===-1)s=e.slice(d,p),d=l=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(r){if(qo[u]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:i||(i=!0),r=!1}else if(o)if(qo[u]===1)d===-1&&(d=p);else if(u===34&&d!==-1)o=!1,l=p;else if(u===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(u===34&&e.charCodeAt(p-1)===61)o=!0;else if(l===-1&&qo[u]===1)d===-1&&(d=p);else if(d!==-1&&(u===32||u===9))l===-1&&(l=p);else if(u===59||u===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1&&(l=p);let f=e.slice(d,l);i&&(f=f.replace(/\\/g,""),i=!1),$n(n,s,f),u===44&&($n(t,a,n),n=Object.create(null),a=void 0),s=void 0,d=l=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=p);let m=e.slice(d,l);return a===void 0?$n(t,m,n):(s===void 0?$n(n,m,!0):i?$n(n,s,m.replace(/\\/g,"")):$n(n,s,m),$n(t,a,n)),t}function CR(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(i=>[t].concat(Object.keys(i).map(r=>{let o=i[r];return Array.isArray(o)||(o=[o]),o.map(a=>a===!0?r:`${r}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}n_.exports={format:CR,parse:xR}});var Hs=Bt((LQ,m_)=>{"use strict";var TR=dt("events"),IR=dt("https"),PR=dt("http"),o_=dt("net"),ER=dt("tls"),{randomBytes:RR,createHash:OR}=dt("crypto"),{Duplex:NQ,Readable:DQ}=dt("stream"),{URL:_c}=dt("url"),sr=$o(),AR=pc(),$R=hc(),{isBlob:MR}=gi(),{BINARY_TYPES:r_,EMPTY_BUFFER:Ks,GUID:jR,kForOnEventAttribute:vc,kListener:qR,kStatusCode:NR,kWebSocket:ht,NOOP:a_}=Jn(),{EventTarget:{addEventListener:DR,removeEventListener:LR}}=t_(),{format:UR,parse:FR}=yc(),{toBuffer:zR}=Oo(),BR=30*1e3,s_=Symbol("kAborted"),bc=[8,13],Gn=["CONNECTING","OPEN","CLOSING","CLOSED"],KR=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ze=class e extends TR{constructor(t,n,i){super(),this._binaryType=r_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ks,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(i=n,n=[]):n=[n]),d_(this,t,n,i)):(this._autoPong=i.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){r_.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,i){let r=new AR({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),o=new $R(t,this._extensions,i.generateMask);this._receiver=r,this._sender=o,this._socket=t,r[ht]=this,o[ht]=this,t[ht]=this,r.on("conclude",HR),r.on("drain",GR),r.on("error",VR),r.on("message",ZR),r.on("ping",QR),r.on("pong",YR),o.onerror=XR,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",c_),t.on("data",Ws),t.on("end",p_),t.on("error",f_),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[sr.extensionName]&&this._extensions[sr.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Kt(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),l_(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,i){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(i=t,t=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){wc(this,t,i);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||Ks,n,i)}pong(t,n,i){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(i=t,t=n=void 0):typeof n=="function"&&(i=n,n=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){wc(this,t,i);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||Ks,n,i)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,i){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(i=n,n={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){wc(this,t,i);return}let r={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[sr.extensionName]||(r.compress=!1),this._sender.send(t||Ks,r,i)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Kt(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ze,"CONNECTING",{enumerable:!0,value:Gn.indexOf("CONNECTING")});Object.defineProperty(Ze.prototype,"CONNECTING",{enumerable:!0,value:Gn.indexOf("CONNECTING")});Object.defineProperty(Ze,"OPEN",{enumerable:!0,value:Gn.indexOf("OPEN")});Object.defineProperty(Ze.prototype,"OPEN",{enumerable:!0,value:Gn.indexOf("OPEN")});Object.defineProperty(Ze,"CLOSING",{enumerable:!0,value:Gn.indexOf("CLOSING")});Object.defineProperty(Ze.prototype,"CLOSING",{enumerable:!0,value:Gn.indexOf("CLOSING")});Object.defineProperty(Ze,"CLOSED",{enumerable:!0,value:Gn.indexOf("CLOSED")});Object.defineProperty(Ze.prototype,"CLOSED",{enumerable:!0,value:Gn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(Ze.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(Ze.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[vc])return t[qR];return null},set(t){for(let n of this.listeners(e))if(n[vc]){this.removeListener(e,n);break}typeof t=="function"&&this.addEventListener(e,t,{[vc]:!0})}})});Ze.prototype.addEventListener=DR;Ze.prototype.removeEventListener=LR;m_.exports=Ze;function d_(e,t,n,i){let r={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:bc[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=r.autoPong,!bc.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${bc.join(", ")})`);let o;if(t instanceof _c)o=t;else try{o=new _c(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),e._url=o.href;let a=o.protocol==="wss:",s=o.protocol==="ws+unix:",d;if(o.protocol!=="ws:"&&!a&&!s?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:s&&!o.pathname?d="The URL's pathname is empty":o.hash&&(d="The URL contains a fragment identifier"),d){let y=new SyntaxError(d);if(e._redirects===0)throw y;Js(e,y);return}let u=a?443:80,l=RR(16).toString("base64"),p=a?IR.request:PR.request,m=new Set,f;if(r.createConnection=r.createConnection||(a?WR:JR),r.defaultPort=r.defaultPort||u,r.port=o.port||u,r.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},r.path=o.pathname+o.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(f=new sr(r.perMessageDeflate!==!0?r.perMessageDeflate:{},!1,r.maxPayload),r.headers["Sec-WebSocket-Extensions"]=UR({[sr.extensionName]:f.offer()})),n.length){for(let y of n){if(typeof y!="string"||!KR.test(y)||m.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(y)}r.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(o.username||o.password)&&(r.auth=`${o.username}:${o.password}`),s){let y=r.path.split(":");r.socketPath=y[0],r.path=y[1]}let h;if(r.followRedirects){if(e._redirects===0){e._originalIpc=s,e._originalSecure=a,e._originalHostOrSocketPath=s?r.socketPath:o.host;let y=i&&i.headers;if(i={...i,headers:{}},y)for(let[w,g]of Object.entries(y))i.headers[w.toLowerCase()]=g}else if(e.listenerCount("redirect")===0){let y=s?e._originalIpc?r.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:o.host===e._originalHostOrSocketPath;(!y||e._originalSecure&&!a)&&(delete r.headers.authorization,delete r.headers.cookie,y||delete r.headers.host,r.auth=void 0)}r.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),h=e._req=p(r),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=p(r);r.timeout&&h.on("timeout",()=>{Kt(e,h,"Opening handshake has timed out")}),h.on("error",y=>{h===null||h[s_]||(h=e._req=null,Js(e,y))}),h.on("response",y=>{let w=y.headers.location,g=y.statusCode;if(w&&r.followRedirects&&g>=300&&g<400){if(++e._redirects>r.maxRedirects){Kt(e,h,"Maximum redirects exceeded");return}h.abort();let v;try{v=new _c(w,t)}catch{let S=new SyntaxError(`Invalid URL: ${w}`);Js(e,S);return}d_(e,v,n,i)}else e.emit("unexpected-response",h,y)||Kt(e,h,`Unexpected server response: ${y.statusCode}`)}),h.on("upgrade",(y,w,g)=>{if(e.emit("upgrade",y),e.readyState!==Ze.CONNECTING)return;h=e._req=null;let v=y.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){Kt(e,w,"Invalid Upgrade header");return}let b=OR("sha1").update(l+jR).digest("base64");if(y.headers["sec-websocket-accept"]!==b){Kt(e,w,"Invalid Sec-WebSocket-Accept header");return}let S=y.headers["sec-websocket-protocol"],T;if(S!==void 0?m.size?m.has(S)||(T="Server sent an invalid subprotocol"):T="Server sent a subprotocol but none was requested":m.size&&(T="Server sent no subprotocol"),T){Kt(e,w,T);return}S&&(e._protocol=S);let C=y.headers["sec-websocket-extensions"];if(C!==void 0){if(!f){Kt(e,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let _;try{_=FR(C)}catch{Kt(e,w,"Invalid Sec-WebSocket-Extensions header");return}let k=Object.keys(_);if(k.length!==1||k[0]!==sr.extensionName){Kt(e,w,"Server indicated an extension that was not requested");return}try{f.accept(_[sr.extensionName])}catch{Kt(e,w,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[sr.extensionName]=f}e.setSocket(w,g,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(h,e):h.end()}function Js(e,t){e._readyState=Ze.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function JR(e){return e.path=e.socketPath,o_.connect(e)}function WR(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=o_.isIP(e.host)?"":e.host),ER.connect(e)}function Kt(e,t,n){e._readyState=Ze.CLOSING;let i=new Error(n);Error.captureStackTrace(i,Kt),t.setHeader?(t[s_]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Js,e,i)):(t.destroy(i),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function wc(e,t,n){if(t){let i=MR(t)?t.size:zR(t).length;e._socket?e._sender._bufferedBytes+=i:e._bufferedAmount+=i}if(n){let i=new Error(`WebSocket is not open: readyState ${e.readyState} (${Gn[e.readyState]})`);process.nextTick(n,i)}}function HR(e,t){let n=this[ht];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[ht]!==void 0&&(n._socket.removeListener("data",Ws),process.nextTick(u_,n._socket),e===1005?n.close():n.close(e,t))}function GR(){let e=this[ht];e.isPaused||e._socket.resume()}function VR(e){let t=this[ht];t._socket[ht]!==void 0&&(t._socket.removeListener("data",Ws),process.nextTick(u_,t._socket),t.close(e[NR])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function i_(){this[ht].emitClose()}function ZR(e,t){this[ht].emit("message",e,t)}function QR(e){let t=this[ht];t._autoPong&&t.pong(e,!this._isServer,a_),t.emit("ping",e)}function YR(e){this[ht].emit("pong",e)}function u_(e){e.resume()}function XR(e){let t=this[ht];t.readyState!==Ze.CLOSED&&(t.readyState===Ze.OPEN&&(t._readyState=Ze.CLOSING,l_(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function l_(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),BR)}function c_(){let e=this[ht];this.removeListener("close",c_),this.removeListener("data",Ws),this.removeListener("end",p_),e._readyState=Ze.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[ht]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",i_),e._receiver.on("finish",i_))}function Ws(e){this[ht]._receiver.write(e)||this.pause()}function p_(){let e=this[ht];e._readyState=Ze.CLOSING,e._receiver.end(),this.end()}function f_(){let e=this[ht];this.removeListener("error",f_),this.on("error",a_),e&&(e._readyState=Ze.CLOSING,this.destroy())}});var __=Bt((FQ,y_)=>{"use strict";var UQ=Hs(),{Duplex:eO}=dt("stream");function h_(e){e.emit("close")}function tO(){!this.destroyed&&this._writableState.finished&&this.destroy()}function g_(e){this.removeListener("error",g_),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function nO(e,t){let n=!0,i=new eO({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(o,a){let s=!a&&i._readableState.objectMode?o.toString():o;i.push(s)||e.pause()}),e.once("error",function(o){i.destroyed||(n=!1,i.destroy(o))}),e.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(r,o){if(e.readyState===e.CLOSED){o(r),process.nextTick(h_,i);return}let a=!1;e.once("error",function(d){a=!0,o(d)}),e.once("close",function(){a||o(r),process.nextTick(h_,i)}),n&&e.terminate()},i._final=function(r){if(e.readyState===e.CONNECTING){e.once("open",function(){i._final(r)});return}e._socket!==null&&(e._socket._writableState.finished?(r(),i._readableState.endEmitted&&i.destroy()):(e._socket.once("finish",function(){r()}),e.close()))},i._read=function(){e.isPaused&&e.resume()},i._write=function(r,o,a){if(e.readyState===e.CONNECTING){e.once("open",function(){i._write(r,o,a)});return}e.send(r,a)},i.on("end",tO),i.on("error",g_),i}y_.exports=nO});var b_=Bt((zQ,v_)=>{"use strict";var{tokenChars:rO}=gi();function iO(e){let t=new Set,n=-1,i=-1,r=0;for(r;r<e.length;r++){let a=e.charCodeAt(r);if(i===-1&&rO[a]===1)n===-1&&(n=r);else if(r!==0&&(a===32||a===9))i===-1&&n!==-1&&(i=r);else if(a===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${r}`);i===-1&&(i=r);let s=e.slice(n,i);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),n=i=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(n===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let o=e.slice(n,r);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}v_.exports={parse:iO}});var I_=Bt((KQ,T_)=>{"use strict";var oO=dt("events"),Gs=dt("http"),{Duplex:BQ}=dt("stream"),{createHash:aO}=dt("crypto"),w_=yc(),Mr=$o(),sO=b_(),dO=Hs(),{GUID:uO,kWebSocket:lO}=Jn(),cO=/^[+/0-9A-Za-z]{22}==$/,S_=0,k_=1,C_=2,Sc=class extends oO{constructor(t,n){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:dO,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=Gs.createServer((i,r)=>{let o=Gs.STATUS_CODES[426];r.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),r.end(o)}),this._server.listen(t.port,t.host,t.backlog,n)):t.server&&(this._server=t.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=pO(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,o,a)=>{this.handleUpgrade(r,o,a,i)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=S_}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===C_){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(No,this);return}if(t&&this.once("close",t),this._state!==k_)if(this._state=k_,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(No,this):process.nextTick(No,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{No(this)})}}shouldHandle(t){if(this.options.path){let n=t.url.indexOf("?");if((n!==-1?t.url.slice(0,n):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,n,i,r){n.on("error",x_);let o=t.headers["sec-websocket-key"],a=t.headers.upgrade,s=+t.headers["sec-websocket-version"];if(t.method!=="GET"){jr(this,t,n,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){jr(this,t,n,400,"Invalid Upgrade header");return}if(o===void 0||!cO.test(o)){jr(this,t,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(s!==13&&s!==8){jr(this,t,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Do(n,400);return}let d=t.headers["sec-websocket-protocol"],u=new Set;if(d!==void 0)try{u=sO.parse(d)}catch{jr(this,t,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=t.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&l!==void 0){let m=new Mr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let f=w_.parse(l);f[Mr.extensionName]&&(m.accept(f[Mr.extensionName]),p[Mr.extensionName]=m)}catch{jr(this,t,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:t.headers[`${s===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,h,y,w)=>{if(!f)return Do(n,h||401,y,w);this.completeUpgrade(p,o,u,t,n,i,r)});return}if(!this.options.verifyClient(m))return Do(n,401)}this.completeUpgrade(p,o,u,t,n,i,r)}completeUpgrade(t,n,i,r,o,a,s){if(!o.readable||!o.writable)return o.destroy();if(o[lO])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>S_)return Do(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${aO("sha1").update(n+uO).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(i.size){let p=this.options.handleProtocols?this.options.handleProtocols(i,r):i.values().next().value;p&&(u.push(`Sec-WebSocket-Protocol: ${p}`),l._protocol=p)}if(t[Mr.extensionName]){let p=t[Mr.extensionName].params,m=w_.format({[Mr.extensionName]:[p]});u.push(`Sec-WebSocket-Extensions: ${m}`),l._extensions=t}this.emit("headers",u,r),o.write(u.concat(`\r
4
4
  `).join(`\r
5
- `)),i.removeListener("error",Sr),c.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Fe,this)})),a(c,o)}};vr.exports=Bn;function Zi(e,n){for(let t of Object.keys(n))e.on(t,n[t]);return function(){for(let r of Object.keys(n))e.removeListener(r,n[r])}}function Fe(e){e._state=br,e.emit("close")}function Sr(){this.destroy()}function Le(e,n,t,r){t=t||dn.STATUS_CODES[n],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${n} ${dn.STATUS_CODES[n]}\r
6
- `+Object.keys(r).map(o=>`${o}: ${r[o]}`).join(`\r
5
+ `)),o.removeListener("error",x_),l.setSocket(o,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(No,this)})),s(l,r)}};T_.exports=Sc;function pO(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let i of Object.keys(t))e.removeListener(i,t[i])}}function No(e){e._state=C_,e.emit("close")}function x_(){this.destroy()}function Do(e,t,n,i){n=n||Gs.STATUS_CODES[t],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...i},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${Gs.STATUS_CODES[t]}\r
6
+ `+Object.keys(i).map(r=>`${r}: ${i[r]}`).join(`\r
7
7
  `)+`\r
8
8
  \r
9
- `+t)}function de(e,n,t,r,o,i){if(e.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,de),e.emit("wsClientError",s,t,n)}else Le(t,r,o,i)}});import{spawn as ht}from"node:child_process";import{randomUUID as yd}from"node:crypto";import{createConnection as _d,createServer as Sd}from"node:net";import{appendFileSync as bd,rmSync as we,writeFileSync as Be,mkdirSync as ke,mkdtempSync as mo,chmodSync as ze,existsSync as pt,readFileSync as yn,readdirSync as vd,statSync as xd,unlinkSync as wd}from"node:fs";import{dirname as ho,join as X}from"node:path";import{randomUUID as Ks}from"node:crypto";var Yi=Ie(fr(),1),Xi=Ie(Fn(),1),es=Ie(Dn(),1),Gn=Ie(an(),1),ns=Ie(xr(),1);function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wr(e){let n=[["threadId",e.threadId],["turnId",e.turnId],["itemId",e.itemId],["processId",e.processId],["requestId",e.requestId]].filter(t=>t[1]!==void 0);return Object.fromEntries(n)}function _(e){return e!==void 0&&C(e)?e:void 0}function j(e){return Array.isArray(e)?e:void 0}function l(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function E(e){return typeof e=="number"&&Number.isInteger(e)?e:void 0}import{appendFileSync as ds,openSync as Wu}from"node:fs";import{homedir as Ir}from"node:os";import{dirname as us,join as Pr,resolve as cs,sep as ls}from"node:path";import{mkdirSync as ps}from"node:fs";var G={_generated:"GENERATED by scripts/naming_dual_emit_codegen.mjs from scripts/naming_canonical_key_map.json (N2.2 dual-emit, D46) - DO NOT EDIT; run: node scripts/naming_dual_emit_codegen.mjs --write",events:[["codex.agent_turn_narration_only_no_reply","harness.agent_turn_narration_only_no_reply"],["codex.cost_cap_402_seen","harness.cost_cap_402_seen"],["codex.edge_blocked_captured","harness.edge_blocked_captured"],["codex.empty_turn_auto_retry_suppressed_cost_cap","harness.empty_turn_auto_retry_suppressed_cost_cap"],["codex.empty_turn_loop_guard_tripped","harness.empty_turn_loop_guard_tripped"],["codex.error_without_http_status_captured","harness.error_without_http_status_captured"],["codex.mid_stream_stall_auto_resume_flagged","harness.mid_stream_stall_auto_resume_flagged"],["codex.mid_stream_stall_fresh_session_resume","harness.mid_stream_stall_fresh_session_resume"],["codex.mid_stream_stall_fresh_session_resume_failed","harness.mid_stream_stall_fresh_session_resume_failed"],["codex.mid_stream_stall_fresh_session_resume_flagged","harness.mid_stream_stall_fresh_session_resume_flagged"],["codex.mid_stream_stall_resume_suppressed_rate_limit","harness.mid_stream_stall_resume_suppressed_rate_limit"],["codex.mid_stream_stall_second_stall_after_resume","harness.mid_stream_stall_second_stall_after_resume"],["codex.pre_first_byte_stall_auto_retry_flagged","harness.pre_first_byte_stall_auto_retry_flagged"],["codex.pre_first_byte_stall_retry_suppressed_cost_cap","harness.pre_first_byte_stall_retry_suppressed_cost_cap"],["codex.provider_outage_flagged_captured","harness.provider_outage_flagged_captured"],["codex.reasoning_loop_breaker_tripped","harness.reasoning_loop_breaker_tripped"],["codex.tool_fatal_captured","harness.tool_fatal_captured"],["codex.turn_completed","job.turn_completed"],["codex.turn_completed_with_protocol_failure","job.turn_completed_with_protocol_failure"],["codex.turn_completed_with_unsupported_tool_call_ignored","job.turn_completed_with_unsupported_tool_call_ignored"],["codex.turn_completed_without_assistant_output","job.turn_completed_without_assistant_output"],["codex.turn_demoted_late_upstream_error","job.turn_demoted_late_upstream_error"],["codex.turn_forward_failed","job.turn_forward_failed"],["codex.upstream_error_captured","harness.upstream_error_captured"],["codex.upstream_rejection_captured","harness.upstream_rejection_captured"],["codex.upstream_turn_error_captured","harness.upstream_turn_error_captured"],["kandan.chat_event","linzumi.chat_event"],["kandan.chat_event_abandoned","linzumi.chat_event_abandoned"],["kandan.chat_event_failed","linzumi.chat_event_failed"],["kandan.chat_event_failure_cleared","linzumi.chat_event_failure_cleared"],["kandan.child_thread_event_failed","linzumi.child_thread_event_failed"],["kandan.child_thread_event_skipped_missing_thread_binding","linzumi.child_thread_event_skipped_missing_thread_binding"],["kandan.child_thread_upsert_failed","linzumi.child_thread_upsert_failed"],["kandan.child_thread_upsert_skipped_missing_thread_binding","linzumi.child_thread_upsert_skipped_missing_thread_binding"],["kandan.claude_code_interrupt_state_push_failed","linzumi.claude_code_interrupt_state_push_failed"],["kandan.claude_code_stop_state_push_failed","linzumi.claude_code_stop_state_push_failed"],["kandan.claude_code_typing_heartbeat_failed","linzumi.claude_code_typing_heartbeat_failed"],["kandan.claude_code_typing_start_wait_timeout","linzumi.claude_code_typing_start_wait_timeout"],["kandan.claude_code_typing_stop_failed","linzumi.claude_code_typing_stop_failed"],["kandan.claude_code_user_input_abort_publish_failed","linzumi.claude_code_user_input_abort_publish_failed"],["kandan.claude_code_user_question_completed_publish_failed","linzumi.claude_code_user_question_completed_publish_failed"],["kandan.codex_command_output_forwarded","linzumi.codex_command_output_forwarded"],["kandan.codex_delta_forwarded","linzumi.codex_delta_forwarded"],["kandan.codex_file_change_forwarded","linzumi.codex_file_change_forwarded"],["kandan.codex_notification_push_failed","linzumi.codex_notification_push_failed"],["kandan.codex_output_forwarded","linzumi.codex_output_forwarded"],["kandan.codex_reasoning_delta_forwarded","linzumi.codex_reasoning_delta_forwarded"],["kandan.codex_web_search_progress_forwarded","linzumi.codex_web_search_progress_forwarded"],["kandan.connection_force_reconnect","linzumi.connection_force_reconnect"],["kandan.connection_force_reconnect_dispatched","linzumi.connection_force_reconnect_dispatched"],["kandan.connection_hard_reset","linzumi.connection_hard_reset"],["kandan.connection_hard_reset_exhausted","linzumi.connection_hard_reset_exhausted"],["kandan.connection_recovered","linzumi.connection_recovered"],["kandan.connection_stale","linzumi.connection_stale"],["kandan.connection_unrecoverable","linzumi.connection_unrecoverable"],["kandan.control","linzumi.control"],["kandan.control_ack_withheld_on_failure","linzumi.control_ack_withheld_on_failure"],["kandan.control_epoch_changed","linzumi.control_epoch_changed"],["kandan.control_handler_threw","linzumi.control_handler_threw"],["kandan.control_ignored","linzumi.control_ignored"],["kandan.control_response_push_failed","linzumi.control_response_push_failed"],["kandan.failed_seq_overflow","linzumi.failed_seq_overflow"],["kandan.forward_port_revoked_push_failed","linzumi.forward_port_revoked_push_failed"],["kandan.forward_response","linzumi.forward_response"],["kandan.forward_response_push_failed","linzumi.forward_response_push_failed"],["kandan.forward_tunnel_error","linzumi.forward_tunnel_error"],["kandan.forward_tunnel_open_failed","linzumi.forward_tunnel_open_failed"],["kandan.heartbeat_push_failed","linzumi.heartbeat_push_failed"],["kandan.local_editor_initial_status_failed","linzumi.local_editor_initial_status_failed"],["kandan.local_editor_status_push_failed","linzumi.local_editor_status_push_failed"],["kandan.message_duplicate_ignored","linzumi.message_duplicate_ignored"],["kandan.message_ignored","linzumi.message_ignored"],["kandan.message_queued","linzumi.message_queued"],["kandan.message_spawn_on_miss","linzumi.message_spawn_on_miss"],["kandan.message_spawn_on_miss_failed","linzumi.message_spawn_on_miss_failed"],["kandan.message_state_refresh_failed","linzumi.message_state_refresh_failed"],["kandan.optional_push_failed","linzumi.optional_push_failed"],["kandan.post_stop_queue_drain_failed","linzumi.post_stop_queue_drain_failed"],["kandan.queue_drain_blocked","linzumi.queue_drain_blocked"],["kandan.queue_drain_dead_worker_fail_publish_failed","linzumi.queue_drain_dead_worker_fail_publish_failed"],["kandan.queue_drain_dead_worker_rebuild","linzumi.queue_drain_dead_worker_rebuild"],["kandan.queue_drain_dead_worker_rebuild_exhausted","linzumi.queue_drain_dead_worker_rebuild_exhausted"],["kandan.queue_drain_dead_worker_rebuild_failed","linzumi.queue_drain_dead_worker_rebuild_failed"],["kandan.reconnect_handling_failed","linzumi.reconnect_handling_failed"],["kandan.reconnect_thread_context_fetch_failed","linzumi.reconnect_thread_context_fetch_failed"],["kandan.reconnect_thread_cwd_failed_state_push_failed","linzumi.reconnect_thread_cwd_failed_state_push_failed"],["kandan.reconnect_thread_failed","linzumi.reconnect_thread_failed"],["kandan.reconnect_thread_processing_state_push_failed","linzumi.reconnect_thread_processing_state_push_failed"],["kandan.reconnect_thread_queue_closed_state_push_failed","linzumi.reconnect_thread_queue_closed_state_push_failed"],["kandan.reconnect_thread_queue_failed_state_push_failed","linzumi.reconnect_thread_queue_failed_state_push_failed"],["kandan.reconnect_thread_queue_state_push_failed","linzumi.reconnect_thread_queue_state_push_failed"],["kandan.reconnect_thread_rehydrate_forced","linzumi.reconnect_thread_rehydrate_forced"],["kandan.reconnect_thread_rehydrated","linzumi.reconnect_thread_rehydrated"],["kandan.reconnect_thread_rehydrated_state_push_failed","linzumi.reconnect_thread_rehydrated_state_push_failed"],["kandan.reconnect_thread_rehydration_failed","linzumi.reconnect_thread_rehydration_failed"],["kandan.reconnect_thread_rehydration_ir_emitted","linzumi.reconnect_thread_rehydration_ir_emitted"],["kandan.reconnect_thread_rehydration_items_failed","linzumi.reconnect_thread_rehydration_items_failed"],["kandan.reconnect_thread_resume_failed","linzumi.reconnect_thread_resume_failed"],["kandan.reconnect_thread_seq_already_applied","linzumi.reconnect_thread_seq_already_applied"],["kandan.reconnect_thread_transcript_fetch_failed","linzumi.reconnect_thread_transcript_fetch_failed"],["kandan.reconnect_thread_unarchive_failed","linzumi.reconnect_thread_unarchive_failed"],["kandan.reconnect_thread_unarchive_resumed","linzumi.reconnect_thread_unarchive_resumed"],["kandan.reconnect_thread_unarchive_started","linzumi.reconnect_thread_unarchive_started"],["kandan.reconnect_thread_unavailable_state_push_failed","linzumi.reconnect_thread_unavailable_state_push_failed"],["kandan.reconnected","linzumi.reconnected"],["kandan.roster_seeded","linzumi.roster_seeded"],["kandan.session_app_server_lost_push_failed","linzumi.session_app_server_lost_push_failed"],["kandan.session_settings_publish_failed","linzumi.session_settings_publish_failed"],["kandan.start_instance_claude_code_attachment_failed_state_push_failed","linzumi.start_instance_claude_code_attachment_failed_state_push_failed"],["kandan.start_instance_codex_app_server_unavailable","linzumi.start_instance_codex_app_server_unavailable"],["kandan.start_instance_cwd_failed_state_push_failed","linzumi.start_instance_cwd_failed_state_push_failed"],["kandan.start_instance_cwd_rejected","linzumi.start_instance_cwd_rejected"],["kandan.start_instance_failed","linzumi.start_instance_failed"],["kandan.start_instance_processing_state_push_failed","linzumi.start_instance_processing_state_push_failed"],["kandan.start_instance_skipped_known_session","linzumi.start_instance_skipped_known_session"],["kandan.start_instance_stale_skipped","linzumi.start_instance_stale_skipped"],["kandan.start_instance_unavailable_state_push_failed","linzumi.start_instance_unavailable_state_push_failed"],["kandan.start_instance_wafer_state_push_failed","linzumi.start_instance_wafer_state_push_failed"],["kandan.start_turn_replay_skipped","linzumi.start_turn_replay_skipped"],["kandan.steer_duplicate_ignored","linzumi.steer_duplicate_ignored"],["kandan.steer_parked_as_own_turn","linzumi.steer_parked_as_own_turn"],["kandan.thread_bind_from_historical_reply_failed","linzumi.thread_bind_from_historical_reply_failed"],["kandan.thread_bound_from_historical_reply","linzumi.thread_bound_from_historical_reply"],["kandan.thread_sessions_reannounce_failed","linzumi.thread_sessions_reannounce_failed"],["kandan.thread_sessions_reannounced","linzumi.thread_sessions_reannounced"],["kandan.tui_input_mirrored","linzumi.tui_input_mirrored"],["kandan.typing_heartbeat_failed","linzumi.typing_heartbeat_failed"],["kandan.typing_stop_after_completion_failed","linzumi.typing_stop_after_completion_failed"]],keys:[["codexThreadId","harness_session_id"],["codex_thread_id","harness_session_id"],["kandanThreadId","thread_id"],["kandan_preview_ticket","linzumi_preview_ticket"],["kandan_thread_id","thread_id"],["linzumiThreadId","thread_id"],["linzumi_thread_id","thread_id"],["local_codex_runner","commander"],["runnerId","commander_id"],["runner_config","commander_config"],["runner_id","commander_id"]],keyPrimaryLegacy:[["commander","local_codex_runner"],["commander_config","runner_config"],["commander_id","runner_id"],["harness_session_id","codex_thread_id"],["linzumi_preview_ticket","kandan_preview_ticket"],["thread_id","kandan_thread_id"]],values:[["engine_boot_reconnect","harness_boot_reconnect"],["engine_for_runner_event_type","harness_for_commander_event_type"],["engine_rejected_steer","harness_rejected_steer"],["engine_unavailable","harness_unavailable"],["join_engine","join_harness"],["kandan-local-codex-runner","linzumi-commander"],["local_codex_runner","commander"],["original_engine","original_harness"],["resume_engine","resume_harness"]],topic:{legacyPrefix:"local_codex_runner:",canonicalPrefix:"commander:"},originator:{legacy:"kandan-local-codex-runner",canonical:"linzumi-commander"}};var rs=new Map(G.events),os=new Map(G.events.map(([e,n])=>[n,e])),Tr=new Map(G.keys),Cr=new Map(G.keyPrimaryLegacy),is=new Map(G.values),ss=new Map(G.values.map(([e,n])=>[n,e])),Ku={eventCanonicalByLegacy:rs,eventLegacyByCanonical:os,keyCanonicalByLegacy:Tr,keyPrimaryLegacyByCanonical:Cr,valueCanonicalByLegacy:is,valueLegacyByCanonical:ss,originator:G.originator,topic:G.topic};function Rr(e){let n=new Set(e);for(let t of e){let r=Tr.get(t);r!==void 0&&n.add(r);let o=Cr.get(t);o!==void 0&&n.add(o)}return n}var kr=new Map;for(let[e,n]of G.keys){let t=kr.get(n)??[];t.push(e),kr.set(n,t)}var ue="<SENSITIVE_DATA>",Er=Rr(new Set(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"])),fs=new Set(["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"]);function ms(e){if(process.env.VITEST===void 0)return;let n=Pr(Ir(),".linzumi"),t=cs(e);if(t===n||t.startsWith(`${n}${ls}`))throw new Error(`test-mode log isolation violated: refusing to open ${e} inside the real ~/.linzumi (point the logger at a temp path; the harness defaults LINZUMI_RUNNER_LOG_FILE / LINZUMI_CLI_AUDIT_LOG for exactly this - see plans/2026-07-10-cli-test-hygiene-spec.md item 2)`)}function Y(e,n,t={}){let r=t.logFile??hs();ms(r);try{ps(us(r),{recursive:!0}),ds(r,`${JSON.stringify({ts:new Date().toISOString(),event:e,...t.sessionId===void 0?{}:{sessionId:t.sessionId},...Ar(n)})}
10
- `,"utf8")}catch{return}}function hs(){let e=process.env.LINZUMI_CLI_AUDIT_LOG?.trim();return e===void 0||e===""?Pr(Ir(),".linzumi","logs","command-events.jsonl"):e}function Ar(e){return Mr(e)}function Wn(e,n){return _s(n)?ue:typeof e=="string"?qr(e):Array.isArray(e)?n==="args"?gs(e):e.map(t=>Wn(t,void 0)):e!==null&&typeof e=="object"?Mr(e):e}function Mr(e){let n=typeof e.name=="string"?e.name.toLowerCase():void 0,t=n==="authorization"||n==="cookie"||n==="set-cookie";return Object.fromEntries(Object.entries(e).filter(([r])=>r!=="runner_console").map(([r,o])=>[r,t&&r==="value"?ue:Wn(o,r)]))}function gs(e){let n=!1;return e.map(t=>{if(typeof t!="string")return n=!1,Wn(t,void 0);if(n)return n=!1,ue;let[r,o]=ys(t);return fs.has(r)?o===void 0?(n=!0,t):`${r}=${ue}`:qr(t)})}function ys(e){let n=e.indexOf("=");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function _s(e){return e===void 0?!1:/^(authorization|cookie|set-cookie|password)$/i.test(e)||/(^|[_-])(access[_-]?token|api[_-]?key|auth[_-]?token|oauth[_-]?code|refresh[_-]?token|secret|token)$/i.test(e)}function qr(e){return Ss(e).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,ue)}function Ss(e){let n;try{n=new URL(e)}catch{return bs(e)}for(let t of[...n.searchParams.keys()])Er.has(t.toLowerCase())&&n.searchParams.set(t,ue);return n.toString()}function bs(e){let n=e.indexOf("?"),t=e.indexOf("#");if(n===-1||t!==-1&&t<n)return e;let r=e.slice(0,n),o=t===-1?e.slice(n+1):e.slice(n+1,t),i=t===-1?"":e.slice(t),s=new URLSearchParams(o),a=!1;for(let d of[...s.keys()])Er.has(d.toLowerCase())&&(s.set(d,ue),a=!0);switch(a){case!0:return`${r}?${s.toString()}${i}`;case!1:return e}}import{stripVTControlCharacters as Is}from"node:util";function un(e){let n=e.channelSession,t=n.linzumiAgentSession===!0,r=t?"read-only":n.sandbox,o=vs(n);return{cwd:e.cwd,...n.model===void 0?{}:{model:n.model},...o===void 0?{}:{config:o},...e.fast===!0?{serviceTier:"fast"}:{},...n.codexEnvironmentId===void 0?{}:{environmentId:n.codexEnvironmentId},approvalPolicy:t?"never":Or(n.approvalPolicy,r,{sandboxedNeverDefault:n.sandboxedApprovalNeverDefault}),...r===void 0?{}:{sandbox:r}}}function Hn(e){let n=e.channelSession,t=n.linzumiAgentSession===!0,r=t?"read-only":n.sandbox;return{cwd:e.cwd,...n.model===void 0?{}:{model:n.model},...n.reasoningEffort===void 0?{}:{effort:n.reasoningEffort},...e.fast===!0?{serviceTier:"fast"}:{},...n.codexEnvironmentId===void 0?{}:{environmentId:n.codexEnvironmentId},approvalPolicy:t?"never":Or(n.approvalPolicy,r,{sandboxedNeverDefault:n.sandboxedApprovalNeverDefault}),...r===void 0?{}:{sandboxPolicy:ks(r,e.cwd)}}}function vs(e){let n=e.reasoningEffort===void 0?{}:{model_reasoning_effort:e.reasoningEffort};return e.linzumiAgentSession!==!0?e.reasoningEffort===void 0?void 0:n:{...n,web_search:"disabled",tools:{view_image:!1},features:{apps:!1,shell_tool:!1,unified_exec:!1,multi_agent:!1,code_mode:!1,image_generation:!1,browser_use:!1,browser_use_external:!1,computer_use:!1,remote_plugin:!1,tool_suggest:!1,workspace_dependencies:!1}}}function xs(e,n,t){let r=t?.sandboxedNeverDefault===!0&&n==="workspace-write";switch(e){case void 0:case"default":return r?"never":"on-request";case"never":return n==="danger-full-access"||r?"never":"on-request";case"on-request":case"on-failure":return e;default:return console.warn(`linzumi approval-policy clamp: unknown Codex approval policy ${e}; clamping to most-restrictive approval (on-request)`),"on-request"}}var ws={granular:{sandbox_approval:!1,rules:!1,skill_approval:!1,request_permissions:!1,mcp_elicitations:!0}};function Or(e,n,t){let r=xs(e,n,t);return r==="never"&&n==="danger-full-access"?ws:r==="on-failure"?"on-request":r}function ks(e,n){switch(e){case"danger-full-access":return{type:"dangerFullAccess"};case"read-only":return{type:"readOnly",networkAccess:!1};case"workspace-write":return{type:"workspaceWrite",writableRoots:[n],networkAccess:!1,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1};default:throw new Error(`unsupported Codex sandbox mode: ${e}`)}}function Fr(e){let n=Is(e),t=n.match(/https:\/\/[^\s\u0000-\u001f\u007f]+/u)?.[0],r=n.match(/\b[A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+\b/u)?.[0];return t===void 0||r===void 0?void 0:{verificationUrl:t,userCode:r}}function Vn(e){return e==="final_answer"?"final_answer":"commentary"}function Qn(e){let n=Ps(e),t=_(e.item);if(!(n===void 0||n===""))return{itemKey:l(e.itemId)??l(e.item_id)??l(_(e.item)?.id)??"assistant-message",turnId:l(e.turnId)??l(e.turn_id)??l(_(e.turn)?.id),delta:n,phase:Vn(e.phase??t?.phase)}}function Zn(e){let n=Lr(e);if(!(n===void 0||n===""))return{itemKey:l(e.itemId)??l(e.item_id)??l(_(e.item)?.id)??"reasoning",turnId:l(e.turnId)??l(e.turn_id)??l(_(e.turn)?.id),delta:n}}function Ps(e){return Lr(e)}function Es(e){return e>=55296&&e<=56319}function As(e){return e>=56320&&e<=57343}function Yn(e,n){let t=Math.min(Math.max(0,n),e.length),r=t>0&&t<e.length&&Es(e.charCodeAt(t-1))&&As(e.charCodeAt(t))?t-1:t;return e.slice(0,r)}function Lr(e){let n=e.delta;return typeof n=="string"?n:C(n)?l(n.text)??l(n.content)??l(n.delta)??l(n.message):l(e.text)??l(e.content)??l(e.message)}import{mkdirSync as Ms,appendFileSync as qs}from"node:fs";import{dirname as Os}from"node:path";function jr(e){return JSON.stringify(e)}var je,Fs=/(^|[_-])(token|secret|api[_-]?key|authorization|cookie|private[_-]?key|login[_-]?url)([_-]|$)/iu;function Xn(){return Dr()!==void 0}function cn(e){let n=Dr();if(n===void 0)return;let t=Ls(n),r=js(e),o={schemaVersion:1,provider:e.provider,captureKind:e.captureKind,ordinal:t.nextOrdinal,offsetMs:Math.max(0,Date.now()-t.startedAtMs),...r.rawText===void 0?{}:{rawText:r.rawText},...r.rawValue===void 0?{}:{rawValue:r.rawValue},...e.captureMetadata===void 0?{}:{captureMetadata:De(e.captureMetadata)},...r.transforms.length===0?e.transforms===void 0?{}:{transforms:e.transforms}:{transforms:[...e.transforms??[],...r.transforms]}};t.nextOrdinal+=1,qs(n,`${jr(o)}
11
- `,"utf8")}function Dr(){let e=process.env.LINZUMI_AGENT_REPLAY_RECORD_FILE?.trim();return e===void 0||e===""?void 0:e}function Ls(e){return je!==void 0&&je.path===e||(Ms(Os(e),{recursive:!0}),je={path:e,startedAtMs:Date.now(),nextOrdinal:0}),je}function js(e){if(process.env.LINZUMI_AGENT_REPLAY_EXACT_RAW==="1")return{rawText:e.rawText,rawValue:e.rawValue,transforms:[]};let n=[],t=e.rawValue===void 0?void 0:De(e.rawValue,"$.rawValue",n);return{rawText:Ds(e.rawText,n),rawValue:t,transforms:n}}function Ds(e,n){if(e!==void 0)try{let t=JSON.parse(e);return JSON.stringify(De(t,"$.rawText",n))}catch{return e}}function De(e,n="$",t=[]){if(Array.isArray(e))return e.map((o,i)=>De(o,`${n}[${i}]`,t));if(!C(e))return e;let r=Object.entries(e).map(([o,i])=>{let s=`${n}.${o}`;return Fs.test(o)?(t.push({type:"credential_redaction",path:s}),[o,"[REDACTED]"]):[o,i===void 0?void 0:De(i,s,t)]});return Object.fromEntries(r)}function Nr(e){return{name:"linzumi",command:e.command??"linzumi",args:[...e.argsPrefix??[],"mcp","server","--api-url",e.kandanUrl,...e.authFilePath===void 0?[]:["--auth-file",e.authFilePath],...e.delegationAuthFilePath===void 0?[]:["--delegation-auth-file",e.delegationAuthFilePath],...e.ownerUsername===void 0?[]:["--owner-username",e.ownerUsername],...e.cwd===void 0?[]:["--cwd",e.cwd],...e.threadId===void 0?[]:["--thread-id",e.threadId],"--mode",e.operatingMode??"text",...e.toolScope===void 0||e.toolScope==="all"?[]:["--tool-scope",e.toolScope],...e.agentSession===!0?["--agent-session"]:[],...e.askUserQuestionTool===!0?["--ask-user-question-tool"]:[],...e.multiAgentJobs===!0?["--multi-agent-jobs"]:[]],env:{...e.accessToken===void 0?{}:{LINZUMI_MCP_ACCESS_TOKEN:e.accessToken},...e.devServices===void 0?{}:{LINZUMI_DEV_SERVICES_SCOPE:e.devServices.scope,LINZUMI_DEV_SERVICES_OWNER_PID:String(e.devServices.ownerPid)},ELECTRON_RUN_AS_NODE:"1"}}}function et(e,n){return["-c",`mcp_servers.${e.name}.command=${JSON.stringify(e.command)}`,"-c",`mcp_servers.${e.name}.args=${Ns(e.args)}`,...Object.entries(e.env).flatMap(([t,r])=>["-c",`mcp_servers.${e.name}.env.${t}=${JSON.stringify(r)}`]),...n.neverEquivalentGranularApprovalPolicy?["-c",`mcp_servers.${e.name}.default_tools_approval_mode="approve"`]:[],...e.args.includes("--ask-user-question-tool")?["-c",`mcp_servers.${e.name}.tool_timeout_sec=${$r}`]:[]]}function Ns(e){return`[${e.map(n=>JSON.stringify(n)).join(", ")}]`}var $r=2147483,$s=$r*1e3-5*6e4;var yc=["# Managed by Linzumi - do not edit by hand.","# This isolated CODEX_HOME keeps Linzumi-spawned codex processes off the","# user's ~/.codex config and the macOS Keychain. See codexHome.ts.",'mcp_oauth_credentials_store = "file"','cli_auth_credentials_store = "file"',""].join(`
12
- `);function Jr(){return["-c",'mcp_oauth_credentials_store="file"',"-c",'cli_auth_credentials_store="file"']}var Js=5*6e4;var zs=(()=>{let e=process.env.LINZUMI_CODEX_WS_KEEPALIVE_MS;if(e===void 0)return 2e4;let n=Number.parseInt(e,10);return Number.isInteger(n)&&n>0?n:2e4})();function Bs(e){let n=e;if(typeof n.ping=="function"&&n.readyState===WebSocket.OPEN)try{n.ping()}catch{}}function zr(e,n={}){return["app-server",...oa(n),"--listen",e]}var Gs=["-c","features.apps=false"],Ws=["-c","features.default_mode_request_user_input=true"],Hs="LINZUMI_CODEX_STREAM_IDLE_TIMEOUT_MS",Vs="LINZUMI_CODEX_STREAM_IDLE_TIMEOUT_SOURCE",Qs=5e3,Zs=6e5,Ys=["flag","env","server_default"];function Xs(e){return Ys.find(n=>n===e)}function ea(e){let n=e?.trim();if(e===void 0||n===void 0||n==="")return{state:"unset"};if(!/^[0-9]+$/.test(n))return{state:"invalid",raw:e};let t=Number(n);return!Number.isSafeInteger(t)||t<Qs||t>Zs?{state:"invalid",raw:e}:{state:"applied",timeoutMs:t}}function na(e=process.env){let n=ea(e[Hs]);if(n.state==="unset")return n;let t=Xs(e[Vs]?.trim())??"env";return{...n,source:t}}function ta(e=process.env){let n=na(e);return n.state==="applied"?n.timeoutMs:void 0}var Br="openai-linzumi";function Gr(){let e=Br;return["-c",`model_providers.${e}.name="OpenAI"`,"-c",`model_providers.${e}.wire_api="responses"`,"-c",`model_providers.${e}.requires_openai_auth=true`,"-c",`model_providers.${e}.supports_websockets=true`]}function ra(e){let n=Br;return[...Gr(),"-c",`model_providers.${n}.stream_idle_timeout_ms=${e}`,"-c",`model_provider="${n}"`]}function oa(e,n=process.env){let t=ta(n);return[...Gs,...e.nativeQuestionBridge==="durable"?Ws:[],...Jr(),...e.model===void 0?[]:["-c",`model=${JSON.stringify(e.model)}`],...e.reasoningEffort===void 0?[]:["-c",`model_reasoning_effort=${JSON.stringify(e.reasoningEffort)}`],...e.fast===!0?["-c",`service_tier=${JSON.stringify("fast")}`]:[],...(e.mcpServers??[]).flatMap(r=>et(r,{neverEquivalentGranularApprovalPolicy:e.neverEquivalentGranularApprovalPolicy===!0})),...e.modelProvider===void 0?t===void 0?Gr():ra(t):ia(e.modelProvider,t)]}function ia(e,n){return["-c",`model_providers.${e.id}.name=${JSON.stringify(e.name)}`,"-c",`model_providers.${e.id}.base_url=${JSON.stringify(e.baseUrl)}`,"-c",`model_providers.${e.id}.env_key=${JSON.stringify(e.envKey)}`,"-c",`model_providers.${e.id}.wire_api=${JSON.stringify(e.wireApi)}`,...Object.entries(e.httpHeaders??{}).flatMap(([t,r])=>["-c",`model_providers.${e.id}.http_headers.${t}=${JSON.stringify(r)}`]),...Object.entries(e.envHttpHeaders??{}).flatMap(([t,r])=>["-c",`model_providers.${e.id}.env_http_headers.${t}=${JSON.stringify(r)}`]),...n===void 0?[]:["-c",`model_providers.${e.id}.stream_idle_timeout_ms=${n}`],"-c",`model_provider=${JSON.stringify(e.id)}`]}async function Wr(e,n=t=>new Gn.default(t)){let t=await ca(e,n),r=Ks(),o=new Map,i=new Set,s=new Set,a=[],d=new Set,u={nextId:1,closeError:void 0},c=h=>{let p=new Error(h);o.forEach(m=>m.reject(p)),o.clear()},f=setInterval(()=>Bs(t),zs);f.unref?.();let y=h=>{if(clearInterval(f),c(h),u.closeError===void 0){u.closeError=new Error(h);for(let p of d)Kr(p,u.closeError);d.clear()}};return t.addEventListener("close",()=>y("codex app-server websocket closed")),t.addEventListener("error",()=>y("codex app-server websocket closed")),t.addEventListener("message",h=>{let p=String(h.data),m=ua(p);if(m===void 0){sa(p,r);return}if(Ne({direction:"codex_to_commander",captureKind:da(m),message:m,rawText:p,connectionId:r}),"id"in m&&("result"in m||"error"in m)){let k=o.get(m.id);k!==void 0&&(o.delete(m.id),k.resolve(m));return}if("id"in m&&typeof m.method=="string"){pa(t,m,s,r);return}if(!("id"in m)&&typeof m.method=="string"){let k=m;i.size===0?a.push(k):i.forEach(I=>Ur(I,k))}}),await ma(t,o,r),{request:(h,p)=>{let m=u.nextId;return u.nextId+=1,Hr(t,o,p===void 0?{jsonrpc:"2.0",id:m,method:h}:{jsonrpc:"2.0",id:m,method:h,params:p},r)},notify:(h,p)=>{let m=p===void 0?{jsonrpc:"2.0",method:h}:{jsonrpc:"2.0",method:h,params:p};Ne({direction:"commander_to_codex",captureKind:"outgoing",message:m,rawText:JSON.stringify(m),connectionId:r}),t.send(JSON.stringify(m))},onNotification:h=>{i.add(h),a.splice(0).forEach(p=>Ur(h,p))},onRequest:h=>{s.add(h)},onClose:h=>{if(u.closeError!==void 0){Kr(h,u.closeError);return}d.add(h)},isClosed:()=>u.closeError!==void 0,close:()=>{clearInterval(f),t.close()}}}function Ne(e){Xn()&&cn({provider:"codex-app-server",captureKind:e.captureKind,rawText:e.rawText,rawValue:{message:e.message},captureMetadata:{direction:e.direction,capturedAtMs:Date.now(),capturePid:process.pid,connectionId:e.connectionId,...aa(e.message),...e.extraMetadata??{}}})}function sa(e,n){Xn()&&cn({provider:"codex-app-server",captureKind:"incoming",rawText:e,captureMetadata:{direction:"codex_to_commander",capturedAtMs:Date.now(),capturePid:process.pid,connectionId:n,malformed:!0}})}function aa(e){return!("params"in e)||!C(e.params)?{}:wr(e.params)}function da(e){return"id"in e&&("result"in e||"error"in e)?"response":"id"in e&&typeof e.method=="string"?"request":"notification"}function ua(e){let n=String(e);try{let t=JSON.parse(n);if(!C(t))throw new Error("codex app-server sent non-object JSON-RPC message");return t}catch(t){Y("codex.app_server_frame_malformed",{purpose:"codex.app_server",message:t instanceof Error?t.message:String(t),payload:Yn(n,512),payloadChars:n.length});return}}function Ur(e,n){try{e(n)}catch(t){Y("codex.notification_callback_failed",{purpose:"codex.app_server",method:n.method,message:t instanceof Error?t.message:String(t)})}}function Kr(e,n){try{e(n)}catch(t){Y("codex.close_callback_failed",{purpose:"codex.app_server",message:t instanceof Error?t.message:String(t)})}}async function ca(e,n,t=2e3){let r=Date.now()+t,o;for(;Date.now()<=r;){let i=n(e);try{return await ha(i),i}catch(s){o=s instanceof Error?s:new Error(String(s)),la(i)}}throw o??new Error("websocket open failed")}function la(e){try{e.close()}catch{}}async function pa(e,n,t,r){let o=i=>fa(e,i,n.method,r);try{if(t.size===0){o({jsonrpc:"2.0",id:n.id,error:{code:-32601,message:`unhandled Codex app-server request: ${n.method}`}});return}for(let i of t){let s=await i(n);if(s!==void 0){o({jsonrpc:"2.0",id:n.id,result:s});return}}o({jsonrpc:"2.0",id:n.id,error:{code:-32601,message:`unhandled Codex app-server request: ${n.method}`}})}catch(i){o({jsonrpc:"2.0",id:n.id,error:{code:-32e3,message:i instanceof Error?i.message:String(i)}})}}function fa(e,n,t,r){let o=JSON.stringify(n);Ne({direction:"commander_to_codex",captureKind:"response",message:n,rawText:o,connectionId:r,extraMetadata:{requestMethod:t}}),e.send(o)}async function ma(e,n,t){let r=await Hr(e,n,{jsonrpc:"2.0",id:"initialize",method:"initialize",params:{clientInfo:{name:"kandan-local-codex-runner",version:"0.0.1"},capabilities:{experimentalApi:!0}}},t);if("error"in r)throw new Error(`codex initialize failed: ${r.error.message}`);let o={jsonrpc:"2.0",method:"initialized"};Ne({direction:"commander_to_codex",captureKind:"outgoing",message:o,rawText:JSON.stringify(o),connectionId:t}),e.send(JSON.stringify(o))}function Hr(e,n,t,r){return e.readyState!==WebSocket.OPEN?Promise.reject(new Error("codex app-server websocket is not open")):new Promise((o,i)=>{n.set(t.id,{resolve:o,reject:i}),Ne({direction:"commander_to_codex",captureKind:"request",message:t,rawText:JSON.stringify(t),connectionId:r}),e.send(JSON.stringify(t))})}function ha(e){return new Promise((n,t)=>{e.addEventListener("open",()=>n(),{once:!0}),e.addEventListener("error",()=>t(new Error("websocket open failed")),{once:!0})})}var Zc=300*1e3;function ln(e){let n=new URL(e);switch(n.protocol){case"ws:":n.protocol="http:";break;case"wss:":n.protocol="https:";break;case"http:":case"https:":break;default:throw new Error("--api-url must be ws://, wss://, http://, or https://")}return n.pathname="",n.search="",n.hash="",n.toString().replace(/\/$/,"")}function $e(e){let n=e.fetchImpl??fetch,t=ln(e.kandanUrl),r=e.authMode==="personal-agent-delegation"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",o=e.operatingMode??"text",i=async(s,a,d,u={})=>{let c=new URL(a,t),f={...d,operating_mode:o},y={method:s,headers:{authorization:`Bearer ${e.accessToken}`},...u.signal===void 0?{}:{signal:u.signal}};if(s==="GET")for(let[I,L]of Object.entries(f))L!=null&&c.searchParams.set(I,String(L));else y.headers={...y.headers,"content-type":"application/json"},y.body=JSON.stringify(f);let v=await n(c,y),h=await v.json(),p=C(h)?h:void 0;if(p===void 0)throw new Error(`Linzumi MCP API returned non-object JSON from ${a}`);if(v.ok&&p.ok===!0)return p;let m=typeof p.error=="string"?p.error:`HTTP ${v.status}`,k=typeof p.detail=="string"?p.detail:void 0;throw new Error(`Linzumi MCP API ${a} failed: ${m}${k===void 0?"":` detail=${k}`}`)};return{validateAuth:()=>i("GET",`${r}/validate`,{}),issueOnboardingDiscoveryToken:s=>i("POST",`${r}/onboarding-discovery-token`,s),getMessage:s=>i("GET",`${r}/message`,s),getThread:s=>i("GET",`${r}/thread`,s),getThreadTranscript:s=>i("GET",`${r}/thread-transcript`,s),getChannel:s=>i("GET",`${r}/channel`,s),searchWorkspace:s=>i("GET",`${r}/search`,s),askWorkspace:s=>i("POST",`${r}/ask`,s),aboutMe:s=>i("GET",`${r}/about-me`,s),webSearch:s=>i("GET",`${r}/web-search`,s),fetchUrl:s=>i("GET",`${r}/fetch-url`,s),listUiTargets:s=>i("GET",`${r}/ui-targets`,s),openUi:s=>i("POST",`${r}/open-ui`,s),getCodingJobMetadata:s=>i("GET",`${r}/coding-job-metadata`,s),listProjects:s=>i("GET",`${r}/projects`,s),getProjectTasks:s=>i("GET",`${r}/project-tasks`,s),createProjectTask:s=>i("POST",`${r}/project-tasks/create`,s),updateProjectTask:s=>i("POST",`${r}/project-tasks/update`,s),deleteProjectTask:s=>i("POST",`${r}/project-tasks/delete`,s),addProjectTaskDependency:s=>i("POST",`${r}/project-tasks/add-dependency`,s),removeProjectTaskDependency:s=>i("POST",`${r}/project-tasks/remove-dependency`,s),getCallTranscript:s=>i("GET",`${r}/call-transcript`,s),renameCodingJob:s=>i("POST",`${r}/coding-job-title`,s),upsertCodingJobPlan:(s,a)=>i("POST",`${r}/coding-job-plan`,s,a),replaceCodingJobPlanSteps:s=>i("POST",`${r}/coding-job-plan/steps`,s),updateCodingJobPlanStep:s=>i("POST",`${r}/coding-job-plan/step`,s),linkCodingJobPullRequest:s=>i("POST",`${r}/coding-job-primary-pr`,s),listVaultSecrets:s=>i("GET",`${r}/vault-secrets`,s),noteProjectDirectory:s=>i("POST",`${r}/discovered-project`,s),noteAgentConversation:s=>i("POST",`${r}/discovered-conversation`,s),noteOnboardingDiscoveryStatus:s=>i("POST",`${r}/discovery-status`,s),sendChannelMessage:s=>i("POST",`${r}/channel-message`,s),editMessage:s=>i("POST",`${r}/message/edit`,s),agentReply:s=>i("POST",`${r}/agent-reply`,s),scheduleWake:s=>i("POST",`${r}/scheduled-wakes`,s),cancelWake:s=>i("POST",`${r}/scheduled-wakes/cancel`,s),declineDocumentAction:s=>i("POST",`${r}/agent/decline-document-action`,s),agentTurnProgress:s=>i("POST",`${r}/agent-turn-progress`,s),agentDocumentTool:s=>i("POST",`${r}/agent/document-tool`,s),agentTopicTool:s=>i("POST",`${r}/agent/topic-tool`,s),agentListCodingJobs:s=>i("GET",`${r}/agent/coding-jobs`,s),agentStartCodingJob:s=>i("POST",`${r}/agent/start-coding-job`,s),agentSpawnChildJob:s=>i("POST",`${r}/agent/spawn-child-job`,s),agentArchiveChildJob:s=>i("POST",`${r}/agent/archive-child-job`,s),agentUnarchiveChildJob:s=>i("POST",`${r}/agent/unarchive-child-job`,s),agentInterruptCodingJob:s=>i("POST",`${r}/agent/interrupt-coding-job`,s),agentSendCodingJobMessage:s=>i("POST",`${r}/agent/send-coding-job-message`,s),agentDiscoverCodingJobs:s=>i("GET",`${r}/agent/discover-coding-jobs`,s),agentReadCodingJobThread:s=>i("GET",`${r}/agent/coding-job-thread`,s),agentResolveJobApproval:s=>i("POST",`${r}/agent/resolve-job-approval`,s),agentArchiveCodingJob:s=>i("POST",`${r}/agent/archive-coding-job`,s),agentUnarchiveCodingJob:s=>i("POST",`${r}/agent/unarchive-coding-job`,s),agentSetThreadStatus:s=>i("POST",`${r}/agent/set-thread-status`,s),agentCreateChannel:s=>i("POST",`${r}/agent/create-channel`,s),agentRenameChannel:s=>i("POST",`${r}/agent/rename-channel`,s),agentArchiveChannel:s=>i("POST",`${r}/agent/archive-channel`,s),agentUnarchiveChannel:s=>i("POST",`${r}/agent/unarchive-channel`,s),agentAddReaction:s=>i("POST",`${r}/agent/add-reaction`,s),agentRemoveReaction:s=>i("POST",`${r}/agent/remove-reaction`,s),agentPinMessage:s=>i("POST",`${r}/agent/pin-message`,s),agentUnpinMessage:s=>i("POST",`${r}/agent/unpin-message`,s),prepareMessageUploads:s=>i("POST",`${r}/message-uploads/prepare`,s),attachMessageFiles:s=>i("POST",`${r}/message-files/attach`,s),prepareCustomEmoji:s=>i("POST",`${r}/custom-emoji/prepare`,s),renameCustomEmoji:s=>i("POST",`${r}/custom-emoji/rename`,s),sendThreadReply:s=>i("POST",`${r}/thread-reply`,s),sendDm:s=>i("POST",`${r}/dm`,s),dmOwner:s=>i("POST",`${r}/dm-owner`,s),getVaultValues:s=>i("POST",`${r}/vault-values`,s)}}import{existsSync as ga,mkdirSync as rl,readFileSync as ya,renameSync as ol,rmSync as il,writeFileSync as sl}from"node:fs";import{homedir as _a}from"node:os";import{dirname as ul,join as Sa}from"node:path";function ba(){return Sa(_a(),".linzumi","auth.json")}function Je(e,n=ba()){if(!ga(n))return;let t=va(ya(n,"utf8")),r=ln(e),o=t.local_codex_runner?.[r];if(!(o===void 0||o.access_token.trim()==="")&&!(o.expires_at!==void 0&&Date.parse(o.expires_at)<=Date.now()))return{accessToken:o.access_token,kandanBaseUrl:r,issuedAt:o.issued_at,expiresAt:o.expires_at}}function va(e){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Kandan auth cache must contain a JSON object");let t=n,r=t.local_codex_runner,o=t.personal_agent_delegation;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new Error("Kandan auth cache local_codex_runner must be an object");if(o!==void 0&&(typeof o!="object"||o===null||Array.isArray(o)))throw new Error("Kandan auth cache personal_agent_delegation must be an object");return{version:1,local_codex_runner:wa(r),personal_agent_delegation:xa(o)}}function xa(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.access_token,t=e.issued_at,r=e.expires_at;if(!(typeof n!="string"||typeof t!="string"))return{access_token:n,issued_at:t,expires_at:typeof r=="string"?r:void 0}}function wa(e){if(!(typeof e!="object"||e===null||Array.isArray(e)))return Object.fromEntries(Object.entries(e).flatMap(([n,t])=>{if(typeof t!="object"||t===null||Array.isArray(t))return[];let r=t.access_token,o=t.issued_at,i=t.expires_at;return typeof r!="string"||typeof o!="string"?[]:[[n,{access_token:r,issued_at:o,expires_at:typeof i=="string"?i:void 0}]]}))}var ka=50,Vr="runner.notice";function Ta(e){let n=new Map;return{report:r=>{let o=r.key??r.message,i=r.audience??"user",s=e.nowMs(),a=n.get(o),d=a===void 0?{key:o,severity:r.severity,message:r.message,audience:i,count:1,firstAtMs:s,lastAtMs:s}:{...a,severity:r.severity,message:r.message,audience:i,count:a.count+1,lastAtMs:s};n.delete(o),n.set(o,d);for(let u of n.keys()){if(n.size<=ka)break;n.delete(u)}return e.writeAuditEvent(Vr,{severity:d.severity,audience:d.audience,key:d.key,message:d.message,count:d.count}),e.tuiActive()?(d.audience==="user"&&e.reportConsoleEvent(Vr,{severity:d.severity,key:d.key,message:d.message,count:d.count}),d):(d.count===1&&e.writeStderr(`${Ca(d.severity)}${d.message}
13
- `),d)},notices:()=>Array.from(n.values()),reset:()=>n.clear()}}function Ca(e){switch(e){case"warning":return"WARNING: ";case"error":return"ERROR: ";case"info":return""}}var Qr={tuiActive:()=>!1,reportConsoleEvent:()=>{}};var yl=Ta({tuiActive:()=>Qr.tuiActive(),writeAuditEvent:(e,n)=>Y(e,n),reportConsoleEvent:(e,n)=>Qr.reportConsoleEvent(e,n),writeStderr:e=>{process.stderr.write(e)},nowMs:Date.now});function fn(e){return`<linzumi_context>
14
- <linzumi_thread_id>${pn(e.threadId)}</linzumi_thread_id>
15
- <linzumi_creator_user_id>${pn(e.creatorUserId)}</linzumi_creator_user_id>
16
- <linzumi_creator_username>${pn(e.creatorUsername)}</linzumi_creator_username>
17
- <linzumi_conversation_url>${pn(e.conversationUrl)}</linzumi_conversation_url>
9
+ `+n)}function jr(e,t,n,i,r,o){if(e.listenerCount("wsClientError")){let a=new Error(r);Error.captureStackTrace(a,jr),e.emit("wsClientError",a,n,t)}else Do(n,i,r,o)}});var oE={};HE(oE,{AbortError:()=>Mt,DirectConnectError:()=>sn,DirectConnectTransport:()=>Bf,EXIT_REASONS:()=>_j,HOOK_EVENTS:()=>ul,InMemorySessionStore:()=>Lp,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:()=>vj,createSdkMcpServer:()=>eV,deleteSession:()=>j8,filterEscalatingDefaultMode:()=>b8,foldSessionSummary:()=>YS,forkSession:()=>q8,getSessionInfo:()=>A8,getSessionMessages:()=>R8,getSubagentMessages:()=>U8,importSessionToStore:()=>N8,listSessions:()=>O8,listSubagents:()=>L8,parseDirectConnectUrl:()=>rV,query:()=>P8,renameSession:()=>$8,resolveSettings:()=>S8,startup:()=>E8,tagSession:()=>M8,tool:()=>XG});import{createRequire as hM}from"node:module";import{execFile as X1}from"child_process";import{randomUUID as mm}from"crypto";import{createReadStream as ej,realpathSync as tj}from"fs";import{copyFile as nj,mkdir as ep,readdir as rj,readFile as HS,rm as ij,writeFile as GS}from"fs/promises";import{createRequire as oj}from"module";import{homedir as Np,tmpdir as aj}from"os";import{dirname as $v,isAbsolute as VS,join as Gt,relative as ZS,resolve as Ma,sep as hm}from"path";import{createInterface as sj}from"readline";import{fileURLToPath as dj}from"url";import{setMaxListeners as uj}from"events";import{realpathSync as cj}from"fs";import{dirname as Mv,resolve as tp,sep as jv}from"path";import{spawn as hj}from"child_process";import{existsSync as gj}from"fs";import{createInterface as yj}from"readline";import{homedir as oN}from"os";import{join as aN}from"path";import{randomUUID as hD}from"crypto";import{join as yb}from"path";import{AsyncLocalStorage as gD}from"async_hooks";import{appendFile as yD,copyFile as _D,mkdir as vD,open as _b,readdir as vb,readFile as bb,stat as bD,unlink as wD,writeFile as fp}from"fs/promises";import{randomBytes as SD}from"crypto";import{chmod as kD,copyFile as xD,rename as CD,unlink as mp,writeFile as TD}from"fs/promises";import{realpathSync as Db}from"fs";import{cwd as Lz}from"process";import{randomUUID as of}from"crypto";import{createHash as Uz}from"crypto";import{appendFile as Wb,mkdir as f2,rename as Hb,stat as m2,symlink as h2,unlink as af}from"fs/promises";import{dirname as sf,join as Um,resolve as g2}from"path";import*as _e from"fs";import{appendFile as x2,chmod as C2,copyFile as T2,link as I2,lstat as P2,mkdir as E2,open as Gb,readdir as R2,readFile as Vb,readlink as O2,realpath as A2,rename as $2,rmdir as M2,rm as j2,stat as q2,symlink as N2,unlink as D2}from"fs/promises";import*as jt from"path";import{existsSync as S4}from"fs";import{readFile as A4}from"fs/promises";import{once as iw}from"events";import{createWriteStream as $4}from"fs";import{open as px,readdir as hf,realpath as M4,stat as j4}from"fs/promises";import{join as Ka}from"path";import{execFile as q4}from"child_process";import{promisify as N4}from"util";import{execFileSync as D4}from"child_process";import{lstatSync as L4}from"fs";import{join as U4}from"path";import{readdir as Bm,stat as CB}from"fs/promises";import{basename as TB,join as Km}from"path";import{constants as dw}from"fs";import{open as jB,readdir as wx,rm as uw,stat as qB}from"fs/promises";import{join as Di}from"path";import{randomUUID as Sd}from"crypto";import{join as yf}from"path";import{readdir as VB,readFile as lw}from"fs/promises";import{join as _f}from"path";import{createHash as eK}from"crypto";import{userInfo as tK}from"os";import{resolve as oV}from"path";import{join as Ui}from"path";import{dirname as aV}from"path";import rt from"node:path";import oP from"node:os";import Wf from"node:process";import{join as TV}from"path";import{readFile as IV}from"fs/promises";import{release as cP}from"os";import{dirname as I5,join as wr,resolve as Ia}from"path";import{join as j5}from"path";import{userInfo as G5}from"os";import{isAbsolute as oS}from"path";import{execFile as r8}from"child_process";import{existsSync as i8}from"fs";function bM(e){return this[e]}function xM(e,t){this[e]=kM.bind(null,t)}function Dp(e=lj){let t=new AbortController;return uj(e,t.signal),t}function Bi(e){return process.platform==="darwin"?e.normalize("NFC"):e}function qd(e){return/^[\\/]{2}/.test(e)}function Id(e){if(process.platform==="win32"||!e.startsWith("/"))return!1;let t=[];for(let n of e.split("/"))if(!(n===""||n===".")){if(n===".."){t.pop();continue}if(t.push(n),t.length===2&&t[0].toLowerCase()==="net")return!0}return!1}function Nd(e){return/^[\\/]{2}wsl(\$|\.localhost)[\\/]/i.test(e)}function QS(e){return e.startsWith("\\\\?\\UNC\\")?"\\\\"+e.slice(8):e.startsWith("\\\\?\\")&&e.length>=7&&e[5]===":"?e.slice(4):e}function pj(e){if(/^\\\\\?\\volume\{/i.test(e))return qv(e);let t=QS(e);return t!==e&&qv(t)?!0:qd(t)&&!Nd(t)}function qv(e){return/(^|[\\/])\.{1,2}([\\/]|$)/.test(e)||e.includes("/")}function Nv(e){try{return QS(cj.native(e))}catch{return null}}function fj(e,t){let n=tp(t).toLowerCase(),i=tp(e).toLowerCase();if(Mv(i)===n||i.startsWith(n+jv))return!0;let r=Nv(t)?.toLowerCase();if(r==null)return!1;let o=Nv(Mv(tp(e)))?.toLowerCase();return o==null?!0:o===r||o.startsWith(r+jv)}function dl(e,t,n){return new Promise((i,r)=>{if(t?.aborted){n?.throwOnAbort||n?.abortError?r(n.abortError?.()??Error("aborted")):i();return}let o=setTimeout((s,d,u)=>{s?.removeEventListener("abort",d),u()},e,t,a,i);function a(){clearTimeout(o),n?.throwOnAbort||n?.abortError?r(n.abortError?.()??Error("aborted")):i()}t?.addEventListener("abort",a,{once:!0}),n?.unref&&o.unref()})}function mj(e,t){e(Error(t))}function Jr(e,t,n){let i,r=new Promise((o,a)=>{i=setTimeout(mj,t,a,n)});return Promise.race([e,r]).finally(()=>{i!==void 0&&clearTimeout(i)})}function gm(e,t){if(e.type!=="user"||e.isMeta===!0||e.isCompactSummary===!0)return;let n=e.message;if(!n)return;let i=n.content,r=[];if(typeof i=="string")r.push(i);else if(Array.isArray(i)){for(let o of i)if(!(!o||typeof o!="object")){if(o.type==="tool_result")return;o.type==="text"&&typeof o.text=="string"&&r.push(o.text)}}for(let o of r){let a=o.replaceAll(`
10
+ `," ").trim();if(!a)continue;let s=wj.exec(a);if(s){t.commandFallback||(t.commandFallback=s[1]);continue}let d=/<bash-input>([\s\S]*?)<\/bash-input>/.exec(a);if(d)return`! ${d[1].trim()}`;if(!bj.test(a))return a.length>200&&(a=a.slice(0,200).trim()+"\u2026"),a}}function YS(e,t,n,i){let r=i?.mtime??e?.mtime??0,o=e!==void 0?{sessionId:e.sessionId,mtime:r,data:{...e.data}}:{sessionId:t.sessionId,mtime:r,data:{}},a=o.data;for(let s of n){let d=Cj(s.timestamp);if(a.isSidechain===void 0&&(a.isSidechain=s.isSidechain===!0),a.createdAt===void 0&&d!==void 0&&(a.createdAt=d),a.cwd===void 0){let u=s.cwd;typeof u=="string"&&u&&(a.cwd=u)}Tj(a,s);for(let[u,l]of Object.entries(Sj)){let p=s[u];typeof p=="string"&&(a[l]=p)}if(s.type==="tag"){let u=s.tag;typeof u=="string"&&u?a.tag=u:delete a.tag}if(s.type==="relocated"){let u=s.relocatedCwd;typeof u=="string"&&u&&(a.cwd=u)}}return o}function kj(e,t){let n=e.data;if(n.isSidechain===!0)return null;let i=dr(n.firstPromptLocked===!0?n.firstPrompt:n.commandFallback)||void 0,r=dr(n.customTitle)||dr(n.aiTitle)||void 0,o=r||dr(n.lastPrompt)||dr(n.summaryHint)||i;return o?{sessionId:e.sessionId,summary:o,lastModified:e.mtime,fileSize:void 0,customTitle:r,firstPrompt:i,gitBranch:dr(n.gitBranch)||void 0,cwd:dr(n.cwd)||t||void 0,tag:dr(n.tag)||void 0,createdAt:xj(n.createdAt)}:null}function dr(e){return typeof e=="string"?e:void 0}function xj(e){return typeof e=="number"?e:void 0}function Cj(e){if(typeof e!="string")return;let t=Date.parse(e);return Number.isNaN(t)?void 0:t}function Tj(e,t){if(e.firstPromptLocked)return;let n={commandFallback:e.commandFallback??""},i=gm(t,n);n.commandFallback&&!e.commandFallback&&(e.commandFallback=n.commandFallback),i!==void 0&&(e.firstPrompt=i,e.firstPromptLocked=!0)}function XS(){return process.versions.bun!==void 0}function kt(e){if(!e)return!1;if(typeof e=="boolean")return e;let t=String(e).toLowerCase().trim();return["1","true","yes","on"].includes(t)}function fs(){let e=new Set;return{subscribe(t){let n=Ij(t);return e.add(n),()=>{e.delete(n)}},emit(...t){let n;for(let i of e)try{i(...t)}catch(r){(n??=[]).push(r)}if(n)throw n.length===1?n[0]:AggregateError(n,"Signal listener(s) threw")},clear(){e.clear()}}}function Mj(e){var t=Aj.call(e,Zo),n=e[Zo];try{e[Zo]=void 0;var i=!0}catch{}var r=$j.call(e);return i&&(t?e[Zo]=n:delete e[Zo]),r}function Dj(e){return Nj.call(e)}function zj(e){return e==null?e===void 0?Fj:Uj:Lv&&Lv in Object(e)?jj(e):Lj(e)}function Bj(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}function Gj(e){if(!Dn(e))return!1;var t=ri(e);return t==Jj||t==Wj||t==Kj||t==Hj}function Zj(e){return!!Uv&&Uv in e}function eq(e){if(e!=null){try{return Xj.call(e)}catch{}try{return e+""}catch{}}return""}function dq(e){if(!Dn(e)||Qj(e))return!1;var t=ym(e)?sq:nq;return t.test(ii(e))}function lq(e,t){return e?.[t]}function pq(e,t){var n=cq(e,t);return uq(n)?n:void 0}function mq(){this.__data__=ja?ja(null):{},this.size=0}function gq(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}function wq(e){var t=this.__data__;if(ja){var n=t[e];return n===_q?void 0:n}return bq.call(t,e)?t[e]:void 0}function Cq(e){var t=this.__data__;return ja?t[e]!==void 0:xq.call(t,e)}function Pq(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=ja&&t===void 0?Iq:t,this}function mo(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Rq(){this.__data__=[],this.size=0}function Aq(e,t){return e===t||e!==e&&t!==t}function $q(e,t){for(var n=e.length;n--;)if(ms(e[n][0],t))return n;return-1}function qq(e){var t=this.__data__,n=ll(t,e);if(n<0)return!1;var i=t.length-1;return n==i?t.pop():jq.call(t,n,1),--this.size,!0}function Dq(e){var t=this.__data__,n=ll(t,e);return n<0?void 0:t[n][1]}function Uq(e){return ll(this.__data__,e)>-1}function zq(e,t){var n=this.__data__,i=ll(n,e);return i<0?(++this.size,n.push([e,t])):n[i][1]=t,this}function ho(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Jq(){this.size=0,this.__data__={hash:new Fv,map:new(qa||cl),string:new Fv}}function Hq(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}function Vq(e,t){var n=e.__data__;return Gq(t)?n[typeof t=="string"?"string":"hash"]:n.map}function Zq(e){var t=pl(this,e).delete(e);return this.size-=t?1:0,t}function Yq(e){return pl(this,e).get(e)}function eN(e){return pl(this,e).has(e)}function nN(e,t){var n=pl(this,e),i=n.size;return n.set(e,t),this.size+=n.size==i?0:1,this}function go(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function _m(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw TypeError(iN);var n=function(){var i=arguments,r=t?t.apply(this,i):i[0],o=n.cache;if(o.has(r))return o.get(r);var a=e.apply(this,i);return n.cache=o.set(r,a)||o,a};return n.cache=new(_m.Cache||fl),n}function ie(e,t,n,i,r){if(i==="m")throw TypeError("Private method is not writable");if(i==="a"&&!r)throw TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(e,n):r?r.value=n:t.set(e,n),n}function N(e,t,n,i){if(n==="a"&&!i)throw TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?i:n==="a"?i.call(e):i?i.value:t.get(e)}function Na(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}function zp(e){return typeof e!="object"?{}:e??{}}function Bv(e){if(!e)return!0;for(let t in e)return!1;return!0}function uN(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function fN(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function hN(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:n}of e){let i=n.exec(navigator.userAgent);if(i){let r=i[1]||0,o=i[2]||0,a=i[3]||0;return{browser:t,version:`${r}.${o}.${a}`}}}return null}function gN(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ik(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ok(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ik({start(){},async pull(n){let{done:i,value:r}=await t.next();i?n.close():n.enqueue(r)},async cancel(){await t.return?.()}})}function bm(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let n=await t.read();return n?.done&&t.releaseLock(),n}catch(n){throw t.releaseLock(),n}},async return(){let n=t.cancel();return t.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function yN(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}function vN(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new me(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function sk(e){if(!e)return;let t;try{t=new URL(e)}catch(i){throw new Fe(`Invalid token endpoint base URL "${e}": ${i}`)}if(t.protocol==="https:")return;let n=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(t.protocol==="http:"&&(n==="localhost"||n==="127.0.0.1"||n==="::1")))throw new Fe(`Refusing to send credential over non-https token endpoint "${e}"`)}async function dk(e,t){let n=await TN(e),i;try{i=JSON.parse(n)}catch{throw new Fe(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,dn(n),t)}if(!i.access_token)throw new Fe(`Token endpoint response missing access_token: ${JSON.stringify(dn(i))}`,e.status,dn(i),t);if(i.token_type&&i.token_type.toLowerCase()!=="bearer")throw new Fe(`Token endpoint response: unsupported token_type "${i.token_type}" (want Bearer)`,e.status,dn(i),t);return i}function dn(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=rp?e:e.slice(0,rp)+`... <${e.length-rp} more chars>`}return JSON.stringify(dn(t))}if(typeof e=="object"&&!Array.isArray(e)){let t={};for(let[n,i]of Object.entries(e))CN.has(n)&&(t[n]=i);return t}return null}async function uk(e,t=n=>console.warn(`anthropic-sdk: ${n}`)){if(typeof process>"u"||process.platform==="win32")return;let n=await import("node:fs"),i=e,r;try{i=await n.promises.realpath(e),r=await n.promises.stat(i)}catch{return}let o=r.mode&511;if(o&18)throw new Fe(`Credentials file at ${i} is group/world-writable (mode 0o${o.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${i}\`.`);if(o&36)throw new Fe(`Credentials file at ${i} is group/world-readable (mode 0o${o.toString(8)}); run \`chmod 600 ${i}\` before retrying.`);typeof process.getuid=="function"&&r.uid!==process.getuid()&&t(`credentials file at ${i} is owned by uid ${r.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function lk(e,t){let n=await import("node:fs"),i=(await import("node:path")).dirname(e);await n.promises.mkdir(i,{recursive:!0,mode:448});let r=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let o=await n.promises.open(r,"w",384);try{await o.writeFile(JSON.stringify(t,null,2)),await o.sync()}finally{await o.close()}await n.promises.rename(r,e)}catch(o){throw await n.promises.unlink(r).catch(()=>{}),o}try{let o=await n.promises.open(i,"r");try{await o.sync()}finally{await o.close()}}catch{}}async function TN(e){if(!e.body)return"";let t=e.body.getReader(),n=[],i=0;for(;;){let{done:o,value:a}=await t.read();if(o)break;if(i+a.length>Hv){let s=Hv-i;s>0&&n.push(a.subarray(0,s)),await t.cancel();break}n.push(a),i+=a.length}let r;if(n.length===1)r=n[0];else{r=new Uint8Array(n.reduce((a,s)=>a+s.length,0));let o=0;for(let a of n)r.set(a,o),o+=a.length}return new TextDecoder("utf-8").decode(r)}function Wr(){return Math.floor(Date.now()/1e3)}function IN(e){let t=0;for(let r of e)t+=r.length;let n=new Uint8Array(t),i=0;for(let r of e)n.set(r,i),i+=r.length;return n}function Sm(e){let t;return(Gv??(t=new globalThis.TextEncoder,Gv=t.encode.bind(t)))(e)}function Zv(e){let t;return(Vv??(t=new globalThis.TextDecoder,Vv=t.decode.bind(t)))(e)}function _a(){}function id(e,t,n){return!t||Gd[e]>Gd[n]?_a:t[e].bind(t)}function gt(e){let t=e.logger,n=e.logLevel??"off";if(!t)return PN;let i=Yv.get(t);if(i&&i[0]===n)return i[1];let r={error:id("error",t,n),warn:id("warn",t,n),info:id("info",t,n),debug:id("debug",t,n)};return Yv.set(t,[n,r]),r}function pk(e){if(!e)throw Error("profile name is empty");if(e==="."||e==="..")throw Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw Error(`profile name "${e}" must not contain path separators`);if(!EN.test(e))throw Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}function Xv(e){if(!e)throw new me("Identity token file path is empty");return async()=>{let t=await import("node:fs"),n;try{n=await t.promises.readFile(e,"utf-8")}catch(r){throw new me(`Failed to read identity token file at ${e}: ${r}`)}let i=n.trim();if(!i)throw new me(`Identity token file at ${e} is empty`);return i}}function $N(e){if(!e)throw new me("Identity token value is empty");return()=>e}function MN(e){return async()=>{sk(e.baseURL);let t=await e.identityTokenProvider();if(t.length>16384)throw new Fe(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let n={grant_type:bN,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(n.service_account_id=e.serviceAccountId),e.workspaceId&&(n.workspace_id=e.workspaceId);let i=`${e.baseURL}${ak}`,r;try{r=await e.fetch(i,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Hd},${SN}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${gr} oidcFederationProvider`},body:JSON.stringify(n)})}catch(d){throw new Fe(`Failed to reach token endpoint ${i}: ${d}`)}let o=r.headers.get("Request-Id");if(!r.ok){let d=await r.text().catch(()=>""),u=dn(d),l="";throw r.status===401&&(l=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new Fe(`Token exchange failed with status ${r.status}${o?` (request-id ${o})`:""}: ${u}${l}`,r.status,u,o)}let a=await dk(r,o),s=Number(a.expires_in);if(!Number.isFinite(s))throw new Fe(`Token endpoint response missing required fields: ${JSON.stringify(dn(a))}`,r.status,dn(a),o);return{token:a.access_token,expiresAt:Wr()+s}}}function jN(e){return async t=>{let n=await import("node:fs");await uk(e.credentialsPath,e.onSafetyWarning);let i;try{i=await n.promises.readFile(e.credentialsPath,"utf-8")}catch(w){throw new Fe(`Credentials file not found at ${e.credentialsPath}: ${w}`)}let r;try{r=JSON.parse(i)}catch(w){throw new Fe(`Credentials file at ${e.credentialsPath} is not valid JSON: ${w}`)}let o=r.access_token;if(!o)throw new Fe(`Credentials file at ${e.credentialsPath} must include 'access_token'`);let a=r.expires_at;if(!t?.forceRefresh&&(a==null||Wr()<a-wm))return{token:o,expiresAt:a??null};let s=r.refresh_token;if(!e.clientId||!s)throw new Fe(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${s?"set":"empty"})`);sk(e.baseURL);let d={grant_type:wN,refresh_token:s,client_id:e.clientId},u=`${e.baseURL}${ak}`,l;try{l=await e.fetch(u,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Hd,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${gr} userOAuthProvider`},body:JSON.stringify(d)})}catch(w){throw new Fe(`User OAuth refresh failed to reach token endpoint: ${w}`)}let p=l.headers.get("Request-Id");if(!l.ok){let w=await l.text().catch(()=>"");throw new Fe(`User OAuth refresh failed (HTTP ${l.status}): ${dn(w)}`,l.status,dn(w),p)}let m=await dk(l,p),f=Number(m.expires_in);if(!Number.isFinite(f))throw new Fe(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(dn(m))}`,l.status,dn(m),p);let h=Wr()+f,y=m.refresh_token||s;return await lk(e.credentialsPath,{...r,version:ck,type:"oauth_token",access_token:m.access_token,expires_at:h,refresh_token:y}),{token:m.access_token,expiresAt:h}}}function mk(e,t){let n=e.authentication.credentials_path??null,i=(e.base_url||t.baseURL).replace(/\/+$/,""),r=NN(e,n,i,t),o={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(o["anthropic-workspace-id"]=e.workspace_id),{provider:r,extraHeaders:o,baseURL:e.base_url||void 0}}async function qN(e,t){let n=await RN(t);if(!n)return null;let{config:i,fromFile:r}=n,o=i.authentication.credentials_path||!r?i:{...i,authentication:{...i.authentication,credentials_path:await ON(i,t)??void 0}};return mk(o,e)}function NN(e,t,n,i){switch(e.authentication.type){case"oidc_federation":{let r=e.authentication,o=DN(r);if(!o)throw new Fe("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!r.federation_rule_id)throw new Fe("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new Fe("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let a=MN({identityTokenProvider:o,federationRuleId:r.federation_rule_id,organizationId:e.organization_id,serviceAccountId:r.service_account_id,workspaceId:e.workspace_id,baseURL:n,fetch:i.fetch,userAgent:i.userAgent});return t?LN(a,t,i.onCacheWriteError,i.onSafetyWarning):a}case"user_oauth":{if(!t)throw new Fe("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return jN({credentialsPath:t,clientId:e.authentication.client_id,baseURL:n,fetch:i.fetch,userAgent:i.userAgent,onSafetyWarning:i.onSafetyWarning})}default:{let r=e.authentication.type;throw new Fe(`authentication.type "${r}" is not a known authentication type`)}}}function DN(e){if(e.identity_token){let i=e.identity_token.source;if(i!=="file")throw new Fe(`identity_token.source "${i}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Fe('identity_token.source "file" requires a non-empty path');return Xv(e.identity_token.path)}let t=Ue("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return Xv(t);let n=Ue("ANTHROPIC_IDENTITY_TOKEN");return n?$N(n):null}function LN(e,t,n,i){return async r=>{let o=await import("node:fs");await uk(t,i);let a;try{let d=await o.promises.readFile(t,"utf-8");a=JSON.parse(d);let u=a?.access_token;if(u&&!r?.forceRefresh){let l=a?.expires_at;if(l==null||Wr()<l-wm)return{token:u,expiresAt:l??null}}}catch(d){d?.code!=="ENOENT"&&!(d instanceof SyntaxError)&&n?.(d)}let s=await e(r);try{await lk(t,{...a??{},version:ck,type:"oauth_token",access_token:s.token,expires_at:s.expiresAt})}catch(d){n?.(d)}return s}}function UN(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function FN(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}async function*zN(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new me("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new me("Attempted to iterate over a response with no body");let n=new Kp,i=new Vr,r=bm(e.body);for await(let o of BN(r))for(let a of i.decode(o)){let s=n.decode(a);s&&(yield s)}for(let o of i.flush()){let a=n.decode(o);a&&(yield a)}}async function*BN(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let i=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?Sm(n):n,r=new Uint8Array(t.length+i.length);r.set(t),r.set(i,t.length),t=r;let o;for(;(o=FN(t))!==-1;)yield t.slice(0,o),t=t.slice(o)}t.length>0&&(yield t)}function KN(e,t){let n=e.indexOf(t);return n!==-1?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}async function hk(e,t){let{response:n,requestLogID:i,retryOfRequestLogID:r,startTime:o}=t,a=await(async()=>{if(t.options.stream)return gt(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):Zr.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let s=n.headers.get("content-type")?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let d=await n.json();return gk(d,n)}return await n.text()})();return gt(e).debug(`[${i}] response parsed`,zr({retryOfRequestLogID:r,url:n.url,status:n.status,body:a,durationMs:Date.now()-o})),a}function gk(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("request-id"),enumerable:!1})}function Ni(e,t,n){return yk(),new File(e,t??"unknown_file",n)}function Pd(e,t){let n=typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"";return t?n.split(/[\\/]/).pop()||void 0:n}function JN(e){let t=typeof e=="function"?e:e.fetch,n=eb.get(t);if(n)return n;let i=(async()=>{try{let r="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new r(o).text()}catch{return!0}})();return eb.set(t,i),i}async function ZN(e,t,n){if(yk(),e=await e,t||(t=Pd(e,!0)),GN(e))return e instanceof File&&t==null&&n==null?e:Ni([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(VN(e)){let r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ni(await Hp(r),t,n)}let i=await Hp(e);if(!n?.type){let r=i.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof r=="string"&&(n={...n,type:r})}return Ni(i,t,n)}async function Hp(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(vk(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(_k(e))for await(let n of e)t.push(...await Hp(n));else{let n=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${n?`; constructor: ${n}`:""}${QN(e)}`)}return t}function QN(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(t=>`"${t}"`).join(", ")}]`}function*YN(e){if(!e)return;if(bk in e){let{values:i,nulls:r}=e;yield*i.entries();for(let o of r)yield[o,null];return}let t=!1,n;e instanceof Headers?n=e.entries():zv(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let i of n){let r=i[0];if(typeof r!="string")throw TypeError("expected header name to be a string");let o=zv(i[1])?i[1]:[i[1]],a=!1;for(let s of o)s!==void 0&&(t&&!a&&(a=!0,yield[r,null]),yield[r,s])}}function wk(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}function Rd(e){return typeof e=="object"&&e!==null&&Pa in e}function Sk(e,t){let n=new Set;if(e)for(let i of e)Rd(i)&&n.add(i[Pa]);if(t){for(let i of t)if(Rd(i)&&n.add(i[Pa]),Array.isArray(i.content))for(let r of i.content)Rd(r)&&n.add(r[Pa])}return Array.from(n)}function kk(e,t){let n=Sk(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(", ")}}function eD(e){return Rd(e)?{"x-stainless-helper":e[Pa]}:{}}function Ck(e){return e?.output_format??e?.output_config?.format}function nb(e,t,n){let i=Ck(t);return!t||!("parse"in(i??{}))?{...e,content:e.content.map(r=>{if(r.type==="text"){let o=Object.defineProperty({...r},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return r}),parsed_output:null}:Tk(e,t,n)}function Tk(e,t,n){let i=null,r=e.content.map(o=>{if(o.type==="text"){let a=tD(t,o.text);i===null&&(i=a);let s=Object.defineProperty({...o},"parsed_output",{value:a,enumerable:!1});return Object.defineProperty(s,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),a},enumerable:!1})}return o});return{...e,content:r,parsed_output:i}}function tD(e,t){let n=Ck(e);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(t):JSON.parse(t)}catch(i){throw new me(`Failed to parse structured output: ${i}`)}}function ab(e){return e.type==="tool_use"||e.type==="server_tool_use"||e.type==="mcp_tool_use"}function db(){let e,t;return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}}async function sD(e,t=e.messages.at(-1),n){if(!t||t.role!=="assistant"||!t.content||typeof t.content=="string")return null;let i=t.content.filter(r=>r.type==="tool_use");return i.length===0?null:{role:"user",content:await Promise.all(i.map(async r=>{let o=e.tools.find(a=>("name"in a?a.name:a.mcp_server_name)===r.name);if(!o||!("run"in o))return{type:"tool_result",tool_use_id:r.id,content:`Error: Tool '${r.name}' not found`,is_error:!0};try{let a=r.input;"parse"in o&&o.parse&&(a=o.parse(a));let s=await o.run(a,{toolUseBlock:r,signal:n?.signal});return{type:"tool_result",tool_use_id:r.id,content:s}}catch(a){return{type:"tool_result",tool_use_id:r.id,content:a instanceof au?a.content:`Error: ${a instanceof Error?a.message:String(a)}`,is_error:!0}}}))}}function lb(e){if(!e.output_format)return e;if(e.output_config?.format)throw new me("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:t,...n}=e;return{...n,output_config:{...e.output_config,format:t}}}function Pk(e){return e?.output_config?.format}function cb(e,t,n){let i=Pk(t);return!t||!("parse"in(i??{}))?{...e,content:e.content.map(r=>r.type==="text"?Object.defineProperty({...r},"parsed_output",{value:null,enumerable:!1}):r),parsed_output:null}:Ek(e,t,n)}function Ek(e,t,n){let i=null,r=e.content.map(o=>{if(o.type==="text"){let a=uD(t,o.text);return i===null&&(i=a),Object.defineProperty({...o},"parsed_output",{value:a,enumerable:!1})}return o});return{...e,content:r,parsed_output:i}}function uD(e,t){let n=Pk(e);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(t):JSON.parse(t)}catch(i){throw new me(`Failed to parse structured output: ${i}`)}}function hb(e){return e.type==="tool_use"||e.type==="server_tool_use"}function ml(e){return e}function hs(e){return e instanceof Error?e:Error(String(e))}function $d(e){return e instanceof Error?e.message:String(e)}function Pt(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}function _o(e){return Pt(e)==="ENOENT"}function Ok(e){return Pt(e)==="EISDIR"}function mD(e){let t=Pt(e);return t==="ENOENT"||t==="EACCES"||t==="EPERM"||t==="ENOTDIR"||t==="ELOOP"||t==="ENAMETOOLONG"||t==="EROFS"}function OD(e,t){if(process.platform!=="win32")return!1;let n=Pt(e);return n!==void 0&&PD.has(n)&&t<ED-1}async function AD(e,t,n=CD){let i=!1;for(let r=0;;r++)try{return await n(e,t),i}catch(o){if(OD(o,r)){i=!0,await dl(RD);continue}throw o}}async function MD(e,t,n){let i=`${e}.tmp.${SD(4).toString("hex")}`;try{await TD(i,t,{encoding:"utf8",mode:n});try{await AD(i,e)}catch(r){let o=Pt(r);if(o!==void 0&&ID.has(o)){try{await xD(i,e),n!==void 0&&await kD(e,n).catch(()=>{})}catch(a){throw $D.has(Pt(a)??"")&&await mp(e).catch(()=>{}),a}await mp(i).catch(()=>{})}else throw r}}catch(r){throw await mp(i).catch(()=>{}),r}}function hp(e,t,n){if(!Number.isInteger(n)||n<0)throw RangeError(`${e}: ${t} must be a non-negative integer, got ${n}`)}async function wb(e,t,n){if(n===0)return Buffer.alloc(0);let i=Buffer.alloc(n),r=0;for(;r<n;){let{bytesRead:o}=await e.read(i,r,n-r,t+r);if(o===0)break;r+=o}return r===n?i:Buffer.from(i.subarray(0,r))}function hu(){return jD.getStore()??new Yp}function Ak(){if(Ci)return Ci;if(!kt(process.env.DEBUG_CLAUDE_AGENT_SDK))return Hr=null,Ci=Promise.resolve(),Ci;let e=yb(yo(),"debug");return Hr=yb(e,`sdk-${hD()}.txt`),process.stderr.write(`SDK debug logs: ${Hr}
11
+ `),Ci=hu().mkdir(e).catch(()=>{}),Ci}function qD(){return Ak(),Hr??null}function an(e){if(Hr===null)return;let t=`${new Date().toISOString()} ${e}
12
+ `;Ak().then(()=>{Hr&&hu().append(Hr,t).catch(()=>{})})}function ND(){this.__data__=new cl,this.size=0}function LD(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}function FD(e){return this.__data__.get(e)}function BD(e){return this.__data__.has(e)}function WD(e,t){var n=this.__data__;if(n instanceof cl){var i=n.__data__;if(!qa||i.length<JD-1)return i.push([e,t]),this.size=++n.size,this;n=this.__data__=new fl(i)}return n.set(e,t),this.size=n.size,this}function vo(e){var t=this.__data__=new cl(e);this.size=t.size}function VD(e,t,n){t=="__proto__"&&gu?gu(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}function YD(e,t,n){var i=e[t];(!(QD.call(e,t)&&ms(i,n))||n===void 0&&!(t in e))&&Tm(e,t,n)}function XD(e,t,n,i){var r=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var s=t[o],d=i?i(n[s],e[s],s,n,e):void 0;d===void 0&&(d=e[s]),r?Tm(n,s,d):$k(n,s,d)}return n}function tL(e,t){for(var n=-1,i=Array(e);++n<e;)i[n]=t(n);return i}function rL(e){return e!=null&&typeof e=="object"}function oL(e){return Sr(e)&&ri(e)==iL}function lL(){return!1}function yL(e,t){var n=typeof e;return t=t??hL,!!t&&(n=="number"||n!="symbol"&&gL.test(e))&&e>-1&&e%1==0&&e<t}function vL(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=_L}function KL(e){return Sr(e)&&Im(e.length)&&!!We[ri(e)]}function WL(e){return function(t){return e(t)}}function XL(e,t){var n=pn(e),i=!n&&za(e),r=!n&&!i&&Ba(e),o=!n&&!i&&!r&&Pm(e),a=n||i||r||o,s=a?nL(e.length,String):[],d=s.length;for(var u in e)(t||YL.call(e,u))&&!(a&&(u=="length"||r&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||hl(u,d)))&&s.push(u);return s}function tU(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||eU;return e===n}function nU(e,t){return function(n){return e(t(n))}}function sU(e){if(!Em(e))return iU(e);var t=[];for(var n in Object(e))aU.call(e,n)&&n!="constructor"&&t.push(n);return t}function uU(e){return e!=null&&Im(e.length)&&!ym(e)}function lU(e){return gl(e)?Nk(e):dU(e)}function cU(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}function hU(e){if(!Dn(e))return pU(e);var t=Em(e),n=[];for(var i in e)i=="constructor"&&(t||!mU.call(e,i))||n.push(i);return n}function yU(e){return gl(e)?Nk(e,!0):gU(e)}function vU(e,t){if(t)return e.slice();var n=e.length,i=Pb?Pb(n):new e.constructor(n);return e.copy(i),i}function bU(e,t){var n=-1,i=e.length;for(t||(t=Array(i));++n<i;)t[n]=e[n];return t}function SU(e,t){for(var n=-1,i=e==null?0:e.length,r=0,o=[];++n<i;){var a=e[n];t(a,n,e)&&(o[r++]=a)}return o}function xU(){return[]}function PU(e,t){for(var n=-1,i=t.length,r=e.length;++n<i;)e[r+n]=t[n];return e}function $U(e,t,n){var i=t(e);return pn(e)?i:Om(i,n(e))}function MU(e){return Kk(e,Lk,Bk)}function jU(e){return Kk(e,Rm,AU)}function GU(e){var t=new e.constructor(e.byteLength);return new yu(t).set(new yu(e)),t}function ZU(e,t){var n=t?VU(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function eF(e){return typeof e.constructor=="function"&&!Em(e)?XU(Am(e)):{}}function rF(e){return this.__data__.set(e,nF),this}function oF(e){return this.__data__.has(e)}function _u(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new fl;++t<n;)this.add(e[t])}function dF(e,t){for(var n=-1,i=e==null?0:e.length;++n<i;)if(t(e[n],n,e))return!0;return!1}function lF(e,t){return e.has(t)}function mF(e,t,n,i,r,o){var a=n&pF,s=e.length,d=t.length;if(s!=d&&!(a&&d>s))return!1;var u=o.get(e),l=o.get(t);if(u&&l)return u==t&&l==e;var p=-1,m=!0,f=n&fF?new sF:void 0;for(o.set(e,t),o.set(t,e);++p<s;){var h=e[p],y=t[p];if(i)var w=a?i(y,h,p,t,e,o):i(h,y,p,e,t,o);if(w!==void 0){if(w)continue;m=!1;break}if(f){if(!uF(t,function(g,v){if(!cF(f,v)&&(h===g||r(h,g,n,i,o)))return f.push(v)})){m=!1;break}}else if(!(h===y||r(h,y,n,i,o))){m=!1;break}}return o.delete(e),o.delete(t),m}function hF(e){var t=-1,n=Array(e.size);return e.forEach(function(i,r){n[++t]=[r,i]}),n}function yF(e){var t=-1,n=Array(e.size);return e.forEach(function(i){n[++t]=i}),n}function AF(e,t,n,i,r,o,a){switch(n){case OF:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case RF:return!(e.byteLength!=t.byteLength||!o(new yu(e),new yu(t)));case wF:case SF:case CF:return ms(+e,+t);case kF:return e.name==t.name&&e.message==t.message;case TF:case PF:return e==t+"";case xF:var s=gF;case IF:var d=i&vF;if(s||(s=_F),e.size!=t.size&&!d)return!1;var u=a.get(e);if(u)return u==t;i|=bF,a.set(e,t);var l=Jk(s(e),s(t),i,r,o,a);return a.delete(e),l;case EF:if(yp)return yp.call(e)==yp.call(t)}return!1}function NF(e,t,n,i,r,o){var a=n&MF,s=Rb(e),d=s.length,u=Rb(t),l=u.length;if(d!=l&&!a)return!1;for(var p=d;p--;){var m=s[p];if(!(a?m in t:qF.call(t,m)))return!1}var f=o.get(e),h=o.get(t);if(f&&h)return f==t&&h==e;var y=!0;o.set(e,t),o.set(t,e);for(var w=a;++p<d;){m=s[p];var g=e[m],v=t[m];if(i)var b=a?i(v,g,m,t,e,o):i(g,v,m,e,t,o);if(!(b===void 0?g===v||r(g,v,n,i,o):b)){y=!1;break}w||(w=m=="constructor")}if(y&&!w){var S=e.constructor,T=t.constructor;S!=T&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof T=="function"&&T instanceof T)&&(y=!1)}return o.delete(e),o.delete(t),y}function FF(e,t,n,i,r,o){var a=pn(e),s=pn(t),d=a?Fb:qb(e),u=s?Fb:qb(t);d=d==Ub?vd:d,u=u==Ub?vd:u;var l=d==vd,p=u==vd,m=d==u;if(m&&Ba(e)){if(!Ba(t))return!1;a=!0,l=!1}if(m&&!l)return o||(o=new Ea),a||Pm(e)?Jk(e,t,n,i,r,o):$F(e,t,d,n,i,r,o);if(!(n&LF)){var f=l&&zb.call(e,"__wrapped__"),h=p&&zb.call(t,"__wrapped__");if(f||h){var y=f?e.value():e,w=h?t.value():t;return o||(o=new Ea),r(y,w,n,i,o)}}return m?(o||(o=new Ea),DF(e,t,n,i,r,o)):!1}function Wk(e,t,n,i,r){return e===t?!0:e==null||t==null||!Sr(e)&&!Sr(t)?e!==e&&t!==t:zF(e,t,n,i,Wk,r)}function JF(e,t,n,i){var r=n.length,o=r,a=!i;if(e==null)return!o;for(e=Object(e);r--;){var s=n[r];if(a&&s[2]?s[1]!==e[s[0]]:!(s[0]in e))return!1}for(;++r<o;){s=n[r];var d=s[0],u=e[d],l=s[1];if(a&&s[2]){if(u===void 0&&!(d in e))return!1}else{var p=new Ea;if(i)var m=i(u,l,d,e,t,p);if(!(m===void 0?Hk(l,u,BF|KF,i,p):m))return!1}}return!0}function HF(e){return e===e&&!Dn(e)}function GF(e){for(var t=Lk(e),n=t.length;n--;){var i=t[n],r=e[i];t[n]=[i,r,Gk(r)]}return t}function ZF(e,t){return function(n){return n==null?!1:n[e]===t&&(t!==void 0||e in Object(n))}}function QF(e){var t=VF(e);return t.length==1&&t[0][2]?Vk(t[0][0],t[0][1]):function(n){return n===e||WF(n,e,t)}}function ez(e){return typeof e=="symbol"||Sr(e)&&ri(e)==XF}function rz(e,t){if(pn(e))return!1;var n=typeof e;return n=="number"||n=="symbol"||n=="boolean"||e==null||$m(e)?!0:nz.test(e)||!tz.test(e)||t!=null&&e in Object(t)}function oz(e){var t=vt(e,function(i){return n.size===iz&&n.clear(),i}),n=t.cache;return t}function cz(e,t){for(var n=-1,i=e==null?0:e.length,r=Array(i);++n<i;)r[n]=t(e[n],n,e);return r}function Qk(e){if(typeof e=="string")return e;if(pn(e))return Zk(e,Qk)+"";if($m(e))return Kb?Kb.call(e):"";var t=e+"";return t=="0"&&1/e==-pz?"-0":t}function mz(e){return e==null?"":fz(e)}function gz(e,t){return pn(e)?e:Mm(e,t)?[e]:lz(hz(e))}function _z(e){if(typeof e=="string"||$m(e))return e;var t=e+"";return t=="0"&&1/e==-yz?"-0":t}function vz(e,t){t=yl(t,e);for(var n=0,i=t.length;e!=null&&n<i;)e=e[gs(t[n++])];return n&&n==i?e:void 0}function bz(e,t,n){var i=e==null?void 0:jm(e,t);return i===void 0?n:i}function Sz(e,t){return e!=null&&t in Object(e)}function xz(e,t,n){t=yl(t,e);for(var i=-1,r=t.length,o=!1;++i<r;){var a=gs(t[i]);if(!(o=e!=null&&n(e,a)))break;e=e[a]}return o||++i!=r?o:(r=e==null?0:e.length,!!r&&Im(r)&&hl(a,r)&&(pn(e)||za(e)))}function Tz(e,t){return e!=null&&Cz(e,t,kz)}function Ez(e,t){return Mm(e)&&Gk(t)?Vk(gs(e),t):function(n){var i=wz(n,e);return i===void 0&&i===t?Yk(n,e):Hk(t,i,Iz|Pz)}}function Oz(e){return e}function Az(e){return function(t){return t?.[e]}}function Mz(e){return function(t){return jm(t,e)}}function qz(e){return Mm(e)?$z(gs(e)):jz(e)}function Dz(e){return typeof e=="function"?e:e==null?qm:typeof e=="object"?pn(e)?Rz(e[0],e[1]):YF(e):Nz(e)}function Fz(e,t){let n=Buffer.from(t.replace(/-/g,""),"hex"),i=Uz("sha1").update(n).update(Buffer.from(e,"utf8")).digest();i[6]=i[6]&15|80,i[8]=i[8]&63|128;let r=i.subarray(0,16).toString("hex");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function Bz(){let e=process.env.CLAUDE_CODE_REMOTE_SESSION_ID?.trim();return e?Fz(e,zz):null}function Kz(){return Nm}function Jz(e){Nm=e}function Wz(e){return vu.has(e)?vu.get(e):void 0}function Hz(e,t){vu.set(e,t)}function Xz(e){return Dm.get(e)}function e2(e,t){Dm.set(e,t)}function Lm(){Nm=null,vu.clear(),Dm.clear(),Yz=void 0,Gz=void 0,Vz=void 0,Zz=void 0,Qz=void 0}function n2(){return t2}function r2(){return{sent:new Set,rejected:new Set}}function o2(){let e="";if(typeof process<"u"&&typeof process.cwd=="function"&&typeof Db=="function"){let t=Lz();try{e=Jb(Db(t))}catch{e=Jb(t)}}return{originalCwd:e,projectRoot:e,totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),sessionLogicalStartTime:void 0,lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:e,modelUsage:{},mainLoopModelOverride:void 0,refusalFallbackModelLatch:void 0,sdkDialogHostActive:!1,sdkSupportedDialogKinds:void 0,sdkSupportedDialogKindsSource:void 0,replConfigArgv:[],initialMainLoopModel:void 0,resolvedOrgDefault:void 0,modelStrings:null,isInteractive:!1,thinkingDisplayExplicit:!1,permissionPromptToolName:void 0,attacherCaps:null,hasStreamingInput:!1,modelOverrideOptOutForSession:!1,rendererMode:void 0,strictToolResultPairing:!1,memoryToggledOff:!1,teamMemoryServerStatus:void 0,sdkAgentProgressSummariesEnabled:!1,userMsgOptIn:!1,searchToolsOptIn:!1,clientType:"cli",sessionSource:void 0,sessionStartType:"fresh",questionPreviewFormat:void 0,sessionIngressToken:void 0,oauthTokenFromFd:void 0,oauthScopesFromFd:void 0,apiKeyFromFd:void 0,gatewayAuth:null,gatewayRefreshInFlight:null,startupPolicySnapshot:void 0,flagSettingsPath:void 0,flagSettingsExpectedContent:void 0,flagSettingsInline:null,parentManagedSettings:null,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,statsStore:null,sessionId:Bz()??of(),mainAgentId:null,parentSessionId:void 0,loggerProvider:null,eventLogger:null,pendingOTelEvents:[],meterProvider:null,tracerProvider:null,cachedTelemetryResource:null,cachedOtlpHttpAgentFactory:{direct:null,proxied:null},foundryDeploymentCapabilities:new Map,agentColorMap:new Map,agentColorIndex:0,lastAPIRequest:null,lastCancelledAPIMessageId:null,lastAPIRequestMessages:null,lastClassifierRequests:null,cachedClaudeMdContent:null,inMemoryErrorLog:[],inlinePlugins:[],inlinePluginsNoMcp:[],inlinePluginUrls:[],syncedPluginDirs:[],chromeFlagOverride:void 0,onboardingShownThisSession:!1,useCoworkPlugins:!1,disableSlashCommands:!1,sessionBypassPermissionsMode:!1,scheduledTasksEnabled:!1,sessionPrResolved:!1,sessionCronTasks:[],loopChainStartedAt:Object.create(null),loopTickInFlightPrompt:null,loopConsecutiveKeepalives:0,sessionCreatedTeams:new Set,surfacedHookSpawnFailures:new Set,bareMcpServerMatchersWarned:new Set,inheritedTeamName:void 0,sessionTrustAccepted:!1,sessionPersistenceDisabled:!1,hasExitedPlanMode:!1,needsPlanModeExitAttachment:!1,needsAutoModeExitAttachment:!1,lspRecommendationShownThisSession:!1,initJsonSchema:null,registeredHooks:null,planSlugCache:new Map,teleportedSessionInfo:null,invokedSkills:new Map,slowOperations:[],sdkBetas:void 0,longContext1mCreditsBlocked:!1,fableCreditsRequired:!1,fableConsentSessionFallback:!1,fableBridgeDialogTimedOut:!1,fableConsentDialogInteracted:!1,sdkOAuthTokenRefreshCallback:null,hostAuthTokenRefreshCallback:null,mainThreadAgentType:void 0,mainThreadAgentHooks:void 0,sessionSkillAllowlist:void 0,caps:i2,replBridgeActive:!1,mainLoopBusy:!1,directConnectServerUrl:void 0,mcpConnectNonBlocking:!1,strictMcpConfig:!1,sessionApprovedMcpServers:[],activeRoutine:void 0,systemPromptSectionCache:new Map,lastEmittedDate:null,additionalDirectoriesForClaudeMd:[],allowedChannels:[],hasDevChannels:!1,sessionProjectDir:null,promptCache1hAllowlist:null,stickyBetas:r2(),thinkingTypeOverrides:new Map,inferenceProfileBackingModels:new Map,promptId:null,promptIndex:0,lastMainRequestId:void 0,lastMainThreadCacheTtlMs:null,lastApiCompletionTimestamp:null,pendingPostCompaction:!1}}function tx(){return s2()?.sessionId??a2.sessionId}function Jb(e){return process.platform==="darwin"?e.normalize("NFC"):e}function y2({writeFn:e,flushIntervalMs:t=1e3,maxBufferSize:n=100,maxBufferBytes:i=1/0,immediateMode:r=!1}){let o=[],a=0,s=null,d=null;function u(){s&&(clearTimeout(s),s=null)}function l(h){try{e(h)}catch{}}function p(){d&&(l(d.join("")),d=null),o.length!==0&&(l(o.join("")),o=[],a=0,u())}function m(){s||(s=setTimeout(p,t))}function f(){if(d){d.push(...o),o=[],a=0,u();return}let h=o;o=[],a=0,u(),d=h,setImmediate(()=>{let y=d;d=null,y&&l(y.join(""))})}return{write(h){if(r){l(h);return}o.push(h),a+=h.length,m(),(o.length>=n||a>=i)&&f()},flush:p,dispose(){p()}}}function _2(e){return typeof e=="function"?e:Symbol.asyncDispose in e?()=>e[Symbol.asyncDispose]():()=>e[Symbol.dispose]()}function nx(e){return v2.register(e)}function w2(e){let t=[],n=e.match(/^MCP server ["']([^"']+)["']/);if(n&&n[1])t.push("mcp"),t.push(n[1].toLowerCase());else{let o=e.match(/^([^:[]+):/);o&&o[1]&&t.push(o[1].trim().toLowerCase())}let i=e.match(/^\[([^\]]+)]/);i&&i[1]&&t.push(i[1].trim().toLowerCase()),e.toLowerCase().includes("1p event:")&&t.push("1p");let r=e.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(r&&r[1]){let o=r[1].trim().toLowerCase();o.length<30&&!o.includes(" ")&&t.push(o)}return Array.from(new Set(t))}function S2(e,t){return t?e.length===0?!1:t.isExclusive?!e.some(n=>t.exclude.includes(n)):e.some(n=>t.include.includes(n)):!0}function k2(e,t){if(!t)return!0;let n=w2(e);return S2(n,t)}function L2(e,t){if(qd(t)&&!Nd(t)||Id(t))return;let n=jt.resolve(t),i=jt.parse(n).root,r=i,o=n.slice(i.length).split(/[\\/]+/).filter(Boolean),a=0,s=64;for(;o.length>0&&a<s;){let d=jt.join(r,o[0]);if(Id(d))return o.length===1?d:jt.join(d,...o.slice(1));let u;try{u=e.lstatSync(d)}catch{return}if(!u.isSymbolicLink()){o.shift(),r=d;continue}a++;let l;try{l=e.readlinkSync(d)}catch{return}let p=jt.isAbsolute(l)?l:jt.resolve(r,l);if(qd(p)&&!Nd(p)||Id(p))return o.shift(),o.length===0?p:jt.join(p,...o);o.shift();let m=jt.parse(p).root||jt.sep;r=m,o=[...p.slice(m.length).split(/[\\/]+/).filter(Boolean),...o]}}function rx(e,t){if(qd(t)&&!Nd(t)||Id(t))return{resolvedPath:t,isSymlink:!1,isCanonical:!1};let n=L2(e,t);if(n!==void 0)return{resolvedPath:n,isSymlink:!0,isCanonical:!1};try{let i=e.realpathSync(t);return{resolvedPath:i,isSymlink:i!==t,isCanonical:!0}}catch{return{resolvedPath:t,isSymlink:!1,isCanonical:!1}}}function Yt(){return F2}function z2(e,t){e.destroyed||e.write(t)}function B2(e){z2(process.stderr,e)}function K2(e){return e.charAt(0).toUpperCase()+e.slice(1)}function J2(e,t,n=t+"s"){return e===1?t:n}function H2(e){return Zb&&Zb(e)?e:e.replace(W2,"")}function G2(e,t){let n=e.indexOf(t);return n===-1?e:e.slice(0,n)}function X2(e){return Y2.map(t=>({id:t.id,confidence:t.confidence,re:new RegExp(t.source,e?(t.flags??"").replace("g","")+"g":t.flags??"")}))}function e4(e){Xb??=X2(!0);for(let t of Xb)e=e.replace(t.re,(n,i)=>{if(typeof i!="string")return"[REDACTED]";let r=i.length>=2&&(i[0]==='"'||i[0]==="'")&&i.at(-1)===i[0]?i[0]:"",o=n.lastIndexOf(i);return`${n.slice(0,o)}${r}[REDACTED]${r}${n.slice(o+i.length)}`});return e}function _l(){if(typeof process>"u"||!Array.isArray(process.argv))return[];let e=process.argv.indexOf("--");return e===-1?process.argv:process.argv.slice(0,e)}function ew(e){return pj(e)?null:g2(e)}function i4(e){if(!ox()||typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;let t=r4();return k2(e,t)}async function s4(e,t,n=a4){if(fa<0?fa=await m2(e).then(i=>i.size).catch(()=>0):fa+=t,!(fa<=n||vp)){vp=!0;try{let i=e.endsWith(".txt")?`${e.slice(0,-4)}.1.txt`:`${e}.1`;try{await Hb(e,i)}catch(r){_o(r)||(await af(i).catch(()=>{}),await Hb(e,i).catch(()=>af(e).catch(()=>{})))}fa=0}finally{vp=!1}}}function dx(e){return uf=Um(e,`${tx()}.txt`),uf}async function d4(e,t,n,i){e&&await f2(t,{recursive:!0}).catch(()=>{});let r=n;try{await Wb(n,i)}catch(o){if(!Ok(o))throw o;r=dx(n),await Wb(r,i)}await s4(r,Buffer.byteLength(i)).catch(ux),c4()}function ux(){}function u4(){Oi.shift()}function l4(){if(!pa){let e=null;pa=y2({writeFn:t=>{if(ka){Oi.push(t),ka();return}let n=lf(),i=sf(n),r=e!==i;e=i,Oi.push(t),_p=_p.then(d4.bind(null,r,i,n,t)).catch(ux).then(u4)},flushIntervalMs:1e3,maxBufferSize:100,immediateMode:ox()}),nx(async()=>{pa?.dispose(),await _p}),!tw&&process.on("exit",tw=()=>{ka=()=>{if(Oi.length===0)return;let t=Oi.join("");Oi.length=0;let n=lf();try{Yt().mkdirSync(sf(n))}catch{}try{Yt().appendFileSync(n,t)}catch(i){if(Ok(i))try{Yt().appendFileSync(dx(n),t)}catch{}}},pa?.flush(),ka()})}return pa}function qe(e,{level:t}={level:"debug"}){if(df[t]<df[t4()]||!i4(e))return;o4&&e.includes(`
13
+ `)&&(e=ut(e));let n=`${new Date().toISOString()} [${t.toUpperCase()}] ${e4(e.trim())}
14
+ `;if(ax()){B2(n);return}let i=l4();i.write(n),ka&&i.flush()}function lf(){return sx()??uf??process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??Um(yo(),"debug",`${tx()}.txt`)}function f4(){return p4}function ut(e,t,n){let i=[];try{let a=Xe(i,tt`JSON.stringify(${e})`,0);return JSON.stringify(e,t,n)}catch(a){var r=a,o=1}finally{et(i,r,o)}}function m4(e){return JSON.parse(e)}function Gi(e,t){let n=[];try{let o=Xe(n,tt`structuredClone(${e})`,0);return structuredClone(e,t)}catch(o){var i=o,r=1}finally{et(n,i,r)}}function h4(e){let t=e.trim();return t.startsWith("{")&&t.endsWith("}")}function g4(e,t){let n={...e};if(t){let i=t.enabled===!0&&t.failIfUnavailable===void 0?{...t,failIfUnavailable:!0}:t,r=n.settings;if(r&&!h4(r))throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");let o={sandbox:i};if(r)try{o={...Rn(r),sandbox:i}}catch{}n.settings=ut(o)}return n}function _4(){for(let e of wu)if(!e.killed)if(process.platform==="win32")try{e.stdin.end()}catch{}else e.kill("SIGTERM")}function v4(e){wu.add(e),!nw&&(nw=!0,process.on("exit",_4))}function b4(e){return![".js",".mjs",".tsx",".ts",".jsx"].some(t=>e.endsWith(t))}function w4(e,t){return gj(e)?t?`Claude Code native binary at ${e} exists but failed to launch. This usually means the binary does not match this system's libc \u2014 e.g. spawning a musl-linked binary on a glibc Linux host fails because the musl dynamic loader (/lib/ld-musl-*) is missing. Specify a matching binary with options.pathToClaudeCodeExecutable.`:`Claude Code executable at ${e} exists but failed to launch.`:t?`Claude Code native binary not found at ${e}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${e}. Is options.pathToClaudeCodeExecutable set?`}function k4(){if(process.platform!=="linux")return!1;let e=typeof process.report?.getReport=="function"?process.report.getReport():null;return e!=null&&e.header?.glibcVersionRuntime===void 0}function x4(e,t=process.platform,n=process.arch,i=S4,r=k4()){let o=t==="win32"?".exe":"",a=(t==="android"?[`${Ti}-linux-${n}-android`]:t==="linux"?r?[`${Ti}-linux-${n}-musl`,`${Ti}-linux-${n}`]:[`${Ti}-linux-${n}`,`${Ti}-linux-${n}-musl`]:[`${Ti}-${t}-${n}`]).map(s=>`${s}/claude${o}`);for(let s of a)try{let d=e(s);if(i(d))return d}catch{}return null}function C4(){return{eventQueue:[],sink:null}}function vl(e,t){let n=T4;if(n.sink===null){n.eventQueue.push({eventName:e,metadata:t,async:!1});return}n.sink.logEvent(e,t)}function lx(e,t){vl("tengu_feature_ok",{feature_name:ml(e),...t})}function cx(e,t,n){vl("tengu_feature_bad",{...n,feature_name:ml(e),error_code:t})}function I4(e,t,n){vl("tengu_feature_sad",{...n,feature_name:ml(e),error_code:t})}async function bn(e,t,n){try{let i=await t();return lx(e),i}catch(i){throw cx(e,n?.(i)??"error"),i}}function E4(e){let t=e.replace(/[\p{Cf}\p{Co}\p{Cn}]/gu,"");return t=t.replace(/[\u200B-\u200F]/g,"").replace(/[\u202A-\u202E]/g,"").replace(/[\u2066-\u2069]/g,"").replace(/[\uFEFF]/g,"").replace(/[\uE000-\uF8FF]/g,""),t}function R4(e){let t=H2(e);for(let n=0;n<10;n++){let i=E4(t);if(i===t)return t;t=i}return t}function O4(e){let t=e,n="",i=0,r=10;for(;t!==n&&i<r;)n=t,t=t.normalize("NFKC"),t=R4(t),i++;if(i>=r)throw Error(`Unicode sanitization reached maximum iterations (${r}) for input: ${e.slice(0,100)}`);return t}function Oa(e){if(typeof e=="string")return O4(e);if(Array.isArray(e))return e.map(Oa);if(e!==null&&typeof e=="object"){let t={};for(let[n,i]of Object.entries(e))t[Oa(n)]=Oa(i);return t}return e}function F4(){return process.platform==="win32"}function ow(e){try{return L4(e,{throwIfNoEntry:!1})===void 0}catch{return!1}}function K4(e){let t=e.toLowerCase().replace(/.*[\\/]/,"").replace(/[. ]+$/,""),n=t.lastIndexOf(".");return n>0&&B4.has(t.slice(n))}function J4(e,t=!1){let n=Ii.get(e);if(n!==void 0)if(n!==null){if(!ow(n))return n;Ii.delete(e)}else{if(!t)return n;Ii.delete(e)}let i=process.env.SYSTEMROOT||"C:\\Windows",r=U4(i,"System32","where.exe");try{let o=D4(r,[e],{stdio:"pipe",encoding:"utf8",timeout:z4,windowsHide:!0,env:process.env}).trim().split(/\r?\n/).filter(Boolean),a=process.cwd(),s=!1;for(let d of o)if(!ow(d)){if(fj(d,a)){s=!0;continue}if(K4(d))return Ii.set(e,d),d}return o.length>0&&!s&&Ii.set(e,null),null}catch(o){return W4(o)&&Ii.set(e,null),null}}function W4(e){if(e===null||typeof e!="object")return!1;let t="status"in e?e.status:void 0,n="signal"in e?e.signal:void 0,i="code"in e?e.code:void 0;return t===1&&!n&&!i}function H4(e,t=!1){return!F4()||e.includes("/")||e.includes("\\")?e:J4(e,t)}async function ys(e){let t=H4("git");if(t===null)return[];try{let{stdout:n}=await G4(t,["worktree","list","--porcelain"],{cwd:e,timeout:5e3,windowsHide:!0});return n?n.split(`
15
+ `).filter(i=>i.startsWith("worktree ")).map(i=>Bi(i.slice(9))):[]}catch{return[]}}function V4(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return t}function Q4(e,t){let n=Aa(e,"entrypoint")??Vt(t,"entrypoint");if(n&&Z4.has(n))return!0;let i=e.split(`
16
+ `).find(o=>o.includes('"parentUuid":'))??e,r=Aa(i,"sessionKind");return r==="daemon"||r==="daemon-worker"}function ot(e){return typeof e!="string"?null:Y4.test(e)?e:null}function fx(e){if(!e.includes("\\"))return e;try{return JSON.parse(`"${e}"`)}catch{return e}}function Aa(e,t){let n=[`"${t}":"`,`"${t}": "`];for(let i of n){let r=e.indexOf(i);if(r<0)continue;let o=r+i.length,a=o;for(;a<e.length;){if(e[a]==="\\"){a+=2;continue}if(e[a]==='"')return fx(e.slice(o,a));a++}}}function Vt(e,t){let n=[`"${t}":"`,`"${t}": "`],i,r=-1;for(let o of n){let a=0;for(;;){let s=e.indexOf(o,a);if(s<0)break;let d=s+o.length,u=d;for(;u<e.length;){if(e[u]==="\\"){u+=2;continue}if(e[u]==='"'){s>r&&(i=fx(e.slice(d,u)),r=s);break}u++}a=u+1}}return i}function X4(e,t,n){let i=`"type":"${t}"`,r=`"${n}":`,o=e.length;for(;o>0;){let a=e.lastIndexOf(`
17
+ `,o-1),s=e.slice(a+1,o);if(o=a,s.includes(i)&&s.includes(r))try{let d=JSON.parse(s);if(typeof d=="object"&&d!==null&&d.type===t){let u=d[n];if(typeof u=="string")return u}}catch{}if(a<0)break}}async function gf(e,t){return eB(e,t,"w")}async function eB(e,t,n){let i=$4(e,{mode:384,flags:n});try{for(let r of t)i.write(JSON.stringify(r)+`
18
+ `)||await iw(i,"drain");i.end(),await iw(i,"finish")}catch(r){throw i.destroy(),r}}function mx(e){let t=0,n={commandFallback:""};for(;t<e.length;){let i=e.indexOf(`
19
+ `,t),r=i>=0?e.slice(t,i):e.slice(t);if(t=i>=0?i+1:e.length,!(!r.includes('"type":"user"')&&!r.includes('"type": "user"'))&&!r.includes('"tool_result"')&&!(r.includes('"isMeta":true')||r.includes('"isMeta": true'))&&!(r.includes('"isCompactSummary":true')||r.includes('"isCompactSummary": true')))try{let o=JSON.parse(r),a=gm(o,n);if(a!==void 0)return a}catch{continue}}return n.commandFallback}function tB(e){let t={commandFallback:""};for(let n of e){if(typeof n!="object"||n===null)continue;let i=gm(n,t);if(i!==void 0)return i}return t.commandFallback}async function hx(e){try{let t=await px(e,"r");try{let n=await t.stat(),i=Buffer.allocUnsafe(er),r=await t.read(i,0,er,0);if(r.bytesRead===0)return null;let o=i.toString("utf8",0,r.bytesRead),a=Math.max(0,n.size-er),s=o;if(a>0){let d=await t.read(i,0,er,a);s=i.toString("utf8",0,d.bytesRead)}return{mtime:n.mtime.getTime(),size:n.size,head:o,tail:s}}finally{await t.close()}}catch{return null}}function nB(e){return Math.abs(V4(e)).toString(36)}function _s(e){let t=e.replace(/[^a-zA-Z0-9]/g,"-");return t.length<=Ja?t:`${t.slice(0,Ja)}-${nB(e)}`}function Tr(){return Ka(yo(),"projects")}function rB(e){return Ka(Tr(),_s(e))}async function vs(e){try{return Bi(await M4(e))}catch{return Bi(e)}}async function kn(e){let t=rB(e),n=[];try{await hf(t),n.push(t)}catch{}let i=_s(e);if(i.length<=Ja)return n;let r=i.slice(0,Ja)+"-",o=Tr();try{for(let a of await hf(o,{withFileTypes:!0})){if(!a.isDirectory()||!a.name.startsWith(r))continue;let s=Ka(o,a.name);s!==t&&n.push(s)}}catch{}return n}async function bl(e,t){let n=`${e}.jsonl`;async function i(a,s){let d=Ka(a,n);try{let u=await j4(d);if(u.size>0)return{filePath:d,projectPath:s,fileSize:u.size}}catch{}}if(t){let a=await vs(t);for(let d of await kn(a)){let u=await i(d,a);if(u)return u}let s;try{s=await ys(a)}catch{s=[]}for(let d of s)if(d!==a)for(let u of await kn(d)){let l=await i(u,d);if(l)return l}return}let r=Tr(),o;try{o=await hf(r)}catch{return}for(let a of o){let s=await i(Ka(r,a),void 0);if(s)return s}}function sB(){return aB??=Buffer.from('"compact_boundary"')}function gx(e){try{let t=JSON.parse(e);return t.type!=="system"||t.subtype!=="compact_boundary"?null:{hasPreservedSegment:!!(t.compactMetadata?.preservedSegment||t.compactMetadata?.preservedMessages)}}catch{return null}}function Gr(e,t,n,i){let r=i-n;if(!(r<=0)){if(e.len+r>e.buf.length){let o=Buffer.allocUnsafe(Math.min(Math.max(e.buf.length*2,e.len+r),e.cap));e.buf.copy(o,0,0,e.len),e.buf=o}t.copy(e.buf,e.len,n,i),e.len+=r}}function ku(e,t,n,i){return i-n>=t.length&&e.compare(t,0,t.length,n,n+t.length)===0}function cB(e,t,n){if(e.straddleSnapCarryLen=0,e.straddleSnapTailEnd=0,e.carryLen===0)return 0;let i=e.carryBuf,r=t.indexOf(Wa);if(r===-1||r>=n)return 0;let o=r+1;if(ku(i,xu,0,e.carryLen))e.straddleSnapCarryLen=e.carryLen,e.straddleSnapTailEnd=o,e.lastSnapSrc=null;else{if(e.carryLen<xu.length)return 0;if(ku(i,dB,0,e.carryLen)){let a=gx(i.toString("utf-8",0,e.carryLen)+t.toString("utf-8",0,r));a?.hasPreservedSegment?e.hasPreservedSegment=!0:a&&(e.out.len=0,e.boundaryStartOffset=e.bufFileOff,e.hasPreservedSegment=!1,e.lastSnapSrc=null)}Gr(e.out,i,0,e.carryLen),Gr(e.out,t,0,o)}return e.bufFileOff+=e.carryLen+o,e.carryLen=0,o}function pB(e,t,n){let i=t.indexOf(n),r=0,o=0,a=-1,s=-1,d=t.indexOf(Wa);for(;d!==-1;){let u=d+1;if(i!==-1&&i<o&&(i=t.indexOf(n,o)),ku(t,xu,o,u))Gr(e.out,t,r,o),a=o,s=u,r=u;else if(i>=o&&i<Math.min(o+lB,u)){let l=gx(t.toString("utf-8",o,d));l?.hasPreservedSegment?e.hasPreservedSegment=!0:l&&(e.out.len=0,e.boundaryStartOffset=e.bufFileOff+o,e.hasPreservedSegment=!1,e.lastSnapSrc=null,a=-1,e.straddleSnapCarryLen=0,r=o),i=t.indexOf(n,i+n.length)}o=u,d=t.indexOf(Wa,o)}return Gr(e.out,t,r,o),{lastSnapStart:a,lastSnapEnd:s,trailStart:o}}function fB(e,t,n,i,r){i!==-1?(e.lastSnapLen=r-i,(e.lastSnapBuf===void 0||e.lastSnapLen>e.lastSnapBuf.length)&&(e.lastSnapBuf=Buffer.allocUnsafe(e.lastSnapLen)),t.copy(e.lastSnapBuf,0,i,r),e.lastSnapSrc=e.lastSnapBuf):e.straddleSnapCarryLen>0&&(e.lastSnapLen=e.straddleSnapCarryLen+e.straddleSnapTailEnd,(e.lastSnapBuf===void 0||e.lastSnapLen>e.lastSnapBuf.length)&&(e.lastSnapBuf=Buffer.allocUnsafe(e.lastSnapLen)),e.carryBuf.copy(e.lastSnapBuf,0,0,e.straddleSnapCarryLen),n.copy(e.lastSnapBuf,e.straddleSnapCarryLen,0,e.straddleSnapTailEnd),e.lastSnapSrc=e.lastSnapBuf)}function mB(e,t,n){e.carryLen=t.length-n,e.carryLen>0&&((e.carryBuf===void 0||e.carryLen>e.carryBuf.length)&&(e.carryBuf=Buffer.allocUnsafe(e.carryLen)),t.copy(e.carryBuf,0,n,t.length))}function hB(e){if(e.carryLen>0){let t=e.carryBuf;ku(t,xu,0,e.carryLen)?(e.lastSnapSrc=t,e.lastSnapLen=e.carryLen):Gr(e.out,t,0,e.carryLen)}e.lastSnapSrc&&(e.out.len>0&&e.out.buf[e.out.len-1]!==Wa&&Gr(e.out,uB,0,1),Gr(e.out,e.lastSnapSrc,0,e.lastSnapLen))}async function gB(e,t){let n=sB(),i=iB,r={out:{buf:Buffer.allocUnsafe(Math.min(t,8388608)),len:0,cap:t+1},boundaryStartOffset:0,hasPreservedSegment:!1,lastSnapSrc:null,lastSnapLen:0,lastSnapBuf:void 0,bufFileOff:0,carryLen:0,carryBuf:void 0,straddleSnapCarryLen:0,straddleSnapTailEnd:0},o=Buffer.allocUnsafe(i),a=await px(e,"r");try{let s=0;for(;s<t;){let{bytesRead:d}=await a.read(o,0,Math.min(i,t-s),s);if(d===0)break;s+=d;let u=cB(r,o,d),l;if(r.carryLen>0){let m=r.carryLen+(d-u);l=Buffer.allocUnsafe(m),r.carryBuf.copy(l,0,0,r.carryLen),o.copy(l,r.carryLen,u,d)}else l=o.subarray(u,d);let p=pB(r,l,n);fB(r,l,o,p.lastSnapStart,p.lastSnapEnd),mB(r,l,p.trailStart),r.bufFileOff+=p.trailStart}hB(r)}finally{await a.close()}return{boundaryStartOffset:r.boundaryStartOffset,postBoundaryBuf:r.out.buf.subarray(0,r.out.len),hasPreservedSegment:r.hasPreservedSegment}}async function yB(e,t){try{return t>oB&&!kt(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)?(await gB(e,t)).postBoundaryBuf:await A4(e)}catch{return null}}async function _B(e){let t=[];try{let r=Xe(t,tt`parseTranscriptEntries(${e.length} bytes)`,0),o=[],a=10,s=e.length,d=0,u=aw;for(;d<s;){d>=u&&(await new Promise(f=>setImmediate(f)),u=d+aw);let l=e.indexOf(a,d);l===-1&&(l=s);let p=d;for(;p<l&&e[p]<=32;)p++;if(d=l+1,p>=l)continue;let m=e.toString("utf-8",p,l);try{let f=m4(m),h=f.type;(h==="user"||h==="assistant"||h==="progress"||h==="system"||h==="attachment")&&typeof f.uuid=="string"&&o.push(f)}catch{}}return o}catch(r){var n=r,i=1}finally{et(t,n,i)}}async function vB(e){let t=new Map;for(let f of e)t.set(f.uuid,f);let n=0;for(let f of t.values()){if(f.type!=="system"||f.subtype!=="compact_boundary")continue;let h=f.compactMetadata?.preservedMessages,y=f.compactMetadata?.preservedSegment;if(h){if(h.uuids.length===0||h.uuids.some(b=>!t.has(b)))continue;let w=h.anchorUuid;for(let b of h.uuids){let S=t.get(b);t.set(b,{...S,parentUuid:w}),w=b}let g=h.uuids[0],v=h.uuids.at(-1);for(let[b,S]of t)++n%sw===0&&await new Promise(T=>setImmediate(T)),S.parentUuid===h.anchorUuid&&b!==g&&t.set(b,{...S,parentUuid:v})}else if(y){let w=t.get(y.headUuid);w&&t.set(y.headUuid,{...w,parentUuid:y.anchorUuid});for(let[g,v]of t)++n%sw===0&&await new Promise(b=>setImmediate(b)),v.parentUuid===y.anchorUuid&&g!==y.headUuid&&t.set(g,{...v,parentUuid:y.tailUuid})}}let i=new Map;for(let f=0;f<e.length;f++)i.set(e[f].uuid,f);let r=new Set;for(let f of t.values())f.parentUuid&&r.add(f.parentUuid);let o=[...t.values()].filter(f=>!r.has(f.uuid)),a=[];for(let f of o){let h=f,y=new Set;for(;h&&!y.has(h.uuid);){if(y.add(h.uuid),h.type==="user"||h.type==="assistant"){a.push(h);break}h=h.parentUuid?t.get(h.parentUuid):void 0}}if(a.length===0)return[];let s=a.filter(f=>!f.isSidechain&&!f.teamName&&!f.isMeta),d=f=>f.reduce((h,y)=>(i.get(y.uuid)??-1)>(i.get(h.uuid)??-1)?y:h),u=s.length>0?d(s):d(a),l=[],p=new Set,m=t.get(u.uuid);for(;m&&!p.has(m.uuid);)p.add(m.uuid),l.push(m),m=m.parentUuid?t.get(m.parentUuid):void 0;return l.reverse(),await new Promise(f=>setImmediate(f)),wB(t,l,p)}function wp(e){if(e.type!=="assistant")return;let t=e.message;if(typeof t!="object"||t===null)return;let n=t.id;return typeof n=="string"?n:void 0}function bB(e){if(e.type!=="user"||!e.parentUuid)return!1;let t=e.message;if(typeof t!="object"||t===null)return!1;let n=t.content;return Array.isArray(n)?n.some(i=>typeof i=="object"&&i!==null&&i.type==="tool_result"):!1}function wB(e,t,n){let i=t.filter(p=>p.type==="assistant");if(i.length===0)return t;let r=new Map;for(let p of i){let m=wp(p);m&&r.set(m,p)}let o=new Map,a=new Map;for(let p of e.values()){let m=wp(p);if(m){let f=o.get(m);f?f.push(p):o.set(m,[p])}else if(bB(p)){let f=p.parentUuid,h=a.get(f);h?h.push(p):a.set(f,[p])}}let s=new Set,d=new Map,u=0;for(let p of i){let m=wp(p);if(!m||s.has(m))continue;s.add(m);let f=o.get(m)??[p],h=f.filter(b=>!n.has(b.uuid)),y=[];for(let b of f){let S=a.get(b.uuid);if(S)for(let T of S)n.has(T.uuid)||y.push(T)}if(h.length===0&&y.length===0)continue;let w=(b,S)=>(b.timestamp??"").localeCompare(S.timestamp??"");h.sort(w),y.sort(w);let g=r.get(m),v=[...h,...y];for(let b of v)n.add(b.uuid);u+=v.length,d.set(g.uuid,v)}if(u===0)return t;let l=[];for(let p of t){l.push(p);let m=d.get(p.uuid);m&&l.push(...m)}return l}function SB(e,t){if(!(e.type==="user"||e.type==="assistant")){if(!(e.type==="system"&&t))return!1}return!(e.isMeta||e.isSidechain||e.teamName)}function yx(e,t){return{type:e.type,uuid:e.uuid,session_id:e.sessionId,message:e.message,parent_tool_use_id:t??null,timestamp:e.timestamp}}function _x(e,t){let n=t?.offset??0;return t?.limit!==void 0&&t.limit>0?e.slice(n,n+t.limit):n>0?e.slice(n):e}async function kB(e,t){let n=[];for(let i of e){if(typeof i!="object"||i===null)continue;let r=i,o=r.type;(o==="user"||o==="assistant"||o==="progress"||o==="system"||o==="attachment")&&typeof r.uuid=="string"&&n.push(r)}return vx(n,t)}async function vx(e,t){let n=await vB(e),i=t?.includeSystemMessages??!1,r=n.filter(o=>SB(o,i)).map(o=>yx(o));return _x(r,t)}async function xB(e,t){if(!ot(e))return[];let n=await bl(e,t?.dir);if(!n)return[];let i=await yB(n.filePath,n.fileSize);return i?vx(await _B(i),t):[]}function wl(e,t,n){let{head:i,tail:r,mtime:o,size:a}=t,s=i.indexOf(`
20
+ `),d=s>=0?i.slice(0,s):i;if(d.includes('"isSidechain":true')||d.includes('"isSidechain": true'))return null;let u=Vt(r,"customTitle")||Vt(i,"customTitle")||Vt(r,"aiTitle")||Vt(i,"aiTitle")||void 0,l=mx(i)||void 0,p=Aa(i,"timestamp"),m;if(p){let v=Date.parse(p);Number.isNaN(v)||(m=v)}let f=u||Vt(r,"lastPrompt")||Vt(r,"summary")||l;if(!f)return null;let h=Vt(r,"gitBranch")||Aa(i,"gitBranch")||void 0,y=X4(r,"relocated","relocatedCwd")||Aa(i,"cwd")||n||void 0,w=r.split(`
21
+ `).findLast(v=>v.includes('"type":"tag"')&&v.includes('"tag":"')),g=w&&Vt(w,"tag")||void 0;return{sessionId:e,summary:f,lastModified:o,fileSize:a,customTitle:u,firstPrompt:l,gitBranch:h,cwd:y,tag:g,createdAt:m}}async function xa(e,t,n){let i;try{i=await Bm(e)}catch{return[]}return(await Promise.all(i.map(async r=>{if(!r.endsWith(".jsonl"))return null;let o=ot(r.slice(0,-6));if(!o)return null;let a=Km(e,r);if(!t)return{sessionId:o,filePath:a,mtime:0,projectPath:n};try{let s=await CB(a);return{sessionId:o,filePath:a,mtime:s.mtime.getTime(),projectPath:n}}catch{return null}}))).filter(r=>r!==null)}async function bx(e,t){let n=await hx(e.filePath);if(!n||!t&&Q4(n.head,n.tail))return null;let i=wl(e.sessionId,n,e.projectPath);return i?(e.mtime&&(i.lastModified=e.mtime),i):null}function PB(e,t){return t.mtime!==e.mtime?t.mtime-e.mtime:t.sessionId<e.sessionId?-1:t.sessionId>e.sessionId?1:0}async function EB(e,t,n,i){e.sort(PB);let r=[],o=t&&t>0?t:1/0,a=0,s=new Set;for(let d=0;d<e.length&&r.length<o;){let u=Math.min(d+IB,e.length),l=e.slice(d,u),p=await Promise.all(l.map(m=>bx(m,i)));for(let m=0;m<p.length&&r.length<o;m++){d++;let f=p[m];if(f&&!s.has(f.sessionId)){if(s.add(f.sessionId),a<n){a++;continue}r.push(f)}}}return r}async function RB(e,t){let n=await Promise.all(e.map(o=>bx(o,t))),i=new Map;for(let o of n){if(!o)continue;let a=i.get(o.sessionId);(!a||o.lastModified>a.lastModified)&&i.set(o.sessionId,o)}let r=[...i.values()];return r.sort((o,a)=>a.lastModified!==o.lastModified?a.lastModified-o.lastModified:a.sessionId<o.sessionId?-1:a.sessionId>o.sessionId?1:0),r}async function OB(e,t,n){let i=await vs(e),r;if(t)try{r=await ys(i)}catch{r=[]}else r=[];if(r.length<=1){let p=[];for(let m of await kn(i))p.push(...await xa(m,n,i));return p}let o=Tr(),a=process.platform==="win32",s=r.map(p=>{let m=_s(p);return{path:p,prefix:a?m.toLowerCase():m}});s.sort((p,m)=>m.prefix.length-p.prefix.length);let d;try{d=await Bm(o,{withFileTypes:!0})}catch{let p=[];for(let m of await kn(i))p.push(...await xa(m,n,i));return p}let u=[],l=new Set;for(let p of await kn(i)){let m=TB(p);l.add(a?m.toLowerCase():m),u.push(...await xa(p,n,i))}for(let p of d){if(!p.isDirectory())continue;let m=a?p.name.toLowerCase():p.name;if(!l.has(m)){for(let{path:f,prefix:h}of s)if(m===h||h.length>=Ja&&m.startsWith(h+"-")){l.add(m),u.push(...await xa(Km(o,p.name),n,f));break}}}return u}async function AB(e){let t=Tr(),n;try{n=await Bm(t,{withFileTypes:!0})}catch{return[]}return(await Promise.all(n.filter(i=>i.isDirectory()).map(i=>xa(Km(t,i.name),e)))).flat()}async function $B(e){let{dir:t,limit:n,offset:i,includeWorktrees:r,includeProgrammatic:o}=e??{},a=i??0,s=o??!0,d=n!==void 0&&n>0||a>0,u=t?await OB(t,r??!0,d):await AB(d);return d?EB(u,n,a,s):RB(u,s)}async function MB(e,t={}){let n=ot(e);if(!n)return;let i=await bl(n,t.dir);if(!i)return;let r=await hx(i.filePath);if(r)return wl(n,r,i.projectPath)??void 0}async function NB(e,t,n={}){if(!ot(e))throw Error(`Invalid sessionId: ${e}`);if(!t.trim())throw Error("title must be non-empty");let i=ut({type:"custom-title",customTitle:t.trim(),sessionId:e})+`
22
+ `;await Sx(e,i,n)}async function DB(e,t,n={}){if(!ot(e))throw Error(`Invalid sessionId: ${e}`);if(t!==null){let r=Oa(t).trim();if(!r)throw Error("tag must be non-empty (use null to clear)");t=r}let i=ut({type:"tag",tag:t??"",sessionId:e})+`
23
+ `;await Sx(e,i,n)}async function LB(e,t={}){if(!ot(e))throw Error(`Invalid sessionId: ${e}`);for(let n of await UB(t)){let i=Di(n,`${e}.jsonl`),r;try{({size:r}=await qB(i))}catch(o){let a=Pt(o);if(a==="ENOENT"||a==="ENOTDIR")continue;throw o}if(r!==0){await uw(i,{force:!0}),await uw(Di(n,e),{recursive:!0,force:!0});return}}throw Error(t.dir?`Session ${e} not found in project directory for ${t.dir}`:`Session ${e} not found in any project directory`)}async function UB(e){if(e.dir){let n=await vs(e.dir),i=await kn(n),r;try{r=await ys(n)}catch{r=[]}for(let o of r)o!==n&&i.push(...await kn(o));return i}let t=Tr();try{return(await wx(t,{withFileTypes:!0})).filter(n=>n.isDirectory()||n.isSymbolicLink()).map(n=>Di(t,n.name))}catch{return[]}}async function Sx(e,t,n){let i=`${e}.jsonl`;if(n.dir){let a=await vs(n.dir);for(let d of await kn(a))if(await Sp(Di(d,i),t))return;let s;try{s=await ys(a)}catch{s=[]}for(let d of s)if(d!==a){for(let u of await kn(d))if(await Sp(Di(u,i),t))return}throw Error(`Session ${e} not found in project directory for ${n.dir}`)}let r=Tr(),o;try{o=await wx(r)}catch{throw Error(`Session ${e} not found (no projects directory)`)}for(let a of o)if(await Sp(Di(r,a,i),t))return;throw Error(`Session ${e} not found in any project directory`)}async function Sp(e,t){let n;try{n=await jB(e,dw.O_WRONLY|dw.O_APPEND)}catch(i){let r=Pt(i);if(r==="ENOENT"||r==="ENOTDIR")return!1;throw i}try{let{size:i}=await n.stat();if(i===0)return!1;let r=process.platform==="win32"?i:void 0,o=Buffer.from(t,"utf8"),a=0;for(;a<o.length;){let{bytesWritten:s}=await n.write(o,a,o.length-a,r);if(s<=0)throw new Cn(`tryAppend: short write to ${e} stalled with ${o.length-a} bytes remaining`,"tryAppend: zero-progress short write");a+=s,r!==void 0&&(r+=s)}return!0}finally{await n.close()}}async function FB(e,t){let n=`${e}.jsonl`;async function i(a){try{let s=await hu().readBytes(yf(a,n));return s.length===0?null:{buf:s,projectDir:a}}catch{return null}}if(t){let a=await vs(t);for(let d of await kn(a)){let u=await i(d);if(u)return u}let s;try{s=await ys(a)}catch{s=[]}for(let d of s)if(d!==a)for(let u of await kn(d)){let l=await i(u);if(l)return l}return null}let r=Tr(),o;try{o=await hu().list(r)}catch{return null}for(let a of o){let s=await i(yf(r,a));if(s)return s}return null}function BB(e,t){let n=[],i=[],r,o=10,a=e.length,s=0;for(;s<a;){let d=e.indexOf(10,s);d===-1&&(d=a);let u=s;for(;u<d&&e[u]<=32;)u++;if(s=d+1,u>=d)continue;let l=e.toString("utf-8",u,d);try{r=kx(Rn(l),t,n,i)??r}catch{}}return{transcript:n,contentReplacements:i,relocatedCwd:r}}function KB(e,t){let n=[],i=[],r;for(let o of e)typeof o!="object"||o===null||(r=kx(o,t,n,i)??r);return{transcript:n,contentReplacements:i,relocatedCwd:r}}function kx(e,t,n,i){if(zB.has(e.type)&&typeof e.uuid=="string")n.push(e);else if(e.type==="content-replacement"&&e.sessionId===t&&Array.isArray(e.replacements))i.push(...e.replacements);else if(e.type==="relocated"&&e.sessionId===t&&typeof e.relocatedCwd=="string")return e.relocatedCwd}async function JB(e,t={}){if(!ot(e))throw new Cn(`Invalid sessionId: ${e}`,"forkSession: invalid sessionId (not a UUID)");if(t.upToMessageId&&!ot(t.upToMessageId))throw new Cn(`Invalid upToMessageId: ${t.upToMessageId}`,"forkSession: invalid upToMessageId (not a UUID)");let n=await FB(e,t.dir);if(!n)throw Error(t.dir?`Session ${e} not found in project directory for ${t.dir}`:`Session ${e} not found`);let{entries:i,forkedSessionId:r}=WB(n.buf,e,t);return await gf(yf(n.projectDir,`${r}.jsonl`),i),{sessionId:r}}function WB(e,t,n){let i=BB(e,t);return xx(i,t,n,()=>{let r=e.length,o=e.toString("utf-8",0,Math.min(r,er)),a=e.toString("utf-8",Math.max(0,r-er));return Vt(a,"customTitle")||Vt(o,"customTitle")||Vt(a,"aiTitle")||Vt(o,"aiTitle")||mx(o)})}function HB(e,t,n){let i=KB(e,t);return xx(i,t,n,()=>GB(e))}function GB(e){let t,n;for(let i of e){if(typeof i!="object"||i===null)continue;let r=i;typeof r.customTitle=="string"&&r.customTitle&&(t=r.customTitle),typeof r.aiTitle=="string"&&r.aiTitle&&(n=r.aiTitle)}return t||n||tB(e)||void 0}function xx(e,t,n,i){let r=e.transcript.filter(m=>!m.isSidechain);if(r.length===0)throw Error(`Session ${t} has no messages to fork`);if(n.upToMessageId){let m=r.findIndex(f=>f.uuid===n.upToMessageId);if(m===-1)throw Error(`Message ${n.upToMessageId} not found in session ${t}`);r=r.slice(0,m+1)}let o=new Map;for(let m of r)o.set(m.uuid,Sd());let a=r.filter(m=>m.type!=="progress");if(a.length===0)throw Error(`Session ${t} has no messages to fork`);let s=new Map;for(let m of r)s.set(m.uuid,m);let d=Sd(),u=new Date().toISOString(),l=[];for(let m=0;m<a.length;m++){let f=a[m],h=o.get(f.uuid),y=null,w=f.parentUuid;for(;w;){let T=s.get(w);if(!T)break;if(T.type!=="progress"){y=o.get(w)??null;break}w=T.parentUuid}let g=m===a.length-1?u:f.timestamp,v=f.logicalParentUuid==null?f.logicalParentUuid:o.get(f.logicalParentUuid)??null,b=f.type==="system"&&f.subtype==="model_refusal_fallback"?{neutralizedByFork:!0}:void 0,S={...f,...b,uuid:h,parentUuid:y,logicalParentUuid:v,sessionId:d,timestamp:g,isSidechain:!1,teamName:void 0,agentName:void 0,sessionKind:void 0,slug:void 0,sourceToolAssistantUUID:void 0,forkedFrom:{sessionId:t,messageUuid:f.uuid}};l.push(S)}e.contentReplacements.length>0&&l.push({type:"content-replacement",sessionId:d,replacements:e.contentReplacements,uuid:Sd(),timestamp:u}),e.relocatedCwd&&l.push({type:"relocated",sessionId:d,relocatedCwd:e.relocatedCwd});let p=n.title?.trim();return p||(p=`${i()||"Forked session"} (fork)`),l.push({type:"custom-title",sessionId:d,customTitle:p,uuid:Sd(),timestamp:u}),{entries:l,forkedSessionId:d}}async function Cx(e,t){let n=await bl(e,t);if(!n)return null;let i=n.filePath.replace(/\.jsonl$/,"");return _f(i,"subagents")}async function Tx(e){let t=[];async function n(i){let r;try{r=await VB(i,{withFileTypes:!0})}catch{return}for(let o of r)if(o.isFile()&&o.name.startsWith("agent-")&&o.name.endsWith(".jsonl")){let a=o.name.slice(6,-6);t.push({agentId:a,filePath:_f(i,o.name)})}else o.isDirectory()&&await n(_f(i,o.name))}return await n(e),t}function ZB(e){let t=[],n=10,i=e.length,r=0;for(;r<i;){let o=e.indexOf(10,r);o===-1&&(o=i);let a=r;for(;a<o&&e[a]<=32;)a++;if(r=o+1,a>=o)continue;let s=e.toString("utf-8",a,o);try{let d=Rn(s),u=d.type;(u==="user"||u==="assistant")&&typeof d.uuid=="string"&&t.push(d)}catch{}}return t}function QB(e){if(e.length===0)return[];let t=new Map;for(let a of e)t.set(a.uuid,a);let n=e.findLast(a=>a.type==="user"||a.type==="assistant");if(!n)return[];let i=[],r=new Set,o=n;for(;o&&!r.has(o.uuid);)r.add(o.uuid),i.push(o),o=o.parentUuid?t.get(o.parentUuid):void 0;return i.reverse(),i}async function YB(e,t){if(!ot(e))return[];let n=await Cx(e,t?.dir);return n?(await Tx(n)).map(i=>i.agentId):[]}async function XB(e,t,n){if(!ot(e))return[];if(!t)return[];let i=await Cx(e,n?.dir);if(!i)return[];let r=(await Tx(i)).find(s=>s.agentId===t);if(!r)return[];let o;try{o=await lw(r.filePath)}catch{return[]}let a;try{let s=r.filePath.replace(/\.jsonl$/,".meta.json");a=Rn(await lw(s,"utf-8")).toolUseId}catch{}return Ix(o,n,a)}function Ix(e,t,n){if(e.length===0)return[];let i=ZB(e),r=QB(i).filter(o=>o.type==="user"||o.type==="assistant").map(o=>yx(o,n));return _x(r,t)}function Px(e,t){let n=0;for(let i of e)n+=+!!t(i);return n}function Ex(e){return[...new Set(e)]}function nK(){return"prod"}function uK(){let e=process.env.CLAUDE_LOCAL_OAUTH_API_BASE?.replace(/\/$/,"")??"http://localhost:8000",t=process.env.CLAUDE_LOCAL_OAUTH_APPS_BASE?.replace(/\/$/,"")??"http://localhost:4000",n=process.env.CLAUDE_LOCAL_OAUTH_CONSOLE_BASE?.replace(/\/$/,"")??"http://localhost:3000";return{BASE_API_URL:e,CONSOLE_AUTHORIZE_URL:`${n}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${t}/oauth/authorize`,CLAUDE_AI_ORIGIN:t,TOKEN_URL:`${e}/v1/oauth/token`,API_KEY_URL:`${e}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${e}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${n}/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code`,CLAUDEAI_SUCCESS_URL:`${n}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${n}/oauth/code/callback`,CLIENT_ID:"22422756-60c9-4084-8eb7-27705fd5cf9a",DESIGN_CLIENT_ID:"00000000-0000-4000-8000-000000000000",OAUTH_FILE_SUFFIX:"-local-oauth",MCP_PROXY_URL:"http://localhost:8205",MCP_PROXY_PATH:"/v1/toolbox/shttp/mcp/{server_id}"}}function cK(){let e=(()=>{switch(nK()){case"local":return uK();case"staging":return dK??cw;case"prod":return cw}})(),t=process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL;if(t){let i=t.replace(/\/$/,"");if(!lK.includes(i))throw Error("CLAUDE_CODE_CUSTOM_OAUTH_URL is not an approved endpoint.");e={...e,BASE_API_URL:i,CONSOLE_AUTHORIZE_URL:`${i}/oauth/authorize`,CLAUDE_AI_AUTHORIZE_URL:`${i}/oauth/authorize`,CLAUDE_AI_ORIGIN:i,TOKEN_URL:`${i}/v1/oauth/token`,API_KEY_URL:`${i}/api/oauth/claude_cli/create_api_key`,ROLES_URL:`${i}/api/oauth/claude_cli/roles`,CONSOLE_SUCCESS_URL:`${i}/oauth/code/success?app=claude-code`,CLAUDEAI_SUCCESS_URL:`${i}/oauth/code/success?app=claude-code`,MANUAL_REDIRECT_URL:`${i}/oauth/code/callback`,OAUTH_FILE_SUFFIX:"-custom-oauth"}}let n=process.env.CLAUDE_CODE_OAUTH_CLIENT_ID;return n&&(e={...e,CLIENT_ID:n}),e}function fK(e=""){let t=process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR,n=t!==void 0?!t:!process.env.CLAUDE_CONFIG_DIR,i=t!==void 0?t.normalize("NFC"):yo(),r=n?"":`-${eK("sha256").update(i).digest("hex").substring(0,8)}`;return`Claude Code${cK().OAUTH_FILE_SUFFIX}${e}${r}`}function hK(){if(process.platform==="win32")return"claude-code-user";let e;try{e=process.env.USER||tK().username}catch{e="claude-code-user"}return mK.test(e)?e:"claude-code-user"}function gK(e,t){if(e==="bypassPermissions")return"canUseTool will not be invoked: permissionMode 'bypassPermissions' auto-approves every tool call (except explicit deny rules) before the callback is consulted. To gate every tool call, use a PreToolUse hook instead.";let n=t.filter(i=>i.length>0&&!i.includes("("));if(n.length!==0)return`canUseTool will not be invoked for: ${n.join(", ")}. Bare allowedTools entries auto-approve the whole tool before the callback is consulted. To gate every tool call, use a PreToolUse hook; or remove the bare names from allowedTools so they fall through to canUseTool. Allow rules from settings files can also shadow the callback but are not visible here.`}function yK(e,t,n){if(!e)return;let i=gK(t,n);i!==void 0&&process.emitWarning(i,{code:"CLAUDE_SDK_CAN_USE_TOOL_SHADOWED"})}function vf(){return vK}function re(e,t){let n=vf(),i=bf({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Ha?void 0:Ha].filter(r=>!!r)});e.common.issues.push(i)}function ke(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:i,description:r}=e;if(t&&(n||i))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:r}:{errorMap:(o,a)=>{let{message:s}=e;return o.code==="invalid_enum_value"?{message:s??a.defaultError}:typeof a.data>"u"?{message:s??i??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:s??n??a.defaultError}},description:r}}function Ax(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function qK(e){return new RegExp(`^${Ax(e)}$`)}function NK(e){let t=`${Ox}T${Ax(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function DK(e,t){return!!((t==="v4"||!t)&&EK.test(e)||(t==="v6"||!t)&&OK.test(e))}function LK(e,t){if(!CK.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let i=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(i));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||t&&r.alg!==t)}catch{return!1}}function UK(e,t){return!!((t==="v4"||!t)&&RK.test(e)||(t==="v6"||!t)&&AK.test(e))}function FK(e,t){let n=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,r=n>i?n:i,o=Number.parseInt(e.toFixed(r).replace(".","")),a=Number.parseInt(t.toFixed(r).replace(".",""));return o%a/10**r}function Ai(e){if(e instanceof Xt){let t={};for(let n in e.shape){let i=e.shape[n];t[n]=cn.create(Ai(i))}return new Xt({...e._def,shape:()=>t})}else return e instanceof kr?new kr({...e._def,type:Ai(e.element)}):e instanceof cn?cn.create(Ai(e.unwrap())):e instanceof ir?ir.create(Ai(e.unwrap())):e instanceof rr?rr.create(e.items.map(t=>Ai(t))):e}function Sf(e,t){let n=mr(e),i=mr(t);if(e===t)return{valid:!0,data:e};if(n===ae.object&&i===ae.object){let r=Oe.objectKeys(t),o=Oe.objectKeys(e).filter(s=>r.indexOf(s)!==-1),a={...e,...t};for(let s of o){let d=Sf(e[s],t[s]);if(!d.valid)return{valid:!1};a[s]=d.data}return{valid:!0,data:a}}else if(n===ae.array&&i===ae.array){if(e.length!==t.length)return{valid:!1};let r=[];for(let o=0;o<e.length;o++){let a=e[o],s=t[o],d=Sf(a,s);if(!d.valid)return{valid:!1};r.push(d.data)}return{valid:!0,data:r}}else return n===ae.date&&i===ae.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function $x(e,t){return new ro({values:e,typeName:V.ZodEnum,...ke(t)})}function q(e,t,n){function i(s,d){var u;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(u=s._zod).traits??(u.traits=new Set),s._zod.traits.add(e),t(s,d);for(let l in a.prototype)l in s||Object.defineProperty(s,l,{value:a.prototype[l].bind(s)});s._zod.constr=a,s._zod.def=d}let r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:e});function a(s){var d;let u=n?.Parent?new o:this;i(u,s),(d=u._zod).deferred??(d.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(a,"init",{value:i}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>n?.Parent&&s instanceof n.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}function At(e){return e&&Object.assign(Pu,e),Pu}function BK(e){return e}function KK(e){return e}function JK(e){}function WK(e){throw Error()}function HK(e){}function Jm(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function te(e,t="|"){return e.map(n=>Ce(n)).join(t)}function Nx(e,t){return typeof t=="bigint"?t.toString():t}function Sl(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error("cached value already set")}}}function ai(e){return e==null}function kl(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Dx(e,t){let n=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,r=n>i?n:i,o=Number.parseInt(e.toFixed(r).replace(".","")),a=Number.parseInt(t.toFixed(r).replace(".",""));return o%a/10**r}function Ne(e,t,n){Object.defineProperty(e,t,{get(){{let i=n();return e[t]=i,i}throw Error("cached value already set")},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Wm(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function GK(e,t){return t?t.reduce((n,i)=>n?.[i],e):e}function VK(e){let t=Object.keys(e),n=t.map(i=>e[i]);return Promise.all(n).then(i=>{let r={};for(let o=0;o<t.length;o++)r[t[o]]=i[o];return r})}function ZK(e=10){let t="";for(let n=0;n<e;n++)t+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return t}function $i(e){return JSON.stringify(e)}function is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function os(e){if(is(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(is(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function QK(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function si(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function On(e,t,n){let i=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(i._zod.parent=e),i}function Q(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function XK(e){let t;return new Proxy({},{get(n,i,r){return t??(t=e()),Reflect.get(t,i,r)},set(n,i,r,o){return t??(t=e()),Reflect.set(t,i,r,o)},has(n,i){return t??(t=e()),Reflect.has(t,i)},deleteProperty(n,i){return t??(t=e()),Reflect.deleteProperty(t,i)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,i){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,i)},defineProperty(n,i,r){return t??(t=e()),Reflect.defineProperty(t,i,r)}})}function Ce(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Fx(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function eJ(e,t){let n={},i=e._zod.def;for(let r in t){if(!(r in i.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(n[r]=i.shape[r])}return On(e,{...e._zod.def,shape:n,checks:[]})}function tJ(e,t){let n={...e._zod.def.shape},i=e._zod.def;for(let r in t){if(!(r in i.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&delete n[r]}return On(e,{...e._zod.def,shape:n,checks:[]})}function nJ(e,t){if(!os(t))throw Error("Invalid input to extend: expected a plain object");let n={...e._zod.def,get shape(){let i={...e._zod.def.shape,...t};return Wm(this,"shape",i),i},checks:[]};return On(e,n)}function rJ(e,t){return On(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Wm(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function iJ(e,t,n){let i=t._zod.def.shape,r={...i};if(n)for(let o in n){if(!(o in i))throw Error(`Unrecognized key: "${o}"`);n[o]&&(r[o]=e?new e({type:"optional",innerType:i[o]}):i[o])}else for(let o in i)r[o]=e?new e({type:"optional",innerType:i[o]}):i[o];return On(t,{...t._zod.def,shape:r,checks:[]})}function oJ(e,t,n){let i=t._zod.def.shape,r={...i};if(n)for(let o in n){if(!(o in r))throw Error(`Unrecognized key: "${o}"`);n[o]&&(r[o]=new e({type:"nonoptional",innerType:i[o]}))}else for(let o in i)r[o]=new e({type:"nonoptional",innerType:i[o]});return On(t,{...t._zod.def,shape:r,checks:[]})}function Li(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function un(e,t){return t.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Ta(e){return typeof e=="string"?e:e?.message}function In(e,t,n){let i={...e,path:e.path??[]};if(!e.message){let r=Ta(e.inst?._zod.def?.error?.(e))??Ta(t?.error?.(e))??Ta(n.customError?.(e))??Ta(n.localeError?.(e))??"Invalid input";i.message=r}return delete i.inst,delete i.continue,!t?.reportInput&&delete i.input,i}function xl(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Cl(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Kx(...e){let[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}function aJ(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Vm(e,t=n=>n.message){let n={},i=[];for(let r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):i.push(t(r));return{formErrors:i,fieldErrors:n}}function Zm(e,t){let n=t||function(o){return o.message},i={_errors:[]},r=o=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(s=>r({issues:s}));else if(a.code==="invalid_key")r({issues:a.issues});else if(a.code==="invalid_element")r({issues:a.issues});else if(a.path.length===0)i._errors.push(n(a));else{let s=i,d=0;for(;d<a.path.length;){let u=a.path[d];d!==a.path.length-1?s[u]=s[u]||{_errors:[]}:(s[u]=s[u]||{_errors:[]},s[u]._errors.push(n(a))),s=s[u],d++}}};return r(e),i}function Wx(e,t){let n=t||function(o){return o.message},i={errors:[]},r=(o,a=[])=>{var s,d;for(let u of o.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(l=>r({issues:l},u.path));else if(u.code==="invalid_key")r({issues:u.issues},u.path);else if(u.code==="invalid_element")r({issues:u.issues},u.path);else{let l=[...a,...u.path];if(l.length===0){i.errors.push(n(u));continue}let p=i,m=0;for(;m<l.length;){let f=l[m],h=m===l.length-1;typeof f=="string"?(p.properties??(p.properties={}),(s=p.properties)[f]??(s[f]={errors:[]}),p=p.properties[f]):(p.items??(p.items=[]),(d=p.items)[f]??(d[f]={errors:[]}),p=p.items[f]),h&&p.errors.push(n(u)),m++}}};return r(e),i}function Hx(e){let t=[];for(let n of e)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function Gx(e){let t=[],n=[...e.issues].sort((i,r)=>i.path.length-r.path.length);for(let i of n)t.push(`\u2716 ${i.message}`),i.path?.length&&t.push(` \u2192 at ${Hx(i.path)}`);return t.join(`
24
+ `)}function i0(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function m0(e){return typeof e.precision=="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function h0(e){return new RegExp(`^${m0(e)}$`)}function g0(e){let t=m0({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");let i=`${t}(?:${n.join("|")})`;return new RegExp(`^${p0}T(?:${i})$`)}function gw(e,t,n){e.issues.length&&t.issues.push(...un(n,e.issues))}function oh(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function pC(e){if(!nh.test(e))return!1;let t=e.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return oh(n)}function hC(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let r=JSON.parse(atob(i));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}function yw(e,t,n){e.issues.length&&t.issues.push(...un(n,e.issues)),t.value[n]=e.value}function kd(e,t,n){e.issues.length&&t.issues.push(...un(n,e.issues)),t.value[n]=e.value}function _w(e,t,n,i){e.issues.length?i[n]===void 0?n in i?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...un(n,e.issues)):e.value===void 0?n in i&&(t.value[n]=void 0):t.value[n]=e.value}function vw(e,t,n,i){for(let r of e)if(r.issues.length===0)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(r=>r.issues.map(o=>In(o,i,At())))}),t}function Tf(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(os(e)&&os(t)){let n=Object.keys(t),i=Object.keys(e).filter(o=>n.indexOf(o)!==-1),r={...e,...t};for(let o of i){let a=Tf(e[o],t[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};r[o]=a.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<e.length;i++){let r=e[i],o=t[i],a=Tf(r,o);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function bw(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Li(e))return e;let i=Tf(t.value,n.value);if(!i.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}function xd(e,t,n){e.issues.length&&t.issues.push(...un(n,e.issues)),t.value[n]=e.value}function ww(e,t,n,i,r,o,a){e.issues.length&&(Eu.has(typeof i)?n.issues.push(...un(i,e.issues)):n.issues.push({origin:"map",code:"invalid_key",input:r,inst:o,issues:e.issues.map(s=>In(s,a,At()))})),t.issues.length&&(Eu.has(typeof i)?n.issues.push(...un(i,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:r,inst:o,key:i,issues:t.issues.map(s=>In(s,a,At()))})),n.value.set(e.value,t.value)}function Sw(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function kw(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function xw(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function Cw(e,t,n){return Li(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}function Tw(e){return e.value=Object.freeze(e.value),e}function Iw(e,t,n,i){if(!e){let r={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(r.params=i._zod.def.params),t.issues.push(Kx(r))}}function _J(){return{localeError:yJ()}}function bJ(){return{localeError:vJ()}}function Pw(e,t,n,i){let r=Math.abs(e),o=r%10,a=r%100;return a>=11&&a<=19?i:o===1?t:o>=2&&o<=4?n:i}function SJ(){return{localeError:wJ()}}function xJ(){return{localeError:kJ()}}function TJ(){return{localeError:CJ()}}function PJ(){return{localeError:IJ()}}function GC(){return{localeError:RJ()}}function $J(){return{localeError:AJ()}}function jJ(){return{localeError:MJ()}}function NJ(){return{localeError:qJ()}}function LJ(){return{localeError:DJ()}}function FJ(){return{localeError:UJ()}}function BJ(){return{localeError:zJ()}}function JJ(){return{localeError:KJ()}}function HJ(){return{localeError:WJ()}}function VJ(){return{localeError:GJ()}}function QJ(){return{localeError:ZJ()}}function XJ(){return{localeError:YJ()}}function t6(){return{localeError:e6()}}function r6(){return{localeError:n6()}}function o6(){return{localeError:i6()}}function s6(){return{localeError:a6()}}function u6(){return{localeError:d6()}}function c6(){return{localeError:l6()}}function f6(){return{localeError:p6()}}function h6(){return{localeError:m6()}}function y6(){return{localeError:g6()}}function v6(){return{localeError:_6()}}function Ew(e,t,n,i){let r=Math.abs(e),o=r%10,a=r%100;return a>=11&&a<=19?i:o===1?t:o>=2&&o<=4?n:i}function w6(){return{localeError:b6()}}function k6(){return{localeError:S6()}}function C6(){return{localeError:x6()}}function I6(){return{localeError:T6()}}function E6(){return{localeError:P6()}}function A6(){return{localeError:O6()}}function M6(){return{localeError:$6()}}function q6(){return{localeError:j6()}}function D6(){return{localeError:N6()}}function U6(){return{localeError:L6()}}function z6(){return{localeError:F6()}}function hh(){return new as}function QC(e,t){return new e({type:"string",...Q(t)})}function YC(e,t){return new e({type:"string",coerce:!0,...Q(t)})}function gh(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Q(t)})}function Mu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Q(t)})}function yh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Q(t)})}function _h(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Q(t)})}function vh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Q(t)})}function bh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Q(t)})}function wh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Q(t)})}function Sh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Q(t)})}function kh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Q(t)})}function xh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Q(t)})}function Ch(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Q(t)})}function Th(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Q(t)})}function Ih(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Q(t)})}function Ph(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Q(t)})}function Eh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Q(t)})}function Rh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Q(t)})}function Oh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Q(t)})}function Ah(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Q(t)})}function $h(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Q(t)})}function Mh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Q(t)})}function jh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Q(t)})}function qh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Q(t)})}function eT(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Q(t)})}function tT(e,t){return new e({type:"string",format:"date",check:"string_format",...Q(t)})}function nT(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Q(t)})}function rT(e,t){return new e({type:"string",format:"duration",check:"string_format",...Q(t)})}function iT(e,t){return new e({type:"number",checks:[],...Q(t)})}function oT(e,t){return new e({type:"number",coerce:!0,checks:[],...Q(t)})}function aT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Q(t)})}function sT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...Q(t)})}function dT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...Q(t)})}function uT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...Q(t)})}function lT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...Q(t)})}function cT(e,t){return new e({type:"boolean",...Q(t)})}function pT(e,t){return new e({type:"boolean",coerce:!0,...Q(t)})}function fT(e,t){return new e({type:"bigint",...Q(t)})}function mT(e,t){return new e({type:"bigint",coerce:!0,...Q(t)})}function hT(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...Q(t)})}function gT(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...Q(t)})}function yT(e,t){return new e({type:"symbol",...Q(t)})}function _T(e,t){return new e({type:"undefined",...Q(t)})}function vT(e,t){return new e({type:"null",...Q(t)})}function bT(e){return new e({type:"any"})}function ju(e){return new e({type:"unknown"})}function wT(e,t){return new e({type:"never",...Q(t)})}function ST(e,t){return new e({type:"void",...Q(t)})}function kT(e,t){return new e({type:"date",...Q(t)})}function xT(e,t){return new e({type:"date",coerce:!0,...Q(t)})}function CT(e,t){return new e({type:"nan",...Q(t)})}function ei(e,t){return new rh({check:"less_than",...Q(t),value:e,inclusive:!1})}function xn(e,t){return new rh({check:"less_than",...Q(t),value:e,inclusive:!0})}function ti(e,t){return new ih({check:"greater_than",...Q(t),value:e,inclusive:!1})}function Zt(e,t){return new ih({check:"greater_than",...Q(t),value:e,inclusive:!0})}function TT(e){return ti(0,e)}function IT(e){return ei(0,e)}function PT(e){return xn(0,e)}function ET(e){return Zt(0,e)}function ss(e,t){return new I0({check:"multiple_of",...Q(t),value:e})}function El(e,t){return new R0({check:"max_size",...Q(t),maximum:e})}function ds(e,t){return new O0({check:"min_size",...Q(t),minimum:e})}function Nh(e,t){return new A0({check:"size_equals",...Q(t),size:e})}function Rl(e,t){return new $0({check:"max_length",...Q(t),maximum:e})}function lo(e,t){return new M0({check:"min_length",...Q(t),minimum:e})}function Ol(e,t){return new j0({check:"length_equals",...Q(t),length:e})}function Dh(e,t){return new q0({check:"string_format",format:"regex",...Q(t),pattern:e})}function Lh(e){return new N0({check:"string_format",format:"lowercase",...Q(e)})}function Uh(e){return new D0({check:"string_format",format:"uppercase",...Q(e)})}function Fh(e,t){return new L0({check:"string_format",format:"includes",...Q(t),includes:e})}function zh(e,t){return new U0({check:"string_format",format:"starts_with",...Q(t),prefix:e})}function Bh(e,t){return new F0({check:"string_format",format:"ends_with",...Q(t),suffix:e})}function RT(e,t,n){return new z0({check:"property",property:e,schema:t,...Q(n)})}function Kh(e,t){return new B0({check:"mime_type",mime:e,...Q(t)})}function di(e){return new K0({check:"overwrite",tx:e})}function Jh(e){return di(t=>t.normalize(e))}function Wh(){return di(e=>e.trim())}function Hh(){return di(e=>e.toLowerCase())}function Gh(){return di(e=>e.toUpperCase())}function Vh(e,t,n){return new e({type:"array",element:t,...Q(n)})}function B6(e,t,n){return new e({type:"union",options:t,...Q(n)})}function K6(e,t,n,i){return new e({type:"union",options:n,discriminator:t,...Q(i)})}function J6(e,t,n){return new e({type:"intersection",left:t,right:n})}function OT(e,t,n,i){let r=n instanceof ve;return new e({type:"tuple",items:t,rest:r?n:null,...Q(r?i:n)})}function W6(e,t,n,i){return new e({type:"record",keyType:t,valueType:n,...Q(i)})}function H6(e,t,n,i){return new e({type:"map",keyType:t,valueType:n,...Q(i)})}function G6(e,t,n){return new e({type:"set",valueType:t,...Q(n)})}function V6(e,t,n){let i=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new e({type:"enum",entries:i,...Q(n)})}function Z6(e,t,n){return new e({type:"enum",entries:t,...Q(n)})}function Q6(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...Q(n)})}function AT(e,t){return new e({type:"file",...Q(t)})}function Y6(e,t){return new e({type:"transform",transform:t})}function X6(e,t){return new e({type:"optional",innerType:t})}function eW(e,t){return new e({type:"nullable",innerType:t})}function tW(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return typeof n=="function"?n():n}})}function nW(e,t,n){return new e({type:"nonoptional",innerType:t,...Q(n)})}function rW(e,t){return new e({type:"success",innerType:t})}function iW(e,t,n){return new e({type:"catch",innerType:t,catchValue:typeof n=="function"?n:()=>n})}function oW(e,t,n){return new e({type:"pipe",in:t,out:n})}function aW(e,t){return new e({type:"readonly",innerType:t})}function sW(e,t,n){return new e({type:"template_literal",parts:t,...Q(n)})}function dW(e,t){return new e({type:"lazy",getter:t})}function uW(e,t){return new e({type:"promise",innerType:t})}function $T(e,t,n){let i=Q(n);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function MT(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Q(n)})}function jT(e,t){let n=Q(t),i=n.truthy??["true","1","yes","on","y","enabled"],r=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(i=i.map(m=>typeof m=="string"?m.toLowerCase():m),r=r.map(m=>typeof m=="string"?m.toLowerCase():m));let o=new Set(i),a=new Set(r),s=e.Pipe??fh,d=e.Boolean??sh,u=e.String??Ss,l=new(e.Transform??ph)({type:"transform",transform:(m,f)=>{let h=m;return n.case!=="sensitive"&&(h=h.toLowerCase()),o.has(h)?!0:a.has(h)?!1:(f.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...a],input:f.value,inst:l}),{})},error:n.error}),p=new s({type:"pipe",in:new u({type:"string",error:n.error}),out:l,error:n.error});return new s({type:"pipe",in:p,out:new d({type:"boolean",error:n.error}),error:n.error})}function qT(e,t,n,i={}){let r=Q(i),o={...Q(i),check:"string_format",type:"string",format:t,fn:typeof n=="function"?n:a=>n.test(a),...r};return n instanceof RegExp&&(o.pattern=n),new e(o)}function NT(e){return new qu({type:"function",input:Array.isArray(e?.input)?OT(Pl,e?.input):e?.input??Vh(uh,ju($u)),output:e?.output??ju($u)})}function Zh(e,t){if(e instanceof as){let i=new us(t),r={};for(let s of e._idmap.entries()){let[d,u]=s;i.process(u)}let o={},a={registry:e,uri:t?.uri||(s=>s),defs:r};for(let s of e._idmap.entries()){let[d,u]=s;o[d]=i.emit(u,{...t,external:a})}if(Object.keys(r).length>0){let s=i.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[s]:r}}return{schemas:o}}let n=new us(t);return n.process(e),n.emit(e,t)}function pt(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let i=e._zod.def;switch(i.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return pt(i.element,n);case"object":{for(let r in i.shape)if(pt(i.shape[r],n))return!0;return!1}case"union":{for(let r of i.options)if(pt(r,n))return!0;return!1}case"intersection":return pt(i.left,n)||pt(i.right,n);case"tuple":{for(let r of i.items)if(pt(r,n))return!0;return!!(i.rest&&pt(i.rest,n))}case"record":return pt(i.keyType,n)||pt(i.valueType,n);case"map":return pt(i.keyType,n)||pt(i.valueType,n);case"set":return pt(i.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return pt(i.innerType,n);case"lazy":return pt(i.getter(),n);case"default":return pt(i.innerType,n);case"prefault":return pt(i.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return pt(i.in,n)||pt(i.out,n);case"success":return!1;case"catch":return!1;default:}throw Error(`Unknown schema type: ${i.type}`)}function Rw(e,t){let n={type:"object",get shape(){return Ee.assignProp(this,"shape",{...e}),this.shape},...Ee.normalizeParams(t)};return new pW(n)}function Un(e){return!!e._zod}function Mi(e){let t=Object.values(e);if(t.length===0)return Rw({});let n=t.every(Un),i=t.every(r=>!Un(r));if(n)return Rw(e);if(i)return zK(e);throw Error("Mixed Zod versions detected in object shape.")}function $a(e,t){return Un(e)?Tl(e,t):e.safeParse(t)}async function xp(e,t){return Un(e)?await Il(e,t):await e.safeParseAsync(t)}function ks(e){if(!e)return;let t;if(Un(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function ma(e){if(e){if(typeof e=="object"){let t=e,n=e;if(!t._def&&!n._zod){let i=Object.values(e);if(i.length>0&&i.every(r=>typeof r=="object"&&r!==null&&(r._def!==void 0||r._zod!==void 0||typeof r.parse=="function")))return Mi(e)}}if(Un(e)){let t=e._zod?.def;if(t&&(t.type==="object"||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Cp(e){if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t=="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function fW(e){return e.description}function mW(e){if(Un(e))return e._zod?.def?.type==="optional";let t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function DT(e){if(Un(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}function LT(e){return eT(Yh,e)}function UT(e){return tT(Xh,e)}function FT(e){return nT(eg,e)}function zT(e){return rT(tg,e)}function U(e){return QC(Al,e)}function gW(e){return gh(rg,e)}function yW(e){return Mu(Nu,e)}function _W(e){return yh(nr,e)}function vW(e){return _h(nr,e)}function bW(e){return vh(nr,e)}function wW(e){return bh(nr,e)}function SW(e){return wh(ig,e)}function kW(e){return Sh(og,e)}function xW(e){return kh(ag,e)}function CW(e){return xh(sg,e)}function TW(e){return Ch(dg,e)}function IW(e){return Th(ug,e)}function PW(e){return Ih(lg,e)}function EW(e){return Ph(cg,e)}function RW(e){return Eh(pg,e)}function OW(e){return Rh(fg,e)}function AW(e){return Oh(mg,e)}function $W(e){return Ah(hg,e)}function MW(e){return $h(gg,e)}function jW(e){return Mh(yg,e)}function qW(e){return jh(_g,e)}function NW(e){return qh(vg,e)}function DW(e,t,n={}){return qT(GT,e,t,n)}function je(e){return iT($l,e)}function If(e){return aT(bo,e)}function LW(e){return sT(bo,e)}function UW(e){return dT(bo,e)}function FW(e){return uT(bo,e)}function zW(e){return lT(bo,e)}function ft(e){return cT(Ml,e)}function BW(e){return fT(jl,e)}function KW(e){return hT(bg,e)}function JW(e){return gT(bg,e)}function WW(e){return yT(VT,e)}function HW(e){return _T(ZT,e)}function wg(e){return vT(QT,e)}function GW(){return bT(YT)}function nt(){return ju(XT)}function ql(e){return wT(eI,e)}function VW(e){return ST(tI,e)}function ZW(e){return kT(Sg,e)}function Re(e,t){return Vh(nI,e,t)}function QW(e){let t=e._zod.def.shape;return ce(Object.keys(t))}function oe(e,t){let n={type:"object",get shape(){return Ee.assignProp(this,"shape",{...e}),this.shape},...Ee.normalizeParams(t)};return new Nl(n)}function YW(e,t){return new Nl({type:"object",get shape(){return Ee.assignProp(this,"shape",{...e}),this.shape},catchall:ql(),...Ee.normalizeParams(t)})}function Et(e,t){return new Nl({type:"object",get shape(){return Ee.assignProp(this,"shape",{...e}),this.shape},catchall:nt(),...Ee.normalizeParams(t)})}function Be(e,t){return new kg({type:"union",options:e,...Ee.normalizeParams(t)})}function xg(e,t,n){return new rI({type:"union",options:t,discriminator:e,...Ee.normalizeParams(n)})}function Dl(e,t){return new iI({type:"intersection",left:e,right:t})}function XW(e,t,n){let i=t instanceof ve,r=i?n:t;return new oI({type:"tuple",items:e,rest:i?t:null,...Ee.normalizeParams(r)})}function ze(e,t,n){return new Cg({type:"record",keyType:e,valueType:t,...Ee.normalizeParams(n)})}function eH(e,t,n){return new Cg({type:"record",keyType:Be([e,ql()]),valueType:t,...Ee.normalizeParams(n)})}function tH(e,t,n){return new aI({type:"map",keyType:e,valueType:t,...Ee.normalizeParams(n)})}function nH(e,t){return new sI({type:"set",valueType:e,...Ee.normalizeParams(t)})}function Lt(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new ls({type:"enum",entries:n,...Ee.normalizeParams(t)})}function rH(e,t){return new ls({type:"enum",entries:e,...Ee.normalizeParams(t)})}function ce(e,t){return new dI({type:"literal",values:Array.isArray(e)?e:[e],...Ee.normalizeParams(t)})}function iH(e){return AT(uI,e)}function Ig(e){return new Tg({type:"transform",transform:e})}function He(e){return new Pg({type:"optional",innerType:e})}function Du(e){return new lI({type:"nullable",innerType:e})}function oH(e){return He(Du(e))}function pI(e,t){return new cI({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}function mI(e,t){return new fI({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}function hI(e,t){return new Eg({type:"nonoptional",innerType:e,...Ee.normalizeParams(t)})}function aH(e){return new gI({type:"success",innerType:e})}function _I(e,t){return new yI({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}function sH(e){return CT(vI,e)}function Lu(e,t){return new Rg({type:"pipe",in:e,out:t})}function wI(e){return new bI({type:"readonly",innerType:e})}function dH(e,t){return new SI({type:"template_literal",parts:e,...Ee.normalizeParams(t)})}function xI(e){return new kI({type:"lazy",getter:e})}function uH(e){return new CI({type:"promise",innerType:e})}function TI(e,t){let n=new at({check:"custom",...Ee.normalizeParams(t)});return n._zod.check=e,n}function II(e,t){return $T(Ll,e??(()=>!0),t)}function PI(e,t={}){return MT(Ll,e,t)}function EI(e,t){let n=TI(i=>(i.addIssue=r=>{if(typeof r=="string")i.issues.push(Ee.issue(r,i.value,n._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=i.value),o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),i.issues.push(Ee.issue(o))}},e(i.value,i)),t);return n}function lH(e,t={error:`Input not instance of ${e.name}`}){let n=new Ll({type:"custom",check:"custom",fn:i=>i instanceof e,abort:!0,...Ee.normalizeParams(t)});return n._zod.bag.Class=e,n}function pH(e){let t=xI(()=>Be([U(e),je(),ft(),wg(),Re(t),ze(U(),t)]));return t}function Og(e,t){return Lu(Ig(e),t)}function mH(e){At({customError:e})}function hH(){return At().customError}function gH(e){return YC(Al,e)}function yH(e){return oT($l,e)}function _H(e){return pT(Ml,e)}function vH(e){return mT(jl,e)}function bH(e){return xT(Sg,e)}function V9(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Z9(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Fr(e){return e==="completed"||e==="failed"||e==="cancelled"}function GI(e,t,n,i){i?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function De(e,t,n,i,r){e[t]=n,GI(e,t,i,r)}function Dt(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?VI(t,e.currentPath):t.join("/")}}function iG(e,t){let n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==V.ZodAny&&(n.items=Me(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&De(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&De(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(De(n,"minItems",e.exactLength.value,e.exactLength.message,t),De(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function oG(e,t){let n={type:"integer",format:"int64"};if(!e.checks)return n;for(let i of e.checks)switch(i.kind){case"min":t.target==="jsonSchema7"?i.inclusive?De(n,"minimum",i.value,i.message,t):De(n,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(n.exclusiveMinimum=!0),De(n,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?De(n,"maximum",i.value,i.message,t):De(n,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(n.exclusiveMaximum=!0),De(n,"maximum",i.value,i.message,t));break;case"multipleOf":De(n,"multipleOf",i.value,i.message,t);break}return n}function aG(){return{type:"boolean"}}function ZI(e,t){return Me(e.type._def,t)}function QI(e,t,n){let i=n??t.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((r,o)=>QI(e,t,r))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return dG(e,t)}}function uG(e,t){return{...Me(e.innerType._def,t),default:e.defaultValue()}}function lG(e,t){return t.effectStrategy==="input"?Me(e.schema._def,t):Dt(t)}function cG(e){return{type:"string",enum:Array.from(e.values)}}function fG(e,t){let n=[Me(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Me(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),i=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,r=[];return n.forEach(o=>{if(pG(o))r.push(...o.allOf),o.unevaluatedProperties===void 0&&(i=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:s,...d}=o;a=d}else i=void 0;r.push(a)}}),r.length?{allOf:r,...i}:void 0}function mG(e,t){let n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}function YI(e,t){let n={type:"string"};if(e.checks)for(let i of e.checks)switch(i.kind){case"min":De(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value,i.message,t);break;case"max":De(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Sn(n,"email",i.message,t);break;case"format:idn-email":Sn(n,"idn-email",i.message,t);break;case"pattern:zod":It(n,wn.email,i.message,t);break}break;case"url":Sn(n,"uri",i.message,t);break;case"uuid":Sn(n,"uuid",i.message,t);break;case"regex":It(n,i.regex,i.message,t);break;case"cuid":It(n,wn.cuid,i.message,t);break;case"cuid2":It(n,wn.cuid2,i.message,t);break;case"startsWith":It(n,RegExp(`^${Ip(i.value,t)}`),i.message,t);break;case"endsWith":It(n,RegExp(`${Ip(i.value,t)}$`),i.message,t);break;case"datetime":Sn(n,"date-time",i.message,t);break;case"date":Sn(n,"date",i.message,t);break;case"time":Sn(n,"time",i.message,t);break;case"duration":Sn(n,"duration",i.message,t);break;case"length":De(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value,i.message,t),De(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case"includes":{It(n,RegExp(Ip(i.value,t)),i.message,t);break}case"ip":{i.version!=="v6"&&Sn(n,"ipv4",i.message,t),i.version!=="v4"&&Sn(n,"ipv6",i.message,t);break}case"base64url":It(n,wn.base64url,i.message,t);break;case"jwt":It(n,wn.jwt,i.message,t);break;case"cidr":{i.version!=="v6"&&It(n,wn.ipv4Cidr,i.message,t),i.version!=="v4"&&It(n,wn.ipv6Cidr,i.message,t);break}case"emoji":It(n,wn.emoji(),i.message,t);break;case"ulid":{It(n,wn.ulid,i.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Sn(n,"binary",i.message,t);break}case"contentEncoding:base64":{De(n,"contentEncoding","base64",i.message,t);break}case"pattern:zod":{It(n,wn.base64,i.message,t);break}}break}case"nanoid":It(n,wn.nanoid,i.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Ip(e,t){return t.patternStrategy==="escape"?gG(e):e}function gG(e){let t="";for(let n=0;n<e.length;n++)hG.has(e[n])||(t+="\\"),t+=e[n];return t}function Sn(e,t,n,i){e.format||e.anyOf?.some(r=>r.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&i.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&i.errorMessages&&{errorMessage:{format:n}}})):De(e,"format",t,n,i)}function It(e,t,n,i){e.pattern||e.allOf?.some(r=>r.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&i.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:$w(t,i),...n&&i.errorMessages&&{errorMessage:{pattern:n}}})):De(e,"pattern",$w(t,i),n,i)}function $w(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},i=n.i?e.source.toLowerCase():e.source,r="",o=!1,a=!1,s=!1;for(let d=0;d<i.length;d++){if(o){r+=i[d],o=!1;continue}if(n.i){if(a){if(i[d].match(/[a-z]/)){s?(r+=i[d],r+=`${i[d-2]}-${i[d]}`.toUpperCase(),s=!1):i[d+1]==="-"&&i[d+2]?.match(/[a-z]/)?(r+=i[d],s=!0):r+=`${i[d]}${i[d].toUpperCase()}`;continue}}else if(i[d].match(/[a-z]/)){r+=`[${i[d]}${i[d].toUpperCase()}]`;continue}}if(n.m){if(i[d]==="^"){r+=`(^|(?<=[\r
25
+ ]))`;continue}else if(i[d]==="$"){r+=`($|(?=[\r
26
+ ]))`;continue}}if(n.s&&i[d]==="."){r+=a?`${i[d]}\r
27
+ `:`[${i[d]}\r
28
+ ]`;continue}r+=i[d],i[d]==="\\"?o=!0:a&&i[d]==="]"?a=!1:!a&&i[d]==="["&&(a=!0)}try{new RegExp(r)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return r}function XI(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===V.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((i,r)=>({...i,[r]:Me(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??Dt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Me(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===V.ZodString&&e.keyType._def.checks?.length){let{type:i,...r}=YI(e.keyType._def,t);return{...n,propertyNames:r}}else{if(e.keyType?._def.typeName===V.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===V.ZodBranded&&e.keyType._def.type._def.typeName===V.ZodString&&e.keyType._def.type._def.checks?.length){let{type:i,...r}=ZI(e.keyType._def,t);return{...n,propertyNames:r}}}return n}function yG(e,t){if(t.mapStrategy==="record")return XI(e,t);let n=Me(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Dt(t),i=Me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Dt(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,i],minItems:2,maxItems:2}}}function _G(e){let t=e.values,n=Object.keys(e.values).filter(r=>typeof t[t[r]]!="number").map(r=>t[r]),i=Array.from(new Set(n.map(r=>typeof r)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function vG(e){return e.target==="openAi"?void 0:{not:Dt({...e,currentPath:[...e.currentPath,"not"]})}}function bG(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}function wG(e,t){if(t.target==="openApi3")return Mw(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(i=>i._def.typeName in Ju&&(!i._def.checks||!i._def.checks.length))){let i=n.reduce((r,o)=>{let a=Ju[o._def.typeName];return a&&!r.includes(a)?[...r,a]:r},[]);return{type:i.length>1?i:i[0]}}else if(n.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){let i=n.reduce((r,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];case"bigint":return[...r,"integer"];case"object":if(o._def.value===null)return[...r,"null"];default:return r}},[]);if(i.length===n.length){let r=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:r.length>1?r:r[0],enum:n.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(n.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((i,r)=>[...i,...r._def.values.filter(o=>!i.includes(o))],[])};return Mw(e,t)}function SG(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ju[e.innerType._def.typeName],nullable:!0}:{type:[Ju[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let i=Me(e.innerType._def,{...t,currentPath:[...t.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}let n=Me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function kG(e,t){let n={type:"number"};if(!e.checks)return n;for(let i of e.checks)switch(i.kind){case"int":n.type="integer",GI(n,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?De(n,"minimum",i.value,i.message,t):De(n,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(n.exclusiveMinimum=!0),De(n,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?De(n,"maximum",i.value,i.message,t):De(n,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(n.exclusiveMaximum=!0),De(n,"maximum",i.value,i.message,t));break;case"multipleOf":De(n,"multipleOf",i.value,i.message,t);break}return n}function xG(e,t){let n=t.target==="openAi",i={type:"object",properties:{}},r=[],o=e.shape();for(let s in o){let d=o[s];if(d===void 0||d._def===void 0)continue;let u=TG(d);u&&n&&(d._def.typeName==="ZodOptional"&&(d=d._def.innerType),d.isNullable()||(d=d.nullable()),u=!1);let l=Me(d._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,!u&&r.push(s))}r.length&&(i.required=r);let a=CG(e,t);return a!==void 0&&(i.additionalProperties=a),i}function CG(e,t){if(e.catchall._def.typeName!=="ZodNever")return Me(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function TG(e){try{return e.isOptional()}catch{return!0}}function EG(e,t){return Me(e.type._def,t)}function RG(e,t){let n={type:"array",uniqueItems:!0,items:Me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&De(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&De(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function OG(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,i)=>Me(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[]),additionalItems:Me(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,i)=>Me(n._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[])}}function AG(e){return{not:Dt(e)}}function $G(e){return Dt(e)}function Me(e,t,n=!1){let i=t.seen.get(e);if(t.override){let s=t.override?.(e,t,i,n);if(s!==tG)return s}if(i&&!n){let s=qG(i,t);if(s!==void 0)return s}let r={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,r);let o=jG(e,e.typeName,t),a=typeof o=="function"?Me(o(),t):o;if(a&&NG(e,t,a),t.postProcess){let s=t.postProcess(a,e,t);return r.jsonSchema=a,s}return r.jsonSchema=a,a}function LG(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function jw(e,t){return Un(e)?Zh(e,{target:LG(t?.target),io:t?.pipeStrategy??"input"}):DG(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function qw(e){let t=ks(e)?.method;if(!t)throw Error("Schema is missing a method literal");let n=DT(t);if(typeof n!="string")throw Error("Schema method literal must be a string");return n}function Nw(e,t){let n=$a(e,t);if(!n.success)throw n.error;return n.data}function Dw(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function FG(e,t){let n={...e};for(let i in t){let r=i,o=t[r];if(o===void 0)continue;let a=n[r];Dw(a)&&Dw(o)?n[r]={...a,...o}:n[r]=o}return n}function KG(){let e=new zG.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return BG.default(e),e}function JG(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function WG(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}function Lw(e){return!!e&&typeof e=="object"&&eP in e}function HG(e){return e[eP]?.complete}function VG(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!GG.test(e)){let n=e.split("").filter(i=>!/[A-Za-z0-9._-]/.test(i)).filter((i,r,o)=>o.indexOf(i)===r);return t.push(`Tool name contains invalid characters: ${n.map(i=>`"${i}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function ZG(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let n of t)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Fw(e){let t=VG(e);return ZG(e,t.warnings),t.isValid}function tP(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function nP(e){return"_def"in e||"_zod"in e||tP(e)}function zf(e){return typeof e!="object"||e===null||nP(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(tP)}function zw(e){if(e){if(zf(e))return Mi(e);if(!nP(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function YG(e){let t=ks(e);return t?Object.entries(t).map(([n,i])=>{let r=fW(i),o=mW(i);return{name:n,description:r,required:!o}}):[]}function pr(e){let t=ks(e)?.method;if(!t)throw Error("Schema is missing a method literal");let n=DT(t);if(typeof n=="string")return n;throw Error("Schema method literal must be a string")}function Bw(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}function XG(e,t,n,i,r){let o={};return r?.searchHint&&(o["anthropic/searchHint"]=r.searchHint),r?.alwaysLoad&&(o["anthropic/alwaysLoad"]=!0),{name:e,description:t,inputSchema:n,handler:i,annotations:r?.annotations,_meta:Object.keys(o).length>0?o:void 0}}function eV(e){let t=new Ff({name:e.name,version:e.version??"1.0.0"},{capabilities:{tools:e.tools?{}:void 0},instructions:e.instructions});return e.tools&&e.tools.forEach(n=>{for(let i of Object.values(n.inputSchema)){if(!tV(i))continue;let r=i.description;r&&!tr.has(i)&&tr.add(i,{description:r})}t.registerTool(n.name,{description:n.description,inputSchema:n.inputSchema,annotations:n.annotations,_meta:e.alwaysLoad?{"anthropic/alwaysLoad":!0,...n._meta}:n._meta},n.handler)}),{type:"sdk",name:e.name,instance:t}}function tV(e){return typeof e=="object"&&e!==null&&"_zod"in e}function J(e){let t;return()=>t??=e()}function rV(e){if(e.startsWith("cc://")){let i=e.slice(5),r=new URL(`http://${i}`),o=r.pathname.slice(1)||void 0;return{serverUrl:`http://${r.host}`,authToken:o}}if(e.startsWith("cc+unix://"))throw new sn("Unix socket connect (cc+unix://) is not supported by the SDK transport");let t=/^https?:\/\//i.test(e)?e:`http://${e}`,n=new URL(t);return{serverUrl:`${n.protocol}//${n.host}`,authToken:void 0}}async function iV(e){let t={"content-type":"application/json"};e.authToken&&(t.authorization=`Bearer ${e.authToken}`);let n={};e.cwd&&(n.cwd=e.cwd),e.sessionKey&&(n.session_key=e.sessionKey),e.permissionMode&&(n.permission_mode=e.permissionMode);let i;try{i=await fetch(`${e.serverUrl}/sessions`,{method:"POST",headers:t,body:ut(n)})}catch(o){throw new sn(`Failed to connect to server at ${e.serverUrl}: ${o instanceof Error?o.message:String(o)}`,"session_create_failed")}if(!i.ok){let o=await i.text().catch(()=>"");throw new sn(`Failed to create session: ${i.status} ${i.statusText}${o?` \u2014 ${o}`:""}`,"session_create_failed")}let r=nV().safeParse(await i.json());if(!r.success)throw new sn(`Invalid session response: ${r.error.message}`,"session_create_invalid_response");return{sessionId:r.data.session_id,wsUrl:r.data.ws_url,workDir:r.data.work_dir}}async function Jw(e,t,n){let i={};n&&(i.authorization=`Bearer ${n}`);try{await fetch(`${e}/sessions/${t}`,{method:"DELETE",headers:i})}catch{}}function rP(){}async function sV(e,t){let n=Yt();try{await n.appendFile(e,t)}catch{await n.mkdir(aV(e)).catch(rP),await n.appendFile(e,t)}}function Jf(e,t,n){let i=uV();if(!i)return;let r={timestamp:new Date().toISOString(),level:e,event:t,data:n??{}},o=ut(r)+`
29
+ `;Kf=Kf.then(sV.bind(null,i,o)).catch(rP),!Ww&&(Ww=!0,nx(dV))}function dV(){return Kf}function uV(){return process.env.CLAUDE_CODE_DIAGNOSTICS_FILE}function lV(e,t,n){let i=e.statSync(t);if(i.isDirectory())throw Object.assign(Error("EISDIR: illegal operation on a directory, read"),{code:"EISDIR",errno:-21,syscall:"read",path:t});if(!i.isFile())throw Object.assign(Error("Not a regular file (device, FIFO, or socket)"),{code:"ERR_NOT_REGULAR_FILE",path:t});if(n!==void 0&&i.size>n)throw Object.assign(Error("File exceeds maxBytes limit"),{code:"ERR_FILE_TOO_LARGE",path:t,size:i.size,maxBytes:n})}function cV(e){let{buffer:t,bytesRead:n}=Yt().readSync(e,{length:4096});return n===0?"utf8":n>=2&&t[0]===255&&t[1]===254?"utf16le":(n>=3&&t[0]===239&&t[1]===187&&t[2]===191,"utf8")}function pV(e){let t=0,n=0;for(let i=0;i<e.length;i++)e[i]===`
30
+ `&&(i>0&&e[i-1]==="\r"?t++:n++);return t>n?"CRLF":"LF"}function fV(e,t){let n=Yt(),{resolvedPath:i,isSymlink:r}=rx(n,e);r&&qe(`Reading through symlink: ${e} -> ${i}`),lV(n,i,t);let o=cV(i),a=n.readFileSync(i,{encoding:o}),s=pV(a.slice(0,4096));return{content:a.replaceAll(`\r
31
+ `,`
32
+ `),encoding:o,lineEndings:s}}function Bl(e,t){return fV(e,t).content}function iP(e){return e.startsWith("\uFEFF")?e.slice(1):e}function yV(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),Wf.platform==="darwin"?mV(e):Wf.platform==="win32"?hV(e):gV(e)}function _V(){return process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC?"essential-traffic":process.env.DISABLE_TELEMETRY||kt(process.env.DO_NOT_TRACK)?"no-telemetry":"default"}function vV(){return _V()==="essential-traffic"}function wV(e){Pp.length>=bV&&Pp.shift(),Pp.push(e)}function aP(e){let t=hs(e);try{if(kt(process.env.CLAUDE_CODE_USE_BEDROCK)||kt(process.env.CLAUDE_CODE_USE_VERTEX)||kt(process.env.CLAUDE_CODE_USE_FOUNDRY)||kt(process.env.CLAUDE_CODE_USE_ANTHROPIC_AWS)||kt(process.env.CLAUDE_CODE_USE_MANTLE)||process.env.DISABLE_ERROR_REPORTING||vV())return;let n={error:t.stack||t.message,timestamp:new Date().toISOString()};if(wV(n),Yw===null){SV.push({type:"error",error:t});return}Yw.logError(t)}catch{}}function xV(e,t,n=100){let i=new Vf({max:n}),r=(...o)=>{let a=t(...o),s=i.get(a);if(s!==void 0)return s;let d=e(...o);return i.set(a,d),d};return r.cache={clear:()=>i.clear(),size:()=>i.size,delete:o=>i.delete(o),get:o=>i.peek(o),has:o=>i.has(o)},r}function lP(e,t){try{return{ok:!0,value:JSON.parse(iP(e))}}catch(n){return t&&aP(fD(n,`safeParseJSON: invalid JSON (${n instanceof Error?n.constructor.name:typeof n}, ${e.length} bytes)`)),{ok:!1}}}function PV(e,t,n){(n!==void 0&&!ms(e[t],n)||n===void 0&&!(t in e))&&Tm(e,t,n)}function EV(e){return function(t,n,i){for(var r=-1,o=Object(t),a=i(t),s=a.length;s--;){var d=a[e?s:++r];if(n(o[d],d,o)===!1)break}return t}}function $V(e){return Sr(e)&&gl(e)}function UV(e){if(!Sr(e)||ri(e)!=jV)return!1;var t=Am(e);if(t===null)return!0;var n=DV.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&pP.call(n)==LV}function zV(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}function BV(e){return eL(e,Rm(e))}function JV(e,t,n,i,r,o,a){var s=Qf(e,n),d=Qf(t,n),u=a.get(d);if(u){Zf(e,n,u);return}var l=o?o(s,d,n+"",e,t,a):void 0,p=l===void 0;if(p){var m=pn(d),f=!m&&Ba(d),h=!m&&!f&&Pm(d);l=d,m||f||h?pn(s)?l=s:MV(s)?l=wU(s):f?(p=!1,l=Fk(d,!0)):h?(p=!1,l=QU(d,!0)):l=[]:FV(d)||za(d)?(l=s,za(s)?l=KV(s):(!Dn(s)||ym(s))&&(l=tF(d))):p=!1}p&&(a.set(d,l),r(l,d,i,o,a),a.delete(d)),Zf(e,n,l)}function fP(e,t,n,i,r){e!==t&&AV(t,function(o,a){if(r||(r=new Ea),Dn(o))WV(e,t,a,n,fP,i,r);else{var s=i?i(Qf(e,a),o,a+"",e,t,r):void 0;s===void 0&&(s=o),Zf(e,a,s)}},Rm)}function GV(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function ZV(e,t,n){return t=tS(t===void 0?e.length-1:t,0),function(){for(var i=arguments,r=-1,o=tS(i.length-t,0),a=Array(o);++r<o;)a[r]=i[t+r];r=-1;for(var s=Array(t+1);++r<t;)s[r]=i[r];return s[t]=n(a),VV(e,this,s)}}function QV(e){return function(){return e}}function i5(e){var t=0,n=0;return function(){var i=r5(),r=n5-(i-n);if(n=i,r>0){if(++t>=t5)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function s5(e,t){return hP(mP(e,t,qm),e+"")}function u5(e,t,n){if(!Dn(n))return!1;var i=typeof t;return(i=="number"?gl(n)&&hl(t,n.length):i=="string"&&t in n)?ms(n[t],e):!1}function c5(e){return d5(function(t,n){var i=-1,r=n.length,o=r>1?n[r-1]:void 0,a=r>2?n[2]:void 0;for(o=e.length>3&&typeof o=="function"?(r--,o):void 0,a&&l5(n[0],n[1],a)&&(o=r<3?void 0:o,r=1),t=Object(t);++i<r;){var s=n[i];s&&e(t,s,i,o)}return t})}function m5(e,t,n,i){if(!Dn(e))return e;t=yl(t,e);for(var r=-1,o=t.length,a=o-1,s=e;s!=null&&++r<o;){var d=gs(t[r]),u=n;if(d==="__proto__"||d==="constructor"||d==="prototype")return e;if(r!=a){var l=s[d];u=i?i(l,d,s):void 0,u===void 0&&(u=Dn(l)?l:hl(t[r+1])?[]:{})}$k(s,d,u),s=s[d]}return e}function g5(e,t,n){for(var i=-1,r=t.length,o={};++i<r;){var a=t[i],s=jm(e,a);n(s,a)&&h5(o,yl(a,e),s)}return o}function y5(e,t){return gP(e,t,function(n,i){return Yk(e,i)})}function v5(e){return pn(e)||za(e)||!!(nS&&e&&e[nS])}function yP(e,t,n,i,r){var o=-1,a=e.length;for(n||(n=b5),r||(r=[]);++o<a;){var s=e[o];t>0&&n(s)?t>1?yP(s,t-1,n,i,r):Om(r,s):i||(r[r.length]=s)}return r}function S5(e){var t=e==null?0:e.length;return t?w5(e,1):[]}function x5(e){return hP(mP(e,void 0,k5),e+"")}function E5(e){if(typeof e!="function")throw TypeError(P5);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}function O5(e,t){if(e==null)return{};var n=Zk(qU(e),function(i){return[i]});return t=Xk(t),gP(e,n,function(i,r){return t(i,r[0])})}function $5(e,t){return A5(e,R5(Xk(t)))}function F5(){return void 0??j5(yo(),D5)}function z5(){try{let e=Bl(F5()),t=Rn(iP(e));return!t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}function K5(e){if(!e?.env)return e;let t=M5(e.env,(n,i)=>B5.has(i.toUpperCase()));return{...e,env:t}}function J5(){if(!void 0&&L5!==!0)return null;if(Rp)return Rp;let e=z5();return e?(Rp=e,Lm(),e):null}function W5(){let e=J5();return e===U5||void 0?e:K5(e)}function wP(){if(process.platform!=="linux")return!1;if(process.env.WSL_DISTRO_NAME)return!0;try{let e=CM("fs").readFileSync("/proc/version","utf8").toLowerCase();return e.includes("microsoft")||e.includes("wsl")}catch{return!1}}function Y5(){let e="";try{e=G5().username}catch{}let t=[];return e&&t.push({path:`/Library/Managed Preferences/${e}/${rS}.plist`,label:"per-user managed preferences"}),t.push({path:`/Library/Managed Preferences/${rS}.plist`,label:"device-level managed preferences"}),t}function l3(){let e=c.object({type:c.literal("command").describe("Shell command hook type"),command:c.string().describe("Shell command to execute"),args:c.array(c.string()).optional().describe("Argument list for exec form. When present, `command` is resolved as an executable and spawned directly with these arguments \u2014 no shell. Path placeholders like ${CLAUDE_PLUGIN_ROOT} are substituted per-element as plain strings, so paths with quotes, $, or backticks never reach a shell parser. When absent, `command` runs through a shell (bash on POSIX, PowerShell on Windows without Git Bash)."),if:ga(),shell:c.enum(u3).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash (powershell on Windows without Git Bash)."),timeout:c.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:c.string().optional().describe("Custom status message to display in spinner while hook runs"),once:c.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:c.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:c.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async."),rewakeMessage:c.string().min(1).optional().describe("@internal Custom prefix for the system-reminder shown to the model when an asyncRewake hook exits with code 2. The hook output is appended after this prefix."),rewakeSummary:c.string().min(1).optional().describe('@internal One-line summary shown to the user in the terminal when an asyncRewake hook exits with code 2. Defaults to "Stop hook feedback".')}),t=c.object({type:c.literal("prompt").describe("LLM prompt hook type"),prompt:c.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:ga(),timeout:c.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:c.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-5"). If not specified, uses the default small fast model.'),continueOnBlock:c.boolean().optional().describe(`Sets the continue value for the decision:"block" produced when ok is false. Default false (turn ends). Whether continue:true lets the turn proceed depends on the event's decision:"block" semantics. On PostToolUse, the reason is fed back to Claude and the turn continues.`),statusMessage:c.string().optional().describe("Custom status message to display in spinner while hook runs"),once:c.boolean().optional().describe("If true, hook runs once and is removed after execution")}),n=c.object({type:c.literal("mcp_tool").describe("MCP tool hook type"),server:c.string().describe("Name of an already-configured MCP server to invoke"),tool:c.string().describe("Name of the tool on that server to call"),input:c.record(c.string(),c.unknown()).optional().describe('Arguments passed to the MCP tool. String values support ${path} interpolation from the hook input JSON (e.g. "${tool_input.file_path}").'),if:ga(),timeout:c.number().positive().optional().describe("Timeout in seconds for this specific tool call"),statusMessage:c.string().optional().describe("Custom status message to display in spinner while hook runs"),once:c.boolean().optional().describe("If true, hook runs once and is removed after execution")}),i=c.object({type:c.literal("http").describe("HTTP hook type"),url:c.string().url().describe("URL to POST the hook input JSON to"),if:ga(),timeout:c.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:c.record(c.string(),c.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:c.array(c.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),statusMessage:c.string().optional().describe("Custom status message to display in spinner while hook runs"),once:c.boolean().optional().describe("If true, hook runs once and is removed after execution")}),r=c.object({type:c.literal("agent").describe("Agentic verifier hook type"),prompt:c.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:ga(),timeout:c.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:c.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-5"). If not specified, uses Haiku.'),statusMessage:c.string().optional().describe("Custom status message to display in spinner while hook runs"),once:c.boolean().optional().describe("If true, hook runs once and is removed after execution")});return{BashCommandHookSchema:e,PromptHookSchema:t,HttpHookSchema:i,AgentHookSchema:r,McpToolHookSchema:n}}function T3(e){return IP.has(e.toLowerCase())?!1:C3.test(e)?!0:x3.test(e)}function G3(e){let t=c.record(c.string(),c.unknown()).safeParse(e);if(!t.success)return;let n=Object.create(null);for(let[i,r]of Object.entries(t.data)){let o=H3().safeParse(r);J3.test(i)&&o.success&&(n[i]=o.data)}return Object.keys(n).length>0?n:void 0}function iZ(e){let t=nZ();return e.flatMap((n,i)=>{let r=t.safeParse(n);if(r.success)return[r.data];let o=rZ().safeParse(n).data?.name,a=r.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ");return o?(qe(`Stubbing unparseable marketplace plugin entry (${o}): ${a}`,{level:"warn"}),[{name:o,source:{source:"unsupported"},strict:!0}]):(qe(`Dropping unparseable marketplace plugin entry (index ${i}): ${a}`,{level:"warn"}),[])})}function qP(){return fZ.filter(e=>Wl[e].buildGate())}function mZ(e){let t={};for(let n of e)t={...t,...Wl[n].shape()};return t}function hZ(e){let t={};for(let n of e)t={...t,...Wl[n].permissionsShape?.()};return t}function gZ(e){let t=[];for(let n of e)t.push(...Wl[n].permissionModes?.()??[]);return t}function NP(e){let t=e.split("__"),[n,i,...r]=t;if(n!=="mcp"||!i)return null;let o=r.length>0?r.join("__"):void 0;return{serverName:i,toolName:o}}function Ei(e){return Object.hasOwn(uS,e)?uS[e]:e}function lS(e){return e.includes("*")}function yZ(e){return e.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function _Z(e){let t=vZ(e,"(");if(t===-1)return{toolName:Ei(e)};let n=bZ(e,")");if(n===-1||n<=t)return{toolName:Ei(e)};if(n!==e.length-1)return{toolName:Ei(e)};let i=e.substring(0,t),r=e.substring(t+1,n);if(!i)return{toolName:Ei(e)};if(r===""||r==="*")return{toolName:Ei(i)};let o=yZ(r);return{toolName:Ei(i),ruleContent:o}}function vZ(e,t){for(let n=0;n<e.length;n++)if(e[n]===t){let i=0,r=n-1;for(;r>=0&&e[r]==="\\";)i++,r--;if(i%2===0)return n}return-1}function bZ(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]===t){let i=0,r=n-1;for(;r>=0&&e[r]==="\\";)i++,r--;if(i%2===0)return n}return-1}function wZ(e){return Zu.filePatternTools.includes(e)}function SZ(e){return Zu.bashPrefixTools.includes(e)}function kZ(e){return Object.hasOwn(Zu.customValidation,e)?Zu.customValidation[e]:void 0}function LP(e,t){let n=0,i=t-1;for(;i>=0&&e[i]==="\\";)n++,i--;return n%2!==0}function Ap(e,t){let n=0;for(let i=0;i<e.length;i++)e[i]===t&&!LP(e,i)&&n++;return n}function xZ(e){for(let t=0;t<e.length-1;t++)if(e[t]==="("&&e[t+1]===")"&&!LP(e,t))return!0;return!1}function cS(e){if(!lS(e))return null;let t=NP(e);return t&&!lS(t.serverName)?null:{valid:!1,error:`Wildcard tool name "${e}" is not supported in allow rules`,suggestion:"An allow pattern must name the scope it widens \u2014 globs are permitted only in the tool position after a literal mcp__<server>__ prefix. Deny and ask rules accept wildcards anywhere",examples:["mcp__puppeteer__*","mcp__github__get_*"]}}function UP(e,t){if(!e||e.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let n=Ap(e,"("),i=Ap(e,")");if(n!==i)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(xZ(e)){let s=e.substring(0,e.indexOf("("));return s?{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${s}" without parentheses`,examples:[`${s}`,`${s}(some-pattern)`]}:{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"}}let r=_Z(e),o=NP(r.toolName);if(o){if(r.ruleContent!==void 0||Ap(e,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${r.toolName}" without parentheses, or use "mcp__${o.serverName}__*" for all tools`,examples:[`mcp__${o.serverName}`,`mcp__${o.serverName}__*`,o.toolName&&o.toolName!=="*"?`mcp__${o.serverName}__${o.toolName}`:void 0].filter(Boolean)};if(t==="allow"){let s=cS(r.toolName);if(s)return s}return{valid:!0}}if(!r.toolName||r.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(t==="allow"){let s=cS(r.toolName);if(s)return s}if(!r.toolName.includes("_")&&r.toolName[0]!==r.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${K2(String(r.toolName))}"`};let a=kZ(r.toolName);if(a&&r.ruleContent!==void 0){let s=a(r.ruleContent);if(!s.valid)return s}if(SZ(r.toolName)&&r.ruleContent!==void 0){let s=r.ruleContent;if(s.includes(":*")&&!s.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(s===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm *)","Bash(git *)"]}}return wZ(r.toolName)&&r.ruleContent!==void 0&&r.ruleContent.includes(":*")?{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${r.toolName}(*.ts) - matches .ts files`,`${r.toolName}(src/**) - matches all files in src`,`${r.toolName}(**/*.test.ts) - matches test files`]}:{valid:!0}}function FP(e){return c.string().superRefine((t,n)=>{let i=UP(t,e);if(!i.valid){let r=i.error;i.suggestion&&(r+=`. ${i.suggestion}`),i.examples&&i.examples.length>0&&(r+=`. Examples: ${i.examples.join(", ")}`),n.addIssue({code:c.ZodIssueCode.custom,message:r,params:{received:t}})}})}function zP(e){return c.object({allow:c.array(CZ()).optional().describe("List of permission rules for allowed operations"),deny:c.array(pS()).optional().describe("List of permission rules for denied operations"),ask:c.array(pS()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:c.enum([...ey,...gZ(e)]).optional().describe("Default permission mode when Claude Code needs access"),disableBypassPermissionsMode:c.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...hZ(e),additionalDirectories:c.array(c.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough()}function RZ(e){return c.object({$schema:c.string().optional().describe("JSON Schema reference for Claude Code settings"),apiKeyHelper:c.string().optional().describe("Path to a script that outputs authentication values"),proxyAuthHelper:c.string().optional().describe("Shell command that outputs a Proxy-Authorization header value (EAP)"),awsCredentialExport:c.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:c.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:c.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),policyHelper:PZ().optional().describe("Executable that computes managed settings at startup. Honored only from admin-controlled policy sources."),...kt(process.env.CLAUDE_CODE_ENABLE_XAA)&&{xaaIdp:c.object({issuer:c.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:c.string().describe("Claude Code's client_id registered at the IdP"),callbackPort:c.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")},fileSuggestion:c.object({type:c.literal("command"),command:c.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:c.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),breakReminder:c.object({enabled:c.boolean().optional().describe("Show a friendly nudge after sustained continuous use (default false). Must be true for the reminder to fire."),intervalMinutes:c.number().int().positive().optional().describe("Minutes of continuous use before the reminder fires (default 120). Re-fires every interval until you take a break."),breakThresholdMinutes:c.number().int().positive().optional().describe("Minutes of inactivity that count as a break and reset the timer (default 15)"),message:c.string().optional().describe("Custom reminder text. Leave unset for a rotating set of friendly nudges.")}).optional().describe("@internal Opt-in break reminder. When enabled, shows a dismissible nudge after sustained continuous use. Never blocks \u2014 just a friendly heads-up."),quietHours:c.object({enabled:c.boolean().optional().describe("Show a one-time nudge when you start or keep using the CLI inside your quiet-hours window (default false)."),start:c.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "22:00")').optional().describe('Start of the quiet-hours window, 24-hour local time "HH:MM".'),end:c.string().regex(/^([01]?\d|2[0-3]):[0-5]\d$/,'Expected 24-hour local time "HH:MM" (e.g. "07:00")').optional().describe('End of the quiet-hours window, 24-hour local time "HH:MM". May be earlier than start for an overnight range.')}).optional().describe("@internal Opt-in quiet hours. When enabled, shows a single soft nudge per session while inside the configured local-time window. Never blocks."),cleanupPeriodDays:c.number().int().positive().optional().describe("Number of days to retain chat transcripts before automatic cleanup (default: 30). Minimum 1. Use a large value for long retention; use --no-session-persistence to disable transcript writes entirely."),skillListingMaxDescChars:c.number().int().positive().optional().describe("Per-skill description character cap in the skill listing sent to Claude (default: 1536). Descriptions longer than this are truncated. Raise to opt in to higher per-turn context cost."),skillListingBudgetFraction:c.number().gt(0).lte(1).optional().describe("Fraction of the context window (in characters) reserved for the skill listing sent to Claude (default: 0.01 = 1%). When the listing exceeds this, descriptions are shortened to fit. Raise to opt in to higher per-turn context cost."),wslInheritsWindowsSettings:c.boolean().optional().describe("When set to true in either admin-only Windows source \u2014 the HKLM SOFTWARE/Policies/ClaudeCode registry key or C:/Program Files/ClaudeCode/managed-settings.json \u2014 WSL reads managed settings from the full Windows policy chain (HKLM, C:/Program Files/ClaudeCode via DrvFs, HKCU) in addition to /etc/claude-code. Windows sources take priority. The flag is also required in HKCU itself for HKCU policy to apply on WSL (double opt-in: admin enables the chain, user confirms HKCU). On native Windows the flag has no effect."),env:TZ().optional().describe("Environment variables to set for Claude Code sessions"),attribution:c.object({commit:c.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:c.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution."),sessionUrl:c.boolean().optional().describe("Whether to append the claude.ai session link to commits and PRs created from web or Remote Control sessions (default: true). Set to false to omit the Claude-Session trailer and PR-body link.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Claude Code attribution if not set."),includeCoAuthoredBy:c.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),includeGitInstructions:c.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:zP(e).optional().describe("Tool usage permissions configuration"),model:c.string().optional().describe("Override the default model used by Claude Code"),fallbackModel:c.array(c.string()).optional().describe('Fallback model(s) tried in order when the primary model is overloaded or unavailable. Each element accepts a model name or alias; "default" expands to the default model. CLI --fallback-model takes precedence.'),availableModels:c.array(c.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),enforceAvailableModels:c.boolean().optional().describe("When true and availableModels is a non-empty array, the Default model selection is also constrained: if the default model for the user tier is not in availableModels, Default resolves to the first allowed availableModels entry instead. Has no effect when availableModels is unset or an empty array. Typically set in managed settings by enterprise administrators."),modelOverrides:c.record(c.string(),c.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:c.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:c.array(c.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:c.array(c.string()).optional().describe("List of rejected MCP servers from .mcp.json"),disableClaudeAiConnectors:c.boolean().optional().describe("When true in any settings source, claude.ai MCP cloud connectors are not auto-fetched or connected. Only gates auto-fetched connectors \u2014 a claudeai-proxy server passed explicitly (e.g. via --mcp-config or the SDK mcpServers option) still follows the normal MCP config trust flow. Any-source-true wins: a project can opt out, but a project-level false cannot override a user-level true."),skillOverrides:c.record(c.string(),c.enum(["on","name-only","user-invocable-only","off"])).optional().describe('Per-skill listing overrides keyed by skill name. "name-only" lists the skill without its description; "user-invocable-only" hides it from the model but keeps /name; "off" hides it from both. Absent = on.'),disableBundledSkills:c.boolean().optional().describe("Disable the skills and workflows that ship with Claude Code: bundled skills and workflows are removed entirely; built-in slash commands stay typable but are hidden from the model. Plugins, .claude/skills/, and .claude/commands/ are unaffected. Equivalent to CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1."),allowedMcpServers:c.array(ry()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:c.array(iy()).optional().describe("Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied."),hooks:Gu().optional().describe("Custom commands to run before/after tool executions"),worktree:c.object({symlinkDirectories:c.array(c.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:c.array(c.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). Dramatically faster in large monorepos \u2014 only the listed paths are written to disk."),baseRef:c.enum(["fresh","head"]).optional().describe("Which ref new worktrees branch from. 'fresh' (default) branches from origin/<default-branch> for a clean tree. 'head' branches from your current local HEAD so unpushed commits and feature-branch state are present. Applies to --worktree, EnterWorktree, and agent isolation."),bgIsolation:c.enum(["worktree","none"]).optional().catch(void 0).describe("Isolation mode for background sessions in this repo. 'worktree' (default) blocks Edit/Write in the main checkout until EnterWorktree is called. 'none' lets background jobs edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:c.boolean().optional().describe("Disable all hooks and statusLine execution"),disableAgentView:c.boolean().optional().describe("Disable agent view (`claude agents`, `--bg`, /background, the on-demand daemon). Typically set in managed settings. Equivalent to CLAUDE_CODE_DISABLE_AGENT_VIEW=1."),disableRemoteControl:c.boolean().optional().describe("Disable Remote Control (claude.ai/code, `claude remote-control`, `--remote-control`/`--rc`, auto-start, and the in-session toggle). Typically set in managed settings."),disableWorkflows:c.boolean().optional().describe("Disable the Workflows feature (also via CLAUDE_CODE_DISABLE_WORKFLOWS)."),disableArtifact:c.boolean().optional().describe("Disable the Artifact tool (also via CLAUDE_CODE_DISABLE_ARTIFACT)."),enableArtifact:c.boolean().optional().describe("Enable or disable the Artifact tool for this user. Unset defaults to enabled once the feature is available."),enableWorkflows:c.boolean().optional().describe("Enable or disable the Workflows feature for this user. Unset = default by plan once the feature is available."),workflowKeywordTriggerEnabled:c.boolean().optional().describe('Enable the "ultracode" keyword trigger: including the keyword in a prompt opts that turn into the Workflow tool. Set to false to disable the trigger. Default: true.'),disableSkillShellExecution:c.boolean().optional().describe("Disable inline shell execution in skills and custom slash commands from user, project, or plugin sources. Commands are replaced with a placeholder instead of being run."),defaultShell:c.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),respondToBashCommands:c.boolean().optional().describe("Whether Claude responds after an input-box ! bash command runs. Set to false to add the command output to context without a response. Default: true."),allowManagedHooksOnly:c.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:c.array(c.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:c.array(c.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:c.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:c.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),allowAllClaudeAiMcps:c.boolean().optional().describe("When true (and set in managed settings), claude.ai cloud MCP connectors load alongside managed-mcp.json instead of being suppressed by its exclusive-control lockdown. Default off preserves the lockdown. Read from managed settings only."),strictPluginOnlyCustomization:c.preprocess(t=>Array.isArray(t)?t.filter(n=>fS.includes(n)):t,c.union([c.boolean(),c.array(c.enum(fS))])).optional().catch(void 0).describe('When set in managed settings, blocks non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. Blocked: ~/.claude/{surface}/, .claude/{surface}/ (project), settings.json hooks, .mcp.json. NOT blocked: managed (policySettings) sources, plugin-provided customizations. Composes with strictKnownMarketplaces for end-to-end admin control \u2014 plugins gated by marketplace allowlist, everything else blocked here.'),statusLine:c.object({type:c.literal("command"),command:c.string(),padding:c.number().optional(),refreshInterval:c.number().min(1).optional().catch(void 0).describe("Re-run the status line command every N seconds in addition to event-driven updates"),hideVimModeIndicator:c.boolean().optional().describe("Hide the built-in `-- INSERT --` / `-- VISUAL --` indicator below the prompt. Use this when your status line script renders `vim.mode` itself.")}).optional().describe("Custom status line display configuration"),prUrlTemplate:c.string().optional().describe('URL template for PR links in the footer link badges and inline messages. The detected git PR is rendered as the first footer-link badge. Placeholders: {host} {owner} {repo} {number} {url}. Example: "https://reviews.example.com/{owner}/{repo}/pull/{number}"'),footerLinksRegexes:c.array(EZ().catch(mS)).transform(t=>t.filter(n=>n!==mS)).optional().catch(void 0).describe("Extra clickable footer badges that appear when a regex matches turn output (tool results and assistant responses). Read from user, flag, and managed settings only; ignored in project .claude/settings.json and local .claude/settings.local.json. At most 5 badges render; the oldest is displaced by newer matches and /clear removes them. Use to surface IDs printed by project CLIs as session links."),subagentStatusLine:c.object({type:c.literal("command"),command:c.string()}).optional().describe("Custom per-subagent status line shown in the agent panel; receives row context as JSON on stdin"),enabledPlugins:c.record(c.string(),c.union([c.array(c.string()),c.boolean(),c.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints. Settings precedence is user < project < local < flag < policy, so to disable a plugin that project settings enable, set it to false in .claude/settings.local.json \u2014 setting false in ~/.claude/settings.json is overridden by the project.'),extraKnownMarketplaces:c.record(c.string(),IZ()).check(t=>{for(let[n,i]of Object.entries(t.value))i.source.source==="settings"&&i.source.name!==n&&t.issues.push({code:"custom",input:i.source.name,path:[n,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${n}" but source.name "${i.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:c.array(Vu()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. Note: this is a policy gate only \u2014 it does NOT register marketplaces. To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:c.array(Vu()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),disableSideloadFlags:c.boolean().optional().describe("When true (and set in managed settings), rejects the --plugin-dir, --plugin-url, --agents, and non-sdk --mcp-config CLI flags at startup. Closes the CLI-flag bypass of strictKnownMarketplaces. Pair with allowedMcpServers for per-server MCP control; this setting does not gate other MCP entry points (SDK setMcpServers, claude mcp add, .mcp.json). Also blocks surfaces that spawn the CLI with these flags internally (see settings documentation). Only honored from managed settings; ignored in user/project/local settings."),pluginSuggestionMarketplaces:c.array(c.string()).optional().describe("Marketplace names whose plugins may surface as contextual install suggestions (relevance-based tips). No marketplace-declared suggestions surface without this allowlist; the built-in first-party frontend-design tip is unaffected. Only honored when set in managed settings (policy scope); the key is ignored in user, project, and local settings. A name only takes effect when the marketplace is registered on the machine AND its registered source is also declared in managed settings, either as the extraKnownMarketplaces entry for that name or as an entry of strictKnownMarketplaces. A marketplace registered from a different source under an allowlisted name is ignored. The official marketplace is exempt from the source requirement: allowlisting its name alone suffices, since that name can only register from the official Anthropic source."),forceLoginMethod:c.enum(["claudeai","console","gateway"]).optional().catch(void 0).describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing, "gateway" for the Cloud gateway OIDC device flow'),forceLoginGatewayUrl:c.string().url().optional().catch(void 0).describe('@internal Cloud gateway URL to pre-fill and auto-connect to during login. Typically set in local managed settings alongside forceLoginMethod: "gateway" so users never type the URL. Hidden from public SDK types until Cloud gateway is documented.'),parentSettingsBehavior:c.enum(["first-wins","merge"]).optional().describe(`Controls whether the SDK parent tier (Options.managedSettings / --managed-settings) layers under this admin tier. "first-wins" (default): parent is dropped \u2014 admin tiers are the only policy source. "merge": parent's restrictive-only-filtered settings union under the admin winner. Has no effect when no admin tier exists (parent applies as the sole policy tier, still filtered restrictive-only).`),forceLoginOrgUUID:c.union([c.string(),c.array(c.string())]).optional().describe("Organization UUID to require for OAuth login. Accepts a single UUID string or an array of UUIDs (any one is permitted). When set in managed settings, login fails if the authenticated account does not belong to a listed organization."),forceRemoteSettingsRefresh:c.boolean().optional().describe("When set in managed settings, the CLI blocks startup until remote managed settings are freshly fetched, and exits if the fetch fails"),otelHeadersHelper:c.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:c.string().optional().describe("Controls the output style for assistant responses"),viewMode:c.enum(["default","verbose","focus"]).optional().catch(void 0).describe("Default transcript view mode on startup"),language:c.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:c.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:xP().optional(),feedbackSurveyRate:c.number().min(0).max(1).optional().describe("Probability (0\u20131) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:c.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:c.object({mode:c.enum(["append","replace"]),verbs:c.array(c.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:c.object({excludeDefault:c.boolean().optional(),tips:c.array(c.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:c.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:c.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:c.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:c.enum(["low","medium","high","xhigh"]).optional().catch(void 0).describe("Persisted effort level for supported models."),ultracode:c.boolean().optional().catch(void 0).describe("Enable ultracode for the session: xhigh effort plus standing dynamic-workflow orchestration. Session-scoped \u2014 typically provided via --settings or the apply_flag_settings control request; interactive toggles never persist it. Requires workflows to be enabled and an xhigh-capable model."),autoCompactWindow:c.number().int().min(1e5).max(1e6).optional().catch(void 0).describe("Auto-compact window size"),advisorModel:c.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:c.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:c.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:c.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),awaySummaryEnabled:c.boolean().optional().describe("@internal When false, the session recap (shown when you return after being away for 5+ minutes) is disabled. When absent or true, recap is enabled. Hidden from public SDK types until external launch."),showClearContextOnPlanAccept:c.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:c.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),companyAnnouncements:c.array(c.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:c.record(c.string(),c.object({mcpServers:c.record(c.string(),c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")}).or(c.undefined())).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:c.object({defaultEnvironmentId:c.string().optional().describe("Default environment ID to use for cloud sessions")}).optional().describe("Cloud session configuration"),autoUpdatesChannel:c.enum(["latest","stable","rc"]).optional().describe("Release channel for auto-updates (latest or stable)"),minimumVersion:c.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),requiredMinimumVersion:c.string().optional().describe("Minimum Claude Code version required to start. If the running version is older, Claude Code exits at startup with instructions to update. Only enforced from managed (policy) settings."),requiredMaximumVersion:c.string().optional().describe("Maximum Claude Code version allowed to start. If the running version is newer, Claude Code exits at startup with instructions to install an approved version. Only enforced from managed (policy) settings."),plansDirectory:c.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),tui:c.enum(["default","fullscreen"]).optional().describe('Terminal UI renderer. "fullscreen" uses the flicker-free alt-screen renderer with virtualized scrollback (equivalent to CLAUDE_CODE_NO_FLICKER=1). "default" uses the classic main-screen renderer.'),voice:c.object({enabled:c.boolean().optional(),mode:c.enum(["hold","tap"]).optional().describe("'hold' (default): hold to talk. 'tap': tap to start, tap to stop+submit."),autoSubmit:c.boolean().optional().describe("Submit the prompt when hold-to-talk is released (hold mode only)")}).optional().describe("Voice mode settings (hold-to-talk / tap-to-toggle dictation)"),channelsEnabled:c.boolean().optional().describe("Managed-org opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). claude.ai Teams/Enterprise: default off. Console: default on unless managed settings exist. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:c.array(c.object({marketplace:c.string(),plugin:c.string()})).optional().describe("Managed-org allowlist of channel plugins. When set, replaces the default Anthropic allowlist \u2014 admins decide which plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),prefersReducedMotion:c.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),doneMeansMerged:c.boolean().optional().describe("@internal When true, Claude keeps working until the PR is ready for you to merge, a cron/Monitor is armed to resume later, or it hands you a self-contained next step."),totalTokensReminder:c.enum(["off","infinite","fixed","countdown","padded-countdown"]).optional().describe("@internal Emit a <total_tokens>N tokens left</total_tokens> block in the system prompt and after each tool result. 'infinite' uses the literal value Infinite, 'fixed' uses 5000000, 'countdown' uses the live remaining context-window tokens, 'padded-countdown' counts down from totalTokensReminderBudget by per-agent cumulative context spend (monotonic across compaction and /clear). Defaults to off. Env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER overrides."),totalTokensReminderBudget:c.number().int().positive().optional().describe("@internal Starting budget (tokens) for totalTokensReminder 'padded-countdown' mode. Defaults to 15000000. Server-controlled via GrowthBook; env var CLAUDE_CODE_TOTAL_TOKENS_REMINDER_BUDGET overrides."),autoMemoryEnabled:c.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:c.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:c.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:c.boolean().optional().describe("Request API-side thinking summaries and show them in the conversation and in the transcript view (ctrl+o). Set explicitly to override the default for your install."),skipDangerousModePermissionPrompt:c.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),skipWorkflowUsageWarning:c.boolean().optional().describe("@internal Whether the user has accepted the multi-agent workflow usage warning. Until set, auto permission mode prompts before running a workflow."),disableAutoMode:c.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:c.array(c.object({id:c.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:c.string().describe("Display name for the SSH connection"),sshHost:c.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:c.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:c.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:c.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMd:c.string().optional().describe("CLAUDE.md-style instructions injected as organization-managed memory. Only honored from managed/policy settings."),claudeMdExcludes:c.array(c.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:c.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").'),theme:c.union([c.enum(a3),c.string().startsWith("custom:").transform(t=>t)]).optional().catch(void 0).describe("Color theme for the UI"),editorMode:c.enum(r3).optional().catch(void 0).describe("Key binding mode for the prompt input"),verbose:c.boolean().optional().describe("Show full tool output instead of truncated summaries"),preferredNotifChannel:c.enum(n3).optional().catch(void 0).describe("Preferred OS notification channel"),autoCompactEnabled:c.boolean().optional().describe("Automatically compact conversation when context fills"),precomputeCompactionEnabled:c.boolean().optional().describe("@internal Precompute the compaction summary in the background before it is needed. Only applies when auto-compact is on."),switchModelsOnFlag:c.boolean().optional().describe("When safety measures flag a message, automatically switch to a different model to keep chatting. When off, your session will pause instead."),autoScrollEnabled:c.boolean().optional().describe("Auto-scroll the conversation view to bottom (fullscreen mode only)"),wheelScrollAccelerationEnabled:c.boolean().optional().describe("Ramp mouse-wheel scroll speed during fast scrolls (fullscreen mode only)"),fileCheckpointingEnabled:c.boolean().optional().describe("Snapshot files before edits so /rewind can restore them"),showTurnDuration:c.boolean().optional().describe('Show "Cooked for Nm Ns" after each assistant turn'),showMessageTimestamps:c.boolean().optional().describe("Stamp each assistant message with its arrival time"),terminalProgressBarEnabled:c.boolean().optional().describe("Emit OSC 9;4 progress sequences during long operations"),todoFeatureEnabled:c.boolean().optional().describe("Enable the todo / task tracking panel"),teammateMode:c.enum(i3).optional().catch(void 0).describe("How spawned teammates execute (tmux, iterm2, in-process, auto)"),remoteControlAtStartup:c.boolean().optional().describe("Start Remote Control bridge automatically each session"),isolatePeerMachines:c.boolean().optional().describe("Require explicit approval before SendMessage can reach a peer session on another machine via Remote Control"),daemonColdStart:c.enum(["transient","ask"]).optional().describe("When no background service is running: 'transient' spawns one for this login session; 'ask' offers to install it persistently"),autoUploadSessions:c.boolean().optional().describe("Mirror local sessions to claude.ai as view-only (no remote control)"),inputNeededNotifEnabled:c.boolean().optional().describe("Push to mobile when a permission prompt or question is waiting"),agentPushNotifEnabled:c.boolean().optional().describe("Allow Claude to push proactive mobile notifications"),...mZ(e)}).passthrough()}function gS(e,t,n){return c.array(t.catch(i=>(n({path:`${e}[]`,message:`Invalid entry was ignored: ${i.issues[0]?.message??"failed validation"}`}),hS))).transform(i=>i.filter(r=>r!==hS)).optional()}function BP(e){let t=Hl(),n={};for(let[o,a]of Object.entries(t.shape))n[o]=a.catch(s=>{e({path:o,message:`${s.issues[0]?.message??"Failed schema validation"}. This field was ignored.`})});n.allowedMcpServers=gS("allowedMcpServers",ry(),e).catch(()=>(e({path:"allowedMcpServers",message:'"allowedMcpServers" was present but invalid; enforcing an empty allowlist (no MCP servers admitted) until it is fixed.'}),[])),n.deniedMcpServers=gS("deniedMcpServers",iy(),e).catch(()=>{e({path:"deniedMcpServers",message:'"deniedMcpServers" was present but invalid and was dropped; its entries cannot be enforced until it is fixed.'})}),n.allowManagedMcpServersOnly=t.shape.allowManagedMcpServersOnly.catch(()=>(e({path:"allowManagedMcpServersOnly",message:'"allowManagedMcpServersOnly" was present but invalid; treating it as true until it is fixed.'}),!0)),n.enforceAvailableModels=t.shape.enforceAvailableModels.catch(()=>(e({path:"enforceAvailableModels",message:'"enforceAvailableModels" was present but invalid; treating it as true until it is fixed.'}),!0)),n.availableModels=c.array(c.unknown()).transform((o,a)=>{let s=[];for(let d of o)typeof d=="string"?s.push(d):e({path:"availableModels",message:`"availableModels" contained a non-string entry (${JSON.stringify(d)}); the entry was ignored.`});return s}).optional().catch(()=>(e({path:"availableModels",message:'"availableModels" was present but invalid; enforcing an empty allowlist (only the default model is available) until it is fixed.'}),[])),n.forceLoginOrgUUID=t.shape.forceLoginOrgUUID.catch(()=>(e({path:"forceLoginOrgUUID",message:'"forceLoginOrgUUID" was present but invalid; no organization is permitted to log in until it is fixed.'}),[]));let i=Object.freeze({mode:"deny"}),r=(o,a)=>c.array(a.catch(s=>(e({path:`sandbox.credentials.${o}[]`,message:`Invalid entry was ignored: ${s.issues[0]?.message??"failed validation"}. This credential is NOT protected until the entry is fixed.`}),i))).transform(s=>s.filter(d=>d!==i)).optional();return n.sandbox=xP().extend({credentials:c.object({files:r("files",SP()),envVars:r("envVars",kP()),allowPlaintextInject:c.boolean().optional().catch(o=>{e({path:"sandbox.credentials.allowPlaintextInject",message:`${o.issues[0]?.message??"Invalid value"}. "allowPlaintextInject" was ignored; plaintext credential injection stays disabled until it is fixed.`})})}).optional().catch(o=>{e({path:"sandbox.credentials",message:`${o.issues[0]?.message??"Failed schema validation"}. The credentials block was dropped; no credential protection is applied until it is fixed.`})})}).optional().catch(o=>{e({path:"sandbox",message:`${o.issues[0]?.message??"Failed schema validation"}. This field was ignored.`})}),c.object(n).passthrough().transform(o=>{for(let a of Object.keys(o))o[a]===void 0&&delete o[a];return o})}function $Z(e){let t=OZ.find(i=>i.matches(e));if(!t)return null;let n={...t.tip};return e.code==="invalid_value"&&e.enumValues&&!n.suggestion&&(n.suggestion=`Valid values: ${e.enumValues.map(i=>`"${i}"`).join(", ")}`),!n.docLink&&e.path&&(n.docLink=AZ[G2(e.path,".")]),n}function yS(e){return e.code==="invalid_type"}function _S(e){return e.code==="invalid_value"}function MZ(e){return e.code==="unrecognized_keys"}function vS(e){return e.code==="too_small"}function zi(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}function bS(e){let t=e.match(/received (\w+)/);return t?t[1]:void 0}function Qu(e,t){return e.issues.map(n=>{let i=n.path.map(String).join("."),r=n.message,o,a,s,d,u;if(_S(n))a=n.values.map(p=>String(p)),s=a.join(" | "),d=void 0,u=void 0;else if(yS(n)){s=n.expected;let p=bS(n.message);d=p??zi(n.input),u=p??zi(n.input)}else vS(n)?s=String(n.minimum):n.code==="custom"&&"params"in n&&(d=n.params.received,u=d);let l=$Z({path:i,code:n.code,expected:s,received:d,enumValues:a,message:n.message,value:d});if(_S(n))o=a?.map(p=>`"${p}"`).join(", "),r=`Invalid value. Expected one of: ${o}`;else if(yS(n)){let p=bS(n.message)??zi(n.input);n.expected==="object"&&p==="null"&&i===""?r="Invalid or malformed JSON":r=`Expected ${n.expected}, but received ${p}`}else if(MZ(n)){let p=n.keys.join(", ");r=`Unrecognized ${J2(n.keys.length,"field")}: ${p}`}else vS(n)&&(r=`Number must be greater than or equal to ${n.minimum}`,o=String(n.minimum));return{file:t,path:i,message:r,expected:o,invalidValue:u,suggestion:l?.suggestion,docLink:l?.docLink}})}function jZ(e,t){if(!e||typeof e!="object")return[];let n=e;if(!n.permissions||typeof n.permissions!="object")return[];let i=n.permissions,r=[];for(let o of["allow","deny","ask"]){let a=i[o];Array.isArray(a)&&(i[o]=a.filter(s=>{if(typeof s!="string")return r.push({file:t,path:`permissions.${o}`,message:`Non-string value in ${o} array was removed`,severity:"warning",invalidValue:s}),!1;let d=UP(s,o);if(!d.valid){let u=`Invalid permission rule "${s}" was skipped: ${d.error}`;return d.suggestion&&(u+=`. ${d.suggestion}`),r.push({file:t,path:`permissions.${o}`,message:u,severity:"warning",invalidValue:s}),!1}return!0}))}return r}function NZ(e,t){if(!e||typeof e!="object")return[];let n=e;if(!("hooks"in n))return[];if(n.hooks===null||typeof n.hooks!="object"||Array.isArray(n.hooks)){let o=zi(n.hooks);return delete n.hooks,[{file:t,path:"hooks",message:`"hooks" must be an object mapping event names to matcher arrays; received ${o}. This field was ignored.`,severity:"warning",invalidValue:o,docLink:"https://code.claude.com/docs/en/hooks"}]}let i=n.hooks,r=[];for(let o of Object.keys(i)){if(!qZ.has(o)){delete i[o],r.push({file:t,path:`hooks.${o}`,message:`Unknown hook event "${o}" was ignored. Valid events: ${ul.join(", ")}`,severity:"warning",invalidValue:o,docLink:"https://code.claude.com/docs/en/hooks"});continue}if(!Array.isArray(i[o])){let a=zi(i[o]);delete i[o],r.push({file:t,path:`hooks.${o}`,message:`Hook event "${o}" must be an array of matchers; received ${a}. This entry was ignored.`,severity:"warning",invalidValue:a,docLink:"https://code.claude.com/docs/en/hooks"})}}return r.length>0&&Object.keys(i).length===0&&delete n.hooks,r}function LZ(e,t){if(!e||typeof e!="object")return[];let n=e,i=[];for(let{key:r,schema:o}of DZ){if(!(r in n))continue;if(!Array.isArray(n[r])){let d=n[r];delete n[r],i.push({file:t,path:r,message:`"${r}" must be an array; received ${zi(d)}. This field was ignored.`,severity:"warning",invalidValue:d});continue}let a=n[r],s=[];for(let d=0;d<a.length;d++){let u=o().safeParse(a[d]);u.success?s.push(a[d]):i.push({file:t,path:`${r}[${d}]`,message:`Invalid entry was ignored: ${u.error.issues[0]?.message??"failed validation"}`,severity:"warning",invalidValue:a[d]})}s.length<a.length&&(n[r]=s)}return i}function ps(e,t,n){return[...jZ(e,t),...NZ(e,t),...n?.skipMcpServerEntryFilter?[]:LZ(e,t)]}function oy(e){let t=new Set(e.allowedSources);return t.add("flagSettings"),t.add("policySettings"),H5.filter(n=>t.has(n))}function UZ(){return wr(cs(),"managed-settings.json")}function KP(e){if(Jl()==="wsl"&&e.wslInherits?.()){let t=$p(Hu);if(t.settings)return t;let n=$p(cs());return{settings:n.settings,errors:[...t.errors,...n.errors]}}return $p(cs())}function $p(e){let t=[],n={},i=!1,{settings:r,errors:o}=Yu(wr(e,"managed-settings.json"),void 0,!0);t.push(...o),r&&Object.keys(r).length>0&&(n=_r(n,r,vr),i=!0);let a=wr(e,"managed-settings.d");try{let u=Yt().readdirSync(a).filter(l=>(l.isFile()||l.isSymbolicLink())&&l.name.endsWith(".json")&&!l.name.startsWith(".")).map(l=>l.name).sort();for(let l of u){let{settings:p,errors:m}=Yu(wr(a,l),void 0,!0);t.push(...m),p&&Object.keys(p).length>0&&(n=_r(n,p,vr),i=!0)}}catch(u){let l=Pt(u);l!=="ENOENT"&&l!=="ENOTDIR"&&qe(`managed-settings.d read failed: ${u}`,{level:"error"})}let{wslInheritsWindowsSettings:s,...d}=n;return{settings:i&&Object.keys(d).length>0?n:null,errors:t}}function FZ(e,t){_o(e)?qe(`Broken symlink or missing file encountered for settings.json at path: ${t}`):qe(`settings file read failed at ${t}: ${e}`,{level:"error"})}function Yu(e,t,n){let i=Xz(e);if(i)return{settings:i.settings?Gi(i.settings):null,errors:i.errors};let r=KZ(e,t,n);return e2(e,r),{settings:r.settings?Gi(r.settings):null,errors:r.errors}}function JP(e){if(!e.mdm)return{settings:null,errors:[]};let t=e.mdm();return{settings:Object.keys(t.settings).length>0?t.settings:null,errors:t.errors}}function ay(e,t){let n=Gi(e),i=ps(n,t,{skipMcpServerEntryFilter:!0}),r=[],o=BP(a=>r.push({file:t,path:a.path,message:a.message,severity:"warning"})).safeParse(n);return o.success?{settings:Object.keys(o.data).length>0?o.data:null,errors:[...i,...r]}:{settings:null,errors:[...i,...Qu(o.error,t)]}}function WP(e){let t=e?.remote?e.remote():W5();return!t||Object.keys(t).length===0?{settings:null,errors:[]}:ay(t,"remote managed settings")}function zZ(e){let t=e.parentManaged;return!t||Object.keys(t).length===0?{settings:null,errors:[]}:ay(t,"parent managed settings")}function HP(e){let t=e.flagInline;if(!t)return{settings:null,errors:[]};let n=Gi(t),i=ps(n,"SDK inline settings"),r=Hl().safeParse(n);return r.success?{settings:r.data,errors:i}:{settings:null,errors:[...i,...Qu(r.error,"SDK inline settings")]}}function KZ(e,t,n){try{let i;if(t!==void 0)i=t;else{let{resolvedPath:s}=rx(Yt(),e);i=Bl(s,BZ)}if(i.trim()==="")return{settings:{},errors:[]};let r=Gi(Kl(i,!1));if(n){let s=ps(r,e,{skipMcpServerEntryFilter:!0}),d=[],u=BP(l=>d.push({file:e,path:l.path,message:l.message,severity:"warning"})).safeParse(r);return u.success?{settings:u.data,errors:[...s,...d]}:{settings:null,errors:[...s,...Qu(u.error,e)]}}let o=ps(r,e),a=Hl().safeParse(r);if(!a.success){let s=Qu(a.error,e);return{settings:null,errors:[...o,...s]}}return{settings:a.data,errors:o}}catch(i){return FZ(i,e),_o(i)?{settings:null,errors:[]}:{settings:null,errors:[{file:e,path:"",message:`Settings file could not be read: ${i instanceof Error?i.message:String(i)}`,severity:"fatal"}]}}}function wS(e,t){switch(e){case"userSettings":return Ia(yo());case"policySettings":case"projectSettings":case"localSettings":return Ia(t.cwd);case"flagSettings":return t.flagPath?I5(Ia(t.flagPath)):Ia(t.cwd)}}function JZ(e){return e.coworkPlugins||kt(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS)?"cowork_settings.json":"settings.json"}function Xu(e,t){switch(e){case"userSettings":return wr(wS(e,t),JZ(t));case"projectSettings":case"localSettings":return wr(wS(e,t),WZ(e));case"policySettings":return UZ();case"flagSettings":return t.flagPath}}function WZ(e){switch(e){case"projectSettings":return wr(".claude","settings.json");case"localSettings":return wr(".claude","settings.local.json")}}function GP(e,t){let n=Wz(e);if(n!==void 0)return n;let i=ZZ(e,t);return Hz(e,i),i}function HZ(e){return!e||e.parentSettingsBehavior==="merge"}function GZ(e,t){let n={};e.allowManagedHooksOnly===!0&&(n.allowManagedHooksOnly=!0),e.allowManagedMcpServersOnly===!0&&(n.allowManagedMcpServersOnly=!0),e.disableClaudeAiConnectors===!0&&(n.disableClaudeAiConnectors=!0),e.allowManagedPermissionRulesOnly===!0&&(n.allowManagedPermissionRulesOnly=!0);let i=e.strictPluginOnlyCustomization;if((i===!0||Array.isArray(i)&&i.length>0)&&(n.strictPluginOnlyCustomization=i),e.deniedMcpServers&&(n.deniedMcpServers=e.deniedMcpServers),t.forceLoginOrgUUID===void 0&&e.forceLoginOrgUUID&&(n.forceLoginOrgUUID=e.forceLoginOrgUUID),t.allowedMcpServers===void 0&&e.allowedMcpServers&&(n.allowedMcpServers=e.allowedMcpServers),t.availableModels===void 0&&e.availableModels&&(n.availableModels=e.availableModels),e.enforceAvailableModels===!0&&(n.enforceAvailableModels=!0),e.permissions){let r=Ep(e.permissions,["deny","ask"]);if(e.permissions.disableBypassPermissionsMode==="disable"&&(r.disableBypassPermissionsMode="disable"),t.allowManagedPermissionRulesOnly!==!0){let{allow:o,additionalDirectories:a}=e.permissions;o&&t.sandbox?.network?.allowManagedDomainsOnly!==!0&&(r.allow=o),a&&(r.additionalDirectories=a)}Object.keys(r).length>0&&(n.permissions=r)}if(e.sandbox){let{network:r,filesystem:o,credentials:a}=e.sandbox,s={};if(e.sandbox.enabled===!0&&(s.enabled=!0),e.sandbox.failIfUnavailable===!0&&(s.failIfUnavailable=!0),e.sandbox.allowUnsandboxedCommands===!1&&(s.allowUnsandboxedCommands=!1),e.sandbox.autoAllowBashIfSandboxed===!1&&(s.autoAllowBashIfSandboxed=!1),r){let d=Ep(r,["deniedDomains"]);r.allowManagedDomainsOnly===!0&&(d.allowManagedDomainsOnly=!0),t.sandbox?.network?.allowManagedDomainsOnly!==!0&&r.allowedDomains&&(d.allowedDomains=r.allowedDomains),Object.keys(d).length>0&&(s.network=d)}if(o){let d=Ep(o,["denyRead","denyWrite"]);o.allowManagedReadPathsOnly===!0&&(d.allowManagedReadPathsOnly=!0),t.sandbox?.filesystem?.allowManagedReadPathsOnly!==!0&&o.allowRead&&(d.allowRead=o.allowRead),Object.keys(d).length>0&&(s.filesystem=d)}if(a){let d=(a.files??[]).filter(p=>p.mode==="deny"),u=(a.envVars??[]).filter(p=>p.mode==="deny"),l={...d.length>0&&{files:d},...u.length>0&&{envVars:u}};a.allowPlaintextInject===!1&&(l.allowPlaintextInject=!1),Object.keys(l).length>0&&(s.credentials=l)}Object.keys(s).length>0&&(n.sandbox=s)}return n}function VZ(e){if(e.helper?.())return"helper";if(WP(e).settings)return"remote";if(JP(e).settings)return Jl()==="macos"?"plist":"hklm";if((e.file?.()??KP(e)).settings)return"file";if(VP(e).parentSlice)return"parent";let t=e.hkcu?.();return t&&Object.keys(t.settings).length>0?"hkcu":null}function VP(e){let t=[],{settings:n,errors:i}=WP(e);t.push(...i);let{settings:r,errors:o}=JP(e);t.push(...o);let{settings:a,errors:s}=e.file?.()??KP(e);t.push(...s);let{settings:d,errors:u}=zZ(e);t.push(...u);let l=[n,r,a].filter(y=>y!==null),p=l[0]??null,m={allowManagedPermissionRulesOnly:l.some(y=>y.allowManagedPermissionRulesOnly===!0)||void 0,forceLoginOrgUUID:l.find(y=>y.forceLoginOrgUUID!==void 0)?.forceLoginOrgUUID,allowedMcpServers:l.find(y=>y.allowedMcpServers!==void 0)?.allowedMcpServers,availableModels:l[0]?.availableModels,sandbox:{network:{allowManagedDomainsOnly:l.some(y=>y.sandbox?.network?.allowManagedDomainsOnly===!0)||void 0},filesystem:{allowManagedReadPathsOnly:l.some(y=>y.sandbox?.filesystem?.allowManagedReadPathsOnly===!0)||void 0}}},f=d&&HZ(p)?GZ(d,m):null,h=f&&Object.keys(f).length>0?f:null;return{tiers:l,admin:p,parentSlice:h,errors:t}}function ZP(e){let t=e.helper?.();if(t)return{settings:t,errors:e.helperWarnings?.()??[]};let{tiers:n,admin:i,parentSlice:r,errors:o}=VP(e);if(!i&&!r){let s=e.hkcu?.();return s&&Object.keys(s.settings).length>0?{settings:s.settings,errors:[...o,...s.errors]}:{settings:null,errors:[...o,...s?.errors??[]]}}let a=_r({},r??{},i??{},vr);return n.some(s=>s.forceRemoteSettingsRefresh===!0)&&(a.forceRemoteSettingsRefresh=!0),{settings:a,errors:o}}function ZZ(e,t){if(e==="policySettings")return ZP(t).settings;let n=Xu(e,t),{settings:i}=n?Yu(n,e==="flagSettings"?t.flagExpectedContent:void 0):{settings:null};if(e==="flagSettings"){let{settings:r}=HP(t);if(r)return _r(i||{},r,vr)}return i}function QZ(e,t){return Ex([...e,...t])}function vr(e,t,n){if(Array.isArray(e)&&Array.isArray(t))return n==="fallbackModel"?t:QZ(e,t)}function YZ(e){if(Mp)return{settings:{},errors:[]};let t=Date.now();Jf("info","settings_load_started"),Mp=!0;try{let n=n2(),i={};n&&(i=_r(i,n,vr));let r=[],o=new Set,a=new Set,s=null;for(let d of oy(e)){if(d==="policySettings"){let{settings:l,errors:p}=ZP(e);s=l,l&&(i=_r(i,l,vr));for(let m of p){let f=`${m.file}:${m.path}:${m.message}`;o.has(f)||(o.add(f),r.push(m))}continue}let u=Xu(d,e);if(u){let l=Ia(u);if(!a.has(l)){a.add(l);let{settings:p,errors:m}=Yu(u,d==="flagSettings"?e.flagExpectedContent:void 0);for(let f of m){let h=`${f.file}:${f.path}:${f.message}`;o.has(h)||(o.add(h),r.push(f))}p&&(i=_r(i,p,vr))}}if(d==="flagSettings"){let{settings:l,errors:p}=HP(e);for(let m of p){let f=`${m.file}:${m.path}:${m.message}`;o.has(f)||(o.add(f),r.push(m))}l&&(i=_r(i,l,vr))}}return s&&(s.availableModels!==void 0&&(i.availableModels=[...s.availableModels]),s.enforceAvailableModels!==void 0&&(i.enforceAvailableModels=s.enforceAvailableModels)),Jf("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:a.size,error_count:r.length}),{settings:i,errors:r}}finally{Mp=!1}}function XZ(e){let t=Kz();if(t!==null)return t;let n=YZ(e);return Jz(n),n}function e8(e){let{settings:t}=XZ(e);return t||{}}function t8(e){Lm();let t=[];for(let n of oy(e)){let i=GP(n,e);i&&Object.keys(i).length>0&&t.push({source:n,settings:i})}return{effective:e8(e),sources:t}}function n8(e,t){let n=oy(t);for(let i=n.length-1;i>=0;i--){let r=n[i];if(GP(r,t)?.[e]!==void 0)return r}return null}function ya(e,t){return new Promise(n=>{try{r8(e,t,{encoding:"utf-8",timeout:Q5,windowsHide:!0},(i,r)=>{n({stdout:r??"",code:i?1:0})})}catch{n({stdout:"",code:1})}})}function a8(){return(async()=>{if(process.platform==="darwin"){let e=Y5(),t=(await Promise.all(e.map(async({path:n,label:i})=>{if(!i8(n))return{stdout:"",label:i,ok:!1};let{stdout:r,code:o}=await ya(V5,[...Z5,n]);return{stdout:r,label:i,ok:o===0&&!!r}}))).find(n=>n.ok);return{plistStdouts:t?[{stdout:t.stdout,label:t.label}]:[],hklmStdout:null,hkcuStdout:null}}if(process.platform==="win32"){let e=`${process.env.SYSTEMROOT||"C:\\Windows"}\\System32\\reg.exe`,[t,n]=await Promise.all([ya(e,["query",Yf,"/v",qi]),ya(e,["query",Xf,"/v",qi])]);return{plistStdouts:null,hklmStdout:t.code===0?t.stdout:null,hkcuStdout:n.code===0?n.stdout:null}}if(wP()){let[e,t]=await Promise.all([ya(iS,["query",Yf,"/v",qi]),ya(iS,["query",Xf,"/v",qi])]);return{plistStdouts:null,hklmStdout:e.code===0?e.stdout:null,hkcuStdout:t.code===0?t.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}function s8(){return o8}function d8(){el||(el=(async()=>{let e=Date.now(),t=s8()??a8(),{mdm:n,hkcu:i,wslInherits:r}=f8(await t);QP=n,YP=i,XP=r;let o=Date.now()-e;if(qe(`MDM settings load completed in ${o}ms`),Object.keys(n.settings).length>0){qe(`MDM settings found: ${Object.keys(n.settings).join(", ")}`);try{Jf("info","mdm_settings_loaded",{duration_ms:o,key_count:Object.keys(n.settings).length,error_count:n.errors.length})}catch{}}})())}async function u8(){el||d8(),await el}function l8(){return QP??hr}function c8(){return YP??hr}function p8(){return XP}function jp(e,t){let n=Kl(e,!1);if(!n||typeof n!="object")return{settings:{},errors:[]};let{settings:i,errors:r}=ay(n,t);return{settings:i??{},errors:r}}function SS(e,t="Settings"){let n=e.split(/\r?\n/),i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^\\s+${i}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let o of n){let a=o.match(r);if(a&&a[1])return a[1].trimEnd()}return null}function f8(e){let t=[];if(e.plistStdouts&&e.plistStdouts.length>0){let{stdout:a,label:s}=e.plistStdouts[0],d=jp(a,s),{wslInheritsWindowsSettings:u,...l}=d.settings;if(Object.keys(l).length>0)return{mdm:d,hkcu:hr,wslInherits:!1};t.push(...d.errors)}let n=null;if(e.hklmStdout){let a=SS(e.hklmStdout);a&&(n=jp(a,`Registry: ${Yf}\\${qi}`))}n&&t.push(...n.errors);let i=t.length>0?{settings:{},errors:t}:hr,r=wP(),o=!1;if(r&&(o=n?.settings.wslInheritsWindowsSettings===!0||h8(),!o))return{mdm:i,hkcu:hr,wslInherits:!1};if(n){let{wslInheritsWindowsSettings:a,...s}=n.settings;if(Object.keys(s).length>0)return{mdm:n,hkcu:hr,wslInherits:o}}if(m8(o))return{mdm:i,hkcu:hr,wslInherits:o};if(e.hkcuStdout){let a=SS(e.hkcuStdout);if(a){let s=jp(a,`Registry: ${Xf}\\${qi}`);if(!r||s.settings.wslInheritsWindowsSettings===!0){let{wslInheritsWindowsSettings:d,...u}=s.settings;return{mdm:i,hkcu:{settings:u,errors:s.errors},wslInherits:o}}if(s.errors.length>0)return{mdm:i,hkcu:{settings:{},errors:s.errors},wslInherits:o}}}return{mdm:i,hkcu:hr,wslInherits:o}}function m8(e){return e&&xS(Hu)?!0:xS(cs())}function kS(e){let t=Gi(Kl(Bl(e),!1));if(!t||typeof t!="object")return!1;ps(t,e);let{wslInheritsWindowsSettings:n,...i}=t;return Object.keys(i).length>0}function h8(){function e(t){try{let n=Kl(Bl(t),!1);return!!n&&typeof n=="object"&&"wslInheritsWindowsSettings"in n&&n.wslInheritsWindowsSettings===!0}catch{return!1}}if(e(Ui(Hu,"managed-settings.json")))return!0;try{let t=Ui(Hu,"managed-settings.d");for(let n of Yt().readdirSync(t))if((n.isFile()||n.isSymbolicLink())&&n.name.endsWith(".json")&&!n.name.startsWith(".")&&e(Ui(t,n.name)))return!0}catch{}return!1}function xS(e){try{if(kS(Ui(e,"managed-settings.json")))return!0}catch{}try{let t=Ui(e,"managed-settings.d"),n=Yt().readdirSync(t);for(let i of n)if(!(!(i.isFile()||i.isSymbolicLink())||!i.name.endsWith(".json")||i.name.startsWith(".")))try{if(kS(Ui(t,i.name)))return!0}catch{}}catch{}return!1}function b8(e){let t=e.effective.permissions?.defaultMode;if(!t||!_8.has(t))return e.effective;for(let n=e.sources.length-1;n>=0;n--){let i=e.sources[n];if(i.settings.permissions?.defaultMode!==void 0){if(v8.has(i.source)){let{defaultMode:r,...o}=e.effective.permissions??{};return{...e.effective,permissions:o}}return e.effective}}return e.effective}async function w8(e={}){await u8();let t={cwd:oV(e.cwd??Yt().cwd()),allowedSources:(e.settingSources??y8).map(n=>g8[n]),parentManaged:e.managedSettings??null,flagInline:null,flagPath:void 0,mdm:l8,hkcu:c8,wslInherits:p8,...e.serverManagedSettings!==void 0&&{remote:()=>e.serverManagedSettings}};try{let{effective:n,sources:i}=t8(t),r=VZ(t)??void 0,o=i.map(({source:s,settings:d})=>({source:CS[s],settings:d,path:s==="policySettings"?void 0:Xu(s,t),...s==="policySettings"&&{policyOrigin:r}})),a={};for(let s of Object.keys(n)){let d=n8(s,t);d&&(a[s]={source:CS[d],path:d==="policySettings"?void 0:Xu(d,t),...d==="policySettings"&&{policyOrigin:r}})}return{effective:n,provenance:a,sources:o}}finally{Lm()}}async function S8(e){return w8(e)}async function k8(e,t){try{await nj(e,t)}catch(n){if(!_o(n))throw n}}async function x8(e,t){if(!e)return;let n=e;try{let i=Rn(e);i?.claudeAiOauth?.refreshToken&&(delete i.claudeAiOauth.refreshToken,n=ut(i))}catch{}await GS(t,n,{mode:384})}function C8(){if(process.platform!=="darwin")return Promise.resolve(void 0);let e=fK(pK);return new Promise(t=>{X1("security",["find-generic-password","-a",hK(),"-w","-s",e],{encoding:"utf-8",timeout:5e3,windowsHide:!0},(n,i)=>t(n?void 0:i.trim()||void 0))})}async function eE(e,t,n,i,r=6e4){if(!ot(t))return;let o=gn(n),a=await Jr(e.load({projectKey:o,sessionId:t}),r,`SessionStore.load() timed out after ${r}ms for session ${t}`);if(!a||a.length===0)return;let s=Gt(aj(),`claude-resume-${mm()}`);try{let d=Gt(s,"projects",o);await ep(d,{recursive:!0});let u=Gt(d,`${t}.jsonl`);await gf(u,a);let l=i?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR,p=l??Gt(Np(),".claude"),m;try{m=await HS(Gt(p,".credentials.json"),"utf-8")}catch(f){if(!_o(f))throw f}if(!l&&!(i??process.env).ANTHROPIC_API_KEY&&!(i??process.env).CLAUDE_CODE_OAUTH_TOKEN&&(m=await C8()??m),await x8(m,Gt(s,".credentials.json")),await k8(Gt(l??Np(),".claude.json"),Gt(s,".claude.json")),e.listSubkeys){let f=Gt(d,t),h=await Jr(e.listSubkeys({projectKey:o,sessionId:t}),r,`SessionStore.listSubkeys() timed out after ${r}ms for session ${t}`);for(let y of h){let w=Ma(f,y+".jsonl");if(!y||VS(y)||y.split(/[\\/]/).includes("..")||!w.startsWith(f+hm)){qe(`[SessionStore] skipping unsafe subpath from listSubkeys: ${y}`,{level:"warn"});continue}let g=await Jr(e.load({projectKey:o,sessionId:t,subpath:y}),r,`SessionStore.load() timed out after ${r}ms for session ${t} subpath ${y}`);if(!g||g.length===0)continue;let v=[],b=[];for(let S of g)om(S)?v.push(S):b.push(S);if(b.length>0&&(await ep($v(w),{recursive:!0}),await gf(w,b)),v.length>0){let S=v.at(-1),T=Ma(f,y+".meta.json");await ep($v(T),{recursive:!0});let{type:C,..._}=S;await GS(T,ut(_),{mode:384})}}}return s}catch(d){throw await tl(s),d}}function rm(e,t,n,i){let{systemPrompt:r,settings:o,managedSettings:a,settingSources:s,sandbox:d,...u}=e??{},l,p,m;r===void 0?l="":typeof r=="string"||Array.isArray(r)?l=r:r.type==="preset"&&(p=r.append,m=r.excludeDynamicSections),process.env.CLAUDE_AGENT_SDK_VERSION="0.3.199";let{abortController:f=Dp(),additionalDirectories:h=[],agent:y,agents:w,allowedTools:g=[],betas:v,canUseTool:b,continue:S,cwd:T,debug:C,debugFile:_,disallowedTools:k=[],tools:I,env:P,executable:R=XS()?"bun":"node",executableArgs:M=[],extraArgs:A={},fallbackModel:F,enableFileCheckpointing:se,toolConfig:he,forkSession:ee,hooks:$e,includeHookEvents:be,includePartialMessages:G,forwardSubagentText:$,onElicitation:B,onUserDialog:L,supportedDialogKinds:x,persistSession:E,sessionStore:O,sessionStoreFlush:ne,thinking:X,effort:we,maxThinkingTokens:Se,maxTurns:Je,maxBudgetUsd:j,taskBudget:D,mcpServers:K,model:Y,outputFormat:ue,permissionMode:xe="default",allowDangerouslySkipPermissions:lt=!1,permissionPromptToolName:Ft,plugins:St,getOAuthToken:yt,getHostAuthToken:st,workload:Kn,resume:Ct,resumeSessionAt:To,sessionId:Er,skills:pi,stderr:Ms,strictMcpConfig:js}=u;if(O&&E===!1)throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. Use CLAUDE_CONFIG_DIR=/tmp for ephemeral local writes with external mirroring.");if(x!==void 0&&x.length>0&&!L)throw Error("supportedDialogKinds requires an onUserDialog callback -- declaring dialog kinds without a handler would park dialogs nothing can answer. Provide onUserDialog, or omit supportedDialogKinds.");if(O&&S&&!Ct&&!O.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");if(O&&se)throw Error("enableFileCheckpointing is not yet supported with sessionStore (backup blobs are not mirrored, so rewindFiles() fails after a store-backed resume).");O&&u.spawnClaudeCodeProcess&&qe("sessionStore with custom spawnClaudeCodeProcess: ensure the subprocess CLAUDE_CONFIG_DIR matches the parent (same path, same separators) or transcript_mirror frames will be dropped.",{level:"warn"}),yK(!!b,xe,g);let Io=u.pathToClaudeCodeExecutable;if(!Io){let zt=dj(import.meta.url),yn=oj(zt),Rr=x4(fi=>yn.resolve(fi));if(!Rr)throw Error(`Native CLI binary for ${process.platform}-${process.arch} not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.`);Io=Rr}let by=ue?.type==="json_schema"?ue.schema:void 0,Tt=P?{...P}:{...process.env};Tt.CLAUDE_CODE_ENTRYPOINT||(Tt.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),Tt.CLAUDE_AGENT_SDK_VERSION||(Tt.CLAUDE_AGENT_SDK_VERSION="0.3.199"),se&&(Tt.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),yt&&(Tt.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH="1"),st&&(Tt.CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH="1"),he?.askUserQuestion?.previewFormat&&(Tt.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT=he.askUserQuestion.previewFormat);let Yl={};if(rw.propagation.inject(rw.context.active(),Yl),"traceparent"in Yl)for(let zt of["TRACEPARENT","TRACESTATE"])zt in(P??{})||delete Tt[zt];for(let[zt,yn]of Object.entries(Yl)){let Rr=zt.toUpperCase();Rr in(P??{})||(Tt[Rr]=yn)}let wy={},Sy=new Map;if(K)for(let[zt,yn]of Object.entries(K))yn.type==="sdk"&&yn.instance?Sy.set(zt,yn.instance):wy[zt]=yn;let Po;if(X)switch(X.type){case"adaptive":Po={type:"adaptive",display:X.display};break;case"enabled":Po={type:"enabled",budgetTokens:X.budgetTokens,display:X.display};break;case"disabled":Po={type:"disabled"};break}else Se!==void 0&&(Po=Se===0?{type:"disabled"}:{type:"enabled",budgetTokens:Se});n&&(Tt.CLAUDE_CONFIG_DIR=n,process.platform==="win32"&&(Tt.CLAUDE_SECURESTORAGE_CONFIG_DIR=P?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??P?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""));let ky=new cf({abortController:f,additionalDirectories:h,agent:y,betas:v,cwd:T,debug:C,debugFile:_,executable:R,executableArgs:M,extraArgs:Kn?{...A,workload:Kn}:A,pathToClaudeCodeExecutable:Io,env:Tt,forkSession:ee,stderr:Ms,thinkingConfig:Po,effort:we,maxTurns:Je,maxBudgetUsd:j,taskBudget:D,model:Y,fallbackModel:F,jsonSchema:by,permissionMode:xe,allowDangerouslySkipPermissions:lt,permissionPromptToolName:Ft,continueConversation:O?void 0:S,resume:Ct,resumeSessionAt:To,sessionId:Er,settings:typeof o=="object"?ut(o):o,managedSettings:a?ut(a):void 0,settingSources:s,skills:pi,allowedTools:g,disallowedTools:k,tools:I,mcpServers:wy,strictMcpConfig:js,canUseTool:!!b,hooks:!!$e,includeHookEvents:be,includePartialMessages:G,persistSession:E,sessionMirror:!!O,plugins:St,sandbox:d,spawnClaudeCodeProcess:u.spawnClaudeCodeProcess,deferSpawn:i}),UE={systemPrompt:l,appendSystemPrompt:p,planModeInstructions:u.planModeInstructions,appendSubagentSystemPrompt:u.appendSubagentSystemPrompt,toolAliases:u.toolAliases,excludeDynamicSections:m,agents:w,title:u.title,skills:pi,webSearchIsolationExemptMcpServers:u.webSearchIsolationExemptMcpServers,promptSuggestions:u.promptSuggestions,agentProgressSummaries:u.agentProgressSummaries,forwardSubagentText:$,supportedDialogKinds:x},Xl=new ff(ky,t,b,$e,f,Sy,by,UE,B,yt,st,L);if(O){let zt=()=>Gt(Tt.CLAUDE_CONFIG_DIR??Gt(Np(),".claude"),"projects"),yn=ne==="eager",Rr=new mf(async(fi,ec)=>{let Eo=ES(fi,zt());Eo?await O.append(Eo,ec):qe(`[SessionStore] dropping mirror frame: filePath ${fi} is not under ${zt()} -- subprocess CLAUDE_CONFIG_DIR likely differs from parent (custom spawnClaudeCodeProcess / container?)`,{level:"warn"})},void 0,(fi,ec)=>{let Eo=ES(fi,zt());Eo&&Xl.reportMirrorError(Eo,ec.message)},yn?0:Fm,yn?0:zm);Xl.setTranscriptMirrorBatcher(Rr)}return{queryInstance:Xl,transport:ky,abortController:f,processEnv:Tt}}function im(e,t,n,i){typeof n=="string"?t.write(ut({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:n}]},parent_tool_use_id:null})+`
33
+ `):e.streamInput(n).catch(r=>i.abort(r))}async function tl(e){for(let t=0;;t++)try{return await ij(e,{recursive:!0,force:!0})}catch(n){if(t>=4||!T8.has(Pt(n)??""))return;await dl((t+1)*100)}}function I8(e,t){e.waitForExit().catch(()=>{}).finally(()=>tl(t))}function P8({prompt:e,options:t}){if((t?.resume||t?.continue)&&t?.sessionStore){let{queryInstance:o,transport:a,abortController:s,processEnv:d}=rm({...t},typeof e=="string",void 0,!0),u=Ma(t.cwd??"."),l=t.sessionStore,p=t.loadTimeoutMs??6e4,m=t.resume;return(async()=>{if(m||(m=(await Jr(l.listSessions(gn(u)),p,`SessionStore.listSessions() timed out after ${p}ms`)).slice().sort((f,h)=>h.mtime-f.mtime)[0]?.sessionId),!!m)return eE(l,m,u,t.env,t.loadTimeoutMs)})().then(f=>{if(f){a.updateResume(m);let h={CLAUDE_CONFIG_DIR:f};if(process.platform==="win32"){let y=t.env?.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??t.env?.CLAUDE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??"";h.CLAUDE_SECURESTORAGE_CONFIG_DIR=y,d.CLAUDE_SECURESTORAGE_CONFIG_DIR=y}a.updateEnv(h),d.CLAUDE_CONFIG_DIR=f,o.addCleanupCallback(()=>I8(a,f))}o.isClosed()||a.spawn()}).catch(f=>{let h=hs(f);a.spawnAbort(h),o.setError(h)}),im(o,a,e,s),o}let{queryInstance:n,transport:i,abortController:r}=rm(t,typeof e=="string");return im(n,i,e,r),n}async function E8({options:e,initializeTimeoutMs:t=6e4}={}){let n,i=e?.resume;if((i||e?.continue)&&e?.sessionStore){let s=Ma(e.cwd??".");if(!i){if(!e.sessionStore.listSessions)throw Error("Options.continue with sessionStore requires store.listSessions to be implemented");let d=e.loadTimeoutMs??6e4;i=(await Jr(e.sessionStore.listSessions(gn(s)),d,`SessionStore.listSessions() timed out after ${d}ms`)).slice().sort((u,l)=>l.mtime-u.mtime)[0]?.sessionId}i&&(n=await eE(e.sessionStore,i,s,e.env,e.loadTimeoutMs))}let r,o,a;try{let s=function(){m||(m=!0,p.close())},d=rm(n&&i&&i!==e?.resume?{...e,resume:i}:e,!1,n);r=d.queryInstance;let{transport:u,abortController:l}=d;o=u;let p=d.queryInstance;if(n){let f=n;p.addCleanupCallback(()=>{a=u.waitForExit().catch(()=>{}).then(()=>tl(f))})}await Jr(p.initializationResult(),t,`Subprocess initialization did not complete within ${t}ms \u2014 check authentication and network connectivity`);let m=!1;return{query(f){if(m)throw Error("WarmQuery.query() can only be called once");m=!0;try{im(p,u,f,l)}catch(h){throw p.close(),h}return typeof f=="string"&&p.setIsSingleUserTurn(!0),p},close:s,async[Symbol.asyncDispose](){m=!0,p.close(),await a}}}catch(s){if(r?.close(),n&&!a){let d=o;a=(d?d.waitForExit().catch(()=>{}):Promise.resolve()).then(()=>tl(n))}throw await a,s}}async function R8(e,t){return t?.sessionStore?B8(t.sessionStore,e,t):xB(e,t)}async function O8(e){return e?.sessionStore?F8(e.sessionStore,e):$B(e)}async function A8(e,t){return t?.sessionStore?K8(t.sessionStore,e,t):MB(e,t)}async function $8(e,t,n){return n?.sessionStore?J8(n.sessionStore,e,t,n.dir):NB(e,t,n)}async function M8(e,t,n){return n?.sessionStore?W8(n.sessionStore,e,t,n.dir):DB(e,t,n)}async function j8(e,t){if(!ot(e))throw new Cn(`Invalid sessionId: ${e}`,"deleteSession: invalid sessionId (must be a UUID)");if(t?.sessionStore){if(!t.sessionStore.delete)return;let n=gn(t.dir);await t.sessionStore.delete({projectKey:n,sessionId:e});return}return LB(e,t)}async function q8(e,t){return t?.sessionStore?H8(t.sessionStore,e,t):JB(e,t)}async function N8(e,t,n){if(!ot(e))throw new Cn(`Invalid sessionId: ${e}`,"importSessionToStore: invalid sessionId (must be a UUID)");let i=await bl(e,n?.dir);if(!i)throw Error(`Session ${e} not found`);let r=gn(n?.dir),o=n?.batchSize&&n.batchSize>0?n.batchSize:Fm;if(await TS(i.filePath,{projectKey:r,sessionId:e},t,o),n?.includeSubagents===!1)return;let a=i.filePath.replace(/\.jsonl$/,""),s=Gt(a,"subagents");for(let d of await D8(s)){let u=ZS(a,d).split(hm);u[u.length-1]=u.at(-1).replace(/\.jsonl$/,"");let l={projectKey:r,sessionId:e,subpath:u.join("/")};await TS(d,l,t,o);let p=d.replace(/\.jsonl$/,".meta.json");try{let m=Rn(await HS(p,"utf8"));await t.append(l,[{type:"agent_metadata",...m}])}catch(m){if(!_o(m))throw m}}}async function TS(e,t,n,i){let r=sj({input:ej(e,{encoding:"utf8"}),crlfDelay:1/0}),o=[],a=0;for await(let s of r)s&&(o.push(Rn(s)),a+=s.length,(o.length>=i||a>=zm)&&(await n.append(t,o),o=[],a=0));o.length>0&&await n.append(t,o)}async function D8(e){let t=[];async function n(i){let r;try{r=await rj(i,{withFileTypes:!0})}catch{return}for(let o of r){let a=Gt(i,o.name);o.isDirectory()?await n(a):o.isFile()&&o.name.endsWith(".jsonl")&&t.push(a)}}return await n(e),t}async function L8(e,t){return t?.sessionStore?G8(t.sessionStore,e,t.dir):YB(e,t)}async function U8(e,t,n){return n?.sessionStore?V8(n.sessionStore,e,t,n):XB(e,t,n)}function tE(e){let t=Ma(e??"."),n;try{n=tj(t)}catch{n=t}return Bi(n)}function gn(e){return _s(tE(e))}function nE(e){return e.map(t=>ut(t)).join(`
34
+ `)+`
35
+ `}function IS(e,t,n){return t!==void 0&&t>0?e.slice(n,n+t):n>0?e.slice(n):e}function om(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="agent_metadata"}async function F8(e,t){let n=tE(t.dir),i=_s(n),r=t.offset??0,o=t.limit;if(e.listSessionSummaries){let d=await e.listSessionSummaries(i),u=e.listSessions?new Map((await e.listSessions(i)).map(f=>[f.sessionId,f])):void 0,l=[];for(let f of d){let h=u?.get(f.sessionId);if(u&&!h)continue;let y=h!==void 0&&f.mtime<h.mtime;l.push({sessionId:f.sessionId,mtime:y?h.mtime:f.mtime,info:y?void 0:kj(f,n)})}if(u){let f=new Set(d.map(h=>h.sessionId));for(let[h,y]of u)f.has(h)||l.push({sessionId:h,mtime:y.mtime})}else qe("listSessionSummaries without listSessions: gap-fill skipped; sessions lacking a sidecar will be omitted");l.sort((f,h)=>h.mtime-f.mtime);let p=IS(l,o,r),m=p.filter(f=>f.info===void 0);if(m.length>0){let f=await PS(e,m,t.dir,n),h=new Map(f.map(y=>[y.sessionId,y]));for(let y of p)y.info===void 0&&(y.info=h.get(y.sessionId)??null)}return p.flatMap(f=>f.info?[f.info]:[])}if(!e.listSessions)throw Error("sessionStore.listSessions is not implemented -- cannot list sessions. Provide a store with a listSessions() method.");let a=(await e.listSessions(i)).slice().sort((d,u)=>u.mtime-d.mtime),s=IS(a,o,r);return PS(e,s,t.dir,n)}async function PS(e,t,n,i){return(await Promise.allSettled(t.map(async r=>{let o=await iE(e,r.sessionId,n);if(!o)return null;let a=wl(r.sessionId,rE(o,r.mtime),i);return a?{...a,lastModified:r.mtime}:null}))).flatMap((r,o)=>{let a=t[o];return r.status==="fulfilled"?r.value?[r.value]:[]:[{sessionId:a.sessionId,summary:"",lastModified:a.mtime}]})}function rE(e,t){let n=Buffer.from(e,"utf-8"),i=n.length,r=n.subarray(0,er).toString("utf-8"),o=i>er?n.subarray(i-er).toString("utf-8"):r;return{mtime:t,size:i,head:r,tail:o}}function z8(e){let t=e.trimEnd(),n=t.slice(t.lastIndexOf(`
36
+ `)+1);try{let i=Rn(n);if(typeof i=="object"&&i!==null&&"timestamp"in i&&typeof i.timestamp=="string"){let r=Date.parse(i.timestamp);if(!Number.isNaN(r))return r}}catch{}return Date.now()}async function iE(e,t,n){let i=gn(n),r=await e.load({projectKey:i,sessionId:t});return!r||r.length===0?null:nE(r)}async function B8(e,t,n){if(!ot(t))return[];let i=gn(n.dir),r=await e.load({projectKey:i,sessionId:t});return!r||r.length===0?[]:kB(r,{limit:n.limit,offset:n.offset,includeSystemMessages:n.includeSystemMessages})}async function K8(e,t,n){if(!ot(t))return;let i=await iE(e,t,n.dir);if(!i)return;let r=rE(i,z8(i));return wl(t,r)??void 0}async function J8(e,t,n,i){if(!ot(t))throw new Cn(`Invalid sessionId: ${t}`,"renameSession: invalid sessionId (must be a UUID)");if(!n.trim())throw Error("title must be non-empty");let r=gn(i);await e.append({projectKey:r,sessionId:t},[{type:"custom-title",customTitle:n.trim(),sessionId:t,uuid:mm(),timestamp:new Date().toISOString()}])}async function W8(e,t,n,i){if(!ot(t))throw new Cn(`Invalid sessionId: ${t}`,"tagSession: invalid sessionId (must be a UUID)");if(n!==null){let o=Oa(n).trim();if(!o)throw Error("tag must be non-empty (use null to clear)");n=o}let r=gn(i);await e.append({projectKey:r,sessionId:t},[{type:"tag",tag:n??"",sessionId:t,uuid:mm(),timestamp:new Date().toISOString()}])}async function H8(e,t,n){if(!ot(t))throw new Cn(`Invalid sessionId: ${t}`,"forkSession: invalid sessionId (must be a UUID)");if(n.upToMessageId&&!ot(n.upToMessageId))throw new Cn(`Invalid upToMessageId: ${n.upToMessageId}`,"forkSession: invalid upToMessageId (must be a UUID)");let i=gn(n.dir),r=await e.load({projectKey:i,sessionId:t});if(!r||r.length===0)throw Error(`Session ${t} not found`);let{entries:o,forkedSessionId:a}=HB(r,t,n);return await e.append({projectKey:i,sessionId:a},o),{sessionId:a}}async function G8(e,t,n){if(!ot(t))return[];if(!e.listSubkeys)throw Error("sessionStore.listSubkeys is not implemented -- cannot list subagents. Provide a store with a listSubkeys() method.");let i=gn(n),r=await e.listSubkeys({projectKey:i,sessionId:t}),o=new Set;for(let a of r){if(!a.startsWith("subagents/"))continue;let s=a.split("/").at(-1);s.startsWith("agent-")&&o.add(s.slice(6))}return[...o]}async function V8(e,t,n,i){if(!ot(t))return[];if(!n)return[];let r=gn(i.dir),o=`subagents/agent-${n}`;if(e.listSubkeys){let l=await e.listSubkeys({projectKey:r,sessionId:t}),p=`agent-${n}`,m=l.find(f=>f.startsWith("subagents/")&&f.split("/").at(-1)===p);if(!m)return[];o=m}let a=await e.load({projectKey:r,sessionId:t,subpath:o});if(!a||a.length===0)return[];let s=a.findLast(om),d=typeof s?.toolUseId=="string"?s.toolUseId:void 0,u=a.filter(l=>!om(l));return u.length===0?[]:Ix(Buffer.from(nE(u)),{limit:i.limit,offset:i.offset},d)}function ES(e,t){let n=ZS(t,e),i=n.split(hm);if(i[0]===".."||VS(n)||i.length<2)return null;let r=i[0],o=i[1];if(i.length===2&&o.endsWith(".jsonl"))return{projectKey:r,sessionId:o.replace(/\.jsonl$/,"")};if(i.length>=4){let a=i.slice(2),s=a.length-1;return a[s]=a.at(-1).replace(/\.jsonl$/,""),{projectKey:r,sessionId:o,subpath:a.join("/")}}return null}var gM,yM,qp,_M,vM,wM,SM,am,z,kM,Fn,CM,TM,IM,Xe,et,PM,EM,RM,RS,OM,po,AM,sm,$M,fo,MM,jM,OS,nl,qM,AS,NM,$S,DM,rl,MS,dm,um,jS,lm,qS,NS,LM,DS,UM,FM,zM,BM,KM,JM,WM,HM,GM,VM,ZM,QM,YM,XM,e1,t1,n1,r1,Md,Av,Te,Ae,Cr,il,i1,LS,US,jd,o1,En,a1,s1,FS,d1,ol,al,cm,sl,pm,u1,zS,l1,c1,p1,f1,m1,h1,g1,y1,_1,v1,b1,w1,S1,k1,x1,fm,C1,T1,I1,P1,BS,KS,E1,R1,O1,A1,$1,JS,M1,j1,q1,N1,D1,L1,U1,F1,z1,B1,K1,J1,W1,H1,G1,V1,WS,Z1,Q1,Y1,lj,zoe,ul,_j,vj,bj,wj,Sj,Lp,Mt,Dv,Ij,Pj,ek,Ej,Rj,zn,Oj,Nn,tk,Aj,$j,Zo,jj,qj,Nj,Lj,Uj,Fj,Lv,ri,Dn,Kj,Jj,Wj,Hj,ym,Vj,np,Uv,Qj,Yj,Xj,ii,tq,nq,rq,iq,oq,aq,sq,uq,cq,oi,fq,ja,hq,yq,_q,vq,bq,Sq,kq,xq,Tq,Iq,Eq,Fv,Oq,ms,ll,Mq,jq,Nq,Lq,Fq,Bq,cl,Kq,qa,Wq,Gq,pl,Qq,Xq,tN,rN,fl,iN,vt,yo,Zoe,nk,Up,me,Rt,Qt,Ki,Dd,Ld,Ud,Fd,zd,Bd,Kd,Jd,Wd,sN,dN,Fp,zv,lN,rk,cN,gr,pN,mN,Kv,Jv,Wv,vm,_N,bN,wN,ak,Hd,SN,kN,wm,xN,Hv,rp,CN,Fe,Bp,Ue,Gv,Vv,Gd,Qv,PN,Yv,zr,ck,EN,RN,ON,km,AN,fk,Wt,Ht,Vr,Qo,Zr,Kp,va,Vd,od,Zd,Jp,Qr,xt,yk,_k,xm,eb,WN,HN,Wp,vk,GN,VN,Ge,bk,H,tb,XN,de,Qd,Pa,Yd,Xd,eu,tu,Da,nu,ru,Ji,iu,ou,xk,nD,Ri,rD,iD,Ik,rn,ur,Si,Yo,ad,Xo,ea,sd,ta,Vn,na,dd,ud,Dr,ld,cd,ra,ip,rb,pd,op,ap,sp,ib,ob,Gp,au,oD,aD,ia,ki,Lr,ct,$t,Jt,Xn,lr,oa,sb,Vp,su,ub,dD,Yr,du,uu,Wi,lu,La,cu,Ua,qt,pu,on,cr,xi,aa,fd,sa,da,md,ua,Zn,la,hd,gd,Ur,yd,_d,ca,dp,pb,up,lp,cp,pp,fb,mb,Zp,fu,Fa,gb,lD,mu,Qp,Cm,Ad,Rk,cD,pD,it,Hi,Cn,fD,ID,PD,ED,RD,rae,$D,Yp,jD,Hr,Ci,DD,UD,zD,KD,JD,HD,Ea,GD,gu,Tm,ZD,QD,$k,eL,nL,Sr,iL,Sb,Mk,aL,sL,dL,za,uL,pn,ba,cL,jk,kb,pL,xb,fL,mL,Ba,hL,gL,hl,_L,Im,bL,wL,SL,kL,xL,CL,TL,IL,PL,EL,RL,OL,AL,$L,ML,jL,qL,NL,DL,LL,UL,FL,zL,BL,We,JL,HL,wa,qk,Ra,GL,gp,VL,Xp,Cb,ZL,Pm,QL,YL,Nk,eU,Em,Dk,rU,iU,oU,aU,dU,gl,Lk,pU,fU,mU,gU,Rm,Sa,Uk,Tb,_U,Ib,Pb,Fk,wU,kU,zk,CU,TU,Eb,IU,Bk,Om,EU,Am,RU,OU,AU,Kk,Rb,qU,NU,ef,DU,tf,LU,nf,UU,rf,Ob,FU,Ab,$b,Mb,jb,zU,BU,KU,JU,WU,Br,qb,HU,yu,VU,QU,Nb,YU,XU,tF,nF,iF,aF,sF,uF,cF,pF,fF,Jk,gF,_F,vF,bF,wF,SF,kF,xF,CF,TF,IF,PF,EF,RF,OF,Lb,yp,$F,MF,jF,qF,DF,LF,Ub,Fb,vd,UF,zb,zF,Hk,BF,KF,WF,Gk,VF,Vk,YF,XF,$m,tz,nz,Mm,iz,az,sz,dz,uz,lz,Zk,pz,Bb,Kb,fz,hz,yl,yz,gs,jm,wz,kz,Cz,Yk,Iz,Pz,Rz,qm,$z,jz,Nz,Xk,ex,uae,lae,zz,Nm,vu,Gz,Vz,Zz,Qz,Yz,Dm,t2,i2,a2,s2,d2,cae,u2,pae,l2,fae,c2,mae,p2,hae,bu,v2,_ae,b2,bd,U2,F2,W2,Zb,bae,V2,Qb,ix,Z2,Yb,Q2,Y2,Xb,df,t4,n4,ox,r4,ax,sx,o4,a4,pa,_p,Oi,ka,tw,fa,vp,uf,c4,wae,p4,tt,Rn,y4,wu,nw,cf,Ti,Su,T4,pf,bp,ff,Fm,zm,P4,mf,rw,Ii,z4,B4,G4,er,Z4,Y4,Ja,iB,oB,aB,xu,dB,Wa,uB,lB,aw,sw,IB,zB,rK,Rx,iK,oK,aK,Gae,sK,Vae,cw,dK,lK,pK,mK,Oe,pw,ae,mr,W,ln,_K,Ha,vK,bf,Ot,ye,Ca,Nt,fw,mw,Vi,Cu,le,fn,hw,Ie,bK,wK,SK,kK,xK,CK,TK,IK,PK,kp,EK,RK,OK,AK,$K,MK,Ox,jK,Zi,Ga,Va,Za,Qa,Ya,Qi,Yi,Xa,br,Ln,es,kr,Xt,Xi,Qn,wf,eo,rr,kf,ts,ns,xf,to,no,ro,io,Xr,Tn,cn,ir,oo,ao,rs,Tu,Iu,so,Zae,V,Qae,Yae,Xae,ese,tse,nse,rse,ise,ose,ase,sse,dse,use,lse,zK,cse,pse,fse,mse,hse,gse,yse,_se,vse,bse,wse,Sse,kse,xse,Cse,Tse,Ise,Pse,Ese,Mx,jx,qx,xr,Pu,Ee,Hm,Lx,YK,Eu,Ux,zx,Bx,Cf,Jx,Gm,bs,Qm,Ru,Ym,Ou,Xm,Tl,eh,Il,th,Vx,Zx,Qx,Yx,Xx,e0,t0,sJ,n0,uo,dJ,uJ,lJ,r0,cJ,pJ,fJ,mJ,hJ,o0,a0,s0,d0,u0,nh,l0,gJ,c0,p0,f0,y0,_0,v0,b0,w0,S0,k0,x0,C0,at,T0,rh,ih,I0,P0,E0,R0,O0,A0,$0,M0,j0,ws,q0,N0,D0,L0,U0,F0,z0,B0,K0,Au,J0,ve,Ss,Ke,W0,H0,G0,V0,Z0,Q0,Y0,X0,eC,tC,nC,rC,iC,oC,aC,sC,dC,uC,lC,cC,fC,mC,gC,yC,ah,_C,sh,dh,vC,bC,wC,SC,kC,$u,xC,CC,TC,uh,lh,ch,IC,PC,Pl,EC,RC,OC,AC,$C,MC,ph,jC,qC,NC,DC,LC,UC,FC,zC,fh,BC,KC,JC,WC,HC,mh,yJ,vJ,wJ,kJ,CJ,IJ,EJ,RJ,OJ,AJ,MJ,qJ,DJ,UJ,zJ,KJ,WJ,GJ,ZJ,YJ,e6,n6,i6,a6,d6,l6,p6,m6,g6,_6,b6,S6,x6,T6,P6,R6,O6,$6,j6,N6,L6,F6,VC,ZC,as,tr,XC,qu,us,lW,cW,pW,c,Qh,Yh,Xh,eg,tg,BT,hW,xs,KT,JT,WT,HT,Pe,ng,Al,Ve,rg,Nu,nr,ig,og,ag,sg,dg,ug,lg,cg,pg,fg,mg,hg,gg,yg,_g,vg,GT,$l,bo,Ml,jl,bg,VT,ZT,QT,YT,XT,eI,tI,Sg,nI,Nl,kg,rI,iI,oI,Cg,aI,sI,ls,dI,uI,Tg,Pg,lI,cI,fI,Eg,gI,yI,vI,Rg,bI,SI,kI,CI,Ll,cH,fH,RI,wH,OI,AI,SH,Kr,Ul,mt,$I,MI,Rse,kH,xH,Ag,en,Cs,CH,bt,mn,hn,wt,Fl,jI,Ow,qI,TH,$g,Cd,ge,Mg,IH,Ose,Ase,jg,PH,qg,EH,Ts,co,NI,RH,OH,AH,$H,MH,jH,DI,qH,NH,LI,Ng,DH,LH,Dg,UH,Is,Ps,FH,Es,zl,zH,Uu,Lg,Ug,Fg,$se,zg,Bg,Kg,BH,UI,FI,Jg,zI,Rs,wo,BI,KH,Pf,JH,Ef,WH,Wg,HH,Rf,GH,VH,ZH,QH,YH,XH,e9,t9,n9,r9,Of,i9,o9,Af,Hg,Gg,Vg,a9,s9,d9,Zg,u9,l9,c9,p9,f9,KI,$f,m9,Qg,Mse,h9,Fu,g9,jse,zu,y9,JI,_9,v9,b9,w9,S9,k9,x9,Bu,C9,T9,I9,Yg,WI,P9,E9,R9,O9,A9,$9,M9,j9,q9,N9,D9,L9,U9,F9,z9,B9,K9,J9,Ku,W9,H9,G9,Mf,Q9,Y9,X9,HI,eG,qse,Nse,Dse,Lse,Use,Fse,pe,jf,tG,Aw,nG,rG,VI,sG,dG,pG,Tp,wn,hG,Ju,Mw,IG,PG,MG,jG,qG,NG,DG,UG,qf,zG,BG,Nf,Df,Lf,eP,Uw,GG,Uf,Ff,QG,ha,Kw,nV,sn,Bf,Kf,Ww,Hw,Jse,Wse,Gw,Vw,Zw,Qw,yr,Xg,ji,mV,hV,gV,Zse,bV,Pp,SV,Yw,Qse,Pi,sP,Hf,dP,Wu,Xw,kV,fr,uP,Fi,Gf,Vf,CV,eS,Kl,Jl,nde,rde,ide,cs,ode,Zf,RV,OV,AV,MV,jV,qV,NV,pP,DV,LV,FV,Qf,KV,WV,HV,VV,tS,mP,YV,XV,e5,t5,n5,r5,o5,a5,hP,d5,l5,p5,f5,_r,h5,gP,_5,nS,b5,w5,k5,C5,T5,Ep,P5,R5,A5,M5,_P,vP,bP,q5,N5,dde,D5,Rp,L5,U5,B5,H5,rS,Yf,Xf,qi,V5,Z5,Q5,iS,Hu,X5,e3,SP,kP,t3,xP,n3,r3,i3,o3,a3,cde,ey,s3,d3,pde,fde,u3,ga,c3,p3,Gu,mde,hde,So,Ir,f3,m3,CP,TP,h3,g3,y3,_3,v3,b3,ty,w3,em,gde,S3,k3,IP,x3,C3,Pn,ni,aS,tm,nm,PP,ny,I3,yde,P3,E3,R3,O3,A3,EP,$3,M3,j3,q3,RP,N3,sS,D3,L3,OP,U3,F3,dS,z3,B3,AP,K3,$P,J3,W3,H3,V3,Z3,Q3,Y3,Vu,Op,MP,X3,eZ,tZ,nZ,rZ,_de,jP,oZ,aZ,sZ,dZ,uZ,lZ,cZ,vde,pZ,bde,fZ,Td,Wl,uS,DP,wde,Sde,Zu,pS,CZ,TZ,kde,IZ,ry,iy,PZ,fS,mS,EZ,Hl,hS,Yn,OZ,AZ,xde,qZ,DZ,BZ,Mp,o8,hr,QP,YP,XP,el,g8,CS,y8,_8,v8,T8,aE=WE(()=>{gM=Object.create,{getPrototypeOf:yM,defineProperty:qp,getOwnPropertyNames:_M}=Object,vM=Object.prototype.hasOwnProperty;am=(e,t,n)=>{var i=e!=null&&typeof e=="object";if(i){var r=t?wM??=new WeakMap:SM??=new WeakMap,o=r.get(e);if(o)return o}n=e!=null?gM(yM(e)):{};let a=t||!e||!e.__esModule?qp(n,"default",{value:e,enumerable:!0}):n;for(let s of _M(e))vM.call(a,s)||qp(a,s,{get:bM.bind(e,s),enumerable:!0});return i&&r.set(e,a),a},z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),kM=e=>e;Fn=(e,t)=>{for(var n in t)qp(e,n,{get:t[n],enumerable:!0,configurable:!0,set:xM.bind(t,n)})},CM=hM(import.meta.url),TM=Symbol.dispose||Symbol.for("Symbol.dispose"),IM=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),Xe=(e,t,n)=>{if(t!=null){if(typeof t!="object"&&typeof t!="function")throw TypeError('Object expected to be assigned to "using" declaration');var i;if(n&&(i=t[IM]),i===void 0&&(i=t[TM]),typeof i!="function")throw TypeError("Object not disposable");e.push([n,i,t])}else n&&e.push([n]);return t},et=(e,t,n)=>{var i=typeof SuppressedError=="function"?SuppressedError:function(a,s,d,u){return u=Error(d),u.name="SuppressedError",u.error=a,u.suppressed=s,u},r=a=>t=n?new i(a,t,"An error was suppressed during disposal"):(n=!0,a),o=a=>{for(;a=e.pop();)try{var s=a[1]&&a[1].call(a[2]);if(a[0])return Promise.resolve(s).then(o,d=>(r(d),o()))}catch(d){r(d)}if(n)throw t};return o()},PM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e._globalThis=void 0,e._globalThis=typeof globalThis=="object"?globalThis:global}),EM=z(e=>{var t=e&&e.__createBinding||(Object.create?function(i,r,o,a){a===void 0&&(a=o),Object.defineProperty(i,a,{enumerable:!0,get:function(){return r[o]}})}:function(i,r,o,a){a===void 0&&(a=o),i[a]=r[o]}),n=e&&e.__exportStar||function(i,r){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(r,o)&&t(r,i,o)};Object.defineProperty(e,"__esModule",{value:!0}),n(PM(),e)}),RM=z(e=>{var t=e&&e.__createBinding||(Object.create?function(i,r,o,a){a===void 0&&(a=o),Object.defineProperty(i,a,{enumerable:!0,get:function(){return r[o]}})}:function(i,r,o,a){a===void 0&&(a=o),i[a]=r[o]}),n=e&&e.__exportStar||function(i,r){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(r,o)&&t(r,i,o)};Object.defineProperty(e,"__esModule",{value:!0}),n(EM(),e)}),RS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.VERSION=void 0,e.VERSION="1.9.0"}),OM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isCompatible=e._makeCompatibilityCheck=void 0;var t=RS(),n=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function i(r){let o=new Set([r]),a=new Set,s=r.match(n);if(!s)return()=>!1;let d={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};if(d.prerelease!=null)return function(p){return p===r};function u(p){return a.add(p),!1}function l(p){return o.add(p),!0}return function(p){if(o.has(p))return!0;if(a.has(p))return!1;let m=p.match(n);if(!m)return u(p);let f={major:+m[1],minor:+m[2],patch:+m[3],prerelease:m[4]};return f.prerelease!=null||d.major!==f.major?u(p):d.major===0?d.minor===f.minor&&d.patch<=f.patch?l(p):u(p):d.minor<=f.minor?l(p):u(p)}}e._makeCompatibilityCheck=i,e.isCompatible=i(t.VERSION)}),po=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.unregisterGlobal=e.getGlobal=e.registerGlobal=void 0;var t=RM(),n=RS(),i=OM(),r=n.VERSION.split(".")[0],o=Symbol.for(`opentelemetry.js.api.${r}`),a=t._globalThis;function s(l,p,m,f=!1){var h;let y=a[o]=(h=a[o])!==null&&h!==void 0?h:{version:n.VERSION};if(!f&&y[l]){let w=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${l}`);return m.error(w.stack||w.message),!1}if(y.version!==n.VERSION){let w=Error(`@opentelemetry/api: Registration of version v${y.version} for ${l} does not match previously registered API v${n.VERSION}`);return m.error(w.stack||w.message),!1}return y[l]=p,m.debug(`@opentelemetry/api: Registered a global for ${l} v${n.VERSION}.`),!0}e.registerGlobal=s;function d(l){var p,m;let f=(p=a[o])===null||p===void 0?void 0:p.version;if(!(!f||!(0,i.isCompatible)(f)))return(m=a[o])===null||m===void 0?void 0:m[l]}e.getGlobal=d;function u(l,p){p.debug(`@opentelemetry/api: Unregistering a global for ${l} v${n.VERSION}.`);let m=a[o];m&&delete m[l]}e.unregisterGlobal=u}),AM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiagComponentLogger=void 0;var t=po();class n{constructor(o){this._namespace=o.namespace||"DiagComponentLogger"}debug(...o){return i("debug",this._namespace,o)}error(...o){return i("error",this._namespace,o)}info(...o){return i("info",this._namespace,o)}warn(...o){return i("warn",this._namespace,o)}verbose(...o){return i("verbose",this._namespace,o)}}e.DiagComponentLogger=n;function i(r,o,a){let s=(0,t.getGlobal)("diag");if(s)return a.unshift(o),s[r](...a)}}),sm=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiagLogLevel=void 0;var t;(function(n){n[n.NONE=0]="NONE",n[n.ERROR=30]="ERROR",n[n.WARN=50]="WARN",n[n.INFO=60]="INFO",n[n.DEBUG=70]="DEBUG",n[n.VERBOSE=80]="VERBOSE",n[n.ALL=9999]="ALL"})(t=e.DiagLogLevel||(e.DiagLogLevel={}))}),$M=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createLogLevelDiagLogger=void 0;var t=sm();function n(i,r){i<t.DiagLogLevel.NONE?i=t.DiagLogLevel.NONE:i>t.DiagLogLevel.ALL&&(i=t.DiagLogLevel.ALL),r=r||{};function o(a,s){let d=r[a];return typeof d=="function"&&i>=s?d.bind(r):function(){}}return{error:o("error",t.DiagLogLevel.ERROR),warn:o("warn",t.DiagLogLevel.WARN),info:o("info",t.DiagLogLevel.INFO),debug:o("debug",t.DiagLogLevel.DEBUG),verbose:o("verbose",t.DiagLogLevel.VERBOSE)}}e.createLogLevelDiagLogger=n}),fo=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiagAPI=void 0;var t=AM(),n=$M(),i=sm(),r=po(),o="diag";class a{constructor(){function d(p){return function(...m){let f=(0,r.getGlobal)("diag");if(f)return f[p](...m)}}let u=this,l=(p,m={logLevel:i.DiagLogLevel.INFO})=>{var f,h,y;if(p===u){let v=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return u.error((f=v.stack)!==null&&f!==void 0?f:v.message),!1}typeof m=="number"&&(m={logLevel:m});let w=(0,r.getGlobal)("diag"),g=(0,n.createLogLevelDiagLogger)((h=m.logLevel)!==null&&h!==void 0?h:i.DiagLogLevel.INFO,p);if(w&&!m.suppressOverrideMessage){let v=(y=Error().stack)!==null&&y!==void 0?y:"<failed to generate stacktrace>";w.warn(`Current logger will be overwritten from ${v}`),g.warn(`Current logger will overwrite one already registered from ${v}`)}return(0,r.registerGlobal)("diag",g,u,!0)};u.setLogger=l,u.disable=()=>{(0,r.unregisterGlobal)(o,u)},u.createComponentLogger=p=>new t.DiagComponentLogger(p),u.verbose=d("verbose"),u.debug=d("debug"),u.info=d("info"),u.warn=d("warn"),u.error=d("error")}static instance(){return this._instance||(this._instance=new a),this._instance}}e.DiagAPI=a}),MM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BaggageImpl=void 0;class t{constructor(i){this._entries=i?new Map(i):new Map}getEntry(i){let r=this._entries.get(i);if(r)return Object.assign({},r)}getAllEntries(){return Array.from(this._entries.entries()).map(([i,r])=>[i,r])}setEntry(i,r){let o=new t(this._entries);return o._entries.set(i,r),o}removeEntry(i){let r=new t(this._entries);return r._entries.delete(i),r}removeEntries(...i){let r=new t(this._entries);for(let o of i)r._entries.delete(o);return r}clear(){return new t}}e.BaggageImpl=t}),jM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.baggageEntryMetadataSymbol=void 0,e.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")}),OS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.baggageEntryMetadataFromString=e.createBaggage=void 0;var t=fo(),n=MM(),i=jM(),r=t.DiagAPI.instance();function o(s={}){return new n.BaggageImpl(new Map(Object.entries(s)))}e.createBaggage=o;function a(s){return typeof s!="string"&&(r.error(`Cannot create baggage metadata from unknown type: ${typeof s}`),s=""),{__TYPE__:i.baggageEntryMetadataSymbol,toString(){return s}}}e.baggageEntryMetadataFromString=a}),nl=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ROOT_CONTEXT=e.createContextKey=void 0;function t(i){return Symbol.for(i)}e.createContextKey=t;class n{constructor(r){let o=this;o._currentContext=r?new Map(r):new Map,o.getValue=a=>o._currentContext.get(a),o.setValue=(a,s)=>{let d=new n(o._currentContext);return d._currentContext.set(a,s),d},o.deleteValue=a=>{let s=new n(o._currentContext);return s._currentContext.delete(a),s}}}e.ROOT_CONTEXT=new n}),qM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiagConsoleLogger=void 0;var t=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class n{constructor(){function r(o){return function(...a){if(console){let s=console[o];if(typeof s!="function"&&(s=console.log),typeof s=="function")return s.apply(console,a)}}}for(let o=0;o<t.length;o++)this[t[o].n]=r(t[o].c)}}e.DiagConsoleLogger=n}),AS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createNoopMeter=e.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=e.NOOP_OBSERVABLE_GAUGE_METRIC=e.NOOP_OBSERVABLE_COUNTER_METRIC=e.NOOP_UP_DOWN_COUNTER_METRIC=e.NOOP_HISTOGRAM_METRIC=e.NOOP_GAUGE_METRIC=e.NOOP_COUNTER_METRIC=e.NOOP_METER=e.NoopObservableUpDownCounterMetric=e.NoopObservableGaugeMetric=e.NoopObservableCounterMetric=e.NoopObservableMetric=e.NoopHistogramMetric=e.NoopGaugeMetric=e.NoopUpDownCounterMetric=e.NoopCounterMetric=e.NoopMetric=e.NoopMeter=void 0;class t{constructor(){}createGauge(f,h){return e.NOOP_GAUGE_METRIC}createHistogram(f,h){return e.NOOP_HISTOGRAM_METRIC}createCounter(f,h){return e.NOOP_COUNTER_METRIC}createUpDownCounter(f,h){return e.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(f,h){return e.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(f,h){return e.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(f,h){return e.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(f,h){}removeBatchObservableCallback(f){}}e.NoopMeter=t;class n{}e.NoopMetric=n;class i extends n{add(f,h){}}e.NoopCounterMetric=i;class r extends n{add(f,h){}}e.NoopUpDownCounterMetric=r;class o extends n{record(f,h){}}e.NoopGaugeMetric=o;class a extends n{record(f,h){}}e.NoopHistogramMetric=a;class s{addCallback(f){}removeCallback(f){}}e.NoopObservableMetric=s;class d extends s{}e.NoopObservableCounterMetric=d;class u extends s{}e.NoopObservableGaugeMetric=u;class l extends s{}e.NoopObservableUpDownCounterMetric=l,e.NOOP_METER=new t,e.NOOP_COUNTER_METRIC=new i,e.NOOP_GAUGE_METRIC=new o,e.NOOP_HISTOGRAM_METRIC=new a,e.NOOP_UP_DOWN_COUNTER_METRIC=new r,e.NOOP_OBSERVABLE_COUNTER_METRIC=new d,e.NOOP_OBSERVABLE_GAUGE_METRIC=new u,e.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new l;function p(){return e.NOOP_METER}e.createNoopMeter=p}),NM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueType=void 0;var t;(function(n){n[n.INT=0]="INT",n[n.DOUBLE=1]="DOUBLE"})(t=e.ValueType||(e.ValueType={}))}),$S=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.defaultTextMapSetter=e.defaultTextMapGetter=void 0,e.defaultTextMapGetter={get(t,n){if(t!=null)return t[n]},keys(t){return t==null?[]:Object.keys(t)}},e.defaultTextMapSetter={set(t,n,i){t!=null&&(t[n]=i)}}}),DM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoopContextManager=void 0;var t=nl();class n{active(){return t.ROOT_CONTEXT}with(r,o,a,...s){return o.call(a,...s)}bind(r,o){return o}enable(){return this}disable(){return this}}e.NoopContextManager=n}),rl=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ContextAPI=void 0;var t=DM(),n=po(),i=fo(),r="context",o=new t.NoopContextManager;class a{constructor(){}static getInstance(){return this._instance||(this._instance=new a),this._instance}setGlobalContextManager(d){return(0,n.registerGlobal)(r,d,i.DiagAPI.instance())}active(){return this._getContextManager().active()}with(d,u,l,...p){return this._getContextManager().with(d,u,l,...p)}bind(d,u){return this._getContextManager().bind(d,u)}_getContextManager(){return(0,n.getGlobal)(r)||o}disable(){this._getContextManager().disable(),(0,n.unregisterGlobal)(r,i.DiagAPI.instance())}}e.ContextAPI=a}),MS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TraceFlags=void 0;var t;(function(n){n[n.NONE=0]="NONE",n[n.SAMPLED=1]="SAMPLED"})(t=e.TraceFlags||(e.TraceFlags={}))}),dm=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.INVALID_SPAN_CONTEXT=e.INVALID_TRACEID=e.INVALID_SPANID=void 0;var t=MS();e.INVALID_SPANID="0000000000000000",e.INVALID_TRACEID="00000000000000000000000000000000",e.INVALID_SPAN_CONTEXT={traceId:e.INVALID_TRACEID,spanId:e.INVALID_SPANID,traceFlags:t.TraceFlags.NONE}}),um=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NonRecordingSpan=void 0;var t=dm();class n{constructor(r=t.INVALID_SPAN_CONTEXT){this._spanContext=r}spanContext(){return this._spanContext}setAttribute(r,o){return this}setAttributes(r){return this}addEvent(r,o){return this}addLink(r){return this}addLinks(r){return this}setStatus(r){return this}updateName(r){return this}end(r){}isRecording(){return!1}recordException(r,o){}}e.NonRecordingSpan=n}),jS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSpanContext=e.setSpanContext=e.deleteSpan=e.setSpan=e.getActiveSpan=e.getSpan=void 0;var t=nl(),n=um(),i=rl(),r=(0,t.createContextKey)("OpenTelemetry Context Key SPAN");function o(p){return p.getValue(r)||void 0}e.getSpan=o;function a(){return o(i.ContextAPI.getInstance().active())}e.getActiveSpan=a;function s(p,m){return p.setValue(r,m)}e.setSpan=s;function d(p){return p.deleteValue(r)}e.deleteSpan=d;function u(p,m){return s(p,new n.NonRecordingSpan(m))}e.setSpanContext=u;function l(p){var m;return(m=o(p))===null||m===void 0?void 0:m.spanContext()}e.getSpanContext=l}),lm=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.wrapSpanContext=e.isSpanContextValid=e.isValidSpanId=e.isValidTraceId=void 0;var t=dm(),n=um(),i=/^([0-9a-f]{32})$/i,r=/^[0-9a-f]{16}$/i;function o(u){return i.test(u)&&u!==t.INVALID_TRACEID}e.isValidTraceId=o;function a(u){return r.test(u)&&u!==t.INVALID_SPANID}e.isValidSpanId=a;function s(u){return o(u.traceId)&&a(u.spanId)}e.isSpanContextValid=s;function d(u){return new n.NonRecordingSpan(u)}e.wrapSpanContext=d}),qS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoopTracer=void 0;var t=rl(),n=jS(),i=um(),r=lm(),o=t.ContextAPI.getInstance();class a{startSpan(u,l,p=o.active()){if(l?.root)return new i.NonRecordingSpan;let m=p&&(0,n.getSpanContext)(p);return s(m)&&(0,r.isSpanContextValid)(m)?new i.NonRecordingSpan(m):new i.NonRecordingSpan}startActiveSpan(u,l,p,m){let f,h,y;if(arguments.length<2)return;arguments.length===2?y=l:arguments.length===3?(f=l,y=p):(f=l,h=p,y=m);let w=h??o.active(),g=this.startSpan(u,f,w),v=(0,n.setSpan)(w,g);return o.with(v,y,void 0,g)}}e.NoopTracer=a;function s(d){return typeof d=="object"&&typeof d.spanId=="string"&&typeof d.traceId=="string"&&typeof d.traceFlags=="number"}}),NS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ProxyTracer=void 0;var t=qS(),n=new t.NoopTracer;class i{constructor(o,a,s,d){this._provider=o,this.name=a,this.version=s,this.options=d}startSpan(o,a,s){return this._getTracer().startSpan(o,a,s)}startActiveSpan(o,a,s,d){let u=this._getTracer();return Reflect.apply(u.startActiveSpan,u,arguments)}_getTracer(){if(this._delegate)return this._delegate;let o=this._provider.getDelegateTracer(this.name,this.version,this.options);return o?(this._delegate=o,this._delegate):n}}e.ProxyTracer=i}),LM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoopTracerProvider=void 0;var t=qS();class n{getTracer(r,o,a){return new t.NoopTracer}}e.NoopTracerProvider=n}),DS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ProxyTracerProvider=void 0;var t=NS(),n=LM(),i=new n.NoopTracerProvider;class r{getTracer(a,s,d){var u;return(u=this.getDelegateTracer(a,s,d))!==null&&u!==void 0?u:new t.ProxyTracer(this,a,s,d)}getDelegate(){var a;return(a=this._delegate)!==null&&a!==void 0?a:i}setDelegate(a){this._delegate=a}getDelegateTracer(a,s,d){var u;return(u=this._delegate)===null||u===void 0?void 0:u.getTracer(a,s,d)}}e.ProxyTracerProvider=r}),UM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SamplingDecision=void 0;var t;(function(n){n[n.NOT_RECORD=0]="NOT_RECORD",n[n.RECORD=1]="RECORD",n[n.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(t=e.SamplingDecision||(e.SamplingDecision={}))}),FM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpanKind=void 0;var t;(function(n){n[n.INTERNAL=0]="INTERNAL",n[n.SERVER=1]="SERVER",n[n.CLIENT=2]="CLIENT",n[n.PRODUCER=3]="PRODUCER",n[n.CONSUMER=4]="CONSUMER"})(t=e.SpanKind||(e.SpanKind={}))}),zM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SpanStatusCode=void 0;var t;(function(n){n[n.UNSET=0]="UNSET",n[n.OK=1]="OK",n[n.ERROR=2]="ERROR"})(t=e.SpanStatusCode||(e.SpanStatusCode={}))}),BM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateValue=e.validateKey=void 0;var t="[_0-9a-z-*/]",n=`[a-z]${t}{0,255}`,i=`[a-z0-9]${t}{0,240}@[a-z]${t}{0,13}`,r=new RegExp(`^(?:${n}|${i})$`),o=/^[ -~]{0,255}[!-~]$/,a=/,|=/;function s(u){return r.test(u)}e.validateKey=s;function d(u){return o.test(u)&&!a.test(u)}e.validateValue=d}),KM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TraceStateImpl=void 0;var t=BM(),n=32,i=512,r=",",o="=";class a{constructor(d){this._internalState=new Map,d&&this._parse(d)}set(d,u){let l=this._clone();return l._internalState.has(d)&&l._internalState.delete(d),l._internalState.set(d,u),l}unset(d){let u=this._clone();return u._internalState.delete(d),u}get(d){return this._internalState.get(d)}serialize(){return this._keys().reduce((d,u)=>(d.push(u+o+this.get(u)),d),[]).join(r)}_parse(d){d.length>i||(this._internalState=d.split(r).reverse().reduce((u,l)=>{let p=l.trim(),m=p.indexOf(o);if(m!==-1){let f=p.slice(0,m),h=p.slice(m+1,l.length);(0,t.validateKey)(f)&&(0,t.validateValue)(h)&&u.set(f,h)}return u},new Map),this._internalState.size>n&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,n))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let d=new a;return d._internalState=new Map(this._internalState),d}}e.TraceStateImpl=a}),JM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createTraceState=void 0;var t=KM();function n(i){return new t.TraceStateImpl(i)}e.createTraceState=n}),WM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.context=void 0;var t=rl();e.context=t.ContextAPI.getInstance()}),HM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.diag=void 0;var t=fo();e.diag=t.DiagAPI.instance()}),GM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NOOP_METER_PROVIDER=e.NoopMeterProvider=void 0;var t=AS();class n{getMeter(r,o,a){return t.NOOP_METER}}e.NoopMeterProvider=n,e.NOOP_METER_PROVIDER=new n}),VM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MetricsAPI=void 0;var t=GM(),n=po(),i=fo(),r="metrics";class o{constructor(){}static getInstance(){return this._instance||(this._instance=new o),this._instance}setGlobalMeterProvider(s){return(0,n.registerGlobal)(r,s,i.DiagAPI.instance())}getMeterProvider(){return(0,n.getGlobal)(r)||t.NOOP_METER_PROVIDER}getMeter(s,d,u){return this.getMeterProvider().getMeter(s,d,u)}disable(){(0,n.unregisterGlobal)(r,i.DiagAPI.instance())}}e.MetricsAPI=o}),ZM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.metrics=void 0;var t=VM();e.metrics=t.MetricsAPI.getInstance()}),QM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoopTextMapPropagator=void 0;class t{inject(i,r){}extract(i,r){return i}fields(){return[]}}e.NoopTextMapPropagator=t}),YM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.deleteBaggage=e.setBaggage=e.getActiveBaggage=e.getBaggage=void 0;var t=rl(),n=nl(),i=(0,n.createContextKey)("OpenTelemetry Baggage Key");function r(d){return d.getValue(i)||void 0}e.getBaggage=r;function o(){return r(t.ContextAPI.getInstance().active())}e.getActiveBaggage=o;function a(d,u){return d.setValue(i,u)}e.setBaggage=a;function s(d){return d.deleteValue(i)}e.deleteBaggage=s}),XM=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PropagationAPI=void 0;var t=po(),n=QM(),i=$S(),r=YM(),o=OS(),a=fo(),s="propagation",d=new n.NoopTextMapPropagator;class u{constructor(){this.createBaggage=o.createBaggage,this.getBaggage=r.getBaggage,this.getActiveBaggage=r.getActiveBaggage,this.setBaggage=r.setBaggage,this.deleteBaggage=r.deleteBaggage}static getInstance(){return this._instance||(this._instance=new u),this._instance}setGlobalPropagator(p){return(0,t.registerGlobal)(s,p,a.DiagAPI.instance())}inject(p,m,f=i.defaultTextMapSetter){return this._getGlobalPropagator().inject(p,m,f)}extract(p,m,f=i.defaultTextMapGetter){return this._getGlobalPropagator().extract(p,m,f)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,t.unregisterGlobal)(s,a.DiagAPI.instance())}_getGlobalPropagator(){return(0,t.getGlobal)(s)||d}}e.PropagationAPI=u}),e1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.propagation=void 0;var t=XM();e.propagation=t.PropagationAPI.getInstance()}),t1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TraceAPI=void 0;var t=po(),n=DS(),i=lm(),r=jS(),o=fo(),a="trace";class s{constructor(){this._proxyTracerProvider=new n.ProxyTracerProvider,this.wrapSpanContext=i.wrapSpanContext,this.isSpanContextValid=i.isSpanContextValid,this.deleteSpan=r.deleteSpan,this.getSpan=r.getSpan,this.getActiveSpan=r.getActiveSpan,this.getSpanContext=r.getSpanContext,this.setSpan=r.setSpan,this.setSpanContext=r.setSpanContext}static getInstance(){return this._instance||(this._instance=new s),this._instance}setGlobalTracerProvider(u){let l=(0,t.registerGlobal)(a,this._proxyTracerProvider,o.DiagAPI.instance());return l&&this._proxyTracerProvider.setDelegate(u),l}getTracerProvider(){return(0,t.getGlobal)(a)||this._proxyTracerProvider}getTracer(u,l){return this.getTracerProvider().getTracer(u,l)}disable(){(0,t.unregisterGlobal)(a,o.DiagAPI.instance()),this._proxyTracerProvider=new n.ProxyTracerProvider}}e.TraceAPI=s}),n1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.trace=void 0;var t=t1();e.trace=t.TraceAPI.getInstance()}),r1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.trace=e.propagation=e.metrics=e.diag=e.context=e.INVALID_SPAN_CONTEXT=e.INVALID_TRACEID=e.INVALID_SPANID=e.isValidSpanId=e.isValidTraceId=e.isSpanContextValid=e.createTraceState=e.TraceFlags=e.SpanStatusCode=e.SpanKind=e.SamplingDecision=e.ProxyTracerProvider=e.ProxyTracer=e.defaultTextMapSetter=e.defaultTextMapGetter=e.ValueType=e.createNoopMeter=e.DiagLogLevel=e.DiagConsoleLogger=e.ROOT_CONTEXT=e.createContextKey=e.baggageEntryMetadataFromString=void 0;var t=OS();Object.defineProperty(e,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return t.baggageEntryMetadataFromString}});var n=nl();Object.defineProperty(e,"createContextKey",{enumerable:!0,get:function(){return n.createContextKey}}),Object.defineProperty(e,"ROOT_CONTEXT",{enumerable:!0,get:function(){return n.ROOT_CONTEXT}});var i=qM();Object.defineProperty(e,"DiagConsoleLogger",{enumerable:!0,get:function(){return i.DiagConsoleLogger}});var r=sm();Object.defineProperty(e,"DiagLogLevel",{enumerable:!0,get:function(){return r.DiagLogLevel}});var o=AS();Object.defineProperty(e,"createNoopMeter",{enumerable:!0,get:function(){return o.createNoopMeter}});var a=NM();Object.defineProperty(e,"ValueType",{enumerable:!0,get:function(){return a.ValueType}});var s=$S();Object.defineProperty(e,"defaultTextMapGetter",{enumerable:!0,get:function(){return s.defaultTextMapGetter}}),Object.defineProperty(e,"defaultTextMapSetter",{enumerable:!0,get:function(){return s.defaultTextMapSetter}});var d=NS();Object.defineProperty(e,"ProxyTracer",{enumerable:!0,get:function(){return d.ProxyTracer}});var u=DS();Object.defineProperty(e,"ProxyTracerProvider",{enumerable:!0,get:function(){return u.ProxyTracerProvider}});var l=UM();Object.defineProperty(e,"SamplingDecision",{enumerable:!0,get:function(){return l.SamplingDecision}});var p=FM();Object.defineProperty(e,"SpanKind",{enumerable:!0,get:function(){return p.SpanKind}});var m=zM();Object.defineProperty(e,"SpanStatusCode",{enumerable:!0,get:function(){return m.SpanStatusCode}});var f=MS();Object.defineProperty(e,"TraceFlags",{enumerable:!0,get:function(){return f.TraceFlags}});var h=JM();Object.defineProperty(e,"createTraceState",{enumerable:!0,get:function(){return h.createTraceState}});var y=lm();Object.defineProperty(e,"isSpanContextValid",{enumerable:!0,get:function(){return y.isSpanContextValid}}),Object.defineProperty(e,"isValidTraceId",{enumerable:!0,get:function(){return y.isValidTraceId}}),Object.defineProperty(e,"isValidSpanId",{enumerable:!0,get:function(){return y.isValidSpanId}});var w=dm();Object.defineProperty(e,"INVALID_SPANID",{enumerable:!0,get:function(){return w.INVALID_SPANID}}),Object.defineProperty(e,"INVALID_TRACEID",{enumerable:!0,get:function(){return w.INVALID_TRACEID}}),Object.defineProperty(e,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return w.INVALID_SPAN_CONTEXT}});var g=WM();Object.defineProperty(e,"context",{enumerable:!0,get:function(){return g.context}});var v=HM();Object.defineProperty(e,"diag",{enumerable:!0,get:function(){return v.diag}});var b=ZM();Object.defineProperty(e,"metrics",{enumerable:!0,get:function(){return b.metrics}});var S=e1();Object.defineProperty(e,"propagation",{enumerable:!0,get:function(){return S.propagation}});var T=n1();Object.defineProperty(e,"trace",{enumerable:!0,get:function(){return T.trace}}),e.default={context:g.context,diag:v.diag,metrics:b.metrics,propagation:S.propagation,trace:T.trace}}),Md=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(v){if(super(),!e.IDENTIFIER.test(v))throw Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=n;class i extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((b,S)=>`${b}${S}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((b,S)=>(S instanceof n&&(b[S.str]=(b[S.str]||0)+1),b),{})}}e._Code=i,e.nil=new i("");function r(g,...v){let b=[g[0]],S=0;for(;S<v.length;)s(b,v[S]),b.push(g[++S]);return new i(b)}e._=r;var o=new i("+");function a(g,...v){let b=[f(g[0])],S=0;for(;S<v.length;)b.push(o),s(b,v[S]),b.push(o,f(g[++S]));return d(b),new i(b)}e.str=a;function s(g,v){v instanceof i?g.push(...v._items):v instanceof n?g.push(v):g.push(p(v))}e.addCodeArg=s;function d(g){let v=1;for(;v<g.length-1;){if(g[v]===o){let b=u(g[v-1],g[v+1]);if(b!==void 0){g.splice(v-1,3,b);continue}g[v++]="+"}v++}}function u(g,v){if(v==='""')return g;if(g==='""')return v;if(typeof g=="string")return v instanceof n||g[g.length-1]!=='"'?void 0:typeof v!="string"?`${g.slice(0,-1)}${v}"`:v[0]==='"'?g.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(g instanceof n))return`"${g}${v.slice(1)}`}function l(g,v){return v.emptyStr()?g:g.emptyStr()?v:a`${g}${v}`}e.strConcat=l;function p(g){return typeof g=="number"||typeof g=="boolean"||g===null?g:f(Array.isArray(g)?g.join(","):g)}function m(g){return new i(f(g))}e.stringify=m;function f(g){return JSON.stringify(g).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function h(g){return typeof g=="string"&&e.IDENTIFIER.test(g)?new i(`.${g}`):r`[${g}]`}e.getProperty=h;function y(g){if(typeof g=="string"&&e.IDENTIFIER.test(g))return new i(`${g}`);throw Error(`CodeGen: invalid export name: ${g}, use explicit $id name mapping`)}e.getEsmExportName=y;function w(g){return new i(g.toString())}e.regexpCode=w}),Av=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=Md();class n extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var i;(function(d){d[d.Started=0]="Started",d[d.Completed=1]="Completed"})(i||(e.UsedValueState=i={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class r{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){let l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,p;if(!((p=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||p===void 0)&&p.has(u)||this._prefixes&&!this._prefixes.has(u))throw Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=r;class o extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:p}){this.value=u,this.scopePath=t._`.${new t.Name(l)}[${p}]`}}e.ValueScopeName=o;var a=t._`\n`;class s extends r{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?a:t.nil}}get(){return this._scope}name(u){return new o(u,this._newName(u))}value(u,l){var p;if(l.ref===void 0)throw Error("CodeGen: ref must be passed in value");let m=this.toName(u),{prefix:f}=m,h=(p=l.key)!==null&&p!==void 0?p:l.ref,y=this._values[f];if(y){let v=y.get(h);if(v)return v}else y=this._values[f]=new Map;y.set(h,m);let w=this._scope[f]||(this._scope[f]=[]),g=w.length;return w[g]=l.ref,m.setValue(l,{property:f,itemIndex:g}),m}getValue(u,l){let p=this._values[u];if(p)return p.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,p=>{if(p.scopePath===void 0)throw Error(`CodeGen: name "${p}" has no value`);return t._`${u}${p.scopePath}`})}scopeCode(u=this._values,l,p){return this._reduceValues(u,m=>{if(m.value===void 0)throw Error(`CodeGen: name "${m}" has no value`);return m.value.code},l,p)}_reduceValues(u,l,p={},m){let f=t.nil;for(let h in u){let y=u[h];if(!y)continue;let w=p[h]=p[h]||new Map;y.forEach(g=>{if(w.has(g))return;w.set(g,i.Started);let v=l(g);if(v){let b=this.opts.es5?e.varKinds.var:e.varKinds.const;f=t._`${f}${b} ${g} = ${v};${this.opts._n}`}else if(v=m?.(g))f=t._`${f}${v}${this.opts._n}`;else throw new n(g);w.set(g,i.Completed)})}return f}}e.ValueScope=s}),Te=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;var t=Md(),n=Av(),i=Md();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return i.Name}});var r=Av();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return r.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return r.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return r.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return r.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class o{optimizeNodes(){return this}optimizeNames(x,E){return this}}class a extends o{constructor(x,E,O){super(),this.varKind=x,this.name=E,this.rhs=O}render({es5:x,_n:E}){let O=x?n.varKinds.var:this.varKind,ne=this.rhs===void 0?"":` = ${this.rhs}`;return`${O} ${this.name}${ne};`+E}optimizeNames(x,E){if(x[this.name.str])return this.rhs&&(this.rhs=F(this.rhs,x,E)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends o{constructor(x,E,O){super(),this.lhs=x,this.rhs=E,this.sideEffects=O}render({_n:x}){return`${this.lhs} = ${this.rhs};`+x}optimizeNames(x,E){if(!(this.lhs instanceof t.Name&&!x[this.lhs.str]&&!this.sideEffects))return this.rhs=F(this.rhs,x,E),this}get names(){let x=this.lhs instanceof t.Name?{}:{...this.lhs.names};return A(x,this.rhs)}}class d extends s{constructor(x,E,O,ne){super(x,O,ne),this.op=E}render({_n:x}){return`${this.lhs} ${this.op}= ${this.rhs};`+x}}class u extends o{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`${this.label}:`+x}}class l extends o{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`break${this.label?` ${this.label}`:""};`+x}}class p extends o{constructor(x){super(),this.error=x}render({_n:x}){return`throw ${this.error};`+x}get names(){return this.error.names}}class m extends o{constructor(x){super(),this.code=x}render({_n:x}){return`${this.code};`+x}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(x,E){return this.code=F(this.code,x,E),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends o{constructor(x=[]){super(),this.nodes=x}render(x){return this.nodes.reduce((E,O)=>E+O.render(x),"")}optimizeNodes(){let{nodes:x}=this,E=x.length;for(;E--;){let O=x[E].optimizeNodes();Array.isArray(O)?x.splice(E,1,...O):O?x[E]=O:x.splice(E,1)}return x.length>0?this:void 0}optimizeNames(x,E){let{nodes:O}=this,ne=O.length;for(;ne--;){let X=O[ne];X.optimizeNames(x,E)||(se(x,X.names),O.splice(ne,1))}return O.length>0?this:void 0}get names(){return this.nodes.reduce((x,E)=>M(x,E.names),{})}}class h extends f{render(x){return"{"+x._n+super.render(x)+"}"+x._n}}class y extends f{}class w extends h{}w.kind="else";class g extends h{constructor(x,E){super(E),this.condition=x}render(x){let E=`if(${this.condition})`+super.render(x);return this.else&&(E+="else "+this.else.render(x)),E}optimizeNodes(){super.optimizeNodes();let x=this.condition;if(x===!0)return this.nodes;let E=this.else;if(E){let O=E.optimizeNodes();E=this.else=Array.isArray(O)?new w(O):O}if(E)return x===!1?E instanceof g?E:E.nodes:this.nodes.length?this:new g(he(x),E instanceof g?[E]:E.nodes);if(!(x===!1||!this.nodes.length))return this}optimizeNames(x,E){var O;if(this.else=(O=this.else)===null||O===void 0?void 0:O.optimizeNames(x,E),!!(super.optimizeNames(x,E)||this.else))return this.condition=F(this.condition,x,E),this}get names(){let x=super.names;return A(x,this.condition),this.else&&M(x,this.else.names),x}}g.kind="if";class v extends h{}v.kind="for";class b extends v{constructor(x){super(),this.iteration=x}render(x){return`for(${this.iteration})`+super.render(x)}optimizeNames(x,E){if(super.optimizeNames(x,E))return this.iteration=F(this.iteration,x,E),this}get names(){return M(super.names,this.iteration.names)}}class S extends v{constructor(x,E,O,ne){super(),this.varKind=x,this.name=E,this.from=O,this.to=ne}render(x){let E=x.es5?n.varKinds.var:this.varKind,{name:O,from:ne,to:X}=this;return`for(${E} ${O}=${ne}; ${O}<${X}; ${O}++)`+super.render(x)}get names(){let x=A(super.names,this.from);return A(x,this.to)}}class T extends v{constructor(x,E,O,ne){super(),this.loop=x,this.varKind=E,this.name=O,this.iterable=ne}render(x){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(x)}optimizeNames(x,E){if(super.optimizeNames(x,E))return this.iterable=F(this.iterable,x,E),this}get names(){return M(super.names,this.iterable.names)}}class C extends h{constructor(x,E,O){super(),this.name=x,this.args=E,this.async=O}render(x){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(x)}}C.kind="func";class _ extends f{render(x){return"return "+super.render(x)}}_.kind="return";class k extends h{render(x){let E="try"+super.render(x);return this.catch&&(E+=this.catch.render(x)),this.finally&&(E+=this.finally.render(x)),E}optimizeNodes(){var x,E;return super.optimizeNodes(),(x=this.catch)===null||x===void 0||x.optimizeNodes(),(E=this.finally)===null||E===void 0||E.optimizeNodes(),this}optimizeNames(x,E){var O,ne;return super.optimizeNames(x,E),(O=this.catch)===null||O===void 0||O.optimizeNames(x,E),(ne=this.finally)===null||ne===void 0||ne.optimizeNames(x,E),this}get names(){let x=super.names;return this.catch&&M(x,this.catch.names),this.finally&&M(x,this.finally.names),x}}class I extends h{constructor(x){super(),this.error=x}render(x){return`catch(${this.error})`+super.render(x)}}I.kind="catch";class P extends h{render(x){return"finally"+super.render(x)}}P.kind="finally";class R{constructor(x,E={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...E,_n:E.lines?`
37
+ `:""},this._extScope=x,this._scope=new n.Scope({parent:x}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(x){return this._scope.name(x)}scopeName(x){return this._extScope.name(x)}scopeValue(x,E){let O=this._extScope.value(x,E);return(this._values[O.prefix]||(this._values[O.prefix]=new Set)).add(O),O}getScopeValue(x,E){return this._extScope.getValue(x,E)}scopeRefs(x){return this._extScope.scopeRefs(x,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(x,E,O,ne){let X=this._scope.toName(E);return O!==void 0&&ne&&(this._constants[X.str]=O),this._leafNode(new a(x,X,O)),X}const(x,E,O){return this._def(n.varKinds.const,x,E,O)}let(x,E,O){return this._def(n.varKinds.let,x,E,O)}var(x,E,O){return this._def(n.varKinds.var,x,E,O)}assign(x,E,O){return this._leafNode(new s(x,E,O))}add(x,E){return this._leafNode(new d(x,e.operators.ADD,E))}code(x){return typeof x=="function"?x():x!==t.nil&&this._leafNode(new m(x)),this}object(...x){let E=["{"];for(let[O,ne]of x)E.length>1&&E.push(","),E.push(O),(O!==ne||this.opts.es5)&&(E.push(":"),(0,t.addCodeArg)(E,ne));return E.push("}"),new t._Code(E)}if(x,E,O){if(this._blockNode(new g(x)),E&&O)this.code(E).else().code(O).endIf();else if(E)this.code(E).endIf();else if(O)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(x){return this._elseNode(new g(x))}else(){return this._elseNode(new w)}endIf(){return this._endBlockNode(g,w)}_for(x,E){return this._blockNode(x),E&&this.code(E).endFor(),this}for(x,E){return this._for(new b(x),E)}forRange(x,E,O,ne,X=this.opts.es5?n.varKinds.var:n.varKinds.let){let we=this._scope.toName(x);return this._for(new S(X,we,E,O),()=>ne(we))}forOf(x,E,O,ne=n.varKinds.const){let X=this._scope.toName(x);if(this.opts.es5){let we=E instanceof t.Name?E:this.var("_arr",E);return this.forRange("_i",0,t._`${we}.length`,Se=>{this.var(X,t._`${we}[${Se}]`),O(X)})}return this._for(new T("of",ne,X,E),()=>O(X))}forIn(x,E,O,ne=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(x,t._`Object.keys(${E})`,O);let X=this._scope.toName(x);return this._for(new T("in",ne,X,E),()=>O(X))}endFor(){return this._endBlockNode(v)}label(x){return this._leafNode(new u(x))}break(x){return this._leafNode(new l(x))}return(x){let E=new _;if(this._blockNode(E),this.code(x),E.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(_)}try(x,E,O){if(!E&&!O)throw Error('CodeGen: "try" without "catch" and "finally"');let ne=new k;if(this._blockNode(ne),this.code(x),E){let X=this.name("e");this._currNode=ne.catch=new I(X),E(X)}return O&&(this._currNode=ne.finally=new P,this.code(O)),this._endBlockNode(I,P)}throw(x){return this._leafNode(new p(x))}block(x,E){return this._blockStarts.push(this._nodes.length),x&&this.code(x).endBlock(E),this}endBlock(x){let E=this._blockStarts.pop();if(E===void 0)throw Error("CodeGen: not in self-balancing block");let O=this._nodes.length-E;if(O<0||x!==void 0&&O!==x)throw Error(`CodeGen: wrong number of nodes: ${O} vs ${x} expected`);return this._nodes.length=E,this}func(x,E=t.nil,O,ne){return this._blockNode(new C(x,E,O)),ne&&this.code(ne).endFunc(),this}endFunc(){return this._endBlockNode(C)}optimize(x=1){for(;x-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(x){return this._currNode.nodes.push(x),this}_blockNode(x){this._currNode.nodes.push(x),this._nodes.push(x)}_endBlockNode(x,E){let O=this._currNode;if(O instanceof x||E&&O instanceof E)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${E?`${x.kind}/${E.kind}`:x.kind}"`)}_elseNode(x){let E=this._currNode;if(!(E instanceof g))throw Error('CodeGen: "else" without "if"');return this._currNode=E.else=x,this}get _root(){return this._nodes[0]}get _currNode(){let x=this._nodes;return x[x.length-1]}set _currNode(x){let E=this._nodes;E[E.length-1]=x}}e.CodeGen=R;function M(L,x){for(let E in x)L[E]=(L[E]||0)+(x[E]||0);return L}function A(L,x){return x instanceof t._CodeOrName?M(L,x.names):L}function F(L,x,E){if(L instanceof t.Name)return O(L);if(!ne(L))return L;return new t._Code(L._items.reduce((X,we)=>(we instanceof t.Name&&(we=O(we)),we instanceof t._Code?X.push(...we._items):X.push(we),X),[]));function O(X){let we=E[X.str];return we===void 0||x[X.str]!==1?X:(delete x[X.str],we)}function ne(X){return X instanceof t._Code&&X._items.some(we=>we instanceof t.Name&&x[we.str]===1&&E[we.str]!==void 0)}}function se(L,x){for(let E in x)L[E]=(L[E]||0)-(x[E]||0)}function he(L){return typeof L=="boolean"||typeof L=="number"||L===null?!L:t._`!${B(L)}`}e.not=he;var ee=$(e.operators.AND);function $e(...L){return L.reduce(ee)}e.and=$e;var be=$(e.operators.OR);function G(...L){return L.reduce(be)}e.or=G;function $(L){return(x,E)=>x===t.nil?E:E===t.nil?x:t._`${B(x)} ${L} ${B(E)}`}function B(L){return L instanceof t.Name?L:t._`(${L})`}}),Ae=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;var t=Te(),n=Md();function i(C){let _={};for(let k of C)_[k]=!0;return _}e.toHash=i;function r(C,_){return typeof _=="boolean"?_:Object.keys(_).length===0?!0:(o(C,_),!a(_,C.self.RULES.all))}e.alwaysValidSchema=r;function o(C,_=C.schema){let{opts:k,self:I}=C;if(!k.strictSchema||typeof _=="boolean")return;let P=I.RULES.keywords;for(let R in _)P[R]||T(C,`unknown keyword: "${R}"`)}e.checkUnknownRules=o;function a(C,_){if(typeof C=="boolean")return!C;for(let k in C)if(_[k])return!0;return!1}e.schemaHasRules=a;function s(C,_){if(typeof C=="boolean")return!C;for(let k in C)if(k!=="$ref"&&_.all[k])return!0;return!1}e.schemaHasRulesButRef=s;function d({topSchemaRef:C,schemaPath:_},k,I,P){if(!P){if(typeof k=="number"||typeof k=="boolean")return k;if(typeof k=="string")return t._`${k}`}return t._`${C}${_}${(0,t.getProperty)(I)}`}e.schemaRefOrVal=d;function u(C){return m(decodeURIComponent(C))}e.unescapeFragment=u;function l(C){return encodeURIComponent(p(C))}e.escapeFragment=l;function p(C){return typeof C=="number"?`${C}`:C.replace(/~/g,"~0").replace(/\//g,"~1")}e.escapeJsonPointer=p;function m(C){return C.replace(/~1/g,"/").replace(/~0/g,"~")}e.unescapeJsonPointer=m;function f(C,_){if(Array.isArray(C))for(let k of C)_(k);else _(C)}e.eachItem=f;function h({mergeNames:C,mergeToName:_,mergeValues:k,resultToName:I}){return(P,R,M,A)=>{let F=M===void 0?R:M instanceof t.Name?(R instanceof t.Name?C(P,R,M):_(P,R,M),M):R instanceof t.Name?(_(P,M,R),R):k(R,M);return A===t.Name&&!(F instanceof t.Name)?I(P,F):F}}e.mergeEvaluated={props:h({mergeNames:(C,_,k)=>C.if(t._`${k} !== true && ${_} !== undefined`,()=>{C.if(t._`${_} === true`,()=>C.assign(k,!0),()=>C.assign(k,t._`${k} || {}`).code(t._`Object.assign(${k}, ${_})`))}),mergeToName:(C,_,k)=>C.if(t._`${k} !== true`,()=>{_===!0?C.assign(k,!0):(C.assign(k,t._`${k} || {}`),w(C,k,_))}),mergeValues:(C,_)=>C===!0?!0:{...C,..._},resultToName:y}),items:h({mergeNames:(C,_,k)=>C.if(t._`${k} !== true && ${_} !== undefined`,()=>C.assign(k,t._`${_} === true ? true : ${k} > ${_} ? ${k} : ${_}`)),mergeToName:(C,_,k)=>C.if(t._`${k} !== true`,()=>C.assign(k,_===!0?!0:t._`${k} > ${_} ? ${k} : ${_}`)),mergeValues:(C,_)=>C===!0?!0:Math.max(C,_),resultToName:(C,_)=>C.var("items",_)})};function y(C,_){if(_===!0)return C.var("props",!0);let k=C.var("props",t._`{}`);return _!==void 0&&w(C,k,_),k}e.evaluatedPropsToName=y;function w(C,_,k){Object.keys(k).forEach(I=>C.assign(t._`${_}${(0,t.getProperty)(I)}`,!0))}e.setEvaluated=w;var g={};function v(C,_){return C.scopeValue("func",{ref:_,code:g[_.code]||(g[_.code]=new n._Code(_.code))})}e.useFunc=v;var b;(function(C){C[C.Num=0]="Num",C[C.Str=1]="Str"})(b||(e.Type=b={}));function S(C,_,k){if(C instanceof t.Name){let I=_===b.Num;return k?I?t._`"[" + ${C} + "]"`:t._`"['" + ${C} + "']"`:I?t._`"/" + ${C}`:t._`"/" + ${C}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return k?(0,t.getProperty)(C).toString():"/"+p(C)}e.getErrorPath=S;function T(C,_,k=C.opts.strictSchema){if(k){if(_=`strict mode: ${_}`,k===!0)throw Error(_);C.self.logger.warn(_)}}e.checkStrictMode=T}),Cr=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};e.default=n}),il=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;var t=Te(),n=Ae(),i=Cr();e.keywordError={message:({keyword:w})=>t.str`must pass "${w}" keyword validation`},e.keyword$DataError={message:({keyword:w,schemaType:g})=>g?t.str`"${w}" keyword must be ${g} ($data)`:t.str`"${w}" keyword is invalid ($data)`};function r(w,g=e.keywordError,v,b){let{it:S}=w,{gen:T,compositeRule:C,allErrors:_}=S,k=p(w,g,v);b??(C||_)?d(T,k):u(S,t._`[${k}]`)}e.reportError=r;function o(w,g=e.keywordError,v){let{it:b}=w,{gen:S,compositeRule:T,allErrors:C}=b,_=p(w,g,v);d(S,_),!(T||C)&&u(b,i.default.vErrors)}e.reportExtraError=o;function a(w,g){w.assign(i.default.errors,g),w.if(t._`${i.default.vErrors} !== null`,()=>w.if(g,()=>w.assign(t._`${i.default.vErrors}.length`,g),()=>w.assign(i.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:w,keyword:g,schemaValue:v,data:b,errsCount:S,it:T}){if(S===void 0)throw Error("ajv implementation error");let C=w.name("err");w.forRange("i",S,i.default.errors,_=>{w.const(C,t._`${i.default.vErrors}[${_}]`),w.if(t._`${C}.instancePath === undefined`,()=>w.assign(t._`${C}.instancePath`,(0,t.strConcat)(i.default.instancePath,T.errorPath))),w.assign(t._`${C}.schemaPath`,t.str`${T.errSchemaPath}/${g}`),T.opts.verbose&&(w.assign(t._`${C}.schema`,v),w.assign(t._`${C}.data`,b))})}e.extendErrors=s;function d(w,g){let v=w.const("err",g);w.if(t._`${i.default.vErrors} === null`,()=>w.assign(i.default.vErrors,t._`[${v}]`),t._`${i.default.vErrors}.push(${v})`),w.code(t._`${i.default.errors}++`)}function u(w,g){let{gen:v,validateName:b,schemaEnv:S}=w;S.$async?v.throw(t._`new ${w.ValidationError}(${g})`):(v.assign(t._`${b}.errors`,g),v.return(!1))}var l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function p(w,g,v){let{createErrors:b}=w.it;return b===!1?t._`{}`:m(w,g,v)}function m(w,g,v={}){let{gen:b,it:S}=w,T=[f(S,v),h(w,v)];return y(w,g,T),b.object(...T)}function f({errorPath:w},{instancePath:g}){let v=g?t.str`${w}${(0,n.getErrorPath)(g,n.Type.Str)}`:w;return[i.default.instancePath,(0,t.strConcat)(i.default.instancePath,v)]}function h({keyword:w,it:{errSchemaPath:g}},{schemaPath:v,parentSchema:b}){let S=b?g:t.str`${g}/${w}`;return v&&(S=t.str`${S}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,S]}function y(w,{params:g,message:v},b){let{keyword:S,data:T,schemaValue:C,it:_}=w,{opts:k,propertyName:I,topSchemaRef:P,schemaPath:R}=_;b.push([l.keyword,S],[l.params,typeof g=="function"?g(w):g||t._`{}`]),k.messages&&b.push([l.message,typeof v=="function"?v(w):v]),k.verbose&&b.push([l.schema,C],[l.parentSchema,t._`${P}${R}`],[i.default.data,T]),I&&b.push([l.propertyName,I])}}),i1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;var t=il(),n=Te(),i=Cr(),r={message:"boolean schema is false"};function o(d){let{gen:u,schema:l,validateName:p}=d;l===!1?s(d,!1):typeof l=="object"&&l.$async===!0?u.return(i.default.data):(u.assign(n._`${p}.errors`,null),u.return(!0))}e.topBoolOrEmptySchema=o;function a(d,u){let{gen:l,schema:p}=d;p===!1?(l.var(u,!1),s(d)):l.var(u,!0)}e.boolOrEmptySchema=a;function s(d,u){let{gen:l,data:p}=d,m={gen:l,keyword:"false schema",data:p,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:d};(0,t.reportError)(m,r,void 0,u)}}),LS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;var t=["string","number","integer","boolean","null","object","array"],n=new Set(t);function i(o){return typeof o=="string"&&n.has(o)}e.isJSONType=i;function r(){let o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r}),US=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:r,self:o},a){let s=o.RULES.types[a];return s&&s!==!0&&n(r,s)}e.schemaHasRulesForType=t;function n(r,o){return o.rules.some(a=>i(r,a))}e.shouldUseGroup=n;function i(r,o){var a;return r[o.keyword]!==void 0||((a=o.definition.implements)===null||a===void 0?void 0:a.some(s=>r[s]!==void 0))}e.shouldUseRule=i}),jd=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;var t=LS(),n=US(),i=il(),r=Te(),o=Ae(),a;(function(b){b[b.Correct=0]="Correct",b[b.Wrong=1]="Wrong"})(a||(e.DataType=a={}));function s(b){let S=d(b.type);if(S.includes("null")){if(b.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!S.length&&b.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');b.nullable===!0&&S.push("null")}return S}e.getSchemaTypes=s;function d(b){let S=Array.isArray(b)?b:b?[b]:[];if(S.every(t.isJSONType))return S;throw Error("type must be JSONType or JSONType[]: "+S.join(","))}e.getJSONTypes=d;function u(b,S){let{gen:T,data:C,opts:_}=b,k=p(S,_.coerceTypes),I=S.length>0&&!(k.length===0&&S.length===1&&(0,n.schemaHasRulesForType)(b,S[0]));if(I){let P=y(S,C,_.strictNumbers,a.Wrong);T.if(P,()=>{k.length?m(b,S,k):g(b)})}return I}e.coerceAndCheckDataType=u;var l=new Set(["string","number","integer","boolean","null"]);function p(b,S){return S?b.filter(T=>l.has(T)||S==="array"&&T==="array"):[]}function m(b,S,T){let{gen:C,data:_,opts:k}=b,I=C.let("dataType",r._`typeof ${_}`),P=C.let("coerced",r._`undefined`);k.coerceTypes==="array"&&C.if(r._`${I} == 'object' && Array.isArray(${_}) && ${_}.length == 1`,()=>C.assign(_,r._`${_}[0]`).assign(I,r._`typeof ${_}`).if(y(S,_,k.strictNumbers),()=>C.assign(P,_))),C.if(r._`${P} !== undefined`);for(let M of T)(l.has(M)||M==="array"&&k.coerceTypes==="array")&&R(M);C.else(),g(b),C.endIf(),C.if(r._`${P} !== undefined`,()=>{C.assign(_,P),f(b,P)});function R(M){switch(M){case"string":C.elseIf(r._`${I} == "number" || ${I} == "boolean"`).assign(P,r._`"" + ${_}`).elseIf(r._`${_} === null`).assign(P,r._`""`);return;case"number":C.elseIf(r._`${I} == "boolean" || ${_} === null
38
+ || (${I} == "string" && ${_} && ${_} == +${_})`).assign(P,r._`+${_}`);return;case"integer":C.elseIf(r._`${I} === "boolean" || ${_} === null
39
+ || (${I} === "string" && ${_} && ${_} == +${_} && !(${_} % 1))`).assign(P,r._`+${_}`);return;case"boolean":C.elseIf(r._`${_} === "false" || ${_} === 0 || ${_} === null`).assign(P,!1).elseIf(r._`${_} === "true" || ${_} === 1`).assign(P,!0);return;case"null":C.elseIf(r._`${_} === "" || ${_} === 0 || ${_} === false`),C.assign(P,null);return;case"array":C.elseIf(r._`${I} === "string" || ${I} === "number"
40
+ || ${I} === "boolean" || ${_} === null`).assign(P,r._`[${_}]`)}}}function f({gen:b,parentData:S,parentDataProperty:T},C){b.if(r._`${S} !== undefined`,()=>b.assign(r._`${S}[${T}]`,C))}function h(b,S,T,C=a.Correct){let _=C===a.Correct?r.operators.EQ:r.operators.NEQ,k;switch(b){case"null":return r._`${S} ${_} null`;case"array":k=r._`Array.isArray(${S})`;break;case"object":k=r._`${S} && typeof ${S} == "object" && !Array.isArray(${S})`;break;case"integer":k=I(r._`!(${S} % 1) && !isNaN(${S})`);break;case"number":k=I();break;default:return r._`typeof ${S} ${_} ${b}`}return C===a.Correct?k:(0,r.not)(k);function I(P=r.nil){return(0,r.and)(r._`typeof ${S} == "number"`,P,T?r._`isFinite(${S})`:r.nil)}}e.checkDataType=h;function y(b,S,T,C){if(b.length===1)return h(b[0],S,T,C);let _,k=(0,o.toHash)(b);if(k.array&&k.object){let I=r._`typeof ${S} != "object"`;_=k.null?I:r._`!${S} || ${I}`,delete k.null,delete k.array,delete k.object}else _=r.nil;k.number&&delete k.integer;for(let I in k)_=(0,r.and)(_,h(I,S,T,C));return _}e.checkDataTypes=y;var w={message:({schema:b})=>`must be ${b}`,params:({schema:b,schemaValue:S})=>typeof b=="string"?r._`{type: ${b}}`:r._`{type: ${S}}`};function g(b){let S=v(b);(0,i.reportError)(S,w)}e.reportTypeError=g;function v(b){let{gen:S,data:T,schema:C}=b,_=(0,o.schemaRefOrVal)(b,C,"type");return{gen:S,keyword:"type",data:T,schema:C.type,schemaCode:_,schemaValue:_,parentSchema:C,params:{},it:b}}}),o1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;var t=Te(),n=Ae();function i(o,a){let{properties:s,items:d}=o.schema;if(a==="object"&&s)for(let u in s)r(o,u,s[u].default);else a==="array"&&Array.isArray(d)&&d.forEach((u,l)=>r(o,l,u.default))}e.assignDefaults=i;function r(o,a,s){let{gen:d,compositeRule:u,data:l,opts:p}=o;if(s===void 0)return;let m=t._`${l}${(0,t.getProperty)(a)}`;if(u){(0,n.checkStrictMode)(o,`default is ignored for: ${m}`);return}let f=t._`${m} === undefined`;p.useDefaults==="empty"&&(f=t._`${f} || ${m} === null || ${m} === ""`),d.if(f,t._`${m} = ${(0,t.stringify)(s)}`)}}),En=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;var t=Te(),n=Ae(),i=Cr(),r=Ae();function o(b,S){let{gen:T,data:C,it:_}=b;T.if(p(T,C,S,_.opts.ownProperties),()=>{b.setParams({missingProperty:t._`${S}`},!0),b.error()})}e.checkReportMissingProp=o;function a({gen:b,data:S,it:{opts:T}},C,_){return(0,t.or)(...C.map(k=>(0,t.and)(p(b,S,k,T.ownProperties),t._`${_} = ${k}`)))}e.checkMissingProp=a;function s(b,S){b.setParams({missingProperty:S},!0),b.error()}e.reportMissingProp=s;function d(b){return b.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:t._`Object.prototype.hasOwnProperty`})}e.hasPropFunc=d;function u(b,S,T){return t._`${d(b)}.call(${S}, ${T})`}e.isOwnProperty=u;function l(b,S,T,C){let _=t._`${S}${(0,t.getProperty)(T)} !== undefined`;return C?t._`${_} && ${u(b,S,T)}`:_}e.propertyInData=l;function p(b,S,T,C){let _=t._`${S}${(0,t.getProperty)(T)} === undefined`;return C?(0,t.or)(_,(0,t.not)(u(b,S,T))):_}e.noPropertyInData=p;function m(b){return b?Object.keys(b).filter(S=>S!=="__proto__"):[]}e.allSchemaProperties=m;function f(b,S){return m(S).filter(T=>!(0,n.alwaysValidSchema)(b,S[T]))}e.schemaProperties=f;function h({schemaCode:b,data:S,it:{gen:T,topSchemaRef:C,schemaPath:_,errorPath:k},it:I},P,R,M){let A=M?t._`${b}, ${S}, ${C}${_}`:S,F=[[i.default.instancePath,(0,t.strConcat)(i.default.instancePath,k)],[i.default.parentData,I.parentData],[i.default.parentDataProperty,I.parentDataProperty],[i.default.rootData,i.default.rootData]];I.opts.dynamicRef&&F.push([i.default.dynamicAnchors,i.default.dynamicAnchors]);let se=t._`${A}, ${T.object(...F)}`;return R!==t.nil?t._`${P}.call(${R}, ${se})`:t._`${P}(${se})`}e.callValidateCode=h;var y=t._`new RegExp`;function w({gen:b,it:{opts:S}},T){let C=S.unicodeRegExp?"u":"",{regExp:_}=S.code,k=_(T,C);return b.scopeValue("pattern",{key:k.toString(),ref:k,code:t._`${_.code==="new RegExp"?y:(0,r.useFunc)(b,_)}(${T}, ${C})`})}e.usePattern=w;function g(b){let{gen:S,data:T,keyword:C,it:_}=b,k=S.name("valid");if(_.allErrors){let P=S.let("valid",!0);return I(()=>S.assign(P,!1)),P}return S.var(k,!0),I(()=>S.break()),k;function I(P){let R=S.const("len",t._`${T}.length`);S.forRange("i",0,R,M=>{b.subschema({keyword:C,dataProp:M,dataPropType:n.Type.Num},k),S.if((0,t.not)(k),P)})}}e.validateArray=g;function v(b){let{gen:S,schema:T,keyword:C,it:_}=b;if(!Array.isArray(T))throw Error("ajv implementation error");if(T.some(P=>(0,n.alwaysValidSchema)(_,P))&&!_.opts.unevaluated)return;let k=S.let("valid",!1),I=S.name("_valid");S.block(()=>T.forEach((P,R)=>{let M=b.subschema({keyword:C,schemaProp:R,compositeRule:!0},I);S.assign(k,t._`${k} || ${I}`),!b.mergeValidEvaluated(M,I)&&S.if((0,t.not)(k))})),b.result(k,()=>b.reset(),()=>b.error(!0))}e.validateUnion=v}),a1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;var t=Te(),n=Cr(),i=En(),r=il();function o(f,h){let{gen:y,keyword:w,schema:g,parentSchema:v,it:b}=f,S=h.macro.call(b.self,g,v,b),T=l(y,w,S);b.opts.validateSchema!==!1&&b.self.validateSchema(S,!0);let C=y.name("valid");f.subschema({schema:S,schemaPath:t.nil,errSchemaPath:`${b.errSchemaPath}/${w}`,topSchemaRef:T,compositeRule:!0},C),f.pass(C,()=>f.error(!0))}e.macroKeywordCode=o;function a(f,h){var y;let{gen:w,keyword:g,schema:v,parentSchema:b,$data:S,it:T}=f;u(T,h);let C=!S&&h.compile?h.compile.call(T.self,v,b,T):h.validate,_=l(w,g,C),k=w.let("valid");f.block$data(k,I),f.ok((y=h.valid)!==null&&y!==void 0?y:k);function I(){if(h.errors===!1)M(),h.modifying&&s(f),A(()=>f.error());else{let F=h.async?P():R();h.modifying&&s(f),A(()=>d(f,F))}}function P(){let F=w.let("ruleErrs",null);return w.try(()=>M(t._`await `),se=>w.assign(k,!1).if(t._`${se} instanceof ${T.ValidationError}`,()=>w.assign(F,t._`${se}.errors`),()=>w.throw(se))),F}function R(){let F=t._`${_}.errors`;return w.assign(F,null),M(t.nil),F}function M(F=h.async?t._`await `:t.nil){let se=T.opts.passContext?n.default.this:n.default.self,he=!("compile"in h&&!S||h.schema===!1);w.assign(k,t._`${F}${(0,i.callValidateCode)(f,_,se,he)}`,h.modifying)}function A(F){var se;w.if((0,t.not)((se=h.valid)!==null&&se!==void 0?se:k),F)}}e.funcKeywordCode=a;function s(f){let{gen:h,data:y,it:w}=f;h.if(w.parentData,()=>h.assign(y,t._`${w.parentData}[${w.parentDataProperty}]`))}function d(f,h){let{gen:y}=f;y.if(t._`Array.isArray(${h})`,()=>{y.assign(n.default.vErrors,t._`${n.default.vErrors} === null ? ${h} : ${n.default.vErrors}.concat(${h})`).assign(n.default.errors,t._`${n.default.vErrors}.length`),(0,r.extendErrors)(f)},()=>f.error())}function u({schemaEnv:f},h){if(h.async&&!f.$async)throw Error("async keyword in sync schema")}function l(f,h,y){if(y===void 0)throw Error(`keyword "${h}" failed to compile`);return f.scopeValue("keyword",typeof y=="function"?{ref:y}:{ref:y,code:(0,t.stringify)(y)})}function p(f,h,y=!1){return!h.length||h.some(w=>w==="array"?Array.isArray(f):w==="object"?f&&typeof f=="object"&&!Array.isArray(f):typeof f==w||y&&typeof f>"u")}e.validSchemaType=p;function m({schema:f,opts:h,self:y,errSchemaPath:w},g,v){if(Array.isArray(g.keyword)?!g.keyword.includes(v):g.keyword!==v)throw Error("ajv implementation error");let b=g.dependencies;if(b?.some(S=>!Object.prototype.hasOwnProperty.call(f,S)))throw Error(`parent schema must have dependencies of ${v}: ${b.join(",")}`);if(g.validateSchema&&!g.validateSchema(f[v])){let S=`keyword "${v}" value is invalid at path "${w}": `+y.errorsText(g.validateSchema.errors);if(h.validateSchema==="log")y.logger.error(S);else throw Error(S)}}e.validateKeywordUsage=m}),s1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;var t=Te(),n=Ae();function i(a,{keyword:s,schemaProp:d,schema:u,schemaPath:l,errSchemaPath:p,topSchemaRef:m}){if(s!==void 0&&u!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(s!==void 0){let f=a.schema[s];return d===void 0?{schema:f,schemaPath:t._`${a.schemaPath}${(0,t.getProperty)(s)}`,errSchemaPath:`${a.errSchemaPath}/${s}`}:{schema:f[d],schemaPath:t._`${a.schemaPath}${(0,t.getProperty)(s)}${(0,t.getProperty)(d)}`,errSchemaPath:`${a.errSchemaPath}/${s}/${(0,n.escapeFragment)(d)}`}}if(u!==void 0){if(l===void 0||p===void 0||m===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:u,schemaPath:l,topSchemaRef:m,errSchemaPath:p}}throw Error('either "keyword" or "schema" must be passed')}e.getSubschema=i;function r(a,s,{dataProp:d,dataPropType:u,data:l,dataTypes:p,propertyName:m}){if(l!==void 0&&d!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:f}=s;if(d!==void 0){let{errorPath:y,dataPathArr:w,opts:g}=s,v=f.let("data",t._`${s.data}${(0,t.getProperty)(d)}`,!0);h(v),a.errorPath=t.str`${y}${(0,n.getErrorPath)(d,u,g.jsPropertySyntax)}`,a.parentDataProperty=t._`${d}`,a.dataPathArr=[...w,a.parentDataProperty]}if(l!==void 0){let y=l instanceof t.Name?l:f.let("data",l,!0);h(y),m!==void 0&&(a.propertyName=m)}p&&(a.dataTypes=p);function h(y){a.data=y,a.dataLevel=s.dataLevel+1,a.dataTypes=[],s.definedProperties=new Set,a.parentData=s.data,a.dataNames=[...s.dataNames,y]}}e.extendSubschemaData=r;function o(a,{jtdDiscriminator:s,jtdMetadata:d,compositeRule:u,createErrors:l,allErrors:p}){u!==void 0&&(a.compositeRule=u),l!==void 0&&(a.createErrors=l),p!==void 0&&(a.allErrors=p),a.jtdDiscriminator=s,a.jtdMetadata=d}e.extendSubschemaMode=o}),FS=z((e,t)=>{t.exports=function n(i,r){if(i===r)return!0;if(i&&r&&typeof i=="object"&&typeof r=="object"){if(i.constructor!==r.constructor)return!1;var o,a,s;if(Array.isArray(i)){if(o=i.length,o!=r.length)return!1;for(a=o;a--!==0;)if(!n(i[a],r[a]))return!1;return!0}if(i.constructor===RegExp)return i.source===r.source&&i.flags===r.flags;if(i.valueOf!==Object.prototype.valueOf)return i.valueOf()===r.valueOf();if(i.toString!==Object.prototype.toString)return i.toString()===r.toString();if(s=Object.keys(i),o=s.length,o!==Object.keys(r).length)return!1;for(a=o;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[a]))return!1;for(a=o;a--!==0;){var d=s[a];if(!n(i[d],r[d]))return!1}return!0}return i!==i&&r!==r}}),d1=z((e,t)=>{var n=t.exports=function(o,a,s){typeof a=="function"&&(s=a,a={}),s=a.cb||s;var d=typeof s=="function"?s:s.pre||function(){},u=s.post||function(){};i(a,d,u,o,"",o)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function i(o,a,s,d,u,l,p,m,f,h){if(d&&typeof d=="object"&&!Array.isArray(d)){a(d,u,l,p,m,f,h);for(var y in d){var w=d[y];if(Array.isArray(w)){if(y in n.arrayKeywords)for(var g=0;g<w.length;g++)i(o,a,s,w[g],u+"/"+y+"/"+g,l,u,y,d,g)}else if(y in n.propsKeywords){if(w&&typeof w=="object")for(var v in w)i(o,a,s,w[v],u+"/"+y+"/"+r(v),l,u,y,d,v)}else(y in n.keywords||o.allKeys&&!(y in n.skipKeywords))&&i(o,a,s,w,u+"/"+y,l,u,y,d)}s(d,u,l,p,m,f,h)}}function r(o){return o.replace(/~/g,"~0").replace(/\//g,"~1")}}),ol=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;var t=Ae(),n=FS(),i=d1(),r=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(w,g=!0){return typeof w=="boolean"?!0:g===!0?!s(w):g?d(w)<=g:!1}e.inlineRef=o;var a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s(w){for(let g in w){if(a.has(g))return!0;let v=w[g];if(Array.isArray(v)&&v.some(s)||typeof v=="object"&&s(v))return!0}return!1}function d(w){let g=0;for(let v in w){if(v==="$ref")return 1/0;if(g++,!r.has(v)&&(typeof w[v]=="object"&&(0,t.eachItem)(w[v],b=>g+=d(b)),g===1/0))return 1/0}return g}function u(w,g="",v){v!==!1&&(g=m(g));let b=w.parse(g);return l(w,b)}e.getFullPath=u;function l(w,g){return w.serialize(g).split("#")[0]+"#"}e._getFullPath=l;var p=/#\/?$/;function m(w){return w?w.replace(p,""):""}e.normalizeId=m;function f(w,g,v){return v=m(v),w.resolve(g,v)}e.resolveUrl=f;var h=/^[a-z_][-a-z0-9._]*$/i;function y(w,g){if(typeof w=="boolean")return{};let{schemaId:v,uriResolver:b}=this.opts,S=m(w[v]||g),T={"":S},C=u(b,S,!1),_={},k=new Set;return i(w,{allKeys:!0},(R,M,A,F)=>{if(F===void 0)return;let se=C+M,he=T[F];typeof R[v]=="string"&&(he=ee.call(this,R[v])),$e.call(this,R.$anchor),$e.call(this,R.$dynamicAnchor),T[M]=he;function ee(be){let G=this.opts.uriResolver.resolve;if(be=m(he?G(he,be):be),k.has(be))throw P(be);k.add(be);let $=this.refs[be];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?I(R,$.schema,be):be!==m(se)&&(be[0]==="#"?(I(R,_[be],be),_[be]=R):this.refs[be]=se),be}function $e(be){if(typeof be=="string"){if(!h.test(be))throw Error(`invalid anchor "${be}"`);ee.call(this,`#${be}`)}}}),_;function I(R,M,A){if(M!==void 0&&!n(R,M))throw P(A)}function P(R){return Error(`reference "${R}" resolves to more than one schema`)}}e.getSchemaRefs=y}),al=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;var t=i1(),n=jd(),i=US(),r=jd(),o=o1(),a=a1(),s=s1(),d=Te(),u=Cr(),l=ol(),p=Ae(),m=il();function f(j){if(C(j)&&(k(j),T(j))){g(j);return}h(j,()=>(0,t.topBoolOrEmptySchema)(j))}e.validateFunctionCode=f;function h({gen:j,validateName:D,schema:K,schemaEnv:Y,opts:ue},xe){ue.code.es5?j.func(D,d._`${u.default.data}, ${u.default.valCxt}`,Y.$async,()=>{j.code(d._`"use strict"; ${b(K,ue)}`),w(j,ue),j.code(xe)}):j.func(D,d._`${u.default.data}, ${y(ue)}`,Y.$async,()=>j.code(b(K,ue)).code(xe))}function y(j){return d._`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${j.dynamicRef?d._`, ${u.default.dynamicAnchors}={}`:d.nil}}={}`}function w(j,D){j.if(u.default.valCxt,()=>{j.var(u.default.instancePath,d._`${u.default.valCxt}.${u.default.instancePath}`),j.var(u.default.parentData,d._`${u.default.valCxt}.${u.default.parentData}`),j.var(u.default.parentDataProperty,d._`${u.default.valCxt}.${u.default.parentDataProperty}`),j.var(u.default.rootData,d._`${u.default.valCxt}.${u.default.rootData}`),D.dynamicRef&&j.var(u.default.dynamicAnchors,d._`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{j.var(u.default.instancePath,d._`""`),j.var(u.default.parentData,d._`undefined`),j.var(u.default.parentDataProperty,d._`undefined`),j.var(u.default.rootData,u.default.data),D.dynamicRef&&j.var(u.default.dynamicAnchors,d._`{}`)})}function g(j){let{schema:D,opts:K,gen:Y}=j;h(j,()=>{K.$comment&&D.$comment&&F(j),R(j),Y.let(u.default.vErrors,null),Y.let(u.default.errors,0),K.unevaluated&&v(j),I(j),se(j)})}function v(j){let{gen:D,validateName:K}=j;j.evaluated=D.const("evaluated",d._`${K}.evaluated`),D.if(d._`${j.evaluated}.dynamicProps`,()=>D.assign(d._`${j.evaluated}.props`,d._`undefined`)),D.if(d._`${j.evaluated}.dynamicItems`,()=>D.assign(d._`${j.evaluated}.items`,d._`undefined`))}function b(j,D){let K=typeof j=="object"&&j[D.schemaId];return K&&(D.code.source||D.code.process)?d._`/*# sourceURL=${K} */`:d.nil}function S(j,D){if(C(j)&&(k(j),T(j))){_(j,D);return}(0,t.boolOrEmptySchema)(j,D)}function T({schema:j,self:D}){if(typeof j=="boolean")return!j;for(let K in j)if(D.RULES.all[K])return!0;return!1}function C(j){return typeof j.schema!="boolean"}function _(j,D){let{schema:K,gen:Y,opts:ue}=j;ue.$comment&&K.$comment&&F(j),M(j),A(j);let xe=Y.const("_errs",u.default.errors);I(j,xe),Y.var(D,d._`${xe} === ${u.default.errors}`)}function k(j){(0,p.checkUnknownRules)(j),P(j)}function I(j,D){if(j.opts.jtd)return ee(j,[],!1,D);let K=(0,n.getSchemaTypes)(j.schema),Y=(0,n.coerceAndCheckDataType)(j,K);ee(j,K,!Y,D)}function P(j){let{schema:D,errSchemaPath:K,opts:Y,self:ue}=j;D.$ref&&Y.ignoreKeywordsWithRef&&(0,p.schemaHasRulesButRef)(D,ue.RULES)&&ue.logger.warn(`$ref: keywords ignored in schema at path "${K}"`)}function R(j){let{schema:D,opts:K}=j;D.default!==void 0&&K.useDefaults&&K.strictSchema&&(0,p.checkStrictMode)(j,"default is ignored in the schema root")}function M(j){let D=j.schema[j.opts.schemaId];D&&(j.baseId=(0,l.resolveUrl)(j.opts.uriResolver,j.baseId,D))}function A(j){if(j.schema.$async&&!j.schemaEnv.$async)throw Error("async schema in sync schema")}function F({gen:j,schemaEnv:D,schema:K,errSchemaPath:Y,opts:ue}){let xe=K.$comment;if(ue.$comment===!0)j.code(d._`${u.default.self}.logger.log(${xe})`);else if(typeof ue.$comment=="function"){let lt=d.str`${Y}/$comment`,Ft=j.scopeValue("root",{ref:D.root});j.code(d._`${u.default.self}.opts.$comment(${xe}, ${lt}, ${Ft}.schema)`)}}function se(j){let{gen:D,schemaEnv:K,validateName:Y,ValidationError:ue,opts:xe}=j;K.$async?D.if(d._`${u.default.errors} === 0`,()=>D.return(u.default.data),()=>D.throw(d._`new ${ue}(${u.default.vErrors})`)):(D.assign(d._`${Y}.errors`,u.default.vErrors),xe.unevaluated&&he(j),D.return(d._`${u.default.errors} === 0`))}function he({gen:j,evaluated:D,props:K,items:Y}){K instanceof d.Name&&j.assign(d._`${D}.props`,K),Y instanceof d.Name&&j.assign(d._`${D}.items`,Y)}function ee(j,D,K,Y){let{gen:ue,schema:xe,data:lt,allErrors:Ft,opts:St,self:yt}=j,{RULES:st}=yt;if(xe.$ref&&(St.ignoreKeywordsWithRef||!(0,p.schemaHasRulesButRef)(xe,st))){ue.block(()=>X(j,"$ref",st.all.$ref.definition));return}St.jtd||be(j,D),ue.block(()=>{for(let Ct of st.rules)Kn(Ct);Kn(st.post)});function Kn(Ct){(0,i.shouldUseGroup)(xe,Ct)&&(Ct.type?(ue.if((0,r.checkDataType)(Ct.type,lt,St.strictNumbers)),$e(j,Ct),D.length===1&&D[0]===Ct.type&&K&&(ue.else(),(0,r.reportTypeError)(j)),ue.endIf()):$e(j,Ct),Ft||ue.if(d._`${u.default.errors} === ${Y||0}`))}}function $e(j,D){let{gen:K,schema:Y,opts:{useDefaults:ue}}=j;ue&&(0,o.assignDefaults)(j,D.type),K.block(()=>{for(let xe of D.rules)(0,i.shouldUseRule)(Y,xe)&&X(j,xe.keyword,xe.definition,D.type)})}function be(j,D){j.schemaEnv.meta||!j.opts.strictTypes||(G(j,D),!j.opts.allowUnionTypes&&$(j,D),B(j,j.dataTypes))}function G(j,D){if(D.length){if(!j.dataTypes.length){j.dataTypes=D;return}D.forEach(K=>{x(j.dataTypes,K)||O(j,`type "${K}" not allowed by context "${j.dataTypes.join(",")}"`)}),E(j,D)}}function $(j,D){D.length>1&&!(D.length===2&&D.includes("null"))&&O(j,"use allowUnionTypes to allow union type keyword")}function B(j,D){let K=j.self.RULES.all;for(let Y in K){let ue=K[Y];if(typeof ue=="object"&&(0,i.shouldUseRule)(j.schema,ue)){let{type:xe}=ue.definition;xe.length&&!xe.some(lt=>L(D,lt))&&O(j,`missing type "${xe.join(",")}" for keyword "${Y}"`)}}}function L(j,D){return j.includes(D)||D==="number"&&j.includes("integer")}function x(j,D){return j.includes(D)||D==="integer"&&j.includes("number")}function E(j,D){let K=[];for(let Y of j.dataTypes)x(D,Y)?K.push(Y):D.includes("integer")&&Y==="number"&&K.push("integer");j.dataTypes=K}function O(j,D){let K=j.schemaEnv.baseId+j.errSchemaPath;D+=` at "${K}" (strictTypes)`,(0,p.checkStrictMode)(j,D,j.opts.strictTypes)}class ne{constructor(D,K,Y){if((0,a.validateKeywordUsage)(D,K,Y),this.gen=D.gen,this.allErrors=D.allErrors,this.keyword=Y,this.data=D.data,this.schema=D.schema[Y],this.$data=K.$data&&D.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,p.schemaRefOrVal)(D,this.schema,Y,this.$data),this.schemaType=K.schemaType,this.parentSchema=D.schema,this.params={},this.it=D,this.def=K,this.$data)this.schemaCode=D.gen.const("vSchema",Je(this.$data,D));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,K.schemaType,K.allowUndefined))throw Error(`${Y} value must be ${JSON.stringify(K.schemaType)}`);("code"in K?K.trackErrors:K.errors!==!1)&&(this.errsCount=D.gen.const("_errs",u.default.errors))}result(D,K,Y){this.failResult((0,d.not)(D),K,Y)}failResult(D,K,Y){this.gen.if(D),Y?Y():this.error(),K?(this.gen.else(),K(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(D,K){this.failResult((0,d.not)(D),void 0,K)}fail(D){if(D===void 0){this.error(),!this.allErrors&&this.gen.if(!1);return}this.gen.if(D),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(D){if(!this.$data)return this.fail(D);let{schemaCode:K}=this;this.fail(d._`${K} !== undefined && (${(0,d.or)(this.invalid$data(),D)})`)}error(D,K,Y){if(K){this.setParams(K),this._error(D,Y),this.setParams({});return}this._error(D,Y)}_error(D,K){(D?m.reportExtraError:m.reportError)(this,this.def.error,K)}$dataError(){(0,m.reportError)(this,this.def.$dataError||m.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,m.resetErrorsCount)(this.gen,this.errsCount)}ok(D){this.allErrors||this.gen.if(D)}setParams(D,K){K?Object.assign(this.params,D):this.params=D}block$data(D,K,Y=d.nil){this.gen.block(()=>{this.check$data(D,Y),K()})}check$data(D=d.nil,K=d.nil){if(!this.$data)return;let{gen:Y,schemaCode:ue,schemaType:xe,def:lt}=this;Y.if((0,d.or)(d._`${ue} === undefined`,K)),D!==d.nil&&Y.assign(D,!0),(xe.length||lt.validateSchema)&&(Y.elseIf(this.invalid$data()),this.$dataError(),D!==d.nil&&Y.assign(D,!1)),Y.else()}invalid$data(){let{gen:D,schemaCode:K,schemaType:Y,def:ue,it:xe}=this;return(0,d.or)(lt(),Ft());function lt(){if(Y.length){if(!(K instanceof d.Name))throw Error("ajv implementation error");let St=Array.isArray(Y)?Y:[Y];return d._`${(0,r.checkDataTypes)(St,K,xe.opts.strictNumbers,r.DataType.Wrong)}`}return d.nil}function Ft(){if(ue.validateSchema){let St=D.scopeValue("validate$data",{ref:ue.validateSchema});return d._`!${St}(${K})`}return d.nil}}subschema(D,K){let Y=(0,s.getSubschema)(this.it,D);(0,s.extendSubschemaData)(Y,this.it,D),(0,s.extendSubschemaMode)(Y,D);let ue={...this.it,...Y,items:void 0,props:void 0};return S(ue,K),ue}mergeEvaluated(D,K){let{it:Y,gen:ue}=this;Y.opts.unevaluated&&(Y.props!==!0&&D.props!==void 0&&(Y.props=p.mergeEvaluated.props(ue,D.props,Y.props,K)),Y.items!==!0&&D.items!==void 0&&(Y.items=p.mergeEvaluated.items(ue,D.items,Y.items,K)))}mergeValidEvaluated(D,K){let{it:Y,gen:ue}=this;if(Y.opts.unevaluated&&(Y.props!==!0||Y.items!==!0))return ue.if(K,()=>this.mergeEvaluated(D,d.Name)),!0}}e.KeywordCxt=ne;function X(j,D,K,Y){let ue=new ne(j,K,D);"code"in K?K.code(ue,Y):ue.$data&&K.validate?(0,a.funcKeywordCode)(ue,K):"macro"in K?(0,a.macroKeywordCode)(ue,K):(K.compile||K.validate)&&(0,a.funcKeywordCode)(ue,K)}var we=/^\/(?:[^~]|~0|~1)*$/,Se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Je(j,{dataLevel:D,dataNames:K,dataPathArr:Y}){let ue,xe;if(j==="")return u.default.rootData;if(j[0]==="/"){if(!we.test(j))throw Error(`Invalid JSON-pointer: ${j}`);ue=j,xe=u.default.rootData}else{let yt=Se.exec(j);if(!yt)throw Error(`Invalid JSON-pointer: ${j}`);let st=+yt[1];if(ue=yt[2],ue==="#"){if(st>=D)throw Error(St("property/index",st));return Y[D-st]}if(st>D)throw Error(St("data",st));if(xe=K[D-st],!ue)return xe}let lt=xe,Ft=ue.split("/");for(let yt of Ft)yt&&(xe=d._`${xe}${(0,d.getProperty)((0,p.unescapeJsonPointer)(yt))}`,lt=d._`${lt} && ${xe}`);return lt;function St(yt,st){return`Cannot access ${yt} ${st} levels up, current level is ${D}`}}e.getData=Je}),cm=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});class t extends Error{constructor(i){super("validation failed"),this.errors=i,this.ajv=this.validation=!0}}e.default=t}),sl=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=ol();class n extends Error{constructor(r,o,a,s){super(s||`can't resolve reference ${a} from id ${o}`),this.missingRef=(0,t.resolveUrl)(r,o,a),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(r,this.missingRef))}}e.default=n}),pm=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;var t=Te(),n=cm(),i=Cr(),r=ol(),o=Ae(),a=al();class s{constructor(v){var b;this.refs={},this.dynamicAnchors={};let S;typeof v.schema=="object"&&(S=v.schema),this.schema=v.schema,this.schemaId=v.schemaId,this.root=v.root||this,this.baseId=(b=v.baseId)!==null&&b!==void 0?b:(0,r.normalizeId)(S?.[v.schemaId||"$id"]),this.schemaPath=v.schemaPath,this.localRefs=v.localRefs,this.meta=v.meta,this.$async=S?.$async,this.refs={}}}e.SchemaEnv=s;function d(g){let v=p.call(this,g);if(v)return v;let b=(0,r.getFullPath)(this.opts.uriResolver,g.root.baseId),{es5:S,lines:T}=this.opts.code,{ownProperties:C}=this.opts,_=new t.CodeGen(this.scope,{es5:S,lines:T,ownProperties:C}),k;g.$async&&(k=_.scopeValue("Error",{ref:n.default,code:t._`require("ajv/dist/runtime/validation_error").default`}));let I=_.scopeName("validate");g.validateName=I;let P={gen:_,allErrors:this.opts.allErrors,data:i.default.data,parentData:i.default.parentData,parentDataProperty:i.default.parentDataProperty,dataNames:[i.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:_.scopeValue("schema",this.opts.code.source===!0?{ref:g.schema,code:(0,t.stringify)(g.schema)}:{ref:g.schema}),validateName:I,ValidationError:k,schema:g.schema,schemaEnv:g,rootId:b,baseId:g.baseId||b,schemaPath:t.nil,errSchemaPath:g.schemaPath||(this.opts.jtd?"":"#"),errorPath:t._`""`,opts:this.opts,self:this},R;try{this._compilations.add(g),(0,a.validateFunctionCode)(P),_.optimize(this.opts.code.optimize);let M=_.toString();R=`${_.scopeRefs(i.default.scope)}return ${M}`,this.opts.code.process&&(R=this.opts.code.process(R,g));let A=Function(`${i.default.self}`,`${i.default.scope}`,R)(this,this.scope.get());if(this.scope.value(I,{ref:A}),A.errors=null,A.schema=g.schema,A.schemaEnv=g,g.$async&&(A.$async=!0),this.opts.code.source===!0&&(A.source={validateName:I,validateCode:M,scopeValues:_._values}),this.opts.unevaluated){let{props:F,items:se}=P;A.evaluated={props:F instanceof t.Name?void 0:F,items:se instanceof t.Name?void 0:se,dynamicProps:F instanceof t.Name,dynamicItems:se instanceof t.Name},A.source&&(A.source.evaluated=(0,t.stringify)(A.evaluated))}return g.validate=A,g}catch(M){throw delete g.validate,delete g.validateName,R&&this.logger.error("Error compiling schema, function code:",R),M}finally{this._compilations.delete(g)}}e.compileSchema=d;function u(g,v,b){var S;b=(0,r.resolveUrl)(this.opts.uriResolver,v,b);let T=g.refs[b];if(T)return T;let C=f.call(this,g,b);if(C===void 0){let _=(S=g.localRefs)===null||S===void 0?void 0:S[b],{schemaId:k}=this.opts;_&&(C=new s({schema:_,schemaId:k,root:g,baseId:v}))}if(C!==void 0)return g.refs[b]=l.call(this,C)}e.resolveRef=u;function l(g){return(0,r.inlineRef)(g.schema,this.opts.inlineRefs)?g.schema:g.validate?g:d.call(this,g)}function p(g){for(let v of this._compilations)if(m(v,g))return v}e.getCompilingSchema=p;function m(g,v){return g.schema===v.schema&&g.root===v.root&&g.baseId===v.baseId}function f(g,v){let b;for(;typeof(b=this.refs[v])=="string";)v=b;return b||this.schemas[v]||h.call(this,g,v)}function h(g,v){let b=this.opts.uriResolver.parse(v),S=(0,r._getFullPath)(this.opts.uriResolver,b),T=(0,r.getFullPath)(this.opts.uriResolver,g.baseId,void 0);if(Object.keys(g.schema).length>0&&S===T)return w.call(this,b,g);let C=(0,r.normalizeId)(S),_=this.refs[C]||this.schemas[C];if(typeof _=="string"){let k=h.call(this,g,_);return typeof k?.schema!="object"?void 0:w.call(this,b,k)}if(typeof _?.schema=="object"){if(_.validate||d.call(this,_),C===(0,r.normalizeId)(v)){let{schema:k}=_,{schemaId:I}=this.opts,P=k[I];return P&&(T=(0,r.resolveUrl)(this.opts.uriResolver,T,P)),new s({schema:k,schemaId:I,root:g,baseId:T})}return w.call(this,b,_)}}e.resolveSchema=h;var y=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function w(g,{baseId:v,schema:b,root:S}){var T;if(((T=g.fragment)===null||T===void 0?void 0:T[0])!=="/")return;for(let k of g.fragment.slice(1).split("/")){if(typeof b=="boolean")return;let I=b[(0,o.unescapeFragment)(k)];if(I===void 0)return;b=I;let P=typeof b=="object"&&b[this.opts.schemaId];!y.has(k)&&P&&(v=(0,r.resolveUrl)(this.opts.uriResolver,v,P))}let C;if(typeof b!="boolean"&&b.$ref&&!(0,o.schemaHasRulesButRef)(b,this.RULES)){let k=(0,r.resolveUrl)(this.opts.uriResolver,v,b.$ref);C=h.call(this,S,k)}let{schemaId:_}=this.opts;if(C=C||new s({schema:b,schemaId:_,root:S,baseId:v}),C.schema!==C.root.schema)return C}}),u1=z((e,t)=>{t.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),zS=z((e,t)=>{var n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),i=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),r=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),a=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function s(_){let k="",I=0,P=0;for(P=0;P<_.length;P++)if(I=_[P].charCodeAt(0),I!==48){if(!(I>=48&&I<=57||I>=65&&I<=70||I>=97&&I<=102))return"";k+=_[P];break}for(P+=1;P<_.length;P++){if(I=_[P].charCodeAt(0),!(I>=48&&I<=57||I>=65&&I<=70||I>=97&&I<=102))return"";k+=_[P]}return k}var d=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function u(_){return _.length=0,!0}function l(_,k,I){if(_.length){let P=s(_);if(P!=="")k.push(P);else return I.error=!0,!1;_.length=0}return!0}function p(_){let k=0,I={error:!1,address:"",zone:""},P=[],R=[],M=!1,A=!1,F=l;for(let se=0;se<_.length;se++){let he=_[se];if(!(he==="["||he==="]"))if(he===":"){if(M===!0&&(A=!0),!F(R,P,I))break;if(++k>7){I.error=!0;break}se>0&&_[se-1]===":"&&(M=!0),P.push(":");continue}else if(he==="%"){if(!F(R,P,I))break;F=u}else{R.push(he);continue}}return R.length&&(F===u?I.zone=R.join(""):A?P.push(R.join("")):P.push(s(R))),I.address=P.join(""),I}function m(_){if(f(_,":")<2)return{host:_,isIPV6:!1};let k=p(_);if(k.error)return{host:_,isIPV6:!1};{let{address:I,address:P}=k;return k.zone&&(I+="%"+k.zone,P+="%25"+k.zone),{host:I,isIPV6:!0,escapedHost:P}}}function f(_,k){let I=0;for(let P=0;P<_.length;P++)_[P]===k&&I++;return I}function h(_){let k=_,I=[],P=-1,R=0;for(;R=k.length;){if(R===1){if(k===".")break;if(k==="/"){I.push("/");break}else{I.push(k);break}}else if(R===2){if(k[0]==="."){if(k[1]===".")break;if(k[1]==="/"){k=k.slice(2);continue}}else if(k[0]==="/"&&(k[1]==="."||k[1]==="/")){I.push("/");break}}else if(R===3&&k==="/.."){I.length!==0&&I.pop(),I.push("/");break}if(k[0]==="."){if(k[1]==="."){if(k[2]==="/"){k=k.slice(3);continue}}else if(k[1]==="/"){k=k.slice(2);continue}}else if(k[0]==="/"&&k[1]==="."){if(k[2]==="/"){k=k.slice(2);continue}else if(k[2]==="."&&k[3]==="/"){k=k.slice(3),I.length!==0&&I.pop();continue}}if((P=k.indexOf("/",1))===-1){I.push(k);break}else I.push(k.slice(0,P)),k=k.slice(P)}return I.join("")}var y={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},w=/[@/?#:]/g,g=/[@/?#]/g;function v(_,k){let I=k?g:w;return I.lastIndex=0,_.replace(I,P=>y[P])}function b(_,k=!1){if(_.indexOf("%")===-1)return _;let I="";for(let P=0;P<_.length;P++){if(_[P]==="%"&&P+2<_.length){let R=_.slice(P+1,P+3);if(r(R)){let M=R.toUpperCase(),A=String.fromCharCode(parseInt(M,16));k&&o(A)?I+=A:I+="%"+M,P+=2;continue}}I+=_[P]}return I}function S(_){let k="";for(let I=0;I<_.length;I++){if(_[I]==="%"&&I+2<_.length){let P=_.slice(I+1,I+3);if(r(P)){let R=P.toUpperCase(),M=String.fromCharCode(parseInt(R,16));M!=="."&&o(M)?k+=M:k+="%"+R,I+=2;continue}}a(_[I])?k+=_[I]:k+=escape(_[I])}return k}function T(_){let k="";for(let I=0;I<_.length;I++){if(_[I]==="%"&&I+2<_.length){let P=_.slice(I+1,I+3);if(r(P)){k+="%"+P.toUpperCase(),I+=2;continue}}k+=escape(_[I])}return k}function C(_){let k=[];if(_.userinfo!==void 0&&(k.push(_.userinfo),k.push("@")),_.host!==void 0){let I=unescape(_.host);if(!i(I)){let P=m(I);P.isIPV6===!0?I=`[${P.escapedHost}]`:I=v(I,!1)}k.push(I)}return(typeof _.port=="number"||typeof _.port=="string")&&(k.push(":"),k.push(String(_.port))),k.length?k.join(""):void 0}t.exports={nonSimpleDomain:d,recomposeAuthority:C,reescapeHostDelimiters:v,normalizePercentEncoding:b,normalizePathEncoding:S,escapePreservingEscapes:T,removeDotSegments:h,isIPv4:i,isUUID:n,normalizeIPv6:m,stringArrayToHexStripped:s}}),l1=z((e,t)=>{var{isUUID:n}=zS(),i=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function o(_){return r.indexOf(_)!==-1}function a(_){return _.secure===!0?!0:_.secure===!1?!1:_.scheme?_.scheme.length===3&&(_.scheme[0]==="w"||_.scheme[0]==="W")&&(_.scheme[1]==="s"||_.scheme[1]==="S")&&(_.scheme[2]==="s"||_.scheme[2]==="S"):!1}function s(_){return _.host||(_.error=_.error||"HTTP URIs must have a host."),_}function d(_){let k=String(_.scheme).toLowerCase()==="https";return(_.port===(k?443:80)||_.port==="")&&(_.port=void 0),_.path||(_.path="/"),_}function u(_){return _.secure=a(_),_.resourceName=(_.path||"/")+(_.query?"?"+_.query:""),_.path=void 0,_.query=void 0,_}function l(_){if((_.port===(a(_)?443:80)||_.port==="")&&(_.port=void 0),typeof _.secure=="boolean"&&(_.scheme=_.secure?"wss":"ws",_.secure=void 0),_.resourceName){let[k,I]=_.resourceName.split("?");_.path=k&&k!=="/"?k:void 0,_.query=I,_.resourceName=void 0}return _.fragment=void 0,_}function p(_,k){if(!_.path)return _.error="URN can not be parsed",_;let I=_.path.match(i);if(I){let P=k.scheme||_.scheme||"urn";_.nid=I[1].toLowerCase(),_.nss=I[2];let R=`${P}:${k.nid||_.nid}`,M=C(R);_.path=void 0,M&&(_=M.parse(_,k))}else _.error=_.error||"URN can not be parsed.";return _}function m(_,k){if(_.nid===void 0)throw Error("URN without nid cannot be serialized");let I=k.scheme||_.scheme||"urn",P=_.nid.toLowerCase(),R=`${I}:${k.nid||P}`,M=C(R);M&&(_=M.serialize(_,k));let A=_,F=_.nss;return A.path=`${P||k.nid}:${F}`,k.skipEscape=!0,A}function f(_,k){let I=_;return I.uuid=I.nss,I.nss=void 0,!k.tolerant&&(!I.uuid||!n(I.uuid))&&(I.error=I.error||"UUID is not valid."),I}function h(_){let k=_;return k.nss=(_.uuid||"").toLowerCase(),k}var y={scheme:"http",domainHost:!0,parse:s,serialize:d},w={scheme:"https",domainHost:y.domainHost,parse:s,serialize:d},g={scheme:"ws",domainHost:!0,parse:u,serialize:l},v={scheme:"wss",domainHost:g.domainHost,parse:g.parse,serialize:g.serialize},b={scheme:"urn",parse:p,serialize:m,skipNormalize:!0},S={scheme:"urn:uuid",parse:f,serialize:h,skipNormalize:!0},T={http:y,https:w,ws:g,wss:v,urn:b,"urn:uuid":S};Object.setPrototypeOf(T,null);function C(_){return _&&(T[_]||T[_.toLowerCase()])||void 0}t.exports={wsIsSecure:a,SCHEMES:T,isValidSchemeName:o,getSchemeHandler:C}}),c1=z((e,t)=>{var{normalizeIPv6:n,removeDotSegments:i,recomposeAuthority:r,normalizePercentEncoding:o,normalizePathEncoding:a,escapePreservingEscapes:s,reescapeHostDelimiters:d,isIPv4:u,nonSimpleDomain:l}=zS(),{SCHEMES:p,getSchemeHandler:m}=l1();function f(P,R){return typeof P=="string"?P=C(P,R):typeof P=="object"&&(P=T(g(P,R),R)),P}function h(P,R,M){let A=M?Object.assign({scheme:"null"},M):{scheme:"null"},F=y(T(P,A),T(R,A),A,!0);return A.skipEscape=!0,g(F,A)}function y(P,R,M,A){let F={};return A||(P=T(g(P,M),M),R=T(g(R,M),M)),M=M||{},!M.tolerant&&R.scheme?(F.scheme=R.scheme,F.userinfo=R.userinfo,F.host=R.host,F.port=R.port,F.path=i(R.path||""),F.query=R.query):(R.userinfo!==void 0||R.host!==void 0||R.port!==void 0?(F.userinfo=R.userinfo,F.host=R.host,F.port=R.port,F.path=i(R.path||""),F.query=R.query):(R.path?(R.path[0]==="/"?F.path=i(R.path):((P.userinfo!==void 0||P.host!==void 0||P.port!==void 0)&&!P.path?F.path="/"+R.path:P.path?F.path=P.path.slice(0,P.path.lastIndexOf("/")+1)+R.path:F.path=R.path,F.path=i(F.path)),F.query=R.query):(F.path=P.path,R.query!==void 0?F.query=R.query:F.query=P.query),F.userinfo=P.userinfo,F.host=P.host,F.port=P.port),F.scheme=P.scheme),F.fragment=R.fragment,F}function w(P,R,M){let A=k(P,M),F=k(R,M);return A!==void 0&&F!==void 0&&A.toLowerCase()===F.toLowerCase()}function g(P,R){let M={host:P.host,scheme:P.scheme,userinfo:P.userinfo,port:P.port,path:P.path,query:P.query,nid:P.nid,nss:P.nss,uuid:P.uuid,fragment:P.fragment,reference:P.reference,resourceName:P.resourceName,secure:P.secure,error:""},A=Object.assign({},R),F=[],se=m(A.scheme||M.scheme);se&&se.serialize&&se.serialize(M,A),M.path!==void 0&&(A.skipEscape?M.path=o(M.path):(M.path=s(M.path),M.scheme!==void 0&&(M.path=M.path.split("%3A").join(":")))),A.reference!=="suffix"&&M.scheme&&F.push(M.scheme,":");let he=r(M);if(he!==void 0&&(A.reference!=="suffix"&&F.push("//"),F.push(he),M.path&&M.path[0]!=="/"&&F.push("/")),M.path!==void 0){let ee=M.path;!A.absolutePath&&(!se||!se.absolutePath)&&(ee=i(ee)),he===void 0&&ee[0]==="/"&&ee[1]==="/"&&(ee="/%2F"+ee.slice(2)),F.push(ee)}return M.query!==void 0&&F.push("?",M.query),M.fragment!==void 0&&F.push("#",M.fragment),F.join("")}var v=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function b(P,R){if(R[2]!==void 0&&P.path&&P.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof P.port=="number"&&(P.port<0||P.port>65535))return"URI port is malformed."}function S(P,R){let M=Object.assign({},R),A={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},F=!1,se=!1;M.reference==="suffix"&&(M.scheme?P=M.scheme+":"+P:P="//"+P);let he=P.match(v);if(he){A.scheme=he[1],A.userinfo=he[3],A.host=he[4],A.port=parseInt(he[5],10),A.path=he[6]||"",A.query=he[7],A.fragment=he[8],isNaN(A.port)&&(A.port=he[5]);let ee=b(A,he);if(ee!==void 0&&(A.error=A.error||ee,F=!0),A.host)if(u(A.host)===!1){let be=n(A.host);A.host=be.host.toLowerCase(),se=be.isIPV6}else se=!0;A.scheme===void 0&&A.userinfo===void 0&&A.host===void 0&&A.port===void 0&&A.query===void 0&&!A.path?A.reference="same-document":A.scheme===void 0?A.reference="relative":A.fragment===void 0?A.reference="absolute":A.reference="uri",M.reference&&M.reference!=="suffix"&&M.reference!==A.reference&&(A.error=A.error||"URI is not a "+M.reference+" reference.");let $e=m(M.scheme||A.scheme);if(!M.unicodeSupport&&(!$e||!$e.unicodeSupport)&&A.host&&(M.domainHost||$e&&$e.domainHost)&&se===!1&&l(A.host))try{A.host=URL.domainToASCII(A.host.toLowerCase())}catch(be){A.error=A.error||"Host's domain name can not be converted to ASCII: "+be}if((!$e||$e&&!$e.skipNormalize)&&(P.indexOf("%")!==-1&&(A.scheme!==void 0&&(A.scheme=unescape(A.scheme)),A.host!==void 0&&(A.host=d(unescape(A.host),se))),A.path&&(A.path=a(A.path)),A.fragment))try{A.fragment=encodeURI(decodeURIComponent(A.fragment))}catch{A.error=A.error||"URI malformed"}$e&&$e.parse&&$e.parse(A,M)}else A.error=A.error||"URI can not be parsed.";return{parsed:A,malformedAuthorityOrPort:F}}function T(P,R){return S(P,R).parsed}function C(P,R){return _(P,R).normalized}function _(P,R){let{parsed:M,malformedAuthorityOrPort:A}=S(P,R);return{normalized:A?P:g(M,R),malformedAuthorityOrPort:A}}function k(P,R){if(typeof P=="string"){let{normalized:M,malformedAuthorityOrPort:A}=_(P,R);return A?void 0:M}if(typeof P=="object")return g(P,R)}var I={SCHEMES:p,normalize:f,resolve:h,resolveComponent:y,equal:w,serialize:g,parse:T};t.exports=I,t.exports.default=I,t.exports.fastUri=I}),p1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=c1();t.code='require("ajv/dist/runtime/uri").default',e.default=t}),f1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=al();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Te();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});var i=cm(),r=sl(),o=LS(),a=pm(),s=Te(),d=ol(),u=jd(),l=Ae(),p=u1(),m=p1(),f=(G,$)=>new RegExp(G,$);f.code="new RegExp";var h=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),w={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},g={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function b(G){var $,B,L,x,E,O,ne,X,we,Se,Je,j,D,K,Y,ue,xe,lt,Ft,St,yt,st,Kn,Ct,To;let Er=G.strict,pi=($=G.code)===null||$===void 0?void 0:$.optimize,Ms=pi===!0||pi===void 0?1:pi||0,js=(L=(B=G.code)===null||B===void 0?void 0:B.regExp)!==null&&L!==void 0?L:f,Io=(x=G.uriResolver)!==null&&x!==void 0?x:m.default;return{strictSchema:(O=(E=G.strictSchema)!==null&&E!==void 0?E:Er)!==null&&O!==void 0?O:!0,strictNumbers:(X=(ne=G.strictNumbers)!==null&&ne!==void 0?ne:Er)!==null&&X!==void 0?X:!0,strictTypes:(Se=(we=G.strictTypes)!==null&&we!==void 0?we:Er)!==null&&Se!==void 0?Se:"log",strictTuples:(j=(Je=G.strictTuples)!==null&&Je!==void 0?Je:Er)!==null&&j!==void 0?j:"log",strictRequired:(K=(D=G.strictRequired)!==null&&D!==void 0?D:Er)!==null&&K!==void 0?K:!1,code:G.code?{...G.code,optimize:Ms,regExp:js}:{optimize:Ms,regExp:js},loopRequired:(Y=G.loopRequired)!==null&&Y!==void 0?Y:v,loopEnum:(ue=G.loopEnum)!==null&&ue!==void 0?ue:v,meta:(xe=G.meta)!==null&&xe!==void 0?xe:!0,messages:(lt=G.messages)!==null&&lt!==void 0?lt:!0,inlineRefs:(Ft=G.inlineRefs)!==null&&Ft!==void 0?Ft:!0,schemaId:(St=G.schemaId)!==null&&St!==void 0?St:"$id",addUsedSchema:(yt=G.addUsedSchema)!==null&&yt!==void 0?yt:!0,validateSchema:(st=G.validateSchema)!==null&&st!==void 0?st:!0,validateFormats:(Kn=G.validateFormats)!==null&&Kn!==void 0?Kn:!0,unicodeRegExp:(Ct=G.unicodeRegExp)!==null&&Ct!==void 0?Ct:!0,int32range:(To=G.int32range)!==null&&To!==void 0?To:!0,uriResolver:Io}}class S{constructor($={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...b($)};let{es5:B,lines:L}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:y,es5:B,lines:L}),this.logger=M($.logger);let x=$.validateFormats;$.validateFormats=!1,this.RULES=(0,o.getRules)(),T.call(this,w,$,"NOT SUPPORTED"),T.call(this,g,$,"DEPRECATED","warn"),this._metaOpts=P.call(this),$.formats&&k.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords&&I.call(this,$.keywords),typeof $.meta=="object"&&this.addMetaSchema($.meta),_.call(this),$.validateFormats=x}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:B,schemaId:L}=this.opts,x=p;L==="id"&&(x={...p},x.id=x.$id,delete x.$id),B&&$&&this.addMetaSchema(x,x[L],!1)}defaultMeta(){let{meta:$,schemaId:B}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[B]||$:void 0}validate($,B){let L;if(typeof $=="string"){if(L=this.getSchema($),!L)throw Error(`no schema with key or ref "${$}"`)}else L=this.compile($);let x=L(B);return"$async"in L||(this.errors=L.errors),x}compile($,B){let L=this._addSchema($,B);return L.validate||this._compileSchemaEnv(L)}compileAsync($,B){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:L}=this.opts;return x.call(this,$,B);async function x(Se,Je){await E.call(this,Se.$schema);let j=this._addSchema(Se,Je);return j.validate||O.call(this,j)}async function E(Se){Se&&!this.getSchema(Se)&&await x.call(this,{$ref:Se},!0)}async function O(Se){try{return this._compileSchemaEnv(Se)}catch(Je){if(!(Je instanceof r.default))throw Je;return ne.call(this,Je),await X.call(this,Je.missingSchema),O.call(this,Se)}}function ne({missingSchema:Se,missingRef:Je}){if(this.refs[Se])throw Error(`AnySchema ${Se} is loaded but ${Je} cannot be resolved`)}async function X(Se){let Je=await we.call(this,Se);this.refs[Se]||await E.call(this,Je.$schema),this.refs[Se]||this.addSchema(Je,Se,B)}async function we(Se){let Je=this._loading[Se];if(Je)return Je;try{return await(this._loading[Se]=L(Se))}finally{delete this._loading[Se]}}}addSchema($,B,L,x=this.opts.validateSchema){if(Array.isArray($)){for(let O of $)this.addSchema(O,void 0,L,x);return this}let E;if(typeof $=="object"){let{schemaId:O}=this.opts;if(E=$[O],E!==void 0&&typeof E!="string")throw Error(`schema ${O} must be string`)}return B=(0,d.normalizeId)(B||E),this._checkUnique(B),this.schemas[B]=this._addSchema($,L,B,x,!0),this}addMetaSchema($,B,L=this.opts.validateSchema){return this.addSchema($,B,!0,L),this}validateSchema($,B){if(typeof $=="boolean")return!0;let L;if(L=$.$schema,L!==void 0&&typeof L!="string")throw Error("$schema must be a string");if(L=L||this.opts.defaultMeta||this.defaultMeta(),!L)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let x=this.validate(L,$);if(!x&&B){let E="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(E);else throw Error(E)}return x}getSchema($){let B;for(;typeof(B=C.call(this,$))=="string";)$=B;if(B===void 0){let{schemaId:L}=this.opts,x=new a.SchemaEnv({schema:{},schemaId:L});if(B=a.resolveSchema.call(this,x,$),!B)return;this.refs[$]=B}return B.validate||this._compileSchemaEnv(B)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let B=C.call(this,$);return typeof B=="object"&&this._cache.delete(B.schema),delete this.schemas[$],delete this.refs[$],this}case"object":{let B=$;this._cache.delete(B);let L=$[this.opts.schemaId];return L&&(L=(0,d.normalizeId)(L),delete this.schemas[L],delete this.refs[L]),this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let B of $)this.addKeyword(B);return this}addKeyword($,B){let L;if(typeof $=="string")L=$,typeof B=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),B.keyword=L);else if(typeof $=="object"&&B===void 0){if(B=$,L=B.keyword,Array.isArray(L)&&!L.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(F.call(this,L,B),!B)return(0,l.eachItem)(L,E=>se.call(this,E)),this;ee.call(this,B);let x={...B,type:(0,u.getJSONTypes)(B.type),schemaType:(0,u.getJSONTypes)(B.schemaType)};return(0,l.eachItem)(L,x.type.length===0?E=>se.call(this,E,x):E=>x.type.forEach(O=>se.call(this,E,x,O))),this}getKeyword($){let B=this.RULES.all[$];return typeof B=="object"?B.definition:!!B}removeKeyword($){let{RULES:B}=this;delete B.keywords[$],delete B.all[$];for(let L of B.rules){let x=L.rules.findIndex(E=>E.keyword===$);x>=0&&L.rules.splice(x,1)}return this}addFormat($,B){return typeof B=="string"&&(B=new RegExp(B)),this.formats[$]=B,this}errorsText($=this.errors,{separator:B=", ",dataVar:L="data"}={}){return!$||$.length===0?"No errors":$.map(x=>`${L}${x.instancePath} ${x.message}`).reduce((x,E)=>x+B+E)}$dataMetaSchema($,B){let L=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let x of B){let E=x.split("/").slice(1),O=$;for(let ne of E)O=O[ne];for(let ne in L){let X=L[ne];if(typeof X!="object")continue;let{$data:we}=X.definition,Se=O[ne];we&&Se&&(O[ne]=be(Se))}}return $}_removeAllSchemas($,B){for(let L in $){let x=$[L];(!B||B.test(L))&&(typeof x=="string"?delete $[L]:x&&!x.meta&&(this._cache.delete(x.schema),delete $[L]))}}_addSchema($,B,L,x=this.opts.validateSchema,E=this.opts.addUsedSchema){let O,{schemaId:ne}=this.opts;if(typeof $=="object")O=$[ne];else{if(this.opts.jtd)throw Error("schema must be object");if(typeof $!="boolean")throw Error("schema must be object or boolean")}let X=this._cache.get($);if(X!==void 0)return X;L=(0,d.normalizeId)(O||L);let we=d.getSchemaRefs.call(this,$,L);return X=new a.SchemaEnv({schema:$,schemaId:ne,meta:B,baseId:L,localRefs:we}),this._cache.set(X.schema,X),E&&!L.startsWith("#")&&(L&&this._checkUnique(L),this.refs[L]=X),x&&this.validateSchema($,!0),X}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta?this._compileMetaSchema($):a.compileSchema.call(this,$),!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let B=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,$)}finally{this.opts=B}}}S.ValidationError=i.default,S.MissingRefError=r.default,e.default=S;function T(G,$,B,L="error"){for(let x in G){let E=x;E in $&&this.logger[L](`${B}: option ${x}. ${G[E]}`)}}function C(G){return G=(0,d.normalizeId)(G),this.schemas[G]||this.refs[G]}function _(){let G=this.opts.schemas;if(G)if(Array.isArray(G))this.addSchema(G);else for(let $ in G)this.addSchema(G[$],$)}function k(){for(let G in this.opts.formats){let $=this.opts.formats[G];$&&this.addFormat(G,$)}}function I(G){if(Array.isArray(G)){this.addVocabulary(G);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let $ in G){let B=G[$];B.keyword||(B.keyword=$),this.addKeyword(B)}}function P(){let G={...this.opts};for(let $ of h)delete G[$];return G}var R={log(){},warn(){},error(){}};function M(G){if(G===!1)return R;if(G===void 0)return console;if(G.log&&G.warn&&G.error)return G;throw Error("logger must implement log, warn and error methods")}var A=/^[a-z_$][a-z0-9_$:-]*$/i;function F(G,$){let{RULES:B}=this;if((0,l.eachItem)(G,L=>{if(B.keywords[L])throw Error(`Keyword ${L} is already defined`);if(!A.test(L))throw Error(`Keyword ${L} has invalid name`)}),!!$&&$.$data&&!("code"in $||"validate"in $))throw Error('$data keyword must have "code" or "validate" function')}function se(G,$,B){var L;let x=$?.post;if(B&&x)throw Error('keyword with "post" flag cannot have "type"');let{RULES:E}=this,O=x?E.post:E.rules.find(({type:X})=>X===B);if(O||(O={type:B,rules:[]},E.rules.push(O)),E.keywords[G]=!0,!$)return;let ne={keyword:G,definition:{...$,type:(0,u.getJSONTypes)($.type),schemaType:(0,u.getJSONTypes)($.schemaType)}};$.before?he.call(this,O,ne,$.before):O.rules.push(ne),E.all[G]=ne,(L=$.implements)===null||L===void 0||L.forEach(X=>this.addKeyword(X))}function he(G,$,B){let L=G.rules.findIndex(x=>x.keyword===B);L>=0?G.rules.splice(L,0,$):(G.rules.push($),this.logger.warn(`rule ${B} is not defined`))}function ee(G){let{metaSchema:$}=G;$!==void 0&&(G.$data&&this.opts.$data&&($=be($)),G.validateSchema=this.compile($,!0))}var $e={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function be(G){return{anyOf:[G,$e]}}}),m1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};e.default=t}),h1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;var t=sl(),n=En(),i=Te(),r=Cr(),o=pm(),a=Ae(),s={keyword:"$ref",schemaType:"string",code(l){let{gen:p,schema:m,it:f}=l,{baseId:h,schemaEnv:y,validateName:w,opts:g,self:v}=f,{root:b}=y;if((m==="#"||m==="#/")&&h===b.baseId)return T();let S=o.resolveRef.call(v,b,h,m);if(S===void 0)throw new t.default(f.opts.uriResolver,h,m);if(S instanceof o.SchemaEnv)return C(S);return _(S);function T(){if(y===b)return u(l,w,y,y.$async);let k=p.scopeValue("root",{ref:b});return u(l,i._`${k}.validate`,b,b.$async)}function C(k){let I=d(l,k);u(l,I,k,k.$async)}function _(k){let I=p.scopeValue("schema",g.code.source===!0?{ref:k,code:(0,i.stringify)(k)}:{ref:k}),P=p.name("valid"),R=l.subschema({schema:k,dataTypes:[],schemaPath:i.nil,topSchemaRef:I,errSchemaPath:m},P);l.mergeEvaluated(R),l.ok(P)}}};function d(l,p){let{gen:m}=l;return p.validate?m.scopeValue("validate",{ref:p.validate}):i._`${m.scopeValue("wrapper",{ref:p})}.validate`}e.getValidate=d;function u(l,p,m,f){let{gen:h,it:y}=l,{allErrors:w,schemaEnv:g,opts:v}=y,b=v.passContext?r.default.this:i.nil;f?S():T();function S(){if(!g.$async)throw Error("async schema referenced by sync schema");let k=h.let("valid");h.try(()=>{h.code(i._`await ${(0,n.callValidateCode)(l,p,b)}`),_(p),!w&&h.assign(k,!0)},I=>{h.if(i._`!(${I} instanceof ${y.ValidationError})`,()=>h.throw(I)),C(I),!w&&h.assign(k,!1)}),l.ok(k)}function T(){l.result((0,n.callValidateCode)(l,p,b),()=>_(p),()=>C(p))}function C(k){let I=i._`${k}.errors`;h.assign(r.default.vErrors,i._`${r.default.vErrors} === null ? ${I} : ${r.default.vErrors}.concat(${I})`),h.assign(r.default.errors,i._`${r.default.vErrors}.length`)}function _(k){var I;if(!y.opts.unevaluated)return;let P=(I=m?.validate)===null||I===void 0?void 0:I.evaluated;if(y.props!==!0)if(P&&!P.dynamicProps)P.props!==void 0&&(y.props=a.mergeEvaluated.props(h,P.props,y.props));else{let R=h.var("props",i._`${k}.evaluated.props`);y.props=a.mergeEvaluated.props(h,R,y.props,i.Name)}if(y.items!==!0)if(P&&!P.dynamicItems)P.items!==void 0&&(y.items=a.mergeEvaluated.items(h,P.items,y.items));else{let R=h.var("items",i._`${k}.evaluated.items`);y.items=a.mergeEvaluated.items(h,R,y.items,i.Name)}}}e.callRef=u,e.default=s}),g1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=m1(),n=h1(),i=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,n.default];e.default=i}),y1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=t.operators,i={maximum:{okStr:"<=",ok:n.LTE,fail:n.GT},minimum:{okStr:">=",ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},r={message:({keyword:a,schemaCode:s})=>t.str`must be ${i[a].okStr} ${s}`,params:({keyword:a,schemaCode:s})=>t._`{comparison: ${i[a].okStr}, limit: ${s}}`},o={keyword:Object.keys(i),type:"number",schemaType:"number",$data:!0,error:r,code(a){let{keyword:s,data:d,schemaCode:u}=a;a.fail$data(t._`${d} ${i[s].fail} ${u} || isNaN(${d})`)}};e.default=o}),_1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n={message:({schemaCode:r})=>t.str`must be multiple of ${r}`,params:({schemaCode:r})=>t._`{multipleOf: ${r}}`},i={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:n,code(r){let{gen:o,data:a,schemaCode:s,it:d}=r,u=d.opts.multipleOfPrecision,l=o.let("res"),p=u?t._`Math.abs(Math.round(${l}) - ${l}) > 1e-${u}`:t._`${l} !== parseInt(${l})`;r.fail$data(t._`(${s} === 0 || (${l} = ${a}/${s}, ${p}))`)}};e.default=i}),v1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(n){let i=n.length,r=0,o=0,a;for(;o<i;)r++,a=n.charCodeAt(o++),a>=55296&&a<=56319&&o<i&&(a=n.charCodeAt(o),(a&64512)===56320&&o++);return r}e.default=t,t.code='require("ajv/dist/runtime/ucs2length").default'}),b1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=Ae(),i=v1(),r={message({keyword:a,schemaCode:s}){let d=a==="maxLength"?"more":"fewer";return t.str`must NOT have ${d} than ${s} characters`},params:({schemaCode:a})=>t._`{limit: ${a}}`},o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:r,code(a){let{keyword:s,data:d,schemaCode:u,it:l}=a,p=s==="maxLength"?t.operators.GT:t.operators.LT,m=l.opts.unicode===!1?t._`${d}.length`:t._`${(0,n.useFunc)(a.gen,i.default)}(${d})`;a.fail$data(t._`${m} ${p} ${u}`)}};e.default=o}),w1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=En(),n=Ae(),i=Te(),r={message:({schemaCode:a})=>i.str`must match pattern "${a}"`,params:({schemaCode:a})=>i._`{pattern: ${a}}`},o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:r,code(a){let{gen:s,data:d,$data:u,schema:l,schemaCode:p,it:m}=a,f=m.opts.unicodeRegExp?"u":"";if(u){let{regExp:h}=m.opts.code,y=h.code==="new RegExp"?i._`new RegExp`:(0,n.useFunc)(s,h),w=s.let("valid");s.try(()=>s.assign(w,i._`${y}(${p}, ${f}).test(${d})`),()=>s.assign(w,!1)),a.fail$data(i._`!${w}`)}else{let h=(0,t.usePattern)(a,l);a.fail$data(i._`!${h}.test(${d})`)}}};e.default=o}),S1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n={message({keyword:r,schemaCode:o}){let a=r==="maxProperties"?"more":"fewer";return t.str`must NOT have ${a} than ${o} properties`},params:({schemaCode:r})=>t._`{limit: ${r}}`},i={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:n,code(r){let{keyword:o,data:a,schemaCode:s}=r,d=o==="maxProperties"?t.operators.GT:t.operators.LT;r.fail$data(t._`Object.keys(${a}).length ${d} ${s}`)}};e.default=i}),k1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=En(),n=Te(),i=Ae(),r={message:({params:{missingProperty:a}})=>n.str`must have required property '${a}'`,params:({params:{missingProperty:a}})=>n._`{missingProperty: ${a}}`},o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:r,code(a){let{gen:s,schema:d,schemaCode:u,data:l,$data:p,it:m}=a,{opts:f}=m;if(!p&&d.length===0)return;let h=d.length>=f.loopRequired;if(m.allErrors?y():w(),f.strictRequired){let b=a.parentSchema.properties,{definedProperties:S}=a.it;for(let T of d)if(b?.[T]===void 0&&!S.has(T)){let C=m.schemaEnv.baseId+m.errSchemaPath,_=`required property "${T}" is not defined at "${C}" (strictRequired)`;(0,i.checkStrictMode)(m,_,m.opts.strictRequired)}}function y(){if(h||p)a.block$data(n.nil,g);else for(let b of d)(0,t.checkReportMissingProp)(a,b)}function w(){let b=s.let("missing");if(h||p){let S=s.let("valid",!0);a.block$data(S,()=>v(b,S)),a.ok(S)}else s.if((0,t.checkMissingProp)(a,d,b)),(0,t.reportMissingProp)(a,b),s.else()}function g(){s.forOf("prop",u,b=>{a.setParams({missingProperty:b}),s.if((0,t.noPropertyInData)(s,l,b,f.ownProperties),()=>a.error())})}function v(b,S){a.setParams({missingProperty:b}),s.forOf(b,u,()=>{s.assign(S,(0,t.propertyInData)(s,l,b,f.ownProperties)),s.if((0,n.not)(S),()=>{a.error(),s.break()})},n.nil)}}};e.default=o}),x1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n={message({keyword:r,schemaCode:o}){let a=r==="maxItems"?"more":"fewer";return t.str`must NOT have ${a} than ${o} items`},params:({schemaCode:r})=>t._`{limit: ${r}}`},i={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:n,code(r){let{keyword:o,data:a,schemaCode:s}=r,d=o==="maxItems"?t.operators.GT:t.operators.LT;r.fail$data(t._`${a}.length ${d} ${s}`)}};e.default=i}),fm=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=FS();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),C1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=jd(),n=Te(),i=Ae(),r=fm(),o={message:({params:{i:s,j:d}})=>n.str`must NOT have duplicate items (items ## ${d} and ${s} are identical)`,params:({params:{i:s,j:d}})=>n._`{i: ${s}, j: ${d}}`},a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:o,code(s){let{gen:d,data:u,$data:l,schema:p,parentSchema:m,schemaCode:f,it:h}=s;if(!l&&!p)return;let y=d.let("valid"),w=m.items?(0,t.getSchemaTypes)(m.items):[];s.block$data(y,g,n._`${f} === false`),s.ok(y);function g(){let T=d.let("i",n._`${u}.length`),C=d.let("j");s.setParams({i:T,j:C}),d.assign(y,!0),d.if(n._`${T} > 1`,()=>(v()?b:S)(T,C))}function v(){return w.length>0&&!w.some(T=>T==="object"||T==="array")}function b(T,C){let _=d.name("item"),k=(0,t.checkDataTypes)(w,_,h.opts.strictNumbers,t.DataType.Wrong),I=d.const("indices",n._`{}`);d.for(n._`;${T}--;`,()=>{d.let(_,n._`${u}[${T}]`),d.if(k,n._`continue`),w.length>1&&d.if(n._`typeof ${_} == "string"`,n._`${_} += "_"`),d.if(n._`typeof ${I}[${_}] == "number"`,()=>{d.assign(C,n._`${I}[${_}]`),s.error(),d.assign(y,!1).break()}).code(n._`${I}[${_}] = ${T}`)})}function S(T,C){let _=(0,i.useFunc)(d,r.default),k=d.name("outer");d.label(k).for(n._`;${T}--;`,()=>d.for(n._`${C} = ${T}; ${C}--;`,()=>d.if(n._`${_}(${u}[${T}], ${u}[${C}])`,()=>{s.error(),d.assign(y,!1).break(k)})))}}};e.default=a}),T1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=Ae(),i=fm(),r={message:"must be equal to constant",params:({schemaCode:a})=>t._`{allowedValue: ${a}}`},o={keyword:"const",$data:!0,error:r,code(a){let{gen:s,data:d,$data:u,schemaCode:l,schema:p}=a;u||p&&typeof p=="object"?a.fail$data(t._`!${(0,n.useFunc)(s,i.default)}(${d}, ${l})`):a.fail(t._`${p} !== ${d}`)}};e.default=o}),I1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=Ae(),i=fm(),r={message:"must be equal to one of the allowed values",params:({schemaCode:a})=>t._`{allowedValues: ${a}}`},o={keyword:"enum",schemaType:"array",$data:!0,error:r,code(a){let{gen:s,data:d,$data:u,schema:l,schemaCode:p,it:m}=a;if(!u&&l.length===0)throw Error("enum must have non-empty array");let f=l.length>=m.opts.loopEnum,h,y=()=>h??(h=(0,n.useFunc)(s,i.default)),w;if(f||u)w=s.let("valid"),a.block$data(w,g);else{if(!Array.isArray(l))throw Error("ajv implementation error");let b=s.const("vSchema",p);w=(0,t.or)(...l.map((S,T)=>v(b,T)))}a.pass(w);function g(){s.assign(w,!1),s.forOf("v",p,b=>s.if(t._`${y()}(${d}, ${b})`,()=>s.assign(w,!0).break()))}function v(b,S){let T=l[S];return typeof T=="object"&&T!==null?t._`${y()}(${d}, ${b}[${S}])`:t._`${d} === ${T}`}}};e.default=o}),P1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=y1(),n=_1(),i=b1(),r=w1(),o=S1(),a=k1(),s=x1(),d=C1(),u=T1(),l=I1(),p=[t.default,n.default,i.default,r.default,o.default,a.default,s.default,d.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,l.default];e.default=p}),BS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;var t=Te(),n=Ae(),i={message:({params:{len:a}})=>t.str`must NOT have more than ${a} items`,params:({params:{len:a}})=>t._`{limit: ${a}}`},r={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:i,code(a){let{parentSchema:s,it:d}=a,{items:u}=s;if(!Array.isArray(u)){(0,n.checkStrictMode)(d,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(a,u)}};function o(a,s){let{gen:d,schema:u,data:l,keyword:p,it:m}=a;m.items=!0;let f=d.const("len",t._`${l}.length`);if(u===!1)a.setParams({len:s.length}),a.pass(t._`${f} <= ${s.length}`);else if(typeof u=="object"&&!(0,n.alwaysValidSchema)(m,u)){let y=d.var("valid",t._`${f} <= ${s.length}`);d.if((0,t.not)(y),()=>h(y)),a.ok(y)}function h(y){d.forRange("i",s.length,f,w=>{a.subschema({keyword:p,dataProp:w,dataPropType:n.Type.Num},y),!m.allErrors&&d.if((0,t.not)(y),()=>d.break())})}}e.validateAdditionalItems=o,e.default=r}),KS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;var t=Te(),n=Ae(),i=En(),r={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(a){let{schema:s,it:d}=a;if(Array.isArray(s))return o(a,"additionalItems",s);d.items=!0,!(0,n.alwaysValidSchema)(d,s)&&a.ok((0,i.validateArray)(a))}};function o(a,s,d=a.schema){let{gen:u,parentSchema:l,data:p,keyword:m,it:f}=a;w(l),f.opts.unevaluated&&d.length&&f.items!==!0&&(f.items=n.mergeEvaluated.items(u,d.length,f.items));let h=u.name("valid"),y=u.const("len",t._`${p}.length`);d.forEach((g,v)=>{(0,n.alwaysValidSchema)(f,g)||(u.if(t._`${y} > ${v}`,()=>a.subschema({keyword:m,schemaProp:v,dataProp:v},h)),a.ok(h))});function w(g){let{opts:v,errSchemaPath:b}=f,S=d.length,T=S===g.minItems&&(S===g.maxItems||g[s]===!1);if(v.strictTuples&&!T){let C=`"${m}" is ${S}-tuple, but minItems or maxItems/${s} are not specified or different at path "${b}"`;(0,n.checkStrictMode)(f,C,v.strictTuples)}}}e.validateTuple=o,e.default=r}),E1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=KS(),n={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:i=>(0,t.validateTuple)(i,"items")};e.default=n}),R1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=Ae(),i=En(),r=BS(),o={message:({params:{len:s}})=>t.str`must NOT have more than ${s} items`,params:({params:{len:s}})=>t._`{limit: ${s}}`},a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:o,code(s){let{schema:d,parentSchema:u,it:l}=s,{prefixItems:p}=u;l.items=!0,!(0,n.alwaysValidSchema)(l,d)&&(p?(0,r.validateAdditionalItems)(s,p):s.ok((0,i.validateArray)(s)))}};e.default=a}),O1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=Ae(),i={message:({params:{min:o,max:a}})=>a===void 0?t.str`must contain at least ${o} valid item(s)`:t.str`must contain at least ${o} and no more than ${a} valid item(s)`,params:({params:{min:o,max:a}})=>a===void 0?t._`{minContains: ${o}}`:t._`{minContains: ${o}, maxContains: ${a}}`},r={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:i,code(o){let{gen:a,schema:s,parentSchema:d,data:u,it:l}=o,p,m,{minContains:f,maxContains:h}=d;l.opts.next?(p=f===void 0?1:f,m=h):p=1;let y=a.const("len",t._`${u}.length`);if(o.setParams({min:p,max:m}),m===void 0&&p===0){(0,n.checkStrictMode)(l,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(m!==void 0&&p>m){(0,n.checkStrictMode)(l,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,n.alwaysValidSchema)(l,s)){let S=t._`${y} >= ${p}`;m!==void 0&&(S=t._`${S} && ${y} <= ${m}`),o.pass(S);return}l.items=!0;let w=a.name("valid");m===void 0&&p===1?v(w,()=>a.if(w,()=>a.break())):p===0?(a.let(w,!0),m!==void 0&&a.if(t._`${u}.length > 0`,g)):(a.let(w,!1),g()),o.result(w,()=>o.reset());function g(){let S=a.name("_valid"),T=a.let("count",0);v(S,()=>a.if(S,()=>b(T)))}function v(S,T){a.forRange("i",0,y,C=>{o.subschema({keyword:"contains",dataProp:C,dataPropType:n.Type.Num,compositeRule:!0},S),T()})}function b(S){a.code(t._`${S}++`),m===void 0?a.if(t._`${S} >= ${p}`,()=>a.assign(w,!0).break()):(a.if(t._`${S} > ${m}`,()=>a.assign(w,!1).break()),p===1?a.assign(w,!0):a.if(t._`${S} >= ${p}`,()=>a.assign(w,!0)))}}};e.default=r}),A1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;var t=Te(),n=Ae(),i=En();e.error={message:({params:{property:d,depsCount:u,deps:l}})=>{let p=u===1?"property":"properties";return t.str`must have ${p} ${l} when property ${d} is present`},params:({params:{property:d,depsCount:u,deps:l,missingProperty:p}})=>t._`{property: ${d},
41
+ missingProperty: ${p},
42
+ depsCount: ${u},
43
+ deps: ${l}}`};var r={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(d){let[u,l]=o(d);a(d,u),s(d,l)}};function o({schema:d}){let u={},l={};for(let p in d){if(p==="__proto__")continue;let m=Array.isArray(d[p])?u:l;m[p]=d[p]}return[u,l]}function a(d,u=d.schema){let{gen:l,data:p,it:m}=d;if(Object.keys(u).length===0)return;let f=l.let("missing");for(let h in u){let y=u[h];if(y.length===0)continue;let w=(0,i.propertyInData)(l,p,h,m.opts.ownProperties);d.setParams({property:h,depsCount:y.length,deps:y.join(", ")}),m.allErrors?l.if(w,()=>{for(let g of y)(0,i.checkReportMissingProp)(d,g)}):(l.if(t._`${w} && (${(0,i.checkMissingProp)(d,y,f)})`),(0,i.reportMissingProp)(d,f),l.else())}}e.validatePropertyDeps=a;function s(d,u=d.schema){let{gen:l,data:p,keyword:m,it:f}=d,h=l.name("valid");for(let y in u)(0,n.alwaysValidSchema)(f,u[y])||(l.if((0,i.propertyInData)(l,p,y,f.opts.ownProperties),()=>{let w=d.subschema({keyword:m,schemaProp:y},h);d.mergeValidEvaluated(w,h)},()=>l.var(h,!0)),d.ok(h))}e.validateSchemaDeps=s,e.default=r}),$1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=Ae(),i={message:"property name must be valid",params:({params:o})=>t._`{propertyName: ${o.propertyName}}`},r={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:i,code(o){let{gen:a,schema:s,data:d,it:u}=o;if((0,n.alwaysValidSchema)(u,s))return;let l=a.name("valid");a.forIn("key",d,p=>{o.setParams({propertyName:p}),o.subschema({keyword:"propertyNames",data:p,dataTypes:["string"],propertyName:p,compositeRule:!0},l),a.if((0,t.not)(l),()=>{o.error(!0),!u.allErrors&&a.break()})}),o.ok(l)}};e.default=r}),JS=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=En(),n=Te(),i=Cr(),r=Ae(),o={message:"must NOT have additional properties",params:({params:s})=>n._`{additionalProperty: ${s.additionalProperty}}`},a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:o,code(s){let{gen:d,schema:u,parentSchema:l,data:p,errsCount:m,it:f}=s;if(!m)throw Error("ajv implementation error");let{allErrors:h,opts:y}=f;if(f.props=!0,y.removeAdditional!=="all"&&(0,r.alwaysValidSchema)(f,u))return;let w=(0,t.allSchemaProperties)(l.properties),g=(0,t.allSchemaProperties)(l.patternProperties);v(),s.ok(n._`${m} === ${i.default.errors}`);function v(){d.forIn("key",p,_=>{!w.length&&!g.length?T(_):d.if(b(_),()=>T(_))})}function b(_){let k;if(w.length>8){let I=(0,r.schemaRefOrVal)(f,l.properties,"properties");k=(0,t.isOwnProperty)(d,I,_)}else w.length?k=(0,n.or)(...w.map(I=>n._`${_} === ${I}`)):k=n.nil;return g.length&&(k=(0,n.or)(k,...g.map(I=>n._`${(0,t.usePattern)(s,I)}.test(${_})`))),(0,n.not)(k)}function S(_){d.code(n._`delete ${p}[${_}]`)}function T(_){if(y.removeAdditional==="all"||y.removeAdditional&&u===!1){S(_);return}if(u===!1){s.setParams({additionalProperty:_}),s.error(),!h&&d.break();return}if(typeof u=="object"&&!(0,r.alwaysValidSchema)(f,u)){let k=d.name("valid");y.removeAdditional==="failing"?(C(_,k,!1),d.if((0,n.not)(k),()=>{s.reset(),S(_)})):(C(_,k),!h&&d.if((0,n.not)(k),()=>d.break()))}}function C(_,k,I){let P={keyword:"additionalProperties",dataProp:_,dataPropType:r.Type.Str};I===!1&&Object.assign(P,{compositeRule:!0,createErrors:!1,allErrors:!1}),s.subschema(P,k)}}};e.default=a}),M1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=al(),n=En(),i=Ae(),r=JS(),o={keyword:"properties",type:"object",schemaType:"object",code(a){let{gen:s,schema:d,parentSchema:u,data:l,it:p}=a;p.opts.removeAdditional==="all"&&u.additionalProperties===void 0&&r.default.code(new t.KeywordCxt(p,r.default,"additionalProperties"));let m=(0,n.allSchemaProperties)(d);for(let g of m)p.definedProperties.add(g);p.opts.unevaluated&&m.length&&p.props!==!0&&(p.props=i.mergeEvaluated.props(s,(0,i.toHash)(m),p.props));let f=m.filter(g=>!(0,i.alwaysValidSchema)(p,d[g]));if(f.length===0)return;let h=s.name("valid");for(let g of f)y(g)?w(g):(s.if((0,n.propertyInData)(s,l,g,p.opts.ownProperties)),w(g),!p.allErrors&&s.else().var(h,!0),s.endIf()),a.it.definedProperties.add(g),a.ok(h);function y(g){return p.opts.useDefaults&&!p.compositeRule&&d[g].default!==void 0}function w(g){a.subschema({keyword:"properties",schemaProp:g,dataProp:g},h)}}};e.default=o}),j1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=En(),n=Te(),i=Ae(),r=Ae(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(a){let{gen:s,schema:d,data:u,parentSchema:l,it:p}=a,{opts:m}=p,f=(0,t.allSchemaProperties)(d),h=f.filter(T=>(0,i.alwaysValidSchema)(p,d[T]));if(f.length===0||h.length===f.length&&(!p.opts.unevaluated||p.props===!0))return;let y=m.strictSchema&&!m.allowMatchingProperties&&l.properties,w=s.name("valid");p.props!==!0&&!(p.props instanceof n.Name)&&(p.props=(0,r.evaluatedPropsToName)(s,p.props));let{props:g}=p;v();function v(){for(let T of f)y&&b(T),p.allErrors?S(T):(s.var(w,!0),S(T),s.if(w))}function b(T){for(let C in y)new RegExp(T).test(C)&&(0,i.checkStrictMode)(p,`property ${C} matches pattern ${T} (use allowMatchingProperties)`)}function S(T){s.forIn("key",u,C=>{s.if(n._`${(0,t.usePattern)(a,T)}.test(${C})`,()=>{let _=h.includes(T);_||a.subschema({keyword:"patternProperties",schemaProp:T,dataProp:C,dataPropType:r.Type.Str},w),p.opts.unevaluated&&g!==!0?s.assign(n._`${g}[${C}]`,!0):!_&&!p.allErrors&&s.if((0,n.not)(w),()=>s.break())})})}}};e.default=o}),q1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Ae(),n={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(i){let{gen:r,schema:o,it:a}=i;if((0,t.alwaysValidSchema)(a,o)){i.fail();return}let s=r.name("valid");i.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),i.failResult(s,()=>i.reset(),()=>i.error())},error:{message:"must NOT be valid"}};e.default=n}),N1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=En(),n={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:t.validateUnion,error:{message:"must match a schema in anyOf"}};e.default=n}),D1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=Ae(),i={message:"must match exactly one schema in oneOf",params:({params:o})=>t._`{passingSchemas: ${o.passing}}`},r={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:i,code(o){let{gen:a,schema:s,parentSchema:d,it:u}=o;if(!Array.isArray(s))throw Error("ajv implementation error");if(u.opts.discriminator&&d.discriminator)return;let l=s,p=a.let("valid",!1),m=a.let("passing",null),f=a.name("_valid");o.setParams({passing:m}),a.block(h),o.result(p,()=>o.reset(),()=>o.error(!0));function h(){l.forEach((y,w)=>{let g;(0,n.alwaysValidSchema)(u,y)?a.var(f,!0):g=o.subschema({keyword:"oneOf",schemaProp:w,compositeRule:!0},f),w>0&&a.if(t._`${f} && ${p}`).assign(p,!1).assign(m,t._`[${m}, ${w}]`).else(),a.if(f,()=>{a.assign(p,!0),a.assign(m,w),g&&o.mergeEvaluated(g,t.Name)})})}}};e.default=r}),L1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Ae(),n={keyword:"allOf",schemaType:"array",code(i){let{gen:r,schema:o,it:a}=i;if(!Array.isArray(o))throw Error("ajv implementation error");let s=r.name("valid");o.forEach((d,u)=>{if((0,t.alwaysValidSchema)(a,d))return;let l=i.subschema({keyword:"allOf",schemaProp:u},s);i.ok(s),i.mergeEvaluated(l)})}};e.default=n}),U1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=Ae(),i={message:({params:a})=>t.str`must match "${a.ifClause}" schema`,params:({params:a})=>t._`{failingKeyword: ${a.ifClause}}`},r={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:i,code(a){let{gen:s,parentSchema:d,it:u}=a;d.then===void 0&&d.else===void 0&&(0,n.checkStrictMode)(u,'"if" without "then" and "else" is ignored');let l=o(u,"then"),p=o(u,"else");if(!l&&!p)return;let m=s.let("valid",!0),f=s.name("_valid");if(h(),a.reset(),l&&p){let w=s.let("ifClause");a.setParams({ifClause:w}),s.if(f,y("then",w),y("else",w))}else l?s.if(f,y("then")):s.if((0,t.not)(f),y("else"));a.pass(m,()=>a.error(!0));function h(){let w=a.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);a.mergeEvaluated(w)}function y(w,g){return()=>{let v=a.subschema({keyword:w},f);s.assign(m,f),a.mergeValidEvaluated(v,m),g?s.assign(g,t._`${w}`):a.setParams({ifClause:w})}}}};function o(a,s){let d=a.schema[s];return d!==void 0&&!(0,n.alwaysValidSchema)(a,d)}e.default=r}),F1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Ae(),n={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:i,parentSchema:r,it:o}){r.if===void 0&&(0,t.checkStrictMode)(o,`"${i}" without "if" is ignored`)}};e.default=n}),z1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=BS(),n=E1(),i=KS(),r=R1(),o=O1(),a=A1(),s=$1(),d=JS(),u=M1(),l=j1(),p=q1(),m=N1(),f=D1(),h=L1(),y=U1(),w=F1();function g(v=!1){let b=[p.default,m.default,f.default,h.default,y.default,w.default,s.default,d.default,a.default,u.default,l.default];return v?b.push(n.default,r.default):b.push(t.default,i.default),b.push(o.default),b}e.default=g}),B1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n={message:({schemaCode:r})=>t.str`must match format "${r}"`,params:({schemaCode:r})=>t._`{format: ${r}}`},i={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:n,code(r,o){let{gen:a,data:s,$data:d,schema:u,schemaCode:l,it:p}=r,{opts:m,errSchemaPath:f,schemaEnv:h,self:y}=p;if(!m.validateFormats)return;d?w():g();function w(){let v=a.scopeValue("formats",{ref:y.formats,code:m.code.formats}),b=a.const("fDef",t._`${v}[${l}]`),S=a.let("fType"),T=a.let("format");a.if(t._`typeof ${b} == "object" && !(${b} instanceof RegExp)`,()=>a.assign(S,t._`${b}.type || "string"`).assign(T,t._`${b}.validate`),()=>a.assign(S,t._`"string"`).assign(T,b)),r.fail$data((0,t.or)(C(),_()));function C(){return m.strictSchema===!1?t.nil:t._`${l} && !${T}`}function _(){let k=h.$async?t._`(${b}.async ? await ${T}(${s}) : ${T}(${s}))`:t._`${T}(${s})`,I=t._`(typeof ${T} == "function" ? ${k} : ${T}.test(${s}))`;return t._`${T} && ${T} !== true && ${S} === ${o} && !${I}`}}function g(){let v=y.formats[u];if(!v){C();return}if(v===!0)return;let[b,S,T]=_(v);b===o&&r.pass(k());function C(){if(m.strictSchema===!1){y.logger.warn(I());return}throw Error(I());function I(){return`unknown format "${u}" ignored in schema at path "${f}"`}}function _(I){let P=I instanceof RegExp?(0,t.regexpCode)(I):m.code.formats?t._`${m.code.formats}${(0,t.getProperty)(u)}`:void 0,R=a.scopeValue("formats",{key:u,ref:I,code:P});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,t._`${R}.validate`]:["string",I,R]}function k(){if(typeof v=="object"&&!(v instanceof RegExp)&&v.async){if(!h.$async)throw Error("async format in sync schema");return t._`await ${T}(${s})`}return typeof S=="function"?t._`${T}(${s})`:t._`${T}.test(${s})`}}}};e.default=i}),K1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=B1(),n=[t.default];e.default=n}),J1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],e.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),W1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=g1(),n=P1(),i=z1(),r=K1(),o=J1(),a=[t.default,n.default,(0,i.default)(),r.default,o.metadataVocabulary,o.contentVocabulary];e.default=a}),H1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(n){n.Tag="tag",n.Mapping="mapping"})(t||(e.DiscrError=t={}))}),G1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Te(),n=H1(),i=pm(),r=sl(),o=Ae(),a={message:({params:{discrError:d,tagName:u}})=>d===n.DiscrError.Tag?`tag "${u}" must be string`:`value of tag "${u}" must be in oneOf`,params:({params:{discrError:d,tag:u,tagName:l}})=>t._`{error: ${d}, tag: ${l}, tagValue: ${u}}`},s={keyword:"discriminator",type:"object",schemaType:"object",error:a,code(d){let{gen:u,data:l,schema:p,parentSchema:m,it:f}=d,{oneOf:h}=m;if(!f.opts.discriminator)throw Error("discriminator: requires discriminator option");let y=p.propertyName;if(typeof y!="string")throw Error("discriminator: requires propertyName");if(p.mapping)throw Error("discriminator: mapping is not supported");if(!h)throw Error("discriminator: requires oneOf keyword");let w=u.let("valid",!1),g=u.const("tag",t._`${l}${(0,t.getProperty)(y)}`);u.if(t._`typeof ${g} == "string"`,()=>v(),()=>d.error(!1,{discrError:n.DiscrError.Tag,tag:g,tagName:y})),d.ok(w);function v(){let T=S();u.if(!1);for(let C in T)u.elseIf(t._`${g} === ${C}`),u.assign(w,b(T[C]));u.else(),d.error(!1,{discrError:n.DiscrError.Mapping,tag:g,tagName:y}),u.endIf()}function b(T){let C=u.name("valid"),_=d.subschema({keyword:"oneOf",schemaProp:T},C);return d.mergeEvaluated(_,t.Name),C}function S(){var T;let C={},_=I(m),k=!0;for(let M=0;M<h.length;M++){let A=h[M];if(A?.$ref&&!(0,o.schemaHasRulesButRef)(A,f.self.RULES)){let se=A.$ref;if(A=i.resolveRef.call(f.self,f.schemaEnv.root,f.baseId,se),A instanceof i.SchemaEnv&&(A=A.schema),A===void 0)throw new r.default(f.opts.uriResolver,f.baseId,se)}let F=(T=A?.properties)===null||T===void 0?void 0:T[y];if(typeof F!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${y}"`);k=k&&(_||I(A)),P(F,M)}if(!k)throw Error(`discriminator: "${y}" must be required`);return C;function I({required:M}){return Array.isArray(M)&&M.includes(y)}function P(M,A){if(M.const)R(M.const,A);else if(M.enum)for(let F of M.enum)R(F,A);else throw Error(`discriminator: "properties/${y}" must have "const" or "enum"`)}function R(M,A){if(typeof M!="string"||M in C)throw Error(`discriminator: "${y}" values must be unique strings`);C[M]=A}}}};e.default=s}),V1=z((e,t)=>{t.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),WS=z((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;var n=f1(),i=W1(),r=G1(),o=V1(),a=["/properties"],s="http://json-schema.org/draft-07/schema";class d extends n.default{_addVocabularies(){super._addVocabularies(),i.default.forEach(h=>this.addVocabulary(h)),this.opts.discriminator&&this.addKeyword(r.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let h=this.opts.$data?this.$dataMetaSchema(o,a):o;this.addMetaSchema(h,s,!1),this.refs["http://json-schema.org/schema"]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}}e.Ajv=d,t.exports=e=d,t.exports.Ajv=d,Object.defineProperty(e,"__esModule",{value:!0}),e.default=d;var u=al();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Te();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var p=cm();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return p.default}});var m=sl();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return m.default}})}),Z1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(R,M){return{validate:R,compare:M}}e.fullFormats={date:t(o,a),time:t(d(!0),u),"date-time":t(m(!0),f),"iso-time":t(d(),l),"iso-date-time":t(m(),h),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:g,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:P,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:b,int32:{type:"number",validate:C},int64:{type:"number",validate:_},float:{type:"number",validate:k},double:{type:"number",validate:k},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,h),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(R){return R%4===0&&(R%100!==0||R%400===0)}var i=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,r=[0,31,28,31,30,31,30,31,31,30,31,30,31];function o(R){let M=i.exec(R);if(!M)return!1;let A=+M[1],F=+M[2],se=+M[3];return F>=1&&F<=12&&se>=1&&se<=(F===2&&n(A)?29:r[F])}function a(R,M){if(R&&M)return R>M?1:R<M?-1:0}var s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function d(R){return function(M){let A=s.exec(M);if(!A)return!1;let F=+A[1],se=+A[2],he=+A[3],ee=A[4],$e=A[5]==="-"?-1:1,be=+(A[6]||0),G=+(A[7]||0);if(be>23||G>59||R&&!ee)return!1;if(F<=23&&se<=59&&he<60)return!0;let $=se-G*$e,B=F-be*$e-($<0?1:0);return(B===23||B===-1)&&($===59||$===-1)&&he<61}}function u(R,M){if(!(R&&M))return;let A=new Date("2020-01-01T"+R).valueOf(),F=new Date("2020-01-01T"+M).valueOf();if(A&&F)return A-F}function l(R,M){if(!(R&&M))return;let A=s.exec(R),F=s.exec(M);if(A&&F)return R=A[1]+A[2]+A[3],M=F[1]+F[2]+F[3],R>M?1:R<M?-1:0}var p=/t|\s/i;function m(R){let M=d(R);return function(A){let F=A.split(p);return F.length===2&&o(F[0])&&M(F[1])}}function f(R,M){if(!(R&&M))return;let A=new Date(R).valueOf(),F=new Date(M).valueOf();if(A&&F)return A-F}function h(R,M){if(!(R&&M))return;let[A,F]=R.split(p),[se,he]=M.split(p),ee=a(A,se);if(ee!==void 0)return ee||u(F,he)}var y=/\/|:/,w=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function g(R){return y.test(R)&&w.test(R)}var v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function b(R){return v.lastIndex=0,v.test(R)}var S=-2147483648,T=2147483647;function C(R){return Number.isInteger(R)&&R<=T&&R>=S}function _(R){return Number.isInteger(R)}function k(){return!0}var I=/[^\\]\\Z/;function P(R){if(I.test(R))return!1;try{return new RegExp(R),!0}catch{return!1}}}),Q1=z(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=WS(),n=Te(),i=n.operators,r={formatMaximum:{okStr:"<=",ok:i.LTE,fail:i.GT},formatMinimum:{okStr:">=",ok:i.GTE,fail:i.LT},formatExclusiveMaximum:{okStr:"<",ok:i.LT,fail:i.GTE},formatExclusiveMinimum:{okStr:">",ok:i.GT,fail:i.LTE}},o={message:({keyword:s,schemaCode:d})=>n.str`should be ${r[s].okStr} ${d}`,params:({keyword:s,schemaCode:d})=>n._`{comparison: ${r[s].okStr}, limit: ${d}}`};e.formatLimitDefinition={keyword:Object.keys(r),type:"string",schemaType:"string",$data:!0,error:o,code(s){let{gen:d,data:u,schemaCode:l,keyword:p,it:m}=s,{opts:f,self:h}=m;if(!f.validateFormats)return;let y=new t.KeywordCxt(m,h.RULES.all.format.definition,"format");y.$data?w():g();function w(){let b=d.scopeValue("formats",{ref:h.formats,code:f.code.formats}),S=d.const("fmt",n._`${b}[${y.schemaCode}]`);s.fail$data((0,n.or)(n._`typeof ${S} != "object"`,n._`${S} instanceof RegExp`,n._`typeof ${S}.compare != "function"`,v(S)))}function g(){let b=y.schema,S=h.formats[b];if(!S||S===!0)return;if(typeof S!="object"||S instanceof RegExp||typeof S.compare!="function")throw Error(`"${p}": format "${b}" does not define "compare" function`);let T=d.scopeValue("formats",{key:b,ref:S,code:f.code.formats?n._`${f.code.formats}${(0,n.getProperty)(b)}`:void 0});s.fail$data(v(T))}function v(b){return n._`${b}.compare(${u}, ${l}) ${r[p].fail} 0`}},dependencies:["format"]};var a=s=>(s.addKeyword(e.formatLimitDefinition),s);e.default=a}),Y1=z((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=Z1(),i=Q1(),r=Te(),o=new r.Name("fullFormats"),a=new r.Name("fastFormats"),s=(u,l={keywords:!0})=>{if(Array.isArray(l))return d(u,l,n.fullFormats,o),u;let[p,m]=l.mode==="fast"?[n.fastFormats,a]:[n.fullFormats,o],f=l.formats||n.formatNames;return d(u,f,p,m),l.keywords&&(0,i.default)(u),u};s.get=(u,l="full")=>{let p=(l==="fast"?n.fastFormats:n.fullFormats)[u];if(!p)throw Error(`Unknown format "${u}"`);return p};function d(u,l,p,m){var f,h;(f=(h=u.opts.code).formats)!==null&&f!==void 0||(h.formats=r._`require("ajv-formats/dist/formats").${m}`);for(let y of l)u.addFormat(y,p[y])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s}),lj=50;zoe=new FinalizationRegistry(({parentSignalRef:e,handler:t})=>{e.deref()?.removeEventListener("abort",t)});ul=["PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","Notification","UserPromptSubmit","UserPromptExpansion","SessionStart","SessionEnd","Stop","StopFailure","SubagentStart","SubagentStop","PreCompact","PostCompact","PermissionRequest","PermissionDenied","Setup","TeammateIdle","TaskCreated","TaskCompleted","Elicitation","ElicitationResult","ConfigChange","WorktreeCreate","WorktreeRemove","InstructionsLoaded","CwdChanged","FileChanged","MessageDisplay"],_j=["clear","resume","logout","prompt_input_exit","other","bypass_permissions_disabled"],vj="__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__",bj=/^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/,wj=/<command-name>(.*?)<\/command-name>/;Sj={customTitle:"customTitle",aiTitle:"aiTitle",lastPrompt:"lastPrompt",summary:"summaryHint",gitBranch:"gitBranch"};Lp=class{store=new Map;mtimes=new Map;summaries=new Map;lastMtime=0;keyToString(t){let n=[t.projectKey,t.sessionId];return t.subpath&&n.push(t.subpath),n.join("/")}async append(t,n){let i=this.keyToString(t),r=this.store.get(i)??[];r.push(...n),this.store.set(i,r);let o=Math.max(Date.now(),this.lastMtime+1);if(this.lastMtime=o,this.mtimes.set(i,o),t.subpath===void 0){let a=`${t.projectKey}/${t.sessionId}`,s=YS(this.summaries.get(a),t,n,{mtime:o});this.summaries.set(a,s)}}async load(t){let n=this.keyToString(t);return this.store.get(n)??null}async listSessions(t){let n=[],i=t+"/";for(let[r]of this.store)if(r.startsWith(i)){let o=r.slice(i.length);o.includes("/")||n.push({sessionId:o,mtime:this.mtimes.get(r)??0})}return n}async listSessionSummaries(t){let n=[],i=t+"/";for(let[r,o]of this.summaries)r.startsWith(i)&&n.push(o);return n}async delete(t){let n=this.keyToString(t);if(this.store.delete(n),this.mtimes.delete(n),t.subpath===void 0){this.summaries.delete(`${t.projectKey}/${t.sessionId}`);let i=`${t.projectKey}/${t.sessionId}/`;for(let r of this.store.keys())r.startsWith(i)&&(this.store.delete(r),this.mtimes.delete(r))}}async listSubkeys(t){let n=`${t.projectKey}/${t.sessionId}/`,i=[];for(let r of this.store.keys())r.startsWith(n)&&i.push(r.slice(n.length));return i}getEntries(t){return this.store.get(this.keyToString(t))??[]}get size(){let t=0;for(let n of this.store.keys()){let i=n.indexOf("/");i!==-1&&!n.slice(i+1).includes("/")&&t++}return t}clear(){this.store.clear(),this.mtimes.clear(),this.summaries.clear()}},Mt=class extends Error{};Dv=globalThis.process?.getBuiltinModule?.("async_hooks"),Ij=Dv?e=>Dv.AsyncResource.bind(e):e=>e;Pj=typeof global=="object"&&global&&global.Object===Object&&global,ek=Pj,Ej=typeof self=="object"&&self&&self.Object===Object&&self,Rj=ek||Ej||Function("return this")(),zn=Rj,Oj=zn.Symbol,Nn=Oj,tk=Object.prototype,Aj=tk.hasOwnProperty,$j=tk.toString,Zo=Nn?Nn.toStringTag:void 0;jj=Mj,qj=Object.prototype,Nj=qj.toString;Lj=Dj,Uj="[object Null]",Fj="[object Undefined]",Lv=Nn?Nn.toStringTag:void 0;ri=zj;Dn=Bj,Kj="[object AsyncFunction]",Jj="[object Function]",Wj="[object GeneratorFunction]",Hj="[object Proxy]";ym=Gj,Vj=zn["__core-js_shared__"],np=Vj,Uv=(function(){var e=/[^.]+$/.exec(np&&np.keys&&np.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();Qj=Zj,Yj=Function.prototype,Xj=Yj.toString;ii=eq,tq=/[\\^$.*+?()[\]{}|]/g,nq=/^\[object .+?Constructor\]$/,rq=Function.prototype,iq=Object.prototype,oq=rq.toString,aq=iq.hasOwnProperty,sq=RegExp("^"+oq.call(aq).replace(tq,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");uq=dq;cq=lq;oi=pq,fq=oi(Object,"create"),ja=fq;hq=mq;yq=gq,_q="__lodash_hash_undefined__",vq=Object.prototype,bq=vq.hasOwnProperty;Sq=wq,kq=Object.prototype,xq=kq.hasOwnProperty;Tq=Cq,Iq="__lodash_hash_undefined__";Eq=Pq;mo.prototype.clear=hq;mo.prototype.delete=yq;mo.prototype.get=Sq;mo.prototype.has=Tq;mo.prototype.set=Eq;Fv=mo;Oq=Rq;ms=Aq;ll=$q,Mq=Array.prototype,jq=Mq.splice;Nq=qq;Lq=Dq;Fq=Uq;Bq=zq;ho.prototype.clear=Oq;ho.prototype.delete=Nq;ho.prototype.get=Lq;ho.prototype.has=Fq;ho.prototype.set=Bq;cl=ho,Kq=oi(zn,"Map"),qa=Kq;Wq=Jq;Gq=Hq;pl=Vq;Qq=Zq;Xq=Yq;tN=eN;rN=nN;go.prototype.clear=Wq;go.prototype.delete=Qq;go.prototype.get=Xq;go.prototype.has=tN;go.prototype.set=rN;fl=go,iN="Expected a function";_m.Cache=fl;vt=_m,yo=vt(()=>(process.env.CLAUDE_CONFIG_DIR??aN(oN(),".claude")).normalize("NFC"),()=>process.env.CLAUDE_CONFIG_DIR),Zoe=vt(()=>kt(process.env.CLAUDE_CODE_SUPERVISED));nk=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return nk=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,i=>(+i^n()&15>>+i/4).toString(16))};Up=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},me=class extends Error{},Rt=class e extends me{constructor(t,n,i,r,o){super(`${e.makeMessage(t,n,i)}`),this.status=t,this.headers=r,this.requestID=r?.get("request-id"),this.error=n,this.type=o??null}static makeMessage(t,n,i){let r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):i;return t&&r?`${t} ${r}`:t?`${t} status code (no body)`:r||"(no status code or body)"}static generate(t,n,i,r){if(!t||!r)return new Ki({message:i,cause:Up(n)});let o=n,a=o?.error?.type;return t===400?new Ld(t,o,i,r,a):t===401?new Ud(t,o,i,r,a):t===403?new Fd(t,o,i,r,a):t===404?new zd(t,o,i,r,a):t===409?new Bd(t,o,i,r,a):t===422?new Kd(t,o,i,r,a):t===429?new Jd(t,o,i,r,a):t>=500?new Wd(t,o,i,r,a):new e(t,o,i,r,a)}},Qt=class extends Rt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}},Ki=class extends Rt{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}},Dd=class extends Ki{constructor({message:t}={}){super({message:t??"Request timed out."})}},Ld=class extends Rt{},Ud=class extends Rt{},Fd=class extends Rt{},zd=class extends Rt{},Bd=class extends Rt{},Kd=class extends Rt{},Jd=class extends Rt{},Wd=class extends Rt{},sN=/^[a-z][a-z0-9+.-]*:/i,dN=e=>sN.test(e),Fp=e=>(Fp=Array.isArray,Fp(e)),zv=Fp;lN=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new me(`${e} must be an integer`);if(t<0)throw new me(`${e} must be a positive integer`);return t},rk=e=>{try{return JSON.parse(e)}catch{return}},cN=e=>new Promise(t=>setTimeout(t,e)),gr="0.94.0",pN=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";mN=()=>{let e=fN();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gr,"X-Stainless-OS":Jv(Deno.build.os),"X-Stainless-Arch":Kv(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gr,"X-Stainless-OS":Jv(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Kv(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=hN();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":gr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};Kv=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Jv=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),vm=()=>Wv??(Wv=mN());_N=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});bN="urn:ietf:params:oauth:grant-type:jwt-bearer",wN="refresh_token",ak="/v1/oauth/token",Hd="oauth-2025-04-20",SN="oidc-federation-2026-04-01",kN=120,wm=30,xN=5,Hv=1048576;rp=2e3,CN=new Set(["error","error_description","error_uri"]);Fe=class extends me{constructor(t,n=null,i=null,r=null){super(t),this.statusCode=n,this.body=i,this.requestId=r}};Bp=class{constructor(t,n){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=t,this.onAdvisoryRefreshError=n}async getToken(){let t=this.nextForce;this.nextForce=!1;let n=this.cached;if(t||n==null)return(await this.refresh(t)).token;if(n.expiresAt==null)return n.token;let i=n.expiresAt-Wr();return i>kN?n.token:i>wm?(this.backgroundRefresh(),n.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(t=!1){return this.pendingRefresh&&!t?this.pendingRefresh:this.doRefresh(t)}backgroundRefresh(){this.pendingRefresh||Wr()-this.lastAdvisoryError<xN||this.doRefresh().catch(t=>{this.lastAdvisoryError=Wr(),this.onAdvisoryRefreshError?.(t)})}doRefresh(t=!1){return this.pendingRefresh=this.provider(t?{forceRefresh:!0}:void 0).then(n=>(this.cached=n,this.pendingRefresh=null,n),n=>{throw this.pendingRefresh=null,n}),this.pendingRefresh}},Ue=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0};Gd={off:0,error:200,warn:300,info:400,debug:500},Qv=(e,t,n)=>{if(e){if(uN(Gd,e))return e;gt(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Gd))}`)}};PN={error:_a,warn:_a,info:_a,debug:_a},Yv=new WeakMap;zr=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,n])=>[t,t.toLowerCase()==="x-api-key"||t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),ck="1.0",EN=/^[A-Za-z0-9_.-]+$/;RN=async e=>{var t,n;let i=await km();if(i===null)return null;let r=e??await fk();if(r===null)return null;pk(r);let o=await import("node:fs"),a=(await import("node:path")).join(i,"configs",`${r}.json`),s;try{s=await o.promises.readFile(a,"utf-8")}catch(l){if(l?.code!=="ENOENT")throw Error(`failed to read config file ${a}: ${l}`);s=null}if(s===null){let l=Ue("ANTHROPIC_ORGANIZATION_ID"),p=Ue("ANTHROPIC_IDENTITY_TOKEN_FILE"),m=Ue("ANTHROPIC_FEDERATION_RULE_ID");return m&&l?{fromFile:!1,config:{organization_id:l,workspace_id:Ue("ANTHROPIC_WORKSPACE_ID"),base_url:Ue("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:m,service_account_id:Ue("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:p?{source:"file",path:p}:void 0,scope:Ue("ANTHROPIC_SCOPE")}}}:null}let d;try{d=JSON.parse(s)}catch(l){throw Error(`failed to parse config file ${a}: ${l}`)}if(!d.authentication)throw Error(`config file ${a} is missing "authentication"`);let u=d.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw Error(`authentication.type "${u}" is not a known authentication type`);if(d.organization_id??(d.organization_id=Ue("ANTHROPIC_ORGANIZATION_ID")),d.workspace_id??(d.workspace_id=Ue("ANTHROPIC_WORKSPACE_ID")),d.base_url??(d.base_url=Ue("ANTHROPIC_BASE_URL")),(t=d.authentication).scope??(t.scope=Ue("ANTHROPIC_SCOPE")),d.authentication.type==="oidc_federation"){if(!d.authentication.identity_token){let l=Ue("ANTHROPIC_IDENTITY_TOKEN_FILE");l&&(d.authentication.identity_token={source:"file",path:l})}d.authentication.federation_rule_id||(d.authentication.federation_rule_id=Ue("ANTHROPIC_FEDERATION_RULE_ID")??""),(n=d.authentication).service_account_id??(n.service_account_id=Ue("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:d,fromFile:!0}},ON=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;let n=await km();if(!n)return null;let i=t??await fk();return i?(pk(i),(await import("node:path")).join(n,"credentials",`${i}.json`)):null},km=async()=>{if(!AN())return null;let e=await import("node:path"),t=Ue("ANTHROPIC_CONFIG_DIR");if(t)return t;if(vm()["X-Stainless-OS"]==="Windows"){let r=Ue("APPDATA");if(r)return e.join(r,"Anthropic");let o=Ue("USERPROFILE");return o?e.join(o,"AppData","Roaming","Anthropic"):null}let n=Ue("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");let i=Ue("HOME");return i?e.join(i,".config","anthropic"):null},AN=()=>{let e=vm()["X-Stainless-Runtime"];return e==="node"||e==="deno"},fk=async()=>{let e=await km();if(!e)return null;let t=Ue("ANTHROPIC_PROFILE");if(t)return t;let n=await import("node:fs"),i=(await import("node:path")).join(e,"active_config");try{return(await n.promises.readFile(i,"utf-8")).trim()||"default"}catch(r){if(r?.code!=="ENOENT")throw Error(`failed to read ${i}: ${r}`);return"default"}};Vr=class{constructor(){Wt.set(this,void 0),Ht.set(this,void 0),ie(this,Wt,new Uint8Array,"f"),ie(this,Ht,null,"f")}decode(t){if(t==null)return[];let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Sm(t):t;ie(this,Wt,IN([N(this,Wt,"f"),n]),"f");let i=[],r;for(;(r=UN(N(this,Wt,"f"),N(this,Ht,"f")))!=null;){if(r.carriage&&N(this,Ht,"f")==null){ie(this,Ht,r.index,"f");continue}if(N(this,Ht,"f")!=null&&(r.index!==N(this,Ht,"f")+1||r.carriage)){i.push(Zv(N(this,Wt,"f").subarray(0,N(this,Ht,"f")-1))),ie(this,Wt,N(this,Wt,"f").subarray(N(this,Ht,"f")),"f"),ie(this,Ht,null,"f");continue}let o=N(this,Ht,"f")!==null?r.preceding-1:r.preceding,a=Zv(N(this,Wt,"f").subarray(0,o));i.push(a),ie(this,Wt,N(this,Wt,"f").subarray(r.index),"f"),ie(this,Ht,null,"f")}return i}flush(){return N(this,Wt,"f").length?this.decode(`
44
+ `):[]}};Wt=new WeakMap,Ht=new WeakMap;Vr.NEWLINE_CHARS=new Set([`
45
+ `,"\r"]);Vr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;Zr=class e{constructor(t,n,i){this.iterator=t,Qo.set(this,void 0),this.controller=n,ie(this,Qo,i,"f")}static fromSSEResponse(t,n,i){let r=!1,o=i?gt(i):console;async function*a(){if(r)throw new me("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let s=!1;try{for await(let d of zN(t,n)){if(d.event==="completion")try{yield JSON.parse(d.data)}catch(u){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),u}if(d.event==="message_start"||d.event==="message_delta"||d.event==="message_stop"||d.event==="content_block_start"||d.event==="content_block_delta"||d.event==="content_block_stop"||d.event==="message"||d.event==="user.message"||d.event==="user.interrupt"||d.event==="user.tool_confirmation"||d.event==="user.custom_tool_result"||d.event==="agent.message"||d.event==="agent.thinking"||d.event==="agent.tool_use"||d.event==="agent.tool_result"||d.event==="agent.mcp_tool_use"||d.event==="agent.mcp_tool_result"||d.event==="agent.custom_tool_use"||d.event==="agent.thread_context_compacted"||d.event==="session.status_running"||d.event==="session.status_idle"||d.event==="session.status_rescheduled"||d.event==="session.status_terminated"||d.event==="session.error"||d.event==="session.deleted"||d.event==="span.model_request_start"||d.event==="span.model_request_end")try{yield JSON.parse(d.data)}catch(u){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),u}if(d.event!=="ping"&&d.event==="error"){let u=rk(d.data)??d.data,l=u?.error?.type;throw new Rt(void 0,u,void 0,t.headers,l)}}s=!0}catch(d){if(Na(d))return;throw d}finally{s||n.abort()}}return new e(a,n,i)}static fromReadableStream(t,n,i){let r=!1;async function*o(){let s=new Vr,d=bm(t);for await(let u of d)for(let l of s.decode(u))yield l;for(let u of s.flush())yield u}async function*a(){if(r)throw new me("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let s=!1;try{for await(let d of o())s||d&&(yield JSON.parse(d));s=!0}catch(d){if(Na(d))return;throw d}finally{s||n.abort()}}return new e(a,n,i)}[(Qo=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],i=this.iterator(),r=o=>({next:()=>{if(o.length===0){let a=i.next();t.push(a),n.push(a)}return o.shift()}});return[new e(()=>r(t),this.controller,N(this,Qo,"f")),new e(()=>r(n),this.controller,N(this,Qo,"f"))]}toReadableStream(){let t=this,n;return ik({async start(){n=t[Symbol.asyncIterator]()},async pull(i){try{let{value:r,done:o}=await n.next();if(o)return i.close();let a=Sm(JSON.stringify(r)+`
46
+ `);i.enqueue(a)}catch(r){i.error(r)}},async cancel(){await n.return?.()}})}};Kp=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
47
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(t),t.startsWith(":"))return null;let[n,i,r]=KN(t,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}};Vd=class e extends Promise{constructor(t,n,i=hk){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=i,va.set(this,void 0),ie(this,va,t,"f")}_thenUnwrap(t){return new e(N(this,va,"f"),this.responsePromise,async(n,i)=>gk(t(await this.parseResponse(n,i),i),i.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(N(this,va,"f"),t))),this.parsedPromise}then(t,n){return this.parse().then(t,n)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};va=new WeakMap;Zd=class{constructor(t,n,i,r){od.set(this,void 0),ie(this,od,t,"f"),this.options=r,this.response=n,this.body=i}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let t=this.nextPageRequestOptions();if(!t)throw new me("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await N(this,od,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(od=new WeakMap,Symbol.asyncIterator)](){for await(let t of this.iterPages())for(let n of t.getPaginatedItems())yield n}},Jp=class extends Vd{constructor(t,n,i){super(t,n,async(r,o)=>new i(r,o.response,await hk(r,o),o.options))}async*[Symbol.asyncIterator](){let t=await this;for await(let n of t)yield n}},Qr=class extends Zd{constructor(t,n,i,r){super(t,n,i,r),this.data=i.data||[],this.has_more=i.has_more||!1,this.first_id=i.first_id||null,this.last_id=i.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let n=this.first_id;return n?{...this.options,query:{...zp(this.options.query),before_id:n}}:null}let t=this.last_id;return t?{...this.options,query:{...zp(this.options.query),after_id:t}}:null}},xt=class extends Zd{constructor(t,n,i,r){super(t,n,i,r),this.data=i.data||[],this.next_page=i.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let t=this.next_page;return t?{...this.options,query:{...zp(this.options.query),page:t}}:null}},yk=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};_k=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",xm=async(e,t,n=!0)=>({...e,body:await WN(e.body,t,n)}),eb=new WeakMap;WN=async(e,t,n=!0)=>{if(!await JN(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let i=new FormData;return await Promise.all(Object.entries(e||{}).map(([r,o])=>Wp(i,r,o,n))),i},HN=e=>e instanceof Blob&&"name"in e,Wp=async(e,t,n,i)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")e.append(t,String(n));else if(n instanceof Response){let r={},o=n.headers.get("Content-Type");o&&(r={type:o}),e.append(t,Ni([await n.blob()],Pd(n,i),r))}else if(_k(n))e.append(t,Ni([await new Response(ok(n)).blob()],Pd(n,i)));else if(HN(n))e.append(t,Ni([n],Pd(n,i),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(r=>Wp(e,t+"[]",r,i)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,o])=>Wp(e,`${t}[${r}]`,o,i)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},vk=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",GN=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&vk(e),VN=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";Ge=class{constructor(t){this._client=t}},bk=Symbol.for("brand.privateNullableHeaders");H=e=>{let t=new Headers,n=new Set;for(let i of e){let r=new Set;for(let[o,a]of YN(i)){let s=o.toLowerCase();r.has(s)||(t.delete(o),r.add(s)),a===null?(t.delete(o),n.add(s)):(t.append(o,a),n.delete(s))}}return{[bk]:!0,values:t,nulls:n}};tb=Object.freeze(Object.create(null)),XN=(e=wk)=>function(t,...n){if(t.length===1)return t[0];let i=!1,r=[],o=t.reduce((u,l,p)=>{/[?#]/.test(l)&&(i=!0);let m=n[p],f=(i?encodeURIComponent:e)(""+m);return p!==n.length&&(m==null||typeof m=="object"&&m.toString===Object.getPrototypeOf(Object.getPrototypeOf(m.hasOwnProperty??tb)??tb)?.toString)&&(f=m+"",r.push({start:u.length+l.length,length:f.length,error:`Value of type ${Object.prototype.toString.call(m).slice(8,-1)} is not a valid path parameter`})),u+l+(p===n.length?"":f)},""),a=o.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=s.exec(a))!==null;)r.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(r.sort((u,l)=>u.start-l.start),r.length>0){let u=0,l=r.reduce((p,m)=>{let f=" ".repeat(m.start-u),h="^".repeat(m.length);return u=m.start+m.length,p+f+h},"");throw new me(`Path parameters result in path with invalid segments:
48
+ ${r.map(p=>p.error).join(`
49
+ `)}
50
+ ${o}
51
+ ${l}`)}return o},de=XN(wk),Qd=class extends Ge{create(t,n){let{betas:i,...r}=t;return this._client.post("/v1/environments?beta=true",{body:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/environments/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}update(t,n,i){let{betas:r,...o}=n;return this._client.post(de`/v1/environments/${t}?beta=true`,{body:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/environments?beta=true",xt,{query:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(t,n={},i){let{betas:r}=n??{};return this._client.delete(de`/v1/environments/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}archive(t,n={},i){let{betas:r}=n??{};return this._client.post(de`/v1/environments/${t}/archive?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}},Pa=Symbol("anthropic.sdk.stainlessHelper");Yd=class extends Ge{list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/files?beta=true",Qr,{query:r,...n,headers:H([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString()},n?.headers])})}delete(t,n={},i){let{betas:r}=n??{};return this._client.delete(de`/v1/files/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},i?.headers])})}download(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/files/${t}/content?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},i?.headers]),__binaryResponse:!0})}retrieveMetadata(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/files/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},i?.headers])})}upload(t,n){let{betas:i,...r}=t;return this._client.post("/v1/files?beta=true",xm({body:r,...n,headers:H([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString()},eD(r.file),n?.headers])},this._client))}},Xd=class extends Ge{retrieve(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/models/${t}?beta=true`,{...i,headers:H([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/models?beta=true",Qr,{query:r,...n,headers:H([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}},eu=class extends Ge{create(t,n){let{betas:i,...r}=t;return this._client.post("/v1/user_profiles?beta=true",{body:r,...n,headers:H([{"anthropic-beta":[...i??[],"user-profiles-2026-03-24"].toString()},n?.headers])})}retrieve(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/user_profiles/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},i?.headers])})}update(t,n,i){let{betas:r,...o}=n;return this._client.post(de`/v1/user_profiles/${t}?beta=true`,{body:o,...i,headers:H([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/user_profiles?beta=true",xt,{query:r,...n,headers:H([{"anthropic-beta":[...i??[],"user-profiles-2026-03-24"].toString()},n?.headers])})}createEnrollmentURL(t,n={},i){let{betas:r}=n??{};return this._client.post(de`/v1/user_profiles/${t}/enrollment_url?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},i?.headers])})}},tu=class extends Ge{list(t,n={},i){let{betas:r,...o}=n??{};return this._client.getAPIList(de`/v1/agents/${t}/versions?beta=true`,xt,{query:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}},Da=class extends Ge{constructor(){super(...arguments),this.versions=new tu(this._client)}create(t,n){let{betas:i,...r}=t;return this._client.post("/v1/agents?beta=true",{body:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(t,n={},i){let{betas:r,...o}=n??{};return this._client.get(de`/v1/agents/${t}?beta=true`,{query:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}update(t,n,i){let{betas:r,...o}=n;return this._client.post(de`/v1/agents/${t}?beta=true`,{body:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/agents?beta=true",xt,{query:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}archive(t,n={},i){let{betas:r}=n??{};return this._client.post(de`/v1/agents/${t}/archive?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}};Da.Versions=tu;nu=class extends Ge{create(t,n,i){let{view:r,betas:o,...a}=n;return this._client.post(de`/v1/memory_stores/${t}/memories?beta=true`,{query:{view:r},body:a,...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}retrieve(t,n,i){let{memory_store_id:r,betas:o,...a}=n;return this._client.get(de`/v1/memory_stores/${r}/memories/${t}?beta=true`,{query:a,...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}update(t,n,i){let{memory_store_id:r,view:o,betas:a,...s}=n;return this._client.post(de`/v1/memory_stores/${r}/memories/${t}?beta=true`,{query:{view:o},body:s,...i,headers:H([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}list(t,n={},i){let{betas:r,...o}=n??{};return this._client.getAPIList(de`/v1/memory_stores/${t}/memories?beta=true`,xt,{query:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}delete(t,n,i){let{memory_store_id:r,expected_content_sha256:o,betas:a}=n;return this._client.delete(de`/v1/memory_stores/${r}/memories/${t}?beta=true`,{query:{expected_content_sha256:o},...i,headers:H([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}},ru=class extends Ge{retrieve(t,n,i){let{memory_store_id:r,betas:o,...a}=n;return this._client.get(de`/v1/memory_stores/${r}/memory_versions/${t}?beta=true`,{query:a,...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}list(t,n={},i){let{betas:r,...o}=n??{};return this._client.getAPIList(de`/v1/memory_stores/${t}/memory_versions?beta=true`,xt,{query:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}redact(t,n,i){let{memory_store_id:r,betas:o}=n;return this._client.post(de`/v1/memory_stores/${r}/memory_versions/${t}/redact?beta=true`,{...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}},Ji=class extends Ge{constructor(){super(...arguments),this.memories=new nu(this._client),this.memoryVersions=new ru(this._client)}create(t,n){let{betas:i,...r}=t;return this._client.post("/v1/memory_stores?beta=true",{body:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/memory_stores/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}update(t,n,i){let{betas:r,...o}=n;return this._client.post(de`/v1/memory_stores/${t}?beta=true`,{body:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/memory_stores?beta=true",xt,{query:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(t,n={},i){let{betas:r}=n??{};return this._client.delete(de`/v1/memory_stores/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}archive(t,n={},i){let{betas:r}=n??{};return this._client.post(de`/v1/memory_stores/${t}/archive?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}};Ji.Memories=nu;Ji.MemoryVersions=ru;iu=class e{constructor(t,n){this.iterator=t,this.controller=n}async*decoder(){let t=new Vr;for await(let n of this.iterator)for(let i of t.decode(n))yield JSON.parse(i);for(let n of t.flush())yield JSON.parse(n)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,n){if(!t.body)throw n.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new me("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new me("Attempted to iterate over a response with no body");return new e(bm(t.body),n)}},ou=class extends Ge{create(t,n){let{betas:i,...r}=t;return this._client.post("/v1/messages/batches?beta=true",{body:r,...n,headers:H([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}retrieve(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/messages/batches/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Qr,{query:r,...n,headers:H([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}delete(t,n={},i){let{betas:r}=n??{};return this._client.delete(de`/v1/messages/batches/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},i?.headers])})}cancel(t,n={},i){let{betas:r}=n??{};return this._client.post(de`/v1/messages/batches/${t}/cancel?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},i?.headers])})}async results(t,n={},i){let r=await this.retrieve(t);if(!r.results_url)throw new me(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);let{betas:o}=n??{};return this._client.get(r.results_url,{...i,headers:H([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},i?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,s)=>iu.fromResponse(s.response,s.controller))}},xk={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};nD=e=>{let t=0,n=[];for(;t<e.length;){let i=e[t];if(i==="\\"){t++;continue}if(i==="{"){n.push({type:"brace",value:"{"}),t++;continue}if(i==="}"){n.push({type:"brace",value:"}"}),t++;continue}if(i==="["){n.push({type:"paren",value:"["}),t++;continue}if(i==="]"){n.push({type:"paren",value:"]"}),t++;continue}if(i===":"){n.push({type:"separator",value:":"}),t++;continue}if(i===","){n.push({type:"delimiter",value:","}),t++;continue}if(i==='"'){let a="",s=!1;for(i=e[++t];i!=='"';){if(t===e.length){s=!0;break}if(i==="\\"){if(t++,t===e.length){s=!0;break}a+=i+e[t],i=e[++t]}else a+=i,i=e[++t]}i=e[++t],!s&&n.push({type:"string",value:a});continue}if(i&&/\s/.test(i)){t++;continue}let r=/[0-9]/;if(i&&r.test(i)||i==="-"||i==="."){let a="";for(i==="-"&&(a+=i,i=e[++t]);i&&r.test(i)||i===".";)a+=i,i=e[++t];n.push({type:"number",value:a});continue}let o=/[a-z]/i;if(i&&o.test(i)){let a="";for(;i&&o.test(i)&&t!==e.length;)a+=i,i=e[++t];if(a=="true"||a=="false"||a==="null")n.push({type:"name",value:a});else{t++;continue}continue}t++}return n},Ri=e=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case"separator":return e=e.slice(0,e.length-1),Ri(e);case"number":let n=t.value[t.value.length-1];if(n==="."||n==="-")return e=e.slice(0,e.length-1),Ri(e);case"string":let i=e[e.length-2];if(i?.type==="delimiter")return e=e.slice(0,e.length-1),Ri(e);if(i?.type==="brace"&&i.value==="{")return e=e.slice(0,e.length-1),Ri(e);break;case"delimiter":return e=e.slice(0,e.length-1),Ri(e)}return e},rD=e=>{let t=[];return e.map(n=>{n.type==="brace"&&(n.value==="{"?t.push("}"):t.splice(t.lastIndexOf("}"),1)),n.type==="paren"&&(n.value==="["?t.push("]"):t.splice(t.lastIndexOf("]"),1))}),t.length>0&&t.reverse().map(n=>{n==="}"?e.push({type:"brace",value:"}"}):n==="]"&&e.push({type:"paren",value:"]"})}),e},iD=e=>{let t="";return e.map(n=>{n.type==="string"?t+='"'+n.value+'"':t+=n.value}),t},Ik=e=>JSON.parse(iD(rD(Ri(nD(e))))),ob="__json_buf";Gp=class e{constructor(t,n){rn.add(this),this.messages=[],this.receivedMessages=[],ur.set(this,void 0),Si.set(this,null),this.controller=new AbortController,Yo.set(this,void 0),ad.set(this,()=>{}),Xo.set(this,()=>{}),ea.set(this,void 0),sd.set(this,()=>{}),ta.set(this,()=>{}),Vn.set(this,{}),na.set(this,!1),dd.set(this,!1),ud.set(this,!1),Dr.set(this,!1),ld.set(this,void 0),cd.set(this,void 0),ra.set(this,void 0),pd.set(this,i=>{if(ie(this,dd,!0,"f"),Na(i)&&(i=new Qt),i instanceof Qt)return ie(this,ud,!0,"f"),this._emit("abort",i);if(i instanceof me)return this._emit("error",i);if(i instanceof Error){let r=new me(i.message);return r.cause=i,this._emit("error",r)}return this._emit("error",new me(String(i)))}),ie(this,Yo,new Promise((i,r)=>{ie(this,ad,i,"f"),ie(this,Xo,r,"f")}),"f"),ie(this,ea,new Promise((i,r)=>{ie(this,sd,i,"f"),ie(this,ta,r,"f")}),"f"),N(this,Yo,"f").catch(()=>{}),N(this,ea,"f").catch(()=>{}),ie(this,Si,t,"f"),ie(this,ra,n?.logger??console,"f")}get response(){return N(this,ld,"f")}get request_id(){return N(this,cd,"f")}async withResponse(){ie(this,Dr,!0,"f");let t=await N(this,Yo,"f");if(!t)throw Error("Could not resolve a `Response` object");return{data:this,response:t,request_id:t.headers.get("request-id")}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,i,{logger:r}={}){let o=new e(n,{logger:r});for(let a of n.messages)o._addMessageParam(a);return ie(o,Si,{...n,stream:!0},"f"),o._run(()=>o._createMessage(t,{...n,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(t){t().then(()=>{this._emitFinal(),this._emit("end")},N(this,pd,"f"))}_addMessageParam(t){this.messages.push(t)}_addMessage(t,n=!0){this.receivedMessages.push(t),n&&this._emit("message",t)}async _createMessage(t,n,i){let r=i?.signal,o;r&&(r.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),r.addEventListener("abort",o));try{N(this,rn,"m",op).call(this);let{response:a,data:s}=await t.create({...n,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(a);for await(let d of s)N(this,rn,"m",ap).call(this,d);if(s.controller.signal?.aborted)throw new Qt;N(this,rn,"m",sp).call(this)}finally{r&&o&&r.removeEventListener("abort",o)}}_connected(t){this.ended||(ie(this,ld,t,"f"),ie(this,cd,t?.headers.get("request-id"),"f"),N(this,ad,"f").call(this,t),this._emit("connect"))}get ended(){return N(this,na,"f")}get errored(){return N(this,dd,"f")}get aborted(){return N(this,ud,"f")}abort(){this.controller.abort()}on(t,n){return(N(this,Vn,"f")[t]||(N(this,Vn,"f")[t]=[])).push({listener:n}),this}off(t,n){let i=N(this,Vn,"f")[t];if(!i)return this;let r=i.findIndex(o=>o.listener===n);return r>=0&&i.splice(r,1),this}once(t,n){return(N(this,Vn,"f")[t]||(N(this,Vn,"f")[t]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,i)=>{ie(this,Dr,!0,"f"),t!=="error"&&this.once("error",i),this.once(t,n)})}async done(){ie(this,Dr,!0,"f"),await N(this,ea,"f")}get currentMessage(){return N(this,ur,"f")}async finalMessage(){return await this.done(),N(this,rn,"m",ip).call(this)}async finalText(){return await this.done(),N(this,rn,"m",rb).call(this)}_emit(t,...n){if(N(this,na,"f"))return;t==="end"&&(ie(this,na,!0,"f"),N(this,sd,"f").call(this));let i=N(this,Vn,"f")[t];if(i&&(N(this,Vn,"f")[t]=i.filter(r=>!r.once),i.forEach(({listener:r})=>r(...n))),t==="abort"){let r=n[0];!N(this,Dr,"f")&&!i?.length&&Promise.reject(r),N(this,Xo,"f").call(this,r),N(this,ta,"f").call(this,r),this._emit("end");return}if(t==="error"){let r=n[0];!N(this,Dr,"f")&&!i?.length&&Promise.reject(r),N(this,Xo,"f").call(this,r),N(this,ta,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",N(this,rn,"m",ip).call(this))}async _fromReadableStream(t,n){let i=n?.signal,r;i&&(i.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),i.addEventListener("abort",r));try{N(this,rn,"m",op).call(this),this._connected(null);let o=Zr.fromReadableStream(t,this.controller);for await(let a of o)N(this,rn,"m",ap).call(this,a);if(o.controller.signal?.aborted)throw new Qt;N(this,rn,"m",sp).call(this)}finally{i&&r&&i.removeEventListener("abort",r)}}[(ur=new WeakMap,Si=new WeakMap,Yo=new WeakMap,ad=new WeakMap,Xo=new WeakMap,ea=new WeakMap,sd=new WeakMap,ta=new WeakMap,Vn=new WeakMap,na=new WeakMap,dd=new WeakMap,ud=new WeakMap,Dr=new WeakMap,ld=new WeakMap,cd=new WeakMap,ra=new WeakMap,pd=new WeakMap,rn=new WeakSet,ip=function(){if(this.receivedMessages.length===0)throw new me("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},rb=function(){if(this.receivedMessages.length===0)throw new me("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new me("stream ended without producing a content block with type=text");return t.join(" ")},op=function(){this.ended||ie(this,ur,void 0,"f")},ap=function(t){if(this.ended)return;let n=N(this,rn,"m",ib).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let i=n.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{ab(i)&&i.input&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}case"compaction_delta":{i.type==="compaction"&&i.content&&this._emit("compaction",i.content);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(nb(n,N(this,Si,"f"),{logger:N(this,ra,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{ie(this,ur,n,"f");break}case"content_block_start":case"message_delta":break}},sp=function(){if(this.ended)throw new me("stream has ended, this shouldn't happen");let t=N(this,ur,"f");if(!t)throw new me("request ended without sending any chunks");return ie(this,ur,void 0,"f"),nb(t,N(this,Si,"f"),{logger:N(this,ra,"f")})},ib=function(t){let n=N(this,ur,"f");if(t.type==="message_start"){if(n)throw new me(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new me(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.container=t.delta.container,n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n.context_management=t.context_management,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),t.usage.iterations!=null&&(n.usage.iterations=t.usage.iterations),n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let i=n.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(n.content[t.index]={...i,text:(i.text||"")+t.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[t.index]={...i,citations:[...i.citations??[],t.delta.citation]});break}case"input_json_delta":{if(i&&ab(i)){let r=i[ob]||"";r+=t.delta.partial_json;let o={...i};if(Object.defineProperty(o,ob,{value:r,enumerable:!1,writable:!0}),r)try{o.input=Ik(r)}catch(a){let s=new me(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${r}`);N(this,pd,"f").call(this,s)}n.content[t.index]=o}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[t.index]={...i,thinking:i.thinking+t.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[t.index]={...i,signature:t.delta.signature});break}case"compaction_delta":{i?.type==="compaction"&&(n.content[t.index]={...i,content:(i.content||"")+t.delta.content});break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let t=[],n=[],i=!1;return this.on("streamEvent",r=>{let o=n.shift();o?o.resolve(r):t.push(r)}),this.on("end",()=>{i=!0;for(let r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{i=!0;for(let o of n)o.reject(r);n.length=0}),this.on("error",r=>{i=!0;for(let o of n)o.reject(r);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((r,o)=>n.push({resolve:r,reject:o})).then(r=>r?{value:r,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Zr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},au=class extends Error{constructor(t){let n=typeof t=="string"?t:t.map(i=>i.type==="text"?i.text:`[${i.type}]`).join(" ");super(n),this.name="ToolError",this.content=t}},oD=1e5,aD=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
52
+ 1. Task Overview
53
+ The user's core request and success criteria
54
+ Any clarifications or constraints they specified
55
+ 2. Current State
56
+ What has been completed so far
57
+ Files created, modified, or analyzed (with paths if relevant)
58
+ Key outputs or artifacts produced
59
+ 3. Important Discoveries
60
+ Technical constraints or requirements uncovered
61
+ Decisions made and their rationale
62
+ Errors encountered and how they were resolved
63
+ What approaches were tried that didn't work (and why)
64
+ 4. Next Steps
65
+ Specific actions needed to complete the task
66
+ Any blockers or open questions to resolve
67
+ Priority order if multiple steps remain
68
+ 5. Context to Preserve
69
+ User preferences or style requirements
70
+ Domain-specific details that aren't obvious
71
+ Any promises made to the user
72
+ Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
73
+ Wrap your summary in <summary></summary> tags.`;su=class{constructor(t,n,i){ia.add(this),this.client=t,ki.set(this,!1),Lr.set(this,!1),ct.set(this,void 0),$t.set(this,void 0),Jt.set(this,void 0),Xn.set(this,void 0),lr.set(this,void 0),oa.set(this,0),ie(this,ct,{params:{...n,messages:structuredClone(n.messages)}},"f");let r=["BetaToolRunner",...Sk(n.tools,n.messages)].join(", ");ie(this,$t,{...i,headers:H([{"x-stainless-helper":r},i?.headers])},"f"),ie(this,lr,db(),"f"),n.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(ki=new WeakMap,Lr=new WeakMap,ct=new WeakMap,$t=new WeakMap,Jt=new WeakMap,Xn=new WeakMap,lr=new WeakMap,oa=new WeakMap,ia=new WeakSet,sb=async function(){let t=N(this,ct,"f").params.compactionControl;if(!t||!t.enabled)return!1;let n=0;if(N(this,Jt,"f")!==void 0)try{let d=await N(this,Jt,"f");n=d.usage.input_tokens+(d.usage.cache_creation_input_tokens??0)+(d.usage.cache_read_input_tokens??0)+d.usage.output_tokens}catch{return!1}let i=t.contextTokenThreshold??oD;if(n<i)return!1;let r=t.model??N(this,ct,"f").params.model,o=t.summaryPrompt??aD,a=N(this,ct,"f").params.messages;if(a[a.length-1].role==="assistant"){let d=a[a.length-1];if(Array.isArray(d.content)){let u=d.content.filter(l=>l.type!=="tool_use");u.length===0?a.pop():d.content=u}}let s=await this.client.beta.messages.create({model:r,messages:[...a,{role:"user",content:[{type:"text",text:o}]}],max_tokens:N(this,ct,"f").params.max_tokens},{signal:N(this,$t,"f").signal,headers:H([N(this,$t,"f").headers,{"x-stainless-helper":"compaction"}])});if(s.content[0]?.type!=="text")throw new me("Expected text response for compaction");return N(this,ct,"f").params.messages=[{role:"user",content:s.content}],!0},Symbol.asyncIterator)](){var t;if(N(this,ki,"f"))throw new me("Cannot iterate over a consumed stream");ie(this,ki,!0,"f"),ie(this,Lr,!0,"f"),ie(this,Xn,void 0,"f");try{for(;;){let n;try{if(N(this,ct,"f").params.max_iterations&&N(this,oa,"f")>=N(this,ct,"f").params.max_iterations)break;ie(this,Lr,!1,"f"),ie(this,Xn,void 0,"f"),ie(this,oa,(t=N(this,oa,"f"),t++,t),"f"),ie(this,Jt,void 0,"f");let{max_iterations:i,compactionControl:r,...o}=N(this,ct,"f").params;if(o.stream?(n=this.client.beta.messages.stream({...o},N(this,$t,"f")),ie(this,Jt,n.finalMessage(),"f"),N(this,Jt,"f").catch(()=>{}),yield n):(ie(this,Jt,this.client.beta.messages.create({...o,stream:!1},N(this,$t,"f")),"f"),yield N(this,Jt,"f")),!await N(this,ia,"m",sb).call(this)){if(!N(this,Lr,"f")){let{role:s,content:d}=await N(this,Jt,"f");N(this,ct,"f").params.messages.push({role:s,content:d})}let a=await N(this,ia,"m",Vp).call(this,N(this,ct,"f").params.messages.at(-1));if(a)N(this,ct,"f").params.messages.push(a);else if(!N(this,Lr,"f"))break}}finally{n&&n.abort()}}if(!N(this,Jt,"f"))throw new me("ToolRunner concluded without a message from the server");N(this,lr,"f").resolve(await N(this,Jt,"f"))}catch(n){throw ie(this,ki,!1,"f"),N(this,lr,"f").promise.catch(()=>{}),N(this,lr,"f").reject(n),ie(this,lr,db(),"f"),n}}setMessagesParams(t){typeof t=="function"?N(this,ct,"f").params=t(N(this,ct,"f").params):N(this,ct,"f").params=t,ie(this,Lr,!0,"f"),ie(this,Xn,void 0,"f")}setRequestOptions(t){typeof t=="function"?ie(this,$t,t(N(this,$t,"f")),"f"):ie(this,$t,{...N(this,$t,"f"),...t},"f")}async generateToolResponse(t=N(this,$t,"f").signal){let n=await N(this,Jt,"f")??this.params.messages.at(-1);return n?N(this,ia,"m",Vp).call(this,n,t):null}done(){return N(this,lr,"f").promise}async runUntilDone(){if(!N(this,ki,"f"))for await(let t of this);return this.done()}get params(){return N(this,ct,"f").params}pushMessages(...t){this.setMessagesParams(n=>({...n,messages:[...n.messages,...t]}))}then(t,n){return this.runUntilDone().then(t,n)}};Vp=async function(e,t=N(this,$t,"f").signal){return N(this,Xn,"f")!==void 0?N(this,Xn,"f"):(ie(this,Xn,sD(N(this,ct,"f").params,e,{...N(this,$t,"f"),signal:t}),"f"),N(this,Xn,"f"))};ub={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},dD=["claude-mythos-preview","claude-opus-4-6"],Yr=class extends Ge{constructor(){super(...arguments),this.batches=new ou(this._client)}create(t,n){let i=lb(t),{betas:r,...o}=i;o.model in ub&&console.warn(`The model '${o.model}' is deprecated and will reach end-of-life on ${ub[o.model]}
74
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),dD.includes(o.model)&&o.thinking&&o.thinking.type==="enabled"&&console.warn(`Using Claude with ${o.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let a=this._client._options.timeout;if(!o.stream&&a==null){let d=xk[o.model]??void 0;a=this._client.calculateNonstreamingTimeout(o.max_tokens,d)}let s=kk(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:a??6e5,...n,headers:H([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},s,n?.headers]),stream:i.stream??!1})}parse(t,n){return n={...n,headers:H([{"anthropic-beta":[...t.betas??[],"structured-outputs-2025-12-15"].toString()},n?.headers])},this.create(t,n).then(i=>Tk(i,t,{logger:this._client.logger??console}))}stream(t,n){return Gp.createMessage(this,t,n)}countTokens(t,n){let i=lb(t),{betas:r,...o}=i;return this._client.post("/v1/messages/count_tokens?beta=true",{body:o,...n,headers:H([{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString()},n?.headers])})}toolRunner(t,n){return new su(this._client,t,n)}};Yr.Batches=ou;Yr.BetaToolRunner=su;Yr.ToolError=au;du=class extends Ge{list(t,n={},i){let{betas:r,...o}=n??{};return this._client.getAPIList(de`/v1/sessions/${t}/events?beta=true`,xt,{query:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}send(t,n,i){let{betas:r,...o}=n;return this._client.post(de`/v1/sessions/${t}/events?beta=true`,{body:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}stream(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/sessions/${t}/events/stream?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers]),stream:!0})}},uu=class extends Ge{retrieve(t,n,i){let{session_id:r,betas:o}=n;return this._client.get(de`/v1/sessions/${r}/resources/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}update(t,n,i){let{session_id:r,betas:o,...a}=n;return this._client.post(de`/v1/sessions/${r}/resources/${t}?beta=true`,{body:a,...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}list(t,n={},i){let{betas:r,...o}=n??{};return this._client.getAPIList(de`/v1/sessions/${t}/resources?beta=true`,xt,{query:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}delete(t,n,i){let{session_id:r,betas:o}=n;return this._client.delete(de`/v1/sessions/${r}/resources/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}add(t,n,i){let{betas:r,...o}=n;return this._client.post(de`/v1/sessions/${t}/resources?beta=true`,{body:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}},Wi=class extends Ge{constructor(){super(...arguments),this.events=new du(this._client),this.resources=new uu(this._client)}create(t,n){let{betas:i,...r}=t;return this._client.post("/v1/sessions?beta=true",{body:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/sessions/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}update(t,n,i){let{betas:r,...o}=n;return this._client.post(de`/v1/sessions/${t}?beta=true`,{body:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/sessions?beta=true",xt,{query:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(t,n={},i){let{betas:r}=n??{};return this._client.delete(de`/v1/sessions/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}archive(t,n={},i){let{betas:r}=n??{};return this._client.post(de`/v1/sessions/${t}/archive?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}};Wi.Events=du;Wi.Resources=uu;lu=class extends Ge{create(t,n={},i){let{betas:r,...o}=n??{};return this._client.post(de`/v1/skills/${t}/versions?beta=true`,xm({body:o,...i,headers:H([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},i?.headers])},this._client))}retrieve(t,n,i){let{skill_id:r,betas:o}=n;return this._client.get(de`/v1/skills/${r}/versions/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},i?.headers])})}list(t,n={},i){let{betas:r,...o}=n??{};return this._client.getAPIList(de`/v1/skills/${t}/versions?beta=true`,xt,{query:o,...i,headers:H([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},i?.headers])})}delete(t,n,i){let{skill_id:r,betas:o}=n;return this._client.delete(de`/v1/skills/${r}/versions/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},i?.headers])})}},La=class extends Ge{constructor(){super(...arguments),this.versions=new lu(this._client)}create(t={},n){let{betas:i,...r}=t??{};return this._client.post("/v1/skills?beta=true",xm({body:r,...n,headers:H([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},n?.headers])},this._client,!1))}retrieve(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/skills/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/skills?beta=true",xt,{query:r,...n,headers:H([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},n?.headers])})}delete(t,n={},i){let{betas:r}=n??{};return this._client.delete(de`/v1/skills/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},i?.headers])})}};La.Versions=lu;cu=class extends Ge{create(t,n,i){let{betas:r,...o}=n;return this._client.post(de`/v1/vaults/${t}/credentials?beta=true`,{body:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}retrieve(t,n,i){let{vault_id:r,betas:o}=n;return this._client.get(de`/v1/vaults/${r}/credentials/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}update(t,n,i){let{vault_id:r,betas:o,...a}=n;return this._client.post(de`/v1/vaults/${r}/credentials/${t}?beta=true`,{body:a,...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}list(t,n={},i){let{betas:r,...o}=n??{};return this._client.getAPIList(de`/v1/vaults/${t}/credentials?beta=true`,xt,{query:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}delete(t,n,i){let{vault_id:r,betas:o}=n;return this._client.delete(de`/v1/vaults/${r}/credentials/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}archive(t,n,i){let{vault_id:r,betas:o}=n;return this._client.post(de`/v1/vaults/${r}/credentials/${t}/archive?beta=true`,{...i,headers:H([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}},Ua=class extends Ge{constructor(){super(...arguments),this.credentials=new cu(this._client)}create(t,n){let{betas:i,...r}=t;return this._client.post("/v1/vaults?beta=true",{body:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/vaults/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}update(t,n,i){let{betas:r,...o}=n;return this._client.post(de`/v1/vaults/${t}?beta=true`,{body:o,...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/vaults?beta=true",xt,{query:r,...n,headers:H([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(t,n={},i){let{betas:r}=n??{};return this._client.delete(de`/v1/vaults/${t}?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}archive(t,n={},i){let{betas:r}=n??{};return this._client.post(de`/v1/vaults/${t}/archive?beta=true`,{...i,headers:H([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},i?.headers])})}};Ua.Credentials=cu;qt=class extends Ge{constructor(){super(...arguments),this.models=new Xd(this._client),this.messages=new Yr(this._client),this.agents=new Da(this._client),this.environments=new Qd(this._client),this.sessions=new Wi(this._client),this.vaults=new Ua(this._client),this.memoryStores=new Ji(this._client),this.files=new Yd(this._client),this.skills=new La(this._client),this.userProfiles=new eu(this._client)}};qt.Models=Xd;qt.Messages=Yr;qt.Agents=Da;qt.Environments=Qd;qt.Sessions=Wi;qt.Vaults=Ua;qt.MemoryStores=Ji;qt.Files=Yd;qt.Skills=La;qt.UserProfiles=eu;pu=class extends Ge{create(t,n){let{betas:i,...r}=t;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...n,headers:H([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers]),stream:t.stream??!1})}};mb="__json_buf";Zp=class e{constructor(t,n){on.add(this),this.messages=[],this.receivedMessages=[],cr.set(this,void 0),xi.set(this,null),this.controller=new AbortController,aa.set(this,void 0),fd.set(this,()=>{}),sa.set(this,()=>{}),da.set(this,void 0),md.set(this,()=>{}),ua.set(this,()=>{}),Zn.set(this,{}),la.set(this,!1),hd.set(this,!1),gd.set(this,!1),Ur.set(this,!1),yd.set(this,void 0),_d.set(this,void 0),ca.set(this,void 0),up.set(this,i=>{if(ie(this,hd,!0,"f"),Na(i)&&(i=new Qt),i instanceof Qt)return ie(this,gd,!0,"f"),this._emit("abort",i);if(i instanceof me)return this._emit("error",i);if(i instanceof Error){let r=new me(i.message);return r.cause=i,this._emit("error",r)}return this._emit("error",new me(String(i)))}),ie(this,aa,new Promise((i,r)=>{ie(this,fd,i,"f"),ie(this,sa,r,"f")}),"f"),ie(this,da,new Promise((i,r)=>{ie(this,md,i,"f"),ie(this,ua,r,"f")}),"f"),N(this,aa,"f").catch(()=>{}),N(this,da,"f").catch(()=>{}),ie(this,xi,t,"f"),ie(this,ca,n?.logger??console,"f")}get response(){return N(this,yd,"f")}get request_id(){return N(this,_d,"f")}async withResponse(){ie(this,Ur,!0,"f");let t=await N(this,aa,"f");if(!t)throw Error("Could not resolve a `Response` object");return{data:this,response:t,request_id:t.headers.get("request-id")}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,i,{logger:r}={}){let o=new e(n,{logger:r});for(let a of n.messages)o._addMessageParam(a);return ie(o,xi,{...n,stream:!0},"f"),o._run(()=>o._createMessage(t,{...n,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(t){t().then(()=>{this._emitFinal(),this._emit("end")},N(this,up,"f"))}_addMessageParam(t){this.messages.push(t)}_addMessage(t,n=!0){this.receivedMessages.push(t),n&&this._emit("message",t)}async _createMessage(t,n,i){let r=i?.signal,o;r&&(r.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),r.addEventListener("abort",o));try{N(this,on,"m",lp).call(this);let{response:a,data:s}=await t.create({...n,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(a);for await(let d of s)N(this,on,"m",cp).call(this,d);if(s.controller.signal?.aborted)throw new Qt;N(this,on,"m",pp).call(this)}finally{r&&o&&r.removeEventListener("abort",o)}}_connected(t){this.ended||(ie(this,yd,t,"f"),ie(this,_d,t?.headers.get("request-id"),"f"),N(this,fd,"f").call(this,t),this._emit("connect"))}get ended(){return N(this,la,"f")}get errored(){return N(this,hd,"f")}get aborted(){return N(this,gd,"f")}abort(){this.controller.abort()}on(t,n){return(N(this,Zn,"f")[t]||(N(this,Zn,"f")[t]=[])).push({listener:n}),this}off(t,n){let i=N(this,Zn,"f")[t];if(!i)return this;let r=i.findIndex(o=>o.listener===n);return r>=0&&i.splice(r,1),this}once(t,n){return(N(this,Zn,"f")[t]||(N(this,Zn,"f")[t]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,i)=>{ie(this,Ur,!0,"f"),t!=="error"&&this.once("error",i),this.once(t,n)})}async done(){ie(this,Ur,!0,"f"),await N(this,da,"f")}get currentMessage(){return N(this,cr,"f")}async finalMessage(){return await this.done(),N(this,on,"m",dp).call(this)}async finalText(){return await this.done(),N(this,on,"m",pb).call(this)}_emit(t,...n){if(N(this,la,"f"))return;t==="end"&&(ie(this,la,!0,"f"),N(this,md,"f").call(this));let i=N(this,Zn,"f")[t];if(i&&(N(this,Zn,"f")[t]=i.filter(r=>!r.once),i.forEach(({listener:r})=>r(...n))),t==="abort"){let r=n[0];!N(this,Ur,"f")&&!i?.length&&Promise.reject(r),N(this,sa,"f").call(this,r),N(this,ua,"f").call(this,r),this._emit("end");return}if(t==="error"){let r=n[0];!N(this,Ur,"f")&&!i?.length&&Promise.reject(r),N(this,sa,"f").call(this,r),N(this,ua,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",N(this,on,"m",dp).call(this))}async _fromReadableStream(t,n){let i=n?.signal,r;i&&(i.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),i.addEventListener("abort",r));try{N(this,on,"m",lp).call(this),this._connected(null);let o=Zr.fromReadableStream(t,this.controller);for await(let a of o)N(this,on,"m",cp).call(this,a);if(o.controller.signal?.aborted)throw new Qt;N(this,on,"m",pp).call(this)}finally{i&&r&&i.removeEventListener("abort",r)}}[(cr=new WeakMap,xi=new WeakMap,aa=new WeakMap,fd=new WeakMap,sa=new WeakMap,da=new WeakMap,md=new WeakMap,ua=new WeakMap,Zn=new WeakMap,la=new WeakMap,hd=new WeakMap,gd=new WeakMap,Ur=new WeakMap,yd=new WeakMap,_d=new WeakMap,ca=new WeakMap,up=new WeakMap,on=new WeakSet,dp=function(){if(this.receivedMessages.length===0)throw new me("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},pb=function(){if(this.receivedMessages.length===0)throw new me("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new me("stream ended without producing a content block with type=text");return t.join(" ")},lp=function(){this.ended||ie(this,cr,void 0,"f")},cp=function(t){if(this.ended)return;let n=N(this,on,"m",fb).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let i=n.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{hb(i)&&i.input&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(cb(n,N(this,xi,"f"),{logger:N(this,ca,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{ie(this,cr,n,"f");break}case"content_block_start":case"message_delta":break}},pp=function(){if(this.ended)throw new me("stream has ended, this shouldn't happen");let t=N(this,cr,"f");if(!t)throw new me("request ended without sending any chunks");return ie(this,cr,void 0,"f"),cb(t,N(this,xi,"f"),{logger:N(this,ca,"f")})},fb=function(t){let n=N(this,cr,"f");if(t.type==="message_start"){if(n)throw new me(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new me(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push({...t.content_block}),n;case"content_block_delta":{let i=n.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(n.content[t.index]={...i,text:(i.text||"")+t.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[t.index]={...i,citations:[...i.citations??[],t.delta.citation]});break}case"input_json_delta":{if(i&&hb(i)){let r=i[mb]||"";r+=t.delta.partial_json;let o={...i};Object.defineProperty(o,mb,{value:r,enumerable:!1,writable:!0}),r&&(o.input=Ik(r)),n.content[t.index]=o}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[t.index]={...i,thinking:i.thinking+t.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[t.index]={...i,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let t=[],n=[],i=!1;return this.on("streamEvent",r=>{let o=n.shift();o?o.resolve(r):t.push(r)}),this.on("end",()=>{i=!0;for(let r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{i=!0;for(let o of n)o.reject(r);n.length=0}),this.on("error",r=>{i=!0;for(let o of n)o.reject(r);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((r,o)=>n.push({resolve:r,reject:o})).then(r=>r?{value:r,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Zr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},fu=class extends Ge{create(t,n){return this._client.post("/v1/messages/batches",{body:t,...n})}retrieve(t,n){return this._client.get(de`/v1/messages/batches/${t}`,n)}list(t={},n){return this._client.getAPIList("/v1/messages/batches",Qr,{query:t,...n})}delete(t,n){return this._client.delete(de`/v1/messages/batches/${t}`,n)}cancel(t,n){return this._client.post(de`/v1/messages/batches/${t}/cancel`,n)}async results(t,n){let i=await this.retrieve(t);if(!i.results_url)throw new me(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);return this._client.get(i.results_url,{...n,headers:H([{Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,o)=>iu.fromResponse(o.response,o.controller))}},Fa=class extends Ge{constructor(){super(...arguments),this.batches=new fu(this._client)}create(t,n){t.model in gb&&console.warn(`The model '${t.model}' is deprecated and will reach end-of-life on ${gb[t.model]}
75
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),lD.includes(t.model)&&t.thinking&&t.thinking.type==="enabled"&&console.warn(`Using Claude with ${t.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let i=this._client._options.timeout;if(!t.stream&&i==null){let o=xk[t.model]??void 0;i=this._client.calculateNonstreamingTimeout(t.max_tokens,o)}let r=kk(t.tools,t.messages);return this._client.post("/v1/messages",{body:t,timeout:i??6e5,...n,headers:H([r,n?.headers]),stream:t.stream??!1})}parse(t,n){return this.create(t,n).then(i=>Ek(i,t,{logger:this._client.logger??console}))}stream(t,n){return Zp.createMessage(this,t,n,{logger:this._client.logger??console})}countTokens(t,n){return this._client.post("/v1/messages/count_tokens",{body:t,...n})}},gb={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"},lD=["claude-mythos-preview","claude-opus-4-6"];Fa.Batches=fu;mu=class extends Ge{retrieve(t,n={},i){let{betas:r}=n??{};return this._client.get(de`/v1/models/${t}`,{...i,headers:H([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},i?.headers])})}list(t={},n){let{betas:i,...r}=t??{};return this._client.getAPIList("/v1/models",Qr,{query:r,...n,headers:H([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}},cD="\\n\\nHuman:",pD="\\n\\nAssistant:",it=class{get credentials(){return this._authState.provider}constructor({baseURL:t=Ue("ANTHROPIC_BASE_URL"),apiKey:n,authToken:i,...r}={}){if(Qp.add(this),this._requestAuthFlags=new WeakMap,Ad.set(this,void 0),n===void 0&&(n=r.profile!=null?null:Ue("ANTHROPIC_API_KEY")??null),i===void 0&&(i=r.profile!=null?null:Ue("ANTHROPIC_AUTH_TOKEN")??null),r.profile!=null&&(r.credentials!=null||r.config!=null))throw TypeError("Pass at most one of `profile`, `credentials`, or `config`.");let o={apiKey:n,authToken:i,...r,baseURL:t||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&pN())throw new me(`It looks like you're running in a browser-like environment.
76
+
77
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
78
+ If you understand the risks and have appropriate mitigations in place,
79
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
80
+
81
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
82
+ `);this.baseURL=o.baseURL,this._baseURLIsExplicit=r.__baseURLIsExplicit??!!t,this.timeout=o.timeout??Cm.DEFAULT_TIMEOUT,this.logger=o.logger??console;let a="warn";this.logLevel=a,this.logLevel=Qv(o.logLevel,"ClientOptions.logLevel",this)??Qv(Ue("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??gN(),ie(this,Ad,_N,"f");let s=Ue("ANTHROPIC_CUSTOM_HEADERS");if(s){let u={};for(let l of s.split(`
83
+ `)){let p=l.indexOf(":");p>=0&&(u[l.substring(0,p).trim()]=l.substring(p+1).trim())}o.defaultHeaders={...u,...o.defaultHeaders}}let d=r.__auth;if(delete o.__auth,delete o.__baseURLIsExplicit,this._options=o,this.apiKey=typeof n=="string"?n:null,this.authToken=i,d)this._authState=d,!this._baseURLIsExplicit&&d.baseURL&&(this.baseURL=d.baseURL);else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let u=o.credentials??null;if(u)this._authState.provider=u,this._authState.tokenCache=this._makeTokenCache(u);else if(o.config!=null){let l=mk(o.config,this._credentialResolverOptions());this._authState.provider=l.provider,this._authState.tokenCache=this._makeTokenCache(l.provider),this._authState.extraHeaders=l.extraHeaders,this._applyCredentialBaseURL(l.baseURL)}else o.profile!=null?this._authState.resolution=this._resolveDefaultCredentials(o.profile):this._authState.resolution=this._resolveDefaultCredentials()}}_applyCredentialBaseURL(t){if(!t)return;let n=t.replace(/\/+$/,"");this._authState.baseURL=n,!this._baseURLIsExplicit&&(this.baseURL=n)}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this.fetch,userAgent:this.getUserAgent(),onCacheWriteError:t=>{gt(this).debug("credential cache write failed (best-effort)",t)},onSafetyWarning:t=>{gt(this).warn(t)}}}_makeTokenCache(t){return new Bp(t,n=>{gt(this).debug("advisory token refresh failed; serving cached token",n)})}withOptions(t){let n="credentials"in t||"config"in t||"profile"in t,i="apiKey"in t||"authToken"in t||n,r={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,credentials:this.credentials,...n?{credentials:void 0,config:void 0,profile:void 0}:{},...t,__auth:i?void 0:this._authState,__baseURLIsExplicit:"baseURL"in t?!0:this._baseURLIsExplicit};return new this.constructor(r)}async _resolveDefaultCredentials(t){try{let n=await qN(this._credentialResolverOptions(),t);if(n)this._authState.provider=n.provider,this._authState.tokenCache=this._makeTokenCache(n.provider),this._authState.extraHeaders=n.extraHeaders,this._applyCredentialBaseURL(n.baseURL);else if(t!=null)throw new me(`Profile "${t}" could not be resolved (no <config_dir>/configs/${t}.json found).`)}catch(n){this._authState.error=n}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:n}){if(!(t.get("x-api-key")||t.get("authorization"))){if(this._authState.error)throw this._authState.error;if(!(this._authState.tokenCache||this._authState.resolution)&&!(this.apiKey&&t.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&t.get("authorization"))&&!n.has("authorization"))throw Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}}_authFlags(t){let n=this._requestAuthFlags.get(t);return n||(n={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set(t,n)),n}async authHeaders(t){if(this._authState.resolution&&await this._authState.resolution,!this._authState.error){if(this._authState.tokenCache&&this.apiKey==null){let n=await this._authState.tokenCache.getToken();return this._authFlags(t).usedTokenCache=!0,H([{Authorization:`Bearer ${n}`}])}return H([await this.apiKeyAuth(t),await this.bearerAuth(t)])}}async apiKeyAuth(t){if(this.apiKey!=null)return H([{"X-Api-Key":this.apiKey}])}async bearerAuth(t){if(this.authToken!=null)return H([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(t){return vN(t)}getUserAgent(){return`${this.constructor.name}/JS ${gr}`}defaultIdempotencyKey(){return`stainless-node-retry-${nk()}`}makeStatusError(t,n,i,r){return Rt.generate(t,n,i,r)}buildURL(t,n,i){let r=!N(this,Qp,"m",Rk).call(this)&&i||this.baseURL,o=dN(t)?new URL(t):new URL(r+(r.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery(),s=Object.fromEntries(o.searchParams);return(!Bv(a)||!Bv(s))&&(n={...s,...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(o.search=this.stringifyQuery(n)),o.toString()}_calculateNonstreamingTimeout(t){if(3600*t/128e3>600)throw new me("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 6e5}async prepareOptions(t){}async prepareRequest(t,{url:n,options:i}){if(this._authState.tokenCache&&this.apiKey==null){let r=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[o,a]of Object.entries(this._authState.extraHeaders))r.has(o)||r.set(o,a);r.get("anthropic-beta")?.split(",").map(o=>o.trim())?.includes(Hd)||r.append("anthropic-beta",Hd),t.headers=r}}get(t,n){return this.methodRequest("get",t,n)}post(t,n){return this.methodRequest("post",t,n)}patch(t,n){return this.methodRequest("patch",t,n)}put(t,n){return this.methodRequest("put",t,n)}delete(t,n){return this.methodRequest("delete",t,n)}methodRequest(t,n,i){return this.request(Promise.resolve(i).then(r=>({method:t,path:n,...r})))}request(t,n=null){return new Vd(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,i){let r=await t,o=r.maxRetries??this.maxRetries;n==null&&(n=o,this._requestAuthFlags.delete(r)),await this.prepareOptions(r);let{req:a,url:s,timeout:d}=await this.buildRequest(r,{retryCount:o-n});await this.prepareRequest(a,{url:s,options:r});let u="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),l=i===void 0?"":`, retryOf: ${i}`,p=Date.now();if(gt(this).debug(`[${u}] sending request`,zr({retryOfRequestLogID:i,method:r.method,url:s,options:r,headers:a.headers})),r.signal?.aborted)throw new Qt;let m=new AbortController,f=await this.fetchWithTimeout(s,a,d,m).catch(Up),h=Date.now();if(f instanceof globalThis.Error){let g=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new Qt;let v=Na(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(n)return gt(this).info(`[${u}] connection ${v?"timed out":"failed"} - ${g}`),gt(this).debug(`[${u}] connection ${v?"timed out":"failed"} (${g})`,zr({retryOfRequestLogID:i,url:s,durationMs:h-p,message:f.message})),this.retryRequest(r,n,i??u);throw gt(this).info(`[${u}] connection ${v?"timed out":"failed"} - error; no more retries left`),gt(this).debug(`[${u}] connection ${v?"timed out":"failed"} (error; no more retries left)`,zr({retryOfRequestLogID:i,url:s,durationMs:h-p,message:f.message})),v?new Dd:new Ki({cause:f})}let y=[...f.headers.entries()].filter(([g])=>g==="request-id").map(([g,v])=>", "+g+": "+JSON.stringify(v)).join(""),w=`[${u}${l}${y}] ${a.method} ${s} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${h-p}ms`;if(!f.ok){let g=await this.shouldRetry(f,r);if(n&&g){let C=`retrying, ${n} attempts remaining`;return await yN(f.body),gt(this).info(`${w} - ${C}`),gt(this).debug(`[${u}] response error (${C})`,zr({retryOfRequestLogID:i,url:f.url,status:f.status,headers:f.headers,durationMs:h-p})),this.retryRequest(r,n,i??u,f.headers)}let v=g?"error; no more retries left":"error; not retryable";gt(this).info(`${w} - ${v}`);let b=await f.text().catch(C=>Up(C).message),S=rk(b),T=S?void 0:b;throw gt(this).debug(`[${u}] response error (${v})`,zr({retryOfRequestLogID:i,url:f.url,status:f.status,headers:f.headers,message:T,durationMs:Date.now()-p})),this.makeStatusError(f.status,S,T,f.headers)}return gt(this).info(w),gt(this).debug(`[${u}] response start`,zr({retryOfRequestLogID:i,url:f.url,status:f.status,headers:f.headers,durationMs:h-p})),{response:f,options:r,controller:m,requestLogID:u,retryOfRequestLogID:i,startTime:p}}getAPIList(t,n,i){return this.requestAPIList(n,i&&"then"in i?i.then(r=>({method:"get",path:t,...r})):{method:"get",path:t,...i})}requestAPIList(t,n){let i=this.makeRequest(n,null,void 0);return new Jp(this,i,t)}async fetchWithTimeout(t,n,i,r){let{signal:o,method:a,...s}=n||{},d=this._makeAbort(r);o&&o.addEventListener("abort",d,{once:!0});let u=setTimeout(d,i),l=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body=="object"&&s.body!==null&&Symbol.asyncIterator in s.body,p={signal:r.signal,...l?{duplex:"half"}:{},method:"GET",...s};a&&(p.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,p)}finally{clearTimeout(u)}}async shouldRetry(t,n){let i=this._authFlags(n);if(t.status===401&&this._authState.tokenCache&&i.usedTokenCache&&!i.didRefreshFor401)return i.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,n,i,r){let o,a=r?.get("retry-after-ms");if(a){let d=parseFloat(a);Number.isNaN(d)||(o=d)}let s=r?.get("retry-after");if(s&&!o){let d=parseFloat(s);Number.isNaN(d)?o=Date.parse(s)-Date.now():o=d*1e3}if(o===void 0){let d=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(n,d)}return await cN(o),this.makeRequest(t,n-1,i)}calculateDefaultRetryTimeoutMillis(t,n){let i=n-t,r=Math.min(.5*Math.pow(2,i),8),o=1-Math.random()*.25;return r*o*1e3}calculateNonstreamingTimeout(t,n){if(36e5*t/128e3>6e5||n!=null&&t>n)throw new me("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(t,{retryCount:n=0}={}){let i={...t},{method:r,path:o,query:a,defaultBaseURL:s}=i;this._authState.resolution&&await this._authState.resolution,!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL&&(this.baseURL=this._authState.baseURL);let d=this.buildURL(o,a,s);"timeout"in i&&lN("timeout",i.timeout),i.timeout=i.timeout??this.timeout;let{bodyHeaders:u,body:l}=this.buildBody({options:i}),p=await this.buildHeaders({options:t,method:r,bodyHeaders:u,retryCount:n});return{req:{method:r,headers:p,...i.signal&&{signal:i.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...i.fetchOptions??{}},url:d,timeout:i.timeout}}async buildHeaders({options:t,method:n,bodyHeaders:i,retryCount:r}){let o={};this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let a=H([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...vm(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(t),this._options.defaultHeaders,i,t.headers]);return this.validateHeaders(a),a.values}_makeAbort(t){return()=>t.abort()}buildBody({options:{body:t,headers:n}}){if(!t)return{bodyHeaders:void 0,body:void 0};let i=H([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&i.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:ok(t)}:typeof t=="object"&&i.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t)}:N(this,Ad,"f").call(this,{body:t,headers:i})}};Cm=it,Ad=new WeakMap,Qp=new WeakSet,Rk=function(){return this.baseURL!=="https://api.anthropic.com"};it.Anthropic=Cm;it.HUMAN_PROMPT=cD;it.AI_PROMPT=pD;it.DEFAULT_TIMEOUT=6e5;it.AnthropicError=me;it.APIError=Rt;it.APIConnectionError=Ki;it.APIConnectionTimeoutError=Dd;it.APIUserAbortError=Qt;it.NotFoundError=zd;it.ConflictError=Bd;it.RateLimitError=Jd;it.BadRequestError=Ld;it.AuthenticationError=Ud;it.InternalServerError=Wd;it.PermissionDeniedError=Fd;it.UnprocessableEntityError=Kd;it.toFile=ZN;Hi=class extends it{constructor(){super(...arguments),this.completions=new pu(this),this.messages=new Fa(this),this.models=new mu(this),this.beta=new qt(this)}};Hi.Completions=pu;Hi.Messages=Fa;Hi.Models=mu;Hi.Beta=qt;Cn=class extends Error{telemetryMessage;constructor(t,n){super(t),this.name="TelemetrySafeError",this.telemetryMessage=n??t}},fD=(e,t)=>e!==null&&typeof e=="object"&&!("telemetryMessage"in e)?Object.assign(e,{telemetryMessage:t}):e;ID=new Set(["EXDEV","EPERM","EEXIST","EBUSY"]),PD=new Set(["EPERM","EBUSY","EACCES"]),ED=4,RD=50,rae=new Int32Array(new SharedArrayBuffer(4));$D=new Set(["ENOSPC","EIO","EDQUOT","EFBIG"]);Yp=class{read(t){return bb(t,"utf8")}readBytes(t){return bb(t)}write(t,n,i){return fp(t,n,{encoding:"utf8",mode:i})}async mkdir(t){try{await vD(t,{recursive:!0})}catch(n){if(Pt(n)!=="EEXIST")throw n}}atomicWrite(t,n,i){return MD(t,n,i)}delete(t){return wD(t)}list(t){return vb(t)}append(t,n,i){return yD(t,n,{encoding:"utf8",mode:i})}writeExclusive(t,n,i){return fp(t,n,{encoding:"utf8",flag:"wx",mode:i})}writeBytes(t,n){return fp(t,n)}copy(t,n){return _D(t,n)}async stat(t){return{mtimeMs:(await bD(t)).mtimeMs}}async listEntries(t){return(await vb(t,{withFileTypes:!0})).map(n=>({name:n.name,isDirectory:n.isDirectory(),isFile:n.isFile()}))}async readRange(t,n,i){hp("readRange","offset",n),hp("readRange","length",i);let r=await _b(t,"r");try{return await wb(r,n,i)}finally{await r.close()}}async readTail(t,n){hp("readTail","maxBytes",n);let i=await _b(t,"r");try{let{size:r}=await i.stat(),o=Math.min(n,r);return await wb(i,r-o,o)}finally{await i.close()}}};jD=new gD;Ci=null;DD=ND;UD=LD;zD=FD;KD=BD,JD=200;HD=WD;vo.prototype.clear=DD;vo.prototype.delete=UD;vo.prototype.get=zD;vo.prototype.has=KD;vo.prototype.set=HD;Ea=vo,GD=(function(){try{var e=oi(Object,"defineProperty");return e({},"",{}),e}catch{}})(),gu=GD;Tm=VD,ZD=Object.prototype,QD=ZD.hasOwnProperty;$k=YD;eL=XD;nL=tL;Sr=rL,iL="[object Arguments]";Sb=oL,Mk=Object.prototype,aL=Mk.hasOwnProperty,sL=Mk.propertyIsEnumerable,dL=Sb((function(){return arguments})())?Sb:function(e){return Sr(e)&&aL.call(e,"callee")&&!sL.call(e,"callee")},za=dL,uL=Array.isArray,pn=uL,ba={};Fn(ba,{default:()=>Ba});cL=lL,jk=typeof ba=="object"&&ba&&!ba.nodeType&&ba,kb=jk&&typeof wd=="object"&&wd&&!wd.nodeType&&wd,pL=kb&&kb.exports===jk,xb=pL?zn.Buffer:void 0,fL=xb?xb.isBuffer:void 0,mL=fL||cL,Ba=mL,hL=9007199254740991,gL=/^(?:0|[1-9]\d*)$/;hl=yL,_L=9007199254740991;Im=vL,bL="[object Arguments]",wL="[object Array]",SL="[object Boolean]",kL="[object Date]",xL="[object Error]",CL="[object Function]",TL="[object Map]",IL="[object Number]",PL="[object Object]",EL="[object RegExp]",RL="[object Set]",OL="[object String]",AL="[object WeakMap]",$L="[object ArrayBuffer]",ML="[object DataView]",jL="[object Float32Array]",qL="[object Float64Array]",NL="[object Int8Array]",DL="[object Int16Array]",LL="[object Int32Array]",UL="[object Uint8Array]",FL="[object Uint8ClampedArray]",zL="[object Uint16Array]",BL="[object Uint32Array]",We={};We[jL]=We[qL]=We[NL]=We[DL]=We[LL]=We[UL]=We[FL]=We[zL]=We[BL]=!0;We[bL]=We[wL]=We[$L]=We[SL]=We[ML]=We[kL]=We[xL]=We[CL]=We[TL]=We[IL]=We[PL]=We[EL]=We[RL]=We[OL]=We[AL]=!1;JL=KL;HL=WL,wa={};Fn(wa,{default:()=>Xp});qk=typeof wa=="object"&&wa&&!wa.nodeType&&wa,Ra=qk&&typeof Ed=="object"&&Ed&&!Ed.nodeType&&Ed,GL=Ra&&Ra.exports===qk,gp=GL&&ek.process,VL=(function(){try{var e=Ra&&Ra.require&&Ra.require("util").types;return e||gp&&gp.binding&&gp.binding("util")}catch{}})(),Xp=VL,Cb=Xp&&Xp.isTypedArray,ZL=Cb?HL(Cb):JL,Pm=ZL,QL=Object.prototype,YL=QL.hasOwnProperty;Nk=XL,eU=Object.prototype;Em=tU;Dk=nU,rU=Dk(Object.keys,Object),iU=rU,oU=Object.prototype,aU=oU.hasOwnProperty;dU=sU;gl=uU;Lk=lU;pU=cU,fU=Object.prototype,mU=fU.hasOwnProperty;gU=hU;Rm=yU,Sa={};Fn(Sa,{default:()=>Fk});Uk=typeof Sa=="object"&&Sa&&!Sa.nodeType&&Sa,Tb=Uk&&typeof Od=="object"&&Od&&!Od.nodeType&&Od,_U=Tb&&Tb.exports===Uk,Ib=_U?zn.Buffer:void 0,Pb=Ib?Ib.allocUnsafe:void 0;Fk=vU;wU=bU;kU=SU;zk=xU,CU=Object.prototype,TU=CU.propertyIsEnumerable,Eb=Object.getOwnPropertySymbols,IU=Eb?function(e){return e==null?[]:(e=Object(e),kU(Eb(e),function(t){return TU.call(e,t)}))}:zk,Bk=IU;Om=PU,EU=Dk(Object.getPrototypeOf,Object),Am=EU,RU=Object.getOwnPropertySymbols,OU=RU?function(e){for(var t=[];e;)Om(t,Bk(e)),e=Am(e);return t}:zk,AU=OU;Kk=$U;Rb=MU;qU=jU,NU=oi(zn,"DataView"),ef=NU,DU=oi(zn,"Promise"),tf=DU,LU=oi(zn,"Set"),nf=LU,UU=oi(zn,"WeakMap"),rf=UU,Ob="[object Map]",FU="[object Object]",Ab="[object Promise]",$b="[object Set]",Mb="[object WeakMap]",jb="[object DataView]",zU=ii(ef),BU=ii(qa),KU=ii(tf),JU=ii(nf),WU=ii(rf),Br=ri;(ef&&Br(new ef(new ArrayBuffer(1)))!=jb||qa&&Br(new qa)!=Ob||tf&&Br(tf.resolve())!=Ab||nf&&Br(new nf)!=$b||rf&&Br(new rf)!=Mb)&&(Br=function(e){var t=ri(e),n=t==FU?e.constructor:void 0,i=n?ii(n):"";if(i)switch(i){case zU:return jb;case BU:return Ob;case KU:return Ab;case JU:return $b;case WU:return Mb}return t});qb=Br,HU=zn.Uint8Array,yu=HU;VU=GU;QU=ZU,Nb=Object.create,YU=(function(){function e(){}return function(t){if(!Dn(t))return{};if(Nb)return Nb(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}})(),XU=YU;tF=eF,nF="__lodash_hash_undefined__";iF=rF;aF=oF;_u.prototype.add=_u.prototype.push=iF;_u.prototype.has=aF;sF=_u;uF=dF;cF=lF,pF=1,fF=2;Jk=mF;gF=hF;_F=yF,vF=1,bF=2,wF="[object Boolean]",SF="[object Date]",kF="[object Error]",xF="[object Map]",CF="[object Number]",TF="[object RegExp]",IF="[object Set]",PF="[object String]",EF="[object Symbol]",RF="[object ArrayBuffer]",OF="[object DataView]",Lb=Nn?Nn.prototype:void 0,yp=Lb?Lb.valueOf:void 0;$F=AF,MF=1,jF=Object.prototype,qF=jF.hasOwnProperty;DF=NF,LF=1,Ub="[object Arguments]",Fb="[object Array]",vd="[object Object]",UF=Object.prototype,zb=UF.hasOwnProperty;zF=FF;Hk=Wk,BF=1,KF=2;WF=JF;Gk=HF;VF=GF;Vk=ZF;YF=QF,XF="[object Symbol]";$m=ez,tz=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,nz=/^\w*$/;Mm=rz,iz=500;az=oz,sz=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,dz=/\\(\\)?/g,uz=az(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(sz,function(n,i,r,o){t.push(r?o.replace(dz,"$1"):i||n)}),t}),lz=uz;Zk=cz,pz=1/0,Bb=Nn?Nn.prototype:void 0,Kb=Bb?Bb.toString:void 0;fz=Qk;hz=mz;yl=gz,yz=1/0;gs=_z;jm=vz;wz=bz;kz=Sz;Cz=xz;Yk=Tz,Iz=1,Pz=2;Rz=Ez;qm=Oz;$z=Az;jz=Mz;Nz=qz;Xk=Dz,ex="[\\w-]{1,63}",uae=new RegExp(`^${ex}$`),lae=new RegExp(`^a(?:${ex}-)?[0-9a-f]{16}$`);zz="3ab19d7e-9f35-45c2-926e-75e271cc60b3";Nm=null;vu=new Map;Dm=new Map;i2={renderTarget:"ink",workspace:"local",canDrive:!0,transcriptSource:"local-jsonl",remote:null};a2=o2(),s2=()=>{};d2=fs(),cae=d2.subscribe;u2=fs(),pae=u2.subscribe,l2=fs(),fae=l2.subscribe,c2=fs(),mae=c2.subscribe,p2=fs(),hae=p2.subscribe;bu=class{#r=new Set;register(t){let n=_2(t);this.#r.add(n);let i=()=>{this.#r.delete(n)};return Object.assign(i,{[Symbol.dispose]:i})}async drain(){let t=Array.from(this.#r);this.#r.clear(),await Promise.all(t.map(async n=>n()))}async[Symbol.asyncDispose](){await this.drain()}get sizeForTesting(){return this.#r.size}},v2=new bu;_ae=new bu,b2=vt(e=>{if(!e||e.trim()==="")return null;let t=e.split(",").map(o=>o.trim()).filter(Boolean);if(t.length===0)return null;let n=t.some(o=>o.startsWith("!")),i=t.some(o=>!o.startsWith("!"));if(n&&i)return null;let r=t.map(o=>o.replace(/^!/,"").toLowerCase());return{include:n?[]:r,exclude:n?r:[],isExclusive:n}});bd="\u2192";U2={cwd(){return process.cwd()},existsSync(e){let t=[];try{let r=Xe(t,tt`fs.existsSync(${e})`,0);return _e.existsSync(e)}catch(r){var n=r,i=1}finally{et(t,n,i)}},async stat(e){return q2(e)},async lstat(e){return P2(e)},async readdir(e){return R2(e,{withFileTypes:!0})},async unlink(e){return D2(e)},async rmdir(e){return M2(e)},async rm(e,t){return j2(e,t)},async mkdir(e,t){try{await E2(e,{recursive:!0,...t})}catch(n){if(Pt(n)!=="EEXIST")throw n}},async readFile(e,t){return Vb(e,{encoding:t.encoding})},async rename(e,t){return $2(e,t)},async realpath(e){return Bi(await A2(e))},async readlink(e){return O2(e)},async copyFile(e,t){return T2(e,t)},async appendFile(e,t,n){if(n?.mode!==void 0)try{let i=await Gb(e,"ax",n.mode);try{await i.appendFile(t)}finally{await i.close()}return}catch(i){if(Pt(i)!=="EEXIST")throw i}return x2(e,t)},async symlink(e,t,n){return N2(e,t,n)},async link(e,t){return I2(e,t)},async chmod(e,t){return C2(e,t)},statSync(e){let t=[];try{let r=Xe(t,tt`fs.statSync(${e})`,0);return _e.statSync(e)}catch(r){var n=r,i=1}finally{et(t,n,i)}},lstatSync(e){let t=[];try{let r=Xe(t,tt`fs.lstatSync(${e})`,0);return _e.lstatSync(e)}catch(r){var n=r,i=1}finally{et(t,n,i)}},readFileSync(e,t){let n=[];try{let o=Xe(n,tt`fs.readFileSync(${e})`,0);return _e.readFileSync(e,{encoding:t.encoding})}catch(o){var i=o,r=1}finally{et(n,i,r)}},readFileBytesSync(e){let t=[];try{let r=Xe(t,tt`fs.readFileBytesSync(${e})`,0);return _e.readFileSync(e)}catch(r){var n=r,i=1}finally{et(t,n,i)}},readSync(e,t){let n=[];try{let o=Xe(n,tt`fs.readSync(${e}, ${t.length} bytes)`,0),a;try{a=_e.openSync(e,"r");let s=Buffer.alloc(t.length),d=_e.readSync(a,s,0,t.length,0);return{buffer:s,bytesRead:d}}finally{a&&_e.closeSync(a)}}catch(o){var i=o,r=1}finally{et(n,i,r)}},appendFileSync(e,t,n){let i=[];try{let a=Xe(i,tt`fs.appendFileSync(${e}, ${t.length} chars)`,0);if(n?.mode!==void 0)try{let s=_e.openSync(e,"ax",n.mode);try{_e.appendFileSync(s,t)}finally{_e.closeSync(s)}return}catch(s){if(Pt(s)!=="EEXIST")throw s}_e.appendFileSync(e,t)}catch(a){var r=a,o=1}finally{et(i,r,o)}},copyFileSync(e,t){let n=[];try{let o=Xe(n,tt`fs.copyFileSync(${e} ${bd} ${t})`,0);_e.copyFileSync(e,t)}catch(o){var i=o,r=1}finally{et(n,i,r)}},unlinkSync(e){let t=[];try{let r=Xe(t,tt`fs.unlinkSync(${e})`,0);_e.unlinkSync(e)}catch(r){var n=r,i=1}finally{et(t,n,i)}},renameSync(e,t){let n=[];try{let o=Xe(n,tt`fs.renameSync(${e} ${bd} ${t})`,0);_e.renameSync(e,t)}catch(o){var i=o,r=1}finally{et(n,i,r)}},linkSync(e,t){let n=[];try{let o=Xe(n,tt`fs.linkSync(${e} ${bd} ${t})`,0);_e.linkSync(e,t)}catch(o){var i=o,r=1}finally{et(n,i,r)}},symlinkSync(e,t,n){let i=[];try{let a=Xe(i,tt`fs.symlinkSync(${e} ${bd} ${t})`,0);_e.symlinkSync(e,t,n)}catch(a){var r=a,o=1}finally{et(i,r,o)}},readlinkSync(e){let t=[];try{let r=Xe(t,tt`fs.readlinkSync(${e})`,0);return _e.readlinkSync(e)}catch(r){var n=r,i=1}finally{et(t,n,i)}},realpathSync(e){let t=[];try{let r=Xe(t,tt`fs.realpathSync(${e})`,0);return Bi(_e.realpathSync(e))}catch(r){var n=r,i=1}finally{et(t,n,i)}},mkdirSync(e,t){let n=[];try{let o=Xe(n,tt`fs.mkdirSync(${e})`,0),a={recursive:!0};t?.mode!==void 0&&(a.mode=t.mode);try{_e.mkdirSync(e,a)}catch(s){if(Pt(s)!=="EEXIST")throw s}}catch(o){var i=o,r=1}finally{et(n,i,r)}},readdirSync(e){let t=[];try{let r=Xe(t,tt`fs.readdirSync(${e})`,0);return _e.readdirSync(e,{withFileTypes:!0})}catch(r){var n=r,i=1}finally{et(t,n,i)}},readdirStringSync(e){let t=[];try{let r=Xe(t,tt`fs.readdirStringSync(${e})`,0);return _e.readdirSync(e)}catch(r){var n=r,i=1}finally{et(t,n,i)}},isDirEmptySync(e){let t=[];try{let r=Xe(t,tt`fs.isDirEmptySync(${e})`,0);return this.readdirSync(e).length===0}catch(r){var n=r,i=1}finally{et(t,n,i)}},rmdirSync(e){let t=[];try{let r=Xe(t,tt`fs.rmdirSync(${e})`,0);_e.rmdirSync(e)}catch(r){var n=r,i=1}finally{et(t,n,i)}},rmSync(e,t){let n=[];try{let o=Xe(n,tt`fs.rmSync(${e})`,0);_e.rmSync(e,t)}catch(o){var i=o,r=1}finally{et(n,i,r)}},createWriteStream(e){return _e.createWriteStream(e)},async readFileBytes(e,t){if(t===void 0)return Vb(e);let n=await Gb(e,"r");try{let{size:i}=await n.stat(),r=Math.min(i,t),o=Buffer.allocUnsafe(r),a=0;for(;a<r;){let{bytesRead:s}=await n.read(o,a,r-a,a);if(s===0)break;a+=s}return a<r?o.subarray(0,a):o}finally{await n.close()}}},F2=U2;W2=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Zb=typeof String.prototype.isWellFormed=="function"?Function.prototype.call.bind(String.prototype.isWellFormed):void 0,bae=typeof String.prototype.toWellFormed=="function"?Function.prototype.call.bind(String.prototype.toWellFormed):void 0;V2=/api[_-]?key|secret|token|password|passwd|credential|bearer|authorization|auth[_-]?header|cookie|session[_-]?(?:id|key)|connection[_-]?string|(?:private|ssh|encryption|signing|access|deploy|master|license)[_-]?key|client[_-]?secret/i,Qb="[^\\s,;&}\\])]+",ix="-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\\s\\S-]{64,}?-----END[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----",Z2=`[^\\s-]{0,4}${ix}['"\`]?`,Yb=`\\[REDACTED\\]|"[^"]*"|'[^']*'|(?:Bearer|Basic)\\s+(?:\\[REDACTED\\]|${Qb})|${Z2}|${Qb}`,Q2=["sk","ant","api"].join("-"),Y2=[{id:"url-userinfo",source:":\\/\\/([^/@\\s]+)@",confidence:"low"},{id:"gcp-service-account",source:"\\b([a-z0-9-]+@[a-z0-9-]+\\.iam\\.gserviceaccount\\.com)\\b",flags:"i",confidence:"low"},{id:"loose-anthropic-key",source:"\\b(sk-ant-?[\\w-]{10,})",confidence:"low"},{id:"http-auth-scheme",source:"\\b(?:Bearer|Basic)\\s+([A-Za-z0-9+/=._~-]{20,})",flags:"i",confidence:"low"},{id:"loose-jwt",source:"\\b(eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,})",confidence:"low"},{id:"sensitive-assign",source:`(?:${V2.source})[\\w.-]*["']?\\s*[=:]\\s*(${Yb})`,flags:"i",confidence:"low"},{id:"cloud-env-var",source:`\\b(?:AWS|GOOGLE|GCP|GCLOUD|AZURE)_\\w+\\s*[=:]\\s*(${Yb})`,flags:"i",confidence:"low"},{id:"aws-access-token",source:"\\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\\b",confidence:"high"},{id:"gcp-api-key",source:"\\b(AIza[\\w-]{35})(?![\\w-])",confidence:"high"},{id:"google-oauth-client-secret",source:"\\bGOCSPX-[\\w-]{28}(?![\\w-])",confidence:"high"},{id:"azure-ad-client-secret",source:`(?:^|[\\\\'"\\x60\\s>=:(,)])([a-zA-Z0-9_~.]{3}\\dQ~[a-zA-Z0-9_~.-]{31,34})(?:$|[\\\\'"\\x60\\s<),])`,confidence:"high"},{id:"digitalocean-pat",source:`\\b(dop_v1_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"digitalocean-access-token",source:`\\b(doo_v1_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"anthropic-api-key",source:`\\b(${Q2}03-[a-zA-Z0-9_\\-]{93}AA)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"anthropic-admin-api-key",source:`\\b(sk-ant-admin01-[a-zA-Z0-9_\\-]{93}AA)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"openai-api-key",source:"sk-[A-Za-z0-9_-]{8,200}T3BlbkFJ[A-Za-z0-9_-]{8,200}",confidence:"high"},{id:"openai-legacy-api-key",source:"\\bsk-[a-zA-Z0-9]{48}(?![a-zA-Z0-9])",confidence:"high"},{id:"huggingface-access-token",source:`\\b(hf_[a-zA-Z]{34})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"supabase-secret-key",source:"\\bsb_secret_[A-Za-z0-9_-]{20,}",confidence:"high"},{id:"supabase-access-token",source:"\\bsbp_[a-z0-9]{40,}",confidence:"high"},{id:"github-pat",source:"ghp_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-fine-grained-pat",source:"github_pat_\\w{82}",confidence:"high"},{id:"github-app-token",source:"(?:ghu|ghs)_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-oauth",source:"gho_[0-9a-zA-Z]{36}",confidence:"high"},{id:"github-refresh-token",source:"ghr_[0-9a-zA-Z]{36}",confidence:"high"},{id:"gitlab-pat",source:"glpat-[\\w-]{20}",confidence:"high"},{id:"gitlab-deploy-token",source:"gldt-[0-9a-zA-Z_\\-]{20}",confidence:"high"},{id:"slack-bot-token",source:"xoxb-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*",confidence:"high"},{id:"slack-user-token",source:"xox[pe](?:-[0-9]{10,13}){3}-[a-zA-Z0-9-]{28,34}",confidence:"high"},{id:"slack-app-token",source:"xapp-\\d-[A-Z0-9]+-\\d+-[a-z0-9]+",flags:"i",confidence:"high"},{id:"twilio-api-key",source:"SK[0-9a-fA-F]{32}",confidence:"high"},{id:"sendgrid-api-token",source:`\\b(SG\\.[a-zA-Z0-9=_\\-.]{66})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"npm-access-token",source:`\\b(npm_[a-zA-Z0-9]{36})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"pypi-upload-token",source:"pypi-AgEIcHlwaS5vcmc[\\w-]{50,1000}",confidence:"high"},{id:"databricks-api-token",source:`\\b(dapi[a-f0-9]{32}(?:-\\d)?)(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"hashicorp-tf-api-token",source:"[a-zA-Z0-9]{14}\\.atlasv1\\.[a-zA-Z0-9\\-_=]{60,70}",confidence:"high"},{id:"pulumi-api-token",source:`\\b(pul-[a-f0-9]{40})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"postman-api-token",source:`\\b(PMAK-[a-fA-F0-9]{24}-[a-fA-F0-9]{34})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-api-key",source:`\\b(eyJrIjoi[A-Za-z0-9+/]{70,400}={0,3})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-cloud-api-token",source:`\\b(glc_[A-Za-z0-9+/]{32,400}={0,3})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"grafana-service-account-token",source:`\\b(glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"sentry-user-token",source:`\\b(sntryu_[a-f0-9]{64})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"sentry-org-token",source:"\\bsntrys_eyJpYXQiO[a-zA-Z0-9+/]{10,200}(?:LCJyZWdpb25fdXJs|InJlZ2lvbl91cmwi|cmVnaW9uX3VybCI6)[a-zA-Z0-9+/]{10,200}={0,2}_[a-zA-Z0-9+/]{43}",confidence:"high"},{id:"stripe-access-token",source:`\\b((?:sk|rk)_(?:test|live|prod)_[a-zA-Z0-9]{10,99})(?:[\\x60'"\\s;]|\\\\[nr]|$)`,confidence:"high"},{id:"shopify-access-token",source:"shpat_[a-fA-F0-9]{32}",confidence:"high"},{id:"shopify-shared-secret",source:"shpss_[a-fA-F0-9]{32}",confidence:"high"},{id:"private-key",source:ix,flags:"i",confidence:"high"}],Xb=null;df={verbose:0,debug:1,info:2,warn:3,error:4},t4=vt(()=>{let e=process.env.CLAUDE_CODE_DEBUG_LOG_LEVEL?.toLowerCase().trim();return e&&Object.hasOwn(df,e)?e:"debug"}),n4=!1;ox=vt(()=>{let e=_l();return n4||kt(process.env.DEBUG)||kt(process.env.DEBUG_SDK)||e.includes("--debug")||e.includes("-d")||ax()||e.some(t=>t.startsWith("--debug="))||sx()!==null}),r4=vt(()=>{let e=_l().find(n=>n.startsWith("--debug="));if(!e)return null;let t=e.substring(8);return b2(t)}),ax=vt(()=>{let e=_l();return e.includes("--debug-to-stderr")||e.includes("-d2e")}),sx=vt(()=>{let e=_l();for(let t=0;t<e.length;t++){let n=e[t];if(n.startsWith("--debug-file="))return ew(n.substring(13));if(n==="--debug-file"&&t+1<e.length)return ew(e[t+1])}return null});o4=!1,a4=10485760,pa=null,_p=Promise.resolve(),Oi=[],ka=null,tw=null,fa=-1,vp=!1,uf=null;c4=vt(async()=>{try{let e=lf(),t=sf(e),n=Um(t,"latest");await af(n).catch(()=>{}),await h2(e,n)}catch{}}),wae=(()=>{let e=process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;if(e!==void 0){let t=Number(e);if(!Number.isNaN(t)&&t>=0)return t}return 1/0})(),p4={[Symbol.dispose](){}};tt=f4;Rn=(e,t)=>{let n=[];try{let o=Xe(n,tt`JSON.parse(${e})`,0);return typeof t>"u"?JSON.parse(e):JSON.parse(e,t)}catch(o){var i=o,r=1}finally{et(n,i,r)}};y4=2e3,wu=new Set,nw=!1;cf=class{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitListeners=[];abortHandler;forwardedAbort=Dp();pendingWrites=[];pendingEndInput=!1;spawnResolve;spawnReject;spawnPromise;constructor(t){this.options=t,this.abortController=t.abortController||Dp(),t.deferSpawn?(this.spawnPromise=new Promise((n,i)=>{this.spawnResolve=n,this.spawnReject=i}),this.spawnPromise.catch(()=>{})):this.initialize()}spawn(){try{this.initialize()}catch(n){throw this.spawnAbort(hs(n)),n}let t=this.pendingWrites;this.pendingWrites=[],this.spawnResolve&&(this.spawnResolve(),this.spawnResolve=void 0,this.spawnReject=void 0);for(let n of t)this.write(n);this.pendingEndInput&&(this.pendingEndInput=!1,this.processStdin?.end())}spawnAbort(t){this.spawnReject&&(this.spawnReject(t),this.spawnReject=void 0,this.spawnResolve=void 0,this.pendingWrites=[])}updateEnv(t){this.options.env?Object.assign(this.options.env,t):this.options.env={...t}}updateResume(t){this.options.resume=t}getDefaultExecutable(){return XS()?"bun":"node"}spawnLocalProcess(t){let{command:n,args:i,cwd:r,env:o,signal:a}=t,s=kt(o.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr?"pipe":"ignore",d=hj(n,i,{cwd:r,stdio:["pipe","pipe",s],signal:a,env:o,windowsHide:!0});return(kt(o.DEBUG_CLAUDE_AGENT_SDK)||this.options.stderr)&&d.stderr.on("data",u=>{let l=u.toString();an(l),this.options.stderr&&this.options.stderr(l)}),{stdin:d.stdin,stdout:d.stdout,get killed(){return d.killed},get exitCode(){return d.exitCode},kill:d.kill.bind(d),on:d.on.bind(d),once:d.once.bind(d),off:d.off.bind(d)}}initialize(){try{let{additionalDirectories:t=[],agent:n,betas:i,cwd:r,executable:o=this.getDefaultExecutable(),executableArgs:a=[],extraArgs:s={},pathToClaudeCodeExecutable:d,env:u={...process.env},thinkingConfig:l,maxTurns:p,maxBudgetUsd:m,taskBudget:f,model:h,fallbackModel:y,jsonSchema:w,permissionMode:g,allowDangerouslySkipPermissions:v,permissionPromptToolName:b,continueConversation:S,resume:T,settingSources:C,skills:_,disallowedTools:k=[],tools:I,mcpServers:P,strictMcpConfig:R,canUseTool:M,includePartialMessages:A,plugins:F,sandbox:se}=this.options,{allowedTools:he=[]}=this.options;if(_!==void 0){let x=_==="all"?["Skill"]:_.map(O=>`Skill(${O})`),E=new Set(he);he=[...he,...x.filter(O=>!E.has(O))]}let ee=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(l){switch(l.type){case"enabled":l.budgetTokens===void 0?ee.push("--thinking","adaptive"):ee.push("--max-thinking-tokens",l.budgetTokens.toString());break;case"disabled":ee.push("--thinking","disabled");break;case"adaptive":ee.push("--thinking","adaptive");break}l.type!=="disabled"&&l.display&&ee.push("--thinking-display",l.display)}if(this.options.effort&&ee.push("--effort",this.options.effort),p&&ee.push("--max-turns",p.toString()),m!==void 0&&ee.push("--max-budget-usd",m.toString()),f&&ee.push("--task-budget",f.total.toString()),h&&ee.push("--model",h),n&&ee.push("--agent",n),i&&i.length>0&&ee.push("--betas",i.join(",")),w&&ee.push("--json-schema",ut(w)),this.options.debugFile?ee.push("--debug-file",this.options.debugFile):this.options.debug&&ee.push("--debug"),!this.options.debugFile&&!this.options.spawnClaudeCodeProcess){let x=qD();x&&ee.push("--debug-file",x)}if(M){if(b)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");ee.push("--permission-prompt-tool","stdio")}else b&&ee.push("--permission-prompt-tool",b);if(S&&ee.push("--continue"),T&&ee.push("--resume",T),this.options.channels&&this.options.channels.length>0&&ee.push("--channels",...this.options.channels),he.length>0&&ee.push("--allowedTools",he.join(",")),k.length>0&&ee.push("--disallowedTools",k.join(",")),I!==void 0&&(Array.isArray(I)?I.length===0?ee.push("--tools",""):ee.push("--tools",I.join(",")):ee.push("--tools","default")),P&&Object.keys(P).length>0&&ee.push("--mcp-config",ut({mcpServers:P})),C!==void 0&&ee.push(`--setting-sources=${C.join(",")}`),R&&ee.push("--strict-mcp-config"),g&&ee.push("--permission-mode",g),v&&ee.push("--allow-dangerously-skip-permissions"),y){if(h&&y===h)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");ee.push("--fallback-model",y)}this.options.includeHookEvents&&ee.push("--include-hook-events"),A&&ee.push("--include-partial-messages"),this.options.sessionMirror&&ee.push("--session-mirror");for(let x of t)ee.push("--add-dir",x);if(F&&F.length>0)for(let x of F)if(x.type==="local")ee.push(x.skipMcpDiscovery?"--plugin-dir-no-mcp":"--plugin-dir",x.path);else throw Error(`Unsupported plugin type: ${x.type}`);this.options.forkSession&&ee.push("--fork-session"),this.options.resumeSessionAt&&ee.push("--resume-session-at",this.options.resumeSessionAt),this.options.sessionId&&ee.push("--session-id",this.options.sessionId),this.options.persistSession===!1&&ee.push("--no-session-persistence"),this.options.managedSettings&&ee.push("--managed-settings",this.options.managedSettings);let $e={...s??{}};this.options.settings&&($e.settings=this.options.settings);let be=g4($e,se);for(let[x,E]of Object.entries(be))E===null?ee.push(`--${x}`):ee.push(`--${x}`,E);u.CLAUDE_CODE_ENTRYPOINT||(u.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),delete u.NODE_OPTIONS,kt(u.DEBUG_CLAUDE_AGENT_SDK)?u.DEBUG="1":delete u.DEBUG;let G=b4(d),$=G?d:o,B=G?[...a,...ee]:[...a,d,...ee],L={command:$,args:B,cwd:r,env:u,signal:this.forwardedAbort.signal};this.options.spawnClaudeCodeProcess?(an(`Spawning Claude Code (custom): ${$} ${B.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(L)):(an(`Spawning Claude Code: ${$} ${B.join(" ")}`),this.process=this.spawnLocalProcess(L)),this.processStdin=this.process.stdin,this.processStdout=this.process.stdout,v4(this.process),this.abortHandler=()=>this.close(),this.abortController.signal.addEventListener("abort",this.abortHandler),this.abortController.signal.aborted&&this.close(),this.process.on("error",x=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new Mt("Claude Code process aborted by user");else if(mD(x)){let E=w4(d,G);this.exitError=ReferenceError(E),an(this.exitError.message)}else this.exitError=Error(`Failed to spawn Claude Code process: ${x.message}`),an(this.exitError.message)}),this.process.on("exit",(x,E)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new Mt("Claude Code process aborted by user");else{let O=this.getProcessExitError(x,E);O&&(this.exitError=O,an(O.message))}}),this.ready=!this.abortController.signal.aborted}catch(t){throw this.ready=!1,t}}getProcessExitError(t,n){if(t!==0&&t!==null)return Error(`Claude Code process exited with code ${t}`);if(n)return Error(`Claude Code process terminated by signal ${n}`)}write(t){if(this.abortController.signal.aborted)throw new Mt("Operation aborted");if(this.spawnResolve){this.pendingWrites.push(t);return}if(!this.ready||!this.processStdin)throw Error("ProcessTransport is not ready for writing");if(this.processStdin.writableEnded){an("[ProcessTransport] Dropping write to ended stdin stream");return}if(this.process?.killed||this.process?.exitCode!==null)throw Error("Cannot write to terminated process");if(this.exitError)throw Error(`Cannot write to process that exited with error: ${this.exitError.message}`);an(`[ProcessTransport] Writing to stdin: ${t.substring(0,100)}`);try{this.processStdin.write(t)||an("[ProcessTransport] Write buffer full, data queued")}catch(n){throw this.ready=!1,Error(`Failed to write to process stdin: ${$d(n)}`)}}[Symbol.dispose](){this.close()}close(){this.spawnAbort(this.abortController.signal.aborted?new Mt("Claude Code process aborted by user"):Error("Query closed before spawn")),this.processStdin&&(this.processStdin.end(),this.processStdin=void 0),this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0);for(let{handler:i}of this.exitListeners)this.process?.off("exit",i);this.exitListeners=[];let t=()=>{this.abortController.signal.aborted&&this.forwardedAbort.abort(this.abortController.signal.reason)},n=this.process;n&&!n.killed&&n.exitCode===null?(setTimeout((i,r)=>{if(i.exitCode!==null){r();return}if(process.platform==="win32"){setTimeout((o,a)=>{o.exitCode===null&&o.kill("SIGKILL"),a()},5e3,i,r).unref();return}i.kill("SIGTERM"),setTimeout(o=>{o.exitCode===null&&o.kill("SIGKILL")},5e3,i).unref(),r()},y4,n,t).unref(),n.once("exit",()=>wu.delete(n))):n&&(wu.delete(n),t()),this.ready=!1}isReady(){return this.ready}async*readMessages(){if(this.spawnPromise&&(await this.spawnPromise,this.spawnPromise=void 0),!this.processStdout)throw Error("ProcessTransport output stream not available");if(this.exitError)throw this.exitError;let t=yj({input:this.processStdout}),n=this.process?(()=>{let i=this.process,r=()=>t.close();return i.on("error",r),()=>i.off("error",r)})():void 0;this.exitError&&t.close();try{for await(let i of t)if(i.trim()){let r;try{r=Rn(i)}catch{an(`Non-JSON stdout: ${i}`);continue}yield r}if(this.exitError)throw this.exitError;await this.waitForExit()}catch(i){throw i}finally{n?.(),t.close()}}endInput(){if(this.spawnResolve){this.pendingEndInput=!0;return}this.processStdin&&this.processStdin.end()}getInputStream(){return this.processStdin}onExit(t){if(!this.process)return()=>{};let n=(i,r)=>{let o=this.getProcessExitError(i,r);t(o)};return this.process.on("exit",n),this.exitListeners.push({callback:t,handler:n}),()=>{this.process&&this.process.off("exit",n);let i=this.exitListeners.findIndex(r=>r.handler===n);i!==-1&&this.exitListeners.splice(i,1)}}async waitForExit(){if(!this.process){if(this.exitError)throw this.exitError;return}if(this.process.exitCode!==null||this.process.killed||this.exitError){if(this.exitError)throw this.exitError;return}return new Promise((t,n)=>{let i=(o,a)=>{if(this.abortController.signal.aborted){n(new Mt("Operation aborted"));return}let s=this.getProcessExitError(o,a);s?n(s):t()};this.process.once("exit",i);let r=o=>{this.process.off("exit",i),n(o)};this.process.once("error",r),this.process.once("exit",()=>{this.process.off("error",r)})})}};Ti="@anthropic-ai/claude-agent-sdk";Su=class{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(t){this.returned=t}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((t,n)=>{this.readResolve=t,this.readReject=n})}enqueue(t){if(this.readResolve){let n=this.readResolve;this.readResolve=void 0,this.readReject=void 0,n({done:!1,value:t})}else this.queue.push(t)}done(){if(this.isDone=!0,this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!0,value:void 0})}}error(t){if(this.hasError=t,this.readReject){let n=this.readReject;this.readResolve=void 0,this.readReject=void 0,n(t)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}};T4=C4();pf=class{sendMcpMessage;isClosed=!1;constructor(t){this.sendMcpMessage=t}onclose;onerror;onmessage;async start(){}async send(t){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(t)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}},bp=Symbol("suppressControlResponse"),ff=class{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;onElicitation;getOAuthToken;getHostAuthToken;onUserDialog;pendingControlResponses=new Map;cleanupPerformed=!1;sdkMessages;inputStream=new Su;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;initHooksPayload;sdkMcpTransports=new Map;sdkMcpServerInstances=new Map;pendingMcpResponses=new Map;firstResultReceivedResolve;firstResultReceived=!1;lastErrorResultText;transcriptMirrorBatcher;cleanupCallbacks=[];cleanupPromise;setIsSingleUserTurn(t){this.isSingleUserTurn=t}setTranscriptMirrorBatcher(t){this.transcriptMirrorBatcher=t}reportMirrorError(t,n){let i={type:"system",subtype:"mirror_error",error:n,key:t,uuid:of(),session_id:t.sessionId};this.inputStream.enqueue(i)}addCleanupCallback(t){this.cleanupPerformed?t():this.cleanupCallbacks.push(t)}isClosed(){return this.cleanupPerformed}hasBidirectionalNeeds(){return this.sdkMcpTransports.size>0||this.hooks!==void 0&&Object.keys(this.hooks).length>0||this.canUseTool!==void 0||this.onElicitation!==void 0||this.onUserDialog!==void 0||this.getOAuthToken!==void 0||this.getHostAuthToken!==void 0}constructor(t,n,i,r,o,a=new Map,s,d,u,l,p,m){this.transport=t,this.isSingleUserTurn=n,this.canUseTool=i,this.hooks=r,this.abortController=o,this.jsonSchema=s,this.initConfig=d,this.onElicitation=u,this.getOAuthToken=l,this.getHostAuthToken=p,this.onUserDialog=m;for(let[f,h]of a)this.connectSdkMcpServer(f,h);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initialization=this.initialize(),this.initialization.catch(()=>{})}setError(t){this.inputStream.error(t)}async stopTask(t){await this.request({subtype:"stop_task",task_id:t})}async backgroundTasks(t){return(await this.request({subtype:"background_tasks",tool_use_id:t})).response.backgrounded??!0}close(){this.cleanup()}cleanup(t){return this.cleanupPromise?this.cleanupPromise:(this.cleanupPerformed=!0,this.cleanupPromise=this.performCleanup(t),this.cleanupPromise)}async performCleanup(t){for(let n of this.cleanupCallbacks)try{n()}catch{}if(this.cleanupCallbacks=[],this.transcriptMirrorBatcher)try{await this.transcriptMirrorBatcher.flush()}catch{}try{for(let i of this.cancelControllers.values())i.abort();this.cancelControllers.clear(),this.transport.close();let n=t??Error("Query closed before response received");for(let{reject:i}of this.pendingControlResponses.values())i(n);this.pendingControlResponses.clear();for(let{reject:i}of this.pendingMcpResponses.values())i(n);this.pendingMcpResponses.clear(),this.hookCallbacks.clear();for(let i of this.sdkMcpTransports.values())i.close().catch(()=>{});this.sdkMcpTransports.clear(),t?this.inputStream.error(t):this.inputStream.done()}catch{}if(this.transport.waitForExit){let n=new AbortController;try{await Promise.race([this.transport.waitForExit(),dl(2e3,n.signal)])}catch{}finally{n.abort()}}}next(...[t]){return this.sdkMessages.next(t)}async return(t){return await this.cleanup(),this.sdkMessages.return(t)}async throw(t){return await this.cleanup(),this.sdkMessages.throw(t)}[Symbol.asyncIterator](){return this.sdkMessages}async[Symbol.asyncDispose](){await this.cleanup()}async readMessages(){try{for await(let t of this.transport.readMessages()){if(t.type==="control_response"){let n=this.pendingControlResponses.get(t.response.request_id);n&&n.handler(t.response);continue}else if(t.type==="control_request"){this.handleControlRequest(t);continue}else if(t.type==="control_cancel_request"){this.handleControlCancelRequest(t);continue}else{if(t.type==="keep_alive")continue;if(t.type==="transcript_mirror"){this.transcriptMirrorBatcher?.enqueue(t.filePath,t.entries);continue}}if(t.type==="system"&&(t.subtype==="post_turn_summary"||t.subtype==="task_summary")){this.inputStream.enqueue(t);continue}if(t.type==="active_goal"){this.inputStream.enqueue(t);continue}t.type==="result"?(this.transcriptMirrorBatcher&&await this.transcriptMirrorBatcher.flush(),this.lastErrorResultText=t.is_error?t.subtype==="success"?t.result:t.errors.join("; "):void 0,this.firstResultReceived=!0,this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleUserTurn&&(qe("[Query.readMessages] First result received for single-turn query, closing stdin"),this.transport.endInput())):t.type==="system"&&t.subtype==="session_state_changed"||(this.lastErrorResultText=void 0),this.inputStream.enqueue(t)}this.transcriptMirrorBatcher&&await this.transcriptMirrorBatcher.flush(),this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.inputStream.done(),this.cleanup()}catch(t){if(this.transcriptMirrorBatcher&&await this.transcriptMirrorBatcher.flush(),this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.lastErrorResultText!==void 0&&!(t instanceof Mt)){let n=Error(`Claude Code returned an error result: ${this.lastErrorResultText}`);qe(`[Query.readMessages] Replacing exit error with result text. Original: ${$d(t)}`),this.inputStream.error(n),this.cleanup(n);return}this.inputStream.error(t),this.cleanup(t)}}async handleControlRequest(t){if(this.cancelControllers.has(t.request_id)){qe(`[Query.handleControlRequest] Duplicate delivery of in-flight request ${t.request_id} (${t.request.subtype}) \u2014 skipping`);return}let n=new AbortController;this.cancelControllers.set(t.request_id,n);try{let i=await this.processControlRequest(t,n.signal);if(this.cleanupPerformed||i===bp)return;let r={type:"control_response",response:{subtype:"success",request_id:t.request_id,response:i}};await Promise.resolve(this.transport.write(ut(r)+`
84
+ `))}catch(i){if(this.cleanupPerformed)return;let r={type:"control_response",response:{subtype:"error",request_id:t.request_id,error:$d(i)}};try{await Promise.resolve(this.transport.write(ut(r)+`
85
+ `))}catch(o){qe(`[Query.handleControlRequest] Error-response write failed: ${$d(o)}`,{level:"error"})}}finally{this.cancelControllers.delete(t.request_id)}}handleControlCancelRequest(t){let n=this.cancelControllers.get(t.request_id);n&&(n.abort(),this.cancelControllers.delete(t.request_id))}async processControlRequest(t,n){if(t.request.subtype==="can_use_tool"){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");let i=await this.canUseTool(t.request.tool_name,t.request.input,{signal:n,suggestions:t.request.permission_suggestions,blockedPath:t.request.blocked_path,decisionReason:t.request.decision_reason,title:t.request.title,displayName:t.request.display_name,description:t.request.description,toolUseID:t.request.tool_use_id,agentID:t.request.agent_id,requestId:t.request_id});return i===null?bp:{...i,toolUseID:t.request.tool_use_id}}else{if(t.request.subtype==="hook_callback")return await this.handleHookCallbacks(t.request.callback_id,t.request.input,t.request.tool_use_id,n);if(t.request.subtype==="mcp_message"){let i=t.request,r=this.sdkMcpTransports.get(i.server_name);if(!r)throw Error(`SDK MCP server not found: ${i.server_name}`);return"method"in i.message&&"id"in i.message&&i.message.id!==null?{mcp_response:await this.handleMcpControlRequest(i.server_name,i,r)}:(r.onmessage&&r.onmessage(i.message),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}else if(t.request.subtype==="elicitation"){let i=t.request;return this.onElicitation?await this.onElicitation({serverName:i.mcp_server_name,message:i.message,mode:i.mode,url:i.url,elicitationId:i.elicitation_id,requestedSchema:i.requested_schema,title:i.title,displayName:i.display_name,description:i.description},{signal:n}):{action:"decline"}}else{if(t.request.subtype==="request_user_dialog")return this.onUserDialog?await this.onUserDialog({dialogKind:t.request.dialog_kind,payload:t.request.payload,toolUseID:t.request.tool_use_id},{signal:n}):(qe(`[Query] No onUserDialog handler for request_user_dialog (kind=${t.request.dialog_kind}) \u2014 staying silent so a capable client (or the worker's park deadline) settles it`),vl("tengu_request_user_dialog_response_ignored",{shape:ml("auto_cancel")}),bp);if(t.request.subtype==="oauth_token_refresh"){if(!this.getOAuthToken)throw Error("getOAuthToken callback is not provided.");return{accessToken:await this.getOAuthToken({signal:n})??null}}else if(t.request.subtype==="host_auth_token_refresh"){if(!this.getHostAuthToken)throw Error("getHostAuthToken callback is not provided.");return{authToken:await this.getHostAuthToken({signal:n})??null}}}}throw Error("Unsupported control request subtype: "+t.request.subtype)}async*readSdkMessages(){try{for await(let t of this.inputStream)yield t}finally{await this.cleanup()}}async initialize(){if(this.hooks&&!this.initHooksPayload){this.initHooksPayload={};for(let[i,r]of Object.entries(this.hooks))r.length>0&&(this.initHooksPayload[i]=r.map(o=>{let a=[];for(let s of o.hooks){let d=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(d,s),a.push(d)}return{matcher:o.matcher,hookCallbackIds:a,timeout:o.timeout}}))}let t=this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,n={subtype:"initialize",hooks:this.initHooksPayload,sdkMcpServers:t,jsonSchema:this.jsonSchema,systemPrompt:typeof this.initConfig?.systemPrompt=="string"?[this.initConfig.systemPrompt]:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,planModeInstructions:this.initConfig?.planModeInstructions,appendSubagentSystemPrompt:this.initConfig?.appendSubagentSystemPrompt,toolAliases:this.initConfig?.toolAliases,excludeDynamicSections:this.initConfig?.excludeDynamicSections,agents:this.initConfig?.agents,title:this.initConfig?.title,skills:Array.isArray(this.initConfig?.skills)?this.initConfig.skills:void 0,webSearchIsolationExemptMcpServers:this.initConfig?.webSearchIsolationExemptMcpServers,promptSuggestions:this.initConfig?.promptSuggestions,agentProgressSummaries:this.initConfig?.agentProgressSummaries,forwardSubagentText:this.initConfig?.forwardSubagentText,supportedDialogKinds:this.initConfig?.supportedDialogKinds};return(await this.request(n)).response}async interrupt(){return bn("sdk_interrupt",async()=>{await this.request({subtype:"interrupt"})})}async setPermissionMode(t){await this.request({subtype:"set_permission_mode",mode:t})}async setMcpPermissionModeOverride(t,n){return(await this.request({subtype:"set_mcp_permission_mode_override",serverName:t,mode:n})).response??{}}async setModel(t){await this.request({subtype:"set_model",model:t})}async setMaxThinkingTokens(t,n){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:t,thinking_display:n})}async applyFlagSettings(t){return bn("sdk_apply_flag_settings",async()=>{await this.request({subtype:"apply_flag_settings",settings:t})})}async getSettings(){return(await this.request({subtype:"get_settings"})).response}async rewindFiles(t,n){return bn("sdk_rewind_files",async()=>(await this.request({subtype:"rewind_files",user_message_id:t,dry_run:n?.dryRun})).response)}async cancelAsyncMessage(t){return(await this.request({subtype:"cancel_async_message",message_uuid:t})).response.cancelled}async seedReadState(t,n){await this.request({subtype:"seed_read_state",path:t,mtime:n})}async enableRemoteControl(t,n){return(await this.request({subtype:"remote_control",enabled:t,...n!==void 0&&{name:n}})).response}async submitFeedback(t,n){return(await this.request({subtype:"submit_feedback",description:t,surface:n?.surface})).response}async generateSessionTitle(t,n){return bn("sdk_session_title_generate",async()=>(await this.request({subtype:"generate_session_title",description:t,persist:n?.persist})).response.title)}async askSideQuestion(t){return bn("sdk_side_question",async()=>{let n=(await this.request({subtype:"side_question",question:t})).response;return n.response===null?null:{response:n.response,synthetic:n.synthetic??!1}})}async launchUltrareview(t,n){return(await this.request({subtype:"ultrareview_launch",args:t,confirm:n?.confirm??!1})).response}async messageRated(t){await this.request({subtype:"message_rated",messageUuid:t.messageUuid,sentiment:t.sentiment,surface:t.surface,cleared:t.cleared??!1})}processPendingPermissionRequests(t){for(let n of t)n.request.subtype==="can_use_tool"&&this.handleControlRequest(n).catch(()=>{})}processPendingUserDialogRequests(t){for(let n of t)n.request.subtype==="request_user_dialog"&&this.handleControlRequest(n).catch(()=>{})}request(t){let n=Math.random().toString(36).substring(2,15),i={request_id:n,type:"control_request",request:t},r=t.subtype==="initialize";return new Promise((o,a)=>{this.pendingControlResponses.set(n,{handler:s=>{this.pendingControlResponses.delete(n),s.subtype==="success"?o(s):a(Error(s.error)),!r&&(s.pending_permission_requests||s.pending_user_dialog_requests)?qe(`[Query] Ignoring prompt-redelivery fields on non-initialize response (subtype=${t.subtype})`):(s.pending_permission_requests&&this.processPendingPermissionRequests(s.pending_permission_requests),s.pending_user_dialog_requests&&this.processPendingUserDialogRequests(s.pending_user_dialog_requests))},reject:a}),Promise.resolve(this.transport.write(ut(i)+`
86
+ `)).catch(s=>{this.pendingControlResponses.delete(n),a(s)})})}initializationResult(){return this.initialization}reinitialize(){return bn("sdk_reinitialize",()=>this.initialize())}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async supportedAgents(){return(await this.initialization).agents}async reconnectMcpServer(t){await this.request({subtype:"mcp_reconnect",serverName:t})}async toggleMcpServer(t,n){return bn("sdk_mcp_toggle_server",async()=>{await this.request({subtype:"mcp_toggle",serverName:t,enabled:n})})}async enableChannel(t){return bn("sdk_mcp_enable_channel",async()=>{await this.request({subtype:"channel_enable",serverName:t})})}async mcpAuthenticate(t,n){return(await this.request({subtype:"mcp_authenticate",serverName:t,redirectUri:n})).response}async mcpClearAuth(t){return(await this.request({subtype:"mcp_clear_auth",serverName:t})).response}async mcpSubmitOAuthCallbackUrl(t,n){return(await this.request({subtype:"mcp_oauth_callback_url",serverName:t,callbackUrl:n})).response}async claudeAuthenticate(t){return(await this.request({subtype:"claude_authenticate",loginWithClaudeAi:t})).response}async claudeOAuthCallback(t,n){return(await this.request({subtype:"claude_oauth_callback",authorizationCode:t,state:n})).response}async claudeOAuthWaitForCompletion(){return(await this.request({subtype:"claude_oauth_wait_for_completion"})).response}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async getContextUsage(){return(await this.request({subtype:"get_context_usage"})).response}async usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(){return(await this.request({subtype:"get_usage"})).response}async readFile(t,n){try{return(await this.request({subtype:"read_file",path:t,max_bytes:n?.maxBytes,encoding:n?.encoding})).response}catch{return null}}async reloadPlugins(){return bn("sdk_reload_plugins",async()=>(await this.request({subtype:"reload_plugins"})).response)}async reloadSkills(){return bn("sdk_reload_skills",async()=>(await this.request({subtype:"reload_skills"})).response)}async setMcpServers(t){return bn("sdk_mcp_set_servers",async()=>{let n={},i={};for(let[s,d]of Object.entries(t))d.type==="sdk"&&"instance"in d?n[s]=d.instance:i[s]=d;let r=new Set(this.sdkMcpServerInstances.keys()),o=new Set(Object.keys(n));for(let s of r)o.has(s)||await this.disconnectSdkMcpServer(s);for(let[s,d]of Object.entries(n))r.has(s)||this.connectSdkMcpServer(s,d);let a={};for(let s of Object.keys(n))a[s]={type:"sdk",name:s};return(await this.request({subtype:"mcp_set_servers",servers:{...i,...a}})).response})}async accountInfo(){return(await this.initialization).account}async streamInput(t){qe("[Query.streamInput] Starting to process input stream");try{let n=0;for await(let i of t){if(n++,qe(`[Query.streamInput] Processing message ${n}: ${i.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(ut(i)+`
87
+ `))}qe(`[Query.streamInput] Finished processing ${n} messages from input stream`),n>0&&this.hasBidirectionalNeeds()&&(qe("[Query.streamInput] Has bidirectional needs, waiting for first result"),await this.waitForFirstResult()),qe("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(n){if(!(n instanceof Mt))throw n}}waitForFirstResult(){return this.firstResultReceived?(qe("[Query.waitForFirstResult] Result already received, returning immediately"),Promise.resolve()):new Promise(t=>{if(this.abortController?.signal.aborted){t();return}this.abortController?.signal.addEventListener("abort",()=>t(),{once:!0}),this.firstResultReceivedResolve=t})}handleHookCallbacks(t,n,i,r){let o=this.hookCallbacks.get(t);if(!o)throw Error(`No hook callback found for ID: ${t}`);return o(n,i,{signal:r})}connectSdkMcpServer(t,n){let i=new pf(r=>this.sendMcpServerMessageToCli(t,r));this.sdkMcpTransports.set(t,i),this.sdkMcpServerInstances.set(t,n),n.connect(i).catch(r=>{this.sdkMcpTransports.get(t)===i&&this.sdkMcpTransports.delete(t),this.sdkMcpServerInstances.get(t)===n&&this.sdkMcpServerInstances.delete(t),qe(`[Query.connectSdkMcpServer] Failed to connect MCP server '${t}': ${r}`,{level:"error"})})}async disconnectSdkMcpServer(t){let n=this.sdkMcpTransports.get(t);n&&(await n.close(),this.sdkMcpTransports.delete(t)),this.sdkMcpServerInstances.delete(t)}sendMcpServerMessageToCli(t,n){if("id"in n&&n.id!==null&&n.id!==void 0){let r=`${t}:${n.id}`,o=this.pendingMcpResponses.get(r);if(o){o.resolve(n),this.pendingMcpResponses.delete(r);return}}let i={type:"control_request",request_id:of(),request:{subtype:"mcp_message",server_name:t,message:n}};Promise.resolve(this.transport.write(ut(i)+`
88
+ `)).catch(r=>{qe(`[Query.sendMcpServerMessageToCli] Transport write failed: ${r}`,{level:"error"})})}handleMcpControlRequest(t,n,i){let r="id"in n.message?n.message.id:null,o=`${t}:${r}`;return new Promise((a,s)=>{let d=()=>{this.pendingMcpResponses.delete(o)},u=p=>{d(),a(p)},l=p=>{d(),s(p)};if(this.pendingMcpResponses.set(o,{resolve:u,reject:l}),i.onmessage)i.onmessage(n.message);else{d(),s(Error("No message handler registered"));return}})}},Fm=500,zm=1048576,P4=[200,800],mf=class{send;sendTimeoutMs;onError;maxPendingEntries;maxPendingBytes;backoffMs;pending=[];pendingEntries=0;pendingBytes=0;flushPromise=null;constructor(t,n=6e4,i,r=Fm,o=zm,a=P4){this.send=t,this.sendTimeoutMs=n,this.onError=i,this.maxPendingEntries=r,this.maxPendingBytes=o,this.backoffMs=a}enqueue(t,n){let i=ut(n).length;this.pending.push({filePath:t,entries:n,bytes:i}),this.pendingEntries+=n.length,this.pendingBytes+=i,(this.pendingEntries>this.maxPendingEntries||this.pendingBytes>this.maxPendingBytes)&&(this.flushPromise=this.drain(),this.flushPromise.catch(()=>{}))}async flush(){let t=this.drain();this.flushPromise=t,await t,this.flushPromise===t&&(this.flushPromise=null)}async drain(){let t=this.flushPromise,n=this.pending.splice(0);this.pendingEntries=0,this.pendingBytes=0,t&&await t,n.length!==0&&await this.doFlush(n)}async doFlush(t){let n=new Map;for(let r of t){let o=n.get(r.filePath);o?o.push(...r.entries):n.set(r.filePath,r.entries.slice())}let i=this.backoffMs.length+1;for(let[r,o]of n){let a=`SessionStore.append() timed out after ${this.sendTimeoutMs}ms for ${r}`,s,d=1;for(;d<=i;d++)try{await Jr(this.send(r,o),this.sendTimeoutMs,a),s=void 0;break}catch(u){if(s=hs(u),s.message===a)break;let l=this.backoffMs[d-1];if(l===void 0)break;await dl(l)}if(s){qe(`[TranscriptMirrorBatcher] flush failed for ${r} after ${d} attempt(s): ${s}`,{level:"error"});try{this.onError?.(r,s)}catch(u){qe(`[TranscriptMirrorBatcher] onError callback threw: ${u}`,{level:"error"})}}}}},rw=am(r1(),1);Ii=new Map,z4=5e3;B4=new Set([".com",".exe",".bat",".cmd"]);G4=N4(q4);er=65536,Z4=new Set(["sdk-cli","sdk-ts","sdk-py"]);Y4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;Ja=200;iB=1048576,oB=5242880;xu=Buffer.from('{"type":"attribution-snapshot"'),dB=Buffer.from('{"type":"system"'),Wa=10,uB=Buffer.from([Wa]),lB=256;aw=524288,sw=8192;IB=32;zB=new Set(["user","assistant","attachment","system","progress"]);rK="user:inference",Rx="user:profile",iK="org:create_api_key",oK=[iK,Rx],aK=[Rx,rK,"user:sessions:claude_code","user:mcp_servers","user:file_upload"],Gae=Ex([...oK,...aK]),sK=["user:design:read","user:design:write"],Vae=[...sK,"user:projects:read","user:projects:write"],cw={BASE_API_URL:"https://api.anthropic.com",CONSOLE_AUTHORIZE_URL:"https://platform.claude.com/oauth/authorize",CLAUDE_AI_AUTHORIZE_URL:"https://claude.com/cai/oauth/authorize",CLAUDE_AI_ORIGIN:"https://claude.ai",TOKEN_URL:"https://platform.claude.com/v1/oauth/token",API_KEY_URL:"https://api.anthropic.com/api/oauth/claude_cli/create_api_key",ROLES_URL:"https://api.anthropic.com/api/oauth/claude_cli/roles",CONSOLE_SUCCESS_URL:"https://platform.claude.com/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code",CLAUDEAI_SUCCESS_URL:"https://platform.claude.com/oauth/code/success?app=claude-code",MANUAL_REDIRECT_URL:"https://platform.claude.com/oauth/code/callback",CLIENT_ID:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",DESIGN_CLIENT_ID:"59637612-477b-4836-a601-b0589eda7704",OAUTH_FILE_SUFFIX:"",MCP_PROXY_URL:"https://mcp-proxy.anthropic.com",MCP_PROXY_PATH:"/v1/mcp/{server_id}"},dK=void 0;lK=["https://beacon.claude-ai.staging.ant.dev","https://claude.fedstart.com","https://claude-staging.fedstart.com"];pK="-credentials";mK=/^[a-zA-Z0-9._-]+$/;(function(e){e.assertEqual=r=>{};function t(r){}e.assertIs=t;function n(r){throw Error()}e.assertNever=n,e.arrayToEnum=r=>{let o={};for(let a of r)o[a]=a;return o},e.getValidEnumValues=r=>{let o=e.objectKeys(r).filter(s=>typeof r[r[s]]!="number"),a={};for(let s of o)a[s]=r[s];return e.objectValues(a)},e.objectValues=r=>e.objectKeys(r).map(function(o){return r[o]}),e.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{let o=[];for(let a in r)Object.prototype.hasOwnProperty.call(r,a)&&o.push(a);return o},e.find=(r,o)=>{for(let a of r)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function i(r,o=" | "){return r.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=i,e.jsonStringifyReplacer=(r,o)=>typeof o=="bigint"?o.toString():o})(Oe||(Oe={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(pw||(pw={}));ae=Oe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mr=e=>{switch(typeof e){case"undefined":return ae.undefined;case"string":return ae.string;case"number":return Number.isNaN(e)?ae.nan:ae.number;case"boolean":return ae.boolean;case"function":return ae.function;case"bigint":return ae.bigint;case"symbol":return ae.symbol;case"object":return Array.isArray(e)?ae.array:e===null?ae.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ae.promise:typeof Map<"u"&&e instanceof Map?ae.map:typeof Set<"u"&&e instanceof Set?ae.set:typeof Date<"u"&&e instanceof Date?ae.date:ae.object;default:return ae.unknown}},W=Oe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ln=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},i={_errors:[]},r=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)i._errors.push(n(a));else{let s=i,d=0;for(;d<a.path.length;){let u=a.path[d];d!==a.path.length-1?s[u]=s[u]||{_errors:[]}:(s[u]=s[u]||{_errors:[]},s[u]._errors.push(n(a))),s=s[u],d++}}};return r(this),i}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Oe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},i=[];for(let r of this.issues)if(r.path.length>0){let o=r.path[0];n[o]=n[o]||[],n[o].push(t(r))}else i.push(t(r));return{formErrors:i,fieldErrors:n}}get formErrors(){return this.flatten()}};ln.create=e=>new ln(e);_K=(e,t)=>{let n;switch(e.code){case W.invalid_type:e.received===ae.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case W.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Oe.jsonStringifyReplacer)}`;break;case W.unrecognized_keys:n=`Unrecognized key(s) in object: ${Oe.joinValues(e.keys,", ")}`;break;case W.invalid_union:n="Invalid input";break;case W.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Oe.joinValues(e.options)}`;break;case W.invalid_enum_value:n=`Invalid enum value. Expected ${Oe.joinValues(e.options)}, received '${e.received}'`;break;case W.invalid_arguments:n="Invalid function arguments";break;case W.invalid_return_type:n="Invalid function return type";break;case W.invalid_date:n="Invalid date";break;case W.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Oe.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case W.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case W.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case W.custom:n="Invalid input";break;case W.invalid_intersection_types:n="Intersection results could not be merged";break;case W.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case W.not_finite:n="Number must be finite";break;default:n=t.defaultError,Oe.assertNever(e)}return{message:n}},Ha=_K,vK=Ha;bf=e=>{let{data:t,path:n,errorMaps:i,issueData:r}=e,o=[...n,...r.path||[]],a={...r,path:o};if(r.message!==void 0)return{...r,path:o,message:r.message};let s="",d=i.filter(u=>!!u).slice().reverse();for(let u of d)s=u(a,{data:t,defaultError:s}).message;return{...r,path:o,message:s}};Ot=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let i=[];for(let r of n){if(r.status==="aborted")return ye;r.status==="dirty"&&t.dirty(),i.push(r.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,n){let i=[];for(let r of n){let o=await r.key,a=await r.value;i.push({key:o,value:a})}return e.mergeObjectSync(t,i)}static mergeObjectSync(t,n){let i={};for(let r of n){let{key:o,value:a}=r;if(o.status==="aborted"||a.status==="aborted")return ye;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet)&&(i[o.value]=a.value)}return{status:t.value,value:i}}},ye=Object.freeze({status:"aborted"}),Ca=e=>({status:"dirty",value:e}),Nt=e=>({status:"valid",value:e}),fw=e=>e.status==="aborted",mw=e=>e.status==="dirty",Vi=e=>e.status==="valid",Cu=e=>typeof Promise<"u"&&e instanceof Promise;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(le||(le={}));fn=class{constructor(t,n,i,r){this._cachedPath=[],this.parent=t,this.data=n,this._path=i,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},hw=(e,t)=>{if(Vi(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new ln(e.common.issues);return this._error=n,this._error}}};Ie=class{get description(){return this._def.description}_getType(t){return mr(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:mr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ot,ctx:{common:t.parent.common,data:t.data,parsedType:mr(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Cu(n))throw Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let i=this.safeParse(t,n);if(i.success)return i.data;throw i.error}safeParse(t,n){let i={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:mr(t)},r=this._parseSync({data:t,path:i.path,parent:i});return hw(i,r)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:mr(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:n});return Vi(i)?{value:i.value}:{issues:n.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(i=>Vi(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(t,n){let i=await this.safeParseAsync(t,n);if(i.success)return i.data;throw i.error}async safeParseAsync(t,n){let i={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:mr(t)},r=this._parse({data:t,path:i.path,parent:i}),o=await(Cu(r)?r:Promise.resolve(r));return hw(i,o)}refine(t,n){let i=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,o)=>{let a=t(r),s=()=>o.addIssue({code:W.custom,...i(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(d=>d?!0:(s(),!1)):a?!0:(s(),!1)})}refinement(t,n){return this._refinement((i,r)=>t(i)?!0:(r.addIssue(typeof n=="function"?n(i,r):n),!1))}_refinement(t){return new Tn({schema:this,typeName:V.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return cn.create(this,this._def)}nullable(){return ir.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return kr.create(this)}promise(){return Xr.create(this,this._def)}or(t){return Xi.create([this,t],this._def)}and(t){return eo.create(this,t,this._def)}transform(t){return new Tn({...ke(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new oo({...ke(this._def),innerType:this,defaultValue:n,typeName:V.ZodDefault})}brand(){return new Tu({typeName:V.ZodBranded,type:this,...ke(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new ao({...ke(this._def),innerType:this,catchValue:n,typeName:V.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return Iu.create(this,t)}readonly(){return so.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},bK=/^c[^\s-]{8,}$/i,wK=/^[0-9a-z]+$/,SK=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kK=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,xK=/^[a-z0-9_-]{21}$/i,CK=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,TK=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,IK=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,PK="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",EK=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,RK=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,OK=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,AK=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$K=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,MK=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ox="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",jK=new RegExp(`^${Ox}$`);Zi=class e extends Ie{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ae.string){let r=this._getOrReturnCtx(t);return re(r,{code:W.invalid_type,expected:ae.string,received:r.parsedType}),ye}let n=new Ot,i;for(let r of this._def.checks)if(r.kind==="min")t.data.length<r.value&&(i=this._getOrReturnCtx(t,i),re(i,{code:W.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),n.dirty());else if(r.kind==="max")t.data.length>r.value&&(i=this._getOrReturnCtx(t,i),re(i,{code:W.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),n.dirty());else if(r.kind==="length"){let o=t.data.length>r.value,a=t.data.length<r.value;(o||a)&&(i=this._getOrReturnCtx(t,i),o?re(i,{code:W.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):a&&re(i,{code:W.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),n.dirty())}else if(r.kind==="email")IK.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"email",code:W.invalid_string,message:r.message}),n.dirty());else if(r.kind==="emoji")kp||(kp=new RegExp(PK,"u")),kp.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"emoji",code:W.invalid_string,message:r.message}),n.dirty());else if(r.kind==="uuid")kK.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"uuid",code:W.invalid_string,message:r.message}),n.dirty());else if(r.kind==="nanoid")xK.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"nanoid",code:W.invalid_string,message:r.message}),n.dirty());else if(r.kind==="cuid")bK.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"cuid",code:W.invalid_string,message:r.message}),n.dirty());else if(r.kind==="cuid2")wK.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"cuid2",code:W.invalid_string,message:r.message}),n.dirty());else if(r.kind==="ulid")SK.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"ulid",code:W.invalid_string,message:r.message}),n.dirty());else if(r.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),re(i,{validation:"url",code:W.invalid_string,message:r.message}),n.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,!r.regex.test(t.data)&&(i=this._getOrReturnCtx(t,i),re(i,{validation:"regex",code:W.invalid_string,message:r.message}),n.dirty())):r.kind==="trim"?t.data=t.data.trim():r.kind==="includes"?t.data.includes(r.value,r.position)||(i=this._getOrReturnCtx(t,i),re(i,{code:W.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),n.dirty()):r.kind==="toLowerCase"?t.data=t.data.toLowerCase():r.kind==="toUpperCase"?t.data=t.data.toUpperCase():r.kind==="startsWith"?t.data.startsWith(r.value)||(i=this._getOrReturnCtx(t,i),re(i,{code:W.invalid_string,validation:{startsWith:r.value},message:r.message}),n.dirty()):r.kind==="endsWith"?t.data.endsWith(r.value)||(i=this._getOrReturnCtx(t,i),re(i,{code:W.invalid_string,validation:{endsWith:r.value},message:r.message}),n.dirty()):r.kind==="datetime"?NK(r).test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{code:W.invalid_string,validation:"datetime",message:r.message}),n.dirty()):r.kind==="date"?jK.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{code:W.invalid_string,validation:"date",message:r.message}),n.dirty()):r.kind==="time"?qK(r).test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{code:W.invalid_string,validation:"time",message:r.message}),n.dirty()):r.kind==="duration"?TK.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"duration",code:W.invalid_string,message:r.message}),n.dirty()):r.kind==="ip"?DK(t.data,r.version)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"ip",code:W.invalid_string,message:r.message}),n.dirty()):r.kind==="jwt"?LK(t.data,r.alg)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"jwt",code:W.invalid_string,message:r.message}),n.dirty()):r.kind==="cidr"?UK(t.data,r.version)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"cidr",code:W.invalid_string,message:r.message}),n.dirty()):r.kind==="base64"?$K.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"base64",code:W.invalid_string,message:r.message}),n.dirty()):r.kind==="base64url"?MK.test(t.data)||(i=this._getOrReturnCtx(t,i),re(i,{validation:"base64url",code:W.invalid_string,message:r.message}),n.dirty()):Oe.assertNever(r);return{status:n.value,value:t.data}}_regex(t,n,i){return this.refinement(r=>t.test(r),{validation:n,code:W.invalid_string,...le.errToObj(i)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...le.errToObj(t)})}url(t){return this._addCheck({kind:"url",...le.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...le.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...le.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...le.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...le.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...le.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...le.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...le.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...le.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...le.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...le.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...le.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...le.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...le.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...le.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...le.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...le.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...le.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...le.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...le.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...le.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...le.errToObj(n)})}nonempty(t){return this.min(1,le.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Zi.create=e=>new Zi({checks:[],typeName:V.ZodString,coerce:e?.coerce??!1,...ke(e)});Ga=class e extends Ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ae.number){let r=this._getOrReturnCtx(t);return re(r,{code:W.invalid_type,expected:ae.number,received:r.parsedType}),ye}let n,i=new Ot;for(let r of this._def.checks)r.kind==="int"?Oe.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),re(n,{code:W.invalid_type,expected:"integer",received:"float",message:r.message}),i.dirty()):r.kind==="min"?(r.inclusive?t.data<r.value:t.data<=r.value)&&(n=this._getOrReturnCtx(t,n),re(n,{code:W.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()):r.kind==="max"?(r.inclusive?t.data>r.value:t.data>=r.value)&&(n=this._getOrReturnCtx(t,n),re(n,{code:W.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()):r.kind==="multipleOf"?FK(t.data,r.value)!==0&&(n=this._getOrReturnCtx(t,n),re(n,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()):r.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),re(n,{code:W.not_finite,message:r.message}),i.dirty()):Oe.assertNever(r);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,le.toString(n))}gt(t,n){return this.setLimit("min",t,!1,le.toString(n))}lte(t,n){return this.setLimit("max",t,!0,le.toString(n))}lt(t,n){return this.setLimit("max",t,!1,le.toString(n))}setLimit(t,n,i,r){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:i,message:le.toString(r)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:le.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:le.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:le.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:le.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:le.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:le.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:le.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:le.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:le.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Oe.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(n===null||i.value>n)&&(n=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(n)&&Number.isFinite(t)}};Ga.create=e=>new Ga({checks:[],typeName:V.ZodNumber,coerce:e?.coerce||!1,...ke(e)});Va=class e extends Ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ae.bigint)return this._getInvalidInput(t);let n,i=new Ot;for(let r of this._def.checks)r.kind==="min"?(r.inclusive?t.data<r.value:t.data<=r.value)&&(n=this._getOrReturnCtx(t,n),re(n,{code:W.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()):r.kind==="max"?(r.inclusive?t.data>r.value:t.data>=r.value)&&(n=this._getOrReturnCtx(t,n),re(n,{code:W.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()):r.kind==="multipleOf"?t.data%r.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),re(n,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()):Oe.assertNever(r);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return re(n,{code:W.invalid_type,expected:ae.bigint,received:n.parsedType}),ye}gte(t,n){return this.setLimit("min",t,!0,le.toString(n))}gt(t,n){return this.setLimit("min",t,!1,le.toString(n))}lte(t,n){return this.setLimit("max",t,!0,le.toString(n))}lt(t,n){return this.setLimit("max",t,!1,le.toString(n))}setLimit(t,n,i,r){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:i,message:le.toString(r)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:le.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:le.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:le.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:le.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:le.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Va.create=e=>new Va({checks:[],typeName:V.ZodBigInt,coerce:e?.coerce??!1,...ke(e)});Za=class extends Ie{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ae.boolean){let n=this._getOrReturnCtx(t);return re(n,{code:W.invalid_type,expected:ae.boolean,received:n.parsedType}),ye}return Nt(t.data)}};Za.create=e=>new Za({typeName:V.ZodBoolean,coerce:e?.coerce||!1,...ke(e)});Qa=class e extends Ie{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ae.date){let r=this._getOrReturnCtx(t);return re(r,{code:W.invalid_type,expected:ae.date,received:r.parsedType}),ye}if(Number.isNaN(t.data.getTime())){let r=this._getOrReturnCtx(t);return re(r,{code:W.invalid_date}),ye}let n=new Ot,i;for(let r of this._def.checks)r.kind==="min"?t.data.getTime()<r.value&&(i=this._getOrReturnCtx(t,i),re(i,{code:W.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),n.dirty()):r.kind==="max"?t.data.getTime()>r.value&&(i=this._getOrReturnCtx(t,i),re(i,{code:W.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),n.dirty()):Oe.assertNever(r);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:le.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:le.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};Qa.create=e=>new Qa({checks:[],coerce:e?.coerce||!1,typeName:V.ZodDate,...ke(e)});Ya=class extends Ie{_parse(t){if(this._getType(t)!==ae.symbol){let n=this._getOrReturnCtx(t);return re(n,{code:W.invalid_type,expected:ae.symbol,received:n.parsedType}),ye}return Nt(t.data)}};Ya.create=e=>new Ya({typeName:V.ZodSymbol,...ke(e)});Qi=class extends Ie{_parse(t){if(this._getType(t)!==ae.undefined){let n=this._getOrReturnCtx(t);return re(n,{code:W.invalid_type,expected:ae.undefined,received:n.parsedType}),ye}return Nt(t.data)}};Qi.create=e=>new Qi({typeName:V.ZodUndefined,...ke(e)});Yi=class extends Ie{_parse(t){if(this._getType(t)!==ae.null){let n=this._getOrReturnCtx(t);return re(n,{code:W.invalid_type,expected:ae.null,received:n.parsedType}),ye}return Nt(t.data)}};Yi.create=e=>new Yi({typeName:V.ZodNull,...ke(e)});Xa=class extends Ie{constructor(){super(...arguments),this._any=!0}_parse(t){return Nt(t.data)}};Xa.create=e=>new Xa({typeName:V.ZodAny,...ke(e)});br=class extends Ie{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Nt(t.data)}};br.create=e=>new br({typeName:V.ZodUnknown,...ke(e)});Ln=class extends Ie{_parse(t){let n=this._getOrReturnCtx(t);return re(n,{code:W.invalid_type,expected:ae.never,received:n.parsedType}),ye}};Ln.create=e=>new Ln({typeName:V.ZodNever,...ke(e)});es=class extends Ie{_parse(t){if(this._getType(t)!==ae.undefined){let n=this._getOrReturnCtx(t);return re(n,{code:W.invalid_type,expected:ae.void,received:n.parsedType}),ye}return Nt(t.data)}};es.create=e=>new es({typeName:V.ZodVoid,...ke(e)});kr=class e extends Ie{_parse(t){let{ctx:n,status:i}=this._processInputParams(t),r=this._def;if(n.parsedType!==ae.array)return re(n,{code:W.invalid_type,expected:ae.array,received:n.parsedType}),ye;if(r.exactLength!==null){let a=n.data.length>r.exactLength.value,s=n.data.length<r.exactLength.value;(a||s)&&(re(n,{code:a?W.too_big:W.too_small,minimum:s?r.exactLength.value:void 0,maximum:a?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),i.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(re(n,{code:W.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),i.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(re(n,{code:W.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),i.dirty()),n.common.async)return Promise.all([...n.data].map((a,s)=>r.type._parseAsync(new fn(n,a,n.path,s)))).then(a=>Ot.mergeArray(i,a));let o=[...n.data].map((a,s)=>r.type._parseSync(new fn(n,a,n.path,s)));return Ot.mergeArray(i,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:le.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:le.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:le.toString(n)}})}nonempty(t){return this.min(1,t)}};kr.create=(e,t)=>new kr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...ke(t)});Xt=class e extends Ie{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=Oe.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==ae.object){let d=this._getOrReturnCtx(t);return re(d,{code:W.invalid_type,expected:ae.object,received:d.parsedType}),ye}let{status:n,ctx:i}=this._processInputParams(t),{shape:r,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ln&&this._def.unknownKeys==="strip"))for(let d in i.data)o.includes(d)||a.push(d);let s=[];for(let d of o){let u=r[d],l=i.data[d];s.push({key:{status:"valid",value:d},value:u._parse(new fn(i,l,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof Ln){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of a)s.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")a.length>0&&(re(i,{code:W.unrecognized_keys,keys:a}),n.dirty());else if(d!=="strip")throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of a){let l=i.data[u];s.push({key:{status:"valid",value:u},value:d._parse(new fn(i,l,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of s){let l=await u.key,p=await u.value;d.push({key:l,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>Ot.mergeObjectSync(n,d)):Ot.mergeObjectSync(n,s)}get shape(){return this._def.shape()}strict(t){return le.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,i)=>{let r=this._def.errorMap?.(n,i).message??i.defaultError;return n.code==="unrecognized_keys"?{message:le.errToObj(t).message??r}:{message:r}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:V.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let i of Oe.objectKeys(t))t[i]&&this.shape[i]&&(n[i]=this.shape[i]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let i of Oe.objectKeys(this.shape))t[i]||(n[i]=this.shape[i]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ai(this)}partial(t){let n={};for(let i of Oe.objectKeys(this.shape)){let r=this.shape[i];t&&!t[i]?n[i]=r:n[i]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let i of Oe.objectKeys(this.shape))if(t&&!t[i])n[i]=this.shape[i];else{let r=this.shape[i];for(;r instanceof cn;)r=r._def.innerType;n[i]=r}return new e({...this._def,shape:()=>n})}keyof(){return $x(Oe.objectKeys(this.shape))}};Xt.create=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strip",catchall:Ln.create(),typeName:V.ZodObject,...ke(t)});Xt.strictCreate=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strict",catchall:Ln.create(),typeName:V.ZodObject,...ke(t)});Xt.lazycreate=(e,t)=>new Xt({shape:e,unknownKeys:"strip",catchall:Ln.create(),typeName:V.ZodObject,...ke(t)});Xi=class extends Ie{_parse(t){let{ctx:n}=this._processInputParams(t),i=this._def.options;function r(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return n.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(s=>new ln(s.ctx.common.issues));return re(n,{code:W.invalid_union,unionErrors:a}),ye}if(n.common.async)return Promise.all(i.map(async o=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(r);{let o,a=[];for(let d of i){let u={...n,common:{...n.common,issues:[]},parent:null},l=d._parseSync({data:n.data,path:n.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let s=a.map(d=>new ln(d));return re(n,{code:W.invalid_union,unionErrors:s}),ye}}get options(){return this._def.options}};Xi.create=(e,t)=>new Xi({options:e,typeName:V.ZodUnion,...ke(t)});Qn=e=>e instanceof to?Qn(e.schema):e instanceof Tn?Qn(e.innerType()):e instanceof no?[e.value]:e instanceof ro?e.options:e instanceof io?Oe.objectValues(e.enum):e instanceof oo?Qn(e._def.innerType):e instanceof Qi?[void 0]:e instanceof Yi?[null]:e instanceof cn?[void 0,...Qn(e.unwrap())]:e instanceof ir?[null,...Qn(e.unwrap())]:e instanceof Tu||e instanceof so?Qn(e.unwrap()):e instanceof ao?Qn(e._def.innerType):[],wf=class e extends Ie{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==ae.object)return re(n,{code:W.invalid_type,expected:ae.object,received:n.parsedType}),ye;let i=this.discriminator,r=n.data[i],o=this.optionsMap.get(r);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(re(n,{code:W.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),ye)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,i){let r=new Map;for(let o of n){let a=Qn(o.shape[t]);if(!a.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let s of a){if(r.has(s))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);r.set(s,o)}}return new e({typeName:V.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:r,...ke(i)})}};eo=class extends Ie{_parse(t){let{status:n,ctx:i}=this._processInputParams(t),r=(o,a)=>{if(fw(o)||fw(a))return ye;let s=Sf(o.value,a.value);return s.valid?((mw(o)||mw(a))&&n.dirty(),{status:n.value,value:s.data}):(re(i,{code:W.invalid_intersection_types}),ye)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([o,a])=>r(o,a)):r(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}};eo.create=(e,t,n)=>new eo({left:e,right:t,typeName:V.ZodIntersection,...ke(n)});rr=class e extends Ie{_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==ae.array)return re(i,{code:W.invalid_type,expected:ae.array,received:i.parsedType}),ye;if(i.data.length<this._def.items.length)return re(i,{code:W.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ye;!this._def.rest&&i.data.length>this._def.items.length&&(re(i,{code:W.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let r=[...i.data].map((o,a)=>{let s=this._def.items[a]||this._def.rest;return s?s._parse(new fn(i,o,i.path,a)):null}).filter(o=>!!o);return i.common.async?Promise.all(r).then(o=>Ot.mergeArray(n,o)):Ot.mergeArray(n,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};rr.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new rr({items:e,typeName:V.ZodTuple,rest:null,...ke(t)})};kf=class e extends Ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==ae.object)return re(i,{code:W.invalid_type,expected:ae.object,received:i.parsedType}),ye;let r=[],o=this._def.keyType,a=this._def.valueType;for(let s in i.data)r.push({key:o._parse(new fn(i,s,i.path,s)),value:a._parse(new fn(i,i.data[s],i.path,s)),alwaysSet:s in i.data});return i.common.async?Ot.mergeObjectAsync(n,r):Ot.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(t,n,i){return n instanceof Ie?new e({keyType:t,valueType:n,typeName:V.ZodRecord,...ke(i)}):new e({keyType:Zi.create(),valueType:t,typeName:V.ZodRecord,...ke(n)})}},ts=class extends Ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==ae.map)return re(i,{code:W.invalid_type,expected:ae.map,received:i.parsedType}),ye;let r=this._def.keyType,o=this._def.valueType,a=[...i.data.entries()].map(([s,d],u)=>({key:r._parse(new fn(i,s,i.path,[u,"key"])),value:o._parse(new fn(i,d,i.path,[u,"value"]))}));if(i.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let d of a){let u=await d.key,l=await d.value;if(u.status==="aborted"||l.status==="aborted")return ye;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),s.set(u.value,l.value)}return{status:n.value,value:s}})}else{let s=new Map;for(let d of a){let{key:u,value:l}=d;if(u.status==="aborted"||l.status==="aborted")return ye;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),s.set(u.value,l.value)}return{status:n.value,value:s}}}};ts.create=(e,t,n)=>new ts({valueType:t,keyType:e,typeName:V.ZodMap,...ke(n)});ns=class e extends Ie{_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.parsedType!==ae.set)return re(i,{code:W.invalid_type,expected:ae.set,received:i.parsedType}),ye;let r=this._def;r.minSize!==null&&i.data.size<r.minSize.value&&(re(i,{code:W.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&i.data.size>r.maxSize.value&&(re(i,{code:W.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());let o=this._def.valueType;function a(d){let u=new Set;for(let l of d){if(l.status==="aborted")return ye;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let s=[...i.data.values()].map((d,u)=>o._parse(new fn(i,d,i.path,u)));return i.common.async?Promise.all(s).then(d=>a(d)):a(s)}min(t,n){return new e({...this._def,minSize:{value:t,message:le.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:le.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};ns.create=(e,t)=>new ns({valueType:e,minSize:null,maxSize:null,typeName:V.ZodSet,...ke(t)});xf=class e extends Ie{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==ae.function)return re(n,{code:W.invalid_type,expected:ae.function,received:n.parsedType}),ye;function i(s,d){return bf({data:s,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vf(),Ha].filter(u=>!!u),issueData:{code:W.invalid_arguments,argumentsError:d}})}function r(s,d){return bf({data:s,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vf(),Ha].filter(u=>!!u),issueData:{code:W.invalid_return_type,returnTypeError:d}})}let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof Xr){let s=this;return Nt(async function(...d){let u=new ln([]),l=await s._def.args.parseAsync(d,o).catch(m=>{throw u.addIssue(i(d,m)),u}),p=await Reflect.apply(a,this,l);return await s._def.returns._def.type.parseAsync(p,o).catch(m=>{throw u.addIssue(r(p,m)),u})})}else{let s=this;return Nt(function(...d){let u=s._def.args.safeParse(d,o);if(!u.success)throw new ln([i(d,u.error)]);let l=Reflect.apply(a,this,u.data),p=s._def.returns.safeParse(l,o);if(!p.success)throw new ln([r(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:rr.create(t).rest(br.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,i){return new e({args:t||rr.create([]).rest(br.create()),returns:n||br.create(),typeName:V.ZodFunction,...ke(i)})}},to=class extends Ie{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};to.create=(e,t)=>new to({getter:e,typeName:V.ZodLazy,...ke(t)});no=class extends Ie{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return re(n,{received:n.data,code:W.invalid_literal,expected:this._def.value}),ye}return{status:"valid",value:t.data}}get value(){return this._def.value}};no.create=(e,t)=>new no({value:e,typeName:V.ZodLiteral,...ke(t)});ro=class e extends Ie{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),i=this._def.values;return re(n,{expected:Oe.joinValues(i),received:n.parsedType,code:W.invalid_type}),ye}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),i=this._def.values;return re(n,{received:n.data,code:W.invalid_enum_value,options:i}),ye}return Nt(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(i=>!t.includes(i)),{...this._def,...n})}};ro.create=$x;io=class extends Ie{_parse(t){let n=Oe.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==ae.string&&i.parsedType!==ae.number){let r=Oe.objectValues(n);return re(i,{expected:Oe.joinValues(r),received:i.parsedType,code:W.invalid_type}),ye}if(this._cache||(this._cache=new Set(Oe.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let r=Oe.objectValues(n);return re(i,{received:i.data,code:W.invalid_enum_value,options:r}),ye}return Nt(t.data)}get enum(){return this._def.values}};io.create=(e,t)=>new io({values:e,typeName:V.ZodNativeEnum,...ke(t)});Xr=class extends Ie{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==ae.promise&&n.common.async===!1)return re(n,{code:W.invalid_type,expected:ae.promise,received:n.parsedType}),ye;let i=n.parsedType===ae.promise?n.data:Promise.resolve(n.data);return Nt(i.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Xr.create=(e,t)=>new Xr({type:e,typeName:V.ZodPromise,...ke(t)});Tn=class extends Ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:i}=this._processInputParams(t),r=this._def.effect||null,o={addIssue:a=>{re(i,a),a.fatal?n.abort():n.dirty()},get path(){return i.path}};if(o.addIssue=o.addIssue.bind(o),r.type==="preprocess"){let a=r.transform(i.data,o);if(i.common.async)return Promise.resolve(a).then(async s=>{if(n.value==="aborted")return ye;let d=await this._def.schema._parseAsync({data:s,path:i.path,parent:i});return d.status==="aborted"?ye:d.status==="dirty"||n.value==="dirty"?Ca(d.value):d});{if(n.value==="aborted")return ye;let s=this._def.schema._parseSync({data:a,path:i.path,parent:i});return s.status==="aborted"?ye:s.status==="dirty"||n.value==="dirty"?Ca(s.value):s}}if(r.type==="refinement"){let a=s=>{let d=r.refinement(s,o);if(i.common.async)return Promise.resolve(d);if(d instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(i.common.async===!1){let s=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?ye:(s.status==="dirty"&&n.dirty(),a(s.value),{status:n.value,value:s.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(s=>s.status==="aborted"?ye:(s.status==="dirty"&&n.dirty(),a(s.value).then(()=>({status:n.value,value:s.value}))))}if(r.type==="transform")if(i.common.async===!1){let a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Vi(a))return ye;let s=r.transform(a.value,o);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:s}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>Vi(a)?Promise.resolve(r.transform(a.value,o)).then(s=>({status:n.value,value:s})):ye);Oe.assertNever(r)}};Tn.create=(e,t,n)=>new Tn({schema:e,typeName:V.ZodEffects,effect:t,...ke(n)});Tn.createWithPreprocess=(e,t,n)=>new Tn({schema:t,effect:{type:"preprocess",transform:e},typeName:V.ZodEffects,...ke(n)});cn=class extends Ie{_parse(t){return this._getType(t)===ae.undefined?Nt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};cn.create=(e,t)=>new cn({innerType:e,typeName:V.ZodOptional,...ke(t)});ir=class extends Ie{_parse(t){return this._getType(t)===ae.null?Nt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ir.create=(e,t)=>new ir({innerType:e,typeName:V.ZodNullable,...ke(t)});oo=class extends Ie{_parse(t){let{ctx:n}=this._processInputParams(t),i=n.data;return n.parsedType===ae.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};oo.create=(e,t)=>new oo({innerType:e,typeName:V.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ke(t)});ao=class extends Ie{_parse(t){let{ctx:n}=this._processInputParams(t),i={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Cu(r)?r.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ln(i.common.issues)},input:i.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ln(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}};ao.create=(e,t)=>new ao({innerType:e,typeName:V.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ke(t)});rs=class extends Ie{_parse(t){if(this._getType(t)!==ae.nan){let n=this._getOrReturnCtx(t);return re(n,{code:W.invalid_type,expected:ae.nan,received:n.parsedType}),ye}return{status:"valid",value:t.data}}};rs.create=e=>new rs({typeName:V.ZodNaN,...ke(e)});Tu=class extends Ie{_parse(t){let{ctx:n}=this._processInputParams(t),i=n.data;return this._def.type._parse({data:i,path:n.path,parent:n})}unwrap(){return this._def.type}},Iu=class e extends Ie{_parse(t){let{status:n,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?ye:r.status==="dirty"?(n.dirty(),Ca(r.value)):this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();{let r=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?ye:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:i.path,parent:i})}}static create(t,n){return new e({in:t,out:n,typeName:V.ZodPipeline})}},so=class extends Ie{_parse(t){let n=this._def.innerType._parse(t),i=r=>(Vi(r)&&(r.value=Object.freeze(r.value)),r);return Cu(n)?n.then(r=>i(r)):i(n)}unwrap(){return this._def.innerType}};so.create=(e,t)=>new so({innerType:e,typeName:V.ZodReadonly,...ke(t)});Zae={object:Xt.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(V||(V={}));Qae=Zi.create,Yae=Ga.create,Xae=rs.create,ese=Va.create,tse=Za.create,nse=Qa.create,rse=Ya.create,ise=Qi.create,ose=Yi.create,ase=Xa.create,sse=br.create,dse=Ln.create,use=es.create,lse=kr.create,zK=Xt.create,cse=Xt.strictCreate,pse=Xi.create,fse=wf.create,mse=eo.create,hse=rr.create,gse=kf.create,yse=ts.create,_se=ns.create,vse=xf.create,bse=to.create,wse=no.create,Sse=ro.create,kse=io.create,xse=Xr.create,Cse=Tn.create,Tse=cn.create,Ise=ir.create,Pse=Tn.createWithPreprocess,Ese=Iu.create,Mx={};Fn(Mx,{version:()=>J0,util:()=>Ee,treeifyError:()=>Wx,toJSONSchema:()=>Zh,toDotPath:()=>Hx,safeParseAsync:()=>Il,safeParse:()=>Tl,registry:()=>hh,regexes:()=>th,prettifyError:()=>Gx,parseAsync:()=>Ou,parse:()=>Ru,locales:()=>mh,isValidJWT:()=>hC,isValidBase64URL:()=>pC,isValidBase64:()=>oh,globalRegistry:()=>tr,globalConfig:()=>Pu,function:()=>NT,formatError:()=>Zm,flattenError:()=>Vm,config:()=>At,clone:()=>On,_xid:()=>Ih,_void:()=>ST,_uuidv7:()=>bh,_uuidv6:()=>vh,_uuidv4:()=>_h,_uuid:()=>yh,_url:()=>wh,_uppercase:()=>Uh,_unknown:()=>ju,_union:()=>B6,_undefined:()=>_T,_ulid:()=>Th,_uint64:()=>gT,_uint32:()=>lT,_tuple:()=>OT,_trim:()=>Wh,_transform:()=>Y6,_toUpperCase:()=>Gh,_toLowerCase:()=>Hh,_templateLiteral:()=>sW,_symbol:()=>yT,_success:()=>rW,_stringbool:()=>jT,_stringFormat:()=>qT,_string:()=>QC,_startsWith:()=>zh,_size:()=>Nh,_set:()=>G6,_safeParseAsync:()=>eh,_safeParse:()=>Xm,_regex:()=>Dh,_refine:()=>MT,_record:()=>W6,_readonly:()=>aW,_property:()=>RT,_promise:()=>uW,_positive:()=>TT,_pipe:()=>oW,_parseAsync:()=>Ym,_parse:()=>Qm,_overwrite:()=>di,_optional:()=>X6,_number:()=>iT,_nullable:()=>eW,_null:()=>vT,_normalize:()=>Jh,_nonpositive:()=>PT,_nonoptional:()=>nW,_nonnegative:()=>ET,_never:()=>wT,_negative:()=>IT,_nativeEnum:()=>Z6,_nanoid:()=>kh,_nan:()=>CT,_multipleOf:()=>ss,_minSize:()=>ds,_minLength:()=>lo,_min:()=>Zt,_mime:()=>Kh,_maxSize:()=>El,_maxLength:()=>Rl,_max:()=>xn,_map:()=>H6,_lte:()=>xn,_lt:()=>ei,_lowercase:()=>Lh,_literal:()=>Q6,_length:()=>Ol,_lazy:()=>dW,_ksuid:()=>Ph,_jwt:()=>qh,_isoTime:()=>nT,_isoDuration:()=>rT,_isoDateTime:()=>eT,_isoDate:()=>tT,_ipv6:()=>Rh,_ipv4:()=>Eh,_intersection:()=>J6,_int64:()=>hT,_int32:()=>uT,_int:()=>aT,_includes:()=>Fh,_guid:()=>Mu,_gte:()=>Zt,_gt:()=>ti,_float64:()=>dT,_float32:()=>sT,_file:()=>AT,_enum:()=>V6,_endsWith:()=>Bh,_emoji:()=>Sh,_email:()=>gh,_e164:()=>jh,_discriminatedUnion:()=>K6,_default:()=>tW,_date:()=>kT,_custom:()=>$T,_cuid2:()=>Ch,_cuid:()=>xh,_coercedString:()=>YC,_coercedNumber:()=>oT,_coercedDate:()=>xT,_coercedBoolean:()=>pT,_coercedBigint:()=>mT,_cidrv6:()=>Ah,_cidrv4:()=>Oh,_catch:()=>iW,_boolean:()=>cT,_bigint:()=>fT,_base64url:()=>Mh,_base64:()=>$h,_array:()=>Vh,_any:()=>bT,TimePrecision:()=>XC,NEVER:()=>jx,JSONSchemaGenerator:()=>us,JSONSchema:()=>lW,Doc:()=>Au,$output:()=>VC,$input:()=>ZC,$constructor:()=>q,$brand:()=>qx,$ZodXID:()=>tC,$ZodVoid:()=>CC,$ZodUnknown:()=>$u,$ZodUnion:()=>ch,$ZodUndefined:()=>wC,$ZodUUID:()=>H0,$ZodURL:()=>V0,$ZodULID:()=>eC,$ZodType:()=>ve,$ZodTuple:()=>Pl,$ZodTransform:()=>ph,$ZodTemplateLiteral:()=>KC,$ZodSymbol:()=>bC,$ZodSuccess:()=>UC,$ZodStringFormat:()=>Ke,$ZodString:()=>Ss,$ZodSet:()=>OC,$ZodRegistry:()=>as,$ZodRecord:()=>EC,$ZodRealError:()=>bs,$ZodReadonly:()=>BC,$ZodPromise:()=>JC,$ZodPrefault:()=>DC,$ZodPipe:()=>fh,$ZodOptional:()=>jC,$ZodObject:()=>lh,$ZodNumberFormat:()=>_C,$ZodNumber:()=>ah,$ZodNullable:()=>qC,$ZodNull:()=>SC,$ZodNonOptional:()=>LC,$ZodNever:()=>xC,$ZodNanoID:()=>Q0,$ZodNaN:()=>zC,$ZodMap:()=>RC,$ZodLiteral:()=>$C,$ZodLazy:()=>WC,$ZodKSUID:()=>nC,$ZodJWT:()=>gC,$ZodIntersection:()=>PC,$ZodISOTime:()=>oC,$ZodISODuration:()=>aC,$ZodISODateTime:()=>rC,$ZodISODate:()=>iC,$ZodIPv6:()=>dC,$ZodIPv4:()=>sC,$ZodGUID:()=>W0,$ZodFunction:()=>qu,$ZodFile:()=>MC,$ZodError:()=>Gm,$ZodEnum:()=>AC,$ZodEmoji:()=>Z0,$ZodEmail:()=>G0,$ZodE164:()=>mC,$ZodDiscriminatedUnion:()=>IC,$ZodDefault:()=>NC,$ZodDate:()=>TC,$ZodCustomStringFormat:()=>yC,$ZodCustom:()=>HC,$ZodCheckUpperCase:()=>D0,$ZodCheckStringFormat:()=>ws,$ZodCheckStartsWith:()=>U0,$ZodCheckSizeEquals:()=>A0,$ZodCheckRegex:()=>q0,$ZodCheckProperty:()=>z0,$ZodCheckOverwrite:()=>K0,$ZodCheckNumberFormat:()=>P0,$ZodCheckMultipleOf:()=>I0,$ZodCheckMinSize:()=>O0,$ZodCheckMinLength:()=>M0,$ZodCheckMimeType:()=>B0,$ZodCheckMaxSize:()=>R0,$ZodCheckMaxLength:()=>$0,$ZodCheckLowerCase:()=>N0,$ZodCheckLessThan:()=>rh,$ZodCheckLengthEquals:()=>j0,$ZodCheckIncludes:()=>L0,$ZodCheckGreaterThan:()=>ih,$ZodCheckEndsWith:()=>F0,$ZodCheckBigIntFormat:()=>E0,$ZodCheck:()=>at,$ZodCatch:()=>FC,$ZodCUID2:()=>X0,$ZodCUID:()=>Y0,$ZodCIDRv6:()=>lC,$ZodCIDRv4:()=>uC,$ZodBoolean:()=>sh,$ZodBigIntFormat:()=>vC,$ZodBigInt:()=>dh,$ZodBase64URL:()=>fC,$ZodBase64:()=>cC,$ZodAsyncError:()=>xr,$ZodArray:()=>uh,$ZodAny:()=>kC});jx=Object.freeze({status:"aborted"});qx=Symbol("zod_brand"),xr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Pu={};Ee={};Fn(Ee,{unwrapMessage:()=>Ta,stringifyPrimitive:()=>Ce,required:()=>oJ,randomString:()=>ZK,propertyKeyTypes:()=>Eu,promiseAllObject:()=>VK,primitiveTypes:()=>Ux,prefixIssues:()=>un,pick:()=>eJ,partial:()=>iJ,optionalKeys:()=>Fx,omit:()=>tJ,numKeys:()=>QK,nullish:()=>ai,normalizeParams:()=>Q,merge:()=>rJ,jsonStringifyReplacer:()=>Nx,joinValues:()=>te,issue:()=>Kx,isPlainObject:()=>os,isObject:()=>is,getSizableOrigin:()=>xl,getParsedType:()=>YK,getLengthableOrigin:()=>Cl,getEnumValues:()=>Jm,getElementAtPath:()=>GK,floatSafeRemainder:()=>Dx,finalizeIssue:()=>In,extend:()=>nJ,escapeRegex:()=>si,esc:()=>$i,defineLazy:()=>Ne,createTransparentProxy:()=>XK,clone:()=>On,cleanRegex:()=>kl,cleanEnum:()=>aJ,captureStackTrace:()=>Hm,cached:()=>Sl,assignProp:()=>Wm,assertNotEqual:()=>KK,assertNever:()=>WK,assertIs:()=>JK,assertEqual:()=>BK,assert:()=>HK,allowsEval:()=>Lx,aborted:()=>Li,NUMBER_FORMAT_RANGES:()=>zx,Class:()=>Cf,BIGINT_FORMAT_RANGES:()=>Bx});Hm=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};Lx=Sl(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch{return!1}});YK=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw Error(`Unknown data type: ${t}`)}},Eu=new Set(["string","number","symbol"]),Ux=new Set(["string","number","bigint","boolean","symbol","undefined"]);zx={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Bx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Cf=class{constructor(...t){}},Jx=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,Nx,2)},enumerable:!0})},Gm=q("$ZodError",Jx),bs=q("$ZodError",Jx,{Parent:Error});Qm=e=>(t,n,i,r)=>{let o=i?Object.assign(i,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new xr;if(a.issues.length){let s=new(r?.Err??e)(a.issues.map(d=>In(d,o,At())));throw Hm(s,r?.callee),s}return a.value},Ru=Qm(bs),Ym=e=>async(t,n,i,r)=>{let o=i?Object.assign(i,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(r?.Err??e)(a.issues.map(d=>In(d,o,At())));throw Hm(s,r?.callee),s}return a.value},Ou=Ym(bs),Xm=e=>(t,n,i)=>{let r=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new xr;return o.issues.length?{success:!1,error:new(e??Gm)(o.issues.map(a=>In(a,r,At())))}:{success:!0,data:o.value}},Tl=Xm(bs),eh=e=>async(t,n,i)=>{let r=i?Object.assign(i,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(a=>In(a,r,At())))}:{success:!0,data:o.value}},Il=eh(bs),th={};Fn(th,{xid:()=>Yx,uuid7:()=>lJ,uuid6:()=>uJ,uuid4:()=>dJ,uuid:()=>uo,uppercase:()=>C0,unicodeEmail:()=>fJ,undefined:()=>k0,ulid:()=>Qx,time:()=>h0,string:()=>y0,rfc5322Email:()=>pJ,number:()=>b0,null:()=>S0,nanoid:()=>e0,lowercase:()=>x0,ksuid:()=>Xx,ipv6:()=>a0,ipv4:()=>o0,integer:()=>v0,html5Email:()=>cJ,hostname:()=>l0,guid:()=>n0,extendedDuration:()=>sJ,emoji:()=>i0,email:()=>r0,e164:()=>c0,duration:()=>t0,domain:()=>gJ,datetime:()=>g0,date:()=>f0,cuid2:()=>Zx,cuid:()=>Vx,cidrv6:()=>d0,cidrv4:()=>s0,browserEmail:()=>mJ,boolean:()=>w0,bigint:()=>_0,base64url:()=>nh,base64:()=>u0,_emoji:()=>hJ});Vx=/^[cC][^\s-]{8,}$/,Zx=/^[0-9a-z]+$/,Qx=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yx=/^[0-9a-vA-V]{20}$/,Xx=/^[A-Za-z0-9]{27}$/,e0=/^[a-zA-Z0-9_-]{21}$/,t0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,sJ=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,n0=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uo=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,dJ=uo(4),uJ=uo(6),lJ=uo(7),r0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,cJ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,pJ=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,fJ=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,mJ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,hJ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";o0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,a0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,s0=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,d0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,u0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nh=/^[A-Za-z0-9_-]*$/,l0=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,gJ=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,c0=/^\+(?:[0-9]){6,14}[0-9]$/,p0="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",f0=new RegExp(`^${p0}$`);y0=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},_0=/^\d+n?$/,v0=/^\d+$/,b0=/^-?\d+(?:\.\d+)?/i,w0=/true|false/i,S0=/null/i,k0=/undefined/i,x0=/^[^A-Z]*$/,C0=/^[^a-z]*$/,at=q("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),T0={number:"number",bigint:"bigint",object:"date"},rh=q("$ZodCheckLessThan",(e,t)=>{at.init(e,t);let n=T0[typeof t.value];e._zod.onattach.push(i=>{let r=i._zod.bag,o=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:n,code:"too_big",maximum:t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ih=q("$ZodCheckGreaterThan",(e,t)=>{at.init(e,t);let n=T0[typeof t.value];e._zod.onattach.push(i=>{let r=i._zod.bag,o=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),I0=q("$ZodCheckMultipleOf",(e,t)=>{at.init(e,t),e._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Dx(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),P0=q("$ZodCheckNumberFormat",(e,t)=>{at.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),i=n?"int":"number",[r,o]=zx[t.format];e._zod.onattach.push(a=>{let s=a._zod.bag;s.format=t.format,s.minimum=r,s.maximum=o,n&&(s.pattern=v0)}),e._zod.check=a=>{let s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:i,format:t.format,code:"invalid_type",input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,continue:!t.abort});return}}s<r&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inst:e})}}),E0=q("$ZodCheckBigIntFormat",(e,t)=>{at.init(e,t);let[n,i]=Bx[t.format];e._zod.onattach.push(r=>{let o=r._zod.bag;o.format=t.format,o.minimum=n,o.maximum=i}),e._zod.check=r=>{let o=r.value;o<n&&r.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>i&&r.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inst:e})}}),R0=q("$ZodCheckMaxSize",(e,t)=>{at.init(e,t),e._zod.when=n=>{let i=n.value;return!ai(i)&&i.size!==void 0},e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;i.size<=t.maximum||n.issues.push({origin:xl(i),code:"too_big",maximum:t.maximum,input:i,inst:e,continue:!t.abort})}}),O0=q("$ZodCheckMinSize",(e,t)=>{at.init(e,t),e._zod.when=n=>{let i=n.value;return!ai(i)&&i.size!==void 0},e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;i.size>=t.minimum||n.issues.push({origin:xl(i),code:"too_small",minimum:t.minimum,input:i,inst:e,continue:!t.abort})}}),A0=q("$ZodCheckSizeEquals",(e,t)=>{at.init(e,t),e._zod.when=n=>{let i=n.value;return!ai(i)&&i.size!==void 0},e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.size,i.maximum=t.size,i.size=t.size}),e._zod.check=n=>{let i=n.value,r=i.size;if(r===t.size)return;let o=r>t.size;n.issues.push({origin:xl(i),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),$0=q("$ZodCheckMaxLength",(e,t)=>{at.init(e,t),e._zod.when=n=>{let i=n.value;return!ai(i)&&i.length!==void 0},e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let r=Cl(i);n.issues.push({origin:r,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),M0=q("$ZodCheckMinLength",(e,t)=>{at.init(e,t),e._zod.when=n=>{let i=n.value;return!ai(i)&&i.length!==void 0},e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let r=Cl(i);n.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),j0=q("$ZodCheckLengthEquals",(e,t)=>{at.init(e,t),e._zod.when=n=>{let i=n.value;return!ai(i)&&i.length!==void 0},e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,r=i.length;if(r===t.length)return;let o=Cl(i),a=r>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ws=q("$ZodCheckStringFormat",(e,t)=>{var n,i;at.init(e,t),e._zod.onattach.push(r=>{let o=r._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),q0=q("$ZodCheckRegex",(e,t)=>{ws.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),N0=q("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=x0),ws.init(e,t)}),D0=q("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=C0),ws.init(e,t)}),L0=q("$ZodCheckIncludes",(e,t)=>{at.init(e,t);let n=si(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),U0=q("$ZodCheckStartsWith",(e,t)=>{at.init(e,t);let n=new RegExp(`^${si(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),F0=q("$ZodCheckEndsWith",(e,t)=>{at.init(e,t);let n=new RegExp(`.*${si(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}});z0=q("$ZodCheckProperty",(e,t)=>{at.init(e,t),e._zod.check=n=>{let i=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(i instanceof Promise)return i.then(r=>gw(r,n,t.property));gw(i,n,t.property)}}),B0=q("$ZodCheckMimeType",(e,t)=>{at.init(e,t);let n=new Set(t.mime);e._zod.onattach.push(i=>{i._zod.bag.mime=t.mime}),e._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:t.mime,input:i.value.type,inst:e})}}),K0=q("$ZodCheckOverwrite",(e,t)=>{at.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}}),Au=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
89
+ `).filter(o=>o),i=Math.min(...n.map(o=>o.length-o.trimStart().length)),r=n.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(let o of r)this.content.push(o)}compile(){let t=Function,n=this?.args,i=[...(this?.content??[""]).map(r=>` ${r}`)];return new t(...n,i.join(`
90
+ `))}},J0={major:4,minor:0,patch:0},ve=q("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=J0;let i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(let r of i)for(let o of r._zod.onattach)o(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let r=(o,a,s)=>{let d=Li(o),u;for(let l of a){if(l._zod.when){if(!l._zod.when(o))continue}else if(d)continue;let p=o.issues.length,m=l._zod.check(o);if(m instanceof Promise&&s?.async===!1)throw new xr;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,o.issues.length!==p&&(d||(d=Li(o,p)))});else{if(o.issues.length===p)continue;d||(d=Li(o,p))}}return u?u.then(()=>o):o};e._zod.run=(o,a)=>{let s=e._zod.parse(o,a);if(s instanceof Promise){if(a.async===!1)throw new xr;return s.then(d=>r(d,i,a))}return r(s,i,a)}}e["~standard"]={validate:r=>{try{let o=Tl(e,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Il(e,r).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Ss=q("$ZodString",(e,t)=>{ve.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??y0(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ke=q("$ZodStringFormat",(e,t)=>{ws.init(e,t),Ss.init(e,t)}),W0=q("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=n0),Ke.init(e,t)}),H0=q("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=uo(n))}else t.pattern??(t.pattern=uo());Ke.init(e,t)}),G0=q("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=r0),Ke.init(e,t)}),V0=q("$ZodURL",(e,t)=>{Ke.init(e,t),e._zod.check=n=>{try{let i=n.value,r=new URL(i),o=r.href;t.hostname&&(t.hostname.lastIndex=0,!t.hostname.test(r.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:l0.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,!t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!i.endsWith("/")&&o.endsWith("/")?n.value=o.slice(0,-1):n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Z0=q("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=i0()),Ke.init(e,t)}),Q0=q("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=e0),Ke.init(e,t)}),Y0=q("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Vx),Ke.init(e,t)}),X0=q("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Zx),Ke.init(e,t)}),eC=q("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Qx),Ke.init(e,t)}),tC=q("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Yx),Ke.init(e,t)}),nC=q("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Xx),Ke.init(e,t)}),rC=q("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=g0(t)),Ke.init(e,t)}),iC=q("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=f0),Ke.init(e,t)}),oC=q("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=h0(t)),Ke.init(e,t)}),aC=q("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=t0),Ke.init(e,t)}),sC=q("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=o0),Ke.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv4"})}),dC=q("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=a0),Ke.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),uC=q("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=s0),Ke.init(e,t)}),lC=q("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=d0),Ke.init(e,t),e._zod.check=n=>{let[i,r]=n.value.split("/");try{if(!r)throw Error();let o=Number(r);if(`${o}`!==r||o<0||o>128)throw Error();new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});cC=q("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=u0),Ke.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{oh(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});fC=q("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=nh),Ke.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{pC(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),mC=q("$ZodE164",(e,t)=>{t.pattern??(t.pattern=c0),Ke.init(e,t)});gC=q("$ZodJWT",(e,t)=>{Ke.init(e,t),e._zod.check=n=>{hC(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),yC=q("$ZodCustomStringFormat",(e,t)=>{Ke.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),ah=q("$ZodNumber",(e,t)=>{ve.init(e,t),e._zod.pattern=e._zod.bag.pattern??b0,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let o=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),_C=q("$ZodNumber",(e,t)=>{P0.init(e,t),ah.init(e,t)}),sh=q("$ZodBoolean",(e,t)=>{ve.init(e,t),e._zod.pattern=w0,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=!!n.value}catch{}let r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),dh=q("$ZodBigInt",(e,t)=>{ve.init(e,t),e._zod.pattern=_0,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),vC=q("$ZodBigInt",(e,t)=>{E0.init(e,t),dh.init(e,t)}),bC=q("$ZodSymbol",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;return typeof r=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),n}}),wC=q("$ZodUndefined",(e,t)=>{ve.init(e,t),e._zod.pattern=k0,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,i)=>{let r=n.value;return typeof r>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),n}}),SC=q("$ZodNull",(e,t)=>{ve.init(e,t),e._zod.pattern=S0,e._zod.values=new Set([null]),e._zod.parse=(n,i)=>{let r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),kC=q("$ZodAny",(e,t)=>{ve.init(e,t),e._zod.parse=n=>n}),$u=q("$ZodUnknown",(e,t)=>{ve.init(e,t),e._zod.parse=n=>n}),xC=q("$ZodNever",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),CC=q("$ZodVoid",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;return typeof r>"u"||n.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),n}}),TC=q("$ZodDate",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}let r=n.value,o=r instanceof Date;return o&&!Number.isNaN(r.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:r,...o?{received:"Invalid Date"}:{},inst:e}),n}});uh=q("$ZodArray",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);let o=[];for(let a=0;a<r.length;a++){let s=r[a],d=t.element._zod.run({value:s,issues:[]},i);d instanceof Promise?o.push(d.then(u=>yw(u,n,a))):yw(d,n,a)}return o.length?Promise.all(o).then(()=>n):n}});lh=q("$ZodObject",(e,t)=>{ve.init(e,t);let n=Sl(()=>{let l=Object.keys(t.shape);for(let m of l)if(!(t.shape[m]instanceof ve))throw Error(`Invalid element at key "${m}": expected a Zod schema`);let p=Fx(t.shape);return{shape:t.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(p)}});Ne(e._zod,"propValues",()=>{let l=t.shape,p={};for(let m in l){let f=l[m]._zod;if(f.values){p[m]??(p[m]=new Set);for(let h of f.values)p[m].add(h)}}return p});let i=l=>{let p=new Au(["shape","payload","ctx"]),m=n.value,f=g=>{let v=$i(g);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),y=0;for(let g of m.keys)h[g]=`key_${y++}`;p.write("const newResult = {}");for(let g of m.keys)if(m.optionalKeys.has(g)){let v=h[g];p.write(`const ${v} = ${f(g)};`);let b=$i(g);p.write(`
91
+ if (${v}.issues.length) {
92
+ if (input[${b}] === undefined) {
93
+ if (${b} in input) {
94
+ newResult[${b}] = undefined;
95
+ }
96
+ } else {
97
+ payload.issues = payload.issues.concat(
98
+ ${v}.issues.map((iss) => ({
99
+ ...iss,
100
+ path: iss.path ? [${b}, ...iss.path] : [${b}],
101
+ }))
102
+ );
103
+ }
104
+ } else if (${v}.value === undefined) {
105
+ if (${b} in input) newResult[${b}] = undefined;
106
+ } else {
107
+ newResult[${b}] = ${v}.value;
108
+ }
109
+ `)}else{let v=h[g];p.write(`const ${v} = ${f(g)};`),p.write(`
110
+ if (${v}.issues.length) payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
111
+ ...iss,
112
+ path: iss.path ? [${$i(g)}, ...iss.path] : [${$i(g)}]
113
+ })));`),p.write(`newResult[${$i(g)}] = ${v}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let w=p.compile();return(g,v)=>w(l,g,v)},r,o=is,a=!Pu.jitless,s=a&&Lx.value,d=t.catchall,u;e._zod.parse=(l,p)=>{u??(u=n.value);let m=l.value;if(!o(m))return l.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),l;let f=[];if(a&&s&&p?.async===!1&&p.jitless!==!0)r||(r=i(t.shape)),l=r(l,p);else{l.value={};let v=u.shape;for(let b of u.keys){let S=v[b],T=S._zod.run({value:m[b],issues:[]},p),C=S._zod.optin==="optional"&&S._zod.optout==="optional";T instanceof Promise?f.push(T.then(_=>C?_w(_,l,b,m):kd(_,l,b))):C?_w(T,l,b,m):kd(T,l,b)}}if(!d)return f.length?Promise.all(f).then(()=>l):l;let h=[],y=u.keySet,w=d._zod,g=w.def.type;for(let v of Object.keys(m)){if(y.has(v))continue;if(g==="never"){h.push(v);continue}let b=w.run({value:m[v],issues:[]},p);b instanceof Promise?f.push(b.then(S=>kd(S,l,v))):kd(b,l,v)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:e}),f.length?Promise.all(f).then(()=>l):l}});ch=q("$ZodUnion",(e,t)=>{ve.init(e,t),Ne(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Ne(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Ne(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),Ne(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){let n=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>kl(i.source)).join("|")})$`)}}),e._zod.parse=(n,i)=>{let r=!1,o=[];for(let a of t.options){let s=a._zod.run({value:n.value,issues:[]},i);if(s instanceof Promise)o.push(s),r=!0;else{if(s.issues.length===0)return s;o.push(s)}}return r?Promise.all(o).then(a=>vw(a,n,e,i)):vw(o,n,e,i)}}),IC=q("$ZodDiscriminatedUnion",(e,t)=>{ch.init(e,t);let n=e._zod.parse;Ne(e._zod,"propValues",()=>{let r={};for(let o of t.options){let a=o._zod.propValues;if(!a||Object.keys(a).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let[s,d]of Object.entries(a)){r[s]||(r[s]=new Set);for(let u of d)r[s].add(u)}}return r});let i=Sl(()=>{let r=t.options,o=new Map;for(let a of r){let s=a._zod.propValues[t.discriminator];if(!s||s.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let d of s){if(o.has(d))throw Error(`Duplicate discriminator value "${String(d)}"`);o.set(d,a)}}return o});e._zod.parse=(r,o)=>{let a=r.value;if(!is(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;let s=i.value.get(a?.[t.discriminator]);return s?s._zod.run(r,o):t.unionFallback?n(r,o):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),r)}}),PC=q("$ZodIntersection",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=n.value,o=t.left._zod.run({value:r,issues:[]},i),a=t.right._zod.run({value:r,issues:[]},i);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([s,d])=>bw(n,s,d)):bw(n,o,a)}});Pl=q("$ZodTuple",(e,t)=>{ve.init(e,t);let n=t.items,i=n.length-[...n].reverse().findIndex(r=>r._zod.optin!=="optional");e._zod.parse=(r,o)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=[];let s=[];if(!t.rest){let u=a.length>n.length,l=a.length<i-1;if(u||l)return r.issues.push({input:a,inst:e,origin:"array",...u?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),r}let d=-1;for(let u of n){if(d++,d>=a.length&&d>=i)continue;let l=u._zod.run({value:a[d],issues:[]},o);l instanceof Promise?s.push(l.then(p=>xd(p,r,d))):xd(l,r,d)}if(t.rest){let u=a.slice(n.length);for(let l of u){d++;let p=t.rest._zod.run({value:l,issues:[]},o);p instanceof Promise?s.push(p.then(m=>xd(m,r,d))):xd(p,r,d)}}return s.length?Promise.all(s).then(()=>r):r}});EC=q("$ZodRecord",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!os(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;let o=[];if(t.keyType._zod.values){let a=t.keyType._zod.values;n.value={};for(let d of a)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){let u=t.valueType._zod.run({value:r[d],issues:[]},i);u instanceof Promise?o.push(u.then(l=>{l.issues.length&&n.issues.push(...un(d,l.issues)),n.value[d]=l.value})):(u.issues.length&&n.issues.push(...un(d,u.issues)),n.value[d]=u.value)}let s;for(let d in r)a.has(d)||(s=s??[],s.push(d));s&&s.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:s})}else{n.value={};for(let a of Reflect.ownKeys(r)){if(a==="__proto__")continue;let s=t.keyType._zod.run({value:a,issues:[]},i);if(s instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(s.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:s.issues.map(u=>In(u,i,At())),input:a,path:[a],inst:e}),n.value[s.value]=s.value;continue}let d=t.valueType._zod.run({value:r[a],issues:[]},i);d instanceof Promise?o.push(d.then(u=>{u.issues.length&&n.issues.push(...un(a,u.issues)),n.value[s.value]=u.value})):(d.issues.length&&n.issues.push(...un(a,d.issues)),n.value[s.value]=d.value)}}return o.length?Promise.all(o).then(()=>n):n}}),RC=q("$ZodMap",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!(r instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:r,inst:e}),n;let o=[];n.value=new Map;for(let[a,s]of r){let d=t.keyType._zod.run({value:a,issues:[]},i),u=t.valueType._zod.run({value:s,issues:[]},i);d instanceof Promise||u instanceof Promise?o.push(Promise.all([d,u]).then(([l,p])=>{ww(l,p,n,a,r,e,i)})):ww(d,u,n,a,r,e,i)}return o.length?Promise.all(o).then(()=>n):n}});OC=q("$ZodSet",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!(r instanceof Set))return n.issues.push({input:r,inst:e,expected:"set",code:"invalid_type"}),n;let o=[];n.value=new Set;for(let a of r){let s=t.valueType._zod.run({value:a,issues:[]},i);s instanceof Promise?o.push(s.then(d=>Sw(d,n))):Sw(s,n)}return o.length?Promise.all(o).then(()=>n):n}});AC=q("$ZodEnum",(e,t)=>{ve.init(e,t);let n=Jm(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(i=>Eu.has(typeof i)).map(i=>typeof i=="string"?si(i):i.toString()).join("|")})$`),e._zod.parse=(i,r)=>{let o=i.value;return e._zod.values.has(o)||i.issues.push({code:"invalid_value",values:n,input:o,inst:e}),i}}),$C=q("$ZodLiteral",(e,t)=>{ve.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?si(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,i)=>{let r=n.value;return e._zod.values.has(r)||n.issues.push({code:"invalid_value",values:t.values,input:r,inst:e}),n}}),MC=q("$ZodFile",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;return r instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:r,inst:e}),n}}),ph=q("$ZodTransform",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=t.transform(n.value,n);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then(o=>(n.value=o,n));if(r instanceof Promise)throw new xr;return n.value=r,n}}),jC=q("$ZodOptional",(e,t)=>{ve.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ne(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ne(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${kl(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,i):n.value===void 0?n:t.innerType._zod.run(n,i)}),qC=q("$ZodNullable",(e,t)=>{ve.init(e,t),Ne(e._zod,"optin",()=>t.innerType._zod.optin),Ne(e._zod,"optout",()=>t.innerType._zod.optout),Ne(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${kl(n.source)}|null)$`):void 0}),Ne(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>n.value===null?n:t.innerType._zod.run(n,i)}),NC=q("$ZodDefault",(e,t)=>{ve.init(e,t),e._zod.optin="optional",Ne(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(n.value===void 0)return n.value=t.defaultValue,n;let r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>kw(o,t)):kw(r,t)}});DC=q("$ZodPrefault",(e,t)=>{ve.init(e,t),e._zod.optin="optional",Ne(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,i))}),LC=q("$ZodNonOptional",(e,t)=>{ve.init(e,t),Ne(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{let r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>xw(o,e)):xw(r,e)}});UC=q("$ZodSuccess",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>{let r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>(n.value=o.issues.length===0,n)):(n.value=r.issues.length===0,n)}}),FC=q("$ZodCatch",(e,t)=>{ve.init(e,t),e._zod.optin="optional",Ne(e._zod,"optout",()=>t.innerType._zod.optout),Ne(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{let r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(o=>(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(a=>In(a,i,At()))},input:n.value}),n.issues=[]),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(o=>In(o,i,At()))},input:n.value}),n.issues=[]),n)}}),zC=q("$ZodNaN",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:e,expected:"nan",code:"invalid_type"}),n)}),fh=q("$ZodPipe",(e,t)=>{ve.init(e,t),Ne(e._zod,"values",()=>t.in._zod.values),Ne(e._zod,"optin",()=>t.in._zod.optin),Ne(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,i)=>{let r=t.in._zod.run(n,i);return r instanceof Promise?r.then(o=>Cw(o,t,i)):Cw(r,t,i)}});BC=q("$ZodReadonly",(e,t)=>{ve.init(e,t),Ne(e._zod,"propValues",()=>t.innerType._zod.propValues),Ne(e._zod,"values",()=>t.innerType._zod.values),Ne(e._zod,"optin",()=>t.innerType._zod.optin),Ne(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,i)=>{let r=t.innerType._zod.run(n,i);return r instanceof Promise?r.then(Tw):Tw(r)}});KC=q("$ZodTemplateLiteral",(e,t)=>{ve.init(e,t);let n=[];for(let i of t.parts)if(i instanceof ve){if(!i._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...i._zod.traits].shift()}`);let r=i._zod.pattern instanceof RegExp?i._zod.pattern.source:i._zod.pattern;if(!r)throw Error(`Invalid template literal part: ${i._zod.traits}`);let o=r.startsWith("^")?1:0,a=r.endsWith("$")?r.length-1:r.length;n.push(r.slice(o,a))}else if(i===null||Ux.has(typeof i))n.push(si(`${i}`));else throw Error(`Invalid template literal part: ${i}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(i,r)=>typeof i.value!="string"?(i.issues.push({input:i.value,inst:e,expected:"template_literal",code:"invalid_type"}),i):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(i.value)||i.issues.push({input:i.value,inst:e,code:"invalid_format",format:"template_literal",pattern:e._zod.pattern.source}),i)}),JC=q("$ZodPromise",(e,t)=>{ve.init(e,t),e._zod.parse=(n,i)=>Promise.resolve(n.value).then(r=>t.innerType._zod.run({value:r,issues:[]},i))}),WC=q("$ZodLazy",(e,t)=>{ve.init(e,t),Ne(e._zod,"innerType",()=>t.getter()),Ne(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Ne(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Ne(e._zod,"optin",()=>e._zod.innerType._zod.optin),Ne(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,i)=>e._zod.innerType._zod.run(n,i)}),HC=q("$ZodCustom",(e,t)=>{at.init(e,t),ve.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=n=>{let i=n.value,r=t.fn(i);if(r instanceof Promise)return r.then(o=>Iw(o,n,i,e));Iw(r,n,i,e)}});mh={};Fn(mh,{zhTW:()=>z6,zhCN:()=>U6,vi:()=>D6,ur:()=>q6,ua:()=>M6,tr:()=>A6,th:()=>E6,ta:()=>I6,sv:()=>C6,sl:()=>k6,ru:()=>w6,pt:()=>v6,ps:()=>h6,pl:()=>y6,ota:()=>f6,no:()=>c6,nl:()=>u6,ms:()=>s6,mk:()=>o6,ko:()=>r6,kh:()=>t6,ja:()=>XJ,it:()=>QJ,id:()=>VJ,hu:()=>HJ,he:()=>JJ,frCA:()=>BJ,fr:()=>FJ,fi:()=>LJ,fa:()=>NJ,es:()=>jJ,eo:()=>$J,en:()=>GC,de:()=>PJ,cs:()=>TJ,ca:()=>xJ,be:()=>SJ,az:()=>bJ,ar:()=>_J});yJ=()=>{let e={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"};return r=>{switch(r.code){case"invalid_type":return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${r.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${Ce(r.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${r.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${r.maximum.toString()} ${a.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${r.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${r.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${r.minimum.toString()} ${a.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${r.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${r.prefix}"`:o.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${o.suffix}"`:o.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${o.includes}"`:o.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${o.pattern}`:`${i[o.format]??r.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${r.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${r.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${r.keys.length>1?"\u0629":""}: ${te(r.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${r.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${r.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};vJ=()=>{let e={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${r.expected}, daxil olan ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${Ce(r.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${r.origin??"d\u0259y\u0259r"} ${o}${r.maximum.toString()} ${a.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${r.origin??"d\u0259y\u0259r"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${r.origin} ${o}${r.minimum.toString()} ${a.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${o.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:o.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${o.suffix}" il\u0259 bitm\u0259lidir`:o.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${o.includes}" daxil olmal\u0131d\u0131r`:o.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${o.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${i[o.format]??r.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${r.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${r.keys.length>1?"lar":""}: ${te(r.keys,", ")}`;case"invalid_key":return`${r.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${r.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};wJ=()=>{let e={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u043B\u0456\u043A";case"object":{if(Array.isArray(r))return"\u043C\u0430\u0441\u0456\u045E";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"};return r=>{switch(r.code){case"invalid_type":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${r.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${Ce(r.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);if(a){let s=Number(r.maximum),d=Pw(s,a.unit.one,a.unit.few,a.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${a.verb} ${o}${r.maximum.toString()} ${d}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);if(a){let s=Number(r.minimum),d=Pw(s,a.unit.one,a.unit.few,a.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${a.verb} ${o}${r.minimum.toString()} ${d}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${i[o.format]??r.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${r.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${te(r.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${r.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${r.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};kJ=()=>{let e={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return r=>{switch(r.code){case"invalid_type":return`Tipus inv\xE0lid: s'esperava ${r.expected}, s'ha rebut ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Valor inv\xE0lid: s'esperava ${Ce(r.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${te(r.values," o ")}`;case"too_big":{let o=r.inclusive?"com a m\xE0xim":"menys de",a=t(r.origin);return a?`Massa gran: s'esperava que ${r.origin??"el valor"} contingu\xE9s ${o} ${r.maximum.toString()} ${a.unit??"elements"}`:`Massa gran: s'esperava que ${r.origin??"el valor"} fos ${o} ${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?"com a m\xEDnim":"m\xE9s de",a=t(r.origin);return a?`Massa petit: s'esperava que ${r.origin} contingu\xE9s ${o} ${r.minimum.toString()} ${a.unit}`:`Massa petit: s'esperava que ${r.origin} fos ${o} ${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${o.prefix}"`:o.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${o.suffix}"`:o.format==="includes"?`Format inv\xE0lid: ha d'incloure "${o.includes}"`:o.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${o.pattern}`:`Format inv\xE0lid per a ${i[o.format]??r.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${r.divisor}`;case"unrecognized_keys":return`Clau${r.keys.length>1?"s":""} no reconeguda${r.keys.length>1?"s":""}: ${te(r.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${r.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${r.origin}`;default:return"Entrada inv\xE0lida"}}};CJ=()=>{let e={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u010D\xEDslo";case"string":return"\u0159et\u011Bzec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(r))return"pole";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"};return r=>{switch(r.code){case"invalid_type":return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${r.expected}, obdr\u017Eeno ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${Ce(r.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${r.origin??"hodnota"} mus\xED m\xEDt ${o}${r.maximum.toString()} ${a.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${r.origin??"hodnota"} mus\xED b\xFDt ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${r.origin??"hodnota"} mus\xED m\xEDt ${o}${r.minimum.toString()} ${a.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${r.origin??"hodnota"} mus\xED b\xFDt ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${o.prefix}"`:o.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${o.suffix}"`:o.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${o.includes}"`:o.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${o.pattern}`:`Neplatn\xFD form\xE1t ${i[o.format]??r.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${r.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${te(r.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${r.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${r.origin}`;default:return"Neplatn\xFD vstup"}}};IJ=()=>{let e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"Zahl";case"object":{if(Array.isArray(r))return"Array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return r=>{switch(r.code){case"invalid_type":return`Ung\xFCltige Eingabe: erwartet ${r.expected}, erhalten ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ung\xFCltige Eingabe: erwartet ${Ce(r.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Zu gro\xDF: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ${a.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ist`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Zu klein: erwartet, dass ${r.origin} ${o}${r.minimum.toString()} ${a.unit} hat`:`Zu klein: erwartet, dass ${r.origin} ${o}${r.minimum.toString()} ist`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ung\xFCltiger String: muss mit "${o.prefix}" beginnen`:o.format==="ends_with"?`Ung\xFCltiger String: muss mit "${o.suffix}" enden`:o.format==="includes"?`Ung\xFCltiger String: muss "${o.includes}" enthalten`:o.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${o.pattern} entsprechen`:`Ung\xFCltig: ${i[o.format]??r.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${r.divisor} sein`;case"unrecognized_keys":return`${r.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${te(r.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${r.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${r.origin}`;default:return"Ung\xFCltige Eingabe"}}};EJ=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},RJ=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(i){return e[i]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return i=>{switch(i.code){case"invalid_type":return`Invalid input: expected ${i.expected}, received ${EJ(i.input)}`;case"invalid_value":return i.values.length===1?`Invalid input: expected ${Ce(i.values[0])}`:`Invalid option: expected one of ${te(i.values,"|")}`;case"too_big":{let r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Too big: expected ${i.origin??"value"} to have ${r}${i.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${r}${i.maximum.toString()}`}case"too_small":{let r=i.inclusive?">=":">",o=t(i.origin);return o?`Too small: expected ${i.origin} to have ${r}${i.minimum.toString()} ${o.unit}`:`Too small: expected ${i.origin} to be ${r}${i.minimum.toString()}`}case"invalid_format":{let r=i;return r.format==="starts_with"?`Invalid string: must start with "${r.prefix}"`:r.format==="ends_with"?`Invalid string: must end with "${r.suffix}"`:r.format==="includes"?`Invalid string: must include "${r.includes}"`:r.format==="regex"?`Invalid string: must match pattern ${r.pattern}`:`Invalid ${n[r.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${te(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};OJ=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":{if(Array.isArray(e))return"tabelo";if(e===null)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},AJ=()=>{let e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(i){return e[i]??null}let n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return i=>{switch(i.code){case"invalid_type":return`Nevalida enigo: atendi\u011Dis ${i.expected}, ricevi\u011Dis ${OJ(i.input)}`;case"invalid_value":return i.values.length===1?`Nevalida enigo: atendi\u011Dis ${Ce(i.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${te(i.values,"|")}`;case"too_big":{let r=i.inclusive?"<=":"<",o=t(i.origin);return o?`Tro granda: atendi\u011Dis ke ${i.origin??"valoro"} havu ${r}${i.maximum.toString()} ${o.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${i.origin??"valoro"} havu ${r}${i.maximum.toString()}`}case"too_small":{let r=i.inclusive?">=":">",o=t(i.origin);return o?`Tro malgranda: atendi\u011Dis ke ${i.origin} havu ${r}${i.minimum.toString()} ${o.unit}`:`Tro malgranda: atendi\u011Dis ke ${i.origin} estu ${r}${i.minimum.toString()}`}case"invalid_format":{let r=i;return r.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${r.prefix}"`:r.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${r.suffix}"`:r.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${r.includes}"`:r.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${r.pattern}`:`Nevalida ${n[r.format]??i.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${i.divisor}`;case"unrecognized_keys":return`Nekonata${i.keys.length>1?"j":""} \u015Dlosilo${i.keys.length>1?"j":""}: ${te(i.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${i.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${i.origin}`;default:return"Nevalida enigo"}}};MJ=()=>{let e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(r))return"arreglo";if(r===null)return"nulo";if(Object.getPrototypeOf(r)!==Object.prototype)return r.constructor.name}}return o},i={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return r=>{switch(r.code){case"invalid_type":return`Entrada inv\xE1lida: se esperaba ${r.expected}, recibido ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Entrada inv\xE1lida: se esperaba ${Ce(r.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Demasiado grande: se esperaba que ${r.origin??"valor"} tuviera ${o}${r.maximum.toString()} ${a.unit??"elementos"}`:`Demasiado grande: se esperaba que ${r.origin??"valor"} fuera ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Demasiado peque\xF1o: se esperaba que ${r.origin} tuviera ${o}${r.minimum.toString()} ${a.unit}`:`Demasiado peque\xF1o: se esperaba que ${r.origin} fuera ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${o.prefix}"`:o.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${o.suffix}"`:o.format==="includes"?`Cadena inv\xE1lida: debe incluir "${o.includes}"`:o.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${o.pattern}`:`Inv\xE1lido ${i[o.format]??r.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${r.divisor}`;case"unrecognized_keys":return`Llave${r.keys.length>1?"s":""} desconocida${r.keys.length>1?"s":""}: ${te(r.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${r.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${r.origin}`;default:return"Entrada inv\xE1lida"}}};qJ=()=>{let e={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(r))return"\u0622\u0631\u0627\u06CC\u0647";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"};return r=>{switch(r.code){case"invalid_type":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${r.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${n(r.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;case"invalid_value":return r.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${Ce(r.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${te(r.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${r.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${r.maximum.toString()} ${a.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${r.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${r.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${r.origin} \u0628\u0627\u06CC\u062F ${o}${r.minimum.toString()} ${a.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${r.origin} \u0628\u0627\u06CC\u062F ${o}${r.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:o.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:o.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${o.includes}" \u0628\u0627\u0634\u062F`:o.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${o.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${i[o.format]??r.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${r.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${r.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${te(r.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${r.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${r.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};DJ=()=>{let e={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return r=>{switch(r.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${r.expected}, oli ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${Ce(r.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Liian suuri: ${a.subject} t\xE4ytyy olla ${o}${r.maximum.toString()} ${a.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Liian pieni: ${a.subject} t\xE4ytyy olla ${o}${r.minimum.toString()} ${a.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${o.prefix}"`:o.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${o.suffix}"`:o.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${o.includes}"`:o.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${o.pattern}`:`Virheellinen ${i[o.format]??r.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${r.divisor} monikerta`;case"unrecognized_keys":return`${r.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${te(r.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};UJ=()=>{let e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"nombre";case"object":{if(Array.isArray(r))return"tableau";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return r=>{switch(r.code){case"invalid_type":return`Entr\xE9e invalide : ${r.expected} attendu, ${n(r.input)} re\xE7u`;case"invalid_value":return r.values.length===1?`Entr\xE9e invalide : ${Ce(r.values[0])} attendu`:`Option invalide : une valeur parmi ${te(r.values,"|")} attendue`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Trop grand : ${r.origin??"valeur"} doit ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${r.origin??"valeur"} doit \xEAtre ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Trop petit : ${r.origin} doit ${a.verb} ${o}${r.minimum.toString()} ${a.unit}`:`Trop petit : ${r.origin} doit \xEAtre ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${o.pattern}`:`${i[o.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${r.divisor}`;case"unrecognized_keys":return`Cl\xE9${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${te(r.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${r.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entr\xE9e invalide"}}};zJ=()=>{let e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return r=>{switch(r.code){case"invalid_type":return`Entr\xE9e invalide : attendu ${r.expected}, re\xE7u ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Entr\xE9e invalide : attendu ${Ce(r.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"\u2264":"<",a=t(r.origin);return a?`Trop grand : attendu que ${r.origin??"la valeur"} ait ${o}${r.maximum.toString()} ${a.unit}`:`Trop grand : attendu que ${r.origin??"la valeur"} soit ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?"\u2265":">",a=t(r.origin);return a?`Trop petit : attendu que ${r.origin} ait ${o}${r.minimum.toString()} ${a.unit}`:`Trop petit : attendu que ${r.origin} soit ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${o.pattern}`:`${i[o.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${r.divisor}`;case"unrecognized_keys":return`Cl\xE9${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${te(r.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${r.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entr\xE9e invalide"}}};KJ=()=>{let e={string:{unit:"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u05E7\u05DC\u05D8",email:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",url:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",emoji:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",date:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",time:"\u05D6\u05DE\u05DF ISO",duration:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",ipv4:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",ipv6:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",cidrv4:"\u05D8\u05D5\u05D5\u05D7 IPv4",cidrv6:"\u05D8\u05D5\u05D5\u05D7 IPv6",base64:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",base64url:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",json_string:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",e164:"\u05DE\u05E1\u05E4\u05E8 E.164",jwt:"JWT",template_literal:"\u05E7\u05DC\u05D8"};return r=>{switch(r.code){case"invalid_type":return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${r.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${Ce(r.values[0])}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${r.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${r.maximum.toString()} ${a.unit??"elements"}`:`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${r.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${r.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${r.minimum.toString()} ${a.unit}`:`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${r.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${o.prefix}"`:o.format==="ends_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${o.suffix}"`:o.format==="includes"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${o.includes}"`:o.format==="regex"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${o.pattern}`:`${i[o.format]??r.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${r.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${r.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${r.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${te(r.keys,", ")}`;case"invalid_key":return`\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${r.origin}`;case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${r.origin}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};WJ=()=>{let e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"sz\xE1m";case"object":{if(Array.isArray(r))return"t\xF6mb";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"};return r=>{switch(r.code){case"invalid_type":return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${r.expected}, a kapott \xE9rt\xE9k ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${Ce(r.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`T\xFAl nagy: ${r.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${o}${r.maximum.toString()} ${a.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${r.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${r.origin} m\xE9rete t\xFAl kicsi ${o}${r.minimum.toString()} ${a.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${r.origin} t\xFAl kicsi ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\xC9rv\xE9nytelen string: "${o.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:o.format==="ends_with"?`\xC9rv\xE9nytelen string: "${o.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:o.format==="includes"?`\xC9rv\xE9nytelen string: "${o.includes}" \xE9rt\xE9ket kell tartalmaznia`:o.format==="regex"?`\xC9rv\xE9nytelen string: ${o.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${i[o.format]??r.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${r.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${r.keys.length>1?"s":""}: ${te(r.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${r.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${r.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};GJ=()=>{let e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Input tidak valid: diharapkan ${r.expected}, diterima ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Input tidak valid: diharapkan ${Ce(r.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Terlalu besar: diharapkan ${r.origin??"value"} memiliki ${o}${r.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: diharapkan ${r.origin??"value"} menjadi ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Terlalu kecil: diharapkan ${r.origin} memiliki ${o}${r.minimum.toString()} ${a.unit}`:`Terlalu kecil: diharapkan ${r.origin} menjadi ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`String tidak valid: harus dimulai dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak valid: harus berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak valid: harus menyertakan "${o.includes}"`:o.format==="regex"?`String tidak valid: harus sesuai pola ${o.pattern}`:`${i[o.format]??r.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${r.keys.length>1?"s":""}: ${te(r.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${r.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${r.origin}`;default:return"Input tidak valid"}}};ZJ=()=>{let e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"numero";case"object":{if(Array.isArray(r))return"vettore";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Input non valido: atteso ${r.expected}, ricevuto ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Input non valido: atteso ${Ce(r.values[0])}`:`Opzione non valida: atteso uno tra ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Troppo grande: ${r.origin??"valore"} deve avere ${o}${r.maximum.toString()} ${a.unit??"elementi"}`:`Troppo grande: ${r.origin??"valore"} deve essere ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Troppo piccolo: ${r.origin} deve avere ${o}${r.minimum.toString()} ${a.unit}`:`Troppo piccolo: ${r.origin} deve essere ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Stringa non valida: deve iniziare con "${o.prefix}"`:o.format==="ends_with"?`Stringa non valida: deve terminare con "${o.suffix}"`:o.format==="includes"?`Stringa non valida: deve includere "${o.includes}"`:o.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${o.pattern}`:`Invalid ${i[o.format]??r.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${r.divisor}`;case"unrecognized_keys":return`Chiav${r.keys.length>1?"i":"e"} non riconosciut${r.keys.length>1?"e":"a"}: ${te(r.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${r.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${r.origin}`;default:return"Input non valido"}}};YJ=()=>{let e={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u6570\u5024";case"object":{if(Array.isArray(r))return"\u914D\u5217";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"};return r=>{switch(r.code){case"invalid_type":return`\u7121\u52B9\u306A\u5165\u529B: ${r.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${n(r.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;case"invalid_value":return r.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${Ce(r.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${te(r.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let o=r.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",a=t(r.origin);return a?`\u5927\u304D\u3059\u304E\u308B\u5024: ${r.origin??"\u5024"}\u306F${r.maximum.toString()}${a.unit??"\u8981\u7D20"}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${r.origin??"\u5024"}\u306F${r.maximum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let o=r.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",a=t(r.origin);return a?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${r.origin}\u306F${r.minimum.toString()}${a.unit}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${r.origin}\u306F${r.minimum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${o.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${i[o.format]??r.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${r.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${r.keys.length>1?"\u7FA4":""}: ${te(r.keys,"\u3001")}`;case"invalid_key":return`${r.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${r.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};e6=()=>{let e={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)":"\u179B\u17C1\u1781";case"object":{if(Array.isArray(r))return"\u17A2\u17B6\u179A\u17C1 (Array)";if(r===null)return"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"};return r=>{switch(r.code){case"invalid_type":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${Ce(r.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${r.maximum.toString()} ${a.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin} ${o} ${r.minimum.toString()} ${a.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin} ${o} ${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${o.prefix}"`:o.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${o.suffix}"`:o.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${o.includes}"`:o.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${o.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${i[o.format]??r.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${r.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${te(r.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${r.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${r.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};n6=()=>{let e={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"};return r=>{switch(r.code){case"invalid_type":return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${r.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${n(r.input)}\uC785\uB2C8\uB2E4`;case"invalid_value":return r.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${Ce(r.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${te(r.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let o=r.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",a=o==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",s=t(r.origin),d=s?.unit??"\uC694\uC18C";return s?`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${r.maximum.toString()}${d} ${o}${a}`:`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${r.maximum.toString()} ${o}${a}`}case"too_small":{let o=r.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",a=o==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",s=t(r.origin),d=s?.unit??"\uC694\uC18C";return s?`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${r.minimum.toString()}${d} ${o}${a}`:`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${r.minimum.toString()} ${o}${a}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:o.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${o.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${i[o.format]??r.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${r.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${te(r.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${r.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${r.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};i6=()=>{let e={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u0431\u0440\u043E\u0458";case"object":{if(Array.isArray(r))return"\u043D\u0438\u0437\u0430";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"};return r=>{switch(r.code){case"invalid_type":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Ce(r.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${o}${r.maximum.toString()} ${a.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin} \u0434\u0430 \u0438\u043C\u0430 ${o}${r.minimum.toString()} ${a.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${o.pattern}`:`Invalid ${i[o.format]??r.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${te(r.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${r.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${r.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};a6=()=>{let e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"nombor";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Input tidak sah: dijangka ${r.expected}, diterima ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Input tidak sah: dijangka ${Ce(r.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Terlalu besar: dijangka ${r.origin??"nilai"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"elemen"}`:`Terlalu besar: dijangka ${r.origin??"nilai"} adalah ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Terlalu kecil: dijangka ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.unit}`:`Terlalu kecil: dijangka ${r.origin} adalah ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`String tidak sah: mesti bermula dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak sah: mesti mengandungi "${o.includes}"`:o.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${o.pattern}`:`${i[o.format]??r.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${te(r.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${r.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${r.origin}`;default:return"Input tidak sah"}}};d6=()=>{let e={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"getal";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return r=>{switch(r.code){case"invalid_type":return`Ongeldige invoer: verwacht ${r.expected}, ontving ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ongeldige invoer: verwacht ${Ce(r.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Te lang: verwacht dat ${r.origin??"waarde"} ${o}${r.maximum.toString()} ${a.unit??"elementen"} bevat`:`Te lang: verwacht dat ${r.origin??"waarde"} ${o}${r.maximum.toString()} is`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Te kort: verwacht dat ${r.origin} ${o}${r.minimum.toString()} ${a.unit} bevat`:`Te kort: verwacht dat ${r.origin} ${o}${r.minimum.toString()} is`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ongeldige tekst: moet met "${o.prefix}" beginnen`:o.format==="ends_with"?`Ongeldige tekst: moet op "${o.suffix}" eindigen`:o.format==="includes"?`Ongeldige tekst: moet "${o.includes}" bevatten`:o.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${o.pattern}`:`Ongeldig: ${i[o.format]??r.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${r.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${r.keys.length>1?"s":""}: ${te(r.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${r.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${r.origin}`;default:return"Ongeldige invoer"}}};l6=()=>{let e={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"tall";case"object":{if(Array.isArray(r))return"liste";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Ugyldig input: forventet ${r.expected}, fikk ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ugyldig verdi: forventet ${Ce(r.values[0])}`:`Ugyldig valg: forventet en av ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`For stor(t): forventet ${r.origin??"value"} til \xE5 ha ${o}${r.maximum.toString()} ${a.unit??"elementer"}`:`For stor(t): forventet ${r.origin??"value"} til \xE5 ha ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`For lite(n): forventet ${r.origin} til \xE5 ha ${o}${r.minimum.toString()} ${a.unit}`:`For lite(n): forventet ${r.origin} til \xE5 ha ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${o.prefix}"`:o.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${o.suffix}"`:o.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${o.includes}"`:o.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${o.pattern}`:`Ugyldig ${i[o.format]??r.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${te(r.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${r.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${r.origin}`;default:return"Ugyldig input"}}};p6=()=>{let e={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"numara";case"object":{if(Array.isArray(r))return"saf";if(r===null)return"gayb";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"};return r=>{switch(r.code){case"invalid_type":return`F\xE2sit giren: umulan ${r.expected}, al\u0131nan ${n(r.input)}`;case"invalid_value":return r.values.length===1?`F\xE2sit giren: umulan ${Ce(r.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Fazla b\xFCy\xFCk: ${r.origin??"value"}, ${o}${r.maximum.toString()} ${a.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${r.origin??"value"}, ${o}${r.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Fazla k\xFC\xE7\xFCk: ${r.origin}, ${o}${r.minimum.toString()} ${a.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${r.origin}, ${o}${r.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let o=r;return o.format==="starts_with"?`F\xE2sit metin: "${o.prefix}" ile ba\u015Flamal\u0131.`:o.format==="ends_with"?`F\xE2sit metin: "${o.suffix}" ile bitmeli.`:o.format==="includes"?`F\xE2sit metin: "${o.includes}" ihtiv\xE2 etmeli.`:o.format==="regex"?`F\xE2sit metin: ${o.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${i[o.format]??r.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${r.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${r.keys.length>1?"s":""}: ${te(r.keys,", ")}`;case"invalid_key":return`${r.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${r.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};m6=()=>{let e={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(r))return"\u0627\u0631\u06D0";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"};return r=>{switch(r.code){case"invalid_type":return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${r.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${n(r.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;case"invalid_value":return r.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${Ce(r.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${te(r.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${r.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${r.maximum.toString()} ${a.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${r.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${r.maximum.toString()} \u0648\u064A`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${r.origin} \u0628\u0627\u06CC\u062F ${o}${r.minimum.toString()} ${a.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${r.origin} \u0628\u0627\u06CC\u062F ${o}${r.minimum.toString()} \u0648\u064A`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:o.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:o.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${o.includes}" \u0648\u0644\u0631\u064A`:o.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${o.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${i[o.format]??r.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${r.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${r.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${te(r.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${r.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${r.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};g6=()=>{let e={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"liczba";case"object":{if(Array.isArray(r))return"tablica";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"};return r=>{switch(r.code){case"invalid_type":return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${r.expected}, otrzymano ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${Ce(r.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${r.maximum.toString()} ${a.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${r.minimum.toString()} ${a.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${o.prefix}"`:o.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${o.suffix}"`:o.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${o.includes}"`:o.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${o.pattern}`:`Nieprawid\u0142ow(y/a/e) ${i[o.format]??r.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${r.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${r.keys.length>1?"s":""}: ${te(r.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${r.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${r.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};_6=()=>{let e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(r))return"array";if(r===null)return"nulo";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return r=>{switch(r.code){case"invalid_type":return`Tipo inv\xE1lido: esperado ${r.expected}, recebido ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Entrada inv\xE1lida: esperado ${Ce(r.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Muito grande: esperado que ${r.origin??"valor"} tivesse ${o}${r.maximum.toString()} ${a.unit??"elementos"}`:`Muito grande: esperado que ${r.origin??"valor"} fosse ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Muito pequeno: esperado que ${r.origin} tivesse ${o}${r.minimum.toString()} ${a.unit}`:`Muito pequeno: esperado que ${r.origin} fosse ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${o.prefix}"`:o.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${o.suffix}"`:o.format==="includes"?`Texto inv\xE1lido: deve incluir "${o.includes}"`:o.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${o.pattern}`:`${i[o.format]??r.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${r.divisor}`;case"unrecognized_keys":return`Chave${r.keys.length>1?"s":""} desconhecida${r.keys.length>1?"s":""}: ${te(r.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${r.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${r.origin}`;default:return"Campo inv\xE1lido"}}};b6=()=>{let e={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(r))return"\u043C\u0430\u0441\u0441\u0438\u0432";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"};return r=>{switch(r.code){case"invalid_type":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${r.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${Ce(r.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);if(a){let s=Number(r.maximum),d=Ew(s,a.unit.one,a.unit.few,a.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${r.maximum.toString()} ${d}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);if(a){let s=Number(r.minimum),d=Ew(s,a.unit.one,a.unit.few,a.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${r.minimum.toString()} ${d}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin} \u0431\u0443\u0434\u0435\u0442 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${i[o.format]??r.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${r.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${r.keys.length>1?"\u0438":""}: ${te(r.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${r.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${r.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};S6=()=>{let e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u0161tevilo";case"object":{if(Array.isArray(r))return"tabela";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"};return r=>{switch(r.code){case"invalid_type":return`Neveljaven vnos: pri\u010Dakovano ${r.expected}, prejeto ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${Ce(r.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Preveliko: pri\u010Dakovano, da bo ${r.origin??"vrednost"} imelo ${o}${r.maximum.toString()} ${a.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${r.origin??"vrednost"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Premajhno: pri\u010Dakovano, da bo ${r.origin} imelo ${o}${r.minimum.toString()} ${a.unit}`:`Premajhno: pri\u010Dakovano, da bo ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${o.prefix}"`:o.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${o.suffix}"`:o.format==="includes"?`Neveljaven niz: mora vsebovati "${o.includes}"`:o.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${o.pattern}`:`Neveljaven ${i[o.format]??r.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${r.divisor}`;case"unrecognized_keys":return`Neprepoznan${r.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${te(r.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${r.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${r.origin}`;default:return"Neveljaven vnos"}}};x6=()=>{let e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"antal";case"object":{if(Array.isArray(r))return"lista";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return r=>{switch(r.code){case"invalid_type":return`Ogiltig inmatning: f\xF6rv\xE4ntat ${r.expected}, fick ${n(r.input)}`;case"invalid_value":return r.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${Ce(r.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`F\xF6r stor(t): f\xF6rv\xE4ntade ${r.origin??"v\xE4rdet"} att ha ${o}${r.maximum.toString()} ${a.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${r.origin??"v\xE4rdet"} att ha ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`F\xF6r lite(t): f\xF6rv\xE4ntade ${r.origin??"v\xE4rdet"} att ha ${o}${r.minimum.toString()} ${a.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${r.origin??"v\xE4rdet"} att ha ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${o.prefix}"`:o.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${o.suffix}"`:o.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${o.includes}"`:o.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${o.pattern}"`:`Ogiltig(t) ${i[o.format]??r.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${te(r.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${r.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${r.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};T6=()=>{let e={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1":"\u0B8E\u0BA3\u0BCD";case"object":{if(Array.isArray(r))return"\u0B85\u0BA3\u0BBF";if(r===null)return"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Ce(r.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${te(r.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${r.maximum.toString()} ${a.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${r.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin} ${o}${r.minimum.toString()} ${a.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin} ${o}${r.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${o.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${i[o.format]??r.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${r.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${r.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${te(r.keys,", ")}`;case"invalid_key":return`${r.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${r.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};P6=()=>{let e={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)":"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";case"object":{if(Array.isArray(r))return"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";if(r===null)return"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"};return r=>{switch(r.code){case"invalid_type":return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${r.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${Ce(r.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",a=t(r.origin);return a?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${r.maximum.toString()} ${a.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",a=t(r.origin);return a?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${r.minimum.toString()} ${a.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${o.prefix}"`:o.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${o.suffix}"`:o.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${o.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:o.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${o.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${i[o.format]??r.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${r.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${te(r.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${r.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${r.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};R6=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},O6=()=>{let e={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function t(i){return e[i]??null}let n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"};return i=>{switch(i.code){case"invalid_type":return`Ge\xE7ersiz de\u011Fer: beklenen ${i.expected}, al\u0131nan ${R6(i.input)}`;case"invalid_value":return i.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${Ce(i.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${te(i.values,"|")}`;case"too_big":{let r=i.inclusive?"<=":"<",o=t(i.origin);return o?`\xC7ok b\xFCy\xFCk: beklenen ${i.origin??"de\u011Fer"} ${r}${i.maximum.toString()} ${o.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${i.origin??"de\u011Fer"} ${r}${i.maximum.toString()}`}case"too_small":{let r=i.inclusive?">=":">",o=t(i.origin);return o?`\xC7ok k\xFC\xE7\xFCk: beklenen ${i.origin} ${r}${i.minimum.toString()} ${o.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${i.origin} ${r}${i.minimum.toString()}`}case"invalid_format":{let r=i;return r.format==="starts_with"?`Ge\xE7ersiz metin: "${r.prefix}" ile ba\u015Flamal\u0131`:r.format==="ends_with"?`Ge\xE7ersiz metin: "${r.suffix}" ile bitmeli`:r.format==="includes"?`Ge\xE7ersiz metin: "${r.includes}" i\xE7ermeli`:r.format==="regex"?`Ge\xE7ersiz metin: ${r.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${n[r.format]??i.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${i.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${i.keys.length>1?"lar":""}: ${te(i.keys,", ")}`;case"invalid_key":return`${i.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${i.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};$6=()=>{let e={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(r))return"\u043C\u0430\u0441\u0438\u0432";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"};return r=>{switch(r.code){case"invalid_type":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${r.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${Ce(r.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin} \u0431\u0443\u0434\u0435 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${i[o.format]??r.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${r.keys.length>1?"\u0456":""}: ${te(r.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${r.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${r.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};j6=()=>{let e={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"\u0646\u0645\u0628\u0631";case"object":{if(Array.isArray(r))return"\u0622\u0631\u06D2";if(r===null)return"\u0646\u0644";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"};return r=>{switch(r.code){case"invalid_type":return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${r.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${n(r.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;case"invalid_value":return r.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${Ce(r.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${te(r.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${r.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${o}${r.maximum.toString()} ${a.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${r.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${o}${r.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${r.origin} \u06A9\u06D2 ${o}${r.minimum.toString()} ${a.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${r.origin} \u06A9\u0627 ${o}${r.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${o.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${i[o.format]??r.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${r.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${r.keys.length>1?"\u0632":""}: ${te(r.keys,"\u060C ")}`;case"invalid_key":return`${r.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${r.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};N6=()=>{let e={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"s\u1ED1";case"object":{if(Array.isArray(r))return"m\u1EA3ng";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"};return r=>{switch(r.code){case"invalid_type":return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${r.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${Ce(r.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${r.origin??"gi\xE1 tr\u1ECB"} ${a.verb} ${o}${r.maximum.toString()} ${a.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${r.origin??"gi\xE1 tr\u1ECB"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${r.origin} ${a.verb} ${o}${r.minimum.toString()} ${a.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${o.prefix}"`:o.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${o.suffix}"`:o.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${o.includes}"`:o.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${o.pattern}`:`${i[o.format]??r.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${r.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${te(r.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${r.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${r.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};L6=()=>{let e={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"\u975E\u6570\u5B57(NaN)":"\u6570\u5B57";case"object":{if(Array.isArray(r))return"\u6570\u7EC4";if(r===null)return"\u7A7A\u503C(null)";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"};return r=>{switch(r.code){case"invalid_type":return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${r.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${Ce(r.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${r.origin??"\u503C"} ${o}${r.maximum.toString()} ${a.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${r.origin??"\u503C"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${r.origin} ${o}${r.minimum.toString()} ${a.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.prefix}" \u5F00\u5934`:o.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.suffix}" \u7ED3\u5C3E`:o.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${o.pattern}`:`\u65E0\u6548${i[o.format]??r.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${r.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${te(r.keys,", ")}`;case"invalid_key":return`${r.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${r.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};F6=()=>{let e={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function t(r){return e[r]??null}let n=r=>{let o=typeof r;switch(o){case"number":return Number.isNaN(r)?"NaN":"number";case"object":{if(Array.isArray(r))return"array";if(r===null)return"null";if(Object.getPrototypeOf(r)!==Object.prototype&&r.constructor)return r.constructor.name}}return o},i={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"};return r=>{switch(r.code){case"invalid_type":return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${r.expected}\uFF0C\u4F46\u6536\u5230 ${n(r.input)}`;case"invalid_value":return r.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${Ce(r.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${te(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",a=t(r.origin);return a?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${r.origin??"\u503C"} \u61C9\u70BA ${o}${r.maximum.toString()} ${a.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${r.origin??"\u503C"} \u61C9\u70BA ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",a=t(r.origin);return a?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${r.origin} \u61C9\u70BA ${o}${r.minimum.toString()} ${a.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${r.origin} \u61C9\u70BA ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.prefix}" \u958B\u982D`:o.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.suffix}" \u7D50\u5C3E`:o.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${o.pattern}`:`\u7121\u6548\u7684 ${i[o.format]??r.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${r.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${r.keys.length>1?"\u5011":""}\uFF1A${te(r.keys,"\u3001")}`;case"invalid_key":return`${r.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${r.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};VC=Symbol("ZodOutput"),ZC=Symbol("ZodInput"),as=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let i=n[0];if(this._map.set(t,i),i&&typeof i=="object"&&"id"in i){if(this._idmap.has(i.id))throw Error(`ID ${i.id} already exists in the registry`);this._idmap.set(i.id,t)}return this}remove(t){return this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let i={...this.get(n)??{}};return delete i.id,{...i,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};tr=hh();XC={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};qu=class{constructor(t){this._def=t,this.def=t}implement(t){if(typeof t!="function")throw Error("implement() must be called with a function");let n=(...i)=>{let r=this._def.input?Ru(this._def.input,i,void 0,{callee:n}):i;if(!Array.isArray(r))throw Error("Invalid arguments schema: not an array or tuple schema.");let o=t(...r);return this._def.output?Ru(this._def.output,o,void 0,{callee:n}):o};return n}implementAsync(t){if(typeof t!="function")throw Error("implement() must be called with a function");let n=async(...i)=>{let r=this._def.input?await Ou(this._def.input,i,void 0,{callee:n}):i;if(!Array.isArray(r))throw Error("Invalid arguments schema: not an array or tuple schema.");let o=await t(...r);return this._def.output?Ou(this._def.output,o,void 0,{callee:n}):o};return n}input(...t){let n=this.constructor;return Array.isArray(t[0])?new n({type:"function",input:new Pl({type:"tuple",items:t[0],rest:t[1]}),output:this._def.output}):new n({type:"function",input:t[0],output:this._def.output})}output(t){return new this.constructor({type:"function",input:this._def.input,output:t})}};us=class{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??tr,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var i;let r=t._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;let s={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,s);let d=t._zod.toJSONSchema?.();if(d)s.schema=d;else{let l={...n,schemaPath:[...n.schemaPath,t],path:n.path},p=t._zod.parent;if(p)s.ref=p,this.process(p,l),this.seen.get(p).isParent=!0;else{let m=s.schema;switch(r.type){case"string":{let f=m;f.type="string";let{minimum:h,maximum:y,format:w,patterns:g,contentEncoding:v}=t._zod.bag;if(typeof h=="number"&&(f.minLength=h),typeof y=="number"&&(f.maxLength=y),w&&(f.format=o[w]??w,f.format===""&&delete f.format),v&&(f.contentEncoding=v),g&&g.size>0){let b=[...g];b.length===1?f.pattern=b[0].source:b.length>1&&(s.schema.allOf=[...b.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{let f=m,{minimum:h,maximum:y,format:w,multipleOf:g,exclusiveMaximum:v,exclusiveMinimum:b}=t._zod.bag;typeof w=="string"&&w.includes("int")?f.type="integer":f.type="number",typeof b=="number"&&(f.exclusiveMinimum=b),typeof h=="number"&&(f.minimum=h,typeof b=="number"&&(b>=h?delete f.minimum:delete f.exclusiveMinimum)),typeof v=="number"&&(f.exclusiveMaximum=v),typeof y=="number"&&(f.maximum=y,typeof v=="number"&&(v<=y?delete f.maximum:delete f.exclusiveMaximum)),typeof g=="number"&&(f.multipleOf=g);break}case"boolean":{let f=m;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":case"never":{m.not={};break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let f=m,{minimum:h,maximum:y}=t._zod.bag;typeof h=="number"&&(f.minItems=h),typeof y=="number"&&(f.maxItems=y),f.type="array",f.items=this.process(r.element,{...l,path:[...l.path,"items"]});break}case"object":{let f=m;f.type="object",f.properties={};let h=r.shape;for(let g in h)f.properties[g]=this.process(h[g],{...l,path:[...l.path,"properties",g]});let y=new Set(Object.keys(h)),w=new Set([...y].filter(g=>{let v=r.shape[g]._zod;return this.io==="input"?v.optin===void 0:v.optout===void 0}));w.size>0&&(f.required=Array.from(w)),r.catchall?._zod.def.type==="never"?f.additionalProperties=!1:r.catchall?r.catchall&&(f.additionalProperties=this.process(r.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=m;f.anyOf=r.options.map((h,y)=>this.process(h,{...l,path:[...l.path,"anyOf",y]}));break}case"intersection":{let f=m,h=this.process(r.left,{...l,path:[...l.path,"allOf",0]}),y=this.process(r.right,{...l,path:[...l.path,"allOf",1]}),w=v=>"allOf"in v&&Object.keys(v).length===1,g=[...w(h)?h.allOf:[h],...w(y)?y.allOf:[y]];f.allOf=g;break}case"tuple":{let f=m;f.type="array";let h=r.items.map((g,v)=>this.process(g,{...l,path:[...l.path,"prefixItems",v]}));if(this.target==="draft-2020-12"?f.prefixItems=h:f.items=h,r.rest){let g=this.process(r.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?f.items=g:f.additionalItems=g}r.rest&&(f.items=this.process(r.rest,{...l,path:[...l.path,"items"]}));let{minimum:y,maximum:w}=t._zod.bag;typeof y=="number"&&(f.minItems=y),typeof w=="number"&&(f.maxItems=w);break}case"record":{let f=m;f.type="object",f.propertyNames=this.process(r.keyType,{...l,path:[...l.path,"propertyNames"]}),f.additionalProperties=this.process(r.valueType,{...l,path:[...l.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=m,h=Jm(r.entries);h.every(y=>typeof y=="number")&&(f.type="number"),h.every(y=>typeof y=="string")&&(f.type="string"),f.enum=h;break}case"literal":{let f=m,h=[];for(let y of r.values)if(y===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(y))}else h.push(y);if(h.length!==0)if(h.length===1){let y=h[0];f.type=y===null?"null":typeof y,f.const=y}else h.every(y=>typeof y=="number")&&(f.type="number"),h.every(y=>typeof y=="string")&&(f.type="string"),h.every(y=>typeof y=="boolean")&&(f.type="string"),h.every(y=>y===null)&&(f.type="null"),f.enum=h;break}case"file":{let f=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:w,mime:g}=t._zod.bag;y!==void 0&&(h.minLength=y),w!==void 0&&(h.maxLength=w),g?g.length===1?(h.contentMediaType=g[0],Object.assign(f,h)):f.anyOf=g.map(v=>({...h,contentMediaType:v})):Object.assign(f,h);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(r.innerType,l);m.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(r.innerType,l),s.ref=r.innerType;break}case"success":{let f=m;f.type="boolean";break}case"default":{this.process(r.innerType,l),s.ref=r.innerType,m.default=JSON.parse(JSON.stringify(r.defaultValue));break}case"prefault":{this.process(r.innerType,l),s.ref=r.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(r.defaultValue)));break}case"catch":{this.process(r.innerType,l),s.ref=r.innerType;let f;try{f=r.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}m.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=m,h=t._zod.pattern;if(!h)throw Error("Pattern not found in template literal");f.type="string",f.pattern=h.source;break}case"pipe":{let f=this.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;this.process(f,l),s.ref=f;break}case"readonly":{this.process(r.innerType,l),s.ref=r.innerType,m.readOnly=!0;break}case"promise":{this.process(r.innerType,l),s.ref=r.innerType;break}case"optional":{this.process(r.innerType,l),s.ref=r.innerType;break}case"lazy":{let f=t._zod.innerType;this.process(f,l),s.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(t);return u&&Object.assign(s.schema,u),this.io==="input"&&pt(t)&&(delete s.schema.examples,delete s.schema.default),this.io==="input"&&s.schema._prefault&&((i=s.schema).default??(i.default=s.schema._prefault)),delete s.schema._prefault,this.seen.get(t).schema}emit(t,n){let i={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},r=this.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=l=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(i.external){let h=i.external.registry.get(l[0])?.id;if(h)return{ref:i.external.uri(h)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${i.external.uri("__shared")}#/${p}/${y}`}}if(l[1]===r)return{ref:"#"};let m=`#/${p}/`,f=l[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:m+f}},a=l=>{if(l[1].schema.$ref)return;let p=l[1],{ref:m,defId:f}=o(l);p.def={...p.schema},f&&(p.defId=f);let h=p.schema;for(let y in h)delete h[y];h.$ref=m};for(let l of this.seen.entries()){let p=l[1];if(t===l[0]){a(l);continue}if(i.external){let m=i.external.registry.get(l[0])?.id;if(t!==l[0]&&m){a(l);continue}}if(this.metadataRegistry.get(l[0])?.id){a(l);continue}if(p.cycle){if(i.cycles==="throw")throw Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
114
+
115
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);i.cycles==="ref"&&a(l);continue}if(p.count>1&&i.reused==="ref"){a(l);continue}}let s=(l,p)=>{let m=this.seen.get(l),f=m.def??m.schema,h={...f};if(m.ref===null)return;let y=m.ref;if(m.ref=null,y){s(y,p);let w=this.seen.get(y).schema;w.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(w)):(Object.assign(f,w),Object.assign(f,h))}m.isParent||this.override({zodSchema:l,jsonSchema:f,path:m.path??[]})};for(let l of[...this.seen.entries()].reverse())s(l[0],{target:this.target});let d={};this.target==="draft-2020-12"?d.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?d.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),Object.assign(d,r.def);let u=i.external?.defs??{};for(let l of this.seen.entries()){let p=l[1];p.def&&p.defId&&(u[p.defId]=p.def)}!i.external&&Object.keys(u).length>0&&(this.target==="draft-2020-12"?d.$defs=u:d.definitions=u);try{return JSON.parse(JSON.stringify(d))}catch{throw Error("Error converting schema to JSON.")}}};lW={},cW=q("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");ve.init(e,t),e.def=t,e.parse=(n,i)=>Ru(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>Tl(e,n,i),e.parseAsync=async(n,i)=>Ou(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>Il(e,n,i),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),e.clone=(n,i)=>On(e,n,i),e.brand=()=>e,e.register=(n,i)=>(n.add(e,i),e)}),pW=q("ZodMiniObject",(e,t)=>{lh.init(e,t),cW.init(e,t),Ee.defineLazy(e,"shape",()=>t.shape)});c={};Fn(c,{xid:()=>PW,void:()=>VW,uuidv7:()=>wW,uuidv6:()=>bW,uuidv4:()=>vW,uuid:()=>_W,url:()=>SW,uppercase:()=>Uh,unknown:()=>nt,union:()=>Be,undefined:()=>HW,ulid:()=>IW,uint64:()=>JW,uint32:()=>zW,tuple:()=>XW,trim:()=>Wh,treeifyError:()=>Wx,transform:()=>Ig,toUpperCase:()=>Gh,toLowerCase:()=>Hh,toJSONSchema:()=>Zh,templateLiteral:()=>dH,symbol:()=>WW,superRefine:()=>EI,success:()=>aH,stringbool:()=>cH,stringFormat:()=>DW,string:()=>U,strictObject:()=>YW,startsWith:()=>zh,size:()=>Nh,setErrorMap:()=>mH,set:()=>nH,safeParseAsync:()=>HT,safeParse:()=>WT,registry:()=>hh,regexes:()=>th,regex:()=>Dh,refine:()=>PI,record:()=>ze,readonly:()=>wI,property:()=>RT,promise:()=>uH,prettifyError:()=>Gx,preprocess:()=>Og,prefault:()=>mI,positive:()=>TT,pipe:()=>Lu,partialRecord:()=>eH,parseAsync:()=>JT,parse:()=>KT,overwrite:()=>di,optional:()=>He,object:()=>oe,number:()=>je,nullish:()=>oH,nullable:()=>Du,null:()=>wg,normalize:()=>Jh,nonpositive:()=>PT,nonoptional:()=>hI,nonnegative:()=>ET,never:()=>ql,negative:()=>IT,nativeEnum:()=>rH,nanoid:()=>xW,nan:()=>sH,multipleOf:()=>ss,minSize:()=>ds,minLength:()=>lo,mime:()=>Kh,maxSize:()=>El,maxLength:()=>Rl,map:()=>tH,lte:()=>xn,lt:()=>ei,lowercase:()=>Lh,looseObject:()=>Et,locales:()=>mh,literal:()=>ce,length:()=>Ol,lazy:()=>xI,ksuid:()=>EW,keyof:()=>QW,jwt:()=>NW,json:()=>pH,iso:()=>Qh,ipv6:()=>OW,ipv4:()=>RW,intersection:()=>Dl,int64:()=>KW,int32:()=>FW,int:()=>If,instanceof:()=>lH,includes:()=>Fh,guid:()=>yW,gte:()=>Zt,gt:()=>ti,globalRegistry:()=>tr,getErrorMap:()=>hH,function:()=>NT,formatError:()=>Zm,float64:()=>UW,float32:()=>LW,flattenError:()=>Vm,file:()=>iH,enum:()=>Lt,endsWith:()=>Bh,emoji:()=>kW,email:()=>gW,e164:()=>qW,discriminatedUnion:()=>xg,date:()=>ZW,custom:()=>II,cuid2:()=>TW,cuid:()=>CW,core:()=>Mx,config:()=>At,coerce:()=>RI,clone:()=>On,cidrv6:()=>$W,cidrv4:()=>AW,check:()=>TI,catch:()=>_I,boolean:()=>ft,bigint:()=>BW,base64url:()=>jW,base64:()=>MW,array:()=>Re,any:()=>GW,_default:()=>pI,_ZodString:()=>ng,ZodXID:()=>lg,ZodVoid:()=>tI,ZodUnknown:()=>XT,ZodUnion:()=>kg,ZodUndefined:()=>ZT,ZodUUID:()=>nr,ZodURL:()=>ig,ZodULID:()=>ug,ZodType:()=>Pe,ZodTuple:()=>oI,ZodTransform:()=>Tg,ZodTemplateLiteral:()=>SI,ZodSymbol:()=>VT,ZodSuccess:()=>gI,ZodStringFormat:()=>Ve,ZodString:()=>Al,ZodSet:()=>sI,ZodRecord:()=>Cg,ZodRealError:()=>xs,ZodReadonly:()=>bI,ZodPromise:()=>CI,ZodPrefault:()=>fI,ZodPipe:()=>Rg,ZodOptional:()=>Pg,ZodObject:()=>Nl,ZodNumberFormat:()=>bo,ZodNumber:()=>$l,ZodNullable:()=>lI,ZodNull:()=>QT,ZodNonOptional:()=>Eg,ZodNever:()=>eI,ZodNanoID:()=>ag,ZodNaN:()=>vI,ZodMap:()=>aI,ZodLiteral:()=>dI,ZodLazy:()=>kI,ZodKSUID:()=>cg,ZodJWT:()=>vg,ZodIssueCode:()=>fH,ZodIntersection:()=>iI,ZodISOTime:()=>eg,ZodISODuration:()=>tg,ZodISODateTime:()=>Yh,ZodISODate:()=>Xh,ZodIPv6:()=>fg,ZodIPv4:()=>pg,ZodGUID:()=>Nu,ZodFile:()=>uI,ZodError:()=>hW,ZodEnum:()=>ls,ZodEmoji:()=>og,ZodEmail:()=>rg,ZodE164:()=>_g,ZodDiscriminatedUnion:()=>rI,ZodDefault:()=>cI,ZodDate:()=>Sg,ZodCustomStringFormat:()=>GT,ZodCustom:()=>Ll,ZodCatch:()=>yI,ZodCUID2:()=>dg,ZodCUID:()=>sg,ZodCIDRv6:()=>hg,ZodCIDRv4:()=>mg,ZodBoolean:()=>Ml,ZodBigIntFormat:()=>bg,ZodBigInt:()=>jl,ZodBase64URL:()=>yg,ZodBase64:()=>gg,ZodArray:()=>nI,ZodAny:()=>YT,TimePrecision:()=>XC,NEVER:()=>jx,$output:()=>VC,$input:()=>ZC,$brand:()=>qx});Qh={};Fn(Qh,{time:()=>FT,duration:()=>zT,datetime:()=>LT,date:()=>UT,ZodISOTime:()=>eg,ZodISODuration:()=>tg,ZodISODateTime:()=>Yh,ZodISODate:()=>Xh});Yh=q("ZodISODateTime",(e,t)=>{rC.init(e,t),Ve.init(e,t)});Xh=q("ZodISODate",(e,t)=>{iC.init(e,t),Ve.init(e,t)});eg=q("ZodISOTime",(e,t)=>{oC.init(e,t),Ve.init(e,t)});tg=q("ZodISODuration",(e,t)=>{aC.init(e,t),Ve.init(e,t)});BT=(e,t)=>{Gm.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Zm(e,n)},flatten:{value:n=>Vm(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},hW=q("ZodError",BT),xs=q("ZodError",BT,{Parent:Error}),KT=Qm(xs),JT=Ym(xs),WT=Xm(xs),HT=eh(xs),Pe=q("ZodType",(e,t)=>(ve.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),e.clone=(n,i)=>On(e,n,i),e.brand=()=>e,e.register=(n,i)=>(n.add(e,i),e),e.parse=(n,i)=>KT(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>WT(e,n,i),e.parseAsync=async(n,i)=>JT(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>HT(e,n,i),e.spa=e.safeParseAsync,e.refine=(n,i)=>e.check(PI(n,i)),e.superRefine=n=>e.check(EI(n)),e.overwrite=n=>e.check(di(n)),e.optional=()=>He(e),e.nullable=()=>Du(e),e.nullish=()=>He(Du(e)),e.nonoptional=n=>hI(e,n),e.array=()=>Re(e),e.or=n=>Be([e,n]),e.and=n=>Dl(e,n),e.transform=n=>Lu(e,Ig(n)),e.default=n=>pI(e,n),e.prefault=n=>mI(e,n),e.catch=n=>_I(e,n),e.pipe=n=>Lu(e,n),e.readonly=()=>wI(e),e.describe=n=>{let i=e.clone();return tr.add(i,{description:n}),i},Object.defineProperty(e,"description",{get(){return tr.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return tr.get(e);let i=e.clone();return tr.add(i,n[0]),i},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),ng=q("_ZodString",(e,t)=>{Ss.init(e,t),Pe.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...i)=>e.check(Dh(...i)),e.includes=(...i)=>e.check(Fh(...i)),e.startsWith=(...i)=>e.check(zh(...i)),e.endsWith=(...i)=>e.check(Bh(...i)),e.min=(...i)=>e.check(lo(...i)),e.max=(...i)=>e.check(Rl(...i)),e.length=(...i)=>e.check(Ol(...i)),e.nonempty=(...i)=>e.check(lo(1,...i)),e.lowercase=i=>e.check(Lh(i)),e.uppercase=i=>e.check(Uh(i)),e.trim=()=>e.check(Wh()),e.normalize=(...i)=>e.check(Jh(...i)),e.toLowerCase=()=>e.check(Hh()),e.toUpperCase=()=>e.check(Gh())}),Al=q("ZodString",(e,t)=>{Ss.init(e,t),ng.init(e,t),e.email=n=>e.check(gh(rg,n)),e.url=n=>e.check(wh(ig,n)),e.jwt=n=>e.check(qh(vg,n)),e.emoji=n=>e.check(Sh(og,n)),e.guid=n=>e.check(Mu(Nu,n)),e.uuid=n=>e.check(yh(nr,n)),e.uuidv4=n=>e.check(_h(nr,n)),e.uuidv6=n=>e.check(vh(nr,n)),e.uuidv7=n=>e.check(bh(nr,n)),e.nanoid=n=>e.check(kh(ag,n)),e.guid=n=>e.check(Mu(Nu,n)),e.cuid=n=>e.check(xh(sg,n)),e.cuid2=n=>e.check(Ch(dg,n)),e.ulid=n=>e.check(Th(ug,n)),e.base64=n=>e.check($h(gg,n)),e.base64url=n=>e.check(Mh(yg,n)),e.xid=n=>e.check(Ih(lg,n)),e.ksuid=n=>e.check(Ph(cg,n)),e.ipv4=n=>e.check(Eh(pg,n)),e.ipv6=n=>e.check(Rh(fg,n)),e.cidrv4=n=>e.check(Oh(mg,n)),e.cidrv6=n=>e.check(Ah(hg,n)),e.e164=n=>e.check(jh(_g,n)),e.datetime=n=>e.check(LT(n)),e.date=n=>e.check(UT(n)),e.time=n=>e.check(FT(n)),e.duration=n=>e.check(zT(n))});Ve=q("ZodStringFormat",(e,t)=>{Ke.init(e,t),ng.init(e,t)}),rg=q("ZodEmail",(e,t)=>{G0.init(e,t),Ve.init(e,t)});Nu=q("ZodGUID",(e,t)=>{W0.init(e,t),Ve.init(e,t)});nr=q("ZodUUID",(e,t)=>{H0.init(e,t),Ve.init(e,t)});ig=q("ZodURL",(e,t)=>{V0.init(e,t),Ve.init(e,t)});og=q("ZodEmoji",(e,t)=>{Z0.init(e,t),Ve.init(e,t)});ag=q("ZodNanoID",(e,t)=>{Q0.init(e,t),Ve.init(e,t)});sg=q("ZodCUID",(e,t)=>{Y0.init(e,t),Ve.init(e,t)});dg=q("ZodCUID2",(e,t)=>{X0.init(e,t),Ve.init(e,t)});ug=q("ZodULID",(e,t)=>{eC.init(e,t),Ve.init(e,t)});lg=q("ZodXID",(e,t)=>{tC.init(e,t),Ve.init(e,t)});cg=q("ZodKSUID",(e,t)=>{nC.init(e,t),Ve.init(e,t)});pg=q("ZodIPv4",(e,t)=>{sC.init(e,t),Ve.init(e,t)});fg=q("ZodIPv6",(e,t)=>{dC.init(e,t),Ve.init(e,t)});mg=q("ZodCIDRv4",(e,t)=>{uC.init(e,t),Ve.init(e,t)});hg=q("ZodCIDRv6",(e,t)=>{lC.init(e,t),Ve.init(e,t)});gg=q("ZodBase64",(e,t)=>{cC.init(e,t),Ve.init(e,t)});yg=q("ZodBase64URL",(e,t)=>{fC.init(e,t),Ve.init(e,t)});_g=q("ZodE164",(e,t)=>{mC.init(e,t),Ve.init(e,t)});vg=q("ZodJWT",(e,t)=>{gC.init(e,t),Ve.init(e,t)});GT=q("ZodCustomStringFormat",(e,t)=>{yC.init(e,t),Ve.init(e,t)});$l=q("ZodNumber",(e,t)=>{ah.init(e,t),Pe.init(e,t),e.gt=(i,r)=>e.check(ti(i,r)),e.gte=(i,r)=>e.check(Zt(i,r)),e.min=(i,r)=>e.check(Zt(i,r)),e.lt=(i,r)=>e.check(ei(i,r)),e.lte=(i,r)=>e.check(xn(i,r)),e.max=(i,r)=>e.check(xn(i,r)),e.int=i=>e.check(If(i)),e.safe=i=>e.check(If(i)),e.positive=i=>e.check(ti(0,i)),e.nonnegative=i=>e.check(Zt(0,i)),e.negative=i=>e.check(ei(0,i)),e.nonpositive=i=>e.check(xn(0,i)),e.multipleOf=(i,r)=>e.check(ss(i,r)),e.step=(i,r)=>e.check(ss(i,r)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});bo=q("ZodNumberFormat",(e,t)=>{_C.init(e,t),$l.init(e,t)});Ml=q("ZodBoolean",(e,t)=>{sh.init(e,t),Pe.init(e,t)});jl=q("ZodBigInt",(e,t)=>{dh.init(e,t),Pe.init(e,t),e.gte=(i,r)=>e.check(Zt(i,r)),e.min=(i,r)=>e.check(Zt(i,r)),e.gt=(i,r)=>e.check(ti(i,r)),e.gte=(i,r)=>e.check(Zt(i,r)),e.min=(i,r)=>e.check(Zt(i,r)),e.lt=(i,r)=>e.check(ei(i,r)),e.lte=(i,r)=>e.check(xn(i,r)),e.max=(i,r)=>e.check(xn(i,r)),e.positive=i=>e.check(ti(BigInt(0),i)),e.negative=i=>e.check(ei(BigInt(0),i)),e.nonpositive=i=>e.check(xn(BigInt(0),i)),e.nonnegative=i=>e.check(Zt(BigInt(0),i)),e.multipleOf=(i,r)=>e.check(ss(i,r));let n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});bg=q("ZodBigIntFormat",(e,t)=>{vC.init(e,t),jl.init(e,t)});VT=q("ZodSymbol",(e,t)=>{bC.init(e,t),Pe.init(e,t)});ZT=q("ZodUndefined",(e,t)=>{wC.init(e,t),Pe.init(e,t)});QT=q("ZodNull",(e,t)=>{SC.init(e,t),Pe.init(e,t)});YT=q("ZodAny",(e,t)=>{kC.init(e,t),Pe.init(e,t)});XT=q("ZodUnknown",(e,t)=>{$u.init(e,t),Pe.init(e,t)});eI=q("ZodNever",(e,t)=>{xC.init(e,t),Pe.init(e,t)});tI=q("ZodVoid",(e,t)=>{CC.init(e,t),Pe.init(e,t)});Sg=q("ZodDate",(e,t)=>{TC.init(e,t),Pe.init(e,t),e.min=(i,r)=>e.check(Zt(i,r)),e.max=(i,r)=>e.check(xn(i,r));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});nI=q("ZodArray",(e,t)=>{uh.init(e,t),Pe.init(e,t),e.element=t.element,e.min=(n,i)=>e.check(lo(n,i)),e.nonempty=n=>e.check(lo(1,n)),e.max=(n,i)=>e.check(Rl(n,i)),e.length=(n,i)=>e.check(Ol(n,i)),e.unwrap=()=>e.element});Nl=q("ZodObject",(e,t)=>{lh.init(e,t),Pe.init(e,t),Ee.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Lt(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:nt()}),e.loose=()=>e.clone({...e._zod.def,catchall:nt()}),e.strict=()=>e.clone({...e._zod.def,catchall:ql()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Ee.extend(e,n),e.merge=n=>Ee.merge(e,n),e.pick=n=>Ee.pick(e,n),e.omit=n=>Ee.omit(e,n),e.partial=(...n)=>Ee.partial(Pg,e,n[0]),e.required=(...n)=>Ee.required(Eg,e,n[0])});kg=q("ZodUnion",(e,t)=>{ch.init(e,t),Pe.init(e,t),e.options=t.options});rI=q("ZodDiscriminatedUnion",(e,t)=>{kg.init(e,t),IC.init(e,t)});iI=q("ZodIntersection",(e,t)=>{PC.init(e,t),Pe.init(e,t)});oI=q("ZodTuple",(e,t)=>{Pl.init(e,t),Pe.init(e,t),e.rest=n=>e.clone({...e._zod.def,rest:n})});Cg=q("ZodRecord",(e,t)=>{EC.init(e,t),Pe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});aI=q("ZodMap",(e,t)=>{RC.init(e,t),Pe.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});sI=q("ZodSet",(e,t)=>{OC.init(e,t),Pe.init(e,t),e.min=(...n)=>e.check(ds(...n)),e.nonempty=n=>e.check(ds(1,n)),e.max=(...n)=>e.check(El(...n)),e.size=(...n)=>e.check(Nh(...n))});ls=q("ZodEnum",(e,t)=>{AC.init(e,t),Pe.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(i,r)=>{let o={};for(let a of i)if(n.has(a))o[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new ls({...t,checks:[],...Ee.normalizeParams(r),entries:o})},e.exclude=(i,r)=>{let o={...t.entries};for(let a of i)if(n.has(a))delete o[a];else throw Error(`Key ${a} not found in enum`);return new ls({...t,checks:[],...Ee.normalizeParams(r),entries:o})}});dI=q("ZodLiteral",(e,t)=>{$C.init(e,t),Pe.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});uI=q("ZodFile",(e,t)=>{MC.init(e,t),Pe.init(e,t),e.min=(n,i)=>e.check(ds(n,i)),e.max=(n,i)=>e.check(El(n,i)),e.mime=(n,i)=>e.check(Kh(Array.isArray(n)?n:[n],i))});Tg=q("ZodTransform",(e,t)=>{ph.init(e,t),Pe.init(e,t),e._zod.parse=(n,i)=>{n.addIssue=o=>{if(typeof o=="string")n.issues.push(Ee.issue(o,n.value,t));else{let a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),n.issues.push(Ee.issue(a))}};let r=t.transform(n.value,n);return r instanceof Promise?r.then(o=>(n.value=o,n)):(n.value=r,n)}});Pg=q("ZodOptional",(e,t)=>{jC.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});lI=q("ZodNullable",(e,t)=>{qC.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});cI=q("ZodDefault",(e,t)=>{NC.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});fI=q("ZodPrefault",(e,t)=>{DC.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});Eg=q("ZodNonOptional",(e,t)=>{LC.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});gI=q("ZodSuccess",(e,t)=>{UC.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});yI=q("ZodCatch",(e,t)=>{FC.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});vI=q("ZodNaN",(e,t)=>{zC.init(e,t),Pe.init(e,t)});Rg=q("ZodPipe",(e,t)=>{fh.init(e,t),Pe.init(e,t),e.in=t.in,e.out=t.out});bI=q("ZodReadonly",(e,t)=>{BC.init(e,t),Pe.init(e,t)});SI=q("ZodTemplateLiteral",(e,t)=>{KC.init(e,t),Pe.init(e,t)});kI=q("ZodLazy",(e,t)=>{WC.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.getter()});CI=q("ZodPromise",(e,t)=>{JC.init(e,t),Pe.init(e,t),e.unwrap=()=>e._zod.def.innerType});Ll=q("ZodCustom",(e,t)=>{HC.init(e,t),Pe.init(e,t)});cH=(...e)=>jT({Pipe:Rg,Boolean:Ml,String:Al,Transform:Tg},...e);fH={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};RI={};Fn(RI,{string:()=>gH,number:()=>yH,date:()=>bH,boolean:()=>_H,bigint:()=>vH});At(GC());wH=c,OI=wH,AI="2025-11-25",SH=[AI,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Kr="io.modelcontextprotocol/related-task",Ul="2.0",mt=II(e=>e!==null&&(typeof e=="object"||typeof e=="function")),$I=Be([U(),je().int()]),MI=U(),Rse=Et({ttl:je().optional(),pollInterval:je().optional()}),kH=oe({ttl:je().optional()}),xH=oe({taskId:U()}),Ag=Et({progressToken:$I.optional(),[Kr]:xH.optional()}),en=oe({_meta:Ag.optional()}),Cs=en.extend({task:kH.optional()}),CH=e=>Cs.safeParse(e).success,bt=oe({method:U(),params:en.loose().optional()}),mn=oe({_meta:Ag.optional()}),hn=oe({method:U(),params:mn.loose().optional()}),wt=Et({_meta:Ag.optional()}),Fl=Be([U(),je().int()]),jI=oe({jsonrpc:ce(Ul),id:Fl,...bt.shape}).strict(),Ow=e=>jI.safeParse(e).success,qI=oe({jsonrpc:ce(Ul),...hn.shape}).strict(),TH=e=>qI.safeParse(e).success,$g=oe({jsonrpc:ce(Ul),id:Fl,result:wt}).strict(),Cd=e=>$g.safeParse(e).success;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ge||(ge={}));Mg=oe({jsonrpc:ce(Ul),id:Fl.optional(),error:oe({code:je().int(),message:U(),data:nt().optional()})}).strict(),IH=e=>Mg.safeParse(e).success,Ose=Be([jI,qI,$g,Mg]),Ase=Be([$g,Mg]),jg=wt.strict(),PH=mn.extend({requestId:Fl.optional(),reason:U().optional()}),qg=hn.extend({method:ce("notifications/cancelled"),params:PH}),EH=oe({src:U(),mimeType:U().optional(),sizes:Re(U()).optional(),theme:Lt(["light","dark"]).optional()}),Ts=oe({icons:Re(EH).optional()}),co=oe({name:U(),title:U().optional()}),NI=co.extend({...co.shape,...Ts.shape,version:U(),websiteUrl:U().optional(),description:U().optional()}),RH=Dl(oe({applyDefaults:ft().optional()}),ze(U(),nt())),OH=Og(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Dl(oe({form:RH.optional(),url:mt.optional()}),ze(U(),nt()).optional())),AH=Et({list:mt.optional(),cancel:mt.optional(),requests:Et({sampling:Et({createMessage:mt.optional()}).optional(),elicitation:Et({create:mt.optional()}).optional()}).optional()}),$H=Et({list:mt.optional(),cancel:mt.optional(),requests:Et({tools:Et({call:mt.optional()}).optional()}).optional()}),MH=oe({experimental:ze(U(),mt).optional(),sampling:oe({context:mt.optional(),tools:mt.optional()}).optional(),elicitation:OH.optional(),roots:oe({listChanged:ft().optional()}).optional(),tasks:AH.optional(),extensions:ze(U(),mt).optional()}),jH=en.extend({protocolVersion:U(),capabilities:MH,clientInfo:NI}),DI=bt.extend({method:ce("initialize"),params:jH}),qH=oe({experimental:ze(U(),mt).optional(),logging:mt.optional(),completions:mt.optional(),prompts:oe({listChanged:ft().optional()}).optional(),resources:oe({subscribe:ft().optional(),listChanged:ft().optional()}).optional(),tools:oe({listChanged:ft().optional()}).optional(),tasks:$H.optional(),extensions:ze(U(),mt).optional()}),NH=wt.extend({protocolVersion:U(),capabilities:qH,serverInfo:NI,instructions:U().optional()}),LI=hn.extend({method:ce("notifications/initialized"),params:mn.optional()}),Ng=bt.extend({method:ce("ping"),params:en.optional()}),DH=oe({progress:je(),total:He(je()),message:He(U())}),LH=oe({...mn.shape,...DH.shape,progressToken:$I}),Dg=hn.extend({method:ce("notifications/progress"),params:LH}),UH=en.extend({cursor:MI.optional()}),Is=bt.extend({params:UH.optional()}),Ps=wt.extend({nextCursor:MI.optional()}),FH=Lt(["working","input_required","completed","failed","cancelled"]),Es=oe({taskId:U(),status:FH,ttl:Be([je(),wg()]),createdAt:U(),lastUpdatedAt:U(),pollInterval:He(je()),statusMessage:He(U())}),zl=wt.extend({task:Es}),zH=mn.merge(Es),Uu=hn.extend({method:ce("notifications/tasks/status"),params:zH}),Lg=bt.extend({method:ce("tasks/get"),params:en.extend({taskId:U()})}),Ug=wt.merge(Es),Fg=bt.extend({method:ce("tasks/result"),params:en.extend({taskId:U()})}),$se=wt.loose(),zg=Is.extend({method:ce("tasks/list")}),Bg=Ps.extend({tasks:Re(Es)}),Kg=bt.extend({method:ce("tasks/cancel"),params:en.extend({taskId:U()})}),BH=wt.merge(Es),UI=oe({uri:U(),mimeType:He(U()),_meta:ze(U(),nt()).optional()}),FI=UI.extend({text:U()}),Jg=U().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),zI=UI.extend({blob:Jg}),Rs=Lt(["user","assistant"]),wo=oe({audience:Re(Rs).optional(),priority:je().min(0).max(1).optional(),lastModified:Qh.datetime({offset:!0}).optional()}),BI=oe({...co.shape,...Ts.shape,uri:U(),description:He(U()),mimeType:He(U()),size:He(je()),annotations:wo.optional(),_meta:He(Et({}))}),KH=oe({...co.shape,...Ts.shape,uriTemplate:U(),description:He(U()),mimeType:He(U()),annotations:wo.optional(),_meta:He(Et({}))}),Pf=Is.extend({method:ce("resources/list")}),JH=Ps.extend({resources:Re(BI)}),Ef=Is.extend({method:ce("resources/templates/list")}),WH=Ps.extend({resourceTemplates:Re(KH)}),Wg=en.extend({uri:U()}),HH=Wg,Rf=bt.extend({method:ce("resources/read"),params:HH}),GH=wt.extend({contents:Re(Be([FI,zI]))}),VH=hn.extend({method:ce("notifications/resources/list_changed"),params:mn.optional()}),ZH=Wg,QH=bt.extend({method:ce("resources/subscribe"),params:ZH}),YH=Wg,XH=bt.extend({method:ce("resources/unsubscribe"),params:YH}),e9=mn.extend({uri:U()}),t9=hn.extend({method:ce("notifications/resources/updated"),params:e9}),n9=oe({name:U(),description:He(U()),required:He(ft())}),r9=oe({...co.shape,...Ts.shape,description:He(U()),arguments:He(Re(n9)),_meta:He(Et({}))}),Of=Is.extend({method:ce("prompts/list")}),i9=Ps.extend({prompts:Re(r9)}),o9=en.extend({name:U(),arguments:ze(U(),U()).optional()}),Af=bt.extend({method:ce("prompts/get"),params:o9}),Hg=oe({type:ce("text"),text:U(),annotations:wo.optional(),_meta:ze(U(),nt()).optional()}),Gg=oe({type:ce("image"),data:Jg,mimeType:U(),annotations:wo.optional(),_meta:ze(U(),nt()).optional()}),Vg=oe({type:ce("audio"),data:Jg,mimeType:U(),annotations:wo.optional(),_meta:ze(U(),nt()).optional()}),a9=oe({type:ce("tool_use"),name:U(),id:U(),input:ze(U(),nt()),_meta:ze(U(),nt()).optional()}),s9=oe({type:ce("resource"),resource:Be([FI,zI]),annotations:wo.optional(),_meta:ze(U(),nt()).optional()}),d9=BI.extend({type:ce("resource_link")}),Zg=Be([Hg,Gg,Vg,d9,s9]),u9=oe({role:Rs,content:Zg}),l9=wt.extend({description:U().optional(),messages:Re(u9)}),c9=hn.extend({method:ce("notifications/prompts/list_changed"),params:mn.optional()}),p9=oe({title:U().optional(),readOnlyHint:ft().optional(),destructiveHint:ft().optional(),idempotentHint:ft().optional(),openWorldHint:ft().optional()}),f9=oe({taskSupport:Lt(["required","optional","forbidden"]).optional()}),KI=oe({...co.shape,...Ts.shape,description:U().optional(),inputSchema:oe({type:ce("object"),properties:ze(U(),mt).optional(),required:Re(U()).optional()}).catchall(nt()),outputSchema:oe({type:ce("object"),properties:ze(U(),mt).optional(),required:Re(U()).optional()}).catchall(nt()).optional(),annotations:p9.optional(),execution:f9.optional(),_meta:ze(U(),nt()).optional()}),$f=Is.extend({method:ce("tools/list")}),m9=Ps.extend({tools:Re(KI)}),Qg=wt.extend({content:Re(Zg).default([]),structuredContent:ze(U(),nt()).optional(),isError:ft().optional()}),Mse=Qg.or(wt.extend({toolResult:nt()})),h9=Cs.extend({name:U(),arguments:ze(U(),nt()).optional()}),Fu=bt.extend({method:ce("tools/call"),params:h9}),g9=hn.extend({method:ce("notifications/tools/list_changed"),params:mn.optional()}),jse=oe({autoRefresh:ft().default(!0),debounceMs:je().int().nonnegative().default(300)}),zu=Lt(["debug","info","notice","warning","error","critical","alert","emergency"]),y9=en.extend({level:zu}),JI=bt.extend({method:ce("logging/setLevel"),params:y9}),_9=mn.extend({level:zu,logger:U().optional(),data:nt()}),v9=hn.extend({method:ce("notifications/message"),params:_9}),b9=oe({name:U().optional()}),w9=oe({hints:Re(b9).optional(),costPriority:je().min(0).max(1).optional(),speedPriority:je().min(0).max(1).optional(),intelligencePriority:je().min(0).max(1).optional()}),S9=oe({mode:Lt(["auto","required","none"]).optional()}),k9=oe({type:ce("tool_result"),toolUseId:U().describe("The unique identifier for the corresponding tool call."),content:Re(Zg).default([]),structuredContent:oe({}).loose().optional(),isError:ft().optional(),_meta:ze(U(),nt()).optional()}),x9=xg("type",[Hg,Gg,Vg]),Bu=xg("type",[Hg,Gg,Vg,a9,k9]),C9=oe({role:Rs,content:Be([Bu,Re(Bu)]),_meta:ze(U(),nt()).optional()}),T9=Cs.extend({messages:Re(C9),modelPreferences:w9.optional(),systemPrompt:U().optional(),includeContext:Lt(["none","thisServer","allServers"]).optional(),temperature:je().optional(),maxTokens:je().int(),stopSequences:Re(U()).optional(),metadata:mt.optional(),tools:Re(KI).optional(),toolChoice:S9.optional()}),I9=bt.extend({method:ce("sampling/createMessage"),params:T9}),Yg=wt.extend({model:U(),stopReason:He(Lt(["endTurn","stopSequence","maxTokens"]).or(U())),role:Rs,content:x9}),WI=wt.extend({model:U(),stopReason:He(Lt(["endTurn","stopSequence","maxTokens","toolUse"]).or(U())),role:Rs,content:Be([Bu,Re(Bu)])}),P9=oe({type:ce("boolean"),title:U().optional(),description:U().optional(),default:ft().optional()}),E9=oe({type:ce("string"),title:U().optional(),description:U().optional(),minLength:je().optional(),maxLength:je().optional(),format:Lt(["email","uri","date","date-time"]).optional(),default:U().optional()}),R9=oe({type:Lt(["number","integer"]),title:U().optional(),description:U().optional(),minimum:je().optional(),maximum:je().optional(),default:je().optional()}),O9=oe({type:ce("string"),title:U().optional(),description:U().optional(),enum:Re(U()),default:U().optional()}),A9=oe({type:ce("string"),title:U().optional(),description:U().optional(),oneOf:Re(oe({const:U(),title:U()})),default:U().optional()}),$9=oe({type:ce("string"),title:U().optional(),description:U().optional(),enum:Re(U()),enumNames:Re(U()).optional(),default:U().optional()}),M9=Be([O9,A9]),j9=oe({type:ce("array"),title:U().optional(),description:U().optional(),minItems:je().optional(),maxItems:je().optional(),items:oe({type:ce("string"),enum:Re(U())}),default:Re(U()).optional()}),q9=oe({type:ce("array"),title:U().optional(),description:U().optional(),minItems:je().optional(),maxItems:je().optional(),items:oe({anyOf:Re(oe({const:U(),title:U()}))}),default:Re(U()).optional()}),N9=Be([j9,q9]),D9=Be([$9,M9,N9]),L9=Be([D9,P9,E9,R9]),U9=Cs.extend({mode:ce("form").optional(),message:U(),requestedSchema:oe({type:ce("object"),properties:ze(U(),L9),required:Re(U()).optional()})}),F9=Cs.extend({mode:ce("url"),message:U(),elicitationId:U(),url:U().url()}),z9=Be([U9,F9]),B9=bt.extend({method:ce("elicitation/create"),params:z9}),K9=mn.extend({elicitationId:U()}),J9=hn.extend({method:ce("notifications/elicitation/complete"),params:K9}),Ku=wt.extend({action:Lt(["accept","decline","cancel"]),content:Og(e=>e===null?void 0:e,ze(U(),Be([U(),je(),ft(),Re(U())])).optional())}),W9=oe({type:ce("ref/resource"),uri:U()}),H9=oe({type:ce("ref/prompt"),name:U()}),G9=en.extend({ref:Be([H9,W9]),argument:oe({name:U(),value:U()}),context:oe({arguments:ze(U(),U()).optional()}).optional()}),Mf=bt.extend({method:ce("completion/complete"),params:G9});Q9=wt.extend({completion:Et({values:Re(U()).max(100),total:He(je().int()),hasMore:He(ft())})}),Y9=oe({uri:U().startsWith("file://"),name:U().optional(),_meta:ze(U(),nt()).optional()}),X9=bt.extend({method:ce("roots/list"),params:en.optional()}),HI=wt.extend({roots:Re(Y9)}),eG=hn.extend({method:ce("notifications/roots/list_changed"),params:mn.optional()}),qse=Be([Ng,DI,Mf,JI,Af,Of,Pf,Ef,Rf,QH,XH,Fu,$f,Lg,Fg,zg,Kg]),Nse=Be([qg,Dg,LI,eG,Uu]),Dse=Be([jg,Yg,WI,Ku,HI,Ug,Bg,zl]),Lse=Be([Ng,I9,B9,X9,Lg,Fg,zg,Kg]),Use=Be([qg,Dg,v9,t9,VH,g9,c9,Uu,J9]),Fse=Be([jg,NH,Q9,l9,i9,JH,WH,GH,Qg,m9,Ug,Bg,zl]),pe=class e extends Error{constructor(t,n,i){super(`MCP error ${t}: ${n}`),this.code=t,this.data=i,this.name="McpError"}static fromError(t,n,i){if(t===ge.UrlElicitationRequired&&i){let r=i;if(r.elicitations)return new jf(r.elicitations,n)}return new e(t,n,i)}},jf=class extends pe{constructor(t,n=`URL elicitation${t.length>1?"s":""} required`){super(ge.UrlElicitationRequired,n,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};tG=Symbol("Let zodToJsonSchema decide on which parser to use"),Aw={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},nG=e=>typeof e=="string"?{...Aw,name:e}:{...Aw,...e},rG=e=>{let t=nG(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([i,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,i],jsonSchema:void 0}]))}};VI=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};sG=(e,t)=>Me(e.innerType._def,t);dG=(e,t)=>{let n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(let i of e.checks)switch(i.kind){case"min":De(n,"minimum",i.value,i.message,t);break;case"max":De(n,"maximum",i.value,i.message,t);break}return n};pG=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;Tp=void 0,wn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Tp===void 0&&(Tp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Tp),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};hG=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");Ju={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Mw=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,r)=>Me(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return n.length?{anyOf:n}:void 0};IG=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Me(e.innerType._def,t);let n=Me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Dt(t)},n]}:Dt(t)},PG=(e,t)=>{if(t.pipeStrategy==="input")return Me(e.in._def,t);if(t.pipeStrategy==="output")return Me(e.out._def,t);let n=Me(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=Me(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,i].filter(r=>r!==void 0)}};MG=(e,t)=>Me(e.innerType._def,t),jG=(e,t,n)=>{switch(t){case V.ZodString:return YI(e,n);case V.ZodNumber:return kG(e,n);case V.ZodObject:return xG(e,n);case V.ZodBigInt:return oG(e,n);case V.ZodBoolean:return aG();case V.ZodDate:return QI(e,n);case V.ZodUndefined:return AG(n);case V.ZodNull:return bG(n);case V.ZodArray:return iG(e,n);case V.ZodUnion:case V.ZodDiscriminatedUnion:return wG(e,n);case V.ZodIntersection:return fG(e,n);case V.ZodTuple:return OG(e,n);case V.ZodRecord:return XI(e,n);case V.ZodLiteral:return mG(e,n);case V.ZodEnum:return cG(e);case V.ZodNativeEnum:return _G(e);case V.ZodNullable:return SG(e,n);case V.ZodOptional:return IG(e,n);case V.ZodMap:return yG(e,n);case V.ZodSet:return RG(e,n);case V.ZodLazy:return()=>e.getter()._def;case V.ZodPromise:return EG(e,n);case V.ZodNaN:case V.ZodNever:return vG(n);case V.ZodEffects:return lG(e,n);case V.ZodAny:return Dt(n);case V.ZodUnknown:return $G(n);case V.ZodDefault:return uG(e,n);case V.ZodBranded:return ZI(e,n);case V.ZodReadonly:return MG(e,n);case V.ZodCatch:return sG(e,n);case V.ZodPipeline:return PG(e,n);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return(i=>{})(t)}};qG=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:VI(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,i)=>t.currentPath[i]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Dt(t)):t.$refStrategy==="seen"?Dt(t):void 0}},NG=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),DG=(e,t)=>{let n=rG(t),i=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((d,[u,l])=>({...d,[u]:Me(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??Dt(n)}),{}):void 0,r=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=Me(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??Dt(n),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(o.title=a),n.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[n.openAiAnyTypeName]||(i[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let s=r===void 0?i?{...o,[n.definitionPath]:i}:o:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...i,[r]:o}};return n.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};UG=6e4,qf=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(qg,n=>{this._oncancel(n)}),this.setNotificationHandler(Dg,n=>{this._onprogress(n)}),this.setRequestHandler(Ng,n=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Lg,async(n,i)=>{let r=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!r)throw new pe(ge.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(Fg,async(n,i)=>{let r=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(s.type==="response"||s.type==="error"){let d=s.message,u=d.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(d);else{let p=d,m=new pe(p.error.code,p.error.message,p.error.data);l(m)}else{let p=s.type==="response"?"Response":"Error";this._onerror(Error(`${p} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:i.requestId})}}let a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new pe(ge.InvalidParams,`Task not found: ${o}`);if(!Fr(a.status))return await this._waitForTaskUpdate(o,i.signal),await r();if(Fr(a.status)){let s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Kr]:{taskId:o}}}}return await r()};return await r()}),this.setRequestHandler(zg,async(n,i)=>{try{let{tasks:r,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,i.sessionId);return{tasks:r,nextCursor:o,_meta:{}}}catch(r){throw new pe(ge.InvalidParams,`Failed to list tasks: ${r instanceof Error?r.message:String(r)}`)}}),this.setRequestHandler(Kg,async(n,i)=>{try{let r=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!r)throw new pe(ge.InvalidParams,`Task not found: ${n.params.taskId}`);if(Fr(r.status))throw new pe(ge.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!o)throw new pe(ge.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(r){throw r instanceof pe?r:new pe(ge.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(t){t.params.requestId&&this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,n,i,r,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(r,n),startTime:Date.now(),timeout:n,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:r})}_resetTimeout(t){let n=this._timeoutInfo.get(t);if(!n)return!1;let i=Date.now()-n.startTime;if(n.maxTotalTimeout&&i>=n.maxTotalTimeout)throw this._timeoutInfo.delete(t),pe.fromError(ge.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:i});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(t){let n=this._timeoutInfo.get(t);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};let r=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{r?.(o,a),Cd(o)||IH(o)?this._onresponse(o):Ow(o)?this._onrequest(o,a):TH(o)?this._onnotification(o):this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(let i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();let n=pe.fromError(ge.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let i of t.values())i(n)}_onerror(t){this.onerror?.(t)}_onnotification(t){let n=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(t)).catch(i=>this._onerror(Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,n){let i=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,r=this._transport,o=t.params?._meta?.[Kr]?.taskId;if(i===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:ge.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},r?.sessionId).catch(p=>this._onerror(Error(`Failed to enqueue error response: ${p}`))):r?.send(l).catch(p=>this._onerror(Error(`Failed to send an error response: ${p}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);let s=CH(t.params)?t.params.task:void 0,d=this._taskStore?this.requestTaskStore(t,r?.sessionId):void 0,u={signal:a.signal,sessionId:r?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;let p={relatedRequestId:t.id};o&&(p.relatedTask={taskId:o}),await this.notification(l,p)},sendRequest:async(l,p,m)=>{if(a.signal.aborted)throw new pe(ge.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:t.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let h=f.relatedTask?.taskId??o;return h&&d&&await d.updateTaskStatus(h,"input_required"),await this.request(l,p,f)},authInfo:n?.authInfo,requestId:t.id,requestInfo:n?.requestInfo,taskId:o,taskStore:d,taskRequestedTtl:s?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>i(t,u)).then(async l=>{if(a.signal.aborted)return;let p={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:p,timestamp:Date.now()},r?.sessionId):await r?.send(p)},async l=>{if(a.signal.aborted)return;let p={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:ge.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},r?.sessionId):await r?.send(p)}).catch(l=>this._onerror(Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:n,...i}=t.params,r=Number(n),o=this._progressHandlers.get(r);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let a=this._responseHandlers.get(r),s=this._timeoutInfo.get(r);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(d){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(d);return}o(i)}_onresponse(t){let n=Number(t.id),i=this._requestResolvers.get(n);if(i){if(this._requestResolvers.delete(n),Cd(t))i(t);else{let a=new pe(t.error.code,t.error.message,t.error.data);i(a)}return}let r=this._responseHandlers.get(n);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(Cd(t)&&t.result&&typeof t.result=="object"){let a=t.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,n))}}if(o||this._progressHandlers.delete(n),Cd(t))r(t);else{let a=pe.fromError(t.error.code,t.error.message,t.error.data);r(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,n,i){let{task:r}=i??{};if(!r){try{yield{type:"result",result:await this.request(t,n,i)}}catch(a){yield{type:"error",error:a instanceof pe?a:new pe(ge.InternalError,String(a))}}return}let o;try{let a=await this.request(t,zl,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new pe(ge.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Fr(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)}:s.status==="failed"?yield{type:"error",error:new pe(ge.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new pe(ge.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)};return}let d=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,d)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof pe?a:new pe(ge.InternalError,String(a))}}}request(t,n,i){let{relatedRequestId:r,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:d}=i??{};return new Promise((u,l)=>{let p=v=>{l(v)};if(!this._transport){p(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(v){p(v);return}i?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:m}}),s&&(f.params={...f.params,task:s}),d&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Kr]:d}});let h=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:r,resumptionToken:o,onresumptiontoken:a}).catch(S=>this._onerror(Error(`Failed to send cancellation: ${S}`)));let b=v instanceof pe?v:new pe(ge.RequestTimeout,String(v));l(b)};this._responseHandlers.set(m,v=>{if(!i?.signal?.aborted){if(v instanceof Error)return l(v);try{let b=$a(n,v.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});let y=i?.timeout??UG,w=()=>h(pe.fromError(ge.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(m,y,i?.maxTotalTimeout,w,i?.resetTimeoutOnProgress??!1);let g=d?.taskId;if(g){let v=b=>{let S=this._responseHandlers.get(m);S?S(b):this._onerror(Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(g,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(m),l(b)})}else this._transport.send(f,{relatedRequestId:r,resumptionToken:o,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(t,n){return this.request({method:"tasks/get",params:t},Ug,n)}async getTaskResult(t,n,i){return this.request({method:"tasks/result",params:t},n,i)}async listTasks(t,n){return this.request({method:"tasks/list",params:t},Bg,n)}async cancelTask(t,n){return this.request({method:"tasks/cancel",params:t},BH,n)}async notification(t,n){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(t.method);let i=n?.relatedTask?.taskId;if(i){let o={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Kr]:n.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:o,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let o={...t,jsonrpc:"2.0"};n?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[Kr]:n.relatedTask}}}),this._transport?.send(o,n).catch(a=>this._onerror(a))});return}let r={...t,jsonrpc:"2.0"};n?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Kr]:n.relatedTask}}}),await this._transport.send(r,n)}setRequestHandler(t,n){let i=qw(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(r,o)=>{let a=Nw(t,r);return Promise.resolve(n(a,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,n){let i=qw(t);this._notificationHandlers.set(i,r=>{let o=Nw(t,r);return Promise.resolve(n(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let n=this._taskProgressTokens.get(t);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,n,i){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,n,i,r)}async _clearTaskQueue(t,n){if(this._taskMessageQueue){let i=await this._taskMessageQueue.dequeueAll(t,n);for(let r of i)if(r.type==="request"&&Ow(r.message)){let o=r.message.id,a=this._requestResolvers.get(o);a?(a(new pe(ge.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,n){let i=this._options?.defaultTaskPollInterval??1e3;try{let r=await this._taskStore?.getTask(t);r?.pollInterval&&(i=r.pollInterval)}catch{}return new Promise((r,o)=>{if(n.aborted){o(new pe(ge.InvalidRequest,"Request cancelled"));return}let a=setTimeout(r,i);n.addEventListener("abort",()=>{clearTimeout(a),o(new pe(ge.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,n){let i=this._taskStore;if(!i)throw Error("No task store configured");return{createTask:async r=>{if(!t)throw Error("No request provided");return await i.createTask(r,t.id,{method:t.method,params:t.params},n)},getTask:async r=>{let o=await i.getTask(r,n);if(!o)throw new pe(ge.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(r,o,a)=>{await i.storeTaskResult(r,o,a,n);let s=await i.getTask(r,n);if(s){let d=Uu.parse({method:"notifications/tasks/status",params:s});await this.notification(d),Fr(s.status)&&this._cleanupTaskProgressHandler(r)}},getTaskResult:r=>i.getTaskResult(r,n),updateTaskStatus:async(r,o,a)=>{let s=await i.getTask(r,n);if(!s)throw new pe(ge.InvalidParams,`Task "${r}" not found - it may have been cleaned up`);if(Fr(s.status))throw new pe(ge.InvalidParams,`Cannot update task "${r}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(r,o,a,n);let d=await i.getTask(r,n);if(d){let u=Uu.parse({method:"notifications/tasks/status",params:d});await this.notification(u),Fr(d.status)&&this._cleanupTaskProgressHandler(r)}},listTasks:r=>i.listTasks(r,n)}}};zG=am(WS(),1),BG=am(Y1(),1);Nf=class{constructor(t){this._ajv=t??KG()}getValidator(t){let n="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}},Df=class{constructor(t){this._server=t}requestStream(t,n,i){return this._server.requestStream(t,n,i)}createMessageStream(t,n){let i=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!i?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(t.messages.length>0){let r=t.messages[t.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],a=o.some(l=>l.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,d=s?Array.isArray(s.content)?s.content:[s.content]:[],u=d.some(l=>l.type==="tool_use");if(a){if(o.some(l=>l.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!u)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(d.filter(m=>m.type==="tool_use").map(m=>m.id)),p=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(l.size!==p.size||![...l].every(m=>p.has(m)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Yg,n)}elicitInputStream(t,n){let i=this._server.getClientCapabilities(),r=t.mode??"form";switch(r){case"url":{if(!i?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!i?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let o=r==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:o},Ku,n)}async getTask(t,n){return this._server.getTask({taskId:t},n)}async getTaskResult(t,n,i){return this._server.getTaskResult({taskId:t},n,i)}async listTasks(t,n){return this._server.listTasks(t?{cursor:t}:void 0,n)}async cancelTask(t,n){return this._server.cancelTask({taskId:t},n)}};Lf=class extends qf{constructor(t,n){super(n),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(zu.options.map((i,r)=>[i,r])),this.isMessageIgnored=(i,r)=>{let o=this._loggingLevels.get(r);return o?this.LOG_LEVEL_SEVERITY.get(i)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Nf,this.setRequestHandler(DI,i=>this._oninitialize(i)),this.setNotificationHandler(LI,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(JI,async(i,r)=>{let o=r.sessionId||r.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=i.params,s=zu.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Df(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=FG(this._capabilities,t)}setRequestHandler(t,n){let i=ks(t)?.method;if(!i)throw Error("Schema is missing a method literal");let r;if(Un(i)){let o=i;r=o._zod?.def?.value??o.value}else{let o=i;r=o._def?.value??o.value}if(typeof r!="string")throw Error("Schema method literal must be a string");if(r==="tools/call"){let o=async(a,s)=>{let d=$a(Fu,a);if(!d.success){let m=d.error instanceof Error?d.error.message:String(d.error);throw new pe(ge.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:u}=d.data,l=await Promise.resolve(n(a,s));if(u.task){let m=$a(zl,l);if(!m.success){let f=m.error instanceof Error?m.error.message:String(m.error);throw new pe(ge.InvalidParams,`Invalid task creation result: ${f}`)}return m.data}let p=$a(Qg,l);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new pe(ge.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(t,o)}return super.setRequestHandler(t,n)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){WG(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&JG(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let n=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:SH.includes(n)?n:AI,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},jg)}async createMessage(t,n){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(t.messages.length>0){let i=t.messages[t.messages.length-1],r=Array.isArray(i.content)?i.content:[i.content],o=r.some(u=>u.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],d=s.some(u=>u.type==="tool_use");if(o){if(r.some(u=>u.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!d)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let u=new Set(s.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(r.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(u.size!==l.size||![...u].every(p=>l.has(p)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},WI,n):this.request({method:"sampling/createMessage",params:t},Yg,n)}async elicitInput(t,n){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let i=t;return this.request({method:"elicitation/create",params:i},Ku,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let i=t.mode==="form"?t:{...t,mode:"form"},r=await this.request({method:"elicitation/create",params:i},Ku,n);if(r.action==="accept"&&r.content&&i.requestedSchema)try{let o=this._jsonSchemaValidator.getValidator(i.requestedSchema)(r.content);if(!o.valid)throw new pe(ge.InvalidParams,`Elicitation response content does not match requested schema: ${o.errorMessage}`)}catch(o){throw o instanceof pe?o:new pe(ge.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return r}}}createElicitationCompletionNotifier(t,n){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},n)}async listRoots(t,n){return this.request({method:"roots/list",params:t},HI,n)}async sendLoggingMessage(t,n){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,n))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}},eP=Symbol.for("mcp.completable");(function(e){e.Completable="McpCompletable"})(Uw||(Uw={}));GG=/^[A-Za-z0-9._-]{1,128}$/;Uf=class{constructor(t){this._mcpServer=t}registerToolTask(t,n,i){let r={taskSupport:"required",...n.execution};if(r.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,r,n._meta,i)}},Ff=class{constructor(t,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Lf(t,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Uf(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(pr($f)),this.server.assertCanSetRequestHandler(pr(Fu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler($f,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,n])=>{let i={name:t,title:n.title,description:n.description,inputSchema:(()=>{let r=ma(n.inputSchema);return r?jw(r,{strictUnions:!0,pipeStrategy:"input"}):QG})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let r=ma(n.outputSchema);r&&(i.outputSchema=jw(r,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(Fu,async(t,n)=>{try{let i=this._registeredTools[t.params.name];if(!i)throw new pe(ge.InvalidParams,`Tool ${t.params.name} not found`);if(!i.enabled)throw new pe(ge.InvalidParams,`Tool ${t.params.name} disabled`);let r=!!t.params.task,o=i.execution?.taskSupport,a="createTask"in i.handler;if((o==="required"||o==="optional")&&!a)throw new pe(ge.InternalError,`Tool ${t.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!r)throw new pe(ge.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!r&&a)return await this.handleAutomaticTaskPolling(i,t,n);let s=await this.validateToolInput(i,t.params.arguments,t.params.name),d=await this.executeToolHandler(i,s,n);return r||await this.validateToolOutput(i,d,t.params.name),d}catch(i){if(i instanceof pe&&i.code===ge.UrlElicitationRequired)throw i;return this.createToolError(i instanceof Error?i.message:String(i))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,n,i){if(!t.inputSchema)return;let r=ma(t.inputSchema)??t.inputSchema,o=await xp(r,n);if(!o.success){let a="error"in o?o.error:"Unknown error",s=Cp(a);throw new pe(ge.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${s}`)}return o.data}async validateToolOutput(t,n,i){if(!t.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new pe(ge.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let r=ma(t.outputSchema),o=await xp(r,n.structuredContent);if(!o.success){let a="error"in o?o.error:"Unknown error",s=Cp(a);throw new pe(ge.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${s}`)}}async executeToolHandler(t,n,i){let r=t.handler;if("createTask"in r){if(!i.taskStore)throw Error("No task store provided.");let o={...i,taskStore:i.taskStore};return t.inputSchema?await Promise.resolve(r.createTask(n,o)):await Promise.resolve(r.createTask(o))}return t.inputSchema?await Promise.resolve(r(n,i)):await Promise.resolve(r(i))}async handleAutomaticTaskPolling(t,n,i){if(!i.taskStore)throw Error("No task store provided for task-capable tool.");let r=await this.validateToolInput(t,n.params.arguments,n.params.name),o=t.handler,a={...i,taskStore:i.taskStore},s=r?await Promise.resolve(o.createTask(r,a)):await Promise.resolve(o.createTask(a)),d=s.task.taskId,u=s.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,l));let p=await i.taskStore.getTask(d);if(!p)throw new pe(ge.InternalError,`Task ${d} not found during polling`);u=p}return await i.taskStore.getTaskResult(d)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(pr(Mf)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Mf,async t=>{switch(t.params.ref.type){case"ref/prompt":return V9(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return Z9(t),this.handleResourceCompletion(t,t.params.ref);default:throw new pe(ge.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,n){let i=this._registeredPrompts[n.name];if(!i)throw new pe(ge.InvalidParams,`Prompt ${n.name} not found`);if(!i.enabled)throw new pe(ge.InvalidParams,`Prompt ${n.name} disabled`);if(!i.argsSchema)return ha;let r=ks(i.argsSchema)?.[t.params.argument.name];if(!Lw(r))return ha;let o=HG(r);if(!o)return ha;let a=await o(t.params.argument.value,t.params.context);return Bw(a)}async handleResourceCompletion(t,n){let i=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===n.uri);if(!i){if(this._registeredResources[n.uri])return ha;throw new pe(ge.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let r=i.resourceTemplate.completeCallback(t.params.argument.name);if(!r)return ha;let o=await r(t.params.argument.value,t.params.context);return Bw(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(pr(Pf)),this.server.assertCanSetRequestHandler(pr(Ef)),this.server.assertCanSetRequestHandler(pr(Rf)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Pf,async(t,n)=>{let i=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),r=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let a=await o.resourceTemplate.listCallback(n);for(let s of a.resources)r.push({...o.metadata,...s})}return{resources:[...i,...r]}}),this.server.setRequestHandler(Ef,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,n])=>({name:t,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Rf,async(t,n)=>{let i=new URL(t.params.uri),r=this._registeredResources[i.toString()];if(r){if(!r.enabled)throw new pe(ge.InvalidParams,`Resource ${i} disabled`);return r.readCallback(i,n)}for(let o of Object.values(this._registeredResourceTemplates)){let a=o.resourceTemplate.uriTemplate.match(i.toString());if(a)return o.readCallback(i,a,n)}throw new pe(ge.InvalidParams,`Resource ${i} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(pr(Of)),this.server.assertCanSetRequestHandler(pr(Af)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Of,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,n])=>({name:t,title:n.title,description:n.description,arguments:n.argsSchema?YG(n.argsSchema):void 0}))})),this.server.setRequestHandler(Af,async(t,n)=>{let i=this._registeredPrompts[t.params.name];if(!i)throw new pe(ge.InvalidParams,`Prompt ${t.params.name} not found`);if(!i.enabled)throw new pe(ge.InvalidParams,`Prompt ${t.params.name} disabled`);if(i.argsSchema){let r=ma(i.argsSchema),o=await xp(r,t.params.arguments);if(!o.success){let d="error"in o?o.error:"Unknown error",u=Cp(d);throw new pe(ge.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${u}`)}let a=o.data,s=i.callback;return await Promise.resolve(s(a,n))}else{let r=i.callback;return await Promise.resolve(r(n))}}),this._promptHandlersInitialized=!0)}resource(t,n,...i){let r;typeof i[0]=="object"&&(r=i.shift());let o=i[0];if(typeof n=="string"){if(this._registeredResources[n])throw Error(`Resource ${n} is already registered`);let a=this._createRegisteredResource(t,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw Error(`Resource template ${t} is already registered`);let a=this._createRegisteredResourceTemplate(t,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,n,i,r){if(typeof n=="string"){if(this._registeredResources[n])throw Error(`Resource ${n} is already registered`);let o=this._createRegisteredResource(t,i.title,n,i,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[t])throw Error(`Resource template ${t} is already registered`);let o=this._createRegisteredResourceTemplate(t,i.title,n,i,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(t,n,i,r,o){let a={name:t,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==i&&(delete this._registeredResources[i],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=a,a}_createRegisteredResourceTemplate(t,n,i,r,o){let a={resourceTemplate:i,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(delete this._registeredResourceTemplates[t],d.name&&(this._registeredResourceTemplates[d.name]=a)),typeof d.title<"u"&&(a.title=d.title),typeof d.template<"u"&&(a.resourceTemplate=d.template),typeof d.metadata<"u"&&(a.metadata=d.metadata),typeof d.callback<"u"&&(a.readCallback=d.callback),typeof d.enabled<"u"&&(a.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=a;let s=i.uriTemplate.variableNames;return Array.isArray(s)&&s.some(d=>!!i.completeCallback(d))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(t,n,i,r,o){let a={title:n,description:i,argsSchema:r===void 0?void 0:Mi(r),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==t&&(delete this._registeredPrompts[t],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=Mi(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=a,r&&Object.values(r).some(s=>{let d=s instanceof cn?s._def?.innerType:s;return Lw(d)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,n,i,r,o,a,s,d,u){Fw(t);let l={title:n,description:i,inputSchema:zw(r),outputSchema:zw(o),annotations:a,execution:s,_meta:d,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==t&&(typeof p.name=="string"&&Fw(p.name),delete this._registeredTools[t],p.name&&(this._registeredTools[p.name]=l)),typeof p.title<"u"&&(l.title=p.title),typeof p.description<"u"&&(l.description=p.description),typeof p.paramsSchema<"u"&&(l.inputSchema=Mi(p.paramsSchema)),typeof p.outputSchema<"u"&&(l.outputSchema=Mi(p.outputSchema)),typeof p.callback<"u"&&(l.handler=p.callback),typeof p.annotations<"u"&&(l.annotations=p.annotations),typeof p._meta<"u"&&(l._meta=p._meta),typeof p.enabled<"u"&&(l.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(t,...n){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let i,r,o,a;if(typeof n[0]=="string"&&(i=n.shift()),n.length>1){let d=n[0];if(zf(d))r=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!zf(n[0])&&(a=n.shift());else if(typeof d=="object"&&d!==null){if(Object.values(d).some(u=>typeof u=="object"&&u!==null))throw Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=n.shift()}}let s=n[0];return this._createRegisteredTool(t,void 0,i,r,o,a,{taskSupport:"forbidden"},void 0,s)}registerTool(t,n,i){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let{title:r,description:o,inputSchema:a,outputSchema:s,annotations:d,_meta:u}=n;return this._createRegisteredTool(t,r,o,a,s,d,{taskSupport:"forbidden"},u,i)}prompt(t,...n){if(this._registeredPrompts[t])throw Error(`Prompt ${t} is already registered`);let i;typeof n[0]=="string"&&(i=n.shift());let r;n.length>1&&(r=n.shift());let o=n[0],a=this._createRegisteredPrompt(t,void 0,i,r,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(t,n,i){if(this._registeredPrompts[t])throw Error(`Prompt ${t} is already registered`);let{title:r,description:o,argsSchema:a}=n,s=this._createRegisteredPrompt(t,r,o,a,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,n){return this.server.sendLoggingMessage(t,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},QG={type:"object",properties:{}};ha={completion:{values:[],hasMore:!1}};Kw=15e3,nV=J(()=>c.object({session_id:c.string(),ws_url:c.string(),work_dir:c.string().optional(),session_key:c.string().optional()})),sn=class extends Error{code;constructor(t,n){super(t),this.name="DirectConnectError",this.code=n}},Bf=class{options;ws;sessionId;workDir;abortController;readyState=!1;closed=!1;exitError;messages=new Su;readyPromise;readyResolve;readyReject;abortHandler;partialChunks=[];telemetryEmitted=!1;constructor(t){this.options=t,this.abortController=t.abortController??new AbortController,this.readyPromise=new Promise((n,i)=>{this.readyResolve=n,this.readyReject=i}),this.readyPromise.catch(()=>{}),this.initialize()}get ready(){return this.readyPromise}getSessionId(){return this.sessionId}getWorkDir(){return this.workDir}async initialize(){if(this.abortController.signal.aborted){this.failInit(new Mt("Connection aborted"));return}this.abortHandler=()=>{this.close(),this.exitError=new Mt("Connection aborted by user")},this.abortController.signal.addEventListener("abort",this.abortHandler);let t;try{let o=await iV(this.options);this.sessionId=o.sessionId,this.workDir=o.workDir,t=o.wsUrl}catch(o){let a=hs(o);if(!(a instanceof Mt)){let s=a instanceof sn&&a.code?a.code:"session_create_failed";this.emitTelemetry("bad",s)}this.failInit(a);return}if(this.closed){this.options.deleteSessionOnClose&&this.sessionId&&Jw(this.options.serverUrl,this.sessionId,this.options.authToken);return}let n={};this.options.authToken&&(n.authorization=`Bearer ${this.options.authToken}`);let i=new WebSocket(t,{headers:n});this.ws=i;let r=setTimeout((o,a)=>{if(!o.readyState){a.close();let s=new sn(`WebSocket connection timeout after ${Kw}ms`);o.exitError=s,o.readyReject?.(s),o.emitTelemetry("bad","connect_timeout")}},Kw,this,i);i.addEventListener("open",()=>{clearTimeout(r),this.readyState=!0,an(`[DirectConnectTransport] Connected to ${this.options.serverUrl}, session=${this.sessionId}`),this.readyResolve?.(),this.emitTelemetry("ok")}),i.addEventListener("message",o=>{let a=typeof o.data=="string"?o.data:"";if(a.indexOf(`
116
+ `)===-1){a&&this.partialChunks.push(a);return}let s=this.partialChunks.join("")+a;this.partialChunks.length=0;let d=s.split(`
117
+ `),u=d.pop()??"";u&&this.partialChunks.push(u);for(let l of d){if(!l)continue;let p;try{p=Rn(l)}catch(m){an(`DirectConnect: dropped malformed JSON line (${l.length} bytes): ${m}`);continue}this.messages.enqueue(p)}}),i.addEventListener("error",()=>{clearTimeout(r);let o=new sn("WebSocket connection error");this.exitError=o,this.readyReject?.(o),this.messages.done(),!this.readyState&&this.emitTelemetry("bad","ws_error")}),i.addEventListener("close",o=>{let a=this.readyState;this.readyState=!1,this.closed=!0;let s=o.code!==1e3&&o.code!==1001;s&&!this.exitError&&(this.exitError=new sn(`WebSocket closed abnormally: ${o.code} ${o.reason}`)),this.messages.done(),a&&s&&!this.abortController.signal.aborted&&this.emitTelemetry("sad","ws_closed_abnormally")})}emitTelemetry(t,n){this.telemetryEmitted||(this.telemetryEmitted=!0,t==="ok"?lx("transport_direct_connect"):t==="bad"?cx("transport_direct_connect",n??"unknown"):I4("transport_direct_connect",n??"unknown"))}failInit(t){this.exitError=t,this.closed=!0,this.readyReject?.(t),this.messages.done()}async write(t){if(this.abortController.signal.aborted)throw new Mt("Operation aborted");if(this.readyState||await this.readyPromise,!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new sn("Transport is not ready for writing");this.ws.send(t)}isReady(){return this.readyState&&this.ws?.readyState===WebSocket.OPEN}endInput(){}[Symbol.dispose](){this.close()}close(){this.closed||(this.closed=!0,this.readyState=!1,this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0),this.abortController.signal.aborted||this.abortController.abort(),this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.close(1e3,"Normal closure"),this.messages.done(),this.options.deleteSessionOnClose&&this.sessionId&&Jw(this.options.serverUrl,this.sessionId,this.options.authToken))}async*readMessages(){if(yield*this.messages,this.exitError)throw this.exitError}};Kf=Promise.resolve(),Ww=!1;(function(e){e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.space=32]="space",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.asterisk=42]="asterisk",e[e.backslash=92]="backslash",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.plus=43]="plus",e[e.slash=47]="slash",e[e.formFeed=12]="formFeed",e[e.tab=9]="tab"})(Hw||(Hw={}));Jse=Array(20).fill(0).map((e,t)=>" ".repeat(t)),Wse={" ":{"\n":Array(200).fill(0).map((e,t)=>`
118
+ `+" ".repeat(t)),"\r":Array(200).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
119
+ `+" ".repeat(t))}," ":{"\n":Array(200).fill(0).map((e,t)=>`
120
+ `+" ".repeat(t)),"\r":Array(200).fill(0).map((e,t)=>"\r"+" ".repeat(t)),"\r\n":Array(200).fill(0).map((e,t)=>`\r
121
+ `+" ".repeat(t))}};(function(e){e.DEFAULT={allowTrailingComma:!1}})(Gw||(Gw={}));(function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"})(Vw||(Vw={}));(function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"})(Zw||(Zw={}));(function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"})(Qw||(Qw={}));yr=oP.homedir(),Xg=oP.tmpdir(),{env:ji}=Wf,mV=e=>{let t=rt.join(yr,"Library");return{data:rt.join(t,"Application Support",e),config:rt.join(t,"Preferences",e),cache:rt.join(t,"Caches",e),log:rt.join(t,"Logs",e),temp:rt.join(Xg,e)}},hV=e=>{let t=ji.APPDATA||rt.join(yr,"AppData","Roaming"),n=ji.LOCALAPPDATA||rt.join(yr,"AppData","Local");return{data:rt.join(n,e,"Data"),config:rt.join(t,e,"Config"),cache:rt.join(n,e,"Cache"),log:rt.join(n,e,"Log"),temp:rt.join(Xg,e)}},gV=e=>{let t=rt.basename(yr);return{data:rt.join(ji.XDG_DATA_HOME||rt.join(yr,".local","share"),e),config:rt.join(ji.XDG_CONFIG_HOME||rt.join(yr,".config"),e),cache:rt.join(ji.XDG_CACHE_HOME||rt.join(yr,".cache"),e),log:rt.join(ji.XDG_STATE_HOME||rt.join(yr,".local","state"),e),temp:rt.join(Xg,t,e)}};Zse=yV("claude-cli");bV=100,Pp=[];SV=[],Yw=null,Qse=vt(()=>process.argv.includes("--hard-fail"));Pi=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,sP=new Set,Hf=typeof process=="object"&&process?process:{},dP=(e,t,n,i)=>{typeof Hf.emitWarning=="function"?Hf.emitWarning(e,t,n,i):console.error(`[${n}] ${t}: ${e}`)},Wu=globalThis.AbortController,Xw=globalThis.AbortSignal;if(typeof Wu>"u"){Xw=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},Wu=class{constructor(){t()}signal=new Xw;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let e=Hf.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,dP("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}kV=e=>!sP.has(e),fr=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),uP=e=>fr(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Fi:null:null,Fi=class extends Array{constructor(t){super(t),this.fill(0)}},Gf=class e{heap;length;static#r=!1;static create(t){let n=uP(t);if(!n)return[];e.#r=!0;let i=new e(t,n);return e.#r=!1,i}constructor(t,n){if(!e.#r)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new n(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Vf=class e{#r;#c;#h;#g;#R;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#y;#i;#n;#e;#u;#p;#d;#a;#_;#s;#v;#b;#f;#w;#T;#l;static unsafeExposeInternals(t){return{starts:t.#b,ttls:t.#f,sizes:t.#v,keyMap:t.#i,keyList:t.#n,valList:t.#e,next:t.#u,prev:t.#p,get head(){return t.#d},get tail(){return t.#a},free:t.#_,isBackgroundFetch:n=>t.#t(n),backgroundFetch:(n,i,r,o)=>t.#M(n,i,r,o),moveToTail:n=>t.#E(n),indexes:n=>t.#S(n),rindexes:n=>t.#k(n),isStale:n=>t.#m(n)}}get max(){return this.#r}get maxSize(){return this.#c}get calculatedSize(){return this.#y}get size(){return this.#o}get fetchMethod(){return this.#R}get memoMethod(){return this.#O}get dispose(){return this.#h}get disposeAfter(){return this.#g}constructor(t){let{max:n=0,ttl:i,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:a,updateAgeOnHas:s,allowStale:d,dispose:u,disposeAfter:l,noDisposeOnSet:p,noUpdateTTL:m,maxSize:f=0,maxEntrySize:h=0,sizeCalculation:y,fetchMethod:w,memoMethod:g,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:S,allowStaleOnFetchAbort:T,ignoreFetchAbort:C}=t;if(n!==0&&!fr(n))throw TypeError("max option must be a nonnegative integer");let _=n?uP(n):Array;if(!_)throw Error("invalid max value: "+n);if(this.#r=n,this.#c=f,this.maxEntrySize=h||this.#c,this.sizeCalculation=y,this.sizeCalculation){if(!this.#c&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw TypeError("sizeCalculation set to non-function")}if(g!==void 0&&typeof g!="function")throw TypeError("memoMethod must be a function if defined");if(this.#O=g,w!==void 0&&typeof w!="function")throw TypeError("fetchMethod must be a function if specified");if(this.#R=w,this.#T=!!w,this.#i=new Map,this.#n=Array(n).fill(void 0),this.#e=Array(n).fill(void 0),this.#u=new _(n),this.#p=new _(n),this.#d=0,this.#a=0,this.#_=Gf.create(n),this.#o=0,this.#y=0,typeof u=="function"&&(this.#h=u),typeof l=="function"?(this.#g=l,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#w=!!this.#h,this.#l=!!this.#g,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!m,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!S,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!C,this.maxEntrySize!==0){if(this.#c!==0&&!fr(this.#c))throw TypeError("maxSize must be a positive integer if specified");if(!fr(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!d,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!s,this.ttlResolution=fr(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=i||0,this.ttl){if(!fr(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#j()}if(this.#r===0&&this.ttl===0&&this.#c===0)throw TypeError("At least one of max, maxSize, or ttl is required");!this.ttlAutopurge&&!this.#r&&!this.#c&&kV("LRU_CACHE_UNBOUNDED")&&(sP.add("LRU_CACHE_UNBOUNDED"),dP("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",e))}getRemainingTTL(t){return this.#i.has(t)?1/0:0}#j(){let t=new Fi(this.#r),n=new Fi(this.#r);this.#f=t,this.#b=n,this.#q=(o,a,s=Pi.now())=>{if(n[o]=a!==0?s:0,t[o]=a,a!==0&&this.ttlAutopurge){let d=setTimeout(()=>{this.#m(o)&&this.#x(this.#n[o],"expire")},a+1);d.unref&&d.unref()}},this.#I=o=>{n[o]=t[o]!==0?Pi.now():0},this.#C=(o,a)=>{if(t[a]){let s=t[a],d=n[a];if(!s||!d)return;o.ttl=s,o.start=d,o.now=i||r();let u=o.now-d;o.remainingTTL=s-u}};let i=0,r=()=>{let o=Pi.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#i.get(o);if(a===void 0)return 0;let s=t[a],d=n[a];if(!s||!d)return 1/0;let u=(i||r())-d;return s-u},this.#m=o=>{let a=n[o],s=t[o];return!!s&&!!a&&(i||r())-a>s}}#I=()=>{};#C=()=>{};#q=()=>{};#m=()=>!1;#F(){let t=new Fi(this.#r);this.#y=0,this.#v=t,this.#P=n=>{this.#y-=t[n],t[n]=0},this.#N=(n,i,r,o)=>{if(this.#t(i))return 0;if(!fr(r))if(o){if(typeof o!="function")throw TypeError("sizeCalculation must be a function");if(r=o(i,n),!fr(r))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return r},this.#A=(n,i,r)=>{if(t[n]=i,this.#c){let o=this.#c-t[n];for(;this.#y>o;)this.#$(!0)}this.#y+=t[n],r&&(r.entrySize=i,r.totalCalculatedSize=this.#y)}}#P=t=>{};#A=(t,n,i)=>{};#N=(t,n,i,r)=>{if(i||r)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:t=this.allowStale}={}){if(this.#o)for(let n=this.#a;!(!this.#D(n)||((t||!this.#m(n))&&(yield n),n===this.#d));)n=this.#p[n]}*#k({allowStale:t=this.allowStale}={}){if(this.#o)for(let n=this.#d;!(!this.#D(n)||((t||!this.#m(n))&&(yield n),n===this.#a));)n=this.#u[n]}#D(t){return t!==void 0&&this.#i.get(this.#n[t])===t}*entries(){for(let t of this.#S())this.#e[t]!==void 0&&this.#n[t]!==void 0&&!this.#t(this.#e[t])&&(yield[this.#n[t],this.#e[t]])}*rentries(){for(let t of this.#k())this.#e[t]!==void 0&&this.#n[t]!==void 0&&!this.#t(this.#e[t])&&(yield[this.#n[t],this.#e[t]])}*keys(){for(let t of this.#S()){let n=this.#n[t];n!==void 0&&!this.#t(this.#e[t])&&(yield n)}}*rkeys(){for(let t of this.#k()){let n=this.#n[t];n!==void 0&&!this.#t(this.#e[t])&&(yield n)}}*values(){for(let t of this.#S())this.#e[t]!==void 0&&!this.#t(this.#e[t])&&(yield this.#e[t])}*rvalues(){for(let t of this.#k())this.#e[t]!==void 0&&!this.#t(this.#e[t])&&(yield this.#e[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,n={}){for(let i of this.#S()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;if(o!==void 0&&t(o,this.#n[i],this))return this.get(this.#n[i],n)}}forEach(t,n=this){for(let i of this.#S()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&t.call(n,o,this.#n[i],this)}}rforEach(t,n=this){for(let i of this.#k()){let r=this.#e[i],o=this.#t(r)?r.__staleWhileFetching:r;o!==void 0&&t.call(n,o,this.#n[i],this)}}purgeStale(){let t=!1;for(let n of this.#k({allowStale:!0}))this.#m(n)&&(this.#x(this.#n[n],"expire"),t=!0);return t}info(t){let n=this.#i.get(t);if(n===void 0)return;let i=this.#e[n],r=this.#t(i)?i.__staleWhileFetching:i;if(r===void 0)return;let o={value:r};if(this.#f&&this.#b){let a=this.#f[n],s=this.#b[n];if(a&&s){let d=a-(Pi.now()-s);o.ttl=d,o.start=Date.now()}}return this.#v&&(o.size=this.#v[n]),o}dump(){let t=[];for(let n of this.#S({allowStale:!0})){let i=this.#n[n],r=this.#e[n],o=this.#t(r)?r.__staleWhileFetching:r;if(o===void 0||i===void 0)continue;let a={value:o};if(this.#f&&this.#b){a.ttl=this.#f[n];let s=Pi.now()-this.#b[n];a.start=Math.floor(Date.now()-s)}this.#v&&(a.size=this.#v[n]),t.unshift([i,a])}return t}load(t){this.clear();for(let[n,i]of t){if(i.start){let r=Date.now()-i.start;i.start=Pi.now()-r}this.set(n,i.value,i)}}set(t,n,i={}){if(n===void 0)return this.delete(t),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:d}=i,{noUpdateTTL:u=this.noUpdateTTL}=i,l=this.#N(t,n,i.size||0,s);if(this.maxEntrySize&&l>this.maxEntrySize)return d&&(d.set="miss",d.maxEntrySizeExceeded=!0),this.#x(t,"set"),this;let p=this.#o===0?void 0:this.#i.get(t);if(p===void 0)p=this.#o===0?this.#a:this.#_.length!==0?this.#_.pop():this.#o===this.#r?this.#$(!1):this.#o,this.#n[p]=t,this.#e[p]=n,this.#i.set(t,p),this.#u[this.#a]=p,this.#p[p]=this.#a,this.#a=p,this.#o++,this.#A(p,l,d),d&&(d.set="add"),u=!1;else{this.#E(p);let m=this.#e[p];if(n!==m){if(this.#T&&this.#t(m)){m.__abortController.abort(Error("replaced"));let{__staleWhileFetching:f}=m;f!==void 0&&!a&&(this.#w&&this.#h?.(f,t,"set"),this.#l&&this.#s?.push([f,t,"set"]))}else a||(this.#w&&this.#h?.(m,t,"set"),this.#l&&this.#s?.push([m,t,"set"]));if(this.#P(p),this.#A(p,l,d),this.#e[p]=n,d){d.set="replace";let f=m&&this.#t(m)?m.__staleWhileFetching:m;f!==void 0&&(d.oldValue=f)}}else d&&(d.set="update")}if(r!==0&&!this.#f&&this.#j(),this.#f&&(u||this.#q(p,r,o),d&&this.#C(d,p)),!a&&this.#l&&this.#s){let m=this.#s,f;for(;f=m?.shift();)this.#g?.(...f)}return this}pop(){try{for(;this.#o;){let t=this.#e[this.#d];if(this.#$(!0),this.#t(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#l&&this.#s){let t=this.#s,n;for(;n=t?.shift();)this.#g?.(...n)}}}#$(t){let n=this.#d,i=this.#n[n],r=this.#e[n];return this.#T&&this.#t(r)?r.__abortController.abort(Error("evicted")):(this.#w||this.#l)&&(this.#w&&this.#h?.(r,i,"evict"),this.#l&&this.#s?.push([r,i,"evict"])),this.#P(n),t&&(this.#n[n]=void 0,this.#e[n]=void 0,this.#_.push(n)),this.#o===1?(this.#d=this.#a=0,this.#_.length=0):this.#d=this.#u[n],this.#i.delete(i),this.#o--,n}has(t,n={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:r}=n,o=this.#i.get(t);if(o!==void 0){let a=this.#e[o];if(this.#t(a)&&a.__staleWhileFetching===void 0)return!1;if(this.#m(o))r&&(r.has="stale",this.#C(r,o));else return i&&this.#I(o),r&&(r.has="hit",this.#C(r,o)),!0}else r&&(r.has="miss");return!1}peek(t,n={}){let{allowStale:i=this.allowStale}=n,r=this.#i.get(t);if(r===void 0||!i&&this.#m(r))return;let o=this.#e[r];return this.#t(o)?o.__staleWhileFetching:o}#M(t,n,i,r){let o=n===void 0?void 0:this.#e[n];if(this.#t(o))return o;let a=new Wu,{signal:s}=i;s?.addEventListener("abort",()=>a.abort(s.reason),{signal:a.signal});let d={signal:a.signal,options:i,context:r},u=(y,w=!1)=>{let{aborted:g}=a.signal,v=i.ignoreFetchAbort&&y!==void 0;if(i.status&&(g&&!w?(i.status.fetchAborted=!0,i.status.fetchError=a.signal.reason,v&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),g&&!v&&!w)return p(a.signal.reason);let b=f;return this.#e[n]===f&&(y===void 0?b.__staleWhileFetching?this.#e[n]=b.__staleWhileFetching:this.#x(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,y,d.options))),y},l=y=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=y),p(y)),p=y=>{let{aborted:w}=a.signal,g=w&&i.allowStaleOnFetchAbort,v=g||i.allowStaleOnFetchRejection,b=v||i.noDeleteOnFetchRejection,S=f;if(this.#e[n]===f&&(!b||S.__staleWhileFetching===void 0?this.#x(t,"fetch"):g||(this.#e[n]=S.__staleWhileFetching)),v)return i.status&&S.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),S.__staleWhileFetching;if(S.__returned===S)throw y},m=(y,w)=>{let g=this.#R?.(t,o,d);g&&g instanceof Promise&&g.then(v=>y(v===void 0?void 0:v),w),a.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(y(void 0),i.allowStaleOnFetchAbort&&(y=v=>u(v,!0)))})};i.status&&(i.status.fetchDispatched=!0);let f=new Promise(m).then(u,l),h=Object.assign(f,{__abortController:a,__staleWhileFetching:o,__returned:void 0});return n===void 0?(this.set(t,h,{...d.options,status:void 0}),n=this.#i.get(t)):this.#e[n]=h,h}#t(t){if(!this.#T)return!1;let n=t;return!!n&&n instanceof Promise&&n.hasOwnProperty("__staleWhileFetching")&&n.__abortController instanceof Wu}async fetch(t,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:d=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:y,forceRefresh:w=!1,status:g,signal:v}=n;if(!this.#T)return g&&(g.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:g});let b={allowStale:i,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:a,noDisposeOnSet:s,size:d,sizeCalculation:u,noUpdateTTL:l,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:h,ignoreFetchAbort:f,status:g,signal:v},S=this.#i.get(t);if(S===void 0){g&&(g.fetch="miss");let T=this.#M(t,S,b,y);return T.__returned=T}else{let T=this.#e[S];if(this.#t(T)){let I=i&&T.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",I&&(g.returnedStale=!0)),I?T.__staleWhileFetching:T.__returned=T}let C=this.#m(S);if(!w&&!C)return g&&(g.fetch="hit"),this.#E(S),r&&this.#I(S),g&&this.#C(g,S),T;let _=this.#M(t,S,b,y),k=_.__staleWhileFetching!==void 0&&i;return g&&(g.fetch=C?"stale":"refresh",k&&C&&(g.returnedStale=!0)),k?_.__staleWhileFetching:_.__returned=_}}async forceFetch(t,n={}){let i=await this.fetch(t,n);if(i===void 0)throw Error("fetch() returned undefined");return i}memo(t,n={}){let i=this.#O;if(!i)throw Error("no memoMethod provided to constructor");let{context:r,forceRefresh:o,...a}=n,s=this.get(t,a);if(!o&&s!==void 0)return s;let d=i(t,s,{options:a,context:r});return this.set(t,d,a),d}get(t,n={}){let{allowStale:i=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:a}=n,s=this.#i.get(t);if(s!==void 0){let d=this.#e[s],u=this.#t(d);return a&&this.#C(a,s),this.#m(s)?(a&&(a.get="stale"),u?(a&&i&&d.__staleWhileFetching!==void 0&&(a.returnedStale=!0),i?d.__staleWhileFetching:void 0):(o||this.#x(t,"expire"),a&&i&&(a.returnedStale=!0),i?d:void 0)):(a&&(a.get="hit"),u?d.__staleWhileFetching:(this.#E(s),r&&this.#I(s),d))}else a&&(a.get="miss")}#L(t,n){this.#p[n]=t,this.#u[t]=n}#E(t){t!==this.#a&&(t===this.#d?this.#d=this.#u[t]:this.#L(this.#p[t],this.#u[t]),this.#L(this.#a,t),this.#a=t)}delete(t){return this.#x(t,"delete")}#x(t,n){let i=!1;if(this.#o!==0){let r=this.#i.get(t);if(r!==void 0)if(i=!0,this.#o===1)this.#U(n);else{this.#P(r);let o=this.#e[r];if(this.#t(o)?o.__abortController.abort(Error("deleted")):(this.#w||this.#l)&&(this.#w&&this.#h?.(o,t,n),this.#l&&this.#s?.push([o,t,n])),this.#i.delete(t),this.#n[r]=void 0,this.#e[r]=void 0,r===this.#a)this.#a=this.#p[r];else if(r===this.#d)this.#d=this.#u[r];else{let a=this.#p[r];this.#u[a]=this.#u[r];let s=this.#u[r];this.#p[s]=this.#p[r]}this.#o--,this.#_.push(r)}}if(this.#l&&this.#s?.length){let r=this.#s,o;for(;o=r?.shift();)this.#g?.(...o)}return i}clear(){return this.#U("delete")}#U(t){for(let n of this.#k({allowStale:!0})){let i=this.#e[n];if(this.#t(i))i.__abortController.abort(Error("deleted"));else{let r=this.#n[n];this.#w&&this.#h?.(i,r,t),this.#l&&this.#s?.push([i,r,t])}}if(this.#i.clear(),this.#e.fill(void 0),this.#n.fill(void 0),this.#f&&this.#b&&(this.#f.fill(0),this.#b.fill(0)),this.#v&&this.#v.fill(0),this.#d=0,this.#a=0,this.#_.length=0,this.#y=0,this.#o=0,this.#l&&this.#s){let n=this.#s,i;for(;i=n?.shift();)this.#g?.(...i)}}};CV=8192;eS=xV(lP,e=>e,50),Kl=Object.assign(function(e,t=!0){if(!e)return null;let n=e.length>CV?lP(e,t):eS(e,t);return n.ok?n.value:null},{cache:eS.cache}),Jl=vt(()=>{try{if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";if(process.platform==="linux"){if(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)return"wsl";try{let e=Yt().readFileSync("/proc/version",{encoding:"utf8"});if(e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl"))return"wsl"}catch(e){qe(`Failed to read /proc/version for WSL detection: ${e}`,{level:"error"})}return"linux"}return"unknown"}catch(e){return aP(e),"unknown"}}),nde=vt(()=>{if(process.platform==="linux")try{let e=Yt().readFileSync("/proc/version",{encoding:"utf8"}),t=e.match(/WSL(\d+)/i);return t&&t[1]?t[1]:e.toLowerCase().includes("microsoft")?"1":void 0}catch(e){qe(`Failed to read /proc/version for WSL detection: ${e}`,{level:"error"});return}}),rde=vt(async()=>{if(process.platform!=="linux")return;let e={linuxKernel:cP()};try{let t=await IV("/etc/os-release","utf8");for(let n of t.split(`
122
+ `)){let i=n.match(/^(ID|VERSION_ID)=(.*)$/);if(i&&i[1]&&i[2]){let r=i[2].replace(/^"|"$/g,"");i[1]==="ID"?e.linuxDistroId=r:e.linuxDistroVersion=r}}}catch{}return e}),ide=vt(()=>{if(process.platform!=="darwin")return;let e=cP().match(/^(\d+)\./);if(!(!e||!e[1]))return parseInt(e[1],10)-9}),cs=vt(function(){switch(Jl()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}}),ode=vt(function(){return TV(cs(),"managed-settings.d")});Zf=PV;RV=EV,OV=RV(),AV=OV;MV=$V,jV="[object Object]",qV=Function.prototype,NV=Object.prototype,pP=qV.toString,DV=NV.hasOwnProperty,LV=pP.call(Object);FV=UV;Qf=zV;KV=BV;WV=JV;HV=fP;VV=GV,tS=Math.max;mP=ZV;YV=QV,XV=gu?function(e,t){return gu(e,"toString",{configurable:!0,enumerable:!1,value:YV(t),writable:!0})}:qm,e5=XV,t5=800,n5=16,r5=Date.now;o5=i5,a5=o5(e5),hP=a5;d5=s5;l5=u5;p5=c5,f5=p5(function(e,t,n,i){HV(e,t,n,i)}),_r=f5;h5=m5;gP=g5;_5=y5,nS=Nn?Nn.isConcatSpreadable:void 0;b5=v5;w5=yP;k5=S5;C5=x5,T5=C5(function(e,t){return e==null?{}:_5(e,t)}),Ep=T5,P5="Expected a function";R5=E5;A5=O5;M5=$5,_P=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_ANTHROPIC_AWS","CLAUDE_CODE_USE_MANTLE","CLAUDE_CODE_USE_GATEWAY","ANTHROPIC_FOUNDRY_RESOURCE","ANTHROPIC_VERTEX_PROJECT_ID","ANTHROPIC_AWS_WORKSPACE_ID","CLOUD_ML_REGION"],vP=["ANTHROPIC_BASE_URL","_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL","ANTHROPIC_VERTEX_BASE_URL","ANTHROPIC_FOUNDRY_BASE_URL","ANTHROPIC_AWS_BASE_URL","ANTHROPIC_BEDROCK_MANTLE_BASE_URL","CLAUDE_CODE_ARTIFACTS_API_BASE_URL"],bP=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_BEARER_TOKEN_BEDROCK","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_AWS_API_KEY","ANTHROPIC_BEDROCK_MANTLE_API_KEY"],q5=["CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH","CLAUDE_CODE_SKIP_MANTLE_AUTH"],N5=["ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_FABLE_MODEL_NAME","ANTHROPIC_DEFAULT_FABLE_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME","ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_OPUS_MODEL_NAME","ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION","ANTHROPIC_DEFAULT_SONNET_MODEL_NAME","ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","CLAUDE_CODE_SUBAGENT_MODEL"],dde=new Set(["CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",..._P,...vP,...bP,...q5,"CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH","CLAUDE_CODE_HOST_AUTH_REFRESH_TIMEOUT_MS","CLAUDE_CODE_HOST_CREDS_FILE",...N5,"ANTHROPIC_BEDROCK_SERVICE_TIER","CLAUDE_CODE_CERT_STORE","DISABLE_GROWTHBOOK"]),D5="remote-settings.json",Rp=null,U5=null;B5=new Set(["HTTPS_PROXY","HTTP_PROXY","NO_PROXY","CLAUDE_CODE_PROXY_RESOLVES_HOSTS","CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER","CLAUDE_CODE_PROXY_AUTH_HELPER_TTL_MS","API_FORCE_IDLE_TIMEOUT","ANTHROPIC_UNIX_SOCKET","NODE_EXTRA_CA_CERTS","CLAUDE_CODE_CERT_STORE","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","ALL_PROXY","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED",..._P,...vP,"CLAUDE_CODE_CUSTOM_OAUTH_URL",...bP,"ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_HOST_CREDS_FILE","CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST","CLAUDE_CODE_HOST_AUTH_ENV_VAR","CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_REMOTE_SETTINGS_PATH","CLAUDE_CODE_MOCK_REMOTE_SETTINGS","USE_LOCAL_OAUTH","USE_STAGING_OAUTH","CLAUDE_LOCAL_OAUTH_API_BASE"].map(e=>e.toUpperCase()));H5=["userSettings","projectSettings","localSettings","flagSettings","policySettings"],rS="com.anthropic.claudecode",Yf="HKLM\\SOFTWARE\\Policies\\ClaudeCode",Xf="HKCU\\SOFTWARE\\Policies\\ClaudeCode",qi="Settings",V5="/usr/bin/plutil",Z5=["-convert","json","-o","-","--"],Q5=5e3,iS="/mnt/c/Windows/System32/reg.exe",Hu="/mnt/c/Program Files/ClaudeCode";X5=J(()=>c.object({allowedDomains:c.array(c.string()).optional(),deniedDomains:c.array(c.string()).optional().describe("Domains that are always blocked, even if matched by allowedDomains. Supports the same wildcard syntax as allowedDomains. Merged from all settings sources regardless of allowManagedDomainsOnly."),allowManagedDomainsOnly:c.boolean().optional().describe("When true (and set in managed settings), only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources."),allowUnixSockets:c.array(c.string()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:c.boolean().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:c.boolean().optional(),allowMachLookup:c.array(c.string().refine(e=>!(e.endsWith("*")?e.slice(0,-1):e).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "com.apple.coresimulator.*"). Needed for tools that communicate via XPC such as the iOS Simulator or Playwright.'),httpProxyPort:c.number().optional(),socksProxyPort:c.number().optional(),tlsTerminate:c.object({caCertPath:c.string().min(1).optional(),caKeyPath:c.string().min(1).optional()}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so the per-request filter can see HTTPS request bodies. Provide a CA cert+key, or omit both to have sandbox-runtime generate an ephemeral one for the session. Only honored from user, managed/policy, or CLI (`--settings`) settings \u2014 project settings (.claude/settings.json and .claude/settings.local.json) are ignored.")}).optional()),e3=J(()=>c.object({allowWrite:c.array(c.string()).optional().describe("Additional paths to allow writing within the sandbox. Merged with paths from Edit(...) allow permission rules."),denyWrite:c.array(c.string()).optional().describe("Additional paths to deny writing within the sandbox. Merged with paths from Edit(...) deny permission rules."),denyRead:c.array(c.string()).optional().describe("Additional paths to deny reading within the sandbox. Merged with paths from Read(...) deny permission rules."),allowRead:c.array(c.string()).optional().describe("Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths."),allowManagedReadPathsOnly:c.boolean().optional().describe("When true (set in managed settings), only allowRead paths from policySettings are used.")}).optional()),SP=J(()=>c.object({path:c.string().min(1).describe("Path to a credential file or directory. Same resolution as sandbox.filesystem.* paths: absolute, ~ expanded, or relative to the settings file root (project root for project settings, ~/.claude for user settings)."),mode:c.literal("deny").describe("Access mode for this path. Only `deny` is supported.")})),kP=J(()=>c.object({name:c.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable name must start with a letter or underscore and contain only letters, digits, and underscores").describe("Environment variable name."),mode:c.enum(["deny","mask"]).describe("Access mode for this environment variable. `deny` unsets the variable for sandboxed commands; `mask` shows sandboxed commands a sentinel value and the host proxy swaps sentinel\u2192real on egress to `injectHosts`."),injectHosts:c.array(c.string()).optional().describe("Optional narrowing of where the proxy substitutes this credential. Only meaningful when mode is `mask`; accepted but ignored for `deny`. If unset, defaults to `network.allowedDomains` \u2014 the credential is injected at every reachable host. Each entry must be reachable via `network.allowedDomains` (sandbox-runtime validates this).")})),t3=J(()=>c.object({files:c.array(SP()).optional().describe("Credential files or directories to protect. `deny` blocks reads inside the sandbox."),envVars:c.array(kP()).optional().describe("Environment variables to protect. `deny` unsets the variable for sandboxed commands; `mask` substitutes a sentinel inside the sandbox and injects the real value at the proxy."),allowPlaintextInject:c.boolean().optional().describe("Allow sentinel\u2192real substitution on the plain-HTTP proxy path. Defaults to false: without TLS termination the upstream identity is unverified and the credential travels in cleartext. Set only for trusted-network test fixtures. Only honored from user, managed/policy, or CLI (`--settings`) settings \u2014 project settings (.claude/settings.json and .claude/settings.local.json) are ignored.")}).optional()),xP=J(()=>c.object({enabled:c.boolean().optional(),failIfUnavailable:c.boolean().optional().describe("Exit with an error at startup if sandbox.enabled is true but the sandbox cannot start (missing dependencies or unsupported platform). When false (default), a warning is shown and commands run unsandboxed. Intended for managed-settings deployments that require sandboxing as a hard gate."),autoAllowBashIfSandboxed:c.boolean().optional(),allowUnsandboxedCommands:c.boolean().optional().describe("Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."),network:X5(),filesystem:e3(),credentials:t3(),ignoreViolations:c.record(c.string(),c.array(c.string())).optional(),enableWeakerNestedSandbox:c.boolean().optional(),enableWeakerNetworkIsolation:c.boolean().optional().describe("macOS only: Allow access to com.apple.trustd.agent in the sandbox. Needed for Go-based CLI tools (gh, gcloud, terraform, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. **Reduces security** \u2014 opens a potential data exfiltration vector through the trustd service. Default: false"),allowAppleEvents:c.boolean().optional().describe("macOS only: Allow sandboxed commands to send Apple Events (and look up the appleeventsd Mach service). Needed for `open`, `osascript`, and browser-based auth flows that open URLs. **Removes code-execution isolation** \u2014 sandboxed commands can launch other applications unsandboxed with no user prompt, and can script running apps (e.g. Terminal) subject to the user's per-app TCC automation consent. Only honored from user, managed/policy, or CLI (--settings) settings \u2014 project settings (.claude/settings.json and .claude/settings.local.json) are ignored. Default: false"),excludedCommands:c.array(c.string()).optional(),ripgrep:c.object({command:c.string(),args:c.array(c.string()).optional()}).optional().describe("Custom ripgrep configuration for bundled ripgrep support"),bwrapPath:c.preprocess(e=>typeof e=="string"&&oS(e)?e:void 0,c.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the bwrap (bubblewrap) binary. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings."),socatPath:c.preprocess(e=>typeof e=="string"&&oS(e)?e:void 0,c.string()).optional().catch(void 0).describe("Linux/WSL only: Absolute path to the socat binary used for the sandbox network proxy. Overrides auto-detection via PATH. Only honored from admin-controlled managed settings.")}).passthrough()),n3=["auto","iterm2","iterm2_with_bell","terminal_bell","kitty","ghostty","notifications_disabled"],r3=["normal","vim"],i3=["auto","tmux","iterm2","in-process"],o3=["dark","light","light-daltonized","dark-daltonized","light-ansi","dark-ansi"],a3=["auto",...o3],cde=Jl()==="macos"?"\u23FA":"\u25CF",ey=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"],s3=[...ey,"bubble"],d3=s3,pde=J(()=>OI.enum(d3)),fde=J(()=>OI.enum(ey)),u3=["bash","powershell"],ga=J(()=>c.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands.'));c3=J(()=>{let{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:n,HttpHookSchema:i,McpToolHookSchema:r}=l3();return c.discriminatedUnion("type",[e,t,n,i,r])}),p3=J(()=>c.object({matcher:c.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:c.array(c3()).describe("List of hooks to execute when the matcher matches")})),Gu=J(()=>c.partialRecord(c.enum(ul),c.array(p3()))),mde=J(()=>c.enum(["local","user","project","dynamic","enterprise","claudeai","managed","agent"])),hde=J(()=>c.enum(["stdio","sse","sse-ide","http","ws","sdk"])),So=J(()=>c.literal("comms").optional().catch(void 0)),Ir=J(()=>c.number().int().positive()),f3=J(()=>c.object({type:c.literal("stdio").optional(),command:c.string().min(1,"Command cannot be empty"),args:c.array(c.string()).default([]),env:c.record(c.string(),c.string()).optional(),timeout:Ir().optional(),alwaysLoad:c.boolean().optional(),role:So()})),m3=J(()=>c.boolean()),CP=J(()=>c.object({clientId:c.string().optional(),callbackPort:c.number().int().positive().optional(),authServerMetadataUrl:c.string().url().startsWith("https://",{message:"authServerMetadataUrl must use https://"}).optional(),scopes:c.string().min(1).optional(),xaa:m3().optional()})),TP=J(()=>c.object({name:c.string(),permission_policy:c.enum(["always_allow","always_ask","always_deny"]).optional()})),h3=J(()=>c.object({type:c.literal("sse"),url:c.string(),headers:c.record(c.string(),c.string()).optional(),headersHelper:c.string().optional(),oauth:CP().optional(),timeout:Ir().optional(),tools:c.array(TP()).optional(),alwaysLoad:c.boolean().optional(),role:So(),toolPermissions:c.record(c.string(),ty()).optional()})),g3=J(()=>c.object({type:c.literal("sse-ide"),url:c.string(),ideName:c.string(),ideRunningInWindows:c.boolean().optional(),timeout:Ir().optional(),alwaysLoad:c.boolean().optional(),role:So()})),y3=J(()=>c.object({type:c.literal("ws-ide"),url:c.string(),ideName:c.string(),authToken:c.string().optional(),ideRunningInWindows:c.boolean().optional(),timeout:Ir().optional(),alwaysLoad:c.boolean().optional(),role:So()})),_3=J(()=>c.object({type:c.enum(["http","streamable-http"]).transform(()=>"http"),url:c.string(),headers:c.record(c.string(),c.string()).optional(),headersHelper:c.string().optional(),oauth:CP().optional(),timeout:Ir().optional(),tools:c.array(TP()).optional(),alwaysLoad:c.boolean().optional(),role:So(),toolPermissions:c.record(c.string(),ty()).optional()})),v3=J(()=>c.object({type:c.literal("ws"),url:c.string(),headers:c.record(c.string(),c.string()).optional(),headersHelper:c.string().optional(),timeout:Ir().optional(),alwaysLoad:c.boolean().optional(),role:So()})),b3=J(()=>c.object({type:c.literal("sdk"),name:c.string(),timeout:Ir().optional(),alwaysLoad:c.boolean().optional()})),ty=J(()=>c.enum(["allow","ask","blocked"])),w3=J(()=>c.object({type:c.literal("claudeai-proxy"),url:c.string(),id:c.string(),displayName:c.string().optional(),iconUrl:c.string().optional(),timeout:Ir().optional(),alwaysLoad:c.boolean().optional(),toolPermissions:c.record(c.string(),ty()).optional(),stateless:c.boolean().optional(),cachedInitResponse:c.record(c.string(),c.unknown()).nullish()})),em=J(()=>c.union([f3(),h3(),g3(),y3(),_3(),v3(),b3(),w3()])),gde=J(()=>c.object({mcpServers:c.record(c.string(),em())})),S3=new Set(["claude-community","claude-plugins-community"]),k3=new Set(["claude-code-marketplace","claude-code-plugins","claude-plugins-official","anthropic-marketplace","anthropic-plugins","agent-skills","anthropic-agent-skills","life-sciences","knowledge-work-plugins","claude-for-legal","claude-for-financial-services","financial-services-plugins"]),IP=new Set([...k3,...S3]),x3=/(?:official[^a-z0-9]*(anthropic|claude)|(?:anthropic|claude)[^a-z0-9]*official|^(?:anthropic|claude)[^a-z0-9]*(marketplace|plugins|official))/i,C3=/[^\u0020-\u007E]/;Pn=J(()=>c.string().startsWith("./")),ni=J(()=>Pn().endsWith(".json")),aS=J(()=>c.union([Pn().refine(e=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB file path must end with .mcpb or .dxt"}).describe("Path to MCPB file relative to plugin root"),c.string().url().refine(e=>e.endsWith(".mcpb")||e.endsWith(".dxt"),{message:"MCPB URL must end with .mcpb or .dxt"}).describe("URL to MCPB file")])),tm=J(()=>Pn().endsWith(".md")),nm=J(()=>c.union([tm(),Pn()])),PP=J(()=>c.string().min(1,"Marketplace must have a name").refine(e=>!e.includes(" "),{message:'Marketplace name cannot contain spaces. Use kebab-case (e.g., "my-marketplace")'}).refine(e=>!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&e!==".",{message:'Marketplace name cannot contain path separators (/ or \\), ".." sequences, or be "."'}).refine(e=>!T3(e),{message:"Marketplace name impersonates an official Anthropic/Claude marketplace"}).refine(e=>e.toLowerCase()!=="inline",{message:'Marketplace name "inline" is reserved for --plugin-dir session plugins'}).refine(e=>e.toLowerCase()!=="builtin",{message:'Marketplace name "builtin" is reserved for built-in plugins'}).refine(e=>e.toLowerCase()!=="skills-dir",{message:'Marketplace name "skills-dir" is reserved for plugins auto-loaded from .claude/skills/'})),ny=J(()=>c.object({name:c.string().min(1,"Author name cannot be empty").describe("Display name of the plugin author or organization"),email:c.string().optional().describe("Contact email for support or feedback"),url:c.string().optional().describe("Website, GitHub profile, or organization URL")})),I3=J(()=>c.object({$schema:c.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:c.string().min(1,"Plugin name cannot be empty").refine(e=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier for the plugin, used for namespacing (prefer kebab-case)"),displayName:c.string().optional().describe('Human-readable name shown in UI (e.g., "GitHub Utils"). Falls back to `name` when omitted. Unlike `name`, may contain spaces and any casing; not used for namespacing or lookup.'),version:c.string().optional().describe("Semantic version (e.g., 1.2.3) following semver.org specification"),description:c.string().optional().describe("Brief, user-facing explanation of what the plugin provides"),author:ny().optional().describe("Information about the plugin creator or maintainer"),homepage:c.string().url().optional().describe("Plugin homepage or documentation URL"),repository:c.string().optional().describe("Source code repository URL"),license:c.string().optional().describe("SPDX license identifier (e.g., MIT, Apache-2.0)"),keywords:c.array(c.string()).optional().describe("Tags for plugin discovery and categorization"),defaultEnabled:c.boolean().optional().describe("Whether the plugin starts enabled when the user has no explicit enabled/disabled setting for it (default: true). Explicit enabledPlugins values always win, and a plugin required by an enabled dependent is enabled regardless of this value."),dependencies:c.array(aZ()).optional().describe(`Plugins that must be enabled for this plugin to function. Bare names (no "@marketplace") are resolved against the declaring plugin's own marketplace.`)})),yde=J(()=>c.object({description:c.string().optional().describe("Brief, user-facing explanation of what these hooks provide"),hooks:c.lazy(()=>Gu()).describe("The hooks provided by the plugin, in the same format as the one used for settings")})),P3=J(()=>c.object({hooks:c.union([ni().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),c.lazy(()=>Gu()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)"),c.array(c.union([ni().describe("Path to file with additional hooks (in addition to those in hooks/hooks.json, if it exists), relative to the plugin root"),c.lazy(()=>Gu()).describe("Additional hooks (in addition to those in hooks/hooks.json, if it exists)")]))])})),E3=J(()=>c.object({source:nm().optional().describe("Path to command markdown file, relative to plugin root"),content:c.string().optional().describe("Inline markdown content for the command"),description:c.string().optional().describe("Command description override"),argumentHint:c.string().optional().describe('Hint for command arguments (e.g., "[file]")'),model:c.string().optional().describe("Default model for this command"),allowedTools:c.array(c.string()).optional().describe("Tools allowed when command runs")}).refine(e=>e.source&&!e.content||!e.source&&e.content,{message:'Command must have either "source" (file path) or "content" (inline markdown), but not both'})),R3=J(()=>c.object({commands:c.union([nm().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded \u2014 list its files here if you want both."),c.array(nm().describe("Path to a command file or skill directory, relative to the plugin root. When set, the commands/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of command file or skill directory paths. When set, the commands/ directory is not auto-loaded."),c.record(c.string(),E3()).describe('Object mapping of command names to their metadata and source files. Command name becomes the slash command name (e.g., "about" \u2192 "/plugin:about")')])})),O3=J(()=>c.object({agents:c.union([tm().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded \u2014 list its files here if you want both."),c.array(tm().describe("Path to an agent file, relative to the plugin root. When set, the agents/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of agent file paths. When set, the agents/ directory is not auto-loaded.")])})),A3=J(()=>c.object({skills:c.union([Pn().describe("Path to a skill directory, relative to the plugin root. Loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring a specific subdirectory replaces the skills/ scan)."),c.array(Pn().describe("Path to a skill directory, relative to the plugin root.")).describe("List of skill directory paths, loaded in addition to the skills/ directory (except: for a marketplace entry whose source resolves to the marketplace root, declaring specific subdirectories replaces the skills/ scan).")])})),EP=J(()=>c.object({outputStyles:c.union([Pn().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded \u2014 list its files here if you want both."),c.array(Pn().describe("Path to an output-styles directory or file, relative to the plugin root. When set, the output-styles/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of output-style directory or file paths. When set, the output-styles/ directory is not auto-loaded.")])})),$3=J(()=>c.string().max(64).regex(/^[a-z][a-z0-9_-]*$/,"must match ^[a-z][a-z0-9_-]*$")),M3=16,j3=J(()=>c.object({id:$3(),remote:c.string().max(256).regex(/^(npm:[@a-z0-9/._-]+(@[a-z0-9._+-]+)?|github:[\w.-]+\/[\w.-]+@[\w./-]+#.+\.js)$/,"must be npm:<pkg>[@ver] or github:<owner>/<repo>@<ref>#<path>.js").optional(),integrity:c.string().max(512).regex(/^sha(256|384|512)-[A-Za-z0-9+/=]+$/,"must be SRI form: sha256-, sha384-, or sha512-<base64>").optional()}).strict()),q3=J(()=>c.object({syntaxHighlighting:c.object({hljsLanguages:c.array(j3()).max(M3)}).strict()})),RP=J(()=>c.object({themes:c.union([Pn().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded \u2014 list its files here if you want both."),c.array(Pn().describe("Path to a themes directory or file, relative to the plugin root. When set, the themes/ directory is not auto-loaded \u2014 list its files here if you want both.")).describe("List of theme directory or file paths. When set, the themes/ directory is not auto-loaded.")])})),N3=J(()=>c.object({})),sS=J(()=>c.string().min(1)),D3=J(()=>c.string().min(2).refine(e=>e.startsWith("."),{message:'File extensions must start with dot (e.g., ".ts", not "ts")'})),L3=J(()=>c.object({mcpServers:c.union([ni().describe("MCP servers to include in the plugin (in addition to those in the .mcp.json file, if it exists)"),aS().describe("Path or URL to MCPB file containing MCP server configuration"),c.record(c.string(),em()).describe("MCP server configurations keyed by server name"),c.array(c.union([ni().describe("Path to MCP servers configuration file"),aS().describe("Path or URL to MCPB file"),c.record(c.string(),em()).describe("Inline MCP server configurations")])).describe("Array of MCP server configurations (paths, MCPB files, or inline definitions)")])})),OP=J(()=>c.object({type:c.enum(["string","number","boolean","directory","file"]).describe("Type of the configuration value"),title:c.string().describe("Human-readable label shown in the config dialog"),description:c.string().describe("Help text shown beneath the field in the config dialog"),required:c.boolean().optional().describe("If true, validation fails when this field is empty"),default:c.union([c.string(),c.number(),c.boolean(),c.array(c.string())]).optional().describe("Default value used when the user provides nothing"),multiple:c.boolean().optional().describe("For string type: allow an array of strings"),sensitive:c.boolean().optional().describe("If true, masks dialog input and stores value in secure storage (keychain/credentials file) instead of settings.json"),min:c.number().optional().describe("Minimum value (number type only)"),max:c.number().optional().describe("Maximum value (number type only)")}).strict()),U3=J(()=>c.object({userConfig:c.record(c.string().regex(/^[A-Za-z_]\w*$/,"Option keys must be valid identifiers (letters, digits, underscore; no leading digit) \u2014 they become CLAUDE_PLUGIN_OPTION_<KEY> env vars in hooks"),OP()).optional().describe("User-configurable values this plugin needs. Prompted at enable time. Non-sensitive values saved to settings.json; sensitive values to secure storage. Available as ${user_config.KEY} in MCP/LSP server config, hook commands, and (non-sensitive only) skill/agent content. Keep sensitive value counts small.")})),F3=J(()=>c.object({channels:c.array(c.object({server:c.string().min(1).describe("Name of the MCP server this channel binds to. Must match a key in this plugin's mcpServers."),displayName:c.string().optional().describe('Human-readable name shown in the config dialog title (e.g., "Telegram"). Defaults to the server name.'),userConfig:c.record(c.string(),OP()).optional().describe("Fields to prompt the user for when enabling this plugin in assistant mode. Saved values are substituted into ${user_config.KEY} references in the mcpServers env.")}).strict()).describe("Channels this plugin provides. Each entry declares an MCP server as a message channel and optionally specifies user configuration to prompt for at enable time.")})),dS=J(()=>c.strictObject({command:c.string().min(1).refine(e=>!(e.includes(" ")&&!e.startsWith("/")),{message:"Command should not contain spaces. Use args array for arguments."}).describe('Command to execute the LSP server (e.g., "typescript-language-server")'),args:c.array(sS()).optional().describe("Command-line arguments to pass to the server"),extensionToLanguage:c.record(D3(),sS()).refine(e=>Object.keys(e).length>0,{message:"extensionToLanguage must have at least one mapping"}).describe("Mapping from file extension to LSP language ID. File extensions and languages are derived from this mapping."),transport:c.enum(["stdio","socket"]).default("stdio").describe("Communication transport mechanism"),env:c.record(c.string(),c.string()).optional().describe("Environment variables to set when starting the server"),initializationOptions:c.unknown().optional().describe("Initialization options passed to the server during initialization"),settings:c.unknown().optional().describe("Settings passed to the server via workspace/didChangeConfiguration"),workspaceFolder:c.string().optional().describe("Workspace folder path to use for the server"),startupTimeout:c.number().int().positive().optional().describe("Maximum time to wait for server startup (milliseconds)"),shutdownTimeout:c.number().int().positive().optional().describe("Maximum time to wait for graceful shutdown (milliseconds)"),restartOnCrash:c.boolean().optional().describe("Whether to restart the server if it crashes"),maxRestarts:c.number().int().nonnegative().optional().describe("Maximum number of restart attempts before giving up"),diagnostics:c.boolean().optional().describe("Whether to push publishDiagnostics into the agent context after edits. Set to false to keep LSP navigation (goToDefinition, hover, etc.) but suppress automatic diagnostic injection. Defaults to true.")})),z3=J(()=>c.strictObject({name:c.string().min(1).describe("Identifier for this monitor, unique within the plugin. Used to dedupe so re-arming (plugin reload, repeat skill invoke) does not spawn duplicates."),command:c.string().min(1).describe('Shell command to run as a persistent background monitor. Each stdout line is delivered to the model as a <task_notification> event; the process runs for the session lifetime. ${CLAUDE_PLUGIN_ROOT}, ${CLAUDE_PLUGIN_DATA}, ${CLAUDE_PROJECT_DIR}, ${user_config.*}, and ${ENV_VAR} are substituted. Runs in the session cwd \u2014 prefix with `cd "${CLAUDE_PLUGIN_ROOT}" && ` if the script needs its own directory.'),description:c.string().min(1).describe("Short human-readable description of what is being monitored (shown in task panel and notification summary)."),when:c.union([c.literal("always"),c.string().startsWith("on-skill-invoke:").refine(e=>e.length>16,{message:"on-skill-invoke: must specify a skill name"})]).default("always").describe('Arm trigger. "always" arms at session start and on plugin reload. "on-skill-invoke:<skill>" arms the first time that skill is dispatched (via Skill tool or slash command).')})),B3=J(()=>c.array(z3()).refine(e=>new Set(e.map(t=>t.name)).size===e.length,{message:"Monitor names must be unique within a plugin"})),AP=J(()=>c.object({monitors:c.union([ni().describe("Path to a JSON file containing the monitors array, relative to the plugin root"),B3()]).describe("Background watch scripts the host arms as persistent Monitor tasks (unsandboxed, same trust tier as hooks) so plugins need not instruct the model to arm them. When omitted, monitors/monitors.json at the plugin root is loaded if present.")})),K3=J(()=>c.object({lspServers:c.union([ni().describe("Path to .lsp.json configuration file relative to plugin root"),c.record(c.string(),dS()).describe("LSP server configurations keyed by server name"),c.array(c.union([ni().describe("Path to LSP configuration file"),c.record(c.string(),dS()).describe("Inline LSP server configurations")])).describe("Array of LSP server configurations (paths or inline definitions)")])})),$P=J(()=>c.string().refine(e=>!e.includes("..")&&!e.includes("//"),"Package name cannot contain path traversal patterns").refine(e=>{let t=/^@[a-z0-9][a-z0-9-._]*\/[a-z0-9][a-z0-9-._]*$/,n=/^[a-z0-9][a-z0-9-._]*$/;return t.test(e)||n.test(e)},"Invalid npm package name format")),J3=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/,W3=/^[0-9a-f]{64}$/,H3=J(()=>c.object({sha256:c.string().regex(W3)}));V3=J(()=>c.object({binaries:c.unknown().transform(G3).describe("sha256-pinned files to fetch into bin/ at install time, keyed by basename (target triple encoded in the name)")})),Z3=J(()=>c.object({settings:c.record(c.string(),c.unknown()).optional().describe("Settings to merge into the user settings while this plugin is enabled. Only the documented allowlisted keys are applied.")})),Q3=J(()=>c.object({experimental:c.preprocess(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,c.object({...RP().partial().shape,...q3().partial().shape,...AP().partial().shape,...EP().partial().shape,evals:c.union([c.string(),c.array(c.string())]).optional().describe("Path(s) to evaluation query files for `claude plugin eval`. Defaults to `evals/`.")}).passthrough().optional().describe("Components whose manifest shape may change without a deprecation cycle. Move a key out of here once it is promoted to stable."))})),Y3=J(()=>c.object({...I3().shape,...P3().partial().shape,...R3().partial().shape,...O3().partial().shape,...A3().partial().shape,...EP().partial().shape,...RP().partial().shape,...N3().shape,...F3().partial().shape,...L3().partial().shape,...K3().partial().shape,...AP().partial().shape,...Z3().partial().shape,...U3().partial().shape,...V3().partial().shape,...Q3().partial().shape})),Vu=J(()=>c.discriminatedUnion("source",[c.object({source:c.literal("url"),url:c.string().url().describe("Direct URL to marketplace.json file"),headers:c.record(c.string(),c.string()).optional().describe("Custom HTTP headers (e.g., for authentication)")}),c.object({source:c.literal("github"),repo:c.string().describe("GitHub repository in owner/repo format"),ref:c.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:c.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:c.array(c.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:c.boolean().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),c.object({source:c.literal("git"),url:c.string().describe("Full git repository URL"),ref:c.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),path:c.string().optional().describe("Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"),sparsePaths:c.array(c.string()).optional().describe('Directories to include via git sparse-checkout (cone mode). Use for monorepos where the marketplace lives in a subdirectory. Example: [".claude-plugin", "plugins"]. If omitted, the full repository is cloned.'),skipLfs:c.boolean().optional().describe("Skip Git LFS smudge during clone and update (sets GIT_LFS_SKIP_SMUDGE=1) so LFS pointer files stay as pointers instead of downloading their content. Use for marketplaces hosted in repos with large LFS objects.")}),c.object({source:c.literal("npm"),package:$P().describe("NPM package containing marketplace.json")}),c.object({source:c.literal("file"),path:c.string().describe("Local file path to marketplace.json")}),c.object({source:c.literal("directory"),path:c.string().describe("Local directory containing .claude-plugin/marketplace.json")}),c.object({source:c.literal("skills-dir")}).describe("Policy-list sentinel for the ~/.claude/skills/ auto-load (@skills-dir plugins). In strictKnownMarketplaces: opt the scan back IN (by default any allowlist blocks it). In blockedMarketplaces: turn the scan OFF without otherwise restricting marketplaces. Only meaningful in those two managed-settings lists (areLocalPluginDirsAllowedByPolicy); known_marketplaces.json / marketplace add etc. ignore it."),c.object({source:c.literal("hostPattern"),hostPattern:c.string().describe('Regex pattern to match the host/domain extracted from any marketplace source type. For github sources, matches against github.com. For git sources (SSH or HTTPS), extracts the hostname from the URL. Use in strictKnownMarketplaces to allow all marketplaces from a specific host (e.g., "^github\\.mycompany\\.com$").')}),c.object({source:c.literal("pathPattern"),pathPattern:c.string().describe('Regex pattern matched against the .path field of file and directory sources. Use in strictKnownMarketplaces to allow filesystem-based marketplaces alongside hostPattern restrictions for network sources. Use ".*" to allow all filesystem paths, or a narrower pattern (e.g., "^/opt/approved/") to restrict to specific directories.')}),c.object({source:c.literal("settings"),name:PP().refine(e=>!IP.has(e.toLowerCase()),{message:"Reserved marketplace names cannot be used with settings sources. validateOfficialNameSource only accepts github/git sources from anthropics/* for these names; a settings source would be rejected after loadAndCacheMarketplace has already written to disk with cleanupNeeded=false."}).describe("Marketplace name. Must match the extraKnownMarketplaces key (enforced); the synthetic manifest is written under this name. Same validation as PluginMarketplaceSchema plus reserved-name rejection \u2014 validateOfficialNameSource runs after the disk write, too late to clean up."),plugins:c.array(X3()).describe("Plugin entries declared inline in settings.json"),owner:ny().optional()}).describe("Inline marketplace manifest defined directly in settings.json. The reconciler writes a synthetic marketplace.json to the cache; diffMarketplaces detects edits via isEqual on the stored source (the plugins array is inside this object, so edits surface as sourceChanged).")])),Op=J(()=>c.string().length(40).regex(/^[a-f0-9]{40}$/,"Must be a full 40-character lowercase git commit SHA")),MP=J(()=>c.union([c.preprocess(e=>e==="."?"./":e,Pn()).describe("Path to the plugin root, relative to the marketplace root (the directory containing .claude-plugin/, not .claude-plugin/ itself)"),c.object({source:c.literal("npm"),package:$P().or(c.string().refine(e=>/^(?:file|https?|git(?:\+https?|\+ssh)?|ssh|github|gitlab|bitbucket):/i.test(e)||!e.includes(".."),'Package reference cannot contain ".." path segments')).describe("Package name (or url, or local path, or anything else that can be passed to `npm` as a package)"),version:c.string().optional().describe("Specific version or version range (e.g., ^1.0.0, ~2.1.0)"),registry:c.string().url().optional().describe("Custom NPM registry URL (defaults to using system default, likely npmjs.org)")}).describe("NPM package as plugin source"),c.object({source:c.literal("url"),url:c.string().describe("Full git repository URL (https:// or git@)"),ref:c.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Op().optional().describe("Specific commit SHA to use")}),c.object({source:c.literal("github"),repo:c.string().describe("GitHub repository in owner/repo format"),ref:c.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Op().optional().describe("Specific commit SHA to use")}),c.object({source:c.literal("git-subdir"),url:c.string().describe("Git repository: GitHub owner/repo shorthand, https://, or git@ URL"),path:c.string().min(1).describe('Subdirectory within the repo containing the plugin (e.g., "tools/claude-plugin"). Cloned sparsely using partial clone (--filter=tree:0) to minimize bandwidth for monorepos.'),ref:c.string().optional().describe('Git branch or tag to use (e.g., "main", "v1.0.0"). Defaults to repository default branch.'),sha:Op().optional().describe("Specific commit SHA to use")}).describe("Plugin located in a subdirectory of a larger repository (monorepo). Only the specified subdirectory is materialized; the rest of the repo is not downloaded."),c.object({source:c.literal("unsupported")}).describe('Placeholder for source types this Claude Code version does not recognize. Never authored by hand \u2014 PluginMarketplaceSchema rewrites unparseable sources to this so the entry remains in marketplace.plugins (detectDelistedPlugins must not see it as removed). Install attempts fail at cachePlugin with a clear "update Claude Code" message.')])),X3=J(()=>c.object({name:c.string().min(1,"Plugin name cannot be empty").refine(e=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Plugin name as it appears in the target repository"),source:MP().describe("Where to fetch the plugin from. Must be a remote source \u2014 relative paths have no marketplace repository to resolve against."),description:c.string().optional(),version:c.string().optional(),strict:c.boolean().optional()}).refine(e=>typeof e.source!="string",{message:'Plugins in a settings-sourced marketplace must use remote sources (github, git-subdir, npm, url). Relative-path sources like "./foo" have no marketplace repository to resolve against.'}).refine(e=>typeof e.source=="string"||e.source.source!=="unsupported",{message:"source.source: 'unsupported' is a parse-time placeholder and cannot be authored. Use a remote source (github, git-subdir, npm, url)."})),eZ=J(()=>c.object({cli:c.array(c.string().max(64)).max(10).optional().describe('First command tokens (e.g. ["stripe"]) \u2014 exact match against commands run this session.'),hosts:c.array(c.string().max(128)).max(20).optional().describe('Hostnames (e.g. ["api.stripe.com"]) \u2014 exact, case-insensitive match against hostnames seen in https?:// URLs in bash commands run this session. Bare hostname only: lowercase, no scheme, no port, no path.'),filesRead:c.array(c.string().max(256)).max(10).optional().describe('Glob patterns (e.g. ["**/*.tf"]) \u2014 the plugin is relevant when a file Claude has read this session matches any pattern. Matched against read-file paths, forward-slash normalized, case-insensitive.'),manifestDeps:c.array(c.object({file:c.string().max(256),pattern:c.string().max(256)})).max(10).optional().describe("Dependency declared in a package manifest. Each {file, pattern} is a pair of RegExp sources: `file` matches the manifest filename (package.json, go.mod, requirements.txt, \u2026); `pattern` matches the dependency declaration inside that file. Evaluated against files read this session."),cwd:c.array(c.string().max(256)).max(10).optional().describe(`Glob patterns (e.g. ["Engine/Source/Runtime/Renderer/**"]) \u2014 the plugin is relevant when the session's working directory is at or under a directory matching the pattern. Matched against the cwd both relative to the enclosing git repo root and as an absolute path, forward-slash normalized, case-insensitive. A bare directory (no glob characters) means "cwd is at or under this directory". Known at session start, so this signal can surface a suggestion before the first turn.`)})),tZ=J(()=>c.object({topic:c.string().max(64).optional().describe('What the user is working with when this plugin is relevant \u2014 fills "Working with {topic}?". Often the product name (e.g. "Stripe"); use a domain (e.g. "design") when the plugin name does not read naturally as a topic. Defaults to the plugin name with each hyphen-segment capitalized.'),signals:eZ().optional().describe("Matchers that determine when the plugin is relevant.")})),nZ=J(()=>Y3().partial().extend({name:c.string().min(1,"Plugin name cannot be empty").refine(e=>!e.includes(" "),{message:'Plugin name cannot contain spaces. Use kebab-case (e.g., "my-plugin")'}).describe("Unique identifier matching the plugin name"),source:MP().describe("Where to fetch the plugin from"),category:c.string().optional().describe('Category for organizing plugins (e.g., "productivity", "development")'),tags:c.array(c.string()).optional().describe("Tags for searchability and discovery"),strict:c.boolean().optional().default(!0).describe("Require the plugin manifest to be present in the plugin folder. If false, the marketplace entry provides the manifest."),relevance:c.preprocess(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,tZ().optional()).describe(`Declares when this plugin is relevant to the user's work. Consumed by the spinner tip ("Working with {topic}?"), session-start auto-suggest, and marketplace browse ranking.`)})),rZ=J(()=>c.object({name:c.string().min(1).refine(e=>!e.includes(" "))}));_de=J(()=>c.object({$schema:c.string().optional().describe("JSON Schema reference for editor autocomplete/validation; ignored at load time"),name:PP(),version:c.string().optional().describe("Marketplace manifest version"),description:c.string().optional().describe("Human-readable description of this marketplace"),owner:ny().describe("Marketplace maintainer or curator information"),plugins:c.array(c.unknown()).transform(iZ).describe("Collection of available plugins in this marketplace"),forceRemoveDeletedPlugins:c.boolean().optional().describe("When true, plugins removed from this marketplace will be automatically uninstalled and flagged for users"),metadata:c.object({pluginRoot:c.string().optional().describe("Base path for relative plugin sources"),version:c.string().optional().describe("Marketplace version"),description:c.string().optional().describe("Marketplace description")}).optional().describe("Optional marketplace metadata"),allowCrossMarketplaceDependenciesOn:c.array(c.string()).optional().describe("Marketplace names whose plugins may be auto-installed as dependencies. Only the root marketplace's allowlist applies \u2014 no transitive trust."),renames:c.record(c.string(),c.string().nullable()).optional().catch(void 0).describe("Append-only map of old plugin name \u2192 current name (or null when removed). The loader follows this on plugin-not-found and migrates user settings to the new name.")})),jP=J(()=>c.string().regex(/^[A-Za-z0-9][-A-Za-z0-9._]*@[A-Za-z0-9][-A-Za-z0-9._]*$/,"Plugin ID must be in format: plugin@marketplace")),oZ=/^[A-Za-z0-9][-A-Za-z0-9._]*(@[A-Za-z0-9][-A-Za-z0-9._]*)?(@\^[^@]*)?$/,aZ=J(()=>c.union([c.string().regex(oZ,"Dependency must be a plugin name, optionally qualified with @marketplace").transform(e=>e.replace(/@\^[^@]*$/,"")),c.object({name:c.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/),marketplace:c.string().min(1).regex(/^[A-Za-z0-9][-A-Za-z0-9._]*$/).optional()}).loose().transform(e=>e.marketplace?`${e.name}@${e.marketplace}`:e.name)])),sZ=J(()=>c.object({version:c.string().describe("Currently installed version"),installedAt:c.string().describe("ISO 8601 timestamp of installation"),lastUpdated:c.string().optional().describe("ISO 8601 timestamp of last update"),installPath:c.string().describe("Absolute path to the installed plugin directory"),gitCommitSha:c.string().optional().describe("Git commit SHA for git-based plugins (for version tracking)"),resolvedVersion:c.string().optional().describe("Tag-derived semver this install resolved to (when fetched via a version constraint). Used by verifyAndDemote in preference to manifest.version, since the upstream may have forgotten to bump plugin.json."),auto:c.boolean().optional().describe("True when this plugin was pulled in as a dependency rather than installed explicitly. Auto-installed plugins are eligible for removal by the orphan sweep when nothing depends on them. Absent = manual (preserves pre-flag installs).")})),dZ=J(()=>c.object({version:c.literal(1).describe("Schema version 1"),plugins:c.record(jP(),sZ()).describe("Map of plugin IDs to their installation metadata")})),uZ=J(()=>c.enum(["managed","user","project","local"])),lZ=J(()=>c.object({scope:uZ().describe("Installation scope"),projectPath:c.string().optional().describe("Project path (required for project/local scopes)"),installPath:c.string().describe("Absolute path to the versioned plugin directory"),version:c.string().optional().describe("Currently installed version"),installedAt:c.string().optional().describe("ISO 8601 timestamp of installation"),lastUpdated:c.string().optional().describe("ISO 8601 timestamp of last update"),gitCommitSha:c.string().optional().describe("Git commit SHA for git-based plugins"),resolvedVersion:c.string().optional().describe("Tag-derived semver this install resolved to"),auto:c.boolean().optional().describe("True when pulled in as a dependency. Eligible for orphan sweep.")})),cZ=J(()=>c.object({version:c.literal(2).describe("Schema version 2"),plugins:c.record(jP(),c.array(lZ())).describe("Map of plugin IDs to arrays of installation entries")})),vde=J(()=>c.union([dZ(),cZ()])),pZ=J(()=>c.object({source:Vu().describe("Where to fetch the marketplace from"),installLocation:c.string().describe("Local cache path where marketplace manifest is stored"),lastUpdated:c.string().describe("ISO 8601 timestamp of last marketplace refresh"),autoUpdate:c.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),bde=J(()=>c.record(c.string(),pZ())),fZ=["autoMode","deepLink","voice","briefView","screenReader"],Td={},Wl={autoMode:{buildGate:()=>!1,shape:()=>Td,permissionsShape:()=>Td,permissionModes:()=>[]},deepLink:{buildGate:()=>!0,shape:()=>({disableDeepLinkRegistration:c.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")})},voice:{buildGate:()=>!1,shape:()=>Td},briefView:{buildGate:()=>!0,shape:()=>({defaultView:c.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")})},screenReader:{buildGate:()=>!1,shape:()=>Td}};uS={Task:"Agent",KillShell:"TaskStop",KillBash:"TaskStop",AgentOutputTool:"TaskOutput",BashOutputTool:"TaskOutput",AgentOutput:"TaskOutput",BashOutput:"TaskOutput",ListPeers:"ListAgents",Brief:"SendUserMessage",ListMcpResources:"ListMcpResourcesTool",ReadMcpResource:"ReadMcpResourceTool",ReadMcpResourceDir:"ReadMcpResourceDirTool"};DP="workspace",wde=`mcp__${DP}__bash`,Sde=`mcp__${DP}__web_fetch`;Zu={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit","Cd"],bashPrefixTools:["Bash"],customValidation:{WebSearch:e=>e.includes("*")||e.includes("?")?{valid:!1,error:"WebSearch does not support wildcards",suggestion:"Use exact search terms without * or ?",examples:["WebSearch(claude ai)","WebSearch(typescript tutorial)"]}:{valid:!0},WebFetch:e=>e.includes("://")||e.startsWith("http")?{valid:!1,error:"WebFetch permissions use domain format, not URLs",suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:github.com)"]}:e.startsWith("domain:")?{valid:!0}:{valid:!1,error:'WebFetch permissions must use "domain:" prefix',suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:*.google.com)"]}}};pS=J(()=>FP()),CZ=J(()=>FP("allow"));TZ=J(()=>c.record(c.string(),c.coerce.string()));kde=J(()=>zP(qP())),IZ=J(()=>c.object({source:Vu().describe("Where to fetch the marketplace from"),installLocation:c.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:c.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),ry=J(()=>c.object({serverName:c.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:c.array(c.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:c.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine(e=>Px([e.serverName!==void 0,e.serverCommand!==void 0,e.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),iy=J(()=>c.object({serverName:c.string().min(1,"Server name must be non-empty").refine(e=>e.trim().length>0,{message:"Server name must not be whitespace-only"}).refine(e=>e===e.trim(),{message:"Server name has leading or trailing whitespace and will never match (names are compared verbatim)"}).optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:c.array(c.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:c.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine(e=>Px([e.serverName!==void 0,e.serverCommand!==void 0,e.serverUrl!==void 0],Boolean)===1,{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),PZ=J(()=>c.object({path:c.string().describe("Absolute path to the helper executable"),timeoutMs:c.number().int().min(1e3).optional(),refreshIntervalMs:c.union([c.literal(0),c.number().int().min(6e4)]).optional()})),fS=["skills","agents","hooks","mcp"],mS=Object.freeze({type:"invalid-entry-stripped"}),EZ=J(()=>c.union([c.object({type:c.literal("regex").describe('Config variant. This client understands "regex": matches turn output and builds a URL from named capture groups. Entries with other variants are preserved but skipped at runtime.'),pattern:c.string().describe("Regex matched against turn output (tool results and assistant text)"),url:c.string().describe("Link target. {name} placeholders are filled from named regex capture groups, e.g. (?<id>...) -> {id}. Values are URL-encoded; the origin must be literal in the template. The scheme must be https, http, or a recognized editor or workspace deep-link scheme: vscode, vscode-insiders, cursor, windsurf, zed, jetbrains, idea, slack, linear, notion, figma."),label:c.string().optional().describe("Badge text. {name} placeholders filled from named capture groups; defaults to the full match.")}).passthrough(),c.object({type:c.string().describe("Config variant discriminator for entries this client does not understand; the entry is preserved as-is and skipped at runtime.")}).passthrough()]));Hl=J(()=>RZ(qP())),hS=Object.freeze({serverName:"invalid-entry-stripped"});Yn="https://code.claude.com/docs/en",OZ=[{matches:e=>e.path==="permissions.defaultMode"&&e.code==="invalid_value",tip:{suggestion:'Valid modes: "acceptEdits" (ask before file changes), "plan" (analysis only), "bypassPermissions" (auto-accept all), or "default" (standard behavior)',docLink:`${Yn}/iam#permission-modes`}},{matches:e=>e.path==="apiKeyHelper"&&e.code==="invalid_type",tip:{suggestion:'Provide a shell command that outputs your API key to stdout. The script should output only the API key. Example: "/bin/generate_temp_api_key.sh"'}},{matches:e=>e.path==="cleanupPeriodDays"&&e.code==="too_small",tip:{suggestion:'cleanupPeriodDays must be at least 1. To keep transcripts for a long time, set a large number (e.g. 3650 for ~10 years). To disable transcript writes entirely, remove this setting and use the --no-session-persistence CLI flag or the SDK persistSession:false option instead. (0 is rejected because it previously silently disabled all transcript writes, which users setting it to mean "never clean up" did not expect.)'}},{matches:e=>e.path.startsWith("env.")&&e.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:`${Yn}/settings#environment-variables`}},{matches:e=>(e.path==="permissions.allow"||e.path==="permissions.deny")&&e.code==="invalid_type"&&e.expected==="array",tip:{suggestion:'Permission rules must be in an array. Format: ["Tool(specifier)"]. Examples: ["Bash(npm run build)", "Edit(docs/**)", "Read(~/.zshrc)"]. Use * for wildcards.'}},{matches:e=>e.path.startsWith("hooks.")&&e.code==="invalid_key",tip:{suggestion:"Not a recognized hook event. Common events: PreToolUse, PostToolUse, UserPromptSubmit, SessionStart, SessionEnd, Stop. Check spelling and capitalization.",docLink:`${Yn}/hooks`}},{matches:e=>/\.hooks\.\d+\.command$/.test(e.path)&&e.code==="invalid_type"&&e.received==="undefined",tip:{suggestion:'Command hooks require `command`. For exec form (no shell), set `command` to the executable and `args` to its arguments: {"type": "command", "command": "echo", "args": ["hi"]}. For shell form, set `command` to the full shell string: {"type": "command", "command": "echo hi"}.',docLink:`${Yn}/hooks#exec-form-and-shell-form`}},{matches:e=>e.path.includes("hooks")&&e.code==="invalid_type",tip:{suggestion:'Hooks use a matcher + hooks array. The matcher is a string: a tool name ("Bash"), pipe-separated list ("Edit|Write"), or empty to match all. Example: {"PostToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "echo Done"}]}]}'}},{matches:e=>e.code==="invalid_type"&&e.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:e=>e.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:`${Yn}/settings`}},{matches:e=>e.code==="invalid_value"&&e.enumValues!==void 0,tip:{suggestion:void 0}},{matches:e=>e.code==="invalid_type"&&e.expected==="object"&&e.received===null&&e.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:e=>e.path==="permissions.additionalDirectories"&&e.code==="invalid_type",tip:{suggestion:'Must be an array of directory paths. Example: ["~/projects", "/tmp/workspace"]. You can also use --add-dir flag or /add-dir command',docLink:`${Yn}/iam#working-directories`}}],AZ={permissions:`${Yn}/iam#configuring-permissions`,env:`${Yn}/settings#environment-variables`,hooks:`${Yn}/hooks`};xde=J(()=>Hl().strict());qZ=new Set(ul);DZ=[{key:"allowedMcpServers",schema:ry},{key:"deniedMcpServers",schema:iy}];BZ=2097152;Mp=!1;o8=null;hr=Object.freeze({settings:{},errors:[]}),QP=null,YP=null,XP=!1,el=null;g8={user:"userSettings",project:"projectSettings",local:"localSettings"},CS={userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag",policySettings:"managed"},y8=["user","project","local"],_8=new Set(["bypassPermissions","auto","acceptEdits"]),v8=new Set(["project"]);process.env.NoDefaultCurrentDirectoryInExePath="1";T8=new Set(["EBUSY","EMFILE","ENFILE","ENOTEMPTY","EPERM"])});import{spawn as vy}from"node:child_process";import{randomUUID as S7}from"node:crypto";import{createConnection as k7,createServer as x7}from"node:net";import{appendFileSync as C7,rmSync as ko,writeFileSync as $s,mkdirSync as Co,mkdtempSync as xE,chmodSync as As,existsSync as xo,readFileSync as ci,readdirSync as T7,statSync as I7,unlinkSync as P7}from"node:fs";import{dirname as CE,join as or}from"node:path";import{spawn as IA}from"node:child_process";import{randomUUID as PA}from"node:crypto";import{createServer as EA}from"node:net";var fO=Ro(__(),1),mO=Ro(pc(),1),hO=Ro(hc(),1),kc=Ro(Hs(),1),gO=Ro(I_(),1);function Le(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function P_(e){let t=[["threadId",e.threadId],["turnId",e.turnId],["itemId",e.itemId],["processId",e.processId],["requestId",e.requestId]].filter(n=>n[1]!==void 0);return Object.fromEntries(t)}function fe(e){return e!==void 0&&Le(e)?e:void 0}function _t(e){return Array.isArray(e)?e:void 0}function Z(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}function Qe(e){return typeof e=="number"&&Number.isInteger(e)?e:void 0}import{appendFileSync as kO,openSync as tY}from"node:fs";import{homedir as $_}from"node:os";import{dirname as xO,join as M_,resolve as CO,sep as TO}from"node:path";import{mkdirSync as IO}from"node:fs";var Mn={_generated:"GENERATED by scripts/naming_dual_emit_codegen.mjs from scripts/naming_canonical_key_map.json (N2.2 dual-emit, D46) - DO NOT EDIT; run: node scripts/naming_dual_emit_codegen.mjs --write",events:[["codex.agent_turn_narration_only_no_reply","harness.agent_turn_narration_only_no_reply"],["codex.cost_cap_402_seen","harness.cost_cap_402_seen"],["codex.edge_blocked_captured","harness.edge_blocked_captured"],["codex.empty_turn_auto_retry_suppressed_cost_cap","harness.empty_turn_auto_retry_suppressed_cost_cap"],["codex.empty_turn_loop_guard_tripped","harness.empty_turn_loop_guard_tripped"],["codex.error_without_http_status_captured","harness.error_without_http_status_captured"],["codex.mid_stream_stall_auto_resume_flagged","harness.mid_stream_stall_auto_resume_flagged"],["codex.mid_stream_stall_fresh_session_resume","harness.mid_stream_stall_fresh_session_resume"],["codex.mid_stream_stall_fresh_session_resume_failed","harness.mid_stream_stall_fresh_session_resume_failed"],["codex.mid_stream_stall_fresh_session_resume_flagged","harness.mid_stream_stall_fresh_session_resume_flagged"],["codex.mid_stream_stall_resume_suppressed_rate_limit","harness.mid_stream_stall_resume_suppressed_rate_limit"],["codex.mid_stream_stall_second_stall_after_resume","harness.mid_stream_stall_second_stall_after_resume"],["codex.pre_first_byte_stall_auto_retry_flagged","harness.pre_first_byte_stall_auto_retry_flagged"],["codex.pre_first_byte_stall_retry_suppressed_cost_cap","harness.pre_first_byte_stall_retry_suppressed_cost_cap"],["codex.provider_outage_flagged_captured","harness.provider_outage_flagged_captured"],["codex.reasoning_loop_breaker_tripped","harness.reasoning_loop_breaker_tripped"],["codex.tool_fatal_captured","harness.tool_fatal_captured"],["codex.turn_completed","job.turn_completed"],["codex.turn_completed_with_protocol_failure","job.turn_completed_with_protocol_failure"],["codex.turn_completed_with_unsupported_tool_call_ignored","job.turn_completed_with_unsupported_tool_call_ignored"],["codex.turn_completed_without_assistant_output","job.turn_completed_without_assistant_output"],["codex.turn_demoted_late_upstream_error","job.turn_demoted_late_upstream_error"],["codex.turn_forward_failed","job.turn_forward_failed"],["codex.upstream_error_captured","harness.upstream_error_captured"],["codex.upstream_rejection_captured","harness.upstream_rejection_captured"],["codex.upstream_turn_error_captured","harness.upstream_turn_error_captured"],["kandan.chat_event","linzumi.chat_event"],["kandan.chat_event_abandoned","linzumi.chat_event_abandoned"],["kandan.chat_event_failed","linzumi.chat_event_failed"],["kandan.chat_event_failure_cleared","linzumi.chat_event_failure_cleared"],["kandan.child_thread_event_failed","linzumi.child_thread_event_failed"],["kandan.child_thread_event_skipped_missing_thread_binding","linzumi.child_thread_event_skipped_missing_thread_binding"],["kandan.child_thread_upsert_failed","linzumi.child_thread_upsert_failed"],["kandan.child_thread_upsert_skipped_missing_thread_binding","linzumi.child_thread_upsert_skipped_missing_thread_binding"],["kandan.claude_code_interrupt_state_push_failed","linzumi.claude_code_interrupt_state_push_failed"],["kandan.claude_code_stop_state_push_failed","linzumi.claude_code_stop_state_push_failed"],["kandan.claude_code_typing_heartbeat_failed","linzumi.claude_code_typing_heartbeat_failed"],["kandan.claude_code_typing_start_wait_timeout","linzumi.claude_code_typing_start_wait_timeout"],["kandan.claude_code_typing_stop_failed","linzumi.claude_code_typing_stop_failed"],["kandan.claude_code_user_input_abort_publish_failed","linzumi.claude_code_user_input_abort_publish_failed"],["kandan.claude_code_user_question_completed_publish_failed","linzumi.claude_code_user_question_completed_publish_failed"],["kandan.codex_command_output_forwarded","linzumi.codex_command_output_forwarded"],["kandan.codex_delta_forwarded","linzumi.codex_delta_forwarded"],["kandan.codex_file_change_forwarded","linzumi.codex_file_change_forwarded"],["kandan.codex_notification_push_failed","linzumi.codex_notification_push_failed"],["kandan.codex_output_forwarded","linzumi.codex_output_forwarded"],["kandan.codex_reasoning_delta_forwarded","linzumi.codex_reasoning_delta_forwarded"],["kandan.codex_web_search_progress_forwarded","linzumi.codex_web_search_progress_forwarded"],["kandan.connection_force_reconnect","linzumi.connection_force_reconnect"],["kandan.connection_force_reconnect_dispatched","linzumi.connection_force_reconnect_dispatched"],["kandan.connection_hard_reset","linzumi.connection_hard_reset"],["kandan.connection_hard_reset_exhausted","linzumi.connection_hard_reset_exhausted"],["kandan.connection_recovered","linzumi.connection_recovered"],["kandan.connection_stale","linzumi.connection_stale"],["kandan.connection_unrecoverable","linzumi.connection_unrecoverable"],["kandan.control","linzumi.control"],["kandan.control_ack_withheld_on_failure","linzumi.control_ack_withheld_on_failure"],["kandan.control_epoch_changed","linzumi.control_epoch_changed"],["kandan.control_handler_threw","linzumi.control_handler_threw"],["kandan.control_ignored","linzumi.control_ignored"],["kandan.control_response_push_failed","linzumi.control_response_push_failed"],["kandan.failed_seq_overflow","linzumi.failed_seq_overflow"],["kandan.forward_port_revoked_push_failed","linzumi.forward_port_revoked_push_failed"],["kandan.forward_response","linzumi.forward_response"],["kandan.forward_response_push_failed","linzumi.forward_response_push_failed"],["kandan.forward_tunnel_error","linzumi.forward_tunnel_error"],["kandan.forward_tunnel_open_failed","linzumi.forward_tunnel_open_failed"],["kandan.heartbeat_push_failed","linzumi.heartbeat_push_failed"],["kandan.local_editor_initial_status_failed","linzumi.local_editor_initial_status_failed"],["kandan.local_editor_status_push_failed","linzumi.local_editor_status_push_failed"],["kandan.message_duplicate_ignored","linzumi.message_duplicate_ignored"],["kandan.message_ignored","linzumi.message_ignored"],["kandan.message_queued","linzumi.message_queued"],["kandan.message_spawn_on_miss","linzumi.message_spawn_on_miss"],["kandan.message_spawn_on_miss_failed","linzumi.message_spawn_on_miss_failed"],["kandan.message_state_refresh_failed","linzumi.message_state_refresh_failed"],["kandan.optional_push_failed","linzumi.optional_push_failed"],["kandan.post_stop_queue_drain_failed","linzumi.post_stop_queue_drain_failed"],["kandan.queue_drain_blocked","linzumi.queue_drain_blocked"],["kandan.queue_drain_dead_worker_fail_publish_failed","linzumi.queue_drain_dead_worker_fail_publish_failed"],["kandan.queue_drain_dead_worker_rebuild","linzumi.queue_drain_dead_worker_rebuild"],["kandan.queue_drain_dead_worker_rebuild_exhausted","linzumi.queue_drain_dead_worker_rebuild_exhausted"],["kandan.queue_drain_dead_worker_rebuild_failed","linzumi.queue_drain_dead_worker_rebuild_failed"],["kandan.reconnect_handling_failed","linzumi.reconnect_handling_failed"],["kandan.reconnect_thread_context_fetch_failed","linzumi.reconnect_thread_context_fetch_failed"],["kandan.reconnect_thread_cwd_failed_state_push_failed","linzumi.reconnect_thread_cwd_failed_state_push_failed"],["kandan.reconnect_thread_failed","linzumi.reconnect_thread_failed"],["kandan.reconnect_thread_processing_state_push_failed","linzumi.reconnect_thread_processing_state_push_failed"],["kandan.reconnect_thread_queue_closed_state_push_failed","linzumi.reconnect_thread_queue_closed_state_push_failed"],["kandan.reconnect_thread_queue_failed_state_push_failed","linzumi.reconnect_thread_queue_failed_state_push_failed"],["kandan.reconnect_thread_queue_state_push_failed","linzumi.reconnect_thread_queue_state_push_failed"],["kandan.reconnect_thread_rehydrate_forced","linzumi.reconnect_thread_rehydrate_forced"],["kandan.reconnect_thread_rehydrated","linzumi.reconnect_thread_rehydrated"],["kandan.reconnect_thread_rehydrated_state_push_failed","linzumi.reconnect_thread_rehydrated_state_push_failed"],["kandan.reconnect_thread_rehydration_failed","linzumi.reconnect_thread_rehydration_failed"],["kandan.reconnect_thread_rehydration_ir_emitted","linzumi.reconnect_thread_rehydration_ir_emitted"],["kandan.reconnect_thread_rehydration_items_failed","linzumi.reconnect_thread_rehydration_items_failed"],["kandan.reconnect_thread_resume_failed","linzumi.reconnect_thread_resume_failed"],["kandan.reconnect_thread_seq_already_applied","linzumi.reconnect_thread_seq_already_applied"],["kandan.reconnect_thread_transcript_fetch_failed","linzumi.reconnect_thread_transcript_fetch_failed"],["kandan.reconnect_thread_unarchive_failed","linzumi.reconnect_thread_unarchive_failed"],["kandan.reconnect_thread_unarchive_resumed","linzumi.reconnect_thread_unarchive_resumed"],["kandan.reconnect_thread_unarchive_started","linzumi.reconnect_thread_unarchive_started"],["kandan.reconnect_thread_unavailable_state_push_failed","linzumi.reconnect_thread_unavailable_state_push_failed"],["kandan.reconnected","linzumi.reconnected"],["kandan.roster_seeded","linzumi.roster_seeded"],["kandan.session_app_server_lost_push_failed","linzumi.session_app_server_lost_push_failed"],["kandan.session_settings_publish_failed","linzumi.session_settings_publish_failed"],["kandan.start_instance_claude_code_attachment_failed_state_push_failed","linzumi.start_instance_claude_code_attachment_failed_state_push_failed"],["kandan.start_instance_codex_app_server_unavailable","linzumi.start_instance_codex_app_server_unavailable"],["kandan.start_instance_cwd_failed_state_push_failed","linzumi.start_instance_cwd_failed_state_push_failed"],["kandan.start_instance_cwd_rejected","linzumi.start_instance_cwd_rejected"],["kandan.start_instance_failed","linzumi.start_instance_failed"],["kandan.start_instance_processing_state_push_failed","linzumi.start_instance_processing_state_push_failed"],["kandan.start_instance_skipped_known_session","linzumi.start_instance_skipped_known_session"],["kandan.start_instance_stale_skipped","linzumi.start_instance_stale_skipped"],["kandan.start_instance_unavailable_state_push_failed","linzumi.start_instance_unavailable_state_push_failed"],["kandan.start_instance_wafer_state_push_failed","linzumi.start_instance_wafer_state_push_failed"],["kandan.start_turn_replay_skipped","linzumi.start_turn_replay_skipped"],["kandan.steer_duplicate_ignored","linzumi.steer_duplicate_ignored"],["kandan.steer_parked_as_own_turn","linzumi.steer_parked_as_own_turn"],["kandan.thread_bind_from_historical_reply_failed","linzumi.thread_bind_from_historical_reply_failed"],["kandan.thread_bound_from_historical_reply","linzumi.thread_bound_from_historical_reply"],["kandan.thread_sessions_reannounce_failed","linzumi.thread_sessions_reannounce_failed"],["kandan.thread_sessions_reannounced","linzumi.thread_sessions_reannounced"],["kandan.tui_input_mirrored","linzumi.tui_input_mirrored"],["kandan.typing_heartbeat_failed","linzumi.typing_heartbeat_failed"],["kandan.typing_stop_after_completion_failed","linzumi.typing_stop_after_completion_failed"]],keys:[["codexThreadId","harness_session_id"],["codex_thread_id","harness_session_id"],["kandanThreadId","thread_id"],["kandan_preview_ticket","linzumi_preview_ticket"],["kandan_thread_id","thread_id"],["linzumiThreadId","thread_id"],["linzumi_thread_id","thread_id"],["local_codex_runner","commander"],["runnerId","commander_id"],["runner_config","commander_config"],["runner_id","commander_id"]],keyPrimaryLegacy:[["commander","local_codex_runner"],["commander_config","runner_config"],["commander_id","runner_id"],["harness_session_id","codex_thread_id"],["linzumi_preview_ticket","kandan_preview_ticket"],["thread_id","kandan_thread_id"]],values:[["engine_boot_reconnect","harness_boot_reconnect"],["engine_for_runner_event_type","harness_for_commander_event_type"],["engine_rejected_steer","harness_rejected_steer"],["engine_unavailable","harness_unavailable"],["join_engine","join_harness"],["kandan-local-codex-runner","linzumi-commander"],["local_codex_runner","commander"],["original_engine","original_harness"],["resume_engine","resume_harness"]],topic:{legacyPrefix:"local_codex_runner:",canonicalPrefix:"commander:"},originator:{legacy:"kandan-local-codex-runner",canonical:"linzumi-commander"}};var _O=new Map(Mn.events),vO=new Map(Mn.events.map(([e,t])=>[t,e])),R_=new Map(Mn.keys),O_=new Map(Mn.keyPrimaryLegacy),bO=new Map(Mn.values),wO=new Map(Mn.values.map(([e,t])=>[t,e])),QQ={eventCanonicalByLegacy:_O,eventLegacyByCanonical:vO,keyCanonicalByLegacy:R_,keyPrimaryLegacyByCanonical:O_,valueCanonicalByLegacy:bO,valueLegacyByCanonical:wO,originator:Mn.originator,topic:Mn.topic};function A_(e){let t=new Set(e);for(let n of e){let i=R_.get(n);i!==void 0&&t.add(i);let r=O_.get(n);r!==void 0&&t.add(r)}return t}var E_=new Map;for(let[e,t]of Mn.keys){let n=E_.get(t)??[];n.push(e),E_.set(t,n)}var qr="<SENSITIVE_DATA>",j_=A_(new Set(["access_token","authorization","code","cookie","kandan_preview_ticket","refresh_token","token"])),PO=new Set(["--access-token","--api-key","--authorization","--cookie","--oauth-code","--password","--refresh-token","--secret","--token"]);function EO(e){if(process.env.VITEST===void 0)return;let t=M_($_(),".linzumi"),n=CO(e);if(n===t||n.startsWith(`${t}${TO}`))throw new Error(`test-mode log isolation violated: refusing to open ${e} inside the real ~/.linzumi (point the logger at a temp path; the harness defaults LINZUMI_RUNNER_LOG_FILE / LINZUMI_CLI_AUDIT_LOG for exactly this - see plans/2026-07-10-cli-test-hygiene-spec.md item 2)`)}function Ye(e,t,n={}){let i=n.logFile??RO();EO(i);try{IO(xO(i),{recursive:!0}),kO(i,`${JSON.stringify({ts:new Date().toISOString(),event:e,...n.sessionId===void 0?{}:{sessionId:n.sessionId},...q_(t)})}
123
+ `,"utf8")}catch{return}}function RO(){let e=process.env.LINZUMI_CLI_AUDIT_LOG?.trim();return e===void 0||e===""?M_($_(),".linzumi","logs","command-events.jsonl"):e}function q_(e){return N_(e)}function xc(e,t){return $O(t)?qr:typeof e=="string"?D_(e):Array.isArray(e)?t==="args"?OO(e):e.map(n=>xc(n,void 0)):e!==null&&typeof e=="object"?N_(e):e}function N_(e){let t=typeof e.name=="string"?e.name.toLowerCase():void 0,n=t==="authorization"||t==="cookie"||t==="set-cookie";return Object.fromEntries(Object.entries(e).filter(([i])=>i!=="runner_console").map(([i,r])=>[i,n&&i==="value"?qr:xc(r,i)]))}function OO(e){let t=!1;return e.map(n=>{if(typeof n!="string")return t=!1,xc(n,void 0);if(t)return t=!1,qr;let[i,r]=AO(n);return PO.has(i)?r===void 0?(t=!0,n):`${i}=${qr}`:D_(n)})}function AO(e){let t=e.indexOf("=");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function $O(e){return e===void 0?!1:/^(authorization|cookie|set-cookie|password)$/i.test(e)||/(^|[_-])(access[_-]?token|api[_-]?key|auth[_-]?token|oauth[_-]?code|refresh[_-]?token|secret|token)$/i.test(e)}function D_(e){return MO(e).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,qr)}function MO(e){let t;try{t=new URL(e)}catch{return jO(e)}for(let n of[...t.searchParams.keys()])j_.has(n.toLowerCase())&&t.searchParams.set(n,qr);return t.toString()}function jO(e){let t=e.indexOf("?"),n=e.indexOf("#");if(t===-1||n!==-1&&n<t)return e;let i=e.slice(0,t),r=n===-1?e.slice(t+1):e.slice(t+1,n),o=n===-1?"":e.slice(n),a=new URLSearchParams(r),s=!1;for(let d of[...a.keys()])j_.has(d.toLowerCase())&&(a.set(d,qr),s=!0);switch(s){case!0:return`${i}?${a.toString()}${o}`;case!1:return e}}import{stripVTControlCharacters as BO}from"node:util";function Vs(e){let t=e.channelSession,n=t.linzumiAgentSession===!0,i=n?"read-only":t.sandbox,r=qO(t);return{cwd:e.cwd,...t.model===void 0?{}:{model:t.model},...r===void 0?{}:{config:r},...e.fast===!0?{serviceTier:"fast"}:{},...t.codexEnvironmentId===void 0?{}:{environmentId:t.codexEnvironmentId},approvalPolicy:n?"never":L_(t.approvalPolicy,i,{sandboxedNeverDefault:t.sandboxedApprovalNeverDefault}),...i===void 0?{}:{sandbox:i}}}function Cc(e){let t=e.channelSession,n=t.linzumiAgentSession===!0,i=n?"read-only":t.sandbox;return{cwd:e.cwd,...t.model===void 0?{}:{model:t.model},...t.reasoningEffort===void 0?{}:{effort:t.reasoningEffort},...e.fast===!0?{serviceTier:"fast"}:{},...t.codexEnvironmentId===void 0?{}:{environmentId:t.codexEnvironmentId},approvalPolicy:n?"never":L_(t.approvalPolicy,i,{sandboxedNeverDefault:t.sandboxedApprovalNeverDefault}),...i===void 0?{}:{sandboxPolicy:LO(i,e.cwd)}}}function qO(e){let t=e.reasoningEffort===void 0?{}:{model_reasoning_effort:e.reasoningEffort};return e.linzumiAgentSession!==!0?e.reasoningEffort===void 0?void 0:t:{...t,web_search:"disabled",tools:{view_image:!1},features:{apps:!1,shell_tool:!1,unified_exec:!1,multi_agent:!1,code_mode:!1,image_generation:!1,browser_use:!1,browser_use_external:!1,computer_use:!1,remote_plugin:!1,tool_suggest:!1,workspace_dependencies:!1}}}function NO(e,t,n){let i=n?.sandboxedNeverDefault===!0&&t==="workspace-write";switch(e){case void 0:case"default":return i?"never":"on-request";case"never":return t==="danger-full-access"||i?"never":"on-request";case"on-request":case"on-failure":return e;default:return console.warn(`linzumi approval-policy clamp: unknown Codex approval policy ${e}; clamping to most-restrictive approval (on-request)`),"on-request"}}var DO={granular:{sandbox_approval:!1,rules:!1,skill_approval:!1,request_permissions:!1,mcp_elicitations:!0}};function L_(e,t,n){let i=NO(e,t,n);return i==="never"&&t==="danger-full-access"?DO:i==="on-failure"?"on-request":i}function LO(e,t){switch(e){case"danger-full-access":return{type:"dangerFullAccess"};case"read-only":return{type:"readOnly",networkAccess:!1};case"workspace-write":return{type:"workspaceWrite",writableRoots:[t],networkAccess:!1,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1};default:throw new Error(`unsupported Codex sandbox mode: ${e}`)}}function U_(e){let t=BO(e),n=t.match(/https:\/\/[^\s\u0000-\u001f\u007f]+/u)?.[0],i=t.match(/\b[A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+\b/u)?.[0];return n===void 0||i===void 0?void 0:{verificationUrl:n,userCode:i}}function Tc(e){return e==="final_answer"?"final_answer":"commentary"}function Ic(e){let t=KO(e),n=fe(e.item);if(!(t===void 0||t===""))return{itemKey:Z(e.itemId)??Z(e.item_id)??Z(fe(e.item)?.id)??"assistant-message",turnId:Z(e.turnId)??Z(e.turn_id)??Z(fe(e.turn)?.id),delta:t,phase:Tc(e.phase??n?.phase)}}function Pc(e){let t=F_(e);if(!(t===void 0||t===""))return{itemKey:Z(e.itemId)??Z(e.item_id)??Z(fe(e.item)?.id)??"reasoning",turnId:Z(e.turnId)??Z(e.turn_id)??Z(fe(e.turn)?.id),delta:t}}function KO(e){return F_(e)}function JO(e){return e>=55296&&e<=56319}function WO(e){return e>=56320&&e<=57343}function Ec(e,t){let n=Math.min(Math.max(0,t),e.length),i=n>0&&n<e.length&&JO(e.charCodeAt(n-1))&&WO(e.charCodeAt(n))?n-1:n;return e.slice(0,i)}function F_(e){let t=e.delta;return typeof t=="string"?t:Le(t)?Z(t.text)??Z(t.content)??Z(t.delta)??Z(t.message):Z(e.text)??Z(e.content)??Z(e.message)}import{mkdirSync as HO,appendFileSync as GO}from"node:fs";import{dirname as VO}from"node:path";function z_(e){return JSON.stringify(e)}var Lo,ZO=/(^|[_-])(token|secret|api[_-]?key|authorization|cookie|private[_-]?key|login[_-]?url)([_-]|$)/iu;function Rc(){return B_()!==void 0}function Fo(e){let t=B_();if(t===void 0)return;let n=QO(t),i=YO(e),r={schemaVersion:1,provider:e.provider,captureKind:e.captureKind,ordinal:n.nextOrdinal,offsetMs:Math.max(0,Date.now()-n.startedAtMs),...i.rawText===void 0?{}:{rawText:i.rawText},...i.rawValue===void 0?{}:{rawValue:i.rawValue},...e.captureMetadata===void 0?{}:{captureMetadata:Uo(e.captureMetadata)},...i.transforms.length===0?e.transforms===void 0?{}:{transforms:e.transforms}:{transforms:[...e.transforms??[],...i.transforms]}};n.nextOrdinal+=1,GO(t,`${z_(r)}
124
+ `,"utf8")}function B_(){let e=process.env.LINZUMI_AGENT_REPLAY_RECORD_FILE?.trim();return e===void 0||e===""?void 0:e}function QO(e){return Lo!==void 0&&Lo.path===e||(HO(VO(e),{recursive:!0}),Lo={path:e,startedAtMs:Date.now(),nextOrdinal:0}),Lo}function YO(e){if(process.env.LINZUMI_AGENT_REPLAY_EXACT_RAW==="1")return{rawText:e.rawText,rawValue:e.rawValue,transforms:[]};let t=[],n=e.rawValue===void 0?void 0:Uo(e.rawValue,"$.rawValue",t);return{rawText:XO(e.rawText,t),rawValue:n,transforms:t}}function XO(e,t){if(e!==void 0)try{let n=JSON.parse(e);return JSON.stringify(Uo(n,"$.rawText",t))}catch{return e}}function Uo(e,t="$",n=[]){if(Array.isArray(e))return e.map((r,o)=>Uo(r,`${t}[${o}]`,n));if(!Le(e))return e;let i=Object.entries(e).map(([r,o])=>{let a=`${t}.${r}`;return ZO.test(r)?(n.push({type:"credential_redaction",path:a}),[r,"[REDACTED]"]):[r,o===void 0?void 0:Uo(o,a,n)]});return Object.fromEntries(i)}import{spawnSync as W_}from"node:child_process";import{existsSync as H_}from"node:fs";import{homedir as eA}from"node:os";import{basename as tA,posix as G_,win32 as nA}from"node:path";function zo(e){return e==="win32"?nA:G_}var Zs="__LINZUMI_LOGIN_PATH_BEGIN__",Ac="__LINZUMI_LOGIN_PATH_END__";function rA(e,t){let n=tA(e).includes("fish")?`printf '%s%s%s' '${Zs}' (string join ':' $PATH) '${Ac}'`:`printf '%s%s%s' '${Zs}' "$PATH" '${Ac}'`;switch(t){case"interactive_login":return["-l","-i","-c",n];case"interactive":return["-i","-c",n];case"login":return["-l","-c",n]}}function iA(e,t){let n=W_(e,[...t],{encoding:"utf8",timeout:5e3,killSignal:"SIGKILL",stdio:["ignore","pipe","ignore"]});return{stdout:typeof n.stdout=="string"?n.stdout:void 0,error:n.error}}function wi(e){return{env:e?.env??process.env,platform:e?.platform??process.platform,homeDir:e?.homeDir??eA(),fileExists:e?.fileExists??H_,runLoginShell:e?.runLoginShell}}var K_,J_=!1;function oA(e){if(e===void 0)return;let t=e.lastIndexOf(Zs),n=e.lastIndexOf(Ac);if(t===-1||n===-1||n<=t)return;let i=e.slice(t+Zs.length,n).trim();return i===""?void 0:i}function $c(e){let t=wi(e);if(t.platform==="win32")return;let n=e===void 0;if(e!==void 0&&e.runLoginShell===void 0||n&&process.env.VITEST!==void 0)return;if(n&&J_)return K_;let i=t.env.SHELL?.trim(),r=t.runLoginShell??iA,o=[];if(i!==void 0&&i!=="")for(let s of["interactive_login","interactive","login"]){let d=r(i,rA(i,s)),u=oA(d.stdout);if(u!==void 0)for(let l of u.split(":"))l!==""&&o.push(l)}let a=o.length===0?void 0:Ys(o).join(":");return n&&(K_=a,J_=!0),a}function V_(e){let t=wi(e);if(t.platform==="win32")return[];let n=t.homeDir,i=G_.join,r=t.env.VOLTA_HOME?.trim(),o=t.env.BUN_INSTALL?.trim(),a=t.env.npm_config_prefix?.trim(),s=t.env.N_PREFIX?.trim();return Ys([i(n,".local","bin"),i(n,".volta","bin"),r===void 0||r===""?void 0:i(r,"bin"),i(n,".bun","bin"),o===void 0||o===""?void 0:i(o,"bin"),i(n,".npm-global","bin"),a===void 0||a===""?void 0:i(a,"bin"),s===void 0||s===""?void 0:i(s,"bin"),i(n,".claude","local"),"/opt/homebrew/bin","/usr/local/bin"].filter(d=>d!==void 0))}function Qs(e,t){return e===void 0?[]:e.split(zo(t).delimiter).filter(n=>n!=="")}function Ys(e){return Array.from(new Set(e))}function Z_(e){let t=wi(e);return Ys([...Qs(t.env.PATH,t.platform),...Qs($c(e),t.platform),...V_(e)])}var Oc;function Q_(e){let t=e===void 0;if(t&&process.env.VITEST!==void 0)return process.env.PATH??"";if(t&&Oc!==void 0)return Oc;let n=wi(e),i=Z_(e).join(zo(n.platform).delimiter);i!==""&&(n.env.PATH=i);let r=$c(e);return r!==void 0&&r!==""&&(n.env[Y_]=r),t&&(Oc=i),i}function Mc(e,t){let n=wi(t);if(e.includes("/")||e.includes("\\"))return n.fileExists(e)?e:void 0;let i=n.platform==="win32"?[`${e}.exe`,`${e}.cmd`,e]:[e],r=zo(n.platform).join;for(let o of Z_(t))for(let a of i){let s=r(o,a);if(n.fileExists(s))return s}}var aA="LINZUMI_DISABLE_JOB_PATH_PARITY",sA="LINZUMI_DIRENV",Y_="LINZUMI_LOGIN_SHELL_PATH";function dA(e){return Ys([...Qs(e.jobPath,e.platform),...Qs(e.loginShellPath,e.platform),...e.installDirs]).join(zo(e.platform).delimiter)}function jc(e,t){if(e[aA]==="1"||t===void 0&&process.env.VITEST!==void 0)return e;let i=wi(t);if(i.platform==="win32")return e;let r=e[Y_]?.trim(),o=r!==void 0&&r!==""?r:$c(t),a=dA({jobPath:e.PATH,loginShellPath:o,installDirs:V_(t),platform:i.platform});return a===""||a===e.PATH?e:{...e,PATH:a}}var uA=3e3;function lA(e,t,n){let i=W_(e,["export","json"],{cwd:t,env:n,encoding:"utf8",timeout:uA,killSignal:"SIGKILL",stdio:["ignore","pipe","pipe"]});return{stdout:typeof i.stdout=="string"?i.stdout:void 0,stderr:typeof i.stderr=="string"?i.stderr:void 0,status:i.status,error:i.error}}function cA(e,t,n){let i=zo(n),r=e;for(let o=0;o<64;o+=1){if(t(i.join(r,".envrc")))return r;let a=i.dirname(r);if(a===r)return;r=a}}function qc(e,t,n){try{if(t[sA]!=="1")return t;let i=n?.platform??process.platform;if(i==="win32")return t;let r=n?.fileExists??H_,o=n?.log??(()=>{}),a=cA(e,r,i);if(a===void 0)return t;let s=Mc("direnv",{env:t,platform:i,fileExists:r});if(s===void 0)return o("direnv.unavailable",{cwd:e,envrc_dir:a}),t;let u=(n?.runDirenvExport??lA)(s,e,t);if(u.error!==void 0||u.status!==0)return o("direnv.export_failed",{cwd:e,envrc_dir:a,status:u.status??null,error:u.error?.message??null,stderr_head:u.stderr?.slice(0,300)??null}),t;let l=u.stdout?.trim()??"";if(l==="")return t;let p=JSON.parse(l);if(p===null||typeof p!="object"||Array.isArray(p))return o("direnv.export_failed",{cwd:e,envrc_dir:a,status:0,error:"direnv export json did not produce an object",stderr_head:null}),t;let m={...t},f=0;for(let[h,y]of Object.entries(p))y===null?(delete m[h],f+=1):typeof y=="string"&&(m[h]=y,f+=1);return f===0?t:(o("direnv.export_applied",{cwd:e,envrc_dir:a,vars:f}),m)}catch(i){return n?.log?.("direnv.export_failed",{cwd:e,envrc_dir:null,status:null,error:i instanceof Error?i.message:String(i),stderr_head:null}),t}}function X_(e){return{name:"linzumi",command:e.command??"linzumi",args:[...e.argsPrefix??[],"mcp","server","--api-url",e.kandanUrl,...e.authFilePath===void 0?[]:["--auth-file",e.authFilePath],...e.delegationAuthFilePath===void 0?[]:["--delegation-auth-file",e.delegationAuthFilePath],...e.ownerUsername===void 0?[]:["--owner-username",e.ownerUsername],...e.cwd===void 0?[]:["--cwd",e.cwd],...e.threadId===void 0?[]:["--thread-id",e.threadId],"--mode",e.operatingMode??"text",...e.toolScope===void 0||e.toolScope==="all"?[]:["--tool-scope",e.toolScope],...e.agentSession===!0?["--agent-session"]:[],...e.askUserQuestionTool===!0?["--ask-user-question-tool"]:[],...e.multiAgentJobs===!0?["--multi-agent-jobs"]:[]],env:{...e.accessToken===void 0?{}:{LINZUMI_MCP_ACCESS_TOKEN:e.accessToken},...e.devServices===void 0?{}:{LINZUMI_DEV_SERVICES_SCOPE:e.devServices.scope,LINZUMI_DEV_SERVICES_OWNER_PID:String(e.devServices.ownerPid)},ELECTRON_RUN_AS_NODE:"1"}}}function Nc(e,t){return["-c",`mcp_servers.${e.name}.command=${JSON.stringify(e.command)}`,"-c",`mcp_servers.${e.name}.args=${pA(e.args)}`,...Object.entries(e.env).flatMap(([n,i])=>["-c",`mcp_servers.${e.name}.env.${n}=${JSON.stringify(i)}`]),...t.neverEquivalentGranularApprovalPolicy?["-c",`mcp_servers.${e.name}.default_tools_approval_mode="approve"`]:[],...e.args.includes("--ask-user-question-tool")?["-c",`mcp_servers.${e.name}.tool_timeout_sec=${ev}`]:[]]}function pA(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}var ev=2147483,fA=ev*1e3-5*6e4;var EY=["# Managed by Linzumi - do not edit by hand.","# This isolated CODEX_HOME keeps Linzumi-spawned codex processes off the","# user's ~/.codex config and the macOS Keychain. See codexHome.ts.",'mcp_oauth_credentials_store = "file"','cli_auth_credentials_store = "file"',""].join(`
125
+ `);function tv(){return["-c",'mcp_oauth_credentials_store="file"',"-c",'cli_auth_credentials_store="file"']}import{spawnSync as mA}from"node:child_process";import{homedir as hA}from"node:os";import{dirname as MY,join as gA}from"node:path";var Dc=5*6e4;var yA={listenersBySource:new Map,lastMirrorPayloadJson:void 0,lastMirrorWriteMs:0,mirrorPathOverride:void 0};function nv(){return gA(hA(),".linzumi","protected-dev-listeners")}function Lc(e=Date.now()){let t=new Set;for(let n of yA.listenersBySource.values())if(!(e-n.updatedAtMs>Dc))for(let i of n.listeners)t.add(i.pid);return t}function _A(e){return e.split(`
126
+ `).map(t=>t.trim().match(/^(\d+)\s+(\d+)$/)).filter(t=>t!==null).map(t=>({pid:Number(t[1]),pgid:Number(t[2])}))}function Uc(e){try{let t=mA("ps",["-axo","pid=,pgid="],{encoding:"utf8",timeout:5e3,killSignal:"SIGKILL"});return t.error!==void 0||t.status!==0?void 0:_A(t.stdout).filter(n=>n.pgid===e).map(n=>n.pid)}catch{return}}function Bo(e,t,n=process.kill,i=Uc,r=Lc()){if(r.size>0){let o=i(e);if(o!==void 0){let a=o.filter(s=>r.has(s));if(a.length>0){let s=[],d=new Set(o.filter(u=>!r.has(u)));d.add(e);for(let u of d)try{n(u,t)}catch(l){vA(l)!=="ESRCH"&&s.push({pid:u,error:l})}return{mode:"individual",sparedPids:a,failures:s}}}}return n(-e,t),{mode:"group",sparedPids:[],failures:[]}}function vA(e){if(e!==null&&typeof e=="object"&&"code"in e){let t=e.code;return typeof t=="string"?t:void 0}}var Nr={children:new Set,handlersInstalled:!1,removeHandlers:void 0},rv="SIGKILL";function iv(e,t=process.kill){return Nr.children.add(e),wA(),{unregister:()=>{Nr.children.delete(e)}}}function Fc(e=process.kill,t="exit"){let n=[...Nr.children];Nr.children.clear();for(let i of n)bA(i,e,t);return n.length}function bA(e,t,n){try{e.stop()}catch(i){Xs(e,n,"stop",i)}if(e.pid!==void 0){if(e.ownProcessGroup)try{let i=Bo(e.pid,rv,t);i.sparedPids.length>0&&SA(e,n,i.sparedPids);for(let r of i.failures)Xs(e,n,`member_kill:${r.pid}`,r.error);return}catch(i){if(zc(i)==="ESRCH")return;Xs(e,n,"group_kill",i)}try{t(e.pid,rv)}catch(i){if(zc(i)==="ESRCH")return;Xs(e,n,"pid_kill",i)}}}function wA(){if(Nr.handlersInstalled)return;Nr.handlersInstalled=!0;let e=()=>{Fc(process.kill,"process_exit")};process.on("exit",e);let t=process.listenerCount("uncaughtException")===0,n=process.listenerCount("unhandledRejection")===0,i=o=>{Fc(process.kill,"uncaught_exception"),process.stderr.write(`linzumi runner uncaughtException: ${o instanceof Error?o.stack??o.message:String(o)}
127
+ `),process.exit(1)},r=o=>{Fc(process.kill,"unhandled_rejection"),process.stderr.write(`linzumi runner unhandledRejection: ${o instanceof Error?o.stack??o.message:String(o)}
128
+ `),process.exit(1)};t&&process.on("uncaughtException",i),n&&process.on("unhandledRejection",r),Nr.removeHandlers=()=>{process.off("exit",e),t&&process.off("uncaughtException",i),n&&process.off("unhandledRejection",r)}}function SA(e,t,n){try{Ye("process.reap_spared_listeners",{purpose:e.kind,pid:e.pid??null,reason:t,sparedPids:[...n]})}catch{}}function Xs(e,t,n,i){Ye("process.reap_failed",{purpose:e.kind,pid:e.pid??null,ownProcessGroup:e.ownProcessGroup,reason:t,stage:n,code:zc(i)??null,message:i instanceof Error?i.message:String(i)})}function zc(e){if(e!==null&&typeof e=="object"&&"code"in e){let t=e.code;return typeof t=="string"?t:void 0}}function kA(e){return JSON.stringify(e)}function xA(){return`
129
+ const { spawn, spawnSync } = require('node:child_process');
130
+ const fs = require('node:fs');
131
+ const config = JSON.parse(process.argv[process.argv.length - 1]);
132
+ const originalParentPid = process.ppid;
133
+ const child = spawn(config.command, config.args, { stdio: 'inherit' });
134
+ let done = false;
135
+ // Dev-server exemption (keep in sync with devServerReapExemption.ts
136
+ // readProtectedPidsFromDir - the freshness bound is textually substituted
137
+ // from protectedListenerFreshnessMs at program build): union of every FRESH
138
+ // mirror file's pids. Any failure is reported and returns an empty set,
139
+ // restoring the classic whole-group kill.
140
+ function reportProtectedMirrorReadFailure(stage, path, error) {
141
+ const message = error && error.message ? error.message : String(error);
142
+ process.stderr.write('protected listener mirror read failed: stage=' + stage + ' path=' + path + ' message=' + message + String.fromCharCode(10));
143
+ }
144
+ function protectedPids() {
145
+ const out = new Set();
146
+ const dir = config.protectedPidsDir;
147
+ if (typeof dir !== 'string' || dir === '') return out;
148
+ let names;
149
+ try { names = fs.readdirSync(dir); } catch (error) {
150
+ if (!error || error.code !== 'ENOENT') reportProtectedMirrorReadFailure('read_directory', dir, error);
151
+ return out;
152
+ }
153
+ const now = Date.now();
154
+ for (const name of names) {
155
+ if (!name.endsWith('.json')) continue;
156
+ const path = dir + '/' + name;
157
+ try {
158
+ const parsed = JSON.parse(fs.readFileSync(path, 'utf8'));
159
+ if (!parsed || typeof parsed.updatedAtMs !== 'number' || !Array.isArray(parsed.pids)) {
160
+ reportProtectedMirrorReadFailure('shape', path, new Error('mirror requires numeric updatedAtMs and pids array'));
161
+ continue;
162
+ }
163
+ if (now - parsed.updatedAtMs > ${Dc}) continue;
164
+ for (const pid of parsed.pids) {
165
+ if (Number.isInteger(pid) && pid > 1) out.add(pid);
166
+ }
167
+ } catch (error) { reportProtectedMirrorReadFailure('read_or_parse', path, error); }
168
+ }
169
+ return out;
170
+ }
171
+ // Group kill that spares protected listener pids: enumerate this group's
172
+ // members (the wrapper leads its own group) and signal each one except the
173
+ // spared listeners and the wrapper itself (the wrapper exits via its own
174
+ // child-exit/parent-death paths). Any enumeration failure, or no protected
175
+ // member in the group, falls back to the atomic kill(-pgid).
176
+ function groupKillExcept(signal) {
177
+ const spare = protectedPids();
178
+ if (spare.size > 0) {
179
+ try {
180
+ const result = spawnSync('ps', ['-axo', 'pid=,pgid='], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' });
181
+ if (result.error === undefined && result.status === 0) {
182
+ const members = [];
183
+ let sparedAny = false;
184
+ for (const line of result.stdout.split('\\n')) {
185
+ const match = line.trim().match(/^(\\d+)\\s+(\\d+)$/);
186
+ if (!match || Number(match[2]) !== process.pid) continue;
187
+ const pid = Number(match[1]);
188
+ if (pid === process.pid) continue;
189
+ if (spare.has(pid)) { sparedAny = true; continue; }
190
+ members.push(pid);
191
+ }
192
+ if (sparedAny) {
193
+ for (const pid of members) { try { process.kill(pid, signal); } catch (_e) {} }
194
+ return;
195
+ }
196
+ }
197
+ } catch (_e) {}
198
+ }
199
+ process.kill(-process.pid, signal);
200
+ }
201
+ function shutdown(signal) {
202
+ if (done) return;
203
+ done = true;
204
+ try { groupKillExcept(signal); }
205
+ catch (_e) { try { child.kill(signal); } catch (_e2) {} }
206
+ }
207
+ process.on('SIGINT', () => shutdown('SIGINT'));
208
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
209
+ process.on('SIGHUP', () => shutdown('SIGTERM'));
210
+ child.on('exit', (code, signal) => {
211
+ clearInterval(watchdog);
212
+ // The child is gone; the wrapper must follow it down rather than linger as an
213
+ // orphan. On the forwarded-signal path (shutdown() above caught SIGINT/SIGTERM
214
+ // /SIGHUP and propagated it to the child), the wrapper still has its own
215
+ // handler installed for that signal, so a bare process.kill(self, signal)
216
+ // would just re-enter shutdown() - a no-op once done is set - and the wrapper
217
+ // would never exit. Remove the handlers first so the signal's DEFAULT
218
+ // disposition (terminate) applies, re-raise to mirror the child's death
219
+ // signal, then exit() as a belt-and-suspenders fallback in case re-raising
220
+ // does not terminate (e.g. a signal with no default-terminate disposition).
221
+ process.removeAllListeners('SIGINT');
222
+ process.removeAllListeners('SIGTERM');
223
+ process.removeAllListeners('SIGHUP');
224
+ if (signal) { try { process.kill(process.pid, signal); } catch (_e) {} }
225
+ process.exit(signal ? 1 : code == null ? 0 : code);
226
+ });
227
+ child.on('error', (err) => {
228
+ process.stderr.write('engine watchdog spawn failed: ' + (err && err.message) + '\\n');
229
+ process.exit(1);
230
+ });
231
+ const watchdog = setInterval(() => {
232
+ // Inlined parentDeathWatchdogShouldReap (keep in sync): reap PURELY on a ppid
233
+ // change from boot - covers reparent-to-subreaper AND reparent-to-init. NO
234
+ // \`=== 1\` arm: a runner that is PID 1 captures originalParentPid === 1, so
235
+ // such an arm would false-fire on the first poll and kill a healthy codex.
236
+ if (process.ppid !== originalParentPid) {
237
+ try { child.kill('SIGKILL'); } catch (_e) {}
238
+ try { groupKillExcept('SIGKILL'); } catch (_e) {}
239
+ process.exit(0);
240
+ }
241
+ }, config.pollIntervalMs);
242
+ `.trim()}function ov(e,t){return{command:e,args:["-e",xA(),kA(t)]}}var RA=2e3,OA=(()=>{let e=process.env.LINZUMI_CODEX_WS_KEEPALIVE_MS;if(e===void 0)return 2e4;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>0?t:2e4})();function AA(e){let t=e;if(typeof t.ping=="function"&&t.readyState===WebSocket.OPEN)try{t.ping()}catch{}}var $A=["LINZUMI_MCP_ACCESS_TOKEN","LINZUMI_MCP_OWNER_USERNAME"];async function MA(){return new Promise((e,t)=>{let n=EA();n.on("error",i=>t(i)),n.listen(0,"127.0.0.1",()=>{let i=n.address();if(typeof i=="object"&&i!==null){let r=i.port;n.close(o=>{o!==void 0?t(o):e(r)})}else n.close(),t(new Error("failed to allocate loopback port"))})})}async function lv(e,t,n={}){return cv(e,t,n,1)}async function cv(e,t,n,i){let o=`ws://127.0.0.1:${await MA()}`,a=Kc(o,n);i===1&&GA();let s="",d=NA(),u=ov(process.execPath,{command:e,args:a,pollIntervalMs:RA,protectedPidsDir:nv()});Ye("process.spawn",{command:e,args:a,cwd:t,purpose:"codex.app_server"});let l=IA(u.command,[...u.args],{cwd:t,env:DA(n.env,n.inheritEnv??!0,t),stdio:d,detached:!0});av(l,"stdout"),av(l,"stderr",y=>{s=jA(`${s}${y}`)});let p=iv({stop:()=>sv(l),pid:l.pid,ownProcessGroup:!0,kind:"codex.app_server"});l.once("exit",()=>p.unregister());let m=()=>{p.unregister(),sv(l)},f,h=()=>(p.unregister(),f??=UA(l),f);Ye("process.spawned",{command:e,args:a,cwd:t,pid:l.pid,purpose:"codex.app_server"}),l.once("exit",(y,w)=>{Ye("process.exit",{command:e,args:a,cwd:t,pid:l.pid,code:y,signal:w,purpose:"codex.app_server"})});try{await u$(o,l)}catch(y){if(m(),qA(y,s,i))return Ye("process.spawn.retry",{command:e,cwd:t,attempt:i,reason:"loopback_bind_in_use",purpose:"codex.app_server"}),cv(e,t,n,i+1);throw y}return{url:o,process:l,stop:m,stopAndWait:h}}function jA(e){return e.length>12e3?e.slice(e.length-12e3):e}function qA(e,t,n){let r=e instanceof Error?e.message:String(e);return n<3&&r.includes("codex app-server exited before readyz")&&t.includes("EADDRINUSE")&&t.includes("listen")}function NA(){return["ignore","pipe","pipe"]}function av(e,t,n=void 0){let i=e[t];i!==null&&i.on("data",r=>{let o=r.toString();n?.(o),Ye("process.output",{pid:e.pid,purpose:"codex.app_server",stream:t,chars:o.length,output:o})})}function DA(e,t,n){let i=t?{...process.env}:{};for(let r of $A)delete i[r];if(e!==void 0)for(let[r,o]of Object.entries(e))o===void 0?delete i[r]:i[r]=o;return t&&(i=jc(i),i=qc(n,i,{log:(r,o)=>Ye(r,o)}),i=jc(i)),i}function sv(e,t=process.kill){if(e.pid!==void 0)try{let n=Bo(e.pid,"SIGINT",t);n.sparedPids.length>0&&Ye("process.group_signal_spared_listeners",{pid:e.pid,signal:"SIGINT",sparedPids:[...n.sparedPids],purpose:"codex.app_server"});return}catch(n){pv(e.pid,"SIGINT",n)}e.kill("SIGINT")}function LA(e){try{return process.kill(-e,0),!0}catch(t){return Bc(t)!=="ESRCH"}}function UA(e,t={}){let n=e.pid;if(n===void 0)return Promise.reject(new Error("cannot reap owned Codex app-server without a process id"));let i=t.sigintGraceMs??5e3,r=t.sigkillWaitMs??5e3,o=t.killProcess??process.kill,a=t.listGroupPids??Uc,s=t.processGroupExists??LA,d=t.protectedPids??Lc;return new Promise((u,l)=>{let p=e.exitCode!==null||e.signalCode!==null,m=!1,f,h,y,w=()=>{f!==void 0&&clearTimeout(f),h!==void 0&&clearTimeout(h),y!==void 0&&clearTimeout(y)},g=_=>{if(!m)switch(m=!0,w(),e.off("exit",C),_){case"reaped":u();break;case"abandoned":l(new Error(`owned Codex app-server process group ${n} could not be confirmed reaped`));break}},v=()=>{let _=a(n);if(_===void 0)return;let k=d();return _.filter(I=>!k.has(I))},b=()=>{let _=v(),k=_===void 0?!s(n):_.length===0;return p&&k?(g("reaped"),!0):!1},S=()=>{m||y!==void 0||(y=setTimeout(()=>{y=void 0,b()||S()},10),y.unref?.())},T=_=>{try{let k=Bo(n,_,o,a,d());k.sparedPids.length>0&&Ye("process.group_signal_spared_listeners",{pid:n,signal:_,sparedPids:[...k.sparedPids],purpose:"codex.app_server"})}catch(k){if(Bc(k)!=="ESRCH"){pv(n,_,k);try{e.kill(_)}catch{}}}},C=()=>{p=!0,b()||S()};e.once("exit",C),T("SIGINT"),!b()&&(f=setTimeout(()=>{m||(T("SIGKILL"),b()||S(),h=setTimeout(()=>g("abandoned"),r),h.unref?.())},i),f.unref?.())})}function pv(e,t,n){let i=Bc(n),r=n instanceof Error?n.message:String(n);Ye(i==="EPERM"?"process.group_signal_denied":i==="ESRCH"?"process.group_signal_missing":"process.group_signal_failed",{pid:e,signal:t,code:i,message:r,fallback:"child_signal",purpose:"codex.app_server"}),i==="EPERM"&&process.stderr.write(`codex app-server process-group ${t} denied for pid ${e}; falling back to direct child ${t}
243
+ `)}function Bc(e){if(e!==null&&typeof e=="object"&&"code"in e){let t=e.code;return typeof t=="string"?t:void 0}}function Kc(e,t={}){return["app-server",...QA(t),"--listen",e]}var FA=["-c","features.apps=false"],zA=["-c","features.default_mode_request_user_input=true"],fv="LINZUMI_CODEX_STREAM_IDLE_TIMEOUT_MS",BA="LINZUMI_CODEX_STREAM_IDLE_TIMEOUT_SOURCE",Jc=5e3,Wc=6e5,KA=["flag","env","server_default"];function JA(e){return KA.find(t=>t===e)}function WA(e){let t=e?.trim();if(e===void 0||t===void 0||t==="")return{state:"unset"};if(!/^[0-9]+$/.test(t))return{state:"invalid",raw:e};let n=Number(t);return!Number.isSafeInteger(n)||n<Jc||n>Wc?{state:"invalid",raw:e}:{state:"applied",timeoutMs:n}}function mv(e=process.env){let t=WA(e[fv]);if(t.state==="unset")return t;let n=JA(e[BA]?.trim())??"env";return{...t,source:n}}function HA(e=process.env){let t=mv(e);return t.state==="applied"?t.timeoutMs:void 0}function GA(e=process.env,t=n=>{process.stderr.write(`${n}
244
+ `)}){let n=mv(e);if(n.state!=="unset"){if(n.state==="invalid"){let i=VA();t(`ERROR: ${fv}='${n.raw}' is invalid; stream-idle-timeout stays OFF. Accepted: ${i}.`),Ye("codex.stream_idle_timeout_config_invalid",{level:"error",raw:n.raw,source:n.source,acceptedFormat:i,minMs:Jc,maxMs:Wc});return}Ye("codex.stream_idle_timeout_config_applied",{level:"info",timeoutMs:n.timeoutMs,source:n.source})}}function VA(){return`a plain positive integer between ${Jc} and ${Wc} (milliseconds)`}var hv="openai-linzumi";function gv(){let e=hv;return["-c",`model_providers.${e}.name="OpenAI"`,"-c",`model_providers.${e}.wire_api="responses"`,"-c",`model_providers.${e}.requires_openai_auth=true`,"-c",`model_providers.${e}.supports_websockets=true`]}function ZA(e){let t=hv;return[...gv(),"-c",`model_providers.${t}.stream_idle_timeout_ms=${e}`,"-c",`model_provider="${t}"`]}function QA(e,t=process.env){let n=HA(t);return[...FA,...e.nativeQuestionBridge==="durable"?zA:[],...tv(),...e.model===void 0?[]:["-c",`model=${JSON.stringify(e.model)}`],...e.reasoningEffort===void 0?[]:["-c",`model_reasoning_effort=${JSON.stringify(e.reasoningEffort)}`],...e.fast===!0?["-c",`service_tier=${JSON.stringify("fast")}`]:[],...(e.mcpServers??[]).flatMap(i=>Nc(i,{neverEquivalentGranularApprovalPolicy:e.neverEquivalentGranularApprovalPolicy===!0})),...e.modelProvider===void 0?n===void 0?gv():ZA(n):YA(e.modelProvider,n)]}function YA(e,t){return["-c",`model_providers.${e.id}.name=${JSON.stringify(e.name)}`,"-c",`model_providers.${e.id}.base_url=${JSON.stringify(e.baseUrl)}`,"-c",`model_providers.${e.id}.env_key=${JSON.stringify(e.envKey)}`,"-c",`model_providers.${e.id}.wire_api=${JSON.stringify(e.wireApi)}`,...Object.entries(e.httpHeaders??{}).flatMap(([n,i])=>["-c",`model_providers.${e.id}.http_headers.${n}=${JSON.stringify(i)}`]),...Object.entries(e.envHttpHeaders??{}).flatMap(([n,i])=>["-c",`model_providers.${e.id}.env_http_headers.${n}=${JSON.stringify(i)}`]),...t===void 0?[]:["-c",`model_providers.${e.id}.stream_idle_timeout_ms=${t}`],"-c",`model_provider=${JSON.stringify(e.id)}`]}async function Hc(e,t=i=>new kc.default(i),n=2e3){let i=await r$(e,t,n),r=PA(),o=new Map,a=new Set,s=new Set,d=[],u=new Set,l={nextId:1,closeError:void 0},p=y=>{let w=new Error(y);o.forEach(g=>g.reject(w)),o.clear()},m=setInterval(()=>AA(i),OA);m.unref?.();let f=y=>{if(clearInterval(m),p(y),l.closeError===void 0){l.closeError=new Error(y);for(let w of u)uv(w,l.closeError);u.clear()}};return i.addEventListener("close",()=>f("codex app-server websocket closed")),i.addEventListener("error",()=>f("codex app-server websocket closed")),i.addEventListener("message",y=>{let w=String(y.data),g=n$(w);if(g===void 0){XA(w,r);return}if(Ko({direction:"codex_to_commander",captureKind:t$(g),message:g,rawText:w,connectionId:r}),"id"in g&&("result"in g||"error"in g)){let v=o.get(g.id);v!==void 0&&(o.delete(g.id),v.resolve(g));return}if("id"in g&&typeof g.method=="string"){o$(i,g,s,r);return}if(!("id"in g)&&typeof g.method=="string"){let v=g;a.size===0?d.push(v):a.forEach(b=>dv(b,v))}}),await s$(i,o,r),{request:(y,w)=>{let g=l.nextId;return l.nextId+=1,yv(i,o,w===void 0?{jsonrpc:"2.0",id:g,method:y}:{jsonrpc:"2.0",id:g,method:y,params:w},r)},notify:(y,w)=>{let g=w===void 0?{jsonrpc:"2.0",method:y}:{jsonrpc:"2.0",method:y,params:w};Ko({direction:"commander_to_codex",captureKind:"outgoing",message:g,rawText:JSON.stringify(g),connectionId:r}),i.send(JSON.stringify(g))},onNotification:y=>{a.add(y),d.splice(0).forEach(w=>dv(y,w))},onRequest:y=>{s.add(y)},onClose:y=>{if(l.closeError!==void 0){uv(y,l.closeError);return}u.add(y)},isClosed:()=>l.closeError!==void 0,close:()=>{clearInterval(m),i.close()}}}function Ko(e){Rc()&&Fo({provider:"codex-app-server",captureKind:e.captureKind,rawText:e.rawText,rawValue:{message:e.message},captureMetadata:{direction:e.direction,capturedAtMs:Date.now(),capturePid:process.pid,connectionId:e.connectionId,...e$(e.message),...e.extraMetadata??{}}})}function XA(e,t){Rc()&&Fo({provider:"codex-app-server",captureKind:"incoming",rawText:e,captureMetadata:{direction:"codex_to_commander",capturedAtMs:Date.now(),capturePid:process.pid,connectionId:t,malformed:!0}})}function e$(e){return!("params"in e)||!Le(e.params)?{}:P_(e.params)}function t$(e){return"id"in e&&("result"in e||"error"in e)?"response":"id"in e&&typeof e.method=="string"?"request":"notification"}function n$(e){let t=String(e);try{let n=JSON.parse(t);if(!Le(n))throw new Error("codex app-server sent non-object JSON-RPC message");return n}catch(n){Ye("codex.app_server_frame_malformed",{purpose:"codex.app_server",message:n instanceof Error?n.message:String(n),payload:Ec(t,512),payloadChars:t.length});return}}function dv(e,t){try{e(t)}catch(n){Ye("codex.notification_callback_failed",{purpose:"codex.app_server",method:t.method,message:n instanceof Error?n.message:String(n)})}}function uv(e,t){try{e(t)}catch(n){Ye("codex.close_callback_failed",{purpose:"codex.app_server",message:n instanceof Error?n.message:String(n)})}}async function r$(e,t,n=2e3){let i=Date.now()+n,r;for(;Date.now()<=i;){let o=t(e);try{return await d$(o,Math.max(1,i-Date.now())),o}catch(a){r=a instanceof Error?a:new Error(String(a)),i$(o)}}throw r??new Error("websocket open failed")}function i$(e){let t=()=>{e.removeEventListener("error",n),e.removeEventListener("close",i)},n=()=>t(),i=()=>t();e.addEventListener("error",n,{once:!0}),e.addEventListener("close",i,{once:!0});try{e.close()}catch(r){t(),console.warn(`codex_app_server_failed_open_close_threw error_name=${r instanceof Error?r.name:"NonErrorThrow"}`)}}async function o$(e,t,n,i){let r=o=>a$(e,o,t.method,i);try{if(n.size===0){r({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`unhandled Codex app-server request: ${t.method}`}});return}for(let o of n){let a=await o(t);if(a!==void 0){r({jsonrpc:"2.0",id:t.id,result:a});return}}r({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`unhandled Codex app-server request: ${t.method}`}})}catch(o){r({jsonrpc:"2.0",id:t.id,error:{code:-32e3,message:o instanceof Error?o.message:String(o)}})}}function a$(e,t,n,i){let r=JSON.stringify(t);Ko({direction:"commander_to_codex",captureKind:"response",message:t,rawText:r,connectionId:i,extraMetadata:{requestMethod:n}}),e.send(r)}async function s$(e,t,n){let i=await yv(e,t,{jsonrpc:"2.0",id:"initialize",method:"initialize",params:{clientInfo:{name:"kandan-local-codex-runner",version:"0.0.1"},capabilities:{experimentalApi:!0}}},n);if("error"in i)throw new Error(`codex initialize failed: ${i.error.message}`);let r={jsonrpc:"2.0",method:"initialized"};Ko({direction:"commander_to_codex",captureKind:"outgoing",message:r,rawText:JSON.stringify(r),connectionId:n}),e.send(JSON.stringify(r))}function yv(e,t,n,i){return e.readyState!==WebSocket.OPEN?Promise.reject(new Error("codex app-server websocket is not open")):new Promise((r,o)=>{t.set(n.id,{resolve:r,reject:o}),Ko({direction:"commander_to_codex",captureKind:"request",message:n,rawText:JSON.stringify(n),connectionId:i}),e.send(JSON.stringify(n))})}function d$(e,t){return new Promise((n,i)=>{let r,o=()=>{r!==void 0&&clearTimeout(r),e.removeEventListener("open",a),e.removeEventListener("error",s)},a=()=>{o(),n()},s=()=>{o(),i(new Error("websocket open failed"))};e.addEventListener("open",a,{once:!0}),e.addEventListener("error",s,{once:!0}),r=setTimeout(()=>{o(),i(new Error("websocket open timed out"))},t),r.unref?.()})}function u$(e,t,n=1e4){let i=l$(e),r=Date.now()+n;return new Promise((o,a)=>{let s=!1,d,u=f=>{s||(s=!0,d!==void 0&&clearTimeout(d),t.off("exit",l),f==="ready"?o():a(f))},l=(f,h)=>{u(new Error(`codex app-server exited before readyz: ${f??h??"unknown"}`))},p=()=>{d=setTimeout(m,50)},m=async()=>{if(Date.now()>r){u(new Error("timed out waiting for codex app-server readyz"));return}try{(await fetch(i)).ok?u("ready"):p()}catch{p()}};t.once("exit",l),m()})}function l$(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/readyz",t.search="",t.hash="",t.toString()}var aX=300*1e3;function ed(e){let t=new URL(e);switch(t.protocol){case"ws:":t.protocol="http:";break;case"wss:":t.protocol="https:";break;case"http:":case"https:":break;default:throw new Error("--api-url must be ws://, wss://, http://, or https://")}return t.pathname="",t.search="",t.hash="",t.toString().replace(/\/$/,"")}function Jo(e){let t=e.fetchImpl??fetch,n=ed(e.kandanUrl),i=e.authMode==="personal-agent-delegation"?"/api/v2/personal-agent-mcp":"/api/v2/local-runner-mcp",r=e.operatingMode??"text",o=async(a,s,d,u={})=>{let l=new URL(s,n),p={...d,operating_mode:r},m={method:a,headers:{authorization:`Bearer ${e.accessToken}`},...u.signal===void 0?{}:{signal:u.signal}};if(a==="GET")for(let[v,b]of Object.entries(p))b!=null&&l.searchParams.set(v,String(b));else m.headers={...m.headers,"content-type":"application/json"},m.body=JSON.stringify(p);let f=await t(l,m),h=await f.json(),y=Le(h)?h:void 0;if(y===void 0)throw new Error(`Linzumi MCP API returned non-object JSON from ${s}`);if(f.ok&&y.ok===!0)return y;let w=typeof y.error=="string"?y.error:`HTTP ${f.status}`,g=typeof y.detail=="string"?y.detail:void 0;throw new Error(`Linzumi MCP API ${s} failed: ${w}${g===void 0?"":` detail=${g}`}`)};return{validateAuth:()=>o("GET",`${i}/validate`,{}),issueOnboardingDiscoveryToken:a=>o("POST",`${i}/onboarding-discovery-token`,a),getMessage:a=>o("GET",`${i}/message`,a),getThread:a=>o("GET",`${i}/thread`,a),getThreadTranscript:a=>o("GET",`${i}/thread-transcript`,a),getChannel:a=>o("GET",`${i}/channel`,a),searchWorkspace:a=>o("GET",`${i}/search`,a),askWorkspace:a=>o("POST",`${i}/ask`,a),aboutMe:a=>o("GET",`${i}/about-me`,a),webSearch:a=>o("GET",`${i}/web-search`,a),fetchUrl:a=>o("GET",`${i}/fetch-url`,a),listUiTargets:a=>o("GET",`${i}/ui-targets`,a),openUi:a=>o("POST",`${i}/open-ui`,a),getCodingJobMetadata:a=>o("GET",`${i}/coding-job-metadata`,a),listProjects:a=>o("GET",`${i}/projects`,a),getProjectTasks:a=>o("GET",`${i}/project-tasks`,a),createProjectTask:a=>o("POST",`${i}/project-tasks/create`,a),updateProjectTask:a=>o("POST",`${i}/project-tasks/update`,a),deleteProjectTask:a=>o("POST",`${i}/project-tasks/delete`,a),addProjectTaskDependency:a=>o("POST",`${i}/project-tasks/add-dependency`,a),removeProjectTaskDependency:a=>o("POST",`${i}/project-tasks/remove-dependency`,a),getCallTranscript:a=>o("GET",`${i}/call-transcript`,a),renameCodingJob:a=>o("POST",`${i}/coding-job-title`,a),upsertCodingJobPlan:(a,s)=>o("POST",`${i}/coding-job-plan`,a,s),replaceCodingJobPlanSteps:a=>o("POST",`${i}/coding-job-plan/steps`,a),updateCodingJobPlanStep:a=>o("POST",`${i}/coding-job-plan/step`,a),linkCodingJobPullRequest:a=>o("POST",`${i}/coding-job-primary-pr`,a),listVaultSecrets:a=>o("GET",`${i}/vault-secrets`,a),noteProjectDirectory:a=>o("POST",`${i}/discovered-project`,a),noteAgentConversation:a=>o("POST",`${i}/discovered-conversation`,a),noteOnboardingDiscoveryStatus:a=>o("POST",`${i}/discovery-status`,a),sendChannelMessage:a=>o("POST",`${i}/channel-message`,a),editMessage:a=>o("POST",`${i}/message/edit`,a),agentReply:a=>o("POST",`${i}/agent-reply`,a),scheduleWake:a=>o("POST",`${i}/scheduled-wakes`,a),cancelWake:a=>o("POST",`${i}/scheduled-wakes/cancel`,a),declineDocumentAction:a=>o("POST",`${i}/agent/decline-document-action`,a),agentTurnProgress:a=>o("POST",`${i}/agent-turn-progress`,a),agentDocumentTool:a=>o("POST",`${i}/agent/document-tool`,a),agentTopicTool:a=>o("POST",`${i}/agent/topic-tool`,a),agentListCodingJobs:a=>o("GET",`${i}/agent/coding-jobs`,a),agentStartCodingJob:a=>o("POST",`${i}/agent/start-coding-job`,a),agentSpawnChildJob:a=>o("POST",`${i}/agent/spawn-child-job`,a),agentArchiveChildJob:a=>o("POST",`${i}/agent/archive-child-job`,a),agentUnarchiveChildJob:a=>o("POST",`${i}/agent/unarchive-child-job`,a),agentInterruptCodingJob:a=>o("POST",`${i}/agent/interrupt-coding-job`,a),agentSendCodingJobMessage:a=>o("POST",`${i}/agent/send-coding-job-message`,a),agentDiscoverCodingJobs:a=>o("GET",`${i}/agent/discover-coding-jobs`,a),agentReadCodingJobThread:a=>o("GET",`${i}/agent/coding-job-thread`,a),agentResolveJobApproval:a=>o("POST",`${i}/agent/resolve-job-approval`,a),agentArchiveCodingJob:a=>o("POST",`${i}/agent/archive-coding-job`,a),agentUnarchiveCodingJob:a=>o("POST",`${i}/agent/unarchive-coding-job`,a),agentSetThreadStatus:a=>o("POST",`${i}/agent/set-thread-status`,a),agentCreateChannel:a=>o("POST",`${i}/agent/create-channel`,a),agentRenameChannel:a=>o("POST",`${i}/agent/rename-channel`,a),agentArchiveChannel:a=>o("POST",`${i}/agent/archive-channel`,a),agentUnarchiveChannel:a=>o("POST",`${i}/agent/unarchive-channel`,a),agentAddReaction:a=>o("POST",`${i}/agent/add-reaction`,a),agentRemoveReaction:a=>o("POST",`${i}/agent/remove-reaction`,a),agentPinMessage:a=>o("POST",`${i}/agent/pin-message`,a),agentUnpinMessage:a=>o("POST",`${i}/agent/unpin-message`,a),prepareMessageUploads:a=>o("POST",`${i}/message-uploads/prepare`,a),attachMessageFiles:a=>o("POST",`${i}/message-files/attach`,a),prepareCustomEmoji:a=>o("POST",`${i}/custom-emoji/prepare`,a),renameCustomEmoji:a=>o("POST",`${i}/custom-emoji/rename`,a),sendThreadReply:a=>o("POST",`${i}/thread-reply`,a),sendDm:a=>o("POST",`${i}/dm`,a),dmOwner:a=>o("POST",`${i}/dm-owner`,a),getVaultValues:a=>o("POST",`${i}/vault-values`,a)}}import{existsSync as c$,mkdirSync as pX,readFileSync as p$,renameSync as fX,rmSync as mX,writeFileSync as hX}from"node:fs";import{homedir as f$}from"node:os";import{dirname as _X,join as m$}from"node:path";function h$(){return m$(f$(),".linzumi","auth.json")}function Wo(e,t=h$()){if(!c$(t))return;let n=g$(p$(t,"utf8")),i=ed(e),r=n.local_codex_runner?.[i];if(!(r===void 0||r.access_token.trim()==="")&&!(r.expires_at!==void 0&&Date.parse(r.expires_at)<=Date.now()))return{accessToken:r.access_token,kandanBaseUrl:i,issuedAt:r.issued_at,expiresAt:r.expires_at}}function g$(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Kandan auth cache must contain a JSON object");let n=t,i=n.local_codex_runner,r=n.personal_agent_delegation;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("Kandan auth cache local_codex_runner must be an object");if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new Error("Kandan auth cache personal_agent_delegation must be an object");return{version:1,local_codex_runner:_$(i),personal_agent_delegation:y$(r)}}function y$(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.access_token,n=e.issued_at,i=e.expires_at;if(!(typeof t!="string"||typeof n!="string"))return{access_token:t,issued_at:n,expires_at:typeof i=="string"?i:void 0}}function _$(e){if(!(typeof e!="object"||e===null||Array.isArray(e)))return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{if(typeof n!="object"||n===null||Array.isArray(n))return[];let i=n.access_token,r=n.issued_at,o=n.expires_at;return typeof i!="string"||typeof r!="string"?[]:[[t,{access_token:i,issued_at:r,expires_at:typeof o=="string"?o:void 0}]]}))}var v$=50,_v="runner.notice";function b$(e){let t=new Map;return{report:i=>{let r=i.key??i.message,o=i.audience??"user",a=e.nowMs(),s=t.get(r),d=s===void 0?{key:r,severity:i.severity,message:i.message,audience:o,count:1,firstAtMs:a,lastAtMs:a}:{...s,severity:i.severity,message:i.message,audience:o,count:s.count+1,lastAtMs:a};t.delete(r),t.set(r,d);for(let u of t.keys()){if(t.size<=v$)break;t.delete(u)}return e.writeAuditEvent(_v,{severity:d.severity,audience:d.audience,key:d.key,message:d.message,count:d.count}),e.tuiActive()?(d.audience==="user"&&e.reportConsoleEvent(_v,{severity:d.severity,key:d.key,message:d.message,count:d.count}),d):(d.count===1&&e.writeStderr(`${w$(d.severity)}${d.message}
245
+ `),d)},notices:()=>Array.from(t.values()),reset:()=>t.clear()}}function w$(e){switch(e){case"warning":return"WARNING: ";case"error":return"ERROR: ";case"info":return""}}var vv={tuiActive:()=>!1,reportConsoleEvent:()=>{}};var S$=b$({tuiActive:()=>vv.tuiActive(),writeAuditEvent:(e,t)=>Ye(e,t),reportConsoleEvent:(e,t)=>vv.reportConsoleEvent(e,t),writeStderr:e=>{process.stderr.write(e)},nowMs:Date.now});function Gc(e){return S$.report(e)}function nd(e){return`<linzumi_context>
246
+ <linzumi_thread_id>${td(e.threadId)}</linzumi_thread_id>
247
+ <linzumi_creator_user_id>${td(e.creatorUserId)}</linzumi_creator_user_id>
248
+ <linzumi_creator_username>${td(e.creatorUsername)}</linzumi_creator_username>
249
+ <linzumi_conversation_url>${td(e.conversationUrl)}</linzumi_conversation_url>
18
250
  </linzumi_context>
19
251
 
20
252
  <linzumi_pr_footer_instruction>
21
253
  For any GitHub pull request you open from this session, include this Markdown footer link in the PR description: [Continue this on Linzumi](${e.conversationUrl})
22
- </linzumi_pr_footer_instruction>`}function pn(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var Ra=["deterministic","transient_upstream","transient_local","rate_limited","needs_approval","needs_decision","route_outage"],jl=new Set(Ra);var Ia={runner_updating:"transient_local",stillborn_worker:"transient_local",infra_turn_kill:"transient_local",resume_transient:"transient_local",start_stage_transient:"transient_local",resume_torn_tail:"transient_local",resurrection_interrupted:"transient_local",dead_letter_exhausted:"transient_local",dead_letter_withheld:"needs_decision",dead_letter_permanent:"deterministic",resume_cwd_not_allowed:"deterministic",cwd_stillbirth_circuit_open:"deterministic",engine_unavailable:"deterministic",provider_binding_rejected:"deterministic",project_untrusted:"deterministic",attachment_download_failed:"transient_local",claude_input_queue_closed:"transient_local",claude_dispatch_wedged:"transient_local"};var Dl=Object.keys(Ia);var Pa=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,zl=new RegExp(Pa.source,"g");var ep=1440*60*1e3;var tp=10*6e4;var Xp=10*6e4;var Zr=new Map([["function_call","function_call_output"],["custom_tool_call","custom_tool_call_output"]]),If=new Set([...Zr.keys(),...Zr.values()]);import{execFile as Ja}from"node:child_process";import{promisify as Ua}from"node:util";var Mf=Ua(Ja);var qf=200*1024*1024,Of=4320*60*1e3;var Ue=String.raw`\bgit\s+(?:-[Cc]\s+\S+\s+|-\S+\s+)*`,Ff=[new RegExp(`${Ue}restore\\b`),new RegExp(`${Ue}checkout\\b[^\\n;|&]*(\\s--(\\s|$)|\\s-f\\b|\\s\\.(\\s|$))`),new RegExp(`${Ue}reset\\b[^\\n;|&]*--(hard|merge|keep)\\b`),new RegExp(`${Ue}clean\\b`),new RegExp(`${Ue}stash\\s+(drop|clear|pop)\\b`),/\brm\s+(-[A-Za-z]*f[A-Za-z]*)\b/];var Yr=76800;function Xr(e){return Math.ceil(e.length/4)}function tt(e){if(!C(e))return;let n=E(e.ir_version),t=j(e.nodes);if(!(n===void 0||t===void 0))return{irVersion:n,threadTitle:l(e.thread_title),nodes:t.flatMap(Ka),hasMore:e.has_more===!0,cursor:E(e.cursor),budget:za(e.budget)}}function Ka(e){if(!C(e))return[];let n=l(e.kind),t=E(e.seq),r=l(e.body)??"";return n===void 0||t===void 0?[]:[{kind:n,seq:t,at:l(e.at),engine:l(e.engine)??"none",body:r,structured:_(e.structured),actor:_(e.actor),attachments:j(e.attachments)??[],sourceSeq:E(e.source_seq),streamKey:l(e.stream_key)}]}function za(e){if(!C(e))return;let n=E(e.context_window),t=E(e.max_emission_tokens);if(!(n===void 0||t===void 0||t<=0))return{model:l(e.model),contextWindow:n,maxEmissionTokens:t}}function Ba(e,n){let t=n>0?n:Yr,r=e.filter(a=>a.kind!=="reasoning"),o=e.length-r.length,i=[],s=0;for(let a=r.length-1;a>=0;a-=1){let d=r[a];if(d===void 0)continue;let u=Xr(eo(d,t));if(i.length>0&&s+u>t)break;s+=u,i.unshift(d)}return{tail:i,omittedNodeCount:r.length-i.length,redactedReasoningCount:o,artifacts:Ga(e)}}function Ga(e){let n=new Set,t=new Set,r=0;for(let o of e){if(o.kind==="error"&&(r+=1),o.kind==="file_change")for(let i of Wa(o.structured))n.add(i);if(o.kind==="command_execution"){let i=l(o.structured?.command)?.trim();i!==void 0&&i!==""&&t.add(i.split(`
23
- `,1)[0]??i)}}return{filesTouched:[...n].slice(0,100),commandsRun:[...t].slice(0,100),errorCount:r}}function Wa(e){if(e===void 0)return[];let n=l(e.path),r=(j(e.paths)??j(e.files)??[]).flatMap(o=>{let i=l(o);if(i!==void 0)return[i];let s=C(o)?l(o.path):void 0;return s===void 0?[]:[s]});return n===void 0?r:[n,...r]}function rt(e){let n=e.budget?.maxEmissionTokens??Yr,t=Ba(e.nodes,n),r=Xa({resumeFailure:e.resumeFailure,threadTitle:e.threadTitle,linzumiContext:e.linzumiContext,budgeted:t,transcriptEmpty:t.tail.length===0}),o=[W(r,"commentary")],i=0;for(let a of t.tail)i+=1,o.push(...Ha(a,n,i));let s=o.reduce((a,d)=>a+Xr(JSON.stringify(d)),0);return{items:o,emittedNodeCount:t.tail.length,omittedNodeCount:t.omittedNodeCount,redactedReasoningCount:t.redactedReasoningCount,emittedTokenEstimate:s,maxEmissionTokens:n}}function Ha(e,n,t){let r=eo(e,n);switch(e.kind){case"user_message":return[{type:"message",role:"user",content:[{type:"input_text",text:Ya(e,r)}]}];case"assistant_message":return[W(r,Za(e))];case"command_execution":return Va(e,r,t);case"tool_call":return Qa(e,r,t);case"reasoning":return[];case"file_change":return[W(`[file change]
24
- ${r}`,"commentary")];case"terminal_input":return[W(`[terminal input]
25
- ${r}`,"commentary")];case"tool_result":return[W(`[tool result]
26
- ${r}`,"commentary")];case"approval_request":return[W(`[approval] ${r}`,"commentary")];case"agent_status":return[W(`[status] ${r}`,"commentary")];case"system_notice":return[W(`[notice] ${r}`,"commentary")];case"error":return[W(`[error] ${r}`,"commentary")];default:return[W(`[${e.kind}] ${r}`,"commentary")]}}function Va(e,n,t){let r=no(e,t),o=l(e.structured?.command),i=l(e.structured?.cwd),s=E(e.structured?.exit_code),a=l(e.structured?.output)??n;return[{type:"function_call",name:"shell",call_id:r,arguments:JSON.stringify({command:o??nd(n),...i===void 0||i===""?{}:{cwd:i}})},{type:"function_call_output",call_id:r,output:s===void 0?a:`exit_code=${s}
27
- ${a}`}]}function Qa(e,n,t){let r=no(e,t);return[{type:"function_call",name:ed(l(e.structured?.title)??"linzumi_replayed_tool"),call_id:r,arguments:JSON.stringify({replayed:!0})},{type:"function_call_output",call_id:r,output:n===""?"[result not recorded]":n}]}function W(e,n){return{type:"message",role:"assistant",content:[{type:"output_text",text:e}],phase:n}}function Za(e){return l(e.structured?.phase)==="commentary"?"commentary":"final_answer"}function Ya(e,n){return e.attachments.length===0?n:`${n}
28
- [${e.attachments.length} attachment(s) in the original message]`}function eo(e,n){let t=Math.max(1e3,n*4),r=e.body;return r.length<=t?r:`[...truncated...]
29
- ${r.slice(r.length-t)}`}function Xa(e){let n=e.resumeFailure.trim(),{artifacts:t}=e.budgeted,r=["Rebuilt Linzumi coding session","","This session was rebuilt after an interrupted durable engine session: the previous engine session for this Linzumi thread could not be resumed"+(n===""?".":` (${td(n,400)}).`),e.transcriptEmpty?"The durable server-side transcript could not be fetched or is empty - ask the user for any missing context instead of guessing.":"You are continuing the SAME task in the SAME Linzumi thread. The transcript below is replayed from the durable server-side record. Re-derive any local state (files, branches, running processes) from the workspace itself; do not assume in-memory state survived.",...e.threadTitle===void 0||e.threadTitle.trim()===""?[]:["",`Thread: ${e.threadTitle.trim()}`],...e.linzumiContext===void 0?[]:["",fn(e.linzumiContext)]],o=[...e.budgeted.omittedNodeCount>0?[`${e.budgeted.omittedNodeCount} older transcript entries were omitted to fit the emission budget.`]:[],...e.budgeted.redactedReasoningCount>0?[`${e.budgeted.redactedReasoningCount} reasoning entries were redacted (provider-private; never replayed).`]:[],...t.filesTouched.length>0?[`Files touched: ${t.filesTouched.join(", ")}`]:[],...t.commandsRun.length>0?[`Commands run: ${t.commandsRun.join("; ")}`]:[],...t.errorCount>0?[`${t.errorCount} error entries in the full history.`]:[]];return[...r,...o.length===0?[]:["",...o]].join(`
30
- `)}function no(e,n){return`linzumi_replay_${e.seq}_${n}`}function ed(e){let n=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64);return n===""?"linzumi_replayed_tool":n}function nd(e){return e.split(`
31
- `,1)[0]??e}function td(e,n){return e.length<=n?e:`[...truncated...]${e.slice(e.length-n)}`}var mn={default:{maxLadderMs:9e5},wafer:{maxLadderMs:36e5}};var rm={maxRecoveryRungs:4,maxLadderMs:mn.default.maxLadderMs,maxRateLimitHoldMs:30*6e4},om={default:mn.default,wafer:mn.wafer};var dm=10*6e4;var sd=[{appName:"Bun",iconKey:"bun",names:["bun","bunx"]},{appName:"Node.js",iconKey:"nodejs",names:["node","nodejs","node.exe"]},{appName:"npm",iconKey:"npm",names:["npm","npm-cli.js","npx"]},{appName:"pnpm",iconKey:"pnpm",names:["pnpm","pnpx"]},{appName:"Yarn",iconKey:"yarn",names:["yarn","yarnpkg","yarn.js"]},{appName:"Corepack",iconKey:"corepack",names:["corepack"]},{appName:"Deno",iconKey:"deno",names:["deno"]},{appName:"Vite",iconKey:"vite",names:["vite","vite-node"]},{appName:"Vitest",iconKey:"vitest",names:["vitest"]},{appName:"Next.js",iconKey:"nextjs",names:["next","next-server"]},{appName:"Nuxt",iconKey:"nuxt",names:["nuxt","nuxi"]},{appName:"Astro",iconKey:"astro",names:["astro"]},{appName:"SvelteKit",iconKey:"svelte",names:["svelte-kit","sveltekit"]},{appName:"Remix",iconKey:"remix",names:["remix"]},{appName:"Expo",iconKey:"expo",names:["expo","expo-cli"]},{appName:"React Native",iconKey:"react",names:["react-native"]},{appName:"Metro",iconKey:"metro",names:["metro","metro-inspector-proxy"]},{appName:"Webpack",iconKey:"webpack",names:["webpack","webpack-dev-server","webpack-cli"]},{appName:"Parcel",iconKey:"parcel",names:["parcel"]},{appName:"Rollup",iconKey:"rollup",names:["rollup"]},{appName:"esbuild",iconKey:"esbuild",names:["esbuild"]},{appName:"SWC",iconKey:"swc",names:["swc"]},{appName:"TypeScript",iconKey:"typescript",names:["tsc","tsserver","tsx","ts-node","typescript-language-server"]},{appName:"ESLint",iconKey:"eslint",names:["eslint","eslint_d"]},{appName:"Prettier",iconKey:"prettier",names:["prettier"]},{appName:"Biome",iconKey:"biome",names:["biome"]},{appName:"Storybook",iconKey:"storybook",names:["storybook","start-storybook"]},{appName:"Playwright",iconKey:"playwright",names:["playwright"]},{appName:"Cypress",iconKey:"cypress",names:["cypress"]},{appName:"Jest",iconKey:"jest",names:["jest"]},{appName:"Python",iconKey:"python",names:["python","python2","python3","python3.9","python3.10","python3.11","python3.12","python3.13","pypy","pypy3"]},{appName:"pip",iconKey:"python",names:["pip","pip2","pip3"]},{appName:"pipx",iconKey:"python",names:["pipx"]},{appName:"uv",iconKey:"python",names:["uv","uvx"]},{appName:"Poetry",iconKey:"poetry",names:["poetry"]},{appName:"Pipenv",iconKey:"python",names:["pipenv"]},{appName:"Conda",iconKey:"conda",names:["conda","mamba","micromamba"]},{appName:"Django",iconKey:"django",names:["django-admin","django-admin.py","manage.py"]},{appName:"Flask",iconKey:"flask",names:["flask"]},{appName:"Uvicorn",iconKey:"uvicorn",names:["uvicorn"]},{appName:"Gunicorn",iconKey:"gunicorn",names:["gunicorn"]},{appName:"Hypercorn",iconKey:"python",names:["hypercorn"]},{appName:"Celery",iconKey:"celery",names:["celery"]},{appName:"Jupyter",iconKey:"jupyter",names:["jupyter","jupyter-lab","jupyter-notebook","ipython"]},{appName:"Ruby",iconKey:"ruby",names:["ruby","erb","irb"]},{appName:"Bundler",iconKey:"ruby",names:["bundle","bundler"]},{appName:"Rails",iconKey:"rails",names:["rails","bin/rails"]},{appName:"Rack",iconKey:"ruby",names:["rackup"]},{appName:"Puma",iconKey:"puma",names:["puma"]},{appName:"Sidekiq",iconKey:"sidekiq",names:["sidekiq"]},{appName:"RSpec",iconKey:"ruby",names:["rspec"]},{appName:"Go",iconKey:"go",names:["go","gofmt","gopls","air"]},{appName:"Delve",iconKey:"go",names:["dlv"]},{appName:"Rust",iconKey:"rust",names:["rustc","rustup","cargo","rust-analyzer"]},{appName:"Java",iconKey:"java",names:["java","javac","jar","jshell","jwebserver"]},{appName:"Gradle",iconKey:"gradle",names:["gradle","gradlew"]},{appName:"Maven",iconKey:"maven",names:["mvn","mvnw"]},{appName:"Spring Boot",iconKey:"spring",names:["spring","spring-boot"]},{appName:"Kotlin",iconKey:"kotlin",names:["kotlin","kotlinc","kotlin-language-server"]},{appName:"Scala",iconKey:"scala",names:["scala","scalac","sbt","metals"]},{appName:"Clojure",iconKey:"clojure",names:["clojure","clj","lein","boot"]},{appName:"PHP",iconKey:"php",names:["php","php-fpm","php-cgi","composer"]},{appName:"Laravel",iconKey:"laravel",names:["artisan","laravel"]},{appName:"Symfony",iconKey:"symfony",names:["symfony"]},{appName:"Elixir",iconKey:"elixir",names:["elixir","iex","mix"]},{appName:"Erlang",iconKey:"erlang",names:["erl","beam.smp","beam","epmd","rebar3"]},{appName:"Phoenix",iconKey:"phoenix",names:["phx.server","phoenix"]},{appName:"PostgreSQL",iconKey:"postgresql",names:["postgres","postmaster","pg_ctl","psql","pg_isready"]},{appName:"Redis",iconKey:"redis",names:["redis-server","redis-cli","redis-sentinel"]},{appName:"MySQL",iconKey:"mysql",names:["mysql","mysqld","mysqladmin"]},{appName:"MariaDB",iconKey:"mariadb",names:["mariadb","mariadbd","mariadb-admin"]},{appName:"SQLite",iconKey:"sqlite",names:["sqlite3","sqlite"]},{appName:"MongoDB",iconKey:"mongodb",names:["mongod","mongosh","mongo"]},{appName:"Elasticsearch",iconKey:"elasticsearch",names:["elasticsearch"]},{appName:"OpenSearch",iconKey:"opensearch",names:["opensearch"]},{appName:"Solr",iconKey:"solr",names:["solr"]},{appName:"Kafka",iconKey:"kafka",names:["kafka-server-start","kafka-console-consumer","kafka-console-producer"]},{appName:"ZooKeeper",iconKey:"zookeeper",names:["zookeeper-server-start","zkserver"]},{appName:"RabbitMQ",iconKey:"rabbitmq",names:["rabbitmq-server","rabbitmqctl"]},{appName:"NATS",iconKey:"nats",names:["nats-server","nats"]},{appName:"Docker",iconKey:"docker",names:["docker","dockerd","docker-compose","docker-proxy","com.docker.backend"]},{appName:"Podman",iconKey:"podman",names:["podman","podman-compose"]},{appName:"Kubernetes",iconKey:"kubernetes",names:["kubectl","kube-apiserver","kubelet","minikube","kind"]},{appName:"Helm",iconKey:"helm",names:["helm"]},{appName:"Tilt",iconKey:"tilt",names:["tilt"]},{appName:"nginx",iconKey:"nginx",names:["nginx"]},{appName:"Caddy",iconKey:"caddy",names:["caddy"]},{appName:"Apache HTTP Server",iconKey:"apache",names:["httpd","apache2","apachectl"]},{appName:"HAProxy",iconKey:"haproxy",names:["haproxy"]},{appName:"Traefik",iconKey:"traefik",names:["traefik"]},{appName:"Envoy",iconKey:"envoy",names:["envoy"]},{appName:"Tailscale",iconKey:"tailscale",names:["tailscale","tailscaled"]},{appName:"Cloudflare Tunnel",iconKey:"cloudflare",names:["cloudflared"]},{appName:"ngrok",iconKey:"ngrok",names:["ngrok"]},{appName:"localtunnel",iconKey:"terminal",names:["lt","localtunnel"]},{appName:"SSH",iconKey:"ssh",names:["ssh","sshd","scp","sftp"]},{appName:"Git",iconKey:"git",names:["git","git-lfs","git-upload-pack","git-receive-pack"]},{appName:"GitHub CLI",iconKey:"github",names:["gh"]},{appName:"GitLab CLI",iconKey:"gitlab",names:["glab"]},{appName:"Subversion",iconKey:"subversion",names:["svn"]},{appName:"Mercurial",iconKey:"mercurial",names:["hg"]},{appName:"AWS CLI",iconKey:"aws",names:["aws","aws-vault","sam"]},{appName:"Azure CLI",iconKey:"azure",names:["az"]},{appName:"Google Cloud CLI",iconKey:"google-cloud",names:["gcloud","gsutil","bq"]},{appName:"Terraform",iconKey:"terraform",names:["terraform"]},{appName:"OpenTofu",iconKey:"opentofu",names:["tofu"]},{appName:"Ansible",iconKey:"ansible",names:["ansible","ansible-playbook"]},{appName:"Pulumi",iconKey:"pulumi",names:["pulumi"]},{appName:"Nomad",iconKey:"nomad",names:["nomad"]},{appName:"Vault",iconKey:"vault",names:["vault"]},{appName:"Consul",iconKey:"consul",names:["consul"]},{appName:"Make",iconKey:"make",names:["make","gmake"]},{appName:"CMake",iconKey:"cmake",names:["cmake","ctest","cpack"]},{appName:"Ninja",iconKey:"ninja",names:["ninja"]},{appName:"Bazel",iconKey:"bazel",names:["bazel","bazelisk"]},{appName:"Buck",iconKey:"buck",names:["buck","buck2"]},{appName:"Clang",iconKey:"clang",names:["clang","clang++","clangd"]},{appName:"GCC",iconKey:"gcc",names:["gcc","g++","cc","c++"]},{appName:"LLDB",iconKey:"terminal",names:["lldb"]},{appName:"GDB",iconKey:"terminal",names:["gdb"]},{appName:"Swift",iconKey:"swift",names:["swift","swiftc","sourcekit-lsp"]},{appName:"Xcode",iconKey:"xcode",names:["xcodebuild","xcrun","simctl"]},{appName:"Zig",iconKey:"zig",names:["zig"]},{appName:"Lua",iconKey:"lua",names:["lua","luajit","lua-language-server"]},{appName:"Perl",iconKey:"perl",names:["perl"]},{appName:"R",iconKey:"r",names:["r","rscript","rserver","rsession"]},{appName:"Julia",iconKey:"julia",names:["julia"]},{appName:"Haskell",iconKey:"haskell",names:["ghc","ghci","cabal","stack","haskell-language-server-wrapper"]},{appName:"OCaml",iconKey:"ocaml",names:["ocaml","ocamlc","dune","opam"]},{appName:"F#",iconKey:"fsharp",names:["fsharpi","fsautocomplete"]},{appName:".NET",iconKey:"dotnet",names:["dotnet","csharp-ls","omnisharp"]},{appName:"PowerShell",iconKey:"powershell",names:["pwsh","powershell"]},{appName:"Bash",iconKey:"terminal",names:["bash"]},{appName:"Zsh",iconKey:"terminal",names:["zsh"]},{appName:"fish",iconKey:"terminal",names:["fish"]},{appName:"tmux",iconKey:"terminal",names:["tmux"]},{appName:"GNU Screen",iconKey:"terminal",names:["screen"]},{appName:"direnv",iconKey:"terminal",names:["direnv"]},{appName:"Nix",iconKey:"nix",names:["nix","nix-shell","nix-daemon","nix-build","nix develop"]},{appName:"Homebrew",iconKey:"homebrew",names:["brew"]},{appName:"mise",iconKey:"terminal",names:["mise"]},{appName:"asdf",iconKey:"terminal",names:["asdf"]},{appName:"Volta",iconKey:"volta",names:["volta"]},{appName:"fnm",iconKey:"nodejs",names:["fnm"]},{appName:"nvm",iconKey:"nodejs",names:["nvm"]},{appName:"curl",iconKey:"terminal",names:["curl"]},{appName:"HTTPie",iconKey:"httpie",names:["http","https","httpie"]},{appName:"wget",iconKey:"terminal",names:["wget"]},{appName:"jq",iconKey:"terminal",names:["jq"]},{appName:"ripgrep",iconKey:"terminal",names:["rg","ripgrep"]},{appName:"fd",iconKey:"terminal",names:["fd"]},{appName:"fzf",iconKey:"terminal",names:["fzf"]},{appName:"bat",iconKey:"terminal",names:["bat"]},{appName:"eza",iconKey:"terminal",names:["eza","exa"]},{appName:"htop",iconKey:"terminal",names:["htop","top","btop"]},{appName:"Vim",iconKey:"vim",names:["vim","view","vimdiff"]},{appName:"Neovim",iconKey:"neovim",names:["nvim","nvim-qt"]},{appName:"Emacs",iconKey:"emacs",names:["emacs","emacsclient"]},{appName:"Visual Studio Code",iconKey:"vscode",names:["code","code-insiders","vscode","visual studio code","visual studio code - insiders"]},{appName:"code-server",iconKey:"vscode",names:["code-server"]},{appName:"Cursor",iconKey:"cursor",names:["cursor"]},{appName:"Zed",iconKey:"zed",names:["zed"]},{appName:"Sublime Text",iconKey:"sublime-text",names:["subl","sublime_text","sublime text"]},{appName:"Atom",iconKey:"atom",names:["atom"]},{appName:"IntelliJ IDEA",iconKey:"intellij-idea",names:["idea","idea.sh","intellij idea","idea64.exe"]},{appName:"WebStorm",iconKey:"webstorm",names:["webstorm","webstorm.sh"]},{appName:"PyCharm",iconKey:"pycharm",names:["pycharm","pycharm.sh"]},{appName:"RubyMine",iconKey:"rubymine",names:["rubymine","rubymine.sh"]},{appName:"GoLand",iconKey:"goland",names:["goland","goland.sh"]},{appName:"CLion",iconKey:"clion",names:["clion","clion.sh"]},{appName:"DataGrip",iconKey:"datagrip",names:["datagrip","datagrip.sh"]},{appName:"Rider",iconKey:"rider",names:["rider","rider.sh"]},{appName:"Android Studio",iconKey:"android-studio",names:["studio","studio.sh","android studio"]},{appName:"Xcode",iconKey:"xcode",names:["xcode","xcode.app"]},{appName:"Postman",iconKey:"postman",names:["postman"]},{appName:"Insomnia",iconKey:"insomnia",names:["insomnia"]},{appName:"Hoppscotch",iconKey:"hoppscotch",names:["hoppscotch"]},{appName:"TablePlus",iconKey:"tableplus",names:["tableplus"]},{appName:"DBeaver",iconKey:"dbeaver",names:["dbeaver"]},{appName:"RedisInsight",iconKey:"redis",names:["redisinsight"]},{appName:"Prisma",iconKey:"prisma",names:["prisma"]},{appName:"Drizzle Kit",iconKey:"drizzle",names:["drizzle-kit"]},{appName:"Supabase",iconKey:"supabase",names:["supabase"]},{appName:"Firebase",iconKey:"firebase",names:["firebase"]},{appName:"Vercel",iconKey:"vercel",names:["vercel"]},{appName:"Netlify",iconKey:"netlify",names:["netlify","ntl"]},{appName:"Fly.io",iconKey:"fly",names:["fly","flyctl"]},{appName:"Heroku",iconKey:"heroku",names:["heroku"]},{appName:"Stripe CLI",iconKey:"stripe",names:["stripe"]},{appName:"Twilio CLI",iconKey:"twilio",names:["twilio"]},{appName:"Mailpit",iconKey:"mail",names:["mailpit"]},{appName:"MailHog",iconKey:"mail",names:["mailhog"]},{appName:"OpenSSL",iconKey:"openssl",names:["openssl"]},{appName:"mkcert",iconKey:"certificate",names:["mkcert"]},{appName:"mkdocs",iconKey:"markdown",names:["mkdocs"]},{appName:"Hugo",iconKey:"hugo",names:["hugo"]},{appName:"Jekyll",iconKey:"jekyll",names:["jekyll"]},{appName:"Eleventy",iconKey:"eleventy",names:["eleventy","11ty"]},{appName:"Docusaurus",iconKey:"docusaurus",names:["docusaurus"]},{appName:"Trunk",iconKey:"rust",names:["trunk"]},{appName:"wasm-pack",iconKey:"webassembly",names:["wasm-pack"]},{appName:"wasmtime",iconKey:"webassembly",names:["wasmtime"]},{appName:"Language Server",iconKey:"language-server",names:["lua-language-server","yaml-language-server","vscode-json-language-server","docker-langserver","bash-language-server","marksman","taplo"]}],to=new Map;for(let e of sd)for(let n of e.names)to.set(dd(n),{appName:e.appName,iconKey:e.iconKey});var xm=to.size;function ad(e){let n=e.toLowerCase();switch(!0){case n.endsWith(".app"):return e.slice(0,-4);case n.endsWith(".exe"):return e.slice(0,-4);case n.endsWith(".cmd"):case n.endsWith(".bat"):return e.slice(0,-4);default:return e}}function dd(e){return ad(e.trim().replaceAll("\\","/").toLowerCase())}var ro=12e4;function ud(){let e=process.env.LINZUMI_CODEX_START_REQUEST_TIMEOUT_MS?.trim();if(e===void 0||e==="")return ro;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>0?n:ro}var ot=class extends Error{constructor(n,t){super(`Codex ${n} did not reply within ${t}ms (start request timed out)`),this.name="CodexStartRequestTimeoutError"}};function cd(e,n,t=ud()){return ld(e,n,t,(r,o)=>new ot(r,o))}function ld(e,n,t,r){return t>0?new Promise((o,i)=>{let s=setTimeout(()=>{i(r(e,t))},t);s.unref?.(),n.then(a=>{clearTimeout(s),o(a)},a=>{clearTimeout(s),i(a)})}):n}function Ke(e,n,t){return cd(n,e.request(n,t))}var pd=e=>/\bsession\b.+\bis archived\b/i.test(e),fd=e=>/^thread not found(?:\s*:|\b)/i.test(e.trim()),md=e=>/\bno rollout found\b/i.test(e)||/\bsession not found\b[\s\S]*\brollout\b/i.test(e);async function oo(e,n,t,r,o,i){i("kandan.reconnect_thread_unarchive_started",{codex_thread_id:n,discovered_by:r,message:o});try{let s=await Ke(e,"thread/unarchive",{threadId:n});if("error"in s)throw new Error(`thread/unarchive failed: ${s.error.message}`);let a=await Ke(e,"thread/resume",t);if("error"in a)throw new Error(`thread/resume after unarchive failed: ${a.error.message}`);return i("kandan.reconnect_thread_unarchive_resumed",{codex_thread_id:n,discovered_by:r}),{mode:"resumed"}}catch(s){let a=s instanceof Error?s.message:String(s);throw i("kandan.reconnect_thread_unarchive_failed",{codex_thread_id:n,discovered_by:r,archive_error:o,message:a}),new Error(r==="forced_inject_not_found"?`thread/inject_items failed: ${o}; archive recovery failed: ${a}`:a)}}async function io(e){let{codex:n,codexThreadId:t,rehydration:r}=e,o={threadId:t,...e.resumeOverrides},i;if(r.forceRehydrate===!0)i="the server marked the durable engine session dead after an acknowledged-but-unexecuted turn";else{let a=await Ke(n,"thread/resume",o);if(!("error"in a))return{mode:"resumed"};if(pd(a.error.message))return await oo(n,t,o,"resume_archived",a.error.message,r.log);if(e.rebuildWhen==="missing-rollout-only"&&!md(a.error.message))throw r.log("linzumi.agent_thread_resume_failed_unrecoverable",{codex_thread_id:t,message:a.error.message,rehydrating:!1}),new Error(a.error.message);i=a.error.message}r.log(r.forceRehydrate===!0?"kandan.reconnect_thread_rehydrate_forced":"kandan.reconnect_thread_resume_failed",{codex_thread_id:t,message:i,forced:r.forceRehydrate===!0,rehydrating:!0});let s;try{let a;try{a=await r.buildRehydrationItems?.(i)}catch(c){r.log("kandan.reconnect_thread_rehydration_items_failed",{codex_thread_id:t,message:c instanceof Error?c.message:String(c)}),a=void 0}let d=a!==void 0&&a.length>0?[...a]:[{type:"agentMessage",text:await r.buildRehydrationText(i)}],u=await Ke(n,"thread/inject_items",{threadId:t,items:d});if("error"in u){if(r.forceRehydrate===!0&&fd(u.error.message))return await oo(n,t,o,"forced_inject_not_found",u.error.message,r.log);s=`thread/inject_items failed: ${u.error.message}`}else{let c=await Ke(n,"thread/resume",o);"error"in c&&(s=`rehydrated thread/resume failed: ${c.error.message}`)}}catch(a){s=a instanceof Error?a.message:String(a)}if(s!==void 0)throw r.log("kandan.reconnect_thread_rehydration_failed",{codex_thread_id:t,resume_failure:i,rehydration_failure:s}),new Error(`could not resume this thread's engine session (${i}) and rebuilding a fresh session from the thread transcript also failed (${s})`);return r.log("kandan.reconnect_thread_rehydrated",{codex_thread_id:t,resume_failure:i}),{mode:"rehydrated",resumeFailure:i}}var it={mcpAuthFileContents:"LINZUMI_CLOUD_MCP_AUTH_JSON",llmProxyToken:"LINZUMI_CLOUD_LLM_PROXY_TOKEN"};function so(e){let n;try{n=JSON.parse(Buffer.from(e,"base64").toString("utf8"))}catch{throw new Error("invalid guest cloud turn config payload (not base64 JSON)")}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("invalid guest cloud turn config payload");let t=n;for(let[r,o]of[["codexVersion",t.codexVersion],["sandbox",t.sandbox],["approvalPolicy",t.approvalPolicy],["kandanUrl",t.kandanUrl],["cwd",t.cwd]])if(typeof o!="string"||o==="")throw new Error(`invalid guest cloud turn config payload (${r} missing)`);if(!Array.isArray(t.input))throw new Error("invalid guest cloud turn config payload (input)");if(typeof t.appServerPort!="number"||!Number.isInteger(t.appServerPort))throw new Error("invalid guest cloud turn config payload (appServerPort)");return t}var ce="/home/agent",hd=`${ce}/.linzumi-provisioned`;var st="/dev/shm/linzumi",Ay=`${st}/codex`,My=`${st}/mcp-auth.json`;var qy=`${st}/codex.env`;var Dy=`${ce}/cloud-supervisor.mjs`,ao=`${ce}/mcp-server.mjs`,at=`${ce}/.secrets`,dt=`${at}/mcp-auth.json`,hn=`${ce}/.codex`,uo=`${hn}/linzumi-thread-map.json`;var ut=`${ce}/.turn-heartbeats`,co=5e3,gd=/^[A-Za-z0-9-]{8,64}$/;function ct(e){if(!gd.test(e))throw new Error(`invalid cloud turn nonce: ${JSON.stringify(e.slice(0,80))}`)}var kd=3e4,Td=200,Cd=18e4,lo="LINZUMI_GUEST_MODEL_CALL_LIVENESS_MS",Rd=15*6e4,po="LINZUMI_GUEST_ACTIVE_LOOP_BUDGET_MS",_n=2147483647;function Id(e){let n=e[po];if(n===void 0)return Rd;let t=Number(n);if(n.trim()===""||!Number.isSafeInteger(t)||t<=0||t>_n)throw new Error(`${po} must be an integer number of milliseconds between 1 and ${_n}, got ${JSON.stringify(n)}`);return t}var ft=class extends Error{code="active_loop_budget_exceeded";budgetMs;constructor(n){super(`active_loop_budget_exceeded: guest turn exceeded the ${n}ms wall-clock budget; killed the guest turn`),this.name="GuestActiveLoopBudgetExceeded",this.budgetMs=n}};function Pd(e){let n=e[lo];if(n===void 0)return Cd;let t=Number(n);if(n.trim()===""||!Number.isSafeInteger(t)||t<=0)throw new Error(`${lo} must be a positive integer number of milliseconds, got ${JSON.stringify(n)}`);return t}var mt=class extends Error{code="guest_turn_liveness_failure";windowMs;constructor(n){super(`guest_turn_liveness_failure: zero upstream model calls for ${n}ms; killed the guest turn`),this.name="GuestTurnLivenessFailure",this.windowMs=n}};function Ed(e,n,t){if(e.method!=="thread/tokenUsage/updated")return;let r=_(e.params)??{};if(l(r.threadId)!==n||l(r.turnId)!==t)return;let o=E(_(_(r.tokenUsage)?.total)?.totalTokens),i=E(_(_(r.tokenUsage)?.last)?.totalTokens);if(!(o===void 0||o<0))return{totalTokens:o,priorCallTotalTokens:i!==void 0&&i>=0&&i<=o?o-i:void 0}}function le(e){return e.replace(/\bsmk_[A-Za-z0-9._-]+/g,"smk_[REDACTED]").replace(/\b(sk|lz|tok|bearer)[-_][A-Za-z0-9._-]{8,}/gi,"$1_[REDACTED]")}var lt=64*1024;function Ad(e,n){let t=n.now??Date.now,r=Buffer.alloc(0),o=null,i=null,s=a=>{let d=Buffer.isBuffer(a)?a:Buffer.from(a,"utf8");r=Buffer.concat([r,d]);let u=lt*2;r.byteLength>u&&(r=r.subarray(r.byteLength-u))};return e.stdout?.on("data",s),e.stderr?.on("data",s),e.once("exit",(a,d)=>{o=a,i=d??null}),{evidence:a=>{let d=Buffer.from(le(r.toString("utf8")),"utf8"),u=d.byteLength<=lt?d:d.subarray(d.byteLength-lt);return{marker:"guest_turn_failure_evidence",empty_output:r.byteLength===0,output_tail:u.toString("utf8"),exit_code:o,signal:i,duration_ms:Math.max(0,t()-n.startedAtMs),model_call_count:a}}}}var Sn;function Md(e){Sn=e;try{ke(ho(e),{recursive:!0}),Be(e,"")}catch{Sn=void 0}}function D(e){let n=`${JSON.stringify(e)}
32
- `;if(process.stdout.write(n),Sn!==void 0)try{bd(Sn,n)}catch{}}function gn(e,n,t,r){D({phase:"exit",ok:e,reason:le(n),turnMs:t,...r===void 0?{}:{evidence:r}})}function qd(e){return{id:e.id,name:e.name,baseUrl:e.baseUrl,envKey:e.envKey,wireApi:e.wireApi,...e.httpHeaders===void 0?{}:{httpHeaders:{...e.httpHeaders}},...e.envHttpHeaders===void 0?{}:{envHttpHeaders:{...e.envHttpHeaders}}}}function Od(e){if(e.sandbox!=="read-only")throw new Error(`guest cloud turn requires sandbox "read-only", got ${JSON.stringify(e.sandbox)}`);if(e.approvalPolicy!=="never")throw new Error(`guest cloud turn requires approvalPolicy "never", got ${JSON.stringify(e.approvalPolicy)}`)}function Fd(e,n=hn){let t=Nr({command:"node",argsPrefix:[ao],kandanUrl:e.kandanUrl,authFilePath:dt,ownerUsername:e.ownerUsername,operatingMode:"text",cwd:e.cwd,threadId:e.threadId,agentSession:!0});return zr(`ws://127.0.0.1:${e.appServerPort}`,{model:e.model,reasoningEffort:e.reasoningEffort,mcpServers:[t],neverEquivalentGranularApprovalPolicy:!0,...e.modelProvider===void 0?{}:{modelProvider:qd(e.modelProvider)},env:{CODEX_HOME:n,...go(e)}})}function go(e){let n=process.env[it.llmProxyToken];return e.modelProvider===void 0||n===void 0||n===""?{}:{[e.modelProvider.envKey]:n}}function Ld(e,n){let t=process.env[it.mcpAuthFileContents];if(t===void 0||t==="")throw new Error("guest cloud turn missing MCP auth-cache (LINZUMI_CLOUD_MCP_AUTH_JSON)");ke(e,{recursive:!0,mode:448}),ze(e,448),Be(n,t,{mode:384}),ze(n,384)}function jd(e){try{we(e,{recursive:!0,force:!0})}catch{}}var Dd=64,Nd=20,fo="My engine session for this thread was lost, so I rebuilt it from this thread's saved history at reduced fidelity. Tell me if I lost something important.";async function $d(e){if(e.config.threadId===void 0||e.config.threadId==="")throw new Error("guest thread rehydration requires the durable Linzumi thread id");let n=Je(e.config.kandanUrl,e.mcpAuthPath);if(n===void 0)throw new Error("guest thread rehydration requires an agent token in the MCP auth file");let t=$e({kandanUrl:e.config.kandanUrl,accessToken:n.accessToken,operatingMode:"text"}),r=[],o,i,s;for(let d=0;d<Nd;d+=1){let u=await t.getThreadTranscript({thread_id:e.config.threadId,...s===void 0?{}:{cursor:s}}),c=tt(u);if(c===void 0)throw new Error(`guest thread rehydration received a malformed durable transcript page ${d}`);if(r=[...c.nodes,...r],o=o??c.budget,i=i??c.threadTitle,!c.hasMore||c.cursor===void 0)break;s=c.cursor}if(r.length===0)throw new Error("guest thread rehydration durable transcript was empty");let a=rt({nodes:r,budget:o,resumeFailure:e.resumeFailure,threadTitle:i,linzumiContext:void 0});if(a.items.length===0)throw new Error("guest thread rehydration compiled zero injection items");return a.items}async function Jd(e){if(e.config.threadId===void 0||e.config.threadId==="")throw new Error("guest session rebuild notice requires a Linzumi thread id");let n=Je(e.config.kandanUrl,e.mcpAuthPath);if(n===void 0)throw new Error("guest session rebuild notice requires an agent token in the MCP auth file");await $e({kandanUrl:e.config.kandanUrl,accessToken:n.accessToken,operatingMode:"voice"}).sendThreadReply({thread_id:e.config.threadId,body:fo,client_message_id:e.notice.noticeId,payload:{structured:{kind:"agent_status_event",item_id:e.notice.noticeId,transcript_unit_id:`agent_status_event:${e.notice.noticeId}`,stream_state:"completed",event_kind:"status",title:"Rebuilt the agent session",body:fo,severity:"info",agent_provider:"codex",raw_provider_metadata:{provider_session_key:e.notice.threadId,resume_failure:e.notice.resumeFailure}}}})}function yo(e){try{let n=JSON.parse(yn(e,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))return{};let t={};for(let[r,o]of Object.entries(n))typeof o=="string"&&o!==""&&(t[r]=o);return t}catch{return{}}}function Ud(e,n,t){try{let r=yo(e);delete r[n];let o=Object.entries(r),i=o.slice(Math.max(0,o.length-(Dd-1)));i.push([n,t]),ke(ho(e),{recursive:!0}),Be(e,JSON.stringify(Object.fromEntries(i)))}catch{}}var Kd=new Set(["turn/completed","turn/failed","turn/aborted"]),zd=2e3;function _o(e){let n=_(_(e)?.item);if(n===void 0||l(n.type)!=="agentMessage")return"";let t=l(n.text);return t!==void 0&&t!==""?t:(j(n.content)??[]).map(i=>{let s=_(i);if(s===void 0)return;let a=l(s.type);if(!(a!=="text"&&a!=="output_text"&&a!=="input_text"))return l(s.text)??l(s.content)}).filter(i=>i!==void 0&&i!=="").join(`
254
+ </linzumi_pr_footer_instruction>`}function td(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}var k$=["deterministic","transient_upstream","transient_local","rate_limited","needs_approval","needs_decision","route_outage"],JX=new Set(k$);var x$={runner_updating:"transient_local",stillborn_worker:"transient_local",infra_turn_kill:"transient_local",resume_transient:"transient_local",start_stage_transient:"transient_local",resume_torn_tail:"transient_local",resurrection_interrupted:"transient_local",dead_letter_exhausted:"transient_local",dead_letter_withheld:"needs_decision",dead_letter_permanent:"deterministic",resume_cwd_not_allowed:"deterministic",cwd_stillbirth_circuit_open:"deterministic",engine_unavailable:"deterministic",provider_binding_rejected:"deterministic",project_untrusted:"deterministic",attachment_download_failed:"transient_local",claude_input_queue_closed:"transient_local",claude_dispatch_wedged:"transient_local"};var WX=Object.keys(x$);var C$=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,YX=new RegExp(C$.source,"g");var dee=1440*60*1e3;var lee=10*6e4;var ste=10*6e4;var bv=new Map([["function_call","function_call_output"],["custom_tool_call","custom_tool_call_output"]]),jte=new Set([...bv.keys(),...bv.values()]);import{execFile as N$}from"node:child_process";import{promisify as D$}from"node:util";var Lte=D$(N$);var Ute=200*1024*1024,Fte=4320*60*1e3;var Ho=String.raw`\bgit\s+(?:-[Cc]\s+\S+\s+|-\S+\s+)*`,zte=[new RegExp(`${Ho}restore\\b`),new RegExp(`${Ho}checkout\\b[^\\n;|&]*(\\s--(\\s|$)|\\s-f\\b|\\s\\.(\\s|$))`),new RegExp(`${Ho}reset\\b[^\\n;|&]*--(hard|merge|keep)\\b`),new RegExp(`${Ho}clean\\b`),new RegExp(`${Ho}stash\\s+(drop|clear|pop)\\b`),/\brm\s+(-[A-Za-z]*f[A-Za-z]*)\b/];var wv=76800;function Sv(e){return Math.ceil(e.length/4)}function Zc(e){if(!Le(e))return;let t=Qe(e.ir_version),n=_t(e.nodes);if(!(t===void 0||n===void 0))return{irVersion:t,threadTitle:Z(e.thread_title),nodes:n.flatMap(L$),hasMore:e.has_more===!0,cursor:Qe(e.cursor),budget:U$(e.budget)}}function L$(e){if(!Le(e))return[];let t=Z(e.kind),n=Qe(e.seq),i=Z(e.body)??"";return t===void 0||n===void 0?[]:[{kind:t,seq:n,at:Z(e.at),engine:Z(e.engine)??"none",body:i,structured:fe(e.structured),actor:fe(e.actor),attachments:_t(e.attachments)??[],sourceSeq:Qe(e.source_seq),streamKey:Z(e.stream_key)}]}function U$(e){if(!Le(e))return;let t=Qe(e.context_window),n=Qe(e.max_emission_tokens);if(!(t===void 0||n===void 0||n<=0))return{model:Z(e.model),contextWindow:t,maxEmissionTokens:n}}function F$(e,t){let n=t>0?t:wv,i=e.filter(s=>s.kind!=="reasoning"),r=e.length-i.length,o=[],a=0;for(let s=i.length-1;s>=0;s-=1){let d=i[s];if(d===void 0)continue;let u=Sv(kv(d,n));if(o.length>0&&a+u>n)break;a+=u,o.unshift(d)}return{tail:o,omittedNodeCount:i.length-o.length,redactedReasoningCount:r,artifacts:z$(e)}}function z$(e){let t=new Set,n=new Set,i=0;for(let r of e){if(r.kind==="error"&&(i+=1),r.kind==="file_change")for(let o of B$(r.structured))t.add(o);if(r.kind==="command_execution"){let o=Z(r.structured?.command)?.trim();o!==void 0&&o!==""&&n.add(o.split(`
255
+ `,1)[0]??o)}}return{filesTouched:[...t].slice(0,100),commandsRun:[...n].slice(0,100),errorCount:i}}function B$(e){if(e===void 0)return[];let t=Z(e.path),i=(_t(e.paths)??_t(e.files)??[]).flatMap(r=>{let o=Z(r);if(o!==void 0)return[o];let a=Le(r)?Z(r.path):void 0;return a===void 0?[]:[a]});return t===void 0?i:[t,...i]}function Qc(e){let t=e.budget?.maxEmissionTokens??wv,n=F$(e.nodes,t),i=V$({resumeFailure:e.resumeFailure,threadTitle:e.threadTitle,linzumiContext:e.linzumiContext,budgeted:n,transcriptEmpty:n.tail.length===0}),r=[jn(i,"commentary")],o=0;for(let s of n.tail)o+=1,r.push(...K$(s,t,o));let a=r.reduce((s,d)=>s+Sv(JSON.stringify(d)),0);return{items:r,emittedNodeCount:n.tail.length,omittedNodeCount:n.omittedNodeCount,redactedReasoningCount:n.redactedReasoningCount,emittedTokenEstimate:a,maxEmissionTokens:t}}function K$(e,t,n){let i=kv(e,t);switch(e.kind){case"user_message":return[{type:"message",role:"user",content:[{type:"input_text",text:G$(e,i)}]}];case"assistant_message":return[jn(i,H$(e))];case"command_execution":return J$(e,i,n);case"tool_call":return W$(e,i,n);case"reasoning":return[];case"file_change":return[jn(`[file change]
256
+ ${i}`,"commentary")];case"terminal_input":return[jn(`[terminal input]
257
+ ${i}`,"commentary")];case"tool_result":return[jn(`[tool result]
258
+ ${i}`,"commentary")];case"approval_request":return[jn(`[approval] ${i}`,"commentary")];case"agent_status":return[jn(`[status] ${i}`,"commentary")];case"system_notice":return[jn(`[notice] ${i}`,"commentary")];case"error":return[jn(`[error] ${i}`,"commentary")];default:return[jn(`[${e.kind}] ${i}`,"commentary")]}}function J$(e,t,n){let i=xv(e,n),r=Z(e.structured?.command),o=Z(e.structured?.cwd),a=Qe(e.structured?.exit_code),s=Z(e.structured?.output)??t;return[{type:"function_call",name:"shell",call_id:i,arguments:JSON.stringify({command:r??Q$(t),...o===void 0||o===""?{}:{cwd:o}})},{type:"function_call_output",call_id:i,output:a===void 0?s:`exit_code=${a}
259
+ ${s}`}]}function W$(e,t,n){let i=xv(e,n);return[{type:"function_call",name:Z$(Z(e.structured?.title)??"linzumi_replayed_tool"),call_id:i,arguments:JSON.stringify({replayed:!0})},{type:"function_call_output",call_id:i,output:t===""?"[result not recorded]":t}]}function jn(e,t){return{type:"message",role:"assistant",content:[{type:"output_text",text:e}],phase:t}}function H$(e){return Z(e.structured?.phase)==="commentary"?"commentary":"final_answer"}function G$(e,t){return e.attachments.length===0?t:`${t}
260
+ [${e.attachments.length} attachment(s) in the original message]`}function kv(e,t){let n=Math.max(1e3,t*4),i=e.body;return i.length<=n?i:`[...truncated...]
261
+ ${i.slice(i.length-n)}`}function V$(e){let t=e.resumeFailure.trim(),{artifacts:n}=e.budgeted,i=["Rebuilt Linzumi coding session","","This session was rebuilt after an interrupted durable engine session: the previous engine session for this Linzumi thread could not be resumed"+(t===""?".":` (${Y$(t,400)}).`),e.transcriptEmpty?"The durable server-side transcript could not be fetched or is empty - ask the user for any missing context instead of guessing.":"You are continuing the SAME task in the SAME Linzumi thread. The transcript below is replayed from the durable server-side record. Re-derive any local state (files, branches, running processes) from the workspace itself; do not assume in-memory state survived.",...e.threadTitle===void 0||e.threadTitle.trim()===""?[]:["",`Thread: ${e.threadTitle.trim()}`],...e.linzumiContext===void 0?[]:["",nd(e.linzumiContext)]],r=[...e.budgeted.omittedNodeCount>0?[`${e.budgeted.omittedNodeCount} older transcript entries were omitted to fit the emission budget.`]:[],...e.budgeted.redactedReasoningCount>0?[`${e.budgeted.redactedReasoningCount} reasoning entries were redacted (provider-private; never replayed).`]:[],...n.filesTouched.length>0?[`Files touched: ${n.filesTouched.join(", ")}`]:[],...n.commandsRun.length>0?[`Commands run: ${n.commandsRun.join("; ")}`]:[],...n.errorCount>0?[`${n.errorCount} error entries in the full history.`]:[]];return[...i,...r.length===0?[]:["",...r]].join(`
262
+ `)}function xv(e,t){return`linzumi_replay_${e.seq}_${t}`}function Z$(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64);return t===""?"linzumi_replayed_tool":t}function Q$(e){return e.split(`
263
+ `,1)[0]??e}function Y$(e,t){return e.length<=t?e:`[...truncated...]${e.slice(e.length-t)}`}var rd={default:{maxLadderMs:9e5},wafer:{maxLadderMs:36e5}};var lne={maxRecoveryRungs:4,maxLadderMs:rd.default.maxLadderMs,maxRateLimitHoldMs:30*6e4},cne={default:rd.default,wafer:rd.wafer};var hne=10*6e4;var nM=[{appName:"Bun",iconKey:"bun",names:["bun","bunx"]},{appName:"Node.js",iconKey:"nodejs",names:["node","nodejs","node.exe"]},{appName:"npm",iconKey:"npm",names:["npm","npm-cli.js","npx"]},{appName:"pnpm",iconKey:"pnpm",names:["pnpm","pnpx"]},{appName:"Yarn",iconKey:"yarn",names:["yarn","yarnpkg","yarn.js"]},{appName:"Corepack",iconKey:"corepack",names:["corepack"]},{appName:"Deno",iconKey:"deno",names:["deno"]},{appName:"Vite",iconKey:"vite",names:["vite","vite-node"]},{appName:"Vitest",iconKey:"vitest",names:["vitest"]},{appName:"Next.js",iconKey:"nextjs",names:["next","next-server"]},{appName:"Nuxt",iconKey:"nuxt",names:["nuxt","nuxi"]},{appName:"Astro",iconKey:"astro",names:["astro"]},{appName:"SvelteKit",iconKey:"svelte",names:["svelte-kit","sveltekit"]},{appName:"Remix",iconKey:"remix",names:["remix"]},{appName:"Expo",iconKey:"expo",names:["expo","expo-cli"]},{appName:"React Native",iconKey:"react",names:["react-native"]},{appName:"Metro",iconKey:"metro",names:["metro","metro-inspector-proxy"]},{appName:"Webpack",iconKey:"webpack",names:["webpack","webpack-dev-server","webpack-cli"]},{appName:"Parcel",iconKey:"parcel",names:["parcel"]},{appName:"Rollup",iconKey:"rollup",names:["rollup"]},{appName:"esbuild",iconKey:"esbuild",names:["esbuild"]},{appName:"SWC",iconKey:"swc",names:["swc"]},{appName:"TypeScript",iconKey:"typescript",names:["tsc","tsserver","tsx","ts-node","typescript-language-server"]},{appName:"ESLint",iconKey:"eslint",names:["eslint","eslint_d"]},{appName:"Prettier",iconKey:"prettier",names:["prettier"]},{appName:"Biome",iconKey:"biome",names:["biome"]},{appName:"Storybook",iconKey:"storybook",names:["storybook","start-storybook"]},{appName:"Playwright",iconKey:"playwright",names:["playwright"]},{appName:"Cypress",iconKey:"cypress",names:["cypress"]},{appName:"Jest",iconKey:"jest",names:["jest"]},{appName:"Python",iconKey:"python",names:["python","python2","python3","python3.9","python3.10","python3.11","python3.12","python3.13","pypy","pypy3"]},{appName:"pip",iconKey:"python",names:["pip","pip2","pip3"]},{appName:"pipx",iconKey:"python",names:["pipx"]},{appName:"uv",iconKey:"python",names:["uv","uvx"]},{appName:"Poetry",iconKey:"poetry",names:["poetry"]},{appName:"Pipenv",iconKey:"python",names:["pipenv"]},{appName:"Conda",iconKey:"conda",names:["conda","mamba","micromamba"]},{appName:"Django",iconKey:"django",names:["django-admin","django-admin.py","manage.py"]},{appName:"Flask",iconKey:"flask",names:["flask"]},{appName:"Uvicorn",iconKey:"uvicorn",names:["uvicorn"]},{appName:"Gunicorn",iconKey:"gunicorn",names:["gunicorn"]},{appName:"Hypercorn",iconKey:"python",names:["hypercorn"]},{appName:"Celery",iconKey:"celery",names:["celery"]},{appName:"Jupyter",iconKey:"jupyter",names:["jupyter","jupyter-lab","jupyter-notebook","ipython"]},{appName:"Ruby",iconKey:"ruby",names:["ruby","erb","irb"]},{appName:"Bundler",iconKey:"ruby",names:["bundle","bundler"]},{appName:"Rails",iconKey:"rails",names:["rails","bin/rails"]},{appName:"Rack",iconKey:"ruby",names:["rackup"]},{appName:"Puma",iconKey:"puma",names:["puma"]},{appName:"Sidekiq",iconKey:"sidekiq",names:["sidekiq"]},{appName:"RSpec",iconKey:"ruby",names:["rspec"]},{appName:"Go",iconKey:"go",names:["go","gofmt","gopls","air"]},{appName:"Delve",iconKey:"go",names:["dlv"]},{appName:"Rust",iconKey:"rust",names:["rustc","rustup","cargo","rust-analyzer"]},{appName:"Java",iconKey:"java",names:["java","javac","jar","jshell","jwebserver"]},{appName:"Gradle",iconKey:"gradle",names:["gradle","gradlew"]},{appName:"Maven",iconKey:"maven",names:["mvn","mvnw"]},{appName:"Spring Boot",iconKey:"spring",names:["spring","spring-boot"]},{appName:"Kotlin",iconKey:"kotlin",names:["kotlin","kotlinc","kotlin-language-server"]},{appName:"Scala",iconKey:"scala",names:["scala","scalac","sbt","metals"]},{appName:"Clojure",iconKey:"clojure",names:["clojure","clj","lein","boot"]},{appName:"PHP",iconKey:"php",names:["php","php-fpm","php-cgi","composer"]},{appName:"Laravel",iconKey:"laravel",names:["artisan","laravel"]},{appName:"Symfony",iconKey:"symfony",names:["symfony"]},{appName:"Elixir",iconKey:"elixir",names:["elixir","iex","mix"]},{appName:"Erlang",iconKey:"erlang",names:["erl","beam.smp","beam","epmd","rebar3"]},{appName:"Phoenix",iconKey:"phoenix",names:["phx.server","phoenix"]},{appName:"PostgreSQL",iconKey:"postgresql",names:["postgres","postmaster","pg_ctl","psql","pg_isready"]},{appName:"Redis",iconKey:"redis",names:["redis-server","redis-cli","redis-sentinel"]},{appName:"MySQL",iconKey:"mysql",names:["mysql","mysqld","mysqladmin"]},{appName:"MariaDB",iconKey:"mariadb",names:["mariadb","mariadbd","mariadb-admin"]},{appName:"SQLite",iconKey:"sqlite",names:["sqlite3","sqlite"]},{appName:"MongoDB",iconKey:"mongodb",names:["mongod","mongosh","mongo"]},{appName:"Elasticsearch",iconKey:"elasticsearch",names:["elasticsearch"]},{appName:"OpenSearch",iconKey:"opensearch",names:["opensearch"]},{appName:"Solr",iconKey:"solr",names:["solr"]},{appName:"Kafka",iconKey:"kafka",names:["kafka-server-start","kafka-console-consumer","kafka-console-producer"]},{appName:"ZooKeeper",iconKey:"zookeeper",names:["zookeeper-server-start","zkserver"]},{appName:"RabbitMQ",iconKey:"rabbitmq",names:["rabbitmq-server","rabbitmqctl"]},{appName:"NATS",iconKey:"nats",names:["nats-server","nats"]},{appName:"Docker",iconKey:"docker",names:["docker","dockerd","docker-compose","docker-proxy","com.docker.backend"]},{appName:"Podman",iconKey:"podman",names:["podman","podman-compose"]},{appName:"Kubernetes",iconKey:"kubernetes",names:["kubectl","kube-apiserver","kubelet","minikube","kind"]},{appName:"Helm",iconKey:"helm",names:["helm"]},{appName:"Tilt",iconKey:"tilt",names:["tilt"]},{appName:"nginx",iconKey:"nginx",names:["nginx"]},{appName:"Caddy",iconKey:"caddy",names:["caddy"]},{appName:"Apache HTTP Server",iconKey:"apache",names:["httpd","apache2","apachectl"]},{appName:"HAProxy",iconKey:"haproxy",names:["haproxy"]},{appName:"Traefik",iconKey:"traefik",names:["traefik"]},{appName:"Envoy",iconKey:"envoy",names:["envoy"]},{appName:"Tailscale",iconKey:"tailscale",names:["tailscale","tailscaled"]},{appName:"Cloudflare Tunnel",iconKey:"cloudflare",names:["cloudflared"]},{appName:"ngrok",iconKey:"ngrok",names:["ngrok"]},{appName:"localtunnel",iconKey:"terminal",names:["lt","localtunnel"]},{appName:"SSH",iconKey:"ssh",names:["ssh","sshd","scp","sftp"]},{appName:"Git",iconKey:"git",names:["git","git-lfs","git-upload-pack","git-receive-pack"]},{appName:"GitHub CLI",iconKey:"github",names:["gh"]},{appName:"GitLab CLI",iconKey:"gitlab",names:["glab"]},{appName:"Subversion",iconKey:"subversion",names:["svn"]},{appName:"Mercurial",iconKey:"mercurial",names:["hg"]},{appName:"AWS CLI",iconKey:"aws",names:["aws","aws-vault","sam"]},{appName:"Azure CLI",iconKey:"azure",names:["az"]},{appName:"Google Cloud CLI",iconKey:"google-cloud",names:["gcloud","gsutil","bq"]},{appName:"Terraform",iconKey:"terraform",names:["terraform"]},{appName:"OpenTofu",iconKey:"opentofu",names:["tofu"]},{appName:"Ansible",iconKey:"ansible",names:["ansible","ansible-playbook"]},{appName:"Pulumi",iconKey:"pulumi",names:["pulumi"]},{appName:"Nomad",iconKey:"nomad",names:["nomad"]},{appName:"Vault",iconKey:"vault",names:["vault"]},{appName:"Consul",iconKey:"consul",names:["consul"]},{appName:"Make",iconKey:"make",names:["make","gmake"]},{appName:"CMake",iconKey:"cmake",names:["cmake","ctest","cpack"]},{appName:"Ninja",iconKey:"ninja",names:["ninja"]},{appName:"Bazel",iconKey:"bazel",names:["bazel","bazelisk"]},{appName:"Buck",iconKey:"buck",names:["buck","buck2"]},{appName:"Clang",iconKey:"clang",names:["clang","clang++","clangd"]},{appName:"GCC",iconKey:"gcc",names:["gcc","g++","cc","c++"]},{appName:"LLDB",iconKey:"terminal",names:["lldb"]},{appName:"GDB",iconKey:"terminal",names:["gdb"]},{appName:"Swift",iconKey:"swift",names:["swift","swiftc","sourcekit-lsp"]},{appName:"Xcode",iconKey:"xcode",names:["xcodebuild","xcrun","simctl"]},{appName:"Zig",iconKey:"zig",names:["zig"]},{appName:"Lua",iconKey:"lua",names:["lua","luajit","lua-language-server"]},{appName:"Perl",iconKey:"perl",names:["perl"]},{appName:"R",iconKey:"r",names:["r","rscript","rserver","rsession"]},{appName:"Julia",iconKey:"julia",names:["julia"]},{appName:"Haskell",iconKey:"haskell",names:["ghc","ghci","cabal","stack","haskell-language-server-wrapper"]},{appName:"OCaml",iconKey:"ocaml",names:["ocaml","ocamlc","dune","opam"]},{appName:"F#",iconKey:"fsharp",names:["fsharpi","fsautocomplete"]},{appName:".NET",iconKey:"dotnet",names:["dotnet","csharp-ls","omnisharp"]},{appName:"PowerShell",iconKey:"powershell",names:["pwsh","powershell"]},{appName:"Bash",iconKey:"terminal",names:["bash"]},{appName:"Zsh",iconKey:"terminal",names:["zsh"]},{appName:"fish",iconKey:"terminal",names:["fish"]},{appName:"tmux",iconKey:"terminal",names:["tmux"]},{appName:"GNU Screen",iconKey:"terminal",names:["screen"]},{appName:"direnv",iconKey:"terminal",names:["direnv"]},{appName:"Nix",iconKey:"nix",names:["nix","nix-shell","nix-daemon","nix-build","nix develop"]},{appName:"Homebrew",iconKey:"homebrew",names:["brew"]},{appName:"mise",iconKey:"terminal",names:["mise"]},{appName:"asdf",iconKey:"terminal",names:["asdf"]},{appName:"Volta",iconKey:"volta",names:["volta"]},{appName:"fnm",iconKey:"nodejs",names:["fnm"]},{appName:"nvm",iconKey:"nodejs",names:["nvm"]},{appName:"curl",iconKey:"terminal",names:["curl"]},{appName:"HTTPie",iconKey:"httpie",names:["http","https","httpie"]},{appName:"wget",iconKey:"terminal",names:["wget"]},{appName:"jq",iconKey:"terminal",names:["jq"]},{appName:"ripgrep",iconKey:"terminal",names:["rg","ripgrep"]},{appName:"fd",iconKey:"terminal",names:["fd"]},{appName:"fzf",iconKey:"terminal",names:["fzf"]},{appName:"bat",iconKey:"terminal",names:["bat"]},{appName:"eza",iconKey:"terminal",names:["eza","exa"]},{appName:"htop",iconKey:"terminal",names:["htop","top","btop"]},{appName:"Vim",iconKey:"vim",names:["vim","view","vimdiff"]},{appName:"Neovim",iconKey:"neovim",names:["nvim","nvim-qt"]},{appName:"Emacs",iconKey:"emacs",names:["emacs","emacsclient"]},{appName:"Visual Studio Code",iconKey:"vscode",names:["code","code-insiders","vscode","visual studio code","visual studio code - insiders"]},{appName:"code-server",iconKey:"vscode",names:["code-server"]},{appName:"Cursor",iconKey:"cursor",names:["cursor"]},{appName:"Zed",iconKey:"zed",names:["zed"]},{appName:"Sublime Text",iconKey:"sublime-text",names:["subl","sublime_text","sublime text"]},{appName:"Atom",iconKey:"atom",names:["atom"]},{appName:"IntelliJ IDEA",iconKey:"intellij-idea",names:["idea","idea.sh","intellij idea","idea64.exe"]},{appName:"WebStorm",iconKey:"webstorm",names:["webstorm","webstorm.sh"]},{appName:"PyCharm",iconKey:"pycharm",names:["pycharm","pycharm.sh"]},{appName:"RubyMine",iconKey:"rubymine",names:["rubymine","rubymine.sh"]},{appName:"GoLand",iconKey:"goland",names:["goland","goland.sh"]},{appName:"CLion",iconKey:"clion",names:["clion","clion.sh"]},{appName:"DataGrip",iconKey:"datagrip",names:["datagrip","datagrip.sh"]},{appName:"Rider",iconKey:"rider",names:["rider","rider.sh"]},{appName:"Android Studio",iconKey:"android-studio",names:["studio","studio.sh","android studio"]},{appName:"Xcode",iconKey:"xcode",names:["xcode","xcode.app"]},{appName:"Postman",iconKey:"postman",names:["postman"]},{appName:"Insomnia",iconKey:"insomnia",names:["insomnia"]},{appName:"Hoppscotch",iconKey:"hoppscotch",names:["hoppscotch"]},{appName:"TablePlus",iconKey:"tableplus",names:["tableplus"]},{appName:"DBeaver",iconKey:"dbeaver",names:["dbeaver"]},{appName:"RedisInsight",iconKey:"redis",names:["redisinsight"]},{appName:"Prisma",iconKey:"prisma",names:["prisma"]},{appName:"Drizzle Kit",iconKey:"drizzle",names:["drizzle-kit"]},{appName:"Supabase",iconKey:"supabase",names:["supabase"]},{appName:"Firebase",iconKey:"firebase",names:["firebase"]},{appName:"Vercel",iconKey:"vercel",names:["vercel"]},{appName:"Netlify",iconKey:"netlify",names:["netlify","ntl"]},{appName:"Fly.io",iconKey:"fly",names:["fly","flyctl"]},{appName:"Heroku",iconKey:"heroku",names:["heroku"]},{appName:"Stripe CLI",iconKey:"stripe",names:["stripe"]},{appName:"Twilio CLI",iconKey:"twilio",names:["twilio"]},{appName:"Mailpit",iconKey:"mail",names:["mailpit"]},{appName:"MailHog",iconKey:"mail",names:["mailhog"]},{appName:"OpenSSL",iconKey:"openssl",names:["openssl"]},{appName:"mkcert",iconKey:"certificate",names:["mkcert"]},{appName:"mkdocs",iconKey:"markdown",names:["mkdocs"]},{appName:"Hugo",iconKey:"hugo",names:["hugo"]},{appName:"Jekyll",iconKey:"jekyll",names:["jekyll"]},{appName:"Eleventy",iconKey:"eleventy",names:["eleventy","11ty"]},{appName:"Docusaurus",iconKey:"docusaurus",names:["docusaurus"]},{appName:"Trunk",iconKey:"rust",names:["trunk"]},{appName:"wasm-pack",iconKey:"webassembly",names:["wasm-pack"]},{appName:"wasmtime",iconKey:"webassembly",names:["wasmtime"]},{appName:"Language Server",iconKey:"language-server",names:["lua-language-server","yaml-language-server","vscode-json-language-server","docker-langserver","bash-language-server","marksman","taplo"]}],Cv=new Map;for(let e of nM)for(let t of e.names)Cv.set(iM(t),{appName:e.appName,iconKey:e.iconKey});var Ene=Cv.size;function rM(e){let t=e.toLowerCase();switch(!0){case t.endsWith(".app"):return e.slice(0,-4);case t.endsWith(".exe"):return e.slice(0,-4);case t.endsWith(".cmd"):case t.endsWith(".bat"):return e.slice(0,-4);default:return e}}function iM(e){return rM(e.trim().replaceAll("\\","/").toLowerCase())}var Tv=100,oM=100,Yc=20,aM=255,qn=class extends Error{constructor(t){super(t),this.name="NativeModelCatalogInvalidResponseError"}},vn=e=>new qn(e),Go=e=>e!==""&&e.length<=aM;async function Ev(e){let t=[],n=new Set,i=new Set,r=[],o=null;for(let s=0;s<Yc;s+=1){let d=await e.request("model/list",{cursor:o,limit:oM,includeHidden:!1}),u=sM(d,"model/list"),l=_t(u.data);if(l===void 0)throw vn("model/list response did not include data");for(let f of l){let h=fe(f),y=Z(h?.model)?.trim(),w=Z(h?.displayName)?.trim(),g=_t(h?.supportedReasoningEfforts),v=Z(h?.defaultReasoningEffort)?.trim();if(h===void 0||y===void 0||!Go(y)||w===void 0||!Go(w)||h.hidden!==!1||g===void 0||v===void 0||!Go(v)||typeof h.isDefault!="boolean")throw vn("model/list included invalid visible model metadata");if(n.has(y))throw vn(`model/list repeated model ${y}`);let b=g.map(S=>{let T=fe(S),C=Z(T?.reasoningEffort)?.trim();if(C===void 0||!Go(C))throw vn(`model/list ${y} included invalid reasoning effort metadata`);return C});if(new Set(b).size!==b.length||!b.includes(v))throw vn(`model/list ${y} included inconsistent reasoning effort metadata`);if(n.add(y),t.push({id:y,displayName:w,reasoningEfforts:b,defaultReasoningEffort:v}),h.isDefault&&r.push(y),t.length>Tv)throw vn(`model/list exceeded ${Tv} visible models`)}let p=u.nextCursor;if(p===null)break;let m=Z(p)?.trim();if(m===void 0||!Go(m))throw vn("model/list included invalid pagination cursor");if(i.has(m))throw vn(`model/list repeated pagination cursor ${m}`);if(i.add(m),o=m,s===Yc-1)throw vn(`model/list exceeded ${Yc} pagination pages`)}if(t.length===0)return{type:"empty"};if(r.length!==1)throw vn("model/list did not advertise exactly one valid default model");let[a]=r;if(a===void 0)throw vn("model/list did not advertise exactly one valid default model");return{type:"ready",catalog:{defaultModel:a,models:t}}}function sM(e,t){if("error"in e)throw new Error(`${t} failed: ${e.error.message}`);let n=fe(e.result);if(n===void 0)throw new Error(`${t} response did not include an object result`);return n}var Iv=12e4;function dM(){let e=process.env.LINZUMI_CODEX_START_REQUEST_TIMEOUT_MS?.trim();if(e===void 0||e==="")return Iv;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:Iv}var Xc=class extends Error{constructor(t,n){super(`Codex ${t} did not reply within ${n}ms (start request timed out)`),this.name="CodexStartRequestTimeoutError"}};function uM(e,t,n=dM()){return lM(e,t,n,(i,r)=>new Xc(i,r))}function lM(e,t,n,i){return n>0?new Promise((r,o)=>{let a=setTimeout(()=>{o(i(e,n))},n);a.unref?.(),t.then(s=>{clearTimeout(a),r(s)},s=>{clearTimeout(a),o(s)})}):t}function Vo(e,t,n){return uM(t,e.request(t,n))}var cM=e=>/\bsession\b.+\bis archived\b/i.test(e),pM=e=>/^thread not found(?:\s*:|\b)/i.test(e.trim()),fM=e=>/\bno rollout found\b/i.test(e)||/\bsession not found\b[\s\S]*\brollout\b/i.test(e);async function Pv(e,t,n,i,r,o){o("kandan.reconnect_thread_unarchive_started",{codex_thread_id:t,discovered_by:i,message:r});try{let a=await Vo(e,"thread/unarchive",{threadId:t});if("error"in a)throw new Error(`thread/unarchive failed: ${a.error.message}`);let s=await Vo(e,"thread/resume",n);if("error"in s)throw new Error(`thread/resume after unarchive failed: ${s.error.message}`);return o("kandan.reconnect_thread_unarchive_resumed",{codex_thread_id:t,discovered_by:i}),{mode:"resumed"}}catch(a){let s=a instanceof Error?a.message:String(a);throw o("kandan.reconnect_thread_unarchive_failed",{codex_thread_id:t,discovered_by:i,archive_error:r,message:s}),new Error(i==="forced_inject_not_found"?`thread/inject_items failed: ${r}; archive recovery failed: ${s}`:s)}}async function Rv(e){let{codex:t,codexThreadId:n,rehydration:i}=e,r={threadId:n,...e.resumeOverrides},o;if(i.forceRehydrate===!0)o="the server marked the durable engine session dead after an acknowledged-but-unexecuted turn";else{let s=await Vo(t,"thread/resume",r);if(!("error"in s))return{mode:"resumed"};if(cM(s.error.message))return await Pv(t,n,r,"resume_archived",s.error.message,i.log);if(e.rebuildWhen==="missing-rollout-only"&&!fM(s.error.message))throw i.log("linzumi.agent_thread_resume_failed_unrecoverable",{codex_thread_id:n,message:s.error.message,rehydrating:!1}),new Error(s.error.message);o=s.error.message}i.log(i.forceRehydrate===!0?"kandan.reconnect_thread_rehydrate_forced":"kandan.reconnect_thread_resume_failed",{codex_thread_id:n,message:o,forced:i.forceRehydrate===!0,rehydrating:!0});let a;try{let s;try{s=await i.buildRehydrationItems?.(o)}catch(l){i.log("kandan.reconnect_thread_rehydration_items_failed",{codex_thread_id:n,message:l instanceof Error?l.message:String(l)}),s=void 0}let d=s!==void 0&&s.length>0?[...s]:[{type:"agentMessage",text:await i.buildRehydrationText(o)}],u=await Vo(t,"thread/inject_items",{threadId:n,items:d});if("error"in u){if(i.forceRehydrate===!0&&pM(u.error.message))return await Pv(t,n,r,"forced_inject_not_found",u.error.message,i.log);a=`thread/inject_items failed: ${u.error.message}`}else{let l=await Vo(t,"thread/resume",r);"error"in l&&(a=`rehydrated thread/resume failed: ${l.error.message}`)}}catch(s){a=s instanceof Error?s.message:String(s)}if(a!==void 0)throw i.log("kandan.reconnect_thread_rehydration_failed",{codex_thread_id:n,resume_failure:o,rehydration_failure:a}),new Error(`could not resume this thread's engine session (${o}) and rebuilding a fresh session from the thread transcript also failed (${a})`);return i.log("kandan.reconnect_thread_rehydrated",{codex_thread_id:n,resume_failure:o}),{mode:"rehydrated",resumeFailure:o}}import{existsSync as Z8,readFileSync as Q8,statSync as Dde}from"node:fs";import{homedir as sE}from"node:os";import{join as An,posix as uy,win32 as Y8}from"node:path";var mM=[/(--token[=\s]+)\S+/gi,/(bearer\s+)[^\s,;"'\]\}]+/gi,/((?:access[_-]?token|api[_-]?key|auth[_-]?token|authorization|secret|password|refresh[_-]?token|session[_-]?token|jwt|token)["']?\s*[:=]\s*["']?)[^\s,;"'\]\}]+/gi,/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g];function Ov(e){return typeof e!="string"||e===""?e:mM.reduce((t,n)=>n.source.startsWith("\\beyJ")?t.replace(n,"<redacted>"):t.replace(n,"$1<redacted>"),e)}var Coe=64*1024;var Toe=16*1024;function X8(){return["user","project","local"]}function e7(e){return[uy.join(e,".local","bin"),uy.join(e,".claude","local")]}function dE(e){return e instanceof Error&&e.message.includes("Native CLI binary for")&&e.message.includes("not found")}function t7(e){let t=e.env.LINZUMI_CLAUDE_CODE_EXECUTABLE?.trim();if(t!==void 0&&t!=="")return e.fileExists(t)?t:void 0;let n=e.platform==="win32",i=e.env.PATH??"",r=n?";":":",o=n?Y8.join:uy.join,a=n?["claude.exe","claude.cmd","claude"]:["claude"],s=[...i.split(r),...!n&&e.homeDir!==void 0?e7(e.homeDir):[]];for(let d of s)if(d!=="")for(let u of a){let l=o(d,u);if(e.fileExists(l))return l}}var uE;var lE,n7="claude_code.probe_executable_fallback";function cE(e,t,n){let i=lE;lE=e,!(i!==void 0&&(i.kind==="sdk"?e.kind==="sdk":e.kind==="fallback"&&i.executable===e.executable))&&(e.kind==="sdk"&&i===void 0||n({severity:e.kind==="fallback"?"warning":"info",key:n7,message:t()}))}var pE=100,sy=255,r7=1e4;async function*i7(){}async function o7(e,t){let n;try{return await Promise.race([e.supportedModels(),new Promise((i,r)=>{n=setTimeout(()=>r(new Error("Claude model discovery timed out")),t),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}}async function a7(e,t=r7){let n=e.query(i7()),i;try{i=await o7(n,t)}finally{await n.return(void 0)}if(i.length===0)return{type:"empty"};let r=[],o=new Set;for(let a of i){let s=a.value.trim(),d=a.displayName.trim(),u=(a.supportedEffortLevels??[]).map(l=>l.trim());if(s===""||s.length>sy||d===""||d.length>sy||o.has(s)||u.some(l=>l===""||l.length>sy)||new Set(u).size!==u.length||a.supportsEffort===!0&&u.length===0||a.supportsEffort===!1&&u.length>0)throw new qn("Claude supportedModels included invalid model metadata");if(o.add(s),r.push({id:s,displayName:d,reasoningEfforts:u}),r.length>pE)throw new qn(`Claude supportedModels exceeded ${pE} models`)}if(!o.has("default"))throw new qn("Claude supportedModels did not advertise the runtime default model");return{type:"ready",catalog:{defaultModel:"default",models:r}}}async function fE(e){try{return await a7(e)}catch(t){let n=t instanceof qn?"invalid_response":"discovery_failed";return Ye("claude_code.model_catalog_discovery_failed",{failure_code:n}),{type:"failed",failureCode:n}}}function mE(e){return e===void 0?{}:{pathToClaudeCodeExecutable:e}}function s7(e){return e!==void 0?e:(Q_(),process.env)}function d7(e){return e instanceof Error&&e.message.includes("initialization did not complete within")}var u7=600;function l7(e){return Ov(e).replace(/\bsk-[A-Za-z0-9_-]{8,}/g,"<redacted>").replace(/(\/\/[^\s/:@]+):[^\s@]+@/g,"$1:<redacted>@")}function hE(e,t){let n=e instanceof Error?e.message:String(e),i=t.map(({executable:o,stderrTail:a})=>a===""?`${o}: (no stderr output from the claude subprocess)`:`${o}: stderr tail: ${a}`),r=t.length===0?"no claude subprocess was spawned":i.join(" | ");return l7(`${n} [probed ${r}]`.replace(/\s+/g," ").trim())}async function gE(e,t){let n=[],i=t?.reportNotice??Gc,r=o=>{let a={executable:o,stderrTail:""};return n.push(a),s=>{a.stderrTail=`${a.stderrTail}${s}`.slice(-u7)}};try{let o=s7(t?.env),a=t?.platform??process.platform,s=t?.fileExists??Z8,d=e.claudeBin===void 0?void 0:Mc(e.claudeBin,{env:o,platform:a,fileExists:s});if(e.claudeBin!==void 0&&d===void 0)return i({severity:"error",key:"claude_code.claude_bin_missing",message:`--claude-bin ${e.claudeBin} does not exist (checked the given path and the runner's search PATH). Claude Code stays disabled; fix the path or remove the flag.`}),{status:"binary_missing",transient:!1};if(d===void 0&&!c7(o,{cwd:e.cwd,homeDir:sE(),platform:a,fileExists:s,readTextFile:_7}))return{status:"not_logged_in",transient:!1};let u=t?.startup??(await Promise.resolve().then(()=>(aE(),oE))).startup,l={cwd:e.cwd,persistSession:!1,settingSources:X8(),tools:[],env:o},p=15e3,m;try{m=await u({options:{...l,...mE(d),stderr:r(d??"the SDK-bundled claude")},initializeTimeoutMs:p})}catch(f){let h=d??t7({env:o,platform:a,fileExists:s,homeDir:sE()});if(h===void 0||h===d)throw f;return cE({kind:"fallback",executable:h},()=>dE(f)?`claude agent SDK native binary is missing; retrying the availability probe with the user-installed claude executable at ${h}`:`claude agent SDK startup failed (${hE(f,n)}); retrying the availability probe with the user-installed claude executable at ${h}`,i),m=await u({options:{...l,...mE(h),stderr:r(h)},initializeTimeoutMs:p}),uE=h,{status:"logged_in",transient:!1,fallbackExecutable:h,modelCatalogDiscovery:await fE(m)}}return uE=d,d===void 0&&cE({kind:"sdk"},()=>"claude agent SDK startup recovered; the availability probe is using the SDK's own claude executable again",i),{status:"logged_in",transient:!1,modelCatalogDiscovery:await fE(m)}}catch(o){let a=dE(o),s=e.claudeBin===void 0?a?`The claude agent SDK's platform-native package (@anthropic-ai/claude-agent-sdk-${t?.platform??process.platform}-${process.arch}) is missing from this install, and no user-installed claude executable was found (checked PATH, ~/.local/bin, ~/.claude/local). Restart the runner on the current CLI (it rebuilds the worker-entry mirror with the native package at boot), or install Claude Code and pass --claude-bin "$(command -v claude)" when starting the runner.`:'If `claude` works in your terminal, pass --claude-bin "$(command -v claude)" when starting the runner, or set LINZUMI_CLAUDE_CODE_EXECUTABLE to the binary\'s absolute path.':`--claude-bin ${e.claudeBin} was found but Claude Code failed to start (an auth or startup error, not a missing binary). Check \`claude\` runs and is logged in, then restart the runner.`,d=hE(o,n),u=d7(o)?" The startup PROBE hit its deadline - this is a liveness verdict about the probe, not proof the binary is broken; the runner re-probes on credential changes without a restart (#2989).":"";return i({severity:"error",key:"claude_code.availability_probe_failed",message:`claude code availability probe failed: ${d}
264
+ Claude Code sessions stay disabled for this runner (Codex is unaffected).${u} ${s}`}),{status:a?"binary_missing":"probe_failed",transient:!a,detail:d}}}function c7(e,t){let n=e.CLAUDE_CONFIG_DIR??An(t.homeDir,".claude");return p7(e)||f7(e)||m7(n,t)||h7(n,t)||y7(t)}function dy(e){return e!==void 0&&e.trim()!==""}function Os(e){let t=e?.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function p7(e){return dy(e.ANTHROPIC_API_KEY)||dy(e.ANTHROPIC_AUTH_TOKEN)||dy(e.CLAUDE_CODE_OAUTH_TOKEN)}function f7(e){return Os(e.CLAUDE_CODE_USE_BEDROCK)||Os(e.CLAUDE_CODE_USE_VERTEX)||Os(e.CLAUDE_CODE_USE_FOUNDRY)||Os(e.CLAUDE_CODE_USE_ANTHROPIC_AWS)||Os(e.CLAUDE_CODE_USE_MANTLE)}function m7(e,t){return t.fileExists(An(e,".credentials.json"))||t.fileExists(An(e,".claude.json"))||t.fileExists(An(t.homeDir,".claude.json"))}function h7(e,t){return[An(e,"settings.json"),An(e,"settings.local.json"),An(t.cwd,".claude","settings.json"),An(t.cwd,".claude","settings.local.json")].some(n=>g7(n,t))}function g7(e,t){let n=t.readTextFile(e);if(n===void 0)return!1;try{let i=fe(JSON.parse(n));return v7(Z(i?.apiKeyHelper))!==void 0}catch{return!1}}function y7(e){return e.platform!=="darwin"?!1:[An(e.homeDir,"Library","Application Support","claude-cli-nodejs"),An(e.homeDir,"Library","Application Support","Claude"),An(e.homeDir,"Library","Preferences","claude-cli-nodejs")].some(t=>e.fileExists(t))}function _7(e){try{return Q8(e,"utf8")}catch{return}}function v7(e){if(e===void 0)return;let t=e.trim();return t.length===0?void 0:t}var ly={mcpAuthFileContents:"LINZUMI_CLOUD_MCP_AUTH_JSON",llmProxyToken:"LINZUMI_CLOUD_LLM_PROXY_TOKEN"};function yE(e){let t;try{t=JSON.parse(Buffer.from(e,"base64").toString("utf8"))}catch{throw new Error("invalid guest cloud turn config payload (not base64 JSON)")}if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("invalid guest cloud turn config payload");let n=t;for(let[i,r]of[["codexVersion",n.codexVersion],["sandbox",n.sandbox],["approvalPolicy",n.approvalPolicy],["kandanUrl",n.kandanUrl],["cwd",n.cwd]])if(typeof r!="string"||r==="")throw new Error(`invalid guest cloud turn config payload (${i} missing)`);if(!Array.isArray(n.input))throw new Error("invalid guest cloud turn config payload (input)");if(typeof n.appServerPort!="number"||!Number.isInteger(n.appServerPort))throw new Error("invalid guest cloud turn config payload (appServerPort)");return n}var ui="/home/agent",b7=`${ui}/.linzumi-provisioned`;var cy="/dev/shm/linzumi",fue=`${cy}/codex`,mue=`${cy}/mcp-auth.json`;var hue=`${cy}/codex.env`;var bue=`${ui}/cloud-supervisor.mjs`,_E=`${ui}/mcp-server.mjs`,py=`${ui}/.secrets`,fy=`${py}/mcp-auth.json`,Gl=`${ui}/.codex`,vE=`${Gl}/linzumi-thread-map.json`;var my=`${ui}/.turn-heartbeats`,bE=5e3,w7=/^[A-Za-z0-9-]{8,64}$/;function hy(e){if(!w7.test(e))throw new Error(`invalid cloud turn nonce: ${JSON.stringify(e.slice(0,80))}`)}var E7=3e4,R7=200,O7=18e4,wE="LINZUMI_GUEST_MODEL_CALL_LIVENESS_MS",A7=15*6e4,SE="LINZUMI_GUEST_ACTIVE_LOOP_BUDGET_MS",Zl=2147483647;function $7(e){let t=e[SE];if(t===void 0)return A7;let n=Number(t);if(t.trim()===""||!Number.isSafeInteger(n)||n<=0||n>Zl)throw new Error(`${SE} must be an integer number of milliseconds between 1 and ${Zl}, got ${JSON.stringify(t)}`);return n}var yy=class extends Error{code="active_loop_budget_exceeded";budgetMs;constructor(t){super(`active_loop_budget_exceeded: guest turn exceeded the ${t}ms wall-clock budget; killed the guest turn`),this.name="GuestActiveLoopBudgetExceeded",this.budgetMs=t}};function M7(e){let t=e[wE];if(t===void 0)return O7;let n=Number(t);if(t.trim()===""||!Number.isSafeInteger(n)||n<=0)throw new Error(`${wE} must be a positive integer number of milliseconds, got ${JSON.stringify(t)}`);return n}var _y=class extends Error{code="guest_turn_liveness_failure";windowMs;constructor(t){super(`guest_turn_liveness_failure: zero upstream model calls for ${t}ms; killed the guest turn`),this.name="GuestTurnLivenessFailure",this.windowMs=t}};function j7(e,t,n){if(e.method!=="thread/tokenUsage/updated")return;let i=fe(e.params)??{};if(Z(i.threadId)!==t||Z(i.turnId)!==n)return;let r=Qe(fe(fe(i.tokenUsage)?.total)?.totalTokens),o=Qe(fe(fe(i.tokenUsage)?.last)?.totalTokens);if(!(r===void 0||r<0))return{totalTokens:r,priorCallTotalTokens:o!==void 0&&o>=0&&o<=r?r-o:void 0}}function li(e){return e.replace(/\bsmk_[A-Za-z0-9._-]+/g,"smk_[REDACTED]").replace(/\b(sk|lz|tok|bearer)[-_][A-Za-z0-9._-]{8,}/gi,"$1_[REDACTED]")}var gy=64*1024;function q7(e,t){let n=t.now??Date.now,i=Buffer.alloc(0),r=null,o=null,a=s=>{let d=Buffer.isBuffer(s)?s:Buffer.from(s,"utf8");i=Buffer.concat([i,d]);let u=gy*2;i.byteLength>u&&(i=i.subarray(i.byteLength-u))};return e.stdout?.on("data",a),e.stderr?.on("data",a),e.once("exit",(s,d)=>{r=s,o=d??null}),{evidence:s=>{let d=Buffer.from(li(i.toString("utf8")),"utf8"),u=d.byteLength<=gy?d:d.subarray(d.byteLength-gy);return{marker:"guest_turn_failure_evidence",empty_output:i.byteLength===0,output_tail:u.toString("utf8"),exit_code:r,signal:o,duration_ms:Math.max(0,n()-t.startedAtMs),model_call_count:s}}}}var Ql;function N7(e){Ql=e;try{Co(CE(e),{recursive:!0}),$s(e,"")}catch{Ql=void 0}}function Ut(e){let t=`${JSON.stringify(e)}
265
+ `;if(process.stdout.write(t),Ql!==void 0)try{C7(Ql,t)}catch{}}function Vl(e,t,n,i){Ut({phase:"exit",ok:e,reason:li(t),turnMs:n,...i===void 0?{}:{evidence:i}})}function D7(e){return{id:e.id,name:e.name,baseUrl:e.baseUrl,envKey:e.envKey,wireApi:e.wireApi,...e.httpHeaders===void 0?{}:{httpHeaders:{...e.httpHeaders}},...e.envHttpHeaders===void 0?{}:{envHttpHeaders:{...e.envHttpHeaders}}}}function L7(e){if(e.sandbox!=="read-only")throw new Error(`guest cloud turn requires sandbox "read-only", got ${JSON.stringify(e.sandbox)}`);if(e.approvalPolicy!=="never")throw new Error(`guest cloud turn requires approvalPolicy "never", got ${JSON.stringify(e.approvalPolicy)}`)}function U7(e,t=Gl){let n=X_({command:"node",argsPrefix:[_E],kandanUrl:e.kandanUrl,authFilePath:fy,ownerUsername:e.ownerUsername,operatingMode:"text",cwd:e.cwd,threadId:e.threadId,agentSession:!0});return Kc(`ws://127.0.0.1:${e.appServerPort}`,{model:e.model,reasoningEffort:e.reasoningEffort,mcpServers:[n],neverEquivalentGranularApprovalPolicy:!0,...e.modelProvider===void 0?{}:{modelProvider:D7(e.modelProvider)},env:{CODEX_HOME:t,...TE(e)}})}function TE(e){let t=process.env[ly.llmProxyToken];return e.modelProvider===void 0||t===void 0||t===""?{}:{[e.modelProvider.envKey]:t}}function F7(e,t){let n=process.env[ly.mcpAuthFileContents];if(n===void 0||n==="")throw new Error("guest cloud turn missing MCP auth-cache (LINZUMI_CLOUD_MCP_AUTH_JSON)");Co(e,{recursive:!0,mode:448}),As(e,448),$s(t,n,{mode:384}),As(t,384)}function z7(e){try{ko(e,{recursive:!0,force:!0})}catch{}}var B7=64,K7=20,kE="My engine session for this thread was lost, so I rebuilt it from this thread's saved history at reduced fidelity. Tell me if I lost something important.";async function J7(e){if(e.config.threadId===void 0||e.config.threadId==="")throw new Error("guest thread rehydration requires the durable Linzumi thread id");let t=Wo(e.config.kandanUrl,e.mcpAuthPath);if(t===void 0)throw new Error("guest thread rehydration requires an agent token in the MCP auth file");let n=Jo({kandanUrl:e.config.kandanUrl,accessToken:t.accessToken,operatingMode:"text"}),i=[],r,o,a;for(let d=0;d<K7;d+=1){let u=await n.getThreadTranscript({thread_id:e.config.threadId,...a===void 0?{}:{cursor:a}}),l=Zc(u);if(l===void 0)throw new Error(`guest thread rehydration received a malformed durable transcript page ${d}`);if(i=[...l.nodes,...i],r=r??l.budget,o=o??l.threadTitle,!l.hasMore||l.cursor===void 0)break;a=l.cursor}if(i.length===0)throw new Error("guest thread rehydration durable transcript was empty");let s=Qc({nodes:i,budget:r,resumeFailure:e.resumeFailure,threadTitle:o,linzumiContext:void 0});if(s.items.length===0)throw new Error("guest thread rehydration compiled zero injection items");return s.items}async function W7(e){if(e.config.threadId===void 0||e.config.threadId==="")throw new Error("guest session rebuild notice requires a Linzumi thread id");let t=Wo(e.config.kandanUrl,e.mcpAuthPath);if(t===void 0)throw new Error("guest session rebuild notice requires an agent token in the MCP auth file");await Jo({kandanUrl:e.config.kandanUrl,accessToken:t.accessToken,operatingMode:"voice"}).sendThreadReply({thread_id:e.config.threadId,body:kE,client_message_id:e.notice.noticeId,payload:{structured:{kind:"agent_status_event",item_id:e.notice.noticeId,transcript_unit_id:`agent_status_event:${e.notice.noticeId}`,stream_state:"completed",event_kind:"status",title:"Rebuilt the agent session",body:kE,severity:"info",agent_provider:"codex",raw_provider_metadata:{provider_session_key:e.notice.threadId,resume_failure:e.notice.resumeFailure}}}})}function IE(e){try{let t=JSON.parse(ci(e,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))return{};let n={};for(let[i,r]of Object.entries(t))typeof r=="string"&&r!==""&&(n[i]=r);return n}catch{return{}}}function H7(e,t,n){try{let i=IE(e);delete i[t];let r=Object.entries(i),o=r.slice(Math.max(0,r.length-(B7-1)));o.push([t,n]),Co(CE(e),{recursive:!0}),$s(e,JSON.stringify(Object.fromEntries(o)))}catch{}}var G7=new Set(["turn/completed","turn/failed","turn/aborted"]),V7=2e3;function PE(e){let t=fe(fe(e)?.item);if(t===void 0||Z(t.type)!=="agentMessage")return"";let n=Z(t.text);return n!==void 0&&n!==""?n:(_t(t.content)??[]).map(o=>{let a=fe(o);if(a===void 0)return;let s=Z(a.type);if(!(s!=="text"&&s!=="output_text"&&s!=="input_text"))return Z(a.text)??Z(a.content)}).filter(o=>o!==void 0&&o!=="").join(`
33
266
 
34
- `)}function Bd(e){let n=_(_(e)?.item);if(n===void 0)return!1;let t=l(n.type);if(t!=="mcpToolCall"&&t!=="dynamicToolCall"&&t!=="collabAgentToolCall"||l(n.status)!=="completed"||n.error!==void 0&&n.error!==null||n.success===!1)return!1;let r=l(n.tool)??"",o=r.split("__").pop()??r;return o==="linzumi_agent_reply"||o==="linzumi_decline_document_action"}var Gd=15e3;function Wd(e){return/already_replied|no_active_asker_binding/i.test(e)}async function Hd(e){let n=e.body.trim();if(n==="")return"skipped";let t=Je(e.kandanUrl,e.mcpAuthPath);if(t===void 0)throw new Error("reply relay: no agent token in the guest MCP auth file");let r=async(i,s)=>{let a=new AbortController,d=setTimeout(()=>a.abort(),Gd);try{return await fetch(i,{...s,signal:a.signal})}finally{clearTimeout(d)}},o=$e({kandanUrl:e.kandanUrl,accessToken:t.accessToken,operatingMode:"text",fetchImpl:r});try{return await o.agentReply({body:n}),"posted"}catch(i){let s=i instanceof Error?i.message:String(i);if(Wd(s))return"already";throw new Error(`reply relay failed: ${s}`)}}var Vd=900,Qd=1e4,Zd=3,Yd=8e3;function Xd(e){return/\bHTTP 4\d\d\b/.test(e)||/\b(forbidden|not_agent_session|no_active_asker_binding|invalid_agent_turn_progress_request|body_required|already_replied)\b/i.test(e)}function eu(e){return async n=>{let t=Je(e.kandanUrl,e.mcpAuthPath);if(t===void 0)throw new Error("turn progress: no agent token in the guest MCP auth file");let r=async(i,s)=>{let a=new AbortController,d=setTimeout(()=>a.abort(),Qd);try{return await fetch(i,{...s,signal:a.signal})}finally{clearTimeout(d)}};return $e({kandanUrl:e.kandanUrl,accessToken:t.accessToken,operatingMode:"text",fetchImpl:r}).agentTurnProgress(n)}}function nu(e){let n=Date.now,t=e.flushIntervalMs??Vd,r=e.log??D,o=e.post??eu({kandanUrl:e.kandanUrl,mcpAuthPath:e.mcpAuthPath}),i=new Map,s=!1,a=0,d=0,u,c,f=!1,y=!1,v=(S,g)=>{let x=i.get(S);if(x!==void 0)return x;let w={kind:g,phase:"commentary",text:"",snapshotIndex:0,state:"streaming",dirty:!1,lastFlushMs:0,ackedState:void 0};return i.set(S,w),w},h=S=>S.state==="streaming"?S.lastFlushMs+t:0,p=async(S,g)=>{let x=g.text,w=g.state;g.dirty=!1,g.snapshotIndex+=1,g.lastFlushMs=n();try{return await o({stream_key:`${e.streamKeyPrefix}:${S}`,item_id:S,kind:g.kind,...g.kind==="codex_assistant_message"?{phase:g.phase}:{},body:x,stream_state:w,snapshot_index:g.snapshotIndex,...e.sourceSeq===void 0?{}:{source_seq:e.sourceSeq}}),d+=1,a=0,g.ackedState=w,!0}catch(T){a+=1;let R=T instanceof Error?T.message:String(T);return Xd(R)?(y=!0,s=!0,r({phase:"progress",outcome:"permanent_reject",message:le(R)}),!1):(r({phase:"progress",outcome:"post_failed",consecutive_failures:a,message:le(R)}),a>=Zd&&(s=!0,r({phase:"progress",outcome:"disabled"})),!1)}},m=async()=>{for(;;){if(s)return;let S=n(),g,x=!1;for(let[w,T]of i){if(!T.dirty||T.text===""||T.state!=="streaming"&&!f)continue;let R=h(T);R<=S?(await p(w,T),x=!0):g=g===void 0?R:Math.min(g,R)}if(!x){g!==void 0&&(clearTimeout(c),c=setTimeout(k,Math.max(10,g-n())),c.unref?.());return}}};function k(){s||f||u!==void 0||(u=m().catch(()=>{}).finally(()=>{u=void 0}))}return{onNotification:S=>{try{let g=_(S.params)??{};if(S.method==="item/agentMessage/delta"){let x=Qn(g);if(x!==void 0){let w=v(x.itemKey,"codex_assistant_message");w.phase=x.phase,w.text+=x.delta,w.dirty=!0,k()}return}if(S.method==="item/reasoning/textDelta"){let x=Zn(g);if(x!==void 0){let w=v(x.itemKey,"codex_reasoning");w.text+=x.delta,w.dirty=!0,k()}return}if(S.method==="item/completed"){let x=_(g.item),w=l(x?.type),T=l(x?.id);if(T===void 0)return;if(w==="agentMessage"){let R=_o(S.params),A=v(T,"codex_assistant_message");A.phase=Vn(x?.phase),R!==""&&(A.text=R),A.state="completed",A.dirty=!0,k()}else if(w==="reasoning"){let R=i.get(T);R!==void 0&&(R.state="completed",R.dirty=!0,k())}}}catch(g){r({phase:"progress",outcome:"notification_error",message:le(g instanceof Error?g.message:String(g))})}},finish:async S=>{try{let g=n()+(e.finishDeadlineMs??Yd),x=()=>new Promise(T=>setTimeout(T,Math.max(0,g-n())).unref?.());f=!0,clearTimeout(c),u!==void 0&&await Promise.race([u,x()]);for(let T of i.values())T.state==="streaming"&&T.text!==""&&(T.state=S);let w=250;for(;;){let T=[...i.entries()].filter(([,A])=>A.text!==""&&A.state!==A.ackedState);if(T.length===0||y||n()>=g)break;let R=!1;for(let[A,Ge]of T){if(y||n()>=g)break;await p(A,Ge)||(R=!0)}R&&!y&&n()<g&&await new Promise(A=>setTimeout(A,w))}r({phase:"progress",outcome:"finished",frames_posted:d,disabled:s})}catch(g){r({phase:"progress",outcome:"finish_error",message:le(g instanceof Error?g.message:String(g))})}}}}function tu(e){if(e==="item/commandExecution/requestApproval"||e==="item/fileChange/requestApproval")return{decision:"decline"}}async function ru(e,n,t){for(;;){if(t.exitCode!==null&&t.exitCode!==void 0)throw new Error(`codex app-server exited before it accepted a connection (code ${t.exitCode})`);try{return await Wr(e)}catch(r){if(Date.now()>=n)throw r;await new Promise(o=>setTimeout(o,Td))}}}var ou=360*60*1e3;function iu(e,n){try{for(let t of vd(e))try{let r=X(e,t);n-xd(r).mtimeMs>ou&&wd(r)}catch{}}catch{}}function su(e,n,t=co){ct(n);let r=X(e,`${n}.beat`),o=()=>{try{Be(r,`${Date.now()}
35
- `)}catch{}};try{ke(e,{recursive:!0})}catch{}iu(e,Date.now()),o();let i=setInterval(o,t);return i.unref?.(),()=>{clearInterval(i);try{we(r,{force:!0})}catch{}}}function au(e,n,t){try{ct(n),ke(e,{recursive:!0}),Be(X(e,`${n}.exit`),`${JSON.stringify({phase:"exit",ok:t.ok,reason:le(t.reason),turnMs:t.turnMs,...t.evidence===void 0?{}:{evidence:t.evidence}})}
36
- `)}catch{}}var So="guestTurnFailureEvidence";function du(e){if(!(typeof e!="object"||e===null))return e[So]}async function uu(e,n={}){let t=n.now??Date.now,r=n.secretsDir??at,o=n.mcpAuthPath??dt,i=n.codexHome??hn,s=n.threadMapPath??uo,a=n.modelCallLivenessWindowMs??Pd(process.env),d=n.activeLoopBudgetMs??Id(process.env),u=n.activeLoopEvidenceLimit??20;if(!Number.isSafeInteger(a)||a<=0)throw new Error(`guest model-call liveness window must be a positive integer number of milliseconds, got ${JSON.stringify(a)}`);if(!Number.isSafeInteger(d)||d<=0||d>_n)throw new Error(`guest active-loop budget must be an integer number of milliseconds between 1 and ${_n}, got ${JSON.stringify(d)}`);if(!Number.isSafeInteger(u)||u<=0)throw new Error(`guest active-loop evidence limit must be a positive integer, got ${JSON.stringify(u)}`);let c=t();Od(e);let f=e.turnNonce!==void 0&&e.turnNonce!==""?su(n.heartbeatDir??ut,e.turnNonce,n.heartbeatIntervalMs):void 0,y,v,h=0,p,m=()=>{if(p!==void 0)return p;if(v!==void 0)return p=v.evidence(h),D({phase:"guest_turn_failure_evidence",...p}),p},k=()=>{try{y?.pid!==void 0&&y.kill("SIGINT")}catch{}};try{Ld(r,o);let I=Fd(e,i),L=`ws://127.0.0.1:${e.appServerPort}`;n.spawnCodex===void 0&&ke(i,{recursive:!0,mode:448}),y=n.spawnCodex?n.spawnCodex(I):ht("codex",I,{cwd:e.cwd,env:{PATH:process.env.PATH??"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",...process.env.HOME===void 0?{}:{HOME:process.env.HOME},CODEX_HOME:i,...go(e)},stdio:["ignore","pipe","pipe"],detached:!1}),v=Ad(y,{startedAtMs:c,now:t});let S=await ru(L,c+kd,y);try{S.onRequest?.(b=>tu(b.method));let g=e.codexThreadId,x;if(g!==void 0&&g!==""){let b=yo(s)[g];if(b!==void 0){let F=un({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox,linzumiAgentSession:!0}}),q=await io({codex:S,codexThreadId:b,resumeOverrides:F,rebuildWhen:"missing-rollout-only",rehydration:{log:(z,he)=>D({phase:z,...he}),buildRehydrationItems:async z=>{let he=n.buildRehydrationItems===void 0?await $d({config:e,mcpAuthPath:o,resumeFailure:z}):await n.buildRehydrationItems();if(he.length===0)throw new Error("guest thread rehydration requires non-empty durable transcript items");return he},buildRehydrationText:async()=>{throw new Error("guest thread rehydration may not fall back to a non-transcript seed")}}});if(x=b,q.mode==="rehydrated"){let z={noticeId:`guest-codex-rebuilt-${yd()}`,threadId:b,resumeFailure:q.resumeFailure};await(n.onSessionRebuilt===void 0?Jd({config:e,mcpAuthPath:o,notice:z}):n.onSessionRebuilt(z))}if(q.mode==="resumed"?D({phase:"thread",mode:"resumed"}):D({phase:"thread",mode:"rehydrated",threadId:b}),x!==b)throw new Error("guest continuity invariant lost mapped thread id")}}if(x===void 0){let b=await S.request("thread/start",{cwd:e.cwd,serviceName:"kandan-cloud-agent",personality:"pragmatic",...un({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox,linzumiAgentSession:!0}})});if("error"in b)throw new Error(`thread/start failed: ${b.error.message}`);let F=l(_(_(b.result)?.thread)?.id);if(F===void 0)throw new Error("thread/start response did not include thread.id");x=F,g!==void 0&&g!==""&&Ud(s,g,x),D({phase:"thread",mode:"started"})}let w="",T=!1,R=!1,A,Ge=-1,bn=new Set,pe,fe,We=[],vn=nu({kandanUrl:e.kandanUrl,mcpAuthPath:o,streamKeyPrefix:e.turnNonce!==void 0&&e.turnNonce!==""?`cloud:${e.turnNonce}`:`cloud:${c}`,...e.sourceSeq===void 0?{}:{sourceSeq:e.sourceSeq},post:n.progressPost,flushIntervalMs:n.progressFlushIntervalMs,now:t}),Te,Co=new Promise((b,F)=>{Te={resolve:b,reject:F}}),He=()=>{pe!==void 0&&(clearTimeout(pe),pe=void 0)},xn=()=>{fe!==void 0&&(clearTimeout(fe),fe=void 0)},gt=()=>{He(),pe=setTimeout(()=>{pe=void 0,R||Te?.reject(new mt(a))},a),pe.unref?.()},yt=b=>{if(R){D({phase:"codex-exit",benign:!0});return}setTimeout(()=>{R||Te?.reject(b())},n.postTerminalGraceMs??zd).unref?.()};S.onNotification(b=>{if(D({phase:"notification",method:b.method}),vn.onNotification(b),A!==void 0){let q=Ed(b,x,A);q!==void 0&&q.totalTokens>Ge&&(Ge=q.totalTokens,q.priorCallTotalTokens!==void 0&&!bn.has(q.priorCallTotalTokens)&&(bn.add(q.priorCallTotalTokens),h+=1),gt())}if(b.method==="item/completed"){let q=_o(b.params);q!==""&&(w=q),Bd(b.params)&&(T=!0);let z=_(b.params),he=A!==void 0&&l(z?.threadId)===x&&l(z?.turnId)===A,Ro=_(z?.item),kn=l(Ro?.type),Re;switch(he?kn:void 0){case"agentMessage":q!==""&&(Re={kind:"narration"});break;case"mcpToolCall":case"dynamicToolCall":case"collabAgentToolCall":{Re={kind:"tool_call",tool_type:kn};break}case"commandExecution":{Re={kind:"tool_call",tool_type:kn};break}}Re!==void 0&&(We.push(Re),We.length>u&&We.shift())}if(!Kd.has(b.method))return;R=!0,He(),xn();let F=b.method==="turn/completed";Te?.resolve({ok:F,reason:b.method==="turn/completed"?"turn completed":`turn terminal: ${b.method}`,turnMs:t()-c})}),S.onClose?.(b=>yt(()=>new Error(`codex connection closed before a turn terminal: ${b?.message??"connection closed"}`))),y?.once("exit",b=>yt(()=>new Error(`codex app-server process exited mid-turn (code ${b})`)));let wn=await S.request("turn/start",{threadId:x,input:e.input,...Hn({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox,linzumiAgentSession:!0}})});if("error"in wn)throw new Error(`turn/start failed: ${wn.error.message}`);if(A=l(_(_(wn.result)?.turn)?.id),A===void 0)throw new Error("turn/start response did not include turn.id");gt(),fe=setTimeout(()=>{fe=void 0,R||(D({phase:"active-loop-budget-exceeded",code:"active_loop_budget_exceeded",budget_ms:d,evidence_limit:u,evidence:We}),k(),Te?.reject(new ft(d)))},d),fe.unref?.();let Ce;try{Ce=await Co}catch(b){throw He(),xn(),await vn.finish("failed"),b}let me=Ce;if(Ce.ok){let b=n.relayReply??Hd;try{let F=await b({kandanUrl:e.kandanUrl,mcpAuthPath:o,body:w});D({phase:"reply",relay:F,reply_tool_call_seen:T,captured_chars:w.length}),F==="skipped"&&!T&&(me={ok:!1,reason:"turn completed but no reply was posted: codex produced no visible output to relay and never called linzumi_agent_reply",turnMs:Ce.turnMs})}catch(F){let q=F instanceof Error?F.message:String(F);D({phase:"reply",relay:"failed",reason:q}),me={ok:!1,reason:q,turnMs:Ce.turnMs}}}if(await vn.finish(me.ok?"completed":"failed"),He(),xn(),!me.ok){let b=m();return{...me,...b===void 0?{}:{evidence:b}}}return me}finally{S.close()}}catch(I){let L=I instanceof Error?I:new Error(String(I)),S=m();throw S!==void 0&&Object.defineProperty(L,So,{value:S,enumerable:!1}),L}finally{f?.(),k(),jd(r)}}async function bo(e=process.argv,n={}){let t=e[2];if(t==="--selftest")return D({phase:"selftest",ok:!0,node:process.version}),0;if(t===void 0||t==="")return gn(!1,"missing turn config argv[2]",0),1;let r;try{r=so(t)}catch(a){return gn(!1,`config decode failed: ${a instanceof Error?a.message:String(a)}`,0),1}let o=n.heartbeatDir??ut;Md(X(o,"last-turn.debug.jsonl")),D({phase:"boot",turn_nonce:r.turnNonce??null,node:process.version});let i=n.runTurn??uu,s=a=>{r.turnNonce!==void 0&&r.turnNonce!==""&&au(o,r.turnNonce,a)};try{let a=await i(r);return s(a),gn(a.ok,a.reason,a.turnMs,a.evidence),a.ok?0:1}catch(a){let d=a instanceof Error?a.message:String(a),u=du(a);return s({ok:!1,reason:d,turnMs:0,evidence:u}),gn(!1,d,0,u),1}}var cu=600*1e3,vo=2e3;function te(e,n){let t=e[n]?.trim();if(t===void 0||t==="")throw new Error(`missing required hosted authorization environment: ${n}`);return t}async function re(e,n,t){let r=await fetch(e,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`hosted authorization callback failed with HTTP ${r.status}`)}function lu(e){return Fr(e)}function xo(e,n=Date.now){let t=Date.parse(e);if(!Number.isFinite(t))throw new Error("invalid hosted authorization expiry");return Math.min(cu,Math.max(0,t-n()))}function pu(e){try{let n=_(JSON.parse(e)),t=_(n?.tokens),r=l(t?.account_id)?.trim(),o=l(t?.id_token)?.trim();if(r===void 0||r===""||o===void 0)return;let i=o.split(".")[1];if(i===void 0)return;let s=_(JSON.parse(Buffer.from(i,"base64url").toString("utf8"))),a=l(s?.email)?.trim();if(a===void 0||a==="")return;let d=l(s?.["https://api.openai.com/auth"])??l(s?.plan_type);return{providerIdentity:r,email:a,...d===void 0?{}:{plan:d}}}catch{return}}function fu(e,n){try{let t=_(JSON.parse(e)),r=_(JSON.parse(n)),o=_(r?.oauthAccount);if(t===void 0||o===void 0)return;let i=l(o.accountUuid)?.trim()??l(o.organizationUuid)?.trim(),s=l(o.emailAddress)?.trim()??l(o.email)?.trim();if(i===void 0||i===""||s===void 0||s==="")return;let a=_(t.claudeAiOauth),d=l(a?.subscriptionType)??l(o.subscriptionType);return{credential:JSON.stringify({credentials:t,oauthAccount:o}),providerIdentity:i,email:s,...d===void 0?{}:{plan:d}}}catch{return}}async function mu(e=process.stdin){return new Promise((n,t)=>{let r="",o=()=>{e.removeListener("data",s),e.removeListener("end",a),e.removeListener("error",d)},i=()=>{let u=r.split(/\r?\n/u,1)[0]?.trim()??"";if(o(),u===""||Buffer.byteLength(u,"utf8")>4096){t(new Error("invalid hosted authorization code input"));return}n(u)},s=u=>{if(r+=u.toString(),Buffer.byteLength(r,"utf8")>4097){o(),t(new Error("invalid hosted authorization code input"));return}r.includes(`
37
- `)&&i()},a=()=>i(),d=()=>{o(),t(new Error("hosted authorization code input failed"))};e.on("data",s),e.once("end",a),e.once("error",d)})}async function wo(e=process.env,n=process.stdin){let t=te(e,"LINZUMI_HOSTED_AUTH_CODE_SOCKET"),r=await mu(n);await new Promise((o,i)=>{let s=_d(t);s.once("error",()=>i(new Error("hosted authorization code socket unavailable"))),s.once("connect",()=>s.end(`${r}
38
- `)),s.once("close",a=>{a||o()})})}async function hu(e,n){we(e,{force:!0});let t=!1,r=!1,o=Sd(i=>{let s="";i.on("data",a=>{if(t||r)return;if(s+=a.toString(),Buffer.byteLength(s,"utf8")>4097){r=!0,i.destroy(),n.kill("SIGTERM");return}if(!s.includes(`
39
- `))return;let d=s.split(/\r?\n/u,1)[0]?.trim()??"";if(d===""||n.stdin===null){r=!0,i.destroy(),n.kill("SIGTERM");return}n.stdin.write(`${d}
40
- `,u=>{if(u!=null){r=!0,n.kill("SIGTERM"),i.destroy();return}t=!0,i.end()})})});return await new Promise((i,s)=>{o.once("error",s),o.listen(e,i)}),ze(e,384),{delivered:()=>t,close:async()=>{await new Promise(i=>o.close(()=>i())),we(e,{force:!0})}}}async function ko(e=process.env,n={}){let t=te(e,"LINZUMI_HOSTED_AUTH_CALLBACK_URL"),r=te(e,"LINZUMI_HOSTED_AUTH_CALLBACK_TOKEN"),o=te(e,"LINZUMI_HOSTED_AUTH_ROOT"),i=te(e,"LINZUMI_HOSTED_AUTH_EXPIRES_AT"),s=te(e,"LINZUMI_HOSTED_AUTH_HARNESS"),a=te(e,"LINZUMI_HOSTED_AUTH_WORKER_ID");if(s==="claude_code"){let f=te(e,"LINZUMI_HOSTED_AUTH_CODE_SOCKET");await gu({env:e,callbackUrl:t,callbackToken:r,authRoot:o,expiresAt:i,workerId:a,codeSocketPath:f,deps:n});return}if(s!=="codex")throw new Error("unsupported hosted authorization harness");let d=xo(i),u=e.LINZUMI_HOSTED_AUTH_CODEX_BIN?.trim()||"codex",c=mo(X(o,"codex-home-"));ze(c,448);try{let f=ht(u,["login","--device-auth"],{cwd:c,env:{PATH:e.PATH,HOME:c,CODEX_HOME:c,NO_COLOR:"1"},stdio:["ignore","pipe","pipe"]}),y="",v,h=x=>{if(y=`${y}${x.toString()}`.slice(-16384),v!==void 0)return;let w=lu(y);w!==void 0&&(v=re(t,r,{event:"state",status:"waiting_for_user",verificationUrl:w.verificationUrl,userCode:w.userCode,workerId:a}))};f.stdout?.on("data",h),f.stderr?.on("data",h);let p=!1,m,k=setTimeout(()=>{p=!0,f.kill("SIGTERM"),m=setTimeout(()=>{f.kill("SIGKILL")},n.sigtermGraceMs??vo),m.unref?.()},d);k.unref?.();let I=await new Promise((x,w)=>{f.once("error",w),f.once("exit",x)}).finally(()=>{clearTimeout(k),m!==void 0&&clearTimeout(m)});await v;let L=X(c,"auth.json");if(p||I!==0||!pt(L)){await re(t,r,{event:"state",status:"failed"});return}let S=yn(L,"utf8"),g=pu(S);if(S.trim()===""||g===void 0){await re(t,r,{event:"state",status:"failed"});return}await re(t,r,{event:"completed",providerIdentity:g.providerIdentity,email:g.email,...g.plan===void 0?{}:{plan:g.plan},credential:S})}finally{we(c,{recursive:!0,force:!0})}}async function gu(e){let n=xo(e.expiresAt),t=e.env.LINZUMI_HOSTED_AUTH_CLAUDE_BIN?.trim()||"claude",r=mo(X(e.authRoot,"claude-home-"));ze(r,448);let o;try{let i=ht(t,["auth","login","--claudeai"],{cwd:r,env:{PATH:e.env.PATH,HOME:r,CLAUDE_CONFIG_DIR:r,BROWSER:"false",NO_COLOR:"1"},stdio:["pipe","pipe","pipe"]});o=await hu(e.codeSocketPath,i);let s="",a,d=!1,u=k=>{if(s=`${s}${k.toString()}`.slice(-16384),a===void 0){let I=s.match(/https:\/\/[^\s\u0000-\u001f\u007f]+/u)?.[0];I!==void 0&&(a=re(e.callbackUrl,e.callbackToken,{event:"state",status:"waiting_for_user",verificationUrl:I,workerId:e.workerId}))}/Invalid code\./u.test(s)&&(d=!0)};i.stdout?.on("data",u),i.stderr?.on("data",u);let c=!1,f,y=setTimeout(()=>{c=!0,i.kill("SIGTERM"),f=setTimeout(()=>i.kill("SIGKILL"),e.deps.sigtermGraceMs??vo),f.unref?.()},n);y.unref?.();let v=await new Promise((k,I)=>{i.once("error",I),i.once("exit",k)}).finally(()=>{clearTimeout(y),f!==void 0&&clearTimeout(f)});await a;let h=X(r,".credentials.json"),p=X(r,".claude.json");if(c||d||v!==0||!o.delivered()||!pt(h)||!pt(p)){await re(e.callbackUrl,e.callbackToken,{event:"state",status:"failed"});return}let m=fu(yn(h,"utf8"),yn(p,"utf8"));if(m===void 0){await re(e.callbackUrl,e.callbackToken,{event:"state",status:"failed"});return}await re(e.callbackUrl,e.callbackToken,{event:"completed",providerIdentity:m.providerIdentity,email:m.email,...m.plan===void 0?{}:{plan:m.plan},credential:m.credential})}finally{o!==void 0&&await o.close(),we(r,{recursive:!0,force:!0})}}function To(e){let n=!1,t=()=>{n||(n=!0,process.exit(e))};try{process.stdout.write("",t)}catch{t()}setTimeout(t,1e3).unref?.()}var yu=process.argv[2]==="--hosted-coding-account-auth"?ko().then(()=>0):process.argv[2]==="--hosted-coding-account-auth-submit"?wo().then(()=>0):bo(process.argv);yu.then(e=>{To(e)}).catch(e=>{process.stdout.write(`${JSON.stringify({phase:"exit",ok:!1,reason:e instanceof Error?e.message:String(e),turnMs:0})}
41
- `),To(1)});
267
+ `)}function Z7(e){let t=fe(fe(e)?.item);if(t===void 0)return!1;let n=Z(t.type);if(n!=="mcpToolCall"&&n!=="dynamicToolCall"&&n!=="collabAgentToolCall"||Z(t.status)!=="completed"||t.error!==void 0&&t.error!==null||t.success===!1)return!1;let i=Z(t.tool)??"",r=i.split("__").pop()??i;return r==="linzumi_agent_reply"||r==="linzumi_decline_document_action"}var Q7=15e3;function Y7(e){return/already_replied|no_active_asker_binding/i.test(e)}async function X7(e){let t=e.body.trim();if(t==="")return"skipped";let n=Wo(e.kandanUrl,e.mcpAuthPath);if(n===void 0)throw new Error("reply relay: no agent token in the guest MCP auth file");let i=async(o,a)=>{let s=new AbortController,d=setTimeout(()=>s.abort(),Q7);try{return await fetch(o,{...a,signal:s.signal})}finally{clearTimeout(d)}},r=Jo({kandanUrl:e.kandanUrl,accessToken:n.accessToken,operatingMode:"text",fetchImpl:i});try{return await r.agentReply({body:t}),"posted"}catch(o){let a=o instanceof Error?o.message:String(o);if(Y7(a))return"already";throw new Error(`reply relay failed: ${a}`)}}var eQ=900,tQ=1e4,nQ=3,rQ=8e3;function iQ(e){return/\bHTTP 4\d\d\b/.test(e)||/\b(forbidden|not_agent_session|no_active_asker_binding|invalid_agent_turn_progress_request|body_required|already_replied)\b/i.test(e)}function oQ(e){return async t=>{let n=Wo(e.kandanUrl,e.mcpAuthPath);if(n===void 0)throw new Error("turn progress: no agent token in the guest MCP auth file");let i=async(o,a)=>{let s=new AbortController,d=setTimeout(()=>s.abort(),tQ);try{return await fetch(o,{...a,signal:s.signal})}finally{clearTimeout(d)}};return Jo({kandanUrl:e.kandanUrl,accessToken:n.accessToken,operatingMode:"text",fetchImpl:i}).agentTurnProgress(t)}}function aQ(e){let t=Date.now,n=e.flushIntervalMs??eQ,i=e.log??Ut,r=e.post??oQ({kandanUrl:e.kandanUrl,mcpAuthPath:e.mcpAuthPath}),o=new Map,a=!1,s=0,d=0,u,l,p=!1,m=!1,f=(S,T)=>{let C=o.get(S);if(C!==void 0)return C;let _={kind:T,phase:"commentary",text:"",snapshotIndex:0,state:"streaming",dirty:!1,lastFlushMs:0,ackedState:void 0};return o.set(S,_),_},h=S=>S.state==="streaming"?S.lastFlushMs+n:0,y=async(S,T)=>{let C=T.text,_=T.state;T.dirty=!1,T.snapshotIndex+=1,T.lastFlushMs=t();try{return await r({stream_key:`${e.streamKeyPrefix}:${S}`,item_id:S,kind:T.kind,...T.kind==="codex_assistant_message"?{phase:T.phase}:{},body:C,stream_state:_,snapshot_index:T.snapshotIndex,...e.sourceSeq===void 0?{}:{source_seq:e.sourceSeq}}),d+=1,s=0,T.ackedState=_,!0}catch(k){s+=1;let I=k instanceof Error?k.message:String(k);return iQ(I)?(m=!0,a=!0,i({phase:"progress",outcome:"permanent_reject",message:li(I)}),!1):(i({phase:"progress",outcome:"post_failed",consecutive_failures:s,message:li(I)}),s>=nQ&&(a=!0,i({phase:"progress",outcome:"disabled"})),!1)}},w=async()=>{for(;;){if(a)return;let S=t(),T,C=!1;for(let[_,k]of o){if(!k.dirty||k.text===""||k.state!=="streaming"&&!p)continue;let I=h(k);I<=S?(await y(_,k),C=!0):T=T===void 0?I:Math.min(T,I)}if(!C){T!==void 0&&(clearTimeout(l),l=setTimeout(g,Math.max(10,T-t())),l.unref?.());return}}};function g(){a||p||u!==void 0||(u=w().catch(()=>{}).finally(()=>{u=void 0}))}return{onNotification:S=>{try{let T=fe(S.params)??{};if(S.method==="item/agentMessage/delta"){let C=Ic(T);if(C!==void 0){let _=f(C.itemKey,"codex_assistant_message");_.phase=C.phase,_.text+=C.delta,_.dirty=!0,g()}return}if(S.method==="item/reasoning/textDelta"){let C=Pc(T);if(C!==void 0){let _=f(C.itemKey,"codex_reasoning");_.text+=C.delta,_.dirty=!0,g()}return}if(S.method==="item/completed"){let C=fe(T.item),_=Z(C?.type),k=Z(C?.id);if(k===void 0)return;if(_==="agentMessage"){let I=PE(S.params),P=f(k,"codex_assistant_message");P.phase=Tc(C?.phase),I!==""&&(P.text=I),P.state="completed",P.dirty=!0,g()}else if(_==="reasoning"){let I=o.get(k);I!==void 0&&(I.state="completed",I.dirty=!0,g())}}}catch(T){i({phase:"progress",outcome:"notification_error",message:li(T instanceof Error?T.message:String(T))})}},finish:async S=>{try{let T=t()+(e.finishDeadlineMs??rQ),C=()=>new Promise(k=>setTimeout(k,Math.max(0,T-t())).unref?.());p=!0,clearTimeout(l),u!==void 0&&await Promise.race([u,C()]);for(let k of o.values())k.state==="streaming"&&k.text!==""&&(k.state=S);let _=250;for(;;){let k=[...o.entries()].filter(([,P])=>P.text!==""&&P.state!==P.ackedState);if(k.length===0||m||t()>=T)break;let I=!1;for(let[P,R]of k){if(m||t()>=T)break;await y(P,R)||(I=!0)}I&&!m&&t()<T&&await new Promise(P=>setTimeout(P,_))}i({phase:"progress",outcome:"finished",frames_posted:d,disabled:a})}catch(T){i({phase:"progress",outcome:"finish_error",message:li(T instanceof Error?T.message:String(T))})}}}}function sQ(e){if(e==="item/commandExecution/requestApproval"||e==="item/fileChange/requestApproval")return{decision:"decline"}}async function dQ(e,t,n){for(;;){if(n.exitCode!==null&&n.exitCode!==void 0)throw new Error(`codex app-server exited before it accepted a connection (code ${n.exitCode})`);try{return await Hc(e)}catch(i){if(Date.now()>=t)throw i;await new Promise(r=>setTimeout(r,R7))}}}var uQ=360*60*1e3;function lQ(e,t){try{for(let n of T7(e))try{let i=or(e,n);t-I7(i).mtimeMs>uQ&&P7(i)}catch{}}catch{}}function cQ(e,t,n=bE){hy(t);let i=or(e,`${t}.beat`),r=()=>{try{$s(i,`${Date.now()}
268
+ `)}catch{}};try{Co(e,{recursive:!0})}catch{}lQ(e,Date.now()),r();let o=setInterval(r,n);return o.unref?.(),()=>{clearInterval(o);try{ko(i,{force:!0})}catch{}}}function pQ(e,t,n){try{hy(t),Co(e,{recursive:!0}),$s(or(e,`${t}.exit`),`${JSON.stringify({phase:"exit",ok:n.ok,reason:li(n.reason),turnMs:n.turnMs,...n.evidence===void 0?{}:{evidence:n.evidence}})}
269
+ `)}catch{}}var EE="guestTurnFailureEvidence";function fQ(e){if(!(typeof e!="object"||e===null))return e[EE]}async function mQ(e,t={}){let n=t.now??Date.now,i=t.secretsDir??py,r=t.mcpAuthPath??fy,o=t.codexHome??Gl,a=t.threadMapPath??vE,s=t.modelCallLivenessWindowMs??M7(process.env),d=t.activeLoopBudgetMs??$7(process.env),u=t.activeLoopEvidenceLimit??20;if(!Number.isSafeInteger(s)||s<=0)throw new Error(`guest model-call liveness window must be a positive integer number of milliseconds, got ${JSON.stringify(s)}`);if(!Number.isSafeInteger(d)||d<=0||d>Zl)throw new Error(`guest active-loop budget must be an integer number of milliseconds between 1 and ${Zl}, got ${JSON.stringify(d)}`);if(!Number.isSafeInteger(u)||u<=0)throw new Error(`guest active-loop evidence limit must be a positive integer, got ${JSON.stringify(u)}`);let l=n();L7(e);let p=e.turnNonce!==void 0&&e.turnNonce!==""?cQ(t.heartbeatDir??my,e.turnNonce,t.heartbeatIntervalMs):void 0,m,f,h=0,y,w=()=>{if(y!==void 0)return y;if(f!==void 0)return y=f.evidence(h),Ut({phase:"guest_turn_failure_evidence",...y}),y},g=()=>{try{m?.pid!==void 0&&m.kill("SIGINT")}catch{}};try{F7(i,r);let v=U7(e,o),b=`ws://127.0.0.1:${e.appServerPort}`;t.spawnCodex===void 0&&Co(o,{recursive:!0,mode:448}),m=t.spawnCodex?t.spawnCodex(v):vy("codex",v,{cwd:e.cwd,env:{PATH:process.env.PATH??"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",...process.env.HOME===void 0?{}:{HOME:process.env.HOME},CODEX_HOME:o,...TE(e)},stdio:["ignore","pipe","pipe"],detached:!1}),f=q7(m,{startedAtMs:l,now:n});let S=await dQ(b,l+E7,m);try{S.onRequest?.(O=>sQ(O.method));let T=e.codexThreadId,C;if(T!==void 0&&T!==""){let O=IE(a)[T];if(O!==void 0){let ne=Vs({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox,linzumiAgentSession:!0}}),X=await Rv({codex:S,codexThreadId:O,resumeOverrides:ne,rebuildWhen:"missing-rollout-only",rehydration:{log:(we,Se)=>Ut({phase:we,...Se}),buildRehydrationItems:async we=>{let Se=t.buildRehydrationItems===void 0?await J7({config:e,mcpAuthPath:r,resumeFailure:we}):await t.buildRehydrationItems();if(Se.length===0)throw new Error("guest thread rehydration requires non-empty durable transcript items");return Se},buildRehydrationText:async()=>{throw new Error("guest thread rehydration may not fall back to a non-transcript seed")}}});if(C=O,X.mode==="rehydrated"){let we={noticeId:`guest-codex-rebuilt-${S7()}`,threadId:O,resumeFailure:X.resumeFailure};await(t.onSessionRebuilt===void 0?W7({config:e,mcpAuthPath:r,notice:we}):t.onSessionRebuilt(we))}if(X.mode==="resumed"?Ut({phase:"thread",mode:"resumed"}):Ut({phase:"thread",mode:"rehydrated",threadId:O}),C!==O)throw new Error("guest continuity invariant lost mapped thread id")}}if(C===void 0){let O=await S.request("thread/start",{cwd:e.cwd,serviceName:"kandan-cloud-agent",personality:"pragmatic",...Vs({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox,linzumiAgentSession:!0}})});if("error"in O)throw new Error(`thread/start failed: ${O.error.message}`);let ne=Z(fe(fe(O.result)?.thread)?.id);if(ne===void 0)throw new Error("thread/start response did not include thread.id");C=ne,T!==void 0&&T!==""&&H7(a,T,C),Ut({phase:"thread",mode:"started"})}let _="",k=!1,I=!1,P,R=-1,M=new Set,A,F,se=[],he=aQ({kandanUrl:e.kandanUrl,mcpAuthPath:r,streamKeyPrefix:e.turnNonce!==void 0&&e.turnNonce!==""?`cloud:${e.turnNonce}`:`cloud:${l}`,...e.sourceSeq===void 0?{}:{sourceSeq:e.sourceSeq},post:t.progressPost,flushIntervalMs:t.progressFlushIntervalMs,now:n}),ee,$e=new Promise((O,ne)=>{ee={resolve:O,reject:ne}}),be=()=>{A!==void 0&&(clearTimeout(A),A=void 0)},G=()=>{F!==void 0&&(clearTimeout(F),F=void 0)},$=()=>{be(),A=setTimeout(()=>{A=void 0,I||ee?.reject(new _y(s))},s),A.unref?.()},B=O=>{if(I){Ut({phase:"codex-exit",benign:!0});return}setTimeout(()=>{I||ee?.reject(O())},t.postTerminalGraceMs??V7).unref?.()};S.onNotification(O=>{if(Ut({phase:"notification",method:O.method}),he.onNotification(O),P!==void 0){let X=j7(O,C,P);X!==void 0&&X.totalTokens>R&&(R=X.totalTokens,X.priorCallTotalTokens!==void 0&&!M.has(X.priorCallTotalTokens)&&(M.add(X.priorCallTotalTokens),h+=1),$())}if(O.method==="item/completed"){let X=PE(O.params);X!==""&&(_=X),Z7(O.params)&&(k=!0);let we=fe(O.params),Se=P!==void 0&&Z(we?.threadId)===C&&Z(we?.turnId)===P,Je=fe(we?.item),j=Z(Je?.type),D;switch(Se?j:void 0){case"agentMessage":X!==""&&(D={kind:"narration"});break;case"mcpToolCall":case"dynamicToolCall":case"collabAgentToolCall":{D={kind:"tool_call",tool_type:j};break}case"commandExecution":{D={kind:"tool_call",tool_type:j};break}}D!==void 0&&(se.push(D),se.length>u&&se.shift())}if(!G7.has(O.method))return;I=!0,be(),G();let ne=O.method==="turn/completed";ee?.resolve({ok:ne,reason:O.method==="turn/completed"?"turn completed":`turn terminal: ${O.method}`,turnMs:n()-l})}),S.onClose?.(O=>B(()=>new Error(`codex connection closed before a turn terminal: ${O?.message??"connection closed"}`))),m?.once("exit",O=>B(()=>new Error(`codex app-server process exited mid-turn (code ${O})`)));let L=await S.request("turn/start",{threadId:C,input:e.input,...Cc({cwd:e.cwd,channelSession:{model:e.model,reasoningEffort:e.reasoningEffort,approvalPolicy:e.approvalPolicy,sandbox:e.sandbox,linzumiAgentSession:!0}})});if("error"in L)throw new Error(`turn/start failed: ${L.error.message}`);if(P=Z(fe(fe(L.result)?.turn)?.id),P===void 0)throw new Error("turn/start response did not include turn.id");$(),F=setTimeout(()=>{F=void 0,I||(Ut({phase:"active-loop-budget-exceeded",code:"active_loop_budget_exceeded",budget_ms:d,evidence_limit:u,evidence:se}),g(),ee?.reject(new yy(d)))},d),F.unref?.();let x;try{x=await $e}catch(O){throw be(),G(),await he.finish("failed"),O}let E=x;if(x.ok){let O=t.relayReply??X7;try{let ne=await O({kandanUrl:e.kandanUrl,mcpAuthPath:r,body:_});Ut({phase:"reply",relay:ne,reply_tool_call_seen:k,captured_chars:_.length}),ne==="skipped"&&!k&&(E={ok:!1,reason:"turn completed but no reply was posted: codex produced no visible output to relay and never called linzumi_agent_reply",turnMs:x.turnMs})}catch(ne){let X=ne instanceof Error?ne.message:String(ne);Ut({phase:"reply",relay:"failed",reason:X}),E={ok:!1,reason:X,turnMs:x.turnMs}}}if(await he.finish(E.ok?"completed":"failed"),be(),G(),!E.ok){let O=w();return{...E,...O===void 0?{}:{evidence:O}}}return E}finally{S.close()}}catch(v){let b=v instanceof Error?v:new Error(String(v)),S=w();throw S!==void 0&&Object.defineProperty(b,EE,{value:S,enumerable:!1}),b}finally{p?.(),g(),z7(i)}}async function RE(e=process.argv,t={}){let n=e[2];if(n==="--selftest")return Ut({phase:"selftest",ok:!0,node:process.version}),0;if(n===void 0||n==="")return Vl(!1,"missing turn config argv[2]",0),1;let i;try{i=yE(n)}catch(s){return Vl(!1,`config decode failed: ${s instanceof Error?s.message:String(s)}`,0),1}let r=t.heartbeatDir??my;N7(or(r,"last-turn.debug.jsonl")),Ut({phase:"boot",turn_nonce:i.turnNonce??null,node:process.version});let o=t.runTurn??mQ,a=s=>{i.turnNonce!==void 0&&i.turnNonce!==""&&pQ(r,i.turnNonce,s)};try{let s=await o(i);return a(s),Vl(s.ok,s.reason,s.turnMs,s.evidence),s.ok?0:1}catch(s){let d=s instanceof Error?s.message:String(s),u=fQ(s);return a({ok:!1,reason:d,turnMs:0,evidence:u}),Vl(!1,d,0,u),1}}var hQ=600*1e3,OE=2e3,gQ=15e3;function AE(e){switch(e.type){case"ready":return{status:"ready",defaultModel:e.catalog.defaultModel,models:e.catalog.models};case"empty":return{status:"empty"}}}async function yQ(e,t={startServer:lv,connect:Hc}){let n=await t.startServer(e.executable,e.authHome,{inheritEnv:!1,env:{PATH:e.env.PATH,HOME:e.authHome,CODEX_HOME:e.authHome}}),i,r;try{return i=await t.connect(n.url),AE(await Promise.race([Ev(i),new Promise((o,a)=>{r=setTimeout(()=>a(new Error("hosted Codex model discovery timed out")),gQ),r.unref?.()})]))}finally{r!==void 0&&clearTimeout(r),i?.close(),await n.stopAndWait()}}async function _Q(e,t={probe:gE,warn:console.warn}){let n=await t.probe({cwd:e.authHome,claudeBin:e.executable},{env:{PATH:e.env.PATH,HOME:e.authHome,CLAUDE_CONFIG_DIR:e.authHome},reportNotice:i=>t.warn(`hosted_claude_model_catalog_notice severity=${i.severity} key=${i.key}`)});if(n.status!=="logged_in"||n.modelCatalogDiscovery===void 0)return t.warn(`hosted_claude_model_catalog_unavailable status=${n.status} catalog_present=${n.modelCatalogDiscovery!==void 0}`),{status:"failed",failureCode:"discovery_failed"};switch(n.modelCatalogDiscovery.type){case"ready":case"empty":return AE(n.modelCatalogDiscovery);case"failed":return{status:"failed",failureCode:n.modelCatalogDiscovery.failureCode}}}async function $E(e){try{let t=e.deps.discoverModelCatalog;if(t!==void 0)return await t({harness:e.harness,authHome:e.authHome,executable:e.executable,env:e.env});switch(e.harness){case"codex":return await yQ(e);case"claude_code":return await _Q(e)}}catch(t){let n=t instanceof qn?"invalid_response":"discovery_failed";return(e.deps.warn??console.warn)(`hosted_model_catalog_discovery_failed harness=${e.harness} failure_code=${n} error_name=${t instanceof Error?t.name:"NonErrorThrow"}`),{status:"failed",failureCode:n}}}function Pr(e,t){let n=e[t]?.trim();if(n===void 0||n==="")throw new Error(`missing required hosted authorization environment: ${t}`);return n}async function Bn(e,t,n){let i=await fetch(e,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(n)});if(!i.ok)throw new Error(`hosted authorization callback failed with HTTP ${i.status}`)}function vQ(e){return U_(e)}function ME(e,t=Date.now){let n=Date.parse(e);if(!Number.isFinite(n))throw new Error("invalid hosted authorization expiry");return Math.min(hQ,Math.max(0,n-t()))}function jE(e){try{let t=fe(JSON.parse(e)),n=fe(t?.tokens),i=Z(n?.account_id)?.trim(),r=Z(n?.id_token)?.trim();if(i===void 0||i===""||r===void 0)return;let o=r.split(".")[1];if(o===void 0)return;let a=fe(JSON.parse(Buffer.from(o,"base64url").toString("utf8"))),s=Z(a?.email)?.trim();if(s===void 0||s==="")return;let d=Z(a?.["https://api.openai.com/auth"])??Z(a?.plan_type);return{providerIdentity:i,email:s,...d===void 0?{}:{plan:d}}}catch{return}}function qE(e,t){try{let n=fe(JSON.parse(e)),i=fe(JSON.parse(t)),r=fe(i?.oauthAccount);if(n===void 0||r===void 0)return;let o=Z(r.accountUuid)?.trim()??Z(r.organizationUuid)?.trim(),a=Z(r.emailAddress)?.trim()??Z(r.email)?.trim();if(o===void 0||o===""||a===void 0||a==="")return;let s=fe(n.claudeAiOauth),d=Z(s?.subscriptionType)??Z(r.subscriptionType);return{credential:JSON.stringify({credentials:n,oauthAccount:r}),providerIdentity:o,email:a,...d===void 0?{}:{plan:d}}}catch{return}}function bQ(e,t){if(!xo(e))return{status:"failed",reason:"credential_missing"};try{let n=ci(e,"utf8"),i=jE(n);return n.trim()===""||i===void 0?{status:"failed",reason:"credential_invalid"}:i.providerIdentity!==t?{status:"failed",reason:"provider_identity_changed"}:{status:"ready",credential:n,metadata:i}}catch{return{status:"failed",reason:"credential_unreadable"}}}function wQ(e,t,n){if(!xo(e)||!xo(t))return{status:"failed",reason:"credential_missing"};try{let i=qE(ci(e,"utf8"),ci(t,"utf8"));return i===void 0?{status:"failed",reason:"credential_invalid"}:i.providerIdentity!==n?{status:"failed",reason:"provider_identity_changed"}:{status:"ready",metadata:i}}catch{return{status:"failed",reason:"credential_unreadable"}}}async function SQ(e=process.stdin){return new Promise((t,n)=>{let i="",r=()=>{e.removeListener("data",a),e.removeListener("end",s),e.removeListener("error",d)},o=()=>{let u=i.split(/\r?\n/u,1)[0]?.trim()??"";if(r(),u===""||Buffer.byteLength(u,"utf8")>4096){n(new Error("invalid hosted authorization code input"));return}t(u)},a=u=>{if(i+=u.toString(),Buffer.byteLength(i,"utf8")>4097){r(),n(new Error("invalid hosted authorization code input"));return}i.includes(`
270
+ `)&&o()},s=()=>o(),d=()=>{r(),n(new Error("hosted authorization code input failed"))};e.on("data",a),e.once("end",s),e.once("error",d)})}async function NE(e=process.env,t=process.stdin){let n=Pr(e,"LINZUMI_HOSTED_AUTH_CODE_SOCKET"),i=await SQ(t);await new Promise((r,o)=>{let a=k7(n);a.once("error",()=>o(new Error("hosted authorization code socket unavailable"))),a.once("connect",()=>a.end(`${i}
271
+ `)),a.once("close",s=>{s||r()})})}async function kQ(e,t){ko(e,{force:!0});let n=!1,i=!1,r=x7(o=>{let a="";o.on("data",s=>{if(n||i)return;if(a+=s.toString(),Buffer.byteLength(a,"utf8")>4097){i=!0,o.destroy(),t.kill("SIGTERM");return}if(!a.includes(`
272
+ `))return;let d=a.split(/\r?\n/u,1)[0]?.trim()??"";if(d===""||t.stdin===null){i=!0,o.destroy(),t.kill("SIGTERM");return}t.stdin.write(`${d}
273
+ `,u=>{if(u!=null){i=!0,t.kill("SIGTERM"),o.destroy();return}n=!0,o.end()})})});return await new Promise((o,a)=>{r.once("error",a),r.listen(e,o)}),As(e,384),{delivered:()=>n,close:async()=>{await new Promise(o=>r.close(()=>o())),ko(e,{force:!0})}}}async function DE(e=process.env,t={}){let n=Pr(e,"LINZUMI_HOSTED_AUTH_CALLBACK_URL"),i=Pr(e,"LINZUMI_HOSTED_AUTH_CALLBACK_TOKEN"),r=Pr(e,"LINZUMI_HOSTED_AUTH_ROOT"),o=Pr(e,"LINZUMI_HOSTED_AUTH_EXPIRES_AT"),a=Pr(e,"LINZUMI_HOSTED_AUTH_HARNESS"),s=Pr(e,"LINZUMI_HOSTED_AUTH_WORKER_ID");if(a==="claude_code"){let p=Pr(e,"LINZUMI_HOSTED_AUTH_CODE_SOCKET");await xQ({env:e,callbackUrl:n,callbackToken:i,authRoot:r,expiresAt:o,workerId:s,codeSocketPath:p,deps:t});return}if(a!=="codex")throw new Error("unsupported hosted authorization harness");let d=ME(o),u=e.LINZUMI_HOSTED_AUTH_CODEX_BIN?.trim()||"codex",l=xE(or(r,"codex-home-"));As(l,448);try{let p=vy(u,["login","--device-auth"],{cwd:l,env:{PATH:e.PATH,HOME:l,CODEX_HOME:l,NO_COLOR:"1"},stdio:["ignore","pipe","pipe"]}),m="",f,h=k=>{if(m=`${m}${k.toString()}`.slice(-16384),f!==void 0)return;let I=vQ(m);I!==void 0&&(f=Bn(n,i,{event:"state",status:"waiting_for_user",verificationUrl:I.verificationUrl,userCode:I.userCode,workerId:s}))};p.stdout?.on("data",h),p.stderr?.on("data",h);let y=!1,w,g=setTimeout(()=>{y=!0,p.kill("SIGTERM"),w=setTimeout(()=>{p.kill("SIGKILL")},t.sigtermGraceMs??OE),w.unref?.()},d);g.unref?.();let v=await new Promise((k,I)=>{p.once("error",I),p.once("exit",k)}).finally(()=>{clearTimeout(g),w!==void 0&&clearTimeout(w)});await f;let b=or(l,"auth.json");if(y||v!==0||!xo(b)){await Bn(n,i,{event:"state",status:"failed"});return}let S=ci(b,"utf8"),T=jE(S);if(S.trim()===""||T===void 0){await Bn(n,i,{event:"state",status:"failed"});return}let C=await $E({harness:"codex",authHome:l,executable:u,env:e,deps:t}),_=bQ(b,T.providerIdentity);if(_.status==="failed"){(t.warn??console.warn)(`hosted_auth_credential_revalidation_failed harness=codex worker_id=${s} reason=${_.reason}`),await Bn(n,i,{event:"state",status:"failed"});return}await Bn(n,i,{event:"completed",providerIdentity:_.metadata.providerIdentity,email:_.metadata.email,..._.metadata.plan===void 0?{}:{plan:_.metadata.plan},modelCatalog:C,credential:_.credential})}finally{ko(l,{recursive:!0,force:!0})}}async function xQ(e){let t=ME(e.expiresAt),n=e.env.LINZUMI_HOSTED_AUTH_CLAUDE_BIN?.trim()||"claude",i=xE(or(e.authRoot,"claude-home-"));As(i,448);let r;try{let o=vy(n,["auth","login","--claudeai"],{cwd:i,env:{PATH:e.env.PATH,HOME:i,CLAUDE_CONFIG_DIR:i,BROWSER:"false",NO_COLOR:"1"},stdio:["pipe","pipe","pipe"]});r=await kQ(e.codeSocketPath,o);let a="",s,d=!1,u=b=>{if(a=`${a}${b.toString()}`.slice(-16384),s===void 0){let S=a.match(/https:\/\/[^\s\u0000-\u001f\u007f]+/u)?.[0];S!==void 0&&(s=Bn(e.callbackUrl,e.callbackToken,{event:"state",status:"waiting_for_user",verificationUrl:S,workerId:e.workerId}))}/Invalid code\./u.test(a)&&(d=!0)};o.stdout?.on("data",u),o.stderr?.on("data",u);let l=!1,p,m=setTimeout(()=>{l=!0,o.kill("SIGTERM"),p=setTimeout(()=>o.kill("SIGKILL"),e.deps.sigtermGraceMs??OE),p.unref?.()},t);m.unref?.();let f=await new Promise((b,S)=>{o.once("error",S),o.once("exit",b)}).finally(()=>{clearTimeout(m),p!==void 0&&clearTimeout(p)});await s;let h=or(i,".credentials.json"),y=or(i,".claude.json");if(l||d||f!==0||!r.delivered()||!xo(h)||!xo(y)){await Bn(e.callbackUrl,e.callbackToken,{event:"state",status:"failed"});return}let w=qE(ci(h,"utf8"),ci(y,"utf8"));if(w===void 0){await Bn(e.callbackUrl,e.callbackToken,{event:"state",status:"failed"});return}let g=await $E({harness:"claude_code",authHome:i,executable:n,env:e.env,deps:e.deps}),v=wQ(h,y,w.providerIdentity);if(v.status==="failed"){(e.deps.warn??console.warn)(`hosted_auth_credential_revalidation_failed harness=claude_code worker_id=${e.workerId} reason=${v.reason}`),await Bn(e.callbackUrl,e.callbackToken,{event:"state",status:"failed"});return}await Bn(e.callbackUrl,e.callbackToken,{event:"completed",providerIdentity:v.metadata.providerIdentity,email:v.metadata.email,...v.metadata.plan===void 0?{}:{plan:v.metadata.plan},modelCatalog:g,credential:v.metadata.credential})}finally{r!==void 0&&await r.close(),ko(i,{recursive:!0,force:!0})}}function LE(e){let t=!1,n=()=>{t||(t=!0,process.exit(e))};try{process.stdout.write("",n)}catch{n()}setTimeout(n,1e3).unref?.()}var CQ=process.argv[2]==="--hosted-coding-account-auth"?DE().then(()=>0):process.argv[2]==="--hosted-coding-account-auth-submit"?NE().then(()=>0):RE(process.argv);CQ.then(e=>{LE(e)}).catch(e=>{process.stdout.write(`${JSON.stringify({phase:"exit",ok:!1,reason:e instanceof Error?e.message:String(e),turnMs:0})}
274
+ `),LE(1)});