@usine/server 0.4.0 → 0.4.1-next.241.gf648872

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 (138) hide show
  1. package/dist/web/assets/CompositeItem-DL5QWzlf.js +1 -0
  2. package/dist/web/assets/ToolbarRootContext-aq6udDVh.js +1 -0
  3. package/dist/web/assets/X.es-ClvLjC9g.js +1 -0
  4. package/dist/web/assets/_agent-DtbWtI4O.js +1 -0
  5. package/dist/web/assets/_loop-CPLcEe-u.js +1 -0
  6. package/dist/web/assets/_name-B-JwwOOx.js +1 -0
  7. package/dist/web/assets/_name-BHymV4y2.js +1 -0
  8. package/dist/web/assets/_name-DHT3Z3pi.js +1 -0
  9. package/dist/web/assets/_name-DOdPCzeN.js +1 -0
  10. package/dist/web/assets/_name-LDfdPJ04.js +6 -0
  11. package/dist/web/assets/_number-CXWY3_sQ.js +1 -0
  12. package/dist/web/assets/_number-DHT3Z3pi.js +1 -0
  13. package/dist/web/assets/_number-DdcjkCP5.js +1 -0
  14. package/dist/web/assets/_run-ChuAgP8W.js +8 -0
  15. package/dist/web/assets/_run-DHT3Z3pi.js +1 -0
  16. package/dist/web/assets/_worker-ve1pwBJ6.js +1 -0
  17. package/dist/web/assets/action-Bma79eWY.js +1 -0
  18. package/dist/web/assets/agents-BXym4S3E.js +1 -0
  19. package/dist/web/assets/agents-WFIojkKz.js +1 -0
  20. package/dist/web/assets/boot-screen-Su4MyrBh.js +1 -0
  21. package/dist/web/assets/button-4rhhIcK8.js +1 -0
  22. package/dist/web/assets/collapsible-CTA-Hwrn.js +1 -0
  23. package/dist/web/assets/{core-wi-Hu_JV.js → core-S_rVxu-b.js} +1 -1
  24. package/dist/web/assets/drawer-Dw6v2BLr.js +1 -0
  25. package/dist/web/assets/dropdown-menu-B5_S4hH-.js +1 -0
  26. package/dist/web/assets/edit-and-retry-CzObi4mf.js +1 -0
  27. package/dist/web/assets/empty-B9bymfss.js +1 -0
  28. package/dist/web/assets/error-alert-NXb1Z8Xz.js +1 -0
  29. package/dist/web/assets/{file-error-SjG2jLJ9.js → file-error-C2s0qbxi.js} +1 -1
  30. package/dist/web/assets/fill-cell-CjksmixH.js +1 -0
  31. package/dist/web/assets/heading-Bp50m3v1.js +1 -0
  32. package/dist/web/assets/index-CPkHl5O3.js +10 -0
  33. package/dist/web/assets/index-jplYOAsa.css +2 -0
  34. package/dist/web/assets/label-badge-DIiohsEI.js +1 -0
  35. package/dist/web/assets/link-C7GfYrMt.js +1 -0
  36. package/dist/web/assets/list-wEAoFt_l.js +1 -0
  37. package/dist/web/assets/loops-xOfOUTbc.js +1 -0
  38. package/dist/web/assets/{markdown-BnyfnuCL.js → markdown-BNebzGGH.js} +3 -3
  39. package/dist/web/assets/matchContext-D_B3XAQH.js +2 -0
  40. package/dist/web/assets/model-DXxFqTtA.js +1 -0
  41. package/dist/web/assets/moves-D_bvNew_.js +1 -0
  42. package/dist/web/assets/not-found-CTNKT4RI.js +1 -0
  43. package/dist/web/assets/outcome-o7LagK-q.js +5 -0
  44. package/dist/web/assets/overview-BdUgx_pE.js +1 -0
  45. package/dist/web/assets/page-BuzrT_cg.js +1 -0
  46. package/dist/web/assets/project-not-found-CutZoVCI.js +1 -0
  47. package/dist/web/assets/pull-request-marks-BLxcb-0V.js +1 -0
  48. package/dist/web/assets/queries-BnlycW8v.js +1 -0
  49. package/dist/web/assets/queries-BwtMk72-.js +1 -0
  50. package/dist/web/assets/reload-yp-6_O8x.js +1 -0
  51. package/dist/web/assets/repositories-MlGwURyP.js +1 -0
  52. package/dist/web/assets/route-Boaf6qM7.js +1 -0
  53. package/dist/web/assets/route-BxsfSGun.js +1 -0
  54. package/dist/web/assets/{routes-BLy5TGH_.js → routes-D25foI3P.js} +19 -19
  55. package/dist/web/assets/routes-DHT3Z3pi.js +1 -0
  56. package/dist/web/assets/run-again-BwF1g66X.js +1 -0
  57. package/dist/web/assets/section-B0ipDPYr.js +1 -0
  58. package/dist/web/assets/section-BhUxD7-H.js +1 -0
  59. package/dist/web/assets/section-BwxXJ9H0.js +1 -0
  60. package/dist/web/assets/settings-DQka4c7B.js +1 -0
  61. package/dist/web/assets/slots-n0NbUO7Z.js +1 -0
  62. package/dist/web/assets/status-badge-CLPsMXtK.js +1 -0
  63. package/dist/web/assets/strings-C9Xdiz_K.js +1 -0
  64. package/dist/web/assets/strings-qxNeGv33.js +301 -0
  65. package/dist/web/assets/table-hbKjhjeL.js +1 -0
  66. package/dist/web/assets/tasks-B51Y5ks_.js +1 -0
  67. package/dist/web/assets/tasks-DHT3Z3pi.js +1 -0
  68. package/dist/web/assets/usage-Bu-ewmBl.js +1 -0
  69. package/dist/web/assets/use-now-vNgLntlV.js +1 -0
  70. package/dist/web/assets/useAnchoredPopupScrollLock-CeE46geY.js +1 -0
  71. package/dist/web/assets/useNavigate-AT5VkfZa.js +1 -0
  72. package/dist/web/assets/usePositioner-B7VCT5LN.js +1 -0
  73. package/dist/web/assets/useRouter-Hur3RN7j.js +1 -0
  74. package/dist/web/assets/useTimeout-BC05Ghyu.js +1 -0
  75. package/dist/web/assets/with-selector-Dwf291_Q.js +1 -0
  76. package/dist/web/assets/workers-BeOqCiLJ.js +1 -0
  77. package/dist/web/index.html +20 -15
  78. package/package.json +9 -9
  79. package/dist/web/assets/CompositeItem-DU6IyNMY.js +0 -1
  80. package/dist/web/assets/ToolbarRootContext-Cytu6o2e.js +0 -1
  81. package/dist/web/assets/X.es-B7iqdxa_.js +0 -1
  82. package/dist/web/assets/_agent-BVKD5odk.js +0 -1
  83. package/dist/web/assets/_loop-BFLzamuo.js +0 -1
  84. package/dist/web/assets/_name-Bh4AQ9sR.js +0 -6
  85. package/dist/web/assets/_name-CMVsmWzq.js +0 -1
  86. package/dist/web/assets/_name-DCkgEma_.js +0 -1
  87. package/dist/web/assets/_name-Ds_pWi15.js +0 -1
  88. package/dist/web/assets/_number-B9aYwvcQ.js +0 -1
  89. package/dist/web/assets/_run-BZWt47QS.js +0 -8
  90. package/dist/web/assets/_worker-Dgfufm5p.js +0 -1
  91. package/dist/web/assets/action-rCd1FeAz.js +0 -1
  92. package/dist/web/assets/agents-Drbg6qpH.js +0 -1
  93. package/dist/web/assets/agents-_6-dEjrY.js +0 -1
  94. package/dist/web/assets/button-DVWXde__.js +0 -1
  95. package/dist/web/assets/collapsible-IOhZV1qg.js +0 -1
  96. package/dist/web/assets/drawer-BiqnR_8i.js +0 -1
  97. package/dist/web/assets/dropdown-menu-C9D1kRkO.js +0 -1
  98. package/dist/web/assets/edit-and-retry-BgOR6mvP.js +0 -1
  99. package/dist/web/assets/error-alert-9tKpTE3v.js +0 -1
  100. package/dist/web/assets/fill-cell-ClM88KFD.js +0 -1
  101. package/dist/web/assets/heading-lX1a1LNN.js +0 -1
  102. package/dist/web/assets/index-BymNZU1Q.js +0 -10
  103. package/dist/web/assets/index-Dyjfp3ET.css +0 -2
  104. package/dist/web/assets/label-badge-aIGT1Bry.js +0 -1
  105. package/dist/web/assets/list-v8WJp2Eq.js +0 -1
  106. package/dist/web/assets/loops-BFoFf_og.js +0 -1
  107. package/dist/web/assets/mark-CC3RwMy_.js +0 -1
  108. package/dist/web/assets/matchContext-BquevSJS.js +0 -2
  109. package/dist/web/assets/model-BerBT6R0.js +0 -1
  110. package/dist/web/assets/moves-Dg9sshX5.js +0 -1
  111. package/dist/web/assets/overview-C_tFKGZ8.js +0 -1
  112. package/dist/web/assets/page-DWnGi6wA.js +0 -301
  113. package/dist/web/assets/project-not-found-CodaBVdu.js +0 -1
  114. package/dist/web/assets/pull-request-marks-DE00nqGW.js +0 -1
  115. package/dist/web/assets/queries-B1SHA_r4.js +0 -1
  116. package/dist/web/assets/reload-Dsl0zjJ7.js +0 -1
  117. package/dist/web/assets/repositories-BdxmD192.js +0 -1
  118. package/dist/web/assets/route-B_gphTYG.js +0 -1
  119. package/dist/web/assets/route-Cc7dKnn5.js +0 -1
  120. package/dist/web/assets/run-again-BTKagSXR.js +0 -1
  121. package/dist/web/assets/section-B3pWIIBa.js +0 -1
  122. package/dist/web/assets/section-CD-MB5r3.js +0 -1
  123. package/dist/web/assets/section-Id99HktI.js +0 -1
  124. package/dist/web/assets/settings-YrDysQXW.js +0 -1
  125. package/dist/web/assets/slots-BraHmbNr.js +0 -1
  126. package/dist/web/assets/status-badge-DnvNo1tG.js +0 -1
  127. package/dist/web/assets/strings-CW2XaR5f.js +0 -1
  128. package/dist/web/assets/table-BjyI4fVI.js +0 -1
  129. package/dist/web/assets/tasks-DCL8kLmD.js +0 -1
  130. package/dist/web/assets/transcript-sxRJzx6t.js +0 -5
  131. package/dist/web/assets/usage-CLQJdX9-.js +0 -1
  132. package/dist/web/assets/use-now-0P8TUXeg.js +0 -1
  133. package/dist/web/assets/useAnchoredPopupScrollLock-CQ83Wy-r.js +0 -1
  134. package/dist/web/assets/useNavigate-BW1WdocJ.js +0 -1
  135. package/dist/web/assets/usePositioner-rNCxnHO-.js +0 -1
  136. package/dist/web/assets/useTimeout-_TcdZXP6.js +0 -1
  137. package/dist/web/assets/with-selector-DoElmmtd.js +0 -1
  138. package/dist/web/assets/workers-BH5CBOR3.js +0 -1
@@ -0,0 +1,301 @@
1
+ var e=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let e=0,r=t.length;e<r;e++)n=t[e](n);return n}}},t={pipe(){return e(this,arguments)}},n=function(){function e(){}return e.prototype=t,e}(),r=function(e,t){if(typeof e==`function`)return function(){return e(arguments)?t.apply(this,arguments):e=>t(e,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(e,n){return arguments.length>=2?t(e,n):function(n){return t(n,e)}};case 3:return function(e,n,r){return arguments.length>=3?t(e,n,r):function(r){return t(r,e,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(e){return t(e,...n)}}}},i=e=>e,a=e=>()=>e,o=a(!0),s=a(!1),c=a(null),l=a(void 0),u=l;function d(t,...n){return e(t,n)}function f(e){let t=new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}function p(e){let t=new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i!==n&&t.set(i,i),i}}var m=e=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;e instanceof Error&&t.delete(`stack`);let n=Object.getPrototypeOf(e),r=n;for(;r!==null&&r!==Object.prototype;){let e=Reflect.ownKeys(r);for(let n=0;n<e.length;n++)t.add(e[n]);r=Object.getPrototypeOf(r)}return t.has(`constructor`)&&typeof e.constructor==`function`&&n===e.constructor.prototype&&t.delete(`constructor`),t},h=new WeakSet,g=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),_=0,v=()=>{_++};function ee(e){return typeof e==`string`}function te(e){return typeof e==`number`}function ne(e){return typeof e==`boolean`}function re(e){return typeof e==`bigint`}function ie(e){return typeof e==`symbol`}function ae(e){return ee(e)||te(e)||ie(e)}function oe(e){return typeof e==`function`}function se(e){return e!==void 0}function ce(e){return e!=null}function le(e){return!1}function ue(e){return!0}function de(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fe(e){return typeof e==`object`&&!!e||oe(e)}var pe=r(2,(e,t)=>fe(e)&&t in e),me=r(2,(e,t)=>pe(e,`_tag`)&&e._tag===t);function he(e){return e instanceof Error}function ge(e){return pe(e,Symbol.iterator)||ee(e)}var _e=`~effect/Hash`,ve=e=>{switch(typeof e){case`number`:return we(e);case`bigint`:return Te(e.toString(10));case`string`:return Te(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?Te(`Invalid Date`):Te(e.toISOString());if(e instanceof RegExp)return Te(e.toString());{if(h.has(e))return ye(e);let t=Pe.get(e);if(t!==void 0)return t;if(Fe.has(e))return v(),Te(`[Circular]`);Fe.add(e);let n=_,r;try{r=`~effect/Hash`in e?e[_e]():typeof e==`function`?ye(e):e instanceof DataView?ke(g(e)):Array.isArray(e)||ArrayBuffer.isView(e)?ke(e):e instanceof Map?Ae(e):e instanceof Set?Me(e):De(e)}finally{Fe.delete(e)}return n===_&&Pe.set(e,r),r}}return Se(be(Te(String(e))))},ye=e=>(Ne.has(e)||Ne.set(e,Se(Math.random()*4294967296|0)),Ne.get(e)),be=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),xe=r(2,(e,t)=>be(Math.imul(e,2654435761)+Math.imul(t,2246822507))),Se=e=>e&3221225471|e>>>1&1073741824,Ce=new DataView(new ArrayBuffer(8)),we=e=>{let t=e|0;return t===e?Se(t):(Ce.setFloat64(0,e===e?e:NaN),Se(xe(Ce.getInt32(0),Ce.getInt32(4))))},Te=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return Se(t)},Ee=(e,t)=>{let n=12289;for(let r of t)n^=xe(ve(r),ve(e[r]));return Se(n)},De=e=>Ee(e,m(e)),Oe=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return Se(r)},ke=e=>{let t=6151;for(let n of e)t=xe(t,ve(n));return Se(t)},Ae=Oe(Te(`Map`),([e,t])=>xe(ve(e),ve(t))),je=Te(`Set`),Me=Oe(je,e=>xe(je,ve(e))),Ne=new WeakMap,Pe=new WeakMap,Fe=new WeakSet,Ie=`~effect/Equal`;function Le(){return arguments.length===1?e=>Re(e,arguments[0]):Re(arguments[0],arguments[1])}function Re(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;return n===typeof t?n===`number`&&e!==e&&t!==t?!0:n!==`object`&&n!==`function`||h.has(e)||h.has(t)?!1:ze(e,t):!1}function ze(e,t){let n=Ve.length;for(let r=n;r-->0;)if(Ve[r]===e&&He[r]===t)return!0;if(n)return Be(e,t);let r=Ue.get(e);r||Ue.set(e,r=new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=Be(e,t)),i}function Be(e,t){Ve.push(e),He.push(t);try{return We(e,t)}finally{Ve.pop(),He.pop()}}var Ve=[],He=[],Ue=new WeakMap;function We(e,t){if(ve(e)!==ve(t))return!1;if(e instanceof Date){if(!(t instanceof Date))return!1;let n=e.getTime(),r=t.getTime();return n===r||Number.isNaN(n)&&Number.isNaN(r)}if(e instanceof RegExp)return t instanceof RegExp&&e.toString()===t.toString();let n=Ze(e);if(n!==Ze(t)||typeof e==`function`&&!n)return!1;if(n)return e[Ie](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:Ge(e,t);if(ArrayBuffer.isView(e)){let n=e instanceof DataView;return!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||n!==t instanceof DataView?!1:n?Ke(g(e),g(t)):Ke(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:Je(e,t,Ye,Xe):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:Je(e,t,ve,Re):qe(e,t)}function Ge(e,t){for(let n=0;n<e.length;n++)if(!Re(e[n],t[n]))return!1;return!0}function Ke(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function qe(e,t){let n=m(e),r=m(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!Re(e[i],t[i]))return!1;return!0}function Je(e,t,n,r){let i=new Map,a=0;for(let e of t){let t=n(e),r=i.get(t);r?r.push(e):i.set(t,[e]),a++}outer:for(let t of e){let e=i.get(n(t));if(e){for(let n=0;n<e.length;n++)if(r(t,e[n])){e[n]=e[e.length-1],e.pop(),a--;continue outer}}return!1}return a===0}var Ye=e=>ve(e[0]),Xe=(e,t)=>Re(e[0],t[0])&&Re(e[1],t[1]),Ze=e=>pe(e,Ie),Qe=()=>Le,$e=Symbol.for(`~effect/Redactable`),et=e=>pe(e,$e);function tt(e){return et(e)?nt(e):e}function nt(e){return e[$e](globalThis[`~effect/Fiber/currentFiber`]?.context??at)}var rt=`~effect/Fiber/currentFiber`,it=new Map,at={"~effect/Context":{},base:it,depth:0,mapUnsafe:it,pipe(){return e(this,arguments)}};function ot(e,t){let n=t?.space??0,r=new WeakSet,i=n?typeof n==`number`?` `.repeat(n):n:``,a=e=>i.repeat(e),o=(e,t)=>{let n=e?.constructor;return n&&n!==Object.prototype.constructor&&n.name?`${n.name}(${t})`:t},s=e=>{try{return Reflect.ownKeys(e)}catch{return[`[ownKeys threw]`]}};function c(e,t=0){try{return l(e,t)}catch{return(typeof e==`object`&&e||typeof e==`function`)&&r.delete(e),`[inspection threw]`}}function l(e,n=0){if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`||e==null||typeof e==`boolean`||typeof e==`symbol`)return String(e);if(typeof e==`bigint`)return String(e)+`n`;if(typeof e==`object`||typeof e==`function`){if(r.has(e))return st;r.add(e);let l;if($e in e)l=c(nt(e),n);else if(Array.isArray(e))l=!i||e.length<=1?`[${e.map(e=>c(e,n)).join(`,`)}]`:`[\n${a(n+1)}${e.map(e=>c(e,n+1)).join(`,
2
+ `+a(n+1))}\n${a(n)}]`;else if(e instanceof Date)l=ut(e);else if(!t?.ignoreToString&&pe(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=dt(e);l=e instanceof Error&&e.cause!==void 0?`${t} (cause: ${c(e.cause,n)})`:t}else if(Symbol.iterator in e)l=`${e.constructor.name}(${c(Array.from(e),n)})`;else{let t=s(e);if(!i||t.length<=1){let r=`{${t.map(t=>`${ct(t)}:${c(ft(e,t),n)}`).join(`,`)}}`;l=o(e,r)}else{let r=`{\n${t.map(t=>`${a(n+1)}${ct(t)}: ${c(ft(e,t),n+1)}`).join(`,
3
+ `)}\n${a(n)}}`;l=o(e,r)}}return r.delete(e),l}return String(e)}return c(e,0)}var st=`[Circular]`;function ct(e){return typeof e==`string`?JSON.stringify(e):String(e)}function lt(e){return e.map(e=>`[${ct(e)}]`).join(``)}function ut(e){try{return e.toISOString()}catch{return`Invalid Date`}}function dt(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function ft(e,t){try{return e[t]}catch{return`[property access threw]`}}function pt(e,t){let n=[];return JSON.stringify(e,function(e,t){let r=Object.getOwnPropertyDescriptor(this,e)?.value,i=pe(r,$e)?tt(r):tt(t);if(typeof i==`bigint`)return ot(i);if(typeof i!=`object`||!i)return i;let a=i instanceof Error&&!pe(i,`toJSON`)?{...i,name:i.name,message:i.message}:i;for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(i))return;if(n.push(i),a!==i&&n.push(a),!mt(a)||ht(a))return a;let o=new Proxy(a,{get(e,t){let n=Reflect.get(e,t,e);return Object.getOwnPropertyDescriptor(e,t)?.get===void 0?n:tt(n)}});return n.push(o),o},t?.space)??`null`}function mt(e){for(let t of Object.getOwnPropertyNames(e))if(Object.getOwnPropertyDescriptor(e,t)?.get!==void 0)return!0;return!1}function ht(e){for(let t of[Number.prototype.valueOf,Boolean.prototype.valueOf,String.prototype.valueOf])try{return Reflect.apply(t,e,[]),!0}catch{}return!1}var gt=Symbol.for(`nodejs.util.inspect.custom`),_t=e=>{try{return e=tt(e),pe(e,`toJSON`)&&oe(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map(_t):e}catch{return`[toJSON threw]`}},vt=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?pt(e,{space:t}):ot(e,{space:t})}catch{return String(e)}},yt={toJSON(){return _t(this)},[gt](){return this.toJSON()},toString(){return ot(this.toJSON())}},bt=class{[gt](){return this.toJSON()}toString(){return ot(this.toJSON())}},xt=(()=>{let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.hasOwn(e,`writable`)?e.writable===!0:e.set!==void 0})(),St=()=>Error.stackTraceLimit,Ct=e=>{xt&&(Error.stackTraceLimit=e)},wt=class{constructor(e){this.value=e,this.done=!1}next(e){return this.done?(this.value=e,this):(this.done=!0,{value:this.value,done:!1})}},Tt=(()=>{let e=`~effect/Utils/internal`,t={[e]:e=>e()},n={[e]:e=>{try{return e()}finally{}}},r=St();if(r===0)return n[e];Ct(2);let i=t[e](()=>Error());return Ct(r),i.stack?.includes(e)===!0?t[e]:n[e]})();function Et(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function Dt(e,t){if(!Object.hasOwn(t,`__proto__`))Object.assign(e,t);else for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&Et(e,n,t[n])}var Ot=`~effect/Effect`,kt=`~effect/Exit`,At={_A:i,_E:i,_R:i},jt=`${Ot}/identifier`,Mt=`${Ot}/args`,Nt=`${Ot}/evaluate`,Pt=`${Ot}/successCont`,Ft=`${Ot}/failureCont`,It=`${Ot}/ensureCont`,Lt=Symbol.for(`effect/Effect/Yield`),Rt={pipe(){return e(this,arguments)},toJSON(){return{...this}},toString(){return ot(this.toJSON(),{ignoreToString:!0,space:2})},[gt](){return this.toJSON()}},zt={[Ot]:At,...Rt,[Symbol.iterator](){return new wt(this)},toJSON(){return{_id:`Effect`,op:this[jt],...`~effect/Effect/args`in this?{args:this[Mt]}:void 0}}},Bt=e=>pe(e,Ot),Vt=e=>pe(e,kt),Ht=`~effect/Cause`,Ut=`~effect/Cause/Reason`,Wt=e=>pe(e,Ht),Gt=e=>pe(e,Ut),Kt=class{constructor(e){this[Ht]=Ht,this.reasons=e}pipe(){return e(this,arguments)}toJSON(){return{_id:`Cause`,reasons:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${ot(this.reasons)})`}[gt](){return this.toJSON()}[Ie](e){return Wt(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>Le(t,e.reasons[n]))}[_e](){return ke(this.reasons)}},qt=new WeakMap,Jt=class{[Ut];annotations;_tag;constructor(e,t,n){if(this[Ut]=Ut,this._tag=e,t!==Yt&&typeof n==`object`&&n&&t.size>0){let e=qt.get(n);e&&(t=new Map([...e,...t])),qt.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((e,r)=>{t?.overwrite!==!0&&n.has(r)||n.set(r,e)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return e(this,arguments)}toString(){return ot(this)}[gt](){return this.toString()}},Yt=new Map,Xt=class extends Jt{constructor(e,t=Yt){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${ot(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[Ie](e){return sn(e)&&Le(this.error,e.error)&&Le(this.annotations,e.annotations)}[_e](){return xe(Te(this._tag))(xe(ve(this.error))(ve(this.annotations)))}},Zt=e=>new Kt(e),Qt=(e,t)=>{let n=new Map,r=[];for(let i of e.concat(t)){let e=ve(i),t=n.get(e);if(t===void 0)n.set(e,[i]);else if(t.some(e=>Le(e,i)))continue;else t.push(i);r.push(i)}return r},$t=r(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new Kt(Qt(e.reasons,t.reasons));return Le(e,n)?e:n}),en=(e,t)=>{let n=e.reasons.slice();for(let e of t.reasons)ln(e)&&!n.some(t=>ln(t)&&t.fiberId===e.fiberId&&t.annotations===e.annotations)&&n.push(e);return n.length===e.reasons.length?e:new Kt(n)},tn=new Kt([]),nn=e=>new Kt([new Xt(e)]),rn=class extends Jt{constructor(e,t=Yt){super(`Die`,t,e),this.defect=e}toString(){return`Die(${ot(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[Ie](e){return cn(e)&&Le(this.defect,e.defect)&&Le(this.annotations,e.annotations)}[_e](){return xe(Te(this._tag))(xe(ve(this.defect))(ve(this.annotations)))}},an=e=>new Kt([new rn(e)]),on=r(e=>Wt(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new Kt(e.reasons.map(e=>e.annotate(t,n)))),sn=e=>e._tag===`Fail`,cn=e=>e._tag===`Die`,ln=e=>e._tag===`Interrupt`;function un(e){return yn(`Effect.evaluate: Not implemented`)}var dn=e=>({...zt,[jt]:e.op,[Nt]:e[`~effect/Effect/evaluate`]??un,[Pt]:e[Pt],[Ft]:e[Ft],[It]:e[It]}),fn=e=>{let t=dn(e),n=function(e){this[Mt]=e};return n.prototype=t,function(e){return new n(e)}},pn=e=>{let t={[kt]:kt,_tag:e.op,get[e.prop](){return this[Mt]},...dn(e),toString(){return`${e.op}(${ot(this[Mt])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[Mt]}},[Ie](e){return Vt(e)&&e._tag===this._tag&&Le(this[`~effect/Effect/args`],e[`~effect/Effect/args`])},[_e](){return xe(Te(e.op),ve(this[Mt]))}},n=function(e){this[Mt]=e};return n.prototype=t,function(e){return new n(e)}},mn=pn({op:`Success`,prop:`value`,[Nt](e){let t=e.getCont(Pt);return t?t[Pt](this[Mt],e,this):e.yieldWith(this)}}),hn={key:`effect/Cause/StackTrace`},gn={key:`effect/Cause/InterruptorStackTrace`},_n=pn({op:`Failure`,prop:`cause`,[Nt](e){let t=this[Mt],n=!1;e.cache.stackFrame&&(t=on(t,{mapUnsafe:new Map([[hn.key,e.cache.stackFrame]])}),n=!0);let r=e.getCont(Ft),i=e._interruptedCause;if(i&&e.interruptible){let a=!1;for(;r&&e.interruptible;)a||=jt in r,r=e.getCont(Ft);a&&(t=Zt(t.reasons.filter(e=>e._tag!==`Fail`))),t=en(t,i),n=!0}return r?r[Ft](t,e,n?void 0:this):e.yieldWith(n?_n(t):this)}}),vn=e=>_n(nn(e)),yn=e=>_n(an(e)),bn=fn({op:`WithFiber`,[Nt](e){return this[Mt](e)}}),xn=function(){class e extends globalThis.Error{}let t=dn({op:`YieldableError`,[Nt](){return vn(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Sn=function(){let e=Symbol.for(`effect/Data/Error/plainArgs`);return class extends xn{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(Dt(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}(),Cn=e=>{class t extends Sn{_tag=e}return t.prototype.name=e,t},wn=`~effect/Cause/NoSuchElementError`,Tn=class extends Cn(`NoSuchElementError`){[wn]=wn;constructor(e){super({message:e})}},En=`~effect/Cause/Done`,Dn=e=>pe(e,En),On={[En]:En,_tag:`Done`,value:void 0},kn=e=>e===void 0?On:{[En]:En,_tag:`Done`,value:e},An=vn(On),jn=e=>e===void 0?An:vn(kn(e)),Mn=e=>dn({op:e.label,[Nt]:e.evaluate}),Nn=e=>(t,n)=>t===n||e(t,n),Pn=(e,t)=>e===t,Fn=()=>Pn;function In(e){return Nn((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e[r](t[r],n[r]))return!1;return!0})}function Ln(e){return Nn((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1;return!0})}var Rn=`~effect/Option`,zn={[Rn]:{_A:e=>e},...Rt,[Symbol.iterator](){return new wt(this)}},Bn=Object.defineProperty(Object.assign(Object.create(zn),{_tag:`Some`,_op:`Some`,[Ie](e){return Un(e)&&Gn(e)&&Le(this.value,e.value)},[_e](){return xe(ve(this._tag))(ve(this.value))},toString(){return`some(${ot(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:_t(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),Vn=ve(`None`),Hn=Object.assign(Object.create(zn),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[Ie](e){return Un(e)&&Wn(e)},[_e](){return Vn},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),Un=e=>pe(e,Rn),Wn=e=>e._tag===`None`,Gn=e=>e._tag===`Some`,Kn=Object.create(Hn),qn=function(e){this.value=e};qn.prototype=Bn;var Jn=e=>new qn(e),Yn=`~effect/Result`,Xn={[Yn]:{_A:e=>e,_E:e=>e},...Rt,[Symbol.iterator](){return new wt(this)}},Zn=Object.assign(Object.create(Xn),{_tag:`Success`,_op:`Success`,[Ie](e){return $n(e)&&tr(e)&&Le(this.success,e.success)},[_e](){return xe(ve(this._tag))(ve(this.success))},toString(){return`success(${ot(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:_t(this.success)}}}),Qn=Object.assign(Object.create(Xn),{_tag:`Failure`,_op:`Failure`,[Ie](e){return $n(e)&&er(e)&&Le(this.failure,e.failure)},[_e](){return xe(ve(this._tag))(ve(this.failure))},toString(){return`failure(${ot(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:_t(this.failure)}}}),$n=e=>pe(e,Yn),er=e=>e._tag===`Failure`,tr=e=>e._tag===`Success`,nr=function(e){this.failure=e};nr.prototype=Qn;var rr=e=>new nr(e),ir=function(e){this.success=e};ir.prototype=Zn;var ar=e=>new ir(e),or=r(2,(e,t)=>Wn(e)?rr(t()):ar(e.value));function sr(e){return(t,n)=>t===n?0:e(t,n)}var cr=sr((e,t)=>e<t?-1:1),lr=sr((e,t)=>globalThis.Number.isNaN(e)&&globalThis.Number.isNaN(t)?0:globalThis.Number.isNaN(e)?-1:globalThis.Number.isNaN(t)?1:e<t?-1:1);function ur(e){return sr((t,n)=>e(n,t))}function dr(e){let t=Array.from(e);return sr((e,n)=>{let r=0;for(let i of t)if(r=i(e,n),r!==0)return r;return r})}var fr=r(2,(e,t)=>sr((n,r)=>e(t(n),t(r)))),pr=e=>r(2,(t,n)=>e(t,n)===-1),mr=e=>r(2,(t,n)=>e(t,n)===1),hr=e=>r(2,(t,n)=>e(t,n)!==1),gr=e=>r(2,(t,n)=>e(t,n)!==-1),y=()=>Kn,b=Jn,_r=Un,x=Wn,S=Gn,vr=r(2,(e,{onNone:t,onSome:n})=>x(e)?t():n(e.value)),yr=r(2,(e,t)=>x(e)?t():e.value),br=r(2,(e,t)=>x(e)?t():e),xr=e=>{let t=y();for(t of e)if(S(t))return t;return t},C=e=>e==null?y():b(e),Sr=e=>e===void 0?y():b(e),Cr=e=>e===null?y():b(e),w=yr(c),wr=yr(l),Tr=e=>(...t)=>{try{return b(e(...t))}catch{return y()}},Er=r(2,(e,t)=>{if(S(e))return e.value;throw t()}),Dr=r(2,(e,t)=>x(e)?y():b(t(e.value))),Or=r(2,(e,t)=>x(e)?y():t(e.value)),kr=Or(i),Ar=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(x(n))return y();t.push(n.value)}return b(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(x(r))return y();Et(t,n,r.value)}return b(t)},jr=e=>x(e)?[]:[e.value],Mr=r(2,(e,t)=>x(e)?y():t(e.value)?b(e.value):y()),Nr=r(2,(e,t)=>t(e)?b(e):y()),Pr=(e=>r(2,(t,n)=>!x(t)&&e(t.value,n)))(Qe()),Fr=r(2,(e,t)=>!x(e)&&t(e.value)),Ir=`~effect/Context/Service`,Lr=function(){function e(){}let t=e;Object.setPrototypeOf(t,Rr);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[Br]=Br,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&zr.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},Rr={[Ir]:Ir,...Mn({label:`Service`,evaluate(e){return mn(li(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return ri(this,e)},use(e){return bn(t=>e(li(t.context,this)))},useSync(e){return bn(t=>mn(e(li(t.context,this))))}},zr=new Set,Br=`~effect/Context/Reference`,Vr=`~effect/Context`,Hr=8,Ur=8,Wr=(e,t,n,r)=>{let i=Object.create(Zr);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Gr=(e,t)=>{t&&(Gr(e,t.parent),e.set(t.key,t.value))},Kr=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Gr(t,e.overlay),e._flat=t},qr=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),Xr(n)},Jr=Symbol(),Yr=(e,t)=>{let n=e;for(let e=n.overlay;e;e=e.parent)if(e.key===t)return e.value;let r=n.base.get(t);return r===void 0&&!n.base.has(t)?Jr:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=Ur&&(n.base=Kr(n),n.overlay=void 0,n.depth=0),r)},Xr=e=>Wr(void 0,e,void 0,0),Zr={get mapUnsafe(){return Kr(this)},...Rt,[Vr]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[Ie](e){if(!$r(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[e,r]of t)if(!n.has(e)||!Le(r,n.get(e)))return!1;return!0},[_e](){return we(this.mapUnsafe.size)}},Qr=(e,t)=>e.cacheRoot===t.cacheRoot,$r=e=>pe(e,Vr),ei=e=>!!e[Br],ti=()=>ni,ni=Xr(new Map),ri=(e,t)=>Xr(new Map([[e.key,t]])),ii=r(3,(e,t,n)=>ai(e,t.key,n)),ai=(e,t,n)=>{let r=e,i=zr.has(t)?void 0:r.cacheRoot;if(r.depth>=Hr){let e=new Map(r._flat??r.base);return r._flat||Gr(e,r.overlay),e.set(t,n),Wr(i,e,void 0,0)}return Wr(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},oi=r(2,(e,t)=>si(e,t.key)),si=(e,t)=>{let n=Yr(e,t);return n===Jr?void 0:n},ci=r(2,(e,t)=>{let n=Yr(e,t.key);if(n===Jr){if(ei(t))return di(t);throw fi(t)}return n}),li=ci,ui=`~effect/Context/defaultValue`,di=e=>ui in e?e[ui]:e[ui]=e.defaultValue(),fi=e=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:``}`);if(t.stack){let e=t.stack.split(`
4
+ `);e.splice(1,3),t.stack=e.join(`
5
+ `)}return t},pi=r(2,(e,t)=>{let n=Yr(e,t.key);return n===Jr?ei(t)?b(di(t)):y():b(n)}),mi=r(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:qr(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),hi=(...e)=>{let t=new Map;for(let n=0;n<e.length;n++)e[n].mapUnsafe.forEach((e,n)=>{t.set(n,e)});return Xr(t)},gi=(...e)=>t=>{if(e.length<=1){let n=new Map;if(e.length===1){let r=e[0].key,i=Yr(t,r);i!==Jr&&n.set(r,i)}return Xr(n)}let n=new Set(e.map(e=>e.key));return qr(t,e=>e.forEach((t,r)=>{n.has(r)||e.delete(r)}))},_i=Lr,vi=e=>e.length>0,yi=e=>e>0?Math.floor(e):0,bi=e=>Math.max(1,yi(e)),xi=ar,Si=rr,Ci=or,wi=e=>{if(oe(e))try{return xi(e())}catch(e){return Si(e)}try{return xi(e.try())}catch(t){return Si(e.catch(t))}},Ti=$n,Ei=er,Di=tr,Oi=r(2,(e,t)=>Di(e)?xi(t(e.success)):e),ki=r(2,(e,{onFailure:t,onSuccess:n})=>Ei(e)?t(e.failure):n(e.success)),Ai=r(2,(e,t)=>{if(Di(e))return e.success;throw t(e.failure)})(i),ji=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(Ei(n))return n;t.push(n.success)}return xi(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(Ei(r))return r;Et(t,n,r.success)}return xi(t)},Mi=(...e)=>e,Ni=In,Pi={[Symbol.iterator](){return Fi}},Fi={next(){return{done:!0,value:void 0}}},Ii=()=>Pi,Li=r(2,(e,t)=>Object.hasOwn(e,t)),Ri=r(2,(e,t)=>{let n={...e};for(let r of zi(e))Et(n,r,t(e[r],r));return n}),zi=e=>Object.keys(e),Bi=e=>r(2,(t,n)=>{for(let r of zi(t))if(!Li(n,r)||!e(t[r],n[r]))return!1;return!0}),Vi=e=>{let t=Bi(e);return(e,n)=>t(e,n)&&t(n,e)},Hi=globalThis.Array,Ui=e=>Hi.isArray(e)?e:Hi.from(e),Wi=e=>Hi.isArray(e)?e:[e],Gi=r(2,(e,t)=>[t,...e]),Ki=r(2,(e,t)=>[...e,t]),qi=r(2,(e,t)=>Ui(e).concat(Ui(t)));Hi.isArray;var Ji=vi,Yi=vi;function Xi(e,t){return!Number.isFinite(e)||e<0||e>=t.length}var Zi=r(2,(e,t)=>{let n=Math.floor(t);return Xi(n,e)?y():b(e[n])}),Qi=r(2,(e,t)=>{let n=Math.floor(t);if(Xi(n,e))throw Error(`Index out of bounds: ${n}`);return e[n]}),$i=Zi(0),ea=Qi(0),ta=e=>e[e.length-1],na=r(2,(e,t)=>{let n=Ui(e);for(let e=n.length-1;e>=0;e--){let r=n[e],i=t(r,e);if(typeof i==`boolean`){if(i)return b(r)}else if(S(i))return i}return y()}),ra=r(2,(e,t)=>{let n=Hi.from(e);return n.sort(t),n}),ia=r(2,(e,t)=>aa(e,t,Mi)),aa=r(3,(e,t,n)=>{let r=Ui(e),i=Ui(t);if(Yi(r)&&Yi(i)){let e=[n(ea(r),ea(i))],t=Math.min(r.length,i.length);for(let a=1;a<t;a++)e[a]=n(r[a],i[a]);return e}return[]}),oa=r(2,(e,t)=>{let n=Ui(e);if(Yi(n)){let[e,r]=t(n),i=[e],a=r;for(;vi(a);){let[e,n]=t(a);i.push(e),a=n}return i}return[]}),sa=r(2,(e,t)=>{let n=bi(t);return n>=e.length?[ca(e),[]]:[Gi(e.slice(1,n),ea(e)),e.slice(n)]}),ca=e=>e.slice(),la=r(2,(e,t)=>{let n=Ui(e);return Yi(n)?oa(n,sa(t)):[]}),ua=r(2,(e,t)=>{let n={};for(let r of e){let e=t(r);Object.hasOwn(n,e)?n[e].push(r):Et(n,e,[r])}return n}),da=(e,t)=>{let n=ve(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(Le(e,t))return!1;return r.push(t),!0},fa=()=>[],pa=e=>[e],ma=r(2,(e,t)=>e.map(t)),ha=e=>{let t=[];for(let n of e)S(n)&&t.push(n.value);return t},ga=Ln,_a=r(2,(e,t)=>{let n=[];next:for(let r of Ui(e)){for(let e=0;e<n.length;e++)if(t(r,n[e]))continue next;n.push(r)}return n}),va=e=>{let t=Ui(e);if(t.length<2)return[...t];let n=new Map,r=[];for(let e of t)da(n,e)&&r.push(e);return r},ya=`~effect/Duration`,ba=BigInt(0),xa=BigInt(1),Sa=BigInt(2),Ca=BigInt(10),wa=BigInt(1e3),Ta=BigInt(1e6),Ea=BigInt(1e9),Da=BigInt(6e10),Oa=BigInt(36e11),ka=BigInt(864e11),Aa=BigInt(6048e11),ja=e=>BigInt(Math.sign(e)*Math.round(Math.abs(e))),Ma=e=>Number.isInteger(e)?BigInt(e)*Ta:ja(e*1e6),Na=e=>qa(Number.isFinite(e)?ja(e):e),Pa=(e,t)=>{let n=Number(e);if(Number.isFinite(n))return n/t;let r=BigInt(t);return Number(e/r)+Number(e%r)/t},Fa=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=Ca**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t;return Ia(r?-o:o,a)},Ia=(e,t)=>{let n=e<ba?-e:e,r=n/t+(n%t*Sa>=t?xa:ba);return e<ba?-r:r},La=(e,t)=>{let n=Number(e)*t;if(!Number.isFinite(n))return qa(n);let r=Fa(e,BigInt(t)*Ta);return qa(Number.isInteger(n)&&BigInt(n)*Ta===r?n:r)},Ra=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,za=e=>{switch(typeof e){case`number`:return $a(e);case`bigint`:return Qa(e);case`string`:{if(e===`Infinity`)return Xa;if(e===`-Infinity`)return Za;let t=Ra.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return Qa(Fa(r,xa));if(i===`micro`||i===`micros`)return Qa(Fa(r,wa));switch(i){case`milli`:case`millis`:return La(r,1);case`second`:case`seconds`:return La(r,1e3);case`minute`:case`minutes`:return La(r,6e4);case`hour`:case`hours`:return La(r,36e5);case`day`:case`days`:return La(r,864e5);case`week`:case`weeks`:return La(r,6048e5)}break}case`object`:{if(e===null)break;if(ya in e)return e;if(Array.isArray(e)){if(e.length!==2||!e.every(te))return Ha(e);if(Number.isNaN(e[0])||Number.isNaN(e[1]))return Ya;if(e[0]===-1/0||e[1]===-1/0)return Za;if(e[0]===1/0||e[1]===1/0)return Xa;let t=e[0]*1e9+e[1];return Number.isFinite(t)&&Number.isInteger(e[0])&&Number.isInteger(e[1])?qa(BigInt(e[0])*Ea+BigInt(e[1])):Na(t)}let t=e,n=0;if(t.weeks&&(n+=t.weeks*6048e5),t.days&&(n+=t.days*864e5),t.hours&&(n+=t.hours*36e5),t.minutes&&(n+=t.minutes*6e4),t.seconds&&(n+=t.seconds*1e3),t.milliseconds&&(n+=t.milliseconds),!t.microseconds&&!t.nanoseconds){if(!Number.isFinite(n))return qa(n);let e=Va(t);return e===void 0||BigInt(n)*Ta===e?qa(n):qa(e)}let r=n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0),i=Number.isFinite(r)?Va(t):void 0;return i===void 0?Na(r):qa(i)}}return Ha(e)},Ba=e=>!e||Number.isInteger(e),Va=e=>{if(!Ba(e.weeks)||!Ba(e.days)||!Ba(e.hours)||!Ba(e.minutes)||!Ba(e.seconds)||!Ba(e.milliseconds)||!Ba(e.microseconds)||!Ba(e.nanoseconds))return;let t=ba;return e.weeks&&(t+=BigInt(e.weeks)*Aa),e.days&&(t+=BigInt(e.days)*ka),e.hours&&(t+=BigInt(e.hours)*Oa),e.minutes&&(t+=BigInt(e.minutes)*Da),e.seconds&&(t+=BigInt(e.seconds)*Ea),e.milliseconds&&(t+=BigInt(e.milliseconds)*Ta),e.microseconds&&(t+=BigInt(e.microseconds)*wa),e.nanoseconds&&(t+=BigInt(e.nanoseconds)),t},Ha=e=>{throw Error(`Invalid Input: ${e}`)},Ua={_tag:`Millis`,millis:0},Wa={_tag:`Infinity`},Ga={_tag:`NegativeInfinity`},Ka={[ya]:ya,[_e](){switch(this.value._tag){case`Millis`:return ve(Ma(this.value.millis));case`Nanos`:return ve(this.value.nanos);default:return De(this.value)}},[Ie](e){return Ja(e)&&so(this,e)},toString(){switch(this.value._tag){case`Infinity`:return`Infinity`;case`NegativeInfinity`:return`-Infinity`;case`Nanos`:return`${this.value.nanos} nanos`;case`Millis`:return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case`Millis`:return{_id:`Duration`,_tag:`Millis`,millis:this.value.millis};case`Nanos`:return{_id:`Duration`,_tag:`Nanos`,nanos:String(this.value.nanos)};case`Infinity`:return{_id:`Duration`,_tag:`Infinity`};case`NegativeInfinity`:return{_id:`Duration`,_tag:`NegativeInfinity`}}},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},qa=e=>{let t=Object.create(Ka);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?Ua:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:Ma(e)}:e>0?Wa:Ga:e===ba?Ua:{_tag:`Nanos`,nanos:e},t},Ja=e=>pe(e,ya),Ya=qa(0),Xa=qa(1/0),Za=qa(-1/0),Qa=e=>qa(e),$a=e=>qa(e),eo=e=>qa(e*1e3),to=e=>qa(e*6e4),no=e=>io(za(e),{onMillis:i,onNanos:e=>Pa(e,1e6),onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),ro=e=>{let t=za(e);switch(t.value._tag){case`Infinity`:case`NegativeInfinity`:throw Error(`Cannot convert infinite duration to nanos`);case`Nanos`:return t.value.nanos;case`Millis`:return Ma(t.value.millis)}},io=r(2,(e,t)=>{switch(e.value._tag){case`Millis`:return t.onMillis(e.value.millis);case`Nanos`:return t.onNanos(e.value.nanos);case`Infinity`:return t.onInfinity();case`NegativeInfinity`:return(t.onNegativeInfinity??t.onInfinity)()}}),ao=r(3,(e,t,n)=>e.value._tag===`Infinity`||e.value._tag===`NegativeInfinity`||t.value._tag===`Infinity`||t.value._tag===`NegativeInfinity`?n.onInfinity(e,t):e.value._tag===`Millis`?t.value._tag===`Millis`?n.onMillis(e.value.millis,t.value.millis):n.onNanos(ro(e),t.value.nanos):n.onNanos(e.value.nanos,ro(t))),oo=(e,t)=>ao(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),so=r(2,(e,t)=>oo(e,t)),co=e=>t=>!Ei(e(t)),lo=e=>t=>t.has(e)?xi(t):Si(t),uo=r(2,(e,t)=>n=>{let r=e(n);return Ei(r)?r:t(r.success)}),fo=_i(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new _o}),po=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},mo=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},ho=e=>{try{return mo(e)}catch{return po(e)}},go=class{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,a=0;for(;a<r&&!(n[a][0]>t);a++)i=n[a];i&&i[0]===t?i[1].push(e):a===r?n.push([t,[e]]):n.splice(a,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}},_o=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?po:ho)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new vo(this.setImmediate)}},vo=class{tasks=new go;running=void 0;setImmediate;constructor(e=ho){this.setImmediate=e}scheduleTask(e,t){this.tasks.scheduleTask(e,t),this.running===void 0&&(this.running=this.setImmediate(this.afterScheduled))}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let e=this.tasks.drain();for(let t=0;t<e.length;t++){let n=e[t][1];for(let e=0;e<n.length;e++)n[e]()}}flush(){for(;this.tasks.buckets.length>0;)this.running!==void 0&&(this.running(),this.running=void 0),this.runTasks()}},yo=_i(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),bo=_i(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),xo=class extends n{constructor(e){super(),e&&Dt(this,e)}},So=e=>class extends xo{_tag=e},Co=Cn,wo=`~effect/encoding/EncodingError`,To=class extends Co(`EncodingError`){[wo]=wo},Eo=e=>Fo(typeof e==`string`?No.encode(e):e),Do=e=>{switch(e){case 16:return jo();case 32:return Mo();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=Ao();return t}}},Oo=Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),ko=()=>Math.random()*4294967296>>>0,Ao=()=>{let e=ko();return String.fromCharCode(Oo[e>>>28],Oo[e>>>24&15],Oo[e>>>20&15],Oo[e>>>16&15],Oo[e>>>12&15],Oo[e>>>8&15],Oo[e>>>4&15],Oo[e&15])},jo=()=>{let e=ko(),t=ko();return String.fromCharCode(Oo[e>>>28],Oo[e>>>24&15],Oo[e>>>20&15],Oo[e>>>16&15],Oo[e>>>12&15],Oo[e>>>8&15],Oo[e>>>4&15],Oo[e&15],Oo[t>>>28],Oo[t>>>24&15],Oo[t>>>20&15],Oo[t>>>16&15],Oo[t>>>12&15],Oo[t>>>8&15],Oo[t>>>4&15],Oo[t&15])},Mo=()=>{let e=ko(),t=ko(),n=ko(),r=ko();return String.fromCharCode(Oo[e>>>28],Oo[e>>>24&15],Oo[e>>>20&15],Oo[e>>>16&15],Oo[e>>>12&15],Oo[e>>>8&15],Oo[e>>>4&15],Oo[e&15],Oo[t>>>28],Oo[t>>>24&15],Oo[t>>>20&15],Oo[t>>>16&15],Oo[t>>>12&15],Oo[t>>>8&15],Oo[t>>>4&15],Oo[t&15],Oo[n>>>28],Oo[n>>>24&15],Oo[n>>>20&15],Oo[n>>>16&15],Oo[n>>>12&15],Oo[n>>>8&15],Oo[n>>>4&15],Oo[n&15],Oo[r>>>28],Oo[r>>>24&15],Oo[r>>>20&15],Oo[r>>>16&15],Oo[r>>>12&15],Oo[r>>>8&15],Oo[r>>>4&15],Oo[r&15])},No=new TextEncoder,Po=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),Fo=e=>{let t=``;for(let n=0;n<e.length;n++)t+=Po[e[n]];return t},Io=`effect/Tracer/ParentSpan`,Lo=class extends Lr()(Io,{fiberCached:!0}){},Ro=e=>e,zo=_i(`effect/Tracer/DisablePropagation`,{defaultValue:s}),Bo=_i(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),Vo=_i(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),Ho=`effect/Tracer`,Uo=Ro({span:e=>new Wo(e)}),Wo=class{_tag=`Span`;sampled;name;parent;annotations;links;startTime;kind;status;_traceId=void 0;_spanId=void 0;_attributes=void 0;_events=void 0;constructor(e){this.name=e.name,this.parent=e.parent,this.annotations=e.annotations,this.links=e.links,this.startTime=e.startTime,this.kind=e.kind,this.sampled=e.sampled,this.status={_tag:`Started`,startTime:e.startTime}}get traceId(){return this._traceId??=wr(this.parent)?.traceId??Do(32)}get spanId(){return this._spanId??=Do(16)}get attributes(){return this._attributes??=new Map}get events(){return this._events??=[]}end(e,t){this.status={_tag:`Ended`,endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}},Go=`effect/Metric/FiberRuntimeMetrics`,Ko=_i(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:l}),qo=_i(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:o}),Jo=_i(`effect/References/TracerTimingEnabled`,{defaultValue:o}),Yo=_i(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),Xo=_i(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),Zo=_i(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),Qo=_i(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),$o=_i(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),es=_i(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),ts=e=>{if(e?.captureStackTrace===!1||e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!=`boolean`)return e;let t=St();if(t===0&&e?.captureStackTrace!==!0)return{...e,captureStackTrace:!1};Ct(3);let n=Error();return Ct(t),{...e,captureStackTrace:rs(()=>n.stack)}},ns=e=>t=>{let n;return()=>{if(n!==void 0)return n;let r=t();if(!r)return;let i=r.split(`
6
+ `);if(i[e]!==void 0)return n=i[e].trim(),n}},rs=ns(3),is=class extends Jt{constructor(e,t=Yt){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[Ie](e){return ln(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[_e](){return Te(`${this._tag}:${this.fiberId}`)}},as=e=>new is(e),os=e=>new Kt([new is(e)]),ss=e=>e.reasons.some(sn),cs=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return xi(n.error)}return Si(e)},ls=e=>e.reasons.some(cn),us=e=>ls(e)&&ss(e)?Zt(e.reasons.map(e=>e._tag===`Fail`&&!Dn(e.error)?new rn(e.error,e.annotations):e)):e,ds=e=>ls(e)?Si(us(e)):cs(e),fs=e=>{let t=e.reasons.find(cn);return t?xi(t.defect):Si(e)},ps=e=>e.reasons.some(ln),ms=e=>{let t;for(let n=0;n<e.reasons.length;n++){let r=e.reasons[n];r._tag===`Interrupt`&&(t??=new Set,r.fiberId!==void 0&&t.add(r.fiberId))}return t?xi(t):Si(e)},hs=e=>e.reasons.length>0&&e.reasons.every(ln),gs=r(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>sn(e)?(n=!0,new Xt(t(e.error),e.annotations)):e);return n?Zt(r):e}),_s=e=>{let t;for(let n of e.reasons){if(n._tag===`Fail`)return n.error;n._tag===`Die`&&(t??=n)}return t===void 0?e.reasons.length>0?new globalThis.Error(`All fibers interrupted without error`):new globalThis.Error(`Empty cause`):t.defect},vs=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=St();i!==0&&Ct(1);try{for(let i of e.reasons)i._tag===`Interrupt`?r.push(i):n.push(ys(i._tag===`Die`?i.defect:i.error,i.annotations,t));if(n.length===0){let e=Error(`The fiber was interrupted by:`);e.name=`InterruptCause`,e.stack=ws(e,r);let i=new globalThis.Error(`All fibers interrupted without error`,{cause:e});i.name=`InterruptError`,i.stack=`${i.name}: ${i.message}`,n.push(ys(i,r[0].annotations,t))}}finally{i!==0&&Ct(i)}return n},ys=(e,t,n,r=new Set)=>{let i=typeof e,a;if(e&&i===`object`){r.add(e);let i=e.cause;if(a=new globalThis.Error(bs(e),{cause:i!==void 0&&!r.has(i)?ys(i,void 0,void 0,r):void 0}),typeof e.name==`string`&&(a.name=e.name),typeof e.stack==`string`)a.stack=Ss(e.stack,a,t);else{let e=`${a.name}: ${a.message}`;a.stack=t?Cs(e,t):e}n?.includeCauseInStack&&(a.stack=Ds(a));for(let t of Object.keys(e))t in a||(a[t]=e[t])}else{a=new globalThis.Error(e?i===`string`?e:pt(e):`Unknown error: ${e}`);let n=`${a.name}: ${a.message}`;a.stack=t?Cs(n,t):n}return a},bs=e=>{if(typeof e.message==`string`)return e.message;if(typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return pt(e)},xs=/\((.*)\)/g,Ss=(e,t,n)=>{let r=`${t.name}: ${t.message}`,i=(e.startsWith(r)?e.slice(r.length):e).split(`
7
+ `),a=[r];for(let e=1;e<i.length&&!/Generator\.next|~effect\/(?:Effect|Utils)/.test(i[e]);e++)a.push(i[e]);return n?Cs(a.join(`
8
+ `),n):a.join(`
9
+ `)},Cs=(e,t)=>{let n=t?.get(hn.key);return n&&(e=`${e}\n${Ts(n)}`),e},ws=(e,t)=>{let n=[`${e.name}: ${e.message}`];for(let e of t){let t=e.fiberId===void 0?`unknown`:`#${e.fiberId}`,r=e.annotations.get(gn.key);n.push(` at fiber (${t})`),r&&n.push(Ts(r))}return n.join(`
10
+ `)},Ts=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(xs),i=!1;for(let[,e]of r)i=!0,t.push(` at ${n.name} (${e})`);i||t.push(` at ${n.name} (${e.replace(/^at /,``)})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(`
11
+ `)},Es=e=>vs(e).map(Ds).join(`
12
+ `),Ds=e=>e.cause?`${e.stack} {\n${Os(e.cause,` `)}\n}`:e.stack,Os=(e,t)=>{let n=e.stack.split(`
13
+ `),r=`${t}[cause]: ${n[0]}`;for(let e=1,i=n.length;e<i;e++)r+=`\n${t}${n[e]}`;return e.cause&&(r+=` {\n${Os(e.cause,`${t} `)}\n${t}}`),r},ks=`~effect/Fiber`,As={_A:i,_E:i},js={id:0},Ms=(()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),Ns=()=>Ms===void 0?void 0:new Ms(`effect/Fiber`),Ps=()=>globalThis[rt],Fs=class{constructor(e,t=!0){this.setContext(e),this.id=++js.id,this.currentOpCount=0,this.interruptible=t,this._stack=[],this._observers=void 0,this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0,this._running=!1,this._deferredInterrupt=!1,this._parent=void 0,this._asyncContext=void 0,this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[ks](){return As}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return li(this.context,e)}addObserver(e){return this._exit?(e(this._exit),u):(this._observers===void 0?this._observers=[e]:this._observers.push(e),()=>this.removeObserver(e))}removeObserver(e){if(this._exit||this._observers===void 0)return;let t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)}interruptUnsafe(e,t){if(this._exit)return;let n=os(e);this.cache.stackFrame&&(n=on(n,ri(hn,this.cache.stackFrame))),t&&(n=on(n,t)),this._interruptedCause=this._interruptedCause?en(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(Js(this._interruptedCause)))}pollUnsafe(){return this._exit}evaluate(e){if(this._exit)return;if(this._asyncContext!==void 0){let t=this._asyncContext;this._asyncContext=void 0;try{return t.runInAsyncScope(this.evaluate,this,e)}finally{t.emitDestroy()}}else if(this._yielded!==void 0){let e=this._yielded;this._yielded=void 0,e()}let t=this.runLoop(e);if(t===Lt){this._asyncContext=Ns();return}let n=zs.interruptChildren&&zs.interruptChildren(this);if(n!==void 0)return this.evaluate(Lc(n,()=>t));if(this._exit=t,this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit),this._parent&&=(this._parent._children?.delete(this),void 0),this._observers!==void 0){let e=this._observers;this._observers=void 0;for(let n=0;n<e.length;n++)e[n](t)}this._stack.length=0,this._children=void 0,this.context=ti()}runLoop(e){let t=globalThis[rt];globalThis[rt]=this;let n=this._running;this._running=!0;let r=!1,i=e;this.currentOpCount=0;try{for(;;)try{this._deferredInterrupt&&(this._deferredInterrupt=!1,i=Js(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=Lc($s,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[Nt](this),i===Lt){let e=this._yielded;if(`~effect/Exit`in e)return this._deferredInterrupt=!1,this._yielded=void 0,e;if(this._deferredInterrupt){this._yielded=void 0,e();continue}return Lt}}catch(e){if(!pe(i,`~effect/Effect/evaluate`))return yn(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=yn(e)}}finally{this._running=n,globalThis[rt]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Ls;for(;;){let t=this._stack.pop();if(!t)return;let n=t[It];if(n!==void 0){let r=n.call(t,this);if(r)return r[e]=r,r}if(t[e])return t}}succeedWith(e){if(!(++this.currentOpCount&Rs-1))return mn(e);let t=this.getCont(Pt);return t?t[Pt](e,this):this.yieldWith(mn(e))}yieldWith(e){return this._yielded=e,Lt}children(){return this._children??=new Set}pipe(){return e(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&Qr(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Is(e);this.cache?.scheduler!==r.scheduler&&(this._dispatcher=void 0),this.cache=r}get currentSpanLocal(){let e=this.cache.span;return e?._tag===`Span`?e:void 0}},Is=e=>{let t=si(e,Ho);return{scheduler:li(e,fo),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:li(e,qo),span:si(e,Io),logLevel:li(e,Qo),minimumLogLevel:li(e,$o),stackFrame:li(e,Ko),runtimeMetrics:si(e,Go),maxOpsBeforeYield:li(e,yo),preventYield:li(e,bo)}},Ls={[Pt](e,t){return Js(t._interruptedCause)},[Ft](e,t){return Js(t._interruptedCause)}},Rs=32,zs={interruptChildren:void 0},Bs=e=>{if(!e.cache.stackFrame)return;let t=new Map;return t.set(gn.key,e.cache.stackFrame),Xr(t)},Vs=e=>{let t=e;return t._exit?qs(t._exit):lc(n=>t._exit?n(qs(t._exit)):Xs(e.addObserver(e=>n(qs(e)))))},Hs=e=>lc(t=>{let n=e[Symbol.iterator](),r=[],i;function a(){let e=n.next();for(;!e.done;)if(e.value._exit)r.push(e.value._exit),e=n.next();else{i=e.value.addObserver(e=>{r.push(e),a()});return}t(qs(r))}return a(),Xs(()=>i?.())}),Us=e=>{let t=e;return t._exit?t._exit:lc(n=>t._exit?n(t._exit):Xs(e.addObserver(n)))},Ws=e=>bn(t=>Gs(e,t.id)),Gs=r(e=>pe(e[0],ks),(e,t,n)=>bn(r=>{let i=Bs(r);return i=i&&n?mi(i,n):i??n,e.interruptUnsafe(t,i),Pc(Vs(e))})),Ks=e=>bn(t=>{let n=Bs(t),r=fa();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return Pc(Hs(r))}),qs=mn,Js=_n,Ys=vn,Xs=fn({op:`Sync`,[Nt](e){let t=this[Mt](),n=e.getCont(Pt);return n?n[Pt](t,e):e.yieldWith(mn(t))}}),Zs=fn({op:`Suspend`,[Nt](e){return this[Mt]()}}),Qs=ki({onFailure:Ys,onSuccess:qs}),$s=fn({op:`Yield`,[Nt](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(Xc)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}})(0),ec=qs(y()),tc=e=>Zs(()=>Js(e())),nc=e=>yn(e),rc=qs(void 0),ic=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new Od(e,`An error occurred in Effect.try`):e.catch;return Zs(()=>{try{return qs(t())}catch(e){return Ys(n(e))}})},ac=e=>sc(function(t,n){e(n).then(e=>t(qs(e)),e=>t(nc(e)))},e.length!==0),oc=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new Od(e,`An error occurred in Effect.tryPromise`):e.catch;return sc(function(e,r){let i=e=>Zs(()=>{try{return Ys(Tt(()=>n(e)))}catch(e){return nc(e)}});try{t(r).then(t=>e(qs(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},sc=function(){let e=dn({op:`Async`,[Nt](e){let t=!1,n=!1,r=this.withSignal?new AbortController:void 0,i=this.register.call(e.cache.scheduler,r=>{t||(t=!0,n?e.evaluate(r):n=r)},r?.signal);return n===!1?(n=!0,e.yieldWith(()=>{t=!0}),r===void 0&&i===void 0||e._stack.push(cc(()=>(t=!0,r?.abort(),i??Xc))),Lt):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),cc=fn({op:`AsyncFinalizer`,[It](e){e.interruptible&&(e.interruptible=!1,e._stack.push(Cu))},[Ft](e,t){return ps(e)?Lc(ql(_n(e),this[Mt]()),()=>Js(e)):Js(e)}}),lc=e=>sc(e,e.length>=2),uc=lc(u),dc=(...e)=>{if(e.length===1){let t=e[0];return Zs(()=>yc(t()))}let[t,n]=e;return Zs(()=>yc(n.call(t.self)))},fc=(e,...t)=>{let n=t.length===0?function(){return Zs(()=>yc(e.apply(this,arguments)))}:function(){let n=Zs(()=>yc(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return pc(e.length,n)},pc=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),mc=ns(2),hc=function(){let e=typeof arguments[0]==`string`,t=e?arguments[0]:`Effect.fn`,n=e?arguments[1]:void 0,r=St(),i;return r!==0&&(Ct(2),i=new globalThis.Error,Ct(r)),e?(r,...a)=>gc(t,r,i,a,e,n):gc(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},gc=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?mc(()=>n.stack):l;return pc(o.length,function(...t){let n=Zs(()=>{let e=o.apply(this,arguments);return Bt(e)?e:yc(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!Bt(n))return n;let u=St(),d;return u!==0&&(Ct(2),d=new globalThis.Error,Ct(u)),il(i?cd(e,a,e=>ld(n,e)):n,Ko,t=>({name:e,stack:d?mc(()=>d.stack):l,parent:{name:s,stack:c,parent:t}}))})},_c=(e,...t)=>pc(e.length,t.length===0?function(){return vc(()=>e.apply(this,arguments))}:function(){let n=vc(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),vc=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return qs(r.value);let i=r.value;if(i&&i._tag===`Success`)n=i.value;else{if(i&&i._tag===`Failure`)return r.value;{let n=!0;return Zs(()=>n?(n=!1,Lc(r.value,e=>yc(t,e))):Zs(()=>yc(e())))}}}}catch(e){return nc(e)}},yc=function(){let e=dn({op:`Iterator`,[Pt](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return qs(r.value);if(!Rc(r.value))return t._stack.push(this),r.value;if(r.value._tag===`Failure`)return r.value;e=r.value.value}},[Nt](e){return this[Pt](this.initial,e)}}),t=function(e,t){this.iterator=e,this.initial=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),bc=r(2,(e,t)=>new Cc(e,wc,qs(t))),xc=function(e){return e._stack.push(this),this[Mt]},Sc=dn({op:`OnSuccess`,[Nt]:xc}),Cc=function(e,t,n){this[Mt]=e,this[Pt]=t,this.payload=n};Cc.prototype=Sc;var wc=function(){return this.payload},Tc=function(e,t){return t.succeedWith(this.payload)},Ec=(()=>{let e=St();if(e===0)return!1;let t=`~effect/Effect/stackProbe`,n={[t]:function(){return Error()}};Ct(1);let r=n[t]();return Ct(e),r.stack?.includes(`[as `+t+`]`)===!0})(),Dc=function(e,t){let n=this.payload;return t.succeedWith(Ec?n(e):Tt(()=>n(e)))},Oc=function(e){let t=this.payload;return t(e)},kc=function(e){let t=this.payload;return new Cc(t(e),Tc,e)},Ac=function(e){return new Cc(this.payload,Tc,e)},jc=e=>Vc(e,b),Mc=r(2,(e,t)=>new Cc(e,Bt(t)?wc:Oc,t)),Nc=r(2,(e,t)=>new Cc(e,Bt(t)?Ac:kc,t)),Pc=e=>new Cc(e,wc,Xc),Fc=(e,t)=>bn(n=>{let r=new Set;return lu(n,()=>r.size===0?void 0:Ks(r)),lc(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=zu(n,s,!0,!0,!1);r.add(c),c.addObserver(o=>{r.delete(c);let s=!a;a=!0,i(o),s&&t?.onWinner&&t.onWinner({fiber:c,index:e,parentFiber:n})})}})}),Ic=r(e=>Bt(e[1]),(e,t,n)=>Fc([e,t],n)),Lc=r(2,(e,t)=>new Cc(e,Oc,t)),Rc=e=>e[kt]!==void 0,zc=r(2,(e,t)=>Rc(e)?e._tag===`Success`?t(e.value):e:Lc(e,t)),Bc=e=>Lc(e,i),Vc=r(2,(e,t)=>new Cc(e,Dc,t)),Hc=r(2,(e,t)=>Rc(e)?Zc(e,t):Vc(e,t)),Uc=r(2,(e,t)=>Rc(e)?Qc(e,t):Tl(e,t)),Wc=r(2,(e,t)=>Rc(e)?$c(e,t):El(e,t)),Gc=e=>_n(os(e)),Kc=e=>e._tag===`Success`,qc=e=>e._tag===`Failure`,Jc=e=>e._tag===`Failure`?xi(e.cause):Si(e),Yc=e=>e._tag===`Failure`&&ps(e.cause),Xc=mn(void 0),Zc=r(2,(e,t)=>e._tag===`Success`?mn(t(e.value)):e),Qc=r(2,(e,t)=>e._tag===`Success`?e:_n(gs(e.cause,t))),$c=r(2,(e,t)=>e._tag===`Success`?mn(t.onSuccess(e.value)):_n(gs(e.cause,t.onFailure))),el=r(2,(e,t)=>Kc(e)?t:e),tl=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?Xc:_n(Zt(t))},nl=e=>bn(t=>qs(pi(t.context,e))),rl=r(2,(e,t)=>bn(n=>{let r=n.context,i=t(r);return r===i||(n.setContext(i),lu(n,()=>{n.setContext(r)})),e})),il=r(3,(e,t,n)=>rl(e,e=>{let r=ci(e,t),i=n(r);return r===i?e:ii(e,t,i)})),al=()=>ol,ol=bn(e=>qs(e.context)),sl=e=>bn(t=>e(t.context)),cl=r(2,(e,t)=>Rc(e)?e:rl(e,mi(t))),ll=function(){return arguments.length===1?r(2,(e,t)=>ul(e,arguments[0],t)):r(3,(e,t,n)=>ul(e,t,n)).apply(this,arguments)},ul=(e,t,n)=>rl(e,ii(t,n)),dl=r(e=>Bt(e[0]),(e,t)=>Au({while:o,body:a(t?.disableYield?e:Lc(e,e=>$s)),step:u})),fl=r(2,(e,t)=>new ml(e,t.length===1?t:e=>t(e))),pl=dn({op:`OnFailure`,[Nt]:xc}),ml=function(e,t){this[Mt]=e,this[Ft]=t};ml.prototype=pl;var hl=r(3,(e,t,n)=>fl(e,e=>{let r=t(e);return Ei(r)?Js(r.failure):n(r.success,e)})),gl=r(2,(e,t)=>hl(e,ds,e=>t(e))),_l=r(2,(e,t)=>hl(e,fs,t)),vl=r(2,(e,t)=>fl(e,e=>Mc(t(e),Js(e)))),yl=r(3,(e,t,n)=>fl(e,e=>{let r=t(e);return Ei(r)?Js(e):Mc(n(r.success,e),Js(e))})),bl=r(2,(e,t)=>yl(e,cs,e=>t(e))),xl=r(e=>Bt(e[0]),(e,t,n,r)=>fl(e,e=>{let i=ds(e);return Ei(i)?Js(i.failure):t(i.success)?n(i.success):r?r(i.success):Js(e)})),Sl=r(e=>Bt(e[0]),(e,t,n,r)=>fl(e,e=>{let i=ds(e);if(Ei(i))return Js(i.failure);let a=t(i.success);return Ei(a)?r?r(a.failure):Js(e):n(a.success)})),Cl=r(e=>Bt(e[0]),(e,t,n,r)=>xl(e,Array.isArray(t)?e=>pe(e,`_tag`)&&t.includes(e._tag):me(t),n,r)),wl=r(e=>Bt(e[0]),(e,t,n)=>{let r;return Sl(e,e=>(r??=Object.keys(t),pe(e,`_tag`)&&ee(e._tag)&&r.includes(e._tag)?xi(e):Si(e)),e=>t[e._tag](e),n)}),Tl=r(2,(e,t)=>fl(e,e=>Js(gs(e,t)))),El=r(2,(e,t)=>jl(e,{onFailure:e=>Js(gs(e,t.onFailure)),onSuccess:e=>Xs(()=>t.onSuccess(e))})),Dl=e=>gl(e,nc),Ol=r(e=>Bt(e[0]),(e,t)=>{if(!t?.log)return Il(e,{onFailure:e=>rc,onSuccess:e=>rc});let n=Ld(t.log===!0?void 0:t.log);return jl(e,{onFailure(e){let r=ds(e);return Ei(r)?Js(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>rc})}),kl=e=>Ll(e,{onFailure:y,onSuccess:b}),Al=e=>Rl(e,{onFailure:Si,onSuccess:xi}),jl=r(2,(e,t)=>new Nl(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),Ml=dn({op:`OnSuccessAndFailure`,[Nt]:xc}),Nl=function(e,t,n){this[Mt]=e,this[Pt]=t,this[Ft]=n};Nl.prototype=Ml;var Pl=function(e,t){let n=this.payload;return t.succeedWith(Ec?n.onSuccess(e):Tt(()=>n.onSuccess(e)))},Fl=((e,t)=>{let n=dn({op:e,[Nt]:xc,[Pt]:Pl,[Ft]:t}),r=function(e,t){this[Mt]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=ds(e);if(Ei(n))return Js(n.failure);let r=this.payload;return t.succeedWith(Ec?r.onFailure(n.success):Tt(()=>r.onFailure(n.success)))}),Il=r(2,(e,t)=>jl(e,{onFailure:e=>{let n=ds(e);return Ei(n)?Js(n.failure):t.onFailure(n.success)},onSuccess:t.onSuccess})),Ll=r(2,(e,t)=>new Fl(e,t)),Rl=r(2,(e,t)=>{if(Rc(e)){if(e._tag===`Success`)return mn(t.onSuccess(e.value));let n=ds(e.cause);return Ei(n)?_n(n.failure):mn(t.onFailure(n.success))}return Ll(e,t)}),zl=e=>Rc(e)?mn(e):Bl(e),Bl=fn({op:`Exit`,[Nt](e){return e._stack.push(this),this[Mt]},[Pt](e,t,n){return t.succeedWith(n??mn(e))},[Ft](e,t,n){return t.succeedWith(n??_n(e))}}),Vl=`~effect/Scope`,Hl=`~effect/Scope/Closeable`,Ul=Lr(`effect/Scope`),Wl=(e,t)=>bn(n=>(Eu(n),Gl(e,t)??rc)),Gl=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&$l(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return Kl(n.finalizer,t);let r=n.finalizers;return r.size===1?Kl(r.values().next().value,t):Jl(e,r,t)},Kl=(e,t)=>{try{return e(t)}catch(e){return yn(e)}},ql=(e,t)=>Kc(e)?t:fl(t,t=>Js(us($t(e.cause,t)))),Jl=fc(function*(e,t,n){let r=[],i=[],a=Array.from(t),o=Ps();for(let t=a.length-1;t>=0;t--){let[s,c]=a[t];e.strategy===`sequential`?r.push(yield*zl(Kl(c,n))):s!==o&&i.push(zu(o,Kl(c,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*Hs(i)),yield*tl(r)}),Yl=(e,t)=>{let n=tu(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(Ql(e,n,e=>Wl(n,e)),n)},Xl=(e,t)=>Zs(()=>e.state._tag===`Closed`?t(e.state.exit):(Ql(e,{},t),rc)),Zl=(e,t)=>Xl(e,a(t)),Ql=(e,t,n)=>{if(e.state._tag===`Empty`)e.state={_tag:`Open`,finalizerKey:t,finalizer:n,finalizers:void 0};else if(e.state._tag===`Open`){let r=e.state;r.finalizer===void 0||(r.finalizers=new Map([[r.finalizerKey,r.finalizer]]),r.finalizerKey=void 0,r.finalizer=void 0),r.finalizers.set(t,n)}},$l=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=nu:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=nu))},eu=e=>tu(e,void 0),tu=(e=`sequential`,t)=>({[Hl]:Hl,[Vl]:Vl,strategy:e,parent:t,state:nu}),nu={_tag:`Empty`},ru=Ul,iu=ll(Ul),au=e=>Zs(()=>{let t=eu();return uu(e(t),e=>Zs(()=>Gl(t,e)??rc))}),ou=(e,t,n)=>sl(r=>Ou(i=>Lc(ru,a=>Nc(n?.interruptible?i(e):e,e=>Xl(a,n=>cl(t(e,n),r)))))),su=function(){let e=dn({op:`OnExit`,[Nt](e){return e._stack.push(this),this.effect},[It](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(Cu),e.interruptible=!1)},[Pt](e,t,n){n??=mn(e);let r;try{r=this.onExit(n)}catch(e){r=yn(e)}return r?Lc(r,e=>n):n},[Ft](e,t,n){n??=_n(e);let r;try{r=this.onExit(n)}catch(e){r=yn(e)}return r?Lc(ql(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),cu=(e,t,n)=>new su(e,t,n),lu=(e,t)=>{e._stack.push(new su(void 0,t,void 0))},uu=r(2,cu),du=r(2,(e,t)=>uu(e,e=>t)),fu=r(3,(e,t,n)=>uu(e,e=>{let r=t(e);return Ei(r)?rc:n(r.success,e)})),pu=r(2,(e,t)=>fu(e,Jc,t)),mu=r(3,(e,t,n)=>uu(e,e=>{if(e._tag!==`Failure`)return rc;let r=t(e.cause);return Ei(r)?rc:n(r.success,e.cause)})),hu=r(2,(e,t)=>mu(ms,t)(e)),gu=(e,t,n)=>Ou(r=>Lc(e,e=>cu(Zs(()=>r(t(e))),t=>n(e,t),!0))),_u=a(1/0),vu=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,lu(e,()=>{if(!(--t.awaiters>0||t.done))return i===t&&(i=void 0),Ws(t.fiber)}),Us(t.fiber));return[bn(o=>{if(i!==void 0)return o===i.fiber?Us(i.fiber):a(o,i);if(r!==void 0&&(n===1/0||o.getRef(md).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(md),c={fiber:new Fs(o.context),awaiters:0,done:!1};i=c;let l=a(o,c);return c.fiber.evaluate(cu(e,e=>{if(c.done=!0,i!==c||(i=void 0,Yc(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e})),c.fiber._exit??l}),Xs(()=>{i=void 0,r=void 0})]},yu=e=>Xs(()=>vu(e,_u)[0]),bu=bn(e=>Js(os(e.id))),xu=e=>bn(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(Cu)),e)),Su=fn({op:`SetInterruptible`,[It](e){if(e.interruptible=this[Mt],e._interruptedCause&&e.interruptible)return()=>Js(e._interruptedCause)}}),Cu=Su(!0),wu=Su(!1),Tu=e=>{if(e.interruptible=!0,e._stack.push(wu),e._interruptedCause)return Js(e._interruptedCause)},Eu=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(Cu))},Du=e=>bn(t=>t.interruptible?e:Tu(t)??e),Ou=e=>bn(t=>t.interruptible?(t.interruptible=!1,t._stack.push(Cu),e(Du)):e(i)),ku=(e,t)=>ge(e)?t?.mode===`result`?ju(e,Al,t):ju(e,i,t):t?.discard?t.mode===`result`?ju(Object.values(e),Al,t):ju(Object.values(e),i,t):Zs(()=>Vc(ju(Object.entries(e),([e,n])=>Vc(t?.mode===`result`?Al(n):n,t=>[e,t]),{concurrency:t?.concurrency}),Object.fromEntries)),Au=fn({op:`While`,[Pt](e,t){return this[Mt].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[Mt].body()):Xc},[Nt](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[Mt].body()):Xc}}),ju=r(e=>typeof e[1]==`function`,(e,t,n)=>Zs(()=>{let r=Nu(n?.concurrency);if(r===1)return Mu(e,t,n);let i=Ui(e),a=i.length;if(a===0)return n?.discard?rc:qs([]);let o=n?.discard?void 0:Array(a),s=Lu({f:t,out:o},i,{concurrency:r});return s?bc(s,o):qs(o)})),Mu=(e,t,n)=>Zs(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return bc(Au({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),Nu=e=>e===`unbounded`?1/0:Math.max(1,e??1),Pu=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>Lc(zl(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??rc),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!Rc(c))return r(e,i,a,o,c);let l=n(e,s,c,a);if(l)return l._tag===`Failure`?l:void 0}};return i},Fu=e=>{let t=e.onItem,n=e.step;return(e,r,i)=>{let a=0,o=i.end??r.length,s=i.concurrency,c=!1,l,u,d,f,p,m=e=>{let t=yn(e);return f=t,c=!0,u&&u.size>0?Lc(xu(Ks(Array.from(u))),()=>f??t):t},h=()=>{let i=!1;for(;!f&&a<o;a++){let o=r[a],g=p??t(e,o,a);if(Rc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=zu(l,g,!0,!0,`inherit`);if(t._exit){if(f=n(e,o,t._exit,a),f)break;continue}u.add(t);let r=a;if(t.addObserver(a=>{u.delete(t);try{if(f){if(a._tag===`Failure`){let e=a.cause.reasons.filter(e=>e._tag!==`Interrupt`);if(e.length>0){let t=Zt(e);f=_n(f._tag===`Failure`?us($t(f.cause,t)):t)}}}else{let t=n(e,o,a,r);t&&(f=t,h())}if(i){let e=h();e&&d(e)}else c&&u.size===0&&d(f??rc)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return lc(e=>{l=Ps(),u=new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):Zs(()=>(f??=Xc,Lc(u?Ks(u):rc,()=>f?._tag===`Failure`?f:rc)))})}if(c=!0,f){if(u&&u.size>0){let e=Bs(l);u.forEach(t=>t.interruptUnsafe(l.id,e));return}if(d||f._tag===`Failure`)return f}else if(d){if(u)u.size===0&&d(rc);else return Xc}};return h()}},Iu=()=>e=>Fu(e),Lu=Fu({onItem(e,t,n){return e.f(t,n)},step(e,t,n,r){if(n._tag===`Failure`)return n;e.out&&(e.out[r]=n.value)}}),Ru=r(e=>ge(e[0])&&!Bt(e[0]),(e,t,n)=>Vc(ju(e,(e,n)=>{let r=t(e,n);return typeof r==`boolean`?qs(r?b(e):y()):Vc(r,t=>t?b(e):y())},n),ha)),zu=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new Fs(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=Ns(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},Bu=e=>()=>bn(t=>t===e?rc:Ws(e)),Vu=r(e=>Bt(e[0]),(e,t,n)=>bn(r=>{let i=t.state._tag===`Closed`?new Fs(r.context):zu(r,e,n?.startImmediately,!0,n?.uninterruptible);return i._exit||(t.state._tag===`Closed`?i.interruptUnsafe(r.id,Bs(r)):(Ql(t,i,Bu(i)),i.addObserver(()=>$l(t,i)))),qs(i)})),Hu=r(e=>Bt(e[0]),(e,t)=>Lc(ru,n=>Vu(e,n,t))),Uu=e=>(t,n)=>{let r=new Fs(n?.scheduler?ii(e,fo,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal){if(n.signal.aborted)r.interruptUnsafe();else{let e=()=>r.interruptUnsafe();n.signal.addEventListener(`abort`,e,{once:!0}),r.addObserver(()=>n.signal.removeEventListener(`abort`,e))}}return n?.onFiberStart&&n.onFiberStart(r),r},Wu=r(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):($l(t,e),Ql(t,e,Bu(e)),e.addObserver(()=>$l(t,e)),e)),Gu=Uu(ti()),Ku=e=>{let t=Uu(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},qu=(e=>{let t=Ku(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw _s(e.cause);return e.value})})(ti()),Ju=e=>{let t=Uu(e);return e=>{if(Rc(e))return e;let n=new _o(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??yn(new Ed(r))}},Yu=Ju(ti()),Xu=(e=>{let t=Ju(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw _s(n.cause);return n.value}})(ti()),Zu=qs(!0),Qu=qs(!1),$u=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return Zu;if(this.scheduled===void 0)this.scheduled=this.waiters,e.currentDispatcher.scheduleTask(this.flushScheduled,0);else for(let e=0;e<this.waiters.length;e++)this.scheduled.push(this.waiters[e]);return this.waiters=[],Zu}flushScheduled=()=>{if(this.scheduled===void 0)return;let e=this.scheduled;this.scheduled=void 0;for(let t=0;t<e.length;t++)e[t](Xc)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](Xc)}open=bn(e=>this._isOpen?Qu:(this._isOpen=!0,this.scheduleUnsafe(e)));release=bn(e=>this._isOpen?Qu:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=lc(e=>this._isOpen?e(rc):(this.waiters.push(e),Xs(()=>{let t=this.waiters.indexOf(e);t===-1?this.scheduled!==void 0&&(t=this.scheduled.indexOf(e),t!==-1&&this.scheduled.splice(t,1)):this.waiters.splice(t,1)})));closeUnsafe(){return this._isOpen?(this._isOpen=!1,!0):!1}close=Xs(()=>this.closeUnsafe());whenOpen=e=>Lc(this.await,()=>e);isOpen(){return this._isOpen}},ed=e=>new $u(e??!1),td=BigInt(0),nd={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:td,endTime:td,exit:Xc},attributes:new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},rd=e=>Object.assign(Object.create(nd),e),id=e=>e?li(e.annotations,zo)?e._tag===`Span`?id(wr(e.parent)):y():b(e):y(),ad=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&li(n.annotations,zo),i=n?.parent===void 0?n?.root?y():id(e.cache.span):b(n.parent),a;if(r)a=rd({name:t,parent:i,annotations:ii(n?.annotations??ti(),zo,!0)});else{let r=e.cache.tracer??Uo,o=e.getRef(md),s=e.getRef(Jo),c=e.getRef(Yo),l=e.getRef(Xo),u=n?.level??e.getRef(Bo),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??ti(),links:d,startTime:s?o.currentTimeNanosUnsafe():td,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(S(i)&&i.value.sampled===!1?!1:!Ad(e.getRef(Vo),u))});for(let e in c)a.attribute(e,c[e]);if(n?.attributes!==void 0)for(let e in n.attributes)a.attribute(e,n.attributes[e])}return a},od=(e,t)=>(t=typeof t==`function`?t:l,il(Ko,n=>({name:e,stack:t,parent:n}))),sd=(e,t,n,r)=>Xs(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():td,t)}),cd=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return bn(t=>{let i=ad(t,e,n),a=t.getRef(md),o=t.getRef(Jo);return lu(t,e=>sd(i,e,a,o)),r(i)})},ld=ll(Lo),ud=function(){let e=Bt(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=i;return t._tag===`Span`&&(n=ts(n),r=od(t.name,n?.captureStackTrace)),e?ld(r(arguments[0]),t):e=>ld(r(e),t)},dd=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=ts(arguments[2]);if(e){let e=arguments[0];return cd(t,arguments[2],t=>ud(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>cd(t,r?r(...a):i,t=>ud(e,t,n))},fd=(...e)=>bn(t=>{let n=t.currentSpanLocal;if(n){if(e.length===1)for(let[t,r]of Object.entries(e[0]))n.attribute(t,r);else n.attribute(e[0],e[1])}return rc}),pd=bn(e=>{let t=e.currentSpanLocal;return t?qs(t):Ys(new Tn)}),md=_i(`effect/Clock`,{defaultValue:()=>new gd}),hd=2**31-1,gd=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=Xs(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return yd()}currentTimeNanos=Xs(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return vd()}monotonicTimeNanos=Xs(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(no(e))}sleepMillis(e){return e<=0?$s:Number.isFinite(e)?lc(t=>{let n=e>hd?this.sleepMillis(e-hd):rc,r=setTimeout(()=>t(n),Math.min(e,hd));return Xs(()=>clearTimeout(r))}):uc}},_d=BigInt(1e6),vd=function(){let e=globalThis.process?.hrtime;if(typeof e?.bigint==`function`)return()=>e.bigint();if(typeof performance<`u`&&typeof performance.now==`function`)return()=>BigInt(Math.round(performance.now()*1e6));let t=BigInt(0);return()=>{let e=BigInt(Date.now())*_d;return e>t&&(t=e),t}}(),yd=function(){let e=BigInt(1e9),t;return()=>{let n=vd(),r=BigInt(Date.now())*_d;if(t===void 0)t=r-n;else{let i=t+n;(r>i?r-i:i-r)>e&&(t=r-n)}return t+n}}(),bd=e=>bn(t=>e(t.getRef(md))),xd=e=>bd(t=>t.sleep(za(e))),Sd=bd(e=>e.currentTimeMillis),Cd=`~effect/Cause/IllegalArgumentError`,wd=class extends Cn(`IllegalArgumentError`){[Cd]=Cd;constructor(e){super({message:e})}},Td=`~effect/Cause/AsyncFiberError`,Ed=class extends Cn(`AsyncFiberError`){[Td]=Td;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}},Dd=`~effect/Cause/UnknownError`,Od=class extends Cn(`UnknownError`){[Dd]=Dd;constructor(e,t){super({message:t,cause:e})}},kd=_i(`effect/Console`,{defaultValue:()=>globalThis.console}),Ad=mr(fr(lr,e=>{switch(e){case`All`:return-(2**53-1);case`Fatal`:return 5e4;case`Error`:return 4e4;case`Warn`:return 3e4;case`Info`:return 2e4;case`Debug`:return 1e4;case`Trace`:return 0;case`None`:return 2**53-1}})),jd=_i(`effect/Logger/CurrentLoggers`,{defaultValue:()=>new Set([Bd,Vd])}),Md=_i(`effect/Logger/LogToStderr`,{defaultValue:s}),Nd={"~effect/Logger":{_Message:i,_Output:i},pipe(){return e(this,arguments)}},Pd=e=>{let t=Object.create(Nd);return t.log=e,t},Fd=e=>e.replace(/[\s="]/g,`_`),Id=(e,t)=>`${Fd(e[0])}=${t-e[1]}ms`,Ld=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];Wt(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?Zt(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=tn),bn(r=>{let i=e??r.cache.logLevel;if(Ad(r.cache.minimumLogLevel,i))return rc;let a=r.getRef(md),o=r.getRef(jd);if(o.size>0){let e=new Date(a.currentTimeMillisUnsafe());for(let a of o)a.log({cause:n,fiber:r,date:e,logLevel:i,message:t})}return rc})},Rd={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};Rd.gray,Rd.blue,Rd.green,Rd.yellow,Rd.red,Rd.bgBrightRed,Rd.black;var zd=e=>`${e.getHours().toString().padStart(2,`0`)}:${e.getMinutes().toString().padStart(2,`0`)}:${e.getSeconds().toString().padStart(2,`0`)}.${e.getMilliseconds().toString().padStart(3,`0`)}`,Bd=Pd(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Es(e));let o=t.getTime(),s=n.getRef(es),c=``;for(let e of s)c+=` ${Id(e,o)}`;let l=n.getRef(Zo);Object.keys(l).length>0&&a.push(l);let u=n.getRef(kd);(n.getRef(Md)?u.error:u.log)(`[${zd(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),Vd=Pd(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(md),a=t.getRef(Zo),o=t.cache.span;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))Et(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=Es(e)),o.event(vt(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)}),Hd=Wt,Ud=Gt,Wd=sn,Gd=Zt,Kd=nn,qd=an,Jd=e=>new Xt(e),Yd=e=>new rn(e),Xd=as,Zd=hs,Qd=gs,$d=$t,ef=_s,tf=ps,nf=ms,rf=Es,af=Dn,of=jn,sf=wd,cf=mn,lf=_n,uf=vn,df=Xc,ff=Kc,pf=qc,mf={"~effect/Deferred":{_A:i,_E:i},pipe(){return e(this,arguments)}},hf=function(){this.resumes=void 0,this.effect=void 0};hf.prototype=mf;var gf=()=>new hf,_f=()=>Xs(()=>gf()),vf=e=>lc(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),Xs(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),yf=r(2,(e,t)=>Xs(()=>Cf(e,t))),bf=e=>Xs(()=>xf(e)),xf=e=>e.effect!==void 0,Sf=r(2,(e,t)=>yf(e,mn(t))),Cf=(e,t)=>{if(e.effect)return!1;if(e.effect=t,e.resumes){let n=e.resumes;e.resumes=void 0;for(let e=0;e<n.length;e++)n[e](t)}return!0},wf=r(2,(e,t)=>Ou(n=>Lc(zl(n(e)),e=>yf(t,e)))),Tf=Jo,Ef=Ul,Df=eu,Of=iu,kf=Xl,Af=Zl,jf=Yl,Mf=Wl,Nf=`~effect/Layer`,Pf=`~effect/Layer/MemoMap`,Ff=(e,t)=>{let n={observers:0,deferred:gf(),scope:Df(),finalizer:r=>Zs(()=>--n.observers>0?rc:(e.map.delete(t),Mf(n.scope,r)))};return n},If=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,Ql(t,{},e.finalizer),!0),Lf={[Nf]:{_ROut:i,_E:i,_RIn:i},pipe(){return e(this,arguments)}},Rf=e=>{let t=Object.create(Lf);return t.build=e,t},zf=e=>Rf((t,n)=>{let r=jf(n);return uu(e(t,r),e=>e._tag===`Failure`?Mf(r,e):rc)}),Bf=e=>{let t=zf((n,r)=>n.getOrElseMemoize(t,r,e));return t},Vf=class{get[Pf](){return Pf}parent;constructor(e){this.parent=e}map=new Map;get(e,t){let n=this.map.get(e);return n?(If(n,t),n.deferred.effect??vf(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return Zs(()=>{let r;return cu(Zs(()=>{let i=this.get(e,t);if(i)return i;let a=Ff(this,e);return If(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&Cf(r,e)})})}},Hf=()=>new Vf,Uf=e=>new Vf(e),Wf=class e extends Lr()(`effect/Layer/CurrentMemoMap`){static forkOrCreate(t){let n=oi(t,e);return n?Uf(n):Hf()}},Gf=r(3,(e,t,n)=>ll(Vc(Zs(()=>e.build(t,n)),ii(Wf,t)),Wf,t)),Kf=r(2,(e,t)=>bn(n=>Gf(e,Wf.forkOrCreate(n.context),t))),qf=function(){return arguments.length===1?e=>Jf(ri(arguments[0],e)):Jf(ri(arguments[0],arguments[1]))},Jf=e=>Rf(a(qs(e))),Yf=function(){return arguments.length===1?e=>Xf(arguments[0],e):Xf(arguments[0],arguments[1])},Xf=(e,t)=>Zf(Vc(t,t=>ri(e,t))),Zf=e=>Bf((t,n)=>Of(e,n)),Qf=e=>Zf(bc(e,ti())),$f=(e,t,n)=>{let r=jf(n,`parallel`);return ju(e,e=>e.build(t,jf(r,`sequential`)),{concurrency:e.length}).pipe(Vc(e=>hi(...e)))},ep=(...e)=>Bf((t,n)=>$f(e,t,n)),tp=(e,t,n)=>Bf((r,i)=>Lc(Array.isArray(t)?$f(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(cl(t),Vc(e=>n(e,t))))),np=r(2,(e,t)=>tp(e,t,i)),rp=r(2,(e,t)=>tp(e,t,(e,t)=>mi(t,e))),ip=md,ap=Sd,op=`~effect/DateTime`,sp=`~effect/DateTime/TimeZone`,cp={[op]:op,pipe(){return e(this,arguments)},[gt](){return this.toString()},toJSON(){return Vp(this).toJSON()}},lp={...cp,_tag:`Utc`,[_e](){return we(this.epochMilliseconds)},[Ie](e){return hp(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Vp(this).toJSON()})`}},up={...cp,_tag:`Zoned`,[_e](){return xe(we(this.epochMilliseconds))(ve(this.zone))},[Ie](e){return hp(e)&&e._tag===`Zoned`&&this.epochMilliseconds===e.epochMilliseconds&&Le(this.zone,e.zone)},toString(){return`DateTime.Zoned(${dm(this)})`}},dp={[sp]:sp,[gt](){return this.toString()}},fp={...dp,_tag:`Named`,[_e](){return Te(`Named:${this.id}`)},[Ie](e){return _p(e)&&e._tag===`Named`&&this.id===e.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:`TimeZone`,_tag:`Named`,id:this.id}}},pp={...dp,_tag:`Offset`,[_e](){return Te(`Offset:${this.offset}`)},[Ie](e){return _p(e)&&e._tag===`Offset`&&this.offset===e.offset},toString(){return`TimeZone.Offset(${Wp(this.offset)})`},toJSON(){return{_id:`TimeZone`,_tag:`Offset`,offset:this.offset}}},mp=(e,t,n)=>{let r=Object.create(up);return r.epochMilliseconds=e,r.zone=t,Object.defineProperty(r,"partsUtc",{value:n,enumerable:!1,writable:!0}),Object.defineProperty(r,"adjustedEpochMillis",{value:void 0,enumerable:!1,writable:!0}),Object.defineProperty(r,"partsAdjusted",{value:void 0,enumerable:!1,writable:!0}),r},hp=e=>pe(e,op),gp=e=>hp(e[0]),_p=e=>pe(e,sp),vp=e=>_p(e)&&e._tag===`Named`,yp=e=>e._tag===`Utc`,bp=e=>e._tag===`Zoned`,xp=e=>{let t=Object.create(lp);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Sp=e=>{let t=e.getTime();if(Number.isNaN(t))throw new sf(`Invalid date`);return xp(t)},Cp=e=>{if(hp(e))return e;if(e instanceof Date)return Sp(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Sp(new Date(e.epochMilliseconds));let t=new Date(0);return Xp(t,e),Sp(t)}return typeof e==`string`&&!wp(e)?Sp(new Date(e+`Z`)):Sp(new Date(e))},wp=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e)||/z$|gmt$/i.test(e),Tp=-864e13+432e5,Ep=864e13-504e5,Dp=(e,t)=>{let n=t?.timeZone;if(n===void 0&&hp(e)&&bp(e))return e;let r=Cp(e);if(r.epochMilliseconds<Tp||r.epochMilliseconds>Ep)throw RangeError(`Epoch millis out of range: ${r.epochMilliseconds}`);n===void 0&&typeof e==`object`&&`timeZoneId`in e&&(n=e.timeZoneId);let i;if(n===void 0)i=Ip(new Date(r.epochMilliseconds).getTimezoneOffset()*-60*1e3);else if(_p(n))i=n;else if(typeof n==`number`)i=Ip(n);else{let e=zp(n);if(x(e))throw new sf(`Invalid time zone: ${n}`);i=e.value}return t?.adjustForTimeZone===!0?Qp(r.epochMilliseconds,i,t?.disambiguation??`compatible`):mp(r.epochMilliseconds,i,r.partsUtc)},Op=Tr(Cp),kp=Vc(ap,xp),Ap=e=>xp(e.epochMilliseconds),jp=r(gp,(e,t,n)=>n?.adjustForTimeZone===!0?Qp(e.epochMilliseconds,t,n?.disambiguation??`compatible`):mp(e.epochMilliseconds,t,e.partsUtc)),Mp=new Map,Np={day:`numeric`,month:`numeric`,year:`numeric`,era:`short`,hour:`numeric`,minute:`numeric`,second:`numeric`,timeZoneName:`longOffset`,fractionalSecondDigits:3,hourCycle:`h23`},Pp=e=>{let t=e.resolvedOptions().timeZone,n=Mp.get(t);if(n!==void 0)return n;let r=Object.create(fp);return r.id=t,r.format=e,Mp.set(t,r),r},Fp=e=>{let t=Mp.get(e);if(t!==void 0)return t;try{let t=Pp(new Intl.DateTimeFormat(`en-US`,{...Np,timeZone:e}));return Mp.set(e,t),t}catch{throw new sf(`Invalid time zone: ${e}`)}},Ip=e=>{let t=Object.create(pp);return t.offset=e,t},Lp=Tr(Fp),Rp=/^(?:GMT)?[+-]/,zp=e=>{if(Rp.test(e)){let t=em(e);return t===null?y():b(Ip(t))}return Lp(e)},Bp=r(gp,(e,t,n)=>Dr(Lp(t),t=>jp(e,t,n))),Vp=e=>new Date(e.epochMilliseconds),Hp=e=>{if(e._tag===`Utc`)return new Date(e.epochMilliseconds);if(e.zone._tag===`Offset`)return new Date(e.epochMilliseconds+e.zone.offset);if(e.adjustedEpochMilliseconds!==void 0)return new Date(e.adjustedEpochMilliseconds);let t=!1,n=e.zone.format.formatToParts(e.epochMilliseconds).filter(e=>e.type===`era`?(t=e.value===`BC`,!1):e.type!==`literal`),r=Number(n[2].value),i=new Date(0);return i.setUTCFullYear(t?1-r:r,Number(n[0].value)-1,Number(n[1].value)),i.setUTCHours(Number(n[3].value),Number(n[4].value),Number(n[5].value),n[6]?.type===`fractionalSecond`?Number(n[6].value):(e.epochMilliseconds%1e3+1e3)%1e3),e.adjustedEpochMilliseconds=i.getTime(),i},Up=e=>Hp(e).getTime()-Kp(e),Wp=e=>{let t=Math.abs(e),n=Math.floor(t/36e5),r=Math.round(t%36e5/6e4);return r===60&&(n+=1,r=0),`${e<0?`-`:`+`}${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`},Gp=e=>Wp(Up(e)),Kp=e=>e.epochMilliseconds,qp=e=>({millisecond:e.getUTCMilliseconds(),second:e.getUTCSeconds(),minute:e.getUTCMinutes(),hour:e.getUTCHours(),day:e.getUTCDate(),weekDay:e.getUTCDay(),month:e.getUTCMonth()+1,year:e.getUTCFullYear()}),Jp=e=>e._tag===`Utc`?Yp(e):(e.partsAdjusted===void 0&&(e.partsAdjusted=am(e,qp)),e.partsAdjusted),Yp=e=>(e.partsUtc===void 0&&(e.partsUtc=om(e,qp)),e.partsUtc),Xp=(e,t)=>{if((t.year!==void 0||t.month!==void 0||t.day!==void 0)&&e.setUTCFullYear(t.year??e.getUTCFullYear(),t.month===void 0?e.getUTCMonth():t.month-1,t.day??e.getUTCDate()),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hour!==void 0&&e.setUTCHours(t.hour),t.minute!==void 0&&e.setUTCMinutes(t.minute),t.second!==void 0&&e.setUTCSeconds(t.second),t.millisecond!==void 0&&e.setUTCMilliseconds(t.millisecond)},Zp=864e5,Qp=(e,t,n)=>{if(t._tag===`Offset`)return mp(e-t.offset,t);let r=tm(e-Zp,e,t),i=tm(e+Zp,e,t);if(r===i)return mp(e-r,t);let a=r<i,o=r-i;if(a){if(tm(e-i,e,t)===i)return mp(e-i,t);let a=mp(e-r,t);if(e!==Hp(a).getTime())switch(n){case`reject`:{let n=new Date(e).toISOString();throw RangeError(`Gap time: ${n} does not exist in time zone ${t.id}`)}case`earlier`:return mp(e-i,t);case`compatible`:case`later`:return a}return a}if(tm(e-r,e,t)===r){if(n===`earlier`||n===`compatible`||tm(e-r+o,e+o,t)===r)return mp(e-r,t);if(n===`reject`){let n=new Date(e).toISOString();throw RangeError(`Ambiguous time: ${n} occurs twice in time zone ${t.id}`)}}return mp(e-i,t)},$p=/([+-])(\d{2}):?(\d{2})$/,em=e=>{let t=$p.exec(e);if(t===null)return null;let[,n,r,i]=t;return(n===`+`?1:-1)*(Number(r)*60+Number(i))*60*1e3},tm=(e,t,n)=>{let r=n.format.formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??``;if(r===`GMT`)return 0;let i=em(r);return i===null?Up(mp(t,n)):i},nm=r(gp,(e,t,n)=>{if(e._tag===`Utc`){let n=Vp(e);return t(n),xp(n.getTime())}let r=Hp(e),i=new Date(r.getTime());return t(i),Qp(i.getTime(),e.zone,n?.disambiguation??`compatible`)}),rm=r(2,(e,t)=>im(e,e=>{let n=new Date(e);return t(n),n.getTime()})),im=r(2,(e,t)=>{let n=t(Kp(e));return e._tag===`Utc`?xp(n):mp(n,e.zone)}),am=r(2,(e,t)=>t(Hp(e))),om=r(2,(e,t)=>t(Vp(e))),sm=r(2,(e,t)=>{let n=rm(e,e=>{t.milliseconds&&e.setTime(e.getTime()+t.milliseconds),t.seconds&&e.setTime(e.getTime()+t.seconds*1e3),t.minutes&&e.setTime(e.getTime()+t.minutes*60*1e3),t.hours&&e.setTime(e.getTime()+t.hours*60*60*1e3)});return!t.days&&!t.weeks&&!t.months&&!t.years?n:nm(n,e=>{if(t.days&&e.setUTCDate(e.getUTCDate()+t.days),t.weeks&&e.setUTCDate(e.getUTCDate()+t.weeks*7),t.months){let n=e.getUTCDate();e.setUTCMonth(e.getUTCMonth()+t.months+1,0),n<e.getUTCDate()&&e.setUTCDate(n)}if(t.years){let n=e.getUTCDate(),r=e.getUTCMonth();e.setUTCFullYear(e.getUTCFullYear()+t.years,r+1,0),n<e.getUTCDate()&&e.setUTCDate(n)}})}),cm=r(2,(e,t)=>{let n={};for(let e in t)n[e]=-1*t[e];return sm(e,n)}),lm=e=>Vp(e).toISOString(),um=e=>{let t=Hp(e);return e._tag===`Utc`?t.toISOString():`${t.toISOString().slice(0,-1)}${Gp(e)}`},dm=e=>e.zone._tag===`Offset`?um(e):`${um(e)}[${e.zone.id}]`;globalThis.Number;var fm=lr;globalThis.String;var pm=e=>e.toLowerCase(),mm=e=>e.length>0,hm=`~effect/Cron`;function gm(e){return{tz:e.tz,and:e.and,seconds:Ui(e.seconds),minutes:Ui(e.minutes),hours:Ui(e.hours),days:Ui(e.days),months:Ui(e.months),weekdays:Ui(e.weekdays)}}var _m={[hm]:hm,[Ie](e){return vm(e)&&Im(this,e)},[_e](){return d(ve(this.tz),xe(ve(this.and)),xe(ke(Ui(this.seconds))),xe(ke(Ui(this.minutes))),xe(ke(Ui(this.hours))),xe(ke(Ui(this.days))),xe(ke(Ui(this.months))),xe(ke(Ui(this.weekdays))))},toObject(){return gm(this)},toString(){return`Cron(${ot(gm(this))})`},toJSON(){let e=gm(this);return e._id=`Cron`,e},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},vm=e=>pe(e,hm),ym=e=>{let t=Object.create(_m);t.seconds=xm.seconds(e.seconds??[0]),t.minutes=xm.minutes(e.minutes),t.hours=xm.hours(e.hours),t.days=xm.days(e.days),t.months=xm.months(e.months),t.weekdays=xm.weekdays(e.weekdays),t.and=e.and===!0,t.tz=Sr(e.tz);let n=Array.from(t.seconds),r=Array.from(t.minutes),i=Array.from(t.hours),a=Array.from(t.days),o=Array.from(t.months),s=Array.from(t.weekdays);return t.first={second:n[0]??0,minute:r[0]??0,hour:i[0]??0,day:a[0]??1,month:(o[0]??1)-1,weekday:s[0]??0},t.last={second:n[n.length-1]??59,minute:r[r.length-1]??59,hour:i[i.length-1]??23,day:a[a.length-1]??31,month:(o[o.length-1]??12)-1,weekday:s[s.length-1]??6},t.next={second:Cm.next.second(n),minute:Cm.next.minute(r),hour:Cm.next.hour(i),day:Cm.next.day(a),month:Cm.next.month(o),weekday:Cm.next.weekday(s)},t.prev={second:Cm.prev.second(n),minute:Cm.prev.minute(r),hour:Cm.prev.hour(i),day:Cm.prev.day(a),month:Cm.prev.month(o),weekday:Cm.prev.weekday(s)},t},bm=(e,t,n,r=e=>e)=>i=>{let a=[];for(let o of i){if(!Number.isInteger(o)||o<t||o>n)throw RangeError(`${e} must contain only integers between ${t} and ${n}`);a.push(r(o))}return new Set(ra(a,fm))},xm={seconds:bm(`seconds`,0,59),minutes:bm(`minutes`,0,59),hours:bm(`hours`,0,23),days:bm(`days`,1,31),months:bm(`months`,1,12),weekdays:bm(`weekdays`,0,7,e=>e===7?0:e)},Sm=(e,t)=>n=>{let r=Array(e).fill(void 0);if(n.length===0)return r;let i;if(t===`next`){let t=n.length-1;for(let a=e-1;a>=0;a--){for(;t>=0&&n[t]>=a;)i=n[t--];r[a]=i}}else{let t=0;for(let a=0;a<e;a++){for(;t<n.length&&n[t]<=a;)i=n[t++];r[a]=i}}return r},Cm={prev:{second:Sm(60,`prev`),minute:Sm(60,`prev`),hour:Sm(24,`prev`),day:Sm(32,`prev`),month:Sm(13,`prev`),weekday:Sm(7,`prev`)},next:{second:Sm(60,`next`),minute:Sm(60,`next`),hour:Sm(24,`next`),day:Sm(32,`next`),month:Sm(13,`next`),weekday:Sm(7,`next`)}},wm=`~effect/Cron/CronParseError`,Tm=class extends Co(`CronParseError`){[wm]=wm},Em=(e,t)=>{let n=e.trim().split(/\s+/).filter(mm);if(n.length!==5&&n.length!==6)return Si(new Tm({message:`Invalid number of segments in cron expression`,input:e}));n.length===5&&n.unshift(`0`);let[r,i,a,o,s,c]=n;return ji({tz:t===void 0||_p(t)?xi(t):Ci(zp(t),()=>new Tm({message:`Invalid time zone in cron expression`,input:t})),seconds:Um(r,Lm),minutes:Um(i,Rm),hours:Um(a,zm),days:Um(o,Bm),months:Um(s,Vm),weekdays:Um(c,Hm)}).pipe(Oi(({tz:e,seconds:t,minutes:n,hours:r,days:i,months:a,weekdays:o})=>ym({tz:e,seconds:t.values,minutes:n.values,hours:r.values,days:i.values,months:a.values,weekdays:o.values,and:(i.wildcard||o.wildcard)&&i.values.size!==0&&o.values.size!==0})))},Dm=(e,t)=>Ai(Em(e,t)),Om=(e,t)=>{let n=Dp(t,{timeZone:wr(e.tz)}).pipe(Jp);return e.seconds.size!==0&&!e.seconds.has(n.second)||e.minutes.size!==0&&!e.minutes.has(n.minute)||e.hours.size!==0&&!e.hours.has(n.hour)||e.months.size!==0&&!e.months.has(n.month)?!1:e.days.size===0&&e.weekdays.size===0?!0:e.and?(e.days.size===0||e.days.has(n.day))&&(e.weekdays.size===0||e.weekdays.has(n.weekDay)):e.weekdays.size===0?e.days.has(n.day):e.days.size===0?e.weekdays.has(n.weekDay):e.days.has(n.day)||e.weekdays.has(n.weekDay)},km=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+1,0)).getUTCDate(),Am=(e,t)=>Mm(e,t,`next`),jm=(e,t)=>Mm(e,t,`prev`),Mm=(e,t,n)=>{let r=wr(e.tz),i=Dp(t??new Date,{timeZone:r}),a=n===`prev`,o=a?-1:1,c=e[n],l=a?e.last:e.first,d=a?(e,t)=>e<t:(e,t)=>e>t,f=r!==void 0&&vp(r)&&r.id===`UTC`,p=f?u:e=>{let t=Dp(e,{timeZone:i.zone,adjustForTimeZone:!0,disambiguation:a?`later`:void 0}).pipe(Hp),n=e.getTime()-t.getTime();(a?n!==0:n>0)&&e.setTime(a?t.getTime():e.getTime()+n)},m=a||f?s:e=>Dp(e,{timeZone:i.zone,adjustForTimeZone:!0}).epochMilliseconds<=i.epochMilliseconds;return Vp(nm(i,t=>{let n=a&&t.getUTCMilliseconds()>0?0:o;t.setUTCSeconds(t.getUTCSeconds()+n,0);for(let n=0;n<1e4;n++){if(e.seconds.size!==0){let e=t.getUTCSeconds(),n=c.second[e];if(n===void 0){t.setUTCMinutes(t.getUTCMinutes()+o,l.second),p(t);continue}if(d(n,e)){t.setUTCSeconds(n),p(t);continue}}if(e.minutes.size!==0){let e=t.getUTCMinutes(),n=c.minute[e];if(n===void 0){t.setUTCHours(t.getUTCHours()+o,l.minute,l.second),p(t);continue}if(d(n,e)){t.setUTCMinutes(n,l.second),p(t);continue}}if(e.hours.size!==0){let e=t.getUTCHours(),n=c.hour[e];if(n===void 0){t.setUTCDate(t.getUTCDate()+o),t.setUTCHours(l.hour,l.minute,l.second),p(t);continue}if(d(n,e)){t.setUTCHours(n,l.minute,l.second),p(t);continue}}if(e.weekdays.size!==0||e.days.size!==0){if(e.and){let n=e.days.size===0||e.days.has(t.getUTCDate()),r=e.weekdays.size===0||e.weekdays.has(t.getUTCDay());if(!n||!r){t.setUTCDate(t.getUTCDate()+o),t.setUTCHours(l.hour,l.minute,l.second),p(t);continue}}else{let n=a?-1/0:1/0,r=a?-1/0:1/0;if(e.weekdays.size!==0){let e=t.getUTCDay(),r=c.weekday[e];n=r===void 0?a?l.weekday-7-e:7-e+l.weekday:r-e}if(e.days.size!==0&&n!==0){let e=t.getUTCDate(),n=c.day[e];if(n===void 0){if(a){let e=new Date(t);e.setUTCDate(0);let n=c.day[e.getUTCDate()];if(n===void 0&&(e.setUTCDate(0),n=c.day[e.getUTCDate()]),n===void 0)throw Error(`Unable to find cron date`);e.setUTCDate(n),r=(e.getTime()-t.getTime())/864e5}else r=km(t)-e+l.day}else r=!a&&n>km(t)?km(t)-e+l.day:n-e}let i=a?Math.max(n,r):Math.min(n,r);if(i!==0){t.setUTCDate(t.getUTCDate()+i),t.setUTCHours(l.hour,l.minute,l.second),p(t);continue}}}if(e.months.size!==0){let n=t.getUTCMonth()+1,r=c.month[n],i=n=>{let r=km(new Date(Date.UTC(t.getUTCFullYear(),n+1,0)));return e.days.size!==0&&e.weekdays.size===0?a?c.day[r]??r:l.day:a?r:1};if(r===void 0){t.setUTCFullYear(t.getUTCFullYear()+o),t.setUTCMonth(l.month,i(l.month)),t.setUTCHours(l.hour,l.minute,l.second),p(t);continue}if(d(r,n)){let e=r-1;t.setUTCMonth(e,i(e)),t.setUTCHours(l.hour,l.minute,l.second),p(t);continue}}if(m(t))t.setUTCSeconds(t.getUTCSeconds()+1),n=-1;else return}throw Error(`Unable to find cron date`)}))},Nm=Nn((e,t)=>Le(e.tz,t.tz)&&e.and===t.and&&Fm(e.seconds,t.seconds)&&Fm(e.minutes,t.minutes)&&Fm(e.hours,t.hours)&&Fm(e.days,t.days)&&Fm(e.months,t.months)&&Fm(e.weekdays,t.weekdays)),Pm=Ln(Fn()),Fm=(e,t)=>Pm(Ui(e),Ui(t)),Im=r(2,(e,t)=>Nm(e,t)),Lm={min:0,max:59},Rm={min:0,max:59},zm={min:0,max:23},Bm={min:1,max:31},Vm={min:1,max:12,aliases:{jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12}},Hm={min:0,max:7,normalize:e=>e===7?0:e,aliases:{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}},Um=(e,t)=>{let n=new Set,r=e.split(`,`),i=Wm(r[0]),a=i[0]===`*`,o=t.normalize??(e=>e),s=a&&(i[1]===void 0||i[1]===1)?u:e=>{n.add(o(e))};for(let n=0;n<r.length;n++){let a=r[n],[o,c]=n===0?i:Wm(a);if(c!==void 0){if(!Number.isInteger(c))return Si(new Tm({message:`Expected step value to be a positive integer`,input:e}));if(c<1)return Si(new Tm({message:`Expected step value to be greater than 0`,input:e}));if(c>t.max)return Si(new Tm({message:`Expected step value to be less than or equal to ${t.max}`,input:e}))}if(o===`*`){if(n===0&&(c===void 0||c===1))continue;for(let e=t.min;e<=t.max;e+=c??1)s(e)}else{let[n,r]=Gm(o,t.aliases);if(!Number.isInteger(n))return Si(new Tm({message:`Expected a positive integer`,input:e}));if(n<t.min||n>t.max)return Si(new Tm({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(r===void 0)for(let e=n;e<=(c===void 0?n:t.max);e+=c??1)s(e);else{if(!Number.isInteger(r))return Si(new Tm({message:`Expected a positive integer`,input:e}));if(r<t.min||r>t.max)return Si(new Tm({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(n>r)return Si(new Tm({message:`Invalid value range`,input:e}));for(let e=n;e<=r;e+=c??1)s(e)}}}return xi({values:n,wildcard:a})},Wm=e=>{let t=e.indexOf(`/`);if(t!==-1){let n=e.slice(t+1);return[e.slice(0,t),qm.test(n)?Number(n):NaN]}return[e,void 0]},Gm=(e,t)=>{let n=e.indexOf(`-`);return n===-1?[Km(e,t),void 0]:[Km(e.slice(0,n),t),Km(e.slice(n+1),t)]};function Km(e,t){return t?.[pm(e)]??(qm.test(e)?Number(e):NaN)}var qm=/^\d+$/,Jm=r(2,(e,t)=>hl(e,Qm,e=>t(e))),Ym=e=>e.reasons.some(Xm),Xm=e=>e._tag===`Fail`&&af(e.error),Zm=e=>{let t,n=!1;for(let r of e.reasons)Xm(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?Si(e):n?Si(Gd(e.reasons.filter(e=>!Xm(e)))):xi(t)},Qm=e=>{let t=Zm(e);return Ei(t)?t:xi(t.success.value)},$m=e=>{let t=Zm(e);return Ei(t)?lf(t.failure):cf(t.success.value)},eh=r(2,(e,t)=>jl(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=Zm(e);return Ei(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),th=`~effect/Schedule`,nh=_i(`effect/Schedule/CurrentMetadata`,{defaultValue:a({input:void 0,output:void 0,duration:Ya,attempt:0,start:0,now:0,elapsed:0,elapsedSincePrevious:0})}),rh={[th]:{_Out:i,_In:i,_Env:i},pipe(){return e(this,arguments)}},ih=e=>pe(e,th),ah=e=>{let t=Object.create(rh);return t.step=e,t},oh=()=>{let e=0,t,n;return(r,i)=>{n===void 0&&(n=r);let a=r-n,o=t===void 0?0:r-t;return t=r,{input:i,attempt:++e,start:n,now:r,elapsed:a,elapsedSincePrevious:o}}},sh=e=>ah(Vc(e,e=>{let t=oh();return(n,r)=>e(t(n,r))})),ch=e=>fl(e.step,e=>qs(()=>Js(e))),lh=e=>bd(t=>Vc(ch(e),e=>{let n=oh();return r=>Zs(()=>{let i=t.currentTimeMillisUnsafe();return Lc(e(i,r),([e,t])=>{let a=n(i,r);return a.output=e,a.duration=t,bc(xd(t),a)})})})),uh=(e,t=2)=>{let n=no(za(e));return sh(qs(e=>{let r=$a(n*t**(e.attempt-1));return qs([r,r])}))},dh=e=>ah(Vc(ch(e),e=>(t,n)=>eh(e(t,n),{onSuccess:e=>qs([n,e[1]]),onFailure:Js,onDone:()=>of(n)}))),fh=e=>{let t=za(e);return sh(qs(e=>qs([e.attempt-1,t])))},ph=r(2,(e,t)=>ah(Vc(ch(e),e=>{let n=oh();return(r,i)=>Lc(e(r,i),e=>{let[a,o]=e,s=t({...n(r,i),output:a,duration:o});return Lc(Bt(s)?s:qs(s),t=>t?qs(e):of(a))})}))),mh=fh(Ya),hh=(e,t,n)=>au(r=>Lc(n?.local?Gf(t,Hf(),r):Kf(t,r),t=>cl(e,t))),gh=r(e=>Bt(e[0]),(e,t,n)=>$r(t)?cl(e,t):hh(e,Array.isArray(t)?ep(...t):t,n)),_h=r(3,(e,t,n)=>Lc(lh(t),t=>{let r=nh.defaultValue(),i,a=hl(Zs(()=>ll(e,nh,r)),ds,e=>(i=e,Lc(t(e),e=>(r=e,a))));return Jm(a,e=>Tt(()=>n(i,e)))})),vh=r(2,(e,t)=>_h(e,typeof t==`function`?t(i):ih(t)?t:bh(t),Ys)),yh=dh(mh),bh=e=>{let t=e.schedule?dh(e.schedule):yh;return e.while&&(t=ph(t,({input:t})=>{let n=e.while(t);return Bt(n)?n:qs(n)})),e.until&&(t=ph(t,({input:t})=>{let n=e.until(t);return Bt(n)?Vc(n,e=>!e):qs(!n)})),e.times!==void 0&&(t=ph(t,({attempt:t})=>qs(t<=e.times))),t},xh=`~effect/MutableHashMap`,Sh={[xh]:xh,[Symbol.iterator](){return this.backing[Symbol.iterator]()},toString(){return`MutableHashMap(${ot(Array.from(this))})`},toJSON(){return{_id:`MutableHashMap`,values:_t(Array.from(this))}},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},Ch=()=>{let e=Object.create(Sh);return e.backing=new Map,e.buckets=new Map,e},wh=r(2,(e,t)=>{if(e.backing.has(t))return b(e.backing.get(t));if(Th(t))return y();let n=ve(t),r=e.buckets.get(n);return r===void 0?y():Eh(e,r,t)}),Th=e=>typeof e!=`object`&&typeof e!=`function`,Eh=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(Le(n,t[r])){let n=t[r];return b(e.backing.get(n))}return y()},Dh=r(2,(e,t)=>S(wh(e,t))),Oh=r(3,(e,t,n)=>{if(e.backing.has(t)||Th(t))return e.backing.set(t,n),e;let r=ve(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=kh(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),kh=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(Le(t,e[n]))return e[n]},Ah=r(2,(e,t)=>{if(Th(t))return e.backing.delete(t),e;let n=ve(t),r=e.buckets.get(n);if(r===void 0)return e;for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i===t||Le(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),jh=Bt,Mh=ku,Nh=ju,Ph=ac,Fh=oc,T=qs,Ih=ec,Lh=Zs,Rh=Xs,zh=rc,Bh=lc,Vh=uc,E=dc,Hh=Ys,Uh=Js,Wh=tc,Gh=nc,Kh=ic,qh=bn,Jh=Qs,D=Lc,Yh=Bc,Xh=Mc,Zh=Nc,Qh=Al,$h=kl,eg=zl,tg=Vc,ng=bc,rg=jc,ig=Pc,ag=gl,og=Cl,sg=wl,cg=fl,lg=_l,ug=Tl,dg=Dl,fg=bl,pg=vl,mg=vh,hg=Ol,gg=xd,_g=Fc,vg=Ic,yg=Ru,bg=Ll,xg=jl,Sg=al,Cg=sl,wg=gh,Tg=cl,Eg=nl,Dg=rl,Og=ll,kg=ou,Ag=gu,jg=du,Mg=pu,Ng=cu,Pg=uu,Fg=yu,Ig=bu,Lg=hu,Rg=xu,zg=Ou,Bg=dl,O=fd,Vg=pd,Hg=cd,Ug=dd,Wg=ud,Gg=Vu,Kg=Hu,qg=Gu,Jg=Uu,Yg=qu,Xg=Xu,Zg=Yu,Qg=fc,k=hc,$g=Ld(`Warn`),e_=Ld(`Error`),A=Ld(`Info`),j=Ld(`Debug`),t_=Hc,n_=Uc,r_=Wc,i_=zc,a_=_c,o_=`~effect/BigDecimal`,s_={[o_]:o_,[_e](){let e=h_(this);return xe(Te(String(e.value)),we(e.scale))},[Ie](e){return c_(e)&&b_(this,e)===0},toString(){return`BigDecimal(${S_(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},c_=e=>pe(e,o_),l_=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(s_);return n.value=e,n.scale=t,n},u_=(e,t)=>{let n=l_(e,t);return n.normalized=n,n},d_=BigInt(0),f_=BigInt(1),p_=BigInt(10),m_=u_(d_,0),h_=e=>{if(e.normalized===void 0){if(e.value===d_)e.normalized=m_;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=u_(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},g_=100,__=[f_],v_=(e,t)=>e===t?0:e<t?-1:1,y_=(e,t)=>{let n=`${e.value<d_?-e.value:e.value}`,r=`${t.value<d_?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==d_)return i<d_?-1:1;let a=Math.max(n.length,r.length);return cr(n.padEnd(a,`0`),r.padEnd(a,`0`))},b_=(e,t)=>{if(e.scale===t.scale)return v_(e.value,t.value);let n=x_(e),r=x_(t);if(n!==r)return n<r?-1:1;if(n===0)return 0;let i=e.scale-t.scale,a=Math.abs(i);if(a>g_)return n===-1?y_(t,e):y_(e,t);let o=__[a]??=p_**BigInt(a);return i>0?v_(e.value,t.value*o):v_(e.value*o,t.value)},x_=e=>e.value===d_?0:e.value<d_?-1:1,S_=e=>{let t=h_(e);if(Math.abs(t.scale)>=16)return C_(t);let n=t.value<d_,r=`${n?-t.value:t.value}`,i=t.scale>0?r.padStart(t.scale+1,`0`):r.padEnd(r.length-t.scale,`0`),a=i.length-t.scale,o=t.scale>0?`${i.slice(0,a)}.${i.slice(a)}`:i;return n?`-${o}`:o},C_=e=>{if(w_(e))return`0e+0`;let t=h_(e),n=`${t.value}`,r=t.value<d_?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},w_=e=>e.value===d_,T_=globalThis.BigInt,E_=e=>e>T_(2**53-1)||e<T_(-(2**53-1))?y():b(Number(e)),D_=BigInt(1),O_=BigInt(1e3),k_=BigInt(1024),A_=[{symbol:`B`,factor:D_,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:O_,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:O_**BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:O_**BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:O_**BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:O_**BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:O_**BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:O_**BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:O_**BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:O_**BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:O_**BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],j_=[A_[0],{symbol:`KiB`,factor:k_,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:k_**BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:k_**BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:k_**BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:k_**BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:k_**BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:k_**BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:k_**BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}];[...A_,...j_.slice(1)];var M_=E_,N_=e=>Er(M_(e),()=>Error(`ByteSize exceeds Number.MAX_SAFE_INTEGER: ${e}`)),P_=hp,F_=yp,I_=Sp,L_=Cp,R_=Op,z_=kp,B_=Ap,V_=Lp,H_=Bp,U_=Vp,W_=Hp,G_=Kp,K_=cm,q_=lm,J_=dm,Y_=e=>Z_(typeof e==`string`?Q_.encode(e):e),X_=e=>{let t=$_(e),n=t.length;if(n%4!=0)return Si(new To({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${n}`}));let r=t.indexOf(`=`);if(r!==-1&&(r<n-2||r===n-2&&t[n-1]!==`=`))return Si(new To({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),r=new Uint8Array(n/4*3-e);for(let e=0,i=0;e<n;e+=4,i+=3){let n=nv(t.charCodeAt(e))<<18|nv(t.charCodeAt(e+1))<<12|nv(t.charCodeAt(e+2))<<6|nv(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return xi(r)}catch(e){return Si(new To({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},Z_=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=ev[e[r-2]>>2],n+=ev[(e[r-2]&3)<<4|e[r-1]>>4],n+=ev[(e[r-1]&15)<<2|e[r]>>6],n+=ev[e[r]&63];return r===t+1&&(n+=ev[e[r-2]>>2],n+=ev[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=ev[e[r-2]>>2],n+=ev[(e[r-2]&3)<<4|e[r-1]>>4],n+=ev[(e[r-1]&15)<<2],n+=`=`),n},Q_=new TextEncoder,$_=e=>e.replace(/[\n\r]/g,``),ev=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,tv=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)tv[ev.charCodeAt(e)]=e;tv[61]=0;var nv=e=>{if(e>=tv.length||tv[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return tv[e]},rv=`~effect/http/Cookies`,iv=`~effect/http/Cookies/Cookie`,av={[rv]:rv,...yt,toJSON(){return{_id:`effect/Cookies`,cookies:Ri(this.cookies,e=>e.toJSON())}},pipe(){return e(this,arguments)}},ov=e=>{let t=Object.create(av);return t.cookies=e,t},sv=e=>{let t={};for(let n of e)Et(t,n.name,n);return ov(t)},cv=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=lv(e.trim());t&&n.push(t)}return sv(n)};function lv(e){let t=e.split(`;`).map(e=>e.trim()).filter(e=>e!==``);if(t.length===0)return;let n=t[0].indexOf(`=`);if(n===-1)return;let r=t[0].slice(0,n);if(!uv.test(r))return;let i=t[0].slice(n+1),a=fv(i);if(t.length===1)return Object.assign(Object.create(dv),{name:r,value:a,valueEncoded:i});let o={};for(let e=1;e<t.length;e++){let n=t[e],r=n.indexOf(`=`),i=r===-1?n:n.slice(0,r).trim(),a=r===-1?void 0:n.slice(r+1).trim();switch(i.toLowerCase()){case`domain`:{if(a===void 0)break;let e=a.trim().replace(/^\./,``);e&&(o.domain=e);break}case`expires`:{if(a===void 0)break;let e=new Date(a);isNaN(e.getTime())||(o.expires=e);break}case`max-age`:{if(a===void 0)break;let e=parseInt(a,10);isNaN(e)||(o.maxAge=eo(e));break}case`path`:if(a===void 0)break;a[0]===`/`&&(o.path=a);break;case`priority`:if(a===void 0)break;switch(a.toLowerCase()){case`low`:o.priority=`low`;break;case`medium`:o.priority=`medium`;break;case`high`:o.priority=`high`}break;case`httponly`:o.httpOnly=!0;break;case`secure`:o.secure=!0;break;case`partitioned`:o.partitioned=!0;break;case`samesite`:if(a===void 0)break;switch(a.toLowerCase()){case`lax`:o.sameSite=`lax`;break;case`strict`:o.sameSite=`strict`;break;case`none`:o.sameSite=`none`}}}return Object.assign(Object.create(dv),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}var uv=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,dv={[iv]:iv,...yt,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}},fv=e=>{try{return decodeURIComponent(e)}catch{return e}},pv=new WeakMap,mv=e=>{if(pv.has(e))return pv.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},hv=`~effect/Redacted`,gv=e=>pe(e,hv),_v=(e,t)=>{let n=Object.create(vv);return t?.label&&(n.label=t.label),pv.set(n,e),n},vv={[hv]:{_A:e=>e},label:void 0,...Rt,toJSON(){return this.toString()},toString(){return`<redacted${ee(this.label)?`:`+this.label:``}>`},[_e](){return ve(pv.get(this))},[Ie](e){return gv(e)&&Le(pv.get(this),pv.get(e))}},yv=mv,bv=e=>Nn((t,n)=>e(yv(t),yv(n))),xv=Symbol.for(`~effect/http/Headers`),Sv=Object.defineProperties(Object.create(null),{[xv]:{value:xv},[$e]:{value(e){return Mv(this,li(e,Pv))}},toJSON:{value(){return tt(this)}},[Ie]:{value(e){return wv(this,e)}},[_e]:{value(){return De(this)}},toString:{value:yt.toString},[gt]:{value:yt[gt]}}),Cv=e=>Object.assign(Object.create(Sv),e),wv=Vi(Fn()),Tv=Object.create(Sv),Ev=e=>{if(e===void 0)return Tv;if(Symbol.iterator in e){let t=Object.create(Sv);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(Sv);for(let[n,r]of Object.entries(e))Array.isArray(r)?t[n.toLowerCase()]=r.join(`, `):r!==void 0&&(t[n.toLowerCase()]=r);return t},Dv=e=>Object.setPrototypeOf(e,Sv),Ov=r(3,(e,t,n)=>{let r=Cv(e);return r[t.toLowerCase()]=n,r}),kv=r(2,(e,t)=>Cv({...e,...Ev(t)})),Av=r(2,(e,t)=>{let n=Cv(e);return Object.assign(n,t),n}),jv=r(2,(e,t)=>{let n=Cv(e);return delete n[t.toLowerCase()],n}),Mv=r(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=_v(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=_v(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),Nv=(e,t)=>{let n=e.toLowerCase();for(let r=0;r<t.length;r++){let i=t[r];if(typeof i==`string`){if(i.toLowerCase()===n)return!0}else if(e.search(i)!==-1)return!0}return!1},Pv=_i(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),Fv=e=>typeof e==`string`?e:yv(e),Iv=`~effect/http/UrlParams`,Lv=e=>pe(e,Iv),Rv={...Rt,[Iv]:Iv,[Symbol.iterator](){return this.params[Symbol.iterator]()},[$e](e){return{_id:`UrlParams`,params:Object.fromEntries(Zv(this,li(e,sy)))}},toJSON(){return tt(this)},[Ie](e){return Uv(this,e)},[_e](){return ke(this.params.flat())}},zv=e=>{let t=Object.create(Rv);return t.params=e,t},Bv=e=>{if(Lv(e))return e;let t=Vv(e),n=[];for(let e=0;e<t.length;e++)if(Array.isArray(t[e][0])){let[r,i]=t[e];n.push([`${r[0]}[${r.slice(1).join(`][`)}]`,i])}else n.push(t[e]);return zv(n)},Vv=e=>{let t=typeof e[Symbol.iterator]==`function`?Ui(e):Object.entries(e),n=[];for(let[e,r]of t)if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]!==void 0&&n.push([e,Hv(r[t])]);else if(typeof r==`object`&&r&&!gv(r)){let t=Vv(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,Hv(r)]);return n},Hv=e=>gv(e)?e:String(e),Uv=Nn((e,t)=>Wv(e.params,t.params)),Wv=ga(Ni([Fn(),Qe()])),Gv=zv([]),Kv=r(2,(e,t)=>zv(t(e.params))),qv=r(2,(e,t)=>{let n=Bv(t).params.slice(),r=new Set;for(let e=0;e<n.length;e++)r.add(n[e][0]);for(let t=0;t<e.params.length;t++)r.has(e.params[t][0])||n.push(e.params[t]);return zv(n)}),Jv=r(2,(e,t)=>Kv(e,qi(Bv(t).params))),Yv=e=>new URLSearchParams(Bv(e).params.map(([e,t])=>[e,Fv(t)])).toString(),Xv=e=>{let t={};for(let[n,r]of e.params){let e=Fv(r);if(!Object.hasOwn(t,n))Et(t,n,e);else{let r=t[n];typeof r==`string`?Et(t,n,[r,e]):r.push(e)}}return t},Zv=r(2,(e,t)=>{let n=Array.isArray(t)?t:[t];return e.params.map(([e,t])=>[e,typeof t==`string`&&Qv(e,n)?_v(t):t])}),Qv=Nv,$v=(e,t=oy())=>{e.includes(`@`)&&(e=ry(e));let n=e.indexOf(`?`);if(n===-1||t.length===0)return e;let r=e.indexOf(`#`);if(r!==-1&&r<n)return e;let i=r===-1?e.length:r;return e.slice(0,n+1)+iy(e.slice(n+1,i),t)+e.slice(i)},ey=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i,ty=/[/\\?#]/,ny=/[/?#]/,ry=e=>{let t=``,n=[];for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i===9||i===10||i===13||t===``&&i<=32||(t+=e[r],n.push(r))}let r=ey.exec(t);if(r===null)return e;let i=r[0].length,a=r[1]!==void 0||!r[0].includes(`:`),o=t.slice(i),s=o.search(a?ty:ny),c=(s===-1?o:o.slice(0,s)).lastIndexOf(`@`);return c===-1?e:e.slice(0,n[i])+`REDACTED:REDACTED`+e.slice(n[i+c])},iy=(e,t)=>e.split(`&`).map(e=>{let n=e.indexOf(`=`);return n!==-1&&Qv(ay(e.slice(0,n)),t)?e.slice(0,n+1)+`REDACTED`:e}).join(`&`),ay=e=>{if(!e.includes(`%`)&&!e.includes(`+`))return e;try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return e}},oy=()=>li(globalThis[`~effect/Fiber/currentFiber`]?.context??ti(),sy),sy=_i(`effect/http/UrlParams/CurrentRedactedNames`,{defaultValue:()=>[`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]});function cy(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function ly(e){return t=>cy(t)?.[e]}var uy=`~structural`,dy=`~sentinels`,fy=`~constructor`,py=f(e=>{let t=cy(e)?.identifier;return typeof t==`string`?t:e.getExpected(py)}),my=Symbol(),hy=cf,gy=hy(my),_y=hy(my),vy=e=>e===my?y():b(e),yy=e=>e._tag===`None`?gy:hy(e.value),by=`~effect/SchemaIssue/Issue`;function xy(e){return pe(e,by)&&e[by]===by}function Sy(e){return Object.hasOwn(e,`input`)}var Cy=class{[by]=by;constructor(e,t){t?.reportInput===!0&&e!==my&&(this.input=e)}},wy=class extends Cy{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},Ty=class extends Cy{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},Ey=class extends Cy{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},Dy=class extends Cy{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},Oy=class extends Cy{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},ky=class extends Cy{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},Ay=class extends Cy{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},jy=class extends Cy{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function My(e,t,n,r,i){return new ky(e,[new Ey([t],n)],r,i)}var Ny=class extends Cy{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},Py=class extends Cy{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},Fy=class extends Cy{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function Iy(e,t,n){if(xy(e))return e;if(typeof e==`string`)return new jy({message:e},t,n);let r=typeof e.issue==`string`?new jy({message:e.issue},t,n):e.issue;return new Ey(e.path,r)}function Ly(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new jy(void 0,t,n):Iy(e,t,n)}function Ry(e,t,n,r){return Array.isArray(t)?Yi(t)?t.length===1?Iy(t[0],n,r):new ky(e,ma(t,e=>Iy(e,n,r)),n,r):void 0:Ly(t,n,r)}var zy=e=>{let t=Zy(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return Wy(py(e.ast),e);case`InvalidValue`:{let t=Uy(e);if(t!==void 0)return Wy(t,e);let n=Hy(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=Hy(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=Hy(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},By=e=>Zy(e)??Zy(e.issue);function Vy(e){return t=>({issues:Ky(t,[],e?.leafHook??zy,e?.checkHook??By)})}function Hy(e){return Sy(e)?ot(e.input):void 0}function Uy(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function Wy(e,t){let n=Hy(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function Gy(e,t){let n=t(e);if(n!==void 0||e.issue._tag!==`InvalidValue`)return n;let r=Uy(e.issue);return r===void 0?Wy(qy(e.filter),e):Wy(r,e.issue)}function Ky(e,t,n,r,i){switch(e._tag){case`Filter`:return Ky(e.issue,t,n,r,i??Gy(e,r));case`Encoding`:return Ky(e.issue,t,n,r,i);case`Pointer`:return Ky(e.issue,[...t,...e.path],n,r,i);case`Composite`:case`AnyOf`:return e._tag===`Composite`||e.issues.length>0?e.issues.flatMap(e=>Ky(e,t,n,r,i)):[{path:t,message:i??Zy(e)??Wy(py(e.ast),e)}];default:return[{path:t,message:i??n(e)}]}}function qy(e){let t=e.annotations?.expected;if(typeof t==`string`)return t;switch(e._tag){case`Filter`:return`<filter>`;case`FilterGroup`:return e.checks.map(e=>qy(e)).join(` & `)}}function Jy(){return e=>Xy(e,``)}var Yy=Jy();function Xy(e,t,n){let r;switch(e._tag){case`Filter`:return Xy(e.issue,t,n??Gy(e,By));case`Encoding`:return Xy(e.issue,t,n);case`Pointer`:return Xy(e.issue,t+lt(e.path),n);case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>Xy(e,t,n)).join(`
14
+ `);r=n??Zy(e)??Wy(py(e.ast),e);break;default:r=n??zy(e)}return t?`${r}\n at ${t}`:r}function Zy(e){if(e._tag===`Pointer`||e._tag===`Composite`)return;if(e._tag===`Encoding`)return Zy(e.issue);let t=(e._tag===`Filter`?e.filter.annotations:`annotations`in e?e.annotations:e.ast.annotations)?.[e._tag===`MissingKey`?`messageMissingKey`:e._tag===`UnexpectedKey`?`messageUnexpectedKey`:`message`];if(typeof t==`string`)return t}function Qy(e){let t;for(let n of e.reasons){if(!Wd(n)||!xy(n.error))return;t??=n.error}return t}function $y(e,t){let n=Qy(e);if(n===void 0)throw Error(t,{cause:e});return n}var eb=e=>Object.assign(Object.create(t),e);function tb(e){return lb((t,n)=>Hh(e(t,n)))}function nb(e){return tb((t,n)=>{let r={message:e(t)};return S(t)?new Ny(r,t.value,n):new Ny(r)})}var rb=nb(()=>`Encoding is not supported`),ib=eb({_tag:`Passthrough`});function ab(){return ib}function ob(e){return eb({_tag:`Transform`,transform:e})}function sb(e){return eb({_tag:`TransformEffect`,transform:e})}function cb(e){return eb({_tag:`TransformOptional`,transform:e})}function lb(e){return eb({_tag:`TransformOptionalEffect`,transform:e})}function ub(){return cb(()=>y())}function db(e){return lb(t=>{let n=Mr(t,se);return S(n)?T(n):t_(e,b)})}function fb(){return ob(globalThis.String)}function pb(){return ob(globalThis.Number)}function mb(){return sb((e,t)=>{try{return T(globalThis.BigInt(e))}catch{return Hh(new jy({expected:`a value that can be converted to a bigint`},e,t))}})}function hb(e){return sb((t,n)=>Kh({try:()=>JSON.parse(t,e?.reviver),catch:()=>new jy({expected:`a valid JSON string`},t,n)}))}function gb(e){return sb((t,n)=>Kh({try:()=>{let n=JSON.stringify(t,e?.replacer,e?.space);if(n===void 0)throw TypeError(`Value cannot be represented as JSON`);return n},catch:()=>new jy({expected:`a JSON-serializable value`},t,n)}))}function _b(){return ob(Y_)}function vb(){return sb((e,t)=>n_(Jh(X_(e)),()=>new jy({expected:`a valid Base64 string`},e,t)))}var yb=class extends n{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new yb(this.encode,this.decode)}},bb=`~effect/SchemaTransformation/Transformation`,xb=class extends n{[bb]=bb;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new xb(this.encode,this.decode)}};function Sb(e){return pe(e,bb)&&e[bb]===bb}var Cb=e=>Sb(e)?e:new xb(e.decode,e.encode);function wb(e){return new xb(sb(e.decode),sb(e.encode))}function Tb(e){return new xb(ob(e.decode),ob(e.encode))}function Eb(e){return new xb(cb(e.decode),cb(e.encode))}var Db=new xb(ab(),ab());function Ob(){return Db}var kb=new xb(pb(),fb()),Ab=new xb(mb(),fb()),jb=e=>de(e)&&typeof e.message==`string`,Mb=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:Ib(e.cause)}):Error(e.message);return typeof e.name==`string`&&e.name!==`Error`&&(t.name=e.name),typeof e.stack==`string`&&(t.stack=e.stack),t},Nb=e=>{try{let t=pt(e);return t===void 0?ot(e):JSON.parse(t)}catch{return ot(e)}},Pb=(e,t,n)=>{let r={name:e.name,message:typeof e.message==`string`?e.message:``};return t?.includeStack&&typeof e.stack==`string`&&(r.stack=e.stack),!t?.excludeCause&&e.cause!==void 0&&(r.cause=n(e.cause)),r},Fb=e=>{let t=new WeakSet,n=r=>{if(he(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=Pb(r,e,n);return t.delete(r),i}return Nb(r)};return n},Ib=e=>jb(e)?Mb(e):e,Lb=e=>Tb({decode:Ib,encode:Fb(e)});function Rb(){return Tb({decode:Cr,encode:w})}function zb(){return Eb({decode:b,encode:kr})}var Bb=wb({decode:(e,t)=>URL.canParse(e)?T(new URL(e)):Hh(new jy({expected:`a valid URL string`},e,t)),encode:e=>T(e.href)}),Vb=new xb(vb(),_b());function Hb(e){return new xb(hb(e??{}),gb(e))}function Ub(e){return t=>t._tag===e}var Wb=Ub(`Declaration`),Gb=Ub(`Null`),Kb=Ub(`Void`),qb=Ub(`Never`),Jb=Ub(`Literal`),Yb=Ub(`UniqueSymbol`),Xb=Ub(`Arrays`),Zb=Ub(`Objects`),Qb=Ub(`Union`),$b=Ub(`Suspend`),ex=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},tx={},nx=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},rx=`~effect/Schema`,ix=class{[rx]=rx;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}},ax=class extends ix{_tag=`Declaration`;typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,a,o,s){super(n,r,i,a),this.typeParameters=e,this.run=t,this.encodingChecks=o,this.encodingRun=s}getParser(){let e;return(t,n)=>{if(t===my)return gy;e??=this.run(this.typeParameters);try{return e(t,this,n)}catch(e){return Gh(e)}}}_rebuild(e,t,n,r,i){let a=AS(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new ax(a,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:`<Declaration>`}},ox=new class extends ix{_tag=`Null`;getParser(){return JS(this,null)}getExpected(){return`null`}},sx=class extends ix{_tag=`Undefined`;getParser(){return JS(this,void 0)}toCodecJson(){return vS(this,[cx])}getExpected(){return`undefined`}},cx=new ex(ox,new xb(ob(()=>void 0),ob(()=>null))),lx=new sx,ux=new class extends ix{_tag=`Void`;getParser(){let e=hy(void 0);return t=>t===my?gy:e}toCodecJson(){return vS(this,[cx])}getExpected(){return`void`}},dx=new class extends ix{_tag=`Never`;getParser(){return YS(this,le)}getExpected(){return`never`}},fx=new class extends ix{_tag=`Unknown`;getParser(){return YS(this,ue)}getExpected(){return`unknown`}},px=class extends ix{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${ot(e)}`);this.literal=e}getParser(){return JS(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?mx(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:mx(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function mx(e){let t=globalThis.String(e.literal);return vS(e,[new ex(new px(t),new xb(ob(()=>e.literal),ob(()=>t)))])}var hx=new class extends ix{_tag=`String`;getParser(){return YS(this,ee)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&sC(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},gx=class extends ix{_tag=`Number`;getParser(){return YS(this,te)}matchKey(e,t){return this._match($S,e,t)}matchPart(e,t){return this._match(QS,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:sC(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(_x(this.checks,`effect/schema/isFinite`)||_x(this.checks,`effect/schema/isInt`))?this:vS(this,[pS])}toCodecStringTree(){return this.toCodecJson()===this?vS(this,[nC]):vS(this,[rC])}getExpected(){return`number`}};function _x(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&_x(e.checks,t))}var vx=new gx,yx=new class extends ix{_tag=`Boolean`;getParser(){return YS(this,ne)}getExpected(){return`boolean`}},bx=new class extends ix{_tag=`BigInt`;getParser(){return YS(this,re)}matchPart(e,t){if(!iC.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:sC(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return vS(this,[oC])}getExpected(){return`bigint`}},xx=class extends ix{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(zS(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(zS(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}let c=e=>{let{input:t,len:r,options:i}=e;if(n.rest.length===0&&r>a)for(let o=a;o<r;o++){let r=new Oy(n,t[o],i),a=new Ey([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Hh(new ky(n,[a],t,i))}return e.issues?Hh(new ky(n,e.issues,t,i)):hy(e.output)},l=(e,t)=>{let r=e.length,i={ast:n,getParser:s,input:e,len:r,tailThreshold:Math.max(a,r-o),output:[],issues:void 0,options:t},u=n.rest.length===0?a:Math.max(r,a+o),d=t.concurrency===void 0?1:Nu(t.concurrency),f=d===1?wx(i,e,0,u):Tx(i,e,{concurrency:d,end:u});if(!f)return c(i);if(Rc(f))return i_(f,()=>c(i));let p=!0;return Lh(()=>p?(p=!1,D(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===my)return gy;try{return Array.isArray(e)?(r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)}))),l(e,a)):Hh(new Ay(n,e,a))}catch(e){return Gh(e)}}}_rebuild(e,t,n){let r=AS(this.elements,e),i=AS(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new xx(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return`array`}};function Sx(e,t,n,r){if(n._tag===`Failure`)return Ex(e,e.ast,r,n);let i=n===_y?t:n[Mt];if(i!==my)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(zS(t.ast))return;let n=new Ey([r],new Dy(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return uf(new ky(e.ast,[n],e.input,e.options))}}var Cx={onItem(e,t,n){let r=n<e.len?t:my;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Sx},wx=Pu()(Cx),Tx=Iu()(Cx),Ex=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Qy(r.cause);if(i===void 0)return lf(Qd(r.cause,r=>new ky(t,[new Ey([n],r)],e.input,e.options)));let a=new Ey([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return uf(new ky(t,[a],e.input,e.options))},Dx=`[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?`;function Ox(e,t,n=tx){let r,i;function a(t){switch(t._tag){case`String`:case`TemplateLiteral`:return(r??=Object.keys(e)).filter(e=>t.matchPart(e,n)!==void 0);case`Number`:return(r??=Object.keys(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Symbol`:return(i??=Object.getOwnPropertySymbols(e)).filter(r=>Object.prototype.propertyIsEnumerable.call(e,r)&&t.matchKey(r,n)!==void 0);case`Union`:return[...new Set(t.types.flatMap(a))];default:return[]}}return a(XS(WS(t)))}var kx=class{name;type;constructor(e,t){this.name=e,this.type=t}};function Ax(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(Ax);default:return!1}}function jx(e){let t=bS(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(jx);default:return!1}}function Mx(e){return Ax(e)&&jx(e)}var Nx=class{parameter;type;constructor(e,t){if(!Mx(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,zS(t)&&!qS(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},Px=class extends ix{_tag=`Objects`;propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=o}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return YS(n,ce);let a,o,s=()=>(a||(a=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),o=i?n.indexSignatures.map(n=>({is:n,parserKey:e(XS(n.parameter)),parserValue:t(n.type)})):void 0),a),c=()=>{let e=new Set(n.propertySignatures.map(e=>typeof e.name==`number`?globalThis.String(e.name):e.name)),t=(t,i,a,o,s)=>{if(s._tag===`Failure`)return Ex(t,n,i,s)??df;let c=s===_y?o:s[Mt];if(a!==my&&c!==my){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return df;Et(t.out,a,c)}return df},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!Rc(t))return D(eg(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return Ex(e,n,r,a)??df;let o=a===_y?r:a[Mt],s=e.input[r],l=i.parserValue(s,e.options);return Rc(l)?t(e,r,o,s,l):D(eg(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return Rc(a)?t(e,n,n,i,a):D(eg(a),r=>t(e,n,n,i,r))},u=i?Iu()({onItem:(e,[t,n])=>n.is.parameter===hx?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return a_(function*(t,d){if(t===my)return my;if(typeof t!=`object`||!t||Array.isArray(t))return yield*Hh(new Ay(n,t,d));s();let f=t,p={},m={ast:n,input:f,out:p,issues:void 0,options:d},h=d.errors===`all`,g=d.onExcessProperty===`error`,_=d.concurrency===void 0?1:Nu(d.concurrency),v=i&&g?n.indexSignatures.map(e=>Ox(f,e.parameter,d)):void 0;if(g){let r=v?new Set(e):e;if(v)for(let e of v)for(let t of e)r.add(t);let i=Reflect.ownKeys(f);for(let e=0;e<i.length;e++){let a=i[e];if(!r.has(a)&&Object.prototype.propertyIsEnumerable.call(f,a)){let e=new Oy(n,f[a],d),r=new Ey([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*Hh(new ky(n,[r],t,d))}}}if(r){let e=_===1?Lx(m,a):Rx(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===hx?l:c,r=v?.[e]??(t.is.parameter===hx?Object.keys(f):Ox(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!Rc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=fa();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===hx?Object.keys(f):Ox(f,n.is.parameter,d));for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=u(m,e,{concurrency:_});t&&(yield*t)}return m.issues?yield*Hh(new ky(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return D(eg(n),n=>{let i={...e,out:{...e.out}},o=Fx(i,r,n);if(o)return o;let s=()=>hy(i.out),c=Lx(i,a.slice(t+1));return c?i_(c,s):s()})};return(e,t)=>{if(e===my)return gy;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Nu(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return Hh(new Ay(n,e,t));let r=s(),i=e,a={},o={ast:n,input:i,out:a,issues:void 0,options:t};try{for(let e=0;e<r.length;e++){let n=r[e],s=n.name,c=Zx(i,s),l=c?i[s]:my,d=n.parser(l,t);if(!Rc(d))return u(o,e,d);if(d===_y){c&&Et(a,s,l);continue}let f=Fx(o,n,d);if(f)return f}}catch(e){return Gh(e)}return hy(a)}}_rebuild(e,t,n,r){let i=AS(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new kx(t.name,n)}),a=AS(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new Nx(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new Px(i,a,this.annotations,n,void 0,this.context,r)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}};function Fx(e,t,n){if(n._tag===`Failure`)return Ex(e,e.ast,t.name,n);if(n===_y)return;let r=n[Mt];if(r!==my)Et(e.out,t.name,r);else if(delete e.out[t.name],!zS(t.type)){let n=new Ey([t.name],new Dy(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return uf(new ky(e.ast,[n],e.input,e.options))}}var Ix={onItem(e,t){if(!Zx(e.input,t.name))return t.parser(my,e.options);let n=e.input[t.name];return Et(e.out,t.name,n),t.parser(n,e.options)},step:Fx},Lx=Pu()(Ix),Rx=Iu()(Ix);function zx(e,t){return e?t?[...e,...t]:e:t}function Bx(e,t,n){return new Px(Reflect.ownKeys(e).map(t=>new kx(t,e[t].ast)),[],n,t)}function Vx(e){return e.ast}function Hx(e,t=void 0){return new xx(!1,e.map(e=>e.ast),[],void 0,t)}function Ux(e,t,n){return new $x(e.map(Vx),t,void 0,n)}function Wx(e,t){if(e.encoding||t.some(e=>e.encoding))throw Error(`StructWithRest does not support encodings`);let n=e.propertySignatures,r=e.indexSignatures,i=e.checks;for(let e of t){for(let t of e.propertySignatures)if(n.some(e=>e.name===t.name))throw Error(`Duplicate identifier: ${JSON.stringify(t.name)}. ts(2300)`);n=n.concat(e.propertySignatures),r=r.concat(e.indexSignatures),i=zx(i,e.checks)}return new Px(n,r,void 0,i)}var Gx=p(e=>{for(;;){if($b(e))return fx;let t=e.encoding;if(!t)return e.recur?.(Gx,i)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==i))return fx;e=t[t.length-1].to}});function Kx(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(Kx)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function qx(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[dy];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!zS(t)){if(Jb(t))return[{key:e.name,literal:t.literal}];if(Yb(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!zS(e)){if(Jb(e))return[{key:t,literal:e.literal}];if(Yb(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>qx(Gx(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return qx(e.thunk())}}var Jx=new WeakMap,Yx=Object.freeze([]),Xx=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Zx=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function Qx(e){let t=Jx.get(e);if(t)return t;let n,r=0,i,a,o=!0,s=[];for(let t=0;t<e.length;t++){let c=e[t],l=Gx(c);if(qb(l))continue;if(Jb(l)||Yb(l)){a??=new Map;let e=Jb(l)?l.literal:l.symbol;s[t]=e;let n=a.get(e);n||a.set(e,n=[]),n.push(t)}else o=!1;let u=qx(l);if(u.length){n??=new Map,r++;for(let{key:e,literal:r}of u){let i=n.get(e);i||n.set(e,i=[new Map,new Set]),i[1].add(t);let a=i[0].get(r);a||i[0].set(r,a=new Set),a.add(t)}}else{i??={};let e=Kx(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Yx);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Yx;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(fe(e)){let n=Zx(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Yx;if(t)return o}return Yx}}else if(n){let e;for(let t of n)(!e||t[1][0].size>e[1][0].size)&&t[1][1].size===r&&(e=t);t=(t,r)=>{let a=Xx(t);if(!fe(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Zx(t,n),u=c?t[n]:void 0;if(c&&(!r||u!==void 0)){let e=i.get(u);if(!e)return l(a);for(let t of e)o.add(t);s=n}}if(s===void 0)for(let[e,[i,a]]of n){let n=Zx(t,e),s=n?t[e]:void 0;if(n&&(!r||s!==void 0)){let e=i.get(s);if(e)for(let t of e)o.add(t)}else if(r)for(let e of a)o.add(e)}for(let[e,[i,a]]of n){if(e===s)continue;let n=Zx(t,e),c=n?t[e]:void 0;if(n&&(!r||c!==void 0)){let e=i.get(c);for(let t of o)a.has(t)&&!e?.has(t)&&o.delete(t)}}return Array.from(o).sort((e,t)=>e-t)}}else t=e=>{let t=l(Xx(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Jx.set(e,t),t}var $x=class extends ix{_tag=`Union`;types;options;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.types=e,this.options=t,this.encodingChecks=o}getParser(e,t){let n=this,r=t!==void 0,i=[],a=t=>i[t]??=e(n.types[t]),o;return(e,t)=>{if(e===my)return gy;let i=(o??=Qx(n.types))(e,r);if(i.length===0)return Hh(new Py(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:Rc(r)?eS(n,r.cause,e,t):tS(n,r,e,t)}return nS(n,a,i,e,t)}}_rebuild(e,t,n){let r=AS(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new $x(r,this.options,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}}getExpected(e){let t=this.annotations?.expected;if(typeof t==`string`)return t;if(this.types.length===0)return`never`;let n=this.types.map(t=>{let n=WS(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Jb);if(t.length>0)return`${oS(n.isMutable)}[ ${t.map(t=>e(t)+sS(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Jb(e.type));if(t.length>0)return`{ ${t.map(t=>`${oS(t.type.context?.isMutable)}${ct(t.name)}${sS(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function eS(e,t,n,r){let i=Qy(t);return i?uf(new Py(e,[i],n,r)):lf(t)}function tS(e,t,n,r){return cg(t,t=>eS(e,t,n,r))}function nS(e,t,n,r,i){let a={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode===`oneOf`?[]:void 0,issues:void 0,options:i},o=iS(a,n);if(!o)return a.out?a.out:Hh(new Py(e,a.issues??[],r,i));if(Rc(o))return rS(o,a);let s=!0;return Lh(()=>s?(s=!1,rS(o,a)):nS(e,t,n,r,i))}function rS(e,t){return i_(e,e=>t.out===_y?T(t.input):t.out?t.out:Hh(new Py(t.ast,t.issues??[],t.input,t.options)))}var iS=Pu()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=Qy(n.cause);if(t===void 0)return n;e.issues?e.issues.push(t):e.issues=[t]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),uf(new Fy(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return df}}}),aS=new $x([new px(`Infinity`),new px(`-Infinity`),new px(`NaN`)]);function oS(e){return e?``:`readonly `}function sS(e){return e?`?`:``}var cS=class extends n{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new cS(this.run,{...this.annotations,...e},this.aborted)}abort(){return new cS(this.run,this.annotations,!0)}and(e,t){return new lS([this,e],t)}},lS=class extends n{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new lS(this.checks,{...this.annotations,...e})}and(e,t){return new lS([this,e],t)}};function uS(e,t,n=!1){return new cS((t,n,r)=>Ry(n,e(t,n,r),t,r),t,n)}function dS(e){return uS(e=>globalThis.Number.isFinite(e),{expected:`a finite number`,representation:{id:`effect/schema/isFinite`,payload:null},toJsonSchema:()=>({type:`number`}),toCode:()=>({runtime:`Schema.isFinite()`}),arbitraryConstraint:{number:`finite`},...e})}var fS=CS(vx,[dS()]),pS=new ex(new $x([fS,aS]),new xb(pb(),ob(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function mS(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return uS(e=>(n.lastIndex=0,n.test(e)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:`effect/schema/isPattern`,payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}var hS=new WeakMap;function gS(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&hS.set(n,_S(e)),n}function _S(e){let t=hS.get(e);if(t!==void 0)return t;if(e.encoding===void 0)return e;let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,{encoding:void 0});return hS.set(e,n),n}function vS(e,t){return e.encoding===t?e:gS(e,{encoding:t})}function yS(e,t){if(e.context===t)return e;let n=_S(e);return n.context===t&&n.encoding===e.encoding?n:gS(e,{context:t})}function bS(e){return e.encoding?bS(e.encoding[e.encoding.length-1].to):e}function xS(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return SS(e,Ki(e.checks.slice(0,-1),n.annotate(t)))}return gS(e,{annotations:{...e.annotations,...t}})}function SS(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:gS(e,{checks:t})}function CS(e,t){return SS(e,zx(e.checks,t))}function wS(e,t){let n=t(e.to);return n===e.to?e:new ex(n,e.transformation)}function TS(e,t){let n=e,r=n[n.length-1],i=wS(r,t);return i===r?e:Ki(e.slice(0,e.length-1),i)}function ES(e){return t=>t.encoding?vS(t,TS(t.encoding,e)):t}function DS(e,t){return ES(e=>yS(e,t))(e)}function OS(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:vS(r,TS(r.encoding,n))}return e(r)}return p(n)}function kS(e,t,n){let r=new ex(e,t);return vS(n,n.encoding?[...n.encoding,r]:[r])}function AS(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],a=t(i);if(n)n[r]=a;else if(a!==i){n=Array(e.length);for(let t=0;t<r;t++)n[t]=e[t];n[r]=a}}return n??e}function jS(e,t){return yS(e,e.context?new nx(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new nx(!1,!1,void 0,t))}var MS=p(e=>NS(yS(e,e.context?e.context.isOptional===!1?new nx(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new nx(!0,!1)))),NS=ES(MS),PS=f(e=>MS(new $x([e,lx])));function FS(e,t){return yS(e,e.context?new nx(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new nx(!1,!1,t))}function IS(e,t,n){return kS(e,n,t)}function LS(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:ae(e.literal)&&!t.includes(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.includes(e.symbol)||t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function RS(e,t){let{literals:n,parameters:r}=LS(e);return new Px(n.map(e=>new kx(e,t)),r.map(e=>new Nx(e,t)))}function zS(e){return e.context?.isOptional??!1}function BS(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(BS)}function VS(e){function t(e){return BS(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Ji(n)?n:void 0}function HS(e){let t=!0;function n(e){return t=t&&!e.encoding&&!$b(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var US=p(e=>{let t=_S(e);if(t!==e){let n=US(t);return n===t&&e.encoding===void 0?e:yS(n,e.context)}let n=`recur`in e?e.recur(US):e;if(`encodingChecks`in n&&n.encodingChecks){let t=HS(e)?n.encodingChecks:Xb(n)||Zb(n)||Wb(n)&&n.typeParameters.length>0?VS(n.encodingChecks):void 0;return gS(n,{encodingChecks:void 0,checks:zx(n.checks,t)})}return n}),WS=p(e=>US(KS(e)));function GS(e,t){let n=t,r=n.length,i=n[r-1],a=[new ex(KS(vS(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new ex(KS(n[e-1].to),n[e].transformation.flip()));let o=KS(i.to);return o.encoding?vS(o,[...o.encoding,...a]):vS(o,a)}var KS=f(e=>{if(e.encoding)return GS(e,e.encoding);let t=_S(e);if(t!==e){let n=KS(t);return n===t?e:yS(n,e.context)}return`flip`in e?e.flip(KS):`recur`in e?e.recur(KS):e});function qS(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(qS);default:return!1}}function JS(e,t){let n=t===0?_y:hy(t);return(r,i)=>r===my?gy:r===t?n:Hh(new Ay(e,r,i))}function YS(e,t){return(n,r)=>n===my?gy:t(n)?_y:Hh(new Ay(e,n,r))}var XS=OS(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(XS)}}),ZS=OS(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(ZS)}}),QS=new globalThis.RegExp(`^${Dx}$`),$S=new globalThis.RegExp(`^(?:${Dx}|Infinity|-Infinity|NaN)$`);function eC(e){return mS(QS,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:QS.source}),...e})}var tC=CS(hx,[eC()]),nC=new ex(tC,kb),rC=new ex(new $x([tC,aS]),kb),iC=new globalThis.RegExp(`^-?\\d+$`);function aC(e){return mS(iC,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:iC.source}),...e})}var oC=new ex(CS(hx,[aC({expected:`a string representing a bigint`})]),Ab);function sC(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=sC(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new wy(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function cC(e){if(!Wb(e))return;let t=e.annotations?.[fy];return oe(t)?t(e.typeParameters):void 0}var lC=cy,uC=ly;function dC(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function fC(e){return e===void 0||typeof e==`string`}function pC(e,t){let n=new WeakMap,r=[];outer:for(;;){if(typeof e!=`object`||!e){if(!t(e))return!1}else{let t=e,i=n.get(t);if(i===!1)return!1;if(i===void 0){let e=Array.isArray(t);if(!e){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null)return!1}n.set(t,!1),r.push({value:t,keys:e?t.length:Object.keys(t),index:0})}}for(;r.length>0;){let t=r[r.length-1],i=t.keys;if(typeof i==`number`){if(t.index<i){e=t.value[t.index++];continue outer}}else if(t.index<i.length){e=t.value[i[t.index++]];continue outer}n.set(t.value,!0),r.pop()}return!0}}function mC(e){return pC(e,dC)}var hC=new ax([],()=>(e,t,n)=>mC(e)?_y:Hh(new Ay(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>yC}),gC=new ex(hC,Ob()),_C=new ex(new $x([new xx(!1,[],[hC]),new Px([],[new Nx(hx,hC)])]),Ob());function vC(e){return pC(e,fC)}var yC=new ex(new ax([],()=>(e,t,n)=>vC(e)?_y:Hh(new Ay(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),Ob()),bC=(e,t,n)=>e===_y?n(t):i_(e,n);function xC(e){let t=SC(e);return(e,n,r)=>{try{return t(e,n,r)}catch(e){return Gh(e)}}}function SC(e){if(e._tag===`Middleware`)return(t,n,r)=>CC(t===_y?e.decode(hy(vy(n)),r):e.decode(t_(t,vy),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===_y?hy(t):e;case`Transform`:{let e=e=>e===my?gy:hy(t.transform(e));return(t,n)=>bC(t,n,e)}case`TransformOptional`:{let e=e=>yy(t.transform(vy(e)));return(t,n)=>bC(t,n,e)}case`TransformEffect`:return(e,n,r)=>bC(e,n,e=>e===my?gy:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>bC(e,n,e=>CC(t.transform(vy(e),r)))}}var CC=e=>i_(e,yy),wC=(e,t,n,r)=>cg(r,r=>Wh(()=>Qd(r,r=>new Ty(e,r,t,n))));function TC(e,t){let n=xC(e.link.transformation),r;return(i,a)=>{if(i===my)return gy;if(e.isConstructed(i))return _y;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function EC(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==my&&r!==void 0)return t(r,i);let a=n;if(Rc(a)&&a._tag===`Success`){let e=t(a[Mt],i);return e===_y?a:e}return i_(wC(e,r,i,a),e=>{let n=t(e,i);return n===_y?hy(e):n})}}function DC(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:EC(e,n)}function OC(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?cC(e):void 0,o=a?TC(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>xC(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);try{if(u&&!n.disableChecks){if(Rc(r)){if(r._tag===`Success`){let i=r===_y?t:r[Mt];if(t!==my&&i!==my){let i=sC(u,t,void 0,e,n);i&&(r=Hh(new ky(e,i,t,n)))}}}else r=D(r,r=>{if(t!==my&&r!==my){let r=sC(u,t,void 0,e,n);if(r)return Hh(new ky(e,r,t,n))}return T(r)})}if(s&&!n.disableChecks){if(Rc(r)){if(r._tag===`Success`){let i=r===_y?t:r[Mt];if(i===my)return r;let a=sC(s,i,void 0,e,n);a&&(r=Hh(new ky(e,a,i,n)))}}else r=D(r,t=>{if(t!==my){let r=sC(s,t,void 0,e,n);if(r)return Hh(new ky(e,r,t,n))}return T(t)})}return r}catch(e){return Gh(e)}},p=i===void 0?f:i(f);return c?(n,r)=>{let i=d??=c.map(e=>t(e.to)),a=n,o=i[i.length-1](n,r);for(let e=c.length-1;e>=0;e--)if(o=l[e](o,a,r),e!==0){let t=i[e-1];o._tag===`Success`?(a=o[Mt],o=t(a,r)):o=i_(o,e=>{let n=t(e,r);return n===_y?hy(e):n})}if(o._tag===`Success`){let e=o[Mt],t=p(e,r);return t===_y?o:t}return o=wC(e,n,r,o),i_(o,e=>{let t=p(e,r);return t===_y?hy(e):t})}:p}var kC=Symbol(),AC=new WeakMap,jC=e=>FC(e).parser,MC=e=>FC(e).makeEffect,NC=e=>DC(e,MC),PC=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=OC(this.ast,jC)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=OC(this.ast,MC,NC)}};function FC(e){let t=AC.get(e);if(t!==void 0)return t;let n=new PC(e);return AC.set(e,n),n}function IC(e){let t=e.ast,n;return(e,r)=>(n??=XC(nw,US(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function LC(e){let t=IC(e);return(e,n)=>{let r=Zg(t(e,n));return ff(r)?b(r.value):($y(r.cause,`Option adapter can only return none for schema issues`),y())}}function RC(e){return ew(US(e.ast))}function zC(e){return VC(e.ast)}function BC(e){{let t=ZC(JC(e));return e=>{let n=t(e,tx);return ff(n)?!0:($y(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function VC(e){let t=US(e),n=e=>(n=BC(t),n(e));return e=>n(e)}function HC(e,t){let n=JC(e.ast);return t===void 0?n:(e,r)=>n(e,KC(t,r))}function UC(e,t){return QC(HC(e,t))}var WC=UC;function GC(e,t){let n=JC(KS(e.ast));return t===void 0?n:(e,r)=>n(e,KC(t,r))}var KC=(e,t)=>t?{...e,...t}:e,qC=e=>e===my?Hh(new jy):T(e);function JC(e){return XC(tw,e)}function YC(e,t){return e===_y?T(t):Rc(e)?e[`~effect/Effect/args`]===my?qC(my):e:i_(e,qC)}function XC(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??tx);return a===_y?T(r):Rc(a)?a[`~effect/Effect/args`]===my?qC(my):a:i_(a,qC)}}function ZC(e){return(t,n)=>Zg(e(t,n))}function QC(e){let t=ZC(e);return(e,n)=>{let r=t(e,n);return ff(r)?b(r.value):($y(r.cause,`Option adapter can only return none for schema issues`),y())}}function $C(e,t){let n=Zg(e);if(ff(n))return n.value;let r=$y(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function ew(e){let t,n;return(r,i)=>{t??=FC(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??tx,o=t.make;if(o!==void 0&&r!==my){let e;try{e=o(r,a)}catch(e){throw $y(qd(e),`Constructor adapter can only throw schema issues`),e}if(e!==kC&&e!==my)return e}return $C(YC((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var tw=e=>FC(e).parser,nw=e=>FC(e).makeEffect,rw=`~effect/Schema/Schema`,iw=Symbol(),aw={[rw]:rw,get make(){let e=RC(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=IC(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=LC(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return e(this,arguments)},annotate(e){return this.rebuild(xS(this.ast,e))},annotateKey(e){return this.rebuild(jS(this.ast,e))},check(...e){return this.rebuild(CS(this.ast,e))},rebuild(e){return ow(e,this[iw])}};function ow(e,t){function n(){}let r=Object.setPrototypeOf(n,aw);return t&&(Object.hasOwn(t,`name`)||Object.hasOwn(t,`length`)||Object.hasOwn(t,`__proto__`))?Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t})):Object.assign(r,t),r[iw]=t,r.ast=e,r}function sw(e){return ow(cw(e.ast),{schema:e})}var cw=OS(e=>{let t=_S(e);if(t!==e){let n=cw(t);if(n===t)return e;if(n.encoding===void 0)return yS(n,e.context)}let n=pw(e,cw),r=e.context;return n===e||r===void 0?n:DS(n,lw(r))});function lw(e){return e.constructorDefault===void 0?e:new nx(e.isOptional,e.isMutable,void 0,e.annotations)}function uw(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function dw(e){return t=>{let n=[...t].sort((t,n)=>e(WS(t))-e(WS(n)));return n.some((e,n)=>e!==t[n])?n:t}}var fw=dw(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function pw(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!oe(n))return vS(e,[gC]);let r=n(e.typeParameters.map(e=>ow(WS(e))));return r===void 0?e:vS(e,[wS(r,t)])}case`Unknown`:return vS(e,[gC]);case`ObjectKeyword`:return vS(e,[_C]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return uw(e),e.recur(t,ZS);case`Union`:{let n=fw(e.types);return n===e.types?e.recur(t):new $x(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}function mw(e){return ow(bw(e.ast),{schema:e})}var hw=dw(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function gw(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>ow(t(WS(e)))),i=e.annotations?.toCodecStringTree;if(oe(i)){let n=i(r);return n===void 0?e:vS(e,[wS(n,t)])}let a=e.annotations?.toCodecJson,o=oe(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??(oe(s)?s(r):void 0);return c===void 0?n(e):vS(e,[wS(c,t)])}case`Null`:return vS(e,[_w]);case`Boolean`:return vS(e,[vw]);case`Unknown`:case`ObjectKeyword`:return vS(e,[yC]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return uw(e),e.recur(t,ZS);case`Union`:{let n=hw(e.types);return n===e.types?e.recur(t):new $x(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}var _w=new ex(new px(`null`),new xb(ob(()=>null),ob(()=>`null`))),vw=new ex(new $x([new px(`true`),new px(`false`)]),new xb(ob(e=>e===`true`),fb())),yw=new xb(ob(e=>typeof e==`string`?[e]:e),ab()),bw=OS(e=>{let t=gw(e,bw,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?DS(t,lw(e.context)):t},{stopAt:e=>e.transformation===yw});function xw(e){return ff(e)?e.value:{issues:[{message:rf(e.cause)}]}}function Sw(e,t){let n=HC(e),r={errors:`all`,...t?.parseOptions},i=Vy(t);return Cw(e,{validate:e=>{let t=new _o(`sync`),a=qg(bg(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?xw(o):new Promise(e=>{a.addObserver(t=>{e(xw(t))})})}})}function Cw(e,t){let n={version:1,vendor:`effect`,...Object.hasOwn(e,`~standard`)?e[`~standard`]:void 0,...t},r=typeof e==`function`?Function.prototype.bind.call(e,void 0):Object.create(Object.getPrototypeOf(e));return Object.defineProperties(r,{...Object.getOwnPropertyDescriptors(e),ast:{value:e.ast,enumerable:!0,configurable:!0},"~standard":{value:n,writable:!0,enumerable:!0,configurable:!0}})}var ww=r(2,(e,t)=>({...e,...t})),Tw=r(2,(e,t)=>Dw(e,(e,n)=>[Object.hasOwn(t,e)?t[e]:e,n])),Ew=e=>e;function Dw(e,t){let n={};for(let r of Reflect.ownKeys(e)){if(!Object.prototype.propertyIsEnumerable.call(e,r))continue;let i=t(r,e[r]);if(i){let[e,t]=i;Et(n,e,t)}}return n}var Ow=`~effect/Schema/SchemaError`;function kw(e){return pe(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}({...yt}),{...yt},{...yt},{...yt},{...yt},{...yt},{...yt},{...yt};var Aw=rw;function jw(){return(e,t,n)=>Xw(new ax(e.map(Vx),e=>t(e.map(e=>Xw(e))),n))}function Mw(e,t){return jw()([],()=>(t,n,r)=>e(t)?T(t):Hh(new Ay(n,t,r)),t)}var Nw=class extends Co(`SchemaError`){[Ow]=Ow;constructor(e){let t=St();Ct(0);try{super({issue:e})}finally{Ct(t)}}get message(){return Yy(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[gt](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}};function Pw(e){return kw(e)}function Fw(e){return Rc(e)?Iw(e):cg(e,e=>Wh(()=>Qd(e,e=>new Nw(e))))}function Iw(e){return ff(e)?e:lf(Qd(e.cause,e=>new Nw(e)))}function Lw(e,t){let n;for(let r of e.reasons){if(!Wd(r)||!Pw(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function Rw(e){let t=Zg(e);if(ff(t))return t.value;throw Lw(t.cause,`Sync adapter can only throw schema errors`)}function zw(e,t){return Sw(e,t)}var Bw=zC;function Vw(e,t){let n=HC(e,t);return(e,t)=>Fw(n(e,t))}var Hw=Vw,Uw=UC,Ww=WC;function Gw(e,t){let n=Vw(e,t);return(e,t)=>Rw(n(e,t))}function Kw(e,t){let n=GC(e,t);return(e,t)=>Fw(n(e,t))}var qw=Kw;function Jw(e,t){let n=Kw(e,t);return(e,t)=>Rw(n(e,t))}var Yw=Jw,Xw=ow;function Zw(e){return pe(e,Aw)&&e[Aw]===Aw}var Qw=Ew(e=>Xw(MS(e.ast),{schema:e})),$w=Ew(e=>{let t=xT(e);return Xw(PS(e.ast),{schema:t})}),eT=Ew(e=>Xw(US(e.ast),{schema:e})),tT=Ew(e=>Xw(WS(e.ast),{schema:e}));function nT(e){let t=Xw(new px(e),{literal:e,transform(n){return t.pipe(ST(nT(n),{decode:ob(()=>n),encode:ob(()=>e)}))}});return t}var rT=Xw(dx),iT=Xw(fx),aT=Xw(ox),oT=Xw(lx),M=Xw(hx),sT=Xw(vx),cT=Xw(yx),lT=Xw(bx),uT=Xw(ux);function dT(e,t){return Xw(e,{fields:t,mapFields(e,t){let n=e(this.fields);return dT(Bx(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function N(e){return dT(Bx(e,void 0),e)}var fT=e=>typeof e==`symbol`?e:globalThis.String(e);function pT(e){return function(t){let n={},r=Object.create(null),i=Object.create(null),a=new Set;for(let o of Reflect.ownKeys(t.fields)){let s=tT(t.fields[o]),c=Object.hasOwn(e,o),l=c?e[o]:o,u=fT(l);if(a.has(u))throw new globalThis.Error(`Duplicate encoded keys: ${ct(l)}`);a.add(u),Et(n,l,s),c&&(r[o]=l,i[l]=o)}return N(n).pipe(ST(t,Tb({decode:Tw(i),encode:Tw(r)})))}}function mT(e,t){return Xw(RS(e.ast,t.ast),{key:e,value:t})}function hT(e,t){return Xw(Wx(e.ast,t.map(Vx)),{schema:e,records:t})}function gT(e,t){return Xw(e,{elements:t,mapElements(e,t){let n=e(this.elements);return gT(Hx(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function _T(e){return gT(Hx(e),e)}var P=Ew(e=>Xw(new xx(!1,[],[e.ast]),{value:e})),vT=Ew(e=>Xw(new xx(!1,[e.ast],[e.ast]),{value:e}));function yT(e,t){return Xw(e,{members:t,mapMembers(e,t){let n=e(this.members);return yT(Ux(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function F(e,t){return yT(Ux(e,t,void 0),e)}function bT(e){let t=e.map(nT);return Xw(Ux(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return F(e(this.members))},pick(e){return bT(e)},transform(e){return F(t.map((t,n)=>t.transform(e[n])))}})}var I=Ew(e=>F([e,aT])),xT=Ew(e=>F([e,oT]));function L(e){return t=>Xw(t.ast,{schema:t,identifier:e})}function ST(e,t){return n=>Xw(IS(n.ast,e.ast,t?Cb(t):Ob()),{from:n,to:e})}function CT(){return(e,t)=>MT()(e,{decode:t,encode:rb})}function wT(e,t){return n=>t?ST(n,t)(e):ST(n)(e)}function TT(e){return t=>Xw(FS(t.ast,e),{schema:t})}function ET(e){return Rc(e)&&e._tag===`Success`?e:cg(e,e=>Wh(()=>Qd(e,e=>e.issue)))}function DT(e,t){let n=t?.encodingStrategy===`omit`?ub():ab();return t=>Qw(tT(t)).pipe(ST(t,{decode:db(ET(e)),encode:n}))}function OT(e,t){return n=>eT(n).pipe(DT(e,t),wT(Qw(n)))}function kT(e){return nT(e).pipe(TT(T(e)))}function AT(e,t){return N({_tag:kT(e),...t})}function jT(e,t){return Mw(t=>t instanceof e,t)}function MT(){return(e,t)=>new ex(e.ast,Cb(t))}var NT=uS;function PT(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${ot(n)})`:`new RegExp(${ot(n)}, ${ot(r)})`;return mS(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var FT=Xw(fS),IT=dS;function LT(e){let t=mr(e.order),n=e.formatter??ot;return(r,i)=>NT(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function RT(e){let t=gr(e.order),n=e.formatter??ot;return(r,i)=>NT(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function zT(e){let t=gr(e.order),n=mr(e.order),r=hr(e.order),i=pr(e.order),a=e.formatter??ot;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return NT(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitraryConstraint:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}},...e.annotate?.(o),...s})}}function BT(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${ot(e)}`);return e}var VT=LT({order:lr,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:BT(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${ot(e)})`})})}),HT=RT({order:lr,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:BT(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${ot(e)})`})})}),UT=zT({order:lr,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:BT(e.minimum),maximum:BT(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${ot(e.minimum)}, maximum: ${ot(e.maximum)}, exclusiveMinimum: ${ot(t)}, exclusiveMaximum: ${ot(n)} })`})}}});function WT(e){return NT(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>({type:`integer`,minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}var R=sT.check(WT());function GT(e,t){return e=YT(e),KT(e,Math.ceil(e/2),t)}function KT(e,t,n){return NT(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:n})=>n===`string`?e<=1?{minLength:t}:[{minLength:t},!0]:n===`array`?{minItems:e}:n===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[uy]:!0,arbitraryConstraint:{minLength:e},...n})}function qT(e){return KT(1,1,e)}function JT(e,t){return e=YT(e),NT(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`string`?e===0?{maxLength:e}:[{maxLength:e},!0]:t===`array`?{maxItems:e}:t===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[uy]:!0,arbitraryConstraint:{maxLength:e},...t})}function YT(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function XT(e){return NT(e=>va(e).length===e.length,{expected:`an array with unique items`,representation:{id:`effect/schema/isUnique`,payload:null},toJsonSchema:()=>({uniqueItems:!0}),toCode:()=>({runtime:`Schema.isUnique()`}),arbitraryConstraint:{uniqueBy:i},...e})}var z=M.check(qT()),ZT=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),QT=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},$T=[];function eE(e){let t=ZT(e),n=$T[t];if(n!==void 0)return n;let r=IE.pipe(ST(iT,Lb(QT(t))));return $T[t]=r,r}globalThis.RegExp;var tE=M.annotate({expected:`a string that will be decoded as a URL`}),nE=jT(globalThis.URL,{representation:{id:`effect/schema/URL`,payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:`URL`,toCodecJson:()=>MT()(tE,Bb)}),rE=tE.pipe(ST(nE,Bb)),iE=M.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function aE(e,t){return iE.pipe(ST(e,Hb(t)))}var oE=aE(iT);globalThis.File,globalThis.URLSearchParams;var sE=M.annotate({expected:`a string that will be decoded as a finite number`}).pipe(ST(FT,kb)),cE=M.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),lE=jT(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>MT()(cE,Vb)});function uE(e,t){return Xw(jw()([e,t],([e,t])=>(n,r,i)=>{if(!Ud(n))return Hh(new Ay(r,n,i));switch(n._tag){case`Fail`:return r_(HC(e)(n.error,i),{onSuccess:Jd,onFailure:e=>My(r,`error`,e,n,i)});case`Die`:return r_(HC(t)(n.defect,i),{onSuccess:Yd,onFailure:e=>My(r,`defect`,e,n,i)});case`Interrupt`:return T(n)}},{representation:{id:`effect/schema/CauseReason`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.CauseReason(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Failure<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause.Failure`,toCodec:([e,t])=>MT()(F([N({_tag:nT(`Fail`),error:e}),N({_tag:nT(`Die`),defect:t}),N({_tag:nT(`Interrupt`),fiberId:xT(FT)})]),Tb({decode:e=>{switch(e._tag){case`Fail`:return Jd(e.error);case`Die`:return Yd(e.defect);case`Interrupt`:return Xd(e.fiberId)}},encode:e=>{switch(e._tag){case`Fail`:return{_tag:`Fail`,error:e.error};case`Die`:return{_tag:`Die`,defect:e.defect};case`Interrupt`:return{_tag:`Interrupt`,fiberId:e.fiberId}}}}))}).ast,{error:e,defect:t})}function dE(e,t){return Xw(jw()([e,t],([e,t])=>{let n=P(uE(e,t));return(e,t,r)=>Hd(e)?r_(HC(n)(e.reasons,r),{onSuccess:Gd,onFailure:n=>My(t,`reasons`,n,e,r)}):Hh(new Ay(t,e,r))},{representation:{id:`effect/schema/Cause`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Cause(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Cause<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause`,toCodec:([e,t])=>MT()(P(uE(e,t)),Tb({decode:Gd,encode:({reasons:e})=>e}))}).ast,{error:e,defect:t})}var fE=wb({decode:(e,t)=>vr(R_(e),{onNone:()=>Hh(new jy({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>T(B_(e))}),encode:e=>T(q_(e))}),pE=-864e13,mE=864e13;function hE(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function gE(e,t){return R.check(UT({minimum:e,maximum:t}))}var _E=Mw(e=>P_(e)&&F_(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=hE(e,pE,mE);return CT()(gE(t,n),ob(L_))},toCodecJson:()=>MT()(M,fE),toFormatter:()=>e=>e.toString()}),vE=M.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(ST(_E,fE));function B(e){return Xw(jw()([e],([e])=>(t,n,r)=>_r(t)?x(t)?Ih:r_(HC(e)(t.value,r),{onSuccess:b,onFailure:e=>My(n,`value`,e,t,r)}):Hh(new Ay(n,t,r)),{representation:{id:`effect/schema/Option`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Option(${e[0].runtime})`,Type:`Option.Option<${e[0].Type}>`,importDeclarations:[`import * as Option from "effect/Option"`]}),expected:`Option`,toCodec:([e])=>MT()(F([N({_tag:nT(`Some`),value:e}),N({_tag:nT(`None`)})]),Tb({decode:e=>e._tag===`None`?y():b(e.value),encode:e=>S(e)?{_tag:`Some`,value:e.value}:{_tag:`None`}}))}).ast,{value:e})}function yE(e){return I(e).pipe(ST(B(eT(e)),Rb()))}var bE=Mw(Lv,{representation:{id:`effect/http/UrlParams`,payload:null},toCode:()=>({runtime:`Schema.UrlParams`,Type:`UrlParams.UrlParams`,importDeclarations:[`import * as UrlParams from "effect/http/UrlParams"`]}),expected:`UrlParams`,toEquivalence:()=>Uv,toCodec:()=>MT()(P(_T([M,M])),Tb({decode:zv,encode:e=>e.params.map(([e,t])=>[e,Fv(t)])}))}).pipe(ST(mT(M,F([M,vT(M)])),Tb({decode:Xv,encode:Bv})));function xE(e){return Qw(e).pipe(ST(B(eT(e)),zb()))}function SE(e,t){let n=typeof t?.label==`string`?t.label:void 0,r=t?.disallowJsonEncode===!0,i=n===void 0?r?{disallowJsonEncode:!0}:void 0:r?{label:n,disallowJsonEncode:!0}:{label:n},a=n===void 0?void 0:HC(nT(n));return Xw(jw()([e],([e])=>(t,n,r)=>gv(t)?i_(a===void 0?zh:n_(a(t.label,r),e=>new Ey([`label`],e)),()=>r_(HC(e)(yv(t),r),{onSuccess:e=>_v(e,{label:t.label}),onFailure:()=>new ky(n,[new Ey([`value`],new jy(void 0,t,r))],t,r)})):Hh(new Ay(n,t,r)),{representation:{id:`effect/schema/Redacted`,payload:i??null},toCode:({typeParameters:e})=>({runtime:i===void 0?`Schema.Redacted(${e[0].runtime})`:`Schema.Redacted(${e[0].runtime}, ${ot(i)})`,Type:`Redacted.Redacted<${e[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:`Redacted`,toCodecJson:([e])=>MT()(e,{decode:ob(e=>_v(e,{label:n})),encode:r?nb(e=>`Cannot serialize Redacted`+(S(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):ob(yv)}),toEquivalence:([e])=>bv(e)}).ast,{value:e})}function CE(e,t){return ST(SE(eT(e),{label:t?.label,disallowJsonEncode:t?.disallowEncode}),{decode:ob(e=>_v(e,{label:t?.label})),encode:t?.disallowEncode?nb(e=>`Cannot encode Redacted`+(S(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):ob(yv)})(e)}var wE=globalThis.Symbol.for(`immer-draftable`),TE={};function EE(t,n,r,i,a){let o=AE(r,n,i),s=kE(n),c=class extends t{constructor(...[e,t]){let n=t?.[`~payload`],i=n?.token===TE?n.value:r.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:TE,value:i}})}static[Aw]=Aw;get[s](){return s}static[wE]=!0;static identifier=n;static fields=r.fields;static get ast(){return o(this).ast}static pipe(){return e(this,arguments)}static rebuild(e){return o(this).rebuild(e)}static make(e,t){return RC(o(this))(e??{},t)}static makeOption(e,t){return LC(o(this))(e??{},t)}static makeEffect(e,t){return o(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(xS(this.ast,e))}static annotateKey(e){return this.rebuild(jS(this.ast,e))}static check(...e){return this.rebuild(CS(this.ast,e))}static extend(e){return(t,n)=>{let i=jE(t)?t:N(t),o={...r.fields,...i.fields},s=Bx(o,r.ast.checks,{identifier:e});return EE(this,e,dT(CS(s,i.ast.checks),o),n,a)}}static mapFields(e,t){return r.mapFields(e,t)}};return a!==void 0&&Object.assign(c.prototype,a(n)),c}function DE(e,t){return new e(t,{"~payload":{token:TE,value:t}})}function OE(e){return new xb(ob(t=>DE(e,t)),ab())}function kE(e){return`~effect/Schema/Class/${e}`}function AE(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=kE(t),o=e=>e instanceof i||pe(e,a),s=OE(i);return r=ST(Xw(new ax([e.ast],()=>(e,t,n)=>o(e)?T(e):Hh(new Ay(t,e,n)),{identifier:t,[fy]:([e])=>({isConstructed:o,link:new ex(e,s)}),toCodec:([e])=>new ex(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[dy]:qx(e.ast),...n})),s)(e)}}function jE(e){return Zw(e)}var V=e=>(t,n)=>EE(xo,e,jE(t)?t:N(t),n,e=>({toString(){return`${e}(${ot({...this})})`}})),H=e=>(t,n,r)=>{let i=jE(n)?n.mapFields(e=>({_tag:kT(t),...e}),{unsafePreserveChecks:!0}):AT(t,n);return V(e??t)(i,r)},ME=e=>(t,n)=>EE(Sn,e,jE(t)?t:N(t),n,e=>({name:e})),NE=e=>(t,n,r)=>{let i=jE(n)?n.mapFields(e=>({_tag:kT(t),...e}),{unsafePreserveChecks:!0}):AT(t,n);return ME(e??t)(i,r)},PE=sw,FE=mw,IE=Xw(xS(hC,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),LE=mT(M,IE),RE=Vs,zE=Us,BE=Ws,VE=Gs,HE=Ks,UE=Wu,WE=ed,GE=`~effect/MutableRef`,KE={[GE]:GE,...Rt,toJSON(){return{_id:`MutableRef`,current:_t(this.current)}}},qE=e=>{let t=Object.create(KE);return t.current=e,t},JE=r(2,(e,t)=>(e.current=t,e)),YE=Symbol.for(`effect/MutableList/Empty`),XE=()=>({head:void 0,tail:void 0,length:0}),ZE=e=>{let t=e.head;t.offset>=1024&&t===e.tail&&t.mutable&&(t.array.length-t.offset)*8<=t.offset&&(e.head=e.tail={array:t.array.slice(t.offset),mutable:!0,offset:0,next:void 0})},QE=()=>({array:[],mutable:!0,offset:0,next:void 0}),$E=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=QE(),e.tail=e.tail.next):e.head=e.tail=QE(),e.tail.array.push(t),e.length++},eD=e=>{e.head=e.tail=void 0,e.length=0},tD=e=>{if(!e.head)return YE;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length?e.head.next?e.head=e.head.next:eD(e):ZE(e),t},nD=`~effect/Queue`,rD=`~effect/Queue/Enqueue`,iD=`~effect/Queue/Dequeue`,aD={_A:i,_E:i},oD={[nD]:aD,[rD]:aD,[iD]:aD,...Rt,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:_D(this)}}},sD=e=>bn(t=>{let n=Object.create(oD);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=XE(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},qs(n)}),cD=e=>sD({capacity:e}),lD=r(2,(e,t)=>Zs(()=>uD(e,t)?yD:e.state._tag===`Open`&&e.strategy===`suspend`?DD(e,t):vD)),uD=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(tD(e.messages),$E(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&($E(e.messages,t),SD(e),!0):($E(e.messages,t),CD(e),!0):!1,dD=r(2,(e,t)=>Xs(()=>fD(e,t))),fD=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=el(_n(t),bD);return e.state.offers.size===0&&e.messages.length===0?(MD(e,n),!0):(e.state={...e.state,_tag:`Closing`,exit:n},CD(e),!0)},pD=e=>Xs(()=>mD(e)),mD=e=>{if(e.state._tag===`Done`)return!1;eD(e.messages);let t=e.state.offers;MD(e,e.state._tag===`Open`?xD:e.state.exit);for(let e of t)kD(e);return!0},hD=e=>wD(()=>gD(e)??Mc(ED(e,()=>TD(e,1)),hD(e))),gD=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=tD(e.messages);return jD(e),mn(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=AD(e.state.offers);return jD(e),mn(t)}},_D=e=>e.state._tag===`Done`?0:e.messages.length,vD=mn(!1),yD=mn(!0),bD=vn(kn()),xD=Gc(),SD=e=>{if(e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(t.ready()&&(e.state.takers.delete(t),t.resume(Xc),e.messages.length===0))break}},CD=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,SD(e)},0))},wD=fn({op:`QueueTake`,[Nt](e){let t=this[Mt]();return Vt(t)?t[Nt](e):t}}),TD=(e,t)=>e.messages.length>=(e.state._tag===`Closing`?1:Math.min(t,e.capacity||1))||e.capacity<=0&&e.state._tag!==`Done`&&e.state.offers.size>0,ED=(e,t)=>lc(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(Xc);let r={ready:t,resume:n};return e.state.takers.add(r),Xs(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),DD=(e,t)=>lc(n=>uD(e,t)?n(yD):OD(e,{_tag:`Single`,message:t,resume:n})),OD=(e,t)=>{if(e.state._tag!==`Open`)return kD(t);let n=e.state.offers;return n.add(t),Xs(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&MD(e,e.state.exit))})},kD=e=>e._tag===`Single`?e.resume(vD):e.resume(mn(e.remaining.slice(e.offset))),AD=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(yD),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(mn([]))),n},jD=e=>{if(e.state._tag===`Done`)return Ym(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(MD(e,e.state.exit),Ym(e.state.exit.cause));for(let t of e.state.offers){let n=e.capacity-e.messages.length;if(n<=0)break;if(t._tag===`Single`)$E(e.messages,t.message),e.state.offers.delete(t),t.resume(yD);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;$E(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(mn([]))}let r=e.state;if(r._tag===`Done`)return Ym(r.exit.cause)}return!1},MD=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e.resume(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},ND=e=>new FD(e),PD=(e,t,n)=>lc(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),Xs(()=>{e.waiters.delete(i)})}),FD=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=Zs(()=>this.free<e?PD(this,e,t):(this.taken+=e,qs(e)));return t}takeIfAvailable(e){return Zs(()=>this.free<e?qs(!1):(this.taken+=e,qs(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return bn(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),rc))}release(e){return bn(t=>qs(this.releaseUnsafe(t,e)))}get releaseAll(){return bn(e=>qs(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>Ou(n=>{let r=Zs(()=>this.free<e?Lc(n(PD(this,e,rc)),()=>r):(this.taken+=e,cu(n(t),()=>{this.releaseUnsafe(Ps(),e)},!0)));return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>Ou(n=>this.free<e?ec:(this.taken+=e,cu(n(jc(t)),()=>{this.releaseUnsafe(Ps(),e)},!0)))}},ID=e=>Xs(()=>new FD(e)),LD=`~effect/Channel`,RD=e=>pe(e,LD),zD={[LD]:{_Env:i,_InErr:i,_InElem:i,_OutErr:i,_OutElem:i},pipe(){return e(this,arguments)}},BD=e=>{let t=Object.create(zD);return t.transform=(t,n)=>cg(e(t,n),e=>T(Uh(e))),t},VD=(e,t)=>BD((n,r)=>D(WD(e)(n,r),e=>t(e,r))),HD=e=>BD((t,n)=>e),UD=e=>BD(Qg(function*(t,n){let r=jf(n),i=e=>Mf(r,$m(e));return Mg(yield*Mg(e(t,n,r),i),i)})),WD=e=>e.transform,GD=e=>BD((t,n)=>Lh(()=>WD(e())(t,n))),KD=e=>HD(T(Hh(e))),qD=e=>HD(Uh(e)),JD=e=>qD(qd(e)),YD=e=>BD((t,n)=>XD({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),XD=e=>{let t=e.readable.getReader(),n=e.exit??qE(void 0),r=Lh(()=>n.current?n.current:xg(Fh({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??Uh(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?of():T(pa(t))}));return ng(Af(e.scope,e.releaseLockOnEnd?Rh(()=>t.releaseLock()):Ph(()=>t.cancel().catch(e=>t.closed.then(()=>Promise.reject(e),u))).pipe(jg(Rh(()=>t.releaseLock())))),r)},ZD=r(2,(e,t)=>VD(e,e=>Rh(()=>{let n=0;return tg(e,e=>t(e,n++))}))),QD=e=>e===void 0||e!==`unbounded`&&e<=1,$D=r(e=>RD(e[0]),(e,t,n)=>QD(n?.concurrency)?eO(e,t):tO(e,t,n)),eO=(e,t)=>BD((n,r)=>{let i=0;return tg(WD(e)(n,r),D(e=>t(e,i++)))}),tO=(e,t,n)=>UD(Qg(function*(r,i,o){let s=0,c=yield*WD(e)(r,i),l=n.concurrency===`unbounded`?2**53-1:Math.min(n.concurrency,2**53-1),u=yield*cD(0);yield*Af(o,pD(u));let d=Jg(yield*Sg()),f=UE(o);if(n.unordered){let e=ND(l),n=a(e.release(1)),r=xg({onFailure:e=>D(dD(u,e),n),onSuccess:e=>D(lD(u,e),n)});yield*e.take(1).pipe(D(()=>c),D(e=>{let n=s++;return f(d(r(Lh(()=>t(e,n))))),zh}),Bg({disableYield:!0}),cg(t=>e.withPermits(l-1)(dD(u,t))),Gg(o))}else{let e=yield*cD(l-2);yield*Af(o,pD(e)),yield*hD(e).pipe(Yh,D(e=>lD(u,e)),Bg({disableYield:!0}),cg(e=>dD(u,e)),Gg(o));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,fD(u,e.cause))};yield*c.pipe(D(i=>{if(n)return Uh(n);let a=s++,o=d(Lh(()=>t(i,a)));return f(o),o.addObserver(r),lD(e,zE(o))}),Bg({disableYield:!0}),cg(t=>lD(e,lf(t)).pipe(Xh(dD(e,t)))),Gg(o))}return hD(u)})),nO=e=>VD(e,e=>{let t,n=0;return T(Lh(function r(){if(t===void 0)return D(e,e=>{switch(e.length){case 0:return r();case 1:return T(e[0]);default:return t=e,T(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),T(i)}))}),rO=r(2,(e,t)=>VD(e,e=>T(D(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return Yi(i)?T(i):D(e,n)})))),iO=r(2,(e,t)=>BD((n,r)=>{let i=jf(r);return tg(WD(e)(n,i),e=>{let a=e.pipe(cg(e=>{if(Ym(e))return Uh(e);let o=i;return i=jf(r),Mf(o,lf(e)).pipe(Xh(WD(t(e))(n,i)),D(e=>(a=e,e)))}));return Lh(()=>a)})})),aO=r(3,(e,t,n)=>iO(e,e=>{let r=t(e);return Ei(r)?qD(r.failure):n(r.success,e)})),oO=r(2,(e,t)=>aO(e,ds,e=>t(e))),sO=r(e=>RD(e[0]),(e,t,n,r)=>oO(e,e=>t(e)?n(e):r?r(e):KD(e))),cO=r(2,(e,t)=>VD(e,e=>T(ug(e,e=>af(e)?e:t(e))))),lO=r(e=>RD(e[0])&&RD(e[1]),(e,t,n)=>UD(Qg(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*cD(0);yield*Af(a,pD(s));let c=0;function l(e,t){if(c++,!Ym(t))return dD(s,t);switch(o){case`both`:return c===2?dD(s,t):zh;case`left`:case`right`:return e===o?dD(s,t):zh;case`either`:return dD(s,t)}}let u=(e,t,n)=>WD(t)(r,n).pipe(D(e=>e.pipe(D(e=>lD(s,e)),Bg)),Mg(t=>Ng($m(t),e=>Mf(n,e)).pipe(xg({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Gg(a));return yield*u(`left`,e,jf(a)),yield*u(`right`,t,jf(a)),hD(s)}))),uO=(e,t)=>BD((n,r)=>Rh(()=>{let r=new TextDecoder(e,t),i={stream:!0},a=n.pipe(tg(ma(e=>r.decode(e,i))),Jm(e=>{a=of(e);let t=r.decode();return t.length>0?T(pa(t)):a}));return Lh(()=>a)})),dO=r(2,(e,t)=>BD((n,r)=>D(WD(e)(n,r),e=>WD(t)(e,r)))),fO=r(2,(e,t)=>lO(e,HD(T(D(t,of))),{haltStrategy:`either`})),pO=r(2,(e,t)=>UD((n,r,i)=>kf(i,t).pipe(Xh(WD(e)(n,r))))),mO=r(2,(e,t)=>pO(e,e=>t)),hO=(e,t,n)=>Lh(()=>{let r=Df();return Jm(D(WD(e)(of(),r),t),n||T).pipe(Pg(e=>Mf(r,e)))}),gO=r(2,(e,t)=>BD((n,r)=>tg(Tg(WD(e)(n,r),t),Tg(t)))),_O=r(2,(e,t)=>hO(e,e=>Bg(D(e,t),{disableYield:!0}))),vO=e=>Lh(()=>{let t=y();return hO(e,e=>e.pipe(rg,D(e=>(t=e,of()))),()=>T(t))}),yO=(e,t)=>WD(e)(of(),t),bO=(e,t)=>()=>{let n=Hw(vT(e),t);return BD((e,t)=>T(D(e,e=>n(e))))},xO=`~effect/Stream`,SO={_R:i,_E:i,_A:i},CO=function(e){this.channel=e};CO.prototype={[xO]:SO,pipe(){return e(this,arguments)}};var wO=e=>new CO(e),TO=`~effect/Stream`,EO=e=>pe(e,TO),DO=wO,OO=(e,t)=>DO(BD((n,r)=>D(yO(e.channel,r),e=>t(e,r)))),kO=e=>e.channel,AO=e=>{let t=DO(GD(()=>e().channel));return jO.set(t,e),t},jO=new WeakMap,MO=e=>DO(KD(e)),NO=e=>DO(JD(e)),PO=e=>DO(YD(e)),FO=r(2,(e,t)=>AO(()=>{let n=0;return DO(ZD(e.channel,ma(e=>t(e,n++))))})),IO=r(e=>EO(e[0]),(e,t,n)=>e.channel.pipe(nO,$D(t,n),ZD(pa),DO)),LO=r(2,(e,t)=>DO($D(e.channel,t))),RO=r(2,(e,t)=>DO(rO(kO(e),t))),zO=r(e=>EO(e[0]),(e,t,n,r)=>DO(sO(kO(e),t,e=>n(e).channel,r&&(e=>r(e).channel)))),BO=r(2,(e,t)=>DO(cO(e.channel,t))),VO=r(2,(e,t)=>DO(dO(e.channel,t))),HO=r(e=>EO(e[0]),(e,t)=>e.channel.pipe(dO(uO(t?.encoding)),DO)),UO=r(2,(e,t)=>DO(fO(e.channel,t))),WO=r(2,(e,t)=>DO(mO(e.channel,t))),GO=r(2,(e,t)=>DO(gO(e.channel,t))),KO=e=>tg(vO(e.channel),Dr(Qi(0))),qO=r(e=>EO(e[0]),(e,t,n)=>{let r,i,a=!1,o=WE(!1),s=n?.signal,c=()=>i.interruptUnsafe();return new ReadableStream({start(n){i=qg(Tg(_O(VD(e.channel,e=>T(o.whenOpen(e))),e=>Rh(()=>{o.closeUnsafe();for(let t=0;t<e.length;t++)n.enqueue(e[t]);r(),r=void 0})),t)),i.addObserver(e=>{s?.removeEventListener(`abort`,c),!a&&(e._tag===`Failure`&&s?.aborted!==!0?n.error(ef(e.cause)):n.close())}),s!==void 0&&i.pollUnsafe()===void 0&&(s.aborted?c():s.addEventListener(`abort`,c,{once:!0}))},pull(){return new Promise(e=>{r=e,o.openUnsafe()})},cancel(){if(i)return a=!0,Yg(ig(BE(i)))}},n?.strategy)}),JO=r(e=>EO(e[0]),(e,t)=>tg(Sg(),n=>qO(e,n,t))),YO=Lr(`effect/Crypto`),XO=`~effect/FiberMap`,ZO=e=>pe(e,XO),QO={[XO]:XO,[Symbol.iterator](){return this.state._tag===`Closed`?Ii():this.state.backing[Symbol.iterator]()},...Rt,toJSON(){return{_id:`FiberMap`,state:this.state}}},$O=(e,t)=>{let n=Object.create(QO);return n.state={_tag:`Open`,backing:e,fibers:new Set},n.deferred=t,n},ek=()=>kg(Rh(()=>$O(Ch(),gf())),e=>Lh(()=>{let t=e.state;return t._tag===`Closed`?zh:(e.state={_tag:`Closed`},HE(t.fibers).pipe(wf(e.deferred)))})),tk=-1,nk=co(uo(nf,lo(tk))),rk=r(e=>ZO(e[0]),(e,t,n,r)=>{if(e.state._tag===`Closed`){n.interruptUnsafe(tk);return}let i=wh(e.state.backing,t);if(i._tag===`Some`){if(i.value===n)return;if(r?.onlyIfMissing===!0){n.interruptUnsafe(tk);return}}Oh(e.state.backing,t,n),e.state.fibers.add(n),i._tag===`Some`&&i.value.interruptUnsafe(tk),n.addObserver(i=>{if(e.state._tag===`Closed`)return;e.state.fibers.delete(n);let a=wh(e.state.backing,t);S(a)&&n===a.value&&Ah(e.state.backing,t),pf(i)&&(r?.propagateInterruption===!0?!nk(i.cause):!Zd(i.cause))&&Cf(e.deferred,i)})}),ik=r(2,(e,t)=>e.state._tag===`Closed`?y():wh(e.state.backing,t)),ak=r(2,(e,t)=>Lh(()=>T(ik(e,t)))),ok=r(2,(e,t)=>e.state._tag!==`Closed`&&Dh(e.state.backing,t)),sk=r(2,(e,t)=>Rh(()=>ok(e,t))),ck=r(2,(e,t)=>Lh(()=>{if(e.state._tag===`Closed`)return zh;let n=wh(e.state.backing,t);return n._tag===`None`?zh:VE(n.value,tk)})),lk=function(){let e;return()=>(e===void 0&&(e=qg(Ig)),e)}(),uk=function(){let e=arguments[0];if(jh(arguments[2]))return dk(e,arguments[1],arguments[2],arguments[3]);let t=arguments[1],n=arguments[2];return r=>dk(e,t,r,n)},dk=(e,t,n,r)=>qh(i=>{if(e.state._tag===`Closed`)return Ig;if(r?.onlyIfMissing===!0&&ok(e,t))return Rh(lk);let a=zu(i,n,r?.startImmediately??!0,!0);return rk(e,t,a,r),T(a)}),fk={"~effect/Match/Matcher":{_input:i,_filters:i,_remaining:i,_result:i,_return:i,_args:i},_tag:`TypeMatcher`,add(e){return pk(this.select,[...this.cases,e])},pipe(){return e(this,arguments)}};function pk(e,t){let n=Object.create(fk);return n.select=e,n.cases=t,n}var mk=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),hk=r(2,(e,t)=>_k(t)(pk(i,[]))(e)),gk=e=>t=>{let n=mk(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},_k=(e=>t=>{let n=gk(e)(t);return e=>bk(n(e))})(`_tag`),vk=e=>{if(e._tag===`ValueMatcher`)return e.value;let t=e.cases.length;if(t===1){let t=e.cases[0];return(...n)=>{let r=e.select(...n);return t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1?xi(t.evaluate(r,...n)):Si(r)}}return(...n)=>{let r=e.select(...n);for(let i=0;i<t;i++){let t=e.cases[i];if(t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1)return xi(t.evaluate(r,...n))}return Si(r)}},yk=`effect/match/Match/exhaustive: absurd`,bk=e=>{let t=vk(e);if(Ti(t)){if(Di(t))return t.success;throw Error(yk)}return(...e)=>{let n=t(...e);if(Di(n))return n.success;throw Error(yk)}},xk=hk,Sk={"~effect/Ref":{_A:i},...Rt,toJSON(){return{_id:`Ref`,ref:this.ref}}},Ck=e=>{let t=Object.create(Sk);return t.ref=qE(e),t},wk=e=>Rh(()=>Ck(e)),Tk=e=>Rh(()=>e.ref.current),Ek=r(2,(e,t)=>Rh(()=>JE(e.ref,t))),Dk=r(2,(e,t)=>Rh(()=>{let[n,r]=t(e.ref.current);return e.ref.current=r,n})),Ok=r(2,(e,t)=>Rh(()=>{e.ref.current=t(e.ref.current)})),kk=r(2,(e,t)=>Rh(()=>e.ref.current=t(e.ref.current))),Ak=r(2,(e,t)=>e===void 0?void 0:t(e)),jk=`~effect/SynchronizedRef`,Mk={...Rt,[jk]:jk,toJSON(){return{_id:`SynchronizedRef`,value:this.backing.ref.current}}},Nk=e=>{let t=Object.create(Mk);return t.semaphore=ND(1),t.backing=Ck(e),t},Pk=e=>Rh(()=>Nk(e)),Fk=e=>e.backing.ref.current,Ik=r(2,(e,t)=>e.semaphore.withPermit(Lh(()=>tg(t(Fk(e)),([t,n])=>(e.backing.ref.current=n,t))))),Lk=M.check(PT(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u,{message:`Expected a full GitHub repo name (owner/name)`})).pipe(L(`RepositoryName`)),Rk=M.check(PT(/^[^\s-]\S*$/u,{message:`Expected a Git revision without whitespace or a leading dash`})).pipe(L(`RepositoryRevision`)),zk=M.check(PT(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u,{message:`Expected a 40- or 64-character lowercase Git object ID`})).pipe(L(`CommitSha`)),Bk=e=>e.replaceAll(/[^A-Za-z0-9_.-]/gu,`_`),Vk=e=>{let t=e.indexOf(`/`);return{owner:e.slice(0,t),name:e.slice(t+1)}},Hk=e=>e.toLowerCase(),Uk=z.pipe(L(`EventId`)),Wk=z.pipe(L(`DedupKey`)),Gk=class extends V(`Event`)({id:Uk,dedupKey:Wk,payload:IE,receivedAt:_E}){},Kk=z.pipe(L(`LoopName`)),qk=[`none`,`required`],Jk=bT(qk),Yk=[`write`,`read`],Xk=bT(Yk),Zk=class extends H(`CancelReason/OperatorCanceled`)(`OperatorCanceled`,{}){},Qk=class extends H(`CancelReason/Superseded`)(`Superseded`,{by:Uk}){},$k=class extends H(`CancelReason/Revoked`)(`Revoked`,{}){},eA=F([Zk,Qk,$k]),tA=class extends H(`RunState/Pending`)(`Pending`,{}){},nA=class extends H(`RunState/Waiting`)(`Waiting`,{}){},rA=class extends H(`RunState/Queued`)(`Queued`,{}){},iA=class extends H(`RunState/Running`)(`Running`,{}){},aA=class extends H(`RunState/Succeeded`)(`Succeeded`,{}){},oA=class extends H(`RunState/Failed`)(`Failed`,{}){},sA=class extends H(`RunState/Canceled`)(`Canceled`,{reason:eA}){},cA=F([tA,nA,rA,iA]),lA=F([...cA.members,aA,oA,sA]),uA=F([tA,nA,rA]),dA=F([tA,rA]),fA=Bw(cA),pA=Bw(uA),mA=Bw(dA),hA=e=>({canApprove:e._tag===`Waiting`,canRetry:e._tag===`Failed`,canResolveFailure:e._tag===`Failed`,canCancel:fA(e),canRunAgain:e._tag===`Succeeded`||e._tag===`Canceled`}),gA=()=>(...e)=>e,_A=gA()(`Pending`,`Waiting`,`Queued`,`Running`),vA=gA()(`Pending`,`Waiting`,`Queued`,`Running`,`Succeeded`,`Failed`,`Canceled`),yA=gA()(`Pending`,`Waiting`,`Queued`),bA=e=>new nA,xA=e=>new rA,SA=e=>new iA,CA=e=>new aA,wA=e=>new oA,TA=e=>new iA,EA=e=>new sA({reason:new Zk}),DA=(e,t)=>new sA({reason:new Qk({by:t})}),OA=e=>new sA({reason:new $k}),kA=z.pipe(L(`RunId`)),AA=class extends V(`Run`)({id:kA,eventId:Uk,loop:Kk,state:lA,openedAt:_E}){},jA=M.check(PT(/\S/u,{message:`Expected a non-blank model ID`})).pipe(L(`ModelId`)),MA=bT([`claude`,`codex`,`pi`]),NA=bT([`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),PA=class extends V(`Agent/BrainSpec`)({harness:MA,model:jA,effort:NA}){},FA=M.check(PT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case agent name`})).pipe(L(`AgentName`)),IA=M.check(PT(/\S/u,{message:`Expected a non-blank agent persona`})).pipe(L(`AgentPersona`)),LA=class extends V(`Agent`)({name:FA,brain:PA,parentModel:yE(jA),parentEffort:xE(NA),persona:IA}){},RA=(e,t)=>xr([e.parentModel,t]),zA=(e,t)=>yr(xr([e.parentEffort,t]),()=>e.brain.effort),BA=M.check(PT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case worker name`})).pipe(L(`WorkerName`)),VA=bT([`local`,`exe.dev`,`ssh`,`cloudflare`]),HA=M.check(PT(/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\[bot\]$/u,{message:`Expected a GitHub bot login: <slug>[bot]`})).pipe(L(`BotLogin`)),UA=R.check(HT(1)).pipe(L(`BotUserId`)),WA=class extends V(`BotAccount`)({login:HA,id:UA}){get noreplyEmail(){return`${String(this.id)}+${this.login}@users.noreply.github.com`}},GA=M.check(PT(/^(?:[A-Za-z0-9._-]+@)?(?:[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?|[0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7})$/u,{message:`Expected an SSH destination: a host name or address, optionally prefixed by a user`})).pipe(L(`SshDestination`)),KA=R.check(UT({minimum:1,maximum:65535})).pipe(L(`SshPort`)),qA=M.check(PT(/^(?:\/|~\/)[!-~]+$/u,{message:`Expected an absolute or ~/ key path without spaces or control characters`})).pipe(L(`SshIdentityFile`)),JA=M.check(PT(/^(?:\/[!-.0-~]+)+$/u,{message:`Expected an absolute directory without spaces, control characters, or a trailing /`})).pipe(L(`WorkerRoot`)),YA=M.check(PT(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u,{message:`Expected a lowercase DNS domain`})).pipe(L(`GatewayDomain`)),XA=R.check(UT({minimum:1,maximum:65535})).pipe(L(`GatewayAdminPort`)),ZA=bT([`anthropic`,`openai`]),QA=bT([`api-key`,`subscription`]),$A=M.check(PT(/^[a-z0-9][A-Za-z0-9._/:@-]{0,254}$/u,{message:`Expected a container image reference, such as ghcr.io/owner/image:tag, without spaces or a leading dash`})).pipe(L(`ContainerImage`)),ej=M.check(PT(/^[0-9a-f]{64}$/u,{message:`Expected a container ID of 64 lowercase hex digits`})).pipe(L(`ContainerId`)),tj=FT.check(VT(0)).pipe(L(`ContainerCpus`)),nj=R.check(HT(256)).pipe(L(`ContainerMemoryMib`)),rj=R.check(HT(64)).pipe(L(`ContainerPids`)),ij=class extends V(`ContainerLimits`)({cpus:tj,memoryMib:nj,pids:rj}){},aj=[`cpus`,`memoryMib`,`pids`],oj=bT([`lite`,`basic`,`standard-1`,`standard-2`,`standard-3`,`standard-4`]),sj=M.check(PT(/^[A-Za-z_][A-Za-z0-9_]{0,62}$/u,{message:`Expected an image name of letters, digits, and underscores that doesn't start with a digit`})).pipe(L(`CloudflareImageName`)),cj=bT([`anthropic`,`openai`]),lj=bT([`hetzner`,`boat`]),uj=M.check(PT(/^[A-Za-z0-9_-]{1,64}$/u,{message:`Expected a provider machine ID`})).pipe(L(`MachineId`)),dj=M.check(PT(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner server type, such as cx33`})).pipe(L(`HetznerServerType`)),fj=M.check(PT(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner location, such as nbg1`})).pipe(L(`HetznerLocation`)),pj=M.check(PT(/^[!-~](?:[ -~]{0,253}[!-~])?$/u,{message:`Expected a Hetzner image ID, snapshot description, or image name`})).pipe(L(`HetznerImage`)),mj=M.check(PT(/^[!-~](?:[ -~]{0,126}[!-~])?$/u,{message:`Expected a Hetzner resource name without control characters`})).pipe(L(`HetznerResourceName`)),hj=/^(?:[a-z0-9A-Z](?:[-_.a-z0-9A-Z]*[a-z0-9A-Z])?\/)?[a-z0-9A-Z](?:[-_.a-z0-9A-Z]{0,61}[a-z0-9A-Z])?$/u,gj=mT(M,M.check(PT(/^(?:[a-z0-9A-Z](?:[-_.a-z0-9A-Z]{0,61}[a-z0-9A-Z])?)?$/u,{message:`Expected a Hetzner label value`}))).check(NT(e=>{let t=Object.keys(e),n=t.find(e=>!hj.test(e));if(n!==void 0)return`Expected a Hetzner label key, not "${n}"`;let r=t.find(e=>e.startsWith(`usine-`));return r===void 0||`Expected a label key that doesn't start with usine-, which usine sets itself, not "${r}"`})),_j=M.check(PT(/^[a-z_][a-z0-9_-]{0,31}$/u,{message:`Expected a Unix user name`})).pipe(L(`SshUser`)),vj=bT([`small`,`default`,`large`,`xlarge`]),yj=z.pipe(L(`AgentSessionId`)),bj=R.check(HT(0)).pipe(L(`TokenCount`)),xj=R.check(HT(1)),Sj=xj.pipe(L(`ChildSessionBudget`)),Cj=xj.pipe(L(`ChildSessionCount`)),wj=F([class extends H(`Agent/ParentSession`)(`ParentSession`,{id:yj,agent:FA,brain:PA}){},class extends H(`Agent/ChildSession`)(`ChildSession`,{id:yj,parentId:yj,agent:FA,brain:PA,gatewayCredential:xE(QA).pipe(TT(T(y())))}){}]),Tj=z.pipe(L(`HarnessSessionId`)),Ej=class extends V(`Agent/HarnessSession`)({id:Tj,cwd:z,home:xE(z).pipe(TT(T(y())))}){},Dj=class extends H(`Agent/SessionStarted`)(`SessionStarted`,{session:wj,harnessSession:xE(Ej).pipe(TT(T(y())))}){},Oj=class extends H(`Agent/TextOutput`)(`TextOutput`,{session:wj,text:z}){},kj=class extends H(`Agent/ToolStarted`)(`ToolStarted`,{session:wj,callId:z,tool:z,input:IE}){},Aj=class extends H(`Agent/ToolFinished`)(`ToolFinished`,{session:wj,callId:z,tool:z,output:IE,isError:cT}){},jj=class extends H(`Agent/SessionFinished`)(`SessionFinished`,{session:wj}){},Mj=class extends H(`Agent/SessionIdle`)(`SessionIdle`,{session:wj}){},Nj=class extends H(`Agent/SessionResumed`)(`SessionResumed`,{session:wj}){},Pj=FT.check(HT(0)).pipe(L(`UsdAmount`)),Fj=R.check(HT(0)),Ij=class extends V(`Agent/TokenBreakdown`)({input:Fj,cachedInput:Fj,cacheWrite:Fj,output:Fj}){},Lj=class extends H(`Agent/SessionTokensUpdated`)(`SessionTokensUpdated`,{session:wj,totalTokens:bj,costUsd:xE(Pj).pipe(TT(T(y()))),breakdown:xE(Ij).pipe(TT(T(y())))}){},Rj=bT([`apiKeys`,`claudePlan`,`chatgptPlan`]),zj=(e,t)=>{switch(e.harness){case`claude`:return Pr(t,`api-key`)?`apiKeys`:`claudePlan`;case`codex`:return Pr(t,`api-key`)?`apiKeys`:`chatgptPlan`;case`pi`:return e.model.startsWith(`openai-codex/`)?`chatgptPlan`:`apiKeys`}},Bj=e=>xk(e,{ParentSession:({brain:e})=>zj(e,y()),ChildSession:({brain:e,gatewayCredential:t})=>zj(e,t)}),Vj=class extends V(`Agent/RateLimitWindow`)({usedPercent:sT,windowDurationMinutes:yE(sT),resetsAt:yE(vE)}){},Hj=class extends V(`Agent/RateLimitsSnapshot`)({limitId:yE(M),limitName:yE(M),primary:yE(Vj),secondary:yE(Vj)}){},Uj=class extends H(`Agent/PoolRateLimitsUpdated`)(`PoolRateLimitsUpdated`,{session:wj,pool:Rj,rateLimits:Hj}){},Wj=xj.pipe(L(`ProviderRetries`)),Gj=F([Dj,Oj,kj,Aj,Uj,jj,Mj,Nj,Lj,class extends H(`Agent/ProviderRetrying`)(`ProviderRetrying`,{session:wj,message:z,retries:Wj}){},class extends H(`Agent/ProviderRecovered`)(`ProviderRecovered`,{session:wj,retries:Wj}){}]),Kj=e=>{let t=N(e),n=new Set(Object.keys(e)),r=mT(M.check(NT(e=>!n.has(e))),rT.annotate({message:`Unexpected key`}));return t.rebuild(hT(t,[r]).ast)},qj=M.check(PT(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u,{message:`Expected a GitHub login`})).pipe(L(`OperatorLogin`)),Jj=class extends H(`StepResult/Commit`)(`Commit`,{sha:zk,summary:z}){},Yj=class extends H(`StepResult/PullRequest`)(`PullRequest`,{number:R.check(HT(1)),url:rE}){},Xj=bT([`issue-comment`,`review`,`review-comment`]),Zj=class extends H(`StepResult/Comment`)(`Comment`,{url:rE,kind:Xj,at:xE(vE)}){},Qj=F([Jj,Yj,Zj]),$j=class extends V(`StepResult`)({message:z,facts:P(Qj)}){},eM=z.pipe(L(`StepName`)),tM=class extends V(`Step`)({runId:kA,name:eM,result:B($j)}){},nM=class extends NE(`AttemptFailure/InfraFailure`)(`InfraFailure`,{message:M,cause:eE()}){},rM=class extends NE(`AttemptFailure/DefectFailure`)(`DefectFailure`,{message:M,cause:eE()}){},iM=class extends NE(`AttemptFailure/AgentFailure`)(`AgentFailure`,{message:M}){},aM=class extends NE(`AttemptFailure/BlockedFailure`)(`BlockedFailure`,{message:z}){},oM=class extends NE(`AttemptFailure/QuestionFailure`)(`QuestionFailure`,{question:z}){},sM=bT([`wall-clock`,`tokens`]),cM=F([nM,rM,iM,aM,oM,class extends NE(`AttemptFailure/RunawayFailure`)(`RunawayFailure`,{ceiling:sM}){},class extends NE(`AttemptFailure/ChildSessionBudgetFailure`)(`ChildSessionBudgetFailure`,{maxChildren:Sj,attemptedChildren:Cj}){}]),lM=Bw(nM),uM=class extends H(`AttemptOutcome/Succeeded`)(`Succeeded`,{}){},dM=class extends H(`AttemptOutcome/Failed`)(`Failed`,{failure:cM}){},fM=class extends H(`AttemptOutcome/Canceled`)(`Canceled`,{}){},pM=F([uM,dM,fM]),mM=z.pipe(L(`SalvageRef`)),hM=(e,t)=>mM.make(`usine/salvage/${Bk(e)}/${t}`),gM=class extends H(`AttemptSalvage/Pushed`)(`Pushed`,{ref:mM,commit:zk}){},_M=F([gM,class extends H(`AttemptSalvage/PartlyPushed`)(`PartlyPushed`,{ref:mM,commit:zk,path:z,message:M}){},class extends H(`AttemptSalvage/Retained`)(`Retained`,{path:z,commit:yE(zk),message:M}){},class extends H(`AttemptSalvage/Rejected`)(`Rejected`,{path:z,commit:zk,message:M}){}]),vM=class extends H(`AttemptStart/Event`)(`Event`,{}){},yM=class extends H(`AttemptStart/Retry`)(`OperatorRetry`,{operator:yE(qj)}){},bM=class extends H(`AttemptStart/EditAndRetry`)(`EditAndRetry`,{operator:yE(qj)}){},xM=class extends H(`AttemptStart/InfraRetry`)(`InfraRetry`,{}){},SM=class extends H(`AttemptStart/AfterRestart`)(`AfterRestart`,{}){},CM=F([yM,bM]),wM=F([vM,yM,bM,xM,SM]),TM=z.pipe(L(`AttemptId`)),EM=R.check(HT(1)).pipe(L(`AttemptNumber`)),DM=M.check(PT(/\S/u,{message:`Expected non-blank task text`})).pipe(L(`AttemptTask`)),OM=bT([`cancel`,`failed`,`startup`]),kM=class extends V(`AttemptContext`)({task:DM,agent:LA,parentModel:yE(jA)}){},AM=class extends V(`FailureResolution`)(Kj({resolvedAt:vE,operator:yE(qj)})){},jM=R.check(HT(1)),MM=class extends V(`OutOfMemoryKills`)({kills:jM,memoryMib:nj}){},NM=class extends V(`ContainerOutOfMemoryKills`)({container:ej,kills:jM,memoryMib:nj}){},PM=e=>new MM({kills:e.reduce((e,{kills:t})=>e+t,0),memoryMib:ta(e).memoryMib}),FM=class extends V(`Attempt`)({id:TM,runId:kA,stepName:eM,worker:BA,number:EM,brain:PA,task:DM,agent:FA,operatorIntervened:cT,parentModel:yE(jA),startedAt:_E,outcome:B(pM),endedAt:B(_E),salvage:B(_M),failureResolution:B(AM).pipe(TT(T(y()))),start:B(wM).pipe(TT(T(y()))),reattachedAt:B(_E).pipe(TT(T(y()))),comments:P(Zj).pipe(TT(T([]))),outOfMemory:B(MM).pipe(TT(T(y())))}){},IM=class extends V(`AttemptWindow`)({attemptId:TM,startedAt:_E,endedAt:B(_E)}){},LM=e=>S(e.outcome)&&x(e.endedAt)?y():b(new IM({attemptId:e.id,startedAt:e.startedAt,endedAt:e.endedAt})),RM=e=>{let t=G_(e.startedAt);return t-t%1e3},zM=(e,t)=>vr(e.endedAt,{onNone:()=>!0,onSome:e=>t<=G_(e)}),BM=(e,t)=>{let n=G_(t);return RM(e)<=n&&zM(e,n)},VM=(e,t)=>zM(e,RM(t))&&zM(t,RM(e)),HM=class extends V(`AttemptWindows`)({own:B(IM),overlapping:P(IM)}){},UM=e=>lM(e.failure)&&e.number<e.maxAutoAttempts,WM=R.check(HT(1)).pipe(L(`AttemptChannelSequence`)),GM=[`inbound`,`outbound`],KM=bT(GM),qM=class extends V(`AttemptChannel/RunSpec`)({attemptId:TM,repository:Lk,revision:Rk,baseCommit:zk,payload:IE,task:DM,agent:LA,parentModel:yE(jA),maxChildren:Sj,parentEffort:NA,resume:yE(gM),conflictingSalvage:yE(gM).pipe(DT(T(null)),TT(T(y()))),preparedAt:yE(vE).pipe(DT(T(null))),botLogin:yE(HA).pipe(DT(T(null)))}){},JM=class extends H(`AttemptChannel/Started`)(`Started`,{parentModel:jA,conflictingSalvage:yE(gM).pipe(DT(T(null)),TT(T(y())))}){},YM=class extends H(`AttemptChannel/SessionEvent`)(`SessionEvent`,{event:Gj}){},XM=class extends H(`AttemptChannel/Final`)(`Final`,{result:$j}){},ZM=class extends H(`AttemptChannel/Failed`)(`Failed`,{failure:cM}){},QM=class extends H(`AttemptChannel/Interrupted`)(`Interrupted`,{}){},$M=class extends H(`AttemptChannel/Steer`)(`Steer`,{message:z}){},eN=class extends H(`AttemptChannel/Interrupt`)(`Interrupt`,{}){},tN=class extends H(`AttemptChannel/Cancel`)(`Cancel`,{}){},nN=class extends H(`AttemptChannel/OperatorMessage`)(`OperatorMessage`,{message:z}){},rN=class extends H(`AttemptChannel/Release`)(`Release`,{}){},iN=F([$M,eN,nN,rN]),aN=F([iN,tN]),oN=class extends H(`AttemptChannel/ParentTarget`)(`Parent`,{}){},sN=class extends H(`AttemptChannel/ChildTarget`)(`Child`,{sessionId:yj}){},cN=F([oN,sN]),lN=class extends V(`AttemptChannel/Intervention`)({operator:z,target:cN,action:iN}){},uN=class extends V(`AttemptChannel/InterventionState`)({held:cT,paused:cT,queued:cT.pipe(DT(T(!1)),TT(T(!1)))}){},dN=class extends H(`AttemptChannel/InterventionApplied`)(`InterventionApplied`,{inputSequence:WM,intervention:lN,state:uN}){},fN=class extends H(`AttemptChannel/InterventionRejected`)(`InterventionRejected`,{inputSequence:WM,intervention:lN,message:z}){},pN=class extends H(`AttemptChannel/WorkerUnresponsive`)(`WorkerUnresponsive`,{worker:BA,lastAnsweredAt:vE,reason:z}){},mN=class extends H(`AttemptChannel/WorkerResponsive`)(`WorkerResponsive`,{worker:BA,lastAnsweredAt:vE}){};F([pN,mN]);var hN=F([JM,YM,XM,ZM,QM,dN,fN,pN,mN]),gN={version:nT(7),attemptId:TM,sequence:WM,sentAt:vE},_N=class extends H(`AttemptChannel/OutboundEnvelope`)(`OutboundEnvelope`,{...gN,payload:hN}){},vN=class extends H(`AttemptChannel/InboundEnvelope`)(`InboundEnvelope`,{...gN,target:cN.pipe(DT(T({_tag:`Parent`}))),operator:z,payload:aN}){},yN=F([_N,vN]),bN=z.pipe(L(`ItemKey`)),xN=R.check(HT(1)).pipe(L(`ItemNumber`)),SN=class e extends Lr()(`@usine/engine/internal/RunDatabase`){static layer=t=>qf(e)(t)},CN=class extends V(`RunAgain`)(Kj({from:kA,requestedBy:yE(qj)})){},wN=[`ui`,`github-ask`],TN=bT(wN),EN=class extends V(`ApprovalSource`)(Kj({channel:TN,approver:yE(qj)}).check(NT(({channel:e,approver:t})=>e!==`github-ask`||S(t),{message:`Expected an approver for a GitHub ask approval`}))){},DN=class extends V(`RunApproval`)({approvedAt:_E,source:B(EN)}){},ON=R.check(HT(1)).pipe(L(`TranscriptSequence`)),kN=bT([3,4]),AN=N({..._N.fields,version:kN}),jN=N({_tag:nT(`InboundEnvelope`),version:kN,attemptId:TM,sequence:WM,sentAt:vE,payload:F([$M,eN])}),MN=bT([5,6]),NN=F([yN,N({..._N.fields,version:MN}),N({...vN.fields,version:MN}),AN,jN]),PN=class extends V(`@usine/engine/TranscriptEntry`)({sequence:ON,attemptId:TM,direction:KM,envelope:NN,receivedAt:_E}){},FN=class extends H(`@usine/engine/TranscriptAllQuery`)(`TranscriptAllQuery`,{attemptId:TM}){},IN=class extends H(`@usine/engine/TranscriptSessionsQuery`)(`TranscriptSessionsQuery`,{attemptId:TM}){},LN=class extends H(`@usine/engine/TranscriptUsageQuery`)(`TranscriptUsageQuery`,{attemptId:TM}){},RN=class extends H(`@usine/engine/TranscriptTailQuery`)(`TranscriptTailQuery`,{attemptId:TM,after:ON,limit:R.check(HT(1))}){},zN=class extends H(`@usine/engine/TranscriptPageQuery`)(`TranscriptPageQuery`,{attemptId:TM,before:B(ON),limit:R.check(HT(1))}){};F([FN,IN,LN,RN,zN]);var BN=class extends V(`@usine/engine/RunSnapshot`)({event:Gk,itemKey:bN,run:AA,step:tM,attempts:P(FM),resolvedFailureAttemptId:B(TM),closedAt:B(_E),approval:B(DN),runAgain:B(CN),repository:Lk,revision:Rk,task:DM,agent:LA,parentModel:B(jA),permissions:Xk}){},VN=class extends V(`@usine/engine/RunEvent`)({runId:kA,event:Gk}){},HN=class extends V(`@usine/engine/RunEvidence`)({snapshot:BN,transcript:P(PN)}){},UN=class extends V(`@usine/engine/RunSummary`)({itemKey:bN,run:AA,step:tM,attempts:P(FM),resolvedFailureAttemptId:B(TM),closedAt:B(_E),approval:B(DN),runAgain:B(CN),repository:Lk,task:DM,agent:LA}){},WN=class extends V(`@usine/engine/WorkerAttempts`)(N({worker:BA,attempts:R.check(HT(1)),running:R.check(HT(0))}).check(NT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},GN=class extends V(`@usine/engine/LoopSighting`)({loop:Kk,itemKey:bN,event:B(Uk),run:B(kA),suppressedBy:B(kA)}){},KN=R.check(HT(0)).pipe(L(`ProjectionRevision`)),qN=R.check(HT(1)).pipe(L(`CycleLimit`)),JN=R.check(HT(0)).pipe(L(`CycleGeneration`)),YN=qN.make(3),XN=R.check(HT(0)).pipe(L(`CycleCount`)),ZN=class extends V(`LoopCycleCount`)(Kj({loop:Kk,admitted:XN,completed:XN}).check(NT(({admitted:e,completed:t})=>t<=e,{message:`Completed runs can't exceed admitted runs`}))){},QN=Uk.pipe(L(`CycleBudgetAskId`)),$N=class extends V(`CycleBudgetAsk`)(Kj({id:QN,itemKey:bN,repository:Lk,loop:Kk,limit:qN,counts:vT(ZN)}).check(NT(({loop:e,limit:t,counts:n})=>new Set(n.map(e=>e.loop)).size===n.length&&n.some(n=>n.loop===e&&n.admitted>=t),{message:`Expected unique participating loops, including the exhausted loop at its limit`}))){get completedCycles(){return XN.make(Math.max(...this.counts.map(({completed:e})=>e)))}},eP=class extends NE(`@usine/engine/RunNotFoundError`)(`RunNotFoundError`,{runId:kA}){},tP=class extends NE(`@usine/engine/RunOperationRejectedError`)(`RunOperationRejectedError`,{runId:kA,operation:bT([`approve`,`retry`,`resolveFailure`,`runAgain`,`cancel`]),state:M}){},nP=class extends NE(`@usine/engine/RunRetryBlockedError`)(`RunRetryBlockedError`,{runId:kA,openRunId:kA,message:z}){},rP=class extends NE(`@usine/engine/EnginePersistenceError`)(`EnginePersistenceError`,{operation:M,cause:eE()}){},iP=class extends NE(`@usine/engine/AttemptCancellationError`)(`AttemptCancellationError`,{attemptId:TM,cause:eE()}){},aP=F([eP,tP,nP,rP]),oP=class extends NE(`@usine/engine/RunInterventionRejectedError`)(`RunInterventionRejectedError`,{runId:kA,attemptId:TM,message:z}){},sP=class extends NE(`@usine/engine/LeftoversDiscardRejectedError`)(`LeftoversDiscardRejectedError`,{worker:BA,running:R.check(HT(0))}){};F([eP,tP,nP,rP,iP,oP]);var cP=`~effect/encoding/Ndjson/NdjsonError`,lP=new TextEncoder,uP=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),dP=class extends Co(`NdjsonError`){[cP]=cP;get message(){return this.kind}},fP=e=>pe(e,cP),pP=()=>BD((e,t)=>T(D(e,e=>{try{return T(pa(e.map(e=>{let t=JSON.stringify(e);if(t===void 0)throw TypeError(`Value cannot be represented as JSON`);return t}).join(`
15
+ `)+`
16
+ `))}catch(e){return Hh(new dP({kind:`Pack`,cause:e}))}}))),mP=()=>ZD(pP(),ma(e=>lP.encode(e))),hP=(e,t,n)=>{let r,i,a=(e,t)=>(r=t,Ji(e)?T(e):t===void 0?void 0:Hh(t)),o=Lh(()=>r===void 0?i===void 0?eh(e,{onSuccess:e=>{let n=[];return a(n,t(e,n))??o},onFailure:Uh,onDone:e=>{i={leftover:e};let t=[];return a(t,n(t))??of(e)}}):of(i.leftover):Hh(r));return o},gP=(e,t,n,r)=>{if(!(n&&e.length===0))try{t.push(JSON.parse(e))}catch(e){return new dP({kind:`Unpack`,reason:`InvalidJson`,unterminated:r,cause:e})}},_P=10,vP=13,yP=new Uint8Array,bP=e=>BD((t,n)=>Rh(()=>{let n=e?.ignoreEmptyLines===!0,r=e?.maxLineBytes??1/0,i=new TextDecoder(`utf-8`,{fatal:!0}),a=[],o=0,s=!1,c=(e,t,n)=>{if(o===0)return e.subarray(t,n);let r=new Uint8Array(o+n-t),i=0;for(let e of a)r.set(e,i),i+=e.length;return r.set(e.subarray(t,n),i),a=[],o=0,r},l=(e,t,r)=>{let a;try{a=i.decode(e)}catch(e){return new dP({kind:`Unpack`,reason:`InvalidUtf8`,unterminated:r,cause:e})}let o=i!==uP;if(i=uP,!(o&&r&&a.length===0))return gP(a,t,n,r)};return hP(t,(e,t)=>{for(let n of e){let e=0;for(let i=0;i<n.length;i++){let a=n[i];if(a===_P||a===vP){if(a===_P&&s)e=i+1;else{let r=l(c(n,e,i),t,!1);if(r!==void 0)return r;e=i+1}s=a===vP}else if(s=!1,o+i+1-e>r)return new dP({kind:`Unpack`,reason:`LineTooLarge`,unterminated:!1,cause:RangeError(`NDJSON line exceeds maxLineBytes of ${r}`)})}e<n.length&&(a.push(n.slice(e)),o+=n.length-e)}},e=>o===0?void 0:l(c(yP,0,0),e,!0))})),xP=`~effect/encoding/Sse/SseError`,SP=class extends Co(`EventTooLarge`){get message(){return`Pending SSE event exceeded the maximum size of ${this.maxEventSize}`}},CP=class extends Co(`SseError`){[xP]=xP;get message(){return this.reason.message}},wP=10485760,TP=e=>BD((t,n)=>Rh(()=>{let n=[],r,i=DP(e=>{e._tag===`Retry`?r=e:n.push(e)},e),a=D(t,e=>{for(let t=0;t<e.length;t++){let n=i.feed(e[t]);if(n!==void 0)return Hh(n)}return zh});return Lh(function e(){if(Ji(n)){let e=n;return n=[],T(e)}return r?Hh(r):D(a,e)})})),EP=(e,t,n)=>dO(TP(t),bO(MP.pipe(ST(e,NP)),n)());function DP(e,t){let n=t?.maxEventSize??wP,r=t?.dispatchEmptyNamedEvents===!0,i,a,o,s,c=0,l,u,d;return f(),{feed:p,reset:f};function f(){c++,i=!0,a=[],o=0,s=!1,l=void 0,u=void 0,d=``}function p(e){i&&e.startsWith(OP)&&(e=e.slice(OP.length)),i=!1;let t=e.length,r=c,l=0;for(;l<t;){if(s&&(s=!1,e.charCodeAt(l)===kP)){++l;continue}let n=l;for(;n<t;){let t=e.charCodeAt(n);if(t===AP||t===kP)break;++n}if(n===t){a.push(e.slice(l)),o+=t-l;break}s=e.charCodeAt(n)===AP;let i=e.slice(l,n);if(a.length>0&&(a.push(i),i=a.join(``),a=[],o=0),m(i),c!==r)return;l=n+1}if(o+d.length>n){let e=new CP({reason:new SP({maxEventSize:n})});return f(),e}}function m(t){if(t.length===0){let t=u!==void 0&&u!==``,n=u||`message`,i=d;u=void 0,d=``,(i.length>0||r&&t)&&e({_tag:`Event`,id:l,event:n,data:i.slice(0,-1)});return}let n=t.indexOf(`:`),i=t,a=``;n>=0&&(i=t.slice(0,n),a=t.slice(t.charCodeAt(n+1)===jP?n+2:n+1)),i===`data`?d+=a+`
17
+ `:i===`event`?u=a:i===`id`&&!a.includes(`\0`)?l=a:i===`retry`&&/^\d+$/.test(a)&&e(new FP({duration:$a(parseInt(a,10)),lastEventId:l}))}}var OP=``,kP=10,AP=13,jP=32,MP=N({_tag:kT(`Event`),id:xT(M),event:M,data:M}),NP=Tb({decode:e=>e.id===void 0?{event:e.event,data:e.data}:{id:e.id,event:e.event,data:e.data},encode:e=>({_tag:`Event`,id:e.id,event:e.event??`message`,data:e.data})}),PP=`~effect/encoding/Sse/Retry`,FP=class e extends So(`Retry`){[PP]=PP;static is(e){return pe(e,PP)}static filter(t){return e.is(t)?xi(t):Si(t)}},IP=class extends V(`@usine/engine/Submission`)({event:Gk,itemKey:bN,loop:Kk,step:eM,approval:Jk,permissions:Xk.pipe(DT(T(`write`)),TT(T(`write`))),cycleLimit:B(qN).pipe(OT(T(b(YN))),TT(T(b(YN)))),cycleGeneration:JN.pipe(DT(T(JN.make(0))),TT(T(JN.make(0)))),repository:Lk,revision:Rk,task:DM,agent:LA,parentModel:B(jA)}){},LP=`@usine/engine/DurableRun`,RP=k(`Submission.runIdFor`)(function*(e){let t=yield*(yield*YO).digest(`SHA-256`,new TextEncoder().encode(`${LP}-${e.event.dedupKey}`)).pipe(dg);return kA.make(Eo(t.subarray(0,16)))}),zP=(e,t,n)=>{let r=Wk.make(JSON.stringify([`reopened`,n,t]));return new IP({...e,event:new Gk({...e.event,id:Uk.make(r),dedupKey:r})})},BP=class extends H(`@usine/engine/Claimed`)(`Claimed`,{eventId:Uk,runId:kA}){},VP=class extends H(`@usine/engine/Queued`)(`Queued`,{eventId:Uk}){},HP=[`superseded`,`revoked`],UP=bT(HP),WP=class extends H(`@usine/engine/Ignored`)(`Ignored`,{eventId:Uk,reason:UP}){},GP=class extends H(`@usine/engine/Suppressed`)(`Suppressed`,{eventId:Uk,runId:kA}){},KP=class extends H(`@usine/engine/CycleBlocked`)(`CycleBlocked`,{eventId:Uk,ask:$N}){},qP=F([BP,VP,GP,WP,KP]),JP=N({eventId:Uk,dedupKey:Wk,payload:IE,receivedAt:vE,itemKey:bN,loop:Kk,step:eM,approval:Jk,permissions:Xk,cycleLimit:I(qN),cycleGeneration:JN,repository:Lk,revision:Rk,task:DM,agent:LA,parentModel:I(jA)}),YP=N({itemKey:bN,repository:Lk,revision:Rk,task:DM,agent:LA,parentModel:I(jA),runId:kA,eventId:Uk,loop:Kk,state:lA,resolvedFailureAttemptId:I(TM),openedAt:vE,closedAt:I(vE),stepName:eM,result:I($j),approvedAt:I(vE),approvalChannel:I(TN),approver:I(qj),againFrom:I(kA),againRequestedBy:I(qj)}),XP=N({attemptId:TM,runId:kA,stepName:eM,worker:BA,number:EM,brain:PA,task:DM,agent:FA,operatorIntervened:cT,parentModel:I(jA),startedAt:vE,outcome:I(pM),endedAt:I(vE),salvage:I(_M),start:I(wM),failureResolution:I(AM),reattachedAt:I(vE),comments:I(P(Zj)),outOfMemory:I(P(NM))}),ZP=N({sequence:ON,attemptId:TM,direction:KM,envelope:PN.fields.envelope,receivedAt:vE}),QP=N({runId:kA}),$P=N({reason:UP}),eF=N({revision:KN}),tF=N({runId:kA,eventId:Uk,dedupKey:Wk,payload:IE,receivedAt:vE}),nF=N({...JP.fields,reopening:R}),rF=N({eventId:Uk,dedupKey:Wk}),iF=Vw(P(JP)),aF=Vw(P(nF)),oF=Vw(P(rF)),sF=Vw(P(YP)),cF=Vw(P(tF)),lF=Vw(P(XP)),uF=Vw(P(QP)),dF=Vw(P($P)),fF=Vw(P(eF)),pF=Vw(P(ZP)),mF=Yw(IE),hF=Yw(vE),gF=Yw(lA),_F=Yw(pM),vF=Yw(_M),yF=Yw(P(Zj)),bF=Yw(P(NM)),xF=Vw(P(N({outOfMemory:I(P(NM))}))),SF=Yw(AM),CF=Yw(wM),wF=Vw(P(N({nextStart:I(CM)}))),TF=Yw($j),EF=Yw(yN),DF=Yw(LA),OF=Yw(PA),kF=Bw(aP),AF=e=>t=>ug(t,t=>kF(t)?t:new rP({operation:e,cause:t})),jF=e=>new Gk({id:e.eventId,dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),MF=e=>new VN({runId:e.runId,event:jF(e)}),NF=e=>new IP({event:jF(e),itemKey:e.itemKey,loop:e.loop,step:e.step,approval:e.approval,permissions:e.permissions,cycleLimit:C(e.cycleLimit),cycleGeneration:e.cycleGeneration,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:C(e.parentModel)}),PF=e=>new AA({id:e.runId,eventId:e.eventId,loop:e.loop,state:e.state,openedAt:e.openedAt}),FF=e=>Dr(C(e.approvedAt),t=>new DN({approvedAt:t,source:Dr(C(e.approvalChannel),t=>new EN({channel:t,approver:C(e.approver)}))})),IF=e=>Dr(C(e.againFrom),t=>new CN({from:t,requestedBy:C(e.againRequestedBy)})),LF=e=>new tM({runId:e.runId,name:e.stepName,result:C(e.result)}),RF=e=>new FM({id:e.attemptId,runId:e.runId,stepName:e.stepName,worker:e.worker,number:e.number,brain:e.brain,task:e.task,agent:e.agent,operatorIntervened:e.operatorIntervened,parentModel:C(e.parentModel),startedAt:e.startedAt,outcome:C(e.outcome),endedAt:C(e.endedAt),salvage:C(e.salvage),start:C(e.start),failureResolution:C(e.failureResolution),reattachedAt:C(e.reattachedAt),comments:e.comments??[],outOfMemory:Nr(e.outOfMemory??[],Yi).pipe(Dr(PM))}),zF=(e,t)=>new UN({itemKey:e.itemKey,run:PF(e),step:LF(e),attempts:t.map(RF),resolvedFailureAttemptId:C(e.resolvedFailureAttemptId),closedAt:C(e.closedAt),approval:FF(e),runAgain:IF(e),repository:e.repository,task:e.task,agent:e.agent}),BF=e=>new PN({sequence:e.sequence,attemptId:e.attemptId,direction:e.direction,envelope:e.envelope,receivedAt:e.receivedAt}),U=Symbol.for(`drizzle:entityKind`),VF=new WeakMap;function HF(e){let t=new Set;for(let n=e;n;n=Object.getPrototypeOf(n))U in n&&t.add(n[U]);return VF.set(e,t),t}var UF=Function.prototype[Symbol.hasInstance];function W(e,t){if(UF.call(t,e))return!0;if(typeof e!=`object`||!e)return!1;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`&&(VF.get(n)??HF(n)).has(t[U])}function WF(e){if(typeof e!=`object`||!e)return;let t=Object.getPrototypeOf(e)?.constructor;if(typeof t==`function`)return VF.get(t)??HF(t)}var GF=class extends Error{static[U]=`DrizzleError`;static[Symbol.hasInstance](e){return W(e,this)}constructor({message:e,cause:t}){super(e),this.name=`DrizzleError`,this.cause=t}},KF=Symbol.for(`drizzle:Name`),qF=Symbol.for(`drizzle:Schema`),JF=Symbol.for(`drizzle:Columns`),YF=Symbol.for(`drizzle:ExtraConfigColumns`),XF=Symbol.for(`drizzle:OriginalName`),ZF=Symbol.for(`drizzle:BaseName`),QF=Symbol.for(`drizzle:CacheKey`),$F=Symbol.for(`drizzle:IsAlias`),eI=Symbol.for(`drizzle:Qualifier`),tI=Symbol.for(`drizzle:ExtraConfigBuilder`),nI=Symbol.for(`drizzle:IsDrizzleTable`),rI=class{static[U]=`Table`;static[Symbol.hasInstance](e){return W(e,this)}static Symbol={Name:KF,Schema:qF,OriginalName:XF,Columns:JF,ExtraConfigColumns:YF,BaseName:ZF,IsAlias:$F,ExtraConfigBuilder:tI,CacheKey:QF};[KF];[XF];[qF];[JF];[YF];[ZF];[QF];[$F]=!1;[nI]=!0;[tI]=void 0;constructor(e,t,n){this[KF]=this[XF]=e,this[qF]=t,this[ZF]=n,this[QF]=t?`${t}.${e}`:e}};function iI(e){return e[KF]}var aI=Symbol.for(`drizzle:OriginalColumn`),oI=e=>e;oI.isNoop=!0;var sI=class{static[U]=`Column`;static[Symbol.hasInstance](e){return W(e,this)}codec;name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;length;isLengthExact;isAlias;config;table;onInit(){}constructor(e,t){this.config=t,this.onInit(),this.table=e,this.name=t.name,this.isAlias=!1,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity,this.length=t.length,this.isLengthExact=t.isLengthExact}mapFromDriverValue=oI;mapToDriverValue=oI;postBuild(){return this}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}[aI](){return this}},G=class{value;static[U]=`StringChunk`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.value=e}},K={", ":new G(`, `)," ":new G(` `),"(":new G(`(`),")":new G(`)`),"((":new G(`((`),"))":new G(`))`),"), (":new G(`), (`),".":new G(`.`),default:new G(`default`),null:new G(`null`),"1 = 0":new G(`1 = 0`),"1 = 1":new G(`1 = 1`)," = ":new G(` = `)," <> ":new G(` <> `)," > ":new G(` > `)," >= ":new G(` >= `)," < ":new G(` < `)," <= ":new G(` <= `)," in ":new G(` in `)," not in ":new G(` not in `),") and (":new G(`) and (`),") or (":new G(`) or (`),"not (":new G(`not (`),"with ":new G(`with `),"select ":new G(`select `),"(select ":new G(`(select `),"values ":new G(`values `)," from ":new G(` from `),".* from ":new G(`.* from `)," as ":new G(` as `),") as ":new G(`) as `)," inner join ":new G(` inner join `)," cross join ":new G(` cross join `)," on ":new G(` on `)," where ":new G(` where `)," order by ":new G(` order by `)," asc":new G(` asc`)," desc":new G(` desc`)," limit ":new G(` limit `)," limit 1":new G(` limit 1`)," offset ":new G(` offset `),"top(1) ":new G(`top(1) `),"exists (select * from ":new G(`exists (select * from `),"not exists (select * from ":new G(`not exists (select * from `),"select count(*) as ":new G(`select count(*) as `),"(select count(*) from ":new G(`(select count(*) from `),"min(":new G(`min(`),"max(":new G(`max(`),"count(":new G(`count(`),"avg(":new G(`avg(`),"first(":new G(`first(`)},cI=Symbol.for(`drizzle:ViewBaseConfig`),lI=Symbol.for(`drizzle:IsDrizzleView`),uI=class{static[U]=`View`;static[Symbol.hasInstance](e){return W(e,this)}[cI];[lI]=!0;get[KF](){return this[cI].name}get[qF](){return this[cI].schema}get[$F](){return this[cI].isAlias}get[XF](){return this[cI].originalName}get[JF](){return this[cI].selectedFields}constructor({name:e,schema:t,selectedFields:n,query:r}){this[cI]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}},dI=class{static[U]=`Subquery`;static[Symbol.hasInstance](e){return W(e,this)}get[KF](){return this._.alias}get[qF](){}get[XF](){return this._.alias}get[$F](){return!1}get[JF](){return this._.selectedFields}constructor(e,t,n,r=!1){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r}}},fI=class extends dI{static[U]=`WithSubquery`};function pI(e){return e!=null&&typeof e.getSQL==`function`}var mI=class e{queryChunks;static[U]=`SQL`;static[Symbol.hasInstance](e){return W(e,this)}decoder=SI;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return this.buildQueryFromSourceParams(this.queryChunks,e)}buildQueryFromSourceParams(e,t){let n={sql:``},r=[],i=t.tagged?[]:void 0;this.collectSQL(e,t,t.paramStartIndex||{value:0},t.inlineParams||this.shouldInlineParams,n,r,i);let a=n.sql;if(i===void 0)return{sql:a,params:r};let o=Array(i.length);for(let e=0;e<i.length;++e)o[e]=a.slice(i[e],e+1<i.length?i[e+1]:a.length);return{sql:a,params:r,_sql:Object.assign(o,{raw:o})}}collectSQL(e,t,n,r,i,a,o){let{escapeName:s,escapeParam:c,codecs:l,invokeSource:u}=t;for(let d=0;d<e.length;++d){o!==void 0&&o.push(i.sql.length);let f=e[d],p=vI(f);if(yI(f,p,q.string))i.sql+=f.value??``;else if(yI(f,p,q.sql))this.collectSQL(f.queryChunks,t,n,r||f.shouldInlineParams,i,a,void 0);else if(yI(f,p,q.name))i.sql+=s(f.value);else if(f!==void 0){if(yI(f,p,q.column)){let e=f.name;if(u===`indexes`){i.sql+=s(e);continue}let t=u===`mssql-check`?void 0:f.table[rI.Symbol.Schema];i.sql+=f.isAlias?s(f.name):f.table[$F]||t===void 0?s(f.table[rI.Symbol.Name])+`.`+s(e):s(t)+`.`+s(f.table[rI.Symbol.Name])+`.`+s(e)}else if(yI(f,p,q.param)){let e=f.value,o=vI(e);if(yI(e,o,q.sql)){let o=e;this.collectSQL(o.queryChunks,t,n,r||o.shouldInlineParams,i,a,void 0);continue}let s=f.encoder,u=l&&vI(s)===q.column?l.codecsOf(s):void 0;if(o===q.placeholder){let e=c(n.value++,f),t=u?.normalizeParam,r=u?.castParam;f.codec=t?e=>t(e,s.dimensions):void 0,i.sql+=r?r(e,s,s.dimensions):e,a.push(f);continue}this.collectBoundValue(e,s,u,t,n,r,i,a)}else if(yI(f,p,q.placeholder))i.sql+=c(n.value++,f),a.push(f);else if(yI(f,p,q.table)){let e=f[rI.Symbol.Schema],t=f[rI.Symbol.Name];if(u===`mssql-view-with-schemabinding`){i.sql+=s(e===void 0?`dbo`:e)+`.`+s(t);continue}i.sql+=e===void 0||f[$F]?s(t):s(e)+`.`+s(t)}else if(yI(f,p,q.view)){let e=f[cI].schema,t=f[cI].name;i.sql+=e===void 0||f[cI].isAlias?s(t):s(e)+`.`+s(t)}else if(yI(f,p,q.aliased)&&f.fieldAlias!==void 0)i.sql+=(f.origin===void 0?``:s(f.origin)+`.`)+s(f.fieldAlias);else if(yI(f,p,q.valueRows)){let{cells:e,encoders:o}=f,s=o.length,c=Array(s);for(let e=0;e<s;++e){let t=o[e];c[e]=l&&vI(t)===q.column?l.codecsOf(t):void 0}i.sql+=`(`;for(let l=0,u=0;l<e.length;++l,++u){u===s?(u=0,i.sql+=`), (`):u>0&&(i.sql+=`, `);let d=e[l],f=vI(d);f===q.other?this.collectBoundValue(d,o[u],c[u],t,n,r,i,a):yI(d,f,q.string)?i.sql+=d.value??``:this.collectSQL([f===q.sql?d:new wI(d,o[u])],t,n,r,i,a,void 0)}i.sql+=`)`}else if(yI(f,p,q.subquery)){if(f._.isWith){i.sql+=s(f._.alias);continue}let e=f._.sql;i.sql+=`(`,this.collectSQL(e.queryChunks,t,n,r||e.shouldInlineParams,i,a,void 0),i.sql+=`) `+s(f._.alias)}else if(typeof f==`function`&&`enumName`in f){if(`schema`in f&&f.schema){i.sql+=s(f.schema)+`.`+s(f.enumName);continue}i.sql+=s(f.enumName)}else if(pI(f)){let e=f.getSQL(),o=r||e.shouldInlineParams;if(f.shouldOmitSQLParens?.()){this.collectSQL(e.queryChunks,t,n,o,i,a,void 0);continue}i.sql+=`(`,this.collectSQL(e.queryChunks,t,n,o,i,a,void 0),i.sql+=`)`}else if(Array.isArray(f)){i.sql+=`(`;let e=[void 0];for(let o=0;o<f.length;++o)o>0&&(i.sql+=`, `),e[0]=f[o],this.collectSQL(e,t,n,r,i,a,void 0);i.sql+=`)`}else r?i.sql+=this.mapInlineParam(f,t):(i.sql+=c(n.value++,f),a.push(f))}}}collectBoundValue(e,t,n,r,i,a,o,s){let c=e;if(e!==null){if(t.mapToDriverValue.isNoop||(c=t.mapToDriverValue(e)),vI(c)===q.sql){let e=c;this.collectSQL(e.queryChunks,r,i,a||e.shouldInlineParams,o,s,void 0);return}let l=n?.normalizeParam;!a&&l&&(c=l(c,t.dimensions))}if(a){o.sql+=this.mapInlineParam(c,r);return}let{escapeParam:l}=r,u=l(i.value++,c),d=n?.castParam;o.sql+=d?d(u,t,t.dimensions):u,s.push(c)}mapInlineParam(e,{escapeString:t}){if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return e.toString();if(typeof e==`string`)return t(e);if(typeof e==`object`){let n=e.toString();return t(n===`[object Object]`?JSON.stringify(e):n)}throw Error(`Unexpected param value: `+e)}getSQL(){return this}as(t){return t===void 0?this:new e.Aliased(this,t)}mapWith(e){return this.decoder=typeof e==`function`?{mapFromDriverValue:e}:e,this}nullable(){return this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},q={other:0,string:1,sql:2,name:3,column:4,param:5,placeholder:6,table:7,view:8,aliased:9,subquery:10,valueRows:11},hI=new WeakMap,gI=Symbol(`drizzle:chunkKind`);function _I(e,t){let n=t.has(G[U])?q.string:t.has(mI[U])?q.sql:t.has(bI[U])?q.name:t.has(sI[U])?q.column:t.has(wI[U])?q.param:t.has(DI[U])?q.placeholder:t.has(rI[U])?q.table:t.has(uI[U])?q.view:t.has(mI.Aliased[U])?q.aliased:t.has(dI[U])?q.subquery:t.has(TI[U])?q.valueRows:q.other;return hI.set(e,n),n!==q.other&&Object.defineProperty(e.prototype,gI,{value:n}),n}function vI(e){if(typeof e!=`object`||!e)return q.other;let t=e[gI];if(t!==void 0)return t;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`?hI.get(n)??_I(n,WF(e)):q.other}function yI(e,t,n){return t===n}var bI=class{value;static[U]=`Name`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e){this.value=e}getSQL(){return new mI([this])}};function xI(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}var SI={mapFromDriverValue:e=>e};SI.mapFromDriverValue.isNoop=!0;var CI={mapToDriverValue:e=>e};CI.mapToDriverValue.isNoop=!0,{...SI,...CI};var wI=class{value;encoder;codec;static[U]=`Param`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e,t=CI,n){this.value=e,this.encoder=t,this.codec=n}getSQL(){return new mI([this])}},TI=class{cells;encoders;static[U]=`ValueRows`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t){this.cells=e,this.encoders=t}getSQL(){let{cells:e,encoders:t}=this,n=t.length,r=[];for(let i=0;i<e.length;++i){let a=i%n;r.push(a===0?i===0?K[`(`]:K[`), (`]:K[`, `]);let o=e[i],s=vI(o);r.push(s===q.sql||s===q.string?o:new wI(o,t[a]))}return r.push(K[`)`]),new mI(r)}shouldOmitSQLParens(){return!0}};function J(e,...t){let n=[];e[0]&&n.push(new G(e[0]));for(let r=0;r<t.length;++r){let i=t[r];i!==void 0&&n.push(i);let a=e[r+1];a&&n.push(new G(a))}return new mI(n)}(function(e){function t(){return new mI([])}e.empty=t;function n(e){return new mI(e)}e.fromList=n;function r(e){return new mI([new G(e)])}e.raw=r;function i(e,t){let{length:n}=e;if(t===void 0||n===0)return new mI(e.slice());let r=Array(n*2-1);for(let i=0,a=0;i<n;++i)r[a++]=e[i],i<n-1&&(r[a++]=t);return new mI(r)}e.join=i;function a(e){return new bI(e)}e.identifier=a;function o(e){return new DI(e)}e.placeholder=o;function s(e,t){return new wI(e,t)}e.param=s;function c(e){let t=EI(e);if(t.length)return J.raw(t)}e.comment=c})(J||={});function EI(e){let t=EI.encodeInput(e);return t.length?`/*${t}*/`:``}(function(e){function t(e,t){let r;if(typeof e==`object`&&typeof t==`object`)r=n({...e,...t});else if(e&&t)r=[n(e),n(t)].filter(e=>e.length).join(`,`);else if(t)r=n(t);else if(e)r=n(e);else return``;return r.length?`/*${r}*/`:``}e.merge=t;function n(e){if(typeof e==`string`)return e.length?i(e):e;let t=[];for(let[n,i]of Object.entries(e)){if(i==null||i===``)continue;let e=r(n),a=r(String(i));t.push(`${e}='${a}'`)}return t.length?t.sort().join(`,`):``}e.encodeInput=n;function r(e){return encodeURIComponent(e).replace(/'/g,`\\'`)}e.sanitizeObjectElement=r;function i(e){return e.replace(/\/\*/g,`/ *`).replace(/\*\//g,`* /`)}e.sanitizeStringInput=i})(EI||={}),(function(e){class t{sql;fieldAlias;static[U]=`SQL.Aliased`;static[Symbol.hasInstance](e){return W(e,this)}isSelectionField=!1;origin;constructor(e,t){this.sql=e,this.fieldAlias=t}getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(mI||={});var DI=class{name;static[U]=`Placeholder`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}getSQL(){return new mI([this])}};function OI(e){let t=e.queryChunks,n;for(let e=0;e<t.length;++e){let r=t[e];W(r,sI)&&((n??=[...t])[e]=J.identifier(r.name))}if(!n)return e;let r=new mI(n);return r.decoder=e.decoder,r.shouldInlineParams=e.shouldInlineParams,r}function kI(e,t){for(let n=0;n<e.length;++n){let r=e[n];switch(vI(r)){case q.table:t.add(r[QF]);break;case q.sql:kI(r.queryChunks,t);break;case q.param:{let e=r.value;vI(e)===q.sql&&kI(e.queryChunks,t);break}case q.subquery:kI(r._.sql.queryChunks,t);break;case q.valueRows:kI(r.cells,t);break;case q.other:case q.aliased:Array.isArray(r)?kI(r,t):pI(r)&&kI(r.getSQL().queryChunks,t)}}}sI.prototype.getSQL=function(){return new mI([this])},G.prototype.getSQL=function(){return new mI([this])},dI.prototype.getSQL=function(){return new mI([this])};function AI(e,t){Object.defineProperty(e,eI,{get(){let e=t(this);return Object.defineProperty(this,eI,{value:e,enumerable:!1,configurable:!0,writable:!0}),e},configurable:!0})}function jI(e,t){return new mI(e===void 0?[new bI(t)]:[new bI(e),K[`.`],new bI(t)])}AI(rI.prototype,e=>jI(e[qF],e[KF])),AI(uI.prototype,e=>jI(e[cI].schema,e[cI].name)),AI(dI.prototype,e=>new bI(e._.alias));function MI(e,t){let n=Array(t.length);for(let r=0;r<t.length;++r){let i=t[r],a=[];for(let t=0;t<e.length;++t){let n=e[t].path;n.length>1&&n[0]===i&&a.push(t)}n[r]={key:i,leaves:a}}return n}var NI=Object.getPrototypeOf(()=>null).constructor;function PI(e,t){let n=[],r=[];r.push(`const [ ${e.map((e,t)=>`c${t}`).join(`, `)} ] = rows[i];`);let i={},a=new Set(t??[]),o=Array(e.length);for(let t=0;t<e.length;++t){let{field:r,fieldType:a,path:s,codec:c,arrayDimensions:l}=e[t],u,d,f;switch(a){case`Column`:u=r,f=`field: decoder${t}`;break;case`SQL`:u=r.decoder,f=`field: { decoder: decoder${t} }`;break;case`Subquery`:u=r._.sql.decoder,f=`field: { _: { sql: { decoder: decoder${t} } } }`;break;default:u=r.sql.decoder,f=`field: { sql: { decoder: decoder${t} } }`}d=`decoder${t}.mapFromDriverValue`,u.mapFromDriverValue.isNoop&&(d=``),d?n.push(`const { ${f}${c?`, codec: codec${t}`:``} } = columns[${t}];`):c&&n.push(`const { codec: codec${t} } = columns[${t}];`);let p=`c${t}`,m=p;c&&(m=`codec${t}(${m}, ${l})`),d&&(m=`${d}(${m})`),o[t]=p===m?`${p}`:`${p} === null ? ${p} : ${m}`,s.length>1&&(i[s[0]]??=[]).push(p)}r.push(`mapped[i] = {`);let s=[];for(let t=0;t<e.length;++t){let{path:n}=e[t],c=n.map(e=>JSON.stringify(e)),l=o[t],u=n.slice(0,-1),d=0;for(;d<s.length&&d<u.length&&s[d]===u[d];)d++;for(let e=s.length-1;e>=d;--e)r.push(`${` `.repeat(e+1)}},`);for(let e=d;e<u.length;++e){let t=e===0&&a.has(n[0]);r.push(`${` `.repeat(e+1)}${c[e]}: ${t?`${i[n[0]].map(e=>`${e} === null`).join(` && `)} ? null : {`:`{`}`)}s=u,r.push(`${` `.repeat(n.length)}${c[n.length-1]}: ${l},`)}for(let e=s.length-1;e>=0;--e)r.push(`${` `.repeat(e+1)}},`);return r.push(`};`),`${n.length?`${n.join(`
18
+ `)}\n\t`:``}for (let i = 0; i < length; ++i) {
19
+ ${r.join(`
20
+ `)}
21
+ }`}function FI(e,t){let n=`\t"use strict";
22
+ const { columns } = this;
23
+ const { length } = rows;
24
+ const mapped = new Array(length);
25
+ ${PI(e,t)}
26
+ return mapped;
27
+ //# sourceURL=drizzle:jit-query-mapper`;return Object.assign(new NI(`rows`,n).bind({columns:e}),{body:`function jitQueryMapper (rows) {\n${n}\n}`})}function II(e,t){let n=Array(e.length);for(let t=0;t<e.length;++t){let{field:r,fieldType:i,codec:a,arrayDimensions:o}=e[t],s;switch(i){case`Column`:s=r;break;case`SQL`:s=r.decoder;break;case`Subquery`:s=r._.sql.decoder;break;default:s=r.sql.decoder}let c;c=s.mapFromDriverValue.isNoop?a?e=>a(e,o):void 0:a?e=>s.mapFromDriverValue(a(e,o)):e=>s.mapFromDriverValue(e),n[t]=c}let r=t?.length?MI(e,t):void 0;return(t=>{let{length:i}=t,a=Array(i);for(let o=0;o<i;++o){let i=t[o],s={};for(let t=0;t<e.length;++t){let{path:r}=e[t],a=s;for(let e=0;e<r.length;++e){let o=r[e];if(e<r.length-1)o in a||(a[o]={}),a=a[o];else{let e=n[t],r=i[t];a[o]=r===null?null:e?e(r):r}}}if(r)for(let e=0;e<r.length;++e){let{key:t,leaves:n}=r[e],a=!0;for(let e=0;e<n.length;++e)if(i[n[e]]!==null){a=!1;break}a&&(s[t]=null)}a[o]=s}return a})}function LI(e,t,n,r=[]){let i=Object.entries(e);for(let e=0;e<i.length;++e){let[a,o]=i[e];if(typeof a!=`string`)return r;let s=t?[...t,a]:[a];if(W(o,sI))r.push({path:s,field:o,fieldType:`Column`,codec:n?.get(o,`normalize`),arrayDimensions:o.dimensions,column:o});else if(W(o,mI)){let e=RI(o);r.push(e?{path:s,field:o,fieldType:`SQL`,codec:n?.get(e,`normalize`),arrayDimensions:e.dimensions,column:e}:{path:s,field:o,fieldType:`SQL`})}else if(W(o,mI.Aliased)){let e=RI(o);r.push(e?{path:s,field:o,fieldType:`SQL.Aliased`,codec:n?.get(e,`normalize`),arrayDimensions:e.dimensions,column:e}:{path:s,field:o,fieldType:`SQL.Aliased`})}else if(W(o,dI)){let e,t=Object.values(o._.selectedFields)[0],i;W(t,sI)?(e=t,i=t):W(t,mI)?(e=RI(t),i=t.decoder):(e=RI(t),i=t.sql.decoder),i&&(o._.sql.decoder=i),r.push(e?{path:s,field:o,fieldType:`Subquery`,codec:n?.get(e,`normalize`),arrayDimensions:e.dimensions,column:e}:{path:s,field:o,fieldType:`Subquery`})}else W(o,rI)?LI(o[rI.Symbol.Columns],s,n,r):LI(o,s,n,r)}return r}function RI(e){let{decoder:t}=e.getSQL();return yI(t,vI(t),q.column)?t:void 0}function zI(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let[e,t]of n.entries())if(t!==r[e])return!1;return!0}function BI(e){return e[rI.Symbol.Columns]}function VI(e){let t=vI(e);return yI(e,t,q.subquery)?e._.alias:yI(e,t,q.view)?e[cI].name:yI(e,t,q.sql)?void 0:e[rI.Symbol.IsAlias]?e[rI.Symbol.Name]:e[rI.Symbol.BaseName]}function HI(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}typeof TextDecoder>`u`||new TextDecoder;function UI(e,t=4096){let n=new Map;return r=>{let i=n.get(r);return i===void 0&&(n.size>=t&&n.clear(),i=e(r),n.set(r,i)),i}}var WI=class{table;ignoreColumnAlias;static[U]=`ColumnTableAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t){this.table=e,this.ignoreColumnAlias=t}get(e,t){return t===`table`?this.table:t===`isAlias`&&this.ignoreColumnAlias?!1:t===aI&&!this.ignoreColumnAlias?()=>e:e[t]}},GI=class{view;selection;ignoreColumnAlias;static[U]=`ViewSelectionAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t,n){this.view=e,this.selection=t,this.ignoreColumnAlias=n}memo;columnHandler;get(e,t){let n=e[t];if(typeof n!=`object`||!n)return n;let r=this.memo??=new WeakMap,i=r.get(n);return i===void 0&&(i=yI(n,vI(n),q.column)?new Proxy(n,this.columnHandler??=new WI(this.view,this.ignoreColumnAlias)):pI(n)?n:new Proxy(n,this),r.set(n,i)),i}},KI=class{alias;replaceOriginalName;ignoreColumnAlias;static[U]=`TableAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t,n){this.alias=e,this.replaceOriginalName=t,this.ignoreColumnAlias=n}qualifier;proxiedColumns;memo;columnHandler;get(e,t,n){if(t===eI)return this.qualifier??=J.identifier(this.alias);if(t===rI.Symbol.IsAlias)return!0;if(t===rI.Symbol.Name||this.replaceOriginalName&&t===rI.Symbol.OriginalName)return this.alias;if(t===rI.Symbol.Columns){let t=e[rI.Symbol.Columns];return t&&(yI(e,vI(e),q.view)?this.aliasSelection(t,n):this.getProxiedColumns(t,n))}if(t===cI){let t=e[cI],r=this.memo??=new WeakMap,i=r.get(t);return i===void 0&&r.set(t,i={...t,name:this.alias,isAlias:!0,selectedFields:this.aliasSelection(t.selectedFields,n)}),i}let r=e[t];if(yI(r,vI(r),q.column)){let i=e[rI.Symbol.Columns];if(typeof t==`string`&&i?.[t]===r)return this.getProxiedColumns(i,n)[t];let a=this.memo??=new WeakMap,o=a.get(r);return o===void 0&&a.set(r,o=this.aliasColumn(r,n)),o}return r}aliasColumn(e,t){return new Proxy(e,this.columnHandler??=new WI(t,this.ignoreColumnAlias))}aliasSelection(e,t){let n=this.memo??=new WeakMap,r=n.get(e);return r===void 0&&n.set(e,r=new Proxy(e,new GI(t,e,this.ignoreColumnAlias))),r}getProxiedColumns(e,t){if(this.proxiedColumns)return this.proxiedColumns;let n={};for(let r of Object.keys(e))n[r]=this.aliasColumn(e[r],t);return this.proxiedColumns=n}},qI=class{subquery;alias;static[U]=`SubquerySelectionAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t){this.subquery=e,this.alias=t}memo;columnHandler;get(e,t){let n=e[t];if(typeof n!=`object`||!n)return n;let r=this.memo??=new WeakMap,i=r.get(n);if(i!==void 0)return i;let a=vI(n);return yI(n,a,q.column)?i=new Proxy(n,this.columnHandler??=new WI(this.subquery,!0)):yI(n,a,q.aliased)?(i=n.clone(),i.isSelectionField=!0,i.origin=this.alias):i=n,r.set(n,i),i}},JI=class{alias;static[U]=`SubqueryAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.alias=e}qualifier;config;selection;get(e,t,n){if(t===eI)return this.qualifier??=J.identifier(this.alias);if(t===rI.Symbol.IsAlias)return!0;if(t===rI.Symbol.Name)return this.alias;if(t===rI.Symbol.OriginalName)return e._.alias;if(t!==rI.Symbol.Schema)return t===`_`?this.config??={...e._,alias:this.alias,isWith:!0,selectedFields:this.aliasSelection(e,n)}:t===rI.Symbol.Columns?this.aliasSelection(e,n):e[t]}aliasSelection(e,t){return this.selection??=new Proxy(e._.selectedFields,new qI(t,this.alias))}},YI=class{alias;static[U]=`ColumnAliasProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.alias=e}get(e,t){return t===`isAlias`?!0:t===`name`?this.alias:t===`keyAsName`?!1:t===aI?()=>e:e[t]}};function XI(e,t){return yI(e,vI(e),q.subquery)?new Proxy(e,new JI(t)):new Proxy(e,new KI(t,!1,!1))}function ZI(e){let t=e[rI.Symbol.Schema],n=J.identifier(e[rI.Symbol.OriginalName]);return t?J`${J.identifier(t)}.${n} ${e}`:J`${n} ${e}`}function QI(e,t){return new Proxy(e,new YI(t))}sI.prototype.as=function(e){return QI(this,e)};function $I(e){return e[aI]()}var eL=class{static[U]=`ColumnBuilder`;static[Symbol.hasInstance](e){return W(e,this)}config;constructor(e,t,n){this.config={name:e,keyAsName:e===``,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default(e){return this.$defaultFn(e)}$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate(e){return this.$onUpdateFn(e)}primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e,t){this.config.name===``&&(this.config.name=t(e))}};function tL(e,t){if(xI(t)&&!pI(e)){let n=vI(e);if(n!==q.param&&n!==q.placeholder&&n!==q.column&&n!==q.table&&n!==q.view)return new wI(e,t)}return e}var nL=(e,t,n)=>new mI([e,t,tL(n,e)]),Y=(e,t)=>nL(e,K[` = `],t),rL=(e,t)=>nL(e,K[` <> `],t),iL=(e,t)=>{let n=Array(e.length*2+1),r=e.length-1;n[0]=K[`((`];for(let i=0;i<r;i++)n[i*2+1]=e[i],n[i*2+2]=t;return n[r*2+1]=e[r],n[r*2+2]=K[`))`],new mI(n)};function aL(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new mI(t):iL(t,K[`) and (`])}function oL(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new mI(t):iL(t,K[`) or (`])}function sL(e){if(e)return W(e,mI)?J`not (${e})`:J`not ${e}`}var cL=(e,t)=>nL(e,K[` > `],t),lL=(e,t)=>nL(e,K[` >= `],t),uL=(e,t)=>nL(e,K[` < `],t),dL=(e,t)=>nL(e,K[` <= `],t);function fL(e,t){return Array.isArray(t)?t.length===0?new mI([K[`1 = 0`]]):new mI([e,K[` in `],t.map(t=>tL(t,e))]):nL(e,K[` in `],t)}function pL(e,t){return Array.isArray(t)?t.length===0?new mI([K[`1 = 1`]]):new mI([e,K[` not in `],t.map(t=>tL(t,e))]):nL(e,K[` not in `],t)}function mL(e){return J`(${e} is null)`}function hL(e){return J`(${e} is not null)`}function gL(e){return J`exists ${e}`}function _L(e){return J`not exists ${e}`}function vL(e,t,n){return J`${e} between ${tL(t,e)} and ${tL(n,e)}`}function yL(e,t,n){return J`${e} not between ${tL(t,e)} and ${tL(n,e)}`}function bL(e,t){return J`${e} like ${t}`}function xL(e,t){return J`${e} not like ${t}`}function SL(e,t){return J`${e} ilike ${t}`}function CL(e,t){return J`${e} not ilike ${t}`}function wL(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContains requires at least one value`);let n=tL(t,e),r=J`${Array.isArray(n)?new wI(n):n}`;return J`${e} @> ${r}`}return J`${e} @> ${tL(t,e)}`}function TL(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContained requires at least one value`);let n=tL(t,e),r=J`${Array.isArray(n)?new wI(n):n}`;return J`${e} <@ ${r}`}return J`${e} <@ ${tL(t,e)}`}function EL(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayOverlaps requires at least one value`);let n=tL(t,e),r=J`${Array.isArray(n)?new wI(n):n}`;return J`${e} && ${r}`}return J`${e} && ${tL(t,e)}`}function DL(e){return J`${e} asc`}function OL(e){return J`${e} desc`}var kL={and:aL,between:vL,eq:Y,exists:gL,gt:cL,gte:lL,ilike:SL,inArray:fL,arrayContains:wL,arrayContained:TL,arrayOverlaps:EL,isNull:mL,isNotNull:hL,like:bL,lt:uL,lte:dL,ne:rL,not:sL,notBetween:yL,notExists:_L,notLike:xL,notIlike:CL,notInArray:pL,or:oL,sql:J},AL={sql:J,asc:DL,desc:OL};function jL(e,t,n,r=!1,i=!1,a=!0){let o=t?1:e.length,s=n.map(({field:e,fieldType:t,codec:n,arrayDimensions:r,subqueryDecoder:i})=>{let o;switch(t){case`Column`:o=e;break;case`SQL`:o=e.decoder;break;case`SQL.Aliased`:o=e.sql.decoder;break;case`Subquery`:o=i??SI;break;case`Nested`:o=SI;break;default:o=e.getSQL().decoder}return a&&e.mapFromJsonValue?t=>e.mapFromJsonValue(t):o.mapFromDriverValue.isNoop?n?e=>n(e,r):void 0:n?e=>o.mapFromDriverValue(n(e,r)):e=>o.mapFromDriverValue(e)});for(let a=0;a<o;++a){let o=t?e:e[a];for(let e=0;e<n.length;++e){let t=n[e];if(t.selection){if(o[t.key]===null)continue;if(r){if(o[t.key]=JSON.parse(o[t.key]),o[t.key]===null)continue}else i&&typeof o[t.key]==`string`&&(o[t.key]=JSON.parse(o[t.key]));if(t.isArray){jL(o[t.key],!1,t.selection,!1,i);continue}jL(o[t.key],!0,t.selection,!1,i);continue}if(o[t.key]===null)continue;let a=s[e];a&&(o[t.key]=a(o[t.key]))}}return e}function ML(e,t,n,r=!1,i=!1){let a=t?1:e.length,o=n.map(({field:e,fieldType:t,codec:n,arrayDimensions:r,subqueryDecoder:i})=>{let a;switch(t){case`Column`:a=e;break;case`SQL`:a=e.decoder;break;case`SQL.Aliased`:a=e.sql.decoder;break;case`Subquery`:a=i??SI;break;case`Nested`:a=SI;break;default:a=e.getSQL().decoder}return a.mapFromDriverValue.isNoop?n?e=>n(e,r):void 0:n?e=>a.mapFromDriverValue(n(e,r)):e=>a.mapFromDriverValue(e)}),s=Array(a);for(let c=0;c<a;++c){let a=t?e:e[c],l={};for(let e=0;e<n.length;++e){let t=n[e],s=a[e];if(t.selection){if(s===null){l[t.key]=null;continue}if(r){if(s=JSON.parse(s),s===null){l[t.key]=null;continue}}else i&&typeof s==`string`&&(s=JSON.parse(s));t.isArray?jL(s,!1,t.selection,!1,i):jL(s,!0,t.selection,!1,i),l[t.key]=s;continue}if(s===null){l[t.key]=null;continue}let c=o[e];l[t.key]=c?c(s):s}s[c]=l}return t?s[0]:s}function NL({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){return(o=>t&&!o[0]?o[0]:a?ML(t?o[0]:o,t,e,n,r):jL(t?o[0]:o,t,e,n,r,i))}function PL(e,t,n,r,i,a,o,s,c){let l=[],u=[],d=!1,f=e.map(()=>`c${s.n++}`),p=e.map((e,t)=>c?f[t]:`${JSON.stringify(e.key)}: ${f[t]}`);l.push(c?`let [ ${p.join(`, `)} ] = ${t};`:`let { ${p.join(`, `)} } = ${t};`);for(let[t,{field:c,fieldType:p,key:m,codec:h,isArray:g,selection:_,arrayDimensions:v,subqueryDecoder:ee}]of e.entries()){let e=`${n}[${t}]`,te=JSON.stringify(m),ne=f[t];if(_){r?(l.push(`if (${ne} !== null) ${ne} = JSON.parse(${ne});`),d=!0):i&&(l.push(`if (typeof ${ne} === 'string') ${ne} = JSON.parse(${ne});`),d=!0);let t=`s${s.n++}`,n=o.length;if(o.push(`const { selection: ${t} } = ${e};`),g){let e=`j${s.n++}`,r=PL(_,`${ne}[${e}]`,t,!1,i,!0,o,s,!1);if(r.hasWork){d=!0,l.push(`if (${ne} !== null) {`),l.push(`\tfor (let ${e} = 0; ${e} < ${ne}.length; ++${e}) {`);for(let e of r.bodyStmts)l.push(`\t\t${e}`);l.push(`\t\t${ne}[${e}] = ${r.literal};`),l.push(` }`),l.push(`}`)}else o.splice(n,1)}else{let e=PL(_,ne,t,!1,i,!0,o,s,!1);if(e.hasWork){d=!0,l.push(`if (${ne} !== null) {`);for(let t of e.bodyStmts)l.push(`\t${t}`);l.push(`\t${ne} = ${e.literal};`),l.push(`}`)}else o.splice(n,1)}u.push(`${te}: ${ne}`);continue}let re=``,ie=``,ae=!1;switch(p){case`Column`:if(a&&c.mapFromJsonValue){ae=!0;let e=s.n++;ie=`field: dec${e}`,re=`dec${e}.mapFromJsonValue`}else if(!c.mapFromDriverValue.isNoop){let e=s.n++;ie=`field: dec${e}`,re=`dec${e}.mapFromDriverValue`}break;case`SQL`:if(a&&c.decoder.mapFromJsonValue){ae=!0;let e=s.n++;ie=`field: { decoder: dec${e} }`,re=`dec${e}.mapFromJsonValue`}else if(!c.decoder.mapFromDriverValue.isNoop){let e=s.n++;ie=`field: { decoder: dec${e} }`,re=`dec${e}.mapFromDriverValue`}break;case`SQL.Aliased`:if(a&&c.sql.decoder.mapFromJsonValue){ae=!0;let e=s.n++;ie=`field: { sql: { decoder: dec${e} } }`,re=`dec${e}.mapFromJsonValue`}else if(!c.sql.decoder.mapFromDriverValue.isNoop){let e=s.n++;ie=`field: { sql: { decoder: dec${e} } }`,re=`dec${e}.mapFromDriverValue`}break;case`Subquery`:if(a&&ee?.mapFromJsonValue){ae=!0;let e=s.n++;ie=`subqueryDecoder: dec${e}`,re=`dec${e}.mapFromJsonValue`}else if(ee&&!ee.mapFromDriverValue.isNoop){let e=s.n++;ie=`subqueryDecoder: dec${e}`,re=`dec${e}.mapFromDriverValue`}break;case`Nested`:break;default:{let t=c.getSQL();if(a&&t.decoder.mapFromJsonValue){ae=!0;let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),re=`dec${t}.mapFromJsonValue`}else if(!t.decoder.mapFromDriverValue.isNoop){let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),re=`dec${t}.mapFromDriverValue`}}}let oe=``;if(!ae&&h&&(oe=`codec${s.n++}`),ie||oe){let t=[];ie&&t.push(ie),oe&&t.push(`codec: ${oe}`),o.push(`const { ${t.join(`, `)} } = ${e};`)}if(re||oe){d=!0;let e=ne;oe&&(e=`${oe}(${e}, ${v})`),re&&(e=`${re}(${e})`),u.push(`${te}: ${ne} === null ? null : ${e}`)}else u.push(`${te}: ${ne}`)}return{bodyStmts:l,literal:`{ ${u.join(`, `)} }`,hasWork:d}}function FL({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){let o=[],s=PL(e,`row`,`selection`,n,r,!a&&i,o,{n:0},!!a),c=[];c.push(` "use strict";
28
+ const { selection } = this;`);for(let e of o)c.push(`\t${e}`);if(a){if(t){c.push(` const row = rows[0];`),c.push(` if (!row) return undefined;`);for(let e of s.bodyStmts)c.push(`\t${e}`);c.push(`\treturn ${s.literal};`)}else{c.push(` const { length } = rows;`),c.push(` const mapped = new Array(length);`),c.push(` for (let i = 0; i < length; ++i) {`),c.push(` const row = rows[i];`);for(let e of s.bodyStmts)c.push(`\t\t${e}`);c.push(`\t\tmapped[i] = ${s.literal};`),c.push(` }`),c.push(` return mapped;`)}}else if(!s.hasWork)c.push(t?` return rows[0];`:` return rows;`);else if(t){c.push(` const row = rows[0];`),c.push(` if (!row) return undefined;`);for(let e of s.bodyStmts)c.push(`\t${e}`);c.push(`\trows[0] = ${s.literal};`),c.push(` return rows[0];`)}else{c.push(` for (let i = 0; i < rows.length; ++i) {`),c.push(` const row = rows[i];`);for(let e of s.bodyStmts)c.push(`\t\t${e}`);c.push(`\t\trows[i] = ${s.literal};`),c.push(` }`),c.push(` return rows;`)}c.push(` //# sourceURL=drizzle:jit-relational-query-mapper`);let l=c.join(`
29
+ `);return Object.assign(new NI(`rows`,l).bind({selection:e}),{body:`function jitRqbMapper (rows) {\n${l}\n}`})}function IL(e,t){let n=e[JF][t],r=vI(n);return yI(n,r,q.column)?n:new mI([e,K[`.`],J.identifier(yI(n,r,q.aliased)?n.fieldAlias:t)])}var LL=class{chunks;separator;static[U]=`ConditionsCollector`;static[Symbol.hasInstance](e){return W(e,this)}start;count=0;mark=0;conditionStart=0;constructor(e,t){this.chunks=e,this.separator=t,this.start=e.length,e.push(void 0)}open(){this.mark=this.chunks.length,this.count&&this.chunks.push(this.separator),this.conditionStart=this.chunks.length}close(){this.chunks.length===this.conditionStart?this.chunks.length=this.mark:++this.count}push(e){e!==void 0&&(this.count&&this.chunks.push(this.separator),this.chunks.push(e),++this.count)}pushChunks(e){if(e?.length){this.count&&this.chunks.push(this.separator);for(let t=0;t<e.length;++t)this.chunks.push(e[t]);++this.count}}finish(){return this.count?(this.count>1&&(this.chunks[this.start]=K[`((`],this.chunks.push(K[`))`])),!0):(this.chunks.length=this.start,!1)}};function RL(e,t,n=[]){if(t===eR)return;if(t===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);if(typeof t!=`object`||W(t,DI))return n.push(Y(e,t)),n;let r=Object.entries(t);if(!r.length)return;let i=new LL(n,K[`) and (`]);for(let[t,a]of r)if(a!==eR){if(a===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);switch(t){case`NOT`:{i.open();let t=n.length;n.push(K[`not (`]),RL(e,a,n),n.length===t+1?n.length=t:n.push(K[`)`]),i.close();continue}case`OR`:case`AND`:{let r=a;if(!r.length)throw Error(`Unexpected empty array in filters' '${t}' section. Omit field or use 'EmptyFilter' if you want filter to be skipped.`);i.open();let o=new LL(n,t===`OR`?K[`) or (`]:K[`) and (`]);for(let t of r)o.open(),RL(e,t,n),o.close();o.finish(),i.close();continue}case`isNotNull`:case`isNull`:if(!a)continue;i.push(kL[t](e));continue;case`in`:i.push(kL.inArray(e,a));continue;case`notIn`:i.push(kL.notInArray(e,a));continue;default:i.push(kL[t](e,a));continue}}return i.finish()?n:void 0}function zL(e,t,n={},r={},i,a=0,o=[]){if(t===eR)return{sql:void 0,hasRelationFilters:!1};if(t===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);let s=Object.entries(t);if(!s.length)return{sql:void 0,hasRelationFilters:!1};let c=new LL(o,K[`) and (`]),l=!1,u=t=>{zL(e,t,n,r,i,a,o).hasRelationFilters&&(l=!0)};for(let[t,d]of s)if(d!==eR){if(d===void 0)throw Error(`Unexpected 'undefined' in filter value. Use 'EmptyFilter' if you want the filter field to be skipped.`);switch(t){case`RAW`:{let t=typeof d==`function`?d(e,kL):d.getSQL();if(t===eR)continue;c.push(t),l=!0;continue}case`OR`:case`AND`:{let e=d;if(!e.length)throw Error(`Unexpected empty array in filters' '${t}' section. Omit field or use 'EmptyFilter' if you want filter to be skipped.`);c.open();let n=new LL(o,t===`OR`?K[`) or (`]:K[`) and (`]);for(let t of e)n.open(),u(t),n.close();n.finish(),c.close();continue}case`NOT`:{c.open();let e=o.length;o.push(K[`not (`]),u(d),o.length===e+1?o.length=e:o.push(K[`)`]),c.close();continue}default:{if(Object.prototype.hasOwnProperty.call(e[JF],t)&&e[JF][t]){c.open(),RL(IL(e,t),d,o),c.close();continue}let s=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!s)throw new GF({message:`Unknown relational filter field: "${t}"`});i&&(QL(i,s.targetTable),QL(i,s.throughTable));let u=XI(s.targetTable,`f${a}`),f=s.throughTable?XI(s.throughTable,`ft${a}`):void 0,p=r[s.targetTableName],m=typeof d==`boolean`;c.open();let h=o.length;o.push(d?K[`exists (select * from `]:K[`not exists (select * from `]),$L(u,o),f&&(o.push(K[` inner join `]),$L(f,o),o.push(K[` on `]));let{filter:g}=qL(s,e,u,f,[],o);o.push(K[` where `]);let _=new LL(o,K[`) and (`]);if(_.pushChunks(g),!m){_.open();let e=zL(u,d,p.relations,r,i,a+1,o);if(_.close(),!e.sql){o.length=h,c.close();continue}}_.finish(),o.push(K[`)`]),c.close(),l=!0}}}return{sql:c.finish()?o:void 0,hasRelationFilters:l}}var BL=new Set([`min`,`max`,`count`,`avg`,`first`]);function VL(e,t){if(typeof e!=`string`)throw new GF({message:`Invalid order "${t}": expected a string, got ${e===null?`null`:typeof e}`});let n=e.split(`(`),r=n[0];if(r!==`asc`&&r!==`desc`)throw new GF({message:`Invalid order "${t}": unknown direction "${r}" in "${e}", expected "asc" or "desc"`});if(n.length===1)return{direction:r};if(n.length>2||!n[1].endsWith(`)`))throw new GF({message:`Invalid order "${t}": malformed value "${e}", expected "${r}" or "${r}(<aggregate>)"`});let i=n[1].slice(0,-1);if(!BL.has(i))throw new GF({message:`Invalid order "${t}": unknown aggregate "${i}" in "${e}", expected one of: ${[...BL].join(`, `)}`});return{direction:r,aggregate:i}}function HL(e,t,n,r,i,a,o,s,c=s.length){for(let[l,u]of Object.entries(t)){if(!u)continue;let t=o?`${o.path}.${l}`:l;if(Object.prototype.hasOwnProperty.call(e[JF],l)&&e[JF][l]){let{direction:n,aggregate:r}=VL(u,t);if(!!r!=!!o?.isAggregated)throw new GF({message:`Invalid order "${t}": expected ${o?.isAggregated?`"asc(<aggregate>)" or "desc(<aggregate>)", with aggregate being one of: min, max, count, avg, first`:`"asc" or "desc"`}, got "${u}"`});let i=IL(e,l);if(s.length>c&&s.push(K[`, `]),!o){s.push(i,n===`asc`?K[` asc`]:K[` desc`]);continue}let d=!r||r===`first`;s.push(K[`(select `]),d?(a===`top`&&s.push(K[`top(1) `]),s.push(i)):s.push(K[`${r}(`],i,K[`)`]),s.push(K[` from `]);for(let e=0;e<o.from.length;++e)s.push(o.from[e]);let f=s.length;s.push(K[` where `]);let p=new LL(s,K[`) and (`]);for(let e=0;e<o.filters.length;++e)p.pushChunks(o.filters[e]);p.finish()||(s.length=f),d&&a===`limit`&&s.push(K[` limit 1`]),s.push(K[`)`],n===`asc`?K[` asc`]:K[` desc`]);continue}let d=Object.prototype.hasOwnProperty.call(n,l)?n[l]:void 0;if(!d)throw new GF({message:`Unknown relational order field: "${t}"`});let f=d.relationType===`many`&&typeof u==`string`?VL(u,t):void 0,p=f?.aggregate===`count`?f.direction:void 0;if(typeof u!=`object`&&!p)throw new GF({message:`Invalid order "${t}": expected an object with fields of relation to order by${d.relationType===`many`?`, "asc(count)" or "desc(count)"`:``}, got "${u}"`});i&&(QL(i,d.targetTable),QL(i,d.throughTable));let m=o?.depth??0,h=XI(d.targetTable,`o${m}`),g=d.throughTable?XI(d.throughTable,`ot${m}`):void 0,_=o?[...o.from,K[` cross join `]]:[];$L(h,_),g&&(_.push(K[` inner join `]),$L(g,_),_.push(K[` on `]));let{filter:v}=qL(d,e,h,g,[],_),ee=o?[...o.filters,v]:[v];if(typeof u!=`object`){s.length>c&&s.push(K[`, `]),s.push(K[`(select count(*) from `]);for(let e=0;e<_.length;++e)s.push(_[e]);let e=s.length;s.push(K[` where `]);let t=new LL(s,K[`) and (`]);for(let e=0;e<ee.length;++e)t.pushChunks(ee[e]);t.finish()||(s.length=e),s.push(K[`)`],p===`asc`?K[` asc`]:K[` desc`])}else HL(h,u,r[d.targetTableName]?.relations??{},r,i,a,{from:_,filters:ee,isAggregated:!!o?.isAggregated||d.relationType===`many`,depth:m+1,path:t},s,c)}return s}function UL(e,t,n={},r={},i,a=`limit`,o=[]){let s=o.length;if(typeof t==`function`){let n=t(e,AL);if(!n)return;let r=vI(n);if(yI(n,r,q.sql))o.push(n);else if(Array.isArray(n))for(let e=0;e<n.length;++e){e&&o.push(K[`, `]);let t=n[e];o.push(t),vI(t)!==q.sql&&o.push(K[` asc`])}else yI(n,r,q.column)&&o.push(n,K[` asc`]);return o.length>s?o:void 0}return HL(e,t,n,r,i,a,void 0,o,s),o.length>s?o:void 0}function WL(e,t,n,r,i=[]){let a=i.length,o=[];for(let[s,c]of Object.entries(t)){let t=typeof c==`function`?c(e,{sql:kL.sql}):c;if(!t)continue;let l=t.getSQL(),u=n?RI(l):void 0,d=u&&(!r||!u.jsonSelectIdentifier)?new mI([n.apply(u,r?`castInJson`:`cast`,new mI([K[`(`],l,K[`)`]])),K[` as `],J.identifier(s)]):new mI([K[`(`],l,K[`) as `],J.identifier(s)]);d.decoder=l.decoder,i.length>a&&i.push(K[`, `]),i.push(d),o.push(u&&(!r||!u.mapFromJsonValue)?{key:s,field:d,fieldType:`SQL`,codec:n.get(u,r?`normalizeInJson`:`normalize`),arrayDimensions:u.dimensions}:{key:s,field:d,fieldType:`SQL`})}return{sql:i.length>a?i:void 0,selection:o}}function GL({_:{column:e,key:t}}){let n=vI(e);return J.identifier(yI(e,n,q.column)?e.name:yI(e,n,q.aliased)?e.fieldAlias:t)}function KL(e,t,n,r,i,a){e.open(),t.push(n,K[`.`],GL(r),K[` = `],i,K[`.`],GL(a)),e.close()}function qL(e,t,n,r,i=[],a=[]){let o=e.isFilterReversed?t:n,s=t[eI],c=n[eI],l=r?.[eI],u=new LL(i,K[`) and (`]);if(e.through){let{sourceColumns:t,targetColumns:n,through:{source:r,target:d}}=e;u.open(),zL(o,e.where,{},{},void 0,0,i),u.close();for(let e=0;e<t.length;++e)KL(u,i,s,t[e],l,r[e]);u.finish();let f=new LL(a,K[`) and (`]);for(let e=0;e<n.length;++e)KL(f,a,l,d[e],c,n[e]);return f.finish(),{filter:i,joinCondition:a}}let{sourceColumns:d,targetColumns:f}=e;for(let e=0;e<d.length;++e)KL(u,i,s,d[e],c,f[e]);return u.open(),zL(o,e.where,{},{},void 0,0,i),u.close(),u.finish(),{filter:i}}function JL(e,t,n,r,i,a,o=[]){let s=new LL(o,K[`) and (`]),c=!1;return t&&`where`in t&&(s.open(),c=zL(e,t.where,n,r,i,0,o).hasRelationFilters,s.close()),s.pushChunks(a),{sql:s.finish()?o:void 0,hasRelationFilters:c}}function YL(e,t,n,r,i,a,o){a?e.push(i.apply(a,o?`castInJson`:`cast`,new mI([t,K[`.`],J.identifier(n)]))):e.push(t,K[`.`],J.identifier(n)),e.push(K[` as `],J.identifier(r))}function XL(e,t,n,r,i,a,o,s){let c,l,u,d=vI(t);if(yI(t,d,q.column)){c=t,u=`Column`;let{jsonSelectIdentifier:i,dimensions:a}=t,l=r&&i?void 0:o.codecsOf(t)[r?`castInJson`:`cast`];if(l||r&&i){let r=new mI([e,K[`.`],J.identifier(t.name)]),o=l?l(r,a):i.call(t,r,J,a);s.push(o,K[` as `],J.identifier(n))}else s.push(e,K[`.`],J.identifier(t.name),K[` as `],J.identifier(n))}else if(yI(t,d,q.sql))c=RI(t),u=`SQL`,YL(s,e,n,n,o,c,r);else if(yI(t,d,q.aliased))c=RI(t),u=`SQL.Aliased`,YL(s,e,t.fieldAlias,n,o,c,r);else if(yI(t,d,q.subquery)){let i=Object.values(t._.selectedFields)[0],a=vI(i);yI(i,a,q.column)?(c=i,l=i):yI(i,a,q.aliased)?(c=RI(i),l=i.sql.decoder):yI(i,a,q.sql)&&(c=RI(i),l=i.decoder),u=`Subquery`,YL(s,e,t._.alias,n,o,c,r)}else if(pI(t))c=RI(t),u=`SQLWrapper`,YL(s,e,n,n,o,c,r);else throw new GF({message:t===void 0?`Unknown column: "${a}"."${n}"`:`Views and subqueries with nested selections are not supported by the relational query builder`});i.push(c?{key:n,field:t,fieldType:u,subqueryDecoder:l,codec:!r||!c.mapFromJsonValue?o.get(c,r?`normalizeInJson`:`normalize`):void 0,arrayDimensions:c.dimensions}:{key:n,field:t,fieldType:u,subqueryDecoder:l})}function ZL(e,t,n,r,i,a,o,s){let c=o.length;if(!s){for(let s of Object.keys(t))o.length>c&&o.push(K[`, `]),XL(e,t[s],s,r,n,i,a,o);return!0}let l;for(let u of Object.keys(s)){let d=s[u];d!==void 0&&(l||=d,d&&(o.length>c&&o.push(K[`, `]),XL(e,t[u],u,r,n,i,a,o)))}if(l===!1)for(let l of Object.keys(t))s[l]!==!1&&(o.length>c&&o.push(K[`, `]),XL(e,t[l],l,r,n,i,a,o));return o.length>c}function QL(e,t){let n=vI(t);if(e.usedTables!==void 0&&yI(t,n,q.table)){e.usedTables.add(t[QF]);return}if(!yI(t,n,q.subquery))return;let r=t._.alias,i=e.subqueries.get(r);if(i&&i._.sql!==t._.sql)throw new GF({message:`Different subqueries with the same alias "${r}" are used in a single relational query - make sure every subquery in schema has a unique alias`});e.subqueries.set(r,t)}function $L(e,t=[]){if(!e[$F])return t.push(e),t;let n=e[qF];return n&&t.push(J.identifier(n),K[`.`]),t.push(J.identifier(e[XF]),K[` as `],e[eI]),t}var eR=Symbol.for(`drizzle:EmptyFilter`),tR=class{static[U]=`SQLiteForeignKeyBuilder`;static[Symbol.hasInstance](e){return W(e,this)}reference;_onUpdate;_onDelete;constructor(e,t){this.reference=()=>{let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new nR(e,this)}},nR=class{table;static[U]=`SQLiteForeignKey`;static[Symbol.hasInstance](e){return W(e,this)}reference;onUpdate;onDelete;constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}getName(){let{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),i=n.map(e=>e.name),a=[this.table[KF],...r,n[0].table[KF],...i];return e??`${a.join(`_`)}_fk`}isNameExplicit(){return!!this.reference().name}};function rR(e){function t(){if(typeof e==`function`){let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignColumns:r}}return e}return new tR(t)}var iR=class extends eL{static[U]=`SQLiteColumnBuilder`;foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:`always`,mode:t?.mode??`virtual`},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>((n,r)=>{let i=new tR(()=>{let t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&i.onUpdate(r.onUpdate),r.onDelete&&i.onDelete(r.onDelete),i.build(t)})(n,r))}},aR=class extends sI{static[U]=`SQLiteColumn`;table;constructor(e,t){super(e,t),this.table=e}},oR={},sR={cast:void 0,castInJson:void 0,castParam:void 0,normalize:void 0,normalizeInJson:void 0,normalizeParam:void 0},cR={cast:`cast`,castArray:`cast`,castInJson:`castInJson`,castArrayInJson:`castInJson`,castParam:`castParam`,castArrayParam:`castParam`,normalize:`normalize`,normalizeArray:`normalize`,normalizeInJson:`normalizeInJson`,normalizeArrayInJson:`normalizeInJson`,normalizeParam:`normalizeParam`,normalizeParamArray:`normalizeParam`},lR=class{resolveTypes;codecs;static[U]=`CodecsCollection`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t=oR){this.resolveTypes=e,this.codecs=t}itemCodecsCache=new Map;arrayCodecsCache=new Map;codecsOf(e,t){let n=t??e.codec;if(!n)return sR;let r=!!e.dimensions,i=r?this.arrayCodecsCache:this.itemCodecsCache,a=i.get(n);if(a===void 0){let e=this.codecs[n];a=e?r?{cast:e.castArray,castInJson:e.castArrayInJson,castParam:e.castArrayParam,normalize:e.normalizeArray,normalizeInJson:e.normalizeArrayInJson,normalizeParam:e.normalizeParamArray}:{cast:e.cast,castInJson:e.castInJson,castParam:e.castParam,normalize:e.normalize,normalizeInJson:e.normalizeInJson,normalizeParam:e.normalizeParam}:sR,i.set(n,a)}return a}get(e,t,n){return this.codecsOf(e,n)[cR[t]]}apply(e,t,n,r){let i=cR[t],a=this.codecsOf(e,r)[i];return a?i===`castParam`?a(n,e,e.dimensions):a(n,e.dimensions):n}},uR={int:`integer`,int2:`integer`,int8:`integer`,tinyint:`integer`,smallint:`integer`,mediumint:`integer`,bool:`integer:boolean`,boolean:`integer:boolean`,float:`real`,double:`real`,"double precision":`real`,decimal:`numeric`,character:`text`,varchar:`text`,"varying character":`text`,nchar:`text`,"native character":`text`,nvarchar:`text`,clob:`text`,json:`text:json`};function dR(e){return uR[e]??e}var fR=typeof Buffer>`u`?new TextEncoder:void 0,pR=fR?e=>fR.encode(e):e=>Buffer.from(e),mR={integer:{integer:`integer`,"integer:boolean":`integer`,"integer:timestamp":`integer`,"integer:timestamp_ms":`integer`,real:`integer`,text:`integer`,"text:json":`integer`,blob:`integer`,"blob:json":`integer`,"blob:bigint":`integer`,numeric:`integer`,"numeric:number":`integer`,"numeric:bigint":`integer`},"integer:boolean":{integer:`integer:boolean`,"integer:boolean":`integer:boolean`,"integer:timestamp":`integer:boolean`,"integer:timestamp_ms":`integer:boolean`,real:`integer:boolean`,text:`integer:boolean`,"text:json":`integer:boolean`,blob:`integer:boolean`,"blob:json":`integer:boolean`,"blob:bigint":`integer:boolean`,numeric:`integer:boolean`,"numeric:number":`integer:boolean`,"numeric:bigint":`integer:boolean`},"integer:timestamp":{integer:`integer:timestamp`,"integer:boolean":`integer:timestamp`,"integer:timestamp":`integer:timestamp`,"integer:timestamp_ms":`integer:timestamp`,real:`integer:timestamp`,text:`integer:timestamp`,"text:json":`integer:timestamp`,blob:`integer:timestamp`,"blob:json":`integer:timestamp`,"blob:bigint":`integer:timestamp`,numeric:`integer:timestamp`,"numeric:number":`integer:timestamp`,"numeric:bigint":`integer:timestamp`},"integer:timestamp_ms":{integer:`integer:timestamp_ms`,"integer:boolean":`integer:timestamp_ms`,"integer:timestamp":`integer:timestamp_ms`,"integer:timestamp_ms":`integer:timestamp_ms`,real:`integer:timestamp_ms`,text:`integer:timestamp_ms`,"text:json":`integer:timestamp_ms`,blob:`integer:timestamp_ms`,"blob:json":`integer:timestamp_ms`,"blob:bigint":`integer:timestamp_ms`,numeric:`integer:timestamp_ms`,"numeric:number":`integer:timestamp_ms`,"numeric:bigint":`integer:timestamp_ms`},real:{integer:`real`,"integer:boolean":`real`,"integer:timestamp":`real`,"integer:timestamp_ms":`real`,real:`real`,text:`real`,"text:json":`real`,blob:`real`,"blob:json":`real`,"blob:bigint":`real`,numeric:`real`,"numeric:number":`real`,"numeric:bigint":`real`},text:{integer:`text`,"integer:boolean":`text`,"integer:timestamp":`text`,"integer:timestamp_ms":`text`,real:`text`,text:`text`,"text:json":`text`,blob:`text`,"blob:json":`text`,"blob:bigint":`text`,numeric:`numeric`,"numeric:number":`text`,"numeric:bigint":`text`},"text:json":{integer:`text:json`,"integer:boolean":`text:json`,"integer:timestamp":`text:json`,"integer:timestamp_ms":`text:json`,real:`text:json`,text:`text:json`,"text:json":`text:json`,blob:`text:json`,"blob:json":`blob:json`,"blob:bigint":`text:json`,numeric:`text:json`,"numeric:number":`text:json`,"numeric:bigint":`text:json`},blob:{integer:`blob`,"integer:boolean":`blob`,"integer:timestamp":`blob`,"integer:timestamp_ms":`blob`,real:`blob`,text:`blob`,"text:json":`blob`,blob:`blob`,"blob:json":`blob`,"blob:bigint":`blob`,numeric:`blob`,"numeric:number":`blob`,"numeric:bigint":`blob`},"blob:json":{integer:`blob:json`,"integer:boolean":`blob:json`,"integer:timestamp":`blob:json`,"integer:timestamp_ms":`blob:json`,real:`blob:json`,text:`blob:json`,"text:json":`blob:json`,blob:`blob:json`,"blob:json":`blob:json`,"blob:bigint":`blob:json`,numeric:`blob:json`,"numeric:number":`blob:json`,"numeric:bigint":`blob:json`},"blob:bigint":{integer:`blob:bigint`,"integer:boolean":`blob:bigint`,"integer:timestamp":`blob:bigint`,"integer:timestamp_ms":`blob:bigint`,real:`blob:bigint`,text:`blob:bigint`,"text:json":`blob:bigint`,blob:`blob:bigint`,"blob:json":`blob:bigint`,"blob:bigint":`blob:bigint`,numeric:`blob:bigint`,"numeric:number":`blob:bigint`,"numeric:bigint":`blob:bigint`},numeric:{integer:`numeric`,"integer:boolean":`numeric`,"integer:timestamp":`numeric`,"integer:timestamp_ms":`numeric`,real:`numeric`,text:`numeric`,"text:json":`numeric`,blob:`numeric`,"blob:json":`numeric`,"blob:bigint":`numeric`,numeric:`numeric`,"numeric:number":`numeric`,"numeric:bigint":`numeric`},"numeric:number":{integer:`numeric:number`,"integer:boolean":`numeric:number`,"integer:timestamp":`numeric:number`,"integer:timestamp_ms":`numeric:number`,real:`numeric:number`,text:`numeric:number`,"text:json":`numeric:number`,blob:`numeric:number`,"blob:json":`numeric:number`,"blob:bigint":`numeric:number`,numeric:`numeric:number`,"numeric:number":`numeric:number`,"numeric:bigint":`numeric:number`},"numeric:bigint":{integer:`numeric:bigint`,"integer:boolean":`numeric:bigint`,"integer:timestamp":`numeric:bigint`,"integer:timestamp_ms":`numeric:bigint`,real:`numeric:bigint`,text:`numeric:bigint`,"text:json":`numeric:bigint`,blob:`numeric:bigint`,"blob:json":`numeric:bigint`,"blob:bigint":`numeric:bigint`,numeric:`numeric:bigint`,"numeric:number":`numeric:bigint`,"numeric:bigint":`numeric:bigint`}};function hR(e,t){return mR[e]?.[t]}var gR=class extends iR{static[U]=`SQLiteBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteBigInt`)}build(e){return new _R(e,this.config)}},_R=class extends aR{static[U]=`SQLiteBigInt`;codec=`blob:bigint`;getSQLType(){return`blob`}mapToDriverValue=e=>pR(e.toString())},vR=class extends iR{static[U]=`SQLiteBlobJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteBlobJson`)}build(e){return new yR(e,this.config)}},yR=class extends aR{static[U]=`SQLiteBlobJson`;codec=`blob:json`;getSQLType(){return`blob`}mapToDriverValue=e=>pR(JSON.stringify(e))},bR=class extends iR{static[U]=`SQLiteBlobBufferBuilder`;constructor(e){super(e,`object buffer`,`SQLiteBlobBuffer`)}build(e){return new xR(e,this.config)}},xR=class extends aR{static[U]=`SQLiteBlobBuffer`;codec=`blob`;getSQLType(){return`blob`}};function SR(e,t){let{name:n,config:r}=HI(e,t);return r?.mode===`bigint`?new gR(n):r?.mode===`buffer`?new bR(n):new vR(n)}var CR=class extends iR{static[U]=`SQLiteCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`SQLiteCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new wR(e,this.config)}},wR=class extends aR{static[U]=`SQLiteCustomColumn`;codec;sqlName;mapFromJsonValue;jsonSelectIdentifier;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapToDriverValue=t.customTypeParams.toDriver??this.mapToDriverValue,this.mapFromDriverValue=t.customTypeParams.fromDriver??this.mapFromDriverValue,this.mapFromJsonValue=t.customTypeParams.fromJson,this.jsonSelectIdentifier=t.customTypeParams.forJsonSelect;let n=typeof t.customTypeParams.codec==`string`||t.customTypeParams.codec===void 0?t.customTypeParams.codec:t.customTypeParams.codec(t.fieldConfig);this.codec=typeof n==`string`?dR(n):void 0}getSQLType(){return this.sqlName}};function TR(e){return(t,n)=>{let{name:r,config:i}=HI(t,n);return new CR(r,i,e)}}var ER=class extends iR{static[U]=`SQLiteBaseIntegerBuilder`;constructor(e,t,n){super(e,t,n),this.config.autoIncrement=!1}primaryKey(e){return e?.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}},DR=class extends aR{static[U]=`SQLiteBaseInteger`;autoIncrement=this.config.autoIncrement;getSQLType(){return`integer`}},OR=class extends ER{static[U]=`SQLiteIntegerBuilder`;constructor(e){super(e,`number int53`,`SQLiteInteger`)}build(e){return new kR(e,this.config)}},kR=class extends DR{static[U]=`SQLiteInteger`;codec=`integer`},AR=class extends ER{static[U]=`SQLiteTimestampBuilder`;constructor(e,t){super(e,`object date`,`SQLiteTimestamp`),this.config.mode=t}defaultNow(){return this.default(J`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new jR(e,this.config)}},jR=class extends DR{static[U]=`SQLiteTimestamp`;codec=`integer:${this.config.mode}`;mode=this.config.mode;mapToDriverValue=e=>{if(typeof e==`number`)return e;let t=e.getTime();return this.config.mode===`timestamp`?Math.floor(t/1e3):t}},MR=class extends ER{static[U]=`SQLiteBooleanBuilder`;constructor(e,t){super(e,`boolean`,`SQLiteBoolean`),this.config.mode=t}build(e){return new NR(e,this.config)}},NR=class extends DR{static[U]=`SQLiteBoolean`;codec=`integer:boolean`;mode=this.config.mode;mapToDriverValue=e=>+!!e};function PR(e,t){let{name:n,config:r}=HI(e,t);return r?.mode===`timestamp`||r?.mode===`timestamp_ms`?new AR(n,r.mode):r?.mode===`boolean`?new MR(n,r.mode):new OR(n)}var FR=class extends iR{static[U]=`SQLiteNumericBuilder`;constructor(e){super(e,`string numeric`,`SQLiteNumeric`)}build(e){return new IR(e,this.config)}},IR=class extends aR{static[U]=`SQLiteNumeric`;codec=`numeric`;getSQLType(){return`numeric`}},LR=class extends iR{static[U]=`SQLiteNumericNumberBuilder`;constructor(e){super(e,`number`,`SQLiteNumericNumber`)}build(e){return new RR(e,this.config)}},RR=class extends aR{static[U]=`SQLiteNumericNumber`;codec=`numeric:number`;mapToDriverValue=String;getSQLType(){return`numeric`}},zR=class extends iR{static[U]=`SQLiteNumericBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteNumericBigInt`)}build(e){return new BR(e,this.config)}},BR=class extends aR{static[U]=`SQLiteNumericBigInt`;codec=`numeric:bigint`;mapToDriverValue=String;getSQLType(){return`numeric`}};function VR(e,t){let{name:n,config:r}=HI(e,t),i=r?.mode;return i===`number`?new LR(n):i===`bigint`?new zR(n):new FR(n)}var HR=class extends iR{static[U]=`SQLiteRealBuilder`;constructor(e){super(e,`number double`,`SQLiteReal`)}build(e){return new UR(e,this.config)}},UR=class extends aR{static[U]=`SQLiteReal`;codec=`real`;getSQLType(){return`real`}};function WR(e){return new HR(e??``)}var GR=class extends iR{static[U]=`SQLiteTextBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`SQLiteText`),this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new KR(e,this.config)}},KR=class extends aR{static[U]=`SQLiteText`;codec=`text`;enumValues=this.config.enumValues;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:``}`}},qR=class extends iR{static[U]=`SQLiteTextJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteTextJson`)}build(e){return new JR(e,this.config)}},JR=class extends aR{static[U]=`SQLiteTextJson`;codec=`text:json`;getSQLType(){return`text`}mapToDriverValue=e=>JSON.stringify(e)};function X(e,t={}){let{name:n,config:r}=HI(e,t);return r.mode===`json`?new qR(n):new GR(n,r)}function YR(){return{blob:SR,customType:TR,integer:PR,numeric:VR,real:WR,text:X}}function XR(e){return(e.replace(/['\u2019]/g,``).match(/[\d\p{Ll}\p{Lo}]+|[\p{Lu}]+(?![\p{Ll}\p{Lo}])|[\p{Lu}][\d\p{Ll}\p{Lo}]+/gu)??[]).map(e=>e.toLowerCase()).join(`_`)}function ZR(e){return(e.replace(/['\u2019]/g,``).match(/[\d\p{Ll}\p{Lo}]+|[\p{Lu}]+(?![\p{Ll}\p{Lo}])|[\p{Lu}][\d\p{Ll}\p{Lo}]+/gu)??[]).reduce((e,t,n)=>e+(n===0?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),``)}function QR(e){return e===`snake_case`?XR:e===`camelCase`?ZR:e=>e}var $R=Symbol.for(`drizzle:SQLiteInlineForeignKeys`),ez=class extends rI{static[U]=`SQLiteTable`;static Symbol=Object.assign({},rI.Symbol,{InlineForeignKeys:$R});[rI.Symbol.Columns];[$R]=[];[rI.Symbol.ExtraConfigBuilder]=void 0};function tz(e,t,n,r,i,a=e){let o=QR(i),s=new ez(e,r,a),c=typeof t==`function`?t(YR()):t,l=Object.fromEntries(Object.entries(c).map(([e,t])=>{let n=t;n.setName(e,o);let r=n.build(s).postBuild();return s[$R].push(...n.buildForeignKeys(r,s)),[e,r]})),u=Object.assign(s,l);return u[rI.Symbol.Columns]=l,u[rI.Symbol.ExtraConfigColumns]=l,n&&(u[ez.Symbol.ExtraConfigBuilder]=n),u}function nz(e){return(t,n,r)=>tz(t,n,r,void 0,e)}var rz=class{name;value;static[U]=`SQLiteCheckBuilder`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e,t){this.name=e,this.value=t}build(e){return new iz(e,this)}},iz=class{table;static[U]=`SQLiteCheck`;static[Symbol.hasInstance](e){return W(e,this)}name;value;constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}};function az(e,t){return new rz(e,t)}var oz=class{name;unique;static[U]=`SQLiteIndexBuilderOn`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t){this.name=e,this.unique=t}on(...e){return new sz(this.name,e,this.unique)}},sz=class{static[U]=`SQLiteIndexBuilder`;static[Symbol.hasInstance](e){return W(e,this)}config;constructor(e,t,n){this.config={name:e,columns:t,unique:n,where:void 0}}where(e){return this.config.where=e,this}build(e){return new cz(this.config,e)}},cz=class{static[U]=`SQLiteIndex`;static[Symbol.hasInstance](e){return W(e,this)}config;isNameExplicit;constructor(e,t){this.config={...e,table:t},this.isNameExplicit=!!e.name}};function lz(e){return new oz(e,!1)}function uz(e){return new oz(e,!0)}function dz(...e){return e[0].columns?new fz(e[0].columns,e[0].name):new fz(e)}var fz=class{static[U]=`SQLitePrimaryKeyBuilder`;static[Symbol.hasInstance](e){return W(e,this)}columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new pz(e,this.columns,this.name)}},pz=class{table;static[U]=`SQLitePrimaryKey`;static[Symbol.hasInstance](e){return W(e,this)}columns;name;isNameExplicit;constructor(e,t,n){this.table=e,this.columns=t,this.name=n,this.isNameExplicit=!!n}getName(){return this.name??`${this.table[ez.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}},mz=UI(e=>`"${e.replace(/"/g,`""`)}"`),hz={json:new G(`json`),object:new G(`_object(`),groupArray:new G(`_group_array(json_object(`),groupArrayClose:new G(`))`),relationFrom:new G(` as "r" from (`),relationClose:new G(`) as "t") as `)},gz=class{static[U]=`SQLiteDialect`;static[Symbol.hasInstance](e){return W(e,this)}codecs;mapperGenerators;constructor(e){this.codecs=new lR(dR,e?.codecs),this.mapperGenerators=e?.useJitMappers?{rows:FI,relationalRows:FL}:{rows:II,relationalRows:NL}}escapeName(e){return mz(e)}escapeParam(e){return`?`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=e.length,n=Array(t+1),r=0;n[r++]=K[`with `];for(let i=0;i<t;++i){let a=e[i];n[r++]=i<t-1?J`${J.identifier(a._.alias)} as (${a._.sql}), `:J`${J.identifier(a._.alias)} as (${a._.sql}) `}return new mI(n)}buildDeleteQuery({table:e,where:t,returning:n,withList:r,limit:i,orderBy:a,useSelectionCastCodecs:o}){let s=this.buildWithCTE(r),c=n?J` returning ${this.buildSelection(n,{isSingleTable:!0,ignoreCastCodecs:!o,table:e})}`:void 0,l=t?J` where ${t}`:void 0,u=this.buildOrderBy(a),d=this.buildLimit(i);return J`${s}delete from ${e}${l}${c}${u}${d}`}buildUpdateSet(e,t){let n=e[rI.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length,a=Array(i);for(let e=0;e<r.length;++e){let o=r[e],s=n[o],c;if(t[o]!==void 0)c=t[o];else{let e=s.onUpdateFn?.();c=W(e,mI)?e:J.param(e,s)}a[e]=e<i-1?J`${J.identifier(s.name)} = ${c}, `:J`${J.identifier(s.name)} = ${c}`}return new mI(a)}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,joins:a,from:o,limit:s,orderBy:c,useSelectionCastCodecs:l}){let u=this.buildWithCTE(i),d=this.buildUpdateSet(e,t),f=o&&new mI([K[` from `],this.buildFromTable(o)]),p=this.buildJoins(a),m=r?J` returning ${this.buildSelection(r,{isSingleTable:!0,ignoreCastCodecs:!l,table:e})}`:void 0,h=n?J` where ${n}`:void 0,g=this.buildOrderBy(c),_=this.buildLimit(s);return J`${u}update ${e} set ${d}${f}${p}${h}${m}${g}${_}`}buildSelection(e,{isSingleTable:t=!1,ignoreCastCodecs:n=!1,table:r}={}){let{length:i}=e,a=[],o=vI(r),s=r?yI(r,o,q.sql)||yI(r,o,q.subquery)?void 0:r[rI.Symbol.IsAlias]||r[rI.Symbol.Schema]===void 0?r[rI.Symbol.Name]:`${r[rI.Symbol.Schema]}.${r[rI.Symbol.Name]}`:void 0;for(let r=0;r<i;++r){let{field:o,codecOverride:c,column:l,fieldType:u}=e[r],d=c;switch(u){case`Column`:{let e;e=t?o.isAlias?J.identifier($I(o).name):J.identifier(o.name):o.isAlias?$I(o):o;let r=n?e:this.codecs.apply(o,`cast`,e,d);a.push(o.isAlias?J`${r} as ${o}`:r);break}case`SQL.Aliased`:if(o.isSelectionField){let e=!t&&o.origin!==void 0?J`${J.identifier(o.origin)}.${J.identifier(o.fieldAlias)}`:J.identifier(o.fieldAlias);l&&!n?a.push(this.codecs.apply(l,`cast`,e,d)):a.push(e)}else{if(t&&s!==void 0){let{queryChunks:e}=o.sql,t=Array(e.length),r=!1;for(let n=0;n<e.length;++n){let i=e[n];if(W(i,sI)){let{table:e}=i;if((e[rI.Symbol.IsAlias]||e[rI.Symbol.Schema]===void 0?e[rI.Symbol.Name]:`${e[rI.Symbol.Schema]}.${e[rI.Symbol.Name]}`)!==s){r=!0;break}t[n]=J.identifier(i.name)}else t[n]=i}if(r)a.push(l&&!n?this.codecs.apply(l,`cast`,o.sql,d):o.sql);else{let e=new mI(t);o.sql.shouldInlineParams&&e.inlineParams(),a.push(l&&!n?this.codecs.apply(l,`cast`,e,d):e)}}else a.push(l&&!n?this.codecs.apply(l,`cast`,o.sql,d):o.sql);a.push(J` as ${J.identifier(o.fieldAlias)}`)}break;case`SQL`:if(t&&s!==void 0){let{queryChunks:e}=o,t=Array(e.length),r=!1;for(let n=0;n<e.length;++n){let i=e[n];if(W(i,sI)){let{table:e}=i;if((e[rI.Symbol.IsAlias]||e[rI.Symbol.Schema]===void 0?e[rI.Symbol.Name]:`${e[rI.Symbol.Schema]}.${e[rI.Symbol.Name]}`)!==s){r=!0;break}t[n]=J.identifier(i.name)}else t[n]=i}if(r)a.push(l&&!n?this.codecs.apply(l,`cast`,o,d):o);else{let e=new mI(t);o.shouldInlineParams&&e.inlineParams(),a.push(l&&!n?this.codecs.apply(l,`cast`,e,d):e)}}else a.push(l&&!n?this.codecs.apply(l,`cast`,o,d):o);break;case`Subquery`:if(o._.isWith)a.push(l&&!n?this.codecs.apply(l,`cast`,o,d):o);else{let e=J`(${o._.sql})`;a.push(J`${l&&!n?this.codecs.apply(l,`cast`,e,d):e} ${J.identifier(o._.alias)}`)}}r<i-1&&a.push(K[`, `])}return new mI(a)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[n,r]of e.entries()){n===0&&t.push(K[` `]);let i=r.table,a=r.on?J` on ${r.on}`:void 0;W(i,ez)?t.push(J`${new G(r.joinType)} join ${i[rI.Symbol.IsAlias]?ZI(i):i}${a}`):t.push(J`${new G(r.joinType)} join ${i}${a}`),n<e.length-1&&t.push(K[` `])}return new mI(t)}buildLimit(e){return typeof e==`object`||typeof e==`number`?J` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e)for(let[n,r]of e.entries())t.push(r),n<e.length-1&&t.push(K[`, `]);return t.length>0?J` order by ${J.join(t)}`:void 0}buildFromTable(e){if(W(e,rI)&&e[rI.Symbol.IsAlias])return ZI(e);if(W(e,uI)&&e[cI].isAlias){let t=J`${J.identifier(e[cI].originalName)}`;return e[cI].schema&&(t=J`${J.identifier(e[cI].schema)}.${t}`),J`${t} ${J.identifier(e[cI].name)}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:n,where:r,having:i,table:a,joins:o,orderBy:s,groupBy:c,limit:l,offset:u,distinct:d,setOperators:f,useSelectionCastCodecs:p}){let m=n??LI(t,void 0,this.codecs),h=vI(a),g=yI(a,h,q.subquery)?a._.alias:yI(a,h,q.view)?a[cI].name:yI(a,h,q.sql)?void 0:iI(a);for(let e of m)if(W(e.field,sI)&&iI(e.field.table)!==g&&!(e=>o?.some(({alias:t})=>t===(e[rI.Symbol.IsAlias]?iI(e):e[rI.Symbol.BaseName])))(e.field.table)){let t=iI(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let _=!o||o.length===0,v=this.buildWithCTE(e),ee=d?J` distinct`:void 0,te=this.buildSelection(m,{isSingleTable:_,table:a,ignoreCastCodecs:!p||f.length>0}),ne=this.buildFromTable(a),re=this.buildJoins(o),ie=r?J` where ${r}`:void 0,ae=i?J` having ${i}`:void 0,oe=[];if(c)for(let[e,t]of c.entries())oe.push(t),e<c.length-1&&oe.push(K[`, `]);let se=oe.length>0?J` group by ${J.join(oe)}`:void 0,ce=this.buildOrderBy(s),le=this.buildLimit(l),ue=u?J` offset ${u}`:void 0,de=J`${v}select${ee} ${te} from ${ne}${re}${ie}${se}${ae}${ce}${le}${ue}`;return f.length>0?this.buildSetOperations(de,m,p,f):de}buildSetOperations(e,t,n,r){for(let n=0;n<r.length;++n){let i=r[n];e=this.buildSetOperationQuery({leftSelect:e,setOperator:i});let a=LI(i.rightSelect.getSelectedFields());for(let e=0;e<t.length;++e){let n=t[e],r=n.path.join(`.`),i=a.find(e=>e.path.join(`.`)===r),o=n.codecOverride??n.column?.codec,s=i.codecOverride??i.column?.codec;n.codecOverride=o&&s?hR(o,s):o}}for(let e=0;e<t.length;++e){let n=t[e];n.codec=n.codecOverride?this.codecs.get(n.column,`normalize`,n.codecOverride):n.codec}return n?J`select ${this.buildSelection(t.map(e=>{if(e.fieldType===`SQL.Aliased`){let t=e.field.clone();return t.isSelectionField=!0,{...e,field:t,fieldType:`SQL.Aliased`}}if(e.fieldType===`Column`&&e.field.isAlias){let t=new mI.Aliased(J`${J.identifier(e.field.name)}`,e.field.name);return t.isSelectionField=!0,{...e,field:t,fieldType:`SQL.Aliased`}}if(e.fieldType===`Subquery`){let t=new mI.Aliased(J`${e.field.getSQL()}`,e.field._.alias);return t.isSelectionField=!0,{...e,field:t,fieldType:`SQL.Aliased`}}return e}),{isSingleTable:!0,ignoreCastCodecs:!n})} from (${e}) ${J.identifier(`drizzle_union`)}`:e}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:n,rightSelect:r,limit:i,orderBy:a,offset:o}}){let s=J`${e.getSQL()} `,c=J`${r.getSQL()}`,l;if(a&&a.length>0){let e=[];for(let t of a)W(t,aR)?e.push(J.identifier(t.name)):W(t,mI)?e.push(J`${OI(t)}`):e.push(J`${t}`);l=J` order by ${J.join(e,K[`, `])}`}let u=typeof i==`object`||typeof i==`number`&&i>=0?J` limit ${i}`:void 0,d=new G(`${t} ${n?`all `:``}`),f=o?J` offset ${o}`:void 0;return J`${s}${d}${c}${l}${u}${f}`}buildInsertQuery({table:e,values:t,onConflict:n,returning:r,withList:i,select:a,columnList:o,useSelectionCastCodecs:s}){let c=e[rI.Symbol.Columns],l=o?o.map(e=>[e,c[e]]):Object.entries(c),u=a&&!W(t,mI)?Object.keys(t.getSelectedFields()).map(e=>[e,c[e]]):l.filter(([e,t])=>!t.shouldDisableInsert()),d=Array(u.length*2+1),f=0;d[f++]=K[`(`];for(let e=0;e<u.length;++e){let[,{name:t}]=u[e];d[f++]=J.identifier(t),e<u.length-1&&(d[f++]=K[`, `])}d[f++]=K[`)`];let p=new mI(d),m;if(a)m=[t.getSQL()];else{let e=t,n=Array(e.length*u.length),r=0;for(let t=0;t<e.length;++t){let i=e[t];for(let e=0;e<u.length;++e){let[t,a]=u[e],o=i[t];o===void 0?a.defaultFn===void 0?a.default!==null&&a.default!==void 0?n[r++]=a.default:a.onUpdateFn===void 0?n[r++]=K.null:n[r++]=a.onUpdateFn():n[r++]=a.defaultFn():n[r++]=o}}m=[K[`values `],new TI(n,u.map(([,e])=>e))]}let h=this.buildWithCTE(i),g=new mI(m),_=r?J` returning ${this.buildSelection(r,{isSingleTable:!0,ignoreCastCodecs:!s,table:e})}`:void 0,v=n?.length?J.join(n):void 0;return J`${h}insert into ${e} ${p} ${g}${v}${_}`}sqlToQuery(e,t){return e.toQuery({escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,codecs:this.codecs,invokeSource:t})}buildRelationalQuery(e){let t=[],n=this.collectRelationalQuery(e,t);return{sql:new mI(t),selection:n}}collectRelationalQuery({schema:e,table:t,tableConfig:n,queryConfig:r,relationWhere:i,mode:a,nested:o,errorPath:s,depth:c,through:l,jsonb:u,withSubqueries:d,usedTables:f},p){let m=[],h=a===`first`,g=r===!0?void 0:r,_=s??``,v=c??0,ee=d??{subqueries:new Map,usedTables:f};v||(QL(ee,t),t=XI(t,`d${v}`));let te=t[eI],ne=h?1:g?.limit,re=g?.offset,{sql:ie}=JL(t,g,n.relations,e,ee,i),ae=g?.orderBy?UL(t,g.orderBy,n.relations,e,ee):void 0,oe=g?g.with:void 0,se=[];if(oe)for(let e of Object.keys(oe))oe[e]&&se.push(e);let ce=v?-1:p.length;v||p.push(void 0),p.push(K[`select `]);let le=+!!ZL(te,n.table[JF],m,!!o,n.name,this.codecs,p,g?.columns);if(g?.extras){let e=p.length;le&&p.push(K[`, `]);let n=WL(t,g.extras,this.codecs,!!o,p);m.push(...n.selection),n.sql?++le:p.length=e}if(!le&&!se.length)throw new GF({message:`No fields selected for table "${n.name}"${_?` ("${_}")`:``}`});for(let r of se){let i=oe[r],a=n.relations[r];if(!a)throw new GF({message:`Unknown relation "${n.name}" -> "${r}"`});let s=a.relationType===`one`;QL(ee,a.targetTable),QL(ee,a.throughTable);let c=XI(a.targetTable,`d${v+1}`),l=a.throughTable?XI(a.throughTable,`tr${v}`):void 0,{filter:d,joinCondition:f}=qL(a,t,c,l);le++&&p.push(K[`, `]);let h=p.length;p.push(void 0,hz.relationFrom);let g=this.collectRelationalQuery({table:c,mode:s?`first`:`many`,schema:e,queryConfig:i,tableConfig:e[a.targetTableName],relationWhere:d,nested:!0,errorPath:`${_.length?`${_}.`:``}${r}`,depth:v+1,withSubqueries:ee,through:l?{table:l,condition:f}:void 0,jsonb:u},p);p.push(hz.relationClose,J.identifier(r));let te=[K[`(select `],o?u:hz.json,s?hz.object:hz.groupArray];for(let e=0;e<g.length;++e){let t=g[e];e&&te.push(K[`, `]),te.push(new G(this.escapeString(t.key)),K[`, `]),t.selection?te.push(u,K[`(`],J.identifier(t.key),K[`)`]):te.push(J.identifier(t.key))}te.push(s?K[`)`]:hz.groupArrayClose),p[h]=new mI(te),m.push({field:c,fieldType:`Nested`,key:r,selection:g,isArray:!s,isOptional:(a.optional??!1)||i!==!0&&!!i.where})}return p.push(K[` from `]),$L(t,p),l&&(p.push(K[` inner join `]),$L(l.table,p),p.push(K[` on `],...l.condition)),ie&&p.push(K[` where `],...ie),ae&&p.push(K[` order by `],...ae),ne!==void 0&&p.push(K[` limit `],ne),re!==void 0&&p.push(K[` offset `],re),ce!==-1&&(p[ce]=this.buildWithCTE([...ee.subqueries.values()])),m}},_z=class extends uI{static[U]=`SQLiteViewBase`},vz=class e{static[U]=`SelectionProxyHandler`;static[Symbol.hasInstance](e){return W(e,this)}config;constructor(e){this.config={...e}}get(t,n,r){if(n===`_`)return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(n===cI)return{...t[cI],selectedFields:new Proxy(t[cI].selectedFields,this)};if(typeof n==`symbol`)return t[n];let i=vI(t),a=(yI(t,i,q.subquery)?t._.selectedFields:yI(t,i,q.view)?t[cI].selectedFields:t)[n];if(a===void 0&&n===`getSQL`){let e=t[n];return typeof e==`function`?e.bind(r??t):e}let o=vI(a);if(yI(a,o,q.aliased)){if(this.config.sqlAliasedBehavior===`sql`&&!a.isSelectionField)return a.sql;let e=a.clone();return e.isSelectionField=!0,e.origin=this.config.alias,e}if(yI(a,o,q.sql)){if(this.config.sqlBehavior===`sql`)return a;throw Error(`You tried to reference "${n}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return yI(a,o,q.column)?this.config.alias?new Proxy(a,new WI(new Proxy(a.table,new KI(this.config.alias,this.config.replaceOriginalName??!1,!0)),!0)):a:typeof a!=`object`||!a?a:new Proxy(a,new e(this.config))}};function yz(e){if(W(e,rI))return[e[QF]];let t=new Set;return kI(e.queryChunks,t),[...t]}var bz=class{static[U]=`TypedQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}getSelectedFields(){return this._.selectedFields}},xz=class{builder;static[U]=`SQLiteSelectBuilder`;static[Symbol.hasInstance](e){return W(e,this)}fields;session;dialect;withList;distinct;constructor(e,t=Sz){this.builder=t,this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,n;return n=this.fields?this.fields:W(e,dI)?Object.fromEntries(Object.keys(e._.selectedFields).map(t=>[t,e[t]])):W(e,_z)?e[cI].selectedFields:W(e,mI)?{}:BI(e),new this.builder({table:e,fields:n,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList??[],distinct:this.distinct})}},Sz=class extends bz{static[U]=`SQLiteSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=VI(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}getUsedTables(e=this.getSQL()){return yz(e)}createJoin(e){return(t,n)=>{let r=this.tableName,i=VI(t);if(typeof i==`string`&&this.config.joins?.some(e=>e.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(this.config.fieldsFlat=void 0,this.config.mapper=void 0,!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof r==`string`&&(this.config.fields={[r]:this.config.fields}),typeof i==`string`&&!W(t,mI))){let e=W(t,dI)?t._.selectedFields:W(t,uI)?t[cI].selectedFields:t[rI.Symbol.Columns];this.config.fields[i]=e}if(typeof n==`function`&&(n=n(new Proxy(this.config.fields,new vz({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:t,joinType:e,alias:i}),typeof i==`string`)switch(e){case`left`:this.joinsNotNullableMap[i]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[i]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!1}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);crossJoin=this.createJoin(`cross`);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(wz()):n;if(!zI(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);except=this.createSetOperator(`except`,!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new vz({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new vz({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new vz({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new vz({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enabled:!0,autoInvalidate:!0}:e===!1?{enabled:!1}:{enabled:!0,autoInvalidate:!0,...e},this}getSQL(e=!1){return this.config.fieldsFlat??=LI(this.config.fields,void 0,this.dialect.codecs),this.dialect.buildSelectQuery(e?{...this.config,useSelectionCastCodecs:!0}:this.config)}toSQL(e=!0){return this.dialect.sqlToQuery(this.getSQL(e))}as(e){return new Proxy(new dI(this.getSQL(),this.config.fields,e),new vz({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new vz({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}};function Cz(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!zI(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}var wz=()=>({union:Tz,unionAll:Ez,intersect:Dz,except:Oz}),Tz=Cz(`union`,!1),Ez=Cz(`union`,!0),Dz=Cz(`intersect`,!1),Oz=Cz(`except`,!1),kz=class{static[U]=`SQLiteQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}dialect;dialectConfig;constructor(e){this.dialect=W(e,gz)?e:void 0,this.dialectConfig=W(e,gz)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>{typeof r==`function`&&(r=r(n));let i=r.getSQL();return new Proxy(new fI(i,t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new vz({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}}};with(...e){let t=this;function n(n){return new xz({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(n){return new xz({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:r}}select(e){return new xz({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new xz({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||=new gz(this.dialectConfig),this.dialect}},Az=class{name;static[U]=`SQLiteViewBuilderCore`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}config={}},jz=class extends Az{static[U]=`SQLiteViewBuilder`;as(e){typeof e==`function`&&(e=e(new kz));let t=new vz({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=e.getSelectedFields();return new Proxy(new Nz({config:{name:this.name,schema:void 0,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},Mz=class extends Az{static[U]=`SQLiteManualViewBuilder`;columns;constructor(e,t,n){super(e),this.columns=BI(tz(e,t,void 0,void 0,n))}existing(){return new Proxy(new Nz({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new vz({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new Nz({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new vz({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},Nz=class extends _z{static[U]=`SQLiteView`;constructor({config:e}){super(e)}};function Pz(e){return((t,n)=>n?new Mz(t,n,e):new jz(t))}function Fz(e,t){return new Proxy(e,new KI(t,!1))}var Iz={table:nz(`snake_case`),view:Pz(`snake_case`)},Lz=class extends V(`CycleBudgetReset`)({itemKey:bN,repository:Lk,generation:JN}){},Rz=class extends NE(`CycleBudgetResetRejectedError`)(`CycleBudgetResetRejectedError`,{askId:QN}){},zz=[`ItemClosed`];bT(zz);var Bz=N({...Lz.fields,ask:yE($N),resetPending:cT}),Vz=Iz.table(`usine_events`,{eventId:X().$type().primaryKey(),dedupKey:X().$type().notNull().unique(),payloadJson:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[az(`usine_events_payload_json_valid`,J`json_valid(${e.payloadJson})`)]),Z=Iz.table(`usine_trigger_events`,{eventId:X().$type().primaryKey().references(()=>Vz.eventId),itemKey:X().$type().notNull(),loopName:X().$type().notNull(),stepName:X().$type().notNull(),approval:X({enum:qk}).$type().notNull(),permissions:X({enum:Yk}).$type().notNull().default(`write`),cycleLimit:PR().$type(),cycleGeneration:PR().notNull().default(0),repository:X().$type().notNull(),revision:X().$type().notNull(),task:X().$type().notNull(),agentJson:X({mode:`json`}).$type().notNull(),parentModel:X().$type(),reopensEventId:X().$type().references(()=>Vz.eventId),reopening:PR().notNull().default(0)},e=>[az(`usine_trigger_events_approval`,J`${e.approval} in ('none', 'required')`),az(`usine_trigger_events_cycle_limit`,J`${e.cycleLimit} is null or ${e.cycleLimit} >= 1`),az(`usine_trigger_events_agent_json_valid`,J`json_valid(${e.agentJson})`),lz(`usine_trigger_events_item`).on(e.loopName,e.itemKey),lz(`usine_trigger_events_item_history`).on(e.itemKey),uz(`usine_trigger_event_reopening`).on(e.reopensEventId,e.reopening)]),Hz=Iz.table(`usine_loop_items`,{loopName:X().$type().notNull(),itemKey:X().$type().notNull(),observedEventId:X().$type().references(()=>Vz.eventId),suppressedByRunId:X().$type().references(()=>Q.runId),suppressedEventId:X().$type().references(()=>Vz.eventId)},e=>[dz({columns:[e.loopName,e.itemKey]})]),Uz=Iz.table(`usine_item_cycle_budgets`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),generation:PR().notNull().default(0),askJson:X({mode:`json`}).$type(),resetPending:PR({mode:`boolean`}).notNull().default(!1)},e=>[az(`usine_item_cycle_generation`,J`${e.generation} >= 0`),az(`usine_item_cycle_ask_json`,J`${e.askJson} is null or json_valid(${e.askJson})`)]),Wz=Iz.table(`usine_cycle_reservations`,{runId:X().$type().primaryKey().references(()=>Q.runId),itemKey:X().$type().notNull().references(()=>Uz.itemKey),generation:PR().notNull(),loop:X().$type().notNull()},e=>[lz(`usine_cycle_reservations_item`).on(e.itemKey,e.generation,e.loop),az(`usine_cycle_reservations_generation`,J`${e.generation} >= 0`)]),Gz=Iz.table(`usine_cycle_resets`,{askId:X().$type().primaryKey(),eventId:X().$type().notNull().unique().references(()=>Vz.eventId),itemKey:X().$type().notNull().references(()=>Uz.itemKey)}),Kz=Iz.table(`usine_cycle_ask_closures`,{askId:X().$type().primaryKey(),itemKey:X().$type().notNull().references(()=>Uz.itemKey),reason:X({enum:zz}).$type().notNull(),askJson:X({mode:`json`}).$type().notNull(),closedAt:X().notNull()},e=>[az(`usine_cycle_ask_closures_reason`,J`${e.reason} in ('ItemClosed')`),az(`usine_cycle_ask_closures_ask_json`,J`json_valid(${e.askJson})`)]),Q=Iz.table(`usine_runs`,{runId:X().$type().primaryKey(),eventId:X().$type().notNull().unique().references(()=>Z.eventId),loopName:X().$type().notNull(),stateJson:X({mode:`json`}).$type().notNull(),resolvedFailureAttemptId:X().$type(),openedAt:X().notNull(),closedAt:X(),repository:X().$type().notNull(),revision:X().$type().notNull(),task:X().$type().notNull(),agentJson:X({mode:`json`}).$type().notNull(),parentModel:X().$type(),nextStartJson:X({mode:`json`}).$type()},e=>[az(`usine_runs_state_json_valid`,J`json_valid(${e.stateJson})`),az(`usine_runs_agent_json_valid`,J`json_valid(${e.agentJson})`)]),qz=Iz.table(`usine_steps`,{runId:X().$type().notNull().references(()=>Q.runId),stepName:X().$type().notNull(),result:X({mode:`json`}).$type()},e=>[dz({columns:[e.runId,e.stepName]}),az(`usine_steps_result_json_valid`,J`${e.result} is null or json_valid(${e.result})`)]),$=Iz.table(`usine_attempts`,{attemptId:X().$type().primaryKey(),runId:X().$type().notNull(),stepName:X().$type().notNull(),workerName:X().$type().notNull(),attemptNumber:PR({mode:`number`}).$type().notNull(),brainJson:X({mode:`json`}).$type().notNull(),task:X().$type().notNull(),agent:X().$type().notNull(),operatorIntervened:PR({mode:`boolean`}).notNull().default(!1),parentModel:X().$type(),startedAt:X().notNull(),outcomeJson:X({mode:`json`}).$type(),endedAt:X(),salvageJson:X({mode:`json`}).$type(),leftoversDiscardedAt:X(),startJson:X({mode:`json`}).$type(),failureResolutionJson:X({mode:`json`}).$type(),reattachedAt:X(),commentsJson:X({mode:`json`}).$type(),outOfMemoryJson:X({mode:`json`}).$type()},e=>[az(`usine_attempts_number`,J`${e.attemptNumber} >= 1`),az(`usine_attempts_brain_json_valid`,J`json_valid(${e.brainJson})`),az(`usine_attempts_outcome_json_valid`,J`${e.outcomeJson} is null or json_valid(${e.outcomeJson})`),az(`usine_attempts_salvage_json_valid`,J`${e.salvageJson} is null or json_valid(${e.salvageJson})`),uz(`usine_attempt_number`).on(e.runId,e.stepName,e.attemptNumber),uz(`usine_one_in_flight_attempt`).on(e.runId).where(J`${e.outcomeJson} is null`),rR({columns:[e.runId,e.stepName],foreignColumns:[qz.runId,qz.stepName]})]),Jz=Iz.table(`usine_attempt_transcripts`,{sequence:PR({mode:`number`}).primaryKey({autoIncrement:!0}),attemptId:X().$type().notNull().references(()=>$.attemptId),direction:X({enum:GM}).notNull(),channelSequence:PR({mode:`number`}).$type().notNull(),envelope:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[az(`usine_attempt_transcripts_direction`,J`${e.direction} in ('inbound', 'outbound')`),az(`usine_attempt_transcripts_sequence`,J`${e.channelSequence} >= 1`),az(`usine_attempt_transcripts_envelope_json_valid`,J`json_valid(${e.envelope})`),uz(`usine_attempt_transcript_envelope`).on(e.attemptId,e.direction,e.channelSequence),lz(`usine_attempt_transcript_tail`).on(e.attemptId,e.sequence)]),Yz=Iz.table(`usine_approvals`,{runId:X().$type().primaryKey().references(()=>Q.runId),eventId:X().$type().notNull().unique().references(()=>Vz.eventId),channel:X({enum:wN}).$type(),approver:X().$type()},e=>[az(`usine_approvals_source`,J`(${e.channel} is null and ${e.approver} is null) or ${e.channel} = 'ui' or (${e.channel} = 'github-ask' and ${e.approver} is not null)`)]),Xz=Iz.table(`usine_run_again_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),fromRunId:X().$type().notNull().references(()=>Q.runId),requestedBy:X().$type()}),Zz=Iz.table(`usine_ignored_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),reason:X({enum:HP}).$type().notNull()},e=>[az(`usine_ignored_events_reason`,J`${e.reason} in ('superseded', 'revoked')`)]),Qz=Iz.table(`usine_cursors`,{cursorKey:X().primaryKey(),valueJson:X({mode:`json`}).$type().notNull()},e=>[az(`usine_cursors_value_json_valid`,J`json_valid(${e.valueJson})`)]),$z=Iz.table(`usine_item_projections`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),source:X().notNull(),itemNumber:PR({mode:`number`}).notNull(),contentHash:X().notNull(),payloadJson:X({mode:`json`}).$type().notNull(),goneAt:X()},e=>[az(`usine_item_projections_number`,J`${e.itemNumber} >= 1`),az(`usine_item_projections_payload_json_valid`,J`json_valid(${e.payloadJson})`),uz(`usine_item_projection_number`).on(e.repository,e.itemNumber)]),eB=Iz.table(`usine_repository_label_projections`,{repository:X().$type().primaryKey(),labelsJson:X({mode:`json`}).$type().notNull()},e=>[az(`usine_repository_label_projections_labels_json_valid`,J`json_valid(${e.labelsJson})`)]),tB=Iz.table(`usine_board_moves`,{moveId:PR({mode:`number`}).primaryKey({autoIncrement:!0}),repository:X().$type().notNull(),itemKey:X().$type().notNull(),movedAt:X().notNull(),fromLane:X().notNull(),toLane:X().notNull(),addedJson:X({mode:`json`}).$type().notNull(),removedJson:X({mode:`json`}).$type().notNull()},e=>[az(`usine_board_moves_added_json_valid`,J`json_valid(${e.addedJson})`),az(`usine_board_moves_removed_json_valid`,J`json_valid(${e.removedJson})`),lz(`usine_board_moves_item`).on(e.itemKey,e.movedAt)]),nB=Iz.table(`usine_loop_runtime`,{loopName:X().$type().primaryKey(),paused:PR({mode:`boolean`}).notNull()}),rB=Iz.table(`usine_projection_revision`,{singleton:PR({mode:`number`}).primaryKey().default(1),revision:PR({mode:`number`}).notNull().default(0)},e=>[az(`usine_projection_revision_singleton`,J`${e.singleton} = 1`)]),iB=mL($.leftoversDiscardedAt),aB=mL($.outcomeJson),oB=e=>{let t=k(`RunStoreQueries.attemptCountsByWorker`)(function*(){let t=yield*e.select({worker:$.workerName,attempts:J`count(*)`,running:J`sum(case when ${aB} then 1 else 0 end)`}).from($).where(iB).groupBy($.workerName).orderBy(DL($.workerName)).execute();return yield*Vw(P(WN))(t)});return{attemptCountsByWorker:t,openAttempts:k(`RunStoreQueries.openAttempts`)(function*(e){return(yield*t()).find(t=>t.worker===e)?.running??0}),discardLeftovers:k(`RunStoreQueries.discardLeftovers`)(function*(t,n){return(yield*e.update($).set({leftoversDiscardedAt:hF(n)}).where(aL(Y($.workerName,t),iB)).returning({attemptId:$.attemptId}).execute()).map(({attemptId:e})=>e)})}},sB={itemKey:Uz.itemKey,repository:Uz.repository,generation:Uz.generation,ask:Uz.askJson,resetPending:Uz.resetPending},cB=Vw(P(Bz),{onExcessProperty:`error`}),lB=e=>{let t=Y(Z.cycleGeneration,J`coalesce((
30
+ select ${Uz.generation} from ${Uz}
31
+ where ${Uz.itemKey} = ${Z.itemKey}
32
+ ), 0)`),n=k(`CycleBudget.get`)(function*(t){return yield*O({itemKey:t}),C((yield*e.select(sB).from(Uz).where(Y(Uz.itemKey,t)).execute().pipe(D(cB)))[0])}),r=k(`CycleBudget.counts`)(function*(t){yield*O({itemKey:t.itemKey,generation:t.generation});let n=gL(e.select({id:$.attemptId}).from($).where(Y($.runId,Q.runId))),r=J`json_extract(${Q.stateJson}, '$._tag')`,i=yield*e.select({loop:Wz.loop,admitted:J`count(*)`,completed:J`sum(case when ${pL(r,[..._A])} and ${n} then 1 else 0 end)`}).from(Wz).innerJoin(Q,Y(Q.runId,Wz.runId)).where(aL(Y(Wz.itemKey,t.itemKey),Y(Wz.generation,t.generation),oL(rL(r,`Canceled`),n))).groupBy(Wz.loop).orderBy(DL(Wz.loop)).execute();return yield*Vw(P(ZN))(i,{onExcessProperty:`error`})});return{admit:k(`CycleBudget.admit`)(function*(t){yield*O({itemKey:t.itemKey,loop:t.loop});let i=yield*n(t.itemKey);if(S(i)&&S(i.value.ask))return yield*A(`Item cycle budget remains exhausted`,{itemKey:t.itemKey,askId:i.value.ask.value.id,loop:t.loop}),i.value.ask;if(x(t.cycleLimit))return y();yield*e.insert(Uz).values({itemKey:t.itemKey,repository:t.repository}).onConflictDoNothing().execute();let a=yield*n(t.itemKey);if(x(a))return yield*Gh(Error(`Cycle budget missing after insertion`));let o=yield*r(a.value),s=o.find(({loop:e})=>e===t.loop);if(s===void 0||s.admitted<t.cycleLimit.value)return y();let c=new $N({id:QN.make(Uk.make(JSON.stringify([t.event.id,a.value.generation]))),itemKey:t.itemKey,repository:t.repository,loop:t.loop,limit:t.cycleLimit.value,counts:[s,...o.filter(({loop:e})=>e!==t.loop)]});return yield*e.update(Uz).set({askJson:Yw($N)(c)}).where(Y(Uz.itemKey,t.itemKey)).execute(),yield*$g(`Item cycle budget exhausted; operator reset required`,{itemKey:t.itemKey,repository:t.repository,askId:c.id,loop:c.loop,limit:c.limit,completedCycles:c.completedCycles,counts:c.counts}),b(c)}),reserve:k(`CycleBudget.reserve`)(function*(t,i){if(x(t.cycleLimit))return;yield*O({runId:i,itemKey:t.itemKey,loop:t.loop});let a=yield*n(t.itemKey);if(x(a))return yield*Gh(Error(`Run admitted without its cycle budget`));yield*e.insert(Wz).values({runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation}).onConflictDoNothing().execute(),yield*A(`Item cycle reserved`,{runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation,counts:yield*r(a.value)})}),get:n,asks:k(`CycleBudget.asks`)(function*(){return(yield*e.select(sB).from(Uz).where(hL(Uz.askJson)).execute().pipe(D(cB))).flatMap(({ask:e})=>jr(e))}),pendingResets:k(`CycleBudget.pendingResets`)(function*(){return yield*e.select(sB).from(Uz).where(Y(Uz.resetPending,!0)).execute().pipe(D(cB))}),isCurrentEvent:k(`CycleBudget.isCurrentEvent`)(function*(e){yield*O({eventId:e.event.id,itemKey:e.itemKey});let t=vr(yield*n(e.itemKey),{onNone:()=>0,onSome:e=>e.generation}),r=e.cycleGeneration===t;return r||(yield*A(`Event observation was superseded by a cycle reset`,{eventId:e.event.id,itemKey:e.itemKey,observedGeneration:e.cycleGeneration,generation:t})),r}),currentEvent:t}},uB=Vw(P(N({observedEventId:I(Uk),suppressedByRunId:I(kA),suppressedEventId:I(Uk)}))),dB=Vw(P(N({loop:Kk,itemKey:bN,observedEventId:I(Uk),suppressedByRunId:I(kA)}))),fB=Vw(P(N({eventId:Uk,reopensEventId:Uk}))),pB=Vw(P(N({eventId:Uk,runId:kA}))),mB=e=>{let t=(e,t)=>aL(Y(Hz.loopName,e),Y(Hz.itemKey,t)),n=k(`LoopItems.row`)(function*(n,r){return C((yield*uB(yield*e.select({observedEventId:Hz.observedEventId,suppressedByRunId:Hz.suppressedByRunId,suppressedEventId:Hz.suppressedEventId}).from(Hz).where(t(n,r)).execute()))[0])});return{sighted:k(`LoopItems.sighted`)(function*(t,r,i){let a=Dr(yield*n(t,r),({observedEventId:e})=>C(e));return yield*e.insert(Hz).values({loopName:t,itemKey:r,observedEventId:i}).onConflictDoUpdate({target:[Hz.loopName,Hz.itemKey],set:{observedEventId:i}}).execute(),a}),unmatched:k(`LoopItems.unmatched`)(function*(n,r){yield*e.update(Hz).set({observedEventId:null,suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),suppression:k(`LoopItems.suppression`)(function*(e,t){return Or(yield*n(e,t),({suppressedByRunId:e,suppressedEventId:t})=>e===null?y():b({runId:e,suppressedEventId:C(t)}))}),startSuppression:k(`LoopItems.startSuppression`)(function*(t,r,i,a,o){if(Fr(yield*n(t,r),({observedEventId:e})=>e===null))return!1;let s=w(o);return yield*e.insert(Hz).values({loopName:t,itemKey:r,observedEventId:a,suppressedByRunId:i,suppressedEventId:s}).onConflictDoUpdate({target:[Hz.loopName,Hz.itemKey],set:{suppressedByRunId:i,suppressedEventId:s}}).execute(),!0}),suppressFrom:k(`LoopItems.suppressFrom`)(function*(n,r,i){yield*e.update(Hz).set({suppressedEventId:i}).where(aL(t(n,r),hL(Hz.suppressedByRunId))).execute()}),lift:k(`LoopItems.lift`)(function*(n,r){yield*e.update(Hz).set({suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),liftRun:k(`LoopItems.liftRun`)(function*(t){return(yield*e.update(Hz).set({suppressedByRunId:null,suppressedEventId:null}).where(Y(Hz.suppressedByRunId,t)).returning({loopName:Hz.loopName}).execute()).length>0}),sightings:k(`LoopItems.sightings`)(function*(t){let n=[...new Set(t)];if(n.length===0)return[];let r=(yield*Nh(la(n,100),t=>e.select({loop:Hz.loopName,itemKey:Hz.itemKey,observedEventId:Hz.observedEventId,suppressedByRunId:Hz.suppressedByRunId}).from(Hz).where(fL(Hz.itemKey,t)).execute().pipe(D(dB)))).flat(),i=[...new Set(r.flatMap(({observedEventId:e})=>e===null?[]:[e]))],a=(yield*Nh(la(i,100),t=>e.select({eventId:Z.eventId,reopensEventId:Z.reopensEventId}).from(Z).where(fL(Z.reopensEventId,t)).orderBy(OL(Z.reopening)).execute().pipe(D(fB)))).flat(),o=new Map;for(let{eventId:e,reopensEventId:t}of a)o.has(t)||o.set(t,e);let s=e=>o.get(e)??e,c=new Map((yield*Nh(la(i.map(s),100),t=>e.select({eventId:Q.eventId,runId:Q.runId}).from(Q).where(fL(Q.eventId,t)).execute().pipe(D(pB)))).flat().map(({eventId:e,runId:t})=>[e,t]));return r.map(({loop:e,itemKey:t,observedEventId:n,suppressedByRunId:r})=>{let i=Dr(C(n),s);return new GN({loop:e,itemKey:t,event:i,run:Or(i,e=>C(c.get(e))),suppressedBy:C(r)})})})}},hB=e=>({appendTranscript:k(`RunStoreQueries.appendTranscript`)(function*(t,n,r){return(yield*e.insert(Jz).values({attemptId:n.attemptId,direction:t,channelSequence:n.sequence,envelope:EF(n),receivedAt:hF(r)}).onConflictDoNothing().returning({sequence:Jz.sequence}).execute()).length>0}),transcript:k(`RunStoreQueries.transcript`)(function*(t){yield*O({attemptId:t.attemptId,query:t._tag});let n=xk(t,{TranscriptSessionsQuery:({attemptId:t})=>fL(Jz.sequence,e.select({sequence:J`max(${Jz.sequence})`}).from(Jz).where(aL(Y(Jz.attemptId,t),J`(
33
+ json_extract(${Jz.envelope}, '$.payload._tag') = 'InterventionApplied'
34
+ OR (json_extract(${Jz.envelope}, '$.payload._tag') = 'SessionEvent'
35
+ AND json_extract(${Jz.envelope}, '$.payload.event._tag') IN ('SessionStarted', 'SessionIdle', 'SessionResumed', 'SessionFinished'))
36
+ )`)).groupBy(J`coalesce(json_extract(${Jz.envelope}, '$.payload.event.session.id'), json_extract(${Jz.envelope}, '$.payload.intervention.target.sessionId'), '@parent')`,J`json_extract(${Jz.envelope}, '$.payload._tag')`,J`json_extract(${Jz.envelope}, '$.payload.event._tag') = 'SessionStarted'`)),TranscriptUsageQuery:({attemptId:t})=>{let n=e.select({sequence:Jz.sequence,tokens:J`max(json_extract(${Jz.envelope}, '$.payload.event.totalTokens'))`.as(`tokens`)}).from(Jz).where(aL(Y(Jz.attemptId,t),J`json_extract(${Jz.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${Jz.envelope}, '$.payload.event._tag') = 'SessionTokensUpdated'`)).groupBy(J`json_extract(${Jz.envelope}, '$.payload.event.session.id')`).as(`highest`);return fL(Jz.sequence,e.select({sequence:n.sequence}).from(n))},TranscriptAllQuery:({attemptId:e})=>Y(Jz.attemptId,e),TranscriptTailQuery:({attemptId:e,after:t})=>aL(Y(Jz.attemptId,e),cL(Jz.sequence,t)),TranscriptPageQuery:({attemptId:e,before:t})=>vr(t,{onNone:()=>Y(Jz.attemptId,e),onSome:t=>aL(Y(Jz.attemptId,e),uL(Jz.sequence,t))})}),r=e.select({sequence:Jz.sequence,attemptId:Jz.attemptId,direction:Jz.direction,envelope:Jz.envelope,receivedAt:Jz.receivedAt}).from(Jz).where(n);return(yield*pF(yield*xk(t,{TranscriptSessionsQuery:()=>r.orderBy(DL(Jz.sequence)).execute(),TranscriptUsageQuery:()=>r.orderBy(DL(Jz.sequence)).execute(),TranscriptAllQuery:()=>r.orderBy(DL(Jz.sequence)).execute(),TranscriptTailQuery:({limit:e})=>r.orderBy(DL(Jz.sequence)).limit(e).execute(),TranscriptPageQuery:({limit:e})=>r.orderBy(OL(Jz.sequence)).limit(e).execute()}),{onExcessProperty:`error`})).map(BF).sort((e,t)=>e.sequence-t.sequence)})}),gB=(e,t)=>G_(t.openedAt)-G_(e.openedAt)||t.runId.localeCompare(e.runId),_B={eventId:Vz.eventId,dedupKey:Vz.dedupKey,payload:Vz.payloadJson,receivedAt:Vz.receivedAt,itemKey:Z.itemKey,loop:Z.loopName,step:Z.stepName,approval:Z.approval,permissions:Z.permissions,cycleLimit:Z.cycleLimit,cycleGeneration:Z.cycleGeneration,repository:Z.repository,revision:Z.revision,task:Z.task,agent:Z.agentJson,parentModel:Z.parentModel},vB=Fz(Vz,`approval_event`),yB={itemKey:Z.itemKey,runId:Q.runId,eventId:Q.eventId,loop:Q.loopName,state:Q.stateJson,resolvedFailureAttemptId:Q.resolvedFailureAttemptId,openedAt:Q.openedAt,closedAt:Q.closedAt,repository:Q.repository,revision:Q.revision,task:Q.task,agent:Q.agentJson,parentModel:Q.parentModel,stepName:qz.stepName,result:qz.result,approvedAt:vB.receivedAt,approvalChannel:Yz.channel,approver:Yz.approver,againFrom:Xz.fromRunId,againRequestedBy:Xz.requestedBy},bB={attemptId:$.attemptId,runId:$.runId,stepName:$.stepName,worker:$.workerName,number:$.attemptNumber,brain:$.brainJson,task:$.task,agent:$.agent,operatorIntervened:$.operatorIntervened,parentModel:$.parentModel,startedAt:$.startedAt,outcome:$.outcomeJson,endedAt:$.endedAt,salvage:$.salvageJson,start:$.startJson,failureResolution:$.failureResolutionJson,reattachedAt:$.reattachedAt,comments:$.commentsJson,outOfMemory:$.outOfMemoryJson},xB=J`json_extract(${Q.stateJson}, '$._tag')`,SB=fL(xB,[..._A]),CB=fL(xB,[...yA]),wB=e=>Gw(IE)(DF(e)),TB=e=>{let t=k(`RunStoreQueries.eventRouteByDedup`)(function*(t){return yield*iF(yield*e.select(_B).from(Vz).innerJoin(Z,Y(Z.eventId,Vz.eventId)).where(Y(Vz.dedupKey,t)).execute())}),n=k(`RunStoreQueries.eventRouteByRun`)(function*(t){return yield*iF(yield*e.select(_B).from(Q).innerJoin(Vz,Y(Vz.eventId,Q.eventId)).innerJoin(Z,Y(Z.eventId,Vz.eventId)).where(Y(Q.runId,t)).execute())}),r=()=>e.select(yB).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).innerJoin(qz,Y(qz.runId,Q.runId)).leftJoin(Yz,Y(Yz.runId,Q.runId)).leftJoin(vB,Y(vB.eventId,Yz.eventId)).leftJoin(Xz,Y(Xz.eventId,Q.eventId)),i=k(`RunStoreQueries.runRows`)(function*(e){return yield*sF(yield*r().where(Y(Q.runId,e)).execute())}),a=(...t)=>E(function*(){let n=yield*e.select({attemptId:$.attemptId,worker:$.workerName,repository:Q.repository,runId:$.runId,loop:Z.loopName,itemKey:Z.itemKey,number:$.attemptNumber,permissions:Z.permissions,outcome:J`coalesce(json_extract(${$.outcomeJson}, '$._tag'), '')`,salvage:$.salvageJson}).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(aL(mL($.leftoversDiscardedAt),...t)).execute();return(yield*Vw(P(N({attemptId:TM,worker:BA,repository:Lk,runId:kA,loop:Kk,itemKey:bN,number:EM,permissions:Xk,outcome:M,salvage:I(_M)})))(n)).map(({number:e,outcome:t,salvage:n,...r})=>({...r,ref:hM(r.runId,e),succeeded:t===`Succeeded`,open:t===``,rejected:n?._tag===`Rejected`?b(n):y()}))}),o=k(`RunStoreQueries.salvageCandidates`)(function*(){return yield*a()}),s=k(`RunStoreQueries.salvageCandidate`)(function*(e){return yield*O({attemptId:e}),$i(yield*a(Y($.attemptId,e)))}),c=k(`RunStoreQueries.attemptRows`)(function*(t){return yield*lF(yield*e.select(bB).from($).where(Y($.runId,t)).orderBy($.attemptNumber).execute())}),l=k(`RunStoreQueries.snapshot`)(function*(e){let[t,r,a]=yield*Mh([i(e),c(e),n(e)]),o=t[0],s=a[0];return o===void 0||s===void 0?yield*new eP({runId:e}):new BN({event:jF(s),itemKey:s.itemKey,run:PF(o),step:LF(o),attempts:r.map(RF),resolvedFailureAttemptId:C(o.resolvedFailureAttemptId),closedAt:C(o.closedAt),approval:FF(o),runAgain:IF(o),repository:o.repository,revision:o.revision,task:o.task,agent:o.agent,parentModel:C(o.parentModel),permissions:s.permissions})}),u=k(`RunStoreQueries.summariesWithAttempts`)(function*(t){let n=ua((yield*Nh(la(t.map(({runId:e})=>e),100),t=>e.select(bB).from($).where(fL($.runId,t)).orderBy(DL($.runId),DL($.attemptNumber)).execute().pipe(D(lF)))).flat(),({runId:e})=>e);return t.map(e=>zF(e,n[e.runId]??[]))}),d=k(`RunStoreQueries.itemRunSummaries`)(function*(e){if(e.length===0)return[];let t=(yield*Nh(la([...new Set(e)],100),e=>r().where(fL(Z.itemKey,e)).execute().pipe(D(sF)))).flat().sort(gB);return yield*u(t)}),f=k(`RunStoreQueries.runSummaries`)(function*(e){let[t,n]=yield*Mh([r().where(SB).orderBy(OL(Q.openedAt),OL(Q.runId)).execute().pipe(D(sF)),r().where(pL(xB,[..._A])).orderBy(OL(Q.openedAt),OL(Q.runId)).limit(e).execute().pipe(D(sF))]),i=[...t,...n].sort(gB);return yield*u(i)}),p=k(`RunStoreQueries.runEvents`)(function*(t){return(yield*Nh(la([...new Set(t)],100),t=>e.select({runId:Q.runId,eventId:Vz.eventId,dedupKey:Vz.dedupKey,payload:Vz.payloadJson,receivedAt:Vz.receivedAt}).from(Q).innerJoin(Vz,Y(Vz.eventId,Q.eventId)).where(fL(Q.runId,t)).execute().pipe(D(cF)))).flat().map(MF)}),m=k(`RunStoreQueries.closedRunSummaries`)(function*(e){let t=yield*r().where(pL(xB,[..._A])).orderBy(OL(Q.closedAt),OL(Q.runId)).limit(e).execute().pipe(D(sF));return yield*u(t)}),h=k(`RunStoreQueries.closedRunSummariesSince`)(function*(e){let t=pL(xB,[..._A]),n=yield*r().where(vr(e,{onNone:()=>t,onSome:e=>aL(t,lL(Q.closedAt,hF(e)))})).orderBy(OL(Q.closedAt),OL(Q.runId)).execute().pipe(D(sF));return yield*u(n)}),g=k(`RunStoreQueries.projectionRevision`)(function*(){return C((yield*fF(yield*e.select({revision:rB.revision}).from(rB).where(Y(rB.singleton,1)).limit(1).execute()))[0]?.revision)}),_=k(`RunStoreQueries.updateState`)(function*(t,n,r){let i=fA(n)?null:hF(r??(yield*z_));if((yield*e.update(Q).set({stateJson:gF(n),closedAt:i}).where(Y(Q.runId,t)).returning({runId:Q.runId}).execute()).length===0)return yield*new eP({runId:t})}),v=k(`RunStoreQueries.resolveFailure`)(function*(t,n,r){yield*O({runId:t,attemptId:n}),yield*e.update($).set({failureResolutionJson:SF(r)}).where(Y($.attemptId,n)).execute(),yield*e.update(Q).set({resolvedFailureAttemptId:n}).where(Y(Q.runId,t)).execute()}),ee=k(`RunStoreQueries.addAttempt`)(function*(t){yield*e.insert($).values({attemptId:t.id,runId:t.runId,stepName:t.stepName,workerName:t.worker,attemptNumber:t.number,brainJson:OF(t.brain),task:t.task,agent:t.agent,operatorIntervened:t.operatorIntervened,parentModel:w(t.parentModel),startedAt:hF(t.startedAt),outcomeJson:null,endedAt:null,salvageJson:null,startJson:vr(t.start,{onNone:()=>null,onSome:CF})}).execute()}),te=k(`RunStoreQueries.recordReattach`)(function*(t,n){yield*O({attemptId:t}),yield*e.update($).set({reattachedAt:hF(n)}).where(Y($.attemptId,t)).execute()}),ne=k(`RunStoreQueries.nextStart`)(function*(t){return C((yield*wF(yield*e.select({nextStart:Q.nextStartJson}).from(Q).where(Y(Q.runId,t)).execute()))[0]?.nextStart)}),re=k(`RunStoreQueries.setNextStart`)(function*(t,n){yield*e.update(Q).set({nextStartJson:vr(n,{onNone:()=>null,onSome:CF})}).where(Y(Q.runId,t)).execute()}),ie=k(`RunStoreQueries.recordSalvage`)(function*(t,n){yield*O({attemptId:t,salvage:n._tag}),yield*e.update($).set({salvageJson:vF(n)}).where(Y($.attemptId,t)).execute()}),ae=k(`RunStoreQueries.recordComments`)(function*(t,n){yield*O({attemptId:t,comments:n.length}),yield*e.update($).set({commentsJson:yF(n)}).where(Y($.attemptId,t)).execute()}),oe=k(`RunStoreQueries.recordOutOfMemory`)(function*(t,n){yield*O({attemptId:t,container:n.container,kills:n.kills});let r=Ki(((yield*xF(yield*e.select({outOfMemory:$.outOfMemoryJson}).from($).where(Y($.attemptId,t)).execute()))[0]?.outOfMemory??[]).filter(({container:e})=>e!==n.container),n);return yield*e.update($).set({outOfMemoryJson:bF(r)}).where(Y($.attemptId,t)).execute(),PM(r)}),se=k(`RunStoreQueries.closeAttempt`)(function*(t,n,r){yield*e.update($).set({outcomeJson:_F(n),endedAt:hF(r)}).where(aL(Y($.attemptId,t),mL($.outcomeJson))).execute()}),ce=k(`RunStoreQueries.amend`)(function*(t,n){yield*O({runId:t,agent:n.agent.name}),yield*e.update(Q).set({task:n.task,agentJson:wB(n.agent),parentModel:w(n.parentModel)}).where(Y(Q.runId,t)).execute()}),le=k(`RunStoreQueries.markIntervened`)(function*(t){yield*O({attemptId:t}),yield*e.update($).set({operatorIntervened:!0}).where(Y($.attemptId,t)).execute()}),ue=k(`RunStoreQueries.updateAttemptParentModel`)(function*(t,n){yield*e.update($).set({parentModel:n}).where(Y($.attemptId,t)).execute()}),de=k(`RunStoreQueries.updateStepResult`)(function*(t,n,r){yield*e.update(qz).set({result:TF(r)}).where(aL(Y(qz.runId,t),Y(qz.stepName,n))).execute()}),fe=k(`RunStoreQueries.approvalExists`)(function*(t){return(yield*e.$count(Yz,Y(Yz.runId,t)).execute())>0}),pe=k(`RunStoreQueries.recordApproval`)(function*(t,n,r){yield*e.insert(Vz).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:mF(n.payload),receivedAt:hF(n.receivedAt)}).onConflictDoNothing().execute(),yield*e.insert(Yz).values({runId:t,eventId:n.id,channel:r.channel,approver:w(r.approver)}).execute()}),me=k(`RunStoreQueries.createRun`)(function*(t,n,r){let i=Fz(Z,`candidate`),a=Fz(Q,`candidate_run`),o=Fz(Zz,`ignored`);yield*e.insert(Zz).select(e.select({eventId:i.eventId,reason:J`'superseded'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).leftJoin(o,Y(o.eventId,i.eventId)).where(aL(Y(i.loopName,t.loop),Y(i.itemKey,t.itemKey),rL(i.eventId,n),mL(a.runId),mL(o.eventId)))).onConflictDoNothing().execute(),yield*e.insert(Q).values({runId:r,eventId:n,loopName:t.loop,stateJson:gF(new tA),openedAt:hF(t.event.receivedAt),repository:t.repository,revision:t.revision,task:t.task,agentJson:wB(t.agent),parentModel:w(t.parentModel)}).onConflictDoNothing().execute(),yield*e.insert(qz).values({runId:r,stepName:t.step,result:null}).onConflictDoNothing().execute()}),he=k(`RunStoreQueries.runForEvent`)(function*(t){return yield*uF(yield*e.select({runId:Q.runId}).from(Q).where(Y(Q.eventId,t)).execute())}),ge=k(`RunStoreQueries.ignoredEvent`)(function*(t){return yield*dF(yield*e.select({reason:Zz.reason}).from(Zz).where(Y(Zz.eventId,t)).execute())}),_e=k(`RunStoreQueries.blockingRun`)(function*(t,n){return yield*uF(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(aL(Y(Z.loopName,t),Y(Z.itemKey,n),SB)).orderBy(OL(Q.openedAt)).limit(1).execute())}),ve=k(`RunStoreQueries.newestReopening`)(function*(t){return Dr(C((yield*aF(yield*e.select({..._B,reopening:Z.reopening}).from(Vz).innerJoin(Z,Y(Z.eventId,Vz.eventId)).where(Y(Z.reopensEventId,t)).orderBy(OL(Z.reopening)).limit(1).execute()))[0]),e=>({submission:NF(e),reopening:e.reopening}))}),ye=k(`RunStoreQueries.reopenedEvent`)(function*(t){let n=Fz(Vz,`reopened_event`);return C((yield*oF(yield*e.select({eventId:n.eventId,dedupKey:n.dedupKey}).from(Z).innerJoin(n,Y(n.eventId,Z.reopensEventId)).where(Y(Z.eventId,t)).execute()))[0])}),be=k(`RunStoreQueries.recordRunAgain`)(function*(t,n){yield*e.insert(Xz).values({eventId:t,fromRunId:n.from,requestedBy:w(n.requestedBy)}).execute()}),xe=k(`RunStoreQueries.recordTriggerEvent`)(function*(n,r=y()){yield*e.insert(Vz).values({eventId:n.event.id,dedupKey:n.event.dedupKey,payloadJson:mF(n.event.payload),receivedAt:hF(n.event.receivedAt)}).onConflictDoNothing().execute();let i=(yield*t(n.event.dedupKey))[0];return i===void 0?(yield*e.insert(Z).values({eventId:n.event.id,itemKey:n.itemKey,loopName:n.loop,stepName:n.step,approval:n.approval,permissions:n.permissions,cycleLimit:w(n.cycleLimit),cycleGeneration:n.cycleGeneration,repository:n.repository,revision:n.revision,task:n.task,agentJson:wB(n.agent),parentModel:w(n.parentModel),reopensEventId:w(Dr(r,({eventId:e})=>e)),reopening:vr(r,{onNone:()=>0,onSome:({reopening:e})=>e})}).execute(),n):NF(i)}),Se=k(`RunStoreQueries.nextQueued`)(function*(t){let r=(yield*n(t))[0];if(r===void 0)return y();let i=yield*mB(e).suppression(r.loop,r.itemKey);if(S(i))return yield*A(`Queued Events wait while a suppression keeps the Item`,{runId:t,suppressedBy:i.value.runId,loop:r.loop,itemKey:r.itemKey}),y();let a=yield*iF(yield*e.select(_B).from(Vz).innerJoin(Z,Y(Z.eventId,Vz.eventId)).leftJoin(Q,Y(Q.eventId,Vz.eventId)).leftJoin(Zz,Y(Zz.eventId,Vz.eventId)).where(aL(Y(Z.loopName,r.loop),Y(Z.itemKey,r.itemKey),lB(e).currentEvent,mL(Q.runId),mL(Zz.eventId))).orderBy(OL(Vz.receivedAt)).execute());return C(a[0]).pipe(Dr(e=>({submission:NF(e),eventIds:a.map(e=>e.eventId)})))}),Ce=k(`RunStoreQueries.runIdsToDrive`)(function*(){return(yield*uF(yield*e.select({runId:Q.runId}).from(Q).where(aL(SB,rL(xB,`Waiting`))).execute())).map(({runId:e})=>e)}),we=k(`RunStoreQueries.pendingContinuations`)(function*(){let t=yield*e.selectDistinct({loop:Z.loopName,itemKey:Z.itemKey}).from(Z).leftJoin(Q,Y(Q.eventId,Z.eventId)).leftJoin(Zz,Y(Zz.eventId,Z.eventId)).leftJoin(Uz,Y(Uz.itemKey,Z.itemKey)).leftJoin(Hz,aL(Y(Hz.loopName,Z.loopName),Y(Hz.itemKey,Z.itemKey))).where(aL(mL(Q.runId),mL(Zz.eventId),mL(Uz.askJson),mL(Hz.suppressedByRunId),lB(e).currentEvent)).execute();return(yield*Nh(yield*Vw(P(N({loop:Kk,itemKey:bN})))(t),({loop:t,itemKey:n})=>E(function*(){return(yield*_e(t,n)).length>0?[]:yield*uF(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(aL(Y(Z.loopName,t),Y(Z.itemKey,n))).orderBy(OL(Q.openedAt),OL(Q.runId)).limit(1).execute())}))).flat().map(({runId:e})=>e)}),Te=k(`RunStoreQueries.revokeQueued`)(function*(t,n,r){let i=Fz(Z,`candidate`),a=Fz(Q,`candidate_run`);return(yield*e.insert(Zz).select(e.select({eventId:i.eventId,reason:J`'revoked'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).where(aL(Y(i.loopName,t),Y(i.itemKey,n),fL(i.eventId,r),mL(a.runId)))).onConflictDoNothing().returning({eventId:Zz.eventId}).execute()).length}),Ee=k(`RunStoreQueries.revokeUnstarted`)(function*(t,n){let r=yield*uF(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(aL(Y(Z.loopName,t),Y(Z.itemKey,n),CB)).execute()),i=e.select({eventId:Z.eventId}).from(Z).where(aL(Y(Z.loopName,t),Y(Z.itemKey,n)));return yield*Te(t,n,i),r});return{salvageCandidates:o,salvageCandidate:s,cycles:lB(e),loopItems:mB(e),...hB(e),addAttempt:ee,recordReattach:te,nextStart:ne,setNextStart:re,recordSalvage:ie,recordComments:ae,recordOutOfMemory:oe,amend:ce,markIntervened:le,approvalExists:fe,blockingRun:_e,closeAttempt:se,createRun:me,eventRouteByRun:n,ignoredEvent:ge,newestReopening:ve,nextQueued:Se,reopenedEvent:ye,recordRunAgain:be,pendingContinuations:we,recordTriggerEvent:xe,runIdsToDrive:Ce,recordApproval:pe,revision:g,revokeQueued:Te,revokeUnstarted:Ee,runSummaries:f,closedRunSummaries:m,closedRunSummariesSince:h,itemRunSummaries:d,runEvents:p,runForEvent:he,snapshot:l,updateStepResult:de,updateAttemptParentModel:ue,updateState:_,resolveFailure:v}},EB=E(function*(){let e=yield*SN,t=TB(e),n=k(`RunReader.inspect`)(e=>t.snapshot(e).pipe(AF(`read run`))),r=k(`RunReader.evidence`)(function*(t){yield*O({runId:t});let n=yield*e.transaction(e=>E(function*(){let n=TB(e),r=yield*n.snapshot(t);return new HN({snapshot:r,transcript:(yield*Nh(r.attempts,({id:e})=>n.transcript(new FN({attemptId:e})))).flat().sort((e,t)=>e.sequence-t.sequence)})})).pipe(AF(`read run evidence`));return yield*j(`Run evidence read`,{runId:t,attempts:n.snapshot.attempts.length,transcriptRows:n.transcript.length}),n}),i=k(`RunReader.list`)(e=>t.runSummaries(e.closedLimit).pipe(AF(`list runs`))),a=k(`RunReader.closed`)(e=>t.closedRunSummaries(e.limit).pipe(AF(`list closed runs`))),o=k(`RunReader.closedSince`)(e=>t.closedRunSummariesSince(e).pipe(AF(`list runs closed since a time`))),s=k(`RunReader.revision`)(()=>t.revision().pipe(AF(`read projection revision`)));return{inspect:n,evidence:r,list:i,closed:a,closedSince:o,forItems:k(`RunReader.forItems`)(e=>t.itemRunSummaries(e).pipe(AF(`read item run histories`))),events:k(`RunReader.events`)(e=>t.runEvents(e).pipe(AF(`read the events of runs`))),revision:s,transcript:k(`RunReader.transcript`)(e=>t.transcript(e).pipe(AF(`read attempt transcript`))),attemptsByWorker:k(`RunReader.attemptsByWorker`)(()=>oB(e).attemptCountsByWorker().pipe(AF(`count attempts by worker`))),sightings:k(`RunReader.sightings`)(e=>t.loopItems.sightings(e).pipe(AF(`read loop sightings`)))}}),DB=class e extends Lr()(`@usine/engine/RunReader`){static layer=Yf(e,EB)},OB=class extends H(`@usine/orchestrator/InfraFailureView`)(`InfraFailure`,{message:M}){},kB=class extends H(`@usine/orchestrator/DefectFailureView`)(`DefectFailure`,{message:M}){},AB=class extends H(`@usine/orchestrator/AgentFailureView`)(`AgentFailure`,{message:M}){},jB=class extends H(`@usine/orchestrator/BlockedFailureView`)(`BlockedFailure`,{message:M}){},MB=class extends H(`@usine/orchestrator/QuestionFailureView`)(`QuestionFailure`,{question:M}){},NB=class extends H(`@usine/orchestrator/RunawayFailureView`)(`RunawayFailure`,{ceiling:sM}){},PB=class extends H(`@usine/orchestrator/ChildSessionBudgetFailureView`)(`ChildSessionBudgetFailure`,{maxChildren:Sj,attemptedChildren:Cj}){},FB=F([OB,kB,AB,jB,MB,NB,PB]),IB=class extends H(`@usine/orchestrator/SucceededAttemptView`)(`Succeeded`,{}){},LB=class extends H(`@usine/orchestrator/FailedAttemptView`)(`Failed`,{failure:FB}){},RB=class extends H(`@usine/orchestrator/CanceledAttemptView`)(`Canceled`,{}){},zB=F([IB,LB,RB]),BB=class extends H(`@usine/orchestrator/LocalWorkerAccess`)(`Local`,{}){},VB=class extends H(`@usine/orchestrator/SshWorkerAccess`)(`Ssh`,{destination:GA,port:I(KA)}){},HB=class extends H(`@usine/orchestrator/ProvisionedWorkerAccess`)(`Provisioned`,{provider:lj}){},UB=class extends H(`@usine/orchestrator/SandboxWorkerAccess`)(`Sandbox`,{}){},WB=F([BB,VB,HB,UB]),GB=class extends V(`@usine/orchestrator/AttemptView`)({id:TM,number:EM,worker:BA,workerAccess:I(WB),brain:PA,task:DM,agent:FA,operatorIntervened:cT,startedAt:M,outcome:I(zB),endedAt:I(M),salvage:I(_M),start:I(wM).pipe(TT(T(null))),reattachedAt:I(M).pipe(TT(T(null))),outOfMemory:I(MM).pipe(TT(T(null)))}){},KB=class extends H(`@usine/orchestrator/FailedTranscriptView`)(`Failed`,{failure:FB}){},qB=F([JM,YM,XM,KB,QM,$M,eN,nN,rN,tN,dN,fN,pN,mN]),JB=class extends V(`@usine/orchestrator/TranscriptEventView`)({sequence:ON,attemptId:TM,receivedAt:M,direction:KM,target:Qw(cN),operator:Qw(z),payload:qB}){},YB=class extends V(`@usine/orchestrator/TranscriptPageCursor`)({attemptId:TM,before:ON}){},XB=class extends H(`@usine/orchestrator/ColdTranscriptRequest`)(`ColdTranscriptRequest`,{}){},ZB=class extends H(`@usine/orchestrator/TailTranscriptRequest`)(`TailTranscriptRequest`,{after:ON}){},QB=class extends H(`@usine/orchestrator/EarlierTranscriptRequest`)(`EarlierTranscriptRequest`,{attemptId:TM,before:ON}){};F([XB,ZB,QB]);var $B=class extends NE(`@usine/orchestrator/TranscriptAttemptNotFoundError`)(`TranscriptAttemptNotFoundError`,{runId:kA,attemptId:TM}){},eV=e=>M.check(PT(/\S/u,{message:e})),tV=e=>NT(t=>new Set(t.map(t=>Hk(e(t)))).size===t.length,{message:`Expected unique repository names, ignoring case`}),nV=M.check(PT(/^\S(?:.*\S)?$/u,{message:`Expected a GitHub label name without surrounding whitespace`}),JT(50,{message:`Expected a GitHub label name of at most 50 characters`})).pipe(L(`GitHubLabelName`)),rV=e=>e.toLowerCase(),iV=M.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex GitHub label color without #`})).pipe(L(`GitHubLabelColor`)),aV=M.check(JT(100,{message:`Expected a GitHub label description of at most 100 characters`})),oV=class extends V(`@usine/config/DeclaredLabel`)({name:nV,color:xE(iV),description:xE(aV)}){},sV=eV(`Expected a non-blank lane name`).pipe(L(`LaneName`)),cV=bT([`issue-open`,`issue-closed`,`pr-open`,`pr-closed`,`pr-merged`]),lV=bT([`issue-closed`,`pr-closed`,`pr-merged`]),uV=Bw(lV),dV=e=>uV(e),fV=class extends V(`@usine/config/LabelLaneSource`)({label:nV}){},pV=F([fV,class extends V(`@usine/config/StateLaneSource`)({state:cV}){}]),mV=class extends V(`@usine/config/Lane`)({name:sV,sources:P(pV).check(qT())}){},hV=bT([`preflight`,`prepare`,`launch`,`cancel`,`cleanup`]),gV=bT([`machine`,`toolchain`,`memory`,`harness-login`,`credentials`,`gateway`,`container`,`provider`]),_V=class extends NE(`@usine/executor/ExecutorOperationError`)(`ExecutorOperationError`,{operation:hV,message:z,cause:eE()}){},vV=bT([`refused`,`unreachable`]),yV=class extends NE(`@usine/executor/CredentialUnavailableError`)(`CredentialUnavailableError`,{repository:Lk,reason:vV,message:z,cause:eE()}){},bV=class extends NE(`@usine/executor/WorkerCapabilityError`)(`WorkerCapabilityError`,{worker:BA,capability:gV,message:z,cause:eE()}){},xV=bT([`capacity`,`quota`,`refused`,`provider`,`unreachable`,`timeout`]);NE(`@usine/executor/MachineUnavailableError`)(`MachineUnavailableError`,{worker:BA,provider:lj,reason:xV,message:z}),F([_V,yV,bV]),V(`@usine/executor/CheckoutRequest`)({attemptId:TM,worker:BA,repository:Lk,loop:Kk,permissions:Xk,revision:Rk,payload:IE,task:DM,agent:LA,parentModel:B(jA),maxChildren:Sj,maxAttemptMinutes:B(R.check(VT(0))),maxAttemptTokens:B(R.check(VT(0))),parentEffort:NA,salvageRef:mM,resume:B(gM),reattach:cT.pipe(TT(T(!1))),botLogin:B(HA).pipe(TT(T(y()))),commitAuthor:WA});var SV=z.pipe(L(`WorktreePath`));V(`@usine/executor/AttemptWorkspace`)({worker:BA,spec:qM,worktree:SV});var CV=Mw(e=>gv(e)&&ee(yv(e)),{expected:`Redacted<string>`});V(`@usine/executor/WorkerCredential`)({value:CV,expiresAt:_E}),Lr()(`@usine/executor/CredentialProvider`),Lr()(`@usine/executor/Executor`);var wV=z.pipe(L(`MachineHold`)),TV=class extends V(`@usine/executor/MachineCheck`)({brains:P(PA),containerLimits:B(ij)}){};V(`@usine/executor/MachineGrant`)({hold:wV,id:uj,worker:BA,provider:lj,checked:B(TV)});var EV=bT([`creating`,`ready`,`deleting`]);V(`@usine/executor/MachineStatus`)({worker:BA,provider:lj,state:EV,id:B(uj),runId:B(kA),attemptId:B(TM),since:_E}),Lr()(`@usine/executor/WorkerMachines`);var DV=class extends V(`@usine/orchestrator/MachineView`)({worker:BA,provider:lj,state:EV,id:I(uj),runId:I(kA),attemptId:I(TM),since:M}){},OV=class extends V(`@usine/orchestrator/ProvisioningPauseView`)({reason:F([xV,nT(`check`)]),message:M,failures:R,failedAt:M,retryAt:M,blocked:cT}){},kV=class extends H(`@usine/orchestrator/HetznerProvisionerView`)(`hetzner`,{tokenEnv:M,serverType:dj,location:fj,image:pj,network:I(mj),firewall:I(mj).pipe(TT(T(null))),sshKey:mj,sshUser:_j,labels:mT(M,M),anthropicKeyEnv:I(M),openaiKeyEnv:I(M)}){},AV=class extends H(`@usine/orchestrator/BoatProvisionerView`)(`boat`,{tokenEnv:M,size:vj,anthropicKeyEnv:I(M),openaiKeyEnv:I(M)}){},jV=F([kV,AV]),MV=e=>new DV({worker:e.worker,provider:e.provider,state:e.state,id:w(e.id),runId:w(e.runId),attemptId:w(e.attemptId),since:q_(e.since)}),NV=e=>new OV({reason:e.reason,message:e.message,failures:e.failures,failedAt:q_(e.failedAt),retryAt:q_(e.retryAt),blocked:e.blocked}),PV=e=>vr(e.provisioner,{onNone:()=>null,onSome:e=>e.provider===`hetzner`?new kV({tokenEnv:e.tokenEnv,serverType:e.serverType,location:e.location,image:e.image,network:w(e.network),firewall:w(e.firewall),sshKey:e.sshKey,sshUser:e.sshUser,labels:e.labels,anthropicKeyEnv:w(e.apiKeys.anthropic),openaiKeyEnv:w(e.apiKeys.openai)}):new AV({tokenEnv:e.tokenEnv,size:e.size,anthropicKeyEnv:w(e.apiKeys.anthropic),openaiKeyEnv:w(e.apiKeys.openai)})}),FV=new Map([[`gpt-6-astra`,{input:10,cachedInput:1,cacheWrite:12.5,output:50}],[`gpt-6.1-sol`,{input:2,cachedInput:.1,cacheWrite:2.5,output:10}],[`gpt-6-sol`,{input:2,cachedInput:.2,cacheWrite:2.5,output:10}],[`gpt-6-luna`,{input:.1,cachedInput:.01,cacheWrite:.125,output:.5}],[`gpt-5.6-sol`,{input:4,cachedInput:.4,cacheWrite:5,output:20}],[`gpt-5.6-terra`,{input:2,cachedInput:.2,cacheWrite:2.5,output:12}],[`gpt-5.6-luna`,{input:.2,cachedInput:.02,cacheWrite:.25,output:1.2}],[`gpt-5.5`,{input:5,cachedInput:.5,output:30}],[`gpt-5.4`,{input:2.5,cachedInput:.25,output:15}],[`gpt-5.4-mini`,{input:.75,cachedInput:.075,output:4.5}],[`gpt-5.2`,{input:1.75,cachedInput:.175,output:14}]]),IV=(e,t)=>Dr(C(FV.get(e)),e=>Pj.make((t.input*e.input+t.cachedInput*e.cachedInput+t.cacheWrite*(e.cacheWrite??e.input)+t.output*e.output)/1e6)),LV=class extends V(`@usine/orchestrator/UsageCostView`)({usd:Pj,estimate:cT}){},RV=class extends V(`@usine/orchestrator/SessionUsageView`)({attemptId:TM,session:wj,pool:Rj,tokens:bj,cost:I(LV)}){},zV=class extends V(`@usine/orchestrator/PoolUsageView`)({pool:Rj,tokens:bj,cost:I(LV)}){},BV=class extends V(`@usine/orchestrator/RunUsageView`)({tokens:bj,pools:P(zV),sessions:P(RV)}){},VV=class extends V(`@usine/orchestrator/TaskPoolUsageView`)({pool:Rj,tokens:bj,cost:I(LV),unpriced:cT}){},HV=class extends V(`@usine/orchestrator/TaskUsageView`)({durationMillis:R.check(HT(0)),runningSince:P(M),unmeasured:R.check(HT(0)),tokens:bj,pools:P(VV),cost:I(LV)}){},UV=[`apiKeys`,`claudePlan`,`chatgptPlan`],WV=(e,t)=>vr(t,{onNone:()=>null,onSome:t=>new LV({usd:t,estimate:e!==`apiKeys`})}),GV=({session:e,costUsd:t,breakdown:n})=>S(t)||e.brain.harness!==`codex`?t:Or(n,t=>IV(e.brain.model,t)),KV=e=>{let t=new Map;for(let{attemptId:n,envelope:r}of e){let e=r.payload;if(e._tag!==`SessionEvent`||e.event._tag!==`SessionTokensUpdated`)continue;let i=`${n} ${e.event.session.id}`,a=t.get(i);a!==void 0&&a.report.totalTokens>=e.event.totalTokens||t.set(i,{attemptId:n,report:e.event})}let n=[...t.values()].map(e=>({...e,price:GV(e.report)})),r=n.map(({attemptId:e,report:t,price:n})=>{let r=Bj(t.session);return new RV({attemptId:e,session:t.session,pool:r,tokens:t.totalTokens,cost:WV(r,n)})}),i=new Set(n.flatMap(({report:e,price:t})=>x(t)&&e.session.brain.harness===`codex`&&S(e.breakdown)?[e.session.brain.model]:[])),a=UV.flatMap(e=>{let t=r.filter(t=>t.pool===e);if(t.length===0)return[];let n=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new zV({pool:e,tokens:bj.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:WV(e,n.length===t.length?b(Pj.make(n.reduce((e,t)=>e+t,0))):y())})]});return{view:new BV({tokens:bj.make(r.reduce((e,{tokens:t})=>e+t,0)),pools:a,sessions:r}),unknownModels:i}},qV=(e,t)=>{let n=0,r=0,i=[];for(let{attempts:t}of e)for(let{startedAt:e,endedAt:a,outcome:o}of t)o===null?i.push(e):a===null?r+=1:n+=Math.max(0,Date.parse(a)-Date.parse(e));let a=e.flatMap(({id:e})=>t.get(e)?.sessions??[]),o=UV.flatMap(e=>{let t=a.filter(t=>t.pool===e);if(t.length===0)return[];let n=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new VV({pool:e,tokens:bj.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:WV(e,n.length===0?y():b(Pj.make(n.reduce((e,t)=>e+t,0)))),unpriced:n.length<t.length})]}),s=o.flatMap(({cost:e})=>e===null?[]:[e]);return new HV({durationMillis:Math.round(n),runningSince:i,unmeasured:r,tokens:bj.make(a.reduce((e,{tokens:t})=>e+t,0)),pools:o,cost:s.length===0?null:new LV({usd:Pj.make(s.reduce((e,{usd:t})=>e+t,0)),estimate:s.some(({estimate:e})=>e)})})},JV=E(function*(){let e=yield*DB,t=yield*Rh(()=>new Map),n=yield*Rh(()=>new Set),r=k(`RunUsageReader.attemptReports`)(function*(n){let r=t.get(n.id);if(r!==void 0)return{reports:r,read:!1};let i=yield*e.transcript(new LN({attemptId:n.id}));return S(n.outcome)&&t.set(n.id,i),{reports:i,read:!0}});return{read:k(`RunUsageReader.read`)(function*(e){yield*O({runId:e.run.id});let t=yield*Nh(e.attempts,r,{concurrency:4}),{view:i,unknownModels:a}=KV(t.flatMap(({reports:e})=>e));for(let t of a)n.has(t)||(n.add(t),yield*$g(`The OpenAI price table has no rates for a Codex model, so its sessions have no cost`,{model:t,runId:e.run.id}));return yield*j(`Read Run usage`,{runId:e.run.id,sessions:i.sessions.length,tokens:i.tokens,attemptsRead:t.filter(({read:e})=>e).length,attemptsCached:t.filter(({read:e})=>!e).length}),i})}});(class e extends Lr()(`@usine/orchestrator/RunUsageReader`){static layer=Yf(e,JV)});var YV=bT(vA),XV=I(M),ZV=class extends V(`@usine/orchestrator/EditAndRetry`)({task:DM,agent:FA}){},QV=class extends V(`@usine/orchestrator/SessionIntervention`)({attemptId:TM,target:cN.pipe(DT(T({_tag:`Parent`}))),action:iN}){};NE(`@usine/orchestrator/RosterAgentNotFoundError`)(`RosterAgentNotFoundError`,{agent:FA,message:M}),NE(`@usine/orchestrator/LoopNotFoundError`)(`LoopNotFoundError`,{loop:Kk,message:M});var $V=class extends V(`@usine/orchestrator/ApprovalView`)({approvedAt:M,source:I(EN)}){},eH=class extends V(`@usine/orchestrator/RunView`)({id:kA,itemKey:bN,loop:Kk,repository:Lk,agent:FA,agentBrain:PA,state:YV,loopPaused:cT,openedAt:M,closedAt:I(M),task:M,attempts:P(GB),approval:I($V),runAgain:I(CN),resultMessage:XV,pullRequestUrl:XV,canApprove:cT,canRetry:cT,canResolveFailure:cT,canCancel:cT,canRunAgain:cT}){},tH=R.check(HT(0)),nH=R.check(HT(0)),rH=class extends V(`@usine/orchestrator/RunDurationView`)({endedMillis:tH,runningSince:I(M),unmeasured:nH}){},iH=class extends V(`@usine/orchestrator/UnconfirmedStopView`)({runId:kA,attemptNumber:EM,worker:BA}){},aH=class extends V(`@usine/orchestrator/RunDetailView`)({run:eH,agentDefinitionChanged:cT,eventDedupKey:M,eventPayload:IE,transcript:P(JB),sessionState:P(JB),earlierTranscript:P(YB),worker:I(BA).pipe(TT(T(null))),settledItemState:I(lV).pipe(TT(T(null))),duration:rH.pipe(TT(T(new rH({endedMillis:0,runningSince:null,unmeasured:0})))),usage:BV.pipe(TT(T(new BV({tokens:bj.make(0),pools:[],sessions:[]})))),unconfirmedStop:I(iH).pipe(TT(T(null))),machine:I(DV).pipe(TT(T(null)))}){},oH=500,sH=500,cH=e=>xk(e,{InfraFailure:({message:e})=>new OB({message:e}),DefectFailure:({message:e})=>new kB({message:e}),AgentFailure:({message:e})=>new AB({message:e}),BlockedFailure:({message:e})=>new jB({message:e}),QuestionFailure:({question:e})=>new MB({question:e}),RunawayFailure:({ceiling:e})=>new NB({ceiling:e}),ChildSessionBudgetFailure:({attemptedChildren:e,maxChildren:t})=>new PB({attemptedChildren:e,maxChildren:t})}),lH=e=>xk(e,{Succeeded:()=>new IB,Failed:({failure:e})=>new LB({failure:cH(e)}),Canceled:()=>new RB}),uH=e=>{switch(e.kind){case`local`:return new BB;case`ssh`:return vr(e.provisioner,{onSome:({provider:e})=>new HB({provider:e}),onNone:()=>new VB({destination:yr(e.destination,()=>GA.make(e.name)),port:w(e.port)})});case`exe.dev`:return new VB({destination:GA.make(`${e.name}.exe.xyz`),port:null});case`cloudflare`:return new UB}},dH=e=>new Map(e.map(e=>[e.name,uH(e)])),fH=(e,t)=>new GB({id:e.id,number:e.number,worker:e.worker,workerAccess:t.get(e.worker)??null,brain:e.brain,task:e.task,agent:e.agent,operatorIntervened:e.operatorIntervened,startedAt:q_(e.startedAt),outcome:vr(e.outcome,{onNone:()=>null,onSome:lH}),endedAt:vr(e.endedAt,{onNone:()=>null,onSome:q_}),salvage:w(e.salvage),start:w(e.start),reattachedAt:vr(e.reattachedAt,{onNone:()=>null,onSome:q_}),outOfMemory:w(e.outOfMemory)});k(`Operator.readUnrecordedEnds`)(function*(e,t){let n=yield*Nh(t.attempts.filter(e=>S(e.outcome)&&x(e.endedAt)),t=>e.transcript(new zN({attemptId:t.id,before:y(),limit:1})).pipe(tg(e=>[t.id,e.at(-1)?.receivedAt])),{concurrency:4});return new Map(n.flatMap(([e,t])=>t===void 0?[]:[[e,t]]))});var pH=k(`Operator.readRunningEvents`)(function*(e,t){let n=t.flatMap(({run:e})=>e.state._tag===`Running`?[e.id]:[]),r=yield*e.events(n);return yield*j(`Read the Events of the running Runs`,{running:n.length,events:r.length}),new Map(r.map(({runId:e,event:t})=>[e,t]))}),mH=(e,t,n)=>{let r=hA(e.run.state),i=w(e.step.result),a=i?.facts.find(e=>e._tag===`PullRequest`);return new eH({id:e.run.id,itemKey:e.itemKey,loop:e.run.loop,repository:e.repository,agent:e.agent.name,agentBrain:e.agent.brain,state:e.run.state._tag,loopPaused:t.has(e.run.loop),openedAt:q_(e.run.openedAt),closedAt:vr(e.closedAt,{onNone:()=>null,onSome:q_}),task:e.task,attempts:e.attempts.map(e=>fH(e,n)),approval:vr(e.approval,{onNone:()=>null,onSome:({approvedAt:e,source:t})=>new $V({approvedAt:q_(e),source:w(t)})}),runAgain:w(e.runAgain),resultMessage:i?.message??null,pullRequestUrl:a?.url.toString()??null,...r,canResolveFailure:r.canResolveFailure&&!Pr(e.resolvedFailureAttemptId,e.attempts.at(-1)?.id)})},hH=e=>xk(e,{Started:e=>e,SessionEvent:e=>e,Final:e=>e,Failed:({failure:e})=>new KB({failure:cH(e)}),Interrupted:e=>e,Steer:e=>e,Interrupt:e=>e,OperatorMessage:e=>e,Release:e=>e,Cancel:e=>e,InterventionApplied:e=>e,InterventionRejected:e=>e,WorkerUnresponsive:e=>e,WorkerResponsive:e=>e}),gH=e=>{let t={sequence:e.sequence,attemptId:e.attemptId,receivedAt:q_(e.receivedAt),direction:e.direction,payload:hH(e.envelope.payload)};return e.envelope._tag===`InboundEnvelope`&&`target`in e.envelope?new JB({...t,target:e.envelope.target,operator:e.envelope.operator}):new JB(t)},_H=e=>[...e].sort((e,t)=>e.sequence-t.sequence).map(gH),vH=k(`Operator.readTranscriptPage`)(function*(e,t,n){yield*O({attemptId:t,before:w(n)});let r=yield*e.transcript(new zN({attemptId:t,before:n,limit:501})),i=r.length>oH,a=i?r.slice(1):r,o=a[0];return yield*j(`Read operator transcript page`,{attemptId:t,before:w(n),returned:a.length,hasEarlier:i}),{events:_H(a),earlier:i&&o!==void 0?[new YB({attemptId:t,before:o.sequence})]:[]}});k(`Operator.readTranscript`)(function*(e,t,n){yield*O({runId:t.run.id,request:n._tag});let r=yield*xk(n,{ColdTranscriptRequest:()=>Nh(t.attempts,t=>vH(e,t.id,y()),{concurrency:4}).pipe(tg(e=>({events:e.flatMap(({events:e})=>e).sort((e,t)=>e.sequence-t.sequence),earlier:e.flatMap(({earlier:e})=>e)}))),TailTranscriptRequest:({after:n})=>Nh(t.attempts,t=>e.transcript(new RN({attemptId:t.id,after:n,limit:sH})),{concurrency:4}).pipe(tg(e=>({events:_H(e.flat()).slice(0,sH),earlier:[]}))),EarlierTranscriptRequest:({attemptId:n,before:r})=>t.attempts.some(e=>e.id===n)?vH(e,n,b(r)):new $B({runId:t.run.id,attemptId:n})});return yield*j(`Read operator transcript`,{runId:t.run.id,request:n._tag,events:r.events.length,earlier:r.earlier.length}),r});var yH=P(z),bH=class extends V(`@usine/engine/BoardMoveRecord`)({repository:Lk,itemKey:bN,at:_E,fromLane:z,toLane:z,added:yH.check(qT()),removed:yH}){},xH=Vw(P(N({repository:bH.fields.repository,itemKey:bH.fields.itemKey,at:vE,fromLane:bH.fields.fromLane,toLane:bH.fields.toLane,added:bH.fields.added,removed:bH.fields.removed}))),SH=Yw(bH.fields.added),CH=Yw(bH.fields.removed),wH=e=>t=>ug(t,t=>new rP({operation:e,cause:t})),TH=E(function*(){let e=yield*SN;return{record:k(`BoardMoves.record`)(function*(t){yield*O({repository:t.repository,itemKey:t.itemKey}),yield*e.insert(tB).values({repository:t.repository,itemKey:t.itemKey,movedAt:hF(t.at),fromLane:t.fromLane,toLane:t.toLane,addedJson:SH(t.added),removedJson:CH(t.removed)}).execute(),yield*j(`Recorded a Board move before writing its labels`,{repository:t.repository,itemKey:t.itemKey,at:hF(t.at),fromLane:t.fromLane,toLane:t.toLane})},wH(`record board move`)),onItem:k(`BoardMoves.onItem`)(function*(t,n){return yield*O({itemKey:t}),(yield*xH(yield*e.select({repository:tB.repository,itemKey:tB.itemKey,at:tB.movedAt,fromLane:tB.fromLane,toLane:tB.toLane,added:tB.addedJson,removed:tB.removedJson}).from(tB).where(aL(Y(tB.itemKey,t),lL(tB.movedAt,hF(n)))).orderBy(DL(tB.movedAt),DL(tB.moveId)).execute(),{onExcessProperty:`error`})).map(e=>new bH(e))},wH(`read board moves`))}}),EH=class e extends Lr()(`@usine/engine/BoardMoves`){static layer=Yf(e,TH)},DH=e=>e.pipe(ug(e=>e instanceof Rz?e:new rP({operation:`update cycle budget`,cause:e}))),OH=class e extends Lr()(`@usine/engine/CycleBudgets`){static layer=Yf(e,E(function*(){let e=yield*SN,t=lB(e);return{generation:k(`CycleBudgets.generation`)(function*(e){return yield*O({itemKey:e}),vr(yield*t.get(e).pipe(ug(e=>new rP({operation:`read cycle generation`,cause:e}))),{onNone:()=>JN.make(0),onSome:e=>e.generation})}),asks:k(`CycleBudgets.asks`)(()=>t.asks().pipe(ug(e=>new rP({operation:`read cycle asks`,cause:e})))),reset:k(`CycleBudgets.reset`)(function*(t,n){yield*O({askId:t,eventId:n.id}),yield*e.transaction(e=>E(function*(){if((yield*e.select().from(Gz).where(Y(Gz.askId,t)).execute())[0]?.eventId===n.id){yield*A(`Cycle budget reset answer already recorded`,{askId:t,eventId:n.id});return}let r=(yield*lB(e).asks()).find(({id:e})=>e===t);if(r===void 0)return yield*new Rz({askId:t});let i=yield*lB(e).get(r.itemKey);if(x(i))return yield*Gh(Error(`Open cycle ask has no budget`));let a=i.value.generation+1;yield*e.insert(Vz).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:mF(n.payload),receivedAt:hF(n.receivedAt)}).execute(),yield*e.insert(Gz).values({askId:t,eventId:n.id,itemKey:r.itemKey}).execute(),yield*e.update(Uz).set({generation:a,askJson:null,resetPending:!0}).where(Y(Uz.itemKey,r.itemKey)).execute(),yield*e.update(Wz).set({generation:a}).where(aL(Y(Wz.itemKey,r.itemKey),fL(Wz.runId,e.select({runId:Q.runId}).from(Q).where(fL(J`json_extract(${Q.stateJson}, '$._tag')`,[...yA]))))).execute(),yield*A(`Operator reset Item cycle budget`,{askId:t,eventId:n.id,itemKey:r.itemKey,repository:r.repository,generation:a,completedCycles:r.completedCycles,counts:r.counts})})).pipe(DH)}),close:k(`CycleBudgets.close`)(function*(t,n){yield*O({askId:t,reason:n});let r=hF(yield*z_);return yield*e.transaction(e=>E(function*(){let i=(yield*lB(e).asks()).find(({id:e})=>e===t);if(i===void 0)return yield*A(`Cycle-budget Ask is no longer open; nothing to close`,{askId:t,reason:n}),!1;let a=Yw($N)(i);return yield*e.insert(Kz).values({askId:t,itemKey:i.itemKey,reason:n,askJson:a,closedAt:r}).onConflictDoUpdate({target:Kz.askId,set:{reason:n,askJson:a,closedAt:r}}).execute(),yield*e.update(Uz).set({askJson:null}).where(Y(Uz.itemKey,i.itemKey)).execute(),yield*A(`Closed cycle-budget Ask without a reset`,{askId:t,reason:n,itemKey:i.itemKey,repository:i.repository,loop:i.loop,completedCycles:i.completedCycles,counts:i.counts}),!0})).pipe(ug(e=>new rP({operation:`close cycle ask`,cause:e})))}),pendingResets:k(`CycleBudgets.pendingResets`)(()=>t.pendingResets().pipe(tg(e=>e.map(e=>new Lz(e))),ug(e=>new rP({operation:`read pending cycle resets`,cause:e})))),acknowledgeReset:k(`CycleBudgets.acknowledgeReset`)(function*(t){yield*O({itemKey:t.itemKey,generation:t.generation}),yield*e.update(Uz).set({resetPending:!1}).where(aL(Y(Uz.itemKey,t.itemKey),Y(Uz.generation,t.generation))).execute().pipe(ug(e=>new rP({operation:`acknowledge cycle reset`,cause:e}))),yield*A(`Cycle reset trigger refresh recorded`,{itemKey:t.itemKey,generation:t.generation})})}}))},kH=new class extends V(`@usine/engine/RetryRequest`)({requestedBy:B(qj),amendment:B(kM)}){}({requestedBy:y(),amendment:y()});V(`@usine/engine/RunAgainRequest`)({step:eM,approval:Jk,cycleLimit:B(qN),permissions:Xk,context:kM,requestedBy:B(qj)});var AH=F([BP,KP]),jH=(e,t,n)=>{let r=Wk.make(JSON.stringify([`operator-run-again`,n.reopening,n.trigger]));return new IP({event:new Gk({id:Uk.make(r),dedupKey:r,payload:e.event.payload,receivedAt:n.receivedAt}),itemKey:e.itemKey,loop:e.run.loop,step:t.step,approval:t.approval,permissions:t.permissions,cycleLimit:t.cycleLimit,cycleGeneration:n.generation,repository:e.repository,revision:e.revision,task:t.context.task,agent:t.context.agent,parentModel:t.context.parentModel})},MH=class extends V(`@usine/engine/StepExecution`)({attempt:FM,event:Gk,run:AA,step:tM,repository:Lk,revision:Rk,task:DM,agent:LA,parentModel:B(jA),permissions:Xk,resume:B(gM),reattach:cT.pipe(TT(T(!1)))}){},NH=class extends Lr()(`@usine/engine/StepExecutor`){},PH=e=>({attemptWindows:k(`RunStoreQueries.attemptWindows`)(function*(t){yield*O({attemptId:t});let[n]=yield*e.select(bB).from($).where(Y($.attemptId,t)).execute().pipe(D(lF));if(n===void 0)return yield*Gh(Error(`No attempt ${t} recorded`));let r=LM(RF(n));if(x(r))return yield*j(`The Attempt ended before end times were recorded, so it has no window and none overlaps it`,{attemptId:t}),new HM({own:r,overlapping:[]});let i=e.select({itemKey:Z.itemKey}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(Y(Q.runId,n.runId));return new HM({own:r,overlapping:(yield*e.select(bB).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(aL(fL(Z.itemKey,i),Y($.agent,n.agent),rL($.attemptId,t))).orderBy($.startedAt).execute().pipe(D(lF))).flatMap(e=>jr(LM(RF(e)))).filter(e=>VM(r.value,e))})})}),FH=EM.make(3),IH=e=>C(e.attempts.at(-1)).pipe(Mr(e=>x(e.outcome))),LH=(e,t,n)=>{let r=new dM({failure:n});return UM({failure:n,number:t.number,maxAutoAttempts:FH})?{_tag:`RetryAttempt`,attempt:t,outcome:r}:{_tag:`RunFailed`,attempt:t,outcome:r,state:wA(e)}},RH=(e,t,n)=>{if(e.run.state._tag!==`Running`)return{_tag:`Unchanged`,reason:`RunNotRunning`};let r=IH(e);return x(r)?{_tag:`Unchanged`,reason:`NoOpenAttempt`}:r.value.id===t?Ei(n)?LH(e.run.state,r.value,n.failure):{_tag:`RunSucceeded`,attempt:r.value,outcome:new uM,state:CA(e.run.state),result:n.success}:{_tag:`Unchanged`,reason:`AttemptReplaced`}},zH=e=>xk(e,{Pushed:e=>b(e),PartlyPushed:({ref:e,commit:t})=>b(new gM({ref:e,commit:t})),Retained:()=>y(),Rejected:()=>y()}),BH=e=>na(e,e=>Or(e.salvage,zH)),VH=(e,t,n,r)=>{let i=e.run.state;if(!mA(i)&&i._tag!==`Running`)return{_tag:`RunClosed`,state:i};let a=y(),o=IH(e);if(i._tag===`Running`&&S(o)){if(Pr(n,o.value.id))return{_tag:`ReattachAttempt`,state:i,attempt:o.value,resume:BH(e.attempts)};let r=LH(i,o.value,t);if(r._tag===`RunFailed`)return r;a=b(r)}let s=S(a)?new SM:yr(r,()=>e.attempts.length===0?new vM:new xM);return{_tag:`StartAttempt`,state:i._tag===`Running`?i:SA(i),number:EM.make((e.attempts.at(-1)?.number??0)+1),start:s,interrupted:a,resume:BH(e.attempts)}},HH=e=>e.run.state._tag===`Canceled`?{_tag:`AlreadyClosed`}:fA(e.run.state)?{_tag:`Canceled`,state:EA(e.run.state),attempt:e.run.state._tag===`Running`?Dr(IH(e),e=>({id:e.id,outcome:new fM})):y()}:{_tag:`CancelRejected`},UH=e=>{let t=e.run.state;return t._tag===`Failed`?{_tag:`Resume`,state:TA(t)}:t._tag===`Running`&&x(IH(e))?{_tag:`ResumePending`}:{_tag:`RetryRejected`}},WH=(e,t)=>vr(e,{onNone:()=>!1,onSome:e=>!Pr(e,t)}),GH=(e,t)=>e._tag===`Owned`?e.run.state._tag===`Canceled`&&t?{_tag:`ReopenEvent`}:{_tag:`JoinRun`,run:e.run}:e.reason===`revoked`&&t?{_tag:`ReopenEvent`}:{_tag:`StayIgnored`,reason:e.reason},KH=e=>{if(e._tag!==`RunFailed`)return y();switch(e.outcome.failure._tag){case`QuestionFailure`:return b(`question`);case`BlockedFailure`:return b(`blocker`);default:return y()}},qH=(e,t)=>vr(e.suppressedEventId,{onNone:()=>({_tag:`SuppressFrom`}),onSome:e=>e===t?{_tag:`Suppress`}:{_tag:`Lift`}}),JH=(e,t)=>{if(x(e))return{_tag:`OpenRun`};let n=e.value;return n.state._tag===`Running`?{_tag:`QueueEvent`}:pA(n.state)?{_tag:`SupersedeRun`,runId:n.id,state:DA(n.state,t)}:{_tag:`OpenRun`}},YH=B(kA).pipe(TT(T(y()))),XH=class extends V(`@usine/engine/internal/Claim`)({result:qP,openedRun:YH,supersededRun:YH}){},ZH=class extends H(`@usine/engine/internal/AttemptStarted`)(`AttemptStarted`,{execution:MH}){},QH=class extends H(`@usine/engine/internal/AttemptRecoveryFailed`)(`AttemptRecoveryFailed`,{}){},$H=class extends H(`@usine/engine/internal/RunClosed`)(`RunClosed`,{}){},eU=E(function*(){let e=yield*SN,t=yield*YO,n=TB(e),r=k(`RunStore.admitRun`)(function*(e,t,n){let r=yield*e.cycles.admit(t);return S(r)?new KP({eventId:t.event.id,ask:r.value}):(yield*e.createRun(t,t.event.id,n),yield*e.cycles.reserve(t,n),new BP({eventId:t.event.id,runId:n}))}),i=k(`RunStore.openRun`)(function*(e,t,n,i=y()){let a=yield*r(e,t,n);return new XH({result:a,openedRun:a._tag===`Claimed`?b(n):y(),supersededRun:i})}),a=e=>RP(e).pipe(Og(YO,t)),o=k(`RunStore.settlementOf`)(function*(e,t){let n=(yield*e.runForEvent(t))[0];if(n!==void 0){let t=(yield*e.snapshot(n.runId)).run;return b({_tag:`Owned`,run:t})}let r=(yield*e.ignoredEvent(t))[0];return r===void 0?y():b({_tag:`Ignored`,reason:r.reason})}),s=k(`RunStore.claimEvent`)(function*(e,t,n){if(!(yield*e.cycles.isCurrentEvent(t)))return new XH({result:new WP({eventId:t.event.id,reason:`superseded`})});let r=yield*e.loopItems.suppression(t.loop,t.itemKey);if(S(r)){let n=qH(r.value,t.event.id),i={eventId:t.event.id,suppressedBy:r.value.runId,loop:t.loop,itemKey:t.itemKey};switch(n._tag){case`SuppressFrom`:return yield*e.loopItems.suppressFrom(t.loop,t.itemKey,t.event.id),yield*A(`First Item state after the Agent stopped for the operator; it waits for the operator`,i),new XH({result:new GP({eventId:t.event.id,runId:r.value.runId})});case`Suppress`:return yield*A(`Item unchanged since the Agent stopped for the operator; no Run opens`,i),new XH({result:new GP({eventId:t.event.id,runId:r.value.runId})});case`Lift`:yield*e.loopItems.lift(t.loop,t.itemKey),yield*A(`Item changed after the Agent stopped for the operator; the Loop acts on its new state`,i)}}let a=(yield*e.blockingRun(t.loop,t.itemKey))[0],o=JH(a===void 0?y():b((yield*e.snapshot(a.runId)).run),t.event.id);switch(yield*A(`Event claim decided`,{eventId:t.event.id,decision:o._tag}),o._tag){case`QueueEvent`:return new XH({result:new VP({eventId:t.event.id})});case`SupersedeRun`:return yield*e.updateState(o.runId,o.state),yield*i(e,t,n,b(o.runId));case`OpenRun`:return yield*i(e,t,n)}}),c=k(`RunStore.recordAndClaim`)(function*(t,n){return yield*O({eventId:t.event.id,runId:n,loop:t.loop,itemKey:t.itemKey}),yield*e.transaction(e=>E(function*(){let r=TB(e),i=yield*r.recordTriggerEvent(t),c=yield*r.loopItems.sighted(i.loop,i.itemKey,i.event.id),l=yr(yield*r.newestReopening(i.event.id),()=>({submission:i,reopening:0})),u=l.submission.event.id,d=yield*o(r,u);if(x(d))return yield*s(r,l.submission,l.reopening===0?n:yield*a(l.submission));let f=GH(d.value,WH(c,i.event.id));switch(f._tag){case`JoinRun`:return yield*A(`Event joined its existing Run`,{eventId:u,runId:f.run.id,state:f.run.state._tag}),new XH({result:new BP({eventId:u,runId:f.run.id})});case`StayIgnored`:return yield*A(`Event remains ignored`,{eventId:u,reason:f.reason}),new XH({result:new WP({eventId:u,reason:f.reason})});case`ReopenEvent`:{let e=l.reopening+1,n=yield*r.recordTriggerEvent(zP(t,i.event.dedupKey,e),b({eventId:i.event.id,reopening:e}));return yield*A(`The Item came back to the state of an Event no Attempt worked on; it opens again`,{eventId:u,settled:d.value._tag,reopenedEventId:n.event.id,reopening:e}),yield*s(r,n,yield*a(n))}}}))},AF(`submit event`)),l=k(`RunStore.parkForApproval`)(function*(t){return yield*O({runId:t}),yield*e.transaction(e=>E(function*(){let n=TB(e),r=yield*n.snapshot(t);if(r.run.state._tag!==`Pending`)return r.run.state;let i=bA(r.run.state);return yield*n.updateState(t,i),i}))},AF(`park run for approval`)),u=k(`RunStore.applyFinish`)(function*(e,t,n){if(yield*O({runId:t}),n._tag===`Unchanged`){yield*A(`Attempt completion ignored`,{runId:t,reason:n.reason});return}let{attempt:r,outcome:i}=n;yield*O({attemptId:r.id});let a={runId:t,attemptId:r.id,number:r.number,decision:n._tag};yield*A(`Attempt completion decided`,xk(i,{Failed:({failure:e})=>({...a,failure:e._tag}),Succeeded:()=>a}));let o=yield*z_;yield*e.closeAttempt(r.id,i,o),n._tag!==`RetryAttempt`&&(n._tag===`RunSucceeded`&&(yield*e.updateStepResult(t,r.stepName,n.result)),yield*e.updateState(t,n.state,o))}),d=k(`RunStore.suppressForOperator`)(function*(e,t,n){let r=t.run.id,i=Dr(yield*e.nextQueued(r),({submission:e})=>e.event.id),a={runId:r,loop:t.run.loop,itemKey:t.itemKey,stop:n};(yield*e.loopItems.startSuppression(t.run.loop,t.itemKey,r,t.event.id,i))?yield*A(`Agent stopped for the operator; its Loop suppresses the Item`,{...a,suppressedEventId:yr(i,()=>`none yet`)}):yield*A(`Agent stopped for the operator, but nothing is suppressed; the Loop last saw the Item not matching`,a)}),f=(e,{attempt:t,state:n,resume:r,reattach:i})=>new MH({attempt:t,event:e.event,run:new AA({id:e.run.id,eventId:e.run.eventId,loop:e.run.loop,state:n,openedAt:e.run.openedAt}),step:e.step,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel,permissions:e.permissions,resume:r,reattach:i}),p=k(`RunStore.beginAttempt`)(function*(t,n,r){return yield*O({runId:t,worker:n}),yield*e.transaction(e=>E(function*(){let i=TB(e),a=yield*i.snapshot(t),o=new nM({message:`The orchestrator stopped during the attempt`,cause:Error(`attempt interrupted by orchestrator restart`)}),s=yield*i.nextStart(t),c=VH(a,o,r,s);if(c._tag===`RunClosed`)return yield*A(`Attempt start skipped`,{runId:t,state:c.state._tag}),new $H;if(c._tag===`RunFailed`)return yield*u(i,t,c),new QH;if(c._tag===`ReattachAttempt`){let e=yield*z_,r=new FM({...c.attempt,reattachedAt:b(e)});return yield*i.recordReattach(r.id,e),yield*O({attemptId:r.id}),yield*A(`Attempt reattached after an orchestrator restart`,{runId:t,attemptId:r.id,number:r.number,worker:r.worker}),r.worker!==n&&(yield*e_(`Reattached Attempt keeps its own Worker, not the reserved one`,{runId:t,attemptId:r.id,worker:r.worker,reservedWorker:n})),new ZH({execution:f(a,{attempt:r,state:c.state,resume:c.resume,reattach:!0})})}S(c.interrupted)&&(yield*u(i,t,c.interrupted.value)),a.run.state._tag!==c.state._tag&&(yield*i.updateState(t,c.state));let l=TM.make(`${t}/${a.step.name}/${c.number}`),d=yield*z_,p=new FM({id:l,runId:t,stepName:a.step.name,worker:n,number:c.number,brain:a.agent.brain,task:a.task,agent:a.agent.name,operatorIntervened:!1,parentModel:a.parentModel,startedAt:d,outcome:y(),endedAt:y(),salvage:y(),start:b(c.start),reattachedAt:y()});return yield*i.addAttempt(p),S(s)&&(yield*i.setNextStart(t,y())),yield*A(`Attempt started`,{runId:t,attemptId:l,number:c.number,worker:n,start:c.start._tag,resumesFrom:Dr(c.resume,({ref:e})=>e)}),new ZH({execution:f(a,{attempt:p,state:c.state,resume:c.resume,reattach:!1})})}))},AF(`begin attempt`)),m=k(`RunStore.recordSalvage`)(function*(t,n){yield*O({attemptId:t,salvage:n._tag}),yield*e.transaction(e=>TB(e).recordSalvage(t,n)),yield*A(`Attempt salvage recorded`,xk(n,{Pushed:({ref:e,commit:n})=>({attemptId:t,ref:e,commit:n}),PartlyPushed:({ref:e,commit:n,path:r})=>({attemptId:t,ref:e,commit:n,path:r}),Retained:({path:e,commit:n})=>({attemptId:t,path:e,commit:n}),Rejected:({path:e,commit:n})=>({attemptId:t,path:e,commit:n})}))},AF(`record attempt salvage`)),h=k(`RunStore.recordComments`)(function*(t,n){yield*O({attemptId:t,comments:n.length}),yield*e.transaction(e=>TB(e).recordComments(t,n)),yield*A(`Recorded the comments an Attempt posted before it ended without success`,{attemptId:t,comments:n.map(({kind:e,url:t})=>`${e} ${t.href}`)})},AF(`record attempt comments`)),g=k(`RunStore.recordOutOfMemory`)(function*(t,n){yield*O({attemptId:t,container:n.container,kills:n.kills});let r=yield*e.transaction(e=>TB(e).recordOutOfMemory(t,n));yield*A(`Recorded the processes the kernel killed in the Attempt's container`,{attemptId:t,container:n.container,kills:n.kills,memoryMib:n.memoryMib,attemptKills:r.kills})},AF(`record attempt out-of-memory kills`)),_=k(`RunStore.attemptWindows`)(function*(t){yield*O({attemptId:t});let n=yield*PH(e).attemptWindows(t);return yield*j(`Read the Attempt's window and the Attempts of the same Agent that overlap it on its Item`,{attemptId:t,recorded:S(n.own),ended:Fr(n.own,({endedAt:e})=>S(e)),overlapping:n.overlapping.map(e=>e.attemptId)}),n},AF(`read attempt windows`)),v=k(`RunStore.discardLeftovers`)(function*(t){yield*O({worker:t});let n=yield*z_;return yield*e.transaction(e=>oB(e).discardLeftovers(t,n))},AF(`discard attempt leftovers`)),ee=k(`RunStore.openAttempts`)(function*(t){return yield*O({worker:t}),yield*oB(e).openAttempts(t)},AF(`count open attempts`)),te=k(`RunStore.finishAttempt`)(function*(t,n){return yield*O({runId:t.runId,attemptId:t.id}),yield*e.transaction(e=>E(function*(){let r=TB(e),i=yield*r.snapshot(t.runId),a=RH(i,t.id,n);yield*u(r,t.runId,a);let o=KH(a);return S(o)&&(yield*d(r,i,o.value)),a}))},AF(`finish attempt`)),ne=k(`RunStore.resolveFailure`)(function*(t,n,r){return yield*O({runId:t,attemptId:n}),yield*e.transaction(e=>E(function*(){let i=TB(e),a=yield*i.snapshot(t),o=a.attempts.at(-1);if(!hA(a.run.state).canResolveFailure||o?.id!==n)return yield*A(`Failure resolution rejected; Run or Attempt changed`,{runId:t,attemptId:n,state:a.run.state._tag,latestAttemptId:o?.id}),yield*new tP({runId:t,operation:`resolveFailure`,state:a.run.state._tag});if(Pr(a.resolvedFailureAttemptId,n))return yield*A(`Run failure already resolved`,{runId:t,attemptId:n}),!1;let s=new AM({resolvedAt:yield*z_,operator:r});yield*i.resolveFailure(t,n,s);let c=yield*i.loopItems.liftRun(t);return yield*A(`Run failure resolved`,{runId:t,attemptId:n,liftedSuppression:c,resolvedAt:q_(s.resolvedAt),operator:w(r)}),c}))},AF(`resolve run failure`)),re=k(`RunStore.approve`)(function*(t,n,r){return yield*O({runId:t,eventId:n.id,channel:r.channel}),yield*e.transaction(e=>E(function*(){let i=TB(e);if(yield*i.approvalExists(t))return!1;let a=yield*i.snapshot(t);return a.run.state._tag===`Waiting`?(yield*i.recordApproval(t,n,r),yield*i.updateState(t,xA(a.run.state)),!0):yield*new tP({runId:t,operation:`approve`,state:a.run.state._tag})}))},AF(`approve run`)),ie=k(`RunStore.retry`)(function*(t,n=kH){let{amendment:r,requestedBy:i}=n;return yield*O({runId:t}),yield*e.transaction(e=>E(function*(){let n=TB(e),a=yield*n.snapshot(t),o=UH(a);if(yield*A(`Operator retry decided`,{runId:t,state:a.run.state._tag,decision:o._tag}),o._tag===`Resume`){let e=(yield*n.blockingRun(a.run.loop,a.itemKey))[0];return e===void 0?(S(r)&&(yield*n.amend(t,r.value),yield*A(`Run effective task and Agent amended`,{runId:t,agent:r.value.agent.name})),(yield*n.loopItems.liftRun(t))&&(yield*A(`Operator retry lifts the suppression of the Item`,{runId:t})),yield*n.setNextStart(t,b(S(r)?new bM({operator:i}):new yM({operator:i}))),yield*n.updateState(t,o.state),!0):(yield*A(`Operator retry rejected; another Run is open on the Item`,{runId:t,openRunId:e.runId,loop:a.run.loop,itemKey:a.itemKey}),yield*new nP({runId:t,openRunId:e.runId,message:`Cannot retry run ${t}: run ${e.runId} of loop "${a.run.loop}" is open on the same item. Cancel run ${e.runId}, or try again after it closes.`}))}return o._tag===`ResumePending`&&x(r)?!1:yield*new tP({runId:t,operation:`retry`,state:a.run.state._tag})}))},AF(`retry run`)),ae=k(`RunStore.runAgain`)(function*(t,n){yield*O({runId:t,agent:n.context.agent.name});let i=yield*z_;return yield*e.transaction(e=>E(function*(){let o=TB(e),s=yield*o.snapshot(t),{loop:c}=s.run,{itemKey:l}=s;if(!hA(s.run.state).canRunAgain)return yield*A(`Run again rejected; only a succeeded or canceled Run runs again`,{runId:t,state:s.run.state._tag}),yield*new tP({runId:t,operation:`runAgain`,state:s.run.state._tag});let u=(yield*o.blockingRun(c,l))[0];if(u!==void 0)return yield*A(`Run again rejected; another Run is open on the Item`,{runId:t,openRunId:u.runId,loop:c,itemKey:l}),yield*new nP({runId:t,openRunId:u.runId,message:`Run ${t} cannot run again: run ${u.runId} of loop "${c}" is open on the same item. Cancel run ${u.runId}, or try again after it closes.`});let d=yr(yield*o.reopenedEvent(s.event.id),()=>({eventId:s.event.id,dedupKey:s.event.dedupKey})),f=vr(yield*o.newestReopening(d.eventId),{onNone:()=>1,onSome:e=>e.reopening+1}),p=vr(yield*o.cycles.get(l),{onNone:()=>JN.make(0),onSome:e=>e.generation}),m=jH(s,n,{trigger:d.dedupKey,reopening:f,generation:p,receivedAt:i}),h=yield*o.recordTriggerEvent(m,b({eventId:d.eventId,reopening:f}));yield*o.recordRunAgain(h.event.id,new CN({from:t,requestedBy:n.requestedBy}));let g=yield*r(o,h,yield*a(h));return yield*A(`Run again decided`,xk(g,{Claimed:({runId:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`OpenRun`,openedRunId:e,requestedBy:yr(n.requestedBy,()=>`none`)}),CycleBlocked:({ask:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`CycleBlocked`,askId:e.id,requestedBy:yr(n.requestedBy,()=>`none`)})})),g}))},AF(`run again`)),oe=k(`RunStore.cancel`)(function*(t){return yield*O({runId:t}),yield*e.transaction(e=>E(function*(){let n=TB(e),r=yield*n.snapshot(t),i=HH(r);if(yield*A(`Operator cancellation decided`,{runId:t,state:r.run.state._tag,decision:i._tag}),i._tag===`AlreadyClosed`)return i;if(i._tag===`CancelRejected`)return yield*new tP({runId:t,operation:`cancel`,state:r.run.state._tag});let a=yield*z_;if(S(i.attempt)){let{id:e,outcome:t}=i.attempt.value;yield*n.closeAttempt(e,t,a)}return yield*n.updateState(t,i.state,a),{_tag:`Canceled`,openAttempt:Dr(i.attempt,({id:e})=>e),loop:r.run.loop,itemKey:r.itemKey}}))},AF(`cancel run`)),se=k(`RunStore.revoke`)(function*(t,n){return yield*e.transaction(e=>E(function*(){let r=TB(e);yield*r.loopItems.unmatched(t,n);let i=yield*r.revokeUnstarted(t,n);for(let e of i){let t=yield*r.snapshot(e.runId);pA(t.run.state)&&(yield*r.updateState(e.runId,OA(t.run.state)))}return i.map(e=>e.runId)}))},AF(`revoke run`)),ce=k(`RunStore.revokeQueued`)(function*(e){let{loop:t,itemKey:r,event:i}=e.submission;return yield*O({loop:t,itemKey:r,eventId:i.id}),yield*n.revokeQueued(t,r,e.eventIds)},AF(`revoke queued events`)),le=k(`RunStore.claimQueued`)(function*(t,n){return yield*e.transaction(e=>E(function*(){let r=TB(e),a=yield*r.runForEvent(t.event.id);return a[0]===void 0?(yield*r.ignoredEvent(t.event.id)).length>0||(yield*r.blockingRun(t.loop,t.itemKey)).length>0||S(yield*r.loopItems.suppression(t.loop,t.itemKey))||!(yield*r.cycles.isCurrentEvent(t))?y():(yield*i(r,t,n)).openedRun:(yield*A(`Queued Event already opened its Run`,{eventId:t.event.id,runId:a[0].runId}),y())}))},AF(`claim queued event`)),ue=k(`RunStore.appendTranscript`)(function*(t,n){let r=yield*z_;yield*e.transaction(e=>E(function*(){let i=TB(e);t===`outbound`&&n.payload._tag===`Started`&&(yield*i.updateAttemptParentModel(n.attemptId,n.payload.parentModel)),t===`outbound`&&n.payload._tag===`InterventionApplied`&&(yield*i.markIntervened(n.attemptId)),(yield*i.appendTranscript(t,n,r))||(yield*j(`Transcript envelope already recorded; keeping the first copy`,{attemptId:n.attemptId,direction:t,sequence:n.sequence}))}))},AF(`append attempt transcript`)),de=k(`RunStore.transcript`)(function*(e){return yield*n.transcript(e)},AF(`read attempt transcript`));return{approve:re,appendTranscript:ue,beginAttempt:p,cancel:oe,claimQueued:le,finishAttempt:te,nextQueued:e=>n.nextQueued(e).pipe(AF(`find queued event`)),parkForApproval:l,pendingContinuations:n.pendingContinuations().pipe(AF(`list pending continuations`)),runIdsToDrive:n.runIdsToDrive().pipe(AF(`list the runs to drive`)),recordAndClaim:c,salvageCandidates:n.salvageCandidates().pipe(AF(`list salvage candidates`)),salvageCandidate:e=>n.salvageCandidate(e).pipe(AF(`read a salvage candidate`)),recordSalvage:m,recordComments:h,recordOutOfMemory:g,attemptWindows:_,discardLeftovers:v,openAttempts:ee,submission:e=>n.eventRouteByRun(e).pipe(D(t=>t[0]===void 0?Hh(new eP({runId:e})):T(NF(t[0]))),AF(`read run submission`)),resolveFailure:ne,retry:ie,revoke:se,revokeQueued:ce,runAgain:ae,snapshot:e=>n.snapshot(e).pipe(AF(`read run`)),transcript:de}}),tU=class e extends Lr()(`@usine/engine/internal/RunStore`){static layer=Yf(e,eU)},nU=z.pipe(L(`ItemProjectionSource`)),rU=z.pipe(L(`ItemContentHash`)),iU=class extends V(`@usine/engine/ItemProjection`)({itemKey:bN,repository:Lk,source:nU,number:xN,contentHash:rU,payload:LE,goneAt:yE(vE).pipe(DT(T(null)),TT(T(y())))}){},aU=N({itemKey:iU.fields.itemKey,repository:Lk,source:nU,number:xN,contentHash:rU,payload:LE,goneAt:iU.fields.goneAt}),oU=Vw(P(aU)),sU=Vw(P(xN)),cU=Yw(LE),lU=Yw(aU.fields.goneAt),uU=e=>t=>ug(t,t=>new rP({operation:e,cause:t})),dU={itemKey:$z.itemKey,repository:$z.repository,source:$z.source,number:$z.itemNumber,contentHash:$z.contentHash,payload:$z.payloadJson,goneAt:$z.goneAt},fU=E(function*(){let e=yield*SN;return{get:k(`ItemProjectionReader.get`)(function*(t){yield*O({itemKey:t});let[n]=yield*oU(yield*e.select(dU).from($z).where(Y($z.itemKey,t)).execute(),{onExcessProperty:`error`});return Dr(C(n),e=>new iU(e))},uU(`read item projection`)),list:k(`ItemProjectionReader.list`)(function*(t,n){return yield*O({repository:t,limit:n.limit}),(yield*oU(yield*e.select(dU).from($z).where(Y($z.repository,t)).orderBy(OL($z.itemNumber)).limit(n.limit).execute(),{onExcessProperty:`error`})).map(e=>new iU(e))},uU(`list item projections`)),openIssues:k(`ItemProjectionReader.openIssues`)(function*(t){return yield*O({repository:t}),yield*sU((yield*e.select({number:$z.itemNumber}).from($z).where(aL(Y($z.repository,t),Y($z.source,`issue`),mL($z.goneAt),J`json_extract(${$z.payloadJson}, '$.state') = 'OPEN'`)).orderBy(DL($z.itemNumber)).execute()).map(({number:e})=>e))},uU(`list open issue projections`))}}),pU=E(function*(){let e=yield*SN;return{upsert:k(`ItemProjectionWriter.upsert`)(function*(t){yield*O({repository:t.repository,item:t.number,itemKey:t.itemKey});let n=lU(t.goneAt);return(yield*e.insert($z).values({itemKey:t.itemKey,repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:cU(t.payload),goneAt:n}).onConflictDoUpdate({target:$z.itemKey,set:{repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:cU(t.payload),goneAt:n},setWhere:J`${$z.contentHash} != ${t.contentHash} OR ${$z.goneAt} IS NOT ${n}`}).returning({itemKey:$z.itemKey}).execute()).length===0?(yield*j(`Item projection already matched the observed snapshot`,{repository:t.repository,item:t.number,contentHash:t.contentHash}),!1):(yield*j(`Item projection updated from trigger polling`,{repository:t.repository,item:t.number,source:t.source,contentHash:t.contentHash}),!0)},uU(`write item projection`)),markGone:k(`ItemProjectionWriter.markGone`)(function*(t,n){return yield*O({itemKey:t}),(yield*e.update($z).set({goneAt:lU(b(n))}).where(aL(Y($z.itemKey,t),mL($z.goneAt))).returning({itemKey:$z.itemKey}).execute()).length===0?(yield*j(`Item projection already gone or never stored`,{itemKey:t}),!1):(yield*A(`Item projection marked gone from GitHub`,{itemKey:t,goneAt:q_(n)}),!0)},uU(`mark item projection gone`))}}),mU=class e extends Lr()(`@usine/engine/ItemProjectionReader`){static layer=Yf(e,fU)},hU=class e extends Lr()(`@usine/engine/ItemProjectionWriter`){static layer=Yf(e,pU)},gU=M.check(PT(/\S/u,{message:`Expected a non-blank repository label`})),_U=M.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})),vU=class extends V(`@usine/engine/RepositoryLabel`)({name:gU,color:yE(_U),description:yE(M)}){},yU=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),bU=P(vU).check(yU),xU=class extends V(`@usine/engine/RepositoryLabelProjection`)({repository:Lk,labels:bU}){},SU=P(M),CU=Bw(SU),wU=N({repository:Lk,labels:F([xU.fields.labels,SU])}),TU=e=>CU(e)?e.map(e=>new vU({name:e,color:y(),description:y()})):e,EU=Vw(P(wU)),DU=Yw(xU.fields.labels),OU=e=>t=>ug(t,t=>new rP({operation:e,cause:t})),kU=E(function*(){let e=yield*SN;return{get:k(`RepositoryLabelProjectionReader.get`)(function*(t){let n=(yield*EU(yield*e.select({repository:eB.repository,labels:eB.labelsJson}).from(eB).where(Y(eB.repository,t)).limit(1).execute(),{onExcessProperty:`error`}))[0];return n===void 0?y():b(new xU({repository:n.repository,labels:TU(n.labels)}))},OU(`read repository label projection`))}}),AU=E(function*(){let e=yield*SN;return{replace:k(`RepositoryLabelProjectionWriter.replace`)(function*(t){yield*O({repository:t.repository});let n=DU(t.labels);return(yield*e.insert(eB).values({repository:t.repository,labelsJson:n}).onConflictDoUpdate({target:eB.repository,set:{labelsJson:n},setWhere:rL(eB.labelsJson,n)}).returning({repository:eB.repository}).execute()).length===0?(yield*j(`Repository label projection already matched GitHub`,{repository:t.repository,labels:t.labels.length}),!1):(yield*j(`Repository label projection updated from trigger polling`,{repository:t.repository,labels:t.labels.length}),!0)},OU(`write repository label projection`))}}),jU=class e extends Lr()(`@usine/engine/RepositoryLabelProjectionReader`){static layer=Yf(e,kU)},MU=class e extends Lr()(`@usine/engine/RepositoryLabelProjectionWriter`){static layer=Yf(e,AU)},NU=class extends Lr()(`@usine/engine/TriggerCondition`){},PU=z.pipe(L(`CursorKey`)),FU=Vw(P(N({value:IE}))),IU=e=>t=>ug(t,t=>new rP({operation:e,cause:t})),LU=class e extends Lr()(`@usine/engine/CursorStore`){static layer=Yf(e,E(function*(){let e=yield*SN;return{read:k(`CursorStore.read`)(function*(t,n){let r=C((yield*E(function*(){return yield*FU(yield*e.select({value:Qz.valueJson}).from(Qz).where(Y(Qz.cursorKey,t)).limit(1).execute())}).pipe(IU(`read runtime cursor`)))[0]);return x(r)?y():yield*Vw(n)(r.value.value,{onExcessProperty:`error`}).pipe(tg(b),ag(e=>$g(`Stored cursor no longer decodes; treating it as absent`,{key:t,detail:e.message}).pipe(ng(y()))))}),write:k(`CursorStore.write`)(function*(t,n,r){let i=yield*qw(n)(r).pipe(IU(`encode runtime cursor`));yield*e.insert(Qz).values({cursorKey:t,valueJson:i}).onConflictDoUpdate({target:Qz.cursorKey,set:{valueJson:i}}).execute().pipe(ig,IU(`write runtime cursor`))})}}))},RU=class extends V(`@usine/engine/LoopRuntimeState`)({loop:Kk,paused:cT}){},zU=e=>t=>t.pipe(ug(t=>new rP({operation:e,cause:t}))),BU=E(function*(){let e=yield*SN,t=k(`LoopControl.stateFor`)(function*(t){yield*O({loop:t});let n=(yield*e.select({loop:nB.loopName,paused:nB.paused}).from(nB).where(Y(nB.loopName,t)).limit(1).execute())[0];return n===void 0?new RU({loop:t,paused:!1}):new RU(n)},zU(`read loop runtime state`)),n=k(`LoopControl.states`)(function*(){return(yield*e.select({loop:nB.loopName,paused:nB.paused}).from(nB).orderBy(DL(nB.loopName)).execute()).map(e=>new RU(e))},zU(`list loop runtime states`)),r=k(`LoopControl.write`)(function*(n){yield*O({loop:n.loop});let r=yield*t(n.loop);return r.paused===n.paused?(yield*j(`Loop runtime state was already set`,{loop:n.loop,paused:n.paused}),r):(yield*e.insert(nB).values({loopName:n.loop,paused:n.paused}).onConflictDoUpdate({target:nB.loopName,set:{paused:n.paused}}).execute().pipe(zU(`write loop runtime state`)),yield*A(n.paused?`Loop paused`:`Loop unpaused`,{loop:n.loop,paused:n.paused}),n)});return{isPaused:k(`LoopControl.isPaused`)(function*(e){return(yield*t(e)).paused}),pause:k(`LoopControl.pause`)(e=>r(new RU({loop:e,paused:!0}))),states:n(),unpause:k(`LoopControl.unpause`)(e=>r(new RU({loop:e,paused:!1})))}}),VU=class e extends Lr()(`@usine/engine/LoopControl`){static layer=Yf(e,BU)},HU=class extends Lr()(`@usine/engine/RunEngineShutdown`){},UU=class e extends Lr()(`@usine/engine/AttemptAdmission`){static layer=Yf(e,E(function*(){let e=yield*Eg(HU),t=S(e)?e.value:yield*_f(),n=yield*wk(new Set),r=yield*_f(),i=k(`AttemptAdmission.enter`)(function*(e){yield*O({runId:e});let r=yield*Dk(n,n=>xf(t)?[!1,n]:[!0,new Set([...n,e])]);return r||(yield*A(`Attempt deferred until restart; the engine is draining`,{runId:e})),r}),a=k(`AttemptAdmission.leave`)(function*(e){yield*O({runId:e});let i=yield*kk(n,t=>new Set([...t].filter(t=>t!==e)));(yield*bf(t))&&(yield*A(`Attempt settled during drain`,{runId:e,remainingRunIds:[...i]}),i.size===0&&(yield*Sf(r,void 0)))});return{withAttempt:k(`AttemptAdmission.withAttempt`)(function*(e,t){return yield*O({runId:e}),yield*Ag(i(e),e=>e?t:Vh,t=>t?a(e):zh)}),drain:k(`AttemptAdmission.drain`)(function*(){yield*Sf(t,void 0);let e=yield*Tk(n);yield*A(`Engine drain started; no further Attempts will be admitted`,{activeRunIds:[...e]}),e.size===0&&(yield*Sf(r,void 0)),yield*vf(r),yield*A(`Engine drain completed; all admitted Attempts settled`)})}}))},WU=class extends NE(`@usine/engine/internal/ParentStopUnconfirmedError`)(`ParentStopUnconfirmedError`,{attemptId:TM,worker:BA,cause:eE()}){},GU=(e,t)=>{let n=new Map(e);return n.delete(t),n},KU=k(`CheckoutRecovery.for`)(function*(e,t){let n=yield*wk(new Map),r=n=>t.recover(n,{salvage:t=>e.recordSalvage(n.attemptId,t),comments:t=>e.recordComments(n.attemptId,t),windows:e.attemptWindows(n.attemptId)}).pipe(fg(e=>e_(`Attempt salvage reconciliation failed; work retained`,{attemptId:n.attemptId,worker:n.worker,message:String(e)})),hg),i=k(`CheckoutRecovery.keep`)(function*(e){yield*t.occupy(e.worker,e.attemptId).pipe(D(e=>Fg(e.release).pipe(tg(t=>({worker:e.worker,release:t,checkoutKept:!0})))),D(t=>Ok(n,n=>new Map(n).set(e.attemptId,t))),Rg)}),a=k(`CheckoutRecovery.recoverOpen`)(function*(e){let n={attemptId:e.attemptId,worker:e.worker};yield*O(n);let a=yield*t.isLive(e.attemptId).pipe(Qh);if(Di(a)&&!a.success)return yield*r(e);Ei(a)?yield*$g(`Could not read whether an open Attempt's parent task is live; its checkout stays for its Run to decide`,{...n,errorTag:a.failure._tag,message:a.failure.message}):yield*A(`Leaving the checkout of an open Attempt whose parent task is live for its Run to reattach`,n),yield*i(e),yield*A(`Occupied a slot on the Worker of an open Attempt kept for its Run to reattach`,n)}),o=k(`CheckoutRecovery.recoverClosed`)(function*(e){let n={attemptId:e.attemptId,runId:e.runId,worker:e.worker};yield*O(n);let a=yield*t.interrupt(e.attemptId,`startup`).pipe(Qh);return Di(a)?(yield*r(e),y()):(yield*$g(`Could not confirm that the parent task of a closed Attempt stopped; its checkout and a slot of its Worker stay kept, and no Attempt starts on its Loop's Item, until a reconcile confirms the stop`,{...n,errorTag:a.failure._tag,message:a.failure.message}),yield*i(e),b(e))}),s=k(`CheckoutRecovery.atStartup`)(function*(){let n=new Set(yield*t.workers),r=yield*e.salvageCandidates,i=r.filter(({worker:e})=>n.has(e)),s=r.filter(({worker:e})=>!n.has(e));return s.length>0&&(yield*$g(`Attempts recorded on Workers that are not configured were not reconciled; their checkouts stay until those Workers are configured again or their leftovers are discarded`,{attempts:s.length,workers:[...new Set(s.map(({worker:e})=>e))].sort().join(`,`)})),ha(yield*Nh(i,e=>e.open?a(e).pipe(ng(y())):o(e)))}),c=k(`CheckoutRecovery.reattachSlot`)(function*(e){return Dr(Mr(Sr((yield*Tk(n)).get(e)),({checkoutKept:e})=>e),t=>({worker:t.worker,release:Tk(n).pipe(D(n=>n.get(e)===t?A(`The slot startup occupied stays kept with the checkout no execution acquired, until the Attempt's parent task is confirmed stopped`,{attemptId:e,worker:t.worker}):t.release))}))}),l=k(`CheckoutRecovery.acquired`)(function*(e){(yield*Dk(n,t=>t.get(e)?.checkoutKept===!0?[!0,GU(t,e)]:[!1,t]))&&(yield*A(`The reattached Attempt's execution acquired the checkout startup kept; its executor releases the checkout from here, and its Run the slot once the Attempt ends`,{attemptId:e}))}),u=k(`CheckoutRecovery.hold`)(function*(e,t){let r={attemptId:e,worker:t.worker};yield*O(r);let i=yield*Fg(t.release);(yield*Dk(n,n=>n.has(e)?[!1,n]:[!0,new Map(n).set(e,{worker:t.worker,release:i,checkoutKept:!1})]))?yield*A(`The Attempt keeps its Run's slot until its parent task is confirmed stopped`,r):(yield*j(`The Attempt already has a slot kept until its parent task is confirmed stopped; releasing its Run's lease`,r),yield*i)},Rg),d=k(`CheckoutRecovery.confirmStop`)(function*(e,n,r){let i={attemptId:e,worker:n.worker,checkoutKept:n.checkoutKept,reason:r};yield*O(i);let a=yield*t.interrupt(e,r).pipe(Qh);if(Di(a))return;let o={...i,errorTag:a.failure._tag,message:a.failure.message};return yield*n.checkoutKept?$g(`Could not confirm that the parent task of an Attempt its Run does not reattach stopped; its checkout and its Worker's slot stay, and the Run starts no next Attempt until the stop is confirmed`,o):$g(`Could not confirm that the parent task of a closed Attempt stopped; its Worker's slot stays taken, and no Attempt starts on its Loop's Item, until a reconcile confirms the stop`,o),yield*new WU({attemptId:e,worker:n.worker,cause:a.failure})}),f=k(`CheckoutRecovery.recoverKept`)(function*(n){let i=yield*e.salvageCandidate(n).pipe(Qh);if(Ei(i)){yield*e_(`Could not read the Attempt whose checkout startup kept; the checkout stays until the next startup`,{attemptId:n,errorTag:i.failure._tag});return}if(x(i.success)){yield*$g(`The leftovers of the Attempt whose checkout startup kept were discarded; the checkout stays`,{attemptId:n});return}let a=i.success.value,o={attemptId:n,worker:a.worker,open:a.open};yield*O(o),(yield*t.workers).includes(a.worker)?(yield*A(`Reconciling the checkout startup kept for an Attempt that was not reattached`,o),yield*r(a)):yield*$g(`The Worker of the Attempt whose checkout startup kept is no longer configured; the checkout stays until it is configured again or its leftovers are discarded`,o)});return{atStartup:s,reattachSlot:c,acquired:l,hold:u,reconcile:k(`CheckoutRecovery.reconcile`)(function*(e,t){yield*O({attemptId:e,reason:t});let r=(yield*Tk(n)).get(e);r===void 0?yield*j(`No slot kept for the Attempt awaits its parent task's stop`,{attemptId:e}):(yield*d(e,r,t),r.checkoutKept&&(yield*f(e)),yield*Ok(n,t=>GU(t,e)).pipe(Xh(r.release),Rg),yield*A(`Released the slot kept for an Attempt whose parent task is confirmed stopped`,{attemptId:e,worker:r.worker,checkoutKept:r.checkoutKept}))})}}),qU=class extends V(`@usine/engine/UnconfirmedStop`)({attemptId:TM,runId:kA,loop:Kk,itemKey:bN,worker:BA,reason:OM}){},JU=class e extends Lr()(`@usine/engine/UnconfirmedStops`){static empty=qf(e)({list:T([])})},YU=e=>sg(e,{EnginePersistenceError:e=>new nM({message:`Runtime store error: could not ${e.operation}`,cause:e}),RunNotFoundError:e=>Gh(e),RunOperationRejectedError:e=>Gh(e),RunRetryBlockedError:e=>Gh(e)}),XU=4,ZU=`100 millis`,QU=(e,t)=>n=>n.pipe(fg(n=>n._tag===`EnginePersistenceError`?$g(`A Run store operation failed to persist`,{runId:e,operation:t,cause:n.cause}):zh),mg({schedule:uh(ZU),times:XU,while:e=>e._tag===`EnginePersistenceError`})),$U=e=>Or(e,e=>e._tag===`Live`?b(e.attempt):y()),eW=class e extends Lr()(`@usine/engine/internal/RunDriver`){static layer=Yf(e,E(function*(){let e=yield*tU,t=yield*NH,n=yield*UU,r=yield*NU,i=yield*hU,a=yield*YO,o=yield*ek(),s=yield*KU(e,t),c=yield*wk(new Map),l=yield*wk(new Map),u=(e,t)=>Dk(l,n=>n.get(e)===t?[!0,GU(n,e)]:[!1,n]).pipe(D(n=>n?t.release:j(`The Run's slot stays with its Attempt until the parent task is confirmed stopped`,{runId:e,worker:t.worker}))),d=k(`RunDriver.launch`)(function*(e){if(yield*O({runId:e}),yield*sk(o,e)){yield*j(`The Run's fiber already runs in this process`,{runId:e});return}yield*j(`Starting the Run's fiber`,{runId:e});let t=yield*$h(Vg);yield*uk(o,e,ee(e).pipe(pg(t=>Zd(t)?zh:e_(`The Run's fiber stopped on an engine failure; the next reconcile or a restart resumes it`,{runId:e,cause:t})),Ug(`RunDriver.drive`,{root:!0,links:jr(Dr(t,e=>({span:e,attributes:{}})))}),cg(e=>Zd(e)?Uh(e):zh)),{onlyIfMissing:!0})}),f=k(`RunDriver.resume`)(function*(e){yield*O({runId:e});let t=yield*ak(o,e);S(t)&&(yield*j(`Waiting for the Run's previous fiber to end`,{runId:e}),yield*RE(t.value)),yield*d(e)}),p=k(`RunDriver.stop`)(function*(e){yield*O({runId:e}),(yield*sk(o,e))?(yield*ck(o,e),yield*A(`The closed Run's fiber stopped`,{runId:e})):yield*j(`The closed Run has no fiber in this process`,{runId:e})}),m=k(`RunDriver.markItemGone`)(function*(e,t){return yield*O({runId:e,itemKey:t.itemKey}),yield*i.markGone(t.itemKey,yield*z_).pipe(QU(e,`mark the item's projection gone`),ag(n=>$g(`Could not mark the gone Item's projection; its Board card stays in place`,{completedRunId:e,itemKey:t.itemKey,errorTag:n._tag}).pipe(ng(!1))))}),h=k(`RunDriver.continueWithNewest`)(function*(t){yield*O({runId:t});let n=yield*e.nextQueued(t).pipe(QU(t,`read the queued events`));if(x(n))return;let i=n.value.submission,o={completedRunId:t,eventId:i.event.id,loop:i.loop,itemKey:i.itemKey},s=yield*r.recheck(i);if(s!==`matches`){let r=yield*e.revokeQueued(n.value).pipe(QU(t,`revoke the queued events`));if(s===`no-longer-matches`){yield*A(`Queued Event no longer matches its trigger; revoked`,{...o,revokedEvents:r});return}let a=yield*m(t,i);yield*A(`Queued Event's Item is gone from its source; revoked its queued Events`,{...o,revokedEvents:r,projectionMarkedGone:a});return}let c=yield*RP(i).pipe(Og(YO,a)),l=yield*e.claimQueued(i,c).pipe(QU(t,`claim the queued event`));x(l)?yield*A(`Queued Event still matches its trigger but could no longer be claimed; no Run opened`,o):(yield*A(`Queued Event still matches its trigger; opening its Run`,{...o,runId:l.value}),yield*d(l.value))}),g=k(`RunDriver.openAttempt`)(function*(n){yield*O({runId:n});let r=yield*e.snapshot(n).pipe(QU(n,`read the run`)),i=r.attempts.at(-1);if(r.run.state._tag!==`Running`||i===void 0||S(i.outcome))return y();let a={runId:n,attemptId:i.id,worker:i.worker};yield*O({attemptId:i.id,worker:i.worker});let o=yield*t.isLive(i.id).pipe(Qh);if(Ei(o))return yield*$g(`Could not read whether the open Attempt is live; the Run does not reattach it`,{...a,errorTag:o.failure._tag,message:o.failure.message}),b({_tag:`Interrupted`,attempt:i});if(o.success)return yield*A(`The open Attempt's parent task is live; reattaching it`,a),b({_tag:`Live`,attempt:i});let s=yield*t.outcome(i.id).pipe(Qh);if(Ei(s))return yield*$g(`Could not read the open Attempt's stored outcome; the Run does not reattach it`,{...a,errorTag:s.failure._tag,message:s.failure.message}),b({_tag:`Interrupted`,attempt:i});if(x(s.success))return yield*A(`The open Attempt's parent task is gone; the Run does not reattach it`,a),b({_tag:`Interrupted`,attempt:i});let c=s.success.value;return yield*A(`The open Attempt's parent task finished before this process recorded it; finishing the Attempt with its stored result`,{...a,outcome:ki(c,{onSuccess:()=>`Succeeded`,onFailure:({_tag:e})=>e})}),b({_tag:`Finished`,attempt:i,result:c})}),_=k(`RunDriver.slot`)(function*(e,n,r,i){yield*O({runId:e});let a=T(r),o=$U(r);if(S(o)){let t=yield*s.reattachSlot(o.value.id);if(S(t))return yield*A(`The Run reattaches its open Attempt in the slot startup occupied on its Worker`,{runId:e,attemptId:o.value.id,worker:t.value.worker}),{lease:t.value,open:a}}return{lease:yield*i(t.reserve(e,n,Dr(o,({worker:e})=>e))),open:S(o)?g(e):a}}),v=k(`RunDriver.attempt`)(function*(n,r,i,a){yield*O({runId:n,worker:i});let o=yield*a;if(S(o)&&o.value._tag===`Finished`){let t=yield*e.finishAttempt(o.value.attempt,o.value.result).pipe(QU(n,`finish the attempt`));if(t._tag!==`RetryAttempt`)return t._tag}let c=yield*e.beginAttempt(n,i,Dr($U(o),({id:e})=>e)).pipe(QU(n,`begin the attempt`));if(c._tag===`AttemptRecoveryFailed`)return`RunFailed`;if(c._tag===`RunClosed`)return`Unchanged`;let l=yield*t.execute(c.execution,{append:(t,n)=>e.appendTranscript(t,n).pipe(YU),salvage:t=>e.recordSalvage(c.execution.attempt.id,t).pipe(YU),comments:t=>e.recordComments(c.execution.attempt.id,t).pipe(YU),outOfMemory:t=>e.recordOutOfMemory(c.execution.attempt.id,t).pipe(YU),windows:e.attemptWindows(c.execution.attempt.id).pipe(QU(n,`read the attempt windows`),YU),transcript:e.transcript(new FN({attemptId:c.execution.attempt.id})).pipe(QU(n,`read the attempt transcript`),YU,tg(e=>e.flatMap(({envelope:e})=>e.version===7?[e]:[]))),checkoutAcquired:s.acquired(c.execution.attempt.id)}).pipe(lg(e=>e_(`Step executor defect; operator intervention required`,{runId:n,attemptId:c.execution.attempt.id,defect:e instanceof Error?e.message:String(e)}).pipe(Xh(new rM({message:`The step executor crashed with an unexpected error`,cause:e})))),Qh);return c.execution.reattach&&Ei(l)&&(yield*s.reconcile(c.execution.attempt.id,`failed`)),Ei(l)&&(yield*re({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,reason:`failed`},i)),(yield*e.finishAttempt(c.execution.attempt,l).pipe(QU(n,`finish the attempt`)))._tag}),ee=Qg(function*(t){let r=yield*e.submission(t).pipe(QU(t,`read the run's submission`));if(yield*O({runId:t,loop:r.loop,itemKey:r.itemKey}),r.approval===`required`&&(yield*e.parkForApproval(t).pipe(QU(t,`park the run for approval`)))._tag===`Waiting`){yield*A(`Run waits for its approval`,{runId:t});return}let i;do{let e=yield*g(t);if(S(e)&&e.value._tag!==`Live`&&(yield*s.reconcile(e.value.attempt.id,`startup`)),x($U(e))){let e=yield*ie(r);if(S(e)){yield*A(`The Run starts no Attempt while the parent task of an earlier Attempt on its Loop's Item is not confirmed stopped; each reconcile tries that stop again, then drives the Run`,{runId:t,loop:r.loop,itemKey:r.itemKey,unstoppedAttemptId:e.value.attemptId,unstoppedRunId:e.value.runId,worker:e.value.worker,reason:e.value.reason});return}}i=yield*zg(i=>_(t,r,e,i).pipe(Zh(({lease:e})=>Ok(l,n=>new Map(n).set(t,e))),D(({lease:e,open:a})=>i(n.withAttempt(t,v(t,r,e.worker,a))).pipe(jg(u(t,e))))))}while(i===`RetryAttempt`);i===`Unchanged`?yield*A(`Run closed by another operation; its fiber ends`,{runId:t}):yield*h(t)}),te=k(`RunDriver.holdSlot`)(function*(e,t){yield*O({runId:e,attemptId:t});let n=yield*Dk(l,t=>[Sr(t.get(e)),GU(t,e)]);x(n)?yield*j(`The Run's fiber holds no slot in this process; no slot moves to its Attempt`,{runId:e,attemptId:t}):yield*s.hold(t,n.value)},Rg),ne=e=>Ok(c,t=>t.has(e.attemptId)?t:new Map(t).set(e.attemptId,e)),re=k(`RunDriver.confirmStopAfterFailure`)(function*(e,n){let{attemptId:r,runId:i}=e,a={runId:i,attemptId:r,worker:n,reason:e.reason};yield*O(a);let o=yield*t.interrupt(r,e.reason).pipe(Qh);Di(o)?yield*j(`The parent task of the failed Attempt is confirmed stopped; the Run's slot is freed`,a):(yield*$g(`Could not confirm that the parent task of the failed Attempt stopped; the Attempt keeps its Run's slot, no Attempt starts on its Loop's Item, and each reconcile tries the stop again`,{...a,errorTag:o.failure._tag,message:o.failure.message}),yield*te(i,r).pipe(Xh(ne(new qU({...e,worker:n}))),Rg))}),ie=e=>Tk(c).pipe(tg(t=>Sr([...t.values()].find(({loop:t,itemKey:n})=>t===e.loop&&n===e.itemKey)))),ae=k(`RunDriver.releaseKept`)(function*(e){let{attemptId:t,runId:n,reason:r}=e;yield*O({runId:n,attemptId:t,reason:r});let i=yield*s.reconcile(t,r).pipe(Qh);if(Di(i)){(yield*Dk(c,e=>[e.has(t),GU(e,t)]))&&(yield*A(`The parent task of a closed Attempt is confirmed stopped; Runs on its Loop's Item start Attempts again`,{runId:n,attemptId:t,loop:e.loop,itemKey:e.itemKey,reason:r}));return}let{worker:a}=i.failure;yield*O({worker:a}),yield*ne(new qU({...e,worker:a})),yield*$g(`The parent task of a closed Attempt is not confirmed stopped; its Worker's slot, and any checkout startup kept, stay kept, no Attempt starts on its Loop's Item, and the next reconcile tries the stop again`,{runId:n,attemptId:t,worker:a,loop:e.loop,itemKey:e.itemKey,reason:r})}),oe=k(`RunDriver.recoverWorkspaces`)(function*(){yield*Nh(yield*s.atStartup(),({attemptId:e,runId:t,loop:n,itemKey:r,worker:i})=>ne(new qU({attemptId:e,runId:t,loop:n,itemKey:r,worker:i,reason:`startup`})),{discard:!0})});return{launch:d,resume:f,stop:p,continueWithNewest:h,reconcile:k(`RunDriver.reconcile`)(function*(){let n=[...(yield*Tk(c)).values()];yield*Nh(n,ae,{discard:!0});let r=yield*e.pendingContinuations;yield*Nh(r,e=>h(e).pipe(fg(t=>e_(`Could not continue the queued Events behind a closed Run`,{runId:e,errorTag:t._tag})),hg),{discard:!0});let i=yield*e.runIdsToDrive,a=yield*yg(i,e=>tg(sk(o,e),e=>!e));yield*Nh(a,d,{discard:!0}),yield*t.sweep;let s={continuedAfterRunIds:r,startedRunIds:a,drivenRunIds:i.length,retriedStopAttemptIds:n.map(({attemptId:e})=>e)};r.length===0&&a.length===0&&n.length===0?yield*j(`Every Run to drive already has its fiber`,s):yield*A(`Runs recovered from the run tables`,s)}),recoverWorkspaces:oe,holdSlot:te,releaseKept:ae,unconfirmedStops:Tk(c).pipe(tg(e=>[...e.values()]))}}))},tW=_i(`@usine/engine/ReconcileInterval`,{defaultValue:()=>`3 minutes`});E(function*(){let e=yield*tU,t=yield*eW,n=yield*UU,r=yield*NH,i=yield*YO,a=k(`RunEngine.submit`)(function*(n){let r=yield*RP(n).pipe(Og(YO,i)),a=yield*e.recordAndClaim(n,r);return S(a.supersededRun)&&(yield*t.stop(a.supersededRun.value)),S(a.openedRun)&&(yield*t.launch(a.openedRun.value)),a.result},Rg),o=k(`RunEngine.approve`)(function*(n,r,i){(yield*e.approve(n,r,i))?(yield*A(`Run approved`,{runId:n,eventId:r.id,channel:i.channel,approver:yr(i.approver,()=>`none`)}),yield*t.resume(n)):yield*j(`Approval was already recorded; the Run is unchanged`,{runId:n,eventId:r.id})},Rg),s=k(`RunEngine.retry`)(function*(n,r=kH){(yield*e.retry(n,r))?yield*t.resume(n):yield*j(`Retry changed nothing; the Run already waits for its next Attempt`,{runId:n})},Rg),c=k(`RunEngine.runAgain`)(function*(n,r){let i=yield*e.runAgain(n,r);return i._tag===`Claimed`&&(yield*t.launch(i.runId)),i},Rg),l=k(`RunEngine.cancel`)(function*(n){let i=yield*e.cancel(n);if(i._tag===`AlreadyClosed`){yield*j(`Cancel was a no-op; the run was already closed`,{runId:n});return}yield*A(`Run canceled`,{runId:n,openAttempt:yr(i.openAttempt,()=>`none`)}),S(i.openAttempt)&&(yield*t.holdSlot(n,i.openAttempt.value));let a=S(i.openAttempt)?yield*r.interrupt(i.openAttempt.value,`cancel`).pipe(Qh):xi(void 0);if(yield*t.stop(n),S(i.openAttempt)&&(yield*t.releaseKept({attemptId:i.openAttempt.value,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`})),yield*t.continueWithNewest(n),S(i.openAttempt)&&Ei(a))return yield*new iP({attemptId:i.openAttempt.value,cause:a.failure})},Rg),u=k(`RunEngine.intervene`)(function*(t,n,i){yield*O({runId:t,attemptId:n,action:i.action._tag});let a=yield*e.snapshot(t),o=a.attempts.at(-1);if(a.run.state._tag!==`Running`||o?.id!==n||S(o.outcome))return yield*A(`Operator input rejected for an inactive Attempt`,{runId:t,attemptId:n}),yield*new oP({runId:t,attemptId:n,message:`This attempt is no longer running`});yield*r.intervene(n,i).pipe(ug(e=>new oP({runId:t,attemptId:n,message:xk(e,{RunawayFailure:()=>`The attempt reached its runaway limit`,ChildSessionBudgetFailure:()=>`The attempt reached its child-session budget`,QuestionFailure:()=>`The attempt ended with a question for the operator`,BlockedFailure:({message:e})=>e,InfraFailure:({message:e})=>e,DefectFailure:({message:e})=>e,AgentFailure:({message:e})=>e})})),fg(e=>$g(`Operator input delivery failed`,{runId:t,attemptId:n,message:e.message})))}),d=k(`RunEngine.resolveFailure`)(function*(n,r,i){yield*O({runId:n,attemptId:r}),(yield*e.resolveFailure(n,r,i))&&(yield*A(`The operator resolved the Agent's question or blocker; the Item's queued Events get their turn`,{runId:n,attemptId:r}),yield*t.continueWithNewest(n))},Rg),f=k(`RunEngine.revoke`)(function*(n,r){let i=yield*e.revoke(n,r);return yield*Nh(i,t.stop,{concurrency:`unbounded`,discard:!0}),i},Rg),p=k(`RunEngine.inspect`)(function*(t){return yield*e.snapshot(t)}),m=k(`RunEngine.transcript`)(function*(t){return yield*e.transcript(t)}),h=k(`RunEngine.discardLeftovers`)(function*(t){if(yield*O({worker:t}),(yield*r.workers).includes(t)){let n=yield*e.openAttempts(t);return yield*A(`Leftovers kept; the Worker is configured or still runs Attempts, so its Attempts stay tracked`,{worker:t,running:n}),yield*new sP({worker:t,running:n})}let n=yield*e.discardLeftovers(t);return yield*A(`Discarded the leftovers of the Attempts on a Worker that is not configured; startup no longer reconciles them`,{worker:t,attempts:n.length}),yield*r.discard(t,n),n.length});return yield*t.recoverWorkspaces(),yield*t.reconcile(),yield*gg(yield*tW).pipe(Xh(t.reconcile()),fg(e=>e_(`Periodic Run reconcile failed; the next one tries again`,{errorTag:e._tag})),hg,Bg,Kg),{approve:o,cancel:l,discardLeftovers:h,drain:n.drain,inspect:p,intervene:u,reconcile:t.reconcile,retry:s,resolveFailure:d,revoke:f,runAgain:c,submit:a,transcript:m}});var nW=class extends Lr()(`@usine/engine/RunEngine`){},rW=`~effect/http/HttpBody`,iW=e=>pe(e,rW),aW=class{[rW];constructor(){this[rW]=rW}[gt](){return this.toJSON()}toString(){return ot(this,{ignoreToString:!0})}},oW=new class extends aW{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}},sW=class extends aW{_tag=`Uint8Array`;contentType;contentLength;text;_body;constructor(e,t,n,r){super(),this._body=e,this.text=r,this.contentType=t,this.contentLength=n}get body(){return this._body??=dW(this.text)}toJSON(){return{_id:`effect/HttpBody`,_tag:`Uint8Array`,body:this.contentType.startsWith(`text/`)||this.contentType.endsWith(`json`)?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}},cW=(e,t)=>new sW(e,t??`application/octet-stream`,e.length),lW=new TextEncoder,uW=globalThis.Buffer,dW=uW===void 0?e=>lW.encode(e):e=>uW.from(e,`utf8`),fW=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),uW!==void 0)return new sW(void 0,t??`text/plain`,uW.byteLength(e,`utf8`),e);let n=lW.encode(e);return new sW(n,t??`text/plain`,n.length,e)},pW=(e,t)=>fW(JSON.stringify(e),t??`application/json`),mW=(e,t)=>fW(Yv(Bv(e)),t??`application/x-www-form-urlencoded`),hW=class extends aW{_tag=`FormData`;contentType=void 0;contentLength=void 0;formData;constructor(e){super(),this.formData=e}toJSON(){return{_id:`effect/HttpBody`,_tag:`FormData`,formData:this.formData}}},gW=e=>new hW(e),_W=class extends aW{_tag=`Stream`;stream;contentType;contentLength;constructor(e,t,n){super(),this.stream=e,this.contentType=t,this.contentLength=n}toJSON(){return{_id:`effect/HttpBody`,_tag:`Stream`,contentType:this.contentType,contentLength:this.contentLength}}},vW=(e,t,n)=>new _W(e,t??`application/octet-stream`,n),yW=`~effect/http/HttpClientError`,bW=class extends Co(`HttpClientError`){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[yW]=yW;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}},xW=e=>e.endsWith(`Error`)?e.slice(0,-5):e,SW=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,CW=e=>`${e.method} ${$v(e.url)}`,wW=class extends Co(`TransportError`){get methodAndUrl(){return CW(this.request)}get message(){return SW(xW(this._tag),this.description,this.methodAndUrl)}},TW=class extends Co(`InvalidUrlError`){get methodAndUrl(){return CW(this.request)}get message(){return SW(xW(this._tag),this.description,this.methodAndUrl)}},EW=class extends Co(`StatusCodeError`){get methodAndUrl(){return CW(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return SW(xW(this._tag),this.description,e)}},DW=class extends Co(`DecodeError`){get methodAndUrl(){return CW(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return SW(xW(this._tag),this.description,e)}},OW=class extends Co(`EmptyBodyError`){get methodAndUrl(){return CW(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return SW(xW(this._tag),this.description,e)}},kW=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,AW=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],jW=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?jv(jv(e,`content-type`),`content-length`):(e=t.contentType===void 0?jv(e,`content-type`):Ov(e,`content-type`,t.contentType),t.contentLength===void 0?jv(e,`content-length`):Ov(e,`content-length`,t.contentLength.toString())),MW=class extends Co(`UrlError`){},NW=(e,t,n)=>wi({try:()=>{let r=new URL(e,PW());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,Fv(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new MW({cause:e})}),PW=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0){let e=location.origin+location.pathname;try{return new URL(e).href}catch{return}}},FW=`~effect/http/HttpClientRequest`,IW={[FW]:FW,...yt,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:$v(this.url),urlParams:this.urlParams,hash:this.hash,headers:tt(this.headers),body:this.body.toJSON()}},pipe(){return e(this,arguments)}};function LW(e,t,n,r,i,a){let o=Object.create(IW);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var RW=LW(`GET`,``,Gv,y(),Tv,oW),zW=e=>(t,n)=>HW(RW,{method:e,url:t,...n??void 0}),BW=zW(`GET`),VW=zW(`POST`),HW=r(2,(e,t)=>{let n=e;return t.method&&(n=UW(n,t.method)),t.url&&(n=YW(n,t.url)),t.headers&&(n=GW(n,t.headers)),t.urlParams&&(n=QW(n,t.urlParams)),t.hash&&(n=eG(n,t.hash)),t.body&&(n=tG(n,t.body)),t.accept&&(n=KW(n,t.accept)),t.acceptJson&&(n=qW(n)),n}),UW=r(2,(e,t)=>LW(t,e.url,e.urlParams,e.hash,e.headers,e.body)),WW=r(3,(e,t,n)=>LW(e.method,e.url,e.urlParams,e.hash,Ov(e.headers,t,n),e.body)),GW=r(2,(e,t)=>LW(e.method,e.url,e.urlParams,e.hash,kv(e.headers,t),e.body)),KW=r(2,(e,t)=>WW(e,`Accept`,t)),qW=KW(`application/json`),JW=r(2,(e,t)=>LW(e.method,e.url,e.urlParams,e.hash,Ov(Ov(e.headers,`connection`,`Upgrade`),`upgrade`,t),e.body)),YW=r(2,(e,t)=>{if(typeof t==`string`)return LW(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Bv(n.searchParams),i=C(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,LW(e.method,n.toString(),r,i,e.headers,e.body)}),XW=r(2,(e,t)=>t===``?e:LW(e.method,ZW(t,e.url),e.urlParams,e.hash,e.headers,e.body)),ZW=(e,t)=>{let n=e.endsWith(`/`),r=t.startsWith(`/`);return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t},QW=r(2,(e,t)=>LW(e.method,e.url,qv(e.urlParams,t),e.hash,e.headers,e.body)),$W=r(2,(e,t)=>LW(e.method,e.url,Jv(e.urlParams,t),e.hash,e.headers,e.body)),eG=r(2,(e,t)=>LW(e.method,e.url,e.urlParams,b(t),e.headers,e.body)),tG=r(2,(e,t)=>LW(e.method,e.url,e.urlParams,e.hash,jW(e.headers,t),t)),nG=r(2,(e,t)=>tG(e,pW(t))),rG=r(2,(e,t)=>tG(e,gW(t)));function iG(e){let t=NW(e.url,e.urlParams,wr(e.hash));return Di(t)?b(t.success):y()}var aG=`~effect/http/HttpIncomingMessage`,oG=(e,t)=>{let n=Hw(PE(e)),r=t?.reviver===void 0?void 0:Hw(aE(PE(e),t));return e=>r===void 0?D(e.json,e=>n(e,t)):D(e.text,i=>i===``?D(e.json,e=>n(e,t)):r(i,t))},sG=(e,t)=>({...t,headers:tt(e.headers),remoteAddress:e.remoteAddress}),cG=`~effect/http/HttpClientResponse/WebSource`,lG=e=>e[cG]?.(),uG=`~effect/http/HttpClientResponse`,dG=(e,t)=>new fG(e,t),fG=class extends bt{[aG];[uG];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[aG]=aG,this[uG]=uG}toJSON(){return sG(this,{_id:`HttpClientResponse`,request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get url(){if(this.source.url)return this.source.url.split(`#`)[0];let e=iG(this.request);return x(e)?``:(e.value.hash=``,e.value.href)}get headers(){return Ev(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=cv(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return y()}[cG](){return this.source}get stream(){return this.source.body?PO({evaluate:()=>this.source.body,onError:e=>new bW({reason:new DW({request:this.request,response:this,cause:e})})}):MO(new bW({reason:new OW({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return D(this.text,e=>Kh({try:()=>e===``?null:JSON.parse(e),catch:e=>new bW({reason:new DW({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=tg(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return D(this.text,e=>Kh({try:()=>Bv(new URLSearchParams(e)),catch:e=>new bW({reason:new DW({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=Fh({try:()=>this.source.formData(),catch:e=>new bW({reason:new DW({request:this.request,response:this,cause:e})})}).pipe(Fg,Xg)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=Fh({try:()=>this.source.arrayBuffer(),catch:e=>new bW({reason:new DW({request:this.request,response:this,cause:e})})}).pipe(Fg,Xg),this.arrayBufferBody}get upgrade(){return Hh(new bW({reason:new EW({request:this.request,response:this,description:`fetch cannot hand over the connection of an HTTP upgrade`})}))}pipe(){return e(this,arguments)}},pG=e=>Dv({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${vr(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),mG={"http:":80,"https:":443,"ws:":80,"wss:":443},hG=(e,t,n)=>{let r=$v(t.search,n).slice(1);if(e.attribute(`url.full`,$v(t.href,n)),e.attribute(`url.path`,t.pathname),r!==``&&e.attribute(`url.query`,r),e.attribute(`url.scheme`,t.protocol.slice(0,-1)),t.hostname!==``){e.attribute(`server.address`,t.hostname.startsWith(`[`)?t.hostname.slice(1,-1):t.hostname);let n=t.port===``?mG[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},gG=(e,t)=>{let n=e.params.filter(([,e])=>typeof e!=`string`).map(([e])=>e);return n.length===0?t:[...t,...new URLSearchParams(n.map(e=>[e,``])).keys()]},_G=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,Nv(a,i)?`<redacted>`:n[a])},vG=`~effect/http/HttpClient`,yG=Lr(`effect/HttpClient`),bG=r(2,(e,t)=>xG(n=>t(e.postprocess(n)),e.preprocess)),xG=(e,t)=>{let n=Object.create(SG);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},SG={[vG]:vG,pipe(){return e(this,arguments)},...yt,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(AW.map(([e,t])=>[t,function(t,n){return this.execute(zW(e)(t,n))}]))},CG=e=>xG(t=>D(t,t=>qh(n=>{let r=MG.get(t),i=r??new AbortController,a=NW(t.url,t.urlParams,wr(t.hash));if(Ei(a))return Hh(new bW({reason:new TW({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(zo)||n.getRef(EG)(t)){let a=e(t,o,i.signal,n);return r?a:zg(e=>xg(e(a),{onSuccess(e){return jG.register(e,i),T(new NG(e,i))},onFailure(e){return tf(e)&&i.abort(),Uh(e)}}))}return Hg(n.getRef(kG)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(Pv);hG(a,o,gG(t.urlParams,n.getRef(sy)));let c=n.getRef(DG);return _G(a,`request`,t.headers,c,s),t=n.getRef(OG)?GW(t,pG(a)):t,zg(l=>l(e(t,o,i.signal,n)).pipe(Wg(a,{captureStackTrace:!1}),xg({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),_G(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),wG(n,a,t,e)),r?T(e):(jG.register(e,i),T(new NG(e,i)))),onFailure(e){return!r&&tf(e)&&i.abort(),Uh(e)}})))})})),T),wG=(e,t,n,r)=>{let i=St();Ct(0);let a;try{a=uf(new bW({reason:new EW({request:n,response:r})}))}finally{Ct(i)}t.end(e.getRef(Tf)?e.getRef(ip).currentTimeNanosUnsafe():BigInt(0),a)},TG=r(2,(e,t)=>xG(e.postprocess,n=>tg(e.preprocess(n),t))),EG=_i(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>s}),DG=_i(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>s}),OG=_i(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:o}),kG=_i(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),AG=e=>Yf(yG)(Cg(t=>tg(e,e=>bG(e,Dg(e=>mi(t,e)))))),jG=(()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=new FinalizationRegistry(e=>{try{e.abort()}catch{}});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=new WeakMap;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),MG=new WeakMap,NG=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[uG]=uG;[aG]=aG;applyInterrupt(e){return Lh(()=>(jG.unregister(this.original),Lg(e,()=>Rh(()=>{this.controller.abort()}))))}get request(){return this.original.request}get url(){return this.original.url}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get upgrade(){return this.applyInterrupt(this.original.upgrade)}[cG](){let e=lG(this.original);return e!==void 0&&jG.unregister(this.original),e}get stream(){return AO(()=>(jG.unregister(this.original),WO(this.original.stream,Rh(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[gt](){return this.original[gt]()}pipe(){return e(this,arguments)}},PG=_i(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),FG=class extends Lr()(`effect/http/FetchHttpClient/RequestInit`){},IG=AG(T(CG((e,t,n,r)=>{if(e.headers.upgrade!==void 0)return Hh(new bW({reason:new wW({request:e,description:`fetch cannot send an HTTP upgrade request`})}));let i=r.getRef(PG),a=oi(r.context,FG)??{},o=a.headers?Av(Ev(a.headers),e.headers):e.headers;o[`content-length`]&&(o=jv(o,`content-length`));let s,c=Rh(()=>s?.abort()),l=r=>tg(Fh({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:typeof ReadableStream<`u`&&r instanceof ReadableStream?`half`:void 0,signal:s?AbortSignal.any([n,s.signal]):n}),catch:t=>new bW({reason:new wW({request:e,cause:t})})}),t=>{let n=dG(e,t);return s?(t.body===null&&s.abort(),Object.create(n,{...Object.fromEntries([`arrayBuffer`,`text`,`json`,`formData`,`urlParamsBody`].map(e=>[e,{get:()=>jg(n[e],c)}])),stream:{get:()=>WO(n.stream,c)}})):n}).pipe(Mg(()=>c));switch(e.body._tag){case`Raw`:case`Uint8Array`:return l(e.body.body);case`FormData`:return l(e.body.formData);case`Stream`:{s=new AbortController;let t=AbortSignal.any([n,s.signal]),r=Bh(e=>{let n=()=>e(Ig);if(t.aborted)n();else return t.addEventListener(`abort`,n,{once:!0}),Rh(()=>t.removeEventListener(`abort`,n))});return D(JO(UO(e.body.stream,r)),l)}}return l(void 0)})));function LG(e,t){let n=1;for(;t<e.length;)if(t++,e[t]===`\\`)t++;else if(e[t]===`)`?n--:e[t]===`(`&&n++,!n)return t;throw TypeError(`Invalid regexp expression in "`+e+`"`)}var RG=Lr(`effect/http/HttpEffect/CurrentRequestState`),zG=e=>qh(t=>{let n=oi(t.context,RG);return n!==void 0&&(n.loggerDisabled=!0),e}),BG=Lr(`effect/http/HttpRouter`),VG=e=>e.endsWith(`/`)?e.slice(0,-1):e,HG=r(2,(e,t)=>(t=VG(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),UG=`~effect/http/HttpRouter/Middleware`,WG=function(){return arguments.length===0?GG:GG(arguments[0],arguments[1])},GG=(e,t)=>t?.global?Qf(E(function*(){let t=yield*BG,n=jh(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new JG(jh(e)?Zf(tg(e,e=>Xr(new Map([[qG,e]])))):Jf(Xr(new Map([[qG,e]])))),KG=0,qG=`effect/http/HttpRouter/MiddlewareFn`,JG=class e{[UG]={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++KG}`;this.layer=Zf(E({self:this},function*(){let e=yield*Sg(),t=[si(e,qG)];if(this.dependencies){let n=yield*Wf,r=li(e,Ef),i=yield*Gf(this.dependencies,n,r);t.push(...XG(i))}return Xr(new Map([[n,t]]))})).pipe(np(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?rp(this.dependencies,t.layer):t.layer)}},YG=new WeakMap,XG=e=>{let t=YG.get(e);if(t)return t;let n=fa(),r=0;for(let[t,i]of e.mapUnsafe)t.startsWith(`effect/http/HttpRouter/Middleware-`)&&(n.push(i),i.length>r&&(r=i.length));if(n.length===0)t=[];else{let e=new Set;for(let t=r-1;t>=0;t--)for(let r of n)t<r.length&&e.add(r[t]);t=Ui(e).reverse()}return YG.set(e,t),t};WG(zG).layer;var ZG={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511},QG=e=>ZG[e],$G=R.check(HT(1)).pipe(L(`GitHubAppId`)),eK=CE(z.check(PT(/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/u,{message:`Expected a PEM-encoded RSA private key`})).pipe(L(`GitHubAppPrivateKey`)),{disallowEncode:!0});V(`@usine/github/AppCredentials`)({appId:$G,privateKey:eK});var tK=class extends Lr()(`@usine/github/GitHubCredentials`){},nK=class extends NE(`@usine/github/AppAuthenticationError`)(`AppAuthenticationError`,{message:z}){},rK=new TextEncoder,iK=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),aK=(...e)=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},oK=e=>{if(e<128)return new Uint8Array([e]);let t=[];for(let n=e;n>0;n>>>=8)t.unshift(n&255);return new Uint8Array([128|t.length,...t])},sK=(e,t)=>aK(new Uint8Array([e]),oK(t.length),t),cK=e=>sK(48,aK(new Uint8Array([2,1,0]),iK,sK(4,e))),lK=e=>{let t=e.includes(`-----BEGIN RSA PRIVATE KEY-----`),n=e.replace(/-----BEGIN (?:RSA )?PRIVATE KEY-----/gu,``).replace(/-----END (?:RSA )?PRIVATE KEY-----/gu,``).replace(/\s/gu,``),r=atob(n),i=Uint8Array.from(r,e=>e.charCodeAt(0));return t?cK(i):i},uK=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/=/gu,``).replace(/\+/gu,`-`).replace(/\//gu,`_`)},dK=e=>uK(rK.encode(JSON.stringify(e))),fK=e=>{let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},pK=k(`AppJwt.import`)(function*(e){let t=yield*Fh({try:async()=>crypto.subtle.importKey(`pkcs8`,fK(lK(yv(e.privateKey))),{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},!1,[`sign`]),catch:()=>new nK({message:`Could not import the GitHub App private key as an RSA private key`})});return k(`AppJwt.sign`)(function*(){let n=Math.floor((yield*ap)/1e3),r=`${dK({alg:`RS256`,typ:`JWT`})}.${dK({iat:n-60,exp:n+540,iss:e.appId})}`,i=yield*Ph(()=>crypto.subtle.sign(`RSASSA-PKCS1-v1_5`,t,fK(rK.encode(r))));return _v(`${r}.${uK(new Uint8Array(i))}`)})}),mK=R.check(HT(1)),hK=mK.pipe(L(`GitHubInstallationId`)),gK=mK.pipe(L(`GitHubRepositoryId`)),_K=z.pipe(L(`GitHubAppSlug`)),vK=class extends V(`@usine/github/Installation`)({id:hK,accountLogin:z,appSlug:_K}){},yK=class extends H(`@usine/github/TokenScope/InstallationWide`)(`InstallationWide`,{}){},bK=class extends H(`@usine/github/TokenScope/SingleRepository`)(`SingleRepository`,{repository:Lk,repositoryId:gK,permissions:Xk}){},xK=F([yK,bK]),SK=class extends V(`@usine/github/InstallationToken`)({value:SE(z,{disallowJsonEncode:!0}),expiresAt:_E,scope:xK}){},CK=bT([`missing`,`multiple`,`suspended`]),wK=class extends NE(`@usine/github/InstallationDiscoveryError`)(`InstallationDiscoveryError`,{reason:CK,message:z}){},TK={checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},EK={write:{checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},read:{checks:`read`,contents:`read`,issues:`write`,metadata:`read`,pull_requests:`write`}},DK=(e,t)=>e===t||t===`read`&&e===`write`,OK=e=>Object.entries(TK).flatMap(([t,n])=>DK(e[t],n)?[]:[`${t}:${n}`]),kK=class extends H(`@usine/github/ProjectAccess/CoveredProject`)(`CoveredProject`,{installationId:hK,repository:Lk,repositoryId:gK}){},AK=class extends NE(`@usine/github/ProjectNotInstalledError`)(`ProjectNotInstalledError`,{repository:Lk,message:z}){};F([kK,AK]);var jK=(e,t,n)=>{let r=new Map(n.map(e=>[e.name.toLowerCase(),e]));return t.map(t=>{let n=r.get(t.toLowerCase());return n===void 0?new AK({repository:t,message:`The GitHub App installation has no access to "${t}"`}):new kK({installationId:e.id,repository:t,repositoryId:n.id})})},MK=class extends NE(`@usine/github/AppPermissionError`)(`AppPermissionError`,{missing:P(z).check(qT()),message:z}){},NK=bT([`create-repository-label`,`discover-installation`,`fetch-base-ref-head`,`fetch-item-labels`,`fetch-issue-snapshot`,`fetch-item-timeline`,`fetch-pull-request-snapshot`,`find-missing-issues`,`list-installation-repositories`,`list-repository-labels`,`mint-installation-token`,`mint-worker-token`,`poll-repository-changes`,`read-bot-account`,`update-item-labels`]),PK=class extends NE(`@usine/github/GitHubApiError`)(`GitHubApiError`,{operation:NK,status:B(R),message:z}){},FK=class extends NE(`@usine/github/GitHubRateLimitError`)(`GitHubRateLimitError`,{operation:NK,retryAt:_E,message:z}){},IK=class extends NE(`@usine/github/InvalidGitHubResponseError`)(`InvalidGitHubResponseError`,{operation:NK,message:z,detail:z}){},LK=class extends NE(`@usine/github/GitHubItemNotFoundError`)(`GitHubItemNotFoundError`,{operation:NK,item:R.check(HT(1)),message:z}){};F([wK,MK,PK,FK,IK]);var RK=`https://api.github.com`,zK=`2026-03-10`,BK=e=>GW({accept:`application/vnd.github+json`,authorization:`Bearer ${yv(e)}`,"user-agent":`usine`,"x-github-api-version":zK}),VK=(e,t)=>new PK({operation:e,status:t.response===void 0?y():b(t.response.status),message:t.response===void 0?`Could not send the request to GitHub`:`GitHub returned HTTP status ${t.response.status}`}),HK=Uw(N({message:z})),UK=(e,t)=>t.json.pipe(tg(t=>vr(HK(t),{onNone:()=>e,onSome:({message:t})=>new PK({operation:e.operation,status:e.status,message:`${e.message}: ${t}`})})),ag(t=>j(`GitHub's error response has no JSON body to read a reason from`,{operation:e.operation,message:t.message}).pipe(ng(e)))),WK=(e,t)=>new IK({operation:e,message:`GitHub returned a response in an unexpected format`,detail:t}),GK=e=>{if(e===void 0||!/^\d+$/u.test(e))return y();let t=Number(e);return Number.isSafeInteger(t)?b(t):y()},KK=(e,t)=>{let n=GK(e);if(S(n))return b(t+n.value*1e3);if(e===void 0)return y();let r=Date.parse(e);return Number.isFinite(r)?b(r):y()},qK=(e,t)=>{let n=GK(e[`x-ratelimit-remaining`]),r=GK(e[`x-ratelimit-reset`]);return S(n)&&n.value<=t&&S(r)?b(r.value*1e3):y()},JK=(e,t)=>Dr(GK(e[`x-poll-interval`]),e=>t+e*1e3),YK=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?y():b(Math.max(...t))},XK=(e,t)=>YK([KK(e[`retry-after`],t),qK(e,0)]),ZK=(e,t,n)=>{let r=Or(XK(t.headers,n),R_);return(t.status===403||t.status===429)&&S(r)?new FK({operation:e,retryAt:r.value,message:`GitHub API rate limit exceeded`}):new PK({operation:e,status:b(t.status),message:`GitHub returned HTTP status ${t.status}`})},QK=36e5,$K=3e5,eq=P(N({id:hK,appSlug:_K,account:N({login:z}),permissions:mT(M,M),suspendedAt:I(M)}).pipe(pT({appSlug:`app_slug`,suspendedAt:`suspended_at`}))),tq=N({login:HA,id:UA}),nq=N({id:gK,name:Lk}).pipe(pT({name:`full_name`})),rq=N({totalCount:R.check(HT(0)),repositories:P(nq)}).pipe(pT({totalCount:`total_count`})),iq=N({token:z,expiresAt:vE,repositories:xE(P(nq))}).pipe(pT({expiresAt:`expires_at`})),aq=e=>e._tag===`InstallationWide`?{operation:`mint-installation-token`,body:{permissions:TK}}:{operation:`mint-worker-token`,body:{permissions:EK[e.permissions],repository_ids:[e.repositoryId]}},oq=class e extends Lr()(`@usine/github/GitHubApp`){static layer=Yf(e,E(function*(){let e=yield*pK(yield*tK),t=yield*yG,n=(e,n,r)=>E(function*(){let i=yield*t.execute(n).pipe(ug(t=>VK(e,t)));if(i.status<200||i.status>=300){let t=ZK(e,i,yield*ap);return t._tag===`GitHubRateLimitError`?yield*t:yield*yield*UK(t,i)}return yield*oG(r)(i).pipe(ug(t=>WK(e,t.message)))}),r=k(`GitHubApp.discoverInstallation`)(function*(){let t=yield*e(),[r,...i]=yield*n(`discover-installation`,BW(`${RK}/app/installations?per_page=2`).pipe(BK(t)),eq);if(r===void 0)return yield*new wK({reason:`missing`,message:`The GitHub App is not installed on any account. Install it on the account that owns the repositories.`});if(i.length>0)return yield*new wK({reason:`multiple`,message:`The GitHub App has more than one installation. Uninstall it from every account except one.`});if(r.suspendedAt!==null)return yield*new wK({reason:`suspended`,message:`The GitHub App installation is suspended. Unsuspend it in the installation settings on GitHub.`});let a=OK(r.permissions);return a.length>0?yield*new MK({missing:a,message:`The GitHub App installation is missing permissions: ${a.join(`, `)}. Grant them in the GitHub App settings, then approve the change on the installation.`}):new vK({id:r.id,accountLogin:r.account.login,appSlug:r.appSlug})}),i=k(`GitHubApp.mintToken`)(function*(t,r){let{operation:i,body:a}=aq(r);yield*O({installationId:t,operation:i,scope:r._tag,permissions:r._tag===`SingleRepository`?r.permissions:`installation`});let o=yield*e(),s=yield*n(i,VW(`${RK}/app/installations/${t}/access_tokens`).pipe(nG(a),BK(o)),iq),c=yield*ap,l=G_(s.expiresAt)-c;if(l<=0||l>378e4)return yield*new IK({operation:i,message:`GitHub returned an installation token that is expired or exceeds the one-hour lifetime limit`,detail:`expires_at ${q_(s.expiresAt)} is ${l}ms from now`});l>QK&&(yield*A(`Accepted GitHub token clock skew; capped the local lease`,{installationId:t,operation:i,skewMillis:l-QK}));let u=yr(s.repositories,()=>[]);return r._tag===`SingleRepository`&&!(u.length===1&&u.every(e=>e.id===r.repositoryId))?yield*new IK({operation:i,message:`GitHub did not confirm that the worker token is scoped to exactly one repository`,detail:`expected repository ID ${r.repositoryId}, got [${u.map(e=>e.id).join(`, `)}]`}):new SK({value:_v(s.token),expiresAt:L_(c+Math.min(l,QK)),scope:r})}),a=k(`GitHubApp.installedRepositories`)(function*(e){let t=[];for(let r=1;;r+=1){let i=yield*n(`list-installation-repositories`,BW(`${RK}/installation/repositories?per_page=100&page=${r}`).pipe(BK(e.value)),rq);if(t.push(...i.repositories),t.length>=i.totalCount)return t;if(i.repositories.length===0)return yield*new IK({operation:`list-installation-repositories`,message:`GitHub returned an empty page before it listed total_count repositories`,detail:`page ${r} was empty after ${t.length} of ${i.totalCount} repositories`})}}),o=yield*Pk(y()),s=k(`GitHubApp.lease`)(()=>Ik(o,e=>E(function*(){let t=yield*ap;if(S(e)&&G_(e.value.token.expiresAt)-t>$K)return[e.value,e];let n=yield*r(),a={installation:n,token:yield*i(n.id,new yK)};return[a,b(a)]}))),c=yield*Pk(y()),l=k(`GitHubApp.botAccount`)(()=>Ik(c,e=>E(function*(){let{installation:t,token:r}=yield*s(),{appSlug:i}=t;if(yield*O({appSlug:i}),S(e)&&e.value.appSlug===i)return[e.value.account,e];let a=new WA(yield*n(`read-bot-account`,BW(`${RK}/users/${encodeURIComponent(`${i}[bot]`)}`).pipe(BK(r.value)),tq));return yield*A(`Read the App's bot account`,{appSlug:i,login:a.login,id:a.id}),[a,b({appSlug:i,account:a})]})));return{installation:k(`GitHubApp.installation`)(()=>tg(s(),e=>e.installation)),botAccount:l,installationToken:k(`GitHubApp.installationToken`)(()=>tg(s(),e=>e.token)),projectAccess:k(`GitHubApp.projectAccess`)(function*(e){let{installation:t,token:n}=yield*s();return jK(t,e,yield*a(n))}),workerToken:k(`GitHubApp.workerToken`)((e,t)=>i(e.installationId,new bK({repository:e.repository,repositoryId:e.repositoryId,permissions:t})))}}))},sq=new Set([`closedAt`,`createdAt`,`mergedAt`,`submittedAt`,`updatedAt`]),cq=e=>Array.isArray(e)?e.map(cq):Bw(LE)(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!sq.has(e)).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,cq(t)])):e,lq=6e4,uq=N({data:Qw(iT),errors:Qw(P(N({message:M,type:Qw(M)})))}),dq=k(`GitHub.queryGraphql`)(function*(e,t,n,r,i,a){let o=VW(`${RK}/graphql`).pipe(nG({query:r,variables:i}),BK(t.value)),s=yield*e.execute(o).pipe(ug(e=>VK(n,e))),c=yield*ap;if(s.status!==200)return yield*ZK(n,s,c);let l=yield*oG(uq)(s).pipe(ug(e=>WK(n,e.message)));if(l.errors!==void 0&&l.errors.length>0){if(l.errors.some(e=>e.type===`RATE_LIMITED`))return yield*new FK({operation:n,retryAt:L_(yr(XK(s.headers,c),()=>c+lq)),message:`GitHub GraphQL API rate limit exceeded`});if(!l.errors.every(e=>e.type===`NOT_FOUND`))return yield*WK(n,`GraphQL errors: ${l.errors.map(e=>e.message).join(`; `)}`)}return yield*Vw(a)(l.data).pipe(ug(e=>WK(n,e.message)))}),fq=z.pipe(L(`GitHubEntityTag`)),pq=z.pipe(L(`GitHubBaseRefName`)),mq=class extends V(`@usine/github/BaseRefHead`)({baseRefName:pq,sha:zk,entityTag:yE(fq)}){},hq=class e extends V(`@usine/github/PollCursor`)({entityTag:yE(fq),watermark:yE(vE)}){static empty=new e({entityTag:y(),watermark:y()})},gq=class extends H(`@usine/github/ChangedIssue`)(`ChangedIssue`,{number:R.check(HT(1)),updatedAt:_E}){},_q=class extends H(`@usine/github/ChangedPullRequest`)(`ChangedPullRequest`,{number:R.check(HT(1)),updatedAt:_E}){},vq=F([gq,_q]),yq=class extends H(`@usine/github/RepositoryNotModified`)(`RepositoryNotModified`,{cursor:hq,nextPollAt:B(_E),backoffUntil:B(_E).pipe(TT(T(y())))}){},bq=class extends H(`@usine/github/RepositoryChanges`)(`RepositoryChanges`,{cursor:hq,items:P(vq),backlog:cT,nextPollAt:B(_E),backoffUntil:B(_E).pipe(TT(T(y())))}){};F([yq,bq]);var xq=R.check(HT(1)),Sq=R.check(HT(0)),Cq=M.check(PT(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u,{message:`Expected a GitHub UTC timestamp`})),wq=(e,t)=>I(e).pipe(ST(e,{decode:ob(e=>e??t),encode:ob(e=>e)})),Tq={totalCount:0,nodes:[]},Eq=N({login:z}),Dq=I(Eq),Oq=N({totalCount:Sq,nodes:P(N({name:z}))}),kq=N({totalCount:Sq,nodes:P(N({author:Dq,body:M,createdAt:Cq}))}),Aq=N({number:xq,title:M,body:M,url:z,state:M,stateReason:I(M),createdAt:Cq,updatedAt:Cq,closedAt:I(Cq),author:Dq,issueType:I(N({name:M})),milestone:I(N({title:M})),labels:wq(Oq,Tq),assignees:N({totalCount:Sq,nodes:P(Eq)}),comments:kq,closedByPullRequestsReferences:wq(N({totalCount:Sq,nodes:P(N({number:xq,state:M,isDraft:cT,url:z}))}),Tq)}),jq=I(N({login:Qw(z)})),Mq=N({author:Dq,state:M,body:M,submittedAt:I(Cq),commit:I(N({oid:z}))}),Nq=N({author:Dq,body:M}),Pq=N({number:xq,title:M,body:M,url:z,state:M,isDraft:cT,merged:cT,createdAt:Cq,updatedAt:Cq,mergedAt:I(Cq),author:Dq,baseRefName:pq,headRefName:M,headRefOid:z,additions:Sq,deletions:Sq,changedFiles:Sq,reviewDecision:I(M),mergeable:M.pipe(DT(T(`UNKNOWN`))),mergeStateStatus:M.pipe(DT(T(`UNKNOWN`))),statusCheckRollup:I(N({state:M})),labels:wq(Oq,Tq),reviewRequests:wq(N({totalCount:Sq,nodes:P(N({requestedReviewer:jq}))}),Tq),reviews:wq(N({totalCount:Sq,nodes:P(Mq)}),Tq),reviewThreads:N({totalCount:Sq,nodes:P(N({isResolved:cT,isOutdated:cT,path:M,comments:N({totalCount:Sq,nodes:P(Nq)})}))}),comments:kq,closingIssuesReferences:wq(N({totalCount:Sq,nodes:P(N({number:xq,state:M}))}),Tq)}),Fq=M.check(PT(/^[a-f0-9]{64}$/u,{message:`Expected a SHA-256 content hash`})).pipe(L(`GitHubContentHash`)),Iq=class extends H(`@usine/github/IssueSnapshot`)(`IssueSnapshot`,{payload:Aq,contentHash:Fq}){},Lq=class extends H(`@usine/github/PullRequestSnapshot`)(`PullRequestSnapshot`,{payload:Pq,contentHash:Fq}){};F([Iq,Lq]);var Rq=z.pipe(L(`GitHubRepositoryLabelName`)),zq=M.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})).pipe(L(`GitHubRepositoryLabelColor`)),Bq=class extends V(`@usine/github/RepositoryLabel`)({name:Rq,color:zq,description:yE(M)}){},Vq=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),Hq=class extends V(`@usine/github/RepositoryLabelCatalog`)({entityTag:yE(fq),labels:P(Bq).check(Vq)}){},Uq=class extends H(`@usine/github/RepositoryLabelsNotModified`)(`RepositoryLabelsNotModified`,{}){};F([Hq,Uq]);var Wq=`
37
+ query UsineIssuePayload($owner: String!, $name: String!, $number: Int!) {
38
+ repository(owner: $owner, name: $name) {
39
+ issue(number: $number) {
40
+ number
41
+ title
42
+ body
43
+ url
44
+ state
45
+ stateReason
46
+ createdAt
47
+ updatedAt
48
+ closedAt
49
+ author { login }
50
+ issueType { name }
51
+ milestone { title }
52
+ labels(first: 50) {
53
+ totalCount
54
+ nodes { name }
55
+ }
56
+ assignees(first: 10) {
57
+ totalCount
58
+ nodes { login }
59
+ }
60
+ comments(last: 20) {
61
+ totalCount
62
+ nodes {
63
+ author { login }
64
+ body
65
+ createdAt
66
+ }
67
+ }
68
+ closedByPullRequestsReferences(first: 10, includeClosedPrs: true) {
69
+ totalCount
70
+ nodes {
71
+ number
72
+ state
73
+ isDraft
74
+ url
75
+ }
76
+ }
77
+ }
78
+ }
79
+ }
80
+ `,Gq=`
81
+ query UsinePullRequestPayload($owner: String!, $name: String!, $number: Int!) {
82
+ repository(owner: $owner, name: $name) {
83
+ pullRequest(number: $number) {
84
+ number
85
+ title
86
+ body
87
+ url
88
+ state
89
+ isDraft
90
+ merged
91
+ createdAt
92
+ updatedAt
93
+ mergedAt
94
+ author { login }
95
+ baseRefName
96
+ headRefName
97
+ headRefOid
98
+ additions
99
+ deletions
100
+ changedFiles
101
+ reviewDecision
102
+ mergeable
103
+ mergeStateStatus
104
+ statusCheckRollup { state }
105
+ labels(first: 50) {
106
+ totalCount
107
+ nodes { name }
108
+ }
109
+ reviewRequests(first: 10) {
110
+ totalCount
111
+ nodes {
112
+ requestedReviewer {
113
+ ... on User { login }
114
+ }
115
+ }
116
+ }
117
+ reviews(last: 20) {
118
+ totalCount
119
+ nodes {
120
+ author { login }
121
+ state
122
+ body
123
+ submittedAt
124
+ commit { oid }
125
+ }
126
+ }
127
+ reviewThreads(first: 50) {
128
+ totalCount
129
+ nodes {
130
+ isResolved
131
+ isOutdated
132
+ path
133
+ comments(first: 10) {
134
+ totalCount
135
+ nodes {
136
+ author { login }
137
+ body
138
+ }
139
+ }
140
+ }
141
+ }
142
+ comments(last: 20) {
143
+ totalCount
144
+ nodes {
145
+ author { login }
146
+ body
147
+ createdAt
148
+ }
149
+ }
150
+ closingIssuesReferences(first: 10) {
151
+ totalCount
152
+ nodes {
153
+ number
154
+ state
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
160
+ `,Kq=e=>{let t=Array.from({length:e},(e,t)=>t);return`
161
+ query UsineIssuesPresent($owner: String!, $name: String!, ${t.map(e=>`$n${e}: Int!`).join(`, `)}) {
162
+ repository(owner: $owner, name: $name) {
163
+ ${t.map(e=>`i${e}: issue(number: $n${e}) { number }`).join(`
164
+ `)}
165
+ }
166
+ }
167
+ `},qq=5e3,Jq=100,Yq=10,Xq=100,Zq=50,Qq=P(N({number:R.check(HT(1)),updatedAt:vE,pullRequest:Qw(iT)}).pipe(pT({updatedAt:`updated_at`,pullRequest:`pull_request`}))),$q=N({object:N({sha:zk})}),eJ=P(N({name:Rq,color:zq,description:I(M)})),tJ=({name:e,color:t,description:n})=>new Bq({name:e,color:t,description:C(n)}),nJ=N({repository:yE(N({issue:yE(Aq)}))}),rJ=N({repository:yE(N({pullRequest:yE(Pq)}))}),iJ=I(N({number:R})),aJ=e=>N({repository:yE(N(Object.fromEntries(Array.from({length:e},(e,t)=>[`i${t}`,iJ]))))}),oJ=e=>R_(e),sJ=e=>e.map(e=>e.pullRequest===void 0?new gq({number:e.number,updatedAt:e.updatedAt}):new _q({number:e.number,updatedAt:e.updatedAt})),cJ=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?y():oJ(Math.max(...t))},lJ=(e,t)=>cJ([KK(e[`retry-after`],t),qK(e,Jq)]),uJ=(e,t)=>cJ([JK(e,t),KK(e[`retry-after`],t),qK(e,Jq)]),dJ=e=>e===void 0?y():C(/<(?<url>[^>]+)>;\s*rel="next"/u.exec(e)?.groups?.url),fJ=e=>{let t=G_(e)-qq;return`${new Date(t-t%1e3).toISOString().slice(0,19)}Z`},pJ=(e,t)=>{let{name:n,owner:r}=Vk(e),i=new URL(`${RK}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues`);return i.searchParams.set(`state`,`all`),i.searchParams.set(`sort`,`updated`),i.searchParams.set(`direction`,`asc`),i.searchParams.set(`per_page`,`100`),S(t.watermark)&&i.searchParams.set(`since`,fJ(t.watermark.value)),i.toString()},mJ=e=>{let{name:t,owner:n}=Vk(e),r=new URL(`${RK}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`);return r.searchParams.set(`per_page`,`100`),r.toString()},hJ=(e,t)=>{let{name:n,owner:r}=Vk(e),i=t.split(`/`).map(encodeURIComponent).join(`/`);return`${RK}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/git/ref/heads/${i}`},gJ=(e,t)=>{let{name:n,owner:r}=Vk(e),i=new URL(`${RK}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues/${t}/labels`);return i.searchParams.set(`per_page`,`100`),i.toString()},_J=(e,t)=>{let n=t.map(({updatedAt:e})=>G_(e));return S(e.watermark)&&n.push(G_(e.watermark.value)),n.length===0?y():oJ(Math.max(...n))},vJ=class e extends Lr()(`@usine/github/GitHubPolling`){static layer=Yf(e,E(function*(){let e=yield*oq,t=yield*YO,n=yield*yG,r=yJ(t),i=k(`GitHubPolling.execute`)(function*(e,t){return yield*n.execute(t).pipe(ug(t=>VK(e,t)))}),a=k(`GitHubPolling.changesPage`)(function*(t){let n=yield*e.installationToken(),r=BW(t).pipe(BK(n.value)),a=yield*i(`poll-repository-changes`,r),o=yield*ap;return a.status===200?{items:sJ(yield*oG(Qq)(a).pipe(ug(e=>WK(`poll-repository-changes`,e.message)))),next:dJ(a.headers.link)}:yield*ZK(`poll-repository-changes`,a,o)}),o=k(`GitHubPolling.labelsPage`)(function*(t,n){let r=yield*e.installationToken(),a=BW(n).pipe(BK(r.value)),o=yield*i(t,a),s=yield*ap;return o.status===200?{labels:(yield*oG(eJ)(o).pipe(ug(e=>WK(t,e.message)))).map(tJ),next:dJ(o.headers.link)}:yield*ZK(t,o,s)}),s=k(`GitHubPolling.remainingLabelPages`)(function*(e,t){let n=[...t.labels],r=t.next,i=1;for(;S(r)&&i<Xq;){let t=yield*o(e,r.value);n.push(...t.labels),r=t.next,i+=1}return S(r)?yield*WK(e,`the GitHub label list has more than ${Xq} pages`):n.sort((e,t)=>e.name.localeCompare(t.name))}),c=k(`GitHubPolling.allLabels`)(function*(e,t){return yield*s(e,yield*o(e,t))}),l=k(`GitHubPolling.labels`)(function*(t,n){yield*O({repository:t});let r=yield*e.installationToken(),a=BW(mJ(t)).pipe(BK(r.value));S(n)&&(a=WW(a,`if-none-match`,n.value));let o=yield*i(`list-repository-labels`,a),c=yield*ap;if(o.status===304)return new Uq;if(o.status!==200)return yield*ZK(`list-repository-labels`,o,c);let l=yield*oG(eJ)(o).pipe(ug(e=>WK(`list-repository-labels`,e.message))),u=yield*s(`list-repository-labels`,{labels:l.map(tJ),next:dJ(o.headers.link)}),d=Uw(fq)(o.headers.etag);return x(d)&&(yield*$g(`GitHub omitted the label catalog ETag; next poll is unconditional`,{repository:t})),new Hq({entityTag:d,labels:u})}),u=k(`GitHubPolling.changes`)(function*(t,n){let r=yield*e.installationToken(),o=BW(pJ(t,n)).pipe(BK(r.value));S(n.entityTag)&&(o=WW(o,`if-none-match`,n.entityTag.value));let s=yield*i(`poll-repository-changes`,o),c=yield*ap,l=uJ(s.headers,c);if(s.status===304)return new yq({cursor:n,nextPollAt:l,backoffUntil:lJ(s.headers,c)});if(s.status!==200)return yield*ZK(`poll-repository-changes`,s,c);let u=sJ(yield*oG(Qq)(s).pipe(ug(e=>WK(`poll-repository-changes`,e.message)))),d=Uw(fq)(s.headers.etag);x(d)&&(yield*$g(`GitHub omitted the changes ETag; next poll is unconditional`,{repository:t}));let f=[...u],p=dJ(s.headers.link),m=1;for(;S(p)&&m<Yq;){let e=yield*a(p.value);f.push(...e.items),p=e.next,m+=1}let h=S(p);return h&&(yield*A(`GitHub changes walk hit the page cap; backlog remains`,{repository:t,pages:m,items:f.length})),new bq({cursor:new hq({entityTag:d,watermark:_J(n,f)}),items:f,backlog:h,nextPollAt:l,backoffUntil:lJ(s.headers,c)})}),d=k(`GitHubPolling.baseRefHead`)(function*(t,n,r){yield*O({repository:t,baseRefName:n});let a=yield*e.installationToken(),o=BW(hJ(t,n)).pipe(BK(a.value)),s=Or(r,({entityTag:e})=>e);S(s)&&(o=WW(o,`if-none-match`,s.value));let c=yield*i(`fetch-base-ref-head`,o),l=yield*ap;if(c.status===304&&S(r))return r.value;if(c.status!==200)return yield*ZK(`fetch-base-ref-head`,c,l);let u=yield*oG($q)(c).pipe(ug(e=>WK(`fetch-base-ref-head`,e.message))),d=Uw(fq)(c.headers.etag);return x(d)&&(yield*$g(`GitHub omitted the base branch ETag; next read is unconditional`,{repository:t,baseRefName:n})),new mq({baseRefName:n,sha:u.object.sha,entityTag:d})}),f=k(`GitHubPolling.graphql`)(function*(t,r,i,a,o){let s=yield*e.installationToken(),{name:c,owner:l}=Vk(r);return yield*dq(n,s,t,a,{owner:l,name:c,number:i},o)});return{changes:u,labels:l,baseRefHead:d,snapshot:k(`GitHubPolling.snapshot`)((e,t)=>E(function*(){let n=t=>WK(t,`repository "${e}" is null: deleted, renamed, or no longer accessible`),i=(n,r)=>new LK({operation:n,item:t.number,message:`GitHub ${r} ${e}#${t.number} was not found. It was deleted or transferred, or the GitHub App can no longer read it.`}),a=k(`GitHubPolling.completeItemLabels`)(function*(n){if(n.labels.nodes.length>=n.labels.totalCount)return n.labels;yield*j(`Completing truncated Item label connection for Board matching`,{repository:e,item:t.number,listedLabels:n.labels.nodes.length,totalLabels:n.labels.totalCount});let r=yield*c(`fetch-item-labels`,gJ(e,t.number));return{totalCount:r.length,nodes:r.map(({name:e})=>({name:e}))}});if(t._tag===`ChangedIssue`){let o=yield*f(`fetch-issue-snapshot`,e,t.number,Wq,nJ);if(x(o.repository))return yield*n(`fetch-issue-snapshot`);let s=o.repository.value.issue;if(x(s))return yield*i(`fetch-issue-snapshot`,`issue`);let c={...s.value,labels:yield*a(s.value)};return new Iq({payload:c,contentHash:yield*r(c)})}let o=yield*f(`fetch-pull-request-snapshot`,e,t.number,Gq,rJ);if(x(o.repository))return yield*n(`fetch-pull-request-snapshot`);let s=o.repository.value.pullRequest;if(x(s))return yield*i(`fetch-pull-request-snapshot`,`pull request`);let l={...s.value,labels:yield*a(s.value)};return new Lq({payload:l,contentHash:yield*r(l)})})),missingIssues:k(`GitHubPolling.missingIssues`)(function*(t,r){yield*O({repository:t,issues:r.length});let{name:i,owner:a}=Vk(t);return(yield*Nh(la(r,Zq),r=>E(function*(){let o=yield*e.installationToken(),s=yield*dq(n,o,`find-missing-issues`,Kq(r.length),{owner:a,name:i,...Object.fromEntries(r.map((e,t)=>[`n${t}`,e]))},aJ(r.length));if(x(s.repository))return yield*WK(`find-missing-issues`,`repository "${t}" is null: deleted, renamed, or no longer accessible`);let c=s.repository.value;return r.filter((e,t)=>c[`i${t}`]===null)}))).flat()})}}))},yJ=e=>k(`GitHubPolling.contentHash`)(function*(t){let n=new TextEncoder().encode(JSON.stringify(cq(t))),r=yield*e.digest(`SHA-256`,n).pipe(dg);return Fq.make(Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``))}),bJ=z.pipe(L(`BoardLaneId`)),xJ=bT([`authored`,`proposed`,`fallback`]),SJ=class extends V(`@usine/orchestrator/BoardItemLink`)({itemKey:bN,kind:bT([`issue`,`pr`]),number:xN,title:M,url:z,state:cV}){},CJ=class extends V(`@usine/orchestrator/BoardPullRequestView`)({number:xN,url:z,state:bT([`pr-open`,`pr-merged`])}){},wJ=class extends V(`@usine/orchestrator/BoardTaskView`)({...SJ.fields,labels:P(nV),items:P(SJ).check(qT()),pullRequest:I(CJ),runs:P(eH),run:I(eH),needsYou:cT,conflicting:cT,loops:P(Kk),usage:HV}){},TJ={id:bJ,name:sV,sources:P(pV),origin:xJ,items:P(wJ)},EJ=class extends H(`@usine/orchestrator/WritableBoardLaneView`)(`WritableBoardLane`,{...TJ,origin:nT(`authored`),labels:P(nV).check(qT())}){},DJ=class extends H(`@usine/orchestrator/ReadOnlyBoardLaneView`)(`ReadOnlyBoardLane`,TJ){},OJ=F([EJ,DJ]),kJ=class extends NE(`@usine/orchestrator/BoardProjectionError`)(`BoardProjectionError`,{repository:Lk,itemKey:bN,message:z}){},AJ=class extends V(`@usine/orchestrator/BoardView`)({lanes:P(OJ),failures:P(kJ)}){},jJ=class extends V(`@usine/orchestrator/LabelView`)({name:nV,color:I(M),description:I(M)}){};V(`@usine/orchestrator/BoardMove`)({repository:Lk,item:xN,toLane:bJ});var MJ=class extends NE(`@usine/orchestrator/BoardProjectNotFoundError`)(`BoardProjectNotFoundError`,{repository:Lk}){},NJ=class extends NE(`@usine/orchestrator/BoardItemNotFoundError`)(`BoardItemNotFoundError`,{repository:Lk,item:xN}){};NE(`@usine/orchestrator/BoardLaneNotFoundError`)(`BoardLaneNotFoundError`,{repository:Lk,lane:bJ}),NE(`@usine/orchestrator/BoardLaneReadOnlyError`)(`BoardLaneReadOnlyError`,{repository:Lk,lane:bJ});var PJ=Vw(P(nV)),FJ=N({labels:Aq.fields.labels}),IJ=N({labels:Pq.fields.labels}),LJ=(e,t)=>Vw(e===`issue`?FJ:IJ)(t).pipe(D(({labels:e})=>PJ(e.nodes.map(({name:e})=>e)))),RJ=(e,t)=>new kJ({repository:e.repository,itemKey:e.itemKey,message:t}),zJ=e=>E(function*(){let t=S(e.goneAt);if(e.source===`issue`){let n=yield*Vw(Aq)(e.payload).pipe(ug(t=>RJ(e,t.message)));return{itemKey:e.itemKey,kind:`issue`,number:xN.make(e.number),title:n.title,url:n.url,state:n.state===`OPEN`&&!t?`issue-open`:`issue-closed`,linkedPullRequests:n.closedByPullRequestsReferences.nodes.map(({url:e})=>e),labels:yield*PJ(n.labels.nodes.map(({name:e})=>e)).pipe(ug(t=>RJ(e,t.message))),conflicting:!1}}if(e.source===`pr`){let n=yield*Vw(Pq)(e.payload).pipe(ug(t=>RJ(e,t.message))),r=n.merged?`pr-merged`:n.state===`OPEN`&&!t?`pr-open`:`pr-closed`;return{itemKey:e.itemKey,kind:`pr`,number:xN.make(e.number),title:n.title,url:n.url,state:r,linkedPullRequests:[],labels:yield*PJ(n.labels.nodes.map(({name:e})=>e)).pipe(ug(t=>RJ(e,t.message))),conflicting:r===`pr-open`&&n.mergeable===`CONFLICTING`}}return yield*RJ(e,`Unsupported item projection source: ${e.source}`)}),BJ=k(`settledItemState`)(function*(e){yield*O({itemKey:e});let t=yield*(yield*mU).get(e);if(x(t))return y();let n=yield*Qh(zJ(t.value));if(Ei(n))return yield*j(`Stored Item payload doesn't decode; treating the Item as open`,{itemKey:e,message:n.failure.message}),y();let{state:r}=n.success;return dV(r)?b(r):y()}),VJ=(e,t)=>e.canApprove||e.canResolveFailure&&!t,HJ=Uw(rE),UJ=e=>new SJ({itemKey:e.itemKey,kind:e.kind,number:e.number,title:e.title,url:e.url,state:e.state}),WJ=(e,t,n,r,i,a)=>{let o=ua(n,({itemKey:e})=>e),s=t.map(e=>({item:e,runs:o[e.itemKey]??[],related:new Set})),c=`/${Hk(e)}/pull/`,l=new Map(s.filter(({item:e})=>e.kind===`pr`).map(e=>[`${c}${e.item.number}`,e])),u=new Set(r);for(let e of s){if(e.item.kind!==`issue`)continue;let t=[...e.item.linkedPullRequests,...e.runs.flatMap(({pullRequestUrl:e})=>e===null?[]:[e])];for(let n of t){let t=HJ(n);if(x(t)||t.value.protocol!==`https:`||t.value.host!==`github.com`)continue;let r=l.get(t.value.pathname.toLowerCase());r!==void 0&&(e.related.add(r),r.related.add(e))}}let d=new Set,f=[];for(let e of s){if(d.has(e))continue;d.add(e);let t=[e];for(let e of t)for(let n of e.related)d.has(n)||(d.add(n),t.push(n));let n=ra(t,({item:e},{item:t})=>(e.kind===t.kind?0:e.kind===`issue`?-1:1)||lr(e.number,t.number)),r=n[0],o=t.flatMap(({item:e,runs:t})=>t.map(t=>({item:e,run:t}))).sort(({run:e},{run:t})=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),s=o.find(({run:e})=>e.canCancel),c=t.filter(({item:e})=>e.kind===`pr`).sort(({item:e},{item:t})=>Number(t.state===`pr-open`)-Number(e.state===`pr-open`)||t.number-e.number),l=s?.item??c[0]?.item??r.item,[p=null]=c.flatMap(({item:{number:e,url:t,state:n}})=>n===`pr-open`||n===`pr-merged`?[new CJ({number:e,url:t,state:n})]:[]),m=o.find(({item:e,run:t})=>VJ(t,dV(e.state)))??s??o[0],h=o.map(({run:e})=>e).reverse(),g=new wJ({...UJ(l),title:r.item.title,labels:l.labels,items:n.map(({item:e})=>UJ(e)),pullRequest:p,runs:h,run:m?.run??null,needsYou:o.some(({item:e,run:t})=>VJ(t,dV(e.state)))||t.some(({item:e})=>u.has(e.itemKey)),conflicting:l.conflicting,loops:[...new Set(n.flatMap(({item:e})=>i.get(e.itemKey)??[]))],usage:qV(h,a)});f.push({view:g,running:s?.run.state===`Running`?s.run:void 0})}return f},GJ=e=>e.flatMap(e=>`label`in e?[e.label]:[]),KJ=e=>e.flatMap(e=>`state`in e?[e.state]:[]),qJ=e=>[...e].sort((e,t)=>e.localeCompare(t)).map(e=>nV.make(e)).map(e=>({lane:new mV({name:sV.make(e),sources:[new fV({label:e})]}),origin:`proposed`})),JJ=(e,t)=>e.lanes.length>0?e.lanes.map(e=>({lane:e,origin:`authored`})):qJ(t),YJ=e=>bJ.make(`${e.origin}:${e.lane.name}`),XJ=(e,t)=>{let n=new Set(e.labels.map(rV));return t.find(({lane:e})=>GJ(e.sources).some(e=>n.has(rV(e))))},ZJ=(e,t)=>t.find(({lane:t})=>KJ(t.sources).includes(e.state)),QJ=(e,t)=>dV(e.state)?ZJ(e,t):XJ(e,t)??ZJ(e,t),$J=k(`Board.runningLane`)(function*(e,t,n,r,i){let a={repository:e.name,itemKey:t.itemKey,runId:n.id,loop:n.loop};if(yield*O(a),dV(t.state))return;let o=XJ(t,r);if(o!==void 0)return yield*j(`Placing the running card in the lane its Item's labels match`,{...a,lane:o.lane.name}),o;let s=i.get(n.id);if(s===void 0){yield*j(`No Event read for the card's running Run; placing it by its Item's state`,a);return}let c=yield*LJ(t.kind,s.payload).pipe(tg(b),ag(e=>$g(`The running Run's Event has no labels to read; placing its card by its Item's state`,{...a,eventId:s.id,errorTag:e._tag,message:e.message}).pipe(ng(y()))));if(x(c))return;let l=XJ({labels:c.value},r);return yield*j(l===void 0?`No lane label when the card's running Run was triggered; placing it by its Item's state`:`Keeping the card in the lane its running Run was triggered from`,{...a,lane:l?.lane.name??`none`}),l}),eY=k(`Board.project`)((e,t,n,r,i=[],a=new Map,o=new Map,s=new Map)=>E(function*(){yield*O({repository:e.name});let c=yield*Nh(n,e=>zJ(e).pipe(Qh)),l=[],u=[];for(let e of c)Di(e)?l.push(e.success):(u.push(e.failure),yield*e_(`Item projection quarantined from Board; siblings continue`,{repository:e.failure.repository,itemKey:e.failure.itemKey,errorTag:e.failure._tag,message:e.failure.message}));let d=JJ(e,t),f=WJ(e.name,l,r,i,a,o);yield*j(`Projected Task cards from linked Items`,{repository:e.name,items:l.length,tasks:f.length,runs:r.length,watchedTasks:f.filter(({view:e})=>e.loops.length>0).length,runningTasks:f.filter(({running:e})=>e!==void 0).length});let p=new Map;for(let e of d)p.set(YJ(e),[]);let m=[];for(let{view:t,running:n}of f){let r=(n===void 0?void 0:yield*$J(e,t,n,d,s))??QJ(t,d);r===void 0?m.push(t):p.get(YJ(r))?.push(t)}let h=e=>e.sort((e,t)=>t.number-e.number);return new AJ({failures:u,lanes:[...d.map(e=>{let t=GJ(e.lane.sources),n={id:YJ(e),name:e.lane.name,sources:e.lane.sources,origin:e.origin,items:h(p.get(YJ(e))??[])};return e.origin===`authored`&&t.length>0?new EJ({...n,origin:e.origin,labels:t}):new DJ(n)}),new DJ({id:bJ.make(`fallback:unmapped`),name:sV.make(`Unmapped`),sources:[],origin:`fallback`,items:h(m)})]})})),tY=eV(`Expected a non-blank registry tag`).pipe(L(`RegistryTag`)),nY=R.check(HT(1)),rY=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique names`}),iY=e=>`label`in e?`label:${rV(e.label)}`:`state:${e.state}`,aY=NT(e=>{let t=e.flatMap(({sources:e})=>e.map(iY));return new Set(t).size===t.length},{message:`Expected each lane source in only one lane`}),oY=P(mV).check(rY,aY),sY=NT(e=>new Set(e.map(({name:e})=>rV(e))).size===e.length,{message:`Expected unique GitHub label names`}),cY=P(oV).check(sY),lY=class extends V(`@usine/config/ManagedRepo`)({name:Lk,tags:P(tY).check(XT()).pipe(DT(T([]))),lanes:oY.pipe(DT(T([])))}){},uY=nY.pipe(DT(T(1))),dY=class extends V(`@usine/config/LocalWorker`)({name:BA,kind:nT(`local`),maxConcurrentAttempts:uY}){},fY=class extends V(`@usine/config/ExeDevWorker`)({name:BA,kind:nT(`exe.dev`),maxConcurrentAttempts:uY}){},pY=M.check(PT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected an environment variable name`})).pipe(L(`EnvironmentVariableName`)),mY=class extends V(`@usine/config/WorkerGateway`)({domain:YA,destination:GA,adminPort:XA.pipe(DT(T(7070))),adminTokenEnv:pY,llmProviders:P(ZA).check(XT()).pipe(DT(T([])))}){},hY=class extends V(`@usine/config/WorkerContainer`)({image:xE($A),cpus:xE(tj),memoryMib:xE(nj),pids:xE(rj)}){},gY=class extends V(`@usine/config/ProviderApiKeys`)({anthropic:xE(pY),openai:xE(pY)}){}.pipe(DT(T({}))),_Y=class extends V(`@usine/config/HetznerProvisioner`)({provider:nT(`hetzner`),tokenEnv:pY,serverType:dj,location:fj,image:pj,network:xE(mj),firewall:xE(mj),sshKey:mj,sshUser:_j.pipe(DT(T(`usine`))),labels:gj.pipe(DT(T({}))),apiKeys:gY}){},vY=class extends V(`@usine/config/BoatProvisioner`)({provider:nT(`boat`),tokenEnv:pY,size:vj.pipe(DT(T(`default`))),apiKeys:gY}){};F([_Y,vY]);var yY=F([_Y.pipe(pT({tokenEnv:`token_env`,serverType:`server_type`,sshKey:`ssh_key`,sshUser:`ssh_user`,apiKeys:`api_keys`})),vY.pipe(pT({tokenEnv:`token_env`,apiKeys:`api_keys`}))]),bY=class extends V(`@usine/config/SshWorker`)({name:BA,kind:nT(`ssh`),maxConcurrentAttempts:uY,destination:xE(GA),provisioner:xE(yY),identityFile:xE(qA),port:xE(KA),root:JA,gateway:xE(mY.pipe(pT({adminPort:`admin_port`,adminTokenEnv:`admin_token_env`,llmProviders:`llm_providers`}))),container:hY.pipe(pT({memoryMib:`memory_mib`}),DT(T({})))}){},xY=e=>{let t=wr(e.provisioner);if(t===void 0)return x(e.destination)?`SSH worker "${e.name}" needs a destination or a provisioner`:void 0;if(S(e.destination))return`SSH worker "${e.name}" sets both destination and provisioner; a provisioned worker creates its machines, so remove destination`;if(S(e.port))return`SSH worker "${e.name}" sets port, which a provisioned worker takes from its provider`;switch(t.provider){case`hetzner`:return S(e.gateway)&&x(t.network)?`SSH worker "${e.name}" has a gateway, so its provisioner needs the gateway's private network in network`:void 0;case`boat`:return S(e.gateway)?`SSH worker "${e.name}" has a Boat provisioner and a gateway; Boat has no network rules, so no gateway can be its machines' only way out. Remove gateway.`:x(e.identityFile)?`SSH worker "${e.name}" has a Boat provisioner and needs identity_file, whose .pub file usine adds to each sandbox`:void 0}},SY=rE.check(NT(e=>e.protocol===`https:`,{message:`Expected an https URL`}),NT(e=>e.username===``&&e.password===``&&e.search===``&&e.hash===``&&e.pathname===`/`,{message:`Expected the Worker's origin, without a path, credentials, or query string`})),CY=class extends V(`@usine/config/CloudflareLlmProviderKey`)({provider:cj,apiKeyEnv:pY}){},wY=NT(e=>new Set(e.map(({provider:e})=>e)).size===e.length,{message:`Expected each provider once`}),TY=class extends V(`@usine/config/CloudflareWorker`)({name:BA,kind:nT(`cloudflare`),maxConcurrentAttempts:uY,workerUrl:SY,accessClientIdEnv:pY,accessClientSecretEnv:pY,image:sj,instanceType:oj.pipe(DT(T(`standard-4`))),llmProviders:P(CY.pipe(pT({apiKeyEnv:`api_key_env`}))).check(wY).pipe(DT(T([])))}){};F([dY,fY,bY,TY]);var EY=class extends V(`@usine/config/Settings`)({pollInterval:nY.pipe(DT(T(60))),maxChildren:Sj.pipe(DT(T(4))),maxAttemptMinutes:xE(nY),maxAttemptTokens:xE(nY),parentModel:xE(jA),parentEffort:xE(NA)}){},DY=F([N({mode:nT(`off`)}),N({mode:nT(`deliveries`)}),N({mode:nT(`endpoint`),publicUrl:rE}).pipe(pT({publicUrl:`public_url`}))]),OY=rE.check(NT(e=>e.protocol===`http:`||e.protocol===`https:`,{message:`Expected an http or https URL`}),NT(e=>e.username===``&&e.password===``&&e.search===``,{message:`Expected a URL without a username, password, or query string; authenticate in a collector next to usine up`})),kY=class extends V(`@usine/config/Tracing`)({otlpUrl:OY,serviceName:eV(`Expected a non-blank service name`).pipe(DT(T(`usine`)))}){},AY=EY.pipe(pT({pollInterval:`poll_interval`,maxChildren:`max_children`,maxAttemptMinutes:`max_attempt_minutes`,maxAttemptTokens:`max_attempt_tokens`,parentModel:`parent_model`,parentEffort:`parent_effort`})),jY=F([dY.pipe(pT({maxConcurrentAttempts:`max_concurrent_attempts`})),fY.pipe(pT({maxConcurrentAttempts:`max_concurrent_attempts`})),bY.pipe(pT({maxConcurrentAttempts:`max_concurrent_attempts`,identityFile:`identity_file`})).check(NT(e=>xY(e)??!0)),TY.pipe(pT({maxConcurrentAttempts:`max_concurrent_attempts`,workerUrl:`worker_url`,accessClientIdEnv:`access_client_id_env`,accessClientSecretEnv:`access_client_secret_env`,instanceType:`instance_type`,llmProviders:`llm_providers`}))]),MY=P(lY).check(tV(e=>e.name)),NY=P(jY).check(qT(),rY),PY=class extends V(`@usine/config/UsineConfig`)({version:nT(1),labels:cY.pipe(DT(T([]))),repos:MY,settings:AY.pipe(DT(T({}))),workers:NY.pipe(DT(T([{name:`local`,kind:`local`}]))),webhooks:DY.pipe(DT(T({mode:`off`}))),operator:xE(qj),tracing:xE(kY.pipe(pT({otlpUrl:`otlp_url`,serviceName:`service_name`})))}){},FY=class extends V(`@usine/config/Selector`)({repos:xE(P(Lk).check(qT(),tV(e=>e))),tags:xE(P(tY).check(qT(),XT()))}){}.check(NT(e=>S(e.repos)||S(e.tags),{message:`Expected selector.repos, selector.tags, or both`})),IY=(e,t)=>vr(e,{onNone:()=>!0,onSome:e=>{let n=vr(e.repos,{onNone:()=>!0,onSome:e=>e.some(e=>Hk(e)===Hk(t.name))}),r=vr(e.tags,{onNone:()=>!0,onSome:e=>e.some(e=>t.tags.includes(e))});return n&&r}}),LY=M.check(PT(/^(?:[A-Za-z_][A-Za-z0-9_.]*|list<[A-Za-z_][A-Za-z0-9_.]*>|map<[A-Za-z_][A-Za-z0-9_.]*,[A-Za-z_][A-Za-z0-9_.]*>)$/u,{message:`Expected a CEL type reference`})).pipe(L(`CelTypeReference`)),RY=M.check(PT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected a CEL identifier`})),zY=M.check(PT(/^[A-Za-z_][A-Za-z0-9_.]*$/u,{message:`Expected a CEL object-type name`})),BY=e=>NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:e}),VY=class extends V(`@usine/expression/ObjectField`)({name:RY,type:LY,nullable:cT.pipe(TT(T(!1)))}){},HY=class extends V(`@usine/expression/ObjectType`)({name:zY,fields:P(VY).check(BY(`Expected unique CEL object-field names`))}){},UY=class extends V(`@usine/expression/Variable`)({name:RY,type:LY}){},WY=class extends V(`@usine/expression/Environment`)({types:P(HY).check(BY(`Expected unique CEL object-type names`)),variables:P(UY).check(BY(`Expected unique CEL variable names`))}){},GY=M.check(PT(/\S/u,{message:`Expected a non-blank CEL expression`})).pipe(L(`ExpressionSource`)),KY=R.check(HT(0)),qY=bT([`check_failed`,`parse_error`,`type_error`,`unexpected_result_type`]);F([class extends NE(`@usine/expression/ExpressionCheckError`)(`ExpressionCheckError`,{source:GY,code:qY,message:z,position:B(KY)}){},class extends NE(`@usine/expression/ExpressionEvaluationError`)(`ExpressionEvaluationError`,{source:GY,message:z}){}]),F([M,sT,lT,cT,aT]);var JY=class extends Lr()(`@usine/expression/ExpressionEngine`){},YY=z.pipe(L(`InstancePath`)),XY=bT([`expression`,`frontmatter`,`read`,`reference`,`schema`,`yaml`]),ZY=class extends NE(`@usine/config/ConfigFileError`)(`ConfigFileError`,{file:YY,stage:XY,expression:xE(GY),message:z}){};F([ZY,class extends NE(`@usine/config/FactoryConfigError`)(`FactoryConfigError`,{file:YY,stage:XY,message:z}){}]);var QY=(e,t,n)=>{let r=`${t}---`,i=e.indexOf(r,n);for(;i>=0;){let n=i+r.length;if(n===e.length||e.startsWith(t,n))return i;i=e.indexOf(r,n)}return-1},$Y=(e,t)=>{let n=t.startsWith(`---\r
168
+ `)?`\r
169
+ `:t.startsWith(`---
170
+ `)?`
171
+ `:void 0;if(n===void 0)return new ZY({file:e,stage:`frontmatter`,expression:y(),message:`Expected the file to start with a YAML frontmatter delimiter (---)`});let r=3+n.length,i=`${n}---`,a=QY(t,n,r);if(a<0)return new ZY({file:e,stage:`frontmatter`,expression:y(),message:`Expected a closing YAML frontmatter delimiter (---)`});let o=a+i.length,s=t.startsWith(n,o)?o+n.length:o;return T({yaml:t.slice(r,a),body:t.slice(s),newline:n})},eX=class extends V(`@usine/config/AgentFile`)({name:FA,harness:MA,model:jA,effort:NA,parentModel:B(jA),parentEffort:B(NA),persona:IA}){get agent(){return new LA({name:this.name,persona:this.persona,brain:new PA({harness:this.harness,model:this.model,effort:this.effort}),parentModel:this.parentModel,parentEffort:this.parentEffort})}},tX=class extends V(`@usine/config/InvalidAgent`)({file:YY,error:ZY}){},nX=M.check(NT(e=>e.trim().split(/\s+/u).length===5&&Di(Em(e)),{message:`Expected a valid five-field cron expression`})).pipe(L(`Cron`)),rX=M.check(NT(e=>S(V_(e)),{message:`Expected an IANA time-zone name`})).pipe(L(`TimeZone`)),iX=class extends V(`@usine/config/IssueTrigger`)({on:nT(`issue`),if:GY}){},aX=class extends V(`@usine/config/PullRequestTrigger`)({on:nT(`pr`),if:GY}){},oX=class extends V(`@usine/config/ScheduleTrigger`)({on:nT(`schedule`),if:GY,cron:nX,tz:rX.pipe(DT(T(`UTC`)))}){},sX=F([iX,aX,oX]),cX=PT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case file name`}),lX=Kk.check(cX),uX=eV(`Expected a non-blank Markdown prompt`).pipe(L(`PromptTemplate`)),dX=R.check(HT(1,{message:`Expected a priority of at least 1`})).pipe(L(`LoopPriority`)),fX=class extends V(`@usine/config/LoopFile`)({name:lX,trigger:sX,selector:B(FY),approval:Jk,maxCycles:qN.pipe(DT(T(YN)),TT(T(YN))),permissions:Xk.pipe(DT(T(`write`)),TT(T(`write`))),priority:B(dX).pipe(TT(T(y()))),step:eM,agent:FA,body:uX}){},pX=class extends V(`@usine/config/QuarantinedLoop`)({file:YY,error:ZY}){},mX=e=>YY.make(`loops/${e}.md`),hX=class extends H(`@usine/config/UndeclaredLaneLabelWarning`)(`UndeclaredLaneLabelWarning`,{repository:Lk,lane:sV,label:nV}){},gX=class extends H(`@usine/config/UndeclaredTriggerLabelWarning`)(`UndeclaredTriggerLabelWarning`,{loop:fX.fields.name,label:nV}){};F([hX,gX]);var _X=Gw(LY),vX=(e,t)=>new HY({name:e,fields:t.map(([e,t,n])=>new VY({name:e,type:_X(t),nullable:n===`nullable`}))}),yX=vX(`Actor`,[[`login`,`string`]]),bX=vX(`Label`,[[`name`,`string`]]),xX=vX(`Milestone`,[[`title`,`string`]]),SX=vX(`IssueType`,[[`name`,`string`]]),CX=vX(`Commit`,[[`oid`,`string`]]),wX=vX(`RepoContext`,[[`name`,`string`],[`owner`,`string`],[`url`,`string`]]),TX=vX(`Labels`,[[`totalCount`,`int`],[`nodes`,`list<Label>`]]),EX=vX(`Assignees`,[[`totalCount`,`int`],[`nodes`,`list<Actor>`]]),DX=vX(`IssueComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),OX=vX(`IssueComments`,[[`totalCount`,`int`],[`nodes`,`list<IssueComment>`]]),kX=vX(`PullRequestReference`,[[`number`,`int`],[`state`,`string`],[`isDraft`,`bool`],[`url`,`string`]]),AX=vX(`PullRequestReferences`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestReference>`]]),jX=vX(`IssuePayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`stateReason`,`string`,`nullable`],[`createdAt`,`string`],[`updatedAt`,`string`],[`closedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`issueType`,`IssueType`,`nullable`],[`milestone`,`Milestone`,`nullable`],[`labels`,`Labels`],[`assignees`,`Assignees`],[`comments`,`IssueComments`],[`closedByPullRequestsReferences`,`PullRequestReferences`]]),MX=vX(`RequestedReviewer`,[[`login`,`string`,`nullable`]]),NX=vX(`ReviewRequest`,[[`requestedReviewer`,`RequestedReviewer`,`nullable`]]),PX=vX(`ReviewRequests`,[[`totalCount`,`int`],[`nodes`,`list<ReviewRequest>`]]),FX=vX(`Review`,[[`author`,`Actor`,`nullable`],[`state`,`string`],[`body`,`string`],[`submittedAt`,`string`,`nullable`],[`commit`,`Commit`,`nullable`]]),IX=vX(`Reviews`,[[`totalCount`,`int`],[`nodes`,`list<Review>`]]),LX=vX(`ReviewThreadComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`]]),RX=vX(`ReviewThreadComments`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThreadComment>`]]),zX=vX(`ReviewThread`,[[`isResolved`,`bool`],[`isOutdated`,`bool`],[`path`,`string`],[`comments`,`ReviewThreadComments`]]),BX=vX(`ReviewThreads`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThread>`]]),VX=vX(`PullRequestComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),HX=vX(`PullRequestComments`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestComment>`]]),UX=vX(`ClosingIssueReference`,[[`number`,`int`],[`state`,`string`]]),WX=vX(`ClosingIssueReferences`,[[`totalCount`,`int`],[`nodes`,`list<ClosingIssueReference>`]]),GX=vX(`StatusCheckRollup`,[[`state`,`string`]]),KX=vX(`PullRequestPayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`isDraft`,`bool`],[`merged`,`bool`],[`createdAt`,`string`],[`updatedAt`,`string`],[`mergedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`baseRefName`,`string`],[`headRefName`,`string`],[`headRefOid`,`string`],[`additions`,`int`],[`deletions`,`int`],[`changedFiles`,`int`],[`reviewDecision`,`string`,`nullable`],[`mergeable`,`string`],[`mergeStateStatus`,`string`],[`statusCheckRollup`,`StatusCheckRollup`,`nullable`],[`labels`,`Labels`],[`reviewRequests`,`ReviewRequests`],[`reviews`,`Reviews`],[`reviewThreads`,`ReviewThreads`],[`comments`,`PullRequestComments`],[`closingIssuesReferences`,`ClosingIssueReferences`]]),qX=vX(`Tick`,[[`scheduledAt`,`string`],[`scheduledAtLocal`,`string`],[`cron`,`string`],[`tz`,`string`]]),JX=vX(`SchedulePayload`,[[`tick`,`Tick`]]),YX=(e,t)=>new WY({types:[wX,...e],variables:[new UY({name:`repo`,type:_X(`RepoContext`)}),new UY({name:`item`,type:_X(t)})]}),XX=YX([yX,bX,xX,SX,TX,EX,DX,OX,kX,AX,jX],`IssuePayload`),ZX=YX([yX,bX,CX,TX,MX,NX,PX,FX,IX,LX,RX,zX,BX,VX,HX,UX,WX,GX,KX],`PullRequestPayload`),QX=YX([qX,JX],`SchedulePayload`),$X=e=>{switch(e){case`issue`:return XX;case`pr`:return ZX;case`schedule`:return QX}},eZ=e=>{let{owner:t}=Vk(e.name);return{name:e.name,owner:t,url:`https://github.com/${e.name}`}},tZ=Symbol.for(`yaml.alias`),nZ=Symbol.for(`yaml.document`),rZ=Symbol.for(`yaml.map`),iZ=Symbol.for(`yaml.pair`),aZ=Symbol.for(`yaml.scalar`),oZ=Symbol.for(`yaml.seq`),sZ=Symbol.for(`yaml.node.type`),cZ=e=>!!e&&typeof e==`object`&&e[sZ]===tZ,lZ=e=>!!e&&typeof e==`object`&&e[sZ]===nZ,uZ=e=>!!e&&typeof e==`object`&&e[sZ]===rZ,dZ=e=>!!e&&typeof e==`object`&&e[sZ]===iZ,fZ=e=>!!e&&typeof e==`object`&&e[sZ]===aZ,pZ=e=>!!e&&typeof e==`object`&&e[sZ]===oZ;function mZ(e){if(e&&typeof e==`object`)switch(e[sZ]){case rZ:case oZ:return!0}return!1}function hZ(e){if(e&&typeof e==`object`)switch(e[sZ]){case tZ:case rZ:case aZ:case oZ:return!0}return!1}var gZ=e=>(fZ(e)||mZ(e))&&!!e.anchor,_Z=Symbol(`break visit`),vZ=Symbol(`skip children`),yZ=Symbol(`remove node`);function bZ(e,t){let n=SZ(t);lZ(e)?xZ(null,e.contents,n,Object.freeze([e]))===yZ&&(e.contents=null):xZ(null,e,n,Object.freeze([]))}bZ.BREAK=_Z,bZ.SKIP=vZ,bZ.REMOVE=yZ;function xZ(e,t,n,r){let i=CZ(e,t,n,r);if(hZ(i)||dZ(i))return wZ(e,r,i),xZ(e,i,n,r);if(typeof i!=`symbol`){if(mZ(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=xZ(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===_Z)return _Z;else i===yZ&&(t.items.splice(e,1),--e)}}else if(dZ(t)){r=Object.freeze(r.concat(t));let e=xZ(`key`,t.key,n,r);if(e===_Z)return _Z;e===yZ&&(t.key=null);let i=xZ(`value`,t.value,n,r);if(i===_Z)return _Z;i===yZ&&(t.value=null)}}return i}function SZ(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function CZ(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(uZ(t))return n.Map?.(e,t,r);if(pZ(t))return n.Seq?.(e,t,r);if(dZ(t))return n.Pair?.(e,t,r);if(fZ(t))return n.Scalar?.(e,t,r);if(cZ(t))return n.Alias?.(e,t,r)}function wZ(e,t,n){let r=t[t.length-1];if(mZ(r))r.items[e]=n;else if(dZ(r))e===`key`?r.key=n:r.value=n;else if(lZ(r))r.contents=n;else{let e=cZ(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var TZ={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},EZ=e=>e.replace(/[!,[\]{}]/g,e=>TZ[e]),DZ=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+EZ(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&hZ(e.contents)){let t={};bZ(e.contents,(e,n)=>{hZ(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
172
+ `)}};DZ.defaultYaml={explicit:!1,version:`1.2`},DZ.defaultTags={"!!":`tag:yaml.org,2002:`};function OZ(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function kZ(e){let t=new Set;return bZ(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function AZ(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function jZ(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=kZ(e);let a=AZ(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(fZ(t.node)||mZ(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function MZ(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=MZ(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=MZ(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=MZ(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=MZ(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function NZ(e,t,n){if(Array.isArray(e))return e.map((e,t)=>NZ(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!gZ(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var PZ=class{constructor(e){Object.defineProperty(this,sZ,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!lZ(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=NZ(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?MZ(i,{"":o},``,o):o}},FZ=class extends PZ{constructor(e){super(tZ),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],bZ(e,{Node:(e,t)=>{(cZ(t)||gZ(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(NZ(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=IZ(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(OZ(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function IZ(e,t,n){if(cZ(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(mZ(t)){let r=0;for(let i of t.items){let t=IZ(e,i,n);t>r&&(r=t)}return r}if(dZ(t)){let r=IZ(e,t.key,n),i=IZ(e,t.value,n);return Math.max(r,i)}return 1}var LZ=e=>!e||typeof e!=`function`&&typeof e!=`object`,RZ=class extends PZ{constructor(e){super(aZ),this.value=e}toJSON(e,t){return t?.keep?this.value:NZ(this.value,e,t)}toString(){return String(this.value)}};RZ.BLOCK_FOLDED=`BLOCK_FOLDED`,RZ.BLOCK_LITERAL=`BLOCK_LITERAL`,RZ.PLAIN=`PLAIN`,RZ.QUOTE_DOUBLE=`QUOTE_DOUBLE`,RZ.QUOTE_SINGLE=`QUOTE_SINGLE`;var zZ=`tag:yaml.org,2002:`;function BZ(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function VZ(e,t,n){if(lZ(e)&&(e=e.contents),hZ(e))return e;if(dZ(e)){let t=n.schema[rZ].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new FZ(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=zZ+t.slice(2));let l=BZ(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new RZ(e);return c&&(c.node=t),t}l=e instanceof Map?o[rZ]:Symbol.iterator in Object(e)?o[oZ]:o[rZ]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new RZ(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function HZ(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return VZ(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var UZ=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,WZ=class extends PZ{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>hZ(t)||dZ(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(UZ(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(mZ(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,HZ(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(mZ(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&fZ(i)?i.value:i:mZ(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!dZ(t))return!1;let n=t.value;return n==null||e&&fZ(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return mZ(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(mZ(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,HZ(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},GZ=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function KZ(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var qZ=(e,t,n)=>e.endsWith(`
173
+ `)?KZ(n,t):n.includes(`
174
+ `)?`
175
+ `+KZ(n,t):(e.endsWith(` `)?``:` `)+n,JZ=`flow`,YZ=`block`,XZ=`quoted`;function ZZ(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=QZ(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
176
+ `)n===`block`&&(h=QZ(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
177
+ `&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
178
+ `&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function QZ(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
179
+ `);r=t,i=t+1,a=e[i]}return r}var $Z=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),eQ=e=>/^(%|---|\.\.\.)/m.test(e);function tQ(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
180
+ `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function nQ(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(eQ(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
181
+
182
+ `;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
183
+ `,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:ZZ(o,a,XZ,$Z(t,!1))}function rQ(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
184
+ `)||/[ \t]\n|\n[ \t]/.test(e))return nQ(e,t);let n=t.indent||(eQ(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:ZZ(r,n,JZ,$Z(t,!1))}function iQ(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=nQ;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?rQ:i&&!t?nQ:n?rQ:nQ}return r(e,t)}var aQ;try{aQ=RegExp(`(^|(?<!
185
+ ))
186
+ +(?!
187
+ |$)`,`g`)}catch{aQ=/\n+(?!\n|$)/g}function oQ({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return iQ(n,r);let l=r.indent||(r.forceBlockIndent||eQ(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===RZ.BLOCK_FOLDED?!1:t===RZ.BLOCK_LITERAL||!tQ(n,c,l.length);if(!n)return u?`|
188
+ `:`>
189
+ `;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
190
+ `&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
191
+ `);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
192
+ `&&(p=p.slice(0,-1)),p.replace(aQ,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
193
+ `)_=g;else break}let v=n.substring(0,_<g?_+1:g);v&&=(n=n.substring(v.length),v.replace(/\n+/g,`$&${l}`));let ee=(h?l?`2`:`1`:``)+d;if(e&&(ee+=` `+s(e.replace(/ ?[\r\n]+/g,` `)),i&&i()),!u){let e=n.replace(/\n+/g,`
194
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=$Z(r,!0);o!==`folded`&&t!==RZ.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=ZZ(`${v}${e}${p}`,l,YZ,a);if(!i)return`>${ee}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${ee}\n${l}${v}${n}${p}`}function sQ(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
195
+ `)||u&&/[[\]{},]/.test(a))return iQ(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
196
+ `)?iQ(a,t):oQ(e,t,n,r);if(!s&&!u&&i!==RZ.PLAIN&&a.includes(`
197
+ `))return oQ(e,t,n,r);if(eQ(a)){if(c===``)return t.forceBlockIndent=!0,oQ(e,t,n,r);if(s&&c===l)return iQ(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return iQ(a,t)}return s?d:ZZ(d,c,JZ,$Z(t,!1))}function cQ(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==RZ.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=RZ.QUOTE_DOUBLE);let c=e=>{switch(e){case RZ.BLOCK_FOLDED:case RZ.BLOCK_LITERAL:return i||a?iQ(o.value,t):oQ(o,t,n,r);case RZ.QUOTE_DOUBLE:return nQ(o.value,t);case RZ.QUOTE_SINGLE:return rQ(o.value,t);case RZ.PLAIN:return sQ(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function lQ(e,t){let n=Object.assign({blockQuote:!0,commentString:GZ,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function uQ(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(fZ(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function dQ(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(fZ(e)||mZ(e))&&e.anchor;a&&OZ(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function fQ(e,t,n,r){if(dZ(e))return e.toString(t,n,r);if(cZ(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=hZ(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=uQ(t.doc.schema.tags,a);let o=dQ(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):fZ(a)?cQ(a,t,n,r):a.toString(t,n,r);return o?fZ(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function pQ({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=hZ(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(mZ(e)||!hZ(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||mZ(e)||(fZ(e)?e.type===RZ.BLOCK_FOLDED||e.type===RZ.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=fQ(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=qZ(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=qZ(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=qZ(g,n.indent,l(f))));let _,v,ee;hZ(t)?(_=!!t.spaceBefore,v=t.commentBefore,ee=t.comment):(_=!1,v=null,ee=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&fZ(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&pZ(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let te=!1,ne=fQ(t,n,()=>te=!0,()=>h=!0),re=` `;if(f||_||v){if(re=_?`
198
+ `:``,v){let e=l(v);re+=`\n${KZ(e,n.indent)}`}ne===``&&!n.inFlow?re===`
199
+ `&&ee&&(re=`
200
+
201
+ `):re+=`\n${n.indent}`}else if(!p&&mZ(t)){let e=ne[0],r=ne.indexOf(`
202
+ `),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=ne.indexOf(` `);e===`&`&&n!==-1&&n<r&&ne[n+1]===`!`&&(n=ne.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(re=`\n${n.indent}`)}}else(ne===``||ne[0]===`
203
+ `)&&(re=``);return g+=re+ne,n.inFlow?te&&r&&r():ee&&!te?g+=qZ(g,n.indent,l(ee)):h&&i&&i(),g}function mQ(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var hQ=`<<`,gQ={identify:e=>e===hQ||typeof e==`symbol`&&e.description===hQ,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new RZ(Symbol(hQ)),{addToJSMap:vQ}),stringify:()=>hQ},_Q=(e,t)=>(gQ.identify(t)||fZ(t)&&(!t.type||t.type===RZ.PLAIN)&&gQ.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===gQ.tag&&e.default);function vQ(e,t,n){let r=bQ(e,n);if(pZ(r))for(let n of r.items)yQ(e,t,n);else if(Array.isArray(r))for(let n of r)yQ(e,t,n);else yQ(e,t,r)}function yQ(e,t,n){let r=bQ(e,n);if(!uZ(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function bQ(e,t){return e&&cZ(t)?t.resolve(e.doc,e):t}function xQ(e,t,{key:n,value:r}){if(hZ(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(_Q(e,n))vQ(e,t,r);else{let i=NZ(n,``,e);if(t instanceof Map)t.set(i,NZ(r,i,e));else if(t instanceof Set)t.add(i);else{let a=SQ(n,i,e),o=NZ(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function SQ(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(hZ(e)&&n?.doc){let t=lQ(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),mQ(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function CQ(e,t,n){return new wQ(VZ(e,void 0,n),VZ(t,void 0,n))}var wQ=class e{constructor(e,t=null){Object.defineProperty(this,sZ,{value:iZ}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return hZ(n)&&(n=n.clone(t)),hZ(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return xQ(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?pQ(this,e,t,n):JSON.stringify(this)}};function TQ(e,t,n){return(t.inFlow??e.flow?DQ:EQ)(e,t,n)}function EQ({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(hZ(i))!d&&i.spaceBefore&&f.push(``),OQ(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(dZ(i)){let e=hZ(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),OQ(n,f,e.commentBefore,d))}d=!1;let s=fQ(i,u,()=>o=null,()=>d=!0);o&&(s+=qZ(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
204
+ `}}return e?(p+=`
205
+ `+KZ(l(e),c),s&&s()):d&&o&&o(),p}function DQ({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(hZ(i))i.spaceBefore&&d.push(``),OQ(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(dZ(i)){let e=hZ(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),OQ(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=hZ(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=fQ(i,c,()=>a=null);l||=d.length>u||o.includes(`
206
+ `),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=qZ(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
207
+ `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function OQ({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=KZ(t(r),e);n.push(i.trimStart())}}function kQ(e,t){let n=fZ(t)?t.value:t;for(let r of e)if(dZ(r)&&(r.key===t||r.key===n||fZ(r.key)&&r.key.value===n))return r}var AQ=class extends WZ{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(rZ,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(CQ(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=dZ(e)?e:!e||typeof e!=`object`||!(`key`in e)?new wQ(e,e?.value):new wQ(e.key,e.value);let r=kQ(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);fZ(r.value)&&LZ(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=kQ(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=kQ(this.items,e)?.value;return(!t&&fZ(n)?n.value:n)??void 0}has(e){return!!kQ(this.items,e)}set(e,t){this.add(new wQ(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)xQ(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!dZ(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),TQ(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},jQ={collection:`map`,default:!0,nodeClass:AQ,tag:`tag:yaml.org,2002:map`,resolve(e,t){return uZ(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>AQ.from(e,t,n)},MQ=class extends WZ{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(oZ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=NQ(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=NQ(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&fZ(r)?r.value:r}has(e){let t=NQ(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=NQ(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];fZ(r)&&LZ(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(NZ(e,String(r++),t));return n}toString(e,t,n){return e?TQ(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(VZ(a,void 0,n))}}return i}};function NQ(e){let t=fZ(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var PQ={collection:`seq`,default:!0,nodeClass:MQ,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return pZ(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>MQ.from(e,t,n)},FQ={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),cQ(e,t,n,r)}},IQ={identify:e=>e==null,createNode:()=>new RZ(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new RZ(null),stringify:({source:e},t)=>typeof e==`string`&&IQ.test.test(e)?e:t.options.nullStr},LQ={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new RZ(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&LQ.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function RQ({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var zQ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:RQ},BQ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():RQ(e)}},VQ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new RZ(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:RQ},HQ=e=>typeof e==`bigint`||Number.isInteger(e),UQ=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function WQ(e,t,n){let{value:r}=e;return HQ(r)&&r>=0?n+r.toString(t):RQ(e)}var GQ={identify:e=>HQ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>UQ(e,2,8,n),stringify:e=>WQ(e,8,`0o`)},KQ={identify:HQ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>UQ(e,0,10,n),stringify:RQ},qQ={identify:e=>HQ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>UQ(e,2,16,n),stringify:e=>WQ(e,16,`0x`)},JQ=[jQ,PQ,FQ,IQ,LQ,GQ,KQ,qQ,zQ,BQ,VQ];function YQ(e){return typeof e==`bigint`||Number.isInteger(e)}var XQ=({value:e})=>JSON.stringify(e),ZQ=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:XQ},{identify:e=>e==null,createNode:()=>new RZ(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:XQ},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:XQ},{identify:YQ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>YQ(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:XQ}],QQ=[jQ,PQ].concat(ZQ,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}}),$Q={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,t){if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:t,value:n},r,i,a){if(!n)return``;let o=n,s;if(typeof btoa==`function`){let e=``;for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);s=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(t??=RZ.BLOCK_LITERAL,t!==RZ.QUOTE_DOUBLE){let e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(s.length/e),i=Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=s.substr(r,e);s=i.join(t===RZ.BLOCK_LITERAL?`
208
+ `:` `)}return cQ({comment:e,type:t,value:s},r,i,a)}};function e$(e,t){if(pZ(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!dZ(r)){if(uZ(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new wQ(new RZ(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=dZ(r)?r:new wQ(r)}}else t(`Expected a sequence for this tag`);return e}function t$(e,t,n){let{replacer:r}=n,i=new MQ(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(CQ(o,s,n))}return i}var n$={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:e$,createNode:t$},r$=class e extends MQ{constructor(){super(),this.add=AQ.prototype.add.bind(this),this.delete=AQ.prototype.delete.bind(this),this.get=AQ.prototype.get.bind(this),this.has=AQ.prototype.has.bind(this),this.set=AQ.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(dZ(e)?(r=NZ(e.key,``,t),i=NZ(e.value,r,t)):r=NZ(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=t$(e,t,n),i=new this;return i.items=r.items,i}};r$.tag=`tag:yaml.org,2002:omap`;var i$={collection:`seq`,identify:e=>e instanceof Map,nodeClass:r$,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=e$(e,t),r=[];for(let{key:e}of n.items)fZ(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new r$,n)},createNode:(e,t,n)=>r$.from(e,t,n)};function a$({value:e,source:t},n){return t&&(e?o$:s$).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var o$={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new RZ(!0),stringify:a$},s$={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new RZ(!1),stringify:a$},c$={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:RQ},l$={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():RQ(e)}},u$={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new RZ(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:RQ},d$=e=>typeof e==`bigint`||Number.isInteger(e);function f$(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function p$(e,t,n){let{value:r}=e;if(d$(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return RQ(e)}var m$={identify:d$,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>f$(e,2,2,n),stringify:e=>p$(e,2,`0b`)},h$={identify:d$,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>f$(e,1,8,n),stringify:e=>p$(e,8,`0`)},g$={identify:d$,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>f$(e,0,10,n),stringify:RQ},_$={identify:d$,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>f$(e,2,16,n),stringify:e=>p$(e,16,`0x`)},v$=class e extends AQ{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=dZ(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new wQ(e.key,null):new wQ(e,null),kQ(this.items,t.key)||this.items.push(t)}get(e,t){let n=kQ(this.items,e);return!t&&dZ(n)?fZ(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=kQ(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new wQ(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(CQ(e,null,n));return i}};v$.tag=`tag:yaml.org,2002:set`;var y$={collection:`map`,identify:e=>e instanceof Set,nodeClass:v$,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>v$.from(e,t,n),resolve(e,t){if(uZ(e)){if(e.hasAllNullValues(!0))return Object.assign(new v$,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}};function b$(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function x$(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return RQ(e);let r=``;t<0&&(r=`-`,t*=n(-1));let i=n(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var S$={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>b$(e,n),stringify:x$},C$={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>b$(e,!1),stringify:x$},w$={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(w$.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+`00`).substr(1,3)):0,l=Date.UTC(n,r-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!==`Z`){let e=b$(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``},T$=[jQ,PQ,FQ,IQ,o$,s$,m$,h$,g$,_$,c$,l$,u$,$Q,gQ,i$,n$,y$,S$,C$,w$],E$=new Map([[`core`,JQ],[`failsafe`,[jQ,PQ,FQ]],[`json`,QQ],[`yaml11`,T$],[`yaml-1.1`,T$]]),D$={binary:$Q,bool:LQ,float:VQ,floatExp:BQ,floatNaN:zQ,floatTime:C$,int:KQ,intHex:qQ,intOct:GQ,intTime:S$,map:jQ,merge:gQ,null:IQ,omap:i$,pairs:n$,seq:PQ,set:y$,timestamp:w$},O$={"tag:yaml.org,2002:binary":$Q,"tag:yaml.org,2002:merge":gQ,"tag:yaml.org,2002:omap":i$,"tag:yaml.org,2002:pairs":n$,"tag:yaml.org,2002:set":y$,"tag:yaml.org,2002:timestamp":w$};function k$(e,t,n){let r=E$.get(t);if(r&&!e)return n&&!r.includes(gQ)?r.concat(gQ):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(E$.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(gQ)),i.reduce((e,t)=>{let n=typeof t==`string`?D$[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(D$).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}var A$=(e,t)=>e.key<t.key?-1:+(e.key>t.key),j$=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?k$(e,`compat`):e?k$(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?O$:{},this.tags=k$(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,rZ,{value:jQ}),Object.defineProperty(this,aZ,{value:FQ}),Object.defineProperty(this,oZ,{value:PQ}),this.sortMapEntries=typeof a==`function`?a:a===!0?A$:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function M$(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push(`---`);let i=lQ(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(KZ(t,``))}let o=!1,s=null;if(e.contents){if(hZ(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(KZ(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=fQ(e.contents,i,()=>s=null,t);s&&(c+=qZ(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(fQ(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
209
+ `)?(n.push(`...`),n.push(KZ(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(KZ(a(t),``)))}return n.join(`
210
+ `)+`
211
+ `}var N$=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,sZ,{value:nZ});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new DZ({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[sZ]:{value:nZ}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=hZ(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){P$(this.contents)&&this.contents.add(e)}addIn(e,t){P$(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=kZ(this);e.anchor=!t||n.has(t)?AZ(t||`a`,n):t}return new FZ(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=jZ(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=VZ(e,l,p);return o&&mZ(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new wQ(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return P$(this.contents)?this.contents.delete(e):!1}deleteIn(e){return UZ(e)?this.contents!=null&&(this.contents=null,!0):P$(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return mZ(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return UZ(e)?!t&&fZ(this.contents)?this.contents.value:this.contents:mZ(this.contents)?this.contents.getIn(e,t):void 0}has(e){return mZ(this.contents)?this.contents.has(e):!1}hasIn(e){return UZ(e)?this.contents!==void 0:mZ(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=HZ(this.schema,[e],t):P$(this.contents)&&this.contents.set(e,t)}setIn(e,t){UZ(e)?this.contents=t:this.contents==null?this.contents=HZ(this.schema,Array.from(e),t):P$(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new DZ({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new DZ({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new j$(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=NZ(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?MZ(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return M$(this,e)}};function P$(e){if(mZ(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var F$=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},I$=class extends F${constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},L$=class extends F${constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},R$=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
212
+ `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function z$(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,ee=null,te=null,ne=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!te||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),te&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),te=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){ee&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),ee=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let re=e[e.length-1],ie=re?re.offset+re.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:ee,found:te,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:ie,start:ne??ie}}function B$(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
213
+ `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(B$(t.key)||B$(t.value))return!0}return!1;default:return!0}}function V$(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&B$(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function H$(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||fZ(e)&&fZ(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var U$=`All mapping items must start at the same column`;function W$({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??AQ)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=z$(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,U$)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
214
+ `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||B$(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,U$);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&V$(r.indent,u,i),n.atKey=!1,H$(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=z$(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&V$(r.indent,f,i),s=c.range[2];let l=new wQ(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
215
+ `+_.comment:g.comment=_.comment);let e=new wQ(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function G$({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??MQ)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=z$(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&V$(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function K$(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var q$=`Block collections are not allowed within flow collections`,J$=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function Y$({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?AQ:MQ))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=z$(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
216
+ `+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&B$(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];dZ(t)&&(t=t.value??t.key),t.comment?t.comment+=`
217
+ `+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],J$(m)&&i(r.range,`BLOCK_IN_FLOW`,q$)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);J$(f)&&i(g.range,`BLOCK_IN_FLOW`,q$),n.atKey=!1;let _=z$(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?J$(m)&&i(v.range,`BLOCK_IN_FLOW`,q$):_.comment&&(g.comment?g.comment+=`
218
+ `+_.comment:g.comment=_.comment);let ee=new wQ(g,v);if(n.options.keepSourceTokens&&(ee.srcToken=l),o){let e=c;H$(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(ee)}else{let e=new AQ(n.schema);e.flow=!0,e.items.push(ee);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=K$(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
219
+ `+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function X$(e,t,n,r,i,a){let o=n.type===`block-map`?W$(e,t,n,r,a):n.type===`block-seq`?G$(e,t,n,r,a):Y$(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function Z$(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===AQ.tagName&&s===`map`||o===MQ.tagName&&s===`seq`)return X$(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),X$(e,t,n,i,o)}let l=X$(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=hZ(u)?u:new RZ(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function Q$(e,t,n){let r=t.offset,i=$$(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?RZ.BLOCK_FOLDED:RZ.BLOCK_LITERAL,o=t.source?e1(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
220
+ `.repeat(Math.max(1,o.length-1)):``,n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:a,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<s;++t){let[r,a]=o[t];if(a===``||a===`\r`)i.indent===0&&r.length>c&&(c=r.length);else{r.length<c&&n(l+r.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),i.indent===0&&(c=r.length),u=t,c===0&&!e.atRoot&&n(l,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}l+=r.length+a.length+1}for(let e=o.length-1;e>=s;--e)o[e][0].length>c&&(s=e+1);let d=``,f=``,p=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+`
221
+ `;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===RZ.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
222
+ `):t.length>c||r[0]===` `?(f===` `?f=`
223
+ `:!p&&f===`
224
+ `&&(f=`
225
+
226
+ `),d+=f+t.slice(c)+r,f=`
227
+ `,p=!0):r===``?f===`
228
+ `?d+=`
229
+ `:f=`
230
+ `:(d+=f+r,f=` `,p=!1)}switch(i.chomp){case`-`:break;case`+`:for(let e=s;e<o.length;++e)d+=`
231
+ `+o[e][0].slice(c);d[d.length-1]!==`
232
+ `&&(d+=`
233
+ `);break;default:d+=`
234
+ `}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function $$({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function e1(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}function t1(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=RZ.PLAIN,c=n1(a,l);break;case`single-quoted-scalar`:s=RZ.QUOTE_SINGLE,c=r1(a,l);break;case`double-quoted-scalar`:s=RZ.QUOTE_DOUBLE,c=a1(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=K$(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function n1(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),i1(e)}function r1(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),i1(e.slice(1,-1)).replace(/''/g,`'`)}function i1(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
235
+ `?a+=o:o=`
236
+ `:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function a1(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
237
+ `){if(i===`
238
+ `){let{fold:t,offset:i}=o1(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=s1[i];if(a)n+=a;else if(i===`
239
+ `)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
240
+ `)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=c1(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
241
+ `&&(a!==`\r`||e[r+2]!==`
242
+ `)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function o1(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
243
+ `||r===`\r`)&&(r!==`\r`||e[t+2]===`
244
+ `);)r===`
245
+ `&&(n+=`
246
+ `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var s1={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
247
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function c1(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}function l1(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Q$(e,t,r):t1(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[aZ]:c?u1(e.schema,i,c,n,r):t.type===`scalar`?d1(e,i,t,r):e.schema[aZ];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=fZ(a)?a:new RZ(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new RZ(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function u1(e,t,n,r,i){if(n===`!`)return e[aZ];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[aZ])}function d1({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[aZ];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[aZ];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}function f1(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var p1={composeNode:m1,composeEmptyNode:h1};function m1(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=g1(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=l1(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=Z$(p1,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=h1(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!fZ(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function h1(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=l1(e,{type:`scalar`,offset:f1(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function g1({options:e},{offset:t,source:n,end:r},i){let a=new FZ(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=K$(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function _1(e,t,{offset:n,start:r,value:i,end:a},o){let s=new N$(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=z$(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});l.found&&(s.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!l.hasNewline&&o(l.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),s.contents=i?m1(c,i,l,o):h1(c,l.end,r,null,l,o);let u=s.contents.range[2],d=K$(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function v1(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function y1(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
248
+
249
+ `:`
250
+ `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var b1=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=v1(e);r?this.warnings.push(new L$(i,t,n)):this.errors.push(new I$(i,t,n))},this.directives=new DZ({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=y1(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(mZ(i)&&!i.flow&&i.items.length>0){let e=i.items[0];dZ(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:y1(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=v1(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=_1(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new I$(v1(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new I$(v1(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=K$(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new I$(v1(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=new N$(void 0,Object.assign({_directives:this.directives},this.options));this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),e.range=[0,t,t],this.decorate(e,!1),yield e}}},x1=Symbol(`break visit`),S1=Symbol(`skip children`),C1=Symbol(`remove item`);function w1(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),T1(Object.freeze([]),e,t)}w1.BREAK=x1,w1.SKIP=S1,w1.REMOVE=C1,w1.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},w1.parentCollection=(e,t)=>{let n=w1.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function T1(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=T1(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===x1)return x1;else r===C1&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function E1(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
251
+ `:case`\r
252
+ `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function D1(e){switch(e){case void 0:case` `:case`
253
+ `:case`\r`:case` `:return!0;default:return!1}}var O1=new Set(`0123456789ABCDEFabcdef`),k1=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),A1=new Set(`,[]{}`),j1=new Set(` ,[]{}
254
+ \r `),M1=e=>!e||j1.has(e),N1=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
255
+ `||t===`\r`&&this.buffer[e+1]===`
256
+ `}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===` `;)t=this.buffer[++n+e];if(t===`\r`){let t=this.buffer[n+e+1];if(t===`
257
+ `||!t&&!this.atEnd)return e+n+1}return t===`
258
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&D1(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
259
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&D1(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!D1(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&D1(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(M1),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&D1(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(M1),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||D1(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
260
+ `,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
261
+ `,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>D1(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
262
+ `:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
263
+ `)break}default:break loop}if(!n&&!this.atEnd)return this.setNext(`block-scalar`);if(t>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?t:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
264
+ `,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===` `;)n=this.buffer[++r];if(n===` `){for(;n===` `||n===` `||n===`\r`||n===`
265
+ `;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let n=e-1,r=this.buffer[n];r===`\r`&&(r=this.buffer[--n]);let i=n;for(;r===` `;)r=this.buffer[--n];if(r===`
266
+ `&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(D1(r)||e&&A1.has(r))break;t=n}else if(D1(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
267
+ `?(n+=1,r=`
268
+ `,i=this.buffer[n+1]):t=n),i===`#`||e&&A1.has(i))break;if(r===`
269
+ `){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&A1.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(M1),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(D1(n)||t&&A1.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!D1(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(k1.has(t))t=this.buffer[++e];else if(t===`%`&&O1.has(this.buffer[e+1])&&O1.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
270
+ `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
271
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},P1=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};function F1(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function I1(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function L1(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function R1(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function z1(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function B1(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function V1(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!F1(t.start,`explicit-key-ind`)&&!F1(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,L1(t.value)?t.value.end?B1(t.value.end,t.sep):t.value.end=t.sep:B1(t.start,t.sep),delete t.sep)}var H1=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new N1,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=E1(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&V1(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&I1(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:I1(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=z1(R1(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
272
+ `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
273
+ `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){B1(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(F1(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=z1(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(F1(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(L1(t.key)&&!F1(t.sep,`newline`)){let e=z1(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):F1(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!F1(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){B1(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||F1(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=z1(R1(t));V1(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
274
+ `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
275
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=z1(R1(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=z1(R1(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function U1(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new P1||null,prettyErrors:t}}function W1(e,t={}){let{lineCounter:n,prettyErrors:r}=U1(t),i=new H1(n?.addNewLine),a=new b1(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new I$(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(R$(e,n)),o.warnings.forEach(R$(e,n))),o}var G1=e=>vr(Uw(N({message:z}))(e),{onNone:()=>`The YAML parser failed without an error message`,onSome:({message:e})=>e}),K1=(e,t)=>E(function*(){let n=yield*Kh({try:()=>W1(t,{keepSourceTokens:!0,prettyErrors:!0,strict:!0,uniqueKeys:!0}),catch:t=>new ZY({file:e,stage:`yaml`,expression:y(),message:G1(t)})}),r=n.errors[0]??n.warnings[0];return r===void 0?n:yield*new ZY({file:e,stage:`yaml`,expression:y(),message:r.message})}),q1=Jy(),J1=F([M,cT]).annotate({message:`Expected a CEL expression. Quote the value so that YAML reads it as a string.`}).pipe(ST(GY,{decode:ob(e=>String(e)),encode:ob(e=>e)})),Y1=F([iX.mapFields(ww({if:J1})).pipe(ST(iX)),aX.mapFields(ww({if:J1})).pipe(ST(aX)),oX.mapFields(ww({if:J1})).pipe(ST(oX))]),X1=class extends V(`@usine/config/LoopFrontmatter`)({trigger:Y1,selector:xE(FY),approval:Jk.pipe(DT(T(`none`))),step:eM.pipe(DT(T(`run`))),agent:FA,maxCycles:fX.fields.maxCycles,permissions:fX.fields.permissions,priority:xE(dX)}){}.pipe(pT({maxCycles:`max_cycles`})),Z1=class extends V(`@usine/config/AgentFrontmatter`)({harness:MA,model:jA,effort:NA,parentModel:xE(jA),parentEffort:xE(NA)}){}.pipe(pT({parentModel:`parent_model`,parentEffort:`parent_effort`})),Q1=(e,t)=>new ZY({file:e,stage:`schema`,expression:y(),message:q1(t.issue)}),$1=Vw(IE),e0=(e,t)=>E(function*(){return yield*$1((yield*K1(e,t)).toJS()).pipe(ug(t=>new ZY({file:e,stage:`yaml`,expression:y(),message:q1(t.issue)})))}),t0=(e,t)=>new ZY({file:e,stage:`expression`,expression:b(t.source),message:t.message}),n0=e=>{let t=e.slice(e.lastIndexOf(`/`)+1);return t.endsWith(`.md`)?T(t.slice(0,-3)):new ZY({file:e,stage:`schema`,expression:y(),message:`Expected a .md filename`})},r0=e=>n0(e).pipe(D(t=>Vw(fX.fields.name)(t).pipe(ug(t=>Q1(e,t))))),i0=e=>n0(e).pipe(D(t=>Vw(FA)(t).pipe(ug(t=>Q1(e,t))))),a0=(e,t)=>E(function*(){let n=[],r=0;for(;r<t.length;){let i=t.indexOf(`{{`,r);if(i<0)break;let a=t.indexOf(`}}`,i+2);if(a<0)return yield*new ZY({file:e,stage:`expression`,expression:y(),message:`The prompt has an unclosed {{ at character ${i}. Close it with }}.`});let o=t.slice(i+2,a).trim(),s=yield*Vw(GY)(o).pipe(ug(t=>Q1(e,t)));n.push({source:s,start:i,end:a+2}),r=a+2}return n}),o0=(e,t,n)=>{let r=mX(t.name),i=$X(t.trigger.on);return E(function*(){let a=yield*Nh(yield*a0(r,t.body),t=>e.evaluateScalar(t.source,i,n).pipe(ug(e=>t0(r,e)),tg(e=>({expression:t,value:e})))),o=``,s=0;for(let{expression:e,value:n}of a)o+=t.body.slice(s,e.start),o+=String(n),s=e.end;return o+t.body.slice(s)})},s0=k(`ConfigParser.parseUsineYaml`)((e,t)=>E(function*(){let n=yield*e0(e,t);return yield*Vw(PY)(n,{onExcessProperty:`error`}).pipe(ug(t=>Q1(e,t)))})),c0=k(`ConfigParser.parseAgentFile`)((e,t)=>E(function*(){let n=yield*i0(e),r=yield*$Y(e,t),i=yield*e0(e,r.yaml),a=yield*Vw(Z1)(i,{onExcessProperty:`error`}).pipe(ug(t=>Q1(e,t))),o=yield*Vw(IA)(r.body).pipe(ug(t=>Q1(e,t)));return new eX({name:n,harness:a.harness,model:a.model,effort:a.effort,parentModel:a.parentModel,parentEffort:a.parentEffort,persona:o})})),l0=e=>k(`ConfigParser.parseLoopFile`)((t,n)=>E(function*(){let r=yield*r0(t),i=yield*$Y(t,n),a=yield*e0(t,i.yaml),o=yield*Vw(X1)(a,{onExcessProperty:`error`}).pipe(ug(e=>Q1(t,e))),s=yield*Vw(uX)(i.body).pipe(ug(e=>Q1(t,e))),c=$X(o.trigger.on);return yield*e.checkBoolean(o.trigger.if,c).pipe(ug(e=>t0(t,e))),yield*Nh(yield*a0(t,s),({source:n})=>e.checkScalar(n,c).pipe(ug(e=>t0(t,e))),{discard:!0}),new fX({name:r,trigger:o.trigger,selector:o.selector,approval:o.approval,maxCycles:o.maxCycles,permissions:o.permissions,priority:o.priority,step:o.step,agent:o.agent,body:s})})),u0=Uw(nV),d0=e=>k(`ConfigParser.configWarnings`)(function*(t,n){let r=new Set(t.labels.map(({name:e})=>rV(e))),i=[];for(let e of t.repos)for(let t of e.lanes)for(let n of t.sources)`label`in n&&!r.has(rV(n.label))&&i.push(new hX({repository:e.name,lane:t.name,label:n.label}));for(let t of n){let n=yield*e.relatedStringLiterals(t.trigger.if,[`item`,`labels`]);for(let e of n){let n=u0(e);S(n)&&!r.has(rV(n.value))&&i.push(new gX({loop:t.name,label:n.value}))}}return i}),f0=class e extends Lr()(`@usine/config/ConfigParser`){static layer=Yf(e,E(function*(){let e=yield*JY;return{configWarnings:d0(e),parseUsineYaml:s0,parseAgentFile:c0,parseLoopFile:l0(e),renderPrompt:k(`ConfigParser.renderPrompt`)((t,n)=>o0(e,t,n))}}))},p0=class extends V(`@usine/github/NewRepositoryLabel`)({name:Rq,color:B(zq),description:B(M)}){},m0=N({name:Rq,color:zq,description:I(M)}),h0=e=>{let{name:t,owner:n}=Vk(e);return`${RK}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`},g0=class e extends Lr()(`@usine/github/GitHubLabelWriter`){static layer=Yf(e,E(function*(){let e=yield*oq,t=yield*yG;return{create:k(`GitHubLabelWriter.create`)(function*(n,r){yield*O({repository:n,label:r.name});let i=yield*e.installationToken(),a={name:r.name};S(r.color)&&(a.color=r.color.value),S(r.description)&&(a.description=r.description.value);let o=VW(h0(n)).pipe(nG(a),BK(i.value)),s=yield*t.execute(o).pipe(ug(e=>VK(`create-repository-label`,e)));if(s.status<200||s.status>=300)return yield*ZK(`create-repository-label`,s,yield*ap);let c=yield*oG(m0)(s).pipe(ug(e=>WK(`create-repository-label`,e.message)));return new Bq({name:c.name,color:c.color,description:C(c.description)})})}}))},_0=class extends V(`@usine/orchestrator/LabelPreflightFinding`)({repository:Lk,label:nV,errorTag:z,message:z}){},v0=(e,t)=>{let n=[];if(S(e.color)){let r=e.color.value.toLowerCase();vr(t.color,{onNone:()=>!0,onSome:e=>e.toLowerCase()!==r})&&n.push(`color`)}if(S(e.description)){let r=e.description.value;vr(t.description,{onNone:()=>!0,onSome:e=>e!==r})&&n.push(`description`)}return n},y0=e=>new p0({name:Rq.make(e.name),color:Dr(e.color,zq.make),description:e.description}),b0=class e extends Lr()(`@usine/orchestrator/LabelReconciler`){static layer=Yf(e,E(function*(){let e=yield*g0;return{reconcile:k(`LabelReconciler.reconcile`)(function*(t,n,r){yield*O({repository:t});let i=[...r],a=new Map(r.map(e=>[rV(e.name),e])),o=[],s=!1,c=y();for(let r of n){let n=a.get(rV(r.name));if(n!==void 0){let e=v0(r,n);e.length>0?yield*$g(`Declared GitHub label differs from the existing repository label; left unchanged`,{repository:t,label:r.name,drift:e.join(`, `)}):yield*j(`Declared GitHub label already exists`,{repository:t,label:r.name});continue}let l=yield*Qh(e.create(t,y0(r)));if(Ei(l)){let e=l.failure;if(o.push(new _0({repository:t,label:r.name,errorTag:e._tag,message:e.message})),e._tag===`GitHubRateLimitError`){c=b(e.retryAt),yield*$g(`Label creation rate-limited; remaining declarations deferred and trigger evaluation continues`,{repository:t,label:r.name,errorTag:e._tag,message:e.message,retryAt:q_(e.retryAt)});break}yield*e_(`Declared GitHub label could not be created; trigger evaluation continues`,{repository:t,label:r.name,errorTag:e._tag,message:e.message});continue}let u=new vU({name:l.success.name,color:b(l.success.color),description:l.success.description});i.push(u),a.set(rV(u.name),u),s=!0,yield*A(`Created declared GitHub label`,{repository:t,label:u.name})}return i.sort((e,t)=>e.name.localeCompare(t.name)),{labels:i,findings:o,catalogChanged:s,nextPollAt:c}})}}))},x0=Rk.make(`HEAD`),S0=class extends NE(`@usine/orchestrator/LoopAgentResolutionError`)(`LoopAgentResolutionError`,{loop:Kk,agent:FA,message:z}){},C0=k(`TriggerRouting.resolveLoop`)(function*(e,t){yield*O({loop:t.name,agent:t.agent});let n=new Map(e.agents.map(e=>[e.name,e])).get(t.agent);if(n===void 0)return yield*new S0({loop:t.name,agent:t.agent,message:`Loop "${t.name}" references agent "${t.agent}", which is not in the roster`});let r=n.agent;return{agent:r,loop:t,parentModel:RA(r,e.config.settings.parentModel)}}),w0=k(`TriggerRouting.resolveLoops`)(function*(e){let t=[];for(let n of e.loops){let r=yield*Qh(C0(e,n));Di(r)?t.push(r.success):yield*e_(`Loaded loop lost its rostered Agent; skipping the loop`,{loop:r.failure.loop,agent:r.failure.agent,errorTag:r.failure._tag,message:r.failure.message})}return t}),T0=e=>e.trigger.on===`schedule`?y():b(e.maxCycles),E0=e=>new IP({event:new Gk({id:Uk.make(e.dedupKey),dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),itemKey:e.itemKey,cycleGeneration:e.cycleGeneration,loop:e.loop.name,step:e.loop.step,approval:e.loop.approval,permissions:e.loop.permissions,cycleLimit:T0(e.loop),repository:e.repository.name,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel}),D0=e=>xk(e,{Claimed:({runId:e})=>({runId:e}),Queued:()=>({}),Suppressed:({runId:e})=>({suppressedBy:e}),Ignored:({reason:e})=>({reason:e}),CycleBlocked:({ask:e})=>({askId:e.id,reason:`cycle-budget-exhausted`})}),O0=e=>vr(e.expression,{onNone:()=>({configFile:e.file,configStage:e.stage}),onSome:t=>({configFile:e.file,configStage:e.stage,expression:t})}),k0=class extends V(`@usine/orchestrator/RepositoryPollFailure`)({repository:Lk,errorTag:z,message:M}){},A0=class extends V(`@usine/orchestrator/RepositoryPoll`)({repository:Lk,completedAt:_E}){},j0=class extends V(`@usine/orchestrator/PollCycle`)({repositoryPolls:P(A0).pipe(TT(T([]))),repositories:R.check(HT(0)),changedItems:R.check(HT(0)),submissions:P(qP),revokedRuns:R.check(HT(0)),failures:P(k0),preflightFindings:P(_0),nextPollAt:B(_E)}){},M0=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...O0(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},N0=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[G_(e)]}));return t.length===0?y():R_(Math.max(...t))},P0=eT(bN).pipe(ST(aE(_T([nT(`github`),Lk,xN])))),F0=Yw(P0),I0=(e,t)=>F0([`github`,Lk.make(Hk(e)),xN.make(t)]),L0={labels:[],findings:[],catalogChanged:!1,nextPollAt:y()},R0=k(`PollingTriggers.applyLabelCatalog`)(function*(e,t,n){yield*O({repository:e});let r=yield*jU,i=yield*MU,a={labelEntityTag:t,entityTagChanged:!1,confirmedLabels:y(),failures:[],nextPollAt:y()};if(Ei(n)){let t=n.failure;return t._tag===`GitHubRateLimitError`?(yield*$g(`Label catalog rate-limited; kept the stored catalog and deferred label provisioning`,{repository:e,operation:t.operation,retryAt:q_(t.retryAt)}),{...a,nextPollAt:b(t.retryAt)}):(yield*e_(`Label catalog request failed; kept the stored catalog, deferred label provisioning, and evaluated items anyway`,{repository:e,...M0(t)}),{...a,failures:[new k0({repository:e,errorTag:t._tag,message:t.message})]})}let o=n.success;if(!(o instanceof Hq)){let t=yield*r.get(e);return x(t)?(yield*$g(`Repository label catalog unchanged (304) but its projection is missing; refetching next cycle and deferring label provisioning`,{repository:e}),{...a,labelEntityTag:y(),entityTagChanged:!0}):(yield*j(`Repository label catalog unchanged (304)`,{repository:e}),{...a,confirmedLabels:b(t.value.labels)})}let s=o.labels.map(({name:e,color:t,description:n})=>new vU({name:e,color:b(t),description:n}));return yield*i.replace(new xU({repository:e,labels:s})),{...a,labelEntityTag:o.entityTag,entityTagChanged:!0,confirmedLabels:b(s)}}),z0=k(`PollingTriggers.synchronizeLabels`)(function*(e,t,n){yield*O({repository:e});let r=yield*vJ,i=yield*b0,a=yield*MU,o=yield*R0(e,n,yield*Qh(r.labels(e,n))),s=yield*vr(o.confirmedLabels,{onNone:()=>T(L0),onSome:n=>i.reconcile(e,t,n)}),c={labelEntityTag:s.catalogChanged?y():o.labelEntityTag,entityTagChanged:o.entityTagChanged||s.catalogChanged,failures:o.failures,preflightFindings:s.findings,nextPollAt:N0([o.nextPollAt,s.nextPollAt])};return s.catalogChanged&&(yield*a.replace(new xU({repository:e,labels:s.labels})).pipe(ug(e=>({_tag:`InterruptedRepositoryCycle`,error:e,failures:c.failures,preflightFindings:c.preflightFindings,nextPollAt:c.nextPollAt})))),c}),B0=k(`PollingTriggers.observeItem`)(function*(e,t){yield*O({repository:e,item:t.number});let n=yield*vJ,r=yield*hU,i=yield*OH,a=I0(e,t.number),o=yield*i.generation(a),s=yield*n.snapshot(e,t),c=new iU({itemKey:a,repository:e,source:nU.make(t._tag===`ChangedIssue`?`issue`:`pr`),number:xN.make(t.number),contentHash:rU.make(s.contentHash),payload:s.payload});return yield*r.upsert(c),yield*j(`Fetched changed-item snapshot`,{repository:e,item:c.number,stream:c.source,contentHash:c.contentHash}),{snapshot:s,projection:c,cycleGeneration:o}}),V0=k(`PollingTriggers.markItemGone`)(function*(e,t){return yield*O({repository:e,item:t}),yield*(yield*hU).markGone(I0(e,t),yield*z_)}),H0=class extends V(`@usine/orchestrator/LoopEvaluationFailure`)({loop:Kk,stage:bT([`if`,`prompt`]),expression:yE(GY),errorTag:z,message:M}){},U0=class extends V(`@usine/orchestrator/FailingItem`)({stream:bT([`issue`,`pr`]),number:xN,updatedAt:vE,contentHash:rU,failures:vT(H0)}){},W0=e=>e.stream===`issue`?new gq({number:e.number,updatedAt:e.updatedAt}):new _q({number:e.number,updatedAt:e.updatedAt}),G0=(e,t,n)=>{let[r,...i]=n;return r===void 0?y():b(new U0({stream:e._tag===`ChangedIssue`?`issue`:`pr`,number:xN.make(e.number),updatedAt:e.updatedAt,contentHash:t,failures:[r,...i]}))},K0=e=>e.stage===`if`?`if:`:vr(e.expression,{onNone:()=>`prompt`,onSome:e=>`prompt {{ ${e} }}`}),q0=(e,t)=>t.failures.map(n=>new k0({repository:e,errorTag:n.errorTag,message:`Loop "${n.loop}": ${K0(n)} failed on ${t.stream===`issue`?`issue`:`pull request`} #${t.number}: ${n.message}`})),J0=e=>vr(e,{onNone:()=>[],onSome:({failures:e})=>e}),Y0=(e,t)=>e.loop===t.loop&&e.stage===t.stage,X0=k(`PollingTriggers.logItemEvaluation`)(function*(e,t,n,r){yield*O({repository:e,item:t});for(let i of jr(r)){let r=vr(n,{onNone:()=>[],onSome:e=>e.contentHash===i.contentHash?e.failures:[]});for(let n of i.failures){let a={repository:e,item:t,contentHash:i.contentHash,loop:n.loop,stage:n.stage,expression:w(n.expression),errorTag:n.errorTag,message:n.message};r.some(e=>Y0(e,n))?yield*j(`Loop evaluation still fails on unchanged Item content`,a):yield*e_(`Loop evaluation failed on an Item; its other Loops and the repository's other Items continue`,a)}}let i=J0(r);for(let r of J0(n))i.some(e=>Y0(e,r))||(yield*A(`Loop evaluation no longer fails on the Item`,{repository:e,item:t,loop:r.loop,stage:r.stage}))}),Z0=(e,t,{projection:n,cycleGeneration:r})=>Wk.make(JSON.stringify([e.name,Hk(t.name),n.number,n.contentHash,...r===0?[]:[r]])),Q0=(e,t,n)=>E(function*(){return yield*(yield*JY).evaluateBoolean(e.trigger.if,$X(e.trigger.on),{repo:eZ(t),item:n})}),$0=(e,t,n)=>E(function*(){let r=yield*JY,i=eZ(t);return yield*r.evaluateBooleanEach(e.trigger.if,$X(e.trigger.on),n.map(e=>({repo:i,item:e})))}),e2=k(`PollingTriggers.evaluateItem`)(function*(e,t,n){let{projection:r,cycleGeneration:i}=n;yield*O({repository:e.name,item:r.number});let a=yield*f0,o=yield*nW,s=t.filter(({loop:e})=>e.trigger.on===r.source),c=r.payload,l={repo:eZ(e),item:c};if(s.length===0)return yield*j(`Item projected without any matching repository Loop`,{repository:e.name,item:r.number,stream:r.source}),{submissions:[],revokedRuns:0,failures:[]};let u=[],d=r.source===`pr`?Rk.make(yield*Vw(zk)(c.headRefOid).pipe(ug(()=>new IK({operation:`fetch-pull-request-snapshot`,message:`The pull request payload has no valid head commit`,detail:`pull request #${r.number} has no full headRefOid`})))):x0,f=[],p=0;for(let{agent:t,loop:m,parentModel:h}of s){yield*O({loop:m.name,agent:t.name});let s=yield*Qh(Q0(m,e,c));if(Ei(s)){f.push(new H0({loop:m.name,stage:`if`,expression:b(s.failure.source),errorTag:s.failure._tag,message:s.failure.message}));continue}if(!s.success){yield*j(`Item did not match its loop expression`,{repository:e.name,loop:m.name,agent:t.name,item:r.number});let n=yield*o.revoke(m.name,r.itemKey);p+=n.length,n.length>0&&(yield*A(`Item stopped matching; revoked its unstarted runs`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,runIds:n.join(`, `)}));continue}let g=Z0(m,e,n),_=yield*z_,v=yield*Qh(a.renderPrompt(m,l));if(Ei(v)){f.push(new H0({loop:m.name,stage:`prompt`,expression:v.failure.expression,errorTag:v.failure._tag,message:v.failure.message}));continue}let ee=yield*o.submit(E0({dedupKey:g,cycleGeneration:i,itemKey:r.itemKey,loop:m,payload:c,receivedAt:_,repository:e,revision:d,task:DM.make(v.success),agent:t,parentModel:h}));yield*A(`Submitted matching item state`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,contentHash:r.contentHash,revision:d,result:ee._tag,...D0(ee)}),u.push(ee)}return{submissions:u,revokedRuns:p,failures:f}}),t2=k(`PollingTriggers.revokeMissingItem`)(function*(e,t,n,r){yield*O({repository:e.name,item:r});let i=yield*nW,a=I0(e.name,r),o=0;for(let{agent:s,loop:c}of t.filter(({loop:e})=>e.trigger.on===n)){let t=yield*i.revoke(c.name,a);o+=t.length,t.length>0&&(yield*A(`Item is gone from GitHub; revoked its unstarted runs`,{repository:e.name,loop:c.name,agent:s.name,item:r,runIds:t.join(`, `)}))}return o}),n2=class e extends Lr()(`@usine/orchestrator/LoopMatches`){static layer=Yf(e,E(function*(){let e=yield*JY;return{matching:k(`LoopMatches.matching`)(function*(e,t,n){yield*O({repository:t.name,items:n.length});let r=e.loops.filter(e=>e.trigger.on!==`schedule`&&IY(e.selector,t)),i=n.filter(({goneAt:e})=>x(e)),a=new Map,o=0;for(let e of r){let n=i.filter(({source:t})=>t===e.trigger.on);if(n.length===0)continue;let r=yield*Qh($0(e,t,n.map(({payload:e})=>e)));if(Ei(r)){o+=n.length,yield*j(`Loop trigger could not be checked; it matches no stored Item`,{repository:t.name,loop:e.name,items:n.length,errorTag:r.failure._tag,message:r.failure.message});continue}let s=new Set;for(let[i,a]of ia(n,r.success))Di(a)?a.success&&s.add(i):(o+=1,yield*j(`Loop trigger could not be evaluated on a stored Item`,{repository:t.name,loop:e.name,item:i.number,errorTag:a.failure._tag,message:a.failure.message}));a.set(e,s)}let s=[];for(let e of i)for(let t of r)a.get(t)?.has(e)===!0&&s.push({loop:t,item:e});return yield*j(`Matched Loop triggers against stored Items`,{repository:t.name,loops:r.length,items:n.length,matches:s.length,failures:o}),s},Og(JY,e))}}))},r2=(e,t)=>e.changes.pipe(RO(e=>e!==t),KO,D(vr({onNone:()=>Vh,onSome:e=>T(e)}))),i2=k(`PollingTriggers.closeAsksOfClosedItems`)(function*(e){yield*O({repository:e});let t=yield*OH,n=(yield*t.asks()).filter(t=>Hk(t.repository)===Hk(e));for(let e of n){let n={askId:e.id,itemKey:e.itemKey,repository:e.repository},r=yield*BJ(e.itemKey);x(r)?yield*j(`Cycle-budget Ask stays open; its Item is open or not stored`,n):(yield*t.close(e.id,`ItemClosed`))&&(yield*A(`Item is closed; its cycle-budget Ask leaves Needs attention`,{...n,itemState:r.value}))}}),a2=E(function*(){let e=new Set,t=yield*sD({capacity:128,strategy:`dropping`}),n=yield*wk(0),r=({repository:e,item:t})=>`${Hk(e)}:${t.number}`,i=e=>vr(e,{onNone:()=>zh,onSome:e=>Ok(n,t=>Math.max(t,G_(e)))});return{offer:k(`PollingTriggers.hint`)(function*(n,a,o=y()){yield*O({repository:n,item:a.number}),yield*i(o);let s={repository:n,item:a},c=r(s);e.has(c)?yield*j(`Self-write Hint coalesced with a pending Item fetch`,{repository:n,item:a.number}):(e.add(c),(yield*lD(t,s))?yield*j(`Self-write Hint queued`,{repository:n,item:a.number}):(e.delete(c),yield*$g(`Self-write Hint queue full; the normal poll will refresh the Item`,{repository:n,item:a.number})))},Rg),take:zg(n=>n(hD(t)).pipe(Zh(t=>Rh(()=>e.delete(r(t)))))),defer:i,awaitBackoff:E(function*(){for(;;){let e=yield*Tk(n),t=yield*ap;if(e<=t)return;yield*A(`GitHub request backoff delays polling and self-write Hints`,{sleepMs:e-t}),yield*gg($a(e-t))}})}}),o2=class e extends Lr()(`@usine/orchestrator/ItemHints`){static layer=Yf(e,a2)},s2=to(10),c2={revokedRuns:0,failures:[],nextPollAt:y()},l2=k(`PollingTriggers.checkOpenIssues`)(function*(e,t){yield*O({repository:e.name});let n=yield*mU,r=yield*vJ,i=yield*n.openIssues(e.name);if(i.length===0)return yield*j(`No open issues to check against GitHub`,{repository:e.name}),c2;let a=yield*Qh(r.missingIssues(e.name,i));if(Ei(a)){let t=a.failure;return t._tag===`GitHubRateLimitError`?(yield*$g(`Open-issue check rate-limited; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,operation:t.operation,retryAt:q_(t.retryAt)}),{...c2,nextPollAt:b(t.retryAt)}):(yield*e_(`Open-issue check failed; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,...M0(t)}),{...c2,failures:[new k0({repository:e.name,errorTag:t._tag,message:t.message})]})}let o=0;for(let n of a.success){let r=yield*t2(e,t,`issue`,n),i=yield*V0(e.name,n);o+=r,yield*A(`GitHub no longer has an open issue; it leaves the open lanes`,{repository:e.name,item:n,revokedRuns:r,projectionMarkedGone:i})}return yield*j(`Checked open issues against GitHub`,{repository:e.name,openIssues:i.length,missingIssues:a.success.length}),{...c2,revokedRuns:o}}),u2=4,d2=class extends V(`@usine/orchestrator/OpenPullRequest`)({number:_q.fields.number,updatedAt:vE,baseRefName:xE(pq),mergeable:M.pipe(DT(T(`UNKNOWN`))),checksUnsettled:cT.pipe(DT(T(!0)))}){},f2=(e,t)=>t._tag===`PullRequestSnapshot`&&t.payload.state===`OPEN`?b(new d2({number:e.number,updatedAt:e.updatedAt,baseRefName:b(t.payload.baseRefName),mergeable:t.payload.mergeable,checksUnsettled:t.payload.statusCheckRollup?.state===`PENDING`||t.payload.statusCheckRollup?.state===`EXPECTED`||t.payload.statusCheckRollup===null&&t.payload.mergeStateStatus===`BLOCKED`})):y(),p2=k(`PollingTriggers.readBaseRef`)(function*(e,t,n,r){yield*O({repository:e,baseRefName:t});let i=yield*Qh((yield*vJ).baseRefHead(e,t,n));if(Ei(i)){let a=i.failure;return a._tag===`GitHubRateLimitError`?yield*a:(yield*$g(`Could not read the base branch head; refreshing its open pull requests in this poll`,{repository:e,baseRefName:t,pullRequests:r.join(`, `),...M0(a)}),{_tag:`Unreadable`,recorded:n})}let a=i.success;return x(n)?(yield*A(`Base branch head recorded; refreshing its open pull requests once`,{repository:e,baseRefName:t,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a}):n.value.sha===a.sha?{_tag:`Unchanged`,head:a}:(yield*A(`Base branch head moved; refreshing its open pull requests`,{repository:e,baseRefName:t,previousHead:n.value.sha,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a})}),m2=(e,t)=>{if(x(e.baseRefName))return b(`baseUnrecorded`);let n=t.get(e.baseRefName.value);return n?._tag===`Moved`?b(`baseMoved`):n?._tag===`Unreadable`?b(`baseUnreadable`):e.mergeable===`UNKNOWN`?b(`mergeableUnknown`):e.checksUnsettled?b(`checksUnsettled`):y()},h2=k(`PollingTriggers.openPullRequestRefresh`)(function*(e,t,n,r){if(yield*O({repository:e}),t.length===0)return{refreshed:[],baseRefHeads:[]};let i=new Map;for(let{number:e,baseRefName:n}of t){if(x(n))continue;let t=i.get(n.value)??[];t.push(e),i.set(n.value,t)}let a=new Map(yield*Nh(i,([t,r])=>p2(e,t,C(n.find(e=>e.baseRefName===t)),r).pipe(tg(e=>[t,e])),{concurrency:u2})),o=t.filter(({number:e})=>!r.has(e)),s=o.flatMap(e=>jr(Dr(m2(e,a),t=>({pullRequest:e,reason:t}))));if(s.length===0)yield*j(`No open pull request needs a refresh`,{repository:e,openPullRequests:t.length,baseRefReads:a.size});else{let t=ua(s,({reason:e})=>e);yield*A(`Refreshing open pull requests`,{repository:e,baseRefReads:a.size,refreshed:s.length,skipped:o.length-s.length,...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.map(({pullRequest:e})=>e.number).join(`, `)]))})}return{refreshed:s.map(({pullRequest:e})=>e),baseRefHeads:[...a.values()].flatMap(e=>e._tag===`Unreadable`?jr(e.recorded):[e.head]).sort((e,t)=>e.baseRefName.localeCompare(t.baseRefName))}}),g2=4,_2=4,v2=z.pipe(L(`GitHubPollWatchKey`)),y2=class extends V(`@usine/orchestrator/StoredPollCursor`)({boardVersion:nT(5),openPullRequests:P(d2),baseRefHeads:P(mq).pipe(DT(T([]))),cursor:hq,labelEntityTag:yE(fq),watches:P(v2).check(XT()),failingItems:P(U0).pipe(DT(T([])))}){},b2=e=>PU.make(`github-poll:${Hk(e.name)}`),x2=({loop:e})=>v2.make(JSON.stringify([e.name,e.trigger.on,e.trigger.if])),S2=(e,t)=>e.config.repos.map(n=>{let r=t.filter(({loop:e})=>e.trigger.on!==`schedule`&&IY(e.selector,n));return{repository:n,declaredLabels:e.config.labels,loops:r,watches:r.map(x2).sort()}}),C2=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),w2=class e extends Lr()(`@usine/orchestrator/PollingTriggers`){static layer=Yf(e,E(function*(){let e=yield*LU,t=yield*OH,n=yield*vJ,r=yield*VU,i=yield*wk(y()),a=yield*wk(new Map),o=yield*o2,s=yield*ID(1),c=yield*wk({instance:y(),repositories:new Set}),l=yield*wk(new Map),u=e=>new y2({boardVersion:5,openPullRequests:[],baseRefHeads:[],cursor:hq.empty,labelEntityTag:y(),watches:e,failingItems:[]}),d=k(`PollingTriggers.readCursor`)(function*(t){yield*O({repository:t.repository.name});let n=yield*e.read(b2(t.repository),y2);return x(n)?u(t.watches):C2(n.value.watches,t.watches)?n.value:(yield*A(`Watched loops changed; re-polling the repository from scratch`,{repository:t.repository.name,previousWatches:n.value.watches.length,currentWatches:t.watches.length}),u(t.watches))}),f=k(`PollingTriggers.writeCursor`)(function*(t,n){yield*O({repository:t.repository.name}),yield*e.write(b2(t.repository),y2,n)}),p=k(`PollingTriggers.checkOpenIssuesWhenDue`)(function*(e){yield*O({repository:e.repository.name});let t=b2(e.repository),n=yield*ap,r=(yield*Tk(l)).get(t);return r!==void 0&&n-r<no(s2)?(yield*j(`Open issues were checked less than 10 minutes ago; skipped`,{repository:e.repository.name,lastCheckedAt:q_(L_(r))}),c2):(yield*Ok(l,e=>new Map(e).set(t,n)),yield*l2(e.repository,e.loops))}),m=k(`PollingTriggers.pollRepository`)(function*(e){yield*O({repository:e.repository.name});let r=(yield*t.pendingResets()).filter(({repository:t})=>Hk(t)===Hk(e.repository.name)),i=r.length>0?u(e.watches):yield*d(e);r.length>0&&(yield*A(`Cycle budget reset requests fresh repository polling`,{repository:e.repository.name,items:r.map(({itemKey:e})=>e)}));let a=yield*z0(e.repository.name,e.declaredLabels,i.labelEntityTag);return yield*o.defer(a.nextPollAt),yield*E(function*(){let s=yield*n.changes(e.repository.name,i.cursor);yield*o.defer(s.backoffUntil);let l=(yield*Tk(c)).repositories.has(b2(e.repository))?[]:i.failingItems,u=s._tag===`RepositoryChanges`?s.items:[],d=new Set(u.map(({number:e})=>e)),m=yield*h2(e.repository.name,i.openPullRequests,i.baseRefHeads,new Set([...d,...l.map(({number:e})=>e)])),h=new Map([...l.map(e=>[e.number,W0(e)]),...m.refreshed.map(({number:e,updatedAt:t})=>[e,new _q({number:e,updatedAt:t})])]);for(let e of u)h.set(e.number,e);s._tag===`RepositoryChanges`&&(yield*A(`Repository changed`,{repository:e.repository.name,changedItems:s.items.length,backlog:s.backlog}));let g=new Set([...m.refreshed,...l].map(({number:e})=>e).filter(e=>!d.has(e)));l.length>0&&(yield*A(`Evaluating Items whose Loops failed before this process started or the instance was reloaded`,{repository:e.repository.name,items:l.map(({number:e})=>e).join(`, `)}));let _=N0([s.nextPollAt,a.nextPollAt]);yield*j(`Refreshing detected Items and open pull requests`,{repository:e.repository.name,detection:s._tag,openPullRequests:i.openPullRequests.length,refreshedPullRequests:m.refreshed.length,items:h.size});let v=new Map(i.failingItems.map(e=>[e.number,e])),ee=yield*Nh(h.values(),t=>E(function*(){let n=yield*B0(e.repository.name,t),r=yield*e2(e.repository,e.loops,n),i=G0(t,n.projection.contentHash,r.failures);return yield*X0(e.repository.name,t.number,C(v.get(t.number)),i),{_tag:`Evaluated`,item:t,observation:n,cycle:r,failing:i}}).pipe(og(`GitHubItemNotFoundError`,n=>E(function*(){if(!g.has(t.number))return yield*n;let r=yield*t2(e.repository,e.loops,t._tag===`ChangedIssue`?`issue`:`pr`,t.number),a=yield*V0(e.repository.name,t.number);return yield*$g(`GitHub no longer has an Item the poll cursor kept; it is dropped from the cursor`,{repository:e.repository.name,item:t.number,openPullRequest:i.openPullRequests.some(({number:e})=>e===t.number),revokedRuns:r,projectionMarkedGone:a,errorTag:n._tag,message:n.message}),{_tag:`Missing`,revokedRuns:r}}))),{concurrency:_2}),te=ee.flatMap(e=>e._tag===`Evaluated`?[e]:[]),ne=ee.reduce((e,t)=>e+(t._tag===`Missing`?t.revokedRuns:0),0),re=te.map(({cycle:e})=>e),ie=yield*p(e);yield*o.defer(ie.nextPollAt),yield*i2(e.repository.name);let ae=[...i.failingItems.filter(({number:e})=>!h.has(e)),...te.flatMap(({failing:e})=>jr(e))].sort((e,t)=>e.number-t.number),oe=[...i.openPullRequests.filter(({number:e})=>!h.has(e)),...te.flatMap(({item:e,observation:t})=>jr(f2(e,t.snapshot)))],se=m.baseRefHeads.filter(({baseRefName:e})=>oe.some(t=>Pr(t.baseRefName,e))),ce=new y2({boardVersion:5,cursor:s.cursor,labelEntityTag:a.labelEntityTag,watches:e.watches,openPullRequests:oe,baseRefHeads:se,failingItems:ae});return(s._tag===`RepositoryChanges`||h.size>0||a.entityTagChanged||!Le(se,i.baseRefHeads))&&(yield*f(e,ce)),yield*Ok(c,t=>({...t,repositories:new Set([...t.repositories,b2(e.repository)])})),yield*Nh(r,t.acknowledgeReset,{discard:!0}),{changedItems:s._tag===`RepositoryChanges`?s.items.length:0,submissions:re.flatMap(({submissions:e})=>e),revokedRuns:re.reduce((e,t)=>e+t.revokedRuns,ne+ie.revokedRuns),failures:[...a.failures,...ie.failures,...ae.flatMap(t=>q0(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:N0([_,ie.nextPollAt])}}).pipe(ug(t=>({_tag:`InterruptedRepositoryCycle`,error:t,failures:[...a.failures,...i.failingItems.flatMap(t=>q0(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:a.nextPollAt})))}),h=(yield*Sg()).pipe(gi(f0,OH,JY,vJ,mU,hU,b0,jU,MU,nW)),g=k(`PollingTriggers.poll`)(function*(e){yield*o.awaitBackoff,yield*Ok(c,t=>Pr(t.instance,e)?t:{instance:b(e),repositories:new Set});let t=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let n of e.loops)n.trigger.on!==`schedule`&&t.has(n.name)&&(yield*j(`Paused Loop skipped during repository polling`,{loop:n.name}));let n=S2(e,(yield*w0(e)).filter(({loop:e})=>!t.has(e.name))),s=yield*Nh(n,e=>Qh(m(e)).pipe(tg(t=>({repository:e,result:t}))),{concurrency:g2}),l=[],u=[],d=[],f=[],p=yield*z_;for(let{repository:e,result:t}of s){if(Di(t)){l.push(t.success),f.push(...t.success.preflightFindings),yield*Ok(a,t=>new Map(t).set(Hk(e.repository.name),new A0({repository:e.repository.name,completedAt:p})));continue}let n=t.failure._tag===`InterruptedRepositoryCycle`,r=n?t.failure.error:t.failure;n&&(u.push(...t.failure.failures),f.push(...t.failure.preflightFindings),d.push(t.failure.nextPollAt),yield*o.defer(t.failure.nextPollAt)),r._tag===`GitHubRateLimitError`?(yield*$g(`GitHub rate limit reached; delaying the next cycle`,{repository:e.repository.name,operation:r.operation,retryAt:q_(r.retryAt)}),d.push(b(r.retryAt)),yield*o.defer(b(r.retryAt))):(yield*e_(`Repository poll cycle failed; siblings were unaffected`,{repository:e.repository.name,...M0(r)}),u.push(new k0({repository:e.repository.name,errorTag:r._tag,message:r.message})))}let h=yield*Tk(a),g=new j0({repositoryPolls:n.flatMap(({repository:e})=>jr(C(h.get(Hk(e.name))))),repositories:n.length,changedItems:l.reduce((e,t)=>e+t.changedItems,0),submissions:l.flatMap(({submissions:e})=>e),revokedRuns:l.reduce((e,t)=>e+t.revokedRuns,0),failures:[...l.flatMap(({failures:e})=>e),...u],preflightFindings:f,nextPollAt:N0([...l.map(({nextPollAt:e})=>e),...d])});return yield*Ek(i,b(g)),g},Tg(h),s.withPermits(1)),_=k(`PollingTriggers.refreshHint`)(function*(e,t){yield*O({repository:t.repository,item:t.item.number}),yield*o.awaitBackoff;let n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop)),i=S2(e,(yield*w0(e)).filter(({loop:e})=>!n.has(e.name))).find(({repository:e})=>Hk(e.name)===Hk(t.repository));if(i===void 0){yield*A(`Self-write Hint ignored for an unmanaged repository`,{repository:t.repository,item:t.item.number});return}let a=yield*B0(i.repository.name,t.item),s=yield*e2(i.repository,i.loops,a);for(let e of s.failures)yield*$g(`Self-write Hint could not evaluate a Loop on the Item`,{repository:t.repository,item:t.item.number,loop:e.loop,stage:e.stage,errorTag:e.errorTag,message:e.message});yield*A(`Self-write Hint refreshed the Item`,{repository:t.repository,item:t.item.number,submissions:s.submissions.length,revokedRuns:s.revokedRuns,failures:s.failures.length})},Tg(h),(e,t,n)=>e.pipe(ag(e=>E(function*(){e._tag===`GitHubRateLimitError`&&(yield*o.defer(b(e.retryAt))),yield*$g(`Self-write Hint refresh failed; the normal poll will retry`,{repository:n.repository,item:n.item.number,...M0(e)})})),s.withPermits(1))),v=(e,t,n,r)=>E(function*(){let i=Math.max(n,r),a=t;for(;;){let t=i-(yield*ap);if(t<=0)return;let n=yield*_g([gg($a(t)).pipe(tg(()=>({_tag:`Due`}))),o.take.pipe(tg(e=>({_tag:`Hint`,hint:e}))),r2(e,a).pipe(tg(e=>({_tag:`Reloaded`,instance:e})))]);if(n._tag===`Due`)return;if(n._tag===`Hint`){yield*_(yield*e.get,n.hint);continue}a=n.instance,i=r;let s=r-(yield*ap);s>0?yield*A(`Instance reloaded; the next poll waits for the time GitHub asked for`,{sleepMs:s}):yield*A(`Instance reloaded; polling now instead of after poll_interval`)}});return{latest:Tk(i),poll:g,run:e=>E(function*(){let t=yield*e.get,n=yield*ap,r=yield*Qh(g(t));if(Ei(r)){let e=t.config.settings.pollInterval*1e3;yield*e_(`Poll cycle could not read Loop runtime state; retrying`,{errorTag:r.failure._tag,message:r.failure.message,operation:r.failure.operation,sleepMs:e}),yield*gg($a(e));return}let i=r.success,a=n+t.config.settings.pollInterval*1e3,o=vr(i.nextPollAt,{onNone:()=>0,onSome:G_}),s=yield*ap,c=Math.max(0,Math.max(a,o)-s);yield*A(`Poll cycle complete`,{repositories:i.repositories,changedItems:i.changedItems,submissions:i.submissions.length,revokedRuns:i.revokedRuns,failures:i.failures.length,preflightFindings:i.preflightFindings.length,sleepMs:c}),yield*v(e,t,a,o)}).pipe(Bg),hint:o.offer}})).pipe(np(o2.layer))},T2=4,E2=6e4,D2=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...O0(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},O2=class extends H(`@usine/orchestrator/ScheduleAgentFailure`)(`ScheduleAgentFailure`,{loop:Kk,agent:FA,message:M}){},k2=class extends H(`@usine/orchestrator/ScheduleTickFailure`)(`ScheduleTickFailure`,{loop:Kk,repository:Lk,scheduledAt:_E,errorTag:z,message:M}){},A2=class extends H(`@usine/orchestrator/ScheduleCronFailure`)(`ScheduleCronFailure`,{loop:Kk,cron:M,tz:M,message:M}){},j2=F([O2,A2,k2]),M2=class extends V(`@usine/orchestrator/ScheduleCycle`)({loops:R.check(HT(0)),fanout:R.check(HT(0)),submissions:P(qP),skipped:R.check(HT(0)),alreadyFired:R.check(HT(0)),failures:P(j2),nextTickAt:B(_E)}){},N2=e=>e.loops.flatMap(t=>{let n=t.trigger;return n.on===`schedule`?[{loop:t,repositories:e.config.repos.filter(e=>IY(t.selector,e)),trigger:n}]:[]}),P2=(e,t)=>{let n=U_(t);return n.setUTCSeconds(0,0),I_(Om(e,n)?n:jm(e,n))},F2=(e,t)=>I_(Am(e,U_(t))),I2=(e,t)=>vr(H_(e,t),{onNone:()=>q_(e),onSome:J_}),L2=e=>e.length===0?y():R_(Math.min(...e.map(G_))),R2=e=>bN.make(JSON.stringify([`github`,Hk(e.name)])),z2=(e,t,n)=>Wk.make(JSON.stringify([e.name,Hk(t.name),q_(n)])),B2=e=>({tick:{scheduledAt:q_(e.scheduledAt),scheduledAtLocal:e.scheduledAtLocal,cron:e.trigger.cron,tz:e.trigger.tz}});(class e extends Lr()(`@usine/orchestrator/ScheduleTriggers`){static layer=Yf(e,E(function*(){let e=yield*f0,t=yield*JY,n=yield*nW,r=yield*VU,i=yield*wk(y()),a=yield*wk({instance:y(),ticks:new Map}),o=new WeakMap,s=e=>{let t=o.get(e);if(t!==void 0)return t;let n=Dm(e.cron,e.tz);return o.set(e,n),n},c=k(`ScheduleTriggers.submitTick`)(function*(r,i){yield*O({loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:q_(r.scheduledAt)});let a=B2(r),o={repo:eZ(r.repository),item:a};if(!(yield*t.evaluateBoolean(r.trigger.if,$X(`schedule`),o)))return yield*j(`Scheduled Tick did not match its expression`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:q_(r.scheduledAt)}),y();let s=z2(r.loop,r.repository,r.scheduledAt),c=yield*e.renderPrompt(r.loop,o),l=yield*n.submit(E0({cycleGeneration:JN.make(0),agent:r.agent,dedupKey:s,itemKey:R2(r.repository),loop:r.loop,payload:a,receivedAt:i,repository:r.repository,revision:x0,task:DM.make(c),parentModel:r.parentModel}));return yield*A(`Submitted scheduled Tick`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:q_(r.scheduledAt),scheduledAtLocal:r.scheduledAtLocal,result:l._tag,...D0(l)}),b(l)}),l=k(`ScheduleTriggers.tick`)(function*(e){let t=yield*z_,n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let t of e.loops)t.trigger.on===`schedule`&&n.has(t.name)&&(yield*j(`Paused Loop skipped during schedule evaluation`,{loop:t.name}));let o=N2(e).filter(({loop:e})=>!n.has(e.name)),l=yield*Dk(a,t=>{let n=Pr(t.instance,e)?t:{instance:b(e),ticks:new Map};return[n.ticks,n]}),u=[],d=[],f=[],p=new Map,m=[],h=0;for(let n of o){n.repositories.length===0&&(yield*$g(`Schedule loop selected no repositories`,{loop:n.loop.name}));let r=yield*Kh({try:()=>{let e=s(n.trigger),r=P2(e,t);return{latest:r,latestLocal:I2(r,n.trigger.tz),next:F2(e,t)}},catch:e=>e}).pipe(Qh);if(Ei(r)){yield*e_(`Schedule cron boundaries could not be computed`,{loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}),f.push(new A2({loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}));continue}let i=r.success;m.push(i.next);let a=G_(i.latest),o=l.get(n.loop.name);if(o!==void 0&&o>=a){h+=1,yield*j(`Tick already fired`,{loop:n.loop.name,scheduledAt:q_(i.latest)});continue}let c=yield*Qh(C0(e,n.loop));if(Ei(c)){let e=c.failure;yield*e_(`Schedule loop could not resolve its Agent`,{loop:e.loop,agent:e.agent,errorTag:e._tag,message:e.message}),d.push(new O2({loop:e.loop,agent:e.agent,message:e.message}))}else if(n.repositories.length!==0){p.set(n.loop.name,a),yield*A(`Schedule tick due`,{loop:n.loop.name,agent:c.success.agent.name,cron:n.trigger.cron,tz:n.trigger.tz,scheduledAt:q_(i.latest),scheduledAtLocal:i.latestLocal,repositories:n.repositories.length,nextTickAt:q_(i.next)});for(let e of n.repositories)u.push({agent:c.success.agent,loop:n.loop,parentModel:c.success.parentModel,repository:e,scheduledAt:i.latest,scheduledAtLocal:i.latestLocal,trigger:n.trigger})}}yield*O({schedules:o.length,fanout:u.length});let g=yield*Nh(u,e=>Qh(c(e,t)).pipe(tg(t=>({candidate:e,result:t}))),{concurrency:T2}),_=[],v=[],ee=new Set,te=new Set,ne=0;for(let{candidate:e,result:t}of g){if(Di(t)){S(t.success)?(_.push(t.success.value),ee.add(e.loop.name)):ne+=1;continue}let n=t.failure;te.add(e.loop.name),yield*e_(`Scheduled Tick failed; sibling fanout was unaffected`,{loop:e.loop.name,repository:e.repository.name,agent:e.agent.name,scheduledAt:q_(e.scheduledAt),...D2(n)}),v.push(new k2({loop:e.loop.name,repository:e.repository.name,scheduledAt:e.scheduledAt,errorTag:n._tag,message:n.message}))}yield*Ok(a,e=>{let t=new Map(e.ticks);for(let[e,n]of p)ee.has(e)&&!te.has(e)&&t.set(e,n);return{...e,ticks:t}});let re=new M2({loops:o.length,fanout:u.length,submissions:_,skipped:ne,alreadyFired:h,failures:[...d,...f,...v],nextTickAt:L2(m)});return yield*Ek(i,b(re)),re}),u=(e,t,n)=>vg(gg($a(n)),r2(e,t).pipe(Xh(A(`Instance reloaded; evaluating schedules now instead of after the sleep`))));return{latest:Tk(i),run:e=>E(function*(){let t=yield*e.get,n=yield*Qh(l(t));if(Ei(n)){yield*e_(`Schedule cycle could not read Loop runtime state; retrying`,{errorTag:n.failure._tag,message:n.failure.message,operation:n.failure.operation,sleepMs:E2}),yield*u(e,t,E2);return}let r=n.success,i=yield*ap,a=vr(r.nextTickAt,{onNone:()=>i+E2,onSome:G_}),o=Math.min(E2,Math.max(0,a-i)),s={loops:r.loops,fanout:r.fanout,submissions:r.submissions.length,skipped:r.skipped,alreadyFired:r.alreadyFired,failures:r.failures.length,nextTickAt:vr(r.nextTickAt,{onNone:()=>`none`,onSome:q_}),sleepMs:o};r.fanout===0&&r.failures.length===0?yield*j(`Schedule cycle complete`,s):yield*A(`Schedule cycle complete`,s),yield*u(e,t,o)}).pipe(Bg),tick:l}}))});var V2=class extends H(`@usine/orchestrator/ApprovalNeed`)(`ApprovalNeed`,{id:M,repository:Lk,runId:kA,loop:Kk,item:I(SJ)}){},H2=class extends H(`@usine/orchestrator/RunFailureNeed`)(`RunFailureNeed`,{id:M,repository:Lk,runId:kA,loop:Kk,failure:FB}){},U2=class extends H(`@usine/orchestrator/PollFailureNeed`)(`PollFailureNeed`,{id:M,failure:k0}){},W2=class extends H(`@usine/orchestrator/PreflightFindingNeed`)(`PreflightFindingNeed`,{id:M,finding:_0}){},G2=class extends H(`@usine/orchestrator/BoardProjectionNeed`)(`BoardProjectionNeed`,{id:M,failure:kJ}){},K2=class extends H(`@usine/orchestrator/ScheduleFailureNeed`)(`ScheduleFailureNeed`,{id:M,failure:j2}){},q2=class extends H(`@usine/orchestrator/ConfigFileNeed`)(`ConfigFileNeed`,{id:M,kind:bT([`loop`,`agent`]),error:ZY}){},J2=class extends H(`@usine/orchestrator/UnconfiguredWorkerNeed`)(`UnconfiguredWorkerNeed`,N({id:M,worker:BA,attempts:R.check(HT(1)),running:R.check(HT(0))}).check(NT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},Y2=class extends H(`@usine/orchestrator/UnconfirmedStopNeed`)(`UnconfirmedStopNeed`,{id:M,repository:Lk,runId:kA,loop:Kk,attemptNumber:EM,worker:BA}){},X2=F([class extends H(`CycleBudgetNeed`)(`CycleBudgetNeed`,{id:M,ask:$N,itemLabel:M,itemUrl:I(M)}){},V2,G2,H2,U2,W2,K2,q2,J2,Y2]),Z2=bT([`clear`,`active`,`needs-you`]),Q2=class extends V(`@usine/orchestrator/ProjectView`)({repository:Lk,status:Z2,runs:P(eH),board:AJ,labels:P(jJ),preflightFindings:P(_0)}){},$2=class extends V(`@usine/orchestrator/LoopView`)({name:Kk,trigger:M,agent:FA,paused:cT}){},e4=class extends H(`@usine/orchestrator/ReadyOverview`)(`Ready`,{projects:P(Q2),loops:P($2),needsYou:P(X2)}){},t4=class extends H(`@usine/orchestrator/NeedsSetupOverview`)(`NeedsSetup`,{errorTag:z,projects:P(Q2),loops:P($2),needsYou:P(X2)}){},n4=F([e4,t4]),r4=10,i4=class extends H(`@usine/github/LabelAdded`)(`LabelAdded`,{at:_E,label:Bq}){},a4=class extends H(`@usine/github/LabelRemoved`)(`LabelRemoved`,{at:_E,label:Bq}){},o4=class extends H(`@usine/github/Commented`)(`Commented`,{at:_E,url:z}){},s4=bT([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`DISMISSED`]),c4=class extends H(`@usine/github/Reviewed`)(`Reviewed`,{at:_E,url:z,state:s4}){};F([i4,a4,o4,c4]);var l4=`
276
+ __typename
277
+ ... on LabeledEvent { createdAt actor { __typename login } label { name color description } }
278
+ ... on UnlabeledEvent { createdAt actor { __typename login } label { name color description } }
279
+ ... on IssueComment { createdAt url author { __typename login } }`,u4=`
280
+ query UsineItemTimeline($owner: String!, $name: String!, $number: Int!, $since: DateTime!, $after: String) {
281
+ repository(owner: $owner, name: $name) {
282
+ issueOrPullRequest(number: $number) {
283
+ ... on Issue {
284
+ timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT]) {
285
+ pageInfo { hasNextPage endCursor }
286
+ nodes {${l4}
287
+ }
288
+ }
289
+ }
290
+ ... on PullRequest {
291
+ timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT, PULL_REQUEST_REVIEW]) {
292
+ pageInfo { hasNextPage endCursor }
293
+ nodes {${l4}
294
+ ... on PullRequestReview { createdAt submittedAt url state author { __typename login } }
295
+ }
296
+ }
297
+ }
298
+ }
299
+ }
300
+ }
301
+ `,d4=I(N({__typename:M,login:M})),f4=N({name:Rq,color:zq,description:I(M)}),p4=e=>N({__typename:nT(e),createdAt:vE,actor:d4,label:f4}),m4=F([p4(`LabeledEvent`),p4(`UnlabeledEvent`),N({__typename:nT(`IssueComment`),createdAt:vE,url:z,author:d4}),N({__typename:nT(`PullRequestReview`),createdAt:vE,submittedAt:I(vE),url:z,state:bT([...s4.literals,`PENDING`]),author:d4})]),h4=N({repository:yE(N({issueOrPullRequest:yE(N({timelineItems:N({pageInfo:N({hasNextPage:cT,endCursor:I(M)}),nodes:P(I(m4))})}))}))}),g4=(e,t)=>{let n=t=>t!==null&&t.__typename===`Bot`&&t.login===e,r=e=>new Bq({name:e.name,color:e.color,description:C(e.description)});switch(t.__typename){case`LabeledEvent`:return n(t.actor)?[new i4({at:t.createdAt,label:r(t.label)})]:[];case`UnlabeledEvent`:return n(t.actor)?[new a4({at:t.createdAt,label:r(t.label)})]:[];case`IssueComment`:return n(t.author)?[new o4({at:t.createdAt,url:t.url})]:[];case`PullRequestReview`:{let e=t.state;return!n(t.author)||e===`PENDING`?[]:[new c4({at:t.submittedAt??t.createdAt,url:t.url,state:e})]}}},_4=class e extends Lr()(`@usine/github/GitHubItemHistory`){static layer=Yf(e,E(function*(){let e=yield*oq,t=yield*yG,n=k(`GitHubItemHistory.timelinePage`)(function*(n,r,i,a){let o=yield*e.installationToken(),{name:s,owner:c}=Vk(n),l=yield*dq(t,o,`fetch-item-timeline`,u4,{owner:c,name:s,number:r,since:i,after:a},h4);if(x(l.repository))return yield*WK(`fetch-item-timeline`,`repository "${n}" is null: deleted, renamed, or no longer accessible`);let u=l.repository.value.issueOrPullRequest;if(x(u))return yield*new LK({operation:`fetch-item-timeline`,item:r,message:`Issue or pull request ${n}#${r} was not found on GitHub. It was deleted or transferred, or the GitHub App can no longer read it.`});let{pageInfo:d,nodes:f}=u.value.timelineItems;return d.hasNextPage?d.endCursor===null?yield*WK(`fetch-item-timeline`,`GitHub returned hasNextPage for the timeline without an endCursor`):{nodes:f,next:b(d.endCursor)}:{nodes:f,next:y()}});return{appChanges:k(`GitHubItemHistory.appChanges`)(function*(t,r,i){yield*O({repository:t,item:r});let{appSlug:a}=yield*e.installation(),o=q_(i),s=[],c=y(),l=0;do{let e=yield*n(t,r,o,w(c));s.push(...e.nodes),c=e.next,l+=1}while(S(c)&&l<r4);if(S(c))return yield*WK(`fetch-item-timeline`,`the timeline of ${t}#${r} since ${o} has more than ${r4} pages`);let u=s.flatMap(e=>e===null?[]:g4(a,e));return yield*j(`Read the App's changes from an Item timeline`,{repository:t,item:r,since:o,pages:l,timelineItems:s.length,appChanges:u.length}),u})}}))},v4=class extends H(`@usine/orchestrator/LabelAddedView`)(`LabelAdded`,{at:M,label:jJ}){},y4=class extends H(`@usine/orchestrator/LabelRemovedView`)(`LabelRemoved`,{at:M,label:jJ}){},b4=class extends H(`@usine/orchestrator/CommentedView`)(`Commented`,{at:M,url:M}){},x4=class extends H(`@usine/orchestrator/ReviewedView`)(`Reviewed`,{at:M,url:M,state:s4}){},S4=class extends H(`@usine/orchestrator/BoardMovedView`)(`BoardMoved`,{at:M,fromLane:sV,toLane:sV}){},C4=F([v4,y4,b4,x4,S4]),w4=class extends V(`@usine/orchestrator/AttemptGitHubChangesView`)({attemptId:TM,changes:P(C4)}){},T4=class extends V(`@usine/orchestrator/RunGitHubChangesView`)({attempts:P(w4)}){},E4=1e3,D4=6e4,O4=1e3,k4=1e4,A4=(e,t)=>{let n=new Map,r=[];for(let i of t){let[t,...a]=e.filter(e=>BM(e,i.at));t!==void 0&&(a.length>0?r.push(i):n.set(t.attemptId,[...n.get(t.attemptId)??[],i]))}return{attributed:n,ambiguous:r}},j4=e=>t=>{let n=G_(t.at),r=n-O4,i=G_(e.at),a=rV(e.label.name);return r-r%1e3<=i&&i<=n+k4&&(e._tag===`LabelAdded`?t.added:t.removed).some(e=>rV(e)===a)},M4=(e,t)=>{let n=new Set,r=[];for(let i of t){let t=i._tag===`LabelAdded`||i._tag===`LabelRemoved`?e.find(j4(i)):void 0;t===void 0?r.push(i):n.add(t)}return{moves:e.filter(e=>n.has(e)),rest:r}},N4=e=>new jJ({name:nV.make(e.name),color:e.color,description:w(e.description)}),P4=e=>xk(e,{LabelAdded:({at:e,label:t})=>new v4({at:q_(e),label:N4(t)}),LabelRemoved:({at:e,label:t})=>new y4({at:q_(e),label:N4(t)}),Commented:({at:e,url:t})=>new b4({at:q_(e),url:t}),Reviewed:({at:e,url:t,state:n})=>new x4({at:q_(e),url:t,state:n})}),F4=e=>new S4({at:q_(e.at),fromLane:sV.make(e.fromLane),toLane:sV.make(e.toLane)}),I4=E(function*(){let e=yield*DB,t=yield*_4,n=yield*EH,r=yield*wk(new Map),i=k(`RunGitHubChanges.windowFor`)(function*(t){let n=LM(t);if(S(n))return n;let[r]=yield*e.transcript(new zN({attemptId:t.id,before:y(),limit:1}));return r===void 0?(yield*A(`An ended Attempt has neither an end time nor a transcript; no GitHub change is placed in it`,{attemptId:t.id}),y()):b(new IM({attemptId:t.id,startedAt:t.startedAt,endedAt:b(r.receivedAt)}))});return{read:k(`RunGitHubChanges.read`)(function*(a){yield*O({runId:a});let o=yield*e.inspect(a),s=Ww(P0)(o.itemKey);if(x(s))return yield*j(`The Run has no GitHub Item, so it has no GitHub changes`,{runId:a}),new T4({attempts:[]});let[,,c]=s.value,l=o.repository;yield*O({repository:l,item:c});let u=e=>new T4({attempts:o.attempts.map(({id:t})=>new w4({attemptId:t,changes:e.get(t)??[]}))}),d=yield*Tk(r),f=o.attempts.filter(({id:e})=>!d.has(e));if(f.length===0)return yield*j(`Served the Run's GitHub changes from the Attempt cache`,{runId:a,attempts:o.attempts.length}),u(d);let p=yield*e.forItems([o.itemKey]),m=(yield*Nh([...new Map([...p.flatMap(({attempts:e})=>e),...o.attempts].map(e=>[e.id,e])).values()],i)).flatMap(jr),h=yield*ap,g=new Map,_=[],v=f.flatMap(e=>{let t=m.find(({attemptId:t})=>t===e.id);return t===void 0?(g.set(e.id,[]),_.push(e.id),[]):[t]});if(v.length>0){let e=Math.min(...v.map(({startedAt:e})=>G_(e))),r=L_(e-e%1e3),[i,s]=yield*Mh([t.appChanges(l,c,r),n.onItem(o.itemKey,K_(r,{milliseconds:k4}))],{concurrency:`unbounded`}),{moves:u,rest:d}=M4(s,i),{attributed:f,ambiguous:p}=A4(m,d);p.length>0&&(yield*A(`Left out GitHub changes that overlapping Attempts on the Item could each have made`,{runId:a,repository:l,item:c,changes:p.length,at:p.map(({at:e})=>q_(e)).join(`, `)}));for(let e of v){let t=[...(f.get(e.attemptId)??[]).map(e=>({at:G_(e.at),view:P4(e)})),...u.flatMap(t=>{let n=G_(t.at);return G_(e.startedAt)<=n&&vr(e.endedAt,{onNone:()=>!0,onSome:e=>n<=G_(e)})?[{at:n,view:F4(t)}]:[]})];g.set(e.attemptId,t.sort((e,t)=>e.at-t.at).map(({view:e})=>e)),S(e.endedAt)&&h-G_(e.endedAt.value)>=D4&&_.push(e.attemptId)}yield*A(`Read the App's GitHub changes on a Run's Item`,{runId:a,repository:l,item:c,since:q_(r),appChanges:i.length,boardMoves:s.length,boardMoveChanges:i.length-d.length,placed:v.reduce((e,{attemptId:t})=>e+(f.get(t)?.length??0),0),cachedAttempts:_.length})}let ee=yield*kk(r,e=>{let t=new Map(e);for(let e of _)t.set(e,g.get(e)??[]);for(let e of[...t.keys()].slice(0,Math.max(0,t.size-E4)))t.delete(e);return t});return u(new Map([...ee,...g]))})}});(class e extends Lr()(`@usine/orchestrator/RunGitHubChanges`){static layer=Yf(e,I4)});var L4=500,R4=class extends V(`@usine/orchestrator/TaskItemView`)({...SJ.fields,labels:P(nV),conflicting:cT}){},z4=class extends V(`@usine/orchestrator/TaskLaneView`)({id:bJ,name:sV}){},B4=class extends V(`@usine/orchestrator/TaskCommentView`)({runId:kA,kind:Xj,url:M,postedAt:I(M),attemptEndedAt:I(M)}){},V4=class extends V(`@usine/orchestrator/TaskView`)({repository:Lk,number:xN,title:M,current:bN,lane:z4,needsYou:cT,items:vT(R4),runs:P(eH),comments:P(B4)}){},H4=vr({onNone:()=>null,onSome:q_}),U4=e=>{let t=(t,n)=>new B4({runId:e.run.id,kind:t.kind,url:t.url.toString(),postedAt:H4(t.at),attemptEndedAt:H4(n)}),n=na(e.attempts,e=>Fr(e.outcome,({_tag:e})=>e===`Succeeded`)).pipe(Or(({endedAt:e})=>e)),r=vr(e.step.result,{onNone:()=>[],onSome:({facts:e})=>e.flatMap(e=>e._tag===`Comment`?[t(e,n)]:[])}),i=e.attempts.flatMap(e=>e.comments.map(n=>t(n,e.endedAt))),a=({postedAt:e,attemptEndedAt:t})=>e??t??``;return _a([...r,...i].sort((e,t)=>a(t).localeCompare(a(e))),(e,t)=>e.url===t.url)},W4=E(function*(){let e=yield*DB,t=yield*VU,n=yield*mU,r=yield*jU,i=yield*OH;return{read:k(`TaskReader.read`)(function*(a,o,s){yield*O({repository:o,item:s});let c=a.config.repos.find(({name:e})=>Hk(e)===Hk(o));if(c===void 0)return yield*A(`Task read refused; the repository is not a registered Project`,{repository:o,item:s}),yield*new MJ({repository:o});let[l,u,d,f]=yield*Mh([n.list(c.name,{limit:L4}),r.get(c.name),t.states,i.asks()],{concurrency:`unbounded`}),p=yield*e.forItems(l.map(({itemKey:e})=>e)),m=yield*pH(e,p),h=new Set(d.filter(e=>e.paused).map(e=>e.loop)),g=dH(a.config.workers),_=(yield*eY(c,vr(u,{onNone:()=>[],onSome:({labels:e})=>e.map(({name:e})=>e)}),l,p.map(e=>mH(e,h,g)),f.map(({itemKey:e})=>e),new Map,new Map,m)).lanes.flatMap(e=>e.items.map(t=>({lane:e,task:t}))).find(({task:e})=>e.items.some(e=>e.number===s));if(_===void 0)return yield*A(`Task read found no Task; the Item is not among the Project's newest Board Items`,{repository:c.name,item:s,window:L4}),yield*new NJ({repository:c.name,item:s});let{lane:v,task:ee}=_,te=new Set(ee.items.map(({itemKey:e})=>e)),ne=yield*Nh(l.filter(({itemKey:e})=>te.has(e)),e=>zJ(e).pipe(Qh)),re=new Map;for(let e of ne){if(Ei(e)){yield*e_(`Task Item could not be projected; the other Items are shown`,{repository:c.name,itemKey:e.failure.itemKey,message:e.failure.message});continue}let{itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}=e.success;re.set(t,new R4({itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}))}let[ie,...ae]=ee.items.flatMap(({itemKey:e})=>{let t=re.get(e);return t===void 0?[]:[t]});if(ie===void 0)return yield*new NJ({repository:c.name,item:s});let oe=new Set(ee.runs.map(({id:e})=>e)),se=p.filter(({run:e})=>oe.has(e.id)).sort((e,t)=>G_(t.run.openedAt)-G_(e.run.openedAt)||t.run.id.localeCompare(e.run.id)).flatMap(U4),ce=new V4({repository:c.name,number:ie.number,title:ee.title,current:ee.itemKey,lane:new z4({id:v.id,name:v.name}),needsYou:ee.needsYou,items:[ie,...ae],runs:[...ee.runs].reverse(),comments:se});return yield*j(`Read a Task`,{repository:c.name,item:s,origin:ce.number,lane:v.name,items:ce.items.length,runs:ce.runs.length,comments:se.length}),ce})}});(class e extends Lr()(`@usine/orchestrator/TaskReader`){static layer=Yf(e,W4)});var G4=bT([`binary`,`version`,`login`]),K4=class extends NE(`HarnessUnavailableError`)(`HarnessUnavailableError`,{harness:MA,capability:G4,message:z}){};F([class extends H(`HarnessReady`)(`HarnessReady`,{harness:MA}){},K4]),Bw(K4),fr(cr,({harness:e})=>e);var q4=class e extends Lr()(`@usine/orchestrator/WorkerStatus`){static idle=qf(e)({slots:T([]),queue:T([]),preflights:T([]),machines:T([]),provisioning:T([])})},J4=class extends V(`@usine/orchestrator/LoopSelectorView`)({repos:I(P(Lk)),tags:I(P(tY))}){},Y4=class extends V(`@usine/orchestrator/LoopFileView`)({name:Kk,file:YY,stream:bT([`issue`,`pr`,`schedule`]),condition:GY,cron:I(nX),timeZone:I(rX),selector:I(J4),repositories:P(Lk),approval:Jk,maxCycles:qN,permissions:Xk,priority:I(dX),step:eM,agent:FA,prompt:uX,paused:cT,undeclaredLabels:P(nV)}){},X4=class extends V(`@usine/orchestrator/QuarantinedLoopView`)({name:z,file:YY,error:ZY}){},Z4=class extends V(`@usine/orchestrator/AgentFileView`)({name:FA,file:YY,harness:MA,model:jA,effort:NA,parentModel:I(jA),parentEffort:I(NA),resolvedParentModel:I(jA),resolvedParentEffort:NA,persona:IA,loops:P(Kk)}){},Q4=class extends V(`@usine/orchestrator/InvalidAgentView`)({name:z,file:YY,error:ZY}){},$4=class extends V(`@usine/orchestrator/GatewayView`)({domain:YA,destination:GA,adminPort:XA,adminTokenEnv:z,llmProviders:P(ZA)}){},e3=class extends V(`@usine/orchestrator/WorkerSlotsView`)({capacity:R,leased:R}){},t3=class extends H(`@usine/orchestrator/PassedCheckView`)(`Passed`,{checkedAt:M}){},n3=class extends H(`@usine/orchestrator/DegradedCheckView`)(`Degraded`,{checkedAt:M,message:M}){},r3=class extends H(`@usine/orchestrator/DeferredCheckView`)(`Deferred`,{checkedAt:M,message:M}){},i3=class extends H(`@usine/orchestrator/FailedCheckView`)(`Failed`,{checkedAt:M,capability:I(gV),message:M}){},a3=F([t3,n3,r3,i3]),o3=class extends V(`@usine/orchestrator/HarnessPreflightView`)({harness:MA,check:a3}){},s3=class extends V(`@usine/orchestrator/ContainerView`)({image:I($A),cpus:I(tj),memoryMib:I(nj),pids:I(rj)}){},c3=class extends V(`@usine/orchestrator/WorkerConfigurationView`)({name:BA,kind:VA,maxConcurrentAttempts:R,destination:I(GA),port:I(KA),identityFile:I(qA),root:I(JA),gateway:I($4),container:I(s3),containerLimits:I(ij).pipe(TT(T(null))),provisioner:I(jV).pipe(TT(T(null))),machines:P(DV).pipe(TT(T([]))),provisioning:I(OV).pipe(TT(T(null))),slots:I(e3),prerequisites:I(a3),harnesses:P(o3)}){},l3=class extends V(`@usine/orchestrator/RemovedWorkerView`)({name:BA,running:R}){},u3=class extends V(`@usine/orchestrator/LabelStateView`)({name:nV,onGitHub:I(cT),color:I(M),description:I(M),declared:cT,failure:I(_0)}){},d3=class extends H(`@usine/orchestrator/LabelLaneSourceView`)(`Label`,{label:u3}){},f3=class extends H(`@usine/orchestrator/StateLaneSourceView`)(`State`,{state:cV}){},p3=F([d3,f3]),m3=class extends V(`@usine/orchestrator/LaneConfigurationView`)({name:sV,sources:P(p3)}){},h3=class extends V(`@usine/orchestrator/RepositoryConfigurationView`)({name:Lk,tags:P(tY),lanes:P(m3),declaredLabels:P(u3),loops:P(Kk)}){},g3=class extends V(`@usine/orchestrator/SettingsView`)({pollInterval:R,maxChildren:R,maxAttemptMinutes:I(R),maxAttemptTokens:I(R),parentModel:I(jA),parentEffort:I(NA),operator:I(qj),webhooks:bT([`off`,`deliveries`,`endpoint`]),webhooksPublicUrl:I(M),tracing:I(N({otlpUrl:M,serviceName:M}))}){},_3=class extends V(`@usine/orchestrator/ConfigurationView`)({loops:P(Y4),quarantinedLoops:P(X4),agents:P(Z4),invalidAgents:P(Q4),workers:P(c3),removedWorkers:P(l3),repositories:P(h3),settings:g3}){},v3=e=>{let t=e.slice(e.lastIndexOf(`/`)+1).replace(/\.md$/u,``);return t===``?e:t},y3=e=>xk(e,{Passed:({checkedAt:e})=>new t3({checkedAt:q_(e)}),Degraded:({checkedAt:e,message:t})=>new n3({checkedAt:q_(e),message:t}),Deferred:({checkedAt:e,message:t})=>new r3({checkedAt:q_(e),message:t}),Failed:({checkedAt:e,capability:t,message:n})=>new i3({checkedAt:q_(e),capability:w(t),message:n})}),b3=e=>e.kind===`ssh`?{destination:w(e.destination),provisioner:PV(e),port:w(e.port),identityFile:w(e.identityFile),root:e.root,gateway:vr(e.gateway,{onNone:()=>null,onSome:e=>new $4({domain:e.domain,destination:e.destination,adminPort:e.adminPort,adminTokenEnv:e.adminTokenEnv,llmProviders:e.llmProviders})}),container:new s3({image:w(e.container.image),cpus:w(e.container.cpus),memoryMib:w(e.container.memoryMib),pids:w(e.container.pids)})}:{destination:null,provisioner:null,port:null,identityFile:null,root:null,gateway:null,container:null},x3=E(function*(){let e=yield*VU,t=yield*jU,n=yield*w2,r=yield*q4,i=k(`OperatorConfiguration.repository`)(function*(e,n,r){let i=Dr(yield*t.get(n.name),({labels:e})=>new Map(e.map(e=>[rV(e.name),e]))),a=new Map(e.config.labels.map(e=>[rV(e.name),e])),o=e=>{let t=rV(e),o=Or(i,e=>C(e.get(t))),s=a.get(t);return new u3({name:e,onGitHub:vr(i,{onNone:()=>null,onSome:()=>S(o)}),color:w(br(Or(o,({color:e})=>e),()=>Or(C(s),({color:e})=>e))),description:w(br(Or(o,({description:e})=>e),()=>Or(C(s),({description:e})=>e))),declared:s!==void 0,failure:r.find(e=>e.repository===n.name&&rV(e.label)===t)??null})};return new h3({name:n.name,tags:n.tags,lanes:n.lanes.map(e=>new m3({name:e.name,sources:e.sources.map(e=>`label`in e?new d3({label:o(e.label)}):new f3({state:e.state}))})),declaredLabels:e.config.labels.map(({name:e})=>o(e)),loops:e.loops.filter(e=>IY(e.selector,n)).map(({name:e})=>e)})});return{view:k(`OperatorConfiguration.view`)(function*(t){let{config:a}=t,[o,s,c,l,u,d]=yield*Mh([e.states,n.latest,r.slots,r.preflights,r.machines,r.provisioning],{concurrency:`unbounded`}),f=new Set(o.filter(e=>e.paused).map(e=>e.loop)),p=vr(s,{onNone:()=>[],onSome:({preflightFindings:e})=>e}),m=yield*Nh(a.repos,e=>i(t,e,p),{concurrency:4}),h=e=>t.warnings.flatMap(t=>t._tag===`UndeclaredTriggerLabelWarning`&&t.loop===e?[t.label]:[]),g=t.loops.map(e=>new Y4({name:e.name,file:YY.make(`loops/${e.name}.md`),stream:e.trigger.on,condition:e.trigger.if,cron:e.trigger.on===`schedule`?e.trigger.cron:null,timeZone:e.trigger.on===`schedule`?e.trigger.tz:null,selector:vr(e.selector,{onNone:()=>null,onSome:({repos:e,tags:t})=>new J4({repos:w(e),tags:w(t)})}),repositories:a.repos.filter(t=>IY(e.selector,t)).map(({name:e})=>e),approval:e.approval,maxCycles:e.maxCycles,permissions:e.permissions,priority:w(e.priority),step:e.step,agent:e.agent,prompt:e.body,paused:f.has(e.name),undeclaredLabels:h(e.name)})),_=t.agents.map(e=>new Z4({name:e.name,file:YY.make(`agents/${e.name}.md`),harness:e.harness,model:e.model,effort:e.effort,parentModel:w(e.parentModel),parentEffort:w(e.parentEffort),resolvedParentModel:w(RA(e.agent,a.settings.parentModel)),resolvedParentEffort:zA(e.agent,a.settings.parentEffort),persona:e.persona,loops:t.loops.filter(({agent:t})=>t===e.name).map(({name:e})=>e)})),v=new Map(c.map(e=>[e.worker,e])),ee=new Map(l.map(e=>[e.worker,e])),te=new Set(a.workers.map(({name:e})=>e)),ne=a.workers.map(e=>{let t=v.get(e.name),n=ee.get(e.name);return new c3({name:e.name,kind:e.kind,maxConcurrentAttempts:e.maxConcurrentAttempts,...b3(e),slots:t===void 0?null:new e3({capacity:t.capacity,leased:t.leased}),prerequisites:n===void 0?null:w(Dr(n.prerequisites,y3)),harnesses:(n?.harnesses??[]).map(({harness:e,check:t})=>new o3({harness:e,check:y3(t)})),containerLimits:n===void 0?null:w(n.containerLimits),machines:u.filter(t=>t.worker===e.name).map(MV),provisioning:w(Dr(C(d.find(t=>t.worker===e.name)),NV))})}),{settings:re,webhooks:ie,tracing:ae}=a,oe=new _3({loops:g,quarantinedLoops:t.quarantinedLoops.map(({file:e,error:t})=>new X4({name:v3(e),file:e,error:t})),agents:_,invalidAgents:t.invalidAgents.map(({file:e,error:t})=>new Q4({name:v3(e),file:e,error:t})),workers:ne,removedWorkers:c.filter(({worker:e,leased:t})=>!te.has(e)&&t>0).map(({worker:e,leased:t})=>new l3({name:e,running:t})),repositories:m,settings:new g3({pollInterval:re.pollInterval,maxChildren:re.maxChildren,maxAttemptMinutes:w(re.maxAttemptMinutes),maxAttemptTokens:w(re.maxAttemptTokens),parentModel:w(re.parentModel),parentEffort:w(re.parentEffort),operator:w(a.operator),webhooks:ie.mode,webhooksPublicUrl:ie.mode===`endpoint`?ie.publicUrl.href:null,tracing:vr(ae,{onNone:()=>null,onSome:({otlpUrl:e,serviceName:t})=>({otlpUrl:e.href,serviceName:t})})})});return yield*j(`Read the configuration view`,{loops:g.length,quarantinedLoops:oe.quarantinedLoops.length,agents:_.length,invalidAgents:oe.invalidAgents.length,workers:ne.length,runningWorkers:c.length,repositories:m.length}),oe})}});(class e extends Lr()(`@usine/orchestrator/OperatorConfiguration`){static layer=Yf(e,x3)});var S3=200,C3=10,w3=100,T3=500,E3=class extends H(`@usine/orchestrator/WorkerSilentView`)(`WorkerSilent`,{worker:BA,lastAnsweredAt:M}){},D3=class extends H(`@usine/orchestrator/ProviderRetryingView`)(`ProviderRetrying`,{agent:FA,message:z,retries:Wj,since:M}){},O3=F([E3,D3]),k3=class extends V(`@usine/orchestrator/RunningAttemptView`)({run:eH,attempt:GB,item:I(SJ),lastActivityAt:I(M),warnings:P(O3)}){},A3=class extends H(`@usine/orchestrator/SuppressedForOperatorView`)(`SuppressedForOperator`,{run:eH}){},j3=class extends H(`@usine/orchestrator/ClosedUnchangedView`)(`ClosedUnchanged`,{run:eH}){},M3=class extends H(`@usine/orchestrator/RunFailedView`)(`RunFailed`,{run:eH}){},N3=class extends H(`@usine/orchestrator/LoopPausedView`)(`LoopPaused`,{}){},P3=class extends H(`@usine/orchestrator/CycleBudgetUsedUpView`)(`CycleBudgetUsedUp`,{ask:$N}){},F3=class extends H(`@usine/orchestrator/AwaitingApprovalView`)(`AwaitingApproval`,{run:eH}){},I3=class extends H(`@usine/orchestrator/QueuedForWorkerView`)(`QueuedForWorker`,{run:eH,ahead:I(R.check(HT(0))),creating:I(DV).pipe(TT(T(null)))}){},L3=class extends H(`@usine/orchestrator/WaitingForStopView`)(`WaitingForStop`,{run:eH,stop:iH}){},R3=class extends H(`@usine/orchestrator/AwaitingPollView`)(`AwaitingPoll`,{}){},z3=F([F3,A3,P3,M3,j3,N3,L3,I3,R3]),B3=class extends V(`@usine/orchestrator/StalledItemView`)({repository:Lk,loop:Kk,item:SJ,reason:z3}){},V3=class extends V(`@usine/orchestrator/ClosedRunView`)({run:eH,item:I(SJ),closedAt:M}){},H3=class extends V(`@usine/orchestrator/WorkerView`)({name:BA,slots:e3,preflight:I(a3),machines:P(DV).pipe(TT(T([]))),provisioning:I(OV).pipe(TT(T(null)))}){},U3=class extends V(`@usine/orchestrator/RepositoryPollView`)({repository:Lk,polledAt:I(M)}){},W3=class extends V(`@usine/orchestrator/DeskView`)({running:P(k3),notMoving:P(B3),lastOutcomes:P(V3),workers:P(H3),polls:P(U3)}){},G3=({runs:e,sighting:t,paused:n,ask:r,ahead:i,creating:a,stop:o})=>{let s=e.find(({state:e})=>_A.some(t=>t===e));if(s!==void 0){let e=s.attempts.at(-1)?.outcome===null;if(S(o)&&s.state!==`Waiting`&&!e)return b(new L3({run:s,stop:o.value}));switch(s.state){case`Running`:return y();case`Waiting`:return b(new F3({run:s}));default:return b(new I3({run:s,ahead:i.get(s.id)??null,creating:a.get(s.id)??null}))}}if(n)return b(new N3);let c=t=>C(e.find(({id:e})=>e===t)),l=Or(Or(t,({suppressedBy:e})=>e),c);if(S(l))return b(new A3({run:l.value}));if(S(r))return b(new P3({ask:r.value}));let u=Or(Or(t,({run:e})=>e),c);return S(u)?b(u.value.state===`Failed`?new M3({run:u.value}):new j3({run:u.value})):b(new R3)},K3=[`AwaitingApproval`,`SuppressedForOperator`,`CycleBudgetUsedUp`,`RunFailed`,`ClosedUnchanged`,`LoopPaused`,`WaitingForStop`,`QueuedForWorker`,`AwaitingPoll`],q3=dr([fr(lr,({reason:e})=>K3.indexOf(e._tag)),fr(cr,({repository:e})=>e),fr(ur(lr),({item:e})=>e.number),fr(cr,({loop:e})=>e)]),J3=({direction:e,envelope:t})=>{let n=t.payload;return e===`outbound`&&n._tag!==`WorkerUnresponsive`&&n._tag!==`WorkerResponsive`&&(n._tag!==`SessionEvent`||n.event._tag!==`PoolRateLimitsUpdated`&&n.event._tag!==`ProviderRetrying`)},Y3=e=>{let t=null,n=new Map,r=null;for(let i of e){J3(i)&&(r=i);let e=i.envelope.payload;if(e._tag===`WorkerUnresponsive`)t=new E3({worker:e.worker,lastAnsweredAt:q_(e.lastAnsweredAt)});else if(e._tag===`WorkerResponsive`)t=null;else if(e._tag===`SessionEvent`){let t=e.event;t._tag===`ProviderRetrying`?n.set(t.session.id,new D3({agent:t.session.agent,message:t.message,retries:t.retries,since:n.get(t.session.id)?.since??q_(i.receivedAt)})):(t._tag===`ProviderRecovered`||t._tag===`SessionIdle`||t._tag===`SessionFinished`)&&n.delete(t.session.id)}}return{lastActivityAt:r===null?null:q_(r.receivedAt),warnings:[...t===null?[]:[t],...n.values()]}},X3=e=>G_(e.checkedAt),Z3=e=>{let t=[...jr(e.prerequisites),...e.harnesses.map(({check:e})=>e)],n=t.filter(({_tag:e})=>e===`Failed`),r=t.filter(({_tag:e})=>e===`Degraded`);return C((n.length>0?n:r.length>0?r:t).reduce((e,t)=>e===void 0||X3(t)>X3(e)?t:e,void 0))},Q3=e=>{let t=e.attempts.at(-1);return e.closedAt??t?.endedAt??t?.startedAt??e.openedAt},$3=({run:e,attempts:t})=>t.length===0&&e.state._tag===`Canceled`&&e.state.reason._tag!==`OperatorCanceled`,e6=E(function*(){let e=yield*DB,t=yield*VU,n=yield*OH,r=yield*mU,i=yield*w2,a=yield*n2,o=yield*q4,s=yield*JU,c=k(`Operator.desk.recentActivity`)(function*(t){return yield*O({attemptId:t.id}),Y3(yield*e.transcript(new zN({attemptId:t.id,before:y(),limit:S3})))});return{desk:k(`Operator.desk`)(function*(l){let[u,d,f,p,m,h,g,_,v,ee,te]=yield*Mh([e.list({closedLimit:0}),e.closed({limit:w3}),t.states,n.asks(),o.slots,o.queue,o.preflights,i.latest,s.list,o.machines,o.provisioning],{concurrency:`unbounded`}),ne=ee.map(MV),re=new Map(ne.flatMap(e=>e.state===`creating`&&e.runId!==null?[[e.runId,e]]:[])),ie=new Map(h.map(({runId:e,ahead:t})=>[e,t])),ae=new Set(f.filter(e=>e.paused).map(e=>e.loop)),oe=dH(l.config.workers),se=yield*Nh(l.config.repos,e=>E(function*(){let t=yield*r.list(e.name,{limit:T3});return{repository:e,items:t,matches:yield*a.matching(l,e,t)}}),{concurrency:4}),ce=new Map;for(let{items:e}of se)for(let t of e){let e=yield*Qh(zJ(t));if(Ei(e))continue;let{itemKey:n,kind:r,number:i,title:a,url:o,state:s}=e.success;ce.set(n,new SJ({itemKey:n,kind:r,number:i,title:a,url:o,state:s}))}let le=se.flatMap(({matches:e})=>e),ue=[...new Set(le.map(({item:e})=>e.itemKey))],[de,fe]=yield*Mh([e.forItems(ue),e.sightings(ue)],{concurrency:`unbounded`}),pe=new Map([...u,...de].map(e=>[e.run.id,mH(e,ae,oe)])),me=[...pe.values()].sort((e,t)=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),he=(e,t)=>Or(C(v.find(n=>n.loop===e&&n.itemKey===t)),e=>Dr(C(pe.get(e.runId)?.attempts.find(({id:t})=>t===e.attemptId)),({number:t})=>new iH({runId:e.runId,attemptNumber:t,worker:e.worker}))),ge=[];for(let{loop:e,item:t}of le){let n=ce.get(t.itemKey);if(n===void 0)continue;let r=G3({runs:me.filter(n=>n.loop===e.name&&n.itemKey===t.itemKey),sighting:C(fe.find(n=>n.loop===e.name&&n.itemKey===t.itemKey)),paused:ae.has(e.name),ask:C(p.find(({itemKey:e})=>e===t.itemKey)),ahead:ie,creating:re,stop:he(e.name,t.itemKey)});x(r)||(yield*j(`Matched Item is not moving`,{repository:t.repository,loop:e.name,item:t.number,reason:r.value._tag,...xk(r.value,{AwaitingApproval:({run:e})=>({runId:e.id}),SuppressedForOperator:({run:e})=>({runId:e.id}),CycleBudgetUsedUp:({ask:e})=>({askId:e.id}),RunFailed:({run:e})=>({runId:e.id}),ClosedUnchanged:({run:e})=>({runId:e.id,state:e.state}),LoopPaused:()=>({}),WaitingForStop:({run:e,stop:t})=>({runId:e.id,unstoppedRunId:t.runId,attemptNumber:t.attemptNumber,worker:t.worker}),QueuedForWorker:({run:e,ahead:t})=>({runId:e.id,ahead:t}),AwaitingPoll:()=>({})})}),ge.push(new B3({repository:t.repository,loop:e.name,item:n,reason:r.value})))}let _e=yield*Nh(me.flatMap(e=>{let t=e.attempts.at(-1);return e.state===`Running`&&t!==void 0&&t.outcome===null?[{run:e,attempt:t}]:[]}),({run:e,attempt:t})=>tg(c(t),n=>new k3({run:e,attempt:t,item:ce.get(e.itemKey)??null,...n})),{concurrency:4}),ve=d.filter(e=>!$3(e)).map(e=>{let t=mH(e,ae,oe);return new V3({run:t,item:ce.get(t.itemKey)??null,closedAt:Q3(t)})}).sort((e,t)=>t.closedAt.localeCompare(e.closedAt)).slice(0,C3),ye=new Map(m.map(e=>[e.worker,e])),be=new Map(g.map(e=>[e.worker,e])),xe=new Set(l.config.workers.map(({name:e})=>e)),Se=[...l.config.workers.map(({name:e})=>e),...m.map(({worker:e})=>e).filter(e=>!xe.has(e))].map(e=>{let t=ye.get(e),n=be.get(e);return new H3({name:e,slots:new e3({capacity:t?.capacity??l.config.workers.find(t=>t.name===e)?.maxConcurrentAttempts??0,leased:t?.leased??0}),preflight:w(Dr(Or(C(n),Z3),y3)),machines:ne.filter(t=>t.worker===e),provisioning:w(Dr(C(te.find(t=>t.worker===e)),NV))})}),Ce=vr(_,{onNone:()=>[],onSome:({repositoryPolls:e})=>e}),we=l.config.repos.map(({name:e})=>{let t=Ce.find(({repository:t})=>Hk(t)===Hk(e));return new U3({repository:e,polledAt:t===void 0?null:q_(t.completedAt)})});return yield*j(`Built the operator desk`,{running:_e.length,matches:le.length,notMoving:ge.length,lastOutcomes:ve.length,workers:Se.length}),new W3({running:_e,notMoving:[...ge].sort(q3),lastOutcomes:ve,workers:Se,polls:we})})}});(class e extends Lr()(`@usine/orchestrator/OperatorDesk`){static layer=Yf(e,e6).pipe(np(n2.layer))});var t6=R.check(HT(0)),n6=R.check(HT(1)),r6=R.check(HT(0)),i6=FT.check(UT({minimum:0,maximum:1})),a6=M.check(PT(/^\d{4}-\d{2}-\d{2}$/u,{message:`Expected a UTC day as YYYY-MM-DD`})),o6=bT([`7d`,`30d`,`all`]),s6=bT([`day`,`week`]),c6=class extends V(`@usine/orchestrator/TaskDoneView`)({repository:Lk,number:xN,mergedAt:M,durationMillis:r6}){},l6=class extends V(`@usine/orchestrator/TaskPeriodView`)({start:a6,tasks:t6,medianMillis:I(r6),firstTimeRight:t6,operatorActions:t6}){},u6=class extends V(`@usine/orchestrator/LoopShareView`)({loop:Kk,share:i6}){},d6=class extends V(`@usine/orchestrator/LoopRunTimeView`)({loop:Kk,runs:n6,medianMillis:r6}){},f6=class extends V(`@usine/orchestrator/TaskTimeView`)({tasks:n6,loops:P(u6),waiting:i6,runs:P(d6)}){},p6=class extends V(`@usine/orchestrator/TaskCostView`)({tasks:n6,medianUsd:Pj,estimate:cT}){},m6=class extends V(`@usine/orchestrator/TaskTokensView`)({tasks:n6,medianTokens:bj,loops:P(u6),cost:I(p6)}){},h6=class extends V(`@usine/orchestrator/UntimedTasksView`)({tasks:n6,before:a6}){},g6=class extends V(`@usine/orchestrator/StatisticsView`)({window:o6,from:M,to:M,bucket:s6,loops:P(Kk),tasks:P(c6),medianMillis:I(r6),periods:P(l6),firstTimeRight:t6,operatorActions:t6,time:I(f6),tokens:I(m6),untimed:I(h6),unmetered:t6}){},_6=class extends V(`@usine/orchestrator/DurationSummaryView`)({count:n6,medianMillis:r6}){},v6=class extends V(`@usine/orchestrator/OutcomeCountsView`)({succeeded:t6,failed:t6,canceled:t6}){},y6=class extends V(`@usine/orchestrator/PoolTokensView`)({pool:Rj,tokens:bj}){},b6=class extends V(`@usine/orchestrator/CostSummaryView`)({usd:Pj,meanUsd:Pj,estimate:cT,priced:n6}){},x6=class extends V(`@usine/orchestrator/UsageSummaryView`)({measured:t6,tokens:bj,meanTokens:I(bj),pools:P(y6),cost:I(b6)}){},S6={outcomes:v6,time:I(_6),usage:x6},C6=class extends V(`@usine/orchestrator/LoopStatisticsView`)({loop:Kk,...S6}){},w6=class extends V(`@usine/orchestrator/AgentStatisticsView`)({agent:FA,...S6}){},T6=class extends V(`@usine/orchestrator/BrainStatisticsView`)({brain:PA,...S6}){},E6=class extends V(`@usine/orchestrator/ThroughputPeriodView`)({start:a6,...v6.fields}){},D6=class extends V(`@usine/orchestrator/WorkerQueueWaitView`)({worker:BA,wait:_6}){},O6=class extends V(`@usine/orchestrator/AttemptCountView`)({attempts:n6,runs:t6}){},k6=class extends V(`@usine/orchestrator/WorkerUtilizationView`)({worker:BA,slots:n6,occupiedMillis:r6,share:i6}){},A6=class extends V(`@usine/orchestrator/NeedsAttentionPeriodView`)({start:a6,approvals:t6,failures:t6}){},j6=class extends V(`@usine/orchestrator/NeedsAttentionView`)({approvals:t6,failures:t6,periods:P(A6),approvalWait:I(_6),retryWait:I(_6),resolutionWait:I(_6),failureWait:I(_6)}){},M6=class extends V(`@usine/orchestrator/RunStatisticsView`)({window:o6,from:M,to:M,bucket:s6,runs:v6,runTime:I(_6),attemptTime:I(_6),unmeasuredAttempts:t6,throughput:P(E6),loops:P(C6),agents:P(w6),brains:P(T6),queueWait:P(D6),attemptsPerRun:P(O6),utilization:P(k6),needsAttention:j6}){},N6=`~effect/http-api/HttpApiSchema/Stream`;function P6(e){let t=typeof e==`string`?QG(e):e;return e=>e.ast.checks!==void 0||e8(e.ast)?e.annotate({httpApiStatus:t}):e.annotateKey({httpApiStatus:t})}var F6=(e=>uT.pipe(P6(e)))(204),I6=e=>Zw(e)&&pe(e,N6),L6=e=>I6(e)&&e._tag===`StreamSse`,R6=e=>I6(e)&&e._tag===`StreamUint8Array`,z6=e=>I6(e)&&e._tag===`StreamNdjson`,B6=`~effect/http-api/HttpApiSchema/Upgrade`,V6=e=>Zw(e)&&pe(e,B6),H6=`~effect/http-api/HttpApiSchema/WithHeaders`,U6=`~effect/http-api/HttpApiSchema/WithHeadersValue`,W6=e=>({[U6]:U6,body:e.body,headers:e.headers}),G6=e=>Zw(e)&&pe(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function K6(e,t,n){return Xw(e.ast,{[H6]:H6,schema:t,headers:n})}function q6(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??J6(t._tag)}})}function J6(e){switch(e){case`Multipart`:return`multipart/form-data`;case`Json`:return`application/json`;case`FormUrlEncoded`:return`application/x-www-form-urlencoded`;case`Uint8Array`:return`application/octet-stream`;case`Text`:return`text/plain`}}function Y6(e){return t=>q6(t,{_tag:`FormUrlEncoded`,...e})}var X6=e=>{if(Kb(e)||Kb(WS(e)))return!0;let t=e.encoding?.[0].to;return t!==void 0&&Kb(t)},Z6=uC(`~httpApiEncoding`),Q6=uC(`~httpApiWithHeaders`),$6=uC(`httpApiStatus`);function e8(e){let t=lC(e);return t!==void 0&&`httpApiStatus`in t}function t8(e){return e8(e)?$6(e):e.checks===void 0?e.context?.annotations?.httpApiStatus:void 0}var n8={_tag:`Json`,contentType:`application/json`},r8={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function i8(e){return Z6(e)??n8}function a8(e,t){return Z6(e)||(kW(t)?n8:r8)}function o8(e){let t=i8(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function s8(e){return t8(e)??200}function c8(e){return G6(e)?t8(e.ast)??s8(e.schema.ast):s8(e.ast)}function l8(e){return G6(e)&&Z6(e.ast)===void 0?o8(e.schema.ast):o8(e.ast)}function u8(e){return t8(e)??500}function d8(e){return G6(e)?t8(e.ast)??u8(e.schema.ast):u8(e.ast)}function f8(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}var p8=`~effect/http-api/HttpApiEndpoint`;function m8(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function h8(e){let t=Array.from(e.success);return Ji(t)?t:[F6]}function g8(e){let t=new Set(e.error),n=e.disableCodecs?i:T8;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}var _8={[p8]:p8,pipe(){return e(this,arguments)},prefix(e){return y8({...v8(this),path:HG(this.path,e)})},middleware(e){return y8({...v8(this),middlewares:new Set([...this.middlewares,e])})},annotate(e,t){return y8({...v8(this),annotations:ii(this.annotations,e,t)})},annotateMerge(e){return y8({...v8(this),annotations:mi(this.annotations,e)})}},v8=e=>({identifier:e.identifier,path:e.path,method:e.method,params:e.params,query:e.query,headers:e.headers,payload:e.payload,success:e.success,error:e.error,annotations:e.annotations,middlewares:e.middlewares,disableCodecs:e.disableCodecs});function y8(e){function t(){}return Object.setPrototypeOf(t,_8),Object.assign(t,e)}var b8=e=>(t,n,r)=>{let a=r?.disableCodecs??!1,o=a?i:FE;return y8({identifier:t,path:n,method:e,params:x8(r?.params,o),query:x8(r?.query,o),headers:x8(r?.headers,o),payload:S8(r?.payload,e,a),success:w8(r?.success,e,r?.payload!==void 0,a),error:E8(r?.error,a),annotations:ti(),middlewares:new Set,disableCodecs:a})};function x8(e,t){if(e!==void 0)return Zw(e)?t(e):t(N(e))}function S8(e,t,n){let r=new Map;if(e===void 0)return r;let a=Array.isArray(e)?e:Zw(e)?[e]:[N(e).pipe(Y6())],o=n?i:I8,s=!1;for(let e of a){if(I6(e)){if(L6(e))throw Error(`StreamSse is response-only and cannot be used as a payload`);if(!kW(t))throw Error(`${t} endpoints cannot declare a streaming payload`);if(s)throw Error(`Multiple streaming payloads are not supported`);s=!0;let n=f8(e.contentType);if(r.has(n))throw Error(`Cannot combine buffered and streaming payloads for content-type: ${e.contentType}`);r.set(n,{encoding:{_tag:`Stream`,contentType:e.contentType},schemas:[e]});continue}let n=a8(e.ast,t),i=f8(n.contentType),a=r.get(i);if(a){if(a.encoding._tag===`Stream`)throw Error(`Cannot combine buffered and streaming payloads for content-type: ${n.contentType}`);if(a.encoding._tag!==n._tag)throw Error(`Multiple payload encodings for content-type: ${n.contentType}`);if(a.encoding._tag===`Multipart`)throw Error(`Multiple multipart payloads for content-type: ${n.contentType}`);a.schemas.push(o(e,t))}else r.set(i,{encoding:n,schemas:[o(e,t)]})}return r}var C8=`effect/http-api/stream/failure`;function w8(e,t,n,r){if(e===void 0)return new Set;let i=Wi(e);return D8(i,t,n),new Set(r?i:i.map(T8))}var T8=f(e=>I6(e)||V6(e)?e:G6(e)?K6(e,I6(e.schema)?e.schema:F8(e.schema,l8(e)),FE(e.headers)):P8(e));function E8(e,t){if(e===void 0)return new Set;let n=Wi(e);for(let e of n){let t=G6(e)?e.schema:e;if(I6(t))throw Error(`Streaming schemas are not supported in error responses`);if(V6(t))throw Error(`Upgrade schemas are not supported in error responses`)}return k8(n,d8),new Set(t?n:n.map(T8))}function D8(e,t,n){if(e.some(V6)){if(e.length>1)throw Error(`Cannot combine an upgrade with other success responses`);if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare an upgrade`);if(n)throw Error(`Upgrade endpoints cannot declare a payload`);return}let r=!1,i=new Map;for(let n of e){let e=G6(n)?n.schema:n,a=c8(n);if(I6(e)){if(A8(e,t),r)throw Error(`Multiple streaming success responses are not supported`);r=!0;let n=O8(i,a);if(n.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(n.bufferedContentTypes.has(f8(e.contentType)))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`);i.set(a,{...n,stream:e})}else{let t=O8(i,a),r=X6(e.ast);if(t.stream!==void 0){if(r)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=l8(n);if(f8(e.contentType)===f8(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}r||t.bufferedContentTypes.add(f8(l8(n).contentType)),t.noContent=t.noContent||r}}k8(e,c8)}function O8(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:new Set,noContent:!1},e.set(t,n)),n}function k8(e,t){let n=new Map;for(let r of e){let e=t(r),i=Q6(r.ast),a=G6(r)?r.schema:i?.body??r,o=X6(a.ast)?``:f8(I6(a)?a.contentType:l8(r).contentType),s=n.get(e);s===void 0&&(s={headerContentType:void 0,plainContentTypes:new Set},n.set(e,s));let c=()=>Error(`Cannot combine a response with headers with another response for status ${e} and content-type: ${o||`<no content>`}`);if(G6(r)||i!==void 0){if(s.headerContentType!==void 0)throw Error(`Cannot declare multiple responses with headers for status ${e}`);if(s.plainContentTypes.has(o))throw c();s.headerContentType=o}else{if(s.headerContentType===o)throw c();s.plainContentTypes.add(o)}}}function A8(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(L6(e)&&j8(e.events.ast))throw Error(`SSE event name is reserved: ${C8}`)}function j8(e){return M8(WS(e),new Set)}function M8(e,t){if(t.has(e))return!1;if(t.add(e),Qb(e))return e.types.some(e=>M8(e,t));if($b(e))return M8(e.thunk(),t);if(!Zb(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&N8(n.type,t)}function N8(e,t){if(t.has(e))return!1;t.add(e);let n=WS(e);return n===e?Jb(e)?e.literal===C8:Qb(e)?e.types.some(e=>N8(e,t)):$b(e)?N8(e.thunk(),t):!1:N8(n,t)}function P8(e){let t=o8(e.ast),n=Q6(e.ast);return n===void 0?F8(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:F8(n.body,t),headersCodec:FE(n.headers)}})}function F8(e,t){switch(t._tag){case`Json`:return PE(e);case`FormUrlEncoded`:return FE(e);case`Text`:case`Uint8Array`:return e}}function I8(e,t){switch(a8(e.ast,t)._tag){case`Json`:return PE(e);case`FormUrlEncoded`:return FE(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}var L8=b8(`GET`),R8=b8(`POST`),z8=`~effect/http-api/HttpApi`,B8={[z8]:z8,pipe(){return e(this,arguments)},add(...e){let t={...this.groups};for(let n of e)Et(t,n.identifier,n);return H8({...V8(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];Et(t,n,r.annotateMerge(mi(e.annotations,r.annotations)))}return H8({...V8(this),groups:t})},prefix(e){return H8({...V8(this),groups:Ri(this.groups,t=>t.prefix(e))})},middleware(e){return H8({...V8(this),groups:Ri(this.groups,t=>t.middleware(e))})},annotate(e,t){return H8({...V8(this),annotations:ii(this.annotations,e,t)})},annotateMerge(e){return H8({...V8(this),annotations:mi(this.annotations,e)})}},V8=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),H8=e=>{function t(){}return Object.setPrototypeOf(t,B8),Object.assign(t,e)},U8=e=>H8({identifier:e,groups:{},annotations:ti()}),W8=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=mi(e.annotations,r.annotations);t.onGroup({group:r,mergedAnnotations:n});let i=Object.values(r.endpoints);for(let e of i)(!t.predicate||t.predicate({endpoint:e,group:r}))&&t.onEndpoint({group:r,endpoint:e,middleware:e.middlewares,mergedAnnotations:mi(n,e.annotations),successes:G8(h8(e),c8),errors:G8(g8(e),d8)})}},G8=(e,t)=>{let n=new Map;return e.forEach(r),n;function r(e){let r=G6(e)?e.schema:e;if(I6(r)||V6(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}},K8=class extends Lr()(`effect/http-api/HttpApi/ParseOptions`){},q8=class extends Lr()(`effect/http-api/HttpApi/ParamsParseOptions`){},J8=class extends Lr()(`effect/http-api/HttpApi/QueryParseOptions`){},Y8=class extends Lr()(`effect/http-api/HttpApi/HeadersParseOptions`){},X8=class extends Lr()(`effect/http-api/HttpApi/PayloadParseOptions`){},Z8=class extends Lr()(`effect/http-api/HttpApi/SuccessParseOptions`){},Q8=class extends Lr()(`effect/http-api/HttpApi/ErrorParseOptions`){},$8=e=>{let t=oi(e,K8);return{params:oi(e,q8)??t,query:oi(e,J8)??t,headers:oi(e,Y8)??t,payload:oi(e,X8)??t,success:oi(e,Z8)??t,error:oi(e,Q8)??t}},e5=`~effect/http-api/HttpApiMiddleware`,t5=`~effect/http-api/HttpApiMiddleware/Security`,n5=()=>(e,t)=>{let n=St(),r;n!==0&&(Ct(2),r=new globalThis.Error,Ct(n));class i extends Lr()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[e5]=e5,a.error=r5(t?.error),a.requiredForClient=t?.requiredForClient??!1,t?.security!==void 0){if(Object.keys(t.security).length===0)throw Error(`HttpApiMiddleware.Service: security object must not be empty`);a[t5]=t5,a.security=t.security}return a};function r5(e){return e===void 0?new Set:new Set(Array.isArray(e)?e:[e])}var i5=new Set;function a5(e){if(e===void 0)return i5;let t=bS(e.ast);return Zb(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function o5(e,t,n){let r=/::|:(\w+)/g,i=``,a=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let s=o[1];if(s===void 0||t!==void 0&&!t.has(s))continue;let c=r.lastIndex;e[c]===`(`&&(c=LG(e,c)+1);let l=e[c]===`?`;l&&c++;let u=n(s,l),d=o.index;u===void 0&&e[d-1]===`/`&&d--,i+=e.slice(a,d)+(u??``),r.lastIndex=c,a=c}return i+e.slice(a)}var s5=(e,t)=>E(function*(){let n=yield*Sg(),r=t.httpClient.pipe(t?.baseUrl===void 0?i:TG(XW(t.baseUrl.toString())));function a(e,t,i,o,s){if(s===-1)return r.execute(i);let c=n.mapUnsafe.get(o[s]);return c===void 0?a(e,t,i,o,s-1):c({endpoint:t,group:e,request:i,next(n){return a(e,t,n,o,s-1)}})}W8(e,{predicate:t?.predicate,onGroup(e){t.onGroup?.(e)},onEndpoint(e){let{group:n,endpoint:r,errors:i,successes:o,mergedAnnotations:s}=e,c=$8(s),l=u5(r.path,r.params),u={orElse:P5},d=new Map;for(let[e,t]of i.entries()){let n=g5(t);for(let[t,r]of n.entries())m5(d,e,t,d5(r,c.error,c.headers))}for(let[e,t]of d.entries()){let n=h5(t);u[e]=e=>D(cg(n(e),t=>Uh($d(Kd(new bW({reason:new EW({request:e.request,response:e})})),t))),Hh)}let f=new Map;for(let[e,t]of o.entries()){let n=g5(t);for(let[t,r]of n.entries())m5(f,e,t,d5(r,c.success,c.headers))}for(let e of x5(r)){let t=y5(e)?e.schema:e;m5(f,c8(e),t.contentType,S5(e,c.success,c.headers))}for(let[e,t]of f.entries())u[e]=h5(t);let p=b5(r);p!==void 0&&(u[101]=e=>tg(e.upgrade,t=>({headers:e.headers,socket:t})));let m=Ak(r.params,e=>Kw(e,c.params)),h=[],g;for(let e of m8(r))R6(e)||z6(e)?g=e:h.push(e);let _=Ak(g,e=>({contentType:e.contentType,encode:I5(e,c.payload)})),v=Ji(h)?Kw(kW(r.method)?L5(h,r.method):F(h),c.payload):void 0,ee=Ak(r.headers,e=>Kw(e,c.headers)),te=Ak(r.query,e=>Kw(e,c.query)),ne=Array.from(e.middleware,e=>`${e.key}/Client`),re=Qg(function*(e){let i=zW(r.method)(r.path);if(e!==void 0){if(m!==void 0){let t=yield*m(e.params);i=YW(i,l(t))}if(_!==void 0&&EO(e.payload)){let t=yield*Sg();i=tG(i,vW(GO(_.encode(e.payload),t),_.contentType))}else if(v!==void 0){if(kW(r.method)){if(e.payload instanceof FormData)i=rG(i,e.payload);else{let t=yield*v(e.payload);i=tG(i,t)}}else{let t=yield*v(e.payload);i=$W(i,t)}}else if(_!==void 0)return yield*new Nw(new jy({message:`Expected a Stream payload`},e.payload));if(ee!==void 0){let t=yield*ee(e.headers);i=GW(i,t)}if(te!==void 0){let t=yield*te(e.query);i=$W(i,t)}}p!==void 0&&(i=JW(i,p.protocol));let o=yield*a(n,r,i,ne,ne.length-1);if(e?.responseMode===`response-only`)return o;let s=(u[o.status]??u.orElse)(o,e?.sseOptions),c=yield*t.transformResponse===void 0?s:t.transformResponse(s);return e?.responseMode===`decoded-and-response`?[c,o]:c});t.onEndpoint({...e,endpointFn:re})}})}),c5=(e,t)=>D(yG,n=>l5(e,{...t,httpClient:t?.transformClient?t.transformClient(n):n})),l5=(e,t)=>{let n={};return s5(e,{...t,onGroup({group:e}){e.topLevel||Et(n,e.identifier,{})},onEndpoint({endpoint:e,endpointFn:t,group:r}){Et(r.topLevel?n:n[r.identifier],e.identifier,t)}}).pipe(ng(n))},u5=(e,t)=>{if(t===void 0||!e.includes(`:`))return t=>e;let n=a5(t);return t=>o5(e,n,(e,n)=>{let r=t[e];if(r!==void 0)return encodeURIComponent(r);if(!n)throw Error(`Missing path parameter: ${e}`)})};function d5(e,t,n){let r=e.some(e=>G6(e)||Q6(e.ast)!==void 0),i=Vw(r?F(e.map(e=>p5(e,t,n))):M5(e),t);return e=>D(e.arrayBuffer,r?t=>i({body:t,headers:e.headers}):i)}var f5=N({body:iT,headers:iT});function p5(e,t,n){let r=Q6(e.ast),i=r===void 0?G6(e)?{body:e.schema,headers:e.headers,toValue:W6}:{body:e,headers:iT,toValue:e=>e.body}:{body:r.bodyCodec,headers:r.headersCodec,toValue:r.transformation.decode},a=Vw(N5(i.body).pipe(ST(i.body)),t),o=Vw(i.headers,n);return f5.pipe(ST(G6(e)?e:eT(e),wb({decode:e=>Mh({body:a(e.body),headers:o(e.headers)}).pipe(tg(i.toValue),ug(e=>e.issue)),encode:(e,t)=>Hh(new Ny({message:`Decode only schema`},e,t))})))}function m5(e,t,n,r){let i=f8(n),a=e.get(t);a===void 0?e.set(t,[{contentType:i,decode:r}]):a.push({contentType:i,decode:r})}function h5(e){let t=e[0];return e.length===1&&t!==void 0?t.decode:(t,n)=>{let r=f8(t.headers[`content-type`]??``),i=e.find(e=>e.contentType===r);return i===void 0?_5(t,r,e):i.decode(t,n)}}function g5(e){let t=new Map;for(let n of e){let e=X6((G6(n)?n.schema:n).ast)?``:f8(l8(n).contentType),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return t}function _5(e,t,n){let r=Array.from(new Set(n.map(e=>e.contentType))).join(`, `);return Hh(new bW({reason:new DW({request:e.request,response:e,description:`Unsupported response content-type for status ${e.status}: ${t||`<missing>`}. Expected one of: ${r}`})}))}var v5=`effect/http-api/stream/failure`,y5=e=>G6(e);function b5(e){for(let t of e.success)if(V6(t))return t}function x5(e){let t=[];for(let n of e.success)I6(G6(n)?n.schema:n)&&t.push(n);return t}function S5(e,t,n){let r=y5(e),i=C5(r?e.schema:e,t),a=(e,t)=>tg(Sg(),n=>GO(i(e,t),n));if(!r)return a;let o=Vw(e.headers,n);return(e,t)=>D(o(e.headers),n=>tg(a(e,t),e=>W6({body:e,headers:n})))}function C5(e,t){if(R6(e))return e=>e.stream;if(z6(e)){let n=Vw(PE(e.schema),t),r=N_(e.maxElementBytes);return e=>e.stream.pipe(VO(bP({ignoreEmptyLines:!0,maxLineBytes:r})),BO(t=>fP(t)?t.reason===`LineTooLarge`?new bW({reason:new DW({request:e.request,response:e,description:`NDJSON line exceeds maxElementBytes of ${r} bytes`})}):T5(t):t),IO(e=>n(e)))}let n=E5(e,t);return(t,r)=>D5(t.stream,e,n(r))}var w5=e=>fP(e)&&e.kind===`Pack`,T5=e=>new Nw(new jy({message:e.reason===`InvalidUtf8`?`Expected valid UTF-8`:e.unterminated?`Expected a valid JSON line, got an unterminated final line`:`Expected a valid JSON line`}));function E5(e,t){let n=F([N({id:$w(M),event:nT(v5),data:aE(PE(dE(e.error,eE())))}),e.events]),r=EP(n,void 0,t);return e=>e===void 0?r:EP(n,e,t)}function D5(e,t,n){let r=OO(e.pipe(HO,VO(n)),e=>Rh(()=>{let t;return Lh(()=>t===void 0?D(e,e=>{for(let n=0;n<e.length;n++){let r=e[n];if(r.event===v5&&Hd(r.data)){if(n===0)return Uh(r.data);t=r.data,e=e.slice(0,n);break}}return T(e)}):Uh(t))}));return t.sseMode===`data`?FO(r,e=>e.data):r}var O5=jT(globalThis.ArrayBuffer,{expected:`ArrayBuffer`}),k5=O5.pipe(ST(lE,Tb({decode(e){return new Uint8Array(e)},encode(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}}))),A5=O5.pipe(ST(M,Tb({decode(e){return new TextDecoder().decode(e)},encode(e){let t=new TextEncoder().encode(e);return t.byteLength===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}))),j5=A5.pipe(ST(F([nT(``).pipe(ST(oT,Tb({decode:()=>void 0,encode:()=>``}))),oE])));function M5(e){return F(e.map(t));function t(e){return N5(e).pipe(ST(e))}}function N5(e){switch(o8(e.ast)._tag){case`Json`:return Gb(WS(e.ast))?j5.pipe(ST(iT,Tb({decode:e=>e===void 0?null:e,encode:e=>e===null?void 0:e}))):j5;case`FormUrlEncoded`:return A5.pipe(ST(bE,Tb({decode:e=>Bv(new URLSearchParams(e)),encode:Yv})));case`Uint8Array`:return k5;case`Text`:return A5}}var P5=e=>Hh(new bW({reason:new DW({request:e.request,response:e})})),F5=Mw(iW);function I5(e,t){if(R6(e))return e=>e;let n=Kw(vT(PE(e.schema)),t);return e=>e.pipe(LO(e=>n(e)),VO(mP()),zO(w5,NO))}function L5(e,t){return F(e.map(e=>z5(e,t)))}var R5=new WeakMap;function z5(e,t){let n=e.ast,r=R5.get(n);if(r!==void 0)return r;let i=a8(n,t),a=F5.pipe(ST(e,wb({decode(e,t){return Hh(new Ny({message:`Encode only schema`},e,t))},encode(e,t){switch(i._tag){case`Multipart`:return Hh(new Ny({message:`Payload must be a FormData`},e,t));case`Json`:try{return T(fW(JSON.stringify(e),i.contentType))}catch{return Hh(new jy({expected:`a JSON-serializable request body`},e,t))}case`Text`:return typeof e==`string`?T(fW(e,i.contentType)):Hh(new jy({message:`Expected a string`},e,t));case`FormUrlEncoded`:return de(e)?T(mW(Bv(e),i.contentType)):Hh(new jy({message:`Expected a record`},e,t));case`Uint8Array`:return e instanceof Uint8Array?T(cW(e,i.contentType)):Hh(new jy({message:`Expected a Uint8Array`},e,t))}}})));return R5.set(n,a),a}var B5=`~effect/http-api/HttpApiGroup`,V5={[B5]:B5,add(...e){let t={...this.endpoints};for(let n of e)Et(t,n.identifier,n);return U5({...H5(this),endpoints:t})},prefix(e){return U5({...H5(this),endpoints:Ri(this.endpoints,t=>t.prefix(e))})},middleware(e){return U5({...H5(this),endpoints:Ri(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return U5({...H5(this),annotations:mi(this.annotations,e)})},annotate(e,t){return U5({...H5(this),annotations:ii(this.annotations,e,t)})},annotateEndpointsMerge(e){return U5({...H5(this),endpoints:Ri(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return U5({...H5(this),endpoints:Ri(this.endpoints,n=>n.annotate(e,t))})},pipe(){return e(this,arguments)}},H5=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),U5=e=>{function t(){}return Object.setPrototypeOf(t,V5),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},W5=(e,t)=>U5({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:ti()}),G5=bT([`workers`,`webhooks`,`tracing`]),K5=e=>N({added:P(e),removed:P(e),changed:P(e)}),q5=class extends V(`@usine/orchestrator/InstanceReload`)({loops:K5(Kk),agents:K5(FA),labels:K5(nV),repos:K5(Lk),workers:K5(BA),settingsChanged:cT,operatorChanged:cT,quarantinedLoops:P(pX),invalidAgents:P(tX)}){},J5={SchemaError:400,InvalidRequestError:400,CrossSiteRequestError:403,RunNotFoundError:404,TranscriptAttemptNotFoundError:404,BoardProjectNotFoundError:404,BoardItemNotFoundError:404,BoardLaneNotFoundError:404,GitHubItemNotFoundError:404,RunOperationRejectedError:409,RunRetryBlockedError:409,RunInterventionRejectedError:409,LeftoversDiscardRejectedError:409,RosterAgentNotFoundError:404,LoopNotFoundError:404,CycleBudgetResetRejectedError:409,BoardLaneReadOnlyError:409,RestartRequiredError:409,ReloadPreflightError:409,FactoryConfigError:422,EnginePersistenceError:500,AttemptCancellationError:500,HttpBodyError:500,GitHubApiError:502,InvalidGitHubResponseError:502,BackendUnavailableError:503,InstallationDiscoveryError:503,AppPermissionError:503,GitHubRateLimitError:503},Y5=class extends ME(`@usine/orchestrator/OperatorHttpError`)({error:bT(zi(J5)),message:M}){get status(){return J5[this.error]}},X5=[...new Set(Object.values(J5))].map(e=>Y5.check(NT(t=>t.status===e)).annotate({httpApiStatus:e})),Z5=class extends n5()(`@usine/orchestrator/OperatorHttpPolicy`,{error:X5}){},Q5=F([AT(`WorkerCapabilityError`,{worker:BA,capability:gV,message:M}),AT(`ExecutorOperationError`,{operation:hV,message:M}),AT(`CredentialUnavailableError`,{repository:Lk,message:M})]),$5=class extends ME(`@usine/orchestrator/RestartRequiredRefusal`)({error:nT(`RestartRequiredError`),message:M,blocks:vT(G5),fields:vT(z)},{httpApiStatus:409}){},e7=class extends ME(`@usine/orchestrator/ReloadPreflightRefusal`)({error:nT(`ReloadPreflightError`),message:M,agents:P(FA),workers:P(BA),cause:Q5},{httpApiStatus:409}){},t7=class extends ME(`@usine/orchestrator/FactoryConfigRefusal`)({error:nT(`FactoryConfigError`),message:M,file:YY,stage:XY},{httpApiStatus:422}){},n7=Qw(rT),r7=F([M,vT(M).pipe(ST(M,Tb({decode:e=>e[0],encode:e=>[e]})))]),i7=r7.pipe(ST(sE),ST(ON)),a7=F([N({after:n7,before:n7,attempt:n7}).pipe(ST(eT(XB),Tb({decode:()=>new XB,encode:()=>({})}))),N({after:i7,before:n7,attempt:n7}).pipe(ST(eT(ZB),Tb({decode:({after:e})=>new ZB({after:e}),encode:({after:e})=>({after:e})}))),N({after:n7,before:i7,attempt:r7.pipe(ST(TM))}).pipe(ST(eT(QB),Tb({decode:({before:e,attempt:t})=>new QB({before:e,attemptId:t}),encode:({before:e,attemptId:t})=>({before:e,attempt:t})})))]),o7=M.check(PT(/^[A-Za-z0-9_.-]+$/u,{message:`Expected a repository path segment`})),s7=N({ok:nT(!0)}),c7={runId:kA},l7={loop:Kk},u7=N({window:r7.pipe(ST(o6),DT(T(`30d`)))}),d7=U8(`OperatorApi`).add(W5(`operator`).add(L8(`overview`,`/api/overview`,{success:n4}),L8(`agents`,`/api/agents`,{success:P(FA)}),R8(`editAndRetry`,`/api/runs/:runId/edit-and-retry`,{params:c7,payload:ZV,success:s7}),R8(`runAgain`,`/api/runs/:runId/run-again`,{params:c7,payload:ZV,success:AH}),R8(`intervene`,`/api/runs/:runId/intervene`,{params:c7,payload:QV,success:s7}),R8(`resetCycleBudget`,`/api/cycle-budgets/reset`,{payload:N({askId:QN}),success:s7}),L8(`detail`,`/api/runs/:runId`,{params:c7,query:a7,success:aH}),L8(`githubChanges`,`/api/runs/:runId/github-changes`,{params:c7,success:T4}),R8(`approve`,`/api/runs/:runId/approve`,{params:c7,success:s7}),R8(`resolveFailure`,`/api/runs/:runId/resolve-failure`,{params:c7,payload:N({attemptId:TM}),success:s7}),R8(`retry`,`/api/runs/:runId/retry`,{params:c7,success:s7}),R8(`cancel`,`/api/runs/:runId/cancel`,{params:c7,success:s7}),R8(`moveBoardItem`,`/api/projects/:owner/:repository/items/:item/lane`,{params:{owner:o7,repository:o7,item:sE.pipe(ST(xN))},payload:N({toLane:bJ}),success:s7}),R8(`discardLeftovers`,`/api/workers/:worker/discard-leftovers`,{params:{worker:BA},success:s7}),R8(`pause`,`/api/loops/:loop/pause`,{params:l7,success:s7}),R8(`unpause`,`/api/loops/:loop/unpause`,{params:l7,success:s7}),R8(`reload`,`/api/instance/reload`,{success:q5,error:[$5,e7,t7]})).add(L8(`task`,`/api/projects/:owner/:repository/tasks/:item`,{params:{owner:o7,repository:o7,item:sE.pipe(ST(xN))},success:V4})).add(L8(`configuration`,`/api/configuration`,{success:_3})).add(L8(`desk`,`/api/desk`,{success:W3})).add(L8(`statistics`,`/api/statistics`,{query:u7,success:g6}),L8(`runStatistics`,`/api/statistics/runs`,{query:u7,success:M6})).annotate(X8,{onExcessProperty:`error`}).middleware(Z5)),f7=()=>c5(d7,{baseUrl:globalThis.location.origin}),p7=e=>Yg(D(f7(),t=>e(t.operator)).pipe(Og(OG,!1),wg(IG))),m7=e=>e instanceof Error?e.message:String(e),h7=e=>`${e.harness} · ${e.model} · ${e.effort}`,g7=e=>{switch(e){case`issue`:return`Issue`;case`pr`:return`PR`;case`schedule`:return`Schedule`;default:return e}},_7=(e,t=Date.now())=>{let n=Math.max(0,t-Date.parse(e));return n<6e4?`now`:n<36e5?`${Math.floor(n/6e4)}m`:n<864e5?`${Math.floor(n/36e5)}h`:`${Math.floor(n/864e5)}d`},v7=(e,t)=>{let n=_7(e,t);return n===`now`?`just now`:`${n} ago`},y7=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`},b7=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],x7=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getDate()} ${b7[t.getMonth()]} ${n(t.getHours())}:${n(t.getMinutes())}`},S7=e=>`${e.getDate()} ${b7[e.getMonth()]}`,C7=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`},w7=e=>{let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.round(t/60);return n<60?`${n} min`:n%60==0?`${Math.floor(n/60)} h`:`${Math.floor(n/60)} h ${n%60} min`},T7=e=>new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}).format(e),E7=e=>e>0&&e<.005?`under $0.01`:`$${e.toFixed(2)}`,D7=e=>({claude:`Claude Code`,codex:`Codex`,pi:`Pi`})[e],O7=e=>({apiKeys:`API keys`,claudePlan:`Claude plan`,chatgptPlan:`ChatGPT plan`})[e],k7=e=>e%1440==0?`${e/1440}-day`:e%60==0?`${e/60}-hour`:`${e}-minute`,A7=`Loading…`,j7=`Could not load the page`,M7=`Try again`;export{IE as $,dV as A,Ug as At,rN as B,wr as Bt,$5 as C,W_ as Ct,ZV as D,$g as Dt,P0 as E,ag as Et,xN as F,Mr as Ft,_A as G,y as Gt,aj as H,S as Ht,sN as I,Or as It,xk as J,jr as Jt,Lk as K,br as Kt,eN as L,C as Lt,QB as M,Yi as Mt,ZB as N,Ar as Nt,aH as O,Xg as Ot,ON as P,Fr as Pt,R as Q,nN as R,yr as Rt,e7 as S,q_ as St,e4 as T,ng as Tt,FA as U,Dr as Ut,DM as V,x as Vt,kA as W,vr as Wt,cT as X,P as Y,sE as Z,k7 as _,JT as _t,x7 as a,M as at,t7 as b,Qw as bt,D7 as c,Ww as ct,O7 as d,Yw as dt,nT as et,y7 as f,aE as ft,E7 as g,HT as gt,M7 as h,IT as ht,S7 as i,mT as it,XB as j,ha as jt,QV as k,Kh as kt,A7 as l,ST as lt,g7 as m,UT as mt,h7 as n,I as nt,w7 as o,N as ot,T7 as p,Bw as pt,Vk as q,b as qt,C7 as r,sT as rt,_7 as s,F as st,v7 as t,bT as tt,j7 as u,Uw as ut,p7 as v,GT as vt,t4 as w,G_ as wt,Y5 as x,zw as xt,m7 as y,$w as yt,oN as z,w as zt};