vibe64 0.1.66 → 0.1.67

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.
Files changed (122) hide show
  1. package/bin/run.js +1986 -1348
  2. package/bin/server.js +210 -207
  3. package/bin/upgrade-state.js +3862 -3786
  4. package/dist/assets/{GithubBrowserTabs-Bf5z_PiF.js → GithubBrowserTabs-CW3GBeJu.js} +1 -1
  5. package/dist/assets/{LocalDatabaseServer-CcfGbn7H.js → LocalDatabaseServer-DYh3UF9q.js} +1 -1
  6. package/dist/assets/{ShellOutlet-DPyl05um.js → ShellOutlet-DkLdtzJW.js} +1 -1
  7. package/dist/assets/{Vibe64AuthSettingsButton-CxJoeOhz.js → Vibe64AuthSettingsButton-Cksj7FS6.js} +1 -1
  8. package/dist/assets/{Vibe64AuthSettingsButton-DFfFPrd7.css → Vibe64AuthSettingsButton-DfKYI6ZS.css} +1 -1
  9. package/dist/assets/{Vibe64ConversationLog-jDb_ZvIF.js → Vibe64ConversationLog-BC0eDtUP.js} +1 -1
  10. package/dist/assets/{Vibe64DashboardShell-Ce1PNB37.js → Vibe64DashboardShell-DX5dOXAB.js} +1 -1
  11. package/dist/assets/{Vibe64DatabaseWorkspace-DiZDKEpx.js → Vibe64DatabaseWorkspace-8i-RDc9y.js} +1 -1
  12. package/dist/assets/{Vibe64FileArea-uRnIJ0Vp.js → Vibe64FileArea-EK5yUio3.js} +1 -1
  13. package/dist/assets/{Vibe64OutputControls-BF5kh2_h.js → Vibe64OutputControls--LB4G83q.js} +1 -1
  14. package/dist/assets/{Vibe64SessionFiles-CxgPB8RR.js → Vibe64SessionFiles-DVHGc7hd.js} +1 -1
  15. package/dist/assets/{Vibe64SessionSourceEditor-yaVu279S.js → Vibe64SessionSourceEditor-Bws5ihr-.js} +1 -1
  16. package/dist/assets/{Vibe64UiStoryboardView-DhbHkz8K.js → Vibe64UiStoryboardView-BmABkyG4.js} +1 -1
  17. package/dist/assets/{Vibe64UnavailableSessions-MmPF-Db1.js → Vibe64UnavailableSessions-C6Bkwsqk.js} +1 -1
  18. package/dist/assets/{_pageId_-Zif-veil.js → _pageId_-FjW-3sqF.js} +1 -1
  19. package/dist/assets/{_sessionId_-DOge-7SB.js → _sessionId_-4cH83Bfi.js} +1 -1
  20. package/dist/assets/_slug_-Cazfy5ui.js +14 -0
  21. package/dist/assets/_slug_-DQDycgFK.css +1 -0
  22. package/dist/assets/{access-DQcblrWN.js → access-mxcxtn7b.js} +1 -1
  23. package/dist/assets/{app-CzApKPmq.js → app-8zP_FAuO.js} +1 -1
  24. package/dist/assets/assistantRouting-Bbxguvre.js +3 -0
  25. package/dist/assets/{client-13v_yX07.js → client-C1i-bIgL.js} +1 -1
  26. package/dist/assets/{client-Dl6I6IVb.js → client-C7yZ1hEm.js} +1 -1
  27. package/dist/assets/{client-Dv4scw6i.js → client-CQ49uWhR.js} +1 -1
  28. package/dist/assets/{client-C8ZjqGdQ.js → client-D46Uu-YO.js} +2 -2
  29. package/dist/assets/{client-5JUUGxRd.js → client-DKNTl1to.js} +2 -2
  30. package/dist/assets/{dashboard-Dm_xwwqU.js → dashboard-CMtWKazq.js} +1 -1
  31. package/dist/assets/{english-definitions-DwTf_alg.js → english-definitions-DiyU9O9D.js} +1 -1
  32. package/dist/assets/{env-B7wB5nBn.js → env-LUc22Wgd.js} +1 -1
  33. package/dist/assets/{error-HfzrYwkQ.js → error-BccdQn04.js} +1 -1
  34. package/dist/assets/{error-CtOws2EC.js → error-DPDAz9Td.js} +1 -1
  35. package/dist/assets/{health-DIkOkzPe.js → health-CfMjMJFf.js} +1 -1
  36. package/dist/assets/{history-Ch597NiY.js → history-hX_kNskf.js} +1 -1
  37. package/dist/assets/{i18n-DcNQE3tT.js → i18n-Dq-ep9n7.js} +1 -1
  38. package/dist/assets/index-BJWiPV6i.css +1 -0
  39. package/dist/assets/{index-DcKFCaBZ.js → index-FVeEbKiO.js} +4 -4
  40. package/dist/assets/{integrations-CoNhnGvq.js → integrations-Ccb8EOEO.js} +14 -15
  41. package/dist/assets/{integrations-CwgrZgmM.css → integrations-CtnIjM1Y.css} +1 -1
  42. package/dist/assets/{issues-Cem4Yt47.js → issues-Bxtt7oqi.js} +1 -1
  43. package/dist/assets/{learning-CU2QyHrj.js → learning-BUx9jo91.js} +1 -1
  44. package/dist/assets/{pages-BzA58NoR.js → pages-D43zM2UW.js} +1 -1
  45. package/dist/assets/{project-files-BBKjl3wZ.js → project-files-BX3zZCcl.js} +1 -1
  46. package/dist/assets/{publish-UFjblZA3.js → publish-DatierL2.js} +1 -1
  47. package/dist/assets/{pull-requests-DibGk1GB.js → pull-requests-DNkOjcuy.js} +1 -1
  48. package/dist/assets/{settings-BjOnPYwD.js → settings-DbR9JIc3.js} +1 -1
  49. package/dist/assets/{useArchivedVibe64Sessions-CXKRFR2f.js → useArchivedVibe64Sessions-B8VDhA9F.js} +1 -1
  50. package/dist/assets/{useCommand-yOr3U8KF.js → useCommand-CfqxMb4C.js} +1 -1
  51. package/dist/assets/{useUiFeedback--0dLsslR.js → useUiFeedback-8Wvg7A_S.js} +1 -1
  52. package/dist/assets/{useVibe64ConversationLog-BB5tVtkt.js → useVibe64ConversationLog-7wgLlKG5.js} +2 -2
  53. package/dist/assets/useVibe64Learning-DkneotqS.js +5 -0
  54. package/dist/assets/{useVibe64SessionData-BSYF_TgH.js → useVibe64SessionData-DuJ-dHR8.js} +1 -1
  55. package/dist/assets/{useVibe64SessionSelection-CxZ3uEAf.js → useVibe64SessionSelection-BwjtqeIR.js} +1 -1
  56. package/dist/assets/vibe64SavedEnvValues-CCZew0j7.js +1 -0
  57. package/dist/assets/{vibe64SessionFocus-DGSVXipO.js → vibe64SessionFocus-B4diopOJ.js} +1 -1
  58. package/dist/index.html +10 -10
  59. package/docs/colleague-usage/ai-accounts.md +7 -7
  60. package/docs/colleague-usage/ai-model-setups.md +1 -1
  61. package/docs/colleague-usage/auto-workflow.md +60 -40
  62. package/docs/colleague-usage/chat-settings.md +115 -114
  63. package/docs/colleague-usage/coding-agent-history.md +9 -0
  64. package/docs/colleague-usage/coding-agent-recovery.md +3 -0
  65. package/docs/colleague-usage/coding-agents.md +10 -4
  66. package/docs/colleague-usage/developing-vibe64.md +11 -5
  67. package/docs/colleague-usage/development-env.md +74 -32
  68. package/docs/colleague-usage/github-work.md +3 -2
  69. package/docs/colleague-usage/integrations.md +2 -2
  70. package/docs/colleague-usage/main-chat-approvals.md +7 -6
  71. package/docs/colleague-usage/message-delivery-recovery.md +1 -1
  72. package/docs/colleague-usage/passes.md +215 -41
  73. package/docs/colleague-usage/plans.md +27 -16
  74. package/docs/colleague-usage/session-timeline.md +93 -0
  75. package/docs/colleague-usage/temporary-chats.md +6 -0
  76. package/docs/colleague-usage/ui-pass.md +29 -35
  77. package/node_modules/@jskit-ai/assistant-core/CHANGELOG.md +4 -0
  78. package/node_modules/@jskit-ai/assistant-core/package.json +1 -1
  79. package/node_modules/@jskit-ai/assistant-runtime/CHANGELOG.md +3 -0
  80. package/node_modules/@jskit-ai/assistant-runtime/package.json +1 -1
  81. package/node_modules/@jskit-ai/assistant-voice/package.json +1 -1
  82. package/node_modules/@jskit-ai/connector-google-calendar/CHANGELOG.md +1 -0
  83. package/node_modules/@jskit-ai/connector-google-calendar/package.json +1 -1
  84. package/node_modules/@jskit-ai/connector-google-calendar/patterns/calendar-cli/example/.env.example +1 -0
  85. package/node_modules/@jskit-ai/connectors-catalog/CHANGELOG.md +1 -0
  86. package/node_modules/@jskit-ai/connectors-catalog/package.json +1 -1
  87. package/node_modules/@jskit-ai/connectors-catalog/patterns/api-key-connection/PATTERN.md +4 -1
  88. package/node_modules/@jskit-ai/connectors-catalog/patterns/oauth-connection/PATTERN.md +3 -1
  89. package/node_modules/@jskit-ai/connectors-core/CHANGELOG.md +1 -0
  90. package/node_modules/@jskit-ai/connectors-core/README.md +3 -1
  91. package/node_modules/@jskit-ai/connectors-core/package.json +1 -1
  92. package/node_modules/@jskit-ai/http-runtime/package.json +1 -1
  93. package/node_modules/@jskit-ai/kernel/CHANGELOG.md +1 -0
  94. package/node_modules/@jskit-ai/kernel/package.json +3 -4
  95. package/node_modules/@jskit-ai/payments-core/CHANGELOG.md +1 -0
  96. package/node_modules/@jskit-ai/payments-core/locales/en.json +1 -1
  97. package/node_modules/@jskit-ai/payments-core/package.json +1 -1
  98. package/node_modules/@jskit-ai/realtime/CHANGELOG.md +1 -0
  99. package/node_modules/@jskit-ai/realtime/package.json +1 -1
  100. package/node_modules/@jskit-ai/realtime/patterns/realtime-application/example/.env.example +1 -0
  101. package/node_modules/@jskit-ai/resource-core/package.json +1 -1
  102. package/node_modules/@jskit-ai/uploads-runtime/package.json +1 -1
  103. package/node_modules/@local/vibe64-core/package.json +2 -0
  104. package/node_modules/@local/vibe64-execution/package.json +1 -0
  105. package/node_modules/@local/vibe64-execution/src/host/execHelper.js +715 -666
  106. package/node_modules/@local/vibe64-genesis/bin/vibe64-genesis-host-context +873 -872
  107. package/node_modules/@local/vibe64-genesis/src/server/agentSpecs.js +101 -85
  108. package/node_modules/@local/vibe64-genesis/src/server/index.js +615 -607
  109. package/node_modules/@local/vibe64-genesis/src/server/promptContext.js +159 -157
  110. package/node_modules/@local/vibe64-runtime/package.json +1 -0
  111. package/node_modules/@local/vibe64-runtime/src/server/codexAppServerProcess.js +901 -900
  112. package/node_modules/@local/vibe64-terminals/package.json +2 -1
  113. package/node_modules/@local/vibe64-terminals/src/server/opencodeSessionEnvironmentPlugin.js +22 -22
  114. package/node_modules/@local/vibe64-terminals/src/server/sessionWorkOperationCommand.js +382 -380
  115. package/package.json +15 -15
  116. package/server.bundle.mjs +40053 -39872
  117. package/dist/assets/_slug_-C71iAiR0.js +0 -14
  118. package/dist/assets/_slug_-CF1TPDUv.css +0 -1
  119. package/dist/assets/assistantRouting-CqIiQy21.js +0 -3
  120. package/dist/assets/index-C-6c5Af1.css +0 -1
  121. package/dist/assets/useVibe64Learning-iAAH83uG.js +0 -5
  122. package/dist/assets/vibe64SavedEnvValues-CgfMvj_h.js +0 -1
@@ -1,30 +1,30 @@
1
1
  import { createRequire as __vibe64CreateRequire } from 'node:module';const require=__vibe64CreateRequire(import.meta.url);
2
- var ys=Object.create;var mn=Object.defineProperty;var _s=Object.getOwnPropertyDescriptor;var gs=Object.getOwnPropertyNames;var Es=Object.getPrototypeOf,ws=Object.prototype.hasOwnProperty;var F=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){
3
- if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var J=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}};var Ss=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of gs(e))!ws.call(t,o)&&o!==r&&mn(t,o,{get:()=>e[o],
4
- enumerable:!(n=_s(e,o))||n.enumerable});return t};var he=(t,e,r)=>(r=t!=null?ys(Es(t)):{},Ss(e||!t||!t.__esModule?mn(r,"default",{value:t,enumerable:!0}):r,t));var le=J((Pf,Un)=>{"use strict";var zn=["nodebuffer","arraybuffer","fragments"],$n=typeof Blob<"u";$n&&zn.push("blob");Un.
5
- exports={BINARY_TYPES:zn,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:$n,
2
+ var gs=Object.create;var hn=Object.defineProperty;var Es=Object.getOwnPropertyDescriptor;var ws=Object.getOwnPropertyNames;var Ss=Object.getPrototypeOf,bs=Object.prototype.hasOwnProperty;var B=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){
3
+ if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var K=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}};var xs=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ws(e))!bs.call(t,o)&&o!==r&&hn(t,o,{get:()=>e[o],
4
+ enumerable:!(n=Es(e,o))||n.enumerable});return t};var he=(t,e,r)=>(r=t!=null?gs(Ss(t)):{},xs(e||!t||!t.__esModule?hn(r,"default",{value:t,enumerable:!0}):r,t));var ue=K((Nf,Bn)=>{"use strict";var Un=["nodebuffer","arraybuffer","fragments"],Vn=typeof Blob<"u";Vn&&Un.push("blob");Bn.
5
+ exports={BINARY_TYPES:Un,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Vn,
6
6
  kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol(
7
- "websocket"),NOOP:()=>{}}});var Ge=J((Rf,ft)=>{"use strict";var{EMPTY_BUFFER:aa}=le(),tr=Buffer[Symbol.species];function ca(t,e){if(t.length===0)return aa;
7
+ "websocket"),NOOP:()=>{}}});var We=K((kf,pt)=>{"use strict";var{EMPTY_BUFFER:ua}=ue(),rr=Buffer[Symbol.species];function la(t,e){if(t.length===0)return ua;
8
8
  if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let o=0;o<t.length;o++){let i=t[o];r.set(i,n),n+=i.length}
9
- return n<e?new tr(r.buffer,r.byteOffset,n):r}function Vn(t,e,r,n,o){for(let i=0;i<o;i++)r[n+i]=t[i]^e[i&3]}function Bn(t,e){
10
- for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function ua(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,
11
- t.byteOffset+t.length)}function rr(t){if(rr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?
12
- e=new tr(t):ArrayBuffer.isView(t)?e=new tr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),rr.readOnly=!1),e}ft.exports=
13
- {concat:ca,mask:Vn,toArrayBuffer:ua,toBuffer:rr,unmask:Bn};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=F("bufferutil");ft.
14
- exports.mask=function(e,r,n,o,i){i<48?Vn(e,r,n,o,i):t.mask(e,r,n,o,i)},ft.exports.unmask=function(e,r){e.length<32?Bn(e,
15
- r):t.unmask(e,r)}}catch{}});var Hn=J((Nf,qn)=>{"use strict";var Fn=Symbol("kDone"),nr=Symbol("kRun"),or=class{constructor(e){this[Fn]=()=>{this.pending--,
16
- this[nr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[nr]()}[nr](){if(this.pending!==
17
- this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Fn])}}};qn.exports=or});var Ne=J((kf,Jn)=>{"use strict";var We=F("zlib"),Gn=Ge(),la=Hn(),{kStatusCode:Wn}=le(),da=Buffer[Symbol.species],fa=Buffer.
18
- from([0,0,255,255]),mt=Symbol("permessage-deflate"),de=Symbol("total-length"),Pe=Symbol("callback"),ye=Symbol("buffers"),
19
- Re=Symbol("error"),pt,ir=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this.
9
+ return n<e?new rr(r.buffer,r.byteOffset,n):r}function Fn(t,e,r,n,o){for(let i=0;i<o;i++)r[n+i]=t[i]^e[i&3]}function qn(t,e){
10
+ for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function da(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,
11
+ t.byteOffset+t.length)}function nr(t){if(nr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?
12
+ e=new rr(t):ArrayBuffer.isView(t)?e=new rr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),nr.readOnly=!1),e}pt.exports=
13
+ {concat:la,mask:Fn,toArrayBuffer:da,toBuffer:nr,unmask:qn};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=B("bufferutil");pt.
14
+ exports.mask=function(e,r,n,o,i){i<48?Fn(e,r,n,o,i):t.mask(e,r,n,o,i)},pt.exports.unmask=function(e,r){e.length<32?qn(e,
15
+ r):t.unmask(e,r)}}catch{}});var Wn=K((jf,Gn)=>{"use strict";var Hn=Symbol("kDone"),or=Symbol("kRun"),ir=class{constructor(e){this[Hn]=()=>{this.pending--,
16
+ this[or]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[or]()}[or](){if(this.pending!==
17
+ this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Hn])}}};Gn.exports=ir});var ke=K((Df,Yn)=>{"use strict";var Xe=B("zlib"),Xn=We(),fa=Wn(),{kStatusCode:Jn}=ue(),pa=Buffer[Symbol.species],ma=Buffer.
18
+ from([0,0,255,255]),ht=Symbol("permessage-deflate"),le=Symbol("total-length"),Re=Symbol("callback"),ye=Symbol("buffers"),
19
+ Ne=Symbol("error"),mt,sr=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this.
20
20
  _options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=
21
- null,this._inflate=null,this.params=null,!pt){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:
22
- 10;pt=new la(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&
21
+ null,this._inflate=null,this.params=null,!mt){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:
22
+ 10;mt=new fa(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&
23
23
  (e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.
24
24
  serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=
25
25
  this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=
26
26
  this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this.
27
- _inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Pe];this._deflate.close(),this._deflate=
27
+ _inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Re];this._deflate.close(),this._deflate=
28
28
  null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,
29
29
  n=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===
30
30
  !1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits==
@@ -43,53 +43,53 @@ y a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let i=+o;i
43
43
  "${n}": ${o}`)}else if(n==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`I\
44
44
  nvalid value for parameter "${n}": ${o}`);o=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){
45
45
  if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);
46
- r[n]=o})}),e}decompress(e,r,n){pt.add(o=>{this._decompress(e,r,(i,s)=>{o(),n(i,s)})})}compress(e,r,n){pt.add(o=>{this._compress(
46
+ r[n]=o})}),e}decompress(e,r,n){mt.add(o=>{this._decompress(e,r,(i,s)=>{o(),n(i,s)})})}compress(e,r,n){mt.add(o=>{this._compress(
47
47
  e,r,(i,s)=>{o(),n(i,s)})})}_decompress(e,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_\
48
- window_bits`,s=typeof this.params[i]!="number"?We.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=We.createInflateRaw(
49
- {...this._options.zlibInflateOptions,windowBits:s}),this._inflate[mt]=this,this._inflate[de]=0,this._inflate[ye]=[],this.
50
- _inflate.on("error",ma),this._inflate.on("data",Xn)}this._inflate[Pe]=n,this._inflate.write(e),r&&this._inflate.write(fa),
51
- this._inflate.flush(()=>{let i=this._inflate[Re];if(i){this._inflate.close(),this._inflate=null,n(i);return}let s=Gn.concat(
52
- this._inflate[ye],this._inflate[de]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):
53
- (this._inflate[de]=0,this._inflate[ye]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,s)})}_compress(e,r,n){
48
+ window_bits`,s=typeof this.params[i]!="number"?Xe.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Xe.createInflateRaw(
49
+ {...this._options.zlibInflateOptions,windowBits:s}),this._inflate[ht]=this,this._inflate[le]=0,this._inflate[ye]=[],this.
50
+ _inflate.on("error",ya),this._inflate.on("data",Kn)}this._inflate[Re]=n,this._inflate.write(e),r&&this._inflate.write(ma),
51
+ this._inflate.flush(()=>{let i=this._inflate[Ne];if(i){this._inflate.close(),this._inflate=null,n(i);return}let s=Xn.concat(
52
+ this._inflate[ye],this._inflate[le]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):
53
+ (this._inflate[le]=0,this._inflate[ye]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,s)})}_compress(e,r,n){
54
54
  let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?
55
- We.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=We.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),
56
- this._deflate[de]=0,this._deflate[ye]=[],this._deflate.on("data",pa)}this._deflate[Pe]=n,this._deflate.write(e),this._deflate.
57
- flush(We.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Gn.concat(this._deflate[ye],this._deflate[de]);r&&(i=new da(i.
58
- buffer,i.byteOffset,i.length-4)),this._deflate[Pe]=null,this._deflate[de]=0,this._deflate[ye]=[],r&&this.params[`${o}_no\
59
- _context_takeover`]&&this._deflate.reset(),n(null,i)})}};Jn.exports=ir;function pa(t){this[ye].push(t),this[de]+=t.length}
60
- function Xn(t){if(this[de]+=t.length,this[mt]._maxPayload<1||this[de]<=this[mt]._maxPayload){this[ye].push(t);return}this[Re]=
61
- new RangeError("Max payload size exceeded"),this[Re].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Re][Wn]=1009,this.removeListener(
62
- "data",Xn),this.reset()}function ma(t){if(this[mt]._inflate=null,this[Re]){this[Pe](this[Re]);return}t[Wn]=1007,this[Pe](
63
- t)}});var ke=J((jf,ht)=>{"use strict";var{isUtf8:Kn}=F("buffer"),{hasBlob:ha}=le(),ya=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
55
+ Xe.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Xe.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),
56
+ this._deflate[le]=0,this._deflate[ye]=[],this._deflate.on("data",ha)}this._deflate[Re]=n,this._deflate.write(e),this._deflate.
57
+ flush(Xe.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Xn.concat(this._deflate[ye],this._deflate[le]);r&&(i=new pa(i.
58
+ buffer,i.byteOffset,i.length-4)),this._deflate[Re]=null,this._deflate[le]=0,this._deflate[ye]=[],r&&this.params[`${o}_no\
59
+ _context_takeover`]&&this._deflate.reset(),n(null,i)})}};Yn.exports=sr;function ha(t){this[ye].push(t),this[le]+=t.length}
60
+ function Kn(t){if(this[le]+=t.length,this[ht]._maxPayload<1||this[le]<=this[ht]._maxPayload){this[ye].push(t);return}this[Ne]=
61
+ new RangeError("Max payload size exceeded"),this[Ne].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ne][Jn]=1009,this.removeListener(
62
+ "data",Kn),this.reset()}function ya(t){if(this[ht]._inflate=null,this[Ne]){this[Re](this[Ne]);return}t[Jn]=1007,this[Re](
63
+ t)}});var je=K((Mf,yt)=>{"use strict";var{isUtf8:Qn}=B("buffer"),{hasBlob:_a}=ue(),ga=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
64
64
  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,
65
- 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 _a(t){return t>=
66
- 1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function sr(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===
65
+ 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 Ea(t){return t>=
66
+ 1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ar(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===
67
67
  0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){
68
68
  if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;
69
69
  r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&
70
- 240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function ga(t){return ha&&typeof t=="o\
70
+ 240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function wa(t){return _a&&typeof t=="o\
71
71
  bject"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]===
72
- "Blob"||t[Symbol.toStringTag]==="File")}ht.exports={isBlob:ga,isValidStatusCode:_a,isValidUTF8:sr,tokenChars:ya};if(Kn)ht.
73
- exports.isValidUTF8=function(t){return t.length<24?sr(t):Kn(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=F("utf-8-validate");
74
- ht.exports.isValidUTF8=function(e){return e.length<32?sr(e):t(e)}}catch{}});var dr=J((Df,no)=>{"use strict";var{Writable:Ea}=F("stream"),Yn=Ne(),{BINARY_TYPES:wa,EMPTY_BUFFER:Qn,kStatusCode:Sa,kWebSocket:ba}=le(),
75
- {concat:ar,toArrayBuffer:xa,unmask:Oa}=Ge(),{isValidStatusCode:Aa,isValidUTF8:Zn}=ke(),yt=Buffer[Symbol.species],te=0,eo=1,
76
- to=2,ro=3,cr=4,ur=5,_t=6,lr=class extends Ea{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==
77
- void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||wa[0],this._extensions=e.extensions||{},this._isServer=
72
+ "Blob"||t[Symbol.toStringTag]==="File")}yt.exports={isBlob:wa,isValidStatusCode:Ea,isValidUTF8:ar,tokenChars:ga};if(Qn)yt.
73
+ exports.isValidUTF8=function(t){return t.length<24?ar(t):Qn(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=B("utf-8-validate");
74
+ yt.exports.isValidUTF8=function(e){return e.length<32?ar(e):t(e)}}catch{}});var fr=K((Lf,io)=>{"use strict";var{Writable:Sa}=B("stream"),Zn=ke(),{BINARY_TYPES:ba,EMPTY_BUFFER:eo,kStatusCode:xa,kWebSocket:Oa}=ue(),
75
+ {concat:cr,toArrayBuffer:Aa,unmask:va}=We(),{isValidStatusCode:Ca,isValidUTF8:to}=je(),_t=Buffer[Symbol.species],te=0,ro=1,
76
+ no=2,oo=3,ur=4,lr=5,gt=6,dr=class extends Sa{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==
77
+ void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ba[0],this._extensions=e.extensions||{},this._isServer=
78
78
  !!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|
79
- 0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ba]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=
79
+ 0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Oa]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=
80
80
  !1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=
81
81
  0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=te}_write(e,r,n){
82
82
  if(this._opcode===8&&this._state==te)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){
83
83
  n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=
84
84
  e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this.
85
- _buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new yt(n.buffer,n.byteOffset+
86
- e,n.length-e),new yt(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],o=r.length-e;e>=n.length?
87
- r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),o),this._buffers[0]=new yt(n.buffer,n.byteOffset+
85
+ _buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new _t(n.buffer,n.byteOffset+
86
+ e,n.length-e),new _t(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],o=r.length-e;e>=n.length?
87
+ r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),o),this._buffers[0]=new _t(n.buffer,n.byteOffset+
88
88
  e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case te:this.getInfo(e);
89
- break;case eo:this.getPayloadLength16(e);break;case to:this.getPayloadLength64(e);break;case ro:this.getMask();break;case cr:
90
- this.getData(e);break;case ur:case _t:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<
89
+ break;case ro:this.getPayloadLength16(e);break;case no:this.getPayloadLength64(e);break;case oo:this.getMask();break;case ur:
90
+ this.getData(e);break;case lr:case gt:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<
91
91
  2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be\
92
- clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[Yn.extensionName]){
92
+ clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[Zn.extensionName]){
93
93
  let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&
94
94
  128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"\
95
95
  RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,
@@ -103,576 +103,577 @@ LOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcod
103
103
  ID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,
104
104
  this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(
105
105
  o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");
106
- e(o);return}this._payloadLength===126?this._state=eo:this._payloadLength===127?this._state=to:this.haveLength(e)}getPayloadLength16(e){
106
+ e(o);return}this._payloadLength===126?this._state=ro:this._payloadLength===127?this._state=no:this.haveLength(e)}getPayloadLength16(e){
107
107
  if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){
108
108
  if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.
109
109
  createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD\
110
110
  _LENGTH");e(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&
111
111
  this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>
112
112
  0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}
113
- this._masked?this._state=ro:this._state=cr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(
114
- 4),this._state=cr}getData(e){let r=Qn;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;
113
+ this._masked?this._state=oo:this._state=ur}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(
114
+ 4),this._state=ur}getData(e){let r=eo;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;
115
115
  return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&
116
- Oa(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){
116
+ va(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){
117
117
  let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this.
118
- _compressed){this._state=ur,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.
119
- push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Yn.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return r(
118
+ _compressed){this._state=lr,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.
119
+ push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Zn.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return r(
120
120
  o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(
121
121
  RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(s);return}this._fragments.push(i)}
122
122
  this.dataMessage(r),this._state===te&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=te;return}let r=this.
123
123
  _messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=
124
- 0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=ar(n,r):this._binaryType==="arraybuffer"?
125
- o=xa(ar(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=
126
- te):(this._state=_t,setImmediate(()=>{this.emit("message",o,!0),this._state=te,this.startLoop(e)}))}else{let o=ar(n,r);if(!this.
127
- _skipUTF8Validation&&!Zn(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}
128
- this._state===ur||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=te):(this._state=_t,setImmediate(()=>{
124
+ 0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=cr(n,r):this._binaryType==="arraybuffer"?
125
+ o=Aa(cr(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=
126
+ te):(this._state=gt,setImmediate(()=>{this.emit("message",o,!0),this._state=te,this.startLoop(e)}))}else{let o=cr(n,r);if(!this.
127
+ _skipUTF8Validation&&!to(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}
128
+ this._state===lr||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=te):(this._state=gt,setImmediate(()=>{
129
129
  this.emit("message",o,!1),this._state=te,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)
130
- this._loop=!1,this.emit("conclude",1005,Qn),this.end();else{let n=e.readUInt16BE(0);if(!Aa(n)){let i=this.createError(RangeError,
131
- `invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let o=new yt(e.buffer,e.byteOffset+2,e.length-
132
- 2);if(!this._skipUTF8Validation&&!Zn(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_U\
130
+ this._loop=!1,this.emit("conclude",1005,eo),this.end();else{let n=e.readUInt16BE(0);if(!Ca(n)){let i=this.createError(RangeError,
131
+ `invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let o=new _t(e.buffer,e.byteOffset+2,e.length-
132
+ 2);if(!this._skipUTF8Validation&&!to(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_U\
133
133
  TF8");r(i);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=te;return}this._allowSynchronousEvents?
134
- (this.emit(this._opcode===9?"ping":"pong",e),this._state=te):(this._state=_t,setImmediate(()=>{this.emit(this._opcode===
134
+ (this.emit(this._opcode===9?"ping":"pong",e),this._state=te):(this._state=gt,setImmediate(()=>{this.emit(this._opcode===
135
135
  9?"ping":"pong",e),this._state=te,this.startLoop(r)}))}createError(e,r,n,o,i){this._loop=!1,this._errored=!0;let s=new e(
136
- n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(s,this.createError),s.code=i,s[Sa]=o,s}};no.exports=
137
- lr});var mr=J((Lf,so)=>{"use strict";var{Duplex:Mf}=F("stream"),{randomFillSync:va}=F("crypto"),{types:{isUint8Array:Ca}}=F("util"),
138
- oo=Ne(),{EMPTY_BUFFER:Ta,kWebSocket:Ia,NOOP:Pa}=le(),{isBlob:je,isValidStatusCode:Ra}=ke(),{mask:io,toBuffer:Se}=Ge(),re=Symbol(
139
- "kByteLength"),Na=Buffer.alloc(4),gt=8*1024,be,De=gt,ie=0,ka=1,ja=2,fr=class t{constructor(e,r,n){this._extensions=r||{},
136
+ n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(s,this.createError),s.code=i,s[xa]=o,s}};io.exports=
137
+ dr});var hr=K(($f,co)=>{"use strict";var{Duplex:zf}=B("stream"),{randomFillSync:Ta}=B("crypto"),{types:{isUint8Array:Ia}}=B("util"),
138
+ so=ke(),{EMPTY_BUFFER:Pa,kWebSocket:Ra,NOOP:Na}=ue(),{isBlob:De,isValidStatusCode:ka}=je(),{mask:ao,toBuffer:be}=We(),re=Symbol(
139
+ "kByteLength"),ja=Buffer.alloc(4),Et=8*1024,xe,Me=Et,ne=0,Da=1,Ma=2,pr=class t{constructor(e,r,n){this._extensions=r||{},
140
140
  n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this.
141
- _bufferedBytes=0,this._queue=[],this._state=ie,this.onerror=Pa,this[Ia]=void 0}static frame(e,r){let n,o=!1,i=2,s=!1;r.mask&&
142
- (n=r.maskBuffer||Na,r.generateMask?r.generateMask(n):(De===gt&&(be===void 0&&(be=Buffer.alloc(gt)),va(be,0,gt),De=0),n[0]=
143
- be[De++],n[1]=be[De++],n[2]=be[De++],n[3]=be[De++]),s=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!r.mask||
141
+ _bufferedBytes=0,this._queue=[],this._state=ne,this.onerror=Na,this[Ra]=void 0}static frame(e,r){let n,o=!1,i=2,s=!1;r.mask&&
142
+ (n=r.maskBuffer||ja,r.generateMask?r.generateMask(n):(Me===Et&&(xe===void 0&&(xe=Buffer.alloc(Et)),Ta(xe,0,Et),Me=0),n[0]=
143
+ xe[Me++],n[1]=xe[Me++],n[2]=xe[Me++],n[3]=xe[Me++]),s=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!r.mask||
144
144
  s)&&r[re]!==void 0?a=r[re]:(e=Buffer.from(e),a=e.length):(a=e.length,o=r.mask&&r.readOnly&&!s);let c=a;a>=65536?(i+=8,c=
145
145
  127):a>125&&(i+=2,c=126);let u=Buffer.allocUnsafe(o?a+i:i);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=
146
146
  c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),r.mask?(u[1]|=128,u[i-4]=n[0],u[i-3]=n[1],u[i-
147
- 2]=n[2],u[i-1]=n[3],s?[u,e]:o?(io(e,n,u,i,a),[u]):(io(e,n,e,0,a),[u,e])):[u,e]}close(e,r,n,o){let i;if(e===void 0)i=Ta;else{
148
- if(typeof e!="number"||!Ra(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.
147
+ 2]=n[2],u[i-1]=n[3],s?[u,e]:o?(ao(e,n,u,i,a),[u]):(ao(e,n,e,0,a),[u,e])):[u,e]}close(e,r,n,o){let i;if(e===void 0)i=Pa;else{
148
+ if(typeof e!="number"||!ka(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.
149
149
  length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The m\
150
150
  essage must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof r=="string")i.write(
151
- r,2);else if(Ca(r))i.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[re]:i.
151
+ r,2);else if(Ia(r))i.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[re]:i.
152
152
  length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==
153
- ie?this.enqueue([this.dispatch,i,!1,s,o]):this.sendFrame(t.frame(i,s),o)}ping(e,r,n){let o,i;if(typeof e=="string"?(o=Buffer.
154
- byteLength(e),i=!1):je(e)?(o=e.size,i=!1):(e=Se(e),o=e.length,i=Se.readOnly),o>125)throw new RangeError("The data size m\
153
+ ne?this.enqueue([this.dispatch,i,!1,s,o]):this.sendFrame(t.frame(i,s),o)}ping(e,r,n){let o,i;if(typeof e=="string"?(o=Buffer.
154
+ byteLength(e),i=!1):De(e)?(o=e.size,i=!1):(e=be(e),o=e.length,i=be.readOnly),o>125)throw new RangeError("The data size m\
155
155
  ust not be greater than 125 bytes");let s={[re]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,
156
- opcode:9,readOnly:i,rsv1:!1};je(e)?this._state!==ie?this.enqueue([this.getBlobData,e,!1,s,n]):this.getBlobData(e,!1,s,n):
157
- this._state!==ie?this.enqueue([this.dispatch,e,!1,s,n]):this.sendFrame(t.frame(e,s),n)}pong(e,r,n){let o,i;if(typeof e==
158
- "string"?(o=Buffer.byteLength(e),i=!1):je(e)?(o=e.size,i=!1):(e=Se(e),o=e.length,i=Se.readOnly),o>125)throw new RangeError(
156
+ opcode:9,readOnly:i,rsv1:!1};De(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,s,n]):this.getBlobData(e,!1,s,n):
157
+ this._state!==ne?this.enqueue([this.dispatch,e,!1,s,n]):this.sendFrame(t.frame(e,s),n)}pong(e,r,n){let o,i;if(typeof e==
158
+ "string"?(o=Buffer.byteLength(e),i=!1):De(e)?(o=e.size,i=!1):(e=be(e),o=e.length,i=be.readOnly),o>125)throw new RangeError(
159
159
  "The data size must not be greater than 125 bytes");let s={[re]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this.
160
- _maskBuffer,opcode:10,readOnly:i,rsv1:!1};je(e)?this._state!==ie?this.enqueue([this.getBlobData,e,!1,s,n]):this.getBlobData(
161
- e,!1,s,n):this._state!==ie?this.enqueue([this.dispatch,e,!1,s,n]):this.sendFrame(t.frame(e,s),n)}send(e,r,n){let o=this.
162
- _extensions[oo.extensionName],i=r.binary?2:1,s=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):je(e)?(a=
163
- e.size,c=!1):(e=Se(e),a=e.length,c=Se.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"\
160
+ _maskBuffer,opcode:10,readOnly:i,rsv1:!1};De(e)?this._state!==ne?this.enqueue([this.getBlobData,e,!1,s,n]):this.getBlobData(
161
+ e,!1,s,n):this._state!==ne?this.enqueue([this.dispatch,e,!1,s,n]):this.sendFrame(t.frame(e,s),n)}send(e,r,n){let o=this.
162
+ _extensions[so.extensionName],i=r.binary?2:1,s=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):De(e)?(a=
163
+ e.size,c=!1):(e=be(e),a=e.length,c=be.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"\
164
164
  server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=o._threshold),this._compress=s):(s=!1,i=0),r.fin&&(this.
165
165
  _firstFragment=!0);let u={[re]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:i,
166
- readOnly:c,rsv1:s};je(e)?this._state!==ie?this.enqueue([this.getBlobData,e,this._compress,u,n]):this.getBlobData(e,this.
167
- _compress,u,n):this._state!==ie?this.enqueue([this.dispatch,e,this._compress,u,n]):this.dispatch(e,this._compress,u,n)}getBlobData(e,r,n,o){
168
- this._bufferedBytes+=n[re],this._state=ja,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socke\
169
- t was closed while the blob was being read");process.nextTick(pr,this,a,o);return}this._bufferedBytes-=n[re];let s=Se(i);
170
- r?this.dispatch(s,r,n,o):(this._state=ie,this.sendFrame(t.frame(s,n),o),this.dequeue())}).catch(i=>{process.nextTick(Da,
171
- this,i,o)})}dispatch(e,r,n,o){if(!r){this.sendFrame(t.frame(e,n),o);return}let i=this._extensions[oo.extensionName];this.
172
- _bufferedBytes+=n[re],this._state=ka,i.compress(e,n.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket w\
173
- as closed while data was being compressed");pr(this,c,o);return}this._bufferedBytes-=n[re],this._state=ie,n.readOnly=!1,
174
- this.sendFrame(t.frame(a,n),o),this.dequeue()})}dequeue(){for(;this._state===ie&&this._queue.length;){let e=this._queue.
166
+ readOnly:c,rsv1:s};De(e)?this._state!==ne?this.enqueue([this.getBlobData,e,this._compress,u,n]):this.getBlobData(e,this.
167
+ _compress,u,n):this._state!==ne?this.enqueue([this.dispatch,e,this._compress,u,n]):this.dispatch(e,this._compress,u,n)}getBlobData(e,r,n,o){
168
+ this._bufferedBytes+=n[re],this._state=Ma,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socke\
169
+ t was closed while the blob was being read");process.nextTick(mr,this,a,o);return}this._bufferedBytes-=n[re];let s=be(i);
170
+ r?this.dispatch(s,r,n,o):(this._state=ne,this.sendFrame(t.frame(s,n),o),this.dequeue())}).catch(i=>{process.nextTick(La,
171
+ this,i,o)})}dispatch(e,r,n,o){if(!r){this.sendFrame(t.frame(e,n),o);return}let i=this._extensions[so.extensionName];this.
172
+ _bufferedBytes+=n[re],this._state=Da,i.compress(e,n.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket w\
173
+ as closed while data was being compressed");mr(this,c,o);return}this._bufferedBytes-=n[re],this._state=ne,n.readOnly=!1,
174
+ this.sendFrame(t.frame(a,n),o),this.dequeue()})}dequeue(){for(;this._state===ne&&this._queue.length;){let e=this._queue.
175
175
  shift();this._bufferedBytes-=e[3][re],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][re],this.
176
176
  _queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this.
177
- _socket.uncork()):this._socket.write(e[0],r)}};so.exports=fr;function pr(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<
178
- t._queue.length;n++){let o=t._queue[n],i=o[o.length-1];typeof i=="function"&&i(e)}}function Da(t,e,r){pr(t,e,r),t.onerror(
179
- e)}});var yo=J((zf,ho)=>{"use strict";var{kForOnEventAttribute:Xe,kListener:hr}=le(),ao=Symbol("kCode"),co=Symbol("kData"),uo=Symbol(
180
- "kError"),lo=Symbol("kMessage"),fo=Symbol("kReason"),Me=Symbol("kTarget"),po=Symbol("kType"),mo=Symbol("kWasClean"),fe=class{constructor(e){
181
- this[Me]=null,this[po]=e}get target(){return this[Me]}get type(){return this[po]}};Object.defineProperty(fe.prototype,"t\
182
- arget",{enumerable:!0});Object.defineProperty(fe.prototype,"type",{enumerable:!0});var xe=class extends fe{constructor(e,r={}){
183
- super(e),this[ao]=r.code===void 0?0:r.code,this[fo]=r.reason===void 0?"":r.reason,this[mo]=r.wasClean===void 0?!1:r.wasClean}get code(){
184
- return this[ao]}get reason(){return this[fo]}get wasClean(){return this[mo]}};Object.defineProperty(xe.prototype,"code",
185
- {enumerable:!0});Object.defineProperty(xe.prototype,"reason",{enumerable:!0});Object.defineProperty(xe.prototype,"wasCle\
186
- an",{enumerable:!0});var Le=class extends fe{constructor(e,r={}){super(e),this[uo]=r.error===void 0?null:r.error,this[lo]=
187
- r.message===void 0?"":r.message}get error(){return this[uo]}get message(){return this[lo]}};Object.defineProperty(Le.prototype,
188
- "error",{enumerable:!0});Object.defineProperty(Le.prototype,"message",{enumerable:!0});var Je=class extends fe{constructor(e,r={}){
189
- super(e),this[co]=r.data===void 0?null:r.data}get data(){return this[co]}};Object.defineProperty(Je.prototype,"data",{enumerable:!0});
190
- var Ma={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Xe]&&o[hr]===e&&!o[Xe])return;let n;if(t==="mess\
191
- age")n=function(i,s){let a=new Je("message",{data:s?i:i.toString()});a[Me]=this,Et(e,this,a)};else if(t==="close")n=function(i,s){
192
- let a=new xe("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Me]=this,Et(
193
- e,this,a)};else if(t==="error")n=function(i){let s=new Le("error",{error:i,message:i.message});s[Me]=this,Et(e,this,s)};else if(t===
194
- "open")n=function(){let i=new fe("open");i[Me]=this,Et(e,this,i)};else return;n[Xe]=!!r[Xe],n[hr]=e,r.once?this.once(t,n):
195
- this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[hr]===e&&!r[Xe]){this.removeListener(t,r);break}}};
196
- ho.exports={CloseEvent:xe,ErrorEvent:Le,Event:fe,EventTarget:Ma,MessageEvent:Je};function Et(t,e,r){typeof t=="object"&&
197
- t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var wt=J(($f,_o)=>{"use strict";var{tokenChars:Ke}=ke();function ce(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function La(t){
198
- let e=Object.create(null),r=Object.create(null),n=!1,o=!1,i=!1,s,a,c=-1,u=-1,l=-1,p=0;for(;p<t.length;p++)if(u=t.charCodeAt(
199
- p),s===void 0)if(l===-1&&Ke[u]===1)c===-1&&(c=p);else if(p!==0&&(u===32||u===9))l===-1&&c!==-1&&(l=p);else if(u===59||u===
200
- 44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1&&(l=p);let h=t.slice(c,l);u===44?(ce(e,
201
- h,r),r=Object.create(null)):s=h,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)
202
- if(l===-1&&Ke[u]===1)c===-1&&(c=p);else if(u===32||u===9)l===-1&&c!==-1&&(l=p);else if(u===59||u===44){if(c===-1)throw new SyntaxError(
203
- `Unexpected character at index ${p}`);l===-1&&(l=p),ce(r,t.slice(c,l),!0),u===44&&(ce(e,s,r),r=Object.create(null),s=void 0),
204
- c=l=-1}else if(u===61&&c!==-1&&l===-1)a=t.slice(c,p),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){
205
- if(Ke[u]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),o=!1}else if(i)if(Ke[u]===
206
- 1)c===-1&&(c=p);else if(u===34&&c!==-1)i=!1,l=p;else if(u===92)o=!0;else throw new SyntaxError(`Unexpected character at \
207
- index ${p}`);else if(u===34&&t.charCodeAt(p-1)===61)i=!0;else if(l===-1&&Ke[u]===1)c===-1&&(c=p);else if(c!==-1&&(u===32||
208
- u===9))l===-1&&(l=p);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1&&
209
- (l=p);let h=t.slice(c,l);n&&(h=h.replace(/\\/g,""),n=!1),ce(r,a,h),u===44&&(ce(e,s,r),r=Object.create(null),s=void 0),a=
210
- void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||i||u===32||u===9)throw new SyntaxError(
211
- "Unexpected end of input");l===-1&&(l=p);let d=t.slice(c,l);return s===void 0?ce(e,d,r):(a===void 0?ce(r,d,!0):n?ce(r,a,
212
- d.replace(/\\/g,"")):ce(r,a,d),ce(e,s,r)),e}function za(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(
177
+ _socket.uncork()):this._socket.write(e[0],r)}};co.exports=pr;function mr(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<
178
+ t._queue.length;n++){let o=t._queue[n],i=o[o.length-1];typeof i=="function"&&i(e)}}function La(t,e,r){mr(t,e,r),t.onerror(
179
+ e)}});var go=K((Uf,_o)=>{"use strict";var{kForOnEventAttribute:Je,kListener:yr}=ue(),uo=Symbol("kCode"),lo=Symbol("kData"),fo=Symbol(
180
+ "kError"),po=Symbol("kMessage"),mo=Symbol("kReason"),Le=Symbol("kTarget"),ho=Symbol("kType"),yo=Symbol("kWasClean"),de=class{constructor(e){
181
+ this[Le]=null,this[ho]=e}get target(){return this[Le]}get type(){return this[ho]}};Object.defineProperty(de.prototype,"t\
182
+ arget",{enumerable:!0});Object.defineProperty(de.prototype,"type",{enumerable:!0});var Oe=class extends de{constructor(e,r={}){
183
+ super(e),this[uo]=r.code===void 0?0:r.code,this[mo]=r.reason===void 0?"":r.reason,this[yo]=r.wasClean===void 0?!1:r.wasClean}get code(){
184
+ return this[uo]}get reason(){return this[mo]}get wasClean(){return this[yo]}};Object.defineProperty(Oe.prototype,"code",
185
+ {enumerable:!0});Object.defineProperty(Oe.prototype,"reason",{enumerable:!0});Object.defineProperty(Oe.prototype,"wasCle\
186
+ an",{enumerable:!0});var ze=class extends de{constructor(e,r={}){super(e),this[fo]=r.error===void 0?null:r.error,this[po]=
187
+ r.message===void 0?"":r.message}get error(){return this[fo]}get message(){return this[po]}};Object.defineProperty(ze.prototype,
188
+ "error",{enumerable:!0});Object.defineProperty(ze.prototype,"message",{enumerable:!0});var Ke=class extends de{constructor(e,r={}){
189
+ super(e),this[lo]=r.data===void 0?null:r.data}get data(){return this[lo]}};Object.defineProperty(Ke.prototype,"data",{enumerable:!0});
190
+ var za={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Je]&&o[yr]===e&&!o[Je])return;let n;if(t==="mess\
191
+ age")n=function(i,s){let a=new Ke("message",{data:s?i:i.toString()});a[Le]=this,wt(e,this,a)};else if(t==="close")n=function(i,s){
192
+ let a=new Oe("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Le]=this,wt(
193
+ e,this,a)};else if(t==="error")n=function(i){let s=new ze("error",{error:i,message:i.message});s[Le]=this,wt(e,this,s)};else if(t===
194
+ "open")n=function(){let i=new de("open");i[Le]=this,wt(e,this,i)};else return;n[Je]=!!r[Je],n[yr]=e,r.once?this.once(t,n):
195
+ this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[yr]===e&&!r[Je]){this.removeListener(t,r);break}}};
196
+ _o.exports={CloseEvent:Oe,ErrorEvent:ze,Event:de,EventTarget:za,MessageEvent:Ke};function wt(t,e,r){typeof t=="object"&&
197
+ t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var St=K((Vf,Eo)=>{"use strict";var{tokenChars:Ye}=je();function se(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function $a(t){
198
+ let e=Object.create(null),r=Object.create(null),n=!1,o=!1,i=!1,s,a,c=-1,u=-1,l=-1,m=0;for(;m<t.length;m++)if(u=t.charCodeAt(
199
+ m),s===void 0)if(l===-1&&Ye[u]===1)c===-1&&(c=m);else if(m!==0&&(u===32||u===9))l===-1&&c!==-1&&(l=m);else if(u===59||u===
200
+ 44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${m}`);l===-1&&(l=m);let _=t.slice(c,l);u===44?(se(e,
201
+ _,r),r=Object.create(null)):s=_,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);else if(a===void 0)
202
+ if(l===-1&&Ye[u]===1)c===-1&&(c=m);else if(u===32||u===9)l===-1&&c!==-1&&(l=m);else if(u===59||u===44){if(c===-1)throw new SyntaxError(
203
+ `Unexpected character at index ${m}`);l===-1&&(l=m),se(r,t.slice(c,l),!0),u===44&&(se(e,s,r),r=Object.create(null),s=void 0),
204
+ c=l=-1}else if(u===61&&c!==-1&&l===-1)a=t.slice(c,m),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${m}`);else if(o){
205
+ if(Ye[u]!==1)throw new SyntaxError(`Unexpected character at index ${m}`);c===-1?c=m:n||(n=!0),o=!1}else if(i)if(Ye[u]===
206
+ 1)c===-1&&(c=m);else if(u===34&&c!==-1)i=!1,l=m;else if(u===92)o=!0;else throw new SyntaxError(`Unexpected character at \
207
+ index ${m}`);else if(u===34&&t.charCodeAt(m-1)===61)i=!0;else if(l===-1&&Ye[u]===1)c===-1&&(c=m);else if(c!==-1&&(u===32||
208
+ u===9))l===-1&&(l=m);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${m}`);l===-1&&
209
+ (l=m);let _=t.slice(c,l);n&&(_=_.replace(/\\/g,""),n=!1),se(r,a,_),u===44&&(se(e,s,r),r=Object.create(null),s=void 0),a=
210
+ void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${m}`);if(c===-1||i||u===32||u===9)throw new SyntaxError(
211
+ "Unexpected end of input");l===-1&&(l=m);let d=t.slice(c,l);return s===void 0?se(e,d,r):(a===void 0?se(r,d,!0):n?se(r,a,
212
+ d.replace(/\\/g,"")):se(r,a,d),se(e,s,r)),e}function Ua(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(
213
213
  r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(o=>{let i=n[o];return Array.isArray(i)||(i=[i]),i.map(s=>s===!0?o:`${o}\
214
- =${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}_o.exports={format:za,parse:La}});var Ot=J((Bf,Io)=>{"use strict";var $a=F("events"),Ua=F("https"),Va=F("http"),wo=F("net"),Ba=F("tls"),{randomBytes:Fa,createHash:qa}=F("crypto"),
215
- {Duplex:Uf,Readable:Vf}=F("stream"),{URL:yr}=F("url"),_e=Ne(),Ha=dr(),Ga=mr(),{isBlob:Wa}=ke(),{BINARY_TYPES:go,CLOSE_TIMEOUT:Xa,
216
- EMPTY_BUFFER:St,GUID:Ja,kForOnEventAttribute:_r,kListener:Ka,kStatusCode:Ya,kWebSocket:W,NOOP:So}=le(),{EventTarget:{addEventListener:Qa,
217
- removeEventListener:Za}}=yo(),{format:ec,parse:tc}=wt(),{toBuffer:rc}=Ge(),bo=Symbol("kAborted"),gr=[8,13],pe=["CONNECTI\
218
- NG","OPEN","CLOSING","CLOSED"],nc=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,V=class t extends $a{constructor(e,r,n){super(),this.
219
- _binaryType=go[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=St,this._closeTimer=
214
+ =${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Eo.exports={format:Ua,parse:$a}});var At=K((qf,Ro)=>{"use strict";var Va=B("events"),Ba=B("https"),Fa=B("http"),bo=B("net"),qa=B("tls"),{randomBytes:Ha,createHash:Ga}=B("crypto"),
215
+ {Duplex:Bf,Readable:Ff}=B("stream"),{URL:_r}=B("url"),_e=ke(),Wa=fr(),Xa=hr(),{isBlob:Ja}=je(),{BINARY_TYPES:wo,CLOSE_TIMEOUT:Ka,
216
+ EMPTY_BUFFER:bt,GUID:Ya,kForOnEventAttribute:gr,kListener:Qa,kStatusCode:Za,kWebSocket:H,NOOP:xo}=ue(),{EventTarget:{addEventListener:ec,
217
+ removeEventListener:tc}}=go(),{format:rc,parse:nc}=St(),{toBuffer:oc}=We(),Oo=Symbol("kAborted"),Er=[8,13],fe=["CONNECTI\
218
+ NG","OPEN","CLOSING","CLOSED"],ic=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,U=class t extends Va{constructor(e,r,n){super(),this.
219
+ _binaryType=wo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=bt,this._closeTimer=
220
220
  null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=
221
221
  null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?
222
- r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),xo(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=
223
- n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){go.includes(e)&&(this._binaryType=
222
+ r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),Ao(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=
223
+ n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){wo.includes(e)&&(this._binaryType=
224
224
  e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+
225
225
  this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){
226
226
  return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){
227
- return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let o=new Ha(
227
+ return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let o=new Wa(
228
228
  {allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,
229
229
  maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),
230
- i=new Ga(e,this._extensions,n.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[W]=this,i[W]=this,e[W]=this,
231
- o.on("conclude",sc),o.on("drain",ac),o.on("error",cc),o.on("message",uc),o.on("ping",lc),o.on("pong",dc),i.onerror=fc,e.
232
- setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",vo),e.on("data",xt),e.on(
233
- "end",Co),e.on("error",To),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,
230
+ i=new Xa(e,this._extensions,n.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[H]=this,i[H]=this,e[H]=this,
231
+ o.on("conclude",cc),o.on("drain",uc),o.on("error",lc),o.on("message",dc),o.on("ping",fc),o.on("pong",pc),i.onerror=mc,e.
232
+ setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",To),e.on("data",Ot),e.on(
233
+ "end",Io),e.on("error",Po),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,
234
234
  this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[_e.extensionName]&&this._extensions[_e.extensionName].
235
235
  cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){
236
- if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the conn\
236
+ if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Q(this,this._req,"WebSocket was closed before the conn\
237
237
  ection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver.
238
238
  _writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,
239
239
  n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),
240
- Ao(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){
240
+ Co(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){
241
241
  if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="func\
242
242
  tion"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){
243
- Er(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||St,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)
243
+ wr(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||bt,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)
244
244
  throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="\
245
- function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Er(this,e,n);return}r===void 0&&
246
- (r=!this._isServer),this._sender.pong(e||St,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this.
245
+ function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){wr(this,e,n);return}r===void 0&&
246
+ (r=!this._isServer),this._sender.pong(e||bt,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this.
247
247
  _paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)
248
248
  throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="numbe\
249
- r"&&(e=e.toString()),this.readyState!==t.OPEN){Er(this,e,n);return}let o={binary:typeof e!="string",mask:!this._isServer,
250
- compress:!0,fin:!0,...r};this._extensions[_e.extensionName]||(o.compress=!1),this._sender.send(e||St,o,n)}terminate(){if(this.
251
- readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection w\
252
- as established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(V,"CO\
253
- NNECTING",{enumerable:!0,value:pe.indexOf("CONNECTING")});Object.defineProperty(V.prototype,"CONNECTING",{enumerable:!0,
254
- value:pe.indexOf("CONNECTING")});Object.defineProperty(V,"OPEN",{enumerable:!0,value:pe.indexOf("OPEN")});Object.defineProperty(
255
- V.prototype,"OPEN",{enumerable:!0,value:pe.indexOf("OPEN")});Object.defineProperty(V,"CLOSING",{enumerable:!0,value:pe.indexOf(
256
- "CLOSING")});Object.defineProperty(V.prototype,"CLOSING",{enumerable:!0,value:pe.indexOf("CLOSING")});Object.defineProperty(
257
- V,"CLOSED",{enumerable:!0,value:pe.indexOf("CLOSED")});Object.defineProperty(V.prototype,"CLOSED",{enumerable:!0,value:pe.
249
+ r"&&(e=e.toString()),this.readyState!==t.OPEN){wr(this,e,n);return}let o={binary:typeof e!="string",mask:!this._isServer,
250
+ compress:!0,fin:!0,...r};this._extensions[_e.extensionName]||(o.compress=!1),this._sender.send(e||bt,o,n)}terminate(){if(this.
251
+ readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Q(this,this._req,"WebSocket was closed before the connection w\
252
+ as established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(U,"CO\
253
+ NNECTING",{enumerable:!0,value:fe.indexOf("CONNECTING")});Object.defineProperty(U.prototype,"CONNECTING",{enumerable:!0,
254
+ value:fe.indexOf("CONNECTING")});Object.defineProperty(U,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(
255
+ U.prototype,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(U,"CLOSING",{enumerable:!0,value:fe.indexOf(
256
+ "CLOSING")});Object.defineProperty(U.prototype,"CLOSING",{enumerable:!0,value:fe.indexOf("CLOSING")});Object.defineProperty(
257
+ U,"CLOSED",{enumerable:!0,value:fe.indexOf("CLOSED")});Object.defineProperty(U.prototype,"CLOSED",{enumerable:!0,value:fe.
258
258
  indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.
259
- defineProperty(V.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(V.prototype,
260
- `on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[_r])return e[Ka];return null},set(e){for(let r of this.
261
- listeners(t))if(r[_r]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[_r]:!0})}})});V.
262
- prototype.addEventListener=Qa;V.prototype.removeEventListener=Za;Io.exports=V;function xo(t,e,r,n){let o={allowSynchronousEvents:!0,
263
- autoPong:!0,closeTimeout:Xa,protocolVersion:gr[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,
259
+ defineProperty(U.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(U.prototype,
260
+ `on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[gr])return e[Qa];return null},set(e){for(let r of this.
261
+ listeners(t))if(r[gr]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[gr]:!0})}})});U.
262
+ prototype.addEventListener=ec;U.prototype.removeEventListener=tc;Ro.exports=U;function Ao(t,e,r,n){let o={allowSynchronousEvents:!0,
263
+ autoPong:!0,closeTimeout:Ka,protocolVersion:Er[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,
264
264
  perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,
265
- method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!gr.includes(
266
- o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${gr.join(
267
- ", ")})`);let i;if(e instanceof yr)i=e;else try{i=new yr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol===
265
+ method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Er.includes(
266
+ o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Er.join(
267
+ ", ")})`);let i;if(e instanceof _r)i=e;else try{i=new _r(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol===
268
268
  "http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let s=i.protocol==="wss:",a=i.protocol===
269
269
  "ws+unix:",c;if(i.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws\
270
270
  +unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let E=new SyntaxError(
271
- c);if(t._redirects===0)throw E;bt(t,E);return}let u=s?443:80,l=Fa(16).toString("base64"),p=s?Ua.request:Va.request,d=new Set,
272
- h;if(o.createConnection=o.createConnection||(s?ic:oc),o.defaultPort=o.defaultPort||u,o.port=i.port||u,o.host=i.hostname.
271
+ c);if(t._redirects===0)throw E;xt(t,E);return}let u=s?443:80,l=Ha(16).toString("base64"),m=s?Ba.request:Fa.request,d=new Set,
272
+ _;if(o.createConnection=o.createConnection||(s?ac:sc),o.defaultPort=o.defaultPort||u,o.port=i.port||u,o.host=i.hostname.
273
273
  startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec\
274
274
  -WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&
275
- (h=new _e({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=ec({[_e.extensionName]:h.
276
- offer()})),r.length){for(let E of r){if(typeof E!="string"||!nc.test(E)||d.has(E))throw new SyntaxError("An invalid or d\
275
+ (_=new _e({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=rc({[_e.extensionName]:_.
276
+ offer()})),r.length){for(let E of r){if(typeof E!="string"||!ic.test(E)||d.has(E))throw new SyntaxError("An invalid or d\
277
277
  uplicated subprotocol was specified");d.add(E)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<
278
278
  13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}\
279
- :${i.password}`),a){let E=o.path.split(":");o.socketPath=E[0],o.path=E[1]}let _;if(o.followRedirects){if(t._redirects===
279
+ :${i.password}`),a){let E=o.path.split(":");o.socketPath=E[0],o.path=E[1]}let g;if(o.followRedirects){if(t._redirects===
280
280
  0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?o.socketPath:i.host;let E=n&&n.headers;if(n={...n,
281
- headers:{}},E)for(let[O,N]of Object.entries(E))n.headers[O.toLowerCase()]=N}else if(t.listenerCount("redirect")===0){let E=a?
281
+ headers:{}},E)for(let[x,R]of Object.entries(E))n.headers[x.toLowerCase()]=R}else if(t.listenerCount("redirect")===0){let E=a?
282
282
  t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!E||
283
283
  t._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,E||delete o.headers.host,o.auth=void 0)}
284
- o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),_=t._req=p(o),
285
- t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=p(o);o.timeout&&_.on("timeout",()=>{Y(t,_,"Opening handshake has \
286
- timed out")}),_.on("error",E=>{_===null||_[bo]||(_=t._req=null,bt(t,E))}),_.on("response",E=>{let O=E.headers.location,N=E.
287
- statusCode;if(O&&o.followRedirects&&N>=300&&N<400){if(++t._redirects>o.maxRedirects){Y(t,_,"Maximum redirects exceeded");
288
- return}_.abort();let D;try{D=new yr(O,e)}catch{let C=new SyntaxError(`Invalid URL: ${O}`);bt(t,C);return}xo(t,D,r,n)}else
289
- t.emit("unexpected-response",_,E)||Y(t,_,`Unexpected server response: ${E.statusCode}`)}),_.on("upgrade",(E,O,N)=>{if(t.
290
- emit("upgrade",E),t.readyState!==V.CONNECTING)return;_=t._req=null;let D=E.headers.upgrade;if(D===void 0||D.toLowerCase()!==
291
- "websocket"){Y(t,O,"Invalid Upgrade header");return}let I=qa("sha1").update(l+Ja).digest("base64");if(E.headers["sec-web\
292
- socket-accept"]!==I){Y(t,O,"Invalid Sec-WebSocket-Accept header");return}let C=E.headers["sec-websocket-protocol"],M;if(C!==
293
- void 0?d.size?d.has(C)||(M="Server sent an invalid subprotocol"):M="Server sent a subprotocol but none was requested":d.
294
- size&&(M="Server sent no subprotocol"),M){Y(t,O,M);return}C&&(t._protocol=C);let A=E.headers["sec-websocket-extensions"];
295
- if(A!==void 0){if(!h){Y(t,O,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let v;
296
- try{v=tc(A)}catch{Y(t,O,"Invalid Sec-WebSocket-Extensions header");return}let b=Object.keys(v);if(b.length!==1||b[0]!==_e.
297
- extensionName){Y(t,O,"Server indicated an extension that was not requested");return}try{h.accept(v[_e.extensionName])}catch{
298
- Y(t,O,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[_e.extensionName]=h}t.setSocket(O,N,{allowSynchronousEvents:o.
284
+ o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),g=t._req=m(o),
285
+ t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=m(o);o.timeout&&g.on("timeout",()=>{Q(t,g,"Opening handshake has \
286
+ timed out")}),g.on("error",E=>{g===null||g[Oo]||(g=t._req=null,xt(t,E))}),g.on("response",E=>{let x=E.headers.location,R=E.
287
+ statusCode;if(x&&o.followRedirects&&R>=300&&R<400){if(++t._redirects>o.maxRedirects){Q(t,g,"Maximum redirects exceeded");
288
+ return}g.abort();let k;try{k=new _r(x,e)}catch{let v=new SyntaxError(`Invalid URL: ${x}`);xt(t,v);return}Ao(t,k,r,n)}else
289
+ t.emit("unexpected-response",g,E)||Q(t,g,`Unexpected server response: ${E.statusCode}`)}),g.on("upgrade",(E,x,R)=>{if(t.
290
+ emit("upgrade",E),t.readyState!==U.CONNECTING)return;g=t._req=null;let k=E.headers.upgrade;if(k===void 0||k.toLowerCase()!==
291
+ "websocket"){Q(t,x,"Invalid Upgrade header");return}let C=Ga("sha1").update(l+Ya).digest("base64");if(E.headers["sec-web\
292
+ socket-accept"]!==C){Q(t,x,"Invalid Sec-WebSocket-Accept header");return}let v=E.headers["sec-websocket-protocol"],D;if(v!==
293
+ void 0?d.size?d.has(v)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":d.
294
+ size&&(D="Server sent no subprotocol"),D){Q(t,x,D);return}v&&(t._protocol=v);let O=E.headers["sec-websocket-extensions"];
295
+ if(O!==void 0){if(!_){Q(t,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let A;
296
+ try{A=nc(O)}catch{Q(t,x,"Invalid Sec-WebSocket-Extensions header");return}let b=Object.keys(A);if(b.length!==1||b[0]!==_e.
297
+ extensionName){Q(t,x,"Server indicated an extension that was not requested");return}try{_.accept(A[_e.extensionName])}catch{
298
+ Q(t,x,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[_e.extensionName]=_}t.setSocket(x,R,{allowSynchronousEvents:o.
299
299
  allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.
300
- maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(_,t):_.end()}function bt(t,e){t._readyState=
301
- V.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function oc(t){return t.path=t.socketPath,wo.connect(t)}function ic(t){
302
- return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=wo.isIP(t.host)?"":t.host),Ba.connect(t)}function Y(t,e,r){
303
- t._readyState=V.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Y),e.setHeader?(e[bo]=!0,e.abort(),e.socket&&!e.socket.
304
- destroyed&&e.socket.destroy(),process.nextTick(bt,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("clo\
305
- se",t.emitClose.bind(t)))}function Er(t,e,r){if(e){let n=Wa(e)?e.size:rc(e).length;t._socket?t._sender._bufferedBytes+=n:
306
- t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${pe[t.readyState]})`);process.
307
- nextTick(r,n)}}function sc(t,e){let r=this[W];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[W]!==void 0&&
308
- (r._socket.removeListener("data",xt),process.nextTick(Oo,r._socket),t===1005?r.close():r.close(t,e))}function ac(){let t=this[W];
309
- t.isPaused||t._socket.resume()}function cc(t){let e=this[W];e._socket[W]!==void 0&&(e._socket.removeListener("data",xt),
310
- process.nextTick(Oo,e._socket),e.close(t[Ya])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Eo(){this[W].
311
- emitClose()}function uc(t,e){this[W].emit("message",t,e)}function lc(t){let e=this[W];e._autoPong&&e.pong(t,!this._isServer,
312
- So),e.emit("ping",t)}function dc(t){this[W].emit("pong",t)}function Oo(t){t.resume()}function fc(t){let e=this[W];e.readyState!==
313
- V.CLOSED&&(e.readyState===V.OPEN&&(e._readyState=V.CLOSING,Ao(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,
314
- e.emit("error",t)))}function Ao(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function vo(){
315
- let t=this[W];if(this.removeListener("close",vo),this.removeListener("data",xt),this.removeListener("end",Co),t._readyState=
316
- V.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.
317
- length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[W]=void 0,clearTimeout(
300
+ maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(g,t):g.end()}function xt(t,e){t._readyState=
301
+ U.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function sc(t){return t.path=t.socketPath,bo.connect(t)}function ac(t){
302
+ return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=bo.isIP(t.host)?"":t.host),qa.connect(t)}function Q(t,e,r){
303
+ t._readyState=U.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Q),e.setHeader?(e[Oo]=!0,e.abort(),e.socket&&!e.socket.
304
+ destroyed&&e.socket.destroy(),process.nextTick(xt,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("clo\
305
+ se",t.emitClose.bind(t)))}function wr(t,e,r){if(e){let n=Ja(e)?e.size:oc(e).length;t._socket?t._sender._bufferedBytes+=n:
306
+ t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${fe[t.readyState]})`);process.
307
+ nextTick(r,n)}}function cc(t,e){let r=this[H];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[H]!==void 0&&
308
+ (r._socket.removeListener("data",Ot),process.nextTick(vo,r._socket),t===1005?r.close():r.close(t,e))}function uc(){let t=this[H];
309
+ t.isPaused||t._socket.resume()}function lc(t){let e=this[H];e._socket[H]!==void 0&&(e._socket.removeListener("data",Ot),
310
+ process.nextTick(vo,e._socket),e.close(t[Za])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function So(){this[H].
311
+ emitClose()}function dc(t,e){this[H].emit("message",t,e)}function fc(t){let e=this[H];e._autoPong&&e.pong(t,!this._isServer,
312
+ xo),e.emit("ping",t)}function pc(t){this[H].emit("pong",t)}function vo(t){t.resume()}function mc(t){let e=this[H];e.readyState!==
313
+ U.CLOSED&&(e.readyState===U.OPEN&&(e._readyState=U.CLOSING,Co(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,
314
+ e.emit("error",t)))}function Co(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function To(){
315
+ let t=this[H];if(this.removeListener("close",To),this.removeListener("data",Ot),this.removeListener("end",Io),t._readyState=
316
+ U.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.
317
+ length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[H]=void 0,clearTimeout(
318
318
  t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on(
319
- "error",Eo),t._receiver.on("finish",Eo))}function xt(t){this[W]._receiver.write(t)||this.pause()}function Co(){let t=this[W];
320
- t._readyState=V.CLOSING,t._receiver.end(),this.end()}function To(){let t=this[W];this.removeListener("error",To),this.on(
321
- "error",So),t&&(t._readyState=V.CLOSING,this.destroy())}});var ko=J((qf,No)=>{"use strict";var Ff=Ot(),{Duplex:pc}=F("stream");function Po(t){t.emit("close")}function mc(){!this.destroyed&&
322
- this._writableState.finished&&this.destroy()}function Ro(t){this.removeListener("error",Ro),this.destroy(),this.listenerCount(
323
- "error")===0&&this.emit("error",t)}function hc(t,e){let r=!0,n=new pc({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});
319
+ "error",So),t._receiver.on("finish",So))}function Ot(t){this[H]._receiver.write(t)||this.pause()}function Io(){let t=this[H];
320
+ t._readyState=U.CLOSING,t._receiver.end(),this.end()}function Po(){let t=this[H];this.removeListener("error",Po),this.on(
321
+ "error",xo),t&&(t._readyState=U.CLOSING,this.destroy())}});var Do=K((Gf,jo)=>{"use strict";var Hf=At(),{Duplex:hc}=B("stream");function No(t){t.emit("close")}function yc(){!this.destroyed&&
322
+ this._writableState.finished&&this.destroy()}function ko(t){this.removeListener("error",ko),this.destroy(),this.listenerCount(
323
+ "error")===0&&this.emit("error",t)}function _c(t,e){let r=!0,n=new hc({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});
324
324
  return t.on("message",function(i,s){let a=!s&&n._readableState.objectMode?i.toString():i;n.push(a)||t.pause()}),t.once("\
325
325
  error",function(i){n.destroyed||(r=!1,n.destroy(i))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(o,i){
326
- if(t.readyState===t.CLOSED){i(o),process.nextTick(Po,n);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("c\
327
- lose",function(){s||i(o),process.nextTick(Po,n)}),r&&t.terminate()},n._final=function(o){if(t.readyState===t.CONNECTING){
326
+ if(t.readyState===t.CLOSED){i(o),process.nextTick(No,n);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("c\
327
+ lose",function(){s||i(o),process.nextTick(No,n)}),r&&t.terminate()},n._final=function(o){if(t.readyState===t.CONNECTING){
328
328
  t.once("open",function(){n._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),n._readableState.
329
329
  endEmitted&&n.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},
330
330
  n._write=function(o,i,s){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(o,i,s)});return}t.send(o,s)},
331
- n.on("end",mc),n.on("error",Ro),n}No.exports=hc});var wr=J((Hf,jo)=>{"use strict";var{tokenChars:yc}=ke();function _c(t){let e=new Set,r=-1,n=-1,o=0;for(o;o<t.length;o++){
332
- let s=t.charCodeAt(o);if(n===-1&&yc[s]===1)r===-1&&(r=o);else if(o!==0&&(s===32||s===9))n===-1&&r!==-1&&(n=o);else if(s===
331
+ n.on("end",yc),n.on("error",ko),n}jo.exports=_c});var Sr=K((Wf,Mo)=>{"use strict";var{tokenChars:gc}=je();function Ec(t){let e=new Set,r=-1,n=-1,o=0;for(o;o<t.length;o++){
332
+ let s=t.charCodeAt(o);if(n===-1&&gc[s]===1)r===-1&&(r=o);else if(o!==0&&(s===32||s===9))n===-1&&r!==-1&&(n=o);else if(s===
333
333
  44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(
334
334
  `The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}
335
335
  if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(r,o);if(e.has(i))throw new SyntaxError(
336
- `The "${i}" subprotocol is duplicated`);return e.add(i),e}jo.exports={parse:_c}});var Vo=J((Wf,Uo)=>{"use strict";var gc=F("events"),At=F("http"),{Duplex:Gf}=F("stream"),{createHash:Ec}=F("crypto"),Do=wt(),
337
- Oe=Ne(),wc=wr(),Sc=Ot(),{CLOSE_TIMEOUT:bc,GUID:xc,kWebSocket:Oc}=le(),Ac=/^[+/0-9A-Za-z]{22}==$/,Mo=0,Lo=1,$o=2,Sr=class extends gc{constructor(e,r){
336
+ `The "${i}" subprotocol is duplicated`);return e.add(i),e}Mo.exports={parse:Ec}});var Fo=K((Jf,Bo)=>{"use strict";var wc=B("events"),vt=B("http"),{Duplex:Xf}=B("stream"),{createHash:Sc}=B("crypto"),Lo=St(),
337
+ Ae=ke(),bc=Sr(),xc=At(),{CLOSE_TIMEOUT:Oc,GUID:Ac,kWebSocket:vc}=ue(),Cc=/^[+/0-9A-Za-z]{22}==$/,zo=0,$o=1,Vo=2,br=class extends wc{constructor(e,r){
338
338
  if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*
339
- 1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:bc,verifyClient:null,
340
- noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Sc,...e},e.port==null&&!e.server&&!e.noServer||
339
+ 1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Oc,verifyClient:null,
340
+ noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:xc,...e},e.port==null&&!e.server&&!e.noServer||
341
341
  e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server"\
342
- , or "noServer" options must be specified');if(e.port!=null?(this._server=At.createServer((n,o)=>{let i=At.STATUS_CODES[426];
342
+ , or "noServer" options must be specified');if(e.port!=null?(this._server=vt.createServer((n,o)=>{let i=vt.STATUS_CODES[426];
343
343
  o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(e.port,e.host,e.
344
344
  backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=
345
- vc(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,s)=>{this.handleUpgrade(
345
+ Tc(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,s)=>{this.handleUpgrade(
346
346
  o,i,s,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=
347
- !1),this.options=e,this._state=Mo}address(){if(this.options.noServer)throw new Error('The server is operating in "noServ\
348
- er" mode');return this._server?this._server.address():null}close(e){if(this._state===$o){e&&this.once("close",()=>{e(new Error(
349
- "The server is not running"))}),process.nextTick(Ye,this);return}if(e&&this.once("close",e),this._state!==Lo)if(this._state=
350
- Lo,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=
351
- null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ye,this):process.nextTick(Ye,this);else{let r=this.
352
- _server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Ye(this)})}}shouldHandle(e){if(this.
347
+ !1),this.options=e,this._state=zo}address(){if(this.options.noServer)throw new Error('The server is operating in "noServ\
348
+ er" mode');return this._server?this._server.address():null}close(e){if(this._state===Vo){e&&this.once("close",()=>{e(new Error(
349
+ "The server is not running"))}),process.nextTick(Qe,this);return}if(e&&this.once("close",e),this._state!==$o)if(this._state=
350
+ $o,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=
351
+ null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Qe,this):process.nextTick(Qe,this);else{let r=this.
352
+ _server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Qe(this)})}}shouldHandle(e){if(this.
353
353
  options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,o){
354
- r.on("error",zo);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!==
355
- "GET"){Ae(this,e,r,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Ae(this,e,r,400,"Inva\
356
- lid Upgrade header");return}if(i===void 0||!Ac.test(i)){Ae(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}
357
- if(a!==13&&a!==8){Ae(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}
358
- if(!this.shouldHandle(e)){Qe(r,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=wc.parse(
359
- c)}catch{Ae(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],p={};
360
- if(this.options.perMessageDeflate&&l!==void 0){let d=new Oe({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.
361
- options.maxPayload});try{let h=Do.parse(l);h[Oe.extensionName]&&(d.accept(h[Oe.extensionName]),p[Oe.extensionName]=d)}catch{
362
- Ae(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let d={
354
+ r.on("error",Uo);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!==
355
+ "GET"){ve(this,e,r,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){ve(this,e,r,400,"Inva\
356
+ lid Upgrade header");return}if(i===void 0||!Cc.test(i)){ve(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}
357
+ if(a!==13&&a!==8){ve(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}
358
+ if(!this.shouldHandle(e)){Ze(r,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=bc.parse(
359
+ c)}catch{ve(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],m={};
360
+ if(this.options.perMessageDeflate&&l!==void 0){let d=new Ae({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.
361
+ options.maxPayload});try{let _=Lo.parse(l);_[Ae.extensionName]&&(d.accept(_[Ae.extensionName]),m[Ae.extensionName]=d)}catch{
362
+ ve(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let d={
363
363
  origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.
364
- options.verifyClient.length===2){this.options.verifyClient(d,(h,_,E,O)=>{if(!h)return Qe(r,_||401,E,O);this.completeUpgrade(
365
- p,i,u,e,r,n,o)});return}if(!this.options.verifyClient(d))return Qe(r,401)}this.completeUpgrade(p,i,u,e,r,n,o)}completeUpgrade(e,r,n,o,i,s,a){
366
- if(!i.readable||!i.writable)return i.destroy();if(i[Oc])throw new Error("server.handleUpgrade() was called more than onc\
367
- e with the same socket, possibly due to a misconfiguration");if(this._state>Mo)return Qe(i,503);let u=["HTTP/1.1 101 Swi\
368
- tching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ec("sha1").update(r+xc).digest("ba\
369
- se64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.
370
- handleProtocols(n,o):n.values().next().value;p&&(u.push(`Sec-WebSocket-Protocol: ${p}`),l._protocol=p)}if(e[Oe.extensionName]){
371
- let p=e[Oe.extensionName].params,d=Do.format({[Oe.extensionName]:[p]});u.push(`Sec-WebSocket-Extensions: ${d}`),l._extensions=
364
+ options.verifyClient.length===2){this.options.verifyClient(d,(_,g,E,x)=>{if(!_)return Ze(r,g||401,E,x);this.completeUpgrade(
365
+ m,i,u,e,r,n,o)});return}if(!this.options.verifyClient(d))return Ze(r,401)}this.completeUpgrade(m,i,u,e,r,n,o)}completeUpgrade(e,r,n,o,i,s,a){
366
+ if(!i.readable||!i.writable)return i.destroy();if(i[vc])throw new Error("server.handleUpgrade() was called more than onc\
367
+ e with the same socket, possibly due to a misconfiguration");if(this._state>zo)return Ze(i,503);let u=["HTTP/1.1 101 Swi\
368
+ tching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Sc("sha1").update(r+Ac).digest("ba\
369
+ se64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(n.size){let m=this.options.handleProtocols?this.options.
370
+ handleProtocols(n,o):n.values().next().value;m&&(u.push(`Sec-WebSocket-Protocol: ${m}`),l._protocol=m)}if(e[Ae.extensionName]){
371
+ let m=e[Ae.extensionName].params,d=Lo.format({[Ae.extensionName]:[m]});u.push(`Sec-WebSocket-Extensions: ${d}`),l._extensions=
372
372
  e}this.emit("headers",u,o),i.write(u.concat(`\r
373
373
  `).join(`\r
374
- `)),i.removeListener("error",zo),l.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.
374
+ `)),i.removeListener("error",Uo),l.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.
375
375
  options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.
376
376
  options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&
377
- !this.clients.size&&process.nextTick(Ye,this)})),a(l,o)}};Uo.exports=Sr;function vc(t,e){for(let r of Object.keys(e))t.on(
378
- r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function Ye(t){t._state=$o,t.emit("close")}
379
- function zo(){this.destroy()}function Qe(t,e,r,n){r=r||At.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/htm\
380
- l","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${At.STATUS_CODES[e]}\r
377
+ !this.clients.size&&process.nextTick(Qe,this)})),a(l,o)}};Bo.exports=br;function Tc(t,e){for(let r of Object.keys(e))t.on(
378
+ r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function Qe(t){t._state=Vo,t.emit("close")}
379
+ function Uo(){this.destroy()}function Ze(t,e,r,n){r=r||vt.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/htm\
380
+ l","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${vt.STATUS_CODES[e]}\r
381
381
  `+Object.keys(n).map(o=>`${o}: ${n[o]}`).join(`\r
382
382
  `)+`\r
383
383
  \r
384
- `+r)}function Ae(t,e,r,n,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,Ae),t.emit(
385
- "wsClientError",s,r,e)}else Qe(r,n,o,i)}});import{createHash as bs}from"node:crypto";import{execFile as xs}from"node:child_process";import{readFile as Ht,rename as Os,
386
- rm as hn,stat as En,writeFile as yn}from"node:fs/promises";import we from"node:path";import{promisify as As}from"node:util";function z(t){return String(t??"").trim()}function qt(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||
387
- e===null}var nd=Object.freeze(["plugins","apps","daemon_auto_start"]);var od=Object.freeze([[".tmp",/^(?:plugins(?:$|[.-])|git-|bundled-marketplaces$)/u],["cache",/^(?:remote_plugin_catalog|codex_apps_tools|codex_apps_server_info|codex_app_directory|bundled_plugin_exclusions)$/u]]);var vs=As(xs);async function _n({command:t,codexHome:e,bundled:r,additionalModels:n}){if(!we.isAbsolute(t))return null;let o=async s=>{
388
- let a=await En(s).catch(()=>null);return a&&[a.dev,a.ino,a.size,a.mtimeMs,a.ctimeMs]},i=await o(t);return i?bs("sha256").
389
- update(JSON.stringify({command:t,binary:i,bundled:r,additionalModels:n,auth:await o(we.join(e,"auth.json")),config:await o(
390
- we.join(e,"config.toml"))})).digest("hex"):null}async function wn({command:t,runtimeDir:e,bundled:r=!1,signal:n,additionalModels:o=[],
384
+ `+r)}function ve(t,e,r,n,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,ve),t.emit(
385
+ "wsClientError",s,r,e)}else Ze(r,n,o,i)}});import{createHash as Os}from"node:crypto";import{execFile as As}from"node:child_process";import{readFile as Gt,rename as vs,
386
+ rm as yn,stat as wn,writeFile as _n}from"node:fs/promises";import Se from"node:path";import{promisify as Cs}from"node:util";function z(t){return String(t??"").trim()}function Ht(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||
387
+ e===null}var id=Object.freeze(["plugins","apps","daemon_auto_start"]);var sd=Object.freeze([[".tmp",/^(?:plugins(?:$|[.-])|git-|bundled-marketplaces$)/u],["cache",/^(?:remote_plugin_catalog|codex_apps_tools|codex_apps_server_info|codex_app_directory|bundled_plugin_exclusions)$/u]]);var Ts=Cs(As);async function gn({command:t,codexHome:e,bundled:r,additionalModels:n}){if(!Se.isAbsolute(t))return null;let o=async s=>{
388
+ let a=await wn(s).catch(()=>null);return a&&[a.dev,a.ino,a.size,a.mtimeMs,a.ctimeMs]},i=await o(t);return i?Os("sha256").
389
+ update(JSON.stringify({command:t,binary:i,bundled:r,additionalModels:n,auth:await o(Se.join(e,"auth.json")),config:await o(
390
+ Se.join(e,"config.toml"))})).digest("hex"):null}async function Sn({command:t,runtimeDir:e,bundled:r=!1,signal:n,additionalModels:o=[],
391
391
  codexHome:i}){if(!i)throw new TypeError("prepareCodexModelCatalog requires the Codex home whose configuration the catalo\
392
- gue reads.");let s=we.join(e,"models.json"),a=we.join(e,"models.revision"),c={command:t,codexHome:i,bundled:r,additionalModels:o},
393
- u=await _n(c);if(u&&await En(s).then(()=>!0,()=>!1)&&await Ht(a,"utf8").catch(()=>"")===u)return s;let l,p=new Map;try{let{
394
- stdout:E}=await vs(t,["debug","models",...r?["--bundled"]:[],"-c","check_for_update_on_startup=false"],{encoding:"utf8",
392
+ gue reads.");let s=Se.join(e,"models.json"),a=Se.join(e,"models.revision"),c={command:t,codexHome:i,bundled:r,additionalModels:o},
393
+ u=await gn(c);if(u&&await wn(s).then(()=>!0,()=>!1)&&await Gt(a,"utf8").catch(()=>"")===u)return s;let l,m=new Map;try{let{
394
+ stdout:E}=await Ts(t,["debug","models",...r?["--bundled"]:[],"-c","check_for_update_on_startup=false"],{encoding:"utf8",
395
395
  maxBuffer:16777216,timeout:2e4,signal:n});if(l=JSON.parse(E),!Array.isArray(l?.models)||!l.models.length)throw new Error(
396
- "Invalid native model catalogue");for(let O of l.models){if(!O||typeof O.slug!="string"||!O.slug.trim()||p.has(O.slug))throw new Error(
397
- "Invalid native model catalogue");p.set(O.slug,O)}}catch{throw new Error("Codex could not load its model catalogue. Rest\
398
- art the assistant service after checking the Codex installation and connection.")}let d=l.models.reduce((E,O)=>Math.max(
399
- E,O.priority||0),0);for(let E of o)p.set(E.slug,{...E,priority:++d});let h=`${s}.tmp`;try{n?.throwIfAborted(),await hn(a,
400
- {force:!0}),await yn(h,JSON.stringify({...l,models:[...p.values()]}),{mode:384}),await Os(h,s)}finally{await hn(h,{force:!0})}
401
- let _=await _n(c);return _&&await yn(a,_,{mode:384}),s}function at(t=""){return Array.from(String(t)).some(e=>{let r=e.codePointAt(0);return r<=31||r===127})}function Gt({models:t}){return{models:t.map((e,r)=>({slug:e.id,display_name:e.label,description:e.label,default_reasoning_level:e.
396
+ "Invalid native model catalogue");for(let x of l.models){if(!x||typeof x.slug!="string"||!x.slug.trim()||m.has(x.slug))throw new Error(
397
+ "Invalid native model catalogue");m.set(x.slug,x)}}catch{throw new Error("Codex could not load its model catalogue. Rest\
398
+ art the assistant service after checking the Codex installation and connection.")}let d=l.models.reduce((E,x)=>Math.max(
399
+ E,x.priority||0),0);for(let E of o)m.set(E.slug,{...E,priority:++d});let _=`${s}.tmp`;try{n?.throwIfAborted(),await yn(a,
400
+ {force:!0}),await _n(_,JSON.stringify({...l,models:[...m.values()]}),{mode:384}),await vs(_,s)}finally{await yn(_,{force:!0})}
401
+ let g=await gn(c);return g&&await _n(a,g,{mode:384}),s}function ct(t=""){return Array.from(String(t)).some(e=>{let r=e.codePointAt(0);return r<=31||r===127})}function Wt({models:t}){return{models:t.map((e,r)=>({slug:e.id,display_name:e.label,description:e.label,default_reasoning_level:e.
402
402
  defaultThinking,supported_reasoning_levels:e.variants.map(n=>({effort:n,description:n})),shell_type:"shell_command",visibility:"\
403
403
  list",supported_in_api:!0,priority:r,base_instructions:"You are a coding assistant. Complete the user's task in the work\
404
404
  space, use the available tools, preserve unrelated work, and verify your changes.",supports_reasoning_summaries:!1,default_reasoning_summary:"\
405
405
  none",support_verbosity:!1,truncation_policy:{mode:"tokens",limit:1e4},context_window:e.contextWindow,max_context_window:e.
406
406
  contextWindow,effective_context_window_percent:95,supports_parallel_tool_calls:e.parallelToolCalls!==!1,experimental_supported_tools:[],
407
407
  input_modalities:e.images?["text","image"]:["text"],prefer_websockets:!1,...e.freeformPatch?{apply_patch_tool_type:"free\
408
- form"}:{}}))}}function Sn(t){return we.join(t,"models.json")}async function He(t){let e=await Ht(we.join(t,"config.toml"),"utf8").catch(n=>{if(n.code==="ENOENT")return"";throw n});if(!/^model_provider = "custom"$/mu.
409
- test(e))return[];let r=JSON.parse(await Ht(Sn(t),"utf8"));if(!Array.isArray(r?.models))throw new Error("Codex custom end\
410
- point home is incomplete.");return r.models}var md=Object.freeze(["none","pending","committed","rolledBack","unknown"]);function k(t,{fallback:e=""}={}){return String(t||"").trim()||e}function se(t,{fallback:e=""}={}){return k(t,{fallback:e}).toLowerCase()}function Z(t,{fallback:e={}}={}){return R(t)?t:{...e}}function R(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}function K(t,{fallback:e=0}={}){let r=Number(t);return!Number.isInteger(r)||r<1?e:r}function ct(t,{fallback:e=null}={}){return t==null?e:typeof t=="string"?t.trim()||e:typeof t=="number"?Number.isFinite(t)?
411
- String(t):e:typeof t=="bigint"?String(t):e}var gd=1024*1024,Ed=256*1024;var wd=16*1024;import Cs from"node:path";var Ts=Object.freeze(["apps","artifact","browser_use","browser_use_external","browser_use_full_cdp_access","code_mode","\
408
+ form"}:{}}))}}function bn(t){return Se.join(t,"models.json")}async function Ge(t){let e=await Gt(Se.join(t,"config.toml"),"utf8").catch(n=>{if(n.code==="ENOENT")return"";throw n});if(!/^model_provider = "custom"$/mu.
409
+ test(e))return[];let r=JSON.parse(await Gt(bn(t),"utf8"));if(!Array.isArray(r?.models))throw new Error("Codex custom end\
410
+ point home is incomplete.");return r.models}var yd=Object.freeze(["none","pending","committed","rolledBack","unknown"]);function N(t,{fallback:e=""}={}){return String(t||"").trim()||e}function oe(t,{fallback:e=""}={}){return N(t,{fallback:e}).toLowerCase()}function Z(t,{fallback:e={}}={}){return I(t)?t:{...e}}function I(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}function Y(t,{fallback:e=0}={}){let r=Number(t);return!Number.isInteger(r)||r<1?e:r}function ut(t,{fallback:e=null}={}){return t==null?e:typeof t=="string"?t.trim()||e:typeof t=="number"?Number.isFinite(t)?
411
+ String(t):e:typeof t=="bigint"?String(t):e}var wd=1024*1024,Sd=256*1024;var bd=16*1024;import Is from"node:path";var Ps=Object.freeze(["apps","artifact","browser_use","browser_use_external","browser_use_full_cdp_access","code_mode","\
412
412
  code_mode_host","computer_use","default_mode_request_user_input","deferred_executor","goals","hooks","image_generation",
413
413
  "in_app_browser","memories","multi_agent","multi_agent_v2","plugins","psp","recommended_plugins","request_permissions_to\
414
414
  ol","shell_tool","skill_mcp_dependency_install","skill_search","tool_call_mcp_elicitation","tool_suggest","unified_exec",
415
- "unified_exec_zsh_fork","view_image"]);function bn(t){if(!t||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.
416
- values(t))bn(e);return Object.freeze(t)}function Is(t="",e={}){let r=new Error(z(t)||"Codex cannot prove the helper exec\
415
+ "unified_exec_zsh_fork","view_image"]);function xn(t){if(!t||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.
416
+ values(t))xn(e);return Object.freeze(t)}function Rs(t="",e={}){let r=new Error(z(t)||"Codex cannot prove the helper exec\
417
417
  ution policy.");r.code="codex_policy_unenforceable",r.details=Object.freeze({...e});for(let[n,o]of Object.entries(r.details))
418
- ["code","details","message","name"].includes(n)||(r[n]=o);return r}function xn({clientName:t="jskit",minimumVersion:e="0\
419
- .151.0",disabledFeatures:r=Ts,limits:{userAgentMaxLength:n=512,mcpServerMaxCount:o=128,mcpServerNameMaxLength:i=256,configResponseMaxBytes:s=256*
420
- 1024,hookMaxCount:a=256,hookErrorMaxCount:c=256,hookFieldMaxLength:u=2048,hookFingerprintMaxLength:l=256*1024,hookResponseMaxBytes:p=512*
421
- 1024}={},createError:d=Is}={}){let h=new WeakSet;function _(f,m,y){let g=0;try{g=Buffer.byteLength(JSON.stringify(f),"ut\
422
- f8")}catch{throw d(`Codex helper execution received an invalid ${y}.`)}if(g>m)throw d(`Codex helper execution received a\
423
- n oversized ${y}.`)}function E(f){if(typeof f?.currentConnectionGeneration!="function")throw d("Codex helper execution c\
424
- annot verify the app-server connection generation.");let m=f.currentConnectionGeneration();if(!Number.isSafeInteger(m)||
425
- m<=0)throw d("Codex helper execution found no active app-server connection.");return m}async function O(f){if(typeof f?.
426
- currentHelperExecutionContext!="function")throw d("Codex helper execution requires its dedicated isolated provider.");let m=await f.
427
- currentHelperExecutionContext(),y=z(m?.cwd),g=z(m?.accountIdentitySignature);if(m?.executionMode!=="helper"||!y||!Cs.isAbsolute(
428
- y)||!/^sha256:[a-f0-9]{64}$/u.test(g))throw d("Codex helper runtime isolation could not be verified.");return Object.freeze(
429
- {accountIdentitySignature:g,cwd:y,executionMode:"helper"})}function N(f=""){let m=z(f).match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u);
430
- if(!m)return null;let y=m.slice(1).map(g=>Number.parseInt(g,10));return y.every(Number.isSafeInteger)?y:null}function D(f=""){
431
- let m=z(f);if(!m||m.length>n||at(m))return null;let y=`${t}/`;if(!m.startsWith(y))return null;let g=m.slice(y.length).match(
432
- /^((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))(?:$|[ \t].*$)/u);return g?N(g[1]):null}function I(f){if(typeof f?.currentServerInfo!=
418
+ ["code","details","message","name"].includes(n)||(r[n]=o);return r}function On({clientName:t="jskit",minimumVersion:e="0\
419
+ .151.0",disabledFeatures:r=Ps,limits:{userAgentMaxLength:n=512,mcpServerMaxCount:o=128,mcpServerNameMaxLength:i=256,configResponseMaxBytes:s=256*
420
+ 1024,hookMaxCount:a=256,hookErrorMaxCount:c=256,hookFieldMaxLength:u=2048,hookFingerprintMaxLength:l=256*1024,hookResponseMaxBytes:m=512*
421
+ 1024}={},createError:d=Rs}={}){let _=new WeakSet;function g(f,p,h){let y=0;try{y=Buffer.byteLength(JSON.stringify(f),"ut\
422
+ f8")}catch{throw d(`Codex helper execution received an invalid ${h}.`)}if(y>p)throw d(`Codex helper execution received a\
423
+ n oversized ${h}.`)}function E(f){if(typeof f?.currentConnectionGeneration!="function")throw d("Codex helper execution c\
424
+ annot verify the app-server connection generation.");let p=f.currentConnectionGeneration();if(!Number.isSafeInteger(p)||
425
+ p<=0)throw d("Codex helper execution found no active app-server connection.");return p}async function x(f){if(typeof f?.
426
+ currentHelperExecutionContext!="function")throw d("Codex helper execution requires its dedicated isolated provider.");let p=await f.
427
+ currentHelperExecutionContext(),h=z(p?.cwd),y=z(p?.accountIdentitySignature);if(p?.executionMode!=="helper"||!h||!Is.isAbsolute(
428
+ h)||!/^sha256:[a-f0-9]{64}$/u.test(y))throw d("Codex helper runtime isolation could not be verified.");return Object.freeze(
429
+ {accountIdentitySignature:y,cwd:h,executionMode:"helper"})}function R(f=""){let p=z(f).match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u);
430
+ if(!p)return null;let h=p.slice(1).map(y=>Number.parseInt(y,10));return h.every(Number.isSafeInteger)?h:null}function k(f=""){
431
+ let p=z(f);if(!p||p.length>n||ct(p))return null;let h=`${t}/`;if(!p.startsWith(h))return null;let y=p.slice(h.length).match(
432
+ /^((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))(?:$|[ \t].*$)/u);return y?R(y[1]):null}function C(f){if(typeof f?.currentServerInfo!=
433
433
  "function")throw d("Codex helper execution cannot verify the app-server version. Update Codex and retry.",{minimumVersion:e});
434
- let m=z(f.currentServerInfo()?.userAgent),y=D(m);if(!y)throw d("Codex helper execution received an unrecognised app-serv\
435
- er version. Update Codex and retry.",{minimumVersion:e});let g=y.join("."),S=N(e),x=y.findIndex((T,$)=>T!==S[$]);if(x!==
436
- -1&&y[x]<S[x])throw d(`Codex helper execution requires app-server ${e} or newer; current version is ${g}. Update Codex a\
437
- nd retry.`,{actualVersion:g,minimumVersion:e});return Object.freeze({minimumVersion:e,version:g})}function C(f=null){if(!qt(
438
- f?.config))throw d("Codex helper execution could not read the effective app-server configuration.");let m=f.config.mcp_servers;
439
- if(m==null)return[];if(_(m,s,"MCP configuration"),!qt(m))throw d("Codex helper execution received an invalid MCP server \
440
- configuration.");let y=Object.keys(m);if(y.length>o||y.some(g=>!g||g.length>i||at(g)))throw d("Codex helper execution re\
441
- ceived an oversized or invalid MCP server inventory.");return y.sort()}function M(f=null,m=""){if(_(f,p,"hook inventory"),
434
+ let p=z(f.currentServerInfo()?.userAgent),h=k(p);if(!h)throw d("Codex helper execution received an unrecognised app-serv\
435
+ er version. Update Codex and retry.",{minimumVersion:e});let y=h.join("."),w=R(e),S=h.findIndex((P,L)=>P!==w[L]);if(S!==
436
+ -1&&h[S]<w[S])throw d(`Codex helper execution requires app-server ${e} or newer; current version is ${y}. Update Codex a\
437
+ nd retry.`,{actualVersion:y,minimumVersion:e});return Object.freeze({minimumVersion:e,version:y})}function v(f=null){if(!Ht(
438
+ f?.config))throw d("Codex helper execution could not read the effective app-server configuration.");let p=f.config.mcp_servers;
439
+ if(p==null)return[];if(g(p,s,"MCP configuration"),!Ht(p))throw d("Codex helper execution received an invalid MCP server \
440
+ configuration.");let h=Object.keys(p);if(h.length>o||h.some(y=>!y||y.length>i||ct(y)))throw d("Codex helper execution re\
441
+ ceived an oversized or invalid MCP server inventory.");return h.sort()}function D(f=null,p=""){if(g(f,m,"hook inventory"),
442
442
  !Array.isArray(f?.data))throw d("Codex helper execution could not enumerate app-server hooks.");if(f.data.length!==1)throw d(
443
- "Codex helper execution received an unexpected hook inventory.");let y=f.data[0];if(z(y?.cwd)!==m||z(y?.cwd).length>u||!Array.
444
- isArray(y.hooks)||!Array.isArray(y.errors)||y.hooks.length>a||y.errors.length>c)throw d("Codex helper execution received\
445
- an incomplete hook inventory.");if(y.errors.length>0)throw d("Codex helper execution cannot continue while hook discove\
446
- ry has errors.",{hookErrorCount:y.errors.length});let g=y.hooks.map(x=>{let T=z(x?.key),$=z(x?.currentHash),j=z(x?.handlerType),
447
- ne=z(x?.sourcePath);if(!T||[T,$,j,ne].some(oe=>oe.length>u||at(oe)))throw d("Codex helper execution found an invalid hoo\
448
- k inventory entry.");if(x?.isManaged===!0&&x?.enabled===!0)throw d("Codex helper execution cannot disable a managed hook\
449
- .");return{currentHash:$,enabled:x?.enabled===!0,handlerType:j,isManaged:x?.isManaged===!0,key:T,sourcePath:ne}}).sort((x,T)=>x.
450
- key.localeCompare(T.key)),S=JSON.stringify(g);if(S.length>l)throw d("Codex helper execution received an oversized hook i\
451
- nventory.");return{fingerprint:S,hookKeys:g.filter(x=>!x.isManaged).map(x=>x.key)}}function A({effort:f="",summary:m="",
452
- hookKeys:y=[],mcpServerNames:g=[]}={}){let S={features:Object.fromEntries(r.map(T=>[T,!1])),hooks:{state:Object.fromEntries(
453
- y.map(T=>[T,{enabled:!1}]))},include_apps_instructions:!1,include_collaboration_mode_instructions:!1,include_environment_context:!1,
454
- include_permissions_instructions:!1,...f?{model_reasoning_effort:f}:{},...m?{model_reasoning_summary:m}:{},mcp_servers:Object.
455
- fromEntries(g.map(T=>[T,{enabled:!1}])),memories:{dedicated_tools:!1,generate_memories:!1,use_memories:!1},notify:[],orchestrator:{
443
+ "Codex helper execution received an unexpected hook inventory.");let h=f.data[0];if(z(h?.cwd)!==p||z(h?.cwd).length>u||!Array.
444
+ isArray(h.hooks)||!Array.isArray(h.errors)||h.hooks.length>a||h.errors.length>c)throw d("Codex helper execution received\
445
+ an incomplete hook inventory.");if(h.errors.length>0)throw d("Codex helper execution cannot continue while hook discove\
446
+ ry has errors.",{hookErrorCount:h.errors.length});let y=h.hooks.map(S=>{let P=z(S?.key),L=z(S?.currentHash),V=z(S?.handlerType),
447
+ j=z(S?.sourcePath);if(!P||[P,L,V,j].some(ae=>ae.length>u||ct(ae)))throw d("Codex helper execution found an invalid hook \
448
+ inventory entry.");if(S?.isManaged===!0&&S?.enabled===!0)throw d("Codex helper execution cannot disable a managed hook.");
449
+ return{currentHash:L,enabled:S?.enabled===!0,handlerType:V,isManaged:S?.isManaged===!0,key:P,sourcePath:j}}).sort((S,P)=>S.
450
+ key.localeCompare(P.key)),w=JSON.stringify(y);if(w.length>l)throw d("Codex helper execution received an oversized hook i\
451
+ nventory.");return{fingerprint:w,hookKeys:y.filter(S=>!S.isManaged).map(S=>S.key)}}function O({effort:f="",summary:p="",
452
+ hookKeys:h=[],mcpServerNames:y=[]}={}){let w={features:Object.fromEntries(r.map(P=>[P,!1])),hooks:{state:Object.fromEntries(
453
+ h.map(P=>[P,{enabled:!1}]))},include_apps_instructions:!1,include_collaboration_mode_instructions:!1,include_environment_context:!1,
454
+ include_permissions_instructions:!1,...f?{model_reasoning_effort:f}:{},...p?{model_reasoning_summary:p}:{},mcp_servers:Object.
455
+ fromEntries(y.map(P=>[P,{enabled:!1}])),memories:{dedicated_tools:!1,generate_memories:!1,use_memories:!1},notify:[],orchestrator:{
456
456
  mcp:{enabled:!1},skills:{enabled:!1}},project_doc_max_bytes:0,shell_environment_policy:{inherit:"none",set:{}},skills:{include_instructions:!1},
457
- tools:{experimental_request_user_input:{enabled:!1},update_plan:{enabled:!1}},web_search:"disabled"},x=bn(S);return h.add(
458
- x),x}function v(f,m,y,{effort:g="",summary:S=""}={}){let x=C(f),T=M(m,y);return{mcpServerNames:x,hookState:T,config:A({effort:g,
459
- summary:S,hookKeys:T.hookKeys,mcpServerNames:x})}}async function b(f,{effort:m="",summary:y=""}={}){if(I(f),typeof f?.readConfig!=
457
+ tools:{experimental_request_user_input:{enabled:!1},update_plan:{enabled:!1}},web_search:"disabled"},S=xn(w);return _.add(
458
+ S),S}function A(f,p,h,{effort:y="",summary:w=""}={}){let S=v(f),P=D(p,h);return{mcpServerNames:S,hookState:P,config:O({effort:y,
459
+ summary:w,hookKeys:P.hookKeys,mcpServerNames:S})}}async function b(f,{effort:p="",summary:h=""}={}){if(C(f),typeof f?.readConfig!=
460
460
  "function"||typeof f?.listHooks!="function")throw d("Codex helper execution cannot inventory configuration and hooks.");
461
- let g=await O(f),S=E(f),x=await f.readConfig({cwd:g.cwd,includeLayers:!1});if(E(f)!==S)throw d("Codex app-server reconne\
462
- cted during helper policy verification.");let T=await f.listHooks([g.cwd]);if(E(f)!==S)throw d("Codex app-server reconne\
463
- cted during helper policy verification.");let{mcpServerNames:$,hookState:j,config:ne}=v(x,T,g.cwd,{effort:m,summary:y});
464
- return Object.freeze({accountIdentitySignature:g.accountIdentitySignature,config:ne,connectionGeneration:S,executionCwd:g.
465
- cwd,hookFingerprint:j.fingerprint,hookKeys:Object.freeze([...j.hookKeys]),mcpServerNames:Object.freeze([...$])})}function L(f=null,m=null){
466
- return f?.accountIdentitySignature===m?.accountIdentitySignature&&f?.connectionGeneration===m?.connectionGeneration&&f?.
467
- executionCwd===m?.executionCwd&&f?.hookFingerprint===m?.hookFingerprint&&JSON.stringify(f?.mcpServerNames||[])===JSON.stringify(
468
- m?.mcpServerNames||[])}function U(f,m,y=""){let g=z(y);if(!m)return f.codexAppServerHelperThreadId=g,f.codexAppServerHelperThreadRetired=
469
- !0,f;let S=d("Codex could not retire a helper thread after policy verification failed.",{cleanupFailed:!0,threadId:g});return S.
470
- codexAppServerHelperThreadCleanupRequired=!0,S.codexAppServerHelperThreadId=g,S}async function G({error:f=null,provider:m=null,
471
- threadId:y=""}={}){let g=null;try{await m.deleteThread(y)}catch(S){g=S}throw U(f,g,y)}async function Q(f,m,y,g,S){try{let x=await b(
472
- f,{effort:m.config.model_reasoning_effort,summary:m.config.model_reasoning_summary});if(!L(m,x))throw d(`Codex execution\
473
- surfaces changed while the helper thread was ${S}.`);return Object.freeze({enforcement:x,thread:y,threadId:g})}catch(x){
474
- await G({error:x,provider:f,threadId:g})}}async function B(f,m){if(typeof f?.startThread!="function"||typeof f?.deleteThread!=
475
- "function")throw d("Codex helper execution cannot own and clean up its app-server thread.");let y=await m(),g=await f.startThread(
476
- y.settings),S=z(g?.id);if(!S)throw d("Codex app-server did not return a helper thread id.");return Q(f,y.enforcement,g,S,
477
- "starting")}async function it(f,m,y){if(typeof f?.resumeThread!="function"||typeof f?.deleteThread!="function")throw d("\
478
- Codex helper execution cannot safely resume and clean up its app-server thread.");let g=z(m);if(!g)throw d("Codex helper\
479
- resume requires a controller-owned thread id.");let S=await y(),x=S.enforcement,T=await f.resumeThread(g,S.settings);return Q(
480
- f,x,T,g,"resuming")}function Ie(f){return h.has(f)}function st({configResult:f,hookResult:m,workdir:y,effort:g="",summary:S=""}){
481
- return v(f,m,y,{effort:g,summary:S}).config}function Vt({approvalPolicy:f,baseInstructions:m,config:y,cwd:g,effectiveSettings:S,
482
- sandbox:x,systemPrompt:T}){return{allowProviderModelFallback:!1,approvalPolicy:f,baseInstructions:m,config:y,cwd:g,systemPrompt:T||
483
- null,dynamicTools:[],environments:[],model:S.model,runtimeWorkspaceRoots:[],sandbox:x,selectedCapabilityRoots:[]}}function Bt(f,m){
484
- return{...f,sessionStartSource:"startup",threadSource:m}}function Ft(f){return{approvalPolicy:f.approvalPolicy,baseInstructions:f.
461
+ let y=await x(f),w=E(f),S=await f.readConfig({cwd:y.cwd,includeLayers:!1});if(E(f)!==w)throw d("Codex app-server reconne\
462
+ cted during helper policy verification.");let P=await f.listHooks([y.cwd]);if(E(f)!==w)throw d("Codex app-server reconne\
463
+ cted during helper policy verification.");let{mcpServerNames:L,hookState:V,config:j}=A(S,P,y.cwd,{effort:p,summary:h});return Object.
464
+ freeze({accountIdentitySignature:y.accountIdentitySignature,config:j,connectionGeneration:w,executionCwd:y.cwd,hookFingerprint:V.
465
+ fingerprint,hookKeys:Object.freeze([...V.hookKeys]),mcpServerNames:Object.freeze([...L])})}function M(f=null,p=null){return f?.
466
+ accountIdentitySignature===p?.accountIdentitySignature&&f?.connectionGeneration===p?.connectionGeneration&&f?.executionCwd===
467
+ p?.executionCwd&&f?.hookFingerprint===p?.hookFingerprint&&JSON.stringify(f?.mcpServerNames||[])===JSON.stringify(p?.mcpServerNames||
468
+ [])}function $(f,p,h=""){let y=z(h);if(!p)return f.codexAppServerHelperThreadId=y,f.codexAppServerHelperThreadRetired=!0,
469
+ f;let w=d("Codex could not retire a helper thread after policy verification failed.",{cleanupFailed:!0,threadId:y});return w.
470
+ codexAppServerHelperThreadCleanupRequired=!0,w.codexAppServerHelperThreadId=y,w}async function G({error:f=null,provider:p=null,
471
+ threadId:h=""}={}){let y=null;try{await p.deleteThread(h)}catch(w){y=w}throw $(f,y,h)}async function J(f,p,h,y,w){try{let S=await b(
472
+ f,{effort:p.config.model_reasoning_effort,summary:p.config.model_reasoning_summary});if(!M(p,S))throw d(`Codex execution\
473
+ surfaces changed while the helper thread was ${w}.`);return Object.freeze({enforcement:S,thread:h,threadId:y})}catch(S){
474
+ await G({error:S,provider:f,threadId:y})}}async function W(f,p){if(typeof f?.startThread!="function"||typeof f?.deleteThread!=
475
+ "function")throw d("Codex helper execution cannot own and clean up its app-server thread.");let h=await p(),y=await f.startThread(
476
+ h.settings),w=z(y?.id);if(!w)throw d("Codex app-server did not return a helper thread id.");return J(f,h.enforcement,y,w,
477
+ "starting")}async function we(f,p,h){if(typeof f?.resumeThread!="function"||typeof f?.deleteThread!="function")throw d("\
478
+ Codex helper execution cannot safely resume and clean up its app-server thread.");let y=z(p);if(!y)throw d("Codex helper\
479
+ resume requires a controller-owned thread id.");let w=await h(),S=w.enforcement,P=await f.resumeThread(y,w.settings);return J(
480
+ f,S,P,y,"resuming")}function st(f){return _.has(f)}function Pe({configResult:f,hookResult:p,workdir:h,effort:y="",summary:w=""}){
481
+ return A(f,p,h,{effort:y,summary:w}).config}function at({approvalPolicy:f,baseInstructions:p,config:h,cwd:y,effectiveSettings:w,
482
+ sandbox:S,systemPrompt:P}){return{allowProviderModelFallback:!1,approvalPolicy:f,baseInstructions:p,config:h,cwd:y,systemPrompt:P||
483
+ null,dynamicTools:[],environments:[],model:w.model,runtimeWorkspaceRoots:[],sandbox:S,selectedCapabilityRoots:[]}}function Bt(f,p){
484
+ return{...f,sessionStartSource:"startup",threadSource:p}}function Ft(f){return{approvalPolicy:f.approvalPolicy,baseInstructions:f.
485
485
  baseInstructions,config:f.config,cwd:f.cwd,systemPrompt:f.systemPrompt,model:f.model,runtimeWorkspaceRoots:f.runtimeWorkspaceRoots,
486
- sandbox:f.sandbox}}function w({approvalPolicy:f,cwd:m,effectiveSettings:y,outputSchema:g}){let S={approvalPolicy:f,cwd:m,
487
- environments:[],model:y.model,outputSchema:g,runtimeWorkspaceRoots:[],sandboxPolicy:{networkAccess:!1,type:"readOnly"},summary:"\
488
- none"};return y.request.reasoning&&(S.effort=y.thinking),S}return Object.freeze({assertCompatibility:I,executionContext:O,
489
- inspect:b,configuration:st,hasConfiguration:Ie,threadSettings:Vt,threadStartSettings:Bt,threadResumeSettings:Ft,turnSettings:w,
490
- start:B,resume:it})}var Ad=xn();import{spawn as Zs}from"node:child_process";import{chmod as yf,mkdir as _f,readFile as gf,readdir as Ef,rename as ea,rm as ta,
491
- stat as wf,writeFile as ra}from"node:fs/promises";import na from"node:os";import jn from"node:path";import{execFile as Ds}from"node:child_process";import{readFile as Wt,readdir as Ms}from"node:fs/promises";import{setTimeout as On}from"node:timers/promises";import{promisify as Ls}from"node:util";var zs=Ls(Ds);async function $s(t){
492
- let{stdout:e}=await zs("ps",t,{env:{...process.env,LC_ALL:"C",TZ:"UTC"},maxBuffer:67108864});return e}function Xt({runtimeTokenEnvironmentName:t="\
486
+ sandbox:f.sandbox}}function qt({approvalPolicy:f,cwd:p,effectiveSettings:h,outputSchema:y}){let w={approvalPolicy:f,cwd:p,
487
+ environments:[],model:h.model,outputSchema:y,runtimeWorkspaceRoots:[],sandboxPolicy:{networkAccess:!1,type:"readOnly"},summary:"\
488
+ none"};return h.request.reasoning&&(w.effort=h.thinking),w}return Object.freeze({assertCompatibility:C,executionContext:x,
489
+ inspect:b,configuration:Pe,hasConfiguration:st,threadSettings:at,threadStartSettings:Bt,threadResumeSettings:Ft,turnSettings:qt,
490
+ start:W,resume:we})}var Cd=On();import{spawn as ta}from"node:child_process";import{chmod as gf,mkdir as Ef,readFile as wf,readdir as Sf,rename as ra,rm as na,
491
+ stat as bf,writeFile as oa}from"node:fs/promises";import ia from"node:os";import Mn from"node:path";import{execFile as Ls}from"node:child_process";import{readFile as Xt,readdir as zs}from"node:fs/promises";import{setTimeout as An}from"node:timers/promises";import{promisify as $s}from"node:util";var Us=$s(Ls),vn=32;async function Vs(t){
492
+ let{stdout:e}=await Us("ps",t,{env:{...process.env,LC_ALL:"C",TZ:"UTC"},maxBuffer:67108864});return e}function Jt({runtimeTokenEnvironmentName:t="\
493
493
  JSKIT_EXECUTION_RUNTIME_TOKEN",commandHashEnvironmentName:e="JSKIT_EXECUTION_COMMAND_HASH",label:r="Native",unavailableCode:n="\
494
- native_process_identity_unavailable",platform:o=process.platform,ps:i=$s}={}){let a=o==="darwin"?100:25,c=1,u=Object.freeze(
495
- {linux:"linux-proc",darwin:"darwin"}),l=u[o]||"",p=Object.freeze({RUNNING:"running",STOPPED:"stopped"}),d=Object.freeze(
496
- {ABSENT:"absent",AMBIGUOUS:"ambiguous",EXACT:"exact",INVALID:"invalid",MISMATCH:"mismatch"});function h(w={}){return!!(Number.
497
- isSafeInteger(Number(w.pid))&&Number(w.pid)>0&&I(w.processIdentity)&&[p.RUNNING,p.STOPPED].includes(w.processState))}function _(w){
498
- let f=Number(w);if(!Number.isSafeInteger(f)||f<=0)return!1;try{return process.kill(f,0),!0}catch{return!1}}function E(w){
499
- let f=Number(w);if(!Number.isSafeInteger(f)||f<=0)return!1;if(process.platform==="win32")return _(f);try{return process.
500
- kill(-f,0),!0}catch{return!1}}function O(w,f){let m=Number(w),y=process.platform==="win32"?m:-m;try{return process.kill(
501
- y,f),!0}catch(g){if(!["ESRCH","EPERM"].includes(String(g?.code||"")))throw g;return!1}}function N(w=""){let f=String(w||
502
- ""),m=f.lastIndexOf(")");if(m<0)return null;let y=f.slice(m+1).trim().split(/\s+/u),g=String(y[0]||""),S=Number(y[1]),x=Number(
503
- y[2]),T=String(y[19]||"");return!/^[A-Z]$/u.test(g)||!Number.isSafeInteger(S)||S<0||!Number.isSafeInteger(x)||x<=0||!/^\d+$/u.
504
- test(T)?null:{parentPid:S,processGroupId:x,startTimeTicks:T,state:g}}function D(w={}){let f=R(w)?w:{};return{commandHash:z(
505
- f.commandHash),platform:z(f.platform),runtimeToken:z(f.runtimeToken),startTimeTicks:z(f.startTimeTicks),version:Number(f.
506
- version||0)}}function I(w={}){let f=D(w);return!!(f.version===c&&Object.values(u).includes(f.platform)&&/^[a-f0-9]{12}$/u.
507
- test(f.commandHash)&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(f.runtimeToken)&&/^\d+$/u.
508
- test(f.startTimeTicks))}function C(w=[],f=""){let m=w.find(y=>y.startsWith(`${f}=`));return m?m.slice(f.length+1):""}async function M(){
509
- let w=[],f=await Ms("/proc",{withFileTypes:!0}).catch(()=>[]);for(let m of f){if(!m.isDirectory()||!/^\d+$/u.test(m.name))
510
- continue;let y=Number(m.name),g=await Wt(`/proc/${m.name}/stat`,"utf8").catch(()=>""),S=N(g);if(!S||S.state==="Z")continue;
511
- let x=null,T=!0;try{x=await Wt(`/proc/${m.name}/environ`)}catch(j){if(String(j?.code||"")==="ENOENT")continue;T=!1}let $=T?
512
- x.toString("utf8").split("\0"):[];w.push({...S,commandHash:C($,e),environmentReadable:T,pid:y,runtimeToken:C($,t)})}return w}
513
- let A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function v(w=""){let f=/^\w{3}\s+(\w{3})\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})$/u.
514
- exec(String(w).trim()),m=f?A.indexOf(f[1]):-1;if(m<0)return"";let[,,y,g,S,x,T]=f.map(Number);return String(Date.UTC(T,m,
515
- y,g,S,x)/1e3)}function b(w=""){let f=new Map;for(let m of String(w).split(`
516
- `)){let y=/^\s*(\d+) (.*)$/u.exec(m);y&&f.set(Number(y[1]),y[2])}return f}function L(w,f){if(w===void 0||!f?.startsWith(
517
- w))return null;let m=f.slice(w.length).split(/\s+/u).filter(y=>/^[^=\s]+=/u.test(y));return m.length?m:null}async function U(){
518
- let w=process.getuid(),f=["-x","-U",String(w),"-ww","-o","pid=,command="],[m,y,g]=await Promise.all([i(["-ax","-o","pid=\
519
- ,pgid=,uid=,stat=,lstart="]),i(f),i(["-E",...f])]),S=b(y),x=b(g),T=[];for(let $ of String(m).split(`
520
- `)){let j=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\w{3}\s+\w{3}\s+\d{1,2}\s+[\d:]{8}\s+\d{4})\s*$/u.exec($);if(!j||j[4].startsWith(
521
- "Z"))continue;let ne=Number(j[1]),oe=Number(j[3])===w?L(S.get(ne),x.get(ne)):null;T.push({commandHash:C(oe||[],e),environmentReadable:!!oe,
522
- pid:ne,processGroupId:Number(j[2]),runtimeToken:C(oe||[],t),startTimeTicks:v(j[5])})}return T}function G(w){let f=Object.
523
- values(d).includes(w?.status)?w.status:d.AMBIGUOUS;return{processGroupIds:[...new Set((Array.isArray(w?.processGroupIds)?
524
- w.processGroupIds:[]).map(Number).filter(m=>Number.isSafeInteger(m)&&m>0))],status:f}}async function Q(w={}){if(!h(w))return{
525
- processGroupIds:[],status:d.INVALID};if(w.processState===p.STOPPED)return{processGroupIds:[],status:d.ABSENT};let f=w.processIdentity,
526
- m=f.platform!==l?null:o==="darwin"?await U().catch(()=>null):await M();if(!m)return{processGroupIds:[],status:d.AMBIGUOUS};
527
- let y=Number(w.pid),g=m.filter(({processGroupId:j})=>j===y),S=[],x=g.some(({environmentReadable:j})=>!j);for(let j of m)
528
- j.environmentReadable&&j.runtimeToken===f.runtimeToken&&j.commandHash===f.commandHash&&S.push(j);let T=S.find(({pid:j})=>j===
529
- y);if(T&&T.startTimeTicks!==f.startTimeTicks)return{processGroupIds:[],status:d.AMBIGUOUS};if(S.length===0)return x?{processGroupIds:[],
530
- status:d.AMBIGUOUS}:{processGroupIds:[],status:g.length>0||E(y)?d.MISMATCH:d.ABSENT};let $=[...new Set(S.map(({processGroupId:j})=>j))];
531
- for(let j of $)if(m.filter(oe=>oe.processGroupId===j).some(oe=>!oe.environmentReadable||!S.some(({pid:hs})=>hs===oe.pid)))
532
- return{processGroupIds:[],status:d.AMBIGUOUS};return g.some(j=>!S.some(({pid:ne})=>ne===j.pid))?{processGroupIds:[],status:d.
533
- AMBIGUOUS}:{processGroupIds:$,status:d.EXACT}}async function B(w={},f={}){let m=f.processIdentityInspector??Q;return G(await m(
534
- w))}async function it(w={},f={},m=0){let y=Date.now()+m,g=await B(w,f);for(;Date.now()<y&&g.status===d.EXACT;)await On(100),
535
- g=await B(w,f);return g}async function Ie(w={},f={}){let m=K(f.processIdentitySettleTimeoutMs,{fallback:1e3}),y=K(f.processIdentitySettlePollMs,
536
- {fallback:a}),g=Date.now()+m,S=await B(w,f);for(;S.status===d.AMBIGUOUS&&Date.now()<g;)await On(Math.min(y,Math.max(1,g-
537
- Date.now()))),S=await B(w,f);return S}async function st(w={},f="SIGTERM",m={}){let y=m.signalProcessGroup??O,g=await Ie(
538
- w,m);if(g.status!==d.EXACT)return{inspection:g,signaledProcessGroups:[]};let S=Number(w.pid),x=[...g.processGroupIds.filter(
539
- $=>$!==S),...g.processGroupIds.filter($=>$===S)],T=[];for(let $ of x){let j=await Ie(w,m);if(j.status===d.ABSENT||j.status===
540
- d.MISMATCH)return{inspection:j,signaledProcessGroups:T};if(j.status!==d.EXACT)return{inspection:j,signaledProcessGroups:T};
541
- j.processGroupIds.includes($)&&(y($,f),T.push($))}return{inspection:await Ie(w,m),signaledProcessGroups:T}}async function Vt(w={},f={}){
542
- if(!h(w))return{identityStatus:d.INVALID,processExitVerified:!1,stopped:!1};if(w.processState===p.STOPPED&&w.processExitVerifiedAt)
543
- return{alreadyStopped:!0,identityStatus:d.ABSENT,processExitVerified:!0,stopped:!1};let m=await Ie(w,f);if(m.status===d.
544
- ABSENT||m.status===d.MISMATCH)return{identityStatus:m.status,processExitVerified:!0,stopped:!1};if(m.status!==d.EXACT)return{
545
- identityStatus:m.status,processExitVerified:!1,stopped:!1};let y=await st(w,"SIGTERM",f);if(y.inspection.status===d.AMBIGUOUS)
494
+ native_process_identity_unavailable",platform:o=process.platform,ps:i=Vs}={}){let a=o==="darwin"?100:25,c=1,u=Object.freeze(
495
+ {linux:"linux-proc",darwin:"darwin"}),l=u[o]||"",m=Object.freeze({RUNNING:"running",STOPPED:"stopped"}),d=Object.freeze(
496
+ {ABSENT:"absent",AMBIGUOUS:"ambiguous",EXACT:"exact",INVALID:"invalid",MISMATCH:"mismatch"});function _(f={}){return!!(Number.
497
+ isSafeInteger(Number(f.pid))&&Number(f.pid)>0&&C(f.processIdentity)&&[m.RUNNING,m.STOPPED].includes(f.processState))}function g(f){
498
+ let p=Number(f);if(!Number.isSafeInteger(p)||p<=0)return!1;try{return process.kill(p,0),!0}catch{return!1}}function E(f){
499
+ let p=Number(f);if(!Number.isSafeInteger(p)||p<=0)return!1;if(process.platform==="win32")return g(p);try{return process.
500
+ kill(-p,0),!0}catch{return!1}}function x(f,p){let h=Number(f),y=process.platform==="win32"?h:-h;try{return process.kill(
501
+ y,p),!0}catch(w){if(!["ESRCH","EPERM"].includes(String(w?.code||"")))throw w;return!1}}function R(f=""){let p=String(f||
502
+ ""),h=p.lastIndexOf(")");if(h<0)return null;let y=p.slice(h+1).trim().split(/\s+/u),w=String(y[0]||""),S=Number(y[1]),P=Number(
503
+ y[2]),L=String(y[19]||"");return!/^[A-Z]$/u.test(w)||!Number.isSafeInteger(S)||S<0||!Number.isSafeInteger(P)||P<=0||!/^\d+$/u.
504
+ test(L)?null:{parentPid:S,processGroupId:P,startTimeTicks:L,state:w}}function k(f={}){let p=I(f)?f:{};return{commandHash:z(
505
+ p.commandHash),platform:z(p.platform),runtimeToken:z(p.runtimeToken),startTimeTicks:z(p.startTimeTicks),version:Number(p.
506
+ version||0)}}function C(f={}){let p=k(f);return!!(p.version===c&&Object.values(u).includes(p.platform)&&/^[a-f0-9]{12}$/u.
507
+ test(p.commandHash)&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(p.runtimeToken)&&/^\d+$/u.
508
+ test(p.startTimeTicks))}function v(f=[],p=""){let h=f.find(y=>y.startsWith(`${p}=`));return h?h.slice(p.length+1):""}async function D(f){
509
+ let p=await Xt(`/proc/${f}/stat`,"utf8").catch(()=>""),h=R(p);if(!h||h.state==="Z")return null;let y=null,w=!0;try{y=await Xt(
510
+ `/proc/${f}/environ`)}catch(P){if(String(P?.code||"")==="ENOENT")return null;w=!1}let S=w?y.toString("utf8").split("\0"):
511
+ [];return{...h,commandHash:v(S,e),environmentReadable:w,pid:Number(f),runtimeToken:v(S,t)}}async function O(){let f=(await zs(
512
+ "/proc",{withFileTypes:!0}).catch(()=>[])).filter(h=>h.isDirectory()&&/^\d+$/u.test(h.name)).map(h=>h.name),p=[];for(let h=0;h<
513
+ f.length;h+=vn)for(let y of await Promise.all(f.slice(h,h+vn).map(D)))y&&p.push(y);return p}let A=["Jan","Feb","Mar","Ap\
514
+ r","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function b(f=""){let p=/^\w{3}\s+(\w{3})\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})$/u.
515
+ exec(String(f).trim()),h=p?A.indexOf(p[1]):-1;if(h<0)return"";let[,,y,w,S,P,L]=p.map(Number);return String(Date.UTC(L,h,
516
+ y,w,S,P)/1e3)}function M(f=""){let p=new Map;for(let h of String(f).split(`
517
+ `)){let y=/^\s*(\d+) (.*)$/u.exec(h);y&&p.set(Number(y[1]),y[2])}return p}function $(f,p){if(f===void 0||!p?.startsWith(
518
+ f))return null;let h=p.slice(f.length).split(/\s+/u).filter(y=>/^[^=\s]+=/u.test(y));return h.length?h:null}async function G(){
519
+ let f=process.getuid(),p=["-x","-U",String(f),"-ww","-o","pid=,command="],[h,y,w]=await Promise.all([i(["-ax","-o","pid=\
520
+ ,pgid=,uid=,stat=,lstart="]),i(p),i(["-E",...p])]),S=M(y),P=M(w),L=[];for(let V of String(h).split(`
521
+ `)){let j=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\w{3}\s+\w{3}\s+\d{1,2}\s+[\d:]{8}\s+\d{4})\s*$/u.exec(V);if(!j||j[4].startsWith(
522
+ "Z"))continue;let ae=Number(j[1]),me=Number(j[3])===f?$(S.get(ae),P.get(ae)):null;L.push({commandHash:v(me||[],e),environmentReadable:!!me,
523
+ pid:ae,processGroupId:Number(j[2]),runtimeToken:v(me||[],t),startTimeTicks:b(j[5])})}return L}function J(f){let p=Object.
524
+ values(d).includes(f?.status)?f.status:d.AMBIGUOUS;return{processGroupIds:[...new Set((Array.isArray(f?.processGroupIds)?
525
+ f.processGroupIds:[]).map(Number).filter(h=>Number.isSafeInteger(h)&&h>0))],status:p}}async function W(f={}){if(!_(f))return{
526
+ processGroupIds:[],status:d.INVALID};if(f.processState===m.STOPPED)return{processGroupIds:[],status:d.ABSENT};let p=f.processIdentity,
527
+ h=p.platform!==l?null:o==="darwin"?await G().catch(()=>null):await O();if(!h)return{processGroupIds:[],status:d.AMBIGUOUS};
528
+ let y=Number(f.pid),w=h.filter(({processGroupId:j})=>j===y),S=[],P=w.some(({environmentReadable:j})=>!j);for(let j of h)
529
+ j.environmentReadable&&j.runtimeToken===p.runtimeToken&&j.commandHash===p.commandHash&&S.push(j);let L=S.find(({pid:j})=>j===
530
+ y);if(L&&L.startTimeTicks!==p.startTimeTicks)return{processGroupIds:[],status:d.AMBIGUOUS};if(S.length===0)return P?{processGroupIds:[],
531
+ status:d.AMBIGUOUS}:{processGroupIds:[],status:w.length>0||E(y)?d.MISMATCH:d.ABSENT};let V=[...new Set(S.map(({processGroupId:j})=>j))];
532
+ for(let j of V)if(h.filter(me=>me.processGroupId===j).some(me=>!me.environmentReadable||!S.some(({pid:_s})=>_s===me.pid)))
533
+ return{processGroupIds:[],status:d.AMBIGUOUS};return w.some(j=>!S.some(({pid:ae})=>ae===j.pid))?{processGroupIds:[],status:d.
534
+ AMBIGUOUS}:{processGroupIds:V,status:d.EXACT}}async function we(f={},p={}){let h=p.processIdentityInspector??W;return J(
535
+ await h(f))}async function st(f={},p={},h=0){let y=Date.now()+h,w=await we(f,p);for(;Date.now()<y&&w.status===d.EXACT;)await An(
536
+ 100),w=await we(f,p);return w}async function Pe(f={},p={}){let h=Y(p.processIdentitySettleTimeoutMs,{fallback:1e3}),y=Y(
537
+ p.processIdentitySettlePollMs,{fallback:a}),w=Date.now()+h,S=await we(f,p);for(;S.status===d.AMBIGUOUS&&Date.now()<w;)await An(
538
+ Math.min(y,Math.max(1,w-Date.now()))),S=await we(f,p);return S}async function at(f={},p="SIGTERM",h={}){let y=h.signalProcessGroup??
539
+ x,w=await Pe(f,h);if(w.status!==d.EXACT)return{inspection:w,signaledProcessGroups:[]};let S=Number(f.pid),P=[...w.processGroupIds.
540
+ filter(V=>V!==S),...w.processGroupIds.filter(V=>V===S)],L=[];for(let V of P){let j=await Pe(f,h);if(j.status===d.ABSENT||
541
+ j.status===d.MISMATCH)return{inspection:j,signaledProcessGroups:L};if(j.status!==d.EXACT)return{inspection:j,signaledProcessGroups:L};
542
+ j.processGroupIds.includes(V)&&(y(V,p),L.push(V))}return{inspection:await Pe(f,h),signaledProcessGroups:L}}async function Bt(f={},p={}){
543
+ if(!_(f))return{identityStatus:d.INVALID,processExitVerified:!1,stopped:!1};if(f.processState===m.STOPPED&&f.processExitVerifiedAt)
544
+ return{alreadyStopped:!0,identityStatus:d.ABSENT,processExitVerified:!0,stopped:!1};let h=await Pe(f,p);if(h.status===d.
545
+ ABSENT||h.status===d.MISMATCH)return{identityStatus:h.status,processExitVerified:!0,stopped:!1};if(h.status!==d.EXACT)return{
546
+ identityStatus:h.status,processExitVerified:!1,stopped:!1};let y=await at(f,"SIGTERM",p);if(y.inspection.status===d.AMBIGUOUS)
546
547
  return{identityStatus:y.inspection.status,processExitVerified:!1,signaledProcessGroups:y.signaledProcessGroups,stopped:!1};
547
- let g=await it(w,f,K(f.termTimeoutMs,{fallback:3e3})),S=[...y.signaledProcessGroups];if(g.status===d.EXACT){let T=await st(
548
- w,"SIGKILL",f);if(S=[...new Set([...S,...T.signaledProcessGroups])],T.inspection.status===d.AMBIGUOUS)return{identityStatus:T.
549
- inspection.status,processExitVerified:!1,signaledProcessGroups:S,stopped:!1};g=await it(w,f,K(f.killTimeoutMs,{fallback:1e3}))}
550
- let x=[d.ABSENT,d.MISMATCH].includes(g.status);return{descendantProcessGroups:S.filter(T=>T!==Number(w.pid)),identityStatus:g.
551
- status,pid:Number(w.pid),processExitVerified:x,signaledProcessGroups:S,stopped:x&&S.length>0}}async function Bt(w){if(o!==
552
- "darwin")return N(await Wt(`/proc/${w}/stat`,"utf8").catch(()=>""));let f=String(await i(["-o","pgid=,lstart=","-p",String(
553
- w)]).catch(()=>"")),m=/^\s*(\d+)\s+(.+?)\s*$/u.exec(f);return m?{processGroupId:Number(m[1]),startTimeTicks:v(m[2])}:null}
554
- async function Ft({commandHash:w="",pid:f=null,reportedIdentity:m=null,runtimeToken:y=""}={}){let g=z(w),S=z(y),x=D(m);if(I(
555
- x)&&x.commandHash===g&&x.runtimeToken===S)return x;let T=Number(f),$=l&&Number.isSafeInteger(T)&&T>0?await Bt(T):null;if(!$?.
556
- startTimeTicks||$.processGroupId!==T){let j=new Error(`${r} process identity could not be captured.`);throw j.code=n,j}return{
557
- commandHash:g,platform:l,runtimeToken:S,startTimeTicks:$.startTimeTicks,version:c}}return Object.freeze({normalize:D,isValid:I,
558
- normalizeInspection:G,capture:Ft,inspect:B,stop:Vt,isProcessAlive:_})}function ut(t){return R(t)?{...t}:{}}var ee=class extends Error{constructor(e,r,n={}){super(r,n.cause===void 0?void 0:{cause:n.cause}),this.name="AppError",this.
559
- status=Number(e)||500,this.statusCode=this.status,this.code=n.code||"APP_ERROR",this.params=ut(n.params),n.messageCode&&
560
- (this.messageCode=String(n.messageCode),this.messageParams=ut(n.messageParams)),this.details=n.details,this.headers=n.headers||
561
- {}}};import{open as Us,realpath as vn}from"node:fs/promises";import{isUtf8 as Vs}from"node:buffer";import{createServer as Bs}from"node:http";
562
- import Fs from"node:path";import{Readable as qs}from"node:stream";import{isDeepStrictEqual as Cn}from"node:util";import{
563
- gunzipSync as Hs,zstdDecompressSync as Gs}from"node:zlib";var lt=(t,e,r,n={})=>Object.freeze({id:t,contextWindow:e,variants:Object.freeze(r),...n}),An=Object.freeze([Object.freeze(
548
+ let w=await st(f,p,Y(p.termTimeoutMs,{fallback:3e3})),S=[...y.signaledProcessGroups];if(w.status===d.EXACT){let L=await at(
549
+ f,"SIGKILL",p);if(S=[...new Set([...S,...L.signaledProcessGroups])],L.inspection.status===d.AMBIGUOUS)return{identityStatus:L.
550
+ inspection.status,processExitVerified:!1,signaledProcessGroups:S,stopped:!1};w=await st(f,p,Y(p.killTimeoutMs,{fallback:1e3}))}
551
+ let P=[d.ABSENT,d.MISMATCH].includes(w.status);return{descendantProcessGroups:S.filter(L=>L!==Number(f.pid)),identityStatus:w.
552
+ status,pid:Number(f.pid),processExitVerified:P,signaledProcessGroups:S,stopped:P&&S.length>0}}async function Ft(f){if(o!==
553
+ "darwin")return R(await Xt(`/proc/${f}/stat`,"utf8").catch(()=>""));let p=String(await i(["-o","pgid=,lstart=","-p",String(
554
+ f)]).catch(()=>"")),h=/^\s*(\d+)\s+(.+?)\s*$/u.exec(p);return h?{processGroupId:Number(h[1]),startTimeTicks:b(h[2])}:null}
555
+ async function qt({commandHash:f="",pid:p=null,reportedIdentity:h=null,runtimeToken:y=""}={}){let w=z(f),S=z(y),P=k(h);if(C(
556
+ P)&&P.commandHash===w&&P.runtimeToken===S)return P;let L=Number(p),V=l&&Number.isSafeInteger(L)&&L>0?await Ft(L):null;if(!V?.
557
+ startTimeTicks||V.processGroupId!==L){let j=new Error(`${r} process identity could not be captured.`);throw j.code=n,j}return{
558
+ commandHash:w,platform:l,runtimeToken:S,startTimeTicks:V.startTimeTicks,version:c}}return Object.freeze({normalize:k,isValid:C,
559
+ normalizeInspection:J,capture:qt,inspect:we,stop:Bt,isProcessAlive:g})}function lt(t){return I(t)?{...t}:{}}var ee=class extends Error{constructor(e,r,n={}){super(r,n.cause===void 0?void 0:{cause:n.cause}),this.name="AppError",this.
560
+ status=Number(e)||500,this.statusCode=this.status,this.code=n.code||"APP_ERROR",this.params=lt(n.params),n.messageCode&&
561
+ (this.messageCode=String(n.messageCode),this.messageParams=lt(n.messageParams)),this.details=n.details,this.headers=n.headers||
562
+ {}}};import{open as Bs,realpath as Tn}from"node:fs/promises";import{isUtf8 as Fs}from"node:buffer";import{createServer as qs}from"node:http";
563
+ import Hs from"node:path";import{Readable as Gs}from"node:stream";import{isDeepStrictEqual as In}from"node:util";import{
564
+ gunzipSync as Ws,zstdDecompressSync as Xs}from"node:zlib";var dt=(t,e,r,n={})=>Object.freeze({id:t,contextWindow:e,variants:Object.freeze(r),...n}),Cn=Object.freeze([Object.freeze(
564
565
  {id:"deepseek",baseUrl:"https://api.deepseek.com/",claudeBaseUrl:"https://api.deepseek.com/anthropic",claudeAutoCompactWindow:786432,
565
- webSearch:!1,models:Object.freeze([lt("deepseek-flash",1048576,["low","high","max"],{images:!0,freeformPatch:!0,codexHistoryRouting:!0}),
566
- lt("deepseek-v4-pro",1048576,["low","high","max"],{freeformPatch:!0,codexHistoryRouting:!0})])}),Object.freeze({id:"zai-\
566
+ webSearch:!1,models:Object.freeze([dt("deepseek-flash",1048576,["low","high","max"],{images:!0,freeformPatch:!0,codexHistoryRouting:!0}),
567
+ dt("deepseek-v4-pro",1048576,["low","high","max"],{freeformPatch:!0,codexHistoryRouting:!0})])}),Object.freeze({id:"zai-\
567
568
  coding-plan",baseUrl:"https://api.z.ai/api/v1",claudeBaseUrl:"https://api.z.ai/api/anthropic",claudeAutoCompactWindow:1e6,
568
- webSearch:!1,models:Object.freeze([lt("glm-5.3",1048576,["low","high","max"],{freeformPatch:!0,codexHistoryRouting:!0})])}),
569
+ webSearch:!1,models:Object.freeze([dt("glm-5.3",1048576,["low","high","max"],{freeformPatch:!0,codexHistoryRouting:!0})])}),
569
570
  Object.freeze({id:"zai",baseUrl:"https://api.z.ai/api/v1",claudeBaseUrl:"https://api.z.ai/api/anthropic",claudeAutoCompactWindow:1e6,
570
- webSearch:!1,models:Object.freeze([lt("glm-5.3",1048576,["low","high","max"],{freeformPatch:!0,codexHistoryRouting:!0})])})]),
571
- ue="custom";function ae(t){return An.find(e=>e.id===t)||null}function dt(t,e=""){for(let r of An){if(e&&r.id!==e)continue;let n=r.models.
572
- find(o=>o.id===t);if(n)return{...n,modelProviderId:r.id}}return null}var Rn=32*1024*1024,Ws=Object.freeze({chatgpt:"https://chatgpt.com/backend-api/codex",apiKey:"https://api.openai.com/v1",
573
- deepseek:ae("deepseek").baseUrl.replace(/\/$/u,""),"zai-coding-plan":ae("zai-coding-plan").baseUrl,zai:ae("zai").baseUrl}),
574
- Xs=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"];function Nn(t){
575
- return!!(ae(t)||t===ue)}function Js(t=""){let e;try{e=new URL(Buffer.from(t,"base64url").toString("utf8"))}catch{return}return["http:","https:"].
576
- includes(e.protocol)&&!e.username&&!e.password&&!e.search&&!e.hash?e.href.replace(/\/$/u,""):void 0}function Yt(t){return new ee(
577
- 422,t,{code:"assistant_codex_history_unsupported"})}function Tn(t){let e=typeof t.output=="string"?[{type:"input_text",text:t.
571
+ webSearch:!1,models:Object.freeze([dt("glm-5.3",1048576,["low","high","max"],{freeformPatch:!0,codexHistoryRouting:!0})])})]),
572
+ ce="custom";function ie(t){return Cn.find(e=>e.id===t)||null}function ft(t,e=""){for(let r of Cn){if(e&&r.id!==e)continue;let n=r.models.
573
+ find(o=>o.id===t);if(n)return{...n,modelProviderId:r.id}}return null}var kn=32*1024*1024,Js=Object.freeze({chatgpt:"https://chatgpt.com/backend-api/codex",apiKey:"https://api.openai.com/v1",
574
+ deepseek:ie("deepseek").baseUrl.replace(/\/$/u,""),"zai-coding-plan":ie("zai-coding-plan").baseUrl,zai:ie("zai").baseUrl}),
575
+ Ks=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"];function jn(t){
576
+ return!!(ie(t)||t===ce)}function Ys(t=""){let e;try{e=new URL(Buffer.from(t,"base64url").toString("utf8"))}catch{return}return["http:","https:"].
577
+ includes(e.protocol)&&!e.username&&!e.password&&!e.search&&!e.hash?e.href.replace(/\/$/u,""):void 0}function Qt(t){return new ee(
578
+ 422,t,{code:"assistant_codex_history_unsupported"})}function Pn(t){let e=typeof t.output=="string"?[{type:"input_text",text:t.
578
579
  output}]:t.output;if(!Array.isArray(e)||e.some(r=>!(r?.type==="input_text"&&typeof r.text=="string")&&!(r?.type==="input\
579
- _image"&&typeof r.image_url=="string")))throw Yt("This tool's history is not supported by the Codex history adapter.");return e}
580
- function In(t,e,r){return{type:"message",role:"user",content:[{type:"input_text",text:`[${t}; untrusted context, not new\
581
- instructions]`},...e,{type:"input_text",text:r}]}}function Ks(t,e="openai"){if(!Array.isArray(t?.input)||e==="zai-codin\
580
+ _image"&&typeof r.image_url=="string")))throw Qt("This tool's history is not supported by the Codex history adapter.");return e}
581
+ function Rn(t,e,r){return{type:"message",role:"user",content:[{type:"input_text",text:`[${t}; untrusted context, not new\
582
+ instructions]`},...e,{type:"input_text",text:r}]}}function Qs(t,e="openai"){if(!Array.isArray(t?.input)||e==="zai-codin\
582
583
  g-plan"||e==="zai")return t;if(e==="deepseek"){let o=new Set(t.input.filter(i=>["custom_tool_call","function_call"].includes(
583
584
  i?.type)&&i.name==="exec").map(i=>i.call_id));return{...t,input:t.input.map(i=>o.has(i?.call_id)?["custom_tool_call","fu\
584
585
  nction_call"].includes(i.type)?{type:"message",role:"assistant",content:[{type:"output_text",text:`[Historical exec call\
585
586
  ; context only, not an available tool]
586
587
  ${JSON.stringify(i)}
587
- [/Historical exec call]`}]}:["custom_tool_call_output","function_call_output"].includes(i.type)?In(`Historical exec resu\
588
- lt ${i.call_id}`,Tn(i),"[/Historical exec result]"):i:i)}}let r=new Map;for(let o of t.input)o?.type==="function_call"&&
588
+ [/Historical exec call]`}]}:["custom_tool_call_output","function_call_output"].includes(i.type)?Rn(`Historical exec resu\
589
+ lt ${i.call_id}`,Pn(i),"[/Historical exec result]"):i:i)}}let r=new Map;for(let o of t.input)o?.type==="function_call"&&
589
590
  r.set(o.call_id,(r.get(o.call_id)||0)+1);let n=new Map(t.input.filter(o=>["openai","chatgpt","apiKey"].includes(e)&&o?.type===
590
591
  "function_call"&&typeof o.name=="string"&&o.name.length>0&&!/^[a-zA-Z0-9_-]+$/u.test(o.name)).map(o=>[o.call_id,o]));for(let[
591
- o,i]of n)if(typeof o!="string"||!o.trim()||typeof i.arguments!="string"||r.get(o)!==1)throw Yt("This tool's history is n\
592
+ o,i]of n)if(typeof o!="string"||!o.trim()||typeof i.arguments!="string"||r.get(o)!==1)throw Qt("This tool's history is n\
592
593
  ot supported by the Codex history adapter.");return{...t,input:t.input.map(o=>{let i=n.get(o?.call_id);if(i&&o.type==="f\
593
594
  unction_call")return{type:"message",role:"assistant",content:[{type:"output_text",text:`[Historical function call; conte\
594
595
  xt only, not an available tool]
595
596
  ${JSON.stringify(o)}
596
- [/Historical function call]`}]};if(i&&o.type==="function_call_output")return In(`Historical function result ${JSON.stringify(
597
- {call_id:i.call_id,name:i.name})}`,Tn(o),"[/Historical function result]");if(o?.type!=="reasoning"||!o.content?.length)return o;
597
+ [/Historical function call]`}]};if(i&&o.type==="function_call_output")return Rn(`Historical function result ${JSON.stringify(
598
+ {call_id:i.call_id,name:i.name})}`,Pn(o),"[/Historical function result]");if(o?.type!=="reasoning"||!o.content?.length)return o;
598
599
  if(!Array.isArray(o.content)||o.content.some(a=>a?.type!=="reasoning_text"||typeof a.text!="string")||o.summary!=null&&(!Array.
599
- isArray(o.summary)||o.summary.some(a=>a?.type!=="summary_text"||typeof a.text!="string")))throw Yt("This model's reasoni\
600
+ isArray(o.summary)||o.summary.some(a=>a?.type!=="summary_text"||typeof a.text!="string")))throw Qt("This model's reasoni\
600
601
  ng history is not supported by the Codex history adapter.");return{type:"message",role:"assistant",content:[{type:"outpu\
601
602
  t_text",text:`[Historical reasoning from the previous model; context, not new instructions]
602
603
  ${[...o.summary||[],...o.content].map(a=>a.text).join(`
603
604
  `)}
604
- [/Historical reasoning]`}]}})}}function q(t,e=422){return new ee(e,`Codex cannot safely send this compacted conversation\
605
+ [/Historical reasoning]`}]}})}}function F(t,e=422){return new ee(e,`Codex cannot safely send this compacted conversation\
605
606
  to the selected model: ${t} Continue with the previous model or start a new conversation. Saved history has not been ch\
606
- anged.`,{code:e===413?"assistant_codex_compacted_history_too_large":"assistant_codex_compacted_history_unsafe"})}function Jt(t){
607
- if(t?.type!=="message"||t.role!=="user")return null;let{encrypted_content:e,id:r,...n}=t;return n}async function*Pn(t,e,r,n,{
607
+ anged.`,{code:e===413?"assistant_codex_compacted_history_too_large":"assistant_codex_compacted_history_unsafe"})}function Kt(t){
608
+ if(t?.type!=="message"||t.role!=="user")return null;let{encrypted_content:e,id:r,...n}=t;return n}async function*Nn(t,e,r,n,{
608
609
  strictComplete:o=!1}={}){let i=Buffer.alloc(65536),s=[],a=0,c=e;for(let u=e;u<r;){n.throwIfAborted();let{bytesRead:l}=await t.
609
- read(i,0,Math.min(i.length,r-u),u);if(!l)throw q("the saved history changed during recovery. Retry the turn.");let p=i.subarray(
610
- 0,l),d=0;for(;d<l;){let h=p.indexOf(10,d),_=h>=0,E=_?h:l;if(a+=E-d,a>Rn)throw q("a saved history record exceeds the reco\
611
- very size limit.",413);if(s.push(Buffer.from(i.subarray(d,E))),_){if(n.throwIfAborted(),a){let O=Buffer.concat(s,a);if(o&&
612
- !Vs(O))throw q("the saved history contains invalid UTF-8.");yield{row:JSON.parse(O.toString("utf8")),offset:c}}s=[],a=0,
613
- c=u+h+1}d=E+(_?1:0)}u+=l}if(o&&a)throw q("the saved history has an incomplete final record.")}async function Ys(t,{destination:e,
614
- historyPath:r,codexHome:n,signal:o,maxRequestBytes:i}){if(!Nn(e)||!Array.isArray(t?.input)||!t.input.some(p=>p?.type==="\
615
- compaction"))return t;let s=e===ue?{modelProviderId:e,codexHistoryRouting:!0}:dt(t.model,e);if(s?.modelProviderId!==e||!s.
616
- codexHistoryRouting)throw q("this model has not been qualified for history recovery.");if(!r||!n)throw q("the native his\
617
- tory location is unavailable.");o.throwIfAborted();let a,c=new Map(t.input.filter(p=>p?.type==="compaction").map(p=>[p.encrypted_content,
618
- {count:0}]));try{let p=await vn(n),d=await vn(r),h=Fs.relative(p,d),_=/^(?:sessions\/\d{4}\/\d{2}\/\d{2}|archived_sessions)\/rollout-[^/]+-([0-9a-f-]{36})\.jsonl$/iu.
619
- exec(h);if(!_)throw q("the history is outside this Codex runtime's saved conversations.");a=await Us(d,"r");let E=await a.
620
- stat();if(!E.isFile())throw q("the saved history is not a regular file.");let O=0,N=0;for await(let{row:I,offset:C}of Pn(
621
- a,0,E.size,o)){if(I.type==="session_meta"&&(O+=1,I.payload?.id!==_[1]||I.payload?.forked_from_id))throw q("the saved his\
622
- tory does not identify one supported conversation.");if(I.type==="event_msg"&&I.payload?.type==="thread_rolled_back")throw q(
623
- "history recovery after Undo is not supported yet.");if(I.type!=="compacted")continue;let M=I.payload?.replacement_history;
624
- for(let[A,v]of c)typeof A=="string"&&A.length&&M?.some(b=>b?.type==="compaction"&&b.encrypted_content===A)&&(v.count+=1,
625
- v.start=N,v.end=C,v.retainedUsers=M.map(Jt).filter(Boolean));typeof I.payload?.message=="string"&&I.payload.message.trim()&&
626
- Array.isArray(M)&&M.length&&!M.some(A=>A?.type==="compaction")&&(N=C)}if(O!==1)throw q("the saved history does not ident\
627
- ify one supported conversation.");let D=0;for(let I of c.values()){if(I.count!==1)throw q("its exact saved compaction bo\
628
- undary could not be identified.");I.history=[];for await(let{row:C,offset:M}of Pn(a,I.start,I.end,o)){let A=[];C.type===
629
- "response_item"?A=[C.payload]:C.type==="compacted"&&M===I.start&&(A=C.payload.replacement_history);for(let v of A||[])if(!(v?.
630
- type==="compaction"||v?.type==="message"&&["developer","system"].includes(v.role))){if(D+=Buffer.byteLength(JSON.stringify(
631
- v)),D>i)throw q("the recovered history exceeds the request size limit.",413);I.history.push(v)}}}}catch(p){throw o.aborted||
632
- p.statusCode?p:q("the native history could not be read completely.")}finally{await a?.close()}let u=[],l=Buffer.byteLength(
633
- JSON.stringify(t));for(let[p,d]of t.input.entries()){if(u.push(d),d?.type!=="compaction")continue;let h=c.get(d.encrypted_content).
634
- history,_=t.input.slice(0,p).map(Jt).filter(Boolean),E=c.get(d.encrypted_content).retainedUsers.filter(C=>{let M=_.findIndex(
635
- A=>Cn(A,C));return M<0?!1:(_.splice(M,1),!0)}),O=[],N=[],D=0;for(let C of h){if(!["message","agent_message","reasoning",
636
- "function_call","function_call_output","custom_tool_call","custom_tool_call_output"].includes(C?.type))throw q("the save\
637
- d history contains an unsupported item.");let{encrypted_content:M,id:A,...v}=C,b=Jt(C),L=N.length;for(let G of["content",
638
- "summary","output"]){let Q=C[G];if(!(Q==null||typeof Q=="string")){if(!Array.isArray(Q))throw q("the saved history conta\
639
- ins unsupported content.");v[G]=Q.map(B=>{if(["input_text","output_text","reasoning_text","summary_text"].includes(B?.type)&&
640
- typeof B.text=="string")return B;if(C.type==="agent_message"&&G==="content"&&B?.type==="encrypted_content"&&typeof B.encrypted_content==
641
- "string"&&B.encrypted_content)return{type:"input_text",text:"[Encrypted agent-message content is unavailable to this pro\
642
- vider; retained in saved native history.]"};if(B?.type==="input_image"&&typeof B.image_url=="string"&&B.image_url){if(!s.
643
- images)throw q("the selected model does not support images in recovered history.");return N.push(B),{type:"input_image",
644
- archived_image:N.length}}throw q("recovery of this non-text history is not supported yet.")})}}let U=b&&E.findIndex(G=>Cn(
645
- G,b));if(b&&U>=0){E.splice(U,1),N.length=L,D+=1;continue}C.type==="reasoning"&&!C.content?.length&&!C.summary?.length||O.
646
- push(v)}if(!O.length){if(D)continue;throw q("the original readable conversation is missing.")}let I={type:"message",role:"\
610
+ read(i,0,Math.min(i.length,r-u),u);if(!l)throw F("the saved history changed during recovery. Retry the turn.");let m=i.subarray(
611
+ 0,l),d=0;for(;d<l;){let _=m.indexOf(10,d),g=_>=0,E=g?_:l;if(a+=E-d,a>kn)throw F("a saved history record exceeds the reco\
612
+ very size limit.",413);if(s.push(Buffer.from(i.subarray(d,E))),g){if(n.throwIfAborted(),a){let x=Buffer.concat(s,a);if(o&&
613
+ !Fs(x))throw F("the saved history contains invalid UTF-8.");yield{row:JSON.parse(x.toString("utf8")),offset:c}}s=[],a=0,
614
+ c=u+_+1}d=E+(g?1:0)}u+=l}if(o&&a)throw F("the saved history has an incomplete final record.")}async function Zs(t,{destination:e,
615
+ historyPath:r,codexHome:n,signal:o,maxRequestBytes:i}){if(!jn(e)||!Array.isArray(t?.input)||!t.input.some(m=>m?.type==="\
616
+ compaction"))return t;let s=e===ce?{modelProviderId:e,codexHistoryRouting:!0}:ft(t.model,e);if(s?.modelProviderId!==e||!s.
617
+ codexHistoryRouting)throw F("this model has not been qualified for history recovery.");if(!r||!n)throw F("the native his\
618
+ tory location is unavailable.");o.throwIfAborted();let a,c=new Map(t.input.filter(m=>m?.type==="compaction").map(m=>[m.encrypted_content,
619
+ {count:0}]));try{let m=await Tn(n),d=await Tn(r),_=Hs.relative(m,d),g=/^(?:sessions\/\d{4}\/\d{2}\/\d{2}|archived_sessions)\/rollout-[^/]+-([0-9a-f-]{36})\.jsonl$/iu.
620
+ exec(_);if(!g)throw F("the history is outside this Codex runtime's saved conversations.");a=await Bs(d,"r");let E=await a.
621
+ stat();if(!E.isFile())throw F("the saved history is not a regular file.");let x=0,R=0;for await(let{row:C,offset:v}of Nn(
622
+ a,0,E.size,o)){if(C.type==="session_meta"&&(x+=1,C.payload?.id!==g[1]||C.payload?.forked_from_id))throw F("the saved his\
623
+ tory does not identify one supported conversation.");if(C.type==="event_msg"&&C.payload?.type==="thread_rolled_back")throw F(
624
+ "history recovery after Undo is not supported yet.");if(C.type!=="compacted")continue;let D=C.payload?.replacement_history;
625
+ for(let[O,A]of c)typeof O=="string"&&O.length&&D?.some(b=>b?.type==="compaction"&&b.encrypted_content===O)&&(A.count+=1,
626
+ A.start=R,A.end=v,A.retainedUsers=D.map(Kt).filter(Boolean));typeof C.payload?.message=="string"&&C.payload.message.trim()&&
627
+ Array.isArray(D)&&D.length&&!D.some(O=>O?.type==="compaction")&&(R=v)}if(x!==1)throw F("the saved history does not ident\
628
+ ify one supported conversation.");let k=0;for(let C of c.values()){if(C.count!==1)throw F("its exact saved compaction bo\
629
+ undary could not be identified.");C.history=[];for await(let{row:v,offset:D}of Nn(a,C.start,C.end,o)){let O=[];v.type===
630
+ "response_item"?O=[v.payload]:v.type==="compacted"&&D===C.start&&(O=v.payload.replacement_history);for(let A of O||[])if(!(A?.
631
+ type==="compaction"||A?.type==="message"&&["developer","system"].includes(A.role))){if(k+=Buffer.byteLength(JSON.stringify(
632
+ A)),k>i)throw F("the recovered history exceeds the request size limit.",413);C.history.push(A)}}}}catch(m){throw o.aborted||
633
+ m.statusCode?m:F("the native history could not be read completely.")}finally{await a?.close()}let u=[],l=Buffer.byteLength(
634
+ JSON.stringify(t));for(let[m,d]of t.input.entries()){if(u.push(d),d?.type!=="compaction")continue;let _=c.get(d.encrypted_content).
635
+ history,g=t.input.slice(0,m).map(Kt).filter(Boolean),E=c.get(d.encrypted_content).retainedUsers.filter(v=>{let D=g.findIndex(
636
+ O=>In(O,v));return D<0?!1:(g.splice(D,1),!0)}),x=[],R=[],k=0;for(let v of _){if(!["message","agent_message","reasoning",
637
+ "function_call","function_call_output","custom_tool_call","custom_tool_call_output"].includes(v?.type))throw F("the save\
638
+ d history contains an unsupported item.");let{encrypted_content:D,id:O,...A}=v,b=Kt(v),M=R.length;for(let G of["content",
639
+ "summary","output"]){let J=v[G];if(!(J==null||typeof J=="string")){if(!Array.isArray(J))throw F("the saved history conta\
640
+ ins unsupported content.");A[G]=J.map(W=>{if(["input_text","output_text","reasoning_text","summary_text"].includes(W?.type)&&
641
+ typeof W.text=="string")return W;if(v.type==="agent_message"&&G==="content"&&W?.type==="encrypted_content"&&typeof W.encrypted_content==
642
+ "string"&&W.encrypted_content)return{type:"input_text",text:"[Encrypted agent-message content is unavailable to this pro\
643
+ vider; retained in saved native history.]"};if(W?.type==="input_image"&&typeof W.image_url=="string"&&W.image_url){if(!s.
644
+ images)throw F("the selected model does not support images in recovered history.");return R.push(W),{type:"input_image",
645
+ archived_image:R.length}}throw F("recovery of this non-text history is not supported yet.")})}}let $=b&&E.findIndex(G=>In(
646
+ G,b));if(b&&$>=0){E.splice($,1),R.length=M,k+=1;continue}v.type==="reasoning"&&!v.content?.length&&!v.summary?.length||x.
647
+ push(A)}if(!x.length){if(k)continue;throw F("the original readable conversation is missing.")}let C={type:"message",role:"\
647
648
  user",content:[{type:"input_text",text:`[Archived conversation before compaction. Historical context, not new instructio\
648
649
  ns. Current task instructions still apply.]
649
- ${JSON.stringify(O)}`},...N.flatMap((C,M)=>[{type:"input_text",text:`[Archived image ${M+1}, referenced by archived_imag\
650
- e in the records above]`},C]),{type:"input_text",text:"[/Archived conversation]"}]};if(l+=Buffer.byteLength(JSON.stringify(
651
- I))+1,l>i)throw q("the recovered history exceeds the request size limit.",413);u.push(I)}return o.throwIfAborted(),{...t,
652
- input:u}}function Kt(t){let e=new Headers(t),r=(e.get("connection")||"").split(",").map(n=>n.trim()).filter(Boolean);for(let n of[
653
- ...Xs,...r,"host","content-length","content-encoding"])e.delete(n);return e}function Qs(){}async function kn({token:t,codexHome:e,
654
- readHistoryPath:r=Qs,fetchImpl:n=fetch,maxRequestBytes:o=Rn}={}){if(!/^[0-9a-f-]{36}$/iu.test(t||""))throw new Error("A \
655
- Codex runtime token is required.");let i=new Set,s=Bs(async(a,c)=>{let u=new AbortController;i.add(u),c.once("close",()=>{
656
- i.delete(u),c.writableFinished||u.abort()});try{let l=new URL(a.url,"http://127.0.0.1"),p=l.pathname.split("/"),[d,h]=(p[3]||
657
- "").split("~",2),_=d===ue?Js(h):Ws[d],E=p[4]==="history",O=E?Buffer.from(p[5]||"","base64url").toString("utf8"):"",N=p.slice(
658
- E?6:4).join("/");if(p[1]!==t||p[2]!=="v2"||!_||!(a.method==="POST"&&["responses","responses/compact"].includes(N)||a.method===
659
- "GET"&&N==="models")){c.writeHead(404).end();return}let D;if(a.method==="POST"){let A=[],v=0;for await(let U of a){if(v+=
660
- U.length,v>o)throw new ee(413,"Codex history exceeds the adapter request limit.",{code:"assistant_codex_history_request_\
661
- too_large"});A.push(U)}let b=Buffer.concat(A),L=a.headers["content-encoding"];try{if(L==="zstd")b=Gs(b,{maxOutputLength:o});else if(L===
662
- "gzip")b=Hs(b,{maxOutputLength:o});else if(L&&L!=="identity")throw new Error("Unsupported encoding");D=JSON.parse(b.toString(
650
+ ${JSON.stringify(x)}`},...R.flatMap((v,D)=>[{type:"input_text",text:`[Archived image ${D+1}, referenced by archived_imag\
651
+ e in the records above]`},v]),{type:"input_text",text:"[/Archived conversation]"}]};if(l+=Buffer.byteLength(JSON.stringify(
652
+ C))+1,l>i)throw F("the recovered history exceeds the request size limit.",413);u.push(C)}return o.throwIfAborted(),{...t,
653
+ input:u}}function Yt(t){let e=new Headers(t),r=(e.get("connection")||"").split(",").map(n=>n.trim()).filter(Boolean);for(let n of[
654
+ ...Ks,...r,"host","content-length","content-encoding"])e.delete(n);return e}function ea(){}async function Dn({token:t,codexHome:e,
655
+ readHistoryPath:r=ea,fetchImpl:n=fetch,maxRequestBytes:o=kn}={}){if(!/^[0-9a-f-]{36}$/iu.test(t||""))throw new Error("A \
656
+ Codex runtime token is required.");let i=new Set,s=qs(async(a,c)=>{let u=new AbortController;i.add(u),c.once("close",()=>{
657
+ i.delete(u),c.writableFinished||u.abort()});try{let l=new URL(a.url,"http://127.0.0.1"),m=l.pathname.split("/"),[d,_]=(m[3]||
658
+ "").split("~",2),g=d===ce?Ys(_):Js[d],E=m[4]==="history",x=E?Buffer.from(m[5]||"","base64url").toString("utf8"):"",R=m.slice(
659
+ E?6:4).join("/");if(m[1]!==t||m[2]!=="v2"||!g||!(a.method==="POST"&&["responses","responses/compact"].includes(R)||a.method===
660
+ "GET"&&R==="models")){c.writeHead(404).end();return}let k;if(a.method==="POST"){let O=[],A=0;for await(let $ of a){if(A+=
661
+ $.length,A>o)throw new ee(413,"Codex history exceeds the adapter request limit.",{code:"assistant_codex_history_request_\
662
+ too_large"});O.push($)}let b=Buffer.concat(O),M=a.headers["content-encoding"];try{if(M==="zstd")b=Xs(b,{maxOutputLength:o});else if(M===
663
+ "gzip")b=Ws(b,{maxOutputLength:o});else if(M&&M!=="identity")throw new Error("Unsupported encoding");k=JSON.parse(b.toString(
663
664
  "utf8"))}catch{throw new ee(400,"Codex sent an unreadable or oversized history request.",{code:"assistant_codex_history_\
664
- request_unreadable"})}if(!O&&Nn(d)&&Array.isArray(D?.input)&&D.input.some(U=>U?.type==="compaction")&&(O=await r(u.signal)),
665
- D=await Ys(D,{destination:d,historyPath:O,codexHome:e,signal:u.signal,maxRequestBytes:o}),D=JSON.stringify(Ks(D,d)),Buffer.
666
- byteLength(D)>o)throw q("the translated history exceeds the request size limit.",413)}let I=Kt(a.headers);I.set("accept-\
667
- encoding","identity");let C;try{C=await n(`${_}/${N}${l.search}`,{method:a.method,headers:I,body:D,signal:u.signal,redirect:"\
668
- error"})}catch(A){throw d!==ue||u.signal.aborted?A:Object.assign(new ee(502,`Your model server at ${_} isn't answering. \
669
- Start it, then send your message again.`,{code:"assistant_custom_endpoint_unreachable"}),{params:{upstream:_}})}if(d==="\
670
- deepseek"&&C.status===400&&C.headers.get("content-type")?.split(";",1)[0].trim()==="application/json"){let A=Buffer.from(
671
- await C.arrayBuffer());try{let v=JSON.parse(A.toString("utf8")),b=v?.error,L=typeof b?.message=="string"&&/^This model's maximum context length is ([1-9]\d*) tokens\. However, you requested ([1-9]\d*) tokens \((\d+) in the messages, (\d+) in the completion\)\. Please reduce the length of the messages or completion\. \(request_id: [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\)$/u.
672
- exec(b.message);if(b?.type==="invalid_request_error"&&b.code==="invalid_request_error"&&L){let[U,G,Q,B]=L.slice(1).map(Number);
673
- [U,G,Q,B].every(Number.isSafeInteger)&&G>U&&G===Q+B&&(b.code="context_length_exceeded",A=Buffer.from(JSON.stringify(v)))}}catch{}
674
- c.writeHead(C.status,Object.fromEntries(Kt(C.headers))).end(A);return}if(c.writeHead(C.status,Object.fromEntries(Kt(C.headers))),
675
- !C.body){c.end();return}let M=qs.fromWeb(C.body);M.once("error",()=>c.destroy()),c.once("close",()=>M.destroy()),M.pipe(
665
+ request_unreadable"})}if(!x&&jn(d)&&Array.isArray(k?.input)&&k.input.some($=>$?.type==="compaction")&&(x=await r(u.signal)),
666
+ k=await Zs(k,{destination:d,historyPath:x,codexHome:e,signal:u.signal,maxRequestBytes:o}),k=JSON.stringify(Qs(k,d)),Buffer.
667
+ byteLength(k)>o)throw F("the translated history exceeds the request size limit.",413)}let C=Yt(a.headers);C.set("accept-\
668
+ encoding","identity");let v;try{v=await n(`${g}/${R}${l.search}`,{method:a.method,headers:C,body:k,signal:u.signal,redirect:"\
669
+ error"})}catch(O){throw d!==ce||u.signal.aborted?O:Object.assign(new ee(502,`Your model server at ${g} isn't answering. \
670
+ Start it, then send your message again.`,{code:"assistant_custom_endpoint_unreachable"}),{params:{upstream:g}})}if(d==="\
671
+ deepseek"&&v.status===400&&v.headers.get("content-type")?.split(";",1)[0].trim()==="application/json"){let O=Buffer.from(
672
+ await v.arrayBuffer());try{let A=JSON.parse(O.toString("utf8")),b=A?.error,M=typeof b?.message=="string"&&/^This model's maximum context length is ([1-9]\d*) tokens\. However, you requested ([1-9]\d*) tokens \((\d+) in the messages, (\d+) in the completion\)\. Please reduce the length of the messages or completion\. \(request_id: [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\)$/u.
673
+ exec(b.message);if(b?.type==="invalid_request_error"&&b.code==="invalid_request_error"&&M){let[$,G,J,W]=M.slice(1).map(Number);
674
+ [$,G,J,W].every(Number.isSafeInteger)&&G>$&&G===J+W&&(b.code="context_length_exceeded",O=Buffer.from(JSON.stringify(A)))}}catch{}
675
+ c.writeHead(v.status,Object.fromEntries(Yt(v.headers))).end(O);return}if(c.writeHead(v.status,Object.fromEntries(Yt(v.headers))),
676
+ !v.body){c.end();return}let D=Gs.fromWeb(v.body);D.once("error",()=>c.destroy()),c.once("close",()=>D.destroy()),D.pipe(
676
677
  c)}catch(l){if(c.destroyed)return;if(c.headersSent){c.destroy();return}c.writeHead(l.statusCode||502,{"content-type":"ap\
677
678
  plication/json"}).end(JSON.stringify({error:{message:l.statusCode?l.message:"The Codex history adapter could not reach t\
678
679
  he model provider. Retry the turn."}}))}});return s.on("upgrade",(a,c)=>{c.end(`HTTP/1.1 426 Upgrade Required\r
@@ -681,311 +682,311 @@ Content-Length: 0\r
681
682
  \r
682
683
  `)}),await new Promise((a,c)=>{s.once("error",c),s.listen(0,"127.0.0.1",()=>{s.removeListener("error",c),a()})}),{baseUrl:`\
683
684
  http://127.0.0.1:${s.address().port}/${t}/v2`,server:s,async close(){for(let c of i)c.abort();let a=new Promise(c=>s.close(
684
- c));s.closeAllConnections(),await a}}}var Dn=Object.freeze({HELPER:"helper",INTERACTIVE:"interactive"}),Tf=Xt();async function Qt({runtimeDir:t,command:e,args:r=[],
685
+ c));s.closeAllConnections(),await a}}}var Ln=Object.freeze({HELPER:"helper",INTERACTIVE:"interactive"}),Pf=Jt();async function Zt({runtimeDir:t,command:e,args:r=[],
685
686
  runtimeToken:n,bundled:o=!1,additionalModels:i=[],env:s}){if(!s)throw new TypeError("runCodexAppServerProcess requires t\
686
- he application's environment, such as process.env.");let a=jn.join(t,"history-adapter.json"),c=new AbortController,u=()=>c.
687
- abort();process.once("SIGTERM",u),process.once("SIGINT",u);let l=s.CODEX_HOME||jn.join(na.homedir(),".codex"),p=await He(
688
- l),d=await wn({command:e,runtimeDir:t,bundled:o,additionalModels:[...i,...p],codexHome:l,signal:c.signal}),h=await kn({token:n,
689
- codexHome:l});await ra(`${a}.tmp`,JSON.stringify({baseUrl:h.baseUrl,runtimeToken:n}),{mode:384}),await ea(`${a}.tmp`,a);
690
- let _=Zs(e,[...r,"-c",`model_catalog_json=${JSON.stringify(d)}`],{stdio:"inherit"}),E=!1,O;function N(I="SIGTERM"){E||(E=
691
- !0,h.close(),_.kill(I),O=setTimeout(()=>_.kill("SIGKILL"),5e3),O.unref())}process.on("SIGTERM",()=>N()),process.on("SIGI\
692
- NT",()=>N("SIGINT")),process.removeListener("SIGTERM",u),process.removeListener("SIGINT",u),c.signal.aborted&&N(),h.server.
693
- on("error",()=>{process.exitCode=1,N()});let D=await new Promise(I=>{_.once("error",()=>I({code:1})),_.once("exit",(C,M)=>I(
694
- {code:C,signal:M}))});clearTimeout(O),await h.close(),await ta(a,{force:!0}),process.exitCode||=D.code??(E?0:1)}var Zt=Object.freeze({UNIX:"unix"});var oa=process.platform==="linux"?107:103,Mn=Object.freeze({MISSING:"missing",RESPONSIVE:"responsive",TIMEOUT:"timeout",
695
- UNREACHABLE:"unreachable"}),ia=Object.freeze({EXITED:"exited",INCOMPATIBLE:"incompatible",LIVE:"live",MISSING:"missing",
696
- SUSPECT:"suspect"}),er=Object.freeze({RUNNING:"running",STOPPED:"stopped"}),Ln=Object.freeze({ABSENT:"absent",AMBIGUOUS:"\
697
- ambiguous",EXACT:"exact",INVALID:"invalid",MISMATCH:"mismatch"});var sa=Object.freeze({runtimeToken:"JSKIT_EXECUTION_RUNTIME_TOKEN",modelCatalogSource:"JSKIT_CODEX_MODEL_CATALOG_SOURCE",
698
- commandHash:"JSKIT_EXECUTION_COMMAND_HASH"});var Cc=he(ko(),1),Tc=he(wt(),1),Ic=he(Ne(),1),Pc=he(dr(),1),Rc=he(mr(),1),Nc=he(wr(),1),kc=he(Ot(),1),jc=he(Vo(),1);var Mp=new URL("./../../../../@jskit-ai/assistant-core/src/server/conversation/codexRuntime.js",import.meta.url).href;var Yp=16*1024*1024;function H(t){if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null||
699
- Xc(e)}function Xc(t){return t!==null&&typeof t=="object"&&Object.getPrototypeOf(t)===null&&Reflect.ownKeys(t).length===0}function Or(t){return t!==null&&typeof t=="object"&&H(t.structure)&&H(t.operations)&&typeof t.validateWith=="function"&&
700
- typeof t.toJsonSchema=="function"&&typeof t.cleanup=="function"}function vt(t,e){if(!Object.hasOwn(e,"items"))return null;
701
- let{items:r}=e;if(Or(r))return{kind:"schema",schema:r};if(!H(r)||typeof r.type!="string")throw new Error(`Array field "${t}\
702
- " must define items as either a Schema instance or a field definition object.`);return{kind:"definition",definition:r}}function Ze(t,e){
703
- if(!Object.hasOwn(e,"values"))return null;let{values:r}=e;if(Or(r))return{kind:"schema",schema:r};if(!H(r)||typeof r.type!=
687
+ he application's environment, such as process.env.");let a=Mn.join(t,"history-adapter.json"),c=new AbortController,u=()=>c.
688
+ abort();process.once("SIGTERM",u),process.once("SIGINT",u);let l=s.CODEX_HOME||Mn.join(ia.homedir(),".codex"),m=await Ge(
689
+ l),d=await Sn({command:e,runtimeDir:t,bundled:o,additionalModels:[...i,...m],codexHome:l,signal:c.signal}),_=await Dn({token:n,
690
+ codexHome:l});await oa(`${a}.tmp`,JSON.stringify({baseUrl:_.baseUrl,runtimeToken:n}),{mode:384}),await ra(`${a}.tmp`,a);
691
+ let g=ta(e,[...r,"-c",`model_catalog_json=${JSON.stringify(d)}`],{stdio:"inherit"}),E=!1,x;function R(C="SIGTERM"){E||(E=
692
+ !0,_.close(),g.kill(C),x=setTimeout(()=>g.kill("SIGKILL"),5e3),x.unref())}process.on("SIGTERM",()=>R()),process.on("SIGI\
693
+ NT",()=>R("SIGINT")),process.removeListener("SIGTERM",u),process.removeListener("SIGINT",u),c.signal.aborted&&R(),_.server.
694
+ on("error",()=>{process.exitCode=1,R()});let k=await new Promise(C=>{g.once("error",()=>C({code:1})),g.once("exit",(v,D)=>C(
695
+ {code:v,signal:D}))});clearTimeout(x),await _.close(),await na(a,{force:!0}),process.exitCode||=k.code??(E?0:1)}var er=Object.freeze({UNIX:"unix"});var sa=process.platform==="linux"?107:103,zn=Object.freeze({MISSING:"missing",RESPONSIVE:"responsive",TIMEOUT:"timeout",
696
+ UNREACHABLE:"unreachable"}),aa=Object.freeze({EXITED:"exited",INCOMPATIBLE:"incompatible",LIVE:"live",MISSING:"missing",
697
+ SUSPECT:"suspect"}),tr=Object.freeze({RUNNING:"running",STOPPED:"stopped"}),$n=Object.freeze({ABSENT:"absent",AMBIGUOUS:"\
698
+ ambiguous",EXACT:"exact",INVALID:"invalid",MISMATCH:"mismatch"});var ca=Object.freeze({runtimeToken:"JSKIT_EXECUTION_RUNTIME_TOKEN",modelCatalogSource:"JSKIT_CODEX_MODEL_CATALOG_SOURCE",
699
+ commandHash:"JSKIT_EXECUTION_COMMAND_HASH"});var Ic=he(Do(),1),Pc=he(St(),1),Rc=he(ke(),1),Nc=he(fr(),1),kc=he(hr(),1),jc=he(Sr(),1),Dc=he(At(),1),Mc=he(Fo(),1);var zp=new URL("./../../../../@jskit-ai/assistant-core/src/server/conversation/codexRuntime.js",import.meta.url).href;var Zp=16*1024*1024;function q(t){if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null||
700
+ Kc(e)}function Kc(t){return t!==null&&typeof t=="object"&&Object.getPrototypeOf(t)===null&&Reflect.ownKeys(t).length===0}function Ar(t){return t!==null&&typeof t=="object"&&q(t.structure)&&q(t.operations)&&typeof t.validateWith=="function"&&
701
+ typeof t.toJsonSchema=="function"&&typeof t.cleanup=="function"}function Ct(t,e){if(!Object.hasOwn(e,"items"))return null;
702
+ let{items:r}=e;if(Ar(r))return{kind:"schema",schema:r};if(!q(r)||typeof r.type!="string")throw new Error(`Array field "${t}\
703
+ " must define items as either a Schema instance or a field definition object.`);return{kind:"definition",definition:r}}function et(t,e){
704
+ if(!Object.hasOwn(e,"values"))return null;let{values:r}=e;if(Ar(r))return{kind:"schema",schema:r};if(!q(r)||typeof r.type!=
704
705
  "string")throw new Error(`Object field "${t}" must define values as either a Schema instance or a field definition objec\
705
- t.`);return{kind:"definition",definition:r}}function Ct(t,e){let r=Object.hasOwn(e,"schema"),n=Object.hasOwn(e,"values"),
706
+ t.`);return{kind:"definition",definition:r}}function Tt(t,e){let r=Object.hasOwn(e,"schema"),n=Object.hasOwn(e,"values"),
706
707
  o=Object.hasOwn(e,"additionalProperties");if(r&&n)throw new Error(`Object field "${t}" cannot define both schema and val\
707
708
  ues.`);if(o&&e.additionalProperties!==!0)throw new Error(`Object field "${t}" only supports additionalProperties: true.`);
708
709
  if(n&&e.additionalProperties===!0)throw new Error(`Object field "${t}" cannot define both values and additionalPropertie\
709
- s: true.`);if(r){if(!Or(e.schema))throw new Error(`Object field "${t}" must define schema as a Schema instance.`);return{
710
- kind:"nested",schema:e.schema,allowAdditionalProperties:e.additionalProperties===!0}}return n?{kind:"map",valuesConfig:Ze(
711
- t,e)}:e.additionalProperties===!0?{kind:"opaque"}:{kind:"plain"}}function ze(t){return t?.type==="number"||t?.type==="integer"||t?.type==="epochMilliseconds"||t?.type==="epochSeconds"}function Ar(t,e=""){
712
- if(H(t))for(let[r,n]of Object.entries(t)){if(!H(n))continue;let o=e?`${e}.${r}`:r;for(let i of["minItems","maxItems"]){if(!Object.
710
+ s: true.`);if(r){if(!Ar(e.schema))throw new Error(`Object field "${t}" must define schema as a Schema instance.`);return{
711
+ kind:"nested",schema:e.schema,allowAdditionalProperties:e.additionalProperties===!0}}return n?{kind:"map",valuesConfig:et(
712
+ t,e)}:e.additionalProperties===!0?{kind:"opaque"}:{kind:"plain"}}function $e(t){return t?.type==="number"||t?.type==="integer"||t?.type==="epochMilliseconds"||t?.type==="epochSeconds"}function vr(t,e=""){
713
+ if(q(t))for(let[r,n]of Object.entries(t)){if(!q(n))continue;let o=e?`${e}.${r}`:r;for(let i of["minItems","maxItems"]){if(!Object.
713
714
  hasOwn(n,i))continue;let s=n[i];if(n.type!=="array"||!Number.isInteger(s)||s<0)throw new Error(`Field "${o}" ${i} must b\
714
715
  e a non-negative integer on an array field.`)}if(n.minItems>n.maxItems)throw new Error(`Field "${o}" minItems (${n.minItems}\
715
- ) is above its maxItems (${n.maxItems}).`);n.type==="array"&&H(n.items)&&typeof n.items.type=="string"&&Ar({"[]":n.items},
716
- o)}}var vr="^(?:0|-?[1-9]\\d*)$",Go="\\d{4}",Wo="0[1-9]|1[0-2]",Xo="0[1-9]|[12]\\d|3[01]",Jo="[01]\\d|2[0-3]",$e="[0-5]\\d",
717
- Tt=`(?:${Jo}):${$e}`,Ko=`(?:Z|[+-](?:${Jo}):${$e})`,Yo=`(${Go})-(${Wo})-(${Xo})`,Qo=`${Go}-(?:${Wo})-(?:${Xo})`,Zo=`^${Qo}\
718
- $`,Jc=new RegExp(`^${Yo}$`),Kc=new RegExp(`^${Tt}(?::${$e}(?:\\.(\\d+))?)?$`),Yc=new RegExp(`^${Yo}T${Tt}:${$e}(?:\\.(\\d+\
719
- ))?${Ko}$`),Qc=new RegExp(vr),Zc=[31,28,31,30,31,30,31,31,30,31,30,31];function eu(t){return t%4===0&&(t%100!==0||t%400===
720
- 0)}function tu(t,e){return e===2?eu(t)?29:28:Zc[e-1]}function ei(t,e,r){let n=Number(t),o=Number(e),i=Number(r);return o>=
721
- 1&&o<=12&&i>=1&&i<=tu(n,o)}function et(t,e){let r=t.temporalPrecision;if(r!==void 0){if(!Number.isInteger(r)||r<0)throw new Error(
722
- `temporalPrecision for "${e}" must be a non-negative integer.`);return r}}function ti(t,e){return t===void 0?!0:e===void 0||
723
- t.length<=e}function ri(t){if(typeof t!="string")return!1;let e=Jc.exec(t);return e!==null&&ei(e[1],e[2],e[3])}function ni(t,e){
724
- if(typeof t!="string")return!1;let r=Kc.exec(t);return r!==null&&ti(r[1],e)}function oi(t,e){if(typeof t!="string")return!1;
725
- let r=Yc.exec(t);return r===null?!1:ei(r[1],r[2],r[3])&&ti(r[4],e)}function ii(t){return t===void 0?"(?:\\.\\d+)?":t===0?
726
- "":`(?:\\.\\d{1,${t}})?`}function si(t,e){let r=et(t,e);return`^${Tt}(?::${$e}${ii(r)})?$`}function ai(t,e){let r=et(t,e);
727
- return`^${Qo}T${Tt}:${$e}${ii(r)}${Ko}$`}function Cr(t,e){let r;if(typeof t=="number")r=t;else if(typeof t=="string"&&Qc.
728
- test(t))r=Number(t);else return null;return!Number.isSafeInteger(r)||r<-e||r>e?null:r===0?0:r}var ru=new Set(["__proto__","prototype","constructor"]);function P(t,e,r){Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0})}function nu(t,e){if(ru.
729
- has(t))throw new Error(`${e}() received unsafe path segment "${t}".`)}function ou(t){return typeof t!="string"?t:t.replace(
730
- /\[(.+?)\]/g,".$1").replace(/^\.+/,"").replace(/\.+/g,".").replace(/\.$/,"")}function Tr(t,e,{normalize:r=!1,allowEmpty:n=!1}={}){
731
- let o=r?ou(t):t;if(typeof o!="string"||o.trim()===""){if(n&&o==="")return[];throw new Error(`${e}() expects a non-empty \
716
+ ) is above its maxItems (${n.maxItems}).`);n.type==="array"&&q(n.items)&&typeof n.items.type=="string"&&vr({"[]":n.items},
717
+ o)}}var Cr="^(?:0|-?[1-9]\\d*)$",Xo="\\d{4}",Jo="0[1-9]|1[0-2]",Ko="0[1-9]|[12]\\d|3[01]",Yo="[01]\\d|2[0-3]",Ue="[0-5]\\d",
718
+ It=`(?:${Yo}):${Ue}`,Qo=`(?:Z|[+-](?:${Yo}):${Ue})`,Zo=`(${Xo})-(${Jo})-(${Ko})`,ei=`${Xo}-(?:${Jo})-(?:${Ko})`,ti=`^${ei}\
719
+ $`,Yc=new RegExp(`^${Zo}$`),Qc=new RegExp(`^${It}(?::${Ue}(?:\\.(\\d+))?)?$`),Zc=new RegExp(`^${Zo}T${It}:${Ue}(?:\\.(\\d+\
720
+ ))?${Qo}$`),eu=new RegExp(Cr),tu=[31,28,31,30,31,30,31,31,30,31,30,31];function ru(t){return t%4===0&&(t%100!==0||t%400===
721
+ 0)}function nu(t,e){return e===2?ru(t)?29:28:tu[e-1]}function ri(t,e,r){let n=Number(t),o=Number(e),i=Number(r);return o>=
722
+ 1&&o<=12&&i>=1&&i<=nu(n,o)}function tt(t,e){let r=t.temporalPrecision;if(r!==void 0){if(!Number.isInteger(r)||r<0)throw new Error(
723
+ `temporalPrecision for "${e}" must be a non-negative integer.`);return r}}function ni(t,e){return t===void 0?!0:e===void 0||
724
+ t.length<=e}function oi(t){if(typeof t!="string")return!1;let e=Yc.exec(t);return e!==null&&ri(e[1],e[2],e[3])}function ii(t,e){
725
+ if(typeof t!="string")return!1;let r=Qc.exec(t);return r!==null&&ni(r[1],e)}function si(t,e){if(typeof t!="string")return!1;
726
+ let r=Zc.exec(t);return r===null?!1:ri(r[1],r[2],r[3])&&ni(r[4],e)}function ai(t){return t===void 0?"(?:\\.\\d+)?":t===0?
727
+ "":`(?:\\.\\d{1,${t}})?`}function ci(t,e){let r=tt(t,e);return`^${It}(?::${Ue}${ai(r)})?$`}function ui(t,e){let r=tt(t,e);
728
+ return`^${ei}T${It}:${Ue}${ai(r)}${Qo}$`}function Tr(t,e){let r;if(typeof t=="number")r=t;else if(typeof t=="string"&&eu.
729
+ test(t))r=Number(t);else return null;return!Number.isSafeInteger(r)||r<-e||r>e?null:r===0?0:r}var ou=new Set(["__proto__","prototype","constructor"]);function T(t,e,r){Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0})}function iu(t,e){if(ou.
730
+ has(t))throw new Error(`${e}() received unsafe path segment "${t}".`)}function su(t){return typeof t!="string"?t:t.replace(
731
+ /\[(.+?)\]/g,".$1").replace(/^\.+/,"").replace(/\.+/g,".").replace(/\.$/,"")}function Ir(t,e,{normalize:r=!1,allowEmpty:n=!1}={}){
732
+ let o=r?su(t):t;if(typeof o!="string"||o.trim()===""){if(n&&o==="")return[];throw new Error(`${e}() expects a non-empty \
732
733
  dotted path string.`)}let i=o.split(".");if(i.some(s=>s===""))throw new Error(`${e}() received an invalid path "${o}".`);
733
- for(let s of i)nu(s,e);return i}var iu="http://json-schema.org/draft-07/schema#",ge="x-json-rest-schema",Ir=["object","array","string","number","boolean"],
734
- Pr=Symbol("json-rest-schema.exportContext"),su=["true","1","yes","y","on"],au=["false","0","no","n","off"];function ci(t){
735
- return{anyOf:[{type:"integer",minimum:-t,maximum:t},{type:"string",pattern:vr}]}}function ve(t,e){return{[ge]:{[t]:e}}}var cu={
736
- none:()=>({type:Ir}),blob:()=>({type:Ir}),serialize:()=>({type:Ir}),object:()=>({type:"object"}),array:()=>({type:"array"}),
734
+ for(let s of i)iu(s,e);return i}var au="http://json-schema.org/draft-07/schema#",ge="x-json-rest-schema",Pr=["object","array","string","number","boolean"],
735
+ Rr=Symbol("json-rest-schema.exportContext"),cu=["true","1","yes","y","on"],uu=["false","0","no","n","off"];function li(t){
736
+ return{anyOf:[{type:"integer",minimum:-t,maximum:t},{type:"string",pattern:Cr}]}}function Ce(t,e){return{[ge]:{[t]:e}}}var lu={
737
+ none:()=>({type:Pr}),blob:()=>({type:Pr}),serialize:()=>({type:Pr}),object:()=>({type:"object"}),array:()=>({type:"array"}),
737
738
  file:()=>({type:"string"}),string:()=>({type:"string"}),number:()=>({type:["number","string"]}),integer:()=>({type:["int\
738
- eger","string"]}),epochMilliseconds:()=>ci(864e13),epochSeconds:()=>ci(864e10),dateTime:({definition:t,fieldName:e})=>({
739
- type:"string",format:"date-time",pattern:ai(t,e)}),date:()=>({type:"string",format:"date",pattern:Zo}),time:({definition:t,
740
- fieldName:e})=>({type:"string",pattern:si(t,e)}),boolean:({definition:t})=>{if(t.strictBoolean===!0)return{type:"boolean"};
741
- let e=new Set([...su,String(t.stringTrueWhen||"true").trim().toLowerCase()]),r=new Set([...au,String(t.stringFalseWhen||
739
+ eger","string"]}),epochMilliseconds:()=>li(864e13),epochSeconds:()=>li(864e10),dateTime:({definition:t,fieldName:e})=>({
740
+ type:"string",format:"date-time",pattern:ui(t,e)}),date:()=>({type:"string",format:"date",pattern:ti}),time:({definition:t,
741
+ fieldName:e})=>({type:"string",pattern:ci(t,e)}),boolean:({definition:t})=>{if(t.strictBoolean===!0)return{type:"boolean"};
742
+ let e=new Set([...cu,String(t.stringTrueWhen||"true").trim().toLowerCase()]),r=new Set([...uu,String(t.stringFalseWhen||
742
743
  "false").trim().toLowerCase()]);return{anyOf:[{type:"boolean"},{type:"number",enum:[0,1]},{type:"string",enum:[...r,...e]}]}},
743
- id:()=>({type:["integer","string"],minimum:1,pattern:"^[1-9][0-9]*$"})},uu={minLength:({definition:t,parameterValue:e})=>t.
744
+ id:()=>({type:["integer","string"],minimum:1,pattern:"^[1-9][0-9]*$"})},du={minLength:({definition:t,parameterValue:e})=>t.
744
745
  type==="string"?{minLength:e}:null,maxLength:({definition:t,parameterValue:e})=>t.type==="string"?{maxLength:e}:null,min:({
745
- definition:t,parameterValue:e})=>ze(t)?{minimum:e}:null,max:({definition:t,parameterValue:e})=>ze(t)?{maximum:e}:null,pattern:({
746
+ definition:t,parameterValue:e})=>$e(t)?{minimum:e}:null,max:({definition:t,parameterValue:e})=>$e(t)?{maximum:e}:null,pattern:({
746
747
  definition:t,parameterValue:e})=>t.type==="string"?{pattern:e instanceof RegExp?e.source:e}:null,enum:({parameterValue:t})=>({
747
748
  enum:t}),minItems:({definition:t,parameterValue:e})=>t.type==="array"?{minItems:e}:null,maxItems:({definition:t,parameterValue:e})=>t.
748
749
  type==="array"?{maxItems:e}:null,notEmpty:({parameterValue:t,definition:e})=>!t||e.type==="array"?null:{minLength:1},uppercase:({
749
- parameterValue:t})=>t?ve("transforms",{uppercase:!0}):null,lowercase:({parameterValue:t})=>t?ve("transforms",{lowercase:!0}):
750
- null,length:({parameterValue:t})=>ve("transforms",{length:t}),unsigned:({parameterValue:t})=>t?ve("metadata",{unsigned:!0}):
751
- null,precision:({parameterValue:t})=>ve("metadata",{precision:t}),scale:({parameterValue:t})=>ve("metadata",{scale:t}),temporalPrecision:({
752
- parameterValue:t})=>ve("metadata",{temporalPrecision:t}),strictBoolean:()=>null,required:()=>null,nullable:()=>null,nullOnEmpty:()=>null,
753
- defaultTo:()=>null};function jr(t,e){for(let r of Object.keys(e)){let n=e[r],o=t[r];if(n&&o&&typeof n=="object"&&typeof o==
754
- "object"&&!Array.isArray(n)&&!Array.isArray(o)){jr(o,n);continue}t[r]=n}}function lu(t,e){if(!e||typeof e!="object"||Array.
750
+ parameterValue:t})=>t?Ce("transforms",{uppercase:!0}):null,lowercase:({parameterValue:t})=>t?Ce("transforms",{lowercase:!0}):
751
+ null,length:({parameterValue:t})=>Ce("transforms",{length:t}),unsigned:({parameterValue:t})=>t?Ce("metadata",{unsigned:!0}):
752
+ null,precision:({parameterValue:t})=>Ce("metadata",{precision:t}),scale:({parameterValue:t})=>Ce("metadata",{scale:t}),temporalPrecision:({
753
+ parameterValue:t})=>Ce("metadata",{temporalPrecision:t}),strictBoolean:()=>null,required:()=>null,nullable:()=>null,nullOnEmpty:()=>null,
754
+ defaultTo:()=>null};function Dr(t,e){for(let r of Object.keys(e)){let n=e[r],o=t[r];if(n&&o&&typeof n=="object"&&typeof o==
755
+ "object"&&!Array.isArray(n)&&!Array.isArray(o)){Dr(o,n);continue}t[r]=n}}function fu(t,e){if(!e||typeof e!="object"||Array.
755
756
  isArray(e))throw new Error("JSON Schema export hooks must return an object or null.");for(let r of Object.keys(e)){if(r===
756
- ge&&t[r]&&typeof t[r]=="object"&&typeof e[r]=="object"&&!Array.isArray(t[r])&&!Array.isArray(e[r])){jr(t[r],e[r]);continue}
757
- t[r]=e[r]}}function du(t,e){let n=[...Array.isArray(t.anyOf)&&Object.keys(t).length===1?t.anyOf:[t],...e];return n.length===
758
- 1?t:{anyOf:n}}function fu(t,e){if(!Object.hasOwn(t.types,e.type))throw new Error(`No casting function for type: ${e.type}`);
759
- let r=t.types[e.type];if(typeof r.toJsonSchema=="function")return r.toJsonSchema;let n=cu[e.type];if(!n)throw new Error(
760
- `Type '${e.type}' cannot be exported to JSON Schema without a toJsonSchema hook.`);return n}function pu(t,e,r){if(!Object.
761
- hasOwn(t.validators,e))return null;let n=t.validators[e];if(typeof n.toJsonSchema=="function")return n.toJsonSchema;let o=uu[e];
757
+ ge&&t[r]&&typeof t[r]=="object"&&typeof e[r]=="object"&&!Array.isArray(t[r])&&!Array.isArray(e[r])){Dr(t[r],e[r]);continue}
758
+ t[r]=e[r]}}function pu(t,e){let n=[...Array.isArray(t.anyOf)&&Object.keys(t).length===1?t.anyOf:[t],...e];return n.length===
759
+ 1?t:{anyOf:n}}function mu(t,e){if(!Object.hasOwn(t.types,e.type))throw new Error(`No casting function for type: ${e.type}`);
760
+ let r=t.types[e.type];if(typeof r.toJsonSchema=="function")return r.toJsonSchema;let n=lu[e.type];if(!n)throw new Error(
761
+ `Type '${e.type}' cannot be exported to JSON Schema without a toJsonSchema hook.`);return n}function hu(t,e,r){if(!Object.
762
+ hasOwn(t.validators,e))return null;let n=t.validators[e];if(typeof n.toJsonSchema=="function")return n.toJsonSchema;let o=du[e];
762
763
  if(o)return o;throw new Error(`Validator '${e}' on field '${r}' cannot be exported to JSON Schema without a toJsonSchema\
763
- hook.`)}function ui(t){if(t===void 0)return"create";if(["create","replace","patch"].includes(t))return t;throw new Error(
764
- `Unsupported JSON Schema export mode '${t}'. Expected 'create', 'replace', or 'patch'.`)}function mu(t,e={}){if(e.mode!==
765
- void 0&&e.operation!==void 0){let r=ui(e.mode);if(r!==e.operation)throw new Error(`Conflicting JSON Schema export option\
764
+ hook.`)}function di(t){if(t===void 0)return"create";if(["create","replace","patch"].includes(t))return t;throw new Error(
765
+ `Unsupported JSON Schema export mode '${t}'. Expected 'create', 'replace', or 'patch'.`)}function yu(t,e={}){if(e.mode!==
766
+ void 0&&e.operation!==void 0){let r=di(e.mode);if(r!==e.operation)throw new Error(`Conflicting JSON Schema export option\
766
767
  s: mode '${r}' does not match operation '${e.operation}'.`)}if(e.operation!==void 0){if(!Object.hasOwn(t.operations,e.operation))
767
- throw new Error(`Unknown JSON Schema export operation '${e.operation}'.`);return e.operation}return ui(e.mode)}function hu(t,e={}){
768
+ throw new Error(`Unknown JSON Schema export operation '${e.operation}'.`);return e.operation}return di(e.mode)}function _u(t,e={}){
768
769
  if(e.operationName!==void 0&&e.operationDescriptor!==void 0)return{operationName:e.operationName,operation:e.operationDescriptor};
769
- let r=mu(t,e);return{operationName:r,operation:t.operations[r]}}function yu(t={}){let e={...t};return Object.defineProperty(
770
- e,Pr,{value:{definitions:{},nodes:[],nextDefinitionId:1,rootNode:null},enumerable:!1}),e}function Pt(t={}){return t[Pr]?
771
- t[Pr]:{definitions:{},nodes:[],nextDefinitionId:1,rootNode:null}}function _u(t){return String(t).replace(/[^a-zA-Z0-9]+/g,
772
- "_").replace(/^_+|_+$/g,"")||"operation"}function Rr(t){return H(t)&&Object.keys(t).length===1&&typeof t.$ref=="string"}
773
- function It(t){return Rr(t)?{allOf:[t]}:t}function gu(t,e,r,n,o){return t.nodes.find(i=>i.schema===e&&i.operationName===
774
- r&&i.operation===n&&i.additionalProperties===o)||null}function Eu(t,e){let r=_u(e),n=`SchemaNode_${t.nextDefinitionId}_${r}`;
775
- return t.nextDefinitionId+=1,n}function li(t,e,r,n,o,{root:i=!1}={}){let s=Pt(e),a=gu(s,t,r,n,o);if(a)return i&&(a.pointer=
770
+ let r=yu(t,e);return{operationName:r,operation:t.operations[r]}}function gu(t={}){let e={...t};return Object.defineProperty(
771
+ e,Rr,{value:{definitions:{},nodes:[],nextDefinitionId:1,rootNode:null},enumerable:!1}),e}function Rt(t={}){return t[Rr]?
772
+ t[Rr]:{definitions:{},nodes:[],nextDefinitionId:1,rootNode:null}}function Eu(t){return String(t).replace(/[^a-zA-Z0-9]+/g,
773
+ "_").replace(/^_+|_+$/g,"")||"operation"}function Nr(t){return q(t)&&Object.keys(t).length===1&&typeof t.$ref=="string"}
774
+ function Pt(t){return Nr(t)?{allOf:[t]}:t}function wu(t,e,r,n,o){return t.nodes.find(i=>i.schema===e&&i.operationName===
775
+ r&&i.operation===n&&i.additionalProperties===o)||null}function Su(t,e){let r=Eu(e),n=`SchemaNode_${t.nextDefinitionId}_${r}`;
776
+ return t.nextDefinitionId+=1,n}function fi(t,e,r,n,o,{root:i=!1}={}){let s=Rt(e),a=wu(s,t,r,n,o);if(a)return i&&(a.pointer=
776
777
  "#",s.rootNode=a),a;let c={schema:t,operationName:r,operation:n,additionalProperties:o,status:"new",definitionName:i?null:
777
- Eu(s,r),pointer:i?"#":null};return i?s.rootNode=c:c.pointer=`#/definitions/${c.definitionName}`,s.nodes.push(c),c}function di(t,e){
778
- if(t.status==="built")return{$ref:t.pointer};if(t.status==="building")return{$ref:t.pointer};let r=Pt(e);t.status="build\
779
- ing",t.pointer!=="#"&&(r.definitions[t.definitionName]={});let n=wu(t.schema,e,t.operationName,t.operation,t.additionalProperties);
780
- return t.status="built",t.pointer==="#"?n:(r.definitions[t.definitionName]=n,{$ref:t.pointer})}function Dr(t,e,r,n,o=!1){
781
- let i=Pt(e),s=li(t,e,r,n,o);return i.rootNode===s?{$ref:"#"}:di(s,e)}function tt(t,{referenceBacked:e=!1}={}){return{schema:t,
782
- referenceBacked:e}}function wu(t,e,r,n,o=!1){let i={},s=[];for(let[c,u]of Object.entries(t.structure))P(i,c,Mr(t,c,u,e,r,
778
+ Su(s,r),pointer:i?"#":null};return i?s.rootNode=c:c.pointer=`#/definitions/${c.definitionName}`,s.nodes.push(c),c}function pi(t,e){
779
+ if(t.status==="built")return{$ref:t.pointer};if(t.status==="building")return{$ref:t.pointer};let r=Rt(e);t.status="build\
780
+ ing",t.pointer!=="#"&&(r.definitions[t.definitionName]={});let n=bu(t.schema,e,t.operationName,t.operation,t.additionalProperties);
781
+ return t.status="built",t.pointer==="#"?n:(r.definitions[t.definitionName]=n,{$ref:t.pointer})}function Mr(t,e,r,n,o=!1){
782
+ let i=Rt(e),s=fi(t,e,r,n,o);return i.rootNode===s?{$ref:"#"}:pi(s,e)}function rt(t,{referenceBacked:e=!1}={}){return{schema:t,
783
+ referenceBacked:e}}function bu(t,e,r,n,o=!1){let i={},s=[];for(let[c,u]of Object.entries(t.structure))T(i,c,Lr(t,c,u,e,r,
783
784
  n)),n.enforceRequired&&u.required===!0&&s.push(c);let a={type:"object",properties:i,additionalProperties:o};return s.length>
784
- 0&&(a.required=s),a}function Su(t,e,r,n,o,i){let s=vt(e,r);if(!s)return null;if(s.kind==="schema")return{...It(Dr(s.schema,
785
+ 0&&(a.required=s),a}function xu(t,e,r,n,o,i){let s=Ct(e,r);if(!s)return null;if(s.kind==="schema")return{...Pt(Mr(s.schema,
785
786
  n,"replace",s.schema.operations.replace,!1)),[ge]:{castType:"object"}};let a=r.items.type==="object"&&Object.hasOwn(r.items,
786
- "schema")?"replace":o,c=a==="replace"?t.operations.replace:i;return Mr(t,`${e}[]`,r.items,n,a,c)}function bu(t,e,r,n,o,i){
787
- let s=Ze(e,r);if(!s)return null;if(s.kind==="schema")return{...It(Dr(s.schema,n,"replace",s.schema.operations.replace,!1)),
787
+ "schema")?"replace":o,c=a==="replace"?t.operations.replace:i;return Lr(t,`${e}[]`,r.items,n,a,c)}function Ou(t,e,r,n,o,i){
788
+ let s=et(e,r);if(!s)return null;if(s.kind==="schema")return{...Pt(Mr(s.schema,n,"replace",s.schema.operations.replace,!1)),
788
789
  [ge]:{castType:"object"}};let a=s.definition.type==="object"&&Object.hasOwn(s.definition,"schema")?"replace":o,c=a==="re\
789
- place"?t.operations.replace:i;return Mr(t,`${e}.*`,s.definition,n,a,c)}function xu(t,e,r,n,o,i){if(r.type==="object"){let a=Ct(
790
- e,r);if(a.kind==="nested")return tt(Dr(a.schema,n,o,i,a.allowAdditionalProperties===!0),{referenceBacked:!0});if(a.kind===
791
- "opaque")return tt({type:"object",additionalProperties:!0});if(a.kind==="map")return tt({type:"object",additionalProperties:bu(
792
- t,e,r,n,o,i)})}let s=fu(t,r)({schema:t,fieldName:e,definition:r,operation:o,mode:o,options:n});if(!s||typeof s!="object"||
790
+ place"?t.operations.replace:i;return Lr(t,`${e}.*`,s.definition,n,a,c)}function Au(t,e,r,n,o,i){if(r.type==="object"){let a=Tt(
791
+ e,r);if(a.kind==="nested")return rt(Mr(a.schema,n,o,i,a.allowAdditionalProperties===!0),{referenceBacked:!0});if(a.kind===
792
+ "opaque")return rt({type:"object",additionalProperties:!0});if(a.kind==="map")return rt({type:"object",additionalProperties:Ou(
793
+ t,e,r,n,o,i)})}let s=mu(t,r)({schema:t,fieldName:e,definition:r,operation:o,mode:o,options:n});if(!s||typeof s!="object"||
793
794
  Array.isArray(s))throw new Error(`Type '${r.type}' on field '${e}' returned an invalid JSON Schema fragment.`);if(r.type===
794
- "array"){let a=Su(t,e,r,n,o,i);if(a)return tt({...s,items:a},{referenceBacked:Rr(s)})}return tt(s,{referenceBacked:Rr(s)})}
795
- function Mr(t,e,r,n,o,i){let s={schema:t,fieldName:e,definition:r,operation:o,mode:o,options:n},a=xu(t,e,r,n,o,i),c=a.referenceBacked?
796
- It(a.schema):{...a.schema},u={castType:r.type};for(let d of Object.keys(r)){if(d==="type"||!Object.hasOwn(t.validators,d))
797
- continue;let h=pu(t,d,e);if(!h)continue;let _=h({...s,parameterName:d,parameterValue:r[d],fieldSchema:{...c}});_&&lu(c,_)}
798
- c[ge]&&(jr(u,c[ge]),delete c[ge]);let l=[];r.nullable===!0&&l.push({type:"null"}),r.nullOnEmpty===!0&&l.push({const:""});
799
- let p=It(du(c,l));if(r.defaultTo!==void 0&&i.applyDefaults)if(typeof r.defaultTo!="function"){let d=t._normalizeDefault(
795
+ "array"){let a=xu(t,e,r,n,o,i);if(a)return rt({...s,items:a},{referenceBacked:Nr(s)})}return rt(s,{referenceBacked:Nr(s)})}
796
+ function Lr(t,e,r,n,o,i){let s={schema:t,fieldName:e,definition:r,operation:o,mode:o,options:n},a=Au(t,e,r,n,o,i),c=a.referenceBacked?
797
+ Pt(a.schema):{...a.schema},u={castType:r.type};for(let d of Object.keys(r)){if(d==="type"||!Object.hasOwn(t.validators,d))
798
+ continue;let _=hu(t,d,e);if(!_)continue;let g=_({...s,parameterName:d,parameterValue:r[d],fieldSchema:{...c}});g&&fu(c,g)}
799
+ c[ge]&&(Dr(u,c[ge]),delete c[ge]);let l=[];r.nullable===!0&&l.push({type:"null"}),r.nullOnEmpty===!0&&l.push({const:""});
800
+ let m=Pt(pu(c,l));if(r.defaultTo!==void 0&&i.applyDefaults)if(typeof r.defaultTo!="function"){let d=t._normalizeDefault(
800
801
  r,r.defaultTo,{fieldPath:e,currentObject:{},containerKey:e,objectBeforeCast:{},options:{},settings:t._buildOperationSettings(
801
- o,i,{})});if(Object.keys(d.errors).length>0){let h=Object.values(d.errors)[0];throw new Error(`defaultTo for "${e}" is i\
802
- nvalid (${h.code}).`)}p.default=d.value}else u.defaults={providedByFunction:!0};return p[ge]=u,p}function fi(t,e={}){let r=yu(
803
- e),{operationName:n,operation:o}=hu(t,r),i=r.additionalProperties===void 0?!1:r.additionalProperties,s=Pt(r),a=li(t,r,n,
804
- o,i,{root:!0}),c={$schema:iu,...di(a,r)};return Object.keys(s.definitions).length>0&&(c.definitions=s.definitions),c}function pi(t){return t!==null&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Br(t){return t instanceof
805
- Be}function Ou(){return{self:!1,children:{}}}function mi(t){return Object.keys(t.children).length>0}function Ce(t,e){return`${t}\
806
- .${String(e)}`}function wi(t,e){return t===""?String(e):Ce(t,e)}function hi(t,e){if(t===e)return"";let r=`${e}.`;return t.
807
- startsWith(r)?t.slice(r.length):null}function Ue(t,e){let r={};for(let n of Object.values(t)){let o=Ce(e,n.field);P(r,o,
808
- {...n,field:o})}return r}function Ur(t){return Tr(t,"validatePath")}function yi(t){let e={};for(let r of t){let n=Ur(r),
809
- o=e;for(let i=0;i<n.length;i++){let s=n[i];Object.hasOwn(o,s)||P(o,s,Ou()),i===n.length-1&&(o[s].self=!0),o=o[s].children}}
810
- return e}function Au(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||!Object.hasOwn(r,n))return;r=r[n]}return r}
811
- function Rt(t){return t===null?!0:Array.isArray(t)||H(t)?Object.keys(t).length>0:t!==void 0}function _i(t){return[...t].
802
+ o,i,{})});if(Object.keys(d.errors).length>0){let _=Object.values(d.errors)[0];throw new Error(`defaultTo for "${e}" is i\
803
+ nvalid (${_.code}).`)}m.default=d.value}else u.defaults={providedByFunction:!0};return m[ge]=u,m}function mi(t,e={}){let r=gu(
804
+ e),{operationName:n,operation:o}=_u(t,r),i=r.additionalProperties===void 0?!1:r.additionalProperties,s=Rt(r),a=fi(t,r,n,
805
+ o,i,{root:!0}),c={$schema:au,...pi(a,r)};return Object.keys(s.definitions).length>0&&(c.definitions=s.definitions),c}function hi(t){return t!==null&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Fr(t){return t instanceof
806
+ Fe}function vu(){return{self:!1,children:{}}}function yi(t){return Object.keys(t.children).length>0}function Te(t,e){return`${t}\
807
+ .${String(e)}`}function bi(t,e){return t===""?String(e):Te(t,e)}function _i(t,e){if(t===e)return"";let r=`${e}.`;return t.
808
+ startsWith(r)?t.slice(r.length):null}function Ve(t,e){let r={};for(let n of Object.values(t)){let o=Te(e,n.field);T(r,o,
809
+ {...n,field:o})}return r}function Vr(t){return Ir(t,"validatePath")}function gi(t){let e={};for(let r of t){let n=Vr(r),
810
+ o=e;for(let i=0;i<n.length;i++){let s=n[i];Object.hasOwn(o,s)||T(o,s,vu()),i===n.length-1&&(o[s].self=!0),o=o[s].children}}
811
+ return e}function Cu(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||!Object.hasOwn(r,n))return;r=r[n]}return r}
812
+ function Nt(t){return t===null?!0:Array.isArray(t)||q(t)?Object.keys(t).length>0:t!==void 0}function Ei(t){return[...t].
812
813
  sort((e,r)=>{let n=/^[0-9]+$/.test(e),o=/^[0-9]+$/.test(r);return n&&o?Number(e)-Number(r):n?-1:o?1:e.localeCompare(r)})}
813
- function vu(t){return/^[0-9]+$/.test(t)}function Cu(t,e=new WeakMap){if(e.has(t))return e.get(t);let r=Object.create(Be.
814
+ function Tu(t){return/^[0-9]+$/.test(t)}function Iu(t,e=new WeakMap){if(e.has(t))return e.get(t);let r=Object.create(Fe.
814
815
  prototype);return e.set(t,r),r.structure=null,r.types=t.types,r.validators=t.validators,r.operations=t.operations,r.structure=
815
- kt(Nt(t.structure,e)),r._installOperationMethods(),Object.freeze(r)}function Nt(t,e=new WeakMap){if(t===null||typeof t!=
816
- "object")return t;if(Br(t))return Cu(t,e);if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){let n=new RegExp(
816
+ jt(kt(t.structure,e)),r._installOperationMethods(),Object.freeze(r)}function kt(t,e=new WeakMap){if(t===null||typeof t!=
817
+ "object")return t;if(Fr(t))return Iu(t,e);if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){let n=new RegExp(
817
818
  t.source,t.flags);return n.lastIndex=t.lastIndex,n}if(e.has(t))return e.get(t);if(Array.isArray(t)){let n=[];e.set(t,n);
818
- for(let o of t)n.push(Nt(o,e));return n}if(!H(t))return t;let r={};e.set(t,r);for(let[n,o]of Object.entries(t))P(r,n,Nt(
819
- o,e));return r}function kt(t,e=new WeakSet){if(t===null||typeof t!="object"||e.has(t)||Br(t))return t;if(e.add(t),Array.
820
- isArray(t))for(let r of t)kt(r,e);else for(let r of Reflect.ownKeys(t))kt(t[r],e);return Object.freeze(t)}function Lr(t){
821
- return kt(Nt(t))}var zr=new WeakMap;function Vr(t,e,r=""){if(!Br(t)||!Array.isArray(e)||e.length<1)return null;let[n,...o]=e;
822
- if(!Object.hasOwn(t.structure,n))return null;let i=t.structure[n];if(o.length<1)return i;let s=wi(r,n);return Si(t,i,o,s)}
823
- function Si(t,e,r,n){if(e?.type==="object"){let o=t._resolveObjectFieldMode(n,e);return o.kind!=="nested"?null:Vr(o.schema,
824
- r,n)}if(e?.type==="array"){let o=t._resolveArrayItemsConfig(n,e);if(!o||r.length<1)return null;let[i,...s]=r;if(!vu(i))return null;
825
- let a=Ce(n,i);return o.kind==="schema"?s.length<1?null:Vr(o.schema,s,a):s.length<1?o.definition:Si(t,o.definition,s,a)}return null}
826
- function Ve(t,e){let r={...t};if(Array.isArray(t.skipFields)){let n=t.skipFields.map(o=>hi(o,e)).filter(o=>o!==null&&o!==
827
- "");n.length>0?r.skipFields=n:delete r.skipFields}if(H(t.skipParams)){let n={};for(let[o,i]of Object.entries(t.skipParams)){
828
- let s=hi(o,e);s===null||s===""||P(n,s,i)}Object.keys(n).length>0?r.skipParams=n:delete r.skipParams}return r}var Tu=Object.
819
+ for(let o of t)n.push(kt(o,e));return n}if(!q(t))return t;let r={};e.set(t,r);for(let[n,o]of Object.entries(t))T(r,n,kt(
820
+ o,e));return r}function jt(t,e=new WeakSet){if(t===null||typeof t!="object"||e.has(t)||Fr(t))return t;if(e.add(t),Array.
821
+ isArray(t))for(let r of t)jt(r,e);else for(let r of Reflect.ownKeys(t))jt(t[r],e);return Object.freeze(t)}function zr(t){
822
+ return jt(kt(t))}var $r=new WeakMap;function Br(t,e,r=""){if(!Fr(t)||!Array.isArray(e)||e.length<1)return null;let[n,...o]=e;
823
+ if(!Object.hasOwn(t.structure,n))return null;let i=t.structure[n];if(o.length<1)return i;let s=bi(r,n);return xi(t,i,o,s)}
824
+ function xi(t,e,r,n){if(e?.type==="object"){let o=t._resolveObjectFieldMode(n,e);return o.kind!=="nested"?null:Br(o.schema,
825
+ r,n)}if(e?.type==="array"){let o=t._resolveArrayItemsConfig(n,e);if(!o||r.length<1)return null;let[i,...s]=r;if(!Tu(i))return null;
826
+ let a=Te(n,i);return o.kind==="schema"?s.length<1?null:Br(o.schema,s,a):s.length<1?o.definition:xi(t,o.definition,s,a)}return null}
827
+ function Be(t,e){let r={...t};if(Array.isArray(t.skipFields)){let n=t.skipFields.map(o=>_i(o,e)).filter(o=>o!==null&&o!==
828
+ "");n.length>0?r.skipFields=n:delete r.skipFields}if(q(t.skipParams)){let n={};for(let[o,i]of Object.entries(t.skipParams)){
829
+ let s=_i(o,e);s===null||s===""||T(n,s,i)}Object.keys(n).length>0?r.skipParams=n:delete r.skipParams}return r}var Pu=Object.
829
830
  freeze({create:Object.freeze({targetFields:"schema",enforceRequired:!0,applyDefaults:!0,outputFields:"validated",rejectExplicitUndefined:!0}),
830
831
  replace:Object.freeze({targetFields:"schema",enforceRequired:!0,applyDefaults:!0,outputFields:"validated",rejectExplicitUndefined:!0}),
831
832
  patch:Object.freeze({targetFields:"input",enforceRequired:!1,applyDefaults:!1,outputFields:"input",rejectExplicitUndefined:!0})});
832
- function gi(t,e,r,n){let o=e[r];if(!n.includes(o))throw new Error(`Operation "${t}" must define ${r} as one of: ${n.join(
833
- ", ")}.`)}function $r(t,e,r,n=!0){let o=e[r];if(!(o===void 0&&!n)&&typeof o!="boolean")throw new Error(`Operation "${t}"\
834
- must define ${r} as a boolean.`)}function Iu(t,e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`Op\
835
- eration "${t}" must be an object.`);return gi(t,e,"targetFields",["schema","input"]),$r(t,e,"enforceRequired"),$r(t,e,"a\
836
- pplyDefaults"),gi(t,e,"outputFields",["validated","input"]),$r(t,e,"rejectExplicitUndefined",!1),Object.freeze({targetFields:e.
833
+ function wi(t,e,r,n){let o=e[r];if(!n.includes(o))throw new Error(`Operation "${t}" must define ${r} as one of: ${n.join(
834
+ ", ")}.`)}function Ur(t,e,r,n=!0){let o=e[r];if(!(o===void 0&&!n)&&typeof o!="boolean")throw new Error(`Operation "${t}"\
835
+ must define ${r} as a boolean.`)}function Ru(t,e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`Op\
836
+ eration "${t}" must be an object.`);return wi(t,e,"targetFields",["schema","input"]),Ur(t,e,"enforceRequired"),Ur(t,e,"a\
837
+ pplyDefaults"),wi(t,e,"outputFields",["validated","input"]),Ur(t,e,"rejectExplicitUndefined",!1),Object.freeze({targetFields:e.
837
838
  targetFields,enforceRequired:e.enforceRequired,applyDefaults:e.applyDefaults,outputFields:e.outputFields,rejectExplicitUndefined:e.
838
- rejectExplicitUndefined===void 0?!0:e.rejectExplicitUndefined})}function Pu(t={}){if(typeof t!="object"||t===null||Array.
839
+ rejectExplicitUndefined===void 0?!0:e.rejectExplicitUndefined})}function Nu(t={}){if(typeof t!="object"||t===null||Array.
839
840
  isArray(t))throw new Error("Schema operations must be an object.");let e=Object.create(null);for(let[r,n]of Object.entries(
840
- Tu))P(e,r,n);for(let[r,n]of Object.entries(t))P(e,r,Iu(r,n));return Object.freeze(e)}function Ei(t){let e=Object.create(
841
- null);for(let[r,n]of Object.entries(t))P(e,r,n);return Object.freeze(e)}function Ru(t){let e={...t};return delete e.operation,
842
- delete e.mode,e}var Be=class{constructor(e,r,n,o={}){Ar(e),this.structure=e,this.types=Ei(r),this.validators=Ei(n),this.
843
- operations=Pu(o),this._installOperationMethods()}_typeError(e){return this._paramError(e,"TYPE_CAST_FAILED","Value could\
841
+ Pu))T(e,r,n);for(let[r,n]of Object.entries(t))T(e,r,Ru(r,n));return Object.freeze(e)}function Si(t){let e=Object.create(
842
+ null);for(let[r,n]of Object.entries(t))T(e,r,n);return Object.freeze(e)}function ku(t){let e={...t};return delete e.operation,
843
+ delete e.mode,e}var Fe=class{constructor(e,r,n,o={}){vr(e),this.structure=e,this.types=Si(r),this.validators=Si(n),this.
844
+ operations=Nu(o),this._installOperationMethods()}_typeError(e){return this._paramError(e,"TYPE_CAST_FAILED","Value could\
844
845
  not be cast to the required type.")}_paramError(e,r,n,o={}){let i=new Error(n);return i.errorObject={field:e,code:r,message:n,
845
846
  params:o},i}_paramToBeSkipped(e,r,n){return typeof r!="object"||r===null?!1:!!(Array.isArray(r[n])&&r[n].includes(e))}_fieldToBeSkipped(e,r){
846
- return Array.isArray(r.skipFields)&&r.skipFields.includes(e)}_mergeErrors(e,r){for(let[n,o]of Object.entries(r))P(e,n,o)}_singleErrorMap(e){
847
- let r={};return P(r,e.field,e),r}_assertSupportedOptions(e={}){if(Object.hasOwn(e,"onlyObjectValues"))throw new Error("U\
847
+ return Array.isArray(r.skipFields)&&r.skipFields.includes(e)}_mergeErrors(e,r){for(let[n,o]of Object.entries(r))T(e,n,o)}_singleErrorMap(e){
848
+ let r={};return T(r,e.field,e),r}_assertSupportedOptions(e={}){if(Object.hasOwn(e,"onlyObjectValues"))throw new Error("U\
848
849
  nsupported validation option `onlyObjectValues`. Call `patch()` directly.");if(Object.hasOwn(e,"mode"))throw new Error("\
849
850
  Unsupported validation option `mode`. Call `validateWith()` or an operation method directly.");if(Object.hasOwn(e,"opera\
850
851
  tion"))throw new Error("Unsupported validation option `operation`. Call `validateWith()` or an operation method directly\
851
852
  .")}_buildOperationSettings(e,r,n){return{operationName:e,operation:r,targetFieldNames:r.targetFields==="input"?Object.keys(
852
853
  n):Object.keys(this.structure),outputFieldNames:r.outputFields==="input"?Object.keys(n):Object.keys(this.structure),enforceRequired:r.
853
854
  enforceRequired,applyDefaults:r.applyDefaults,rejectExplicitUndefined:r.rejectExplicitUndefined,defaultedFields:new Set,
854
- isFieldPresent:o=>Object.hasOwn(n,o)}}_assertPlainObjectInput(e,r){if(!H(r))throw new Error(`${e}() expects a plain obje\
855
+ isFieldPresent:o=>Object.hasOwn(n,o)}}_assertPlainObjectInput(e,r){if(!q(r))throw new Error(`${e}() expects a plain obje\
855
856
  ct input.`)}_resolvePathValidationRequest(e={}){let r=e.operation??e.mode??"patch";if(Object.hasOwn(e,"operation")&&Object.
856
857
  hasOwn(e,"mode")&&e.operation!==e.mode)throw new Error("Path validation options `operation` and `mode` must match when b\
857
858
  oth are provided.");if(!Object.hasOwn(this.operations,r))throw new Error(`Unknown operation "${r}".`);let n=this.operations[r];
858
- return{operationName:r,operation:n,validationOptions:Ru(e)}}_buildOperationResult(e,r,n){let o={};for(let i of n.outputFieldNames){
859
+ return{operationName:r,operation:n,validationOptions:ku(e)}}_buildOperationResult(e,r,n){let o={};for(let i of n.outputFieldNames){
859
860
  if(!Object.hasOwn(this.structure,i))continue;let s=n.isFieldPresent(i);(r[i]!==void 0||s&&e[i]===null||n.defaultedFields.
860
- has(i))&&(!s&&!n.defaultedFields.has(i)||P(o,i,r[i]))}return o}_resolveObjectFieldMode(e,r){return Ct(e,r)}_resolveArrayItemsConfig(e,r){
861
- return vt(e,r)}_resolveObjectValuesConfig(e,r){return Ze(e,r)}_buildArrayItemSettings(e,r){return e.type==="object"&&Object.
861
+ has(i))&&(!s&&!n.defaultedFields.has(i)||T(o,i,r[i]))}return o}_resolveObjectFieldMode(e,r){return Tt(e,r)}_resolveArrayItemsConfig(e,r){
862
+ return Ct(e,r)}_resolveObjectValuesConfig(e,r){return et(e,r)}_buildArrayItemSettings(e,r){return e.type==="object"&&Object.
862
863
  hasOwn(e,"schema")?{...r,operationName:"replace",operation:this.operations.replace}:r}_castValue(e,r,n,o,i,s,a,c){let u=e.
863
864
  nullable===!0||a.nullable===!0,l=e.nullOnEmpty===!0||a.nullOnEmpty===!0;if(!Object.hasOwn(this.types,e.type))throw new Error(
864
- `No casting function for type: ${e.type}`);let p=this.types[e.type];if(r===null)return u?(P(o,i,null),{errors:{},shouldContinue:!1}):
865
+ `No casting function for type: ${e.type}`);let m=this.types[e.type];if(r===null)return u?(T(o,i,null),{errors:{},shouldContinue:!1}):
865
866
  {errors:this._singleErrorMap({field:n,code:"NOT_NULLABLE",message:"Field cannot be null",params:{}}),shouldContinue:!1};
866
- if(r===""&&l)return P(o,i,null),{errors:{},shouldContinue:!1};let d={schema:this,definition:e,value:r,fieldName:n,object:o,
867
+ if(r===""&&l)return T(o,i,null),{errors:{},shouldContinue:!1};let d={schema:this,definition:e,value:r,fieldName:n,object:o,
867
868
  objectBeforeCast:s,valueBeforeCast:r,options:a,mode:c.operationName,operation:c.operationName,fieldPresent:!0,computedOptions:{
868
- nullable:u||l,nullOnEmpty:l},throwTypeError:()=>{throw this._typeError(n)},throwParamError:(h,_,E)=>{throw this._paramError(
869
- n,h,_,E)}};try{let h=p(d);if(pi(h))throw new Error(`Type handler for "${e.type}" must be synchronous.`);h!==void 0&&(P(o,
870
- i,h),d.value=h)}catch(h){if(h.errorObject)return{errors:this._singleErrorMap(h.errorObject),shouldContinue:!1};throw h}return{
869
+ nullable:u||l,nullOnEmpty:l},throwTypeError:()=>{throw this._typeError(n)},throwParamError:(_,g,E)=>{throw this._paramError(
870
+ n,_,g,E)}};try{let _=m(d);if(hi(_))throw new Error(`Type handler for "${e.type}" must be synchronous.`);_!==void 0&&(T(o,
871
+ i,_),d.value=_)}catch(_){if(_.errorObject)return{errors:this._singleErrorMap(_.errorObject),shouldContinue:!1};throw _}return{
871
872
  errors:{},context:d,shouldContinue:!0}}_runFieldValidators(e,r,n,o,i,s){for(let a of Object.keys(e)){if(a==="type"||this.
872
873
  _paramToBeSkipped(a,s.skipParams,r)||!Object.hasOwn(this.validators,a))continue;let c=this.validators[a];try{i.parameterName=
873
- a,i.parameterValue=e[a];let u=c(i);if(pi(u))throw new Error(`Validator handler for "${a}" must be synchronous.`);u!==void 0&&
874
- (P(n,o,u),i.value=u)}catch(u){if(u.errorObject)return this._singleErrorMap(u.errorObject);throw u}}return{}}_normalizeAndValidateValue(e,r,n,o,i,s,a,c){
874
+ a,i.parameterValue=e[a];let u=c(i);if(hi(u))throw new Error(`Validator handler for "${a}" must be synchronous.`);u!==void 0&&
875
+ (T(n,o,u),i.value=u)}catch(u){if(u.errorObject)return this._singleErrorMap(u.errorObject);throw u}}return{}}_normalizeAndValidateValue(e,r,n,o,i,s,a,c){
875
876
  let u=this._castValue(e,r,n,o,i,s,a,c);if(Object.keys(u.errors).length>0)return u.errors;if(!u.shouldContinue)return{};let{
876
- context:l}=u,p=this._validateNestedValue(e,n,o,i,a,c);return Object.keys(p).length>0?p:(l.value=o[i],this._runFieldValidators(
877
+ context:l}=u,m=this._validateNestedValue(e,n,o,i,a,c);return Object.keys(m).length>0?m:(l.value=o[i],this._runFieldValidators(
877
878
  e,n,o,i,l,a))}_normalizeDefault(e,r,{fieldPath:n,currentObject:o,containerKey:i,objectBeforeCast:s,options:a,settings:c}){
878
- let u={...o};return P(u,i,r),{errors:this._normalizeAndValidateValue(e,r,n,u,i,s,a,c),value:u[i]}}_validateNestedValue(e,r,n,o,i,s){
879
+ let u={...o};return T(u,i,r),{errors:this._normalizeAndValidateValue(e,r,n,u,i,s,a,c),value:u[i]}}_validateNestedValue(e,r,n,o,i,s){
879
880
  if(e.type==="object"){let c=this._resolveObjectFieldMode(r,e);return c.kind==="nested"?this._validateNestedObjectSchema(
880
881
  c,r,n,o,i,s):c.kind==="map"?this._validateObjectValues(r,n,o,c.valuesConfig,i,s):{}}if(e.type!=="array")return{};let a=this.
881
882
  _resolveArrayItemsConfig(r,e);return a?this._validateArrayItems(r,n,o,a,i,s):{}}_validateNestedObjectSchema(e,r,n,o,i,s){
882
883
  let a=n[o],c=e.allowAdditionalProperties?this._extractKnownObjectFields(a,e.schema):a,u=e.schema._validateWithOperation(
883
- s.operationName,s.operation,c,Ve(i,r));return P(n,o,e.allowAdditionalProperties?this._mergeKnownAndPassthroughObjectFields(
884
- a,e.schema,u.validatedObject):u.validatedObject),Ue(u.errors,r)}_extractKnownObjectFields(e,r){let n={};for(let[o,i]of Object.
885
- entries(e))Object.hasOwn(r.structure,o)&&P(n,o,i);return n}_mergeKnownAndPassthroughObjectFields(e,r,n){let o={};for(let i of Object.
886
- keys(e)){if(!Object.hasOwn(r.structure,i)){P(o,i,e[i]);continue}Object.hasOwn(n,i)&&P(o,i,n[i])}for(let[i,s]of Object.entries(
887
- n))Object.hasOwn(o,i)||P(o,i,s);return o}_validateObjectValues(e,r,n,o,i,s){let a=r[n],c={...a},u={};P(r,n,c);for(let l of Object.
888
- keys(a)){let p=Ce(e,l);if(this._fieldToBeSkipped(p,i))continue;let d=c[l];if(d===void 0){s.rejectExplicitUndefined?this.
889
- _mergeErrors(u,this._singleErrorMap(this._typeError(p).errorObject)):delete c[l];continue}if(o.kind==="schema"){let _=o.
890
- schema._validateWithOperation("replace",o.schema.operations.replace,d,Ve(i,p));P(c,l,_.validatedObject),this._mergeErrors(
891
- u,Ue(_.errors,p));continue}let h=this._normalizeAndValidateValue(o.definition,d,p,c,l,a,i,this._buildArrayItemSettings(o.
892
- definition,s));this._mergeErrors(u,h)}return u}_validateArrayItems(e,r,n,o,i,s){let a=r[n],c=a.slice(),u={};P(r,n,c);for(let l=0;l<
893
- c.length;l++){let p=Ce(e,l);if(this._fieldToBeSkipped(p,i))continue;if(!Object.hasOwn(a,l)||c[l]===void 0){s.rejectExplicitUndefined?
894
- this._mergeErrors(u,this._singleErrorMap(this._typeError(p).errorObject)):delete c[l];continue}if(o.kind==="schema"){let h=o.
895
- schema._validateWithOperation("replace",o.schema.operations.replace,c[l],Ve(i,p));P(c,l,h.validatedObject),this._mergeErrors(
896
- u,Ue(h.errors,p));continue}let d=this._normalizeAndValidateValue(o.definition,c[l],p,c,l,a,i,this._buildArrayItemSettings(
884
+ s.operationName,s.operation,c,Be(i,r));return T(n,o,e.allowAdditionalProperties?this._mergeKnownAndPassthroughObjectFields(
885
+ a,e.schema,u.validatedObject):u.validatedObject),Ve(u.errors,r)}_extractKnownObjectFields(e,r){let n={};for(let[o,i]of Object.
886
+ entries(e))Object.hasOwn(r.structure,o)&&T(n,o,i);return n}_mergeKnownAndPassthroughObjectFields(e,r,n){let o={};for(let i of Object.
887
+ keys(e)){if(!Object.hasOwn(r.structure,i)){T(o,i,e[i]);continue}Object.hasOwn(n,i)&&T(o,i,n[i])}for(let[i,s]of Object.entries(
888
+ n))Object.hasOwn(o,i)||T(o,i,s);return o}_validateObjectValues(e,r,n,o,i,s){let a=r[n],c={...a},u={};T(r,n,c);for(let l of Object.
889
+ keys(a)){let m=Te(e,l);if(this._fieldToBeSkipped(m,i))continue;let d=c[l];if(d===void 0){s.rejectExplicitUndefined?this.
890
+ _mergeErrors(u,this._singleErrorMap(this._typeError(m).errorObject)):delete c[l];continue}if(o.kind==="schema"){let g=o.
891
+ schema._validateWithOperation("replace",o.schema.operations.replace,d,Be(i,m));T(c,l,g.validatedObject),this._mergeErrors(
892
+ u,Ve(g.errors,m));continue}let _=this._normalizeAndValidateValue(o.definition,d,m,c,l,a,i,this._buildArrayItemSettings(o.
893
+ definition,s));this._mergeErrors(u,_)}return u}_validateArrayItems(e,r,n,o,i,s){let a=r[n],c=a.slice(),u={};T(r,n,c);for(let l=0;l<
894
+ c.length;l++){let m=Te(e,l);if(this._fieldToBeSkipped(m,i))continue;if(!Object.hasOwn(a,l)||c[l]===void 0){s.rejectExplicitUndefined?
895
+ this._mergeErrors(u,this._singleErrorMap(this._typeError(m).errorObject)):delete c[l];continue}if(o.kind==="schema"){let _=o.
896
+ schema._validateWithOperation("replace",o.schema.operations.replace,c[l],Be(i,m));T(c,l,_.validatedObject),this._mergeErrors(
897
+ u,Ve(_.errors,m));continue}let d=this._normalizeAndValidateValue(o.definition,c[l],m,c,l,a,i,this._buildArrayItemSettings(
897
898
  o.definition,s));this._mergeErrors(u,d)}return u}_validateField(e,r,n,o,i){if(!Object.hasOwn(this.structure,e))return{};
898
899
  let s=this.structure[e];if(this._fieldToBeSkipped(e,o))return{};let a=i.isFieldPresent(e),c=r[e],u=c===void 0;return i.enforceRequired&&
899
900
  s.required&&(!a||u)&&!this._paramToBeSkipped("required",o.skipParams,e)?this._singleErrorMap({field:e,code:"REQUIRED",message:"\
900
901
  Field is required",params:{}}):a?u?i.rejectExplicitUndefined?this._singleErrorMap(this._typeError(e).errorObject):{}:this.
901
902
  _normalizeAndValidateValue(s,c,e,n,e,r,o,i):{}}_validateWithOperation(e,r,n,o){this._assertSupportedOptions(o);let i={},
902
- s={...n},a=this._buildOperationSettings(e,r,n);for(let c of Object.keys(n))Object.hasOwn(this.structure,c)||P(i,c,{field:c,
903
+ s={...n},a=this._buildOperationSettings(e,r,n);for(let c of Object.keys(n))Object.hasOwn(this.structure,c)||T(i,c,{field:c,
903
904
  code:"FIELD_NOT_ALLOWED",message:"Field not allowed",params:{}});for(let c of a.targetFieldNames){let u=this._validateField(
904
905
  c,n,s,o,a);this._mergeErrors(i,u)}if(a.applyDefaults){for(let c of Object.keys(this.structure))if(!a.isFieldPresent(c)&&
905
906
  this.structure[c].defaultTo!==void 0){let u=this.structure[c],l=typeof u.defaultTo=="function"?u.defaultTo():u.defaultTo,
906
- p=this._normalizeDefault(u,l,{fieldPath:c,currentObject:s,containerKey:c,objectBeforeCast:n,options:o,settings:a});if(this.
907
- _mergeErrors(i,p.errors),Object.keys(p.errors).length>0)continue;P(s,c,p.value),a.defaultedFields.add(c)}}return{validatedObject:this.
908
- _buildOperationResult(n,s,a),errors:i}}_validateSelectedTree(e,r,n,o,i=""){let s={},a={};for(let c of _i(Object.keys(e))){
909
- let u=wi(i,c);if(!Object.hasOwn(this.structure,c))throw new Error(`Unknown schema path "${u}".`);let l=this._validateSelectedField(
907
+ m=this._normalizeDefault(u,l,{fieldPath:c,currentObject:s,containerKey:c,objectBeforeCast:n,options:o,settings:a});if(this.
908
+ _mergeErrors(i,m.errors),Object.keys(m.errors).length>0)continue;T(s,c,m.value),a.defaultedFields.add(c)}}return{validatedObject:this.
909
+ _buildOperationResult(n,s,a),errors:i}}_validateSelectedTree(e,r,n,o,i=""){let s={},a={};for(let c of Ei(Object.keys(e))){
910
+ let u=bi(i,c);if(!Object.hasOwn(this.structure,c))throw new Error(`Unknown schema path "${u}".`);let l=this._validateSelectedField(
910
911
  c,e[c],r,a,n,o,u);this._mergeErrors(s,l)}return{validatedObject:a,errors:s}}_validateSelectedField(e,r,n,o,i,s,a){if(!Object.
911
- hasOwn(this.structure,e))return{};let c=this.structure[e],u=r.self===!0,l=mi(r);if(this._fieldToBeSkipped(a,i))return{};
912
- let p=Object.hasOwn(n,e),d=n[e],h={};if(!p){if(u&&s.enforceRequired&&c.required&&!this._paramToBeSkipped("required",i.skipParams,
913
- a)&&this._mergeErrors(h,this._singleErrorMap({field:a,code:"REQUIRED",message:"Field is required",params:{}})),u&&s.applyDefaults&&
914
- c.defaultTo!==void 0){let N=typeof c.defaultTo=="function"?c.defaultTo():c.defaultTo,D=this._normalizeDefault(c,N,{fieldPath:a,
915
- currentObject:o,containerKey:e,objectBeforeCast:n,options:i,settings:s});this._mergeErrors(h,D.errors),Object.keys(D.errors).
916
- length===0&&P(o,e,D.value)}return h}if(d===void 0)return u&&s.rejectExplicitUndefined?this._singleErrorMap(this._typeError(
917
- a).errorObject):{};let _={[e]:d};if(u){let N=this._normalizeAndValidateValue(c,d,a,_,e,n,i,s);return Object.hasOwn(_,e)&&
918
- _[e]!==void 0?P(o,e,_[e]):_[e]===null&&P(o,e,null),N}if(!l)return{};let E=this._castValue(c,d,a,_,e,n,i,s);if(Object.keys(
919
- E.errors).length>0)return E.errors;if(!E.shouldContinue)return{};let O=this._validateSelectedDescendants(c,r.children,a,
920
- _,e,i,s);return Rt(_[e])&&P(o,e,_[e]),O}_validateSelectedDescendants(e,r,n,o,i,s,a){if(e.type==="object"){let c=this._resolveObjectFieldMode(
921
- n,e);if(c.kind!=="nested")throw new Error(`Schema path "${n}" does not support nested field selection.`);let u=o[i];if(!H(
922
- u))return{};let l=c.schema._validateSelectedTree(r,u,Ve(s,n),{...a,defaultedFields:new Set});return P(o,i,l.validatedObject),
923
- Ue(l.errors,n)}if(e.type==="array"){let c=this._resolveArrayItemsConfig(n,e);if(!c)throw new Error(`Schema path "${n}" d\
912
+ hasOwn(this.structure,e))return{};let c=this.structure[e],u=r.self===!0,l=yi(r);if(this._fieldToBeSkipped(a,i))return{};
913
+ let m=Object.hasOwn(n,e),d=n[e],_={};if(!m){if(u&&s.enforceRequired&&c.required&&!this._paramToBeSkipped("required",i.skipParams,
914
+ a)&&this._mergeErrors(_,this._singleErrorMap({field:a,code:"REQUIRED",message:"Field is required",params:{}})),u&&s.applyDefaults&&
915
+ c.defaultTo!==void 0){let R=typeof c.defaultTo=="function"?c.defaultTo():c.defaultTo,k=this._normalizeDefault(c,R,{fieldPath:a,
916
+ currentObject:o,containerKey:e,objectBeforeCast:n,options:i,settings:s});this._mergeErrors(_,k.errors),Object.keys(k.errors).
917
+ length===0&&T(o,e,k.value)}return _}if(d===void 0)return u&&s.rejectExplicitUndefined?this._singleErrorMap(this._typeError(
918
+ a).errorObject):{};let g={[e]:d};if(u){let R=this._normalizeAndValidateValue(c,d,a,g,e,n,i,s);return Object.hasOwn(g,e)&&
919
+ g[e]!==void 0?T(o,e,g[e]):g[e]===null&&T(o,e,null),R}if(!l)return{};let E=this._castValue(c,d,a,g,e,n,i,s);if(Object.keys(
920
+ E.errors).length>0)return E.errors;if(!E.shouldContinue)return{};let x=this._validateSelectedDescendants(c,r.children,a,
921
+ g,e,i,s);return Nt(g[e])&&T(o,e,g[e]),x}_validateSelectedDescendants(e,r,n,o,i,s,a){if(e.type==="object"){let c=this._resolveObjectFieldMode(
922
+ n,e);if(c.kind!=="nested")throw new Error(`Schema path "${n}" does not support nested field selection.`);let u=o[i];if(!q(
923
+ u))return{};let l=c.schema._validateSelectedTree(r,u,Be(s,n),{...a,defaultedFields:new Set});return T(o,i,l.validatedObject),
924
+ Ve(l.errors,n)}if(e.type==="array"){let c=this._resolveArrayItemsConfig(n,e);if(!c)throw new Error(`Schema path "${n}" d\
924
925
  oes not define array items for nested selection.`);return this._validateSelectedArrayItems(n,o,i,c,r,s,a)}throw new Error(
925
926
  `Schema path "${n}" does not support nested field selection.`)}_validateSelectedArrayItems(e,r,n,o,i,s,a){let c=[],u=r[n],
926
- l={};P(r,n,c);for(let p of _i(Object.keys(i))){if(!/^[0-9]+$/.test(p))throw new Error(`Schema path "${Ce(e,p)}" is inval\
927
- id because array segments must use numeric indexes.`);let d=Number(p),h=Ce(e,d),_=i[p],E=_.self===!0,O=mi(_);if(this._fieldToBeSkipped(
928
- h,s))continue;if(!Object.hasOwn(u,d)){E&&a.rejectExplicitUndefined&&P(l,h,this._typeError(h).errorObject);continue}let N=u[d];
929
- if(N===void 0){E&&a.rejectExplicitUndefined&&P(l,h,this._typeError(h).errorObject);continue}if(o.kind==="schema"){if(E){
930
- let v=o.schema._validateWithOperation("replace",o.schema.operations.replace,N,Ve(s,h));Rt(v.validatedObject)&&P(c,d,v.validatedObject),
931
- this._mergeErrors(l,Ue(v.errors,h));continue}if(!O)continue;let A=o.schema._validateSelectedTree(_.children,N,Ve(s,h),{...a,
932
- operationName:"replace",operation:o.schema.operations.replace,defaultedFields:new Set});Rt(A.validatedObject)&&P(c,d,A.validatedObject),
933
- this._mergeErrors(l,Ue(A.errors,h));continue}let D=this._buildArrayItemSettings(o.definition,a),I=[N];if(E){let A=this._normalizeAndValidateValue(
934
- o.definition,N,h,I,0,u,s,D);Object.hasOwn(I,0)&&I[0]!==void 0?P(c,d,I[0]):I[0]===null&&P(c,d,null),this._mergeErrors(l,A);
935
- continue}if(!O)continue;let C=this._castValue(o.definition,N,h,I,0,u,s,D);if(Object.keys(C.errors).length>0){this._mergeErrors(
936
- l,C.errors);continue}if(!C.shouldContinue)continue;let M=this._validateSelectedDescendants(o.definition,_.children,h,I,0,
937
- s,D);Rt(I[0])&&P(c,d,I[0]),this._mergeErrors(l,M)}return l}validateWith(e,r,n={}){if(!Object.hasOwn(this.operations,e))throw new Error(
927
+ l={};T(r,n,c);for(let m of Ei(Object.keys(i))){if(!/^[0-9]+$/.test(m))throw new Error(`Schema path "${Te(e,m)}" is inval\
928
+ id because array segments must use numeric indexes.`);let d=Number(m),_=Te(e,d),g=i[m],E=g.self===!0,x=yi(g);if(this._fieldToBeSkipped(
929
+ _,s))continue;if(!Object.hasOwn(u,d)){E&&a.rejectExplicitUndefined&&T(l,_,this._typeError(_).errorObject);continue}let R=u[d];
930
+ if(R===void 0){E&&a.rejectExplicitUndefined&&T(l,_,this._typeError(_).errorObject);continue}if(o.kind==="schema"){if(E){
931
+ let A=o.schema._validateWithOperation("replace",o.schema.operations.replace,R,Be(s,_));Nt(A.validatedObject)&&T(c,d,A.validatedObject),
932
+ this._mergeErrors(l,Ve(A.errors,_));continue}if(!x)continue;let O=o.schema._validateSelectedTree(g.children,R,Be(s,_),{...a,
933
+ operationName:"replace",operation:o.schema.operations.replace,defaultedFields:new Set});Nt(O.validatedObject)&&T(c,d,O.validatedObject),
934
+ this._mergeErrors(l,Ve(O.errors,_));continue}let k=this._buildArrayItemSettings(o.definition,a),C=[R];if(E){let O=this._normalizeAndValidateValue(
935
+ o.definition,R,_,C,0,u,s,k);Object.hasOwn(C,0)&&C[0]!==void 0?T(c,d,C[0]):C[0]===null&&T(c,d,null),this._mergeErrors(l,O);
936
+ continue}if(!x)continue;let v=this._castValue(o.definition,R,_,C,0,u,s,k);if(Object.keys(v.errors).length>0){this._mergeErrors(
937
+ l,v.errors);continue}if(!v.shouldContinue)continue;let D=this._validateSelectedDescendants(o.definition,g.children,_,C,0,
938
+ s,k);Nt(C[0])&&T(c,d,C[0]),this._mergeErrors(l,D)}return l}validateWith(e,r,n={}){if(!Object.hasOwn(this.operations,e))throw new Error(
938
939
  `Unknown operation "${e}".`);let o=this.operations[e];return this._assertPlainObjectInput(e,r),this._validateWithOperation(
939
- e,o,r,n)}validateAt(e,r,n={}){this._assertPlainObjectInput("validateAt",r);let o=Ur(e),{operationName:i,operation:s,validationOptions:a}=this.
940
- _resolvePathValidationRequest(n),c=this._validateSelectedTree(yi([e]),r,a,this._buildOperationSettings(i,s,r));return{validatedValue:Au(
940
+ e,o,r,n)}validateAt(e,r,n={}){this._assertPlainObjectInput("validateAt",r);let o=Vr(e),{operationName:i,operation:s,validationOptions:a}=this.
941
+ _resolvePathValidationRequest(n),c=this._validateSelectedTree(gi([e]),r,a,this._buildOperationSettings(i,s,r));return{validatedValue:Cu(
941
942
  c.validatedObject,o),errors:c.errors}}validatePaths(e,r,n={}){if(this._assertPlainObjectInput("validatePaths",r),!Array.
942
943
  isArray(e)||e.length===0)throw new Error("validatePaths() expects a non-empty array of schema paths.");let{operationName:o,
943
- operation:i,validationOptions:s}=this._resolvePathValidationRequest(n);return this._validateSelectedTree(yi(e),r,s,this.
944
+ operation:i,validationOptions:s}=this._resolvePathValidationRequest(n);return this._validateSelectedTree(gi(e),r,s,this.
944
945
  _buildOperationSettings(o,i,r))}_installOperationMethods(){for(let e of Object.keys(this.operations)){if(e in this)throw new Error(
945
946
  `Operation name "${e}" is reserved and cannot be used as a schema method.`);this[e]=(r,n={})=>this.validateWith(e,r,n)}}toJsonSchema(e={}){
946
- return fi(this,e)}getFieldDefinitions(){return zr.has(this)||zr.set(this,Lr(this.structure)),zr.get(this)}getFieldDefinition(e){
947
- if(typeof e!="string"||e.trim()==="")throw new Error("Field path must be a non-empty string.");let r=Vr(this,Ur(e.trim()));
948
- return r===null?null:Lr(r)}getFieldMessages(e){let r=this.getFieldDefinition(e);return!r||typeof r.messages!="object"||r.
949
- messages===null?Object.freeze({}):Lr(r.messages)}cleanup(e,r){let n={};for(let o of Object.keys(e))Object.hasOwn(this.structure,
950
- o)&&this.structure[o][r]&&P(n,o,e[o]);return n}};var{parse:Em,stringify:Nu}=JSON,{keys:wm}=Object,ku=String,ju="string";var bi="object",Du=(t,e)=>e;var xi=(t,e,r)=>{let n=ku(e.push(r)-1);return t.set(r,n),n};var Oi=(t,e,r)=>{let n=e&&typeof e===bi?(l,p)=>l===""||-1<e.indexOf(l)?p:void 0:e||Du,o=new Map,i=[],s=[],a=+xi(o,i,n.call(
951
- {"":t},"",t)),c=!a;for(;a<i.length;)c=!0,s[a]=Nu(i[a++],u,r);return"["+s.join(",")+"]";function u(l,p){if(c)return c=!c,
952
- p;let d=n.call(this,l,p);switch(typeof d){case bi:if(d===null)return d;case ju:return o.get(d)||xi(o,i,d)}return d}};var Lu=new Set(["true","1","yes","y","on"]),zu=new Set(["false","0","no","n","off"]);function $u(t){return t!==null&&(typeof t==
953
- "object"||typeof t=="function")&&typeof t.then=="function"}function Ai(t){if(typeof t=="number")return Number.isFinite(t)?
947
+ return mi(this,e)}getFieldDefinitions(){return $r.has(this)||$r.set(this,zr(this.structure)),$r.get(this)}getFieldDefinition(e){
948
+ if(typeof e!="string"||e.trim()==="")throw new Error("Field path must be a non-empty string.");let r=Br(this,Vr(e.trim()));
949
+ return r===null?null:zr(r)}getFieldMessages(e){let r=this.getFieldDefinition(e);return!r||typeof r.messages!="object"||r.
950
+ messages===null?Object.freeze({}):zr(r.messages)}cleanup(e,r){let n={};for(let o of Object.keys(e))Object.hasOwn(this.structure,
951
+ o)&&this.structure[o][r]&&T(n,o,e[o]);return n}};var{parse:Sm,stringify:ju}=JSON,{keys:bm}=Object,Du=String,Mu="string";var Oi="object",Lu=(t,e)=>e;var Ai=(t,e,r)=>{let n=Du(e.push(r)-1);return t.set(r,n),n};var vi=(t,e,r)=>{let n=e&&typeof e===Oi?(l,m)=>l===""||-1<e.indexOf(l)?m:void 0:e||Lu,o=new Map,i=[],s=[],a=+Ai(o,i,n.call(
952
+ {"":t},"",t)),c=!a;for(;a<i.length;)c=!0,s[a]=ju(i[a++],u,r);return"["+s.join(",")+"]";function u(l,m){if(c)return c=!c,
953
+ m;let d=n.call(this,l,m);switch(typeof d){case Oi:if(d===null)return d;case Mu:return o.get(d)||Ai(o,i,d)}return d}};var $u=new Set(["true","1","yes","y","on"]),Uu=new Set(["false","0","no","n","off"]);function Vu(t){return t!==null&&(typeof t==
954
+ "object"||typeof t=="function")&&typeof t.then=="function"}function Ci(t){if(typeof t=="number")return Number.isFinite(t)?
954
955
  t:null;if(typeof t=="bigint"){let e=Number(t);return Number.isSafeInteger(e)?e:null}if(typeof t=="string"){let e=t.trim();
955
- if(e==="")return null;let r=Number(e);return Number.isFinite(r)?r:null}return null}function Fr(t,e){if(Object.is(t,e))return!0;
956
+ if(e==="")return null;let r=Number(e);return Number.isFinite(r)?r:null}return null}function qr(t,e){if(Object.is(t,e))return!0;
956
957
  if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t instanceof RegExp&&e instanceof RegExp)return t.
957
958
  source===e.source&&t.flags===e.flags;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==
958
- e.length)return!1;for(let o=0;o<t.length;o++)if(!Fr(t[o],e[o]))return!1;return!0}if(t===null||e===null||typeof t!="objec\
959
+ e.length)return!1;for(let o=0;o<t.length;o++)if(!qr(t[o],e[o]))return!1;return!0}if(t===null||e===null||typeof t!="objec\
959
960
  t"||typeof e!="object"||Object.getPrototypeOf(t)!==Object.getPrototypeOf(e))return!1;let r=Object.keys(t),n=Object.keys(
960
- e);if(r.length!==n.length)return!1;for(let o of r)if(!Object.hasOwn(e,o)||!Fr(t[o],e[o]))return!1;return!0}var Uu={install(t){
961
+ e);if(r.length!==n.length)return!1;for(let o of r)if(!Object.hasOwn(e,o)||!qr(t[o],e[o]))return!1;return!0}var Bu={install(t){
961
962
  let{addType:e,addValidator:r}=t;e("none",n=>n.value),e("file",n=>{let o=n.value;o==null&&n.throwTypeError();let i=typeof o;
962
963
  if(i==="string"||i==="number"||i==="boolean"){let s=o.toString();return n.definition.noTrim?s:s.trim()}n.throwTypeError()}),
963
964
  e("string",n=>{let o=n.value;if(o==null)return"";let i=typeof o;if(i==="string"||i==="number"||i==="boolean"){let s=o.toString();
964
- return n.definition.noTrim?s:s.trim()}n.throwTypeError()}),e("blob",n=>n.value),e("number",n=>{let o=Ai(n.value);return o===
965
- null&&n.throwTypeError(),o}),e("integer",n=>{let o=Ai(n.value);return(o===null||!Number.isInteger(o))&&n.throwTypeError(),
966
- o}),e("epochMilliseconds",n=>{let o=Cr(n.value,864e13);return o===null&&n.throwTypeError(),o}),e("epochSeconds",n=>{let o=Cr(
967
- n.value,864e10);return o===null&&n.throwTypeError(),o}),e("dateTime",n=>{let o=et(n.definition,n.fieldName);return oi(n.
968
- value,o)||n.throwTypeError(),n.value}),e("date",n=>(ri(n.value)||n.throwTypeError(),n.value)),e("time",n=>{let o=et(n.definition,
969
- n.fieldName);return ni(n.value,o)||n.throwTypeError(),n.value}),e("array",n=>n.definition.type==="array"&&!Array.isArray(
970
- n.value)?[n.value]:n.value),e("object",n=>(H(n.value)||n.throwTypeError(),n.value)),e("serialize",n=>{try{return JSON.stringify(
971
- n.value)}catch{try{return Oi(n.value)}catch{n.throwTypeError()}}}),e("boolean",n=>{if(typeof n.value=="boolean")return n.
965
+ return n.definition.noTrim?s:s.trim()}n.throwTypeError()}),e("blob",n=>n.value),e("number",n=>{let o=Ci(n.value);return o===
966
+ null&&n.throwTypeError(),o}),e("integer",n=>{let o=Ci(n.value);return(o===null||!Number.isInteger(o))&&n.throwTypeError(),
967
+ o}),e("epochMilliseconds",n=>{let o=Tr(n.value,864e13);return o===null&&n.throwTypeError(),o}),e("epochSeconds",n=>{let o=Tr(
968
+ n.value,864e10);return o===null&&n.throwTypeError(),o}),e("dateTime",n=>{let o=tt(n.definition,n.fieldName);return si(n.
969
+ value,o)||n.throwTypeError(),n.value}),e("date",n=>(oi(n.value)||n.throwTypeError(),n.value)),e("time",n=>{let o=tt(n.definition,
970
+ n.fieldName);return ii(n.value,o)||n.throwTypeError(),n.value}),e("array",n=>n.definition.type==="array"&&!Array.isArray(
971
+ n.value)?[n.value]:n.value),e("object",n=>(q(n.value)||n.throwTypeError(),n.value)),e("serialize",n=>{try{return JSON.stringify(
972
+ n.value)}catch{try{return vi(n.value)}catch{n.throwTypeError()}}}),e("boolean",n=>{if(typeof n.value=="boolean")return n.
972
973
  value;if(typeof n.value=="number"){if(n.value===1)return!0;if(n.value===0)return!1;n.throwTypeError()}if(typeof n.value==
973
974
  "bigint"){if(n.value===1n)return!0;if(n.value===0n)return!1;n.throwTypeError()}if(typeof n.value=="string"){let o=String(
974
975
  n.definition.stringFalseWhen||"false").trim().toLowerCase(),i=String(n.definition.stringTrueWhen||"true").trim().toLowerCase(),
975
- s=n.value.trim().toLowerCase(),a=new Set([...zu,o]),c=new Set([...Lu,i]);if(a.has(s))return!1;if(c.has(s))return!0}n.throwTypeError()}),
976
+ s=n.value.trim().toLowerCase(),a=new Set([...Uu,o]),c=new Set([...$u,i]);if(a.has(s))return!1;if(c.has(s))return!0}n.throwTypeError()}),
976
977
  e("id",n=>{if(typeof n.value=="number"){if(Number.isSafeInteger(n.value)&&n.value>0)return n.value;n.throwTypeError()}if(typeof n.
977
978
  value=="bigint"){if(n.value>0n&&n.value<=BigInt(Number.MAX_SAFE_INTEGER))return Number(n.value);n.throwTypeError()}if(typeof n.
978
979
  value=="string"){let o=n.value.trim();/^[1-9][0-9]*$/.test(o)||n.throwTypeError();let i=Number(o);return Number.isSafeInteger(
979
980
  i)||n.throwTypeError(),i}n.throwTypeError()}),r("minLength",n=>{n.value!==void 0&&n.definition.type==="string"&&n.value.
980
981
  toString&&n.value.toString().length<n.parameterValue&&n.throwParamError("MIN_LENGTH",`Length must be at least ${n.parameterValue}\
981
- characters.`,{min:n.parameterValue,actual:n.value.toString().length})}),r("min",n=>{n.value!==void 0&&ze(n.definition)&&
982
+ characters.`,{min:n.parameterValue,actual:n.value.toString().length})}),r("min",n=>{n.value!==void 0&&$e(n.definition)&&
982
983
  typeof n.value=="number"&&n.value<n.parameterValue&&n.throwParamError("MIN_VALUE",`Value must be at least ${n.parameterValue}\
983
984
  .`,{min:n.parameterValue,actual:n.value})}),r("maxLength",n=>{n.value!==void 0&&n.definition.type==="string"&&n.value.toString&&
984
985
  n.value.toString().length>n.parameterValue&&n.throwParamError("MAX_LENGTH",`Length must be no more than ${n.parameterValue}\
985
- characters.`,{max:n.parameterValue,actual:n.value.toString().length})}),r("max",n=>{n.value!==void 0&&ze(n.definition)&&
986
+ characters.`,{max:n.parameterValue,actual:n.value.toString().length})}),r("max",n=>{n.value!==void 0&&$e(n.definition)&&
986
987
  typeof n.value=="number"&&n.value>n.parameterValue&&n.throwParamError("MAX_VALUE",`Value must be no more than ${n.parameterValue}\
987
988
  .`,{max:n.parameterValue,actual:n.value})}),r("enum",n=>{if(!Array.isArray(n.parameterValue))throw new Error(`Enum for ${n.
988
- fieldName} must be an array.`);n.parameterValue.some(i=>Fr(i,n.value))||n.throwParamError("ENUM_VALUE","Value must match\
989
+ fieldName} must be an array.`);n.parameterValue.some(i=>qr(i,n.value))||n.throwParamError("ENUM_VALUE","Value must match\
989
990
  one of the allowed enum values.",{allowed:n.parameterValue})}),r("pattern",n=>{if(n.value===void 0||n.definition.type!==
990
991
  "string"||typeof n.value!="string")return;let o=n.parameterValue,i=o instanceof RegExp?new RegExp(o.source,o.flags):typeof o==
991
992
  "string"?new RegExp(o):null;if(!i)throw new Error(`Pattern for ${n.fieldName} must be a string or RegExp.`);i.test(n.value)||
@@ -993,7 +994,7 @@ n.throwParamError("PATTERN","Value does not match the required pattern.",{patter
993
994
  parameterValue){if(n.definition.type!=="boolean")throw new Error(`strictBoolean can only be used on boolean fields (${n.
994
995
  fieldName}).`);typeof n.valueBeforeCast!="boolean"&&n.throwParamError("STRICT_BOOLEAN","Value must be a boolean.")}}),r(
995
996
  "validator",n=>{if(typeof n.parameterValue!="function")throw new Error(`Validator for ${n.fieldName} must be a function.`);
996
- let o=n.parameterValue(n.value,n.object,n);if($u(o))throw new Error(`Custom validator for "${n.fieldName}" must be synch\
997
+ let o=n.parameterValue(n.value,n.object,n);if(Vu(o))throw new Error(`Custom validator for "${n.fieldName}" must be synch\
997
998
  ronous.`);typeof o=="string"&&n.throwParamError("CUSTOM_VALIDATOR_FAILED",o)}),r("uppercase",n=>{if(typeof n.value=="str\
998
999
  ing")return n.value.toUpperCase()}),r("lowercase",n=>{if(typeof n.value=="string")return n.value.toLowerCase()}),r("leng\
999
1000
  th",n=>{if(typeof n.value=="string")return n.value.substr(0,n.parameterValue);Number.isInteger(Number(n.valueBeforeCast))&&
@@ -1005,27 +1006,27 @@ n.throwParamError("MAX_ITEMS",`Must have no more than ${n.parameterValue} items.
1005
1006
  r("notEmpty",n=>{n.parameterValue&&typeof n.value=="string"&&n.value===""&&n.throwParamError("NOT_EMPTY","Field cannot b\
1006
1007
  e empty.")}),r("required",()=>{}),r("unsigned",()=>{}),r("precision",()=>{}),r("scale",()=>{}),r("temporalPrecision",n=>{
1007
1008
  if(n.definition.type!=="time"&&n.definition.type!=="dateTime")throw new Error(`temporalPrecision can only be used on tim\
1008
- e or dateTime fields (${n.fieldName}).`)}),r("nullable",()=>{}),r("nullOnEmpty",()=>{}),r("defaultTo",()=>{})}},vi=Uu;var Pi=new WeakMap,Ri=new WeakMap,Ni=Symbol.for("json-rest-schema.registry-metadata"),jt=new WeakSet;function Vu(t,e,r){
1009
- if(typeof r!="function")throw new Error(`Type handler for '${e}' must be a function.`);P(t,e,r)}function Bu(t,e,r){if(typeof r!=
1010
- "function")throw new Error(`Validator handler for '${e}' must be a function.`);P(t,e,r)}function Dt(t={}){let e=Object.create(
1011
- null);for(let[r,n]of Object.entries(t))P(e,r,n);return e}function Ci(t,e){if(typeof t.install!="function")throw new Error(
1012
- "Plugin must have an install method.");t.install(e)}function Ti(t,e,r){Pi.set(t,e),Ri.set(t,r),Object.defineProperty(t,Ni,
1013
- {value:Object.freeze({getTypes:()=>e,getValidators:()=>r}),enumerable:!1,configurable:!1,writable:!1})}function Fu(t){if(!t||
1014
- typeof t!="object"&&typeof t!="function")return null;let e=Pi.get(t),r=Ri.get(t);if(e&&r)return{types:e,validators:r};let n=t[Ni];
1009
+ e or dateTime fields (${n.fieldName}).`)}),r("nullable",()=>{}),r("nullOnEmpty",()=>{}),r("defaultTo",()=>{})}},Ti=Bu;var Ni=new WeakMap,ki=new WeakMap,ji=Symbol.for("json-rest-schema.registry-metadata"),Dt=new WeakSet;function Fu(t,e,r){
1010
+ if(typeof r!="function")throw new Error(`Type handler for '${e}' must be a function.`);T(t,e,r)}function qu(t,e,r){if(typeof r!=
1011
+ "function")throw new Error(`Validator handler for '${e}' must be a function.`);T(t,e,r)}function Mt(t={}){let e=Object.create(
1012
+ null);for(let[r,n]of Object.entries(t))T(e,r,n);return e}function Ii(t,e){if(typeof t.install!="function")throw new Error(
1013
+ "Plugin must have an install method.");t.install(e)}function Pi(t,e,r){Ni.set(t,e),ki.set(t,r),Object.defineProperty(t,ji,
1014
+ {value:Object.freeze({getTypes:()=>e,getValidators:()=>r}),enumerable:!1,configurable:!1,writable:!1})}function Hu(t){if(!t||
1015
+ typeof t!="object"&&typeof t!="function")return null;let e=Ni.get(t),r=ki.get(t);if(e&&r)return{types:e,validators:r};let n=t[ji];
1015
1016
  return n&&typeof n.getTypes=="function"&&typeof n.getValidators=="function"?{types:n.getTypes(),validators:n.getValidators()}:
1016
1017
  typeof t=="object"&&t.types&&typeof t.types=="object"&&t.validators&&typeof t.validators=="object"&&typeof t.create=="fu\
1017
1018
  nction"&&typeof t.replace=="function"&&typeof t.patch=="function"&&typeof t.toJsonSchema=="function"?{types:t.types,validators:t.
1018
- validators}:null}function qu(t){return t.length===1&&Array.isArray(t[0])?t[0]:t}function Ii(t,e,r){for(let[n,o]of Object.
1019
- entries(e)){if(Object.hasOwn(t,n)&&t[n]!==o){if(jt.has(o))continue;if(!jt.has(t[n]))throw new Error(`Cannot merge schema\
1020
- factories with conflicting ${r} "${n}".`)}P(t,n,o)}}function Hu(t,e,r){let n=qu(r).filter(Boolean);if(n.length<1)return{
1021
- types:Dt(t),validators:Dt(e)};let o=Object.create(null),i=Object.create(null);for(let s of n){let a=Fu(s);if(!a)throw new Error(
1022
- "Factory sources must be schema instances or schema factories created by json-rest-schema.");Ii(o,a.types,"type"),Ii(i,a.
1023
- validators,"validator")}return{types:o,validators:i}}function ki({types:t={},validators:e={},installCore:r=!0}={}){let n=Dt(
1024
- t),o=Dt(e),i=(s,a={})=>{let c=new Be(s,n,o,a.operations);return Ti(c,n,o),c};return Ti(i,n,o),i.addType=(s,a)=>{Vu(n,s,a)},
1025
- i.addValidator=(s,a)=>{Bu(o,s,a)},i.use=s=>{Ci(s,{addType:i.addType,addValidator:i.addValidator})},i.createFactory=(...s)=>{
1026
- let a=Hu(n,o,s);return ki({types:a.types,validators:a.validators,installCore:!1})},r&&Ci(vi,{addType:(s,a)=>{jt.add(a),i.
1027
- addType(s,a)},addValidator:(s,a)=>{jt.add(a),i.addValidator(s,a)}}),i}var me=ki({installCore:!0});function Te(t,e=new WeakSet){if(!t||typeof t!="object"||e.has(t))return t;e.add(t);for(let r of Object.getOwnPropertyNames(
1028
- t))Te(t[r],e);return Object.freeze(t)}var Gu=new Set(["create","replace","patch"]),Wu=Object.freeze({REQUIRED:{messageKey:"required",code:"kernel.validation.f\
1019
+ validators}:null}function Gu(t){return t.length===1&&Array.isArray(t[0])?t[0]:t}function Ri(t,e,r){for(let[n,o]of Object.
1020
+ entries(e)){if(Object.hasOwn(t,n)&&t[n]!==o){if(Dt.has(o))continue;if(!Dt.has(t[n]))throw new Error(`Cannot merge schema\
1021
+ factories with conflicting ${r} "${n}".`)}T(t,n,o)}}function Wu(t,e,r){let n=Gu(r).filter(Boolean);if(n.length<1)return{
1022
+ types:Mt(t),validators:Mt(e)};let o=Object.create(null),i=Object.create(null);for(let s of n){let a=Hu(s);if(!a)throw new Error(
1023
+ "Factory sources must be schema instances or schema factories created by json-rest-schema.");Ri(o,a.types,"type"),Ri(i,a.
1024
+ validators,"validator")}return{types:o,validators:i}}function Di({types:t={},validators:e={},installCore:r=!0}={}){let n=Mt(
1025
+ t),o=Mt(e),i=(s,a={})=>{let c=new Fe(s,n,o,a.operations);return Pi(c,n,o),c};return Pi(i,n,o),i.addType=(s,a)=>{Fu(n,s,a)},
1026
+ i.addValidator=(s,a)=>{qu(o,s,a)},i.use=s=>{Ii(s,{addType:i.addType,addValidator:i.addValidator})},i.createFactory=(...s)=>{
1027
+ let a=Wu(n,o,s);return Di({types:a.types,validators:a.validators,installCore:!1})},r&&Ii(Ti,{addType:(s,a)=>{Dt.add(a),i.
1028
+ addType(s,a)},addValidator:(s,a)=>{Dt.add(a),i.addValidator(s,a)}}),i}var pe=Di({installCore:!0});function Ie(t,e=new WeakSet){if(!t||typeof t!="object"||e.has(t))return t;e.add(t);for(let r of Object.getOwnPropertyNames(
1029
+ t))Ie(t[r],e);return Object.freeze(t)}var Xu=new Set(["create","replace","patch"]),Ju=Object.freeze({REQUIRED:{messageKey:"required",code:"kernel.validation.f\
1029
1030
  ield.required"},TYPE_CAST_FAILED:{messageKey:"default",code:"kernel.validation.field.typeCastFailed"},NOT_NULLABLE:{messageKey:"\
1030
1031
  default",code:"kernel.validation.field.notNullable"},MIN_LENGTH:{messageKey:"minLength",code:"kernel.validation.field.mi\
1031
1032
  nLength"},MAX_LENGTH:{messageKey:"maxLength",code:"kernel.validation.field.maxLength"},MIN_ITEMS:{messageKey:"minItems",
@@ -1035,35 +1036,35 @@ alue"},PATTERN:{messageKey:"pattern",code:"kernel.validation.field.pattern"},ENU
1035
1036
  validation.field.enumValue"},FIELD_NOT_ALLOWED:{messageKey:"additionalProperties",code:"kernel.validation.field.notAllow\
1036
1037
  ed"},CUSTOM_VALIDATOR_FAILED:{messageKey:"validator",code:""},STRICT_BOOLEAN:{messageKey:"default",code:"kernel.validati\
1037
1038
  on.field.strictBoolean"},RANGE_EXCEEDED:{messageKey:"default",code:"kernel.validation.field.rangeExceeded"},NOT_EMPTY:{messageKey:"\
1038
- default",code:"kernel.validation.field.notEmpty"}}),Xu=Object.freeze({code:"kernel.validation.invalid",message:"Invalid \
1039
- value."}),Ju=Object.freeze(["create","replace","patch","toJsonSchema"]);function Mt(t){return!!t&&typeof t=="object"&&Ju.
1040
- every(e=>typeof t[e]=="function")}function Di(t=null,{defaultMode:e="create",context:r="schema definition.mode"}={}){let n=Z(t),o=k(e).toLowerCase()||"cre\
1041
- ate",i=Object.prototype.hasOwnProperty.call(n,"mode")?k(n.mode).toLowerCase():"";if(!i)return o;if(!Gu.has(i))throw new TypeError(
1042
- `${r} must be one of: create, replace, patch.`);return i}function Mi(t=null,e=""){let r=k(e);if(!r)return{};let n=Z(t);return Mt(n.schema)?Z(n.schema.getFieldMessages(r)):{}}function Ku(t=null,e=""){
1043
- let r=k(e).split(".").filter(Boolean);return r.length<2?{}:(r.pop(),Mi(t,r.join(".")))}function ji(t,e){let r=e?t[e]:void 0;
1044
- if(typeof r=="string"){let i=k(r);return i?{message:i}:null}if(!R(r))return null;let n=k(r.message);if(!n)return null;let o=k(
1045
- r.code);return o?{message:n,code:o,params:Z(r.params)}:{message:n}}function Yu(t,e,r=null){let n=k(e?.code).toUpperCase(),
1046
- o=Wu[n]||{},i=Z(e?.params),s=Mi(r,t),a=n==="FIELD_NOT_ALLOWED"&&Object.keys(s).length<1?Ku(r,t):s,c=ji(a,o.messageKey)||
1047
- ji(a,"default");if(c)return c.code?{message:c.message,code:c.code,params:{...i,...c.params}}:{message:c.message};let u=k(
1048
- e?.message);if(u)return o.code?{message:u,code:o.code,params:i}:{message:u};let l=k(e?.code);return l?{message:l}:{...Xu,
1049
- params:{}}}function qr(t={},e=null){let r=Z(t),n={},o={};for(let[i,s]of Object.entries(r)){let a=k(i);if(!a)continue;if(typeof s==
1050
- "string"){n[a]=s;continue}let{message:c,code:u,params:l}=Yu(a,s,e);n[a]=c,u&&(o[a]={code:u,params:l})}return{fieldErrors:n,
1051
- fieldErrorCodes:o}}function Qu(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&(Object.prototype.hasOwnProperty.call(t,"schema")||Object.
1052
- prototype.hasOwnProperty.call(t,"mode"))}function Fe(t,{context:e="schema definition",defaultMode:r=""}={}){if(t==null)return null;
1053
- if(!Qu(t))throw new TypeError(`${e} must be a schema definition object.`);let n=Z(t);if(!Object.prototype.hasOwnProperty.
1054
- call(n,"schema"))throw new TypeError(`${e}.schema is required.`);if(!Mt(n.schema))throw new TypeError(`${e}.schema must \
1055
- be a json-rest-schema schema instance.`);let o={schema:n.schema},i=k(r).toLowerCase();return o.mode=Di(n,{defaultMode:i||
1056
- "patch",context:`${e}.mode`}),Object.freeze(o)}function Hr(t,e,{context:r="schema definition",defaultMode:n=""}={}){let o=Fe(t,{context:r,defaultMode:n});return o?o.schema[o.
1057
- mode](e):null}var Zu=me({cursor:{type:"id",required:!1},limit:{type:"number",required:!1,min:1,unsigned:!0}}),el=Object.freeze({schema:Zu,
1058
- mode:"patch"});var Li=Object.freeze({type:"string",pattern:"^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d)?$",minLength:5}),tl=Object.freeze(
1059
- {...Li,nullable:!0});var zi="Schema validation failed.";function $i({message:t=zi,fieldErrors:e=null,fieldErrorCodes:r=null,errors:n=null,cause:o,
1060
- statusCode:i=null}={}){let s=new Error(t,o?{cause:o}:void 0);if(t===zi&&(s.messageCode="kernel.validation.schemaFailed",
1061
- s.messageParams={}),Number.isInteger(i)&&i>=400&&i<=599&&(s.statusCode=i),R(e)){let a=R(r)&&Object.keys(r).length>0?r:null;
1039
+ default",code:"kernel.validation.field.notEmpty"}}),Ku=Object.freeze({code:"kernel.validation.invalid",message:"Invalid \
1040
+ value."}),Yu=Object.freeze(["create","replace","patch","toJsonSchema"]);function Lt(t){return!!t&&typeof t=="object"&&Yu.
1041
+ every(e=>typeof t[e]=="function")}function Li(t=null,{defaultMode:e="create",context:r="schema definition.mode"}={}){let n=Z(t),o=N(e).toLowerCase()||"cre\
1042
+ ate",i=Object.prototype.hasOwnProperty.call(n,"mode")?N(n.mode).toLowerCase():"";if(!i)return o;if(!Xu.has(i))throw new TypeError(
1043
+ `${r} must be one of: create, replace, patch.`);return i}function zi(t=null,e=""){let r=N(e);if(!r)return{};let n=Z(t);return Lt(n.schema)?Z(n.schema.getFieldMessages(r)):{}}function Qu(t=null,e=""){
1044
+ let r=N(e).split(".").filter(Boolean);return r.length<2?{}:(r.pop(),zi(t,r.join(".")))}function Mi(t,e){let r=e?t[e]:void 0;
1045
+ if(typeof r=="string"){let i=N(r);return i?{message:i}:null}if(!I(r))return null;let n=N(r.message);if(!n)return null;let o=N(
1046
+ r.code);return o?{message:n,code:o,params:Z(r.params)}:{message:n}}function Zu(t,e,r=null){let n=N(e?.code).toUpperCase(),
1047
+ o=Ju[n]||{},i=Z(e?.params),s=zi(r,t),a=n==="FIELD_NOT_ALLOWED"&&Object.keys(s).length<1?Qu(r,t):s,c=Mi(a,o.messageKey)||
1048
+ Mi(a,"default");if(c)return c.code?{message:c.message,code:c.code,params:{...i,...c.params}}:{message:c.message};let u=N(
1049
+ e?.message);if(u)return o.code?{message:u,code:o.code,params:i}:{message:u};let l=N(e?.code);return l?{message:l}:{...Ku,
1050
+ params:{}}}function Hr(t={},e=null){let r=Z(t),n={},o={};for(let[i,s]of Object.entries(r)){let a=N(i);if(!a)continue;if(typeof s==
1051
+ "string"){n[a]=s;continue}let{message:c,code:u,params:l}=Zu(a,s,e);n[a]=c,u&&(o[a]={code:u,params:l})}return{fieldErrors:n,
1052
+ fieldErrorCodes:o}}function el(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&(Object.prototype.hasOwnProperty.call(t,"schema")||Object.
1053
+ prototype.hasOwnProperty.call(t,"mode"))}function qe(t,{context:e="schema definition",defaultMode:r=""}={}){if(t==null)return null;
1054
+ if(!el(t))throw new TypeError(`${e} must be a schema definition object.`);let n=Z(t);if(!Object.prototype.hasOwnProperty.
1055
+ call(n,"schema"))throw new TypeError(`${e}.schema is required.`);if(!Lt(n.schema))throw new TypeError(`${e}.schema must \
1056
+ be a json-rest-schema schema instance.`);let o={schema:n.schema},i=N(r).toLowerCase();return o.mode=Li(n,{defaultMode:i||
1057
+ "patch",context:`${e}.mode`}),Object.freeze(o)}function Gr(t,e,{context:r="schema definition",defaultMode:n=""}={}){let o=qe(t,{context:r,defaultMode:n});return o?o.schema[o.
1058
+ mode](e):null}var tl=pe({cursor:{type:"id",required:!1},limit:{type:"number",required:!1,min:1,unsigned:!0}}),rl=Object.freeze({schema:tl,
1059
+ mode:"patch"});var $i=Object.freeze({type:"string",pattern:"^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d)?$",minLength:5}),nl=Object.freeze(
1060
+ {...$i,nullable:!0});var Ui="Schema validation failed.";function Vi({message:t=Ui,fieldErrors:e=null,fieldErrorCodes:r=null,errors:n=null,cause:o,
1061
+ statusCode:i=null}={}){let s=new Error(t,o?{cause:o}:void 0);if(t===Ui&&(s.messageCode="kernel.validation.schemaFailed",
1062
+ s.messageParams={}),Number.isInteger(i)&&i>=400&&i<=599&&(s.statusCode=i),I(e)){let a=I(r)&&Object.keys(r).length>0?r:null;
1062
1063
  s.fieldErrors=e,a&&(s.fieldErrorCodes=a),s.details={...s.details||{},fieldErrors:e,...a?{fieldErrorCodes:a}:{}}}else n!=
1063
- null&&(s.details={...s.details||{},errors:n});return s}function rt(t,e,{phase:r="input",context:n="schema definition",statusCode:o=null}={}){
1064
- if(t==null)return e;let i=Hr(t,e,{defaultMode:r==="output"?"replace":"patch",context:n}),{fieldErrors:s,fieldErrorCodes:a}=qr(
1065
- i.errors,t);if(Object.keys(s).length>0)throw $i({fieldErrors:s,fieldErrorCodes:a,statusCode:o});return i.validatedObject??
1066
- e}var lh=new Map([{keyword:"required",code:"kernel.validation.required"},{keyword:"type",code:"kernel.validation.type"},{keyword:"\
1064
+ null&&(s.details={...s.details||{},errors:n});return s}function nt(t,e,{phase:r="input",context:n="schema definition",statusCode:o=null}={}){
1065
+ if(t==null)return e;let i=Gr(t,e,{defaultMode:r==="output"?"replace":"patch",context:n}),{fieldErrors:s,fieldErrorCodes:a}=Hr(
1066
+ i.errors,t);if(Object.keys(s).length>0)throw Vi({fieldErrors:s,fieldErrorCodes:a,statusCode:o});return i.validatedObject??
1067
+ e}var fh=new Map([{keyword:"required",code:"kernel.validation.required"},{keyword:"type",code:"kernel.validation.type"},{keyword:"\
1067
1068
  minLength",code:"kernel.validation.minLength"},{keyword:"maxLength",code:"kernel.validation.maxLength"},{keyword:"minimu\
1068
1069
  m",code:"kernel.validation.minimum"},{keyword:"maximum",code:"kernel.validation.maximum"},{keyword:"exclusiveMinimum",code:"\
1069
1070
  kernel.validation.exclusiveMinimum"},{keyword:"exclusiveMaximum",code:"kernel.validation.exclusiveMaximum"},{keyword:"mu\
@@ -1075,198 +1076,198 @@ additionalItems",code:"kernel.validation.additionalItems"},{keyword:"uniqueItems
1075
1076
  perties"},{keyword:"additionalProperties",code:"kernel.validation.additionalProperties"},{keyword:"propertyNames",code:"\
1076
1077
  kernel.validation.propertyNames"},{keyword:"oneOf",code:"kernel.validation.oneOf"},{keyword:"anyOf",code:"kernel.validat\
1077
1078
  ion.anyOf"},{keyword:"not",code:"kernel.validation.not"},{keyword:"if",code:"kernel.validation.if"}].map(({keyword:t,code:e})=>[
1078
- t,e]));var Ui="^[1-9][0-9]*$",Gr=Te({type:"string",minLength:1,pattern:Ui}),rl=Te({...Gr,nullable:!0}),nl=Te({schema:me({recordId:{
1079
- ...Gr,required:!0,messages:{pattern:{code:"kernel.validation.recordIdInvalid",message:"Record id must be a canonical pos\
1080
- itive integer string."}}}}),mode:"patch"});function Ee(t){let e=Array.isArray(t)?t:[t],r=new Set;for(let n of e){let o=k(n);o&&r.add(o)}return[...r]}function Vi(t=[],e=""){
1081
- let r=k(e);if(!r)return!0;let n=Ee(t);if(n.includes("*")||n.includes(r))return!0;for(let o of n){if(!o.endsWith(".*"))continue;
1082
- let i=o.slice(0,-2);if(i&&r.startsWith(`${i}.`))return!0}return!1}function Wr(t,e,r){if(t==="all"){let n=e.find(o=>!Vi(r,
1083
- o));return n===void 0?null:{permission:n}}return e.some(n=>Vi(r,n))?null:{requiredPermissions:e}}var nt=/^[a-z][a-z0-9_.-]*$/u,sl=/^[A-Za-z_$][A-Za-z0-9_$]*$/u;function al(t){return String(t||"").trim().toLowerCase()}
1084
- function Jr(t,e){let r=al(t);if(!nt.test(r))throw new TypeError(`${e} must match ${nt.toString()}.`);return r}function Lt(t,e){
1085
- if(t==null)return Object.freeze({});if(!R(t))throw new TypeError(`${e} must be an object mapping local names to capabili\
1086
- ty ids.`);let r={},n=new Set;for(let[o,i]of Object.entries(t)){let s=String(o||"").trim();if(!sl.test(s))throw new TypeError(
1087
- `${e} local name "${s}" must be a JavaScript identifier.`);let a=Jr(i,`${e}.${s}`);if(n.has(a))throw new TypeError(`${e}\
1088
- declares capability "${a}" more than once.`);n.add(a),r[s]=a}return Object.freeze(r)}function cl(t,e,r){if(t==null)return Object.
1089
- freeze({});if(!R(t))throw new TypeError(`${r}.hints must be an object mapping required capability ids to what to registe\
1090
- r.`);let n=new Set(Object.values(e)),o={};for(let[i,s]of Object.entries(t)){let a=Jr(i,`${r}.hints key`);if(!n.has(a))throw new TypeError(
1079
+ t,e]));var Bi="^[1-9][0-9]*$",Wr=Ie({type:"string",minLength:1,pattern:Bi}),ol=Ie({...Wr,nullable:!0}),il=Ie({schema:pe({recordId:{
1080
+ ...Wr,required:!0,messages:{pattern:{code:"kernel.validation.recordIdInvalid",message:"Record id must be a canonical pos\
1081
+ itive integer string."}}}}),mode:"patch"});function Ee(t){let e=Array.isArray(t)?t:[t],r=new Set;for(let n of e){let o=N(n);o&&r.add(o)}return[...r]}function Fi(t=[],e=""){
1082
+ let r=N(e);if(!r)return!0;let n=Ee(t);if(n.includes("*")||n.includes(r))return!0;for(let o of n){if(!o.endsWith(".*"))continue;
1083
+ let i=o.slice(0,-2);if(i&&r.startsWith(`${i}.`))return!0}return!1}function Xr(t,e,r){if(t==="all"){let n=e.find(o=>!Fi(r,
1084
+ o));return n===void 0?null:{permission:n}}return e.some(n=>Fi(r,n))?null:{requiredPermissions:e}}var ot=/^[a-z][a-z0-9_.-]*$/u,cl=/^[A-Za-z_$][A-Za-z0-9_$]*$/u;function ul(t){return String(t||"").trim().toLowerCase()}
1085
+ function Kr(t,e){let r=ul(t);if(!ot.test(r))throw new TypeError(`${e} must match ${ot.toString()}.`);return r}function zt(t,e){
1086
+ if(t==null)return Object.freeze({});if(!I(t))throw new TypeError(`${e} must be an object mapping local names to capabili\
1087
+ ty ids.`);let r={},n=new Set;for(let[o,i]of Object.entries(t)){let s=String(o||"").trim();if(!cl.test(s))throw new TypeError(
1088
+ `${e} local name "${s}" must be a JavaScript identifier.`);let a=Kr(i,`${e}.${s}`);if(n.has(a))throw new TypeError(`${e}\
1089
+ declares capability "${a}" more than once.`);n.add(a),r[s]=a}return Object.freeze(r)}function ll(t,e,r){if(t==null)return Object.
1090
+ freeze({});if(!I(t))throw new TypeError(`${r}.hints must be an object mapping required capability ids to what to registe\
1091
+ r.`);let n=new Set(Object.values(e)),o={};for(let[i,s]of Object.entries(t)){let a=Kr(i,`${r}.hints key`);if(!n.has(a))throw new TypeError(
1091
1092
  `${r}.hints names "${a}", which the provider does not require.`);if(typeof s!="string"||!s.trim())throw new TypeError(`${r}\
1092
- .hints["${a}"] must be the text that says what to register.`);o[a]=s.trim()}return Object.freeze(o)}function ul(t){let e=new Map;
1093
+ .hints["${a}"] must be the text that says what to register.`);o[a]=s.trim()}return Object.freeze(o)}function dl(t){let e=new Map;
1093
1094
  for(let[r,n]of Object.entries(t))for(let o of Object.keys(n)){if(e.has(o))throw new TypeError(`Provider local name "${o}\
1094
- " is declared by both ${e.get(o)} and ${r}.`);e.set(o,r)}}function ll(t,e,r){for(let n of Object.values(e))for(let[o,i]of Object.
1095
+ " is declared by both ${e.get(o)} and ${r}.`);e.set(o,r)}}function fl(t,e,r){for(let n of Object.values(e))for(let[o,i]of Object.
1095
1096
  entries(r))if(Object.values(i).includes(n))throw new TypeError(o==="provides"?`Provider "${t}" cannot late-require capab\
1096
- ility "${n}" that it provides.`:`Provider "${t}" names capability "${n}" under both late and ${o}.`)}function Xr(t,e){if(t==
1097
- null)return null;if(typeof t!="function")throw new TypeError(`${e} must be a function when provided.`);return t}function qe({
1098
- id:t,requires:e={},optional:r={},late:n={},provides:o={},hints:i={},setup:s,boot:a=null,shutdown:c=null}={}){let u=Jr(t,
1099
- "Provider id"),l=Lt(e,`${u}.requires`),p=Lt(r,`${u}.optional`),d=Lt(n,`${u}.late`),h=Lt(o,`${u}.provides`);ul({requires:l,
1100
- optional:p,late:d,provides:h}),ll(u,d,{provides:h,requires:l,optional:p});let _=Xr(s,`${u}.setup`);if(!_)throw new TypeError(
1101
- `${u}.setup is required.`);return Object.freeze({id:u,requires:l,optional:p,late:d,provides:h,hints:cl(i,{...l,...d},u),
1102
- setup:_,boot:Xr(a,`${u}.boot`),shutdown:Xr(c,`${u}.shutdown`)})}var Kr=new WeakSet;function Bi(t,e){return t===null||typeof t!="object"||Kr.has(t)||e.has(t)?!0:Object.isFrozen(t)?(e.add(
1103
- t),Reflect.ownKeys(t).every(r=>{let n=Object.getOwnPropertyDescriptor(t,r);return!Object.hasOwn(n,"value")||Bi(n.value,e)})):
1104
- !1}function Fi(t){if(t===null||typeof t!="object"||Kr.has(t))return!0;if(!Object.isFrozen(t))return!1;let e=new Set;if(!Bi(
1105
- t,e))return!1;for(let r of e)Kr.add(r);return!0}var dl=Object.freeze(["query","command","stream"]),Gi=Object.freeze(["none","authenticated","all","any"]),fl=new Set(dl),
1106
- pl=new Set(Gi),Wi="create",Xi=Object.freeze({required:!0,defaultMode:Wi,refuseOneOf:!0}),X=class extends Error{constructor(e,r,n={}){
1097
+ ility "${n}" that it provides.`:`Provider "${t}" names capability "${n}" under both late and ${o}.`)}function Jr(t,e){if(t==
1098
+ null)return null;if(typeof t!="function")throw new TypeError(`${e} must be a function when provided.`);return t}function He({
1099
+ id:t,requires:e={},optional:r={},late:n={},provides:o={},hints:i={},setup:s,boot:a=null,shutdown:c=null}={}){let u=Kr(t,
1100
+ "Provider id"),l=zt(e,`${u}.requires`),m=zt(r,`${u}.optional`),d=zt(n,`${u}.late`),_=zt(o,`${u}.provides`);dl({requires:l,
1101
+ optional:m,late:d,provides:_}),fl(u,d,{provides:_,requires:l,optional:m});let g=Jr(s,`${u}.setup`);if(!g)throw new TypeError(
1102
+ `${u}.setup is required.`);return Object.freeze({id:u,requires:l,optional:m,late:d,provides:_,hints:ll(i,{...l,...d},u),
1103
+ setup:g,boot:Jr(a,`${u}.boot`),shutdown:Jr(c,`${u}.shutdown`)})}var Yr=new WeakSet;function qi(t,e){return t===null||typeof t!="object"||Yr.has(t)||e.has(t)?!0:Object.isFrozen(t)?(e.add(
1104
+ t),Reflect.ownKeys(t).every(r=>{let n=Object.getOwnPropertyDescriptor(t,r);return!Object.hasOwn(n,"value")||qi(n.value,e)})):
1105
+ !1}function Hi(t){if(t===null||typeof t!="object"||Yr.has(t))return!0;if(!Object.isFrozen(t))return!1;let e=new Set;if(!qi(
1106
+ t,e))return!1;for(let r of e)Yr.add(r);return!0}var pl=Object.freeze(["query","command","stream"]),Xi=Object.freeze(["none","authenticated","all","any"]),ml=new Set(pl),
1107
+ hl=new Set(Xi),Ji="create",Ki=Object.freeze({required:!0,defaultMode:Ji,refuseOneOf:!0}),X=class extends Error{constructor(e,r,n={}){
1107
1108
  super(r),this.name="ActionRuntimeError",this.status=Number(e)||500,this.statusCode=this.status,this.code=String(n.code||
1108
1109
  "ACTION_RUNTIME_ERROR"),this.params=n.params&&typeof n.params=="object"?{...n.params}:{},this.details=n.details,this.headers=
1109
- n.headers||{},this.cause=n.cause}};function Ji(t,{context:e="domain"}={}){let r=k(t).toLowerCase();if(!r)throw new Error(
1110
- `${e} is required.`);if(!nt.test(r))throw new Error(`${e} must match ${nt.toString()} (lowercase letters, digits, _, -, \
1111
- .).`);return r}function qi(t,e){let r=Array.isArray(t)?t:[],n=Array.from(new Set(r.map(o=>k(o).toLowerCase()).filter(Boolean)));
1112
- if(n.length<1)throw new Error(`Action definition ${e} must include at least one value.`);return n}function Yr(t){return t&&
1113
- typeof t.getFieldDefinitions=="function"?t.getFieldDefinitions():null}var Hi=new WeakSet;function Qr(t,e,r=""){for(let[n,
1114
- o]of Object.entries(t))Zr(o,e,r?`${r}.${n}`:n)}function Zr(t,e,r){let n=Yr(t);if(n){Qr(n,e,r);return}if(R(t)){if(Object.
1110
+ n.headers||{},this.cause=n.cause}};function Yi(t,{context:e="domain"}={}){let r=N(t).toLowerCase();if(!r)throw new Error(
1111
+ `${e} is required.`);if(!ot.test(r))throw new Error(`${e} must match ${ot.toString()} (lowercase letters, digits, _, -, \
1112
+ .).`);return r}function Gi(t,e){let r=Array.isArray(t)?t:[],n=Array.from(new Set(r.map(o=>N(o).toLowerCase()).filter(Boolean)));
1113
+ if(n.length<1)throw new Error(`Action definition ${e} must include at least one value.`);return n}function Qr(t){return t&&
1114
+ typeof t.getFieldDefinitions=="function"?t.getFieldDefinitions():null}var Wi=new WeakSet;function Zr(t,e,r=""){for(let[n,
1115
+ o]of Object.entries(t))en(o,e,r?`${r}.${n}`:n)}function en(t,e,r){let n=Qr(t);if(n){Zr(n,e,r);return}if(I(t)){if(Object.
1115
1116
  hasOwn(t,"oneOf"))throw new Error(`Action definition ${e} field "${r}" declares oneOf, which does not restrict its value\
1116
- ; list the allowed values with enum.`);Qr(Yr(t.schema)||{},e,r),Object.hasOwn(t,"items")&&Zr(t.items,e,`${r}[]`),Object.
1117
- hasOwn(t,"values")&&Zr(t.values,e,`${r}.*`)}}function en(t,e,{required:r=!1,defaultMode:n="",refuseOneOf:o=!1}={}){if(t==
1117
+ ; list the allowed values with enum.`);Zr(Qr(t.schema)||{},e,r),Object.hasOwn(t,"items")&&en(t.items,e,`${r}[]`),Object.
1118
+ hasOwn(t,"values")&&en(t.values,e,`${r}.*`)}}function tn(t,e,{required:r=!1,defaultMode:n="",refuseOneOf:o=!1}={}){if(t==
1118
1119
  null){if(!r)return null;throw new Error(`Action definition ${e} is required.`)}if(Array.isArray(t))throw new Error(`Acti\
1119
- on definition ${e} must be a single schema definition.`);if(!R(t))throw new Error(`Action definition ${e} must be a json\
1120
- -rest-schema schema definition.`);let i;try{i=Fe(t,{context:`Action definition ${e}`,defaultMode:n})}catch(s){throw new Error(
1121
- s?.message||`Action definition ${e} is invalid.`)}return o&&!Hi.has(i.schema)&&(Qr(Yr(i.schema)||{},e),Fi(i.schema)&&Hi.
1122
- add(i.schema)),i}function ml(t,e){if(t==null)return Object.freeze({require:"none",permissions:Object.freeze([]),message:"",
1123
- code:""});if(!R(t))throw new Error(`Action definition "${e}" permission must be an object when provided.`);let r=k(t.require||
1124
- "authenticated").toLowerCase();if(!pl.has(r))throw new Error(`Action definition "${e}" permission.require must be one of\
1125
- : ${Gi.join(", ")}.`);return Object.freeze({require:r,permissions:Object.freeze(Ee(t.permissions)),message:k(t.message),
1126
- code:k(t.code)})}function hl(t){if(t==null)return Object.freeze({});if(!R(t))throw new Error("Action definition extensio\
1127
- ns must be an object when provided.");return Object.freeze({...t})}function yl(t,e){if(t==null)return Object.freeze([]);
1120
+ on definition ${e} must be a single schema definition.`);if(!I(t))throw new Error(`Action definition ${e} must be a json\
1121
+ -rest-schema schema definition.`);let i;try{i=qe(t,{context:`Action definition ${e}`,defaultMode:n})}catch(s){throw new Error(
1122
+ s?.message||`Action definition ${e} is invalid.`)}return o&&!Wi.has(i.schema)&&(Zr(Qr(i.schema)||{},e),Hi(i.schema)&&Wi.
1123
+ add(i.schema)),i}function yl(t,e){if(t==null)return Object.freeze({require:"none",permissions:Object.freeze([]),message:"",
1124
+ code:""});if(!I(t))throw new Error(`Action definition "${e}" permission must be an object when provided.`);let r=N(t.require||
1125
+ "authenticated").toLowerCase();if(!hl.has(r))throw new Error(`Action definition "${e}" permission.require must be one of\
1126
+ : ${Xi.join(", ")}.`);return Object.freeze({require:r,permissions:Object.freeze(Ee(t.permissions)),message:N(t.message),
1127
+ code:N(t.code)})}function _l(t){if(t==null)return Object.freeze({});if(!I(t))throw new Error("Action definition extensio\
1128
+ ns must be an object when provided.");return Object.freeze({...t})}function gl(t,e){if(t==null)return Object.freeze([]);
1128
1129
  if(!Array.isArray(t))throw new Error(`Action definition "${e}" events must be an array.`);return Object.freeze(t.map((r,n)=>{
1129
- if(typeof r!="function")throw new Error(`Action definition "${e}" events[${n}] must be a function.`);return r}))}function _l(t,{
1130
- contributorId:e="",contributorDomain:r=""}={}){let n=t&&typeof t=="object"?t:{},o=k(n.id);if(!o)throw new Error("Action \
1131
- definition id is required.");let i=K(n.version,{fallback:1}),s=Ji(n.domain||r,{context:`Action definition "${o}" domain`}),
1132
- a=k(n.kind||"command").toLowerCase();if(!fl.has(a))throw new Error(`Action definition "${o}" has unsupported kind "${a}"\
1133
- .`);let c=qi(n.channels,"channels"),u=qi(n.surfaces,"surfaces");if(Object.hasOwn(n,"idempotency"))throw new Error(`Actio\
1130
+ if(typeof r!="function")throw new Error(`Action definition "${e}" events[${n}] must be a function.`);return r}))}function El(t,{
1131
+ contributorId:e="",contributorDomain:r=""}={}){let n=t&&typeof t=="object"?t:{},o=N(n.id);if(!o)throw new Error("Action \
1132
+ definition id is required.");let i=Y(n.version,{fallback:1}),s=Yi(n.domain||r,{context:`Action definition "${o}" domain`}),
1133
+ a=N(n.kind||"command").toLowerCase();if(!ml.has(a))throw new Error(`Action definition "${o}" has unsupported kind "${a}"\
1134
+ .`);let c=Gi(n.channels,"channels"),u=Gi(n.surfaces,"surfaces");if(Object.hasOwn(n,"idempotency"))throw new Error(`Actio\
1134
1135
  n definition "${o}" declares idempotency. Action definitions no longer declare idempotency.`);if(typeof n.execute!="func\
1135
1136
  tion")throw new Error(`Action definition "${o}" execute handler is required.`);if(n.checkInput!=null&&typeof n.checkInput!=
1136
1137
  "function")throw new Error(`Action definition "${o}" checkInput must be a function when provided.`);return Object.freeze(
1137
- {id:o,version:i,domain:s,kind:a,channels:c,surfaces:u,input:en(n.input,"input",Xi),output:en(n.output,"output",{defaultMode:"\
1138
- replace"}),permission:ml(n.permission,o),extensions:hl(n.extensions),events:yl(n.events,o),checkInput:n.checkInput??null,
1139
- execute:n.execute,contributorId:k(e)})}function gl(t){let e=t&&typeof t=="object"?t:{},r=k(e.contributorId);if(!r)throw new Error(
1140
- "Action contributor contributorId is required.");let n=Ji(e.domain,{context:`Action contributor "${r}" domain`}),i=(Array.
1141
- isArray(e.actions)?e.actions:[]).map(s=>_l(s,{contributorId:r,contributorDomain:n}));return Object.freeze({contributorId:r,
1142
- domain:n,actions:Object.freeze(i)})}function El(t,e){let r=e.input(t);return r===t.input?t:Object.freeze({...t,input:en(
1143
- r,"input",Xi)})}function Ki(t,e){let{contributorId:r,domain:n,actions:o}=gl(t);return Object.freeze({contributorId:r,domain:n,
1144
- actions:Object.freeze(o.map(i=>Object.freeze({declared:i,definition:El(i,e)})))})}function tn(t,e){return`${k(t)}@v${K(e,
1145
- {fallback:1})}`}function Yi(t){return t?.requestMeta?.request||null}function Qi(t,e){let r=e||Yi(t);return t?.actor||r?.user||null}function rn(t,e){
1146
- return ct(Qi(t,e)?.id)}var Zh=Object.freeze({schema:me({}),mode:"replace"});function Zi(t){let e=t.fieldErrorCodes||t.details?.fieldErrorCodes;return{fieldErrors:t.fieldErrors||t.details?.fieldErrors,
1147
- ...R(e)?{fieldErrorCodes:e}:{}}}function nn({details:t,cause:e}){return new X(400,"Validation failed.",{code:"ACTION_VAL\
1148
- IDATION_FAILED",details:t,cause:e})}function ts(t,e){let r=se(e.channel);if(!r||!t.channels.includes(r))throw new X(403,
1149
- "Forbidden.",{code:"ACTION_CHANNEL_FORBIDDEN",details:{actionId:t.id,channel:r}})}function rs(t,e){let r=se(e.surface),n=t.
1138
+ {id:o,version:i,domain:s,kind:a,channels:c,surfaces:u,input:tn(n.input,"input",Ki),output:tn(n.output,"output",{defaultMode:"\
1139
+ replace"}),permission:yl(n.permission,o),extensions:_l(n.extensions),events:gl(n.events,o),checkInput:n.checkInput??null,
1140
+ execute:n.execute,contributorId:N(e)})}function wl(t){let e=t&&typeof t=="object"?t:{},r=N(e.contributorId);if(!r)throw new Error(
1141
+ "Action contributor contributorId is required.");let n=Yi(e.domain,{context:`Action contributor "${r}" domain`}),i=(Array.
1142
+ isArray(e.actions)?e.actions:[]).map(s=>El(s,{contributorId:r,contributorDomain:n}));return Object.freeze({contributorId:r,
1143
+ domain:n,actions:Object.freeze(i)})}function Sl(t,e){let r=e.input(t);return r===t.input?t:Object.freeze({...t,input:tn(
1144
+ r,"input",Ki)})}function Qi(t,e){let{contributorId:r,domain:n,actions:o}=wl(t);return Object.freeze({contributorId:r,domain:n,
1145
+ actions:Object.freeze(o.map(i=>Object.freeze({declared:i,definition:Sl(i,e)})))})}function rn(t,e){return`${N(t)}@v${Y(e,
1146
+ {fallback:1})}`}function Zi(t){return t?.requestMeta?.request||null}function es(t,e){let r=e||Zi(t);return t?.actor||r?.user||null}function nn(t,e){
1147
+ return ut(es(t,e)?.id)}var ty=Object.freeze({schema:pe({}),mode:"replace"});function ts(t){let e=t.fieldErrorCodes||t.details?.fieldErrorCodes;return{fieldErrors:t.fieldErrors||t.details?.fieldErrors,
1148
+ ...I(e)?{fieldErrorCodes:e}:{}}}function on({details:t,cause:e}){return new X(400,"Validation failed.",{code:"ACTION_VAL\
1149
+ IDATION_FAILED",details:t,cause:e})}function ns(t,e){let r=oe(e.channel);if(!r||!t.channels.includes(r))throw new X(403,
1150
+ "Forbidden.",{code:"ACTION_CHANNEL_FORBIDDEN",details:{actionId:t.id,channel:r}})}function os(t,e){let r=oe(e.surface),n=t.
1150
1151
  surfaces;if(!n.includes("*")&&(!r||!n.includes(r)))throw new X(403,"Forbidden.",{code:"ACTION_SURFACE_FORBIDDEN",details:{
1151
- actionId:t.id,surface:r}})}function ns(t,e){let{permission:r}=t,n=r.require;if(n==="none")return;if(rn(e)==null)throw new X(
1152
+ actionId:t.id,surface:r}})}function is(t,e){let{permission:r}=t,n=r.require;if(n==="none")return;if(nn(e)==null)throw new X(
1152
1153
  401,r.message||"Authentication required.",{code:r.code||"ACTION_AUTHENTICATION_REQUIRED",details:{actionId:t.id}});if(n===
1153
- "authenticated")return;let i=r.permissions;if(i.length<1)return;let s=Wr(n,i,Ee(e.permissions));if(s)throw new X(403,r.message||
1154
- "Forbidden.",{code:r.code||"ACTION_PERMISSION_DENIED",details:{actionId:t.id,...s}})}function es(t){return R(t?.fieldErrors)||
1155
- R(t?.details?.fieldErrors)}async function os(t,e){let r;try{r=rt(t.input,e,{phase:"input",context:`Action ${t.id} input`})}catch(n){
1156
- throw es(n)?nn({details:Zi(n),cause:n}):n?.code==="ACTION_VALIDATION_FAILED"?n:nn({details:{error:String(n?.message||"In\
1157
- valid input.")},cause:n})}if(t.checkInput)try{await t.checkInput(r)}catch(n){throw es(n)?nn({details:Zi(n),cause:n}):n}return r}
1158
- async function is(t,e){if(!t.output)return e;try{return rt(t.output,e,{phase:"output",context:`Action ${t.id} output`})}catch(r){
1159
- throw new Error("Action output validation failed.",{cause:r})}}var wl=Object.freeze(["requestId","commandId","ip","userAgent"]);function ss(t={}){let e=t&&typeof t=="object"?t:{},r={...e,
1160
- request:e.request||null};for(let n of wl)r[n]=k(e[n]);return r}function Sl(t){return R(t)?{...t}:null}function bl(t){let e=Sl(t);return e?(e.id==null&&(e.id=null),e):null}function xl(t){
1161
- let e=t&&typeof t=="object"?t:{};return{now:e.now instanceof Date?e.now:new Date,timezone:k(e.timezone),locale:k(e.locale)}}
1162
- var Ol=new Set(["actor","permissions","surface","channel","requestMeta","timeMeta"]);function Al(t={}){let e={...t};for(let r of Ol)
1163
- delete e[r];return e}var vl=Symbol("jskit.actions.unloggedExecution");function on(t){return!(t&&typeof t=="object"&&t[vl]===!0)}function Cl(t){return se(t)||"internal"}function zt(t={}){let e=t&&
1164
- typeof t=="object"?t:{},r=Al(e);return Object.freeze({...r,actor:bl(e.actor),permissions:Ee(e.permissions),surface:se(e.
1165
- surface),channel:Cl(e.channel),requestMeta:ss(e.requestMeta),timeMeta:xl(e.timeMeta)})}async function Tl(t,e,r){for(let n of e){let o=await n(r),i=Array.isArray(o)?o:[o];for(let s of i)s!=null&&await t.publish(
1166
- s)}}function as(t,{definition:e,context:r,outcome:n,startedAt:o,errorCode:i=null}){on(r)&&t.debug({action:e.id,version:e.
1154
+ "authenticated")return;let i=r.permissions;if(i.length<1)return;let s=Xr(n,i,Ee(e.permissions));if(s)throw new X(403,r.message||
1155
+ "Forbidden.",{code:r.code||"ACTION_PERMISSION_DENIED",details:{actionId:t.id,...s}})}function rs(t){return I(t?.fieldErrors)||
1156
+ I(t?.details?.fieldErrors)}async function ss(t,e){let r;try{r=nt(t.input,e,{phase:"input",context:`Action ${t.id} input`})}catch(n){
1157
+ throw rs(n)?on({details:ts(n),cause:n}):n?.code==="ACTION_VALIDATION_FAILED"?n:on({details:{error:String(n?.message||"In\
1158
+ valid input.")},cause:n})}if(t.checkInput)try{await t.checkInput(r)}catch(n){throw rs(n)?on({details:ts(n),cause:n}):n}return r}
1159
+ async function as(t,e){if(!t.output)return e;try{return nt(t.output,e,{phase:"output",context:`Action ${t.id} output`})}catch(r){
1160
+ throw new Error("Action output validation failed.",{cause:r})}}var bl=Object.freeze(["requestId","commandId","ip","userAgent"]);function cs(t={}){let e=t&&typeof t=="object"?t:{},r={...e,
1161
+ request:e.request||null};for(let n of bl)r[n]=N(e[n]);return r}function xl(t){return I(t)?{...t}:null}function Ol(t){let e=xl(t);return e?(e.id==null&&(e.id=null),e):null}function Al(t){
1162
+ let e=t&&typeof t=="object"?t:{};return{now:e.now instanceof Date?e.now:new Date,timezone:N(e.timezone),locale:N(e.locale)}}
1163
+ var vl=new Set(["actor","permissions","surface","channel","requestMeta","timeMeta"]);function Cl(t={}){let e={...t};for(let r of vl)
1164
+ delete e[r];return e}var Tl=Symbol("jskit.actions.unloggedExecution");function sn(t){return!(t&&typeof t=="object"&&t[Tl]===!0)}function Il(t){return oe(t)||"internal"}function $t(t={}){let e=t&&
1165
+ typeof t=="object"?t:{},r=Cl(e);return Object.freeze({...r,actor:Ol(e.actor),permissions:Ee(e.permissions),surface:oe(e.
1166
+ surface),channel:Il(e.channel),requestMeta:cs(e.requestMeta),timeMeta:Al(e.timeMeta)})}async function Pl(t,e,r){for(let n of e){let o=await n(r),i=Array.isArray(o)?o:[o];for(let s of i)s!=null&&await t.publish(
1167
+ s)}}function us(t,{definition:e,context:r,outcome:n,startedAt:o,errorCode:i=null}){sn(r)&&t.debug({action:e.id,version:e.
1167
1168
  version,channel:r.channel,surface:r.surface,requestId:r.requestMeta.requestId||null,durationMs:Date.now()-o,outcome:n,errorCode:i},
1168
- "action.execution")}async function sn({definition:t,declared:e,input:r,context:n,deps:o,events:i,logger:s,policy:a}){let c=zt(
1169
- n),u=Date.now();try{ts(t,c),rs(t,c),ns(t,c);let l=await os(t,r),p=await a.execute(Object.freeze({definition:e,input:l,context:c,
1170
- run:(h,_)=>t.execute(h,_,o)})),d=await is(t,p);return await Tl(i,t.events,Object.freeze({definition:t,input:l,result:d,context:c})),
1171
- as(s,{definition:t,context:c,outcome:"success",startedAt:u}),d}catch(l){throw as(s,{definition:t,context:c,outcome:"fail\
1172
- ure",startedAt:u,errorCode:String(l?.code||"ACTION_EXECUTION_FAILED").trim()}),l}}function cn(t,e){let r=new Map;for(let{definition:n}of e.actions){let o=tn(n.id,n.version),i=t.get(o)??r.get(o);if(i)throw new Error(
1169
+ "action.execution")}async function an({definition:t,declared:e,input:r,context:n,deps:o,events:i,logger:s,policy:a}){let c=$t(
1170
+ n),u=Date.now();try{ns(t,c),os(t,c),is(t,c);let l=await ss(t,r),m=await a.execute(Object.freeze({definition:e,input:l,context:c,
1171
+ run:(_,g)=>t.execute(_,g,o)})),d=await as(t,m);return await Pl(i,t.events,Object.freeze({definition:t,input:l,result:d,context:c})),
1172
+ us(s,{definition:t,context:c,outcome:"success",startedAt:u}),d}catch(l){throw us(s,{definition:t,context:c,outcome:"fail\
1173
+ ure",startedAt:u,errorCode:String(l?.code||"ACTION_EXECUTION_FAILED").trim()}),l}}function un(t,e){let r=new Map;for(let{definition:n}of e.actions){let o=rn(n.id,n.version),i=t.get(o)??r.get(o);if(i)throw new Error(
1173
1174
  `Action definition "${o}" is duplicated between contributors "${i.contributorId}" and "${e.contributorId}".`);r.set(o,n)}
1174
- return r}function Il(t){let e=[],r=new Map,n=new Map,o=new Map;for(let i of t){for(let[s,a]of cn(r,i))r.set(s,a);for(let{
1175
+ return r}function Rl(t){let e=[],r=new Map,n=new Map,o=new Map;for(let i of t){for(let[s,a]of un(r,i))r.set(s,a);for(let{
1175
1176
  definition:s,declared:a}of i.actions)o.set(s,a),e.push(s),n.has(s.id)||n.set(s.id,[]),n.get(s.id).push(s)}for(let i of n.
1176
1177
  values())i.sort((s,a)=>a.version-s.version);return{definitions:Object.freeze(e),byVersionKey:r,byActionId:n,declaredByDefinition:o}}
1177
- function Pl(t){let e=Number(t);if(!Number.isInteger(e)||e<1)throw new X(400,"Validation failed.",{code:"ACTION_VERSION_I\
1178
+ function Nl(t){let e=Number(t);if(!Number.isInteger(e)||e<1)throw new X(400,"Validation failed.",{code:"ACTION_VERSION_I\
1178
1179
  NVALID",details:{fieldErrors:{version:"version must be an integer >= 1."},fieldErrorCodes:{version:{code:"kernel.action.\
1179
- versionInvalid",params:{}}}}});return e}function an(t,e,r){let n=String(e||"").trim();if(!n)throw new X(400,"Validation \
1180
+ versionInvalid",params:{}}}}});return e}function cn(t,e,r){let n=String(e||"").trim();if(!n)throw new X(400,"Validation \
1180
1181
  failed.",{code:"ACTION_ID_REQUIRED",details:{fieldErrors:{actionId:"actionId is required."},fieldErrorCodes:{actionId:{code:"\
1181
1182
  kernel.action.idRequired",params:{}}}}});if(r==null){let a=t.byActionId.get(n)||[];if(a.length<1)throw new X(404,"Not fo\
1182
- und.",{code:"ACTION_NOT_FOUND",details:{actionId:n}});return a[0]}let o=Pl(r),i=tn(n,o),s=t.byVersionKey.get(i);if(!s)throw new X(
1183
- 404,"Not found.",{code:"ACTION_NOT_FOUND",details:{actionId:n,version:o}});return s}function cs({contributors:t,events:e,
1184
- logger:r,policy:n}){let o=Il(t);async function i({actionId:u,version:l,input:p,context:d,deps:h}){let _=an(o,u,l);return sn(
1185
- {definition:_,declared:o.declaredByDefinition.get(_),input:p,context:d,deps:h,events:e,logger:r,policy:n})}async function s({
1186
- actionId:u,version:l,input:p,context:d,deps:h}){let _=an(o,u,l);if(_.kind!=="stream")throw new X(400,"Validation failed.",
1187
- {code:"ACTION_STREAM_KIND_REQUIRED",details:{actionId:_.id,version:_.version,kind:_.kind}});return sn({definition:_,declared:o.
1188
- declaredByDefinition.get(_),input:p,context:d,deps:h,events:e,logger:r,policy:n})}function a(){return o.definitions.slice()}
1189
- function c(u,l=null){return an(o,u,l)}return Object.freeze({execute:i,executeStream:s,listDefinitions:a,getDefinition:c})}var $t=Object.freeze({input(t){return t.input},execute({input:t,context:e,run:r}){return r(t,e)}});function Rl(t){if(!R(t))throw new TypeError("Event listener must be an object.");let e=String(t.id||"").trim();if(!e)throw new TypeError(
1183
+ und.",{code:"ACTION_NOT_FOUND",details:{actionId:n}});return a[0]}let o=Nl(r),i=rn(n,o),s=t.byVersionKey.get(i);if(!s)throw new X(
1184
+ 404,"Not found.",{code:"ACTION_NOT_FOUND",details:{actionId:n,version:o}});return s}function ls({contributors:t,events:e,
1185
+ logger:r,policy:n}){let o=Rl(t);async function i({actionId:u,version:l,input:m,context:d,deps:_}){let g=cn(o,u,l);return an(
1186
+ {definition:g,declared:o.declaredByDefinition.get(g),input:m,context:d,deps:_,events:e,logger:r,policy:n})}async function s({
1187
+ actionId:u,version:l,input:m,context:d,deps:_}){let g=cn(o,u,l);if(g.kind!=="stream")throw new X(400,"Validation failed.",
1188
+ {code:"ACTION_STREAM_KIND_REQUIRED",details:{actionId:g.id,version:g.version,kind:g.kind}});return an({definition:g,declared:o.
1189
+ declaredByDefinition.get(g),input:m,context:d,deps:_,events:e,logger:r,policy:n})}function a(){return o.definitions.slice()}
1190
+ function c(u,l=null){return cn(o,u,l)}return Object.freeze({execute:i,executeStream:s,listDefinitions:a,getDefinition:c})}var Ut=Object.freeze({input(t){return t.input},execute({input:t,context:e,run:r}){return r(t,e)}});function kl(t){if(!I(t))throw new TypeError("Event listener must be an object.");let e=String(t.id||"").trim();if(!e)throw new TypeError(
1190
1191
  "Event listener id is required.");if(typeof t.handle!="function")throw new TypeError(`Event listener "${e}" requires han\
1191
1192
  dle().`);if(t.matches!=null&&typeof t.matches!="function")throw new TypeError(`Event listener "${e}" matches must be a f\
1192
- unction when provided.`);return Object.freeze({id:e,handle:t.handle,matches:t.matches??null})}function Nl(t){if(!R(t))throw new TypeError(
1193
+ unction when provided.`);return Object.freeze({id:e,handle:t.handle,matches:t.matches??null})}function jl(t){if(!I(t))throw new TypeError(
1193
1194
  "Published event must be an object.");let e=String(t.type||"").trim();if(!e)throw new TypeError("Published event type is\
1194
- required.");return Object.freeze({...t,type:e})}function ot(){let t=[],e=new Set;function r(s){let a=Rl(s);if(e.has(a.id))
1195
- throw new Error(`Event listener "${a.id}" is duplicated.`);return e.add(a.id),t.push(a),i}async function n(s){let a=Nl(s);
1195
+ required.");return Object.freeze({...t,type:e})}function it(){let t=[],e=new Set;function r(s){let a=kl(s);if(e.has(a.id))
1196
+ throw new Error(`Event listener "${a.id}" is duplicated.`);return e.add(a.id),t.push(a),i}async function n(s){let a=jl(s);
1196
1197
  for(let c of t)c.matches&&c.matches(a)!==!0||await c.handle(a);return a}function o(){return Object.freeze({listenerIds:Object.
1197
- freeze(t.map(s=>s.id))})}let i=Object.freeze({register:r,publish:n,diagnostics:o});return i}var us=Object.freeze({debug(){},info(){},warn(){},error(){}});function kl(t){if(!R(t))throw new TypeError("Action catalogue registration must be an action contributor object.");return t}
1198
- function un({events:t=ot(),logger:e=us,policy:r=$t}={}){let n=[],o=[],i=new Set,s=new Map,a=null,c=!1;function u(A){if(c)
1199
- throw new Error("Action catalogue registration is closed after discovery or execution begins.");let v=Ki(kl(A),r);for(let[
1200
- b,L]of cn(s,v))s.set(b,L);return n.push(v),M}function l({id:A,contribute:v}={}){if(c)throw new Error("Action catalogue r\
1201
- egistration is closed after discovery or execution begins.");let b=String(A||"").trim();if(!b)throw new TypeError("Actio\
1202
- n context contributor id is required.");if(typeof v!="function")throw new TypeError(`Action context contributor "${b}" r\
1198
+ freeze(t.map(s=>s.id))})}let i=Object.freeze({register:r,publish:n,diagnostics:o});return i}var ds=Object.freeze({debug(){},info(){},warn(){},error(){}});function Dl(t){if(!I(t))throw new TypeError("Action catalogue registration must be an action contributor object.");return t}
1199
+ function ln({events:t=it(),logger:e=ds,policy:r=Ut}={}){let n=[],o=[],i=new Set,s=new Map,a=null,c=!1;function u(O){if(c)
1200
+ throw new Error("Action catalogue registration is closed after discovery or execution begins.");let A=Qi(Dl(O),r);for(let[
1201
+ b,M]of un(s,A))s.set(b,M);return n.push(A),D}function l({id:O,contribute:A}={}){if(c)throw new Error("Action catalogue r\
1202
+ egistration is closed after discovery or execution begins.");let b=String(O||"").trim();if(!b)throw new TypeError("Actio\
1203
+ n context contributor id is required.");if(typeof A!="function")throw new TypeError(`Action context contributor "${b}" r\
1203
1204
  equires contribute().`);if(i.has(b))throw new Error(`Action context contributor "${b}" is duplicated.`);return i.add(b),
1204
- o.push(Object.freeze({id:b,contribute:v})),M}function p(){return c=!0,a??=cs({contributors:n,events:t,logger:e,policy:r}),
1205
- a}function d(A,v){let b={...A};for(let[L,U]of Object.entries(R(v)?v:{}))L==="requestMeta"?b.requestMeta={...R(U)?U:{},...R(
1206
- b.requestMeta)?b.requestMeta:{}}:Object.hasOwn(b,L)||(b[L]=U);return b}async function h({definition:A,input:v,context:b}){
1207
- let L={...R(b)?b:{}};for(let U of o){let G=await U.contribute(Object.freeze({actionId:A?.id??null,version:A?.version??null,
1208
- definition:A,input:Object.freeze({...R(v)?v:{}}),context:Object.freeze({...L})}));L=d(L,G)}return Object.freeze(L)}function _({
1209
- actionId:A,version:v,input:b,context:L}){return h({definition:p().getDefinition(A,v),input:b,context:L})}async function E({
1210
- input:A,context:v}={}){return c=!0,zt(await h({definition:null,input:A,context:v}))}async function O(A,v={}){let b=v&&typeof v==
1211
- "object"?v:{},L=b.input&&typeof b.input=="object"?b.input:{},U=b.version==null?null:b.version,G=await _({actionId:b.actionId,
1212
- version:U,input:L,context:b.context});return p()[A]({actionId:b.actionId,version:U,input:L,context:G,deps:R(b.deps)?b.deps:
1213
- {}})}function N(A){return O("execute",A)}function D(A){return O("executeStream",A)}function I(){return p().listDefinitions()}
1214
- function C(A,v=null){return p().getDefinition(A,v)}let M=Object.freeze({register:u,registerContextContributor:l,execute:N,
1215
- executeStream:D,contextFor:E,listDefinitions:I,getDefinition:C});return M}var jl=qe({id:"runtime.actions",requires:{events:"runtime.events",logger:"runtime.logger"},optional:{policy:"runtime.act\
1216
- ions.policy"},provides:{actions:"runtime.actions"},setup({events:t,logger:e,policy:r}){return{actions:un({events:t,logger:e,
1217
- policy:r??$t})}}});var ls="public";var Ml="/api",ds=`${Ml}/bootstrap`;function ln(){let t=[],e=new Set,r=!1;function n({id:a,order:c=0,contribute:u}={}){if(r)throw new Error("Bootstrap regis\
1218
- tration is closed after the first payload is resolved.");let l=k(a);if(!l)throw new TypeError("Bootstrap contributor id \
1205
+ o.push(Object.freeze({id:b,contribute:A})),D}function m(){return c=!0,a??=ls({contributors:n,events:t,logger:e,policy:r}),
1206
+ a}function d(O,A){let b={...O};for(let[M,$]of Object.entries(I(A)?A:{}))M==="requestMeta"?b.requestMeta={...I($)?$:{},...I(
1207
+ b.requestMeta)?b.requestMeta:{}}:Object.hasOwn(b,M)||(b[M]=$);return b}async function _({definition:O,input:A,context:b}){
1208
+ let M={...I(b)?b:{}};for(let $ of o){let G=await $.contribute(Object.freeze({actionId:O?.id??null,version:O?.version??null,
1209
+ definition:O,input:Object.freeze({...I(A)?A:{}}),context:Object.freeze({...M})}));M=d(M,G)}return Object.freeze(M)}function g({
1210
+ actionId:O,version:A,input:b,context:M}){return _({definition:m().getDefinition(O,A),input:b,context:M})}async function E({
1211
+ input:O,context:A}={}){return c=!0,$t(await _({definition:null,input:O,context:A}))}async function x(O,A={}){let b=A&&typeof A==
1212
+ "object"?A:{},M=b.input&&typeof b.input=="object"?b.input:{},$=b.version==null?null:b.version,G=await g({actionId:b.actionId,
1213
+ version:$,input:M,context:b.context});return m()[O]({actionId:b.actionId,version:$,input:M,context:G,deps:I(b.deps)?b.deps:
1214
+ {}})}function R(O){return x("execute",O)}function k(O){return x("executeStream",O)}function C(){return m().listDefinitions()}
1215
+ function v(O,A=null){return m().getDefinition(O,A)}let D=Object.freeze({register:u,registerContextContributor:l,execute:R,
1216
+ executeStream:k,contextFor:E,listDefinitions:C,getDefinition:v});return D}var Ml=He({id:"runtime.actions",requires:{events:"runtime.events",logger:"runtime.logger"},optional:{policy:"runtime.act\
1217
+ ions.policy"},provides:{actions:"runtime.actions"},setup({events:t,logger:e,policy:r}){return{actions:ln({events:t,logger:e,
1218
+ policy:r??Ut})}}});var fs="public";var zl="/api",ps=`${zl}/bootstrap`;function dn(){let t=[],e=new Set,r=!1;function n({id:a,order:c=0,contribute:u}={}){if(r)throw new Error("Bootstrap regis\
1219
+ tration is closed after the first payload is resolved.");let l=N(a);if(!l)throw new TypeError("Bootstrap contributor id \
1219
1220
  is required.");if(typeof u!="function")throw new TypeError(`Bootstrap contributor "${l}" requires contribute().`);if(e.has(
1220
1221
  l))throw new Error(`Bootstrap contributor "${l}" is duplicated.`);return e.add(l),t.push(Object.freeze({id:l,order:Number.
1221
- isFinite(c)?Number(c):0,contribute:u})),s}async function o(a={}){r=!0;let c={},u=t.map((l,p)=>({entry:l,index:p})).sort(
1222
- (l,p)=>l.entry.order-p.entry.order||l.index-p.index).map(({entry:l})=>l);for(let l of u){let p=await l.contribute(Object.
1223
- freeze({...R(a)?a:{},payload:Object.freeze({...c})}));c={...c,...R(p)?p:{}}}return Object.freeze(c)}function i(){return Object.
1222
+ isFinite(c)?Number(c):0,contribute:u})),s}async function o(a={}){r=!0;let c={},u=t.map((l,m)=>({entry:l,index:m})).sort(
1223
+ (l,m)=>l.entry.order-m.entry.order||l.index-m.index).map(({entry:l})=>l);for(let l of u){let m=await l.contribute(Object.
1224
+ freeze({...I(a)?a:{},payload:Object.freeze({...c})}));c={...c,...I(m)?m:{}}}return Object.freeze(c)}function i(){return Object.
1224
1225
  freeze({sealed:r,contributorIds:Object.freeze(t.map(a=>a.id).sort())})}let s=Object.freeze({register:n,resolve:o,diagnostics:i});
1225
- return s}var Ll=qe({id:"runtime.bootstrap",requires:{http:"runtime.http"},provides:{bootstrap:"runtime.bootstrap"},setup({http:t}){
1226
- let e=ln();return t.router.register("GET",ds,{auth:ls,meta:{tags:["bootstrap"],summary:"Resolve app bootstrap payload"}},
1227
- async(r,n)=>{n.code(200).send(await e.resolve({request:r,reply:n,query:r.query||{}}))}),{bootstrap:e}}});var zl=qe({id:"runtime.events",provides:{events:"runtime.events"},setup(){return{events:ot()}}});var Ul=8,G_=Object.freeze({notOffered:"This assistant does not keep unsaved tool calls out of what it saves, so it is no\
1226
+ return s}var $l=He({id:"runtime.bootstrap",requires:{http:"runtime.http"},provides:{bootstrap:"runtime.bootstrap"},setup({http:t}){
1227
+ let e=dn();return t.router.register("GET",ps,{auth:fs,meta:{tags:["bootstrap"],summary:"Resolve app bootstrap payload"}},
1228
+ async(r,n)=>{n.code(200).send(await e.resolve({request:r,reply:n,query:r.query||{}}))}),{bootstrap:e}}});var Ul=He({id:"runtime.events",provides:{events:"runtime.events"},setup(){return{events:it()}}});var Bl=8,X_=Object.freeze({notOffered:"This assistant does not keep unsaved tool calls out of what it saves, so it is no\
1228
1229
  t offered here.",discoveryOnly:"Only the discovery tools are offered here, and an unsaved action is never discoverable.",
1229
- directLimit:`At most ${Ul} actions are offered directly beside action discovery.`});var fs=20,W_=32*1024,Vl=48*1024,dn=Object.freeze({search:"assistant_action_search",contract:"assistant_action_contract",
1230
- execute:"assistant_action_execute"}),fn=Object.freeze({type:"object",additionalProperties:!0}),Bl=Object.freeze({type:"o\
1230
+ directLimit:`At most ${Bl} actions are offered directly beside action discovery.`});var ms=20,J_=32*1024,Fl=48*1024,fn=Object.freeze({search:"assistant_action_search",contract:"assistant_action_contract",
1231
+ execute:"assistant_action_execute"}),pn=Object.freeze({type:"object",additionalProperties:!0}),ql=Object.freeze({type:"o\
1231
1232
  bject",additionalProperties:!1,properties:{query:{type:"string",maxLength:200,description:"Optional literal words or act\
1232
1233
  ion-id fragments; every word must match. Use short resource or operation terms such as list. Omit query to browse all av\
1233
1234
  ailable actions."},cursor:{type:"string",maxLength:1e3,description:"Opaque cursor returned by the previous search page."},
1234
- limit:{type:"integer",minimum:1,maximum:fs,description:"Maximum compact matches to return."}}}),Fl=Object.freeze({type:"\
1235
- object",additionalProperties:!1,required:["items","nextCursor","total"],properties:{items:{type:"array",maxItems:fs,items:{
1235
+ limit:{type:"integer",minimum:1,maximum:ms,description:"Maximum compact matches to return."}}}),Hl=Object.freeze({type:"\
1236
+ object",additionalProperties:!1,required:["items","nextCursor","total"],properties:{items:{type:"array",maxItems:ms,items:{
1236
1237
  type:"object",additionalProperties:!1,required:["actionId","version","kind","description"],properties:{actionId:{type:"s\
1237
1238
  tring"},version:{type:"integer",minimum:1},kind:{type:"string"},description:{type:"string"}}}},nextCursor:{anyOf:[{type:"\
1238
- string"},{type:"null"}]},total:{type:"integer",minimum:0}}}),ql=Object.freeze({type:"object",additionalProperties:!1,required:[
1239
- "actionId"],properties:{actionId:{type:"string",minLength:1,maxLength:300},version:{type:"integer",minimum:1}}}),Hl=Object.
1239
+ string"},{type:"null"}]},total:{type:"integer",minimum:0}}}),Gl=Object.freeze({type:"object",additionalProperties:!1,required:[
1240
+ "actionId"],properties:{actionId:{type:"string",minLength:1,maxLength:300},version:{type:"integer",minimum:1}}}),Wl=Object.
1240
1241
  freeze({type:"object",additionalProperties:!1,required:["actionId","version","kind","description","inputSchema","outputS\
1241
1242
  chema"],properties:{actionId:{type:"string"},version:{type:"integer",minimum:1},kind:{type:"string"},description:{type:"\
1242
- string"},inputSchema:fn,outputSchema:fn}}),Gl=Object.freeze({type:"object",additionalProperties:!1,required:["actionId",
1243
- "input"],properties:{actionId:{type:"string",minLength:1,maxLength:300},version:{type:"integer",minimum:1},input:fn}}),Wl=Object.
1243
+ string"},inputSchema:pn,outputSchema:pn}}),Xl=Object.freeze({type:"object",additionalProperties:!1,required:["actionId",
1244
+ "input"],properties:{actionId:{type:"string",minLength:1,maxLength:300},version:{type:"integer",minimum:1},input:pn}}),Jl=Object.
1244
1245
  freeze({type:"object",additionalProperties:!1,required:["actionId","version","result"],properties:{actionId:{type:"strin\
1245
- g"},version:{type:"integer",minimum:1},result:{}}}),X_=Object.freeze([Object.freeze({name:dn.search,description:"Discove\
1246
+ g"},version:{type:"integer",minimum:1},result:{}}}),K_=Object.freeze([Object.freeze({name:fn.search,description:"Discove\
1246
1247
  r application actions available to the current user and surface, including list, search, and query operations for multip\
1247
1248
  le records. Search before claiming a capability is unavailable. If terminology does not match, use broader terms or omit\
1248
- query to browse. Returns compact paged matches without schemas; follow nextCursor when more discovery is needed.",parameters:Bl,
1249
- outputSchema:Fl}),Object.freeze({name:dn.contract,description:"Load the exact input and output contract for one availabl\
1250
- e action before executing it.",parameters:ql,outputSchema:Hl}),Object.freeze({name:dn.execute,description:"Execute one a\
1251
- vailable action after loading its exact contract in this turn. The action result is returned in result.",parameters:Gl,outputSchema:Wl})]);var Q_=new URL("./../../../../@jskit-ai/assistant-core/src/server/conversation/commandWrapper.js",import.meta.url).href;var Cg=256*1024,Tg=Object.freeze({codex:Object.freeze({path:"/responses",name:"Responses API",urlHint:"Codex needs an Op\
1249
+ query to browse. Returns compact paged matches without schemas; follow nextCursor when more discovery is needed.",parameters:ql,
1250
+ outputSchema:Hl}),Object.freeze({name:fn.contract,description:"Load the exact input and output contract for one availabl\
1251
+ e action before executing it.",parameters:Gl,outputSchema:Wl}),Object.freeze({name:fn.execute,description:"Execute one a\
1252
+ vailable action after loading its exact contract in this turn. The action result is returned in result.",parameters:Xl,outputSchema:Jl})]);var eg=new URL("./../../../../@jskit-ai/assistant-core/src/server/conversation/commandWrapper.js",import.meta.url).href;var Ig=256*1024,Pg=Object.freeze({codex:Object.freeze({path:"/responses",name:"Responses API",urlHint:"Codex needs an Op\
1252
1253
  enAI Responses-compatible base URL, which usually ends in /v1.",body:t=>({model:t,input:"Reply with OK.",max_output_tokens:64,
1253
1254
  store:!1}),usable:t=>!!t?.id&&Array.isArray(t.output)&&["completed","incomplete"].includes(t.status)}),claude:Object.freeze(
1254
1255
  {path:"/v1/messages",name:"Anthropic Messages API",urlHint:"Claude Code needs an Anthropic-compatible base URL without /\
1255
1256
  v1.",body:t=>({model:t,max_tokens:64,messages:[{role:"user",content:"Reply with OK."}]}),usable:t=>!!t?.id&&t.type==="me\
1256
1257
  ssage"&&Array.isArray(t.content)}),opencode:Object.freeze({path:"/chat/completions",name:"Chat Completions API",urlHint:"\
1257
1258
  OpenCode needs an OpenAI-compatible base URL, which usually ends in /v1.",body:t=>({model:t,max_tokens:64,messages:[{role:"\
1258
- user",content:"Reply with OK."}]}),usable:t=>!!t?.id&&Array.isArray(t.choices)&&t.choices.length>0})});var Ut=(t,e,r,n)=>{let{modelProviderId:o,...i}=dt(e,t);return Object.freeze({...i,label:r,defaultThinking:n})},ps=Object.
1259
- freeze([Object.freeze({...ae("deepseek"),label:"DeepSeek",shortLabel:"DeepSeek",description:"DeepSeek API key \xB7 usage-ba\
1259
+ user",content:"Reply with OK."}]}),usable:t=>!!t?.id&&Array.isArray(t.choices)&&t.choices.length>0})});var Vt=(t,e,r,n)=>{let{modelProviderId:o,...i}=ft(e,t);return Object.freeze({...i,label:r,defaultThinking:n})},hs=Object.
1260
+ freeze([Object.freeze({...ie("deepseek"),label:"DeepSeek",shortLabel:"DeepSeek",description:"DeepSeek API key \xB7 usage-ba\
1260
1261
  sed billing",keyUrl:"https://platform.deepseek.com/api_keys",guideUrl:"https://api-docs.deepseek.com/quick_start/agent_i\
1261
- ntegrations/codex/",ownerOnly:!1,models:Object.freeze([Ut("deepseek","deepseek-flash","DeepSeek V4.1 Flash","high"),Ut("\
1262
- deepseek","deepseek-v4-pro","DeepSeek V4 Pro","high")])}),Object.freeze({...ae("zai-coding-plan"),label:"GLM \xB7 Coding Pl\
1262
+ ntegrations/codex/",ownerOnly:!1,models:Object.freeze([Vt("deepseek","deepseek-flash","DeepSeek V4.1 Flash","high"),Vt("\
1263
+ deepseek","deepseek-v4-pro","DeepSeek V4 Pro","high")])}),Object.freeze({...ie("zai-coding-plan"),label:"GLM \xB7 Coding Pl\
1263
1264
  an",shortLabel:"GLM",description:"Z.AI Coding Plan key \xB7 uses your subscription quota",keyUrl:"https://z.ai/manage-ap\
1264
- ikey/apikey-list",guideUrl:"https://docs.z.ai/devpack/tool/codex",ownerOnly:!0,models:Object.freeze([Ut("zai-coding-plan",
1265
- "glm-5.3","GLM 5.3","max")])}),Object.freeze({...ae("zai"),label:"GLM \xB7 Pay-as-you-go API",shortLabel:"GLM",description:"\
1265
+ ikey/apikey-list",guideUrl:"https://docs.z.ai/devpack/tool/codex",ownerOnly:!0,models:Object.freeze([Vt("zai-coding-plan",
1266
+ "glm-5.3","GLM 5.3","max")])}),Object.freeze({...ie("zai"),label:"GLM \xB7 Pay-as-you-go API",shortLabel:"GLM",description:"\
1266
1267
  Z.AI API key \xB7 pay-as-you-go account",keyUrl:"https://z.ai/manage-apikey/apikey-list",guideUrl:"https://docs.z.ai/gui\
1267
1268
  des/overview/quick-start",setupNote:"Use a key from a Z.AI account without a Coding Plan. Pay-as-you-go access through C\
1268
1269
  odex and Claude Code still needs live verification; a successful check confirms model access, not billing.",ownerOnly:!1,
1269
- models:Object.freeze([Ut("zai","glm-5.3","GLM 5.3","max")])}),Object.freeze({id:ue,custom:!0,label:"Custom endpoint",shortLabel:"\
1270
- Custom",description:"Your own model server \xB7 no Vibe64 billing",ownerOnly:!0,models:Object.freeze([])})]);var nE=Object.freeze(["auth","codex","status.json"]),oE=Object.freeze(["auth","codex","auth-status.json"]);var pn="VIBE64_CODEX_CUSTOM_HOME",CE=Object.freeze({codex:"Codex",claude:"Claude Code",opencode:"OpenCode"});function ms(t){let e=t?.models||[...new Map(ps.flatMap(r=>r.models).map(r=>[r.id,r])).values()];return Gt({models:e})}var[Ql,Zl,...ed]=process.argv.slice(2);await Qt({runtimeDir:Ql,command:Zl,args:ed,runtimeToken:process.env.VIBE64_CODEX_APP_SERVER_RUNTIME_TOKEN,
1271
- bundled:process.env.VIBE64_CODEX_MODEL_CATALOG_SOURCE==="bundled",additionalModels:[...ms().models,...process.env[pn]?await He(
1272
- process.env[pn]):[]],env:process.env});
1270
+ models:Object.freeze([Vt("zai","glm-5.3","GLM 5.3","max")])}),Object.freeze({id:ce,custom:!0,label:"Custom endpoint",shortLabel:"\
1271
+ Custom",description:"Your own model server \xB7 no Vibe64 billing",ownerOnly:!0,models:Object.freeze([])})]);var iE=Object.freeze(["auth","codex","status.json"]),sE=Object.freeze(["auth","codex","auth-status.json"]);var mn="VIBE64_CODEX_CUSTOM_HOME",IE=Object.freeze({codex:"Codex",claude:"Claude Code",opencode:"OpenCode"});function ys(t){let e=t?.models||[...new Map(hs.flatMap(r=>r.models).map(r=>[r.id,r])).values()];return Wt({models:e})}var[ed,td,...rd]=process.argv.slice(2);await Zt({runtimeDir:ed,command:td,args:rd,runtimeToken:process.env.VIBE64_CODEX_APP_SERVER_RUNTIME_TOKEN,
1272
+ bundled:process.env.VIBE64_CODEX_MODEL_CATALOG_SOURCE==="bundled",additionalModels:[...ys().models,...process.env[mn]?await Ge(
1273
+ process.env[mn]):[]],env:process.env});