@usine/server 0.4.1-next.325.g79174da.1.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +7 -1
  2. package/dist/auth/api.d.ts +108 -0
  3. package/dist/auth/api.d.ts.map +1 -0
  4. package/dist/auth/api.js +109 -0
  5. package/dist/auth/api.js.map +1 -0
  6. package/dist/auth/http.d.ts.map +1 -1
  7. package/dist/auth/http.js +26 -33
  8. package/dist/auth/http.js.map +1 -1
  9. package/dist/http.d.ts.map +1 -1
  10. package/dist/http.js +2 -1
  11. package/dist/http.js.map +1 -1
  12. package/dist/openapi.d.ts +6 -0
  13. package/dist/openapi.d.ts.map +1 -0
  14. package/dist/openapi.js +68 -0
  15. package/dist/openapi.js.map +1 -0
  16. package/dist/web/assets/_agent-DduvwaVK.js +1 -0
  17. package/dist/web/assets/_label-CeJTfdyr.js +1 -0
  18. package/dist/web/assets/{_loop-CI8wT73I.js → _loop-xu3sbDMH.js} +1 -1
  19. package/dist/web/assets/{_name-BIiHdJIM.js → _name-DHJA0DfK.js} +1 -1
  20. package/dist/web/assets/{_number-DOftkarN.js → _number-CxL2Fcpl.js} +1 -1
  21. package/dist/web/assets/_number-DAq4EEnO.js +1 -0
  22. package/dist/web/assets/{_number-zDnuidOW.js → _number-DlcNbQyC.js} +1 -1
  23. package/dist/web/assets/_project-DAq4EEnO.js +1 -0
  24. package/dist/web/assets/{_project-DwYWqZaq.js → _project-DwpEglrZ.js} +1 -1
  25. package/dist/web/assets/{_project-CVPqKw8_.js → _project-GK2-urBn.js} +1 -1
  26. package/dist/web/assets/_run-DAq4EEnO.js +1 -0
  27. package/dist/web/assets/{_run-B4-87ibA.js → _run-jX-octY4.js} +1 -1
  28. package/dist/web/assets/{_worker-BBfkUdTZ.js → _worker-C_Nw6Vto.js} +1 -1
  29. package/dist/web/assets/{action-CAwzK5mk.js → action-CniC234z.js} +1 -1
  30. package/dist/web/assets/{actions-BXWVnBF3.js → actions-BJ8FViiC.js} +1 -1
  31. package/dist/web/assets/{agents-BStm1azV.js → agents-BD_MpjbH.js} +1 -1
  32. package/dist/web/assets/agents-Csj7pU8B.js +1 -0
  33. package/dist/web/assets/api-D3RWLycx.js +335 -0
  34. package/dist/web/assets/{code-block-CgYM2MuQ.js → code-block-d5zwBZo-.js} +1 -1
  35. package/dist/web/assets/{drawer-BB7jwe-O.js → drawer-D6KxeZBZ.js} +1 -1
  36. package/dist/web/assets/{edit-and-retry-B0OIPvbt.js → edit-and-retry-BKxt-FIG.js} +1 -1
  37. package/dist/web/assets/{file-error-DeQv_cj8.js → file-error-LMdCcTon.js} +1 -1
  38. package/dist/web/assets/{history-Dg2dL6yf.js → history-34nvr9sY.js} +1 -1
  39. package/dist/web/assets/{index-BGr-Cg-z.js → index-B_6qmKij.js} +3 -3
  40. package/dist/web/assets/{label-badge-C3PtxhEk.js → label-badge-cRUT7_pk.js} +1 -1
  41. package/dist/web/assets/{labels-DFfLQe0K.js → labels-BGCA9v1C.js} +1 -1
  42. package/dist/web/assets/{list-CHD0VbJL.js → list-qM2KUYvo.js} +1 -1
  43. package/dist/web/assets/loops-BXqvj3ko.js +1 -0
  44. package/dist/web/assets/{members-Cl_WCHwt.js → members-B14AFaH7.js} +1 -1
  45. package/dist/web/assets/{model-D9QKZ_Hk.js → model-C6gErpq3.js} +1 -1
  46. package/dist/web/assets/{moves-BQl144Rz.js → moves-BYTLKqNE.js} +1 -1
  47. package/dist/web/assets/{not-found-C8JhxsFV.js → not-found-CCicx33l.js} +1 -1
  48. package/dist/web/assets/{outcome-Bmu_N2Ni.js → outcome-D5IWnu4P.js} +1 -1
  49. package/dist/web/assets/{overview-CUn9OtUH.js → overview-DLYaCoiG.js} +1 -1
  50. package/dist/web/assets/{page-CmRQu9F2.js → page-BEpkTOW0.js} +1 -1
  51. package/dist/web/assets/{projects-D7j8WXJK.js → projects-B6PO2z2B.js} +1 -1
  52. package/dist/web/assets/{queries-Cvt0xQVN.js → queries-Bhp4FeLT.js} +1 -1
  53. package/dist/web/assets/{queries-CKjxlPEk.js → queries-CU77zJnf.js} +1 -1
  54. package/dist/web/assets/{queries-D5TGw8Nr.js → queries-C_qC_nGu.js} +1 -1
  55. package/dist/web/assets/{queries-Cdfj6CtB.js → queries-ESTqS3FK.js} +1 -1
  56. package/dist/web/assets/{repositories-B_mXysRY.js → repositories-Db6PsyxS.js} +1 -1
  57. package/dist/web/assets/{repository-link-B7-4fVcX.js → repository-link-OOfhq6c8.js} +1 -1
  58. package/dist/web/assets/route-D8Nd9ZwI.js +1 -0
  59. package/dist/web/assets/route-DjjbuG-J.js +1 -0
  60. package/dist/web/assets/{route-status-tny9_oCm.js → route-status-Cxocu6W_.js} +1 -1
  61. package/dist/web/assets/routes-DAq4EEnO.js +1 -0
  62. package/dist/web/assets/{routes-DRogv1gQ.js → routes-Dq3R4rSX.js} +1 -1
  63. package/dist/web/assets/{run-again-DVg9Ncn3.js → run-again-DHlW6Dcb.js} +1 -1
  64. package/dist/web/assets/{section-CjCP4gvu.js → section-C75aUrac.js} +1 -1
  65. package/dist/web/assets/{section-Du_ZZiFG.js → section-Db-f1liW.js} +1 -1
  66. package/dist/web/assets/{section-BjpSGYua.js → section-Wflvjspx.js} +1 -1
  67. package/dist/web/assets/{settings-DlN91oPk.js → settings-CpA5zhaC.js} +1 -1
  68. package/dist/web/assets/{sign-in-i_b9opnw.js → sign-in-D5kDf9C5.js} +1 -1
  69. package/dist/web/assets/{strings-DhGEKt5X.js → strings-DmAVtEUC.js} +1 -1
  70. package/dist/web/assets/tasks-DAq4EEnO.js +1 -0
  71. package/dist/web/assets/{tasks-DG6D0ByG.js → tasks-Dmzf4nUy.js} +1 -1
  72. package/dist/web/assets/{tokens-Dfsm5C2T.js → tokens-BHREcyDp.js} +1 -1
  73. package/dist/web/assets/{usage-cNWB4RMb.js → usage-ZTnmWdRP.js} +1 -1
  74. package/dist/web/assets/{use-project-links-C3F9c85T.js → use-project-links-CdgpfpoU.js} +1 -1
  75. package/dist/web/assets/{useTriggerFocusGuards-BEdypEdV.js → useTriggerFocusGuards-u-Jz4hr2.js} +1 -1
  76. package/dist/web/assets/{workers-DkgWKjiI.js → workers-D8lcf3zo.js} +1 -1
  77. package/dist/web/index.html +12 -12
  78. package/package.json +11 -10
  79. package/dist/web/assets/_agent-DIZrJ2oZ.js +0 -1
  80. package/dist/web/assets/_label-DMFWLPtF.js +0 -1
  81. package/dist/web/assets/_number-Bn_57si9.js +0 -1
  82. package/dist/web/assets/_project-Bn_57si9.js +0 -1
  83. package/dist/web/assets/_run-Bn_57si9.js +0 -1
  84. package/dist/web/assets/agents-BZV7-W7e.js +0 -1
  85. package/dist/web/assets/api-CoJQoiOc.js +0 -335
  86. package/dist/web/assets/loops-CRPsfOzn.js +0 -1
  87. package/dist/web/assets/route-Di3rgfZ0.js +0 -1
  88. package/dist/web/assets/route-DjL-s2L0.js +0 -1
  89. package/dist/web/assets/routes-Bn_57si9.js +0 -1
  90. package/dist/web/assets/tasks-Bn_57si9.js +0 -1
@@ -0,0 +1,335 @@
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()}},eee={[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}}},zt=e=>pe(e,Ot),Bt=e=>pe(e,kt),Vt=`~effect/Cause`,Ht=`~effect/Cause/Reason`,Ut=e=>pe(e,Vt),Wt=e=>pe(e,Ht),Gt=class{constructor(e){this[Vt]=Vt,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 Ut(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>Le(t,e.reasons[n]))}[_e](){return ke(this.reasons)}},Kt=new WeakMap,qt=class{[Ht];annotations;_tag;constructor(e,t,n){if(this[Ht]=Ht,this._tag=e,t!==Jt&&typeof n==`object`&&n&&t.size>0){let e=Kt.get(n);e&&(t=new Map([...e,...t])),Kt.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()}},Jt=new Map,Yt=class extends qt{constructor(e,t=Jt){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${ot(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[Ie](e){return on(e)&&Le(this.error,e.error)&&Le(this.annotations,e.annotations)}[_e](){return xe(Te(this._tag))(xe(ve(this.error))(ve(this.annotations)))}},Xt=e=>new Gt(e),Zt=(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},Qt=r(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new Gt(Zt(e.reasons,t.reasons));return Le(e,n)?e:n}),$t=(e,t)=>{let n=e.reasons.slice();for(let e of t.reasons)cn(e)&&!n.some(t=>cn(t)&&t.fiberId===e.fiberId&&t.annotations===e.annotations)&&n.push(e);return n.length===e.reasons.length?e:new Gt(n)},en=new Gt([]),tn=e=>new Gt([new Yt(e)]),nn=class extends qt{constructor(e,t=Jt){super(`Die`,t,e),this.defect=e}toString(){return`Die(${ot(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[Ie](e){return sn(e)&&Le(this.defect,e.defect)&&Le(this.annotations,e.annotations)}[_e](){return xe(Te(this._tag))(xe(ve(this.defect))(ve(this.annotations)))}},rn=e=>new Gt([new nn(e)]),an=r(e=>Ut(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new Gt(e.reasons.map(e=>e.annotate(t,n)))),on=e=>e._tag===`Fail`,sn=e=>e._tag===`Die`,cn=e=>e._tag===`Interrupt`;function tee(e){return _n(`Effect.evaluate: Not implemented`)}var ln=e=>({...eee,[jt]:e.op,[Nt]:e[`~effect/Effect/evaluate`]??tee,[Pt]:e[Pt],[Ft]:e[Ft],[It]:e[It]}),un=e=>{let t=ln(e),n=function(e){this[Mt]=e};return n.prototype=t,function(e){return new n(e)}},dn=e=>{let t={[kt]:kt,_tag:e.op,get[e.prop](){return this[Mt]},...ln(e),toString(){return`${e.op}(${ot(this[Mt])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[Mt]}},[Ie](e){return Bt(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)}},fn=dn({op:`Success`,prop:`value`,[Nt](e){let t=e.getCont(Pt);return t?t[Pt](this[Mt],e,this):e.yieldWith(this)}}),pn={key:`effect/Cause/StackTrace`},mn={key:`effect/Cause/InterruptorStackTrace`},hn=dn({op:`Failure`,prop:`cause`,[Nt](e){let t=this[Mt],n=!1;e.cache.stackFrame&&(t=an(t,{mapUnsafe:new Map([[pn.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=Xt(t.reasons.filter(e=>e._tag!==`Fail`))),t=$t(t,i),n=!0}return r?r[Ft](t,e,n?void 0:this):e.yieldWith(n?hn(t):this)}}),gn=e=>hn(tn(e)),_n=e=>hn(rn(e)),vn=un({op:`WithFiber`,[Nt](e){return this[Mt](e)}}),yn=function(){class e extends globalThis.Error{}let t=ln({op:`YieldableError`,[Nt](){return gn(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),bn=function(){let e=Symbol.for(`effect/Data/Error/plainArgs`);return class extends yn{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}}}}(),xn=e=>{class t extends bn{_tag=e}return t.prototype.name=e,t},Sn=`~effect/Cause/NoSuchElementError`,Cn=class extends xn(`NoSuchElementError`){[Sn]=Sn;constructor(e){super({message:e})}},wn=`~effect/Cause/Done`,Tn=e=>pe(e,wn),En={[wn]:wn,_tag:`Done`,value:void 0},Dn=e=>e===void 0?En:{[wn]:wn,_tag:`Done`,value:e},On=gn(En),kn=e=>e===void 0?On:gn(Dn(e)),An=e=>ln({op:e.label,[Nt]:e.evaluate}),jn=e=>(t,n)=>t===n||e(t,n),Mn=(e,t)=>e===t,Nn=()=>Mn;function Pn(e){return jn((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 Fn(e){return jn((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 In=`~effect/Option`,Ln={[In]:{_A:e=>e},...Rt,[Symbol.iterator](){return new wt(this)}},nee=Object.defineProperty(Object.assign(Object.create(Ln),{_tag:`Some`,_op:`Some`,[Ie](e){return Rn(e)&&Bn(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}}),ree=ve(`None`),iee=Object.assign(Object.create(Ln),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[Ie](e){return Rn(e)&&zn(e)},[_e](){return ree},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),Rn=e=>pe(e,In),zn=e=>e._tag===`None`,Bn=e=>e._tag===`Some`,Vn=Object.create(iee),Hn=function(e){this.value=e};Hn.prototype=nee;var Un=e=>new Hn(e),Wn=`~effect/Result`,Gn={[Wn]:{_A:e=>e,_E:e=>e},...Rt,[Symbol.iterator](){return new wt(this)}},Kn=Object.assign(Object.create(Gn),{_tag:`Success`,_op:`Success`,[Ie](e){return Jn(e)&&Xn(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(Gn),{_tag:`Failure`,_op:`Failure`,[Ie](e){return Jn(e)&&Yn(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)}}}),Jn=e=>pe(e,Wn),Yn=e=>e._tag===`Failure`,Xn=e=>e._tag===`Success`,Zn=function(e){this.failure=e};Zn.prototype=qn;var Qn=e=>new Zn(e),$n=function(e){this.success=e};$n.prototype=Kn;var er=e=>new $n(e),tr=r(2,(e,t)=>zn(e)?Qn(t()):er(e.value));function nr(e){return(t,n)=>t===n?0:e(t,n)}var rr=nr((e,t)=>e<t?-1:1),ir=nr((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 ar(e){return nr((t,n)=>e(n,t))}function or(e){let t=Array.from(e);return nr((e,n)=>{let r=0;for(let i of t)if(r=i(e,n),r!==0)return r;return r})}var sr=r(2,(e,t)=>nr((n,r)=>e(t(n),t(r)))),cr=e=>r(2,(t,n)=>e(t,n)===-1),lr=e=>r(2,(t,n)=>e(t,n)===1),ur=e=>r(2,(t,n)=>e(t,n)!==1),dr=e=>r(2,(t,n)=>e(t,n)!==-1),y=()=>Vn,b=Un,fr=Rn,x=zn,S=Bn,pr=r(2,(e,{onNone:t,onSome:n})=>x(e)?t():n(e.value)),mr=r(2,(e,t)=>x(e)?t():e.value),hr=r(2,(e,t)=>x(e)?t():e),gr=e=>{let t=y();for(t of e)if(S(t))return t;return t},_r=e=>e==null?y():b(e),vr=e=>e===void 0?y():b(e),yr=e=>e===null?y():b(e),C=mr(c),br=mr(l),xr=e=>(...t)=>{try{return b(e(...t))}catch{return y()}},aee=r(2,(e,t)=>{if(S(e))return e.value;throw t()}),Sr=r(2,(e,t)=>x(e)?y():b(t(e.value))),Cr=r(2,(e,t)=>x(e)?y():t(e.value)),oee=Cr(i),see=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)},wr=e=>x(e)?[]:[e.value],Tr=r(2,(e,t)=>x(e)?y():t(e.value)?b(e.value):y()),cee=r(2,(e,t)=>t(e)?b(e):y()),Er=(e=>r(2,(t,n)=>!x(t)&&e(t.value,n)))(Qe()),Dr=r(2,(e,t)=>!x(e)&&t(e.value)),Or=`~effect/Context/Service`,kr=function(){function e(){}let t=e;Object.setPrototypeOf(t,Ar);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[Mr]=Mr,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&jr.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},Ar={[Or]:Or,...An({label:`Service`,evaluate(e){return fn(ti(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return Yr(this,e)},use(e){return vn(t=>e(ti(t.context,this)))},useSync(e){return vn(t=>fn(e(ti(t.context,this))))}},jr=new Set,Mr=`~effect/Context/Reference`,Nr=`~effect/Context`,Pr=8,Fr=8,Ir=(e,t,n,r)=>{let i=Object.create(Ur);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Lr=(e,t)=>{t&&(Lr(e,t.parent),e.set(t.key,t.value))},Rr=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Lr(t,e.overlay),e._flat=t},zr=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),Hr(n)},Br=Symbol(),Vr=(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)?Br:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=Fr&&(n.base=Rr(n),n.overlay=void 0,n.depth=0),r)},Hr=e=>Ir(void 0,e,void 0,0),Ur={get mapUnsafe(){return Rr(this)},...Rt,[Nr]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[Ie](e){if(!Gr(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)}},Wr=(e,t)=>e.cacheRoot===t.cacheRoot,Gr=e=>pe(e,Nr),Kr=e=>!!e[Mr],qr=()=>Jr,Jr=Hr(new Map),Yr=(e,t)=>Hr(new Map([[e.key,t]])),Xr=r(3,(e,t,n)=>Zr(e,t.key,n)),Zr=(e,t,n)=>{let r=e,i=jr.has(t)?void 0:r.cacheRoot;if(r.depth>=Pr){let e=new Map(r._flat??r.base);return r._flat||Lr(e,r.overlay),e.set(t,n),Ir(i,e,void 0,0)}return Ir(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},Qr=r(2,(e,t)=>$r(e,t.key)),$r=(e,t)=>{let n=Vr(e,t);return n===Br?void 0:n},ei=r(2,(e,t)=>{let n=Vr(e,t.key);if(n===Br){if(Kr(t))return ri(t);throw ii(t)}return n}),ti=ei,ni=`~effect/Context/defaultValue`,ri=e=>ni in e?e[ni]:e[ni]=e.defaultValue(),ii=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},ai=r(2,(e,t)=>{let n=Vr(e,t.key);return n===Br?Kr(t)?b(ri(t)):y():b(n)}),oi=r(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:zr(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),si=(...e)=>{let t=new Map;for(let n=0;n<e.length;n++)e[n].mapUnsafe.forEach((e,n)=>{t.set(n,e)});return Hr(t)},ci=(...e)=>t=>{if(e.length<=1){let n=new Map;if(e.length===1){let r=e[0].key,i=Vr(t,r);i!==Br&&n.set(r,i)}return Hr(n)}let n=new Set(e.map(e=>e.key));return zr(t,e=>e.forEach((t,r)=>{n.has(r)||e.delete(r)}))},li=kr,ui=e=>e.length>0,di=e=>e>0?Math.floor(e):0,fi=e=>Math.max(1,di(e)),pi=er,mi=Qn,hi=tr,gi=e=>{if(oe(e))try{return pi(e())}catch(e){return mi(e)}try{return pi(e.try())}catch(t){return mi(e.catch(t))}},_i=Jn,vi=Yn,yi=Xn,bi=r(2,(e,t)=>vi(e)?mi(t(e.failure)):e),xi=r(2,(e,t)=>yi(e)?pi(t(e.success)):e),Si=r(2,(e,{onFailure:t,onSuccess:n})=>vi(e)?t(e.failure):n(e.success)),Ci=r(2,(e,t)=>{if(yi(e))return e.success;throw t(e.failure)})(i),wi=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(vi(n))return n;t.push(n.success)}return pi(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(vi(r))return r;Et(t,n,r.success)}return pi(t)},Ti=(...e)=>e,Ei=Pn,Di={[Symbol.iterator](){return Oi}},Oi={next(){return{done:!0,value:void 0}}},ki=()=>Di,Ai=r(2,(e,t)=>Object.hasOwn(e,t)),ji=r(2,(e,t)=>{let n={...e};for(let r of Mi(e))Et(n,r,t(e[r],r));return n}),Mi=e=>Object.keys(e),Ni=e=>r(2,(t,n)=>{for(let r of Mi(t))if(!Ai(n,r)||!e(t[r],n[r]))return!1;return!0}),Pi=e=>{let t=Ni(e);return(e,n)=>t(e,n)&&t(n,e)},Fi=globalThis.Array,Ii=e=>Fi.isArray(e)?e:Fi.from(e),Li=e=>Fi.isArray(e)?e:[e],lee=r(2,(e,t)=>[t,...e]),Ri=r(2,(e,t)=>[...e,t]),uee=r(2,(e,t)=>Ii(e).concat(Ii(t)));Fi.isArray;var zi=ui,Bi=ui;function Vi(e,t){return!Number.isFinite(e)||e<0||e>=t.length}var dee=r(2,(e,t)=>{let n=Math.floor(t);return Vi(n,e)?y():b(e[n])}),Hi=r(2,(e,t)=>{let n=Math.floor(t);if(Vi(n,e))throw Error(`Index out of bounds: ${n}`);return e[n]}),fee=dee(0),Ui=Hi(0),pee=e=>e[e.length-1],Wi=r(2,(e,t)=>{let n=Ii(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()}),Gi=r(2,(e,t)=>{let n=Fi.from(e);return n.sort(t),n}),mee=r(2,(e,t)=>hee(e,t,Ti)),hee=r(3,(e,t,n)=>{let r=Ii(e),i=Ii(t);if(Bi(r)&&Bi(i)){let e=[n(Ui(r),Ui(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[]}),gee=r(2,(e,t)=>{let n=Ii(e);if(Bi(n)){let[e,r]=t(n),i=[e],a=r;for(;ui(a);){let[e,n]=t(a);i.push(e),a=n}return i}return[]}),Ki=r(2,(e,t)=>{let n=fi(t);return n>=e.length?[qi(e),[]]:[lee(e.slice(1,n),Ui(e)),e.slice(n)]}),qi=e=>e.slice(),Ji=r(2,(e,t)=>{let n=Ii(e);return Bi(n)?gee(n,Ki(t)):[]}),Yi=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}),Xi=(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},Zi=()=>[],Qi=e=>[e],$i=r(2,(e,t)=>e.map(t)),ea=e=>{let t=[];for(let n of e)S(n)&&t.push(n.value);return t},ta=Fn,na=r(2,(e,t)=>{let n=[];next:for(let r of Ii(e)){for(let e=0;e<n.length;e++)if(t(r,n[e]))continue next;n.push(r)}return n}),ra=e=>{let t=Ii(e);if(t.length<2)return[...t];let n=new Map,r=[];for(let e of t)Xi(n,e)&&r.push(e);return r},ia=`~effect/Duration`,aa=BigInt(0),oa=BigInt(1),sa=BigInt(2),ca=BigInt(10),la=BigInt(1e3),ua=BigInt(1e6),da=BigInt(1e9),fa=BigInt(6e10),pa=BigInt(36e11),ma=BigInt(864e11),ha=BigInt(6048e11),ga=e=>BigInt(Math.sign(e)*Math.round(Math.abs(e))),_a=e=>Number.isInteger(e)?BigInt(e)*ua:ga(e*1e6),va=e=>Ma(Number.isFinite(e)?ga(e):e),ya=(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},ba=(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 xa(r?-o:o,a)},xa=(e,t)=>{let n=e<aa?-e:e,r=n/t+(n%t*sa>=t?oa:aa);return e<aa?-r:r},Sa=(e,t)=>{let n=Number(e)*t;if(!Number.isFinite(n))return Ma(n);let r=ba(e,BigInt(t)*ua);return Ma(Number.isInteger(n)&&BigInt(n)*ua===r?n:r)},Ca=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,wa=e=>{switch(typeof e){case`number`:return Ra(e);case`bigint`:return La(e);case`string`:{if(e===`Infinity`)return Fa;if(e===`-Infinity`)return Ia;let t=Ca.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return La(ba(r,oa));if(i===`micro`||i===`micros`)return La(ba(r,la));switch(i){case`milli`:case`millis`:return Sa(r,1);case`second`:case`seconds`:return Sa(r,1e3);case`minute`:case`minutes`:return Sa(r,6e4);case`hour`:case`hours`:return Sa(r,36e5);case`day`:case`days`:return Sa(r,864e5);case`week`:case`weeks`:return Sa(r,6048e5)}break}case`object`:{if(e===null)break;if(ia in e)return e;if(Array.isArray(e)){if(e.length!==2||!e.every(te))return Da(e);if(Number.isNaN(e[0])||Number.isNaN(e[1]))return Pa;if(e[0]===-1/0||e[1]===-1/0)return Ia;if(e[0]===1/0||e[1]===1/0)return Fa;let t=e[0]*1e9+e[1];return Number.isFinite(t)&&Number.isInteger(e[0])&&Number.isInteger(e[1])?Ma(BigInt(e[0])*da+BigInt(e[1])):va(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 Ma(n);let e=Ea(t);return e===void 0||BigInt(n)*ua===e?Ma(n):Ma(e)}let r=n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0),i=Number.isFinite(r)?Ea(t):void 0;return i===void 0?va(r):Ma(i)}}return Da(e)},Ta=e=>!e||Number.isInteger(e),Ea=e=>{if(!Ta(e.weeks)||!Ta(e.days)||!Ta(e.hours)||!Ta(e.minutes)||!Ta(e.seconds)||!Ta(e.milliseconds)||!Ta(e.microseconds)||!Ta(e.nanoseconds))return;let t=aa;return e.weeks&&(t+=BigInt(e.weeks)*ha),e.days&&(t+=BigInt(e.days)*ma),e.hours&&(t+=BigInt(e.hours)*pa),e.minutes&&(t+=BigInt(e.minutes)*fa),e.seconds&&(t+=BigInt(e.seconds)*da),e.milliseconds&&(t+=BigInt(e.milliseconds)*ua),e.microseconds&&(t+=BigInt(e.microseconds)*la),e.nanoseconds&&(t+=BigInt(e.nanoseconds)),t},Da=e=>{throw Error(`Invalid Input: ${e}`)},Oa={_tag:`Millis`,millis:0},ka={_tag:`Infinity`},Aa={_tag:`NegativeInfinity`},ja={[ia]:ia,[_e](){switch(this.value._tag){case`Millis`:return ve(_a(this.value.millis));case`Nanos`:return ve(this.value.nanos);default:return De(this.value)}},[Ie](e){return Na(e)&&Ka(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)}},Ma=e=>{let t=Object.create(ja);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?Oa:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:_a(e)}:e>0?ka:Aa:e===aa?Oa:{_tag:`Nanos`,nanos:e},t},Na=e=>pe(e,ia),Pa=Ma(0),Fa=Ma(1/0),Ia=Ma(-1/0),La=e=>Ma(e),Ra=e=>Ma(e),za=e=>Ma(e*1e3),Ba=e=>Ma(e*6e4),Va=e=>Ua(wa(e),{onMillis:i,onNanos:e=>ya(e,1e6),onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),Ha=e=>{let t=wa(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 _a(t.value.millis)}},Ua=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)()}}),Wa=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(Ha(e),t.value.nanos):n.onNanos(e.value.nanos,Ha(t))),Ga=(e,t)=>Wa(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),Ka=r(2,(e,t)=>Ga(e,t)),qa=e=>t=>!vi(e(t)),Ja=e=>t=>t.has(e)?pi(t):mi(t),Ya=r(2,(e,t)=>n=>{let r=e(n);return vi(r)?r:t(r.success)}),Xa=li(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new to}),Za=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},Qa=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},$a=e=>{try{return Qa(e)}catch{return Za(e)}},eo=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}},to=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?Za:$a)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new no(this.setImmediate)}},no=class{tasks=new eo;running=void 0;setImmediate;constructor(e=$a){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()}},ro=li(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),io=li(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),ao=class extends n{constructor(e){super(),e&&Dt(this,e)}},oo=e=>class extends ao{_tag=e},so=xn,co=`~effect/encoding/EncodingError`,lo=class extends so(`EncodingError`){[co]=co},uo=e=>bo(typeof e==`string`?vo.encode(e):e),fo=e=>{switch(e){case 16:return go();case 32:return _o();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=ho();return t}}},po=Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),mo=()=>Math.random()*4294967296>>>0,ho=()=>{let e=mo();return String.fromCharCode(po[e>>>28],po[e>>>24&15],po[e>>>20&15],po[e>>>16&15],po[e>>>12&15],po[e>>>8&15],po[e>>>4&15],po[e&15])},go=()=>{let e=mo(),t=mo();return String.fromCharCode(po[e>>>28],po[e>>>24&15],po[e>>>20&15],po[e>>>16&15],po[e>>>12&15],po[e>>>8&15],po[e>>>4&15],po[e&15],po[t>>>28],po[t>>>24&15],po[t>>>20&15],po[t>>>16&15],po[t>>>12&15],po[t>>>8&15],po[t>>>4&15],po[t&15])},_o=()=>{let e=mo(),t=mo(),n=mo(),r=mo();return String.fromCharCode(po[e>>>28],po[e>>>24&15],po[e>>>20&15],po[e>>>16&15],po[e>>>12&15],po[e>>>8&15],po[e>>>4&15],po[e&15],po[t>>>28],po[t>>>24&15],po[t>>>20&15],po[t>>>16&15],po[t>>>12&15],po[t>>>8&15],po[t>>>4&15],po[t&15],po[n>>>28],po[n>>>24&15],po[n>>>20&15],po[n>>>16&15],po[n>>>12&15],po[n>>>8&15],po[n>>>4&15],po[n&15],po[r>>>28],po[r>>>24&15],po[r>>>20&15],po[r>>>16&15],po[r>>>12&15],po[r>>>8&15],po[r>>>4&15],po[r&15])},vo=new TextEncoder,yo=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),bo=e=>{let t=``;for(let n=0;n<e.length;n++)t+=yo[e[n]];return t},xo=`effect/Tracer/ParentSpan`,So=class extends kr()(xo,{fiberCached:!0}){},Co=e=>e,wo=li(`effect/Tracer/DisablePropagation`,{defaultValue:s}),To=li(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),Eo=li(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),Do=`effect/Tracer`,Oo=Co({span:e=>new ko(e)}),ko=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??=br(this.parent)?.traceId??fo(32)}get spanId(){return this._spanId??=fo(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)}},Ao=`effect/Metric/FiberRuntimeMetrics`,jo=li(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:l}),Mo=li(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:o}),No=li(`effect/References/TracerTimingEnabled`,{defaultValue:o}),Po=li(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),Fo=li(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),Io=li(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),Lo=li(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),Ro=li(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),zo=li(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),Bo=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:Ho(()=>n.stack)}},Vo=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}},Ho=Vo(3),Uo=class extends qt{constructor(e,t=Jt){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[Ie](e){return cn(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[_e](){return Te(`${this._tag}:${this.fiberId}`)}},Wo=e=>new Uo(e),Go=e=>new Gt([new Uo(e)]),Ko=e=>e.reasons.some(on),qo=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return pi(n.error)}return mi(e)},Jo=e=>e.reasons.some(sn),Yo=e=>Jo(e)&&Ko(e)?Xt(e.reasons.map(e=>e._tag===`Fail`&&!Tn(e.error)?new nn(e.error,e.annotations):e)):e,Xo=e=>Jo(e)?mi(Yo(e)):qo(e),Zo=e=>{let t=e.reasons.find(sn);return t?pi(t.defect):mi(e)},Qo=e=>e.reasons.some(cn),$o=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?pi(t):mi(e)},es=e=>e.reasons.length>0&&e.reasons.every(cn),ts=r(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>on(e)?(n=!0,new Yt(t(e.error),e.annotations)):e);return n?Xt(r):e}),ns=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},rs=(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(is(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=ls(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(is(i,r[0].annotations,t))}}finally{i!==0&&Ct(i)}return n},is=(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(as(e),{cause:i!==void 0&&!r.has(i)?is(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=fs(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},as=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)},os=/\((.*)\)/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(pn.key);return n&&(e=`${e}\n${us(n)}`),e},ls=(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(mn.key);n.push(` at fiber (${t})`),r&&n.push(us(r))}return n.join(`
10
+ `)},us=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(os),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
+ `)},ds=e=>rs(e).map(fs).join(`
12
+ `),fs=e=>e.cause?`${e.stack} {\n${ps(e.cause,` `)}\n}`:e.stack,ps=(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${ps(e.cause,`${t} `)}\n${t}}`),r},ms=`~effect/Fiber`,hs={_A:i,_E:i},gs={id:0},_s=(()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),vs=()=>_s===void 0?void 0:new _s(`effect/Fiber`),ys=()=>globalThis[rt],bs=class{constructor(e,t=!0){this.setContext(e),this.id=++gs.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[ms](){return hs}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return ti(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=Go(e);this.cache.stackFrame&&(n=an(n,Yr(pn,this.cache.stackFrame))),t&&(n=an(n,t)),this._interruptedCause=this._interruptedCause?$t(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(As(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=vs();return}let n=xs.interruptChildren&&xs.interruptChildren(this);if(n!==void 0)return this.evaluate(vc(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=qr()}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=As(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=vc(Ps,()=>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 _n(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=_n(e)}}finally{this._running=n,globalThis[rt]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,vee;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&yee-1))return fn(e);let t=this.getCont(Pt);return t?t[Pt](e,this):this.yieldWith(fn(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&&Wr(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=_ee(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}},_ee=e=>{let t=$r(e,Do);return{scheduler:ti(e,Xa),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:ti(e,Mo),span:$r(e,xo),logLevel:ti(e,Lo),minimumLogLevel:ti(e,Ro),stackFrame:ti(e,jo),runtimeMetrics:$r(e,Ao),maxOpsBeforeYield:ti(e,ro),preventYield:ti(e,io)}},vee={[Pt](e,t){return As(t._interruptedCause)},[Ft](e,t){return As(t._interruptedCause)}},yee=32,xs={interruptChildren:void 0},Ss=e=>{if(!e.cache.stackFrame)return;let t=new Map;return t.set(mn.key,e.cache.stackFrame),Hr(t)},Cs=e=>{let t=e;return t._exit?ks(t._exit):Ws(n=>t._exit?n(ks(t._exit)):Ms(e.addObserver(e=>n(ks(e)))))},ws=e=>Ws(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(ks(r))}return a(),Ms(()=>i?.())}),Ts=e=>{let t=e;return t._exit?t._exit:Ws(n=>t._exit?n(t._exit):Ms(e.addObserver(n)))},Es=e=>vn(t=>Ds(e,t.id)),Ds=r(e=>pe(e[0],ms),(e,t,n)=>vn(r=>{let i=Ss(r);return i=i&&n?oi(i,n):i??n,e.interruptUnsafe(t,i),hc(Cs(e))})),Os=e=>vn(t=>{let n=Ss(t),r=Zi();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return hc(ws(r))}),ks=fn,As=hn,js=gn,Ms=un({op:`Sync`,[Nt](e){let t=this[Mt](),n=e.getCont(Pt);return n?n[Pt](t,e):e.yieldWith(fn(t))}}),Ns=un({op:`Suspend`,[Nt](e){return this[Mt]()}}),bee=Si({onFailure:js,onSuccess:ks}),Ps=un({op:`Yield`,[Nt](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(jc)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}})(0),Fs=ks(y()),Is=e=>Ns(()=>As(e())),Ls=e=>_n(e),Rs=ks(void 0),zs=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new ld(e,`An error occurred in Effect.try`):e.catch;return Ns(()=>{try{return ks(t())}catch(e){return js(n(e))}})},Bs=e=>Hs(function(t,n){e(n).then(e=>t(ks(e)),e=>t(Ls(e)))},e.length!==0),Vs=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new ld(e,`An error occurred in Effect.tryPromise`):e.catch;return Hs(function(e,r){let i=e=>Ns(()=>{try{return js(Tt(()=>n(e)))}catch(e){return Ls(e)}});try{t(r).then(t=>e(ks(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},Hs=function(){let e=ln({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(Us(()=>(t=!0,r?.abort(),i??jc))),Lt):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),Us=un({op:`AsyncFinalizer`,[It](e){e.interruptible&&(e.interruptible=!1,e._stack.push(iu))},[Ft](e,t){return Qo(e)?vc(Ol(hn(e),this[Mt]()),()=>As(e)):As(e)}}),Ws=e=>Hs(e,e.length>=2),Gs=Ws(u),Ks=(...e)=>{if(e.length===1){let t=e[0];return Ns(()=>ec(t()))}let[t,n]=e;return Ns(()=>ec(n.call(t.self)))},qs=(e,...t)=>{let n=t.length===0?function(){return Ns(()=>ec(e.apply(this,arguments)))}:function(){let n=Ns(()=>ec(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return Js(e.length,n)},Js=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),Ys=Vo(2),Xs=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)=>Zs(t,r,i,a,e,n):Zs(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},Zs=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?Ys(()=>n.stack):l;return Js(o.length,function(...t){let n=Ns(()=>{let e=o.apply(this,arguments);return zt(e)?e:ec(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!zt(n))return n;let u=St(),d;return u!==0&&(Ct(2),d=new globalThis.Error,Ct(u)),zc(i?Uu(e,a,e=>Wu(n,e)):n,jo,t=>({name:e,stack:d?Ys(()=>d.stack):l,parent:{name:s,stack:c,parent:t}}))})},Qs=(e,...t)=>Js(e.length,t.length===0?function(){return $s(()=>e.apply(this,arguments))}:function(){let n=$s(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),$s=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return ks(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 Ns(()=>n?(n=!1,vc(r.value,e=>ec(t,e))):Ns(()=>ec(e())))}}}}catch(e){return Ls(e)}},ec=function(){let e=ln({op:`Iterator`,[Pt](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return ks(r.value);if(!yc(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)}}(),tc=r(2,(e,t)=>new ic(e,ac,ks(t))),nc=function(e){return e._stack.push(this),this[Mt]},rc=ln({op:`OnSuccess`,[Nt]:nc}),ic=function(e,t,n){this[Mt]=e,this[Pt]=t,this.payload=n};ic.prototype=rc;var ac=function(){return this.payload},oc=function(e,t){return t.succeedWith(this.payload)},sc=(()=>{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})(),cc=function(e,t){let n=this.payload;return t.succeedWith(sc?n(e):Tt(()=>n(e)))},lc=function(e){let t=this.payload;return t(e)},uc=function(e){let t=this.payload;return new ic(t(e),oc,e)},dc=function(e){return new ic(this.payload,oc,e)},fc=e=>Sc(e,b),pc=r(2,(e,t)=>new ic(e,zt(t)?ac:lc,t)),mc=r(2,(e,t)=>new ic(e,zt(t)?dc:uc,t)),hc=e=>new ic(e,ac,jc),gc=(e,t)=>vn(n=>{let r=new Set;return Wl(n,()=>r.size===0?void 0:Os(r)),Ws(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=bu(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})})}})}),_c=r(e=>zt(e[1]),(e,t,n)=>gc([e,t],n)),vc=r(2,(e,t)=>new ic(e,lc,t)),yc=e=>e[kt]!==void 0,bc=r(2,(e,t)=>yc(e)?e._tag===`Success`?t(e.value):e:vc(e,t)),xc=e=>vc(e,i),Sc=r(2,(e,t)=>new ic(e,cc,t)),Cc=r(2,(e,t)=>yc(e)?Mc(e,t):Sc(e,t)),wc=r(2,(e,t)=>yc(e)?Nc(e,t):ol(e,t)),Tc=r(2,(e,t)=>yc(e)?Pc(e,t):sl(e,t)),Ec=e=>hn(Go(e)),Dc=e=>e._tag===`Success`,Oc=e=>e._tag===`Failure`,kc=e=>e._tag===`Failure`?pi(e.cause):mi(e),Ac=e=>e._tag===`Failure`&&Qo(e.cause),jc=fn(void 0),Mc=r(2,(e,t)=>e._tag===`Success`?fn(t(e.value)):e),Nc=r(2,(e,t)=>e._tag===`Success`?e:hn(ts(e.cause,t))),Pc=r(2,(e,t)=>e._tag===`Success`?fn(t.onSuccess(e.value)):hn(ts(e.cause,t.onFailure))),Fc=r(2,(e,t)=>Dc(e)?t:e),Ic=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?jc:hn(Xt(t))},Lc=e=>vn(t=>ks(ai(t.context,e))),Rc=r(2,(e,t)=>vn(n=>{let r=n.context,i=t(r);return r===i||(n.setContext(i),Wl(n,()=>{n.setContext(r)})),e})),zc=r(3,(e,t,n)=>Rc(e,e=>{let r=ei(e,t),i=n(r);return r===i?e:Xr(e,t,i)})),Bc=()=>Vc,Vc=vn(e=>ks(e.context)),Hc=e=>vn(t=>e(t.context)),Uc=r(2,(e,t)=>yc(e)?e:Rc(e,oi(t))),Wc=function(){return arguments.length===1?r(2,(e,t)=>Gc(e,arguments[0],t)):r(3,(e,t,n)=>Gc(e,t,n)).apply(this,arguments)},Gc=(e,t,n)=>Rc(e,Xr(t,n)),Kc=r(e=>zt(e[0]),(e,t)=>du({while:o,body:a(t?.disableYield?e:vc(e,e=>Ps)),step:u})),qc=r(2,(e,t)=>new Yc(e,t.length===1?t:e=>t(e))),Jc=ln({op:`OnFailure`,[Nt]:nc}),Yc=function(e,t){this[Mt]=e,this[Ft]=t};Yc.prototype=Jc;var Xc=r(3,(e,t,n)=>qc(e,e=>{let r=t(e);return vi(r)?As(r.failure):n(r.success,e)})),Zc=r(2,(e,t)=>Xc(e,Xo,e=>t(e))),Qc=r(2,(e,t)=>Xc(e,Zo,t)),$c=r(2,(e,t)=>qc(e,e=>pc(t(e),As(e)))),el=r(3,(e,t,n)=>qc(e,e=>{let r=t(e);return vi(r)?As(e):pc(n(r.success,e),As(e))})),tl=r(2,(e,t)=>el(e,qo,e=>t(e))),nl=r(e=>zt(e[0]),(e,t,n,r)=>qc(e,e=>{let i=Xo(e);return vi(i)?As(i.failure):t(i.success)?n(i.success):r?r(i.success):As(e)})),rl=r(e=>zt(e[0]),(e,t,n,r)=>qc(e,e=>{let i=Xo(e);if(vi(i))return As(i.failure);let a=t(i.success);return vi(a)?r?r(a.failure):As(e):n(a.success)})),il=r(e=>zt(e[0]),(e,t,n,r)=>nl(e,Array.isArray(t)?e=>pe(e,`_tag`)&&t.includes(e._tag):me(t),n,r)),al=r(e=>zt(e[0]),(e,t,n)=>{let r;return rl(e,e=>(r??=Object.keys(t),pe(e,`_tag`)&&ee(e._tag)&&r.includes(e._tag)?pi(e):mi(e)),e=>t[e._tag](e),n)}),ol=r(2,(e,t)=>qc(e,e=>As(ts(e,t)))),sl=r(2,(e,t)=>fl(e,{onFailure:e=>As(ts(e,t.onFailure)),onSuccess:e=>Ms(()=>t.onSuccess(e))})),cl=e=>Zc(e,Ls),ll=r(e=>zt(e[0]),(e,t)=>{if(!t?.log)return _l(e,{onFailure:e=>Rs,onSuccess:e=>Rs});let n=vd(t.log===!0?void 0:t.log);return fl(e,{onFailure(e){let r=Xo(e);return vi(r)?As(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>Rs})}),ul=e=>vl(e,{onFailure:y,onSuccess:b}),dl=e=>yl(e,{onFailure:mi,onSuccess:pi}),fl=r(2,(e,t)=>new ml(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),pl=ln({op:`OnSuccessAndFailure`,[Nt]:nc}),ml=function(e,t,n){this[Mt]=e,this[Pt]=t,this[Ft]=n};ml.prototype=pl;var hl=function(e,t){let n=this.payload;return t.succeedWith(sc?n.onSuccess(e):Tt(()=>n.onSuccess(e)))},gl=((e,t)=>{let n=ln({op:e,[Nt]:nc,[Pt]:hl,[Ft]:t}),r=function(e,t){this[Mt]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=Xo(e);if(vi(n))return As(n.failure);let r=this.payload;return t.succeedWith(sc?r.onFailure(n.success):Tt(()=>r.onFailure(n.success)))}),_l=r(2,(e,t)=>fl(e,{onFailure:e=>{let n=Xo(e);return vi(n)?As(n.failure):t.onFailure(n.success)},onSuccess:t.onSuccess})),vl=r(2,(e,t)=>new gl(e,t)),yl=r(2,(e,t)=>{if(yc(e)){if(e._tag===`Success`)return fn(t.onSuccess(e.value));let n=Xo(e.cause);return vi(n)?hn(n.failure):fn(t.onFailure(n.success))}return vl(e,t)}),bl=e=>yc(e)?fn(e):xl(e),xl=un({op:`Exit`,[Nt](e){return e._stack.push(this),this[Mt]},[Pt](e,t,n){return t.succeedWith(n??fn(e))},[Ft](e,t,n){return t.succeedWith(n??hn(e))}}),Sl=`~effect/Scope`,Cl=`~effect/Scope/Closeable`,wl=kr(`effect/Scope`),Tl=(e,t)=>vn(n=>(su(n),El(e,t)??Rs)),El=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&Pl(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return Dl(n.finalizer,t);let r=n.finalizers;return r.size===1?Dl(r.values().next().value,t):kl(e,r,t)},Dl=(e,t)=>{try{return e(t)}catch(e){return _n(e)}},Ol=(e,t)=>Dc(e)?t:qc(t,t=>As(Yo(Qt(e.cause,t)))),kl=qs(function*(e,t,n){let r=[],i=[],a=Array.from(t),o=ys();for(let t=a.length-1;t>=0;t--){let[s,c]=a[t];e.strategy===`sequential`?r.push(yield*bl(Dl(c,n))):s!==o&&i.push(bu(o,Dl(c,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*ws(i)),yield*Ic(r)}),Al=(e,t)=>{let n=Il(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(Nl(e,n,e=>Tl(n,e)),n)},jl=(e,t)=>Ns(()=>e.state._tag===`Closed`?t(e.state.exit):(Nl(e,{},t),Rs)),Ml=(e,t)=>jl(e,a(t)),Nl=(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)}},Pl=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=Ll:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=Ll))},Fl=e=>Il(e,void 0),Il=(e=`sequential`,t)=>({[Cl]:Cl,[Sl]:Sl,strategy:e,parent:t,state:Ll}),Ll={_tag:`Empty`},Rl=wl,zl=Wc(wl),Bl=e=>Ns(()=>{let t=Fl();return Gl(e(t),e=>Ns(()=>El(t,e)??Rs))}),Vl=(e,t,n)=>Hc(r=>lu(i=>vc(Rl,a=>mc(n?.interruptible?i(e):e,e=>jl(a,n=>Uc(t(e,n),r)))))),Hl=function(){let e=ln({op:`OnExit`,[Nt](e){return e._stack.push(this),this.effect},[It](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(iu),e.interruptible=!1)},[Pt](e,t,n){n??=fn(e);let r;try{r=this.onExit(n)}catch(e){r=_n(e)}return r?vc(r,e=>n):n},[Ft](e,t,n){n??=hn(e);let r;try{r=this.onExit(n)}catch(e){r=_n(e)}return r?vc(Ol(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),Ul=(e,t,n)=>new Hl(e,t,n),Wl=(e,t)=>{e._stack.push(new Hl(void 0,t,void 0))},Gl=r(2,Ul),Kl=r(2,(e,t)=>Gl(e,e=>t)),ql=r(3,(e,t,n)=>Gl(e,e=>{let r=t(e);return vi(r)?Rs:n(r.success,e)})),Jl=r(2,(e,t)=>ql(e,kc,t)),Yl=r(3,(e,t,n)=>Gl(e,e=>{if(e._tag!==`Failure`)return Rs;let r=t(e.cause);return vi(r)?Rs:n(r.success,e.cause)})),Xl=r(2,(e,t)=>Yl($o,t)(e)),Zl=(e,t,n)=>lu(r=>vc(e,e=>Ul(Ns(()=>r(t(e))),t=>n(e,t),!0))),Ql=a(1/0),$l=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,Wl(e,()=>{if(!(--t.awaiters>0||t.done))return i===t&&(i=void 0),Es(t.fiber)}),Ts(t.fiber));return[vn(o=>{if(i!==void 0)return o===i.fiber?Ts(i.fiber):a(o,i);if(r!==void 0&&(n===1/0||o.getRef(Yu).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(Yu),c={fiber:new bs(o.context),awaiters:0,done:!1};i=c;let l=a(o,c);return c.fiber.evaluate(Ul(e,e=>{if(c.done=!0,i!==c||(i=void 0,Ac(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e})),c.fiber._exit??l}),Ms(()=>{i=void 0,r=void 0})]},eu=e=>Ms(()=>$l(e,Ql)[0]),tu=vn(e=>As(Go(e.id))),nu=e=>vn(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(iu)),e)),ru=un({op:`SetInterruptible`,[It](e){if(e.interruptible=this[Mt],e._interruptedCause&&e.interruptible)return()=>As(e._interruptedCause)}}),iu=ru(!0),au=ru(!1),ou=e=>{if(e.interruptible=!0,e._stack.push(au),e._interruptedCause)return As(e._interruptedCause)},su=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(iu))},cu=e=>vn(t=>t.interruptible?e:ou(t)??e),lu=e=>vn(t=>t.interruptible?(t.interruptible=!1,t._stack.push(iu),e(cu)):e(i)),uu=(e,t)=>ge(e)?t?.mode===`result`?fu(e,dl,t):fu(e,i,t):t?.discard?t.mode===`result`?fu(Object.values(e),dl,t):fu(Object.values(e),i,t):Ns(()=>Sc(fu(Object.entries(e),([e,n])=>Sc(t?.mode===`result`?dl(n):n,t=>[e,t]),{concurrency:t?.concurrency}),Object.fromEntries)),du=un({op:`While`,[Pt](e,t){return this[Mt].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[Mt].body()):jc},[Nt](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[Mt].body()):jc}}),fu=r(e=>typeof e[1]==`function`,(e,t,n)=>Ns(()=>{let r=mu(n?.concurrency);if(r===1)return pu(e,t,n);let i=Ii(e),a=i.length;if(a===0)return n?.discard?Rs:ks([]);let o=n?.discard?void 0:Array(a),s=vu({f:t,out:o},i,{concurrency:r});return s?tc(s,o):ks(o)})),pu=(e,t,n)=>Ns(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return tc(du({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),mu=e=>e===`unbounded`?1/0:Math.max(1,e??1),hu=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>vc(bl(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??Rs),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!yc(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},gu=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=_n(e);return f=t,c=!0,u&&u.size>0?vc(nu(Os(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(yc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=bu(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=Xt(e);f=hn(f._tag===`Failure`?Yo(Qt(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??Rs)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return Ws(e=>{l=ys(),u=new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):Ns(()=>(f??=jc,vc(u?Os(u):Rs,()=>f?._tag===`Failure`?f:Rs)))})}if(c=!0,f){if(u&&u.size>0){let e=Ss(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(Rs);else return jc}};return h()}},_u=()=>e=>gu(e),vu=gu({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)}}),yu=r(e=>ge(e[0])&&!zt(e[0]),(e,t,n)=>Sc(fu(e,(e,n)=>{let r=t(e,n);return typeof r==`boolean`?ks(r?b(e):y()):Sc(r,t=>t?b(e):y())},n),ea)),bu=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new bs(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=vs(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},xu=e=>()=>vn(t=>t===e?Rs:Es(e)),Su=r(e=>zt(e[0]),(e,t,n)=>vn(r=>{let i=t.state._tag===`Closed`?new bs(r.context):bu(r,e,n?.startImmediately,!0,n?.uninterruptible);return i._exit||(t.state._tag===`Closed`?i.interruptUnsafe(r.id,Ss(r)):(Nl(t,i,xu(i)),i.addObserver(()=>Pl(t,i)))),ks(i)})),Cu=r(e=>zt(e[0]),(e,t)=>vc(Rl,n=>Su(e,n,t))),wu=e=>(t,n)=>{let r=new bs(n?.scheduler?Xr(e,Xa,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},Tu=r(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):(Pl(t,e),Nl(t,e,xu(e)),e.addObserver(()=>Pl(t,e)),e)),Eu=wu(qr()),Du=e=>{let t=wu(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},Ou=(e=>{let t=Du(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw ns(e.cause);return e.value})})(qr()),ku=e=>{let t=wu(e);return e=>{if(yc(e))return e;let n=new to(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??_n(new sd(r))}},Au=ku(qr()),ju=(e=>{let t=ku(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw ns(n.cause);return n.value}})(qr()),Mu=ks(!0),Nu=ks(!1),Pu=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return Mu;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=[],Mu}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](jc)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](jc)}open=vn(e=>this._isOpen?Nu:(this._isOpen=!0,this.scheduleUnsafe(e)));release=vn(e=>this._isOpen?Nu:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=Ws(e=>this._isOpen?e(Rs):(this.waiters.push(e),Ms(()=>{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=Ms(()=>this.closeUnsafe());whenOpen=e=>vc(this.await,()=>e);isOpen(){return this._isOpen}},Fu=e=>new Pu(e??!1),Iu=BigInt(0),Lu={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:Iu,endTime:Iu,exit:jc},attributes:new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},Ru=e=>Object.assign(Object.create(Lu),e),zu=e=>e?ti(e.annotations,wo)?e._tag===`Span`?zu(br(e.parent)):y():b(e):y(),Bu=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&ti(n.annotations,wo),i=n?.parent===void 0?n?.root?y():zu(e.cache.span):b(n.parent),a;if(r)a=Ru({name:t,parent:i,annotations:Xr(n?.annotations??qr(),wo,!0)});else{let r=e.cache.tracer??Oo,o=e.getRef(Yu),s=e.getRef(No),c=e.getRef(Po),l=e.getRef(Fo),u=n?.level??e.getRef(To),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??qr(),links:d,startTime:s?o.currentTimeNanosUnsafe():Iu,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(S(i)&&i.value.sampled===!1?!1:!dd(e.getRef(Eo),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},Vu=(e,t)=>(t=typeof t==`function`?t:l,zc(jo,n=>({name:e,stack:t,parent:n}))),Hu=(e,t,n,r)=>Ms(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():Iu,t)}),Uu=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return vn(t=>{let i=Bu(t,e,n),a=t.getRef(Yu),o=t.getRef(No);return Wl(t,e=>Hu(i,e,a,o)),r(i)})},Wu=Wc(So),Gu=function(){let e=zt(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=i;return t._tag===`Span`&&(n=Bo(n),r=Vu(t.name,n?.captureStackTrace)),e?Wu(r(arguments[0]),t):e=>Wu(r(e),t)},Ku=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=Bo(arguments[2]);if(e){let e=arguments[0];return Uu(t,arguments[2],t=>Gu(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>Uu(t,r?r(...a):i,t=>Gu(e,t,n))},qu=(...e)=>vn(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 Rs}),Ju=vn(e=>{let t=e.currentSpanLocal;return t?ks(t):js(new Cn)}),Yu=li(`effect/Clock`,{defaultValue:()=>new Zu}),Xu=2**31-1,Zu=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=Ms(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return ed()}currentTimeNanos=Ms(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return $u()}monotonicTimeNanos=Ms(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(Va(e))}sleepMillis(e){return e<=0?Ps:Number.isFinite(e)?Ws(t=>{let n=e>Xu?this.sleepMillis(e-Xu):Rs,r=setTimeout(()=>t(n),Math.min(e,Xu));return Ms(()=>clearTimeout(r))}):Gs}},Qu=BigInt(1e6),$u=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())*Qu;return e>t&&(t=e),t}}(),ed=function(){let e=BigInt(1e9),t;return()=>{let n=$u(),r=BigInt(Date.now())*Qu;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}}(),td=e=>vn(t=>e(t.getRef(Yu))),nd=e=>td(t=>t.sleep(wa(e))),rd=td(e=>e.currentTimeMillis),id=`~effect/Cause/IllegalArgumentError`,ad=class extends xn(`IllegalArgumentError`){[id]=id;constructor(e){super({message:e})}},od=`~effect/Cause/AsyncFiberError`,sd=class extends xn(`AsyncFiberError`){[od]=od;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}},cd=`~effect/Cause/UnknownError`,ld=class extends xn(`UnknownError`){[cd]=cd;constructor(e,t){super({message:t,cause:e})}},ud=li(`effect/Console`,{defaultValue:()=>globalThis.console}),dd=lr(sr(ir,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}})),fd=li(`effect/Logger/CurrentLoggers`,{defaultValue:()=>new Set([xd,Sd])}),pd=li(`effect/Logger/LogToStderr`,{defaultValue:s}),md={"~effect/Logger":{_Message:i,_Output:i},pipe(){return e(this,arguments)}},hd=e=>{let t=Object.create(md);return t.log=e,t},gd=e=>e.replace(/[\s="]/g,`_`),_d=(e,t)=>`${gd(e[0])}=${t-e[1]}ms`,vd=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];Ut(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?Xt(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=en),vn(r=>{let i=e??r.cache.logLevel;if(dd(r.cache.minimumLogLevel,i))return Rs;let a=r.getRef(Yu),o=r.getRef(fd);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 Rs})},yd={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};yd.gray,yd.blue,yd.green,yd.yellow,yd.red,yd.bgBrightRed,yd.black;var bd=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`)}`,xd=hd(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(ds(e));let o=t.getTime(),s=n.getRef(zo),c=``;for(let e of s)c+=` ${_d(e,o)}`;let l=n.getRef(Io);Object.keys(l).length>0&&a.push(l);let u=n.getRef(ud);(n.getRef(pd)?u.error:u.log)(`[${bd(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),Sd=hd(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(Yu),a=t.getRef(Io),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`]=ds(e)),o.event(vt(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)}),Cd=Ut,wd=Wt,Td=on,Ed=Xt,Dd=tn,Od=rn,kd=e=>new Yt(e),Ad=e=>new nn(e),jd=Wo,Md=es,Nd=ts,Pd=Qt,Fd=ns,Id=Qo,Ld=$o,Rd=ds,zd=Tn,Bd=kn,Vd=ad,Hd=fn,Ud=hn,Wd=gn,Gd=jc,Kd=Dc,qd=Oc,Jd={"~effect/Deferred":{_A:i,_E:i},pipe(){return e(this,arguments)}},Yd=function(){this.resumes=void 0,this.effect=void 0};Yd.prototype=Jd;var Xd=()=>new Yd,Zd=()=>Ms(()=>Xd()),Qd=e=>Ws(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),Ms(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),$d=r(2,(e,t)=>Ms(()=>rf(e,t))),ef=e=>Ms(()=>tf(e)),tf=e=>e.effect!==void 0,nf=r(2,(e,t)=>$d(e,fn(t))),rf=(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},af=r(2,(e,t)=>lu(n=>vc(bl(n(e)),e=>$d(t,e)))),of=No,sf=wl,cf=Fl,lf=zl,uf=jl,df=Ml,ff=Al,pf=Tl,mf=`~effect/Layer`,hf=`~effect/Layer/MemoMap`,gf=(e,t)=>{let n={observers:0,deferred:Xd(),scope:cf(),finalizer:r=>Ns(()=>--n.observers>0?Rs:(e.map.delete(t),pf(n.scope,r)))};return n},_f=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,Nl(t,{},e.finalizer),!0),vf={[mf]:{_ROut:i,_E:i,_RIn:i},pipe(){return e(this,arguments)}},yf=e=>{let t=Object.create(vf);return t.build=e,t},xee=e=>yf((t,n)=>{let r=ff(n);return Gl(e(t,r),e=>e._tag===`Failure`?pf(r,e):Rs)}),bf=e=>{let t=xee((n,r)=>n.getOrElseMemoize(t,r,e));return t},xf=class{get[hf](){return hf}parent;constructor(e){this.parent=e}map=new Map;get(e,t){let n=this.map.get(e);return n?(_f(n,t),n.deferred.effect??Qd(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return Ns(()=>{let r;return Ul(Ns(()=>{let i=this.get(e,t);if(i)return i;let a=gf(this,e);return _f(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&rf(r,e)})})}},Sf=()=>new xf,See=e=>new xf(e),Cf=class e extends kr()(`effect/Layer/CurrentMemoMap`){static forkOrCreate(t){let n=Qr(t,e);return n?See(n):Sf()}},wf=r(3,(e,t,n)=>Wc(Sc(Ns(()=>e.build(t,n)),Xr(Cf,t)),Cf,t)),Cee=r(2,(e,t)=>vn(n=>wf(e,Cf.forkOrCreate(n.context),t))),Tf=function(){return arguments.length===1?e=>Ef(Yr(arguments[0],e)):Ef(Yr(arguments[0],arguments[1]))},Ef=e=>yf(a(ks(e))),Df=function(){return arguments.length===1?e=>Of(arguments[0],e):Of(arguments[0],arguments[1])},Of=(e,t)=>kf(Sc(t,t=>Yr(e,t))),kf=e=>bf((t,n)=>lf(e,n)),wee=e=>kf(tc(e,qr())),Af=(e,t,n)=>{let r=ff(n,`parallel`);return fu(e,e=>e.build(t,ff(r,`sequential`)),{concurrency:e.length}).pipe(Sc(e=>si(...e)))},Tee=(...e)=>bf((t,n)=>Af(e,t,n)),jf=(e,t,n)=>bf((r,i)=>vc(Array.isArray(t)?Af(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(Uc(t),Sc(e=>n(e,t))))),Mf=r(2,(e,t)=>jf(e,t,i)),Eee=r(2,(e,t)=>jf(e,t,(e,t)=>oi(t,e))),Dee=Yu,Nf=rd,Pf=`~effect/DateTime`,Ff=`~effect/DateTime/TimeZone`,If={[Pf]:Pf,pipe(){return e(this,arguments)},[gt](){return this.toString()},toJSON(){return dp(this).toJSON()}},Oee={...If,_tag:`Utc`,[_e](){return we(this.epochMilliseconds)},[Ie](e){return zf(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${dp(this).toJSON()})`}},kee={...If,_tag:`Zoned`,[_e](){return xe(we(this.epochMilliseconds))(ve(this.zone))},[Ie](e){return zf(e)&&e._tag===`Zoned`&&this.epochMilliseconds===e.epochMilliseconds&&Le(this.zone,e.zone)},toString(){return`DateTime.Zoned(${Fp(this)})`}},Lf={[Ff]:Ff,[gt](){return this.toString()}},Aee={...Lf,_tag:`Named`,[_e](){return Te(`Named:${this.id}`)},[Ie](e){return Vf(e)&&e._tag===`Named`&&this.id===e.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:`TimeZone`,_tag:`Named`,id:this.id}}},jee={...Lf,_tag:`Offset`,[_e](){return Te(`Offset:${this.offset}`)},[Ie](e){return Vf(e)&&e._tag===`Offset`&&this.offset===e.offset},toString(){return`TimeZone.Offset(${mp(this.offset)})`},toJSON(){return{_id:`TimeZone`,_tag:`Offset`,offset:this.offset}}},Rf=(e,t,n)=>{let r=Object.create(kee);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},zf=e=>pe(e,Pf),Bf=e=>zf(e[0]),Vf=e=>pe(e,Ff),Hf=e=>Vf(e)&&e._tag===`Named`,Uf=e=>e._tag===`Utc`,Wf=e=>e._tag===`Zoned`,Gf=e=>{let t=Object.create(Oee);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Kf=e=>{let t=e.getTime();if(Number.isNaN(t))throw new Vd(`Invalid date`);return Gf(t)},qf=e=>{if(zf(e))return e;if(e instanceof Date)return Kf(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Kf(new Date(e.epochMilliseconds));let t=new Date(0);return bp(t,e),Kf(t)}return typeof e==`string`&&!Jf(e)?Kf(new Date(e+`Z`)):Kf(new Date(e))},Jf=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e)||/z$|gmt$/i.test(e),Yf=-864e13+432e5,Xf=864e13-504e5,Zf=(e,t)=>{let n=t?.timeZone;if(n===void 0&&zf(e)&&Wf(e))return e;let r=qf(e);if(r.epochMilliseconds<Yf||r.epochMilliseconds>Xf)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=op(new Date(r.epochMilliseconds).getTimezoneOffset()*-60*1e3);else if(Vf(n))i=n;else if(typeof n==`number`)i=op(n);else{let e=lp(n);if(x(e))throw new Vd(`Invalid time zone: ${n}`);i=e.value}return t?.adjustForTimeZone===!0?Sp(r.epochMilliseconds,i,t?.disambiguation??`compatible`):Rf(r.epochMilliseconds,i,r.partsUtc)},Qf=xr(qf),$f=Sc(Nf,Gf),ep=e=>Gf(e.epochMilliseconds),tp=r(Bf,(e,t,n)=>n?.adjustForTimeZone===!0?Sp(e.epochMilliseconds,t,n?.disambiguation??`compatible`):Rf(e.epochMilliseconds,t,e.partsUtc)),np=new Map,rp={day:`numeric`,month:`numeric`,year:`numeric`,era:`short`,hour:`numeric`,minute:`numeric`,second:`numeric`,timeZoneName:`longOffset`,fractionalSecondDigits:3,hourCycle:`h23`},ip=e=>{let t=e.resolvedOptions().timeZone,n=np.get(t);if(n!==void 0)return n;let r=Object.create(Aee);return r.id=t,r.format=e,np.set(t,r),r},ap=e=>{let t=np.get(e);if(t!==void 0)return t;try{let t=ip(new Intl.DateTimeFormat(`en-US`,{...rp,timeZone:e}));return np.set(e,t),t}catch{throw new Vd(`Invalid time zone: ${e}`)}},op=e=>{let t=Object.create(jee);return t.offset=e,t},sp=xr(ap),cp=/^(?:GMT)?[+-]/,lp=e=>{if(cp.test(e)){let t=wp(e);return t===null?y():b(op(t))}return sp(e)},up=r(Bf,(e,t,n)=>Sr(sp(t),t=>tp(e,t,n))),dp=e=>new Date(e.epochMilliseconds),fp=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},pp=e=>fp(e).getTime()-gp(e),mp=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`)}`},hp=e=>mp(pp(e)),gp=e=>e.epochMilliseconds,_p=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()}),vp=e=>e._tag===`Utc`?yp(e):(e.partsAdjusted===void 0&&(e.partsAdjusted=kp(e,_p)),e.partsAdjusted),yp=e=>(e.partsUtc===void 0&&(e.partsUtc=Ap(e,_p)),e.partsUtc),bp=(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)},xp=864e5,Sp=(e,t,n)=>{if(t._tag===`Offset`)return Rf(e-t.offset,t);let r=Tp(e-xp,e,t),i=Tp(e+xp,e,t);if(r===i)return Rf(e-r,t);let a=r<i,o=r-i;if(a){if(Tp(e-i,e,t)===i)return Rf(e-i,t);let a=Rf(e-r,t);if(e!==fp(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 Rf(e-i,t);case`compatible`:case`later`:return a}return a}if(Tp(e-r,e,t)===r){if(n===`earlier`||n===`compatible`||Tp(e-r+o,e+o,t)===r)return Rf(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 Rf(e-i,t)},Cp=/([+-])(\d{2}):?(\d{2})$/,wp=e=>{let t=Cp.exec(e);if(t===null)return null;let[,n,r,i]=t;return(n===`+`?1:-1)*(Number(r)*60+Number(i))*60*1e3},Tp=(e,t,n)=>{let r=n.format.formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??``;if(r===`GMT`)return 0;let i=wp(r);return i===null?pp(Rf(t,n)):i},Ep=r(Bf,(e,t,n)=>{if(e._tag===`Utc`){let n=dp(e);return t(n),Gf(n.getTime())}let r=fp(e),i=new Date(r.getTime());return t(i),Sp(i.getTime(),e.zone,n?.disambiguation??`compatible`)}),Dp=r(2,(e,t)=>Op(e,e=>{let n=new Date(e);return t(n),n.getTime()})),Op=r(2,(e,t)=>{let n=t(gp(e));return e._tag===`Utc`?Gf(n):Rf(n,e.zone)}),kp=r(2,(e,t)=>t(fp(e))),Ap=r(2,(e,t)=>t(dp(e))),jp=r(2,(e,t)=>{let n=Dp(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:Ep(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)}})}),Mp=r(2,(e,t)=>{let n={};for(let e in t)n[e]=-1*t[e];return jp(e,n)}),Np=e=>dp(e).toISOString(),Pp=e=>{let t=fp(e);return e._tag===`Utc`?t.toISOString():`${t.toISOString().slice(0,-1)}${hp(e)}`},Fp=e=>e.zone._tag===`Offset`?Pp(e):`${Pp(e)}[${e.zone.id}]`;globalThis.Number;var Ip=ir;globalThis.String;var Lp=e=>e.toLowerCase(),Rp=e=>e.length>0,zp=`~effect/Cron`;function Bp(e){return{tz:e.tz,and:e.and,seconds:Ii(e.seconds),minutes:Ii(e.minutes),hours:Ii(e.hours),days:Ii(e.days),months:Ii(e.months),weekdays:Ii(e.weekdays)}}var Vp={[zp]:zp,[Ie](e){return Hp(e)&&om(this,e)},[_e](){return d(ve(this.tz),xe(ve(this.and)),xe(ke(Ii(this.seconds))),xe(ke(Ii(this.minutes))),xe(ke(Ii(this.hours))),xe(ke(Ii(this.days))),xe(ke(Ii(this.months))),xe(ke(Ii(this.weekdays))))},toObject(){return Bp(this)},toString(){return`Cron(${ot(Bp(this))})`},toJSON(){let e=Bp(this);return e._id=`Cron`,e},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},Hp=e=>pe(e,zp),Up=e=>{let t=Object.create(Vp);t.seconds=Gp.seconds(e.seconds??[0]),t.minutes=Gp.minutes(e.minutes),t.hours=Gp.hours(e.hours),t.days=Gp.days(e.days),t.months=Gp.months(e.months),t.weekdays=Gp.weekdays(e.weekdays),t.and=e.and===!0,t.tz=vr(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:qp.next.second(n),minute:qp.next.minute(r),hour:qp.next.hour(i),day:qp.next.day(a),month:qp.next.month(o),weekday:qp.next.weekday(s)},t.prev={second:qp.prev.second(n),minute:qp.prev.minute(r),hour:qp.prev.hour(i),day:qp.prev.day(a),month:qp.prev.month(o),weekday:qp.prev.weekday(s)},t},Wp=(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(Gi(a,Ip))},Gp={seconds:Wp(`seconds`,0,59),minutes:Wp(`minutes`,0,59),hours:Wp(`hours`,0,23),days:Wp(`days`,1,31),months:Wp(`months`,1,12),weekdays:Wp(`weekdays`,0,7,e=>e===7?0:e)},Kp=(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},qp={prev:{second:Kp(60,`prev`),minute:Kp(60,`prev`),hour:Kp(24,`prev`),day:Kp(32,`prev`),month:Kp(13,`prev`),weekday:Kp(7,`prev`)},next:{second:Kp(60,`next`),minute:Kp(60,`next`),hour:Kp(24,`next`),day:Kp(32,`next`),month:Kp(13,`next`),weekday:Kp(7,`next`)}},Jp=`~effect/Cron/CronParseError`,Yp=class extends so(`CronParseError`){[Jp]=Jp},Xp=(e,t)=>{let n=e.trim().split(/\s+/).filter(Rp);if(n.length!==5&&n.length!==6)return mi(new Yp({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 wi({tz:t===void 0||Vf(t)?pi(t):hi(lp(t),()=>new Yp({message:`Invalid time zone in cron expression`,input:t})),seconds:pm(r,sm),minutes:pm(i,cm),hours:pm(a,lm),days:pm(o,um),months:pm(s,dm),weekdays:pm(c,fm)}).pipe(xi(({tz:e,seconds:t,minutes:n,hours:r,days:i,months:a,weekdays:o})=>Up({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})))},Zp=(e,t)=>Ci(Xp(e,t)),Qp=(e,t)=>{let n=Zf(t,{timeZone:br(e.tz)}).pipe(vp);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)},$p=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+1,0)).getUTCDate(),em=(e,t)=>nm(e,t,`next`),tm=(e,t)=>nm(e,t,`prev`),nm=(e,t,n)=>{let r=br(e.tz),i=Zf(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&&Hf(r)&&r.id===`UTC`,p=f?u:e=>{let t=Zf(e,{timeZone:i.zone,adjustForTimeZone:!0,disambiguation:a?`later`:void 0}).pipe(fp),n=e.getTime()-t.getTime();(a?n!==0:n>0)&&e.setTime(a?t.getTime():e.getTime()+n)},m=a||f?s:e=>Zf(e,{timeZone:i.zone,adjustForTimeZone:!0}).epochMilliseconds<=i.epochMilliseconds;return dp(Ep(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=$p(t)-e+l.day}else r=!a&&n>$p(t)?$p(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=$p(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`)}))},rm=jn((e,t)=>Le(e.tz,t.tz)&&e.and===t.and&&am(e.seconds,t.seconds)&&am(e.minutes,t.minutes)&&am(e.hours,t.hours)&&am(e.days,t.days)&&am(e.months,t.months)&&am(e.weekdays,t.weekdays)),im=Fn(Nn()),am=(e,t)=>im(Ii(e),Ii(t)),om=r(2,(e,t)=>rm(e,t)),sm={min:0,max:59},cm={min:0,max:59},lm={min:0,max:23},um={min:1,max:31},dm={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}},fm={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}},pm=(e,t)=>{let n=new Set,r=e.split(`,`),i=mm(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:mm(a);if(c!==void 0){if(!Number.isInteger(c))return mi(new Yp({message:`Expected step value to be a positive integer`,input:e}));if(c<1)return mi(new Yp({message:`Expected step value to be greater than 0`,input:e}));if(c>t.max)return mi(new Yp({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]=hm(o,t.aliases);if(!Number.isInteger(n))return mi(new Yp({message:`Expected a positive integer`,input:e}));if(n<t.min||n>t.max)return mi(new Yp({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 mi(new Yp({message:`Expected a positive integer`,input:e}));if(r<t.min||r>t.max)return mi(new Yp({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(n>r)return mi(new Yp({message:`Invalid value range`,input:e}));for(let e=n;e<=r;e+=c??1)s(e)}}}return pi({values:n,wildcard:a})},mm=e=>{let t=e.indexOf(`/`);if(t!==-1){let n=e.slice(t+1);return[e.slice(0,t),_m.test(n)?Number(n):NaN]}return[e,void 0]},hm=(e,t)=>{let n=e.indexOf(`-`);return n===-1?[gm(e,t),void 0]:[gm(e.slice(0,n),t),gm(e.slice(n+1),t)]};function gm(e,t){return t?.[Lp(e)]??(_m.test(e)?Number(e):NaN)}var _m=/^\d+$/,vm=r(2,(e,t)=>Xc(e,Sm,e=>t(e))),ym=e=>e.reasons.some(bm),bm=e=>e._tag===`Fail`&&zd(e.error),xm=e=>{let t,n=!1;for(let r of e.reasons)bm(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?mi(e):n?mi(Ed(e.reasons.filter(e=>!bm(e)))):pi(t)},Sm=e=>{let t=xm(e);return vi(t)?t:pi(t.success.value)},Cm=e=>{let t=xm(e);return vi(t)?Ud(t.failure):Hd(t.success.value)},wm=r(2,(e,t)=>fl(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=xm(e);return vi(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),Tm=`~effect/Schedule`,Em=li(`effect/Schedule/CurrentMetadata`,{defaultValue:a({input:void 0,output:void 0,duration:Pa,attempt:0,start:0,now:0,elapsed:0,elapsedSincePrevious:0})}),Dm={[Tm]:{_Out:i,_In:i,_Env:i},pipe(){return e(this,arguments)}},Om=e=>pe(e,Tm),km=e=>{let t=Object.create(Dm);return t.step=e,t},Am=()=>{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}}},jm=e=>km(Sc(e,e=>{let t=Am();return(n,r)=>e(t(n,r))})),Mm=e=>qc(e.step,e=>ks(()=>As(e))),Nm=e=>td(t=>Sc(Mm(e),e=>{let n=Am();return r=>Ns(()=>{let i=t.currentTimeMillisUnsafe();return vc(e(i,r),([e,t])=>{let a=n(i,r);return a.output=e,a.duration=t,tc(nd(t),a)})})})),Pm=(e,t=2)=>{let n=Va(wa(e));return jm(ks(e=>{let r=Ra(n*t**(e.attempt-1));return ks([r,r])}))},Fm=e=>km(Sc(Mm(e),e=>(t,n)=>wm(e(t,n),{onSuccess:e=>ks([n,e[1]]),onFailure:As,onDone:()=>Bd(n)}))),Im=e=>{let t=wa(e);return jm(ks(e=>ks([e.attempt-1,t])))},Lm=r(2,(e,t)=>km(Sc(Mm(e),e=>{let n=Am();return(r,i)=>vc(e(r,i),e=>{let[a,o]=e,s=t({...n(r,i),output:a,duration:o});return vc(zt(s)?s:ks(s),t=>t?ks(e):Bd(a))})}))),Rm=Im(Pa),zm=(e,t,n)=>Bl(r=>vc(n?.local?wf(t,Sf(),r):Cee(t,r),t=>Uc(e,t))),Bm=r(e=>zt(e[0]),(e,t,n)=>Gr(t)?Uc(e,t):zm(e,Array.isArray(t)?Tee(...t):t,n)),Vm=r(3,(e,t,n)=>vc(Nm(t),t=>{let r=Em.defaultValue(),i,a=Xc(Ns(()=>Wc(e,Em,r)),Xo,e=>(i=e,vc(t(e),e=>(r=e,a))));return vm(a,e=>Tt(()=>n(i,e)))})),Hm=r(2,(e,t)=>Vm(e,typeof t==`function`?t(i):Om(t)?t:Wm(t),js)),Um=Fm(Rm),Wm=e=>{let t=e.schedule?Fm(e.schedule):Um;return e.while&&(t=Lm(t,({input:t})=>{let n=e.while(t);return zt(n)?n:ks(n)})),e.until&&(t=Lm(t,({input:t})=>{let n=e.until(t);return zt(n)?Sc(n,e=>!e):ks(!n)})),e.times!==void 0&&(t=Lm(t,({attempt:t})=>ks(t<=e.times))),t},Gm=`~effect/MutableHashMap`,Km={[Gm]:Gm,[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)}},qm=()=>{let e=Object.create(Km);return e.backing=new Map,e.buckets=new Map,e},Jm=r(2,(e,t)=>{if(e.backing.has(t))return b(e.backing.get(t));if(Ym(t))return y();let n=ve(t),r=e.buckets.get(n);return r===void 0?y():Xm(e,r,t)}),Ym=e=>typeof e!=`object`&&typeof e!=`function`,Xm=(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()},Zm=r(2,(e,t)=>S(Jm(e,t))),Qm=r(3,(e,t,n)=>{if(e.backing.has(t)||Ym(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=$m(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),$m=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(Le(t,e[n]))return e[n]},eh=r(2,(e,t)=>{if(Ym(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}),th=zt,nh=uu,rh=fu,ih=Bs,ah=Vs,w=ks,oh=Fs,sh=Ns,ch=Ms,lh=Rs,uh=Ws,dh=Gs,T=Ks,fh=js,ph=As,mh=Is,hh=Ls,gh=zs,_h=vn,vh=bee,E=vc,yh=xc,bh=pc,xh=mc,Sh=dl,Ch=ul,wh=bl,Th=Sc,Eh=tc,Dh=fc,Oh=hc,kh=Zc,Ah=il,jh=al,Mh=qc,Nh=Qc,Ph=ol,Fh=cl,Ih=tl,Lh=$c,Rh=Hm,zh=ll,Bh=nd,Vh=gc,Hh=_c,Uh=yu,Wh=vl,Gh=fl,Kh=Bc,qh=Hc,Jh=Bm,Yh=Uc,Xh=Lc,Zh=Rc,Qh=Wc,$h=Vl,eg=Zl,tg=Kl,ng=Jl,rg=Ul,ig=Gl,ag=eu,og=tu,sg=Xl,cg=nu,lg=lu,ug=Kc,D=qu,dg=Ju,fg=Uu,pg=Ku,mg=Gu,hg=Su,gg=Cu,_g=Eu,vg=wu,yg=Ou,bg=ju,xg=Au,Sg=qs,O=Xs,Cg=vd(`Warn`),wg=vd(`Error`),k=vd(`Info`),A=vd(`Debug`),Tg=Cc,Eg=wc,Dg=Tc,Og=bc,kg=Qs,Ag=`~effect/BigDecimal`,jg={[Ag]:Ag,[_e](){let e=zg(this);return xe(Te(String(e.value)),we(e.scale))},[Ie](e){return Mg(e)&&Wg(this,e)===0},toString(){return`BigDecimal(${Kg(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},Mg=e=>pe(e,Ag),Ng=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(jg);return n.value=e,n.scale=t,n},Pg=(e,t)=>{let n=Ng(e,t);return n.normalized=n,n},Fg=BigInt(0),Ig=BigInt(1),Lg=BigInt(10),Rg=Pg(Fg,0),zg=e=>{if(e.normalized===void 0){if(e.value===Fg)e.normalized=Rg;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=Pg(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Bg=100,Vg=[Ig],Hg=(e,t)=>e===t?0:e<t?-1:1,Ug=(e,t)=>{let n=`${e.value<Fg?-e.value:e.value}`,r=`${t.value<Fg?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==Fg)return i<Fg?-1:1;let a=Math.max(n.length,r.length);return rr(n.padEnd(a,`0`),r.padEnd(a,`0`))},Wg=(e,t)=>{if(e.scale===t.scale)return Hg(e.value,t.value);let n=Gg(e),r=Gg(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>Bg)return n===-1?Ug(t,e):Ug(e,t);let o=Vg[a]??=Lg**BigInt(a);return i>0?Hg(e.value,t.value*o):Hg(e.value*o,t.value)},Gg=e=>e.value===Fg?0:e.value<Fg?-1:1,Kg=e=>{let t=zg(e);if(Math.abs(t.scale)>=16)return qg(t);let n=t.value<Fg,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},qg=e=>{if(Jg(e))return`0e+0`;let t=zg(e),n=`${t.value}`,r=t.value<Fg?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Jg=e=>e.value===Fg,Yg=globalThis.BigInt,Xg=e=>e>Yg(2**53-1)||e<Yg(-(2**53-1))?y():b(Number(e)),Zg=BigInt(1),Qg=BigInt(1e3),$g=BigInt(1024),e_=[{symbol:`B`,factor:Zg,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:Qg,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:Qg**BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:Qg**BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:Qg**BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:Qg**BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:Qg**BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:Qg**BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:Qg**BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:Qg**BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:Qg**BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],t_=[e_[0],{symbol:`KiB`,factor:$g,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:$g**BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:$g**BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:$g**BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:$g**BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:$g**BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:$g**BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:$g**BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}];[...e_,...t_.slice(1)];var n_=Xg,r_=e=>aee(n_(e),()=>Error(`ByteSize exceeds Number.MAX_SAFE_INTEGER: ${e}`)),i_=zf,a_=Uf,o_=Kf,s_=qf,c_=Qf,l_=$f,u_=ep,d_=sp,f_=up,p_=dp,m_=fp,h_=gp,g_=jp,__=Mp,v_=Np,Mee=Fp,y_=e=>x_(typeof e==`string`?S_.encode(e):e),b_=e=>{let t=C_(e),n=t.length;if(n%4!=0)return mi(new lo({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 mi(new lo({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=E_(t.charCodeAt(e))<<18|E_(t.charCodeAt(e+1))<<12|E_(t.charCodeAt(e+2))<<6|E_(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return pi(r)}catch(e){return mi(new lo({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},x_=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=w_[e[r-2]>>2],n+=w_[(e[r-2]&3)<<4|e[r-1]>>4],n+=w_[(e[r-1]&15)<<2|e[r]>>6],n+=w_[e[r]&63];return r===t+1&&(n+=w_[e[r-2]>>2],n+=w_[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=w_[e[r-2]>>2],n+=w_[(e[r-2]&3)<<4|e[r-1]>>4],n+=w_[(e[r-1]&15)<<2],n+=`=`),n},S_=new TextEncoder,C_=e=>e.replace(/[\n\r]/g,``),w_=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,T_=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)T_[w_.charCodeAt(e)]=e;T_[61]=0;var E_=e=>{if(e>=T_.length||T_[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return T_[e]},D_=`~effect/http/Cookies`,O_=`~effect/http/Cookies/Cookie`,k_={[D_]:D_,...yt,toJSON(){return{_id:`effect/Cookies`,cookies:ji(this.cookies,e=>e.toJSON())}},pipe(){return e(this,arguments)}},A_=e=>{let t=Object.create(k_);return t.cookies=e,t},j_=e=>{let t={};for(let n of e)Et(t,n.name,n);return A_(t)},M_=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=N_(e.trim());t&&n.push(t)}return j_(n)};function N_(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(!P_.test(r))return;let i=t[0].slice(n+1),a=I_(i);if(t.length===1)return Object.assign(Object.create(F_),{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=za(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(F_),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}var P_=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,F_={[O_]:O_,...yt,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}},I_=e=>{try{return decodeURIComponent(e)}catch{return e}},L_=new WeakMap,R_=e=>{if(L_.has(e))return L_.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},z_=`~effect/Redacted`,B_=e=>pe(e,z_),V_=(e,t)=>{let n=Object.create(H_);return t?.label&&(n.label=t.label),L_.set(n,e),n},H_={[z_]:{_A:e=>e},label:void 0,...Rt,toJSON(){return this.toString()},toString(){return`<redacted${ee(this.label)?`:`+this.label:``}>`},[_e](){return ve(L_.get(this))},[Ie](e){return B_(e)&&Le(L_.get(this),L_.get(e))}},U_=R_,W_=e=>jn((t,n)=>e(U_(t),U_(n))),G_=Symbol.for(`~effect/http/Headers`),K_=Object.defineProperties(Object.create(null),{[G_]:{value:G_},[$e]:{value(e){return nv(this,ti(e,iv))}},toJSON:{value(){return tt(this)}},[Ie]:{value(e){return J_(this,e)}},[_e]:{value(){return De(this)}},toString:{value:yt.toString},[gt]:{value:yt[gt]}}),q_=e=>Object.assign(Object.create(K_),e),J_=Pi(Nn()),Y_=Object.create(K_),X_=e=>{if(e===void 0)return Y_;if(Symbol.iterator in e){let t=Object.create(K_);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(K_);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},Z_=e=>Object.setPrototypeOf(e,K_),Q_=r(3,(e,t,n)=>{let r=q_(e);return r[t.toLowerCase()]=n,r}),$_=r(2,(e,t)=>q_({...e,...X_(t)})),ev=r(2,(e,t)=>{let n=q_(e);return Object.assign(n,t),n}),tv=r(2,(e,t)=>{let n=q_(e);return delete n[t.toLowerCase()],n}),nv=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}),rv=(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},iv=li(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),av=e=>typeof e==`string`?e:U_(e),ov=`~effect/http/UrlParams`,sv=e=>pe(e,ov),cv={...Rt,[ov]:ov,[Symbol.iterator](){return this.params[Symbol.iterator]()},[$e](e){return{_id:`UrlParams`,params:Object.fromEntries(xv(this,ti(e,jv)))}},toJSON(){return tt(this)},[Ie](e){return pv(this,e)},[_e](){return ke(this.params.flat())}},lv=e=>{let t=Object.create(cv);return t.params=e,t},uv=e=>{if(sv(e))return e;let t=dv(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 lv(n)},dv=e=>{let t=typeof e[Symbol.iterator]==`function`?Ii(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,fv(r[t])]);else if(typeof r==`object`&&r&&!B_(r)){let t=dv(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,fv(r)]);return n},fv=e=>B_(e)?e:String(e),pv=jn((e,t)=>mv(e.params,t.params)),mv=ta(Ei([Nn(),Qe()])),hv=lv([]),gv=r(2,(e,t)=>lv(t(e.params))),_v=r(2,(e,t)=>{let n=uv(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 lv(n)}),vv=r(2,(e,t)=>gv(e,uee(uv(t).params))),yv=e=>new URLSearchParams(uv(e).params.map(([e,t])=>[e,av(t)])).toString(),bv=e=>{let t={};for(let[n,r]of e.params){let e=av(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},xv=r(2,(e,t)=>{let n=Array.isArray(t)?t:[t];return e.params.map(([e,t])=>[e,typeof t==`string`&&Sv(e,n)?V_(t):t])}),Sv=rv,Cv=(e,t=Av())=>{e.includes(`@`)&&(e=Dv(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)+Ov(e.slice(n+1,i),t)+e.slice(i)},wv=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i,Tv=/[/\\?#]/,Ev=/[/?#]/,Dv=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=wv.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?Tv:Ev),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])},Ov=(e,t)=>e.split(`&`).map(e=>{let n=e.indexOf(`=`);return n!==-1&&Sv(kv(e.slice(0,n)),t)?e.slice(0,n+1)+`REDACTED`:e}).join(`&`),kv=e=>{if(!e.includes(`%`)&&!e.includes(`+`))return e;try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return e}},Av=()=>ti(globalThis[`~effect/Fiber/currentFiber`]?.context??qr(),jv),jv=li(`effect/http/UrlParams/CurrentRedactedNames`,{defaultValue:()=>[`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]});function Mv(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Nv(e){return t=>Mv(t)?.[e]}var Pv=`~structural`,Fv=`~identifier`,Iv=`~sentinels`,Lv=`~constructor`,Rv=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],zv=Nv(`identifier`),Bv=Nv(Fv),Vv=f(e=>{let t=Mv(e)?.identifier;return typeof t==`string`?t:e.getExpected(Vv)}),Hv=new Set([Iv,Pv,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),Uv=Symbol(),Wv=Hd,Gv=Wv(Uv),Kv=Wv(Uv),qv=e=>e===Uv?y():b(e),Jv=e=>e._tag===`None`?Gv:Wv(e.value),Yv=`~effect/SchemaIssue/Issue`;function Xv(e){return pe(e,Yv)&&e[Yv]===Yv}function Zv(e){return Object.hasOwn(e,`input`)}var Qv=class{[Yv]=Yv;constructor(e,t){t?.reportInput===!0&&e!==Uv&&(this.input=e)}},$v=class extends Qv{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},ey=class extends Qv{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},ty=class extends Qv{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},ny=class extends Qv{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},ry=class extends Qv{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},iy=class extends Qv{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},ay=class extends Qv{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},oy=class extends Qv{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function sy(e,t,n,r,i){return new iy(e,[new ty([t],n)],r,i)}var cy=class extends Qv{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},ly=class extends Qv{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},uy=class extends Qv{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function dy(e,t,n){if(Xv(e))return e;if(typeof e==`string`)return new oy({message:e},t,n);let r=typeof e.issue==`string`?new oy({message:e.issue},t,n):e.issue;return new ty(e.path,r)}function fy(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new oy(void 0,t,n):dy(e,t,n)}function py(e,t,n,r){return Array.isArray(t)?Bi(t)?t.length===1?dy(t[0],n,r):new iy(e,$i(t,e=>dy(e,n,r)),n,r):void 0:fy(t,n,r)}var my=e=>{let t=Ey(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return yy(Vv(e.ast),e);case`InvalidValue`:{let t=vy(e);if(t!==void 0)return yy(t,e);let n=_y(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=_y(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=_y(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},hy=e=>Ey(e)??Ey(e.issue);function gy(e){return t=>({issues:xy(t,[],e?.leafHook??my,e?.checkHook??hy)})}function _y(e){return Zv(e)?ot(e.input):void 0}function vy(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function yy(e,t){let n=_y(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function by(e,t){let n=t(e);if(n!==void 0||e.issue._tag!==`InvalidValue`)return n;let r=vy(e.issue);return r===void 0?yy(Sy(e.filter),e):yy(r,e.issue)}function xy(e,t,n,r,i){switch(e._tag){case`Filter`:return xy(e.issue,t,n,r,i??by(e,r));case`Encoding`:return xy(e.issue,t,n,r,i);case`Pointer`:return xy(e.issue,[...t,...e.path],n,r,i);case`Composite`:case`AnyOf`:return e._tag===`Composite`||e.issues.length>0?e.issues.flatMap(e=>xy(e,t,n,r,i)):[{path:t,message:i??Ey(e)??yy(Vv(e.ast),e)}];default:return[{path:t,message:i??n(e)}]}}function Sy(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=>Sy(e)).join(` & `)}}function Cy(){return e=>Ty(e,``)}var wy=Cy();function Ty(e,t,n){let r;switch(e._tag){case`Filter`:return Ty(e.issue,t,n??by(e,hy));case`Encoding`:return Ty(e.issue,t,n);case`Pointer`:return Ty(e.issue,t+lt(e.path),n);case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>Ty(e,t,n)).join(`
14
+ `);r=n??Ey(e)??yy(Vv(e.ast),e);break;default:r=n??my(e)}return t?`${r}\n at ${t}`:r}function Ey(e){if(e._tag===`Pointer`||e._tag===`Composite`)return;if(e._tag===`Encoding`)return Ey(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 Dy(e){let t;for(let n of e.reasons){if(!Td(n)||!Xv(n.error))return;t??=n.error}return t}function Oy(e,t){let n=Dy(e);if(n===void 0)throw Error(t,{cause:e});return n}var ky=e=>Object.assign(Object.create(t),e);function Ay(e){return Ry((t,n)=>fh(e(t,n)))}function jy(e){return Ay((t,n)=>{let r={message:e(t)};return S(t)?new cy(r,t.value,n):new cy(r)})}var My=jy(()=>`Encoding is not supported`),Ny=ky({_tag:`Passthrough`});function Py(){return Ny}function Fy(e){return ky({_tag:`Transform`,transform:e})}function Iy(e){return ky({_tag:`TransformEffect`,transform:e})}function Ly(e){return ky({_tag:`TransformOptional`,transform:e})}function Ry(e){return ky({_tag:`TransformOptionalEffect`,transform:e})}function zy(){return Ly(()=>y())}function By(e){return Ry(t=>{let n=Tr(t,se);return S(n)?w(n):Tg(e,b)})}function Vy(){return Fy(globalThis.String)}function Hy(){return Fy(globalThis.Number)}function Uy(){return Iy((e,t)=>{try{return w(globalThis.BigInt(e))}catch{return fh(new oy({expected:`a value that can be converted to a bigint`},e,t))}})}function Wy(e){return Iy((t,n)=>gh({try:()=>JSON.parse(t,e?.reviver),catch:()=>new oy({expected:`a valid JSON string`},t,n)}))}function Gy(e){return Iy((t,n)=>gh({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 oy({expected:`a JSON-serializable value`},t,n)}))}function Ky(){return Fy(y_)}function qy(){return Iy((e,t)=>Eg(vh(b_(e)),()=>new oy({expected:`a valid Base64 string`},e,t)))}var Jy=class extends n{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Jy(this.encode,this.decode)}},Yy=`~effect/SchemaTransformation/Transformation`,Xy=class extends n{[Yy]=Yy;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Xy(this.encode,this.decode)}};function Zy(e){return pe(e,Yy)&&e[Yy]===Yy}var Qy=e=>Zy(e)?e:new Xy(e.decode,e.encode);function $y(e){return new Xy(Iy(e.decode),Iy(e.encode))}function eb(e){return new Xy(Fy(e.decode),Fy(e.encode))}function tb(e){return new Xy(Ly(e.decode),Ly(e.encode))}var nb=new Xy(Py(),Py());function rb(){return nb}var ib=new Xy(Hy(),Vy()),ab=new Xy(Uy(),Vy()),ob=e=>de(e)&&typeof e.message==`string`,sb=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:db(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},cb=e=>{try{let t=pt(e);return t===void 0?ot(e):JSON.parse(t)}catch{return ot(e)}},lb=(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},ub=e=>{let t=new WeakSet,n=r=>{if(he(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=lb(r,e,n);return t.delete(r),i}return cb(r)};return n},db=e=>ob(e)?sb(e):e,fb=e=>eb({decode:db,encode:ub(e)});function pb(){return eb({decode:yr,encode:C})}function mb(){return tb({decode:b,encode:oee})}var hb=$y({decode:(e,t)=>URL.canParse(e)?w(new URL(e)):fh(new oy({expected:`a valid URL string`},e,t)),encode:e=>w(e.href)}),gb=new Xy(qy(),Ky());function _b(e){return new Xy(Wy(e??{}),Gy(e))}function vb(e){return t=>t._tag===e}var yb=vb(`Declaration`),bb=vb(`Null`),xb=vb(`Void`),Sb=vb(`Never`),Cb=vb(`Literal`),wb=vb(`UniqueSymbol`),Tb=vb(`Arrays`),Eb=vb(`Objects`),Db=vb(`Union`),Ob=vb(`Suspend`),kb=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Ab={},jb=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}},Mb=`~effect/Schema`,Nb=class{[Mb]=Mb;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}>`}},Pb=class extends Nb{_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===Uv)return Gv;e??=this.run(this.typeParameters);try{return e(t,this,n)}catch(e){return hh(e)}}}_rebuild(e,t,n,r,i){let a=$x(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Pb(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>`}},Fb=new class extends Nb{_tag=`Null`;getParser(){return vS(this,null)}getExpected(){return`null`}},Ib=class extends Nb{_tag=`Undefined`;getParser(){return vS(this,void 0)}toCodecJson(){return Vx(this,[Lb])}getExpected(){return`undefined`}},Lb=new kb(Fb,new Xy(Fy(()=>void 0),Fy(()=>null))),Rb=new Ib,zb=new class extends Nb{_tag=`Void`;getParser(){let e=Wv(void 0);return t=>t===Uv?Gv:e}toCodecJson(){return Vx(this,[Lb])}getExpected(){return`void`}},Bb=new class extends Nb{_tag=`Never`;getParser(){return yS(this,le)}getExpected(){return`never`}},Vb=new class extends Nb{_tag=`Unknown`;getParser(){return yS(this,ue)}getExpected(){return`unknown`}},Hb=class extends Nb{_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 vS(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Ub(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Ub(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Ub(e){let t=globalThis.String(e.literal);return Vx(e,[new kb(new Hb(t),new Xy(Fy(()=>e.literal),Fy(()=>t)))])}var Wb=new class extends Nb{_tag=`String`;getParser(){return yS(this,ee)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&MS(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Gb=class extends Nb{_tag=`Number`;getParser(){return yS(this,te)}matchKey(e,t){return this._match(wS,e,t)}matchPart(e,t){return this._match(CS,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:MS(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Kb(this.checks,`effect/schema/isFinite`)||Kb(this.checks,`effect/schema/isInt`))?this:Vx(this,[Ix])}toCodecStringTree(){return this.toCodecJson()===this?Vx(this,[DS]):Vx(this,[OS])}getExpected(){return`number`}};function Kb(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Kb(e.checks,t))}var qb=new Gb,Jb=new class extends Nb{_tag=`Boolean`;getParser(){return yS(this,ne)}getExpected(){return`boolean`}},Yb=new class extends Nb{_tag=`BigInt`;getParser(){return yS(this,re)}matchPart(e,t){if(!kS.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:MS(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return Vx(this,[jS])}getExpected(){return`bigint`}},Xb=class extends Nb{_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(cS(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(cS(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 ry(n,t[o],i),a=new ty([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return fh(new iy(n,[a],t,i))}return e.issues?fh(new iy(n,e.issues,t,i)):Wv(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:mu(t.concurrency),f=d===1?$b(i,e,0,u):ex(i,e,{concurrency:d,end:u});if(!f)return c(i);if(yc(f))return Og(f,()=>c(i));let p=!0;return sh(()=>p?(p=!1,E(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===Uv)return Gv;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)):fh(new ay(n,e,a))}catch(e){return hh(e)}}}_rebuild(e,t,n){let r=$x(this.elements,e),i=$x(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Xb(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 Zb(e,t,n,r){if(n._tag===`Failure`)return tx(e,e.ast,r,n);let i=n===Kv?t:n[Mt];if(i!==Uv)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(cS(t.ast))return;let n=new ty([r],new ny(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return Wd(new iy(e.ast,[n],e.input,e.options))}}var Qb={onItem(e,t,n){let r=n<e.len?t:Uv;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Zb},$b=hu()(Qb),ex=_u()(Qb),tx=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Dy(r.cause);if(i===void 0)return Ud(Nd(r.cause,r=>new iy(t,[new ty([n],r)],e.input,e.options)));let a=new ty([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Wd(new iy(t,[a],e.input,e.options))},nx=`[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?`;function rx(e,t,n=Ab){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(bS(mS(t)))}var ix=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 ox(e){let t=Ux(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(ox);default:return!1}}function Nee(e){return ax(e)&&ox(e)}var sx=class{parameter;type;constructor(e,t){if(!Nee(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,cS(t)&&!_S(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},cx=class extends Nb{_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(bS(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 tx(t,n,i,s)??Gd;let c=s===Kv?o:s[Mt];if(a!==Uv&&c!==Uv){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Gd;Et(t.out,a,c)}return Gd},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!yc(t))return E(wh(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return tx(e,n,r,a)??Gd;let o=a===Kv?r:a[Mt],s=e.input[r],l=i.parserValue(s,e.options);return yc(l)?t(e,r,o,s,l):E(wh(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return yc(a)?t(e,n,n,i,a):E(wh(a),r=>t(e,n,n,i,r))},u=i?_u()({onItem:(e,[t,n])=>n.is.parameter===Wb?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return kg(function*(t,d){if(t===Uv)return Uv;if(typeof t!=`object`||!t||Array.isArray(t))return yield*fh(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:mu(d.concurrency),v=i&&g?n.indexSignatures.map(e=>rx(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 ry(n,f[a],d),r=new ty([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*fh(new iy(n,[r],t,d))}}}if(r){let e=_===1?dx(m,a):Pee(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===Wb?l:c,r=v?.[e]??(t.is.parameter===Wb?Object.keys(f):rx(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!yc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=Zi();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===Wb?Object.keys(f):rx(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*fh(new iy(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return E(wh(n),n=>{let i={...e,out:{...e.out}},o=lx(i,r,n);if(o)return o;let s=()=>Wv(i.out),c=dx(i,a.slice(t+1));return c?Og(c,s):s()})};return(e,t)=>{if(e===Uv)return Gv;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&mu(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return fh(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=Cx(i,s),l=c?i[s]:Uv,d=n.parser(l,t);if(!yc(d))return u(o,e,d);if(d===Kv){c&&Et(a,s,l);continue}let f=lx(o,n,d);if(f)return f}}catch(e){return hh(e)}return Wv(a)}}_rebuild(e,t,n,r){let i=$x(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new ix(t.name,n)}),a=$x(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new sx(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new cx(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 lx(e,t,n){if(n._tag===`Failure`)return tx(e,e.ast,t.name,n);if(n===Kv)return;let r=n[Mt];if(r!==Uv)Et(e.out,t.name,r);else if(delete e.out[t.name],!cS(t.type)){let n=new ty([t.name],new ny(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return Wd(new iy(e.ast,[n],e.input,e.options))}}var ux={onItem(e,t){if(!Cx(e.input,t.name))return t.parser(Uv,e.options);let n=e.input[t.name];return Et(e.out,t.name,n),t.parser(n,e.options)},step:lx},dx=hu()(ux),Pee=_u()(ux);function fx(e,t){return e?t?[...e,...t]:e:t}function px(e,t,n){return new cx(Reflect.ownKeys(e).map(t=>new ix(t,e[t].ast)),[],n,t)}function mx(e){return e.ast}function hx(e,t=void 0){return new Xb(!1,e.map(e=>e.ast),[],void 0,t)}function gx(e,t,n){return new wx(e.map(mx),t,void 0,n)}function Fee(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=fx(i,e.checks)}return new cx(n,r,void 0,i)}var _x=p(e=>{for(;;){if(Ob(e))return Vb;let t=e.encoding;if(!t)return e.recur?.(_x,i)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==i))return Vb;e=t[t.length-1].to}});function vx(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(vx)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function yx(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[Iv];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!cS(t)){if(Cb(t))return[{key:e.name,literal:t.literal}];if(wb(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!cS(e)){if(Cb(e))return[{key:t,literal:e.literal}];if(wb(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>yx(_x(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return yx(e.thunk())}}var bx=new WeakMap,xx=Object.freeze([]),Sx=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Cx=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function Iee(e){let t=bx.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=_x(c);if(Sb(l))continue;if(Cb(l)||wb(l)){a??=new Map;let e=Cb(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=yx(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=vx(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??xx);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??xx;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=Cx(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??xx;if(t)return o}return xx}}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=Sx(t);if(!fe(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Cx(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=Cx(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=Cx(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(Sx(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return bx.set(e,t),t}var wx=class extends Nb{_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===Uv)return Gv;let i=(o??=Iee(n.types))(e,r);if(i.length===0)return fh(new ly(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:yc(r)?Tx(n,r.cause,e,t):Lee(n,r,e,t)}return Ex(n,a,i,e,t)}}_rebuild(e,t,n){let r=$x(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new wx(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=mS(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Cb);if(t.length>0)return`${kx(n.isMutable)}[ ${t.map(t=>e(t)+Ax(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Cb(e.type));if(t.length>0)return`{ ${t.map(t=>`${kx(t.type.context?.isMutable)}${ct(t.name)}${Ax(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Tx(e,t,n,r){let i=Dy(t);return i?Wd(new ly(e,[i],n,r)):Ud(t)}function Lee(e,t,n,r){return Mh(t,t=>Tx(e,t,n,r))}function Ex(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=Ree(a,n);if(!o)return a.out?a.out:fh(new ly(e,a.issues??[],r,i));if(yc(o))return Dx(o,a);let s=!0;return sh(()=>s?(s=!1,Dx(o,a)):Ex(e,t,n,r,i))}function Dx(e,t){return Og(e,e=>t.out===Kv?w(t.input):t.out?t.out:fh(new ly(t.ast,t.issues??[],t.input,t.options)))}var Ree=hu()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=Dy(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]),Wd(new uy(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Gd}}}),Ox=new wx([new Hb(`Infinity`),new Hb(`-Infinity`),new Hb(`NaN`)]);function kx(e){return e?``:`readonly `}function Ax(e){return e?`?`:``}var jx=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 jx(this.run,{...this.annotations,...e},this.aborted)}abort(){return new jx(this.run,this.annotations,!0)}and(e,t){return new Mx([this,e],t)}},Mx=class extends n{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Mx(this.checks,{...this.annotations,...e})}and(e,t){return new Mx([this,e],t)}};function Nx(e,t,n=!1){return new jx((t,n,r)=>py(n,e(t,n,r),t,r),t,n)}function Px(e){return Nx(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 Fx=Kx(qb,[Px()]),Ix=new kb(new wx([Fx,Ox]),new Xy(Hy(),Fy(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Lx(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Nx(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 Rx=new WeakMap;function zx(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Rx.set(n,Bx(e)),n}function Bx(e){let t=Rx.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 Rx.set(e,n),n}function Vx(e,t){return e.encoding===t?e:zx(e,{encoding:t})}function Hx(e,t){if(e.context===t)return e;let n=Bx(e);return n.context===t&&n.encoding===e.encoding?n:zx(e,{context:t})}function Ux(e){return e.encoding?Ux(e.encoding[e.encoding.length-1].to):e}function Wx(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Gx(e,Ri(e.checks.slice(0,-1),n.annotate(t)))}return zx(e,{annotations:{...e.annotations,...t}})}function Gx(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:zx(e,{checks:t})}function Kx(e,t){return Gx(e,fx(e.checks,t))}function qx(e,t){let n=t(e.to);return n===e.to?e:new kb(n,e.transformation)}function Jx(e,t){let n=e,r=n[n.length-1],i=qx(r,t);return i===r?e:Ri(e.slice(0,e.length-1),i)}function Yx(e){return t=>t.encoding?Vx(t,Jx(t.encoding,e)):t}function Xx(e,t){return Yx(e=>Hx(e,t))(e)}function Zx(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:Vx(r,Jx(r.encoding,n))}return e(r)}return p(n)}function Qx(e,t,n){let r=new kb(e,t);return Vx(n,n.encoding?[...n.encoding,r]:[r])}function $x(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 eS(e,t){return Hx(e,e.context?new jb(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new jb(!1,!1,void 0,t))}var tS=p(e=>nS(Hx(e,e.context?e.context.isOptional===!1?new jb(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new jb(!0,!1)))),nS=Yx(tS),rS=f(e=>tS(new wx([e,Rb])));function iS(e,t){return Hx(e,e.context?new jb(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new jb(!1,!1,t))}function aS(e,t,n){return Qx(e,n,t)}function oS(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 sS(e,t){let{literals:n,parameters:r}=oS(e);return new cx(n.map(e=>new ix(e,t)),r.map(e=>new sx(e,t)))}function cS(e){return e.context?.isOptional??!1}function lS(e){return e.context?.isMutable??!1}function uS(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(uS)}function dS(e){function t(e){return uS(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return zi(n)?n:void 0}function fS(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Ob(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var pS=p(e=>{let t=Bx(e);if(t!==e){let n=pS(t);return n===t&&e.encoding===void 0?e:Hx(n,e.context)}let n=`recur`in e?e.recur(pS):e;if(`encodingChecks`in n&&n.encodingChecks){let t=fS(e)?n.encodingChecks:Tb(n)||Eb(n)||yb(n)&&n.typeParameters.length>0?dS(n.encodingChecks):void 0;return zx(n,{encodingChecks:void 0,checks:fx(n.checks,t)})}return n}),mS=p(e=>pS(gS(e)));function hS(e,t){let n=t,r=n.length,i=n[r-1],a=[new kb(gS(Vx(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new kb(gS(n[e-1].to),n[e].transformation.flip()));let o=gS(i.to);return o.encoding?Vx(o,[...o.encoding,...a]):Vx(o,a)}var gS=f(e=>{if(e.encoding)return hS(e,e.encoding);let t=Bx(e);if(t!==e){let n=gS(t);return n===t?e:Hx(n,e.context)}return`flip`in e?e.flip(gS):`recur`in e?e.recur(gS):e});function _S(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(_S);default:return!1}}function vS(e,t){let n=t===0?Kv:Wv(t);return(r,i)=>r===Uv?Gv:r===t?n:fh(new ay(e,r,i))}function yS(e,t){return(n,r)=>n===Uv?Gv:t(n)?Kv:fh(new ay(e,n,r))}var bS=Zx(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(bS)}}),xS=Zx(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(xS)}}),SS=`[\\s\\S]*?`,CS=new globalThis.RegExp(`^${nx}$`),wS=new globalThis.RegExp(`^(?:${nx}|Infinity|-Infinity|NaN)$`);function TS(e){return Lx(CS,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:CS.source}),...e})}var ES=Kx(Wb,[TS()]),DS=new kb(ES,ib),OS=new kb(new wx([ES,Ox]),ib),kS=new globalThis.RegExp(`^-?\\d+$`);function AS(e){return Lx(kS,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:kS.source}),...e})}var jS=new kb(Kx(Wb,[AS({expected:`a string representing a bigint`})]),ab);function MS(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=MS(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 $v(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function NS(e){if(!yb(e))return;let t=e.annotations?.[Lv];return oe(t)?t(e.typeParameters):void 0}var PS=Mv,FS=Nv;function IS(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function LS(e){return e===void 0||typeof e==`string`}function RS(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 zS(e){return RS(e,IS)}var BS=new Pb([],()=>(e,t,n)=>zS(e)?Kv:fh(new ay(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>WS}),VS=new kb(BS,rb()),HS=new kb(new wx([new Xb(!1,[],[BS]),new cx([],[new sx(Wb,BS)])]),rb());function US(e){return RS(e,LS)}var WS=new kb(new Pb([],()=>(e,t,n)=>US(e)?Kv:fh(new ay(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),rb()),GS=(e,t,n)=>e===Kv?n(t):Og(e,n);function KS(e){let t=qS(e);return(e,n,r)=>{try{return t(e,n,r)}catch(e){return hh(e)}}}function qS(e){if(e._tag===`Middleware`)return(t,n,r)=>JS(t===Kv?e.decode(Wv(qv(n)),r):e.decode(Tg(t,qv),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===Kv?Wv(t):e;case`Transform`:{let e=e=>e===Uv?Gv:Wv(t.transform(e));return(t,n)=>GS(t,n,e)}case`TransformOptional`:{let e=e=>Jv(t.transform(qv(e)));return(t,n)=>GS(t,n,e)}case`TransformEffect`:return(e,n,r)=>GS(e,n,e=>e===Uv?Gv:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>GS(e,n,e=>JS(t.transform(qv(e),r)))}}var JS=e=>Og(e,Jv),YS=(e,t,n,r)=>Mh(r,r=>mh(()=>Nd(r,r=>new ey(e,r,t,n))));function XS(e,t){let n=KS(e.link.transformation),r;return(i,a)=>{if(i===Uv)return Gv;if(e.isConstructed(i))return Kv;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function ZS(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==Uv&&r!==void 0)return t(r,i);let a=n;if(yc(a)&&a._tag===`Success`){let e=t(a[Mt],i);return e===Kv?a:e}return Og(YS(e,r,i,a),e=>{let n=t(e,i);return n===Kv?Wv(e):n})}}function QS(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:ZS(e,n)}function $S(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?NS(e):void 0,o=a?XS(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>KS(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(yc(r)){if(r._tag===`Success`){let i=r===Kv?t:r[Mt];if(t!==Uv&&i!==Uv){let i=MS(u,t,void 0,e,n);i&&(r=fh(new iy(e,i,t,n)))}}}else r=E(r,r=>{if(t!==Uv&&r!==Uv){let r=MS(u,t,void 0,e,n);if(r)return fh(new iy(e,r,t,n))}return w(r)})}if(s&&!n.disableChecks){if(yc(r)){if(r._tag===`Success`){let i=r===Kv?t:r[Mt];if(i===Uv)return r;let a=MS(s,i,void 0,e,n);a&&(r=fh(new iy(e,a,i,n)))}}else r=E(r,t=>{if(t!==Uv){let r=MS(s,t,void 0,e,n);if(r)return fh(new iy(e,r,t,n))}return w(t)})}return r}catch(e){return hh(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=Og(o,e=>{let n=t(e,r);return n===Kv?Wv(e):n})}if(o._tag===`Success`){let e=o[Mt],t=p(e,r);return t===Kv?o:t}return o=YS(e,n,r,o),Og(o,e=>{let t=p(e,r);return t===Kv?Wv(e):t})}:p}var eC=Symbol(),tC=new WeakMap,nC=e=>oC(e).parser,rC=e=>oC(e).makeEffect,iC=e=>QS(e,rC),aC=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=$S(this.ast,nC)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=$S(this.ast,rC,iC)}};function oC(e){let t=tC.get(e);if(t!==void 0)return t;let n=new aC(e);return tC.set(e,n),n}function sC(e){let t=e.ast,n;return(e,r)=>(n??=SC(kC,pS(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function cC(e){let t=sC(e);return(e,n)=>{let r=xg(t(e,n));return Kd(r)?b(r.value):(Oy(r.cause,`Option adapter can only return none for schema issues`),y())}}function lC(e){return DC(pS(e.ast))}function uC(e){return fC(e.ast)}function dC(e){{let t=CC(bC(e));return e=>{let n=t(e,Ab);return Kd(n)?!0:(Oy(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function fC(e){let t=pS(e),n=e=>(n=dC(t),n(e));return e=>n(e)}function pC(e,t){let n=bC(e.ast);return t===void 0?n:(e,r)=>n(e,vC(t,r))}function mC(e,t){return wC(pC(e,t))}var hC=mC;function gC(e,t){return TC(pC(e,t))}function _C(e,t){let n=bC(gS(e.ast));return t===void 0?n:(e,r)=>n(e,vC(t,r))}var vC=(e,t)=>t?{...e,...t}:e,yC=e=>e===Uv?fh(new oy):w(e);function bC(e){return SC(OC,e)}function xC(e,t){return e===Kv?w(t):yc(e)?e[`~effect/Effect/args`]===Uv?yC(Uv):e:Og(e,yC)}function SC(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Ab);return a===Kv?w(r):yc(a)?a[`~effect/Effect/args`]===Uv?yC(Uv):a:Og(a,yC)}}function CC(e){return(t,n)=>xg(e(t,n))}function wC(e){let t=CC(e);return(e,n)=>{let r=t(e,n);return Kd(r)?b(r.value):(Oy(r.cause,`Option adapter can only return none for schema issues`),y())}}function TC(e){let t=CC(e);return(e,n)=>{let r=t(e,n);return Kd(r)?pi(r.value):mi(Oy(r.cause,`Result adapter can only return schema issues`))}}function EC(e,t){let n=xg(e);if(Kd(n))return n.value;let r=Oy(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function DC(e){let t,n;return(r,i)=>{t??=oC(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Ab,o=t.make;if(o!==void 0&&r!==Uv){let e;try{e=o(r,a)}catch(e){throw Oy(Od(e),`Constructor adapter can only throw schema issues`),e}if(e!==eC&&e!==Uv)return e}return EC(xC((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var OC=e=>oC(e).parser,kC=e=>oC(e).makeEffect,AC=`~effect/Schema/Schema`,jC=Symbol(),MC={[AC]:AC,get make(){let e=lC(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=sC(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=cC(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return e(this,arguments)},annotate(e){return this.rebuild(Wx(this.ast,e))},annotateKey(e){return this.rebuild(eS(this.ast,e))},check(...e){return this.rebuild(Kx(this.ast,e))},rebuild(e){return NC(e,this[jC])}};function NC(e,t){function n(){}let r=Object.setPrototypeOf(n,MC);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[jC]=t,r.ast=e,r}function PC(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function FC(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function IC(e){return encodeURI(PC(e)).replace(/#/g,`%23`)}function LC(e){if(e.length===0||e===`#`)return``;if(!e.startsWith(`#`))return;let t=e.slice(1);try{if(encodeURI(t).replace(/%25/g,`%`).replace(/#/g,`%23`)!==t)return;let e=decodeURIComponent(t);return e.startsWith(`/`)&&!/~(?:[^01]|$)/.test(e)?e:void 0}catch{return}}function RC(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!de(e))return e;let a=r||!i&&HC(e.$id),o={};for(let t of Object.keys(e)){let r=e[t],i=r;switch(t){case`$defs`:case`properties`:case`patternProperties`:case`dependentSchemas`:i=VC(r,e=>n(e,a))??r;break;case`allOf`:case`anyOf`:case`oneOf`:case`prefixItems`:i=Array.isArray(r)?r.map(e=>n(e,a)):r;break;case`not`:case`additionalProperties`:case`propertyNames`:case`unevaluatedProperties`:case`items`:case`contains`:case`unevaluatedItems`:case`if`:case`then`:case`else`:case`contentSchema`:i=n(r,a)}Et(o,t,i)}return t(o,a),o}}function zC(e,t){return RC(e,e=>{BC(e,t)})}function BC(e,t){typeof e.$ref==`string`&&Et(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&Et(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function VC(e,t){if(!de(e))return;let n={};for(let r of Object.keys(e))Et(n,r,t(e[r],r));return n}function HC(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}var UC=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...UC],[...UC];function WC(e){return NC(GC(e.ast),{schema:e})}var GC=Zx(e=>{let t=Bx(e);if(t!==e){let n=GC(t);if(n===t)return e;if(n.encoding===void 0)return Hx(n,e.context)}let n=XC(e,GC),r=e.context;return n===e||r===void 0?n:Xx(n,KC(r))});function KC(e){return e.constructorDefault===void 0?e:new jb(e.isOptional,e.isMutable,void 0,e.annotations)}function qC(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function JC(e){return t=>{let n=[...t].sort((t,n)=>e(mS(t))-e(mS(n)));return n.some((e,n)=>e!==t[n])?n:t}}var YC=JC(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function XC(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!oe(n))return Vx(e,[VS]);let r=n(e.typeParameters.map(e=>NC(mS(e))));return r===void 0?e:Vx(e,[qx(r,t)])}case`Unknown`:return Vx(e,[VS]);case`ObjectKeyword`:return Vx(e,[HS]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return qC(e),e.recur(t,xS);case`Union`:{let n=YC(e.types);return n===e.types?e.recur(t):new wx(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 ZC(e){return NC(rw(e.ast),{schema:e})}var QC=JC(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function $C(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>NC(t(mS(e)))),i=e.annotations?.toCodecStringTree;if(oe(i)){let n=i(r);return n===void 0?e:Vx(e,[qx(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):Vx(e,[qx(c,t)])}case`Null`:return Vx(e,[ew]);case`Boolean`:return Vx(e,[tw]);case`Unknown`:case`ObjectKeyword`:return Vx(e,[WS]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return qC(e),e.recur(t,xS);case`Union`:{let n=QC(e.types);return n===e.types?e.recur(t):new wx(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 ew=new kb(new Hb(`null`),new Xy(Fy(()=>null),Fy(()=>`null`))),tw=new kb(new wx([new Hb(`true`),new Hb(`false`)]),new Xy(Fy(e=>e===`true`),Vy())),nw=new Xy(Fy(e=>typeof e==`string`?[e]:e),Py()),rw=Zx(e=>{let t=$C(e,rw,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?Xx(t,KC(e.context)):t},{stopAt:e=>e.transformation===nw});globalThis.RegExp;var iw=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function aw(e,t){return t.length>0&&(e+=`\n at ${lt(t)}`),Error(e)}function ow(e){return`#/$defs/${IC(e)}`}var sw=new Set([...Hv,Fv,...Rv]);function cw(e,t){if(e===void 0)return;let n={};for(let t of[`title`,`description`,`format`,`contentEncoding`,`contentMediaType`]){let r=e[t];typeof r==`string`&&(n[t]=r)}for(let t of[`readOnly`,`writeOnly`]){let r=e[t];typeof r==`boolean`&&(n[t]=r)}let r=e.expected;n.description===void 0&&t?.generateDescriptions===!0&&typeof r==`string`&&(n.description=r);let i=e.default;zS(i)&&(n.default=i);let a=e.examples;Array.isArray(a)&&zS(a)&&(n.examples=a);let o=e.contentSchema;if(zS(o)&&(n.contentSchema=o),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))!sw.has(r)&&t.includeAnnotationKey(r)&&zS(i)&&Et(n,r,i);return Object.keys(n).length===0?void 0:n}function lw(e){let t=e.type===`number`||e.type===`integer`?e.type:void 0,n=e;if(t!==void 0&&(n={...e},delete n.type),Array.isArray(n.allOf)){let e=[],r=!1;for(let i of n.allOf){let n=lw(i);n.type!==void 0&&(r=!0,(t===void 0||n.type===`integer`)&&(t=n.type)),Object.keys(n.schema).length>0&&e.push(n.schema)}if(r){let{allOf:t,...r}=n;n=e.length===0?r:{...r,allOf:e}}}return{type:t,schema:n}}function uw(e){if(!Array.isArray(e.anyOf)||e.anyOf.length!==2||e.anyOf[0]?.type!==`number`)return!1;let t=e.anyOf[1];return t?.type===`string`&&Array.isArray(t.enum)&&t.enum.length===3&&t.enum.includes(`NaN`)&&t.enum.includes(`Infinity`)&&t.enum.includes(`-Infinity`)}var dw=`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`;function fw(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function pw(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}var mw=`|minimum|exclusiveMinimum|minLength|minItems|minProperties|`,hw=`|maximum|exclusiveMaximum|maxLength|maxItems|maxProperties|`;function gw(e,t,n){if(typeof e.$ref==`string`)return;let r={...e,...t};for(let i of n){if(!Object.hasOwn(e,i))continue;let n=e[i],a=t[i];if(typeof n!=`number`||typeof a!=`number`)return;if(mw.includes(`|${i}|`))r[i]=Math.max(n,a);else if(hw.includes(`|${i}|`))r[i]=Math.min(n,a);else return}return typeof r.minimum==`number`&&typeof r.exclusiveMinimum==`number`&&delete r[r.exclusiveMinimum>=r.minimum?`minimum`:`exclusiveMinimum`],typeof r.maximum==`number`&&typeof r.exclusiveMaximum==`number`&&delete r[r.exclusiveMaximum<=r.maximum?`maximum`:`exclusiveMaximum`],r}var _w=`|title|description|default|examples|readOnly|writeOnly|`,vw=dw+_w;function yw(e,t,n){if(Object.keys(e).length===0)return t;let r=Object.keys(t);if(r.length===0)return e;let i=e.type===`number`||e.type===`integer`?e.type:void 0,a=uw(e);if(i!==void 0||a){let r=lw(t);if(r.type!==void 0){let t=i===`integer`||r.type===`integer`?`integer`:`number`,o={...e,type:t};a&&delete o.anyOf;let s=Object.keys(r.schema);return s.length===0?o:fw(r.schema,_w)&&pw(o,s)?{...o,...r.schema}:yw(o,r.schema,n)}}if(n){let n=gw(e,t,r);if(n!==void 0)return n}let o=Array.isArray(t.allOf)&&r.length===1?t.allOf:[t];return Array.isArray(e.allOf)?{...e,allOf:[...e.allOf,...o]}:typeof e.$ref==`string`?{allOf:[e,...o]}:{...e,allOf:o}}function bw(e,t=new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>bw(e,t)))}function xw(e){return Array.isArray(e)}function Sw(e,t,n,r){let i=new Map,a=new Map,o=new WeakMap,s=new Map,c=new Map,l=Object.keys(n);for(let e of l)m(e,[`references`,e]);let u=$i(e,(e,n)=>v(e,t[n],[]));for(let[e,t]of s.values())if(!bw(e))for(let e of t)Array.isArray(e.oneOf)&&(e.anyOf=e.oneOf,delete e.oneOf);for(let e of l){let t=n[e],r=g(t);if(r===void 0)continue;let o=i.get(e)[0],s=c.get(r),l=s?.find(e=>Le(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=$i(u,h),f={};for(let e of l)a.has(e)||Et(f,e,h(i.get(e)[0]));return{dialect:`draft-2020-12`,schemas:d,definitions:f};function p(e){return Array.isArray(e.oneOf)&&s.get(e.oneOf)?.[1].push(e),e}function m(e,t){if(!Object.hasOwn(n,e))throw aw(`Invalid reference ${e}`,[...t,`$ref`]);let r=i.get(e);if(r!==void 0)return r;let a=[{},[]];return i.set(e,a),a[0]=v(n[e],[`references`,e],a[1]),a}function h(e){return zC(e,e=>{let t=LC(e);if(t===void 0){if(/^#(?:\/|%2f)/i.test(e))throw Error(`Invalid JSON Pointer URI fragment ${JSON.stringify(e)}`);return e}if(!t.startsWith(`/$defs/`))return e;let n=t.indexOf(`/`,7),r=a.get(FC(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,ow(r))})}function g(e){if(e._tag===`Reference`)return;let t=e.checks.length===0?e.annotations:e.checks[e.checks.length-1].annotations;return typeof t?.identifier!=`string`&&typeof t?.[`~identifier`]==`string`?t[Fv]:void 0}function _(e,t,n,i){let a=e.annotations,o=a?.toJsonSchema;if(o!==void 0){let s=o({type:t,schemas:e.representation?.schemas?.map((e,t)=>v(e,[...n,`representation`,`schemas`,t],i))??[]}),c=xw(s);c&&i.push(!1);let l=c?s[0]:s,u=cw(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?dw:vw;return[d,e._tag===`Filter`&&fw(d,f)&&(u===void 0||fw(u,_w))?!0:void 0]}if(e._tag===`Filter`){i.push(!1);return}let s=e.checks.flatMap((e,r)=>{let a=_(e,t,[...n,`checks`,r],i);return a===void 0?[]:[a[0]]});if(s.length===0)return;let c=cw(a,r),l={allOf:s};return[c===void 0?l:{...l,...c}]}function v(e,t,n){if(e._tag===`Reference`)return n.push(m(e.$ref,t)[1]),{$ref:ow(e.$ref)};let i=o.get(e);if(i!==void 0)return n.push(i[1]),i[0];let a=[];n.push(a);let s=ee(e,t,a),c=cw(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&Cw(s.type)?s.type:void 0,i=_(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=yw(s,...i))}return o.set(e,[s,a]),p(s)}function ee(e,t,n){switch(e._tag){case`Any`:case`Unknown`:return{};case`ObjectKeyword`:return{anyOf:[{type:`object`},{type:`array`}]};case`Void`:case`Undefined`:case`Null`:return{type:`null`};case`BigInt`:return{type:`string`,allOf:[{pattern:`^-?\\d+$`}]};case`Symbol`:return{type:`string`,allOf:[{pattern:`^Symbol\\(([\\s\\S]*)\\)$`}]};case`UniqueSymbol`:return globalThis.Symbol.keyFor(e.symbol)===void 0?{not:{}}:{type:`string`,enum:[globalThis.String(e.symbol)]};case`Declaration`:return n.push(!1),{};case`Suspend`:return v(e.thunk,[...t,`thunk`],n);case`Never`:return{not:{}};case`String`:return{type:`string`};case`Number`:return{anyOf:[{type:`number`},{type:`string`,enum:[`NaN`,`Infinity`,`-Infinity`]}]};case`Boolean`:return{type:`boolean`};case`Literal`:{let t=e.literal;return typeof t==`bigint`?{type:`string`,enum:[globalThis.String(t)]}:{type:typeof t,enum:[t]}}case`Enum`:{let t=e.enums.map(([e,t])=>({type:typeof t,enum:[t],title:e}));return t.length===0?{not:{}}:{anyOf:t}}case`TemplateLiteral`:return{type:`string`,pattern:`^${e.parts.map(Tw).join(``)}$`};case`Arrays`:{let i={type:`array`},a=e.elements.length,o=e.elements.map((e,i)=>{e.isOptional&&a--;let o=v(e.type,[...t,`elements`,i,`type`],n),s=cw(e.annotations,r);return s===void 0?o:p(yw(o,s))});if(o.length>0?(i.prefixItems=o,i.maxItems=e.elements.length,a>0&&(i.minItems=a)):i.items=!1,e.rest.length===1){delete i.maxItems;let r=v(e.rest[0],[...t,`rest`,0],n);Object.keys(r).length>0?i.items=r:delete i.items}else e.rest.length>1&&(delete i.maxItems,delete i.items,i.minItems=a+e.rest.length-1,n.push(!1));return i}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return{not:{type:`null`}};let i={type:`object`},a={},o=[];for(let i=0;i<e.propertySignatures.length;i++){let s=e.propertySignatures[i];if(typeof s.name!=`string`)throw aw(`Objects property names must be strings`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=v(s.type,[...t,`propertySignatures`,i,`type`],n),u=cw(s.annotations,r);Et(a,c,u===void 0?l:p(yw(l,u))),s.isOptional||o.push(c)}e.propertySignatures.length>0&&(i.properties=a),o.length>0&&(i.required=o);let s={},c=[],l=[],u=!1;for(let r=0;r<e.indexSignatures.length;r++){let i=e.indexSignatures[r],a=v(i.type,[...t,`indexSignatures`,r,`type`],n);Le(a,{not:{}})&&(a=!1),l.push(a);let o=ne(i.parameter,[...t,`indexSignatures`,r,`parameter`],new Set);if(o===void 0)u=!0,n.push(!1);else if(o.length===0)c.push(a);else for(let e of o){let t=s[e];Et(s,e,t===void 0?a:t===!1||a===!1?!1:p(yw(t,a)))}}let d=Object.keys(s).length>0;if(d&&(i.patternProperties=s),u&&r?.onExcessProperty===`error`){let r=[];e.propertySignatures.length>0&&r.push({enum:Object.keys(a)});for(let i=0;i<e.indexSignatures.length;i++)r.push(te(e.indexSignatures[i].parameter,[...t,`indexSignatures`,i,`parameter`],n,new Set));i.propertyNames=r.length===1?r[0]:{anyOf:r},i.additionalProperties=l.length===1?l[0]:{anyOf:l},c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})))}else c.length===0?i.additionalProperties=u||r?.onExcessProperty!==`error`:c.length===1&&e.propertySignatures.length===0&&!d?i.additionalProperties=c[0]:c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})));return typeof i.additionalProperties==`object`&&i.additionalProperties!==null&&Object.keys(i.additionalProperties).length===0&&delete i.additionalProperties,i}case`Union`:{let r=[],i=e.types.map((e,n)=>v(e,[...t,`types`,n],r));if(n.push(r),i.length===0)return{not:{}};if(e.options?.mode===`oneOf`)return s.set(i,[r,[]]),{oneOf:i};if(i.length>1){let e=ww(i);if(e!==void 0)return e}return{anyOf:i.flatMap(e=>Array.isArray(e.anyOf)&&Object.keys(e).length===1?e.anyOf:[e])}}}}function te(e,t,r,i){switch(e._tag){case`Number`:return{type:`string`,pattern:`^(?:${nx}|Infinity|-Infinity|NaN)$`};case`Reference`:return i.has(e.$ref)?{type:`string`}:te(n[e.$ref],[`references`,e.$ref],r,new Set(i).add(e.$ref));case`Union`:return{anyOf:e.types.map(e=>te(e,t,r,i))};default:return v(e,t,r)}}function ne(e,t,r){switch(e._tag){case`Reference`:{if(m(e.$ref,t),r.has(e.$ref))return;let i=new Set(r).add(e.$ref);return ne(n[e.$ref],[`references`,e.$ref],i)}case`String`:{if(e.checks.length===0)return[];if(e.checks.length!==1||e.checks[0]._tag!==`Filter`||e.checks[0].annotations?.toJsonSchema===void 0)return;let n=[],r=v(e,t,n);return bw(n)&&r.type===`string`&&typeof r.pattern==`string`&&fw(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(Tw).join(``)}$`]:void 0;case`Union`:{if(e.types.length===0||e.checks.length>0||e.options?.mode===`oneOf`)return;let n=[];for(let i=0;i<e.types.length;i++){let a=ne(e.types[i],[...t,`types`,i],r);if(a===void 0)return;if(a.length===0)return[];n.push(...a)}return n}case`Number`:return e.checks.length===0?[`^(?:${nx}|Infinity|-Infinity|NaN)$`]:void 0;default:throw aw(`Invalid index signature parameter ${e._tag}`,t)}}}function Cw(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function ww(e){let t,n=[];for(let r of e){if(Object.keys(r).length!==2||r.type===void 0||!Array.isArray(r.enum)||r.enum.length===0)return;if(t===void 0)t=r.type;else if(r.type!==t)return;for(let e of r.enum){if(n.includes(e))return;n.push(e)}}return{type:t,enum:n}}function Tw(e){switch(e._tag){case`Literal`:return iw(globalThis.String(e.literal));case`String`:return SS;case`Number`:return nx;case`BigInt`:return`-?\\d+`;case`TemplateLiteral`:return e.parts.map(Tw).join(``);case`Union`:return`(?:${e.types.map(Tw).join(`|`)})`;default:throw aw(`Invalid TemplateLiteral part ${e._tag}`,[])}}function Ew(e,t){let n=Sw([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}var Dw=({identifier:e})=>e;function Ow(e){return e===void 0?void 0:{annotations:e}}function kw(e,t){let{references:n,representations:r}=Aw([e],t);return{representation:r[0],references:n}}function Aw(e,t){let n={},r=new Map,i=new Set,a=new Map,o=new Set;for(let t of e)f(t);let s=t?.referencePolicy??Dw;for(let e of a.values())for(let t of e.values()){let e=s({ast:t.ast,occurrences:t.occurrences,identifier:t.identifier});e===void 0?t.isRecursive&&(t.reference=c(`${t.ast._tag}_`,t,``)):t.reference=c(e,t,e===t.identifier||!e.endsWith(`_`)?`_`:``)}return{representations:$i(e,e=>m(e)),references:n};function c(e,t,n=`_`){let i=e,a=0;for(;r.has(i);){if(r.get(i)===t)return i;i=`${e}${n}${++a}`}return r.set(i,t),i}function l(e,t,n){let r=t.fallback;return r===void 0?n===t.identifier?e:Wx(e,{identifier:n}):Bv(e)===r?e:Wx(e,{[Fv]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=h(t);i.delete(e),Et(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=Ux(e),n=Bx(t),r=zv(t),i=r===void 0?(t===e?void 0:zv(e))??Bv(t):void 0;i!==void 0&&(r=`${i}Encoded`);let o=a.get(n);o===void 0&&(o=new Map,a.set(n,o));let s=o.get(r);return s===void 0&&(s={ast:n,identifier:r,fallback:i,occurrences:0,isRecursive:!1,reference:void 0},o.set(r,s)),s}function f(e){let t=d(e),n=t.ast;if(t.occurrences++,o.has(t))t.isRecursive=!0;else if(!(t.occurrences>1)){switch(o.add(t),p(n.checks),n._tag){case`Declaration`:case`Arrays`:case`Objects`:case`Union`:n.recur(e=>(f(e),e));break;case`TemplateLiteral`:n.parts.forEach(f);break;case`Suspend`:f(n.thunk())}o.delete(t)}}function p(e){e?.forEach(e=>{e.annotations?.representation?.schemas?.forEach(e=>f(pS(e))),e._tag===`FilterGroup`&&p(e.checks)})}function m(e){let t=d(e),n=t.ast,r=t.reference;return r===void 0?h(n):u(r,t.identifier===void 0?n:l(n,t,r))}function h(e){let t=g(e.checks);switch(e._tag){case`Declaration`:return{_tag:`Declaration`,typeParameters:e.typeParameters.map(e=>m(e)),checks:t,...v(e.annotations)};case`Null`:case`Undefined`:case`Void`:case`Never`:case`Unknown`:case`Any`:case`String`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`ObjectKeyword`:return{_tag:e._tag,checks:t,...Ow(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...Ow(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...Ow(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...Ow(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...Ow(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=Ux(e),n=t.context?.annotations;return{isOptional:cS(t),type:m(e),...Ow(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...Ow(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=Ux(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:cS(t),isMutable:lS(t),...Ow(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...Ow(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...Ow(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...Ow(e.annotations)}}}function g(e){return e?.map(_)??[]}function _(e){switch(e._tag){case`Filter`:return{_tag:`Filter`,aborted:e.aborted,...ee(e.annotations)};case`FilterGroup`:return{_tag:`FilterGroup`,checks:$i(e.checks,_),...ee(e.annotations)}}}function v(e){if(e===void 0)return;let{representation:t,...n}=e;return{...t===void 0?void 0:{representation:t},...Object.keys(n).length===0?void 0:{annotations:n}}}function ee(e){if(e===void 0)return;let{representation:t,...n}=e,r=t===void 0?void 0:t.schemas===void 0?t:{...t,schemas:t.schemas.map(e=>m(pS(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function jw(e){return Kd(e)?e.value:{issues:[{message:Rd(e.cause)}]}}function Mw(e,t){let n=pC(e),r={errors:`all`,...t?.parseOptions},i=gy(t);return Nw(e,{validate:e=>{let t=new to(`sync`),a=_g(Wh(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?jw(o):new Promise(e=>{a.addObserver(t=>{e(jw(t))})})}})}function Nw(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 Pw=r(2,(e,t)=>({...e,...t})),Fw=r(2,(e,t)=>Lw(e,(e,n)=>[Object.hasOwn(t,e)?t[e]:e,n])),Iw=e=>e;function Lw(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 Rw=`~effect/Schema/SchemaError`;function zw(e){return pe(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}({...yt}),{...yt},{...yt},{...yt},{...yt},{...yt},{...yt},{...yt};var Bw=AC;function Vw(){return(e,t,n)=>sT(new Pb(e.map(mx),e=>t(e.map(e=>sT(e))),n))}function Hw(e,t){return Vw()([],()=>(t,n,r)=>e(t)?w(t):fh(new ay(n,t,r)),t)}var Uw=class extends so(`SchemaError`){[Rw]=Rw;constructor(e){let t=St();Ct(0);try{super({issue:e})}finally{Ct(t)}}get message(){return wy(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[gt](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}};function Ww(e){return zw(e)}function Gw(e){return yc(e)?Kw(e):Mh(e,e=>mh(()=>Nd(e,e=>new Uw(e))))}function Kw(e){return Kd(e)?e:Ud(Nd(e.cause,e=>new Uw(e)))}function qw(e,t){let n;for(let r of e.reasons){if(!Td(r)||!Ww(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 Jw(e){let t=xg(e);if(Kd(t))return t.value;throw qw(t.cause,`Sync adapter can only throw schema errors`)}function Yw(e,t){return Mw(e,t)}var Xw=uC;function Zw(e,t){let n=pC(e,t);return(e,t)=>Gw(n(e,t))}var Qw=Zw,$w=mC,eT=hC;function tT(e,t){let n=gC(e,t);return(e,t)=>bi(n(e,t),e=>new Uw(e))}function nT(e,t){let n=Zw(e,t);return(e,t)=>Jw(n(e,t))}function rT(e,t){let n=_C(e,t);return(e,t)=>Gw(n(e,t))}var iT=rT;function aT(e,t){let n=rT(e,t);return(e,t)=>Jw(n(e,t))}var oT=aT,sT=NC;function cT(e){return pe(e,Bw)&&e[Bw]===Bw}var lT=Iw(e=>sT(tS(e.ast),{schema:e})),uT=Iw(e=>{let t=MT(e);return sT(rS(e.ast),{schema:t})}),dT=Iw(e=>sT(pS(e.ast),{schema:e})),fT=Iw(e=>sT(mS(e.ast),{schema:e}));function pT(e){let t=sT(new Hb(e),{literal:e,transform(n){return t.pipe(NT(pT(n),{decode:Fy(()=>n),encode:Fy(()=>e)}))}});return t}var mT=sT(Bb),hT=sT(Vb),gT=sT(Fb),_T=sT(Rb),j=sT(Wb),vT=sT(qb),yT=sT(Jb),bT=sT(Yb),xT=sT(zb);function ST(e,t){return sT(e,{fields:t,mapFields(e,t){let n=e(this.fields);return ST(px(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function M(e){return ST(px(e,void 0),e)}var CT=e=>typeof e==`symbol`?e:globalThis.String(e);function wT(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=fT(t.fields[o]),c=Object.hasOwn(e,o),l=c?e[o]:o,u=CT(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 M(n).pipe(NT(t,eb({decode:Fw(i),encode:Fw(r)})))}}function TT(e,t){return sT(sS(e.ast,t.ast),{key:e,value:t})}function ET(e,t){return sT(Fee(e.ast,t.map(mx)),{schema:e,records:t})}function DT(e,t){return sT(e,{elements:t,mapElements(e,t){let n=e(this.elements);return DT(hx(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function OT(e){return DT(hx(e),e)}var N=Iw(e=>sT(new Xb(!1,[],[e.ast]),{value:e})),kT=Iw(e=>sT(new Xb(!1,[e.ast],[e.ast]),{value:e}));function AT(e,t){return sT(e,{members:t,mapMembers(e,t){let n=e(this.members);return AT(gx(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function P(e,t){return AT(gx(e,t,void 0),e)}function jT(e){let t=e.map(pT);return sT(gx(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return P(e(this.members))},pick(e){return jT(e)},transform(e){return P(t.map((t,n)=>t.transform(e[n])))}})}var F=Iw(e=>P([e,gT])),MT=Iw(e=>P([e,_T]));function I(e){return t=>sT(t.ast,{schema:t,identifier:e})}function NT(e,t){return n=>sT(aS(n.ast,e.ast,t?Qy(t):rb()),{from:n,to:e})}function PT(){return(e,t)=>UT()(e,{decode:t,encode:My})}function FT(e,t){return n=>t?NT(n,t)(e):NT(n)(e)}function IT(e){return t=>sT(iS(t.ast,e),{schema:t})}function LT(e){return yc(e)&&e._tag===`Success`?e:Mh(e,e=>mh(()=>Nd(e,e=>e.issue)))}function RT(e,t){let n=t?.encodingStrategy===`omit`?zy():Py();return t=>lT(fT(t)).pipe(NT(t,{decode:By(LT(e)),encode:n}))}function zT(e,t){return n=>dT(n).pipe(RT(e,t),FT(lT(n)))}function BT(e){return pT(e).pipe(IT(w(e)))}function VT(e,t){return M({_tag:BT(e),...t})}function HT(e,t){return Hw(t=>t instanceof e,t)}function UT(){return(e,t)=>new kb(e.ast,Qy(t))}var WT=Nx;function GT(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 Lx(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var KT=sT(Fx),qT=Px;function JT(e){let t=lr(e.order),n=e.formatter??ot;return(r,i)=>WT(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function YT(e){let t=dr(e.order),n=e.formatter??ot;return(r,i)=>WT(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 XT(e){let t=dr(e.order),n=lr(e.order),r=ur(e.order),i=cr(e.order),a=e.formatter??ot;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return WT(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 ZT(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${ot(e)}`);return e}var QT=JT({order:ir,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:ZT(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${ot(e)})`})})}),$T=YT({order:ir,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:ZT(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${ot(e)})`})})}),eE=XT({order:ir,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:ZT(e.minimum),maximum:ZT(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 tE(e){return WT(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 L=vT.check(tE());function nE(e,t){return e=oE(e),rE(e,Math.ceil(e/2),t)}function rE(e,t,n){return WT(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})`}),[Pv]:!0,arbitraryConstraint:{minLength:e},...n})}function iE(e){return rE(1,1,e)}function aE(e,t){return e=oE(e),WT(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})`}),[Pv]:!0,arbitraryConstraint:{maxLength:e},...t})}function oE(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function sE(e){return WT(e=>ra(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 R=j.check(iE()),cE=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),lE=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},uE=[];function dE(e){let t=cE(e),n=uE[t];if(n!==void 0)return n;let r=JE.pipe(NT(hT,fb(lE(t))));return uE[t]=r,r}globalThis.RegExp;var fE=j.annotate({expected:`a string that will be decoded as a URL`}),pE=HT(globalThis.URL,{representation:{id:`effect/schema/URL`,payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:`URL`,toCodecJson:()=>UT()(fE,hb)}),mE=fE.pipe(NT(pE,hb)),hE=j.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function gE(e,t){return hE.pipe(NT(e,_b(t)))}var _E=gE(hT);globalThis.File,globalThis.URLSearchParams;var vE=j.annotate({expected:`a string that will be decoded as a finite number`}).pipe(NT(KT,ib)),yE=j.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),bE=HT(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>UT()(yE,gb)});function xE(e,t){return sT(Vw()([e,t],([e,t])=>(n,r,i)=>{if(!wd(n))return fh(new ay(r,n,i));switch(n._tag){case`Fail`:return Dg(pC(e)(n.error,i),{onSuccess:kd,onFailure:e=>sy(r,`error`,e,n,i)});case`Die`:return Dg(pC(t)(n.defect,i),{onSuccess:Ad,onFailure:e=>sy(r,`defect`,e,n,i)});case`Interrupt`:return w(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])=>UT()(P([M({_tag:pT(`Fail`),error:e}),M({_tag:pT(`Die`),defect:t}),M({_tag:pT(`Interrupt`),fiberId:MT(KT)})]),eb({decode:e=>{switch(e._tag){case`Fail`:return kd(e.error);case`Die`:return Ad(e.defect);case`Interrupt`:return jd(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 SE(e,t){return sT(Vw()([e,t],([e,t])=>{let n=N(xE(e,t));return(e,t,r)=>Cd(e)?Dg(pC(n)(e.reasons,r),{onSuccess:Ed,onFailure:n=>sy(t,`reasons`,n,e,r)}):fh(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])=>UT()(N(xE(e,t)),eb({decode:Ed,encode:({reasons:e})=>e}))}).ast,{error:e,defect:t})}var CE=$y({decode:(e,t)=>pr(c_(e),{onNone:()=>fh(new oy({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>w(u_(e))}),encode:e=>w(v_(e))}),wE=-864e13,TE=864e13;function EE(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 DE(e,t){return L.check(eE({minimum:e,maximum:t}))}var OE=Hw(e=>i_(e)&&a_(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]=EE(e,wE,TE);return PT()(DE(t,n),Fy(s_))},toCodecJson:()=>UT()(j,CE),toFormatter:()=>e=>e.toString()}),kE=j.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(NT(OE,CE));function z(e){return sT(Vw()([e],([e])=>(t,n,r)=>fr(t)?x(t)?oh:Dg(pC(e)(t.value,r),{onSuccess:b,onFailure:e=>sy(n,`value`,e,t,r)}):fh(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])=>UT()(P([M({_tag:pT(`Some`),value:e}),M({_tag:pT(`None`)})]),eb({decode:e=>e._tag===`None`?y():b(e.value),encode:e=>S(e)?{_tag:`Some`,value:e.value}:{_tag:`None`}}))}).ast,{value:e})}function AE(e){return F(e).pipe(NT(z(dT(e)),pb()))}var jE=Hw(sv,{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:()=>pv,toCodec:()=>UT()(N(OT([j,j])),eb({decode:lv,encode:e=>e.params.map(([e,t])=>[e,av(t)])}))}).pipe(NT(TT(j,P([j,kT(j)])),eb({decode:bv,encode:uv})));function ME(e){return lT(e).pipe(NT(z(dT(e)),mb()))}function NE(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:pC(pT(n));return sT(Vw()([e],([e])=>(t,n,r)=>B_(t)?Og(a===void 0?lh:Eg(a(t.label,r),e=>new ty([`label`],e)),()=>Dg(pC(e)(U_(t),r),{onSuccess:e=>V_(e,{label:t.label}),onFailure:()=>new iy(n,[new ty([`value`],new oy(void 0,t,r))],t,r)})):fh(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])=>UT()(e,{decode:Fy(e=>V_(e,{label:n})),encode:r?jy(e=>`Cannot serialize Redacted`+(S(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):Fy(U_)}),toEquivalence:([e])=>W_(e)}).ast,{value:e})}function PE(e,t){return NT(NE(dT(e),{label:t?.label,disallowJsonEncode:t?.disallowEncode}),{decode:Fy(e=>V_(e,{label:t?.label})),encode:t?.disallowEncode?jy(e=>`Cannot encode Redacted`+(S(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):Fy(U_)})(e)}var FE=globalThis.Symbol.for(`immer-draftable`),IE={};function LE(t,n,r,i,a){let o=VE(r,n,i),s=BE(n),c=class extends t{constructor(...[e,t]){let n=t?.[`~payload`],i=n?.token===IE?n.value:r.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:IE,value:i}})}static[Bw]=Bw;get[s](){return s}static[FE]=!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 lC(o(this))(e??{},t)}static makeOption(e,t){return cC(o(this))(e??{},t)}static makeEffect(e,t){return o(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(Wx(this.ast,e))}static annotateKey(e){return this.rebuild(eS(this.ast,e))}static check(...e){return this.rebuild(Kx(this.ast,e))}static extend(e){return(t,n)=>{let i=HE(t)?t:M(t),o={...r.fields,...i.fields},s=px(o,r.ast.checks,{identifier:e});return LE(this,e,ST(Kx(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 RE(e,t){return new e(t,{"~payload":{token:IE,value:t}})}function zE(e){return new Xy(Fy(t=>RE(e,t)),Py())}function BE(e){return`~effect/Schema/Class/${e}`}function VE(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=BE(t),o=e=>e instanceof i||pe(e,a),s=zE(i);return r=NT(sT(new Pb([e.ast],()=>(e,t,n)=>o(e)?w(e):fh(new ay(t,e,n)),{identifier:t,[Lv]:([e])=>({isConstructed:o,link:new kb(e,s)}),toCodec:([e])=>new kb(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[Iv]:yx(e.ast),...n})),s)(e)}}function HE(e){return cT(e)}var B=e=>(t,n)=>LE(ao,e,HE(t)?t:M(t),n,e=>({toString(){return`${e}(${ot({...this})})`}})),V=e=>(t,n,r)=>{let i=HE(n)?n.mapFields(e=>({_tag:BT(t),...e}),{unsafePreserveChecks:!0}):VT(t,n);return B(e??t)(i,r)},UE=e=>(t,n)=>LE(bn,e,HE(t)?t:M(t),n,e=>({name:e})),WE=e=>(t,n,r)=>{let i=HE(n)?n.mapFields(e=>({_tag:BT(t),...e}),{unsafePreserveChecks:!0}):VT(t,n);return UE(e??t)(i,r)};function GE(e,t){return Ew(kw(GC(e.ast),t),t)}var KE=WC,qE=ZC,JE=sT(Wx(BS,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),YE=TT(j,JE),XE=Cs,ZE=Ts,QE=Es,$E=Ds,eD=Os,tD=Tu,nD=Fu,rD=`~effect/MutableRef`,iD={[rD]:rD,...Rt,toJSON(){return{_id:`MutableRef`,current:_t(this.current)}}},aD=e=>{let t=Object.create(iD);return t.current=e,t},oD=r(2,(e,t)=>(e.current=t,e)),sD=Symbol.for(`effect/MutableList/Empty`),cD=()=>({head:void 0,tail:void 0,length:0}),lD=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})},uD=()=>({array:[],mutable:!0,offset:0,next:void 0}),dD=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=uD(),e.tail=e.tail.next):e.head=e.tail=uD(),e.tail.array.push(t),e.length++},fD=e=>{e.head=e.tail=void 0,e.length=0},pD=e=>{if(!e.head)return sD;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:fD(e):lD(e),t},mD=`~effect/Queue`,hD=`~effect/Queue/Enqueue`,gD=`~effect/Queue/Dequeue`,_D={_A:i,_E:i},vD={[mD]:_D,[hD]:_D,[gD]:_D,...Rt,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:kD(this)}}},yD=e=>vn(t=>{let n=Object.create(vD);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=cD(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},ks(n)}),bD=e=>yD({capacity:e}),xD=r(2,(e,t)=>Ns(()=>SD(e,t)?jD:e.state._tag===`Open`&&e.strategy===`suspend`?zD(e,t):AD)),SD=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(pD(e.messages),dD(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(dD(e.messages,t),PD(e),!0):(dD(e.messages,t),FD(e),!0):!1,CD=r(2,(e,t)=>Ms(()=>wD(e,t))),wD=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=Fc(hn(t),MD);return e.state.offers.size===0&&e.messages.length===0?(WD(e,n),!0):(e.state={...e.state,_tag:`Closing`,exit:n},FD(e),!0)},TD=e=>Ms(()=>ED(e)),ED=e=>{if(e.state._tag===`Done`)return!1;fD(e.messages);let t=e.state.offers;WD(e,e.state._tag===`Open`?ND:e.state.exit);for(let e of t)VD(e);return!0},DD=e=>ID(()=>OD(e)??pc(RD(e,()=>LD(e,1)),DD(e))),OD=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=pD(e.messages);return UD(e),fn(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=HD(e.state.offers);return UD(e),fn(t)}},kD=e=>e.state._tag===`Done`?0:e.messages.length,AD=fn(!1),jD=fn(!0),MD=gn(Dn()),ND=Ec(),PD=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(jc),e.messages.length===0))break}},FD=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,PD(e)},0))},ID=un({op:`QueueTake`,[Nt](e){let t=this[Mt]();return Bt(t)?t[Nt](e):t}}),LD=(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,RD=(e,t)=>Ws(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(jc);let r={ready:t,resume:n};return e.state.takers.add(r),Ms(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),zD=(e,t)=>Ws(n=>SD(e,t)?n(jD):BD(e,{_tag:`Single`,message:t,resume:n})),BD=(e,t)=>{if(e.state._tag!==`Open`)return VD(t);let n=e.state.offers;return n.add(t),Ms(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&WD(e,e.state.exit))})},VD=e=>e._tag===`Single`?e.resume(AD):e.resume(fn(e.remaining.slice(e.offset))),HD=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(jD),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(fn([]))),n},UD=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&&(WD(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`)dD(e.messages,t.message),e.state.offers.delete(t),t.resume(jD);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;dD(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(fn([]))}let r=e.state;if(r._tag===`Done`)return ym(r.exit.cause)}return!1},WD=(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()},GD=e=>new qD(e),KD=(e,t,n)=>Ws(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),Ms(()=>{e.waiters.delete(i)})}),qD=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=Ns(()=>this.free<e?KD(this,e,t):(this.taken+=e,ks(e)));return t}takeIfAvailable(e){return Ns(()=>this.free<e?ks(!1):(this.taken+=e,ks(!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 vn(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),Rs))}release(e){return vn(t=>ks(this.releaseUnsafe(t,e)))}get releaseAll(){return vn(e=>ks(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>lu(n=>{let r=Ns(()=>this.free<e?vc(n(KD(this,e,Rs)),()=>r):(this.taken+=e,Ul(n(t),()=>{this.releaseUnsafe(ys(),e)},!0)));return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>lu(n=>this.free<e?Fs:(this.taken+=e,Ul(n(fc(t)),()=>{this.releaseUnsafe(ys(),e)},!0)))}},JD=e=>Ms(()=>new qD(e)),YD=`~effect/Channel`,XD=e=>pe(e,YD),ZD={[YD]:{_Env:i,_InErr:i,_InElem:i,_OutErr:i,_OutElem:i},pipe(){return e(this,arguments)}},QD=e=>{let t=Object.create(ZD);return t.transform=(t,n)=>Mh(e(t,n),e=>w(ph(e))),t},$D=(e,t)=>QD((n,r)=>E(nO(e)(n,r),e=>t(e,r))),eO=e=>QD((t,n)=>e),tO=e=>QD(Sg(function*(t,n){let r=ff(n),i=e=>pf(r,Cm(e));return ng(yield*ng(e(t,n,r),i),i)})),nO=e=>e.transform,rO=e=>QD((t,n)=>sh(()=>nO(e())(t,n))),iO=e=>eO(w(fh(e))),aO=e=>eO(ph(e)),oO=e=>aO(Od(e)),sO=e=>QD((t,n)=>cO({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),cO=e=>{let t=e.readable.getReader(),n=e.exit??aD(void 0),r=sh(()=>n.current?n.current:Gh(ah({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??ph(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?Bd():w(Qi(t))}));return Eh(df(e.scope,e.releaseLockOnEnd?ch(()=>t.releaseLock()):ih(()=>t.cancel().catch(e=>t.closed.then(()=>Promise.reject(e),u))).pipe(tg(ch(()=>t.releaseLock())))),r)},lO=r(2,(e,t)=>$D(e,e=>ch(()=>{let n=0;return Th(e,e=>t(e,n++))}))),uO=e=>e===void 0||e!==`unbounded`&&e<=1,dO=r(e=>XD(e[0]),(e,t,n)=>uO(n?.concurrency)?fO(e,t):pO(e,t,n)),fO=(e,t)=>QD((n,r)=>{let i=0;return Th(nO(e)(n,r),E(e=>t(e,i++)))}),pO=(e,t,n)=>tO(Sg(function*(r,i,o){let s=0,c=yield*nO(e)(r,i),l=n.concurrency===`unbounded`?2**53-1:Math.min(n.concurrency,2**53-1),u=yield*bD(0);yield*df(o,TD(u));let d=vg(yield*Kh()),f=tD(o);if(n.unordered){let e=GD(l),n=a(e.release(1)),r=Gh({onFailure:e=>E(CD(u,e),n),onSuccess:e=>E(xD(u,e),n)});yield*e.take(1).pipe(E(()=>c),E(e=>{let n=s++;return f(d(r(sh(()=>t(e,n))))),lh}),ug({disableYield:!0}),Mh(t=>e.withPermits(l-1)(CD(u,t))),hg(o))}else{let e=yield*bD(l-2);yield*df(o,TD(e)),yield*DD(e).pipe(yh,E(e=>xD(u,e)),ug({disableYield:!0}),Mh(e=>CD(u,e)),hg(o));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,wD(u,e.cause))};yield*c.pipe(E(i=>{if(n)return ph(n);let a=s++,o=d(sh(()=>t(i,a)));return f(o),o.addObserver(r),xD(e,ZE(o))}),ug({disableYield:!0}),Mh(t=>xD(e,Ud(t)).pipe(bh(CD(e,t)))),hg(o))}return DD(u)})),mO=e=>$D(e,e=>{let t,n=0;return w(sh(function r(){if(t===void 0)return E(e,e=>{switch(e.length){case 0:return r();case 1:return w(e[0]);default:return t=e,w(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),w(i)}))}),hO=r(2,(e,t)=>$D(e,e=>w(E(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return Bi(i)?w(i):E(e,n)})))),gO=r(2,(e,t)=>QD((n,r)=>{let i=ff(r);return Th(nO(e)(n,i),e=>{let a=e.pipe(Mh(e=>{if(ym(e))return ph(e);let o=i;return i=ff(r),pf(o,Ud(e)).pipe(bh(nO(t(e))(n,i)),E(e=>(a=e,e)))}));return sh(()=>a)})})),_O=r(3,(e,t,n)=>gO(e,e=>{let r=t(e);return vi(r)?aO(r.failure):n(r.success,e)})),vO=r(2,(e,t)=>_O(e,Xo,e=>t(e))),yO=r(e=>XD(e[0]),(e,t,n,r)=>vO(e,e=>t(e)?n(e):r?r(e):iO(e))),bO=r(2,(e,t)=>$D(e,e=>w(Ph(e,e=>zd(e)?e:t(e))))),xO=r(e=>XD(e[0])&&XD(e[1]),(e,t,n)=>tO(Sg(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*bD(0);yield*df(a,TD(s));let c=0;function l(e,t){if(c++,!ym(t))return CD(s,t);switch(o){case`both`:return c===2?CD(s,t):lh;case`left`:case`right`:return e===o?CD(s,t):lh;case`either`:return CD(s,t)}}let u=(e,t,n)=>nO(t)(r,n).pipe(E(e=>e.pipe(E(e=>xD(s,e)),ug)),ng(t=>rg(Cm(t),e=>pf(n,e)).pipe(Gh({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),hg(a));return yield*u(`left`,e,ff(a)),yield*u(`right`,t,ff(a)),DD(s)}))),SO=(e,t)=>QD((n,r)=>ch(()=>{let r=new TextDecoder(e,t),i={stream:!0},a=n.pipe(Th($i(e=>r.decode(e,i))),vm(e=>{a=Bd(e);let t=r.decode();return t.length>0?w(Qi(t)):a}));return sh(()=>a)})),CO=r(2,(e,t)=>QD((n,r)=>E(nO(e)(n,r),e=>nO(t)(e,r)))),wO=r(2,(e,t)=>xO(e,eO(w(E(t,Bd))),{haltStrategy:`either`})),TO=r(2,(e,t)=>tO((n,r,i)=>uf(i,t).pipe(bh(nO(e)(n,r))))),EO=r(2,(e,t)=>TO(e,e=>t)),DO=(e,t,n)=>sh(()=>{let r=cf();return vm(E(nO(e)(Bd(),r),t),n||w).pipe(ig(e=>pf(r,e)))}),OO=r(2,(e,t)=>QD((n,r)=>Th(Yh(nO(e)(n,r),t),Yh(t)))),kO=r(2,(e,t)=>DO(e,e=>ug(E(e,t),{disableYield:!0}))),AO=e=>sh(()=>{let t=y();return DO(e,e=>e.pipe(Dh,E(e=>(t=e,Bd()))),()=>w(t))}),jO=(e,t)=>nO(e)(Bd(),t),MO=(e,t)=>()=>{let n=Qw(kT(e),t);return QD((e,t)=>w(E(e,e=>n(e))))},NO=`~effect/Stream`,PO={_R:i,_E:i,_A:i},FO=function(e){this.channel=e};FO.prototype={[NO]:PO,pipe(){return e(this,arguments)}};var IO=e=>new FO(e),LO=`~effect/Stream`,RO=e=>pe(e,LO),zO=IO,BO=(e,t)=>zO(QD((n,r)=>E(jO(e.channel,r),e=>t(e,r)))),VO=e=>e.channel,HO=e=>{let t=zO(rO(()=>e().channel));return UO.set(t,e),t},UO=new WeakMap,WO=e=>zO(iO(e)),GO=e=>zO(oO(e)),KO=e=>zO(sO(e)),qO=r(2,(e,t)=>HO(()=>{let n=0;return zO(lO(e.channel,$i(e=>t(e,n++))))})),JO=r(e=>RO(e[0]),(e,t,n)=>e.channel.pipe(mO,dO(t,n),lO(Qi),zO)),YO=r(2,(e,t)=>zO(dO(e.channel,t))),XO=r(2,(e,t)=>zO(hO(VO(e),t))),ZO=r(e=>RO(e[0]),(e,t,n,r)=>zO(yO(VO(e),t,e=>n(e).channel,r&&(e=>r(e).channel)))),QO=r(2,(e,t)=>zO(bO(e.channel,t))),$O=r(2,(e,t)=>zO(CO(e.channel,t))),ek=r(e=>RO(e[0]),(e,t)=>e.channel.pipe(CO(SO(t?.encoding)),zO)),tk=r(2,(e,t)=>zO(wO(e.channel,t))),nk=r(2,(e,t)=>zO(EO(e.channel,t))),rk=r(2,(e,t)=>zO(OO(e.channel,t))),ik=e=>Th(AO(e.channel),Sr(Hi(0))),ak=r(e=>RO(e[0]),(e,t,n)=>{let r,i,a=!1,o=nD(!1),s=n?.signal,c=()=>i.interruptUnsafe();return new ReadableStream({start(n){i=_g(Yh(kO($D(e.channel,e=>w(o.whenOpen(e))),e=>ch(()=>{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(Fd(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(Oh(QE(i)))}},n?.strategy)}),ok=r(e=>RO(e[0]),(e,t)=>Th(Kh(),n=>ak(e,n,t))),sk=kr(`effect/Crypto`),ck=`~effect/FiberMap`,lk=e=>pe(e,ck),uk={[ck]:ck,[Symbol.iterator](){return this.state._tag===`Closed`?ki():this.state.backing[Symbol.iterator]()},...Rt,toJSON(){return{_id:`FiberMap`,state:this.state}}},dk=(e,t)=>{let n=Object.create(uk);return n.state={_tag:`Open`,backing:e,fibers:new Set},n.deferred=t,n},fk=()=>$h(ch(()=>dk(qm(),Xd())),e=>sh(()=>{let t=e.state;return t._tag===`Closed`?lh:(e.state={_tag:`Closed`},eD(t.fibers).pipe(af(e.deferred)))})),pk=-1,mk=qa(Ya(Ld,Ja(pk))),hk=r(e=>lk(e[0]),(e,t,n,r)=>{if(e.state._tag===`Closed`){n.interruptUnsafe(pk);return}let i=Jm(e.state.backing,t);if(i._tag===`Some`){if(i.value===n)return;if(r?.onlyIfMissing===!0){n.interruptUnsafe(pk);return}}Qm(e.state.backing,t,n),e.state.fibers.add(n),i._tag===`Some`&&i.value.interruptUnsafe(pk),n.addObserver(i=>{if(e.state._tag===`Closed`)return;e.state.fibers.delete(n);let a=Jm(e.state.backing,t);S(a)&&n===a.value&&eh(e.state.backing,t),qd(i)&&(r?.propagateInterruption===!0?!mk(i.cause):!Md(i.cause))&&rf(e.deferred,i)})}),gk=r(2,(e,t)=>e.state._tag===`Closed`?y():Jm(e.state.backing,t)),_k=r(2,(e,t)=>sh(()=>w(gk(e,t)))),vk=r(2,(e,t)=>e.state._tag!==`Closed`&&Zm(e.state.backing,t)),yk=r(2,(e,t)=>ch(()=>vk(e,t))),bk=r(2,(e,t)=>sh(()=>{if(e.state._tag===`Closed`)return lh;let n=Jm(e.state.backing,t);return n._tag===`None`?lh:$E(n.value,pk)})),xk=function(){let e;return()=>(e===void 0&&(e=_g(og)),e)}(),Sk=function(){let e=arguments[0];if(th(arguments[2]))return Ck(e,arguments[1],arguments[2],arguments[3]);let t=arguments[1],n=arguments[2];return r=>Ck(e,t,r,n)},Ck=(e,t,n,r)=>_h(i=>{if(e.state._tag===`Closed`)return og;if(r?.onlyIfMissing===!0&&vk(e,t))return ch(xk);let a=bu(i,n,r?.startImmediately??!0,!0);return hk(e,t,a,r),w(a)}),wk=`~effect/Match/Matcher`,Tk={[wk]:{_input:i,_filters:i,_remaining:i,_result:i,_return:i,_args:i},_tag:`TypeMatcher`,add(e){return Ek(this.select,[...this.cases,e])},pipe(){return e(this,arguments)}};function Ek(e,t){let n=Object.create(Tk);return n.select=e,n.cases=t,n}var Dk={[wk]:{_input:i,_filters:i,_result:i,_return:i,_flavor:i},_tag:`ValueMatcher`,add(e){return yi(this.value)?this:e._tag===`When`&&e.guard(this.provided)===!0||e._tag===`Not`&&e.guard(this.provided)===!1?Ok(this.provided,pi(e.evaluate(this.provided))):this},pipe(){return e(this,arguments)}};function Ok(e,t){let n=Object.create(Dk);return n.provided=e,n.value=t,n}var kk=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),Ak=e=>{if(typeof e==`function`)return e;if(Array.isArray(e)){let t=e.map(Ak),n=t.length;return e=>{if(!Array.isArray(e))return!1;for(let r=0;r<n;r++)if(t[r](e[r])===!1)return!1;return!0}}if(typeof e==`object`&&e){let t=Reflect.ownKeys(e).map(t=>[t,Ak(e[t])]),n=t.length;return e=>{if(typeof e!=`object`||!e)return!1;for(let r=0;r<n;r++){let[n,i]=t[r];if(!(n in e)||i(e[n])===!1)return!1}return!0}}return t=>t===e},jk=e=>Ok(e,mi(e)),Mk=r(2,(e,t)=>Fk(t)(Ek(i,[]))(e)),Nk=(e,t)=>n=>n.add(kk(Ak(e),t)),Pk=e=>t=>{let n=kk(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},Fk=(e=>t=>{let n=Pk(e)(t);return e=>zk(n(e))})(`_tag`),Ik=e=>t=>{let n=Lk(t);return _i(n)?n._tag===`Success`?n.success:e(n.failure):(...t)=>{let r=n(...t);return yi(r)?r.success:e(r.failure,...t)}},Lk=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?pi(t.evaluate(r,...n)):mi(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 pi(t.evaluate(r,...n))}return mi(r)}},Rk=`effect/match/Match/exhaustive: absurd`,zk=e=>{let t=Lk(e);if(_i(t)){if(yi(t))return t.success;throw Error(Rk)}return(...e)=>{let n=t(...e);if(yi(n))return n.success;throw Error(Rk)}},Bk=jk,Vk=Mk,Hk=Nk,Uk=ee,Wk=te,Gk=ie,Kk=Ik,qk={"~effect/Ref":{_A:i},...Rt,toJSON(){return{_id:`Ref`,ref:this.ref}}},Jk=e=>{let t=Object.create(qk);return t.ref=aD(e),t},Yk=e=>ch(()=>Jk(e)),Xk=e=>ch(()=>e.ref.current),Zk=r(2,(e,t)=>ch(()=>oD(e.ref,t))),Qk=r(2,(e,t)=>ch(()=>{let[n,r]=t(e.ref.current);return e.ref.current=r,n})),$k=r(2,(e,t)=>ch(()=>{e.ref.current=t(e.ref.current)})),eA=r(2,(e,t)=>ch(()=>e.ref.current=t(e.ref.current))),tA=r(2,(e,t)=>e===void 0?void 0:t(e)),nA=`~effect/SynchronizedRef`,rA={...Rt,[nA]:nA,toJSON(){return{_id:`SynchronizedRef`,value:this.backing.ref.current}}},iA=e=>{let t=Object.create(rA);return t.semaphore=GD(1),t.backing=Jk(e),t},aA=e=>ch(()=>iA(e)),oA=e=>e.backing.ref.current,sA=r(2,(e,t)=>e.semaphore.withPermit(sh(()=>Th(t(oA(e)),([t,n])=>(e.backing.ref.current=n,t))))),H=j.check(GT(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u,{message:`Expected a full GitHub repo name (owner/name)`})).pipe(I(`RepositoryName`)),cA=j.check(GT(/^[^\s-]\S*$/u,{message:`Expected a Git revision without whitespace or a leading dash`})).pipe(I(`RepositoryRevision`)),lA=j.check(GT(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u,{message:`Expected a 40- or 64-character lowercase Git object ID`})).pipe(I(`CommitSha`)),uA=e=>e.replaceAll(/[^A-Za-z0-9_.-]/gu,`_`),dA=e=>{let t=e.indexOf(`/`);return{owner:e.slice(0,t),name:e.slice(t+1)}},fA=e=>e.toLowerCase(),pA=j.check(GT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a project slug`})).pipe(I(`ProjectId`)),mA=M({message:j}),hA=()=>document.cookie.split(`; `).find(e=>e.startsWith(`usine_csrf=`))?.slice(11)??``,gA=async(e,t,n={})=>{let r={method:n.method??`GET`,credentials:`same-origin`,headers:{"content-type":`application/json`,"x-usine-csrf":hA()}};n.body!==void 0&&(r.body=JSON.stringify(n.body));let i=await fetch(e,r);i.status===401&&!e.startsWith(`/api/auth/`)&&window.location.replace(`/sign-in`);let a=await i.json();if(!i.ok)throw Error(nT(mA)(a).message);return nT(t)(a)},_A=M({ok:yT}),vA=j.check(GT(/\S/u,{message:`Expected a non-blank model ID`})).pipe(I(`ModelId`)),yA=jT([`claude`,`codex`,`pi`]),bA=jT([`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),xA=class extends B(`Agent/BrainSpec`)({harness:yA,model:vA,effort:bA}){},SA=j.check(GT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case agent name`})).pipe(I(`AgentName`)),CA=j.check(GT(/\S/u,{message:`Expected a non-blank agent persona`})).pipe(I(`AgentPersona`)),wA=class extends B(`Agent`)({name:SA,brain:xA,parentModel:AE(vA),parentEffort:ME(bA),persona:CA}){},TA=(e,t)=>gr([e.parentModel,t]),EA=(e,t)=>mr(gr([e.parentEffort,t]),()=>e.brain.effort),DA=R.pipe(I(`LoopName`)),OA=[`none`,`required`],kA=jT(OA),AA=[`write`,`read`],jA=jT(AA),MA=j.check(GT(/^\S(?:.*\S)?$/u,{message:`Expected a GitHub label name without surrounding whitespace`}),aE(50,{message:`Expected a GitHub label name of at most 50 characters`})).pipe(I(`GitHubLabelName`)),NA=e=>e.toLowerCase(),PA=j.check(GT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex GitHub label color without #`})).pipe(I(`GitHubLabelColor`)),FA=j.check(aE(100,{message:`Expected a GitHub label description of at most 100 characters`})),IA=class extends B(`@usine/config/DeclaredLabel`)({name:MA,color:ME(PA),description:ME(FA)}){},U=Symbol.for(`drizzle:entityKind`),LA=new WeakMap;function RA(e){let t=new Set;for(let n=e;n;n=Object.getPrototypeOf(n))U in n&&t.add(n[U]);return LA.set(e,t),t}var zA=Function.prototype[Symbol.hasInstance];function W(e,t){if(zA.call(t,e))return!0;if(typeof e!=`object`||!e)return!1;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`&&(LA.get(n)??RA(n)).has(t[U])}function BA(e){if(typeof e!=`object`||!e)return;let t=Object.getPrototypeOf(e)?.constructor;if(typeof t==`function`)return LA.get(t)??RA(t)}var VA=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}},HA=Symbol.for(`drizzle:Name`),UA=Symbol.for(`drizzle:Schema`),WA=Symbol.for(`drizzle:Columns`),GA=Symbol.for(`drizzle:ExtraConfigColumns`),KA=Symbol.for(`drizzle:OriginalName`),qA=Symbol.for(`drizzle:BaseName`),JA=Symbol.for(`drizzle:CacheKey`),YA=Symbol.for(`drizzle:IsAlias`),XA=Symbol.for(`drizzle:Qualifier`),ZA=Symbol.for(`drizzle:ExtraConfigBuilder`),QA=Symbol.for(`drizzle:IsDrizzleTable`),$A=class{static[U]=`Table`;static[Symbol.hasInstance](e){return W(e,this)}static Symbol={Name:HA,Schema:UA,OriginalName:KA,Columns:WA,ExtraConfigColumns:GA,BaseName:qA,IsAlias:YA,ExtraConfigBuilder:ZA,CacheKey:JA};[HA];[KA];[UA];[WA];[GA];[qA];[JA];[YA]=!1;[QA]=!0;[ZA]=void 0;constructor(e,t,n){this[HA]=this[KA]=e,this[UA]=t,this[qA]=n,this[JA]=t?`${t}.${e}`:e}};function ej(e){return e[HA]}var tj=Symbol.for(`drizzle:OriginalColumn`),nj=e=>e;nj.isNoop=!0;var rj=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=nj;mapToDriverValue=nj;postBuild(){return this}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}[tj](){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(`)},ij=Symbol.for(`drizzle:ViewBaseConfig`),aj=Symbol.for(`drizzle:IsDrizzleView`),oj=class{static[U]=`View`;static[Symbol.hasInstance](e){return W(e,this)}[ij];[aj]=!0;get[HA](){return this[ij].name}get[UA](){return this[ij].schema}get[YA](){return this[ij].isAlias}get[KA](){return this[ij].originalName}get[WA](){return this[ij].selectedFields}constructor({name:e,schema:t,selectedFields:n,query:r}){this[ij]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}},sj=class{static[U]=`Subquery`;static[Symbol.hasInstance](e){return W(e,this)}get[HA](){return this._.alias}get[UA](){}get[KA](){return this._.alias}get[YA](){return!1}get[WA](){return this._.selectedFields}constructor(e,t,n,r=!1){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r}}},cj=class extends sj{static[U]=`WithSubquery`};function lj(e){return e!=null&&typeof e.getSQL==`function`}var uj=class e{queryChunks;static[U]=`SQL`;static[Symbol.hasInstance](e){return W(e,this)}decoder=vj;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=mj(f);if(hj(f,p,q.string))i.sql+=f.value??``;else if(hj(f,p,q.sql))this.collectSQL(f.queryChunks,t,n,r||f.shouldInlineParams,i,a,void 0);else if(hj(f,p,q.name))i.sql+=s(f.value);else if(f!==void 0){if(hj(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[$A.Symbol.Schema];i.sql+=f.isAlias?s(f.name):f.table[YA]||t===void 0?s(f.table[$A.Symbol.Name])+`.`+s(e):s(t)+`.`+s(f.table[$A.Symbol.Name])+`.`+s(e)}else if(hj(f,p,q.param)){let e=f.value,o=mj(e);if(hj(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&&mj(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(hj(f,p,q.placeholder))i.sql+=c(n.value++,f),a.push(f);else if(hj(f,p,q.table)){let e=f[$A.Symbol.Schema],t=f[$A.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[YA]?s(t):s(e)+`.`+s(t)}else if(hj(f,p,q.view)){let e=f[ij].schema,t=f[ij].name;i.sql+=e===void 0||f[ij].isAlias?s(t):s(e)+`.`+s(t)}else if(hj(f,p,q.aliased)&&f.fieldAlias!==void 0)i.sql+=(f.origin===void 0?``:s(f.origin)+`.`)+s(f.fieldAlias);else if(hj(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&&mj(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=mj(d);f===q.other?this.collectBoundValue(d,o[u],c[u],t,n,r,i,a):hj(d,f,q.string)?i.sql+=d.value??``:this.collectSQL([f===q.sql?d:new bj(d,o[u])],t,n,r,i,a,void 0)}i.sql+=`)`}else if(hj(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(lj(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)),mj(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},dj=new WeakMap,fj=Symbol(`drizzle:chunkKind`);function pj(e,t){let n=t.has(G[U])?q.string:t.has(uj[U])?q.sql:t.has(gj[U])?q.name:t.has(rj[U])?q.column:t.has(bj[U])?q.param:t.has(Cj[U])?q.placeholder:t.has($A[U])?q.table:t.has(oj[U])?q.view:t.has(uj.Aliased[U])?q.aliased:t.has(sj[U])?q.subquery:t.has(xj[U])?q.valueRows:q.other;return dj.set(e,n),n!==q.other&&Object.defineProperty(e.prototype,fj,{value:n}),n}function mj(e){if(typeof e!=`object`||!e)return q.other;let t=e[fj];if(t!==void 0)return t;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`?dj.get(n)??pj(n,BA(e)):q.other}function hj(e,t,n){return t===n}var gj=class{value;static[U]=`Name`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e){this.value=e}getSQL(){return new uj([this])}};function _j(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}var vj={mapFromDriverValue:e=>e};vj.mapFromDriverValue.isNoop=!0;var yj={mapToDriverValue:e=>e};yj.mapToDriverValue.isNoop=!0,{...vj,...yj};var bj=class{value;encoder;codec;static[U]=`Param`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e,t=yj,n){this.value=e,this.encoder=t,this.codec=n}getSQL(){return new uj([this])}},xj=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=mj(o);r.push(s===q.sql||s===q.string?o:new bj(o,t[a]))}return r.push(K[`)`]),new uj(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 uj(n)}(function(e){function t(){return new uj([])}e.empty=t;function n(e){return new uj(e)}e.fromList=n;function r(e){return new uj([new G(e)])}e.raw=r;function i(e,t){let{length:n}=e;if(t===void 0||n===0)return new uj(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 uj(r)}e.join=i;function a(e){return new gj(e)}e.identifier=a;function o(e){return new Cj(e)}e.placeholder=o;function s(e,t){return new bj(e,t)}e.param=s;function c(e){let t=Sj(e);if(t.length)return J.raw(t)}e.comment=c})(J||={});function Sj(e){let t=Sj.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})(Sj||={}),(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})(uj||={});var Cj=class{name;static[U]=`Placeholder`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}getSQL(){return new uj([this])}};function wj(e){let t=e.queryChunks,n;for(let e=0;e<t.length;++e){let r=t[e];W(r,rj)&&((n??=[...t])[e]=J.identifier(r.name))}if(!n)return e;let r=new uj(n);return r.decoder=e.decoder,r.shouldInlineParams=e.shouldInlineParams,r}function Tj(e,t){for(let n=0;n<e.length;++n){let r=e[n];switch(mj(r)){case q.table:t.add(r[JA]);break;case q.sql:Tj(r.queryChunks,t);break;case q.param:{let e=r.value;mj(e)===q.sql&&Tj(e.queryChunks,t);break}case q.subquery:Tj(r._.sql.queryChunks,t);break;case q.valueRows:Tj(r.cells,t);break;case q.other:case q.aliased:Array.isArray(r)?Tj(r,t):lj(r)&&Tj(r.getSQL().queryChunks,t)}}}rj.prototype.getSQL=function(){return new uj([this])},G.prototype.getSQL=function(){return new uj([this])},sj.prototype.getSQL=function(){return new uj([this])};function Ej(e,t){Object.defineProperty(e,XA,{get(){let e=t(this);return Object.defineProperty(this,XA,{value:e,enumerable:!1,configurable:!0,writable:!0}),e},configurable:!0})}function Dj(e,t){return new uj(e===void 0?[new gj(t)]:[new gj(e),K[`.`],new gj(t)])}Ej($A.prototype,e=>Dj(e[UA],e[HA])),Ej(oj.prototype,e=>Dj(e[ij].schema,e[ij].name)),Ej(sj.prototype,e=>new gj(e._.alias));function Oj(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 kj=Object.getPrototypeOf(()=>null).constructor;function Aj(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(`
15
+ `)}\n\t`:``}for (let i = 0; i < length; ++i) {
16
+ ${r.join(`
17
+ `)}
18
+ }`}function jj(e,t){let n=`\t"use strict";
19
+ const { columns } = this;
20
+ const { length } = rows;
21
+ const mapped = new Array(length);
22
+ ${Aj(e,t)}
23
+ return mapped;
24
+ //# sourceURL=drizzle:jit-query-mapper`;return Object.assign(new kj(`rows`,n).bind({columns:e}),{body:`function jitQueryMapper (rows) {\n${n}\n}`})}function Mj(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?Oj(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 Nj(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,rj))r.push({path:s,field:o,fieldType:`Column`,codec:n?.get(o,`normalize`),arrayDimensions:o.dimensions,column:o});else if(W(o,uj)){let e=Pj(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,uj.Aliased)){let e=Pj(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,sj)){let e,t=Object.values(o._.selectedFields)[0],i;W(t,rj)?(e=t,i=t):W(t,uj)?(e=Pj(t),i=t.decoder):(e=Pj(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,$A)?Nj(o[$A.Symbol.Columns],s,n,r):Nj(o,s,n,r)}return r}function Pj(e){let{decoder:t}=e.getSQL();return hj(t,mj(t),q.column)?t:void 0}function Fj(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 Ij(e){return e[$A.Symbol.Columns]}function Lj(e){let t=mj(e);return hj(e,t,q.subquery)?e._.alias:hj(e,t,q.view)?e[ij].name:hj(e,t,q.sql)?void 0:e[$A.Symbol.IsAlias]?e[$A.Symbol.Name]:e[$A.Symbol.BaseName]}function Rj(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}typeof TextDecoder>`u`||new TextDecoder;function zj(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 Bj=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===tj&&!this.ignoreColumnAlias?()=>e:e[t]}},Vj=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=hj(n,mj(n),q.column)?new Proxy(n,this.columnHandler??=new Bj(this.view,this.ignoreColumnAlias)):lj(n)?n:new Proxy(n,this),r.set(n,i)),i}},Hj=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===XA)return this.qualifier??=J.identifier(this.alias);if(t===$A.Symbol.IsAlias)return!0;if(t===$A.Symbol.Name||this.replaceOriginalName&&t===$A.Symbol.OriginalName)return this.alias;if(t===$A.Symbol.Columns){let t=e[$A.Symbol.Columns];return t&&(hj(e,mj(e),q.view)?this.aliasSelection(t,n):this.getProxiedColumns(t,n))}if(t===ij){let t=e[ij],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(hj(r,mj(r),q.column)){let i=e[$A.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 Bj(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 Vj(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}},Uj=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=mj(n);return hj(n,a,q.column)?i=new Proxy(n,this.columnHandler??=new Bj(this.subquery,!0)):hj(n,a,q.aliased)?(i=n.clone(),i.isSelectionField=!0,i.origin=this.alias):i=n,r.set(n,i),i}},Wj=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===XA)return this.qualifier??=J.identifier(this.alias);if(t===$A.Symbol.IsAlias)return!0;if(t===$A.Symbol.Name)return this.alias;if(t===$A.Symbol.OriginalName)return e._.alias;if(t!==$A.Symbol.Schema)return t===`_`?this.config??={...e._,alias:this.alias,isWith:!0,selectedFields:this.aliasSelection(e,n)}:t===$A.Symbol.Columns?this.aliasSelection(e,n):e[t]}aliasSelection(e,t){return this.selection??=new Proxy(e._.selectedFields,new Uj(t,this.alias))}},Gj=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===tj?()=>e:e[t]}};function Kj(e,t){return hj(e,mj(e),q.subquery)?new Proxy(e,new Wj(t)):new Proxy(e,new Hj(t,!1,!1))}function qj(e){let t=e[$A.Symbol.Schema],n=J.identifier(e[$A.Symbol.OriginalName]);return t?J`${J.identifier(t)}.${n} ${e}`:J`${n} ${e}`}function Jj(e,t){return new Proxy(e,new Gj(t))}rj.prototype.as=function(e){return Jj(this,e)};function Yj(e){return e[tj]()}var Xj=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 Zj(e,t){if(_j(t)&&!lj(e)){let n=mj(e);if(n!==q.param&&n!==q.placeholder&&n!==q.column&&n!==q.table&&n!==q.view)return new bj(e,t)}return e}var Qj=(e,t,n)=>new uj([e,t,Zj(n,e)]),Y=(e,t)=>Qj(e,K[` = `],t),$j=(e,t)=>Qj(e,K[` <> `],t),eM=(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 uj(n)};function tM(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new uj(t):eM(t,K[`) and (`])}function nM(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new uj(t):eM(t,K[`) or (`])}function rM(e){if(e)return W(e,uj)?J`not (${e})`:J`not ${e}`}var iM=(e,t)=>Qj(e,K[` > `],t),aM=(e,t)=>Qj(e,K[` >= `],t),oM=(e,t)=>Qj(e,K[` < `],t),sM=(e,t)=>Qj(e,K[` <= `],t);function cM(e,t){return Array.isArray(t)?t.length===0?new uj([K[`1 = 0`]]):new uj([e,K[` in `],t.map(t=>Zj(t,e))]):Qj(e,K[` in `],t)}function lM(e,t){return Array.isArray(t)?t.length===0?new uj([K[`1 = 1`]]):new uj([e,K[` not in `],t.map(t=>Zj(t,e))]):Qj(e,K[` not in `],t)}function uM(e){return J`(${e} is null)`}function dM(e){return J`(${e} is not null)`}function fM(e){return J`exists ${e}`}function pM(e){return J`not exists ${e}`}function mM(e,t,n){return J`${e} between ${Zj(t,e)} and ${Zj(n,e)}`}function hM(e,t,n){return J`${e} not between ${Zj(t,e)} and ${Zj(n,e)}`}function gM(e,t){return J`${e} like ${t}`}function _M(e,t){return J`${e} not like ${t}`}function vM(e,t){return J`${e} ilike ${t}`}function yM(e,t){return J`${e} not ilike ${t}`}function bM(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContains requires at least one value`);let n=Zj(t,e),r=J`${Array.isArray(n)?new bj(n):n}`;return J`${e} @> ${r}`}return J`${e} @> ${Zj(t,e)}`}function xM(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContained requires at least one value`);let n=Zj(t,e),r=J`${Array.isArray(n)?new bj(n):n}`;return J`${e} <@ ${r}`}return J`${e} <@ ${Zj(t,e)}`}function SM(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayOverlaps requires at least one value`);let n=Zj(t,e),r=J`${Array.isArray(n)?new bj(n):n}`;return J`${e} && ${r}`}return J`${e} && ${Zj(t,e)}`}function CM(e){return J`${e} asc`}function wM(e){return J`${e} desc`}var TM={and:tM,between:mM,eq:Y,exists:fM,gt:iM,gte:aM,ilike:vM,inArray:cM,arrayContains:bM,arrayContained:xM,arrayOverlaps:SM,isNull:uM,isNotNull:dM,like:gM,lt:oM,lte:sM,ne:$j,not:rM,notBetween:hM,notExists:pM,notLike:_M,notIlike:yM,notInArray:lM,or:nM,sql:J},EM={sql:J,asc:CM,desc:wM};function DM(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??vj;break;case`Nested`:o=vj;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){DM(o[t.key],!1,t.selection,!1,i);continue}DM(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 OM(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??vj;break;case`Nested`:a=vj;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?DM(s,!1,t.selection,!1,i):DM(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 kM({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){return(o=>t&&!o[0]?o[0]:a?OM(t?o[0]:o,t,e,n,r):DM(t?o[0]:o,t,e,n,r,i))}function AM(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=AM(_,`${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=AM(_,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 jM({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){let o=[],s=AM(e,`row`,`selection`,n,r,!a&&i,o,{n:0},!!a),c=[];c.push(` "use strict";
25
+ 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(`
26
+ `);return Object.assign(new kj(`rows`,l).bind({selection:e}),{body:`function jitRqbMapper (rows) {\n${l}\n}`})}function MM(e,t){let n=e[WA][t],r=mj(n);return hj(n,r,q.column)?n:new uj([e,K[`.`],J.identifier(hj(n,r,q.aliased)?n.fieldAlias:t)])}var NM=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 PM(e,t,n=[]){if(t===XM)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,Cj))return n.push(Y(e,t)),n;let r=Object.entries(t);if(!r.length)return;let i=new NM(n,K[`) and (`]);for(let[t,a]of r)if(a!==XM){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 (`]),PM(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 NM(n,t===`OR`?K[`) or (`]:K[`) and (`]);for(let t of r)o.open(),PM(e,t,n),o.close();o.finish(),i.close();continue}case`isNotNull`:case`isNull`:if(!a)continue;i.push(TM[t](e));continue;case`in`:i.push(TM.inArray(e,a));continue;case`notIn`:i.push(TM.notInArray(e,a));continue;default:i.push(TM[t](e,a));continue}}return i.finish()?n:void 0}function FM(e,t,n={},r={},i,a=0,o=[]){if(t===XM)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 NM(o,K[`) and (`]),l=!1,u=t=>{FM(e,t,n,r,i,a,o).hasRelationFilters&&(l=!0)};for(let[t,d]of s)if(d!==XM){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,TM):d.getSQL();if(t===XM)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 NM(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[WA],t)&&e[WA][t]){c.open(),PM(MM(e,t),d,o),c.close();continue}let s=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!s)throw new VA({message:`Unknown relational filter field: "${t}"`});i&&(JM(i,s.targetTable),JM(i,s.throughTable));let u=Kj(s.targetTable,`f${a}`),f=s.throughTable?Kj(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 `]),YM(u,o),f&&(o.push(K[` inner join `]),YM(f,o),o.push(K[` on `]));let{filter:g}=UM(s,e,u,f,[],o);o.push(K[` where `]);let _=new NM(o,K[`) and (`]);if(_.pushChunks(g),!m){_.open();let e=FM(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 IM=new Set([`min`,`max`,`count`,`avg`,`first`]);function LM(e,t){if(typeof e!=`string`)throw new VA({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 VA({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 VA({message:`Invalid order "${t}": malformed value "${e}", expected "${r}" or "${r}(<aggregate>)"`});let i=n[1].slice(0,-1);if(!IM.has(i))throw new VA({message:`Invalid order "${t}": unknown aggregate "${i}" in "${e}", expected one of: ${[...IM].join(`, `)}`});return{direction:r,aggregate:i}}function RM(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[WA],l)&&e[WA][l]){let{direction:n,aggregate:r}=LM(u,t);if(!!r!=!!o?.isAggregated)throw new VA({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=MM(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 NM(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 VA({message:`Unknown relational order field: "${t}"`});let f=d.relationType===`many`&&typeof u==`string`?LM(u,t):void 0,p=f?.aggregate===`count`?f.direction:void 0;if(typeof u!=`object`&&!p)throw new VA({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&&(JM(i,d.targetTable),JM(i,d.throughTable));let m=o?.depth??0,h=Kj(d.targetTable,`o${m}`),g=d.throughTable?Kj(d.throughTable,`ot${m}`):void 0,_=o?[...o.from,K[` cross join `]]:[];YM(h,_),g&&(_.push(K[` inner join `]),YM(g,_),_.push(K[` on `]));let{filter:v}=UM(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 NM(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 RM(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 zM(e,t,n={},r={},i,a=`limit`,o=[]){let s=o.length;if(typeof t==`function`){let n=t(e,EM);if(!n)return;let r=mj(n);if(hj(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),mj(t)!==q.sql&&o.push(K[` asc`])}else hj(n,r,q.column)&&o.push(n,K[` asc`]);return o.length>s?o:void 0}return RM(e,t,n,r,i,a,void 0,o,s),o.length>s?o:void 0}function BM(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:TM.sql}):c;if(!t)continue;let l=t.getSQL(),u=n?Pj(l):void 0,d=u&&(!r||!u.jsonSelectIdentifier)?new uj([n.apply(u,r?`castInJson`:`cast`,new uj([K[`(`],l,K[`)`]])),K[` as `],J.identifier(s)]):new uj([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 VM({_:{column:e,key:t}}){let n=mj(e);return J.identifier(hj(e,n,q.column)?e.name:hj(e,n,q.aliased)?e.fieldAlias:t)}function HM(e,t,n,r,i,a){e.open(),t.push(n,K[`.`],VM(r),K[` = `],i,K[`.`],VM(a)),e.close()}function UM(e,t,n,r,i=[],a=[]){let o=e.isFilterReversed?t:n,s=t[XA],c=n[XA],l=r?.[XA],u=new NM(i,K[`) and (`]);if(e.through){let{sourceColumns:t,targetColumns:n,through:{source:r,target:d}}=e;u.open(),FM(o,e.where,{},{},void 0,0,i),u.close();for(let e=0;e<t.length;++e)HM(u,i,s,t[e],l,r[e]);u.finish();let f=new NM(a,K[`) and (`]);for(let e=0;e<n.length;++e)HM(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)HM(u,i,s,d[e],c,f[e]);return u.open(),FM(o,e.where,{},{},void 0,0,i),u.close(),u.finish(),{filter:i}}function WM(e,t,n,r,i,a,o=[]){let s=new NM(o,K[`) and (`]),c=!1;return t&&`where`in t&&(s.open(),c=FM(e,t.where,n,r,i,0,o).hasRelationFilters,s.close()),s.pushChunks(a),{sql:s.finish()?o:void 0,hasRelationFilters:c}}function GM(e,t,n,r,i,a,o){a?e.push(i.apply(a,o?`castInJson`:`cast`,new uj([t,K[`.`],J.identifier(n)]))):e.push(t,K[`.`],J.identifier(n)),e.push(K[` as `],J.identifier(r))}function KM(e,t,n,r,i,a,o,s){let c,l,u,d=mj(t);if(hj(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 uj([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(hj(t,d,q.sql))c=Pj(t),u=`SQL`,GM(s,e,n,n,o,c,r);else if(hj(t,d,q.aliased))c=Pj(t),u=`SQL.Aliased`,GM(s,e,t.fieldAlias,n,o,c,r);else if(hj(t,d,q.subquery)){let i=Object.values(t._.selectedFields)[0],a=mj(i);hj(i,a,q.column)?(c=i,l=i):hj(i,a,q.aliased)?(c=Pj(i),l=i.sql.decoder):hj(i,a,q.sql)&&(c=Pj(i),l=i.decoder),u=`Subquery`,GM(s,e,t._.alias,n,o,c,r)}else if(lj(t))c=Pj(t),u=`SQLWrapper`,GM(s,e,n,n,o,c,r);else throw new VA({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 qM(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[`, `]),KM(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[`, `]),KM(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[`, `]),KM(e,t[l],l,r,n,i,a,o));return o.length>c}function JM(e,t){let n=mj(t);if(e.usedTables!==void 0&&hj(t,n,q.table)){e.usedTables.add(t[JA]);return}if(!hj(t,n,q.subquery))return;let r=t._.alias,i=e.subqueries.get(r);if(i&&i._.sql!==t._.sql)throw new VA({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 YM(e,t=[]){if(!e[YA])return t.push(e),t;let n=e[UA];return n&&t.push(J.identifier(n),K[`.`]),t.push(J.identifier(e[KA]),K[` as `],e[XA]),t}var XM=Symbol.for(`drizzle:EmptyFilter`),ZM=j.check(GT(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u,{message:`Expected a GitHub login`})).pipe(I(`OperatorLogin`)),QM=li(`@usine/core/ActingMember`,{defaultValue:y}),$M=R.pipe(I(`AttentionRevision`)),eN=class extends B(`@usine/engine/AttentionKey`)({id:R,revision:$M}){};B(`@usine/engine/AttentionAcknowledgement`)({...eN.fields,dismissedBy:AE(ZM),dismissedAt:kE});var tN=e=>{let t=M(e),n=new Set(Object.keys(e)),r=TT(j.check(WT(e=>!n.has(e))),mT.annotate({message:`Unexpected key`}));return t.rebuild(ET(t,[r]).ast)},nN=R.pipe(I(`EventId`)),rN=R.pipe(I(`DedupKey`)),iN=class extends B(`Event`)({id:nN,dedupKey:rN,payload:JE,receivedAt:OE}){},aN=class extends V(`CancelReason/OperatorCanceled`)(`OperatorCanceled`,{by:AE(ZM).pipe(RT(w(null)),IT(w(y())))}){},oN=class extends V(`CancelReason/Superseded`)(`Superseded`,{by:nN}){},sN=class extends V(`CancelReason/Revoked`)(`Revoked`,{}){},cN=P([aN,oN,sN]),lN=class extends V(`RunState/Pending`)(`Pending`,{}){},uN=class extends V(`RunState/Waiting`)(`Waiting`,{}){},dN=class extends V(`RunState/Queued`)(`Queued`,{}){},fN=class extends V(`RunState/Running`)(`Running`,{}){},pN=class extends V(`RunState/Succeeded`)(`Succeeded`,{}){},mN=class extends V(`RunState/Failed`)(`Failed`,{}){},hN=class extends V(`RunState/Canceled`)(`Canceled`,{reason:cN}){},gN=P([lN,uN,dN,fN]),_N=P([...gN.members,pN,mN,hN]),vN=P([lN,uN,dN]),yN=P([lN,dN]),bN=Xw(gN),xN=Xw(vN),SN=Xw(yN),CN=e=>({canApprove:e._tag===`Waiting`,canRetry:e._tag===`Failed`,canResolveFailure:e._tag===`Failed`,canCancel:bN(e),canRunAgain:e._tag===`Succeeded`||e._tag===`Canceled`}),wN=()=>(...e)=>e,TN=wN()(`Pending`,`Waiting`,`Queued`,`Running`),EN=wN()(`Pending`,`Waiting`,`Queued`,`Running`,`Succeeded`,`Failed`,`Canceled`),DN=wN()(`Pending`,`Waiting`,`Queued`),ON=e=>new uN,kN=e=>new dN,AN=e=>new fN,jN=e=>new pN,MN=e=>new mN,NN=e=>new fN,PN=(e,t=y())=>new hN({reason:new aN({by:t})}),FN=(e,t)=>new hN({reason:new oN({by:t})}),IN=e=>new hN({reason:new sN}),LN=R.pipe(I(`RunId`)),RN=class extends B(`Run`)({id:LN,eventId:nN,loop:DA,state:_N,openedAt:OE}){},zN=class extends V(`StepResult/Commit`)(`Commit`,{sha:lA,summary:R}){},BN=class extends V(`StepResult/PullRequest`)(`PullRequest`,{number:L.check($T(1)),url:mE}){},VN=jT([`issue-comment`,`review`,`review-comment`]),HN=class extends V(`StepResult/Comment`)(`Comment`,{url:mE,kind:VN,at:ME(kE)}){},UN=P([zN,BN,HN]),WN=class extends B(`StepResult`)({message:R,facts:N(UN)}){},GN=R.pipe(I(`StepName`)),KN=class extends B(`Step`)({runId:LN,name:GN,result:z(WN)}){},qN=j.check(GT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case worker name`})).pipe(I(`WorkerName`)),JN=jT([`local`,`exe.dev`,`ssh`,`cloudflare`]),YN=j.check(GT(/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\[bot\]$/u,{message:`Expected a GitHub bot login: <slug>[bot]`})).pipe(I(`BotLogin`)),XN=L.check($T(1)).pipe(I(`BotUserId`)),ZN=class extends B(`BotAccount`)({login:YN,id:XN}){get noreplyEmail(){return`${String(this.id)}+${this.login}@users.noreply.github.com`}},QN=j.check(GT(/^(?:[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(I(`SshDestination`)),$N=L.check(eE({minimum:1,maximum:65535})).pipe(I(`SshPort`)),eP=j.check(GT(/^(?:\/|~\/)[!-~]+$/u,{message:`Expected an absolute or ~/ key path without spaces or control characters`})).pipe(I(`SshIdentityFile`)),tP=j.check(GT(/^(?:\/[!-.0-~]+)+$/u,{message:`Expected an absolute directory without spaces, control characters, or a trailing /`})).pipe(I(`WorkerRoot`)),nP=j.check(GT(/^(?:[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(I(`GatewayDomain`)),rP=L.check(eE({minimum:1,maximum:65535})).pipe(I(`GatewayAdminPort`)),iP=jT([`anthropic`,`openai`]),aP=jT([`api-key`,`subscription`]),oP=j.check(GT(/^[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(I(`ContainerImage`)),sP=j.check(GT(/^[0-9a-f]{64}$/u,{message:`Expected a container ID of 64 lowercase hex digits`})).pipe(I(`ContainerId`)),cP=KT.check(QT(0)).pipe(I(`ContainerCpus`)),lP=L.check($T(256)).pipe(I(`ContainerMemoryMib`)),uP=L.check($T(64)).pipe(I(`ContainerPids`)),dP=class extends B(`ContainerLimits`)({cpus:cP,memoryMib:lP,pids:uP}){},fP=[`cpus`,`memoryMib`,`pids`],pP=jT([`lite`,`basic`,`standard-1`,`standard-2`,`standard-3`,`standard-4`]),mP=j.check(GT(/^[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(I(`CloudflareImageName`)),hP=jT([`anthropic`,`openai`]),gP=jT([`hetzner`,`boat`]),_P=j.check(GT(/^[A-Za-z0-9_-]{1,64}$/u,{message:`Expected a provider machine ID`})).pipe(I(`MachineId`)),vP=j.check(GT(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner server type, such as cx33`})).pipe(I(`HetznerServerType`)),yP=j.check(GT(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner location, such as nbg1`})).pipe(I(`HetznerLocation`)),bP=j.check(GT(/^[!-~](?:[ -~]{0,253}[!-~])?$/u,{message:`Expected a Hetzner image ID, snapshot description, or image name`})).pipe(I(`HetznerImage`)),xP=j.check(GT(/^[!-~](?:[ -~]{0,126}[!-~])?$/u,{message:`Expected a Hetzner resource name without control characters`})).pipe(I(`HetznerResourceName`)),SP=/^(?:[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,CP=TT(j,j.check(GT(/^(?:[a-z0-9A-Z](?:[-_.a-z0-9A-Z]{0,61}[a-z0-9A-Z])?)?$/u,{message:`Expected a Hetzner label value`}))).check(WT(e=>{let t=Object.keys(e),n=t.find(e=>!SP.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}"`})),wP=j.check(GT(/^[a-z_][a-z0-9_-]{0,31}$/u,{message:`Expected a Unix user name`})).pipe(I(`SshUser`)),TP=jT([`small`,`default`,`large`,`xlarge`]),EP=j.check(GT(/^[a-z0-9][a-z0-9-]{0,62}$/u),WT(e=>![`latest`,`tree`,`pull`,`rm`,`save`,`current`,`self`,`new`].includes(e),{message:`Expected a non-reserved Boat snapshot name`})).pipe(I(`BoatSnapshotName`)),DP=j.check(GT(/^100\.(?:6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/u,{message:`Expected a Tailscale IPv4 address in 100.64.0.0/10`})).pipe(I(`TailnetAddress`)),OP=L.check(eE({minimum:1,maximum:2147483})).pipe(I(`ProvisionerSeconds`)),kP=e=>OP.pipe(RT(w(e)),IT(w(OP.make(e)))),AP=class extends B(`ProvisionerTimings`)(M({sshWait:kP(600),creationBackoffMin:kP(30),creationBackoffMax:kP(600),machineCheckInterval:kP(86400)}).check(WT(e=>e.creationBackoffMin<=e.creationBackoffMax||`Creation backoff minimum must not exceed its maximum`))){},jP=R.pipe(I(`AgentSessionId`)),MP=L.check($T(0)).pipe(I(`TokenCount`)),NP=L.check($T(1)),PP=NP.pipe(I(`ChildSessionBudget`)),FP=NP.pipe(I(`ChildSessionCount`)),IP=P([class extends V(`Agent/ParentSession`)(`ParentSession`,{id:jP,agent:SA,brain:xA}){},class extends V(`Agent/ChildSession`)(`ChildSession`,{id:jP,parentId:jP,agent:SA,brain:xA,gatewayCredential:ME(aP).pipe(IT(w(y())))}){}]),LP=R.pipe(I(`HarnessSessionId`)),RP=class extends B(`Agent/HarnessSession`)({id:LP,cwd:R,home:ME(R).pipe(IT(w(y())))}){},zP=class extends V(`Agent/SessionStarted`)(`SessionStarted`,{session:IP,harnessSession:ME(RP).pipe(IT(w(y())))}){},BP=class extends V(`Agent/TextOutput`)(`TextOutput`,{session:IP,text:R}){},VP=class extends V(`Agent/ToolStarted`)(`ToolStarted`,{session:IP,callId:R,tool:R,input:JE}){},HP=class extends V(`Agent/ToolFinished`)(`ToolFinished`,{session:IP,callId:R,tool:R,output:JE,isError:yT}){},UP=class extends V(`Agent/SessionFinished`)(`SessionFinished`,{session:IP}){},WP=class extends V(`Agent/SessionIdle`)(`SessionIdle`,{session:IP}){},GP=class extends V(`Agent/SessionResumed`)(`SessionResumed`,{session:IP}){},KP=KT.check($T(0)).pipe(I(`UsdAmount`)),qP=L.check($T(0)),JP=class extends B(`Agent/TokenBreakdown`)({input:qP,cachedInput:qP,cacheWrite:qP,output:qP}){},YP=class extends V(`Agent/SessionTokensUpdated`)(`SessionTokensUpdated`,{session:IP,totalTokens:MP,costUsd:ME(KP).pipe(IT(w(y()))),breakdown:ME(JP).pipe(IT(w(y())))}){},XP=jT([`apiKeys`,`claudePlan`,`chatgptPlan`]),ZP=(e,t)=>{switch(e.harness){case`claude`:return Er(t,`api-key`)?`apiKeys`:`claudePlan`;case`codex`:return Er(t,`api-key`)?`apiKeys`:`chatgptPlan`;case`pi`:return e.model.startsWith(`openai-codex/`)?`chatgptPlan`:`apiKeys`}},QP=e=>Vk(e,{ParentSession:({brain:e})=>ZP(e,y()),ChildSession:({brain:e,gatewayCredential:t})=>ZP(e,t)}),$P=class extends B(`Agent/RateLimitWindow`)({usedPercent:vT,windowDurationMinutes:AE(vT),resetsAt:AE(kE)}){},eF=class extends B(`Agent/RateLimitsSnapshot`)({limitId:AE(j),limitName:AE(j),primary:AE($P),secondary:AE($P)}){},tF=R.pipe(I(`PoolLogin`)),nF=class extends V(`Agent/PoolRateLimitsUpdated`)(`PoolRateLimitsUpdated`,{session:IP,pool:XP,login:ME(tF).pipe(IT(w(y()))),rateLimits:eF}){},rF=NP.pipe(I(`ProviderRetries`)),iF=P([zP,BP,VP,HP,nF,UP,WP,GP,YP,class extends V(`Agent/ProviderRetrying`)(`ProviderRetrying`,{session:IP,message:R,retries:rF}){},class extends V(`Agent/ProviderRecovered`)(`ProviderRecovered`,{session:IP,retries:rF}){}]),aF=class extends WE(`AttemptFailure/GitHubPushFailure`)(`GitHubPushFailure`,{repository:H,ref:R,message:j}){},oF=class extends WE(`AttemptFailure/InfraFailure`)(`InfraFailure`,{message:j,cause:dE()}){},sF=class extends WE(`AttemptFailure/DefectFailure`)(`DefectFailure`,{message:j,cause:dE()}){},cF=class extends WE(`AttemptFailure/ProviderCapacityFailure`)(`ProviderCapacityFailure`,{message:R}){},lF=class extends WE(`AttemptFailure/AgentFailure`)(`AgentFailure`,{message:j}){},uF=class extends WE(`AttemptFailure/BlockedFailure`)(`BlockedFailure`,{message:R}){},dF=class extends WE(`AttemptFailure/QuestionFailure`)(`QuestionFailure`,{question:R}){},fF=jT([`wall-clock`,`tokens`]),pF=P([aF,oF,cF,sF,lF,uF,dF,class extends WE(`AttemptFailure/RunawayFailure`)(`RunawayFailure`,{ceiling:fF}){},class extends WE(`AttemptFailure/ChildSessionBudgetFailure`)(`ChildSessionBudgetFailure`,{maxChildren:PP,attemptedChildren:FP}){}]),mF=Xw(P([oF,cF])),hF=class extends V(`AttemptOutcome/Succeeded`)(`Succeeded`,{}){},gF=class extends V(`AttemptOutcome/Failed`)(`Failed`,{failure:pF}){},_F=class extends V(`AttemptOutcome/Canceled`)(`Canceled`,{}){},vF=P([hF,gF,_F]),yF=R.pipe(I(`SalvageRef`)),bF=(e,t)=>yF.make(`usine/salvage/${uA(e)}/${t}`),xF=class extends V(`AttemptSalvage/Pushed`)(`Pushed`,{ref:yF,commit:lA}){},SF=P([xF,class extends V(`AttemptSalvage/PartlyPushed`)(`PartlyPushed`,{ref:yF,commit:lA,path:R,message:j}){},class extends V(`AttemptSalvage/Retained`)(`Retained`,{path:R,commit:AE(lA),message:j,pushFailure:AE(aF).pipe(RT(w(null)),IT(w(y())))}){},class extends V(`AttemptSalvage/Rejected`)(`Rejected`,{path:R,commit:lA,message:j}){}]),CF=class extends V(`AttemptStart/Event`)(`Event`,{}){},wF=class extends V(`AttemptStart/Retry`)(`OperatorRetry`,{operator:AE(ZM)}){},TF=class extends V(`AttemptStart/EditAndRetry`)(`EditAndRetry`,{operator:AE(ZM)}){},EF=class extends V(`AttemptStart/InfraRetry`)(`InfraRetry`,{}){},DF=class extends V(`AttemptStart/ProviderRetry`)(`ProviderRetry`,{}){},OF=class extends V(`AttemptStart/AfterRestart`)(`AfterRestart`,{}){},kF=P([wF,TF]),AF=P([CF,wF,TF,EF,DF,OF]),jF=R.pipe(I(`AttemptId`)),MF=L.check($T(1)).pipe(I(`AttemptNumber`)),NF=MF.make(3),PF=j.check(GT(/\S/u,{message:`Expected non-blank task text`})).pipe(I(`AttemptTask`)),FF=jT([`cancel`,`failed`,`startup`]),IF=class extends B(`AttemptContext`)({task:PF,agent:wA,parentModel:AE(vA)}){},LF=class extends B(`FailureResolution`)(tN({resolvedAt:kE,operator:AE(ZM)})){},RF=L.check($T(1)),zF=class extends B(`OutOfMemoryKills`)({kills:RF,memoryMib:lP}){},BF=class extends B(`ContainerOutOfMemoryKills`)({container:sP,kills:RF,memoryMib:lP}){},VF=e=>new zF({kills:e.reduce((e,{kills:t})=>e+t,0),memoryMib:pee(e).memoryMib}),HF=class extends B(`Attempt`)({id:jF,runId:LN,stepName:GN,worker:qN,number:MF,brain:xA,task:PF,agent:SA,operatorIntervened:yT,parentModel:AE(vA),startedAt:OE,outcome:z(vF),endedAt:z(OE),salvage:z(SF),failureResolution:z(LF).pipe(IT(w(y()))),start:z(AF).pipe(IT(w(y()))),reattachedAt:z(OE).pipe(IT(w(y()))),comments:N(HN).pipe(IT(w([]))),outOfMemory:z(zF).pipe(IT(w(y())))}){},UF=class extends B(`AttemptWindow`)({attemptId:jF,startedAt:OE,endedAt:z(OE)}){},WF=e=>S(e.outcome)&&x(e.endedAt)?y():b(new UF({attemptId:e.id,startedAt:e.startedAt,endedAt:e.endedAt})),GF=e=>{let t=h_(e.startedAt);return t-t%1e3},KF=(e,t)=>pr(e.endedAt,{onNone:()=>!0,onSome:e=>t<=h_(e)}),zee=(e,t)=>{let n=h_(t);return GF(e)<=n&&KF(e,n)},Bee=(e,t)=>KF(e,GF(t))&&KF(t,GF(e)),qF=class extends B(`AttemptWindows`)({own:z(UF),overlapping:N(UF)}){},Vee=e=>mF(e.failure)&&e.number<e.maxAutoAttempts,JF=class extends B(`ProviderRetry`)(tN({nextAttempt:MF.check($T(2)),retryAt:kE,message:R})){},YF=(e,t)=>{if(e._tag!==`Running`)return y();let n=t.at(-1);if(n===void 0||n.number>=NF||x(n.outcome)||x(n.endedAt))return y();let r=n.outcome.value;return r._tag!==`Failed`||r.failure._tag!==`ProviderCapacityFailure`?y():b(new JF({nextAttempt:MF.make(n.number+1),retryAt:g_(n.endedAt.value,{minutes:n.number===1?2:5}),message:r.failure.message}))},XF=L.check($T(1)).pipe(I(`AttemptChannelSequence`)),ZF=[`inbound`,`outbound`],QF=jT(ZF),Hee=class extends B(`AttemptChannel/RunSpec`)({attemptId:jF,repository:H,revision:cA,baseCommit:lA,payload:JE,task:PF,agent:wA,parentModel:AE(vA),maxChildren:PP,parentEffort:bA,resume:AE(xF),conflictingSalvage:AE(xF).pipe(RT(w(null)),IT(w(y()))),preparedAt:AE(kE).pipe(RT(w(null))),botLogin:AE(YN).pipe(RT(w(null)))}){},$F=class extends V(`AttemptChannel/Started`)(`Started`,{parentModel:vA,conflictingSalvage:AE(xF).pipe(RT(w(null)),IT(w(y())))}){},eI=class extends V(`AttemptChannel/SessionEvent`)(`SessionEvent`,{event:iF}){},tI=class extends V(`AttemptChannel/Final`)(`Final`,{result:WN}){},Uee=class extends V(`AttemptChannel/Failed`)(`Failed`,{failure:pF}){},nI=class extends V(`AttemptChannel/Interrupted`)(`Interrupted`,{}){},rI=class extends V(`AttemptChannel/Steer`)(`Steer`,{message:R}){},iI=class extends V(`AttemptChannel/Interrupt`)(`Interrupt`,{}){},aI=class extends V(`AttemptChannel/Cancel`)(`Cancel`,{}){},oI=class extends V(`AttemptChannel/OperatorMessage`)(`OperatorMessage`,{message:R}){},sI=class extends V(`AttemptChannel/Release`)(`Release`,{}){},cI=P([rI,iI,oI,sI]),Wee=P([cI,aI]),lI=class extends V(`AttemptChannel/ParentTarget`)(`Parent`,{}){},uI=class extends V(`AttemptChannel/ChildTarget`)(`Child`,{sessionId:jP}){},dI=P([lI,uI]),fI=class extends B(`AttemptChannel/Intervention`)({operator:R,target:dI,action:cI}){},Gee=class extends B(`AttemptChannel/InterventionState`)({held:yT,paused:yT,queued:yT.pipe(RT(w(!1)),IT(w(!1)))}){},pI=class extends V(`AttemptChannel/InterventionApplied`)(`InterventionApplied`,{inputSequence:XF,intervention:fI,state:Gee}){},mI=class extends V(`AttemptChannel/InterventionRejected`)(`InterventionRejected`,{inputSequence:XF,intervention:fI,message:R}){},hI=class extends V(`AttemptChannel/WorkerUnresponsive`)(`WorkerUnresponsive`,{worker:qN,lastAnsweredAt:kE,reason:R,unansweredProbes:L.check($T(1)).pipe(RT(w(1)),IT(w(1)))}){},gI=class extends V(`AttemptChannel/WorkerResponsive`)(`WorkerResponsive`,{worker:qN,lastAnsweredAt:kE,recovered:yT.pipe(RT(w(!0)),IT(w(!0)))}){};P([hI,gI]);var Kee=P([$F,eI,tI,Uee,nI,pI,mI,hI,gI]),_I={version:pT(7),attemptId:jF,sequence:XF,sentAt:kE},vI=class extends V(`AttemptChannel/OutboundEnvelope`)(`OutboundEnvelope`,{..._I,payload:Kee}){},yI=class extends V(`AttemptChannel/InboundEnvelope`)(`InboundEnvelope`,{..._I,target:dI.pipe(RT(w({_tag:`Parent`}))),operator:R,payload:Wee}){},bI=P([vI,yI]),xI=R.pipe(I(`ItemKey`)),SI=L.check($T(1)).pipe(I(`ItemNumber`)),CI=L.check($T(1)).pipe(I(`CycleLimit`)),wI=L.check($T(0)).pipe(I(`CycleGeneration`)),TI=CI.make(3),EI=L.check($T(0)).pipe(I(`CycleCount`)),DI=class extends B(`LoopCycleCount`)(tN({loop:DA,admitted:EI,completed:EI}).check(WT(({admitted:e,completed:t})=>t<=e,{message:`Completed runs can't exceed admitted runs`}))){},OI=nN.pipe(I(`CycleBudgetAskId`)),kI=class extends B(`CycleBudgetAsk`)(tN({id:OI,itemKey:xI,repository:H,loop:DA,limit:CI,counts:kT(DI)}).check(WT(({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 EI.make(Math.max(...this.counts.map(({completed:e})=>e)))}},AI=[`ui`],jI=jT(AI),MI=class extends B(`ApprovalSource`)(tN({channel:jI,approver:AE(ZM)})){},NI=class extends B(`RunApproval`)({approvedAt:OE,source:z(MI)}){},PI=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 FI(e,this)}},FI=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[HA],...r,n[0].table[HA],...i];return e??`${a.join(`_`)}_fk`}isNameExplicit(){return!!this.reference().name}};function II(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 PI(t)}var LI=class extends Xj{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 PI(()=>{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))}},RI=class extends rj{static[U]=`SQLiteColumn`;table;constructor(e,t){super(e,t),this.table=e}},zI={},BI={cast:void 0,castInJson:void 0,castParam:void 0,normalize:void 0,normalizeInJson:void 0,normalizeParam:void 0},VI={cast:`cast`,castArray:`cast`,castInJson:`castInJson`,castArrayInJson:`castInJson`,castParam:`castParam`,castArrayParam:`castParam`,normalize:`normalize`,normalizeArray:`normalize`,normalizeInJson:`normalizeInJson`,normalizeArrayInJson:`normalizeInJson`,normalizeParam:`normalizeParam`,normalizeParamArray:`normalizeParam`},HI=class{resolveTypes;codecs;static[U]=`CodecsCollection`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t=zI){this.resolveTypes=e,this.codecs=t}itemCodecsCache=new Map;arrayCodecsCache=new Map;codecsOf(e,t){let n=t??e.codec;if(!n)return BI;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}:BI,i.set(n,a)}return a}get(e,t,n){return this.codecsOf(e,n)[VI[t]]}apply(e,t,n,r){let i=VI[t],a=this.codecsOf(e,r)[i];return a?i===`castParam`?a(n,e,e.dimensions):a(n,e.dimensions):n}},UI={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 WI(e){return UI[e]??e}var GI=typeof Buffer>`u`?new TextEncoder:void 0,KI=GI?e=>GI.encode(e):e=>Buffer.from(e),qI={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 JI(e,t){return qI[e]?.[t]}var YI=class extends LI{static[U]=`SQLiteBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteBigInt`)}build(e){return new XI(e,this.config)}},XI=class extends RI{static[U]=`SQLiteBigInt`;codec=`blob:bigint`;getSQLType(){return`blob`}mapToDriverValue=e=>KI(e.toString())},ZI=class extends LI{static[U]=`SQLiteBlobJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteBlobJson`)}build(e){return new QI(e,this.config)}},QI=class extends RI{static[U]=`SQLiteBlobJson`;codec=`blob:json`;getSQLType(){return`blob`}mapToDriverValue=e=>KI(JSON.stringify(e))},$I=class extends LI{static[U]=`SQLiteBlobBufferBuilder`;constructor(e){super(e,`object buffer`,`SQLiteBlobBuffer`)}build(e){return new eL(e,this.config)}},eL=class extends RI{static[U]=`SQLiteBlobBuffer`;codec=`blob`;getSQLType(){return`blob`}};function tL(e,t){let{name:n,config:r}=Rj(e,t);return r?.mode===`bigint`?new YI(n):r?.mode===`buffer`?new $I(n):new ZI(n)}var nL=class extends LI{static[U]=`SQLiteCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`SQLiteCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new rL(e,this.config)}},rL=class extends RI{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`?WI(n):void 0}getSQLType(){return this.sqlName}};function iL(e){return(t,n)=>{let{name:r,config:i}=Rj(t,n);return new nL(r,i,e)}}var aL=class extends LI{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()}},oL=class extends RI{static[U]=`SQLiteBaseInteger`;autoIncrement=this.config.autoIncrement;getSQLType(){return`integer`}},sL=class extends aL{static[U]=`SQLiteIntegerBuilder`;constructor(e){super(e,`number int53`,`SQLiteInteger`)}build(e){return new cL(e,this.config)}},cL=class extends oL{static[U]=`SQLiteInteger`;codec=`integer`},lL=class extends aL{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 uL(e,this.config)}},uL=class extends oL{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}},dL=class extends aL{static[U]=`SQLiteBooleanBuilder`;constructor(e,t){super(e,`boolean`,`SQLiteBoolean`),this.config.mode=t}build(e){return new fL(e,this.config)}},fL=class extends oL{static[U]=`SQLiteBoolean`;codec=`integer:boolean`;mode=this.config.mode;mapToDriverValue=e=>+!!e};function pL(e,t){let{name:n,config:r}=Rj(e,t);return r?.mode===`timestamp`||r?.mode===`timestamp_ms`?new lL(n,r.mode):r?.mode===`boolean`?new dL(n,r.mode):new sL(n)}var mL=class extends LI{static[U]=`SQLiteNumericBuilder`;constructor(e){super(e,`string numeric`,`SQLiteNumeric`)}build(e){return new hL(e,this.config)}},hL=class extends RI{static[U]=`SQLiteNumeric`;codec=`numeric`;getSQLType(){return`numeric`}},gL=class extends LI{static[U]=`SQLiteNumericNumberBuilder`;constructor(e){super(e,`number`,`SQLiteNumericNumber`)}build(e){return new _L(e,this.config)}},_L=class extends RI{static[U]=`SQLiteNumericNumber`;codec=`numeric:number`;mapToDriverValue=String;getSQLType(){return`numeric`}},vL=class extends LI{static[U]=`SQLiteNumericBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteNumericBigInt`)}build(e){return new yL(e,this.config)}},yL=class extends RI{static[U]=`SQLiteNumericBigInt`;codec=`numeric:bigint`;mapToDriverValue=String;getSQLType(){return`numeric`}};function bL(e,t){let{name:n,config:r}=Rj(e,t),i=r?.mode;return i===`number`?new gL(n):i===`bigint`?new vL(n):new mL(n)}var xL=class extends LI{static[U]=`SQLiteRealBuilder`;constructor(e){super(e,`number double`,`SQLiteReal`)}build(e){return new SL(e,this.config)}},SL=class extends RI{static[U]=`SQLiteReal`;codec=`real`;getSQLType(){return`real`}};function CL(e){return new xL(e??``)}var wL=class extends LI{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 TL(e,this.config)}},TL=class extends RI{static[U]=`SQLiteText`;codec=`text`;enumValues=this.config.enumValues;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:``}`}},EL=class extends LI{static[U]=`SQLiteTextJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteTextJson`)}build(e){return new DL(e,this.config)}},DL=class extends RI{static[U]=`SQLiteTextJson`;codec=`text:json`;getSQLType(){return`text`}mapToDriverValue=e=>JSON.stringify(e)};function X(e,t={}){let{name:n,config:r}=Rj(e,t);return r.mode===`json`?new EL(n):new wL(n,r)}function OL(){return{blob:tL,customType:iL,integer:pL,numeric:bL,real:CL,text:X}}function kL(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 AL(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 jL(e){return e===`snake_case`?kL:e===`camelCase`?AL:e=>e}var ML=Symbol.for(`drizzle:SQLiteInlineForeignKeys`),NL=class extends $A{static[U]=`SQLiteTable`;static Symbol=Object.assign({},$A.Symbol,{InlineForeignKeys:ML});[$A.Symbol.Columns];[ML]=[];[$A.Symbol.ExtraConfigBuilder]=void 0};function PL(e,t,n,r,i,a=e){let o=jL(i),s=new NL(e,r,a),c=typeof t==`function`?t(OL()):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[ML].push(...n.buildForeignKeys(r,s)),[e,r]})),u=Object.assign(s,l);return u[$A.Symbol.Columns]=l,u[$A.Symbol.ExtraConfigColumns]=l,n&&(u[NL.Symbol.ExtraConfigBuilder]=n),u}function FL(e){return(t,n,r)=>PL(t,n,r,void 0,e)}var IL=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 LL(e,this)}},LL=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 RL(e,t){return new IL(e,t)}var zL=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 BL(this.name,e,this.unique)}},BL=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 VL(this.config,e)}},VL=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 HL(e){return new zL(e,!1)}function UL(e){return new zL(e,!0)}function WL(...e){return e[0].columns?new GL(e[0].columns,e[0].name):new GL(e)}var GL=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 KL(e,this.columns,this.name)}},KL=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[NL.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}},qL=zj(e=>`"${e.replace(/"/g,`""`)}"`),JL={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 `)},YL=class{static[U]=`SQLiteDialect`;static[Symbol.hasInstance](e){return W(e,this)}codecs;mapperGenerators;constructor(e){this.codecs=new HI(WI,e?.codecs),this.mapperGenerators=e?.useJitMappers?{rows:jj,relationalRows:jM}:{rows:Mj,relationalRows:kM}}escapeName(e){return qL(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 uj(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[$A.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,uj)?e:J.param(e,s)}a[e]=e<i-1?J`${J.identifier(s.name)} = ${c}, `:J`${J.identifier(s.name)} = ${c}`}return new uj(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 uj([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=mj(r),s=r?hj(r,o,q.sql)||hj(r,o,q.subquery)?void 0:r[$A.Symbol.IsAlias]||r[$A.Symbol.Schema]===void 0?r[$A.Symbol.Name]:`${r[$A.Symbol.Schema]}.${r[$A.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(Yj(o).name):J.identifier(o.name):o.isAlias?Yj(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,rj)){let{table:e}=i;if((e[$A.Symbol.IsAlias]||e[$A.Symbol.Schema]===void 0?e[$A.Symbol.Name]:`${e[$A.Symbol.Schema]}.${e[$A.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 uj(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,rj)){let{table:e}=i;if((e[$A.Symbol.IsAlias]||e[$A.Symbol.Schema]===void 0?e[$A.Symbol.Name]:`${e[$A.Symbol.Schema]}.${e[$A.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 uj(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 uj(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,NL)?t.push(J`${new G(r.joinType)} join ${i[$A.Symbol.IsAlias]?qj(i):i}${a}`):t.push(J`${new G(r.joinType)} join ${i}${a}`),n<e.length-1&&t.push(K[` `])}return new uj(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,$A)&&e[$A.Symbol.IsAlias])return qj(e);if(W(e,oj)&&e[ij].isAlias){let t=J`${J.identifier(e[ij].originalName)}`;return e[ij].schema&&(t=J`${J.identifier(e[ij].schema)}.${t}`),J`${t} ${J.identifier(e[ij].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??Nj(t,void 0,this.codecs),h=mj(a),g=hj(a,h,q.subquery)?a._.alias:hj(a,h,q.view)?a[ij].name:hj(a,h,q.sql)?void 0:ej(a);for(let e of m)if(W(e.field,rj)&&ej(e.field.table)!==g&&!(e=>o?.some(({alias:t})=>t===(e[$A.Symbol.IsAlias]?ej(e):e[$A.Symbol.BaseName])))(e.field.table)){let t=ej(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=Nj(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?JI(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 uj.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 uj.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,RI)?e.push(J.identifier(t.name)):W(t,uj)?e.push(J`${wj(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[$A.Symbol.Columns],l=o?o.map(e=>[e,c[e]]):Object.entries(c),u=a&&!W(t,uj)?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 uj(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 xj(n,u.map(([,e])=>e))]}let h=this.buildWithCTE(i),g=new uj(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 uj(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||(JM(ee,t),t=Kj(t,`d${v}`));let te=t[XA],ne=h?1:g?.limit,re=g?.offset,{sql:ie}=WM(t,g,n.relations,e,ee,i),ae=g?.orderBy?zM(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=+!!qM(te,n.table[WA],m,!!o,n.name,this.codecs,p,g?.columns);if(g?.extras){let e=p.length;le&&p.push(K[`, `]);let n=BM(t,g.extras,this.codecs,!!o,p);m.push(...n.selection),n.sql?++le:p.length=e}if(!le&&!se.length)throw new VA({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 VA({message:`Unknown relation "${n.name}" -> "${r}"`});let s=a.relationType===`one`;JM(ee,a.targetTable),JM(ee,a.throughTable);let c=Kj(a.targetTable,`d${v+1}`),l=a.throughTable?Kj(a.throughTable,`tr${v}`):void 0,{filter:d,joinCondition:f}=UM(a,t,c,l);le++&&p.push(K[`, `]);let h=p.length;p.push(void 0,JL.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(JL.relationClose,J.identifier(r));let te=[K[`(select `],o?u:JL.json,s?JL.object:JL.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[`)`]:JL.groupArrayClose),p[h]=new uj(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 `]),YM(t,p),l&&(p.push(K[` inner join `]),YM(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}},XL=class extends oj{static[U]=`SQLiteViewBase`},ZL=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===ij)return{...t[ij],selectedFields:new Proxy(t[ij].selectedFields,this)};if(typeof n==`symbol`)return t[n];let i=mj(t),a=(hj(t,i,q.subquery)?t._.selectedFields:hj(t,i,q.view)?t[ij].selectedFields:t)[n];if(a===void 0&&n===`getSQL`){let e=t[n];return typeof e==`function`?e.bind(r??t):e}let o=mj(a);if(hj(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(hj(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 hj(a,o,q.column)?this.config.alias?new Proxy(a,new Bj(new Proxy(a.table,new Hj(this.config.alias,this.config.replaceOriginalName??!1,!0)),!0)):a:typeof a!=`object`||!a?a:new Proxy(a,new e(this.config))}};function QL(e){if(W(e,$A))return[e[JA]];let t=new Set;return Tj(e.queryChunks,t),[...t]}var $L=class{static[U]=`TypedQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}getSelectedFields(){return this._.selectedFields}},eR=class{builder;static[U]=`SQLiteSelectBuilder`;static[Symbol.hasInstance](e){return W(e,this)}fields;session;dialect;withList;distinct;constructor(e,t=tR){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,sj)?Object.fromEntries(Object.keys(e._.selectedFields).map(t=>[t,e[t]])):W(e,XL)?e[ij].selectedFields:W(e,uj)?{}:Ij(e),new this.builder({table:e,fields:n,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList??[],distinct:this.distinct})}},tR=class extends $L{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=Lj(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}getUsedTables(e=this.getSQL()){return QL(e)}createJoin(e){return(t,n)=>{let r=this.tableName,i=Lj(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,uj))){let e=W(t,sj)?t._.selectedFields:W(t,oj)?t[ij].selectedFields:t[$A.Symbol.Columns];this.config.fields[i]=e}if(typeof n==`function`&&(n=n(new Proxy(this.config.fields,new ZL({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(rR()):n;if(!Fj(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 ZL({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new ZL({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 ZL({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 ZL({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??=Nj(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 sj(this.getSQL(),this.config.fields,e),new ZL({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new ZL({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}};function nR(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!Fj(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 rR=()=>({union:iR,unionAll:aR,intersect:oR,except:sR}),iR=nR(`union`,!1),aR=nR(`union`,!0),oR=nR(`intersect`,!1),sR=nR(`except`,!1),cR=class{static[U]=`SQLiteQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}dialect;dialectConfig;constructor(e){this.dialect=W(e,YL)?e:void 0,this.dialectConfig=W(e,YL)?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 cj(i,t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new ZL({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}}};with(...e){let t=this;function n(n){return new eR({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(n){return new eR({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:r}}select(e){return new eR({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new eR({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||=new YL(this.dialectConfig),this.dialect}},lR=class{name;static[U]=`SQLiteViewBuilderCore`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}config={}},uR=class extends lR{static[U]=`SQLiteViewBuilder`;as(e){typeof e==`function`&&(e=e(new cR));let t=new ZL({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=e.getSelectedFields();return new Proxy(new fR({config:{name:this.name,schema:void 0,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},dR=class extends lR{static[U]=`SQLiteManualViewBuilder`;columns;constructor(e,t,n){super(e),this.columns=Ij(PL(e,t,void 0,void 0,n))}existing(){return new Proxy(new fR({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new ZL({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new fR({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new ZL({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},fR=class extends XL{static[U]=`SQLiteView`;constructor({config:e}){super(e)}};function pR(e){return((t,n)=>n?new dR(t,n,e):new uR(t))}function mR(e,t){return new Proxy(e,new Hj(t,!1))}var hR={table:FL(`snake_case`),view:pR(`snake_case`)},gR=class extends B(`CycleBudgetReset`)({itemKey:xI,repository:H,generation:wI}){},_R=class extends WE(`CycleBudgetResetRejectedError`)(`CycleBudgetResetRejectedError`,{askId:OI}){},vR=[`ItemClosed`];jT(vR);var yR=M({...gR.fields,ask:AE(kI),resetPending:yT}),bR=`~effect/encoding/Ndjson/NdjsonError`,xR=new TextEncoder,SR=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),CR=class extends so(`NdjsonError`){[bR]=bR;get message(){return this.kind}},wR=e=>pe(e,bR),TR=()=>QD((e,t)=>w(E(e,e=>{try{return w(Qi(e.map(e=>{let t=JSON.stringify(e);if(t===void 0)throw TypeError(`Value cannot be represented as JSON`);return t}).join(`
27
+ `)+`
28
+ `))}catch(e){return fh(new CR({kind:`Pack`,cause:e}))}}))),ER=()=>lO(TR(),$i(e=>xR.encode(e))),DR=(e,t,n)=>{let r,i,a=(e,t)=>(r=t,zi(e)?w(e):t===void 0?void 0:fh(t)),o=sh(()=>r===void 0?i===void 0?wm(e,{onSuccess:e=>{let n=[];return a(n,t(e,n))??o},onFailure:ph,onDone:e=>{i={leftover:e};let t=[];return a(t,n(t))??Bd(e)}}):Bd(i.leftover):fh(r));return o},OR=(e,t,n,r)=>{if(!(n&&e.length===0))try{t.push(JSON.parse(e))}catch(e){return new CR({kind:`Unpack`,reason:`InvalidJson`,unterminated:r,cause:e})}},kR=10,AR=13,jR=new Uint8Array,MR=e=>QD((t,n)=>ch(()=>{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 CR({kind:`Unpack`,reason:`InvalidUtf8`,unterminated:r,cause:e})}let o=i!==SR;if(i=SR,!(o&&r&&a.length===0))return OR(a,t,n,r)};return DR(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===kR||a===AR){if(a===kR&&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===AR}else if(s=!1,o+i+1-e>r)return new CR({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(jR,0,0),e,!0))})),NR=`~effect/encoding/Sse/SseError`,PR=class extends so(`EventTooLarge`){get message(){return`Pending SSE event exceeded the maximum size of ${this.maxEventSize}`}},FR=class extends so(`SseError`){[NR]=NR;get message(){return this.reason.message}},IR=10485760,LR=e=>QD((t,n)=>ch(()=>{let n=[],r,i=zR(e=>{e._tag===`Retry`?r=e:n.push(e)},e),a=E(t,e=>{for(let t=0;t<e.length;t++){let n=i.feed(e[t]);if(n!==void 0)return fh(n)}return lh});return sh(function e(){if(zi(n)){let e=n;return n=[],w(e)}return r?fh(r):E(a,e)})})),RR=(e,t,n)=>CO(LR(t),MO(WR.pipe(NT(e,GR)),n)());function zR(e,t){let n=t?.maxEventSize??IR,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(BR)&&(e=e.slice(BR.length)),i=!1;let t=e.length,r=c,l=0;for(;l<t;){if(s&&(s=!1,e.charCodeAt(l)===VR)){++l;continue}let n=l;for(;n<t;){let t=e.charCodeAt(n);if(t===HR||t===VR)break;++n}if(n===t){a.push(e.slice(l)),o+=t-l;break}s=e.charCodeAt(n)===HR;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 FR({reason:new PR({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)===UR?n+2:n+1)),i===`data`?d+=a+`
29
+ `:i===`event`?u=a:i===`id`&&!a.includes(`\0`)?l=a:i===`retry`&&/^\d+$/.test(a)&&e(new qR({duration:Ra(parseInt(a,10)),lastEventId:l}))}}var BR=``,VR=10,HR=13,UR=32,WR=M({_tag:BT(`Event`),id:MT(j),event:j,data:j}),GR=eb({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})}),KR=`~effect/encoding/Sse/Retry`,qR=class e extends oo(`Retry`){[KR]=KR;static is(e){return pe(e,KR)}static filter(t){return e.is(t)?pi(t):mi(t)}},JR=class extends B(`@usine/engine/Submission`)({event:iN,itemKey:xI,loop:DA,step:GN,approval:kA,permissions:jA.pipe(RT(w(`write`)),IT(w(`write`))),cycleLimit:z(CI).pipe(zT(w(b(TI))),IT(w(b(TI)))),cycleGeneration:wI.pipe(RT(w(wI.make(0))),IT(w(wI.make(0)))),repository:H,revision:cA,task:PF,agent:wA,parentModel:z(vA)}){},YR=`@usine/engine/DurableRun`,XR=O(`Submission.runIdFor`)(function*(e){let t=yield*(yield*sk).digest(`SHA-256`,new TextEncoder().encode(`${YR}-${e.event.dedupKey}`)).pipe(Fh);return LN.make(uo(t.subarray(0,16)))}),ZR=(e,t,n)=>{let r=rN.make(JSON.stringify([`reopened`,n,t]));return new JR({...e,event:new iN({...e.event,id:nN.make(r),dedupKey:r})})},QR=class extends V(`@usine/engine/Claimed`)(`Claimed`,{eventId:nN,runId:LN}){},$R=class extends V(`@usine/engine/Queued`)(`Queued`,{eventId:nN}){},ez=[`superseded`,`revoked`],tz=jT(ez),nz=class extends V(`@usine/engine/Ignored`)(`Ignored`,{eventId:nN,reason:tz}){},rz=class extends V(`@usine/engine/Suppressed`)(`Suppressed`,{eventId:nN,runId:LN}){},iz=class extends V(`@usine/engine/CycleBlocked`)(`CycleBlocked`,{eventId:nN,ask:kI}){},az=P([QR,$R,rz,nz,iz]),oz=hR.table(`usine_events`,{eventId:X().$type().primaryKey(),dedupKey:X().$type().notNull().unique(),payloadJson:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[RL(`usine_events_payload_json_valid`,J`json_valid(${e.payloadJson})`)]),Z=hR.table(`usine_trigger_events`,{eventId:X().$type().primaryKey().references(()=>oz.eventId),itemKey:X().$type().notNull(),loopName:X().$type().notNull(),stepName:X().$type().notNull(),approval:X({enum:OA}).$type().notNull(),permissions:X({enum:AA}).$type().notNull().default(`write`),cycleLimit:pL().$type(),cycleGeneration:pL().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(()=>oz.eventId),reopening:pL().notNull().default(0)},e=>[RL(`usine_trigger_events_approval`,J`${e.approval} in ('none', 'required')`),RL(`usine_trigger_events_cycle_limit`,J`${e.cycleLimit} is null or ${e.cycleLimit} >= 1`),RL(`usine_trigger_events_agent_json_valid`,J`json_valid(${e.agentJson})`),HL(`usine_trigger_events_item`).on(e.loopName,e.itemKey),HL(`usine_trigger_events_item_history`).on(e.itemKey),UL(`usine_trigger_event_reopening`).on(e.reopensEventId,e.reopening)]),sz=hR.table(`usine_loop_items`,{loopName:X().$type().notNull(),itemKey:X().$type().notNull(),observedEventId:X().$type().references(()=>oz.eventId),suppressedByRunId:X().$type().references(()=>Q.runId),suppressedEventId:X().$type().references(()=>oz.eventId)},e=>[WL({columns:[e.loopName,e.itemKey]})]),cz=hR.table(`usine_item_cycle_budgets`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),generation:pL().notNull().default(0),askJson:X({mode:`json`}).$type(),resetPending:pL({mode:`boolean`}).notNull().default(!1)},e=>[RL(`usine_item_cycle_generation`,J`${e.generation} >= 0`),RL(`usine_item_cycle_ask_json`,J`${e.askJson} is null or json_valid(${e.askJson})`)]),lz=hR.table(`usine_cycle_reservations`,{runId:X().$type().primaryKey().references(()=>Q.runId),itemKey:X().$type().notNull().references(()=>cz.itemKey),generation:pL().notNull(),loop:X().$type().notNull()},e=>[HL(`usine_cycle_reservations_item`).on(e.itemKey,e.generation,e.loop),RL(`usine_cycle_reservations_generation`,J`${e.generation} >= 0`)]),uz=hR.table(`usine_cycle_resets`,{askId:X().$type().primaryKey(),eventId:X().$type().notNull().unique().references(()=>oz.eventId),itemKey:X().$type().notNull().references(()=>cz.itemKey)}),dz=hR.table(`usine_cycle_ask_closures`,{askId:X().$type().primaryKey(),itemKey:X().$type().notNull().references(()=>cz.itemKey),reason:X({enum:vR}).$type().notNull(),askJson:X({mode:`json`}).$type().notNull(),closedAt:X().notNull()},e=>[RL(`usine_cycle_ask_closures_reason`,J`${e.reason} in ('ItemClosed')`),RL(`usine_cycle_ask_closures_ask_json`,J`json_valid(${e.askJson})`)]),Q=hR.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=>[RL(`usine_runs_state_json_valid`,J`json_valid(${e.stateJson})`),RL(`usine_runs_agent_json_valid`,J`json_valid(${e.agentJson})`)]),fz=hR.table(`usine_steps`,{runId:X().$type().notNull().references(()=>Q.runId),stepName:X().$type().notNull(),result:X({mode:`json`}).$type()},e=>[WL({columns:[e.runId,e.stepName]}),RL(`usine_steps_result_json_valid`,J`${e.result} is null or json_valid(${e.result})`)]),$=hR.table(`usine_attempts`,{attemptId:X().$type().primaryKey(),runId:X().$type().notNull(),stepName:X().$type().notNull(),workerName:X().$type().notNull(),attemptNumber:pL({mode:`number`}).$type().notNull(),brainJson:X({mode:`json`}).$type().notNull(),task:X().$type().notNull(),agent:X().$type().notNull(),operatorIntervened:pL({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=>[RL(`usine_attempts_number`,J`${e.attemptNumber} >= 1`),RL(`usine_attempts_brain_json_valid`,J`json_valid(${e.brainJson})`),RL(`usine_attempts_outcome_json_valid`,J`${e.outcomeJson} is null or json_valid(${e.outcomeJson})`),RL(`usine_attempts_salvage_json_valid`,J`${e.salvageJson} is null or json_valid(${e.salvageJson})`),UL(`usine_attempt_number`).on(e.runId,e.stepName,e.attemptNumber),UL(`usine_one_in_flight_attempt`).on(e.runId).where(J`${e.outcomeJson} is null`),II({columns:[e.runId,e.stepName],foreignColumns:[fz.runId,fz.stepName]})]),pz=hR.table(`usine_attempt_transcripts`,{sequence:pL({mode:`number`}).primaryKey({autoIncrement:!0}),attemptId:X().$type().notNull().references(()=>$.attemptId),direction:X({enum:ZF}).notNull(),channelSequence:pL({mode:`number`}).$type().notNull(),envelope:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[RL(`usine_attempt_transcripts_direction`,J`${e.direction} in ('inbound', 'outbound')`),RL(`usine_attempt_transcripts_sequence`,J`${e.channelSequence} >= 1`),RL(`usine_attempt_transcripts_envelope_json_valid`,J`json_valid(${e.envelope})`),UL(`usine_attempt_transcript_envelope`).on(e.attemptId,e.direction,e.channelSequence),HL(`usine_attempt_transcript_tail`).on(e.attemptId,e.sequence),HL(`usine_attempt_transcript_pool_limits`).on(J`json_extract(${e.envelope}, '$.payload.event.pool')`,e.sequence).where(J`${e.direction} = 'outbound'
30
+ and json_extract(${e.envelope}, '$.payload._tag') = 'SessionEvent'
31
+ and json_extract(${e.envelope}, '$.payload.event._tag') = 'PoolRateLimitsUpdated'`)]),mz=hR.table(`usine_approvals`,{runId:X().$type().primaryKey().references(()=>Q.runId),eventId:X().$type().notNull().unique().references(()=>oz.eventId),channel:X({enum:AI}).$type(),approver:X().$type()},e=>[RL(`usine_approvals_source`,J`(${e.channel} is null and ${e.approver} is null) or ${e.channel} = 'ui'`)]),hz=hR.table(`usine_run_again_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),fromRunId:X().$type().notNull().references(()=>Q.runId),requestedBy:X().$type()}),gz=hR.table(`usine_ignored_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),reason:X({enum:ez}).$type().notNull()},e=>[RL(`usine_ignored_events_reason`,J`${e.reason} in ('superseded', 'revoked')`)]),_z=hR.table(`usine_cursors`,{cursorKey:X().primaryKey(),valueJson:X({mode:`json`}).$type().notNull()},e=>[RL(`usine_cursors_value_json_valid`,J`json_valid(${e.valueJson})`)]),vz=hR.table(`usine_item_projections`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),source:X().notNull(),itemNumber:pL({mode:`number`}).notNull(),contentHash:X().notNull(),payloadJson:X({mode:`json`}).$type().notNull(),goneAt:X()},e=>[RL(`usine_item_projections_number`,J`${e.itemNumber} >= 1`),RL(`usine_item_projections_payload_json_valid`,J`json_valid(${e.payloadJson})`),UL(`usine_item_projection_number`).on(e.repository,e.itemNumber)]),yz=hR.table(`usine_repository_label_projections`,{repository:X().$type().primaryKey(),labelsJson:X({mode:`json`}).$type().notNull()},e=>[RL(`usine_repository_label_projections_labels_json_valid`,J`json_valid(${e.labelsJson})`)]),bz=hR.table(`usine_board_moves`,{moveId:pL({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=>[RL(`usine_board_moves_added_json_valid`,J`json_valid(${e.addedJson})`),RL(`usine_board_moves_removed_json_valid`,J`json_valid(${e.removedJson})`),HL(`usine_board_moves_item`).on(e.itemKey,e.movedAt)]),xz=hR.table(`usine_loop_runtime`,{loopName:X().$type().primaryKey(),paused:pL({mode:`boolean`}).notNull()}),Sz=hR.table(`usine_projection_revision`,{singleton:pL({mode:`number`}).primaryKey().default(1),revision:pL({mode:`number`}).notNull().default(0)},e=>[RL(`usine_projection_revision_singleton`,J`${e.singleton} = 1`)]);hR.table(`usine_attention_acknowledgements`,{id:X().notNull(),revision:X().$type().notNull(),dismissedBy:X().$type(),dismissedAt:X().notNull()},e=>[WL({columns:[e.id,e.revision]})]);var Cz=class extends WE(`@usine/engine/RunNotFoundError`)(`RunNotFoundError`,{runId:LN}){},wz=class extends WE(`@usine/engine/RunOperationRejectedError`)(`RunOperationRejectedError`,{runId:LN,operation:jT([`approve`,`retry`,`resolveFailure`,`runAgain`,`cancel`]),state:j}){},Tz=class extends WE(`@usine/engine/RunRetryBlockedError`)(`RunRetryBlockedError`,{runId:LN,openRunId:LN,message:R}){},Ez=class extends WE(`@usine/engine/EnginePersistenceError`)(`EnginePersistenceError`,{operation:j,cause:dE()}){},Dz=class extends WE(`@usine/engine/AttemptCancellationError`)(`AttemptCancellationError`,{attemptId:jF,cause:dE()}){},Oz=P([Cz,wz,Tz,Ez]),kz=class extends WE(`@usine/engine/RunInterventionRejectedError`)(`RunInterventionRejectedError`,{runId:LN,attemptId:jF,message:R}){},Az=class extends WE(`@usine/engine/LeftoversDiscardRejectedError`)(`LeftoversDiscardRejectedError`,{worker:qN,running:L.check($T(0))}){};P([Cz,wz,Tz,Ez,Dz,kz]);var jz=class e extends kr()(`@usine/engine/internal/RunDatabase`){static layer=t=>Tf(e)(t)},Mz=j.check(GT(/\S/u,{message:`Expected a non-blank repository label`})),Nz=j.check(GT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})),Pz=class extends B(`@usine/engine/RepositoryLabel`)({name:Mz,color:AE(Nz),description:AE(j)}){},Fz=WT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),Iz=N(Pz).check(Fz),Lz=class extends B(`@usine/engine/RepositoryLabelProjection`)({repository:H,labels:Iz}){},Rz=N(j),zz=Xw(Rz),Bz=M({repository:H,labels:P([Lz.fields.labels,Rz])}),Vz=e=>zz(e)?e.map(e=>new Pz({name:e,color:y(),description:y()})):e,Hz=Zw(N(Bz)),Uz=oT(Lz.fields.labels),Wz=e=>t=>Ph(t,t=>new Ez({operation:e,cause:t})),Gz=T(function*(){let e=yield*jz;return{get:O(`RepositoryLabelProjectionReader.get`)(function*(t){let n=(yield*Hz(yield*e.select({repository:yz.repository,labels:yz.labelsJson}).from(yz).where(Y(yz.repository,t)).limit(1).execute(),{onExcessProperty:`error`}))[0];return n===void 0?y():b(new Lz({repository:n.repository,labels:Vz(n.labels)}))},Wz(`read repository label projection`))}}),Kz=T(function*(){let e=yield*jz;return{replace:O(`RepositoryLabelProjectionWriter.replace`)(function*(t){yield*D({repository:t.repository});let n=Uz(t.labels);return(yield*e.insert(yz).values({repository:t.repository,labelsJson:n}).onConflictDoUpdate({target:yz.repository,set:{labelsJson:n},setWhere:$j(yz.labelsJson,n)}).returning({repository:yz.repository}).execute()).length===0?(yield*A(`Repository label projection already matched GitHub`,{repository:t.repository,labels:t.labels.length}),!1):(yield*A(`Repository label projection updated from trigger polling`,{repository:t.repository,labels:t.labels.length}),!0)},Wz(`write repository label projection`))}}),qz=class e extends kr()(`@usine/engine/RepositoryLabelProjectionReader`){static layer=Df(e,Gz)},Jz=class e extends kr()(`@usine/engine/RepositoryLabelProjectionWriter`){static layer=Df(e,Kz)},Yz=`~effect/http/HttpBody`,Xz=e=>pe(e,Yz),Zz=class{[Yz];constructor(){this[Yz]=Yz}[gt](){return this.toJSON()}toString(){return ot(this,{ignoreToString:!0})}},Qz=new class extends Zz{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}},$z=class extends Zz{_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??=rB(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}}},eB=(e,t)=>new $z(e,t??`application/octet-stream`,e.length),tB=new TextEncoder,nB=globalThis.Buffer,rB=nB===void 0?e=>tB.encode(e):e=>nB.from(e,`utf8`),iB=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),nB!==void 0)return new $z(void 0,t??`text/plain`,nB.byteLength(e,`utf8`),e);let n=tB.encode(e);return new $z(n,t??`text/plain`,n.length,e)},aB=(e,t)=>iB(JSON.stringify(e),t??`application/json`),oB=(e,t)=>iB(yv(uv(e)),t??`application/x-www-form-urlencoded`),sB=class extends Zz{_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}}},cB=e=>new sB(e),lB=class extends Zz{_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}}},uB=(e,t,n)=>new lB(e,t??`application/octet-stream`,n),dB=`~effect/http/HttpClientError`,fB=class extends so(`HttpClientError`){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[dB]=dB;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}},pB=e=>e.endsWith(`Error`)?e.slice(0,-5):e,mB=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,hB=e=>`${e.method} ${Cv(e.url)}`,gB=class extends so(`TransportError`){get methodAndUrl(){return hB(this.request)}get message(){return mB(pB(this._tag),this.description,this.methodAndUrl)}},_B=class extends so(`InvalidUrlError`){get methodAndUrl(){return hB(this.request)}get message(){return mB(pB(this._tag),this.description,this.methodAndUrl)}},vB=class extends so(`StatusCodeError`){get methodAndUrl(){return hB(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return mB(pB(this._tag),this.description,e)}},yB=class extends so(`DecodeError`){get methodAndUrl(){return hB(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return mB(pB(this._tag),this.description,e)}},bB=class extends so(`EmptyBodyError`){get methodAndUrl(){return hB(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return mB(pB(this._tag),this.description,e)}},xB=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,SB=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],CB=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?tv(tv(e,`content-type`),`content-length`):(e=t.contentType===void 0?tv(e,`content-type`):Q_(e,`content-type`,t.contentType),t.contentLength===void 0?tv(e,`content-length`):Q_(e,`content-length`,t.contentLength.toString())),wB=class extends so(`UrlError`){},TB=(e,t,n)=>gi({try:()=>{let r=new URL(e,EB());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,av(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new wB({cause:e})}),EB=()=>{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}}},DB=`~effect/http/HttpClientRequest`,OB={[DB]:DB,...yt,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:Cv(this.url),urlParams:this.urlParams,hash:this.hash,headers:tt(this.headers),body:this.body.toJSON()}},pipe(){return e(this,arguments)}};function kB(e,t,n,r,i,a){let o=Object.create(OB);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var AB=kB(`GET`,``,hv,y(),Y_,Qz),jB=e=>(t,n)=>FB(AB,{method:e,url:t,...n??void 0}),MB=jB(`GET`),NB=jB(`POST`),PB=jB(`PATCH`),FB=r(2,(e,t)=>{let n=e;return t.method&&(n=IB(n,t.method)),t.url&&(n=HB(n,t.url)),t.headers&&(n=RB(n,t.headers)),t.urlParams&&(n=GB(n,t.urlParams)),t.hash&&(n=qB(n,t.hash)),t.body&&(n=JB(n,t.body)),t.accept&&(n=zB(n,t.accept)),t.acceptJson&&(n=BB(n)),n}),IB=r(2,(e,t)=>kB(t,e.url,e.urlParams,e.hash,e.headers,e.body)),LB=r(3,(e,t,n)=>kB(e.method,e.url,e.urlParams,e.hash,Q_(e.headers,t,n),e.body)),RB=r(2,(e,t)=>kB(e.method,e.url,e.urlParams,e.hash,$_(e.headers,t),e.body)),zB=r(2,(e,t)=>LB(e,`Accept`,t)),BB=zB(`application/json`),VB=r(2,(e,t)=>kB(e.method,e.url,e.urlParams,e.hash,Q_(Q_(e.headers,`connection`,`Upgrade`),`upgrade`,t),e.body)),HB=r(2,(e,t)=>{if(typeof t==`string`)return kB(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=uv(n.searchParams),i=_r(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,kB(e.method,n.toString(),r,i,e.headers,e.body)}),UB=r(2,(e,t)=>t===``?e:kB(e.method,WB(t,e.url),e.urlParams,e.hash,e.headers,e.body)),WB=(e,t)=>{let n=e.endsWith(`/`),r=t.startsWith(`/`);return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t},GB=r(2,(e,t)=>kB(e.method,e.url,_v(e.urlParams,t),e.hash,e.headers,e.body)),KB=r(2,(e,t)=>kB(e.method,e.url,vv(e.urlParams,t),e.hash,e.headers,e.body)),qB=r(2,(e,t)=>kB(e.method,e.url,e.urlParams,b(t),e.headers,e.body)),JB=r(2,(e,t)=>kB(e.method,e.url,e.urlParams,e.hash,CB(e.headers,t),t)),YB=r(2,(e,t)=>JB(e,aB(t))),XB=r(2,(e,t)=>JB(e,cB(t)));function ZB(e){let t=TB(e.url,e.urlParams,br(e.hash));return yi(t)?b(t.success):y()}var QB=`~effect/http/HttpIncomingMessage`,$B=(e,t)=>{let n=Qw(KE(e)),r=t?.reviver===void 0?void 0:Qw(gE(KE(e),t));return e=>r===void 0?E(e.json,e=>n(e,t)):E(e.text,i=>i===``?E(e.json,e=>n(e,t)):r(i,t))},eV=(e,t)=>({...t,headers:tt(e.headers),remoteAddress:e.remoteAddress}),tV=`~effect/http/HttpClientResponse/WebSource`,nV=e=>e[tV]?.(),rV=`~effect/http/HttpClientResponse`,iV=(e,t)=>new aV(e,t),aV=class extends bt{[QB];[rV];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[QB]=QB,this[rV]=rV}toJSON(){return eV(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=ZB(this.request);return x(e)?``:(e.value.hash=``,e.value.href)}get headers(){return X_(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=M_(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return y()}[tV](){return this.source}get stream(){return this.source.body?KO({evaluate:()=>this.source.body,onError:e=>new fB({reason:new yB({request:this.request,response:this,cause:e})})}):WO(new fB({reason:new bB({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return E(this.text,e=>gh({try:()=>e===``?null:JSON.parse(e),catch:e=>new fB({reason:new yB({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=Th(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return E(this.text,e=>gh({try:()=>uv(new URLSearchParams(e)),catch:e=>new fB({reason:new yB({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=ah({try:()=>this.source.formData(),catch:e=>new fB({reason:new yB({request:this.request,response:this,cause:e})})}).pipe(ag,bg)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=ah({try:()=>this.source.arrayBuffer(),catch:e=>new fB({reason:new yB({request:this.request,response:this,cause:e})})}).pipe(ag,bg),this.arrayBufferBody}get upgrade(){return fh(new fB({reason:new vB({request:this.request,response:this,description:`fetch cannot hand over the connection of an HTTP upgrade`})}))}pipe(){return e(this,arguments)}},oV=e=>Z_({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${pr(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),sV={"http:":80,"https:":443,"ws:":80,"wss:":443},cV=(e,t,n)=>{let r=Cv(t.search,n).slice(1);if(e.attribute(`url.full`,Cv(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===``?sV[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},lV=(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()]},uV=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,rv(a,i)?`<redacted>`:n[a])},dV=`~effect/http/HttpClient`,fV=kr(`effect/HttpClient`),pV=r(2,(e,t)=>mV(n=>t(e.postprocess(n)),e.preprocess)),mV=(e,t)=>{let n=Object.create(hV);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},hV={[dV]:dV,pipe(){return e(this,arguments)},...yt,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(SB.map(([e,t])=>[t,function(t,n){return this.execute(jB(e)(t,n))}]))},gV=e=>mV(t=>E(t,t=>_h(n=>{let r=EV.get(t),i=r??new AbortController,a=TB(t.url,t.urlParams,br(t.hash));if(vi(a))return fh(new fB({reason:new _B({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(wo)||n.getRef(bV)(t)){let a=e(t,o,i.signal,n);return r?a:lg(e=>Gh(e(a),{onSuccess(e){return TV.register(e,i),w(new DV(e,i))},onFailure(e){return Id(e)&&i.abort(),ph(e)}}))}return fg(n.getRef(CV)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(iv);cV(a,o,lV(t.urlParams,n.getRef(jv)));let c=n.getRef(xV);return uV(a,`request`,t.headers,c,s),t=n.getRef(SV)?RB(t,oV(a)):t,lg(l=>l(e(t,o,i.signal,n)).pipe(mg(a,{captureStackTrace:!1}),Gh({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),uV(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),_V(n,a,t,e)),r?w(e):(TV.register(e,i),w(new DV(e,i)))),onFailure(e){return!r&&Id(e)&&i.abort(),ph(e)}})))})})),w),_V=(e,t,n,r)=>{let i=St();Ct(0);let a;try{a=Wd(new fB({reason:new vB({request:n,response:r})}))}finally{Ct(i)}t.end(e.getRef(of)?e.getRef(Dee).currentTimeNanosUnsafe():BigInt(0),a)},vV=r(2,(e,t)=>mV(e.postprocess,n=>Th(e.preprocess(n),t))),yV=r(2,(e,t)=>pV(e,xh(t))),bV=li(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>s}),xV=li(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>s}),SV=li(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:o}),CV=li(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),wV=e=>Df(fV)(qh(t=>Th(e,e=>pV(e,Zh(e=>oi(t,e)))))),TV=(()=>{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))}}})(),EV=new WeakMap,DV=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[rV]=rV;[QB]=QB;applyInterrupt(e){return sh(()=>(TV.unregister(this.original),sg(e,()=>ch(()=>{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)}[tV](){let e=nV(this.original);return e!==void 0&&TV.unregister(this.original),e}get stream(){return HO(()=>(TV.unregister(this.original),nk(this.original.stream,ch(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[gt](){return this.original[gt]()}pipe(){return e(this,arguments)}},OV=li(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),kV=class extends kr()(`effect/http/FetchHttpClient/RequestInit`){},AV=wV(w(gV((e,t,n,r)=>{if(e.headers.upgrade!==void 0)return fh(new fB({reason:new gB({request:e,description:`fetch cannot send an HTTP upgrade request`})}));let i=r.getRef(OV),a=Qr(r.context,kV)??{},o=a.headers?ev(X_(a.headers),e.headers):e.headers;o[`content-length`]&&(o=tv(o,`content-length`));let s,c=ch(()=>s?.abort()),l=r=>Th(ah({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 fB({reason:new gB({request:e,cause:t})})}),t=>{let n=iV(e,t);return s?(t.body===null&&s.abort(),Object.create(n,{...Object.fromEntries([`arrayBuffer`,`text`,`json`,`formData`,`urlParamsBody`].map(e=>[e,{get:()=>tg(n[e],c)}])),stream:{get:()=>nk(n.stream,c)}})):n}).pipe(ng(()=>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=uh(e=>{let n=()=>e(og);if(t.aborted)n();else return t.addEventListener(`abort`,n,{once:!0}),ch(()=>t.removeEventListener(`abort`,n))});return E(ok(tk(e.body.stream,r)),l)}}return l(void 0)})));function jV(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 MV=kr(`effect/http/HttpEffect/CurrentRequestState`),NV=e=>_h(t=>{let n=Qr(t.context,MV);return n!==void 0&&(n.loggerDisabled=!0),e}),PV=kr(`effect/http/HttpRouter`),FV=e=>e.endsWith(`/`)?e.slice(0,-1):e,IV=r(2,(e,t)=>(t=FV(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),LV=`~effect/http/HttpRouter/Middleware`,RV=function(){return arguments.length===0?zV:zV(arguments[0],arguments[1])},zV=(e,t)=>t?.global?wee(T(function*(){let t=yield*PV,n=th(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new HV(th(e)?kf(Th(e,e=>Hr(new Map([[VV,e]])))):Ef(Hr(new Map([[VV,e]])))),BV=0,VV=`effect/http/HttpRouter/MiddlewareFn`,HV=class e{[LV]={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++BV}`;this.layer=kf(T({self:this},function*(){let e=yield*Kh(),t=[$r(e,VV)];if(this.dependencies){let n=yield*Cf,r=ti(e,sf),i=yield*wf(this.dependencies,n,r);t.push(...WV(i))}return Hr(new Map([[n,t]]))})).pipe(Mf(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?Eee(this.dependencies,t.layer):t.layer)}},UV=new WeakMap,WV=e=>{let t=UV.get(e);if(t)return t;let n=Zi(),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=Ii(e).reverse()}return UV.set(e,t),t};RV(NV).layer;var GV={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},KV=e=>GV[e],qV=L.check($T(1)).pipe(I(`GitHubAppId`)),JV=PE(R.check(GT(/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/u,{message:`Expected a PEM-encoded RSA private key`})).pipe(I(`GitHubAppPrivateKey`)),{disallowEncode:!0});B(`@usine/github/AppCredentials`)({appId:qV,privateKey:JV});var YV=class extends kr()(`@usine/github/GitHubCredentials`){},XV=class extends WE(`@usine/github/AppAuthenticationError`)(`AppAuthenticationError`,{message:R}){},ZV=new TextEncoder,QV=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),$V=(...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},eH=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])},tH=(e,t)=>$V(new Uint8Array([e]),eH(t.length),t),nH=e=>tH(48,$V(new Uint8Array([2,1,0]),QV,tH(4,e))),rH=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?nH(i):i},iH=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/=/gu,``).replace(/\+/gu,`-`).replace(/\//gu,`_`)},aH=e=>iH(ZV.encode(JSON.stringify(e))),oH=e=>{let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},sH=O(`AppJwt.import`)(function*(e){let t=yield*ah({try:async()=>crypto.subtle.importKey(`pkcs8`,oH(rH(U_(e.privateKey))),{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},!1,[`sign`]),catch:()=>new XV({message:`Could not import the GitHub App private key as an RSA private key`})});return O(`AppJwt.sign`)(function*(){let n=Math.floor((yield*Nf)/1e3),r=`${aH({alg:`RS256`,typ:`JWT`})}.${aH({iat:n-60,exp:n+540,iss:e.appId})}`,i=yield*ih(()=>crypto.subtle.sign(`RSASSA-PKCS1-v1_5`,t,oH(ZV.encode(r))));return V_(`${r}.${iH(new Uint8Array(i))}`)})}),cH=L.check($T(1)),lH=cH.pipe(I(`GitHubInstallationId`)),uH=cH.pipe(I(`GitHubRepositoryId`)),dH=R.pipe(I(`GitHubAppSlug`)),fH=class extends B(`@usine/github/Installation`)({id:lH,accountLogin:R,appSlug:dH}){},pH=class extends V(`@usine/github/TokenScope/InstallationWide`)(`InstallationWide`,{}){},mH=class extends V(`@usine/github/TokenScope/SingleRepository`)(`SingleRepository`,{repository:H,repositoryId:uH,permissions:jA}){},hH=P([pH,mH]),gH=class extends B(`@usine/github/InstallationToken`)({value:NE(R,{disallowJsonEncode:!0}),expiresAt:OE,scope:hH}){},_H=jT([`missing`,`multiple`,`suspended`]),vH=class extends WE(`@usine/github/InstallationDiscoveryError`)(`InstallationDiscoveryError`,{reason:_H,message:R}){},yH={checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},bH={write:{checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},read:{checks:`read`,contents:`read`,issues:`write`,metadata:`read`,pull_requests:`write`}},xH=(e,t)=>e===t||t===`read`&&e===`write`,SH=e=>Object.entries(yH).flatMap(([t,n])=>xH(e[t],n)?[]:[`${t}:${n}`]),CH=class extends V(`@usine/github/ProjectAccess/CoveredProject`)(`CoveredProject`,{installationId:lH,repository:H,repositoryId:uH}){},wH=class extends WE(`@usine/github/ProjectNotInstalledError`)(`ProjectNotInstalledError`,{repository:H,message:R}){};P([CH,wH]);var TH=(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 wH({repository:t,message:`The GitHub App installation has no access to "${t}"`}):new CH({installationId:e.id,repository:t,repositoryId:n.id})})},EH=class extends WE(`@usine/github/AppPermissionError`)(`AppPermissionError`,{missing:N(R).check(iE()),message:R}){},DH=jT([`configure-webhook`,`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`,`poll-webhook-deliveries`,`read-bot-account`,`update-item-labels`]),OH=class extends WE(`@usine/github/GitHubApiError`)(`GitHubApiError`,{operation:DH,status:z(L),message:R}){},kH=class extends WE(`@usine/github/GitHubRateLimitError`)(`GitHubRateLimitError`,{operation:DH,retryAt:OE,message:R}){},AH=class extends WE(`@usine/github/InvalidGitHubResponseError`)(`InvalidGitHubResponseError`,{operation:DH,message:R,detail:R}){},jH=class extends WE(`@usine/github/GitHubItemNotFoundError`)(`GitHubItemNotFoundError`,{operation:DH,item:L.check($T(1)),message:R}){};P([vH,EH,OH,kH,AH]);var MH=`https://api.github.com`,NH=`2026-03-10`,PH=e=>RB({accept:`application/vnd.github+json`,authorization:`Bearer ${U_(e)}`,"user-agent":`usine`,"x-github-api-version":NH}),FH=(e,t)=>new OH({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}`}),IH=$w(M({message:R})),LH=(e,t)=>t.json.pipe(Th(t=>pr(IH(t),{onNone:()=>e,onSome:({message:t})=>new OH({operation:e.operation,status:e.status,message:`${e.message}: ${t}`})})),kh(t=>A(`GitHub's error response has no JSON body to read a reason from`,{operation:e.operation,message:t.message}).pipe(Eh(e)))),RH=(e,t)=>new AH({operation:e,message:`GitHub returned a response in an unexpected format`,detail:t}),zH=e=>{if(e===void 0||!/^\d+$/u.test(e))return y();let t=Number(e);return Number.isSafeInteger(t)?b(t):y()},BH=(e,t)=>{let n=zH(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()},VH=(e,t)=>{let n=zH(e[`x-ratelimit-remaining`]),r=zH(e[`x-ratelimit-reset`]);return S(n)&&n.value<=t&&S(r)?b(r.value*1e3):y()},HH=(e,t)=>Sr(zH(e[`x-poll-interval`]),e=>t+e*1e3),UH=e=>{let t=e.flatMap(e=>pr(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?y():b(Math.max(...t))},WH=(e,t)=>UH([BH(e[`retry-after`],t),VH(e,0)]),GH=(e,t,n)=>{let r=Cr(WH(t.headers,n),c_);return(t.status===403||t.status===429)&&S(r)?new kH({operation:e,retryAt:r.value,message:`GitHub API rate limit exceeded`}):new OH({operation:e,status:b(t.status),message:`GitHub returned HTTP status ${t.status}`})},KH=e=>e===void 0?y():_r(/<(?<url>[^>]+)>;\s*rel="next"/u.exec(e)?.groups?.url),qH=j.check(GT(/^[1-9][0-9]*$/u)).pipe(I(`WebhookDeliveryId`)),JH=gE(N(class extends B(`@usine/github/WebhookDelivery`)({id:qH,event:R,repositoryId:AE(uH)}){}.pipe(wT({repositoryId:`repository_id`}))),{reviver:(e,t,n)=>e===`id`?n?.source:t}),YH=36e5,XH=3e5,ZH=N(M({id:lH,appSlug:dH,account:M({login:R}),permissions:TT(j,j),suspendedAt:F(j)}).pipe(wT({appSlug:`app_slug`,suspendedAt:`suspended_at`}))),QH=M({login:YN,id:XN}),$H=M({id:uH,name:H}).pipe(wT({name:`full_name`})),eU=M({totalCount:L.check($T(0)),repositories:N($H)}).pipe(wT({totalCount:`total_count`})),tU=M({token:R,expiresAt:kE,repositories:ME(N($H))}).pipe(wT({expiresAt:`expires_at`})),nU=e=>e._tag===`InstallationWide`?{operation:`mint-installation-token`,body:{permissions:yH}}:{operation:`mint-worker-token`,body:{permissions:bH[e.permissions],repository_ids:[e.repositoryId]}},rU=class e extends kr()(`@usine/github/GitHubApp`){static layer=Df(e,T(function*(){let e=yield*YV,t=yield*sH(e),n=yield*fV,r=O(`GitHubApp.fetch`)(function*(t,r){yield*D({appId:e.appId,operation:t});let i=yield*n.execute(r).pipe(Ph(e=>FH(t,e)));if(i.status<200||i.status>=300){let e=GH(t,i,yield*Nf);return e._tag===`GitHubRateLimitError`?yield*e:yield*yield*LH(e,i)}return i}),i=(e,t,n)=>r(e,t).pipe(E(t=>$B(n)(t).pipe(Ph(t=>RH(e,t.message))))),a=O(`GitHubApp.deliveries`)(function*(n){yield*D({appId:e.appId,after:C(n)});let i=yield*t(),a=b(`${MH}/app/hook/deliveries?per_page=100`),o=[];for(let e=0;e<10&&S(a);e+=1){let e=yield*r(`poll-webhook-deliveries`,MB(a.value).pipe(PH(i))),t=yield*e.text.pipe(E(Zw(JH)),Ph(e=>RH(`poll-webhook-deliveries`,e.message))),s=t.filter(e=>x(n)||BigInt(e.id)>BigInt(n.value));if(o.push(...s),s.length<t.length)return o;a=KH(e.headers.link)}return S(a)&&(yield*Cg(`Webhook delivery page limit reached; older hints dropped`,{appId:e.appId,deliveries:o.length})),o}),o=O(`GitHubApp.discoverInstallation`)(function*(){let e=yield*t(),[n,...r]=yield*i(`discover-installation`,MB(`${MH}/app/installations?per_page=2`).pipe(PH(e)),ZH);if(n===void 0)return yield*new vH({reason:`missing`,message:`The GitHub App is not installed on any account. Install it on the account that owns the repositories.`});if(r.length>0)return yield*new vH({reason:`multiple`,message:`The GitHub App has more than one installation. Uninstall it from every account except one.`});if(n.suspendedAt!==null)return yield*new vH({reason:`suspended`,message:`The GitHub App installation is suspended. Unsuspend it in the installation settings on GitHub.`});let a=SH(n.permissions);return a.length>0?yield*new EH({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 fH({id:n.id,accountLogin:n.account.login,appSlug:n.appSlug})}),s=O(`GitHubApp.mintToken`)(function*(e,n){let{operation:r,body:a}=nU(n);yield*D({installationId:e,operation:r,scope:n._tag,permissions:n._tag===`SingleRepository`?n.permissions:`installation`});let o=yield*t(),s=yield*i(r,NB(`${MH}/app/installations/${e}/access_tokens`).pipe(YB(a),PH(o)),tU),c=yield*Nf,l=h_(s.expiresAt)-c;if(l<=0||l>378e4)return yield*new AH({operation:r,message:`GitHub returned an installation token that is expired or exceeds the one-hour lifetime limit`,detail:`expires_at ${v_(s.expiresAt)} is ${l}ms from now`});l>YH&&(yield*k(`Accepted GitHub token clock skew; capped the local lease`,{installationId:e,operation:r,skewMillis:l-YH}));let u=mr(s.repositories,()=>[]);return n._tag===`SingleRepository`&&!(u.length===1&&u.every(e=>e.id===n.repositoryId))?yield*new AH({operation:r,message:`GitHub did not confirm that the worker token is scoped to exactly one repository`,detail:`expected repository ID ${n.repositoryId}, got [${u.map(e=>e.id).join(`, `)}]`}):new gH({value:V_(s.token),expiresAt:s_(c+Math.min(l,YH)),scope:n})}),c=O(`GitHubApp.installedRepositories`)(function*(e){let t=[];for(let n=1;;n+=1){let r=yield*i(`list-installation-repositories`,MB(`${MH}/installation/repositories?per_page=100&page=${n}`).pipe(PH(e.value)),eU);if(t.push(...r.repositories),t.length>=r.totalCount)return t;if(r.repositories.length===0)return yield*new AH({operation:`list-installation-repositories`,message:`GitHub returned an empty page before it listed total_count repositories`,detail:`page ${n} was empty after ${t.length} of ${r.totalCount} repositories`})}}),l=yield*aA(y()),u=O(`GitHubApp.lease`)(()=>sA(l,e=>T(function*(){let t=yield*Nf;if(S(e)&&h_(e.value.token.expiresAt)-t>XH)return[e.value,e];let n=yield*o(),r={installation:n,token:yield*s(n.id,new pH)};return[r,b(r)]}))),d=yield*aA(y()),f=O(`GitHubApp.botAccount`)(()=>sA(d,e=>T(function*(){let{installation:t,token:n}=yield*u(),{appSlug:r}=t;if(yield*D({appSlug:r}),S(e)&&e.value.appSlug===r)return[e.value.account,e];let a=new ZN(yield*i(`read-bot-account`,MB(`${MH}/users/${encodeURIComponent(`${r}[bot]`)}`).pipe(PH(n.value)),QH));return yield*k(`Read the App's bot account`,{appSlug:r,login:a.login,id:a.id}),[a,b({appSlug:r,account:a})]})));return{configureWebhook:O(`GitHubApp.configureWebhook`)(function*(n){yield*D({appId:e.appId});let i=yield*t();yield*r(`configure-webhook`,PB(`${MH}/app/hook/config`).pipe(YB({url:n.href,content_type:`json`}),PH(i))),yield*k(`Configured the App webhook endpoint`,{appId:e.appId})}),deliveries:a,repositories:O(`GitHubApp.repositories`)(function*(){let{token:e,installation:t}=yield*u();yield*D({installationId:t.id});let n=yield*c(e);return yield*A(`Listed installation repositories`,{count:n.length}),n.map(({name:e})=>e)}),installation:O(`GitHubApp.installation`)(()=>Th(u(),e=>e.installation)),botAccount:f,installationToken:O(`GitHubApp.installationToken`)(()=>Th(u(),e=>e.token)),projectAccess:O(`GitHubApp.projectAccess`)(function*(e){let{installation:t,token:n}=yield*u();return TH(t,e,yield*c(n))}),workerToken:O(`GitHubApp.workerToken`)((e,t)=>s(e.installationId,new mH({repository:e.repository,repositoryId:e.repositoryId,permissions:t})))}}))},iU=R.pipe(I(`GitHubEntityTag`)),aU=R.pipe(I(`GitHubBaseRefName`)),oU=class extends B(`@usine/github/BaseRefHead`)({baseRefName:aU,sha:lA,entityTag:AE(iU)}){},sU=class e extends B(`@usine/github/PollCursor`)({entityTag:AE(iU),watermark:AE(kE)}){static empty=new e({entityTag:y(),watermark:y()})},cU=class extends V(`@usine/github/ChangedIssue`)(`ChangedIssue`,{number:L.check($T(1)),updatedAt:OE}){},lU=class extends V(`@usine/github/ChangedPullRequest`)(`ChangedPullRequest`,{number:L.check($T(1)),updatedAt:OE}){},uU=P([cU,lU]),dU=class extends V(`@usine/github/RepositoryNotModified`)(`RepositoryNotModified`,{cursor:sU,nextPollAt:z(OE),backoffUntil:z(OE).pipe(IT(w(y())))}){},fU=class extends V(`@usine/github/RepositoryChanges`)(`RepositoryChanges`,{cursor:sU,items:N(uU),backlog:yT,nextPollAt:z(OE),backoffUntil:z(OE).pipe(IT(w(y())))}){};P([dU,fU]);var pU=R.pipe(I(`GitHubRepositoryLabelName`)),mU=j.check(GT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})).pipe(I(`GitHubRepositoryLabelColor`)),hU=class extends B(`@usine/github/RepositoryLabel`)({name:pU,color:mU,description:AE(j)}){},gU=WT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),_U=class extends B(`@usine/github/RepositoryLabelCatalog`)({entityTag:AE(iU),labels:N(hU).check(gU)}){},vU=class extends V(`@usine/github/RepositoryLabelsNotModified`)(`RepositoryLabelsNotModified`,{}){};P([_U,vU]);var yU=class extends B(`@usine/github/NewRepositoryLabel`)({name:pU,color:z(mU),description:z(j)}){},bU=M({name:pU,color:mU,description:F(j)}),xU=e=>{let{name:t,owner:n}=dA(e);return`${MH}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`},SU=class e extends kr()(`@usine/github/GitHubLabelWriter`){static layer=Df(e,T(function*(){let e=yield*rU,t=yield*fV;return{create:O(`GitHubLabelWriter.create`)(function*(n,r){yield*D({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=NB(xU(n)).pipe(YB(a),PH(i.value)),s=yield*t.execute(o).pipe(Ph(e=>FH(`create-repository-label`,e)));if(s.status<200||s.status>=300)return yield*GH(`create-repository-label`,s,yield*Nf);let c=yield*$B(bU)(s).pipe(Ph(e=>RH(`create-repository-label`,e.message)));return new hU({name:c.name,color:c.color,description:_r(c.description)})})}}))},CU=6e4,wU=M({data:lT(hT),errors:lT(N(M({message:j,type:lT(j)})))}),TU=O(`GitHub.queryGraphql`)(function*(e,t,n,r,i,a){let o=NB(`${MH}/graphql`).pipe(YB({query:r,variables:i}),PH(t.value)),s=yield*e.execute(o).pipe(Ph(e=>FH(n,e))),c=yield*Nf;if(s.status!==200)return yield*GH(n,s,c);let l=yield*$B(wU)(s).pipe(Ph(e=>RH(n,e.message)));if(l.errors!==void 0&&l.errors.length>0){if(l.errors.some(e=>e.type===`RATE_LIMITED`))return yield*new kH({operation:n,retryAt:s_(mr(WH(s.headers,c),()=>c+CU)),message:`GitHub GraphQL API rate limit exceeded`});if(!l.errors.every(e=>e.type===`NOT_FOUND`))return yield*RH(n,`GraphQL errors: ${l.errors.map(e=>e.message).join(`; `)}`)}return yield*Zw(a)(l.data).pipe(Ph(e=>RH(n,e.message)))}),EU=L.check($T(1)),DU=L.check($T(0)),OU=j.check(GT(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u,{message:`Expected a GitHub UTC timestamp`})),kU=(e,t)=>F(e).pipe(NT(e,{decode:Fy(e=>e??t),encode:Fy(e=>e)})),AU={totalCount:0,nodes:[]},jU=M({login:R}),MU=F(jU),NU=M({totalCount:DU,nodes:N(M({name:R}))}),PU=M({actor:F(M({login:R,type:R})),createdAt:OU}),FU=TT(j,PU).pipe(RT(w({}))),IU=M({totalCount:DU,nodes:N(M({author:MU,body:j,createdAt:OU}))}),LU=M({number:EU,title:j,body:j,url:R,state:j,stateReason:F(j),createdAt:OU,updatedAt:OU,closedAt:F(OU),author:MU,issueType:F(M({name:j})),milestone:F(M({title:j})),labels:kU(NU,AU),labelEvents:FU,assignees:M({totalCount:DU,nodes:N(jU)}),comments:IU,closedByPullRequestsReferences:kU(M({totalCount:DU,nodes:N(M({number:EU,state:j,isDraft:yT,url:R}))}),AU)}),RU=F(M({login:lT(R)})),zU=M({author:MU,state:j,body:j,submittedAt:F(OU),commit:F(M({oid:R}))}),BU=M({author:MU,body:j}),VU=M({number:EU,title:j,body:j,url:R,state:j,isDraft:yT,merged:yT,createdAt:OU,updatedAt:OU,mergedAt:F(OU),author:MU,baseRefName:aU,headRefName:j,headRefOid:R,additions:DU,deletions:DU,changedFiles:DU,reviewDecision:F(j),mergeable:j.pipe(RT(w(`UNKNOWN`))),mergeStateStatus:j.pipe(RT(w(`UNKNOWN`))),statusCheckRollup:F(M({state:j})),labels:kU(NU,AU),labelEvents:FU,reviewRequests:kU(M({totalCount:DU,nodes:N(M({requestedReviewer:RU}))}),AU),reviews:kU(M({totalCount:DU,nodes:N(zU)}),AU),reviewThreads:M({totalCount:DU,nodes:N(M({isResolved:yT,isOutdated:yT,path:j,comments:M({totalCount:DU,nodes:N(BU)})}))}),comments:IU,closingIssuesReferences:kU(M({totalCount:DU,nodes:N(M({number:EU,state:j}))}),AU)}),HU=j.check(GT(/^[a-f0-9]{64}$/u,{message:`Expected a SHA-256 content hash`})).pipe(I(`GitHubContentHash`)),UU=class extends V(`@usine/github/IssueSnapshot`)(`IssueSnapshot`,{payload:LU,contentHash:HU}){},WU=class extends V(`@usine/github/PullRequestSnapshot`)(`PullRequestSnapshot`,{payload:VU,contentHash:HU}){};P([UU,WU]);var GU=e=>`
32
+ timelineItems(last: 100, before: ${e}, itemTypes: [LABELED_EVENT]) {
33
+ pageInfo { hasPreviousPage startCursor }
34
+ nodes {
35
+ ... on LabeledEvent {
36
+ actor { login type: __typename }
37
+ createdAt
38
+ label { name }
39
+ }
40
+ }
41
+ }
42
+ `,KU=`
43
+ query UsineLabelEvents($owner: String!, $name: String!, $number: Int!, $before: String!) {
44
+ repository(owner: $owner, name: $name) {
45
+ issueOrPullRequest(number: $number) {
46
+ ... on Issue { ${GU(`$before`)} }
47
+ ... on PullRequest { ${GU(`$before`)} }
48
+ }
49
+ }
50
+ }
51
+ `,qU=`
52
+ query UsineIssuePayload($owner: String!, $name: String!, $number: Int!) {
53
+ repository(owner: $owner, name: $name) {
54
+ issue(number: $number) {
55
+ number
56
+ title
57
+ body
58
+ url
59
+ state
60
+ stateReason
61
+ createdAt
62
+ updatedAt
63
+ closedAt
64
+ author { login }
65
+ issueType { name }
66
+ milestone { title }
67
+ ${GU(`null`)}
68
+ labels(first: 50) {
69
+ totalCount
70
+ nodes { name }
71
+ }
72
+ assignees(first: 10) {
73
+ totalCount
74
+ nodes { login }
75
+ }
76
+ comments(last: 20) {
77
+ totalCount
78
+ nodes {
79
+ author { login }
80
+ body
81
+ createdAt
82
+ }
83
+ }
84
+ closedByPullRequestsReferences(first: 10, includeClosedPrs: true) {
85
+ totalCount
86
+ nodes {
87
+ number
88
+ state
89
+ isDraft
90
+ url
91
+ }
92
+ }
93
+ }
94
+ }
95
+ }
96
+ `,JU=`
97
+ query UsinePullRequestPayload($owner: String!, $name: String!, $number: Int!) {
98
+ repository(owner: $owner, name: $name) {
99
+ pullRequest(number: $number) {
100
+ number
101
+ title
102
+ body
103
+ url
104
+ state
105
+ isDraft
106
+ merged
107
+ createdAt
108
+ updatedAt
109
+ mergedAt
110
+ author { login }
111
+ baseRefName
112
+ headRefName
113
+ headRefOid
114
+ additions
115
+ deletions
116
+ changedFiles
117
+ reviewDecision
118
+ mergeable
119
+ mergeStateStatus
120
+ statusCheckRollup { state }
121
+ ${GU(`null`)}
122
+ labels(first: 50) {
123
+ totalCount
124
+ nodes { name }
125
+ }
126
+ reviewRequests(first: 10) {
127
+ totalCount
128
+ nodes {
129
+ requestedReviewer {
130
+ ... on User { login }
131
+ }
132
+ }
133
+ }
134
+ reviews(last: 20) {
135
+ totalCount
136
+ nodes {
137
+ author { login }
138
+ state
139
+ body
140
+ submittedAt
141
+ commit { oid }
142
+ }
143
+ }
144
+ reviewThreads(first: 50) {
145
+ totalCount
146
+ nodes {
147
+ isResolved
148
+ isOutdated
149
+ path
150
+ comments(first: 10) {
151
+ totalCount
152
+ nodes {
153
+ author { login }
154
+ body
155
+ }
156
+ }
157
+ }
158
+ }
159
+ comments(last: 20) {
160
+ totalCount
161
+ nodes {
162
+ author { login }
163
+ body
164
+ createdAt
165
+ }
166
+ }
167
+ closingIssuesReferences(first: 10) {
168
+ totalCount
169
+ nodes {
170
+ number
171
+ state
172
+ }
173
+ }
174
+ }
175
+ }
176
+ }
177
+ `,YU=e=>{let t=Array.from({length:e},(e,t)=>t);return`
178
+ query UsineIssuesPresent($owner: String!, $name: String!, ${t.map(e=>`$n${e}: Int!`).join(`, `)}) {
179
+ repository(owner: $owner, name: $name) {
180
+ ${t.map(e=>`i${e}: issue(number: $n${e}) { number }`).join(`
181
+ `)}
182
+ }
183
+ }
184
+ `},XU=10,ZU=M({pageInfo:M({hasPreviousPage:yT,startCursor:F(R)}),nodes:N(F(M({...PU.fields,label:M({name:R})})))}),QU=M({repository:AE(M({issueOrPullRequest:AE(M({timelineItems:ZU}))}))}),$U=O(`GitHubPolling.labelEvents`)(function*(e,t,n,r,i){yield*D({repository:t,item:n});let a=new Set(r.map(({name:e})=>e)),o=new Map,s=i,c=1;for(;;){for(let e of[...s.nodes].reverse())e!==null&&a.delete(e.label.name)&&o.set(e.label.name,{actor:e.actor,createdAt:e.createdAt});if(a.size===0||!s.pageInfo.hasPreviousPage)break;if(c>=XU||s.pageInfo.startCursor===null){if(yield*Cg(`Cannot complete current label provenance`,{repository:t,item:n,pages:c,missingLabels:[...a]}),s.pageInfo.startCursor===null)return yield*RH(`fetch-item-timeline`,`GitHub returned hasPreviousPage for label events without a startCursor`);break}yield*A(`Reading older events for current labels`,{repository:t,item:n,pages:c,missingLabels:[...a]});let r=yield*e.app.installationToken(),{owner:i,name:l}=dA(t),u=yield*TU(e.http,r,`fetch-item-timeline`,KU,{owner:i,name:l,number:n,before:s.pageInfo.startCursor},QU);if(x(u.repository))return yield*RH(`fetch-item-timeline`,`repository "${t}" is null`);let d=u.repository.value.issueOrPullRequest;if(x(d))return yield*new jH({operation:`fetch-item-timeline`,item:n,message:`GitHub item ${t}#${n} was not found while reading label events`});s=d.value.timelineItems,c+=1}return a.size>0&&!s.pageInfo.hasPreviousPage&&(yield*Cg(`GitHub has no label event for some current labels`,{repository:t,item:n,missingLabels:[...a]})),yield*A(`Read current label provenance`,{repository:t,item:n,pages:c,labels:o.size}),Object.fromEntries(o)}),eW=new Set([`closedAt`,`createdAt`,`mergedAt`,`submittedAt`,`updatedAt`]),tW=e=>Array.isArray(e)?e.map(tW):Xw(YE)(e)?Object.fromEntries(Object.entries(e).filter(([e,t])=>!eW.has(e)||!ee(t)&&t!==null).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,tW(t)])):e,nW=5e3,rW=100,iW=10,aW=100,oW=50,sW=N(M({number:L.check($T(1)),updatedAt:kE,pullRequest:lT(hT)}).pipe(wT({updatedAt:`updated_at`,pullRequest:`pull_request`}))),cW=M({object:M({sha:lA})}),lW=N(M({name:pU,color:mU,description:F(j)})),uW=({name:e,color:t,description:n})=>new hU({name:e,color:t,description:_r(n)}),dW=M({repository:AE(M({issue:AE(M({...LU.fields,timelineItems:ZU}))}))}),fW=M({repository:AE(M({pullRequest:AE(M({...VU.fields,timelineItems:ZU}))}))}),pW=F(M({number:L})),mW=e=>M({repository:AE(M(Object.fromEntries(Array.from({length:e},(e,t)=>[`i${t}`,pW]))))}),hW=e=>c_(e),gW=e=>e.map(e=>e.pullRequest===void 0?new cU({number:e.number,updatedAt:e.updatedAt}):new lU({number:e.number,updatedAt:e.updatedAt})),_W=e=>{let t=e.flatMap(e=>pr(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?y():hW(Math.max(...t))},vW=(e,t)=>_W([BH(e[`retry-after`],t),VH(e,rW)]),yW=(e,t)=>_W([HH(e,t),BH(e[`retry-after`],t),VH(e,rW)]),bW=e=>{let t=h_(e)-nW;return`${new Date(t-t%1e3).toISOString().slice(0,19)}Z`},xW=(e,t)=>{let{name:n,owner:r}=dA(e),i=new URL(`${MH}/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`,bW(t.watermark.value)),i.toString()},SW=e=>{let{name:t,owner:n}=dA(e),r=new URL(`${MH}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`);return r.searchParams.set(`per_page`,`100`),r.toString()},CW=(e,t)=>{let{name:n,owner:r}=dA(e),i=t.split(`/`).map(encodeURIComponent).join(`/`);return`${MH}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/git/ref/heads/${i}`},wW=(e,t)=>{let{name:n,owner:r}=dA(e),i=new URL(`${MH}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues/${t}/labels`);return i.searchParams.set(`per_page`,`100`),i.toString()},TW=(e,t)=>{let n=t.map(({updatedAt:e})=>h_(e));return S(e.watermark)&&n.push(h_(e.watermark.value)),n.length===0?y():hW(Math.max(...n))},EW=class e extends kr()(`@usine/github/GitHubPolling`){static layer=Df(e,T(function*(){let e=yield*rU,t=yield*sk,n=yield*fV,r=DW(t),i=O(`GitHubPolling.execute`)(function*(e,t){return yield*n.execute(t).pipe(Ph(t=>FH(e,t)))}),a=O(`GitHubPolling.changesPage`)(function*(t){let n=yield*e.installationToken(),r=MB(t).pipe(PH(n.value)),a=yield*i(`poll-repository-changes`,r),o=yield*Nf;return a.status===200?{items:gW(yield*$B(sW)(a).pipe(Ph(e=>RH(`poll-repository-changes`,e.message)))),next:KH(a.headers.link)}:yield*GH(`poll-repository-changes`,a,o)}),o=O(`GitHubPolling.labelsPage`)(function*(t,n){let r=yield*e.installationToken(),a=MB(n).pipe(PH(r.value)),o=yield*i(t,a),s=yield*Nf;return o.status===200?{labels:(yield*$B(lW)(o).pipe(Ph(e=>RH(t,e.message)))).map(uW),next:KH(o.headers.link)}:yield*GH(t,o,s)}),s=O(`GitHubPolling.remainingLabelPages`)(function*(e,t){let n=[...t.labels],r=t.next,i=1;for(;S(r)&&i<aW;){let t=yield*o(e,r.value);n.push(...t.labels),r=t.next,i+=1}return S(r)?yield*RH(e,`the GitHub label list has more than ${aW} pages`):n.sort((e,t)=>e.name.localeCompare(t.name))}),c=O(`GitHubPolling.allLabels`)(function*(e,t){return yield*s(e,yield*o(e,t))}),l=O(`GitHubPolling.labels`)(function*(t,n){yield*D({repository:t});let r=yield*e.installationToken(),a=MB(SW(t)).pipe(PH(r.value));S(n)&&(a=LB(a,`if-none-match`,n.value));let o=yield*i(`list-repository-labels`,a),c=yield*Nf;if(o.status===304)return new vU;if(o.status!==200)return yield*GH(`list-repository-labels`,o,c);let l=yield*$B(lW)(o).pipe(Ph(e=>RH(`list-repository-labels`,e.message))),u=yield*s(`list-repository-labels`,{labels:l.map(uW),next:KH(o.headers.link)}),d=$w(iU)(o.headers.etag);return x(d)&&(yield*Cg(`GitHub omitted the label catalog ETag; next poll is unconditional`,{repository:t})),new _U({entityTag:d,labels:u})}),u=O(`GitHubPolling.changes`)(function*(t,n){let r=yield*e.installationToken(),o=MB(xW(t,n)).pipe(PH(r.value));S(n.entityTag)&&(o=LB(o,`if-none-match`,n.entityTag.value));let s=yield*i(`poll-repository-changes`,o),c=yield*Nf,l=yW(s.headers,c);if(s.status===304)return new dU({cursor:n,nextPollAt:l,backoffUntil:vW(s.headers,c)});if(s.status!==200)return yield*GH(`poll-repository-changes`,s,c);let u=gW(yield*$B(sW)(s).pipe(Ph(e=>RH(`poll-repository-changes`,e.message)))),d=$w(iU)(s.headers.etag);x(d)&&(yield*Cg(`GitHub omitted the changes ETag; next poll is unconditional`,{repository:t}));let f=[...u],p=KH(s.headers.link),m=1;for(;S(p)&&m<iW;){let e=yield*a(p.value);f.push(...e.items),p=e.next,m+=1}let h=S(p);return h&&(yield*k(`GitHub changes walk hit the page cap; backlog remains`,{repository:t,pages:m,items:f.length})),new fU({cursor:new sU({entityTag:d,watermark:TW(n,f)}),items:f,backlog:h,nextPollAt:l,backoffUntil:vW(s.headers,c)})}),d=O(`GitHubPolling.baseRefHead`)(function*(t,n,r){yield*D({repository:t,baseRefName:n});let a=yield*e.installationToken(),o=MB(CW(t,n)).pipe(PH(a.value)),s=Cr(r,({entityTag:e})=>e);S(s)&&(o=LB(o,`if-none-match`,s.value));let c=yield*i(`fetch-base-ref-head`,o),l=yield*Nf;if(c.status===304&&S(r))return r.value;if(c.status!==200)return yield*GH(`fetch-base-ref-head`,c,l);let u=yield*$B(cW)(c).pipe(Ph(e=>RH(`fetch-base-ref-head`,e.message))),d=$w(iU)(c.headers.etag);return x(d)&&(yield*Cg(`GitHub omitted the base branch ETag; next read is unconditional`,{repository:t,baseRefName:n})),new oU({baseRefName:n,sha:u.object.sha,entityTag:d})}),f=O(`GitHubPolling.graphql`)(function*(t,r,i,a,o){let s=yield*e.installationToken(),{name:c,owner:l}=dA(r);return yield*TU(n,s,t,a,{owner:l,name:c,number:i},o)});return{changes:u,labels:l,baseRefHead:d,snapshot:O(`GitHubPolling.snapshot`)((t,i)=>T(function*(){let a=e=>RH(e,`repository "${t}" is null: deleted, renamed, or no longer accessible`),o=(e,n)=>new jH({operation:e,item:i.number,message:`GitHub ${n} ${t}#${i.number} was not found. It was deleted or transferred, or the GitHub App can no longer read it.`}),s=O(`GitHubPolling.completeItemLabels`)(function*(e){if(e.labels.nodes.length>=e.labels.totalCount)return e.labels;yield*A(`Completing truncated Item label connection for Board matching`,{repository:t,item:i.number,listedLabels:e.labels.nodes.length,totalLabels:e.labels.totalCount});let n=yield*c(`fetch-item-labels`,wW(t,i.number));return{totalCount:n.length,nodes:n.map(({name:e})=>({name:e}))}});if(i._tag===`ChangedIssue`){let c=yield*f(`fetch-issue-snapshot`,t,i.number,qU,dW);if(x(c.repository))return yield*a(`fetch-issue-snapshot`);let l=c.repository.value.issue;if(x(l))return yield*o(`fetch-issue-snapshot`,`issue`);let{timelineItems:u,...d}=l.value,p=yield*s(d),m={...d,labels:p,labelEvents:yield*$U({http:n,app:e},t,i.number,p.nodes,u)};return new UU({payload:m,contentHash:yield*r(m)})}let l=yield*f(`fetch-pull-request-snapshot`,t,i.number,JU,fW);if(x(l.repository))return yield*a(`fetch-pull-request-snapshot`);let u=l.repository.value.pullRequest;if(x(u))return yield*o(`fetch-pull-request-snapshot`,`pull request`);let{timelineItems:d,...p}=u.value,m=yield*s(p),h={...p,labels:m,labelEvents:yield*$U({http:n,app:e},t,i.number,m.nodes,d)};return new WU({payload:h,contentHash:yield*r(h)})})),missingIssues:O(`GitHubPolling.missingIssues`)(function*(t,r){yield*D({repository:t,issues:r.length});let{name:i,owner:a}=dA(t);return(yield*rh(Ji(r,oW),r=>T(function*(){let o=yield*e.installationToken(),s=yield*TU(n,o,`find-missing-issues`,YU(r.length),{owner:a,name:i,...Object.fromEntries(r.map((e,t)=>[`n${t}`,e]))},mW(r.length));if(x(s.repository))return yield*RH(`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()})}}))},DW=e=>O(`GitHubPolling.contentHash`)(function*(t){let n=new TextEncoder().encode(JSON.stringify(tW(t))),r=yield*e.digest(`SHA-256`,n).pipe(Fh);return HU.make(Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``))}),OW=class extends B(`@usine/orchestrator/LabelPreflightFinding`)({repository:H,label:MA,errorTag:R,message:R}){},kW=(e,t)=>{let n=[];if(S(e.color)){let r=e.color.value.toLowerCase();pr(t.color,{onNone:()=>!0,onSome:e=>e.toLowerCase()!==r})&&n.push(`color`)}if(S(e.description)){let r=e.description.value;pr(t.description,{onNone:()=>!0,onSome:e=>e!==r})&&n.push(`description`)}return n},AW=e=>new yU({name:pU.make(e.name),color:Sr(e.color,mU.make),description:e.description}),jW=class e extends kr()(`@usine/orchestrator/LabelReconciler`){static layer=Df(e,T(function*(){let e=yield*SU;return{reconcile:O(`LabelReconciler.reconcile`)(function*(t,n,r){yield*D({repository:t});let i=[...r],a=new Map(r.map(e=>[NA(e.name),e])),o=[],s=!1,c=y();for(let r of n){let n=a.get(NA(r.name));if(n!==void 0){let e=kW(r,n);e.length>0?yield*Cg(`Declared GitHub label differs from the existing repository label; left unchanged`,{repository:t,label:r.name,drift:e.join(`, `)}):yield*A(`Declared GitHub label already exists`,{repository:t,label:r.name});continue}let l=yield*Sh(e.create(t,AW(r)));if(vi(l)){let e=l.failure;if(o.push(new OW({repository:t,label:r.name,errorTag:e._tag,message:e.message})),e._tag===`GitHubRateLimitError`){c=b(e.retryAt),yield*Cg(`Label creation rate-limited; remaining declarations deferred and trigger evaluation continues`,{repository:t,label:r.name,errorTag:e._tag,message:e.message,retryAt:v_(e.retryAt)});break}yield*wg(`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 Pz({name:l.success.name,color:b(l.success.color),description:l.success.description});i.push(u),a.set(NA(u.name),u),s=!0,yield*k(`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}})}}))},MW=e=>j.check(GT(/\S/u,{message:e})),NW=e=>WT(t=>new Set(t.map(t=>fA(e(t)))).size===t.length,{message:`Expected unique repository names, ignoring case`}),PW=MW(`Expected a non-blank lane name`).pipe(I(`LaneName`)),FW=jT([`issue-open`,`issue-closed`,`pr-open`,`pr-closed`,`pr-merged`]),IW=jT([`issue-closed`,`pr-closed`,`pr-merged`]),LW=Xw(IW),RW=e=>LW(e),zW=class extends B(`@usine/config/LabelLaneSource`)({label:MA}){},BW=P([zW,class extends B(`@usine/config/StateLaneSource`)({state:FW}){}]),VW=class extends B(`@usine/config/Lane`)({name:PW,sources:N(BW).check(iE())}){},HW=class extends B(`RunAgain`)(tN({from:LN,requestedBy:AE(ZM)})){},UW=class extends V(`@usine/orchestrator/GitHubPushFailureView`)(`GitHubPushFailure`,{message:j}){},WW=class extends V(`@usine/orchestrator/InfraFailureView`)(`InfraFailure`,{message:j}){},GW=class extends V(`@usine/orchestrator/ProviderCapacityFailureView`)(`ProviderCapacityFailure`,{message:j}){},KW=class extends V(`@usine/orchestrator/DefectFailureView`)(`DefectFailure`,{message:j}){},qW=class extends V(`@usine/orchestrator/AgentFailureView`)(`AgentFailure`,{message:j}){},JW=class extends V(`@usine/orchestrator/BlockedFailureView`)(`BlockedFailure`,{message:j}){},YW=class extends V(`@usine/orchestrator/QuestionFailureView`)(`QuestionFailure`,{question:j}){},XW=class extends V(`@usine/orchestrator/RunawayFailureView`)(`RunawayFailure`,{ceiling:fF}){},ZW=class extends V(`@usine/orchestrator/ChildSessionBudgetFailureView`)(`ChildSessionBudgetFailure`,{maxChildren:PP,attemptedChildren:FP}){},QW=P([UW,WW,GW,KW,qW,JW,YW,XW,ZW]),$W=class extends V(`@usine/orchestrator/SucceededAttemptView`)(`Succeeded`,{}){},eG=class extends V(`@usine/orchestrator/FailedAttemptView`)(`Failed`,{failure:QW}){},tG=class extends V(`@usine/orchestrator/CanceledAttemptView`)(`Canceled`,{}){},nG=P([$W,eG,tG]),rG=class extends V(`@usine/orchestrator/LocalWorkerAccess`)(`Local`,{}){},iG=class extends V(`@usine/orchestrator/SshWorkerAccess`)(`Ssh`,{destination:QN,port:F($N)}){},aG=class extends V(`@usine/orchestrator/ProvisionedWorkerAccess`)(`Provisioned`,{provider:gP}){},oG=class extends V(`@usine/orchestrator/SandboxWorkerAccess`)(`Sandbox`,{}){},sG=P([rG,iG,aG,oG]),cG=class extends B(`@usine/orchestrator/AttemptView`)({id:jF,number:MF,worker:qN,workerAccess:F(sG),brain:xA,task:PF,agent:SA,operatorIntervened:yT,startedAt:j,outcome:F(nG),endedAt:F(j),salvage:F(SF),start:F(AF).pipe(IT(w(null))),reattachedAt:F(j).pipe(IT(w(null))),outOfMemory:F(zF).pipe(IT(w(null)))}){},lG=YN.make(`exe-dev-github-integration[bot]`),uG=j.check(GT(/^[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*$/u,{message:`Expected an exe.dev integration name of letters and digits, separated by single dots, underscores, or hyphens`})).pipe(I(`ExeDevIntegrationName`));j.check(GT(/^\/[^\0\r\n]*$/u,{message:`Expected an absolute remote home directory without control bytes`})).pipe(I(`ExeDevHomePath`)),B(`@usine/executor/ExeDevGitHubIntegration`)({repository:H,name:uG}),L.check($T(1)).pipe(I(`ExeDevCredentialGrantMinutes`));var dG=(e,t)=>{switch(e){case`local`:case`ssh`:case`cloudflare`:return t;case`exe.dev`:return lG}},fG=jT([`preflight`,`prepare`,`launch`,`cancel`,`cleanup`]),pG=jT([`machine`,`toolchain`,`memory`,`harness-login`,`credentials`,`gateway`,`container`,`provider`]),mG=class extends WE(`@usine/executor/ExecutorOperationError`)(`ExecutorOperationError`,{operation:fG,message:R,cause:dE()}){},hG=jT([`refused`,`unreachable`]),gG=class extends WE(`@usine/executor/CredentialUnavailableError`)(`CredentialUnavailableError`,{repository:H,reason:hG,message:R,cause:dE()}){},_G=class extends WE(`@usine/executor/WorkerCapabilityError`)(`WorkerCapabilityError`,{worker:qN,capability:pG,message:R,cause:dE()}){},vG=jT([`capacity`,`quota`,`refused`,`provider`,`unreachable`,`timeout`]);WE(`@usine/executor/MachineUnavailableError`)(`MachineUnavailableError`,{worker:qN,provider:gP,reason:vG,message:R}),P([mG,gG,_G]),B(`@usine/executor/CheckoutRequest`)({attemptId:jF,worker:qN,repository:H,loop:DA,permissions:jA,revision:cA,payload:JE,task:PF,agent:wA,parentModel:z(vA),maxChildren:PP,maxAttemptMinutes:z(L.check(QT(0))),maxAttemptTokens:z(L.check(QT(0))),parentEffort:bA,salvageRef:yF,resume:z(xF),reattach:yT.pipe(IT(w(!1))),botLogin:z(YN).pipe(IT(w(y()))),commitAuthor:ZN});var yG=R.pipe(I(`WorktreePath`));B(`@usine/executor/AttemptWorkspace`)({worker:qN,spec:Hee,worktree:yG});var bG=Hw(e=>B_(e)&&ee(U_(e)),{expected:`Redacted<string>`});B(`@usine/executor/WorkerCredential`)({value:bG,expiresAt:OE}),kr()(`@usine/executor/CredentialProvider`),kr()(`@usine/executor/Executor`);var xG=R.pipe(I(`MachineHold`)),SG=class extends B(`@usine/executor/MachineCheck`)({brains:N(xA),containerLimits:z(dP)}){};B(`@usine/executor/MachineGrant`)({hold:xG,id:_P,worker:qN,provider:gP,checked:z(SG)});var CG=jT([`creating`,`ready`,`deleting`]);B(`@usine/executor/MachineStatus`)({worker:qN,provider:gP,state:CG,id:z(_P),runId:z(LN),attemptId:z(jF),since:OE}),kr()(`@usine/executor/WorkerMachines`);var wG=class extends B(`@usine/orchestrator/MachineQuotaWait`)({worker:qN,message:j}){},TG=e=>new Map(e.flatMap(e=>pr(e.quota,{onNone:()=>[],onSome:t=>e.waitingRuns.map(n=>[n,new wG({worker:e.worker,message:t})])}))),EG=class extends B(`@usine/orchestrator/MachineView`)({worker:qN,provider:gP,state:CG,id:F(_P),runId:F(LN),attemptId:F(jF),since:j}){},DG=class extends B(`@usine/orchestrator/ProvisioningPauseView`)({reason:P([vG,pT(`check`)]),message:j,failures:L,failedAt:j,retryAt:j,blocked:yT}){},OG=class extends V(`@usine/orchestrator/HetznerProvisionerView`)(`hetzner`,{tokenEnv:j,serverType:vP,location:yP,image:bP,network:F(xP),firewall:F(xP).pipe(IT(w(null))),sshKey:xP,sshUser:wP,labels:TT(j,j),anthropicKeyEnv:F(j),openaiKeyEnv:F(j)}){},kG=class extends V(`@usine/orchestrator/BoatProvisionerView`)(`boat`,{tokenEnv:j,size:TP,anthropicKeyEnv:F(j),openaiKeyEnv:F(j)}){},AG=P([OG,kG]),jG=e=>new EG({worker:e.worker,provider:e.provider,state:e.state,id:C(e.id),runId:C(e.runId),attemptId:C(e.attemptId),since:v_(e.since)}),MG=e=>new DG({reason:e.reason,message:e.message,failures:e.failures,failedAt:v_(e.failedAt),retryAt:v_(e.retryAt),blocked:e.blocked}),NG=e=>pr(e.provisioner,{onNone:()=>null,onSome:e=>e.provider===`hetzner`?new OG({tokenEnv:e.tokenEnv,serverType:e.serverType,location:e.location,image:e.image,network:C(e.network),firewall:C(e.firewall),sshKey:e.sshKey,sshUser:e.sshUser,labels:e.labels,anthropicKeyEnv:C(e.apiKeys.anthropic),openaiKeyEnv:C(e.apiKeys.openai)}):new kG({tokenEnv:e.tokenEnv,size:e.size,anthropicKeyEnv:C(e.apiKeys.anthropic),openaiKeyEnv:C(e.apiKeys.openai)})}),PG=L.check($T(1)).pipe(I(`TranscriptSequence`)),FG=jT([3,4]),IG=M({...vI.fields,version:FG}),LG=M({_tag:pT(`InboundEnvelope`),version:FG,attemptId:jF,sequence:XF,sentAt:kE,payload:P([rI,iI])}),RG=jT([5,6]),zG=P([bI,M({...vI.fields,version:RG}),M({...yI.fields,version:RG}),IG,LG]),BG=class extends B(`@usine/engine/TranscriptEntry`)({sequence:PG,attemptId:jF,direction:QF,envelope:zG,receivedAt:OE}){},VG=class extends V(`@usine/engine/TranscriptAllQuery`)(`TranscriptAllQuery`,{attemptId:jF}){},HG=class extends V(`@usine/engine/TranscriptSessionsQuery`)(`TranscriptSessionsQuery`,{attemptId:jF}){},UG=class extends V(`@usine/engine/TranscriptWorkerQuery`)(`TranscriptWorkerQuery`,{attemptId:jF}){},WG=class extends V(`@usine/engine/TranscriptUsageQuery`)(`TranscriptUsageQuery`,{attemptId:jF}){},GG=class extends V(`@usine/engine/TranscriptTailQuery`)(`TranscriptTailQuery`,{attemptId:jF,after:PG,limit:L.check($T(1))}){},KG=class extends V(`@usine/engine/TranscriptPageQuery`)(`TranscriptPageQuery`,{attemptId:jF,before:z(PG),limit:L.check($T(1))}){};P([VG,HG,UG,WG,GG,KG]);var qG=class extends V(`@usine/orchestrator/FailedTranscriptView`)(`Failed`,{failure:QW}){},JG=P([$F,eI,tI,qG,nI,rI,iI,oI,sI,aI,pI,mI,hI,gI]),YG=class extends B(`@usine/orchestrator/TranscriptEventView`)({sequence:PG,attemptId:jF,receivedAt:j,direction:QF,target:lT(dI),operator:lT(R),payload:JG}){},XG=class extends B(`@usine/orchestrator/TranscriptPageCursor`)({attemptId:jF,before:PG}){},ZG=class extends V(`@usine/orchestrator/ColdTranscriptRequest`)(`ColdTranscriptRequest`,{}){},QG=class extends V(`@usine/orchestrator/TailTranscriptRequest`)(`TailTranscriptRequest`,{after:PG}){},$G=class extends V(`@usine/orchestrator/EarlierTranscriptRequest`)(`EarlierTranscriptRequest`,{attemptId:jF,before:PG}){};P([ZG,QG,$G]);var eK=class extends WE(`@usine/orchestrator/TranscriptAttemptNotFoundError`)(`TranscriptAttemptNotFoundError`,{runId:LN,attemptId:jF}){},tK=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}]]),nK=(e,t)=>Sr(_r(tK.get(e)),e=>KP.make((t.input*e.input+t.cachedInput*e.cachedInput+t.cacheWrite*(e.cacheWrite??e.input)+t.output*e.output)/1e6)),rK=class extends B(`@usine/engine/RunSnapshot`)({event:iN,itemKey:xI,run:RN,step:KN,attempts:N(HF),resolvedFailureAttemptId:z(jF),closedAt:z(OE),approval:z(NI),runAgain:z(HW),repository:H,revision:cA,task:PF,agent:wA,parentModel:z(vA),permissions:jA}){},iK=class extends B(`@usine/engine/RunEvent`)({runId:LN,event:iN}){},aK=class extends B(`@usine/engine/RunEvidence`)({snapshot:rK,transcript:N(BG)}){},oK=class extends B(`@usine/engine/RunSummary`)({itemKey:xI,run:RN,step:KN,attempts:N(HF),resolvedFailureAttemptId:z(jF),closedAt:z(OE),approval:z(NI),runAgain:z(HW),repository:H,task:PF,agent:wA}){},sK=class extends B(`@usine/engine/WorkerAttempts`)(M({worker:qN,attempts:L.check($T(1)),running:L.check($T(0))}).check(WT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},cK=class extends B(`@usine/engine/LoopSighting`)({loop:DA,itemKey:xI,event:z(nN),run:z(LN),suppressedBy:z(LN)}){},lK=L.check($T(0)).pipe(I(`ProjectionRevision`)),uK=M({eventId:nN,dedupKey:rN,payload:JE,receivedAt:kE,itemKey:xI,loop:DA,step:GN,approval:kA,permissions:jA,cycleLimit:F(CI),cycleGeneration:wI,repository:H,revision:cA,task:PF,agent:wA,parentModel:F(vA)}),dK=M({itemKey:xI,repository:H,revision:cA,task:PF,agent:wA,parentModel:F(vA),runId:LN,eventId:nN,loop:DA,state:_N,resolvedFailureAttemptId:F(jF),openedAt:kE,closedAt:F(kE),stepName:GN,result:F(WN),approvedAt:F(kE),approvalChannel:F(jI),approver:F(ZM),againFrom:F(LN),againRequestedBy:F(ZM)}),fK=M({attemptId:jF,runId:LN,stepName:GN,worker:qN,number:MF,brain:xA,task:PF,agent:SA,operatorIntervened:yT,parentModel:F(vA),startedAt:kE,outcome:F(vF),endedAt:F(kE),salvage:F(SF),start:F(AF),failureResolution:F(LF),reattachedAt:F(kE),comments:F(N(HN)),outOfMemory:F(N(BF))}),pK=M({sequence:PG,attemptId:jF,direction:QF,envelope:BG.fields.envelope,receivedAt:kE}),mK=M({runId:LN}),hK=M({reason:tz}),gK=M({revision:lK}),_K=M({runId:LN,eventId:nN,dedupKey:rN,payload:JE,receivedAt:kE}),vK=M({...uK.fields,reopening:L}),yK=M({eventId:nN,dedupKey:rN}),bK=Zw(N(uK)),xK=Zw(N(vK)),SK=Zw(N(yK)),CK=Zw(N(dK)),wK=Zw(N(_K)),TK=Zw(N(fK)),EK=Zw(N(mK)),DK=Zw(N(hK)),OK=Zw(N(gK)),kK=Zw(N(pK)),AK=oT(JE),jK=oT(kE),MK=oT(_N),NK=oT(vF),PK=oT(SF),FK=oT(N(HN)),IK=oT(N(BF)),LK=Zw(N(M({outOfMemory:F(N(BF))}))),RK=oT(LF),zK=oT(AF),BK=Zw(N(M({nextStart:F(kF)}))),VK=oT(WN),HK=oT(bI),UK=oT(wA),WK=oT(xA),GK=Xw(Oz),KK=e=>t=>Ph(t,t=>GK(t)?t:new Ez({operation:e,cause:t})),qK=e=>new iN({id:e.eventId,dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),JK=e=>new iK({runId:e.runId,event:qK(e)}),YK=e=>new JR({event:qK(e),itemKey:e.itemKey,loop:e.loop,step:e.step,approval:e.approval,permissions:e.permissions,cycleLimit:_r(e.cycleLimit),cycleGeneration:e.cycleGeneration,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:_r(e.parentModel)}),XK=e=>new RN({id:e.runId,eventId:e.eventId,loop:e.loop,state:e.state,openedAt:e.openedAt}),ZK=e=>Sr(_r(e.approvedAt),t=>new NI({approvedAt:t,source:Sr(_r(e.approvalChannel),t=>new MI({channel:t,approver:_r(e.approver)}))})),QK=e=>Sr(_r(e.againFrom),t=>new HW({from:t,requestedBy:_r(e.againRequestedBy)})),$K=e=>new KN({runId:e.runId,name:e.stepName,result:_r(e.result)}),eq=e=>new HF({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:_r(e.parentModel),startedAt:e.startedAt,outcome:_r(e.outcome),endedAt:_r(e.endedAt),salvage:_r(e.salvage),start:_r(e.start),failureResolution:_r(e.failureResolution),reattachedAt:_r(e.reattachedAt),comments:e.comments??[],outOfMemory:cee(e.outOfMemory??[],Bi).pipe(Sr(VF))}),tq=(e,t)=>new oK({itemKey:e.itemKey,run:XK(e),step:$K(e),attempts:t.map(eq),resolvedFailureAttemptId:_r(e.resolvedFailureAttemptId),closedAt:_r(e.closedAt),approval:ZK(e),runAgain:QK(e),repository:e.repository,task:e.task,agent:e.agent}),nq=e=>new BG({sequence:e.sequence,attemptId:e.attemptId,direction:e.direction,envelope:e.envelope,receivedAt:e.receivedAt}),rq=uM($.leftoversDiscardedAt),iq=uM($.outcomeJson),aq=e=>{let t=O(`RunStoreQueries.attemptCountsByWorker`)(function*(){let t=yield*e.select({worker:$.workerName,attempts:J`count(*)`,running:J`sum(case when ${iq} then 1 else 0 end)`}).from($).where(rq).groupBy($.workerName).orderBy(CM($.workerName)).execute();return yield*Zw(N(sK))(t)});return{attemptCountsByWorker:t,openAttempts:O(`RunStoreQueries.openAttempts`)(function*(e){return(yield*t()).find(t=>t.worker===e)?.running??0}),discardLeftovers:O(`RunStoreQueries.discardLeftovers`)(function*(t,n){return(yield*e.update($).set({leftoversDiscardedAt:jK(n)}).where(tM(Y($.workerName,t),rq)).returning({attemptId:$.attemptId}).execute()).map(({attemptId:e})=>e)})}},oq={itemKey:cz.itemKey,repository:cz.repository,generation:cz.generation,ask:cz.askJson,resetPending:cz.resetPending},sq=Zw(N(yR),{onExcessProperty:`error`}),cq=e=>{let t=Y(Z.cycleGeneration,J`coalesce((
185
+ select ${cz.generation} from ${cz}
186
+ where ${cz.itemKey} = ${Z.itemKey}
187
+ ), 0)`),n=O(`CycleBudget.get`)(function*(t){return yield*D({itemKey:t}),_r((yield*e.select(oq).from(cz).where(Y(cz.itemKey,t)).execute().pipe(E(sq)))[0])}),r=O(`CycleBudget.counts`)(function*(t){yield*D({itemKey:t.itemKey,generation:t.generation});let n=fM(e.select({id:$.attemptId}).from($).where(Y($.runId,Q.runId))),r=J`json_extract(${Q.stateJson}, '$._tag')`,i=yield*e.select({loop:lz.loop,admitted:J`count(*)`,completed:J`sum(case when ${lM(r,[...TN])} and ${n} then 1 else 0 end)`}).from(lz).innerJoin(Q,Y(Q.runId,lz.runId)).where(tM(Y(lz.itemKey,t.itemKey),Y(lz.generation,t.generation),nM($j(r,`Canceled`),n))).groupBy(lz.loop).orderBy(CM(lz.loop)).execute();return yield*Zw(N(DI))(i,{onExcessProperty:`error`})});return{admit:O(`CycleBudget.admit`)(function*(t){yield*D({itemKey:t.itemKey,loop:t.loop});let i=yield*n(t.itemKey);if(S(i)&&S(i.value.ask))return yield*k(`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(cz).values({itemKey:t.itemKey,repository:t.repository}).onConflictDoNothing().execute();let a=yield*n(t.itemKey);if(x(a))return yield*hh(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 kI({id:OI.make(nN.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(cz).set({askJson:oT(kI)(c)}).where(Y(cz.itemKey,t.itemKey)).execute(),yield*Cg(`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:O(`CycleBudget.reserve`)(function*(t,i){if(x(t.cycleLimit))return;yield*D({runId:i,itemKey:t.itemKey,loop:t.loop});let a=yield*n(t.itemKey);if(x(a))return yield*hh(Error(`Run admitted without its cycle budget`));yield*e.insert(lz).values({runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation}).onConflictDoNothing().execute(),yield*k(`Item cycle reserved`,{runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation,counts:yield*r(a.value)})}),get:n,asks:O(`CycleBudget.asks`)(function*(){return(yield*e.select(oq).from(cz).where(dM(cz.askJson)).execute().pipe(E(sq))).flatMap(({ask:e})=>wr(e))}),pendingResets:O(`CycleBudget.pendingResets`)(function*(){return yield*e.select(oq).from(cz).where(Y(cz.resetPending,!0)).execute().pipe(E(sq))}),isCurrentEvent:O(`CycleBudget.isCurrentEvent`)(function*(e){yield*D({eventId:e.event.id,itemKey:e.itemKey});let t=pr(yield*n(e.itemKey),{onNone:()=>0,onSome:e=>e.generation}),r=e.cycleGeneration===t;return r||(yield*k(`Event observation was superseded by a cycle reset`,{eventId:e.event.id,itemKey:e.itemKey,observedGeneration:e.cycleGeneration,generation:t})),r}),currentEvent:t}},lq=Zw(N(M({observedEventId:F(nN),suppressedByRunId:F(LN),suppressedEventId:F(nN)}))),uq=Zw(N(M({loop:DA,itemKey:xI,observedEventId:F(nN),suppressedByRunId:F(LN)}))),dq=Zw(N(M({eventId:nN,reopensEventId:nN}))),fq=Zw(N(M({eventId:nN,runId:LN}))),pq=e=>{let t=(e,t)=>tM(Y(sz.loopName,e),Y(sz.itemKey,t)),n=O(`LoopItems.row`)(function*(n,r){return _r((yield*lq(yield*e.select({observedEventId:sz.observedEventId,suppressedByRunId:sz.suppressedByRunId,suppressedEventId:sz.suppressedEventId}).from(sz).where(t(n,r)).execute()))[0])});return{sighted:O(`LoopItems.sighted`)(function*(t,r,i){let a=Sr(yield*n(t,r),({observedEventId:e})=>_r(e));return yield*e.insert(sz).values({loopName:t,itemKey:r,observedEventId:i}).onConflictDoUpdate({target:[sz.loopName,sz.itemKey],set:{observedEventId:i}}).execute(),a}),unmatched:O(`LoopItems.unmatched`)(function*(n,r){yield*e.update(sz).set({observedEventId:null,suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),suppression:O(`LoopItems.suppression`)(function*(e,t){return Cr(yield*n(e,t),({suppressedByRunId:e,suppressedEventId:t})=>e===null?y():b({runId:e,suppressedEventId:_r(t)}))}),startSuppression:O(`LoopItems.startSuppression`)(function*(t,r,i,a,o){if(Dr(yield*n(t,r),({observedEventId:e})=>e===null))return!1;let s=C(o);return yield*e.insert(sz).values({loopName:t,itemKey:r,observedEventId:a,suppressedByRunId:i,suppressedEventId:s}).onConflictDoUpdate({target:[sz.loopName,sz.itemKey],set:{suppressedByRunId:i,suppressedEventId:s}}).execute(),!0}),suppressFrom:O(`LoopItems.suppressFrom`)(function*(n,r,i){yield*e.update(sz).set({suppressedEventId:i}).where(tM(t(n,r),dM(sz.suppressedByRunId))).execute()}),lift:O(`LoopItems.lift`)(function*(n,r){yield*e.update(sz).set({suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),liftRun:O(`LoopItems.liftRun`)(function*(t){return(yield*e.update(sz).set({suppressedByRunId:null,suppressedEventId:null}).where(Y(sz.suppressedByRunId,t)).returning({loopName:sz.loopName}).execute()).length>0}),sightings:O(`LoopItems.sightings`)(function*(t){let n=[...new Set(t)];if(n.length===0)return[];let r=(yield*rh(Ji(n,100),t=>e.select({loop:sz.loopName,itemKey:sz.itemKey,observedEventId:sz.observedEventId,suppressedByRunId:sz.suppressedByRunId}).from(sz).where(cM(sz.itemKey,t)).execute().pipe(E(uq)))).flat(),i=[...new Set(r.flatMap(({observedEventId:e})=>e===null?[]:[e]))],a=(yield*rh(Ji(i,100),t=>e.select({eventId:Z.eventId,reopensEventId:Z.reopensEventId}).from(Z).where(cM(Z.reopensEventId,t)).orderBy(wM(Z.reopening)).execute().pipe(E(dq)))).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*rh(Ji(i.map(s),100),t=>e.select({eventId:Q.eventId,runId:Q.runId}).from(Q).where(cM(Q.eventId,t)).execute().pipe(E(fq)))).flat().map(({eventId:e,runId:t})=>[e,t]));return r.map(({loop:e,itemKey:t,observedEventId:n,suppressedByRunId:r})=>{let i=Sr(_r(n),s);return new cK({loop:e,itemKey:t,event:i,run:Cr(i,e=>_r(c.get(e))),suppressedBy:_r(r)})})})}},mq=e=>({appendTranscript:O(`RunStoreQueries.appendTranscript`)(function*(t,n,r){return(yield*e.insert(pz).values({attemptId:n.attemptId,direction:t,channelSequence:n.sequence,envelope:HK(n),receivedAt:jK(r)}).onConflictDoNothing().returning({sequence:pz.sequence}).execute()).length>0}),transcript:O(`RunStoreQueries.transcript`)(function*(t){yield*D({attemptId:t.attemptId,query:t._tag});let n=Vk(t,{TranscriptWorkerQuery:({attemptId:e})=>tM(Y(pz.attemptId,e),Y(pz.direction,`outbound`),J`json_extract(${pz.envelope}, '$.payload._tag') IN ('WorkerUnresponsive', 'WorkerResponsive')`),TranscriptSessionsQuery:({attemptId:t})=>cM(pz.sequence,e.select({sequence:J`max(${pz.sequence})`}).from(pz).where(tM(Y(pz.attemptId,t),J`(
188
+ json_extract(${pz.envelope}, '$.payload._tag') = 'InterventionApplied'
189
+ OR (json_extract(${pz.envelope}, '$.payload._tag') = 'SessionEvent'
190
+ AND json_extract(${pz.envelope}, '$.payload.event._tag') IN ('SessionStarted', 'SessionIdle', 'SessionResumed', 'SessionFinished'))
191
+ )`)).groupBy(J`coalesce(json_extract(${pz.envelope}, '$.payload.event.session.id'), json_extract(${pz.envelope}, '$.payload.intervention.target.sessionId'), '@parent')`,J`json_extract(${pz.envelope}, '$.payload._tag')`,J`json_extract(${pz.envelope}, '$.payload.event._tag') = 'SessionStarted'`)),TranscriptUsageQuery:({attemptId:t})=>{let n=e.select({sequence:pz.sequence,tokens:J`max(json_extract(${pz.envelope}, '$.payload.event.totalTokens'))`.as(`tokens`)}).from(pz).where(tM(Y(pz.attemptId,t),J`json_extract(${pz.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${pz.envelope}, '$.payload.event._tag') = 'SessionTokensUpdated'`)).groupBy(J`json_extract(${pz.envelope}, '$.payload.event.session.id')`).as(`highest`);return cM(pz.sequence,e.select({sequence:n.sequence}).from(n))},TranscriptAllQuery:({attemptId:e})=>Y(pz.attemptId,e),TranscriptTailQuery:({attemptId:e,after:t})=>tM(Y(pz.attemptId,e),iM(pz.sequence,t)),TranscriptPageQuery:({attemptId:e,before:t})=>pr(t,{onNone:()=>Y(pz.attemptId,e),onSome:t=>tM(Y(pz.attemptId,e),oM(pz.sequence,t))})}),r=e.select({sequence:pz.sequence,attemptId:pz.attemptId,direction:pz.direction,envelope:pz.envelope,receivedAt:pz.receivedAt}).from(pz).where(n);return(yield*kK(yield*Vk(t,{TranscriptWorkerQuery:()=>r.orderBy(wM(pz.sequence)).limit(1).execute(),TranscriptSessionsQuery:()=>r.orderBy(CM(pz.sequence)).execute(),TranscriptUsageQuery:()=>r.orderBy(CM(pz.sequence)).execute(),TranscriptAllQuery:()=>r.orderBy(CM(pz.sequence)).execute(),TranscriptTailQuery:({limit:e})=>r.orderBy(CM(pz.sequence)).limit(e).execute(),TranscriptPageQuery:({limit:e})=>r.orderBy(wM(pz.sequence)).limit(e).execute()}),{onExcessProperty:`error`})).map(nq).sort((e,t)=>e.sequence-t.sequence)})}),hq=(e,t)=>h_(t.openedAt)-h_(e.openedAt)||t.runId.localeCompare(e.runId),gq={eventId:oz.eventId,dedupKey:oz.dedupKey,payload:oz.payloadJson,receivedAt:oz.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},_q=mR(oz,`approval_event`),vq={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:fz.stepName,result:fz.result,approvedAt:_q.receivedAt,approvalChannel:mz.channel,approver:mz.approver,againFrom:hz.fromRunId,againRequestedBy:hz.requestedBy},yq={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},bq=J`json_extract(${Q.stateJson}, '$._tag')`,xq=cM(bq,[...TN]),Sq=cM(bq,[...DN]),Cq=e=>nT(JE)(UK(e)),wq=e=>{let t=O(`RunStoreQueries.eventRouteByDedup`)(function*(t){return yield*bK(yield*e.select(gq).from(oz).innerJoin(Z,Y(Z.eventId,oz.eventId)).where(Y(oz.dedupKey,t)).execute())}),n=O(`RunStoreQueries.eventRouteByRun`)(function*(t){return yield*bK(yield*e.select(gq).from(Q).innerJoin(oz,Y(oz.eventId,Q.eventId)).innerJoin(Z,Y(Z.eventId,oz.eventId)).where(Y(Q.runId,t)).execute())}),r=()=>e.select(vq).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).innerJoin(fz,Y(fz.runId,Q.runId)).leftJoin(mz,Y(mz.runId,Q.runId)).leftJoin(_q,Y(_q.eventId,mz.eventId)).leftJoin(hz,Y(hz.eventId,Q.eventId)),i=O(`RunStoreQueries.runRows`)(function*(e){return yield*CK(yield*r().where(Y(Q.runId,e)).execute())}),a=(...t)=>T(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(tM(uM($.leftoversDiscardedAt),...t)).execute();return(yield*Zw(N(M({attemptId:jF,worker:qN,repository:H,runId:LN,loop:DA,itemKey:xI,number:MF,permissions:jA,outcome:j,salvage:F(SF)})))(n)).map(({number:e,outcome:t,salvage:n,...r})=>({...r,ref:bF(r.runId,e),succeeded:t===`Succeeded`,open:t===``,rejected:n?._tag===`Rejected`?b(n):y()}))}),o=O(`RunStoreQueries.salvageCandidates`)(function*(){return yield*a()}),s=O(`RunStoreQueries.salvageCandidate`)(function*(e){return yield*D({attemptId:e}),fee(yield*a(Y($.attemptId,e)))}),c=O(`RunStoreQueries.attemptRows`)(function*(t){return yield*TK(yield*e.select(yq).from($).where(Y($.runId,t)).orderBy($.attemptNumber).execute())}),l=O(`RunStoreQueries.snapshot`)(function*(e){let[t,r,a]=yield*nh([i(e),c(e),n(e)]),o=t[0],s=a[0];return o===void 0||s===void 0?yield*new Cz({runId:e}):new rK({event:qK(s),itemKey:s.itemKey,run:XK(o),step:$K(o),attempts:r.map(eq),resolvedFailureAttemptId:_r(o.resolvedFailureAttemptId),closedAt:_r(o.closedAt),approval:ZK(o),runAgain:QK(o),repository:o.repository,revision:o.revision,task:o.task,agent:o.agent,parentModel:_r(o.parentModel),permissions:s.permissions})}),u=O(`RunStoreQueries.summariesWithAttempts`)(function*(t){let n=Yi((yield*rh(Ji(t.map(({runId:e})=>e),100),t=>e.select(yq).from($).where(cM($.runId,t)).orderBy(CM($.runId),CM($.attemptNumber)).execute().pipe(E(TK)))).flat(),({runId:e})=>e);return t.map(e=>tq(e,n[e.runId]??[]))}),d=O(`RunStoreQueries.itemRunSummaries`)(function*(e){if(e.length===0)return[];let t=(yield*rh(Ji([...new Set(e)],100),e=>r().where(cM(Z.itemKey,e)).execute().pipe(E(CK)))).flat().sort(hq);return yield*u(t)}),f=O(`RunStoreQueries.runSummaries`)(function*(e){let[t,n]=yield*nh([r().where(xq).orderBy(wM(Q.openedAt),wM(Q.runId)).execute().pipe(E(CK)),r().where(lM(bq,[...TN])).orderBy(wM(Q.openedAt),wM(Q.runId)).limit(e).execute().pipe(E(CK))]),i=[...t,...n].sort(hq);return yield*u(i)}),p=O(`RunStoreQueries.runEvents`)(function*(t){return(yield*rh(Ji([...new Set(t)],100),t=>e.select({runId:Q.runId,eventId:oz.eventId,dedupKey:oz.dedupKey,payload:oz.payloadJson,receivedAt:oz.receivedAt}).from(Q).innerJoin(oz,Y(oz.eventId,Q.eventId)).where(cM(Q.runId,t)).execute().pipe(E(wK)))).flat().map(JK)}),m=O(`RunStoreQueries.closedRunSummaries`)(function*(e){let t=yield*r().where(lM(bq,[...TN])).orderBy(wM(Q.closedAt),wM(Q.runId)).limit(e).execute().pipe(E(CK));return yield*u(t)}),h=O(`RunStoreQueries.closedRunSummariesSince`)(function*(e){let t=lM(bq,[...TN]),n=yield*r().where(pr(e,{onNone:()=>t,onSome:e=>tM(t,aM(Q.closedAt,jK(e)))})).orderBy(wM(Q.closedAt),wM(Q.runId)).execute().pipe(E(CK));return yield*u(n)}),g=O(`RunStoreQueries.projectionRevision`)(function*(){return _r((yield*OK(yield*e.select({revision:Sz.revision}).from(Sz).where(Y(Sz.singleton,1)).limit(1).execute()))[0]?.revision)}),_=O(`RunStoreQueries.updateState`)(function*(t,n,r){let i=bN(n)?null:jK(r??(yield*l_));if((yield*e.update(Q).set({stateJson:MK(n),closedAt:i}).where(Y(Q.runId,t)).returning({runId:Q.runId}).execute()).length===0)return yield*new Cz({runId:t})}),v=O(`RunStoreQueries.resolveFailure`)(function*(t,n,r){yield*D({runId:t,attemptId:n}),yield*e.update($).set({failureResolutionJson:RK(r)}).where(Y($.attemptId,n)).execute(),yield*e.update(Q).set({resolvedFailureAttemptId:n}).where(Y(Q.runId,t)).execute()}),ee=O(`RunStoreQueries.addAttempt`)(function*(t){yield*e.insert($).values({attemptId:t.id,runId:t.runId,stepName:t.stepName,workerName:t.worker,attemptNumber:t.number,brainJson:WK(t.brain),task:t.task,agent:t.agent,operatorIntervened:t.operatorIntervened,parentModel:C(t.parentModel),startedAt:jK(t.startedAt),outcomeJson:null,endedAt:null,salvageJson:null,startJson:pr(t.start,{onNone:()=>null,onSome:zK})}).execute()}),te=O(`RunStoreQueries.recordReattach`)(function*(t,n){yield*D({attemptId:t}),yield*e.update($).set({reattachedAt:jK(n)}).where(Y($.attemptId,t)).execute()}),ne=O(`RunStoreQueries.nextStart`)(function*(t){return _r((yield*BK(yield*e.select({nextStart:Q.nextStartJson}).from(Q).where(Y(Q.runId,t)).execute()))[0]?.nextStart)}),re=O(`RunStoreQueries.setNextStart`)(function*(t,n){yield*e.update(Q).set({nextStartJson:pr(n,{onNone:()=>null,onSome:zK})}).where(Y(Q.runId,t)).execute()}),ie=O(`RunStoreQueries.recordSalvage`)(function*(t,n){yield*D({attemptId:t,salvage:n._tag}),yield*e.update($).set({salvageJson:PK(n)}).where(Y($.attemptId,t)).execute(),n._tag===`Retained`&&S(n.pushFailure)&&(yield*e.update($).set({outcomeJson:NK(new gF({failure:n.pushFailure.value}))}).where(tM(Y($.attemptId,t),J`json_extract(${$.outcomeJson}, '$._tag') = 'Failed'`,J`json_extract(${$.outcomeJson}, '$.failure._tag') != 'GitHubPushFailure'`)).execute())}),ae=O(`RunStoreQueries.recordComments`)(function*(t,n){yield*D({attemptId:t,comments:n.length}),yield*e.update($).set({commentsJson:FK(n)}).where(Y($.attemptId,t)).execute()}),oe=O(`RunStoreQueries.recordOutOfMemory`)(function*(t,n){yield*D({attemptId:t,container:n.container,kills:n.kills});let r=Ri(((yield*LK(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:IK(r)}).where(Y($.attemptId,t)).execute(),VF(r)}),se=O(`RunStoreQueries.closeAttempt`)(function*(t,n,r){yield*e.update($).set({outcomeJson:NK(n),endedAt:jK(r)}).where(tM(Y($.attemptId,t),uM($.outcomeJson))).execute()}),ce=O(`RunStoreQueries.amend`)(function*(t,n){yield*D({runId:t,agent:n.agent.name}),yield*e.update(Q).set({task:n.task,agentJson:Cq(n.agent),parentModel:C(n.parentModel)}).where(Y(Q.runId,t)).execute()}),le=O(`RunStoreQueries.markIntervened`)(function*(t){yield*D({attemptId:t}),yield*e.update($).set({operatorIntervened:!0}).where(Y($.attemptId,t)).execute()}),ue=O(`RunStoreQueries.updateAttemptParentModel`)(function*(t,n){yield*e.update($).set({parentModel:n}).where(Y($.attemptId,t)).execute()}),de=O(`RunStoreQueries.updateStepResult`)(function*(t,n,r){yield*e.update(fz).set({result:VK(r)}).where(tM(Y(fz.runId,t),Y(fz.stepName,n))).execute()}),fe=O(`RunStoreQueries.approvalExists`)(function*(t){return(yield*e.$count(mz,Y(mz.runId,t)).execute())>0}),pe=O(`RunStoreQueries.recordApproval`)(function*(t,n,r){yield*e.insert(oz).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:AK(n.payload),receivedAt:jK(n.receivedAt)}).onConflictDoNothing().execute(),yield*e.insert(mz).values({runId:t,eventId:n.id,channel:r.channel,approver:C(r.approver)}).execute()}),me=O(`RunStoreQueries.createRun`)(function*(t,n,r){let i=mR(Z,`candidate`),a=mR(Q,`candidate_run`),o=mR(gz,`ignored`);yield*e.insert(gz).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(tM(Y(i.loopName,t.loop),Y(i.itemKey,t.itemKey),$j(i.eventId,n),uM(a.runId),uM(o.eventId)))).onConflictDoNothing().execute(),yield*e.insert(Q).values({runId:r,eventId:n,loopName:t.loop,stateJson:MK(new lN),openedAt:jK(t.event.receivedAt),repository:t.repository,revision:t.revision,task:t.task,agentJson:Cq(t.agent),parentModel:C(t.parentModel)}).onConflictDoNothing().execute(),yield*e.insert(fz).values({runId:r,stepName:t.step,result:null}).onConflictDoNothing().execute()}),he=O(`RunStoreQueries.runForEvent`)(function*(t){return yield*EK(yield*e.select({runId:Q.runId}).from(Q).where(Y(Q.eventId,t)).execute())}),ge=O(`RunStoreQueries.ignoredEvent`)(function*(t){return yield*DK(yield*e.select({reason:gz.reason}).from(gz).where(Y(gz.eventId,t)).execute())}),_e=O(`RunStoreQueries.blockingRun`)(function*(t,n){return yield*EK(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(tM(Y(Z.loopName,t),Y(Z.itemKey,n),xq)).orderBy(wM(Q.openedAt)).limit(1).execute())}),ve=O(`RunStoreQueries.newestReopening`)(function*(t){return Sr(_r((yield*xK(yield*e.select({...gq,reopening:Z.reopening}).from(oz).innerJoin(Z,Y(Z.eventId,oz.eventId)).where(Y(Z.reopensEventId,t)).orderBy(wM(Z.reopening)).limit(1).execute()))[0]),e=>({submission:YK(e),reopening:e.reopening}))}),ye=O(`RunStoreQueries.reopenedEvent`)(function*(t){let n=mR(oz,`reopened_event`);return _r((yield*SK(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=O(`RunStoreQueries.recordRunAgain`)(function*(t,n){yield*e.insert(hz).values({eventId:t,fromRunId:n.from,requestedBy:C(n.requestedBy)}).execute()}),xe=O(`RunStoreQueries.recordTriggerEvent`)(function*(n,r=y()){yield*e.insert(oz).values({eventId:n.event.id,dedupKey:n.event.dedupKey,payloadJson:AK(n.event.payload),receivedAt:jK(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:C(n.cycleLimit),cycleGeneration:n.cycleGeneration,repository:n.repository,revision:n.revision,task:n.task,agentJson:Cq(n.agent),parentModel:C(n.parentModel),reopensEventId:C(Sr(r,({eventId:e})=>e)),reopening:pr(r,{onNone:()=>0,onSome:({reopening:e})=>e})}).execute(),n):YK(i)}),Se=O(`RunStoreQueries.nextQueued`)(function*(t){let r=(yield*n(t))[0];if(r===void 0)return y();let i=yield*pq(e).suppression(r.loop,r.itemKey);if(S(i))return yield*k(`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*bK(yield*e.select(gq).from(oz).innerJoin(Z,Y(Z.eventId,oz.eventId)).leftJoin(Q,Y(Q.eventId,oz.eventId)).leftJoin(gz,Y(gz.eventId,oz.eventId)).where(tM(Y(Z.loopName,r.loop),Y(Z.itemKey,r.itemKey),cq(e).currentEvent,uM(Q.runId),uM(gz.eventId))).orderBy(wM(oz.receivedAt)).execute());return _r(a[0]).pipe(Sr(e=>({submission:YK(e),eventIds:a.map(e=>e.eventId)})))}),Ce=O(`RunStoreQueries.runIdsToDrive`)(function*(){return(yield*EK(yield*e.select({runId:Q.runId}).from(Q).where(tM(xq,$j(bq,`Waiting`))).execute())).map(({runId:e})=>e)}),we=O(`RunStoreQueries.pendingContinuations`)(function*(){let t=yield*e.selectDistinct({loop:Z.loopName,itemKey:Z.itemKey}).from(Z).leftJoin(Q,Y(Q.eventId,Z.eventId)).leftJoin(gz,Y(gz.eventId,Z.eventId)).leftJoin(cz,Y(cz.itemKey,Z.itemKey)).leftJoin(sz,tM(Y(sz.loopName,Z.loopName),Y(sz.itemKey,Z.itemKey))).where(tM(uM(Q.runId),uM(gz.eventId),uM(cz.askJson),uM(sz.suppressedByRunId),cq(e).currentEvent)).execute();return(yield*rh(yield*Zw(N(M({loop:DA,itemKey:xI})))(t),({loop:t,itemKey:n})=>T(function*(){return(yield*_e(t,n)).length>0?[]:yield*EK(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(tM(Y(Z.loopName,t),Y(Z.itemKey,n))).orderBy(wM(Q.openedAt),wM(Q.runId)).limit(1).execute())}))).flat().map(({runId:e})=>e)}),Te=O(`RunStoreQueries.revokeQueued`)(function*(t,n,r){let i=mR(Z,`candidate`),a=mR(Q,`candidate_run`);return(yield*e.insert(gz).select(e.select({eventId:i.eventId,reason:J`'revoked'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).where(tM(Y(i.loopName,t),Y(i.itemKey,n),cM(i.eventId,r),uM(a.runId)))).onConflictDoNothing().returning({eventId:gz.eventId}).execute()).length}),Ee=O(`RunStoreQueries.revokeUnstarted`)(function*(t,n){let r=yield*EK(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(tM(Y(Z.loopName,t),Y(Z.itemKey,n),Sq)).execute()),i=e.select({eventId:Z.eventId}).from(Z).where(tM(Y(Z.loopName,t),Y(Z.itemKey,n)));return yield*Te(t,n,i),r});return{salvageCandidates:o,salvageCandidate:s,cycles:cq(e),loopItems:pq(e),...mq(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}},Tq=T(function*(){let e=yield*jz,t=wq(e),n=O(`RunReader.inspect`)(e=>t.snapshot(e).pipe(KK(`read run`))),r=O(`RunReader.evidence`)(function*(t){yield*D({runId:t});let n=yield*e.transaction(e=>T(function*(){let n=wq(e),r=yield*n.snapshot(t);return new aK({snapshot:r,transcript:(yield*rh(r.attempts,({id:e})=>n.transcript(new VG({attemptId:e})))).flat().sort((e,t)=>e.sequence-t.sequence)})})).pipe(KK(`read run evidence`));return yield*A(`Run evidence read`,{runId:t,attempts:n.snapshot.attempts.length,transcriptRows:n.transcript.length}),n}),i=O(`RunReader.list`)(e=>t.runSummaries(e.closedLimit).pipe(KK(`list runs`))),a=O(`RunReader.closed`)(e=>t.closedRunSummaries(e.limit).pipe(KK(`list closed runs`))),o=O(`RunReader.closedSince`)(e=>t.closedRunSummariesSince(e).pipe(KK(`list runs closed since a time`))),s=O(`RunReader.revision`)(()=>t.revision().pipe(KK(`read projection revision`)));return{inspect:n,evidence:r,list:i,closed:a,closedSince:o,forItems:O(`RunReader.forItems`)(e=>t.itemRunSummaries(e).pipe(KK(`read item run histories`))),events:O(`RunReader.events`)(e=>t.runEvents(e).pipe(KK(`read the events of runs`))),revision:s,transcript:O(`RunReader.transcript`)(e=>t.transcript(e).pipe(KK(`read attempt transcript`))),latestPoolRateLimits:O(`RunReader.latestPoolRateLimits`)(function*(){let t=yield*e.select({event:J`json_extract(${pz.envelope}, '$.payload.event')`}).from(pz).where(cM(pz.sequence,e.select({sequence:J`max(${pz.sequence})`}).from(pz).where(tM(Y(pz.direction,`outbound`),J`json_extract(${pz.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${pz.envelope}, '$.payload.event._tag') = 'PoolRateLimitsUpdated'`)).groupBy(J`json_extract(${pz.envelope}, '$.payload.event.pool')`))).execute(),n=yield*Zw(N(M({event:gE(nF)})))(t,{onExcessProperty:`error`});return yield*D({pools:n.map(({event:e})=>e.pool)}),yield*A(`Read latest pool rate limits`,{pools:n.map(({event:e})=>e.pool)}),n.map(({event:e})=>e)},KK(`read latest pool rate limits`)),attemptsByWorker:O(`RunReader.attemptsByWorker`)(()=>aq(e).attemptCountsByWorker().pipe(KK(`count attempts by worker`))),sightings:O(`RunReader.sightings`)(e=>t.loopItems.sightings(e).pipe(KK(`read loop sightings`)))}}),Eq=class e extends kr()(`@usine/engine/RunReader`){static layer=Df(e,Tq)},Dq=class extends B(`@usine/orchestrator/UsageCostView`)({usd:KP,estimate:yT}){},Oq=class extends B(`@usine/orchestrator/SessionUsageView`)({attemptId:jF,session:IP,pool:XP,tokens:MP,cost:F(Dq)}){},kq=class extends B(`@usine/orchestrator/PoolUsageView`)({pool:XP,tokens:MP,cost:F(Dq)}){},Aq=class extends B(`@usine/orchestrator/RunUsageView`)({tokens:MP,pools:N(kq),sessions:N(Oq)}){},jq=class extends B(`@usine/orchestrator/TaskPoolUsageView`)({pool:XP,tokens:MP,cost:F(Dq),unpriced:yT}){},Mq=class extends B(`@usine/orchestrator/TaskUsageView`)({durationMillis:L.check($T(0)),runningSince:N(j),unmeasured:L.check($T(0)),tokens:MP,pools:N(jq),cost:F(Dq)}){},Nq=[`apiKeys`,`claudePlan`,`chatgptPlan`],Pq=(e,t)=>pr(t,{onNone:()=>null,onSome:t=>new Dq({usd:t,estimate:e!==`apiKeys`})}),Fq=({session:e,costUsd:t,breakdown:n})=>S(t)||e.brain.harness!==`codex`?t:Cr(n,t=>nK(e.brain.model,t)),Iq=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:Fq(e.report)})),r=n.map(({attemptId:e,report:t,price:n})=>{let r=QP(t.session);return new Oq({attemptId:e,session:t.session,pool:r,tokens:t.totalTokens,cost:Pq(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=Nq.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 kq({pool:e,tokens:MP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:Pq(e,n.length===t.length?b(KP.make(n.reduce((e,t)=>e+t,0))):y())})]});return{view:new Aq({tokens:MP.make(r.reduce((e,{tokens:t})=>e+t,0)),pools:a,sessions:r}),unknownModels:i}},Lq=(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=Nq.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 jq({pool:e,tokens:MP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:Pq(e,n.length===0?y():b(KP.make(n.reduce((e,t)=>e+t,0)))),unpriced:n.length<t.length})]}),s=o.flatMap(({cost:e})=>e===null?[]:[e]);return new Mq({durationMillis:Math.round(n),runningSince:i,unmeasured:r,tokens:MP.make(a.reduce((e,{tokens:t})=>e+t,0)),pools:o,cost:s.length===0?null:new Dq({usd:KP.make(s.reduce((e,{usd:t})=>e+t,0)),estimate:s.some(({estimate:e})=>e)})})},Rq=T(function*(){let e=yield*Eq,t=yield*ch(()=>new Map),n=yield*ch(()=>new Set),r=O(`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 WG({attemptId:n.id}));return S(n.outcome)&&t.set(n.id,i),{reports:i,read:!0}});return{read:O(`RunUsageReader.read`)(function*(e){yield*D({runId:e.run.id});let t=yield*rh(e.attempts,r,{concurrency:4}),{view:i,unknownModels:a}=Iq(t.flatMap(({reports:e})=>e));for(let t of a)n.has(t)||(n.add(t),yield*Cg(`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*A(`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 kr()(`@usine/orchestrator/RunUsageReader`){static layer=Df(e,Rq)});var zq=jT(EN),Bq=F(j),Vq=class extends B(`@usine/orchestrator/EditAndRetry`)({task:PF,agent:SA}){},Hq=class extends B(`@usine/orchestrator/SessionIntervention`)({attemptId:jF,target:dI.pipe(RT(w({_tag:`Parent`}))),action:cI}){};WE(`@usine/orchestrator/RosterAgentNotFoundError`)(`RosterAgentNotFoundError`,{agent:SA,message:j}),WE(`@usine/orchestrator/LoopNotFoundError`)(`LoopNotFoundError`,{loop:DA,message:j});var Uq=class extends B(`@usine/orchestrator/ApprovalView`)({approvedAt:j,source:F(MI)}){},Wq=class extends B(`@usine/orchestrator/RunView`)({id:LN,itemKey:xI,loop:DA,repository:H,agent:SA,agentBrain:xA,state:zq,providerRetry:F(JF).pipe(RT(w(null)),IT(w(null))),machineWait:F(wG).pipe(RT(w(null)),IT(w(null))),loopPaused:yT,openedAt:j,closedAt:F(j),task:j,attempts:N(cG),approval:F(Uq),runAgain:F(HW),resultMessage:Bq,pullRequestUrl:Bq,canApprove:yT,canRetry:yT,canResolveFailure:yT,canCancel:yT,canRunAgain:yT}){},Gq=L.check($T(0)),Kq=L.check($T(0)),qq=class extends B(`@usine/orchestrator/RunDurationView`)({endedMillis:Gq,runningSince:F(j),unmeasured:Kq}){},Jq=class extends B(`@usine/orchestrator/UnconfirmedStopView`)({runId:LN,attemptNumber:MF,worker:qN}){},Yq=class extends B(`@usine/orchestrator/RunDetailView`)({run:Wq,agentDefinitionChanged:yT,eventDedupKey:j,eventPayload:JE,transcript:N(YG),sessionState:N(YG),earlierTranscript:N(XG),worker:F(qN).pipe(IT(w(null))),settledItemState:F(IW).pipe(IT(w(null))),duration:qq.pipe(IT(w(new qq({endedMillis:0,runningSince:null,unmeasured:0})))),usage:Aq.pipe(IT(w(new Aq({tokens:MP.make(0),pools:[],sessions:[]})))),unconfirmedStop:F(Jq).pipe(IT(w(null))),machine:F(EG).pipe(IT(w(null)))}){},Xq=R.pipe(I(`BoardLaneId`)),Zq=jT([`authored`,`proposed`,`fallback`]),Qq=class extends B(`@usine/orchestrator/BoardItemLink`)({itemKey:xI,kind:jT([`issue`,`pr`]),number:SI,title:j,url:R,state:FW}){},$q=class extends B(`@usine/orchestrator/BoardPullRequestView`)({number:SI,url:R,state:jT([`pr-open`,`pr-merged`])}){},eJ=class extends B(`@usine/orchestrator/BoardTaskView`)({...Qq.fields,repository:H,labels:N(MA),items:N(Qq).check(iE()),pullRequest:F($q),runs:N(Wq),run:F(Wq),needsYou:yT,conflicting:yT,loops:N(DA),usage:Mq}){},tJ={id:Xq,name:PW,sources:N(BW),origin:Zq,items:N(eJ)},nJ=class extends V(`@usine/orchestrator/WritableBoardLaneView`)(`WritableBoardLane`,{...tJ,origin:pT(`authored`),labels:N(MA).check(iE())}){},rJ=class extends V(`@usine/orchestrator/ReadOnlyBoardLaneView`)(`ReadOnlyBoardLane`,tJ){},iJ=P([nJ,rJ]),aJ=class extends WE(`@usine/orchestrator/BoardProjectionError`)(`BoardProjectionError`,{repository:H,itemKey:xI,message:R}){},oJ=class extends B(`@usine/orchestrator/BoardView`)({lanes:N(iJ),failures:N(aJ)}){},sJ=class extends B(`@usine/orchestrator/LabelView`)({name:MA,color:F(j),description:F(j)}){};B(`@usine/orchestrator/BoardMove`)({repository:H,item:SI,toLane:Xq});var cJ=class extends WE(`@usine/orchestrator/BoardProjectNotFoundError`)(`BoardProjectNotFoundError`,{repository:H}){get message(){return`Project "${this.repository}" was not found.`}},lJ=class extends WE(`@usine/orchestrator/BoardItemNotFoundError`)(`BoardItemNotFoundError`,{repository:H,item:SI}){get message(){return`Item ${this.repository}#${this.item} was not found on the board.`}};WE(`@usine/orchestrator/BoardLaneNotFoundError`)(`BoardLaneNotFoundError`,{repository:H,lane:Xq}),WE(`@usine/orchestrator/BoardLaneReadOnlyError`)(`BoardLaneReadOnlyError`,{repository:H,lane:Xq});var uJ=j.check(GT(/^(?:[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(I(`CelTypeReference`)),dJ=j.check(GT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected a CEL identifier`})),fJ=j.check(GT(/^[A-Za-z_][A-Za-z0-9_.]*$/u,{message:`Expected a CEL object-type name`})),pJ=e=>WT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:e}),mJ=class extends B(`@usine/expression/ObjectField`)({name:dJ,type:uJ,nullable:yT.pipe(IT(w(!1)))}){},hJ=class extends B(`@usine/expression/ObjectType`)({name:fJ,fields:N(mJ).check(pJ(`Expected unique CEL object-field names`))}){},gJ=class extends B(`@usine/expression/Variable`)({name:dJ,type:uJ}){},_J=class extends B(`@usine/expression/Environment`)({types:N(hJ).check(pJ(`Expected unique CEL object-type names`)),variables:N(gJ).check(pJ(`Expected unique CEL variable names`))}){},vJ=j.check(GT(/\S/u,{message:`Expected a non-blank CEL expression`})).pipe(I(`ExpressionSource`)),yJ=L.check($T(0)),bJ=jT([`check_failed`,`parse_error`,`type_error`,`unexpected_result_type`]),xJ=class extends WE(`@usine/expression/ExpressionCheckError`)(`ExpressionCheckError`,{source:vJ,code:bJ,message:R,position:z(yJ)}){},SJ=class extends WE(`@usine/expression/ExpressionEvaluationError`)(`ExpressionEvaluationError`,{source:vJ,message:R}){};P([xJ,SJ]),P([j,vT,bT,yT,gT]);var CJ=class extends kr()(`@usine/expression/ExpressionEngine`){},wJ=R.pipe(I(`InstancePath`)),TJ=jT([`expression`,`frontmatter`,`read`,`reference`,`schema`,`yaml`]),EJ=M({path:N(P([j,vT])),message:j,expression:lT(vJ),position:lT(L.check($T(0)))}),DJ=class e extends WE(`@usine/config/ConfigFileError`)(`ConfigFileError`,{file:wJ,stage:TJ,expression:ME(vJ),message:R,details:lT(N(EJ))}){static fromSchema(t,n){let r=gy()(n.issue).issues.map(({path:e,message:t})=>({path:(e??[]).map(e=>Bk(e).pipe(Hk(Uk,e=>e),Hk(Wk,e=>e),Hk(Gk,String),Kk(({key:e})=>String(e)))),message:t}));return new e({file:t,stage:`schema`,expression:y(),message:Cy()(n.issue),details:r})}};P([DJ,class extends WE(`@usine/config/FactoryConfigError`)(`FactoryConfigError`,{file:wJ,stage:TJ,message:R}){}]);var OJ=jT([`latest`,`next`]),kJ=jT([`off`,`propose`,`automatic`]),AJ=j.check(GT(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u)).pipe(I(`ReleaseVersion`)),jJ=jT([`idle`,`now`]),MJ={previous:AJ,target:AJ},NJ=P([class extends B(`@usine/core/UpgradeInstalling`)({...MJ,status:pT(`installing`)}){},class extends B(`@usine/core/UpgradeGood`)({...MJ,status:pT(`good`)}){},class extends B(`@usine/core/UpgradeRolledBack`)({...MJ,status:pT(`rolled-back`),reason:R,failureStage:jT([`install`,`health-check`,`unknown`]).pipe(RT(w(`unknown`)))}){},class extends B(`@usine/core/UpgradeFailed`)({...MJ,status:pT(`failed`),reason:R}){}]),PJ=e=>`label`in e?`label:${NA(e.label)}`:`state:${e.state}`,FJ=WT(e=>{let t=e.flatMap(({sources:e})=>e.map(PJ));return new Set(t).size===t.length},{message:`Expected each lane source in only one lane`}),IJ=N(VW).check(WT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique lane names`}),FJ),LJ=class extends B(`@usine/config/Project`)({id:pA,name:MW(`Expected a project display name`),repositories:kT(H).check(NW(e=>e)),lanes:IJ.pipe(RT(w([])),IT(w([])))}){includes(e){return this.repositories.some(t=>fA(t)===fA(e))}},RJ=MW(`Expected a non-blank registry tag`).pipe(I(`RegistryTag`)),zJ=L.check($T(1)),BJ=WT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique names`}),VJ=WT(e=>new Set(e.map(({name:e})=>NA(e))).size===e.length,{message:`Expected unique GitHub label names`}),HJ=N(IA).check(VJ),UJ=class extends B(`@usine/config/ManagedRepo`)({name:H,tags:N(RJ).check(sE()).pipe(RT(w([]))),lanes:IJ.pipe(RT(w([])))}){},WJ=zJ.pipe(RT(w(1))),GJ=class extends B(`@usine/config/LocalWorker`)({name:qN,kind:pT(`local`),maxConcurrentAttempts:WJ}){},KJ=class extends B(`@usine/config/ExeDevWorker`)({name:qN,kind:pT(`exe.dev`),maxConcurrentAttempts:WJ}){},qJ=j.check(GT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected an environment variable name`})).pipe(I(`EnvironmentVariableName`)),JJ=class extends B(`@usine/config/WorkerGateway`)({domain:nP,destination:QN,adminPort:rP.pipe(RT(w(7070))),adminTokenEnv:qJ,llmProviders:N(iP).check(sE()).pipe(RT(w([])))}){},YJ=class extends B(`@usine/config/WorkerContainer`)({image:ME(oP),cpus:ME(cP),memoryMib:ME(lP),pids:ME(uP)}){},XJ=class extends B(`@usine/config/ProviderApiKeys`)({anthropic:ME(qJ),openai:ME(qJ)}){}.pipe(RT(w({}))),ZJ=AP.pipe(wT({sshWait:`ssh_wait`,creationBackoffMin:`creation_backoff_min`,creationBackoffMax:`creation_backoff_max`,machineCheckInterval:`machine_check_interval`}),RT(w({}))),QJ=class extends B(`@usine/config/HetznerProvisioner`)({provider:pT(`hetzner`),tokenEnv:qJ,serverType:vP,location:yP,image:bP,network:ME(xP),firewall:ME(xP),sshKey:xP,sshUser:wP.pipe(RT(w(`usine`))),labels:CP.pipe(RT(w({}))),apiKeys:XJ,timings:ZJ}){},$J=class extends B(`@usine/config/BoatTailnet`)({gatewayAddress:DP,clientIdEnv:qJ,clientSecretEnv:qJ}){},eY=class extends B(`@usine/config/BoatProvisioner`)({provider:pT(`boat`),tokenEnv:qJ,size:TP.pipe(RT(w(`default`))),snapshot:ME(EP),tailnet:ME($J.pipe(wT({gatewayAddress:`gateway_address`,clientIdEnv:`client_id_env`,clientSecretEnv:`client_secret_env`}))),apiKeys:XJ,timings:ZJ}){};P([QJ,eY]);var tY=P([QJ.pipe(wT({tokenEnv:`token_env`,serverType:`server_type`,sshKey:`ssh_key`,sshUser:`ssh_user`,apiKeys:`api_keys`})),eY.pipe(wT({tokenEnv:`token_env`,apiKeys:`api_keys`}))]),nY=class extends B(`@usine/config/SshWorker`)({name:qN,kind:pT(`ssh`),maxConcurrentAttempts:WJ,destination:ME(QN),provisioner:ME(tY),identityFile:ME(eP),port:ME($N),root:tP,gateway:ME(JJ.pipe(wT({adminPort:`admin_port`,adminTokenEnv:`admin_token_env`,llmProviders:`llm_providers`}))),container:YJ.pipe(wT({memoryMib:`memory_mib`}),RT(w({})))}){},rY=e=>{let t=br(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)&&(x(t.tailnet)||x(t.snapshot))?`SSH worker "${e.name}" needs provisioner.tailnet and provisioner.snapshot to use a Boat gateway`:S(t.tailnet)&&x(e.gateway)?`SSH worker "${e.name}" sets provisioner.tailnet without a 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}},iY=mE.check(WT(e=>e.protocol===`https:`,{message:`Expected an https URL`}),WT(e=>e.username===``&&e.password===``&&e.search===``&&e.hash===``&&e.pathname===`/`,{message:`Expected the Worker's origin, without a path, credentials, or query string`})),aY=class extends B(`@usine/config/CloudflareLlmProviderKey`)({provider:hP,apiKeyEnv:qJ}){},oY=WT(e=>new Set(e.map(({provider:e})=>e)).size===e.length,{message:`Expected each provider once`}),sY=class extends B(`@usine/config/CloudflareWorker`)({name:qN,kind:pT(`cloudflare`),maxConcurrentAttempts:WJ,workerUrl:iY,accessClientIdEnv:qJ,accessClientSecretEnv:qJ,image:mP,instanceType:pP.pipe(RT(w(`standard-4`))),llmProviders:N(aY.pipe(wT({apiKeyEnv:`api_key_env`}))).check(oY).pipe(RT(w([])))}){},cY=P([GJ,KJ,nY,sY]),lY=class extends B(`@usine/config/Settings`)({upgradeChannel:OJ.pipe(RT(w(`latest`))),upgradeMode:kJ.pipe(RT(w(`propose`))),pollInterval:zJ.pipe(RT(w(60))),maxChildren:PP.pipe(RT(w(4))),maxAttemptMinutes:ME(zJ),maxAttemptTokens:ME(zJ),parentModel:ME(vA),parentEffort:ME(bA)}){},uY=P([M({mode:pT(`off`)}),M({mode:pT(`deliveries`)}),M({mode:pT(`endpoint`),publicUrl:mE}).pipe(wT({publicUrl:`public_url`}))]),dY=mE.check(WT(e=>e.protocol===`http:`||e.protocol===`https:`,{message:`Expected an http or https URL`}),WT(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`})),fY=class extends B(`@usine/config/Tracing`)({otlpUrl:dY,serviceName:MW(`Expected a non-blank service name`).pipe(RT(w(`usine`)))}){},pY=lY.pipe(wT({upgradeChannel:`upgrade_channel`,upgradeMode:`upgrade_mode`,pollInterval:`poll_interval`,maxChildren:`max_children`,maxAttemptMinutes:`max_attempt_minutes`,maxAttemptTokens:`max_attempt_tokens`,parentModel:`parent_model`,parentEffort:`parent_effort`})),mY=P([GJ.pipe(wT({maxConcurrentAttempts:`max_concurrent_attempts`})),KJ.pipe(wT({maxConcurrentAttempts:`max_concurrent_attempts`})),nY.pipe(wT({maxConcurrentAttempts:`max_concurrent_attempts`,identityFile:`identity_file`})).check(WT(e=>rY(e)??!0)),sY.pipe(wT({maxConcurrentAttempts:`max_concurrent_attempts`,workerUrl:`worker_url`,accessClientIdEnv:`access_client_id_env`,accessClientSecretEnv:`access_client_secret_env`,instanceType:`instance_type`,llmProviders:`llm_providers`}))]),hY=N(UJ).check(NW(e=>e.name)),gY=N(mY).check(iE(),BJ),_Y=class extends B(`@usine/config/UsineConfig`)(M({version:jT([1,2]),projects:N(LJ).pipe(RT(w([])),IT(w([]))),labels:HJ.pipe(RT(w([]))),repos:hY,settings:pY.pipe(RT(w({}))),workers:gY.pipe(RT(w([{name:`local`,kind:`local`}]))),webhooks:uY.pipe(RT(w({mode:`off`}))),operator:ME(ZM),tracing:ME(fY.pipe(wT({otlpUrl:`otlp_url`,serviceName:`service_name`})))}).check(WT(({version:e,projects:t,repos:n})=>{if(e===1)return t.length===0;let r=t.flatMap(({repositories:e})=>e.map(fA)),i=new Set(n.map(({name:e})=>fA(e)));return new Set(t.map(({id:e})=>e)).size===t.length&&new Set(r).size===r.length&&r.every(e=>i.has(e))&&n.every(({lanes:e})=>e.length===0)},{message:`Projects require version 2, unique identifiers, and registered repositories in at most one project; lanes belong to projects`}))){},vY=nT(uJ),yY=(e,t)=>new hJ({name:e,fields:t.map(([e,t,n])=>new mJ({name:e,type:vY(t),nullable:n===`nullable`}))}),bY=yY(`Actor`,[[`login`,`string`]]),xY=yY(`LabelActor`,[[`login`,`string`],[`type`,`string`]]),SY=yY(`LabelEvent`,[[`actor`,`LabelActor`,`nullable`],[`createdAt`,`string`]]),CY=yY(`Label`,[[`name`,`string`]]),wY=yY(`Milestone`,[[`title`,`string`]]),TY=yY(`IssueType`,[[`name`,`string`]]),EY=yY(`Commit`,[[`oid`,`string`]]),DY=yY(`RepoContext`,[[`name`,`string`],[`owner`,`string`],[`url`,`string`]]),OY=yY(`Labels`,[[`totalCount`,`int`],[`nodes`,`list<Label>`]]),kY=yY(`Assignees`,[[`totalCount`,`int`],[`nodes`,`list<Actor>`]]),AY=yY(`IssueComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),jY=yY(`IssueComments`,[[`totalCount`,`int`],[`nodes`,`list<IssueComment>`]]),MY=yY(`PullRequestReference`,[[`number`,`int`],[`state`,`string`],[`isDraft`,`bool`],[`url`,`string`]]),NY=yY(`PullRequestReferences`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestReference>`]]),PY=yY(`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`],[`labelEvents`,`map<string,LabelEvent>`],[`assignees`,`Assignees`],[`comments`,`IssueComments`],[`closedByPullRequestsReferences`,`PullRequestReferences`]]),FY=yY(`RequestedReviewer`,[[`login`,`string`,`nullable`]]),IY=yY(`ReviewRequest`,[[`requestedReviewer`,`RequestedReviewer`,`nullable`]]),LY=yY(`ReviewRequests`,[[`totalCount`,`int`],[`nodes`,`list<ReviewRequest>`]]),RY=yY(`Review`,[[`author`,`Actor`,`nullable`],[`state`,`string`],[`body`,`string`],[`submittedAt`,`string`,`nullable`],[`commit`,`Commit`,`nullable`]]),zY=yY(`Reviews`,[[`totalCount`,`int`],[`nodes`,`list<Review>`]]),BY=yY(`ReviewThreadComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`]]),VY=yY(`ReviewThreadComments`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThreadComment>`]]),HY=yY(`ReviewThread`,[[`isResolved`,`bool`],[`isOutdated`,`bool`],[`path`,`string`],[`comments`,`ReviewThreadComments`]]),UY=yY(`ReviewThreads`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThread>`]]),WY=yY(`PullRequestComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),GY=yY(`PullRequestComments`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestComment>`]]),KY=yY(`ClosingIssueReference`,[[`number`,`int`],[`state`,`string`]]),qY=yY(`ClosingIssueReferences`,[[`totalCount`,`int`],[`nodes`,`list<ClosingIssueReference>`]]),JY=yY(`StatusCheckRollup`,[[`state`,`string`]]),YY=yY(`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`],[`labelEvents`,`map<string,LabelEvent>`],[`reviewRequests`,`ReviewRequests`],[`reviews`,`Reviews`],[`reviewThreads`,`ReviewThreads`],[`comments`,`PullRequestComments`],[`closingIssuesReferences`,`ClosingIssueReferences`]]),XY=yY(`Tick`,[[`scheduledAt`,`string`],[`scheduledAtLocal`,`string`],[`cron`,`string`],[`tz`,`string`]]),ZY=yY(`SchedulePayload`,[[`tick`,`Tick`]]),QY=(e,t)=>new _J({types:[DY,...e],variables:[new gJ({name:`repo`,type:vY(`RepoContext`)}),new gJ({name:`item`,type:vY(t)})]}),$Y=QY([bY,xY,SY,CY,wY,TY,OY,kY,AY,jY,MY,NY,PY],`IssuePayload`),eX=QY([bY,xY,SY,CY,EY,OY,FY,IY,LY,RY,zY,BY,VY,HY,UY,WY,GY,KY,qY,JY,YY],`PullRequestPayload`),tX=QY([XY,ZY],`SchedulePayload`),nX=e=>{switch(e){case`issue`:return $Y;case`pr`:return eX;case`schedule`:return tX}},rX=e=>{let{owner:t}=dA(e.name);return{name:e.name,owner:t,url:`https://github.com/${e.name}`}},iX=class extends B(`@usine/config/Selector`)({repos:ME(N(H).check(iE(),NW(e=>e))),tags:ME(N(RJ).check(iE(),sE()))}){}.check(WT(e=>S(e.repos)||S(e.tags),{message:`Expected selector.repos, selector.tags, or both`})),aX=(e,t)=>pr(e,{onNone:()=>!0,onSome:e=>{let n=pr(e.repos,{onNone:()=>!0,onSome:e=>e.some(e=>fA(e)===fA(t.name))}),r=pr(e.tags,{onNone:()=>!0,onSome:e=>e.some(e=>t.tags.includes(e))});return n&&r}}),oX=j.check(WT(e=>e.trim().split(/\s+/u).length===5&&yi(Xp(e)),{message:`Expected a valid five-field cron expression`})).pipe(I(`Cron`)),sX=j.check(WT(e=>S(d_(e)),{message:`Expected an IANA time-zone name`})).pipe(I(`TimeZone`)),cX=class extends B(`@usine/config/IssueTrigger`)({on:pT(`issue`),if:vJ}){},lX=class extends B(`@usine/config/PullRequestTrigger`)({on:pT(`pr`),if:vJ}){},uX=class extends B(`@usine/config/ScheduleTrigger`)({on:pT(`schedule`),if:vJ,cron:oX,tz:sX.pipe(RT(w(`UTC`)))}){},dX=P([cX,lX,uX]),fX=jT([`issue`,`pr`,`schedule`]),pX=GT(/^(?:[a-z0-9]+(?:-[a-z0-9]+)*\/)?[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a loop name or project/loop identifier`}),mX=DA.check(pX),hX=MW(`Expected a non-blank Markdown prompt`).pipe(I(`PromptTemplate`)),gX=L.pipe(I(`PriorityValue`)),_X=P([gX,vJ]),vX=class extends B(`@usine/config/LoopFile`)({name:mX,trigger:dX,selector:z(iX),approval:kA,maxCycles:CI.pipe(RT(w(TI)),IT(w(TI))),permissions:jA.pipe(RT(w(`write`)),IT(w(`write`))),priority:z(_X).pipe(IT(w(y()))),step:GN,agent:SA,body:hX}){},yX=class extends B(`@usine/config/QuarantinedLoop`)({file:wJ,error:DJ}){},bX=e=>{let[t,n]=e.split(`/`);return wJ.make(n===void 0?`loops/${e}.md`:`projects/${t}/loops/${n}.md`)};O(`Loop.evaluatePriority`)(function*(e,t,n){if(yield*D({loop:t.name}),x(t.priority))return gX.make(0);let r=t.priority.value;if(te(r))return r;let i=yield*e.evaluateInteger(r,nX(t.trigger.on),n);return yield*Zw(gX)(Number(i)).pipe(Ph(()=>new SJ({source:r,message:`Priority must be a safe integer between -9007199254740991 and 9007199254740991`})))});var xX=class extends B(`@usine/config/AgentFile`)({name:SA,harness:yA,model:vA,effort:bA,parentModel:z(vA),parentEffort:z(bA),persona:CA}){get agent(){return new wA({name:this.name,persona:this.persona,brain:new xA({harness:this.harness,model:this.model,effort:this.effort}),parentModel:this.parentModel,parentEffort:this.parentEffort})}},SX=class extends B(`@usine/config/InvalidAgent`)({file:wJ,error:DJ}){},CX=class extends V(`@usine/config/UndeclaredLaneLabelWarning`)(`UndeclaredLaneLabelWarning`,{repository:H,lane:PW,label:MA}){},wX=class extends V(`@usine/config/UndeclaredTriggerLabelWarning`)(`UndeclaredTriggerLabelWarning`,{loop:vX.fields.name,label:MA}){},TX=P([CX,wX]),EX=(e,t)=>({agentNames:new Set(t.map(({name:e})=>e)),registryTags:new Set(e.repos.flatMap(({tags:e})=>e)),repoNames:new Set(e.repos.map(({name:e})=>fA(e)))}),DX=e=>e.map(e=>`"${e}"`).join(`, `),OX=(e,t,n)=>{let r=[],i=()=>r.length===0?y():b(new DJ({file:e,stage:`reference`,expression:y(),message:r.map(({message:e})=>e).join(`
192
+ `),details:r}));if(t.agent!==void 0&&!n.agentNames.has(t.agent)&&r.push({path:[`agent`],message:`Unknown agent "${t.agent}": agents/${t.agent}.md is missing or invalid. Fix the agent file, or set agent to an existing agent.`}),x(t.selector))return i();if(S(t.selector.value.repos)){let e=t.selector.value.repos.value.filter(e=>!n.repoNames.has(fA(e)));e.length>0&&r.push({path:[`selector`,`repos`],message:`Unknown repositories in selector.repos: ${DX(e)}. Add them under repos in usine.yaml.`})}if(S(t.selector.value.tags)){let e=t.selector.value.tags.value.filter(e=>!n.registryTags.has(e));e.length>0&&r.push({path:[`selector`,`tags`],message:`Unknown tags in selector.tags: ${DX(e)}. Add them to a repository's tags in usine.yaml.`})}return i()},kX=class extends B(`@usine/config/LoadedInstance`)(M({config:_Y,agents:N(xX),invalidAgents:N(SX),loops:N(vX),quarantinedLoops:N(yX),warnings:N(TX)}).check(WT(({agents:e,config:t,loops:n})=>{let r=EX(t,e);return new Set(n.map(({name:e})=>e)).size!==n.length||t.version===2&&!n.every(({name:e})=>t.projects.some(({id:t})=>e.startsWith(`${t}/`)))?!1:n.every(e=>x(OX(bX(e.name),e,r)))},{message:`Expected every loop to reference only loaded agents and registry entries`}))){},AX=L.check($T(0)).pipe(I(`ConfigurationRevisionNumber`)),jX=jT([`settings`,`worker`,`repository`,`project`,`label`,`loop`,`agent`]),MX=R.pipe(I(`ConfigurationEntityId`)),NX=class extends B(`@usine/config/ConfigurationEntityKey`)({kind:jX,identifier:MX}){get key(){return`${this.kind}:${this.identifier}`}},PX=class extends B(`@usine/config/ConfigurationEntity`)({key:NX,value:JE}){},FX=class extends B(`@usine/config/ConfigurationChange`)({key:NX,before:z(JE),after:z(JE),position:lT(L.check($T(0)))}){};(class e extends B(`@usine/config/Configuration`)(M({number:AX,instance:z(kX)}).check(WT(({number:e,instance:t})=>e===0===x(t),{message:`Only an uninitialized configuration has revision zero`}))){get actor(){return Cr(this.instance,({config:e})=>e.operator)}static empty=new e({number:AX.make(0),instance:y()})}),B(`@usine/config/ConfigurationRevision`)({number:AX.check(QT(0)),actor:z(ZM),time:OE,message:z(j),changes:N(FX)}),WE(`@usine/config/StaleRevision`)(`StaleRevision`,{expected:AX,actual:AX});var IX=class extends WE(`@usine/config/ConfigurationInvalid`)(`ConfigurationInvalid`,{problems:kT(DJ)}){};WE(`@usine/config/ConfigurationStoreError`)(`ConfigurationStoreError`,{operation:j,cause:dE()}),WE(`@usine/config/ConfigurationRevertBlocked`)(`ConfigurationRevertBlocked`,{entities:kT(NX)});var LX=(e,t,n)=>aX(t.selector,n)&&(e.version===1||e.projects.some(e=>t.name.startsWith(`${e.id}/`)&&e.includes(n.name))),RX=e=>e.version===1?e.repos:e.projects.flatMap(t=>t.repositories.flatMap(n=>e.repos.filter(e=>fA(e.name)===fA(n)).map(e=>new UJ({...e,lanes:t.lanes})))),zX=(e,t)=>{let n=new Map(e.labels.map(e=>[NA(e.name),e]));for(let r of e.projects.filter(e=>e.includes(t)))for(let e of r.lanes.flatMap(({sources:e})=>e))`label`in e&&!n.has(NA(e.label))&&n.set(NA(e.label),new IA({name:e.label,color:y(),description:y()}));return[...n.values()]},BX=(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},VX=(e,t)=>{let n=t.startsWith(`---\r
193
+ `)?`\r
194
+ `:t.startsWith(`---
195
+ `)?`
196
+ `:void 0;if(n===void 0)return new DJ({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=BX(t,n,r);if(a<0)return new DJ({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 w({yaml:t.slice(r,a),body:t.slice(s),newline:n})},HX=Symbol.for(`yaml.alias`),UX=Symbol.for(`yaml.document`),WX=Symbol.for(`yaml.map`),GX=Symbol.for(`yaml.pair`),KX=Symbol.for(`yaml.scalar`),qX=Symbol.for(`yaml.seq`),JX=Symbol.for(`yaml.node.type`),YX=e=>!!e&&typeof e==`object`&&e[JX]===HX,XX=e=>!!e&&typeof e==`object`&&e[JX]===UX,ZX=e=>!!e&&typeof e==`object`&&e[JX]===WX,QX=e=>!!e&&typeof e==`object`&&e[JX]===GX,$X=e=>!!e&&typeof e==`object`&&e[JX]===KX,eZ=e=>!!e&&typeof e==`object`&&e[JX]===qX;function tZ(e){if(e&&typeof e==`object`)switch(e[JX]){case WX:case qX:return!0}return!1}function nZ(e){if(e&&typeof e==`object`)switch(e[JX]){case HX:case WX:case KX:case qX:return!0}return!1}var rZ=e=>($X(e)||tZ(e))&&!!e.anchor,iZ=Symbol(`break visit`),aZ=Symbol(`skip children`),oZ=Symbol(`remove node`);function sZ(e,t){let n=lZ(t);XX(e)?cZ(null,e.contents,n,Object.freeze([e]))===oZ&&(e.contents=null):cZ(null,e,n,Object.freeze([]))}sZ.BREAK=iZ,sZ.SKIP=aZ,sZ.REMOVE=oZ;function cZ(e,t,n,r){let i=uZ(e,t,n,r);if(nZ(i)||QX(i))return dZ(e,r,i),cZ(e,i,n,r);if(typeof i!=`symbol`){if(tZ(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=cZ(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===iZ)return iZ;else i===oZ&&(t.items.splice(e,1),--e)}}else if(QX(t)){r=Object.freeze(r.concat(t));let e=cZ(`key`,t.key,n,r);if(e===iZ)return iZ;e===oZ&&(t.key=null);let i=cZ(`value`,t.value,n,r);if(i===iZ)return iZ;i===oZ&&(t.value=null)}}return i}function lZ(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 uZ(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(ZX(t))return n.Map?.(e,t,r);if(eZ(t))return n.Seq?.(e,t,r);if(QX(t))return n.Pair?.(e,t,r);if($X(t))return n.Scalar?.(e,t,r);if(YX(t))return n.Alias?.(e,t,r)}function dZ(e,t,n){let r=t[t.length-1];if(tZ(r))r.items[e]=n;else if(QX(r))e===`key`?r.key=n:r.value=n;else if(XX(r))r.contents=n;else{let e=YX(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var fZ={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},pZ=e=>e.replace(/[!,[\]{}]/g,e=>fZ[e]),mZ=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+pZ(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&&nZ(e.contents)){let t={};sZ(e.contents,(e,n)=>{nZ(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(`
197
+ `)}};mZ.defaultYaml={explicit:!1,version:`1.2`},mZ.defaultTags={"!!":`tag:yaml.org,2002:`};function hZ(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 gZ(e){let t=new Set;return sZ(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function _Z(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function vZ(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=gZ(e);let a=_Z(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&($X(t.node)||tZ(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 yZ(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=yZ(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=yZ(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=yZ(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=yZ(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function bZ(e,t,n){if(Array.isArray(e))return e.map((e,t)=>bZ(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!rZ(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 xZ=class{constructor(e){Object.defineProperty(this,JX,{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(!XX(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=bZ(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?yZ(i,{"":o},``,o):o}},SZ=class extends xZ{constructor(e){super(HX),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=[],sZ(e,{Node:(e,t)=>{(YX(t)||rZ(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||=(bZ(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=CZ(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(hZ(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 CZ(e,t,n){if(YX(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(tZ(t)){let r=0;for(let i of t.items){let t=CZ(e,i,n);t>r&&(r=t)}return r}if(QX(t)){let r=CZ(e,t.key,n),i=CZ(e,t.value,n);return Math.max(r,i)}return 1}var wZ=e=>!e||typeof e!=`function`&&typeof e!=`object`,TZ=class extends xZ{constructor(e){super(KX),this.value=e}toJSON(e,t){return t?.keep?this.value:bZ(this.value,e,t)}toString(){return String(this.value)}};TZ.BLOCK_FOLDED=`BLOCK_FOLDED`,TZ.BLOCK_LITERAL=`BLOCK_LITERAL`,TZ.PLAIN=`PLAIN`,TZ.QUOTE_DOUBLE=`QUOTE_DOUBLE`,TZ.QUOTE_SINGLE=`QUOTE_SINGLE`;var EZ=`tag:yaml.org,2002:`;function DZ(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 OZ(e,t,n){if(XX(e)&&(e=e.contents),nZ(e))return e;if(QX(e)){let t=n.schema[WX].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 SZ(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=EZ+t.slice(2));let l=DZ(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new TZ(e);return c&&(c.node=t),t}l=e instanceof Map?o[WX]:Symbol.iterator in Object(e)?o[qX]:o[WX]}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 TZ(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function kZ(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 OZ(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var AZ=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,jZ=class extends xZ{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=>nZ(t)||QX(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(AZ(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(tZ(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,kZ(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(tZ(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&&$X(i)?i.value:i:tZ(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!QX(t))return!1;let n=t.value;return n==null||e&&$X(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 tZ(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(tZ(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,kZ(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},MZ=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function NZ(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var PZ=(e,t,n)=>e.endsWith(`
198
+ `)?NZ(n,t):n.includes(`
199
+ `)?`
200
+ `+NZ(n,t):(e.endsWith(` `)?``:` `)+n,FZ=`flow`,IZ=`block`,LZ=`quoted`;function RZ(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=zZ(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===`
201
+ `)n===`block`&&(h=zZ(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
202
+ `&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
203
+ `&&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 zZ(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!==`
204
+ `);r=t,i=t+1,a=e[i]}return r}var BZ=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),VZ=e=>/^(%|---|\.\.\.)/m.test(e);function HZ(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]===`
205
+ `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function UZ(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(VZ(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)+`
206
+
207
+ `;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
208
+ `,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:RZ(o,a,LZ,BZ(t,!1))}function WZ(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
209
+ `)||/[ \t]\n|\n[ \t]/.test(e))return UZ(e,t);let n=t.indent||(VZ(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:RZ(r,n,FZ,BZ(t,!1))}function GZ(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=UZ;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?WZ:i&&!t?UZ:n?WZ:UZ}return r(e,t)}var KZ;try{KZ=RegExp(`(^|(?<!
210
+ ))
211
+ +(?!
212
+ |$)`,`g`)}catch{KZ=/\n+(?!\n|$)/g}function qZ({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 GZ(n,r);let l=r.indent||(r.forceBlockIndent||VZ(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===TZ.BLOCK_FOLDED?!1:t===TZ.BLOCK_LITERAL||!HZ(n,c,l.length);if(!n)return u?`|
213
+ `:`>
214
+ `;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
215
+ `&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
216
+ `);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
217
+ `&&(p=p.slice(0,-1)),p.replace(KZ,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
218
+ `)_=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,`
219
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=BZ(r,!0);o!==`folded`&&t!==TZ.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=RZ(`${v}${e}${p}`,l,IZ,a);if(!i)return`>${ee}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${ee}\n${l}${v}${n}${p}`}function JZ(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(`
220
+ `)||u&&/[[\]{},]/.test(a))return GZ(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
221
+ `)?GZ(a,t):qZ(e,t,n,r);if(!s&&!u&&i!==TZ.PLAIN&&a.includes(`
222
+ `))return qZ(e,t,n,r);if(VZ(a)){if(c===``)return t.forceBlockIndent=!0,qZ(e,t,n,r);if(s&&c===l)return GZ(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 GZ(a,t)}return s?d:RZ(d,c,FZ,BZ(t,!1))}function YZ(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!==TZ.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=TZ.QUOTE_DOUBLE);let c=e=>{switch(e){case TZ.BLOCK_FOLDED:case TZ.BLOCK_LITERAL:return i||a?GZ(o.value,t):qZ(o,t,n,r);case TZ.QUOTE_DOUBLE:return UZ(o.value,t);case TZ.QUOTE_SINGLE:return WZ(o.value,t);case TZ.PLAIN:return JZ(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 XZ(e,t){let n=Object.assign({blockQuote:!0,commentString:MZ,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 ZZ(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($X(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 QZ(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=($X(e)||tZ(e))&&e.anchor;a&&hZ(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 $Z(e,t,n,r){if(QX(e))return e.toString(t,n,r);if(YX(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=nZ(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=ZZ(t.doc.schema.tags,a);let o=QZ(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):$X(a)?YZ(a,t,n,r):a.toString(t,n,r);return o?$X(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function eQ({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=nZ(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(tZ(e)||!nZ(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||tZ(e)||($X(e)?e.type===TZ.BLOCK_FOLDED||e.type===TZ.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=$Z(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+=PZ(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=PZ(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=PZ(g,n.indent,l(f))));let _,v,ee;nZ(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&&$X(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&eZ(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let te=!1,ne=$Z(t,n,()=>te=!0,()=>h=!0),re=` `;if(f||_||v){if(re=_?`
223
+ `:``,v){let e=l(v);re+=`\n${NZ(e,n.indent)}`}ne===``&&!n.inFlow?re===`
224
+ `&&ee&&(re=`
225
+
226
+ `):re+=`\n${n.indent}`}else if(!p&&tZ(t)){let e=ne[0],r=ne.indexOf(`
227
+ `),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]===`
228
+ `)&&(re=``);return g+=re+ne,n.inFlow?te&&r&&r():ee&&!te?g+=PZ(g,n.indent,l(ee)):h&&i&&i(),g}function tQ(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var nQ=`<<`,rQ={identify:e=>e===nQ||typeof e==`symbol`&&e.description===nQ,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new TZ(Symbol(nQ)),{addToJSMap:aQ}),stringify:()=>nQ},iQ=(e,t)=>(rQ.identify(t)||$X(t)&&(!t.type||t.type===TZ.PLAIN)&&rQ.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===rQ.tag&&e.default);function aQ(e,t,n){let r=sQ(e,n);if(eZ(r))for(let n of r.items)oQ(e,t,n);else if(Array.isArray(r))for(let n of r)oQ(e,t,n);else oQ(e,t,r)}function oQ(e,t,n){let r=sQ(e,n);if(!ZX(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 sQ(e,t){return e&&YX(t)?t.resolve(e.doc,e):t}function cQ(e,t,{key:n,value:r}){if(nZ(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(iQ(e,n))aQ(e,t,r);else{let i=bZ(n,``,e);if(t instanceof Map)t.set(i,bZ(r,i,e));else if(t instanceof Set)t.add(i);else{let a=lQ(n,i,e),o=bZ(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function lQ(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(nZ(e)&&n?.doc){let t=XZ(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)+`..."`),tQ(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 uQ(e,t,n){return new dQ(OZ(e,void 0,n),OZ(t,void 0,n))}var dQ=class e{constructor(e,t=null){Object.defineProperty(this,JX,{value:GX}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return nZ(n)&&(n=n.clone(t)),nZ(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return cQ(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?eQ(this,e,t,n):JSON.stringify(this)}};function fQ(e,t,n){return(t.inFlow??e.flow?mQ:pQ)(e,t,n)}function pQ({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(nZ(i))!d&&i.spaceBefore&&f.push(``),hQ(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(QX(i)){let e=nZ(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),hQ(n,f,e.commentBefore,d))}d=!1;let s=$Z(i,u,()=>o=null,()=>d=!0);o&&(s+=PZ(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}`:`
229
+ `}}return e?(p+=`
230
+ `+NZ(l(e),c),s&&s()):d&&o&&o(),p}function mQ({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(nZ(i))i.spaceBefore&&d.push(``),hQ(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(QX(i)){let e=nZ(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),hQ(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=nZ(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=$Z(i,c,()=>a=null);l||=d.length>u||o.includes(`
231
+ `),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+=PZ(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}`:`
232
+ `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function hQ({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=NZ(t(r),e);n.push(i.trimStart())}}function gQ(e,t){let n=$X(t)?t.value:t;for(let r of e)if(QX(r)&&(r.key===t||r.key===n||$X(r.key)&&r.key.value===n))return r}var _Q=class extends jZ{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(WX,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(uQ(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=QX(e)?e:!e||typeof e!=`object`||!(`key`in e)?new dQ(e,e?.value):new dQ(e.key,e.value);let r=gQ(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);$X(r.value)&&wZ(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=gQ(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=gQ(this.items,e)?.value;return(!t&&$X(n)?n.value:n)??void 0}has(e){return!!gQ(this.items,e)}set(e,t){this.add(new dQ(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)cQ(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!QX(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})),fQ(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},vQ={collection:`map`,default:!0,nodeClass:_Q,tag:`tag:yaml.org,2002:map`,resolve(e,t){return ZX(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>_Q.from(e,t,n)},yQ=class extends jZ{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(qX,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=bQ(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=bQ(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&$X(r)?r.value:r}has(e){let t=bQ(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=bQ(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];$X(r)&&wZ(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(bZ(e,String(r++),t));return n}toString(e,t,n){return e?fQ(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(OZ(a,void 0,n))}}return i}};function bQ(e){let t=$X(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var xQ={collection:`seq`,default:!0,nodeClass:yQ,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return eZ(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>yQ.from(e,t,n)},SQ={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),YZ(e,t,n,r)}},CQ={identify:e=>e==null,createNode:()=>new TZ(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new TZ(null),stringify:({source:e},t)=>typeof e==`string`&&CQ.test.test(e)?e:t.options.nullStr},wQ={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new TZ(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&wQ.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function TQ({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 EQ={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:TQ},DQ={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():TQ(e)}},OQ={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 TZ(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:TQ},kQ=e=>typeof e==`bigint`||Number.isInteger(e),AQ=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function jQ(e,t,n){let{value:r}=e;return kQ(r)&&r>=0?n+r.toString(t):TQ(e)}var MQ={identify:e=>kQ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>AQ(e,2,8,n),stringify:e=>jQ(e,8,`0o`)},NQ={identify:kQ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>AQ(e,0,10,n),stringify:TQ},PQ={identify:e=>kQ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>AQ(e,2,16,n),stringify:e=>jQ(e,16,`0x`)},FQ=[vQ,xQ,SQ,CQ,wQ,MQ,NQ,PQ,EQ,DQ,OQ];function IQ(e){return typeof e==`bigint`||Number.isInteger(e)}var LQ=({value:e})=>JSON.stringify(e),RQ=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:LQ},{identify:e=>e==null,createNode:()=>new TZ(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:LQ},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:LQ},{identify:IQ,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})=>IQ(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:LQ}],zQ=[vQ,xQ].concat(RQ,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}}),BQ={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??=TZ.BLOCK_LITERAL,t!==TZ.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===TZ.BLOCK_LITERAL?`
233
+ `:` `)}return YZ({comment:e,type:t,value:s},r,i,a)}};function VQ(e,t){if(eZ(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!QX(r)){if(ZX(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new dQ(new TZ(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]=QX(r)?r:new dQ(r)}}else t(`Expected a sequence for this tag`);return e}function HQ(e,t,n){let{replacer:r}=n,i=new yQ(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(uQ(o,s,n))}return i}var UQ={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:VQ,createNode:HQ},WQ=class e extends yQ{constructor(){super(),this.add=_Q.prototype.add.bind(this),this.delete=_Q.prototype.delete.bind(this),this.get=_Q.prototype.get.bind(this),this.has=_Q.prototype.has.bind(this),this.set=_Q.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(QX(e)?(r=bZ(e.key,``,t),i=bZ(e.value,r,t)):r=bZ(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=HQ(e,t,n),i=new this;return i.items=r.items,i}};WQ.tag=`tag:yaml.org,2002:omap`;var GQ={collection:`seq`,identify:e=>e instanceof Map,nodeClass:WQ,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=VQ(e,t),r=[];for(let{key:e}of n.items)$X(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new WQ,n)},createNode:(e,t,n)=>WQ.from(e,t,n)};function KQ({value:e,source:t},n){return t&&(e?qQ:JQ).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var qQ={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 TZ(!0),stringify:KQ},JQ={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 TZ(!1),stringify:KQ},YQ={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:TQ},XQ={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():TQ(e)}},ZQ={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 TZ(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:TQ},QQ=e=>typeof e==`bigint`||Number.isInteger(e);function $Q(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 e$(e,t,n){let{value:r}=e;if(QQ(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return TQ(e)}var t$={identify:QQ,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>$Q(e,2,2,n),stringify:e=>e$(e,2,`0b`)},n$={identify:QQ,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>$Q(e,1,8,n),stringify:e=>e$(e,8,`0`)},r$={identify:QQ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>$Q(e,0,10,n),stringify:TQ},i$={identify:QQ,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>$Q(e,2,16,n),stringify:e=>e$(e,16,`0x`)},a$=class e extends _Q{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=QX(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new dQ(e.key,null):new dQ(e,null),gQ(this.items,t.key)||this.items.push(t)}get(e,t){let n=gQ(this.items,e);return!t&&QX(n)?$X(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=gQ(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new dQ(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(uQ(e,null,n));return i}};a$.tag=`tag:yaml.org,2002:set`;var o$={collection:`map`,identify:e=>e instanceof Set,nodeClass:a$,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>a$.from(e,t,n),resolve(e,t){if(ZX(e)){if(e.hasAllNullValues(!0))return Object.assign(new a$,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}};function s$(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 c$(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return TQ(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 l$={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})=>s$(e,n),stringify:c$},u$={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=>s$(e,!1),stringify:c$},d$={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(d$.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=s$(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$/,``)??``},f$=[vQ,xQ,SQ,CQ,qQ,JQ,t$,n$,r$,i$,YQ,XQ,ZQ,BQ,rQ,GQ,UQ,o$,l$,u$,d$],p$=new Map([[`core`,FQ],[`failsafe`,[vQ,xQ,SQ]],[`json`,zQ],[`yaml11`,f$],[`yaml-1.1`,f$]]),m$={binary:BQ,bool:wQ,float:OQ,floatExp:DQ,floatNaN:EQ,floatTime:u$,int:NQ,intHex:PQ,intOct:MQ,intTime:l$,map:vQ,merge:rQ,null:CQ,omap:GQ,pairs:UQ,seq:xQ,set:o$,timestamp:d$},h$={"tag:yaml.org,2002:binary":BQ,"tag:yaml.org,2002:merge":rQ,"tag:yaml.org,2002:omap":GQ,"tag:yaml.org,2002:pairs":UQ,"tag:yaml.org,2002:set":o$,"tag:yaml.org,2002:timestamp":d$};function g$(e,t,n){let r=p$.get(t);if(r&&!e)return n&&!r.includes(rQ)?r.concat(rQ):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(p$.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(rQ)),i.reduce((e,t)=>{let n=typeof t==`string`?m$[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(m$).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 _$=(e,t)=>e.key<t.key?-1:+(e.key>t.key),v$=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?g$(e,`compat`):e?g$(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?h$:{},this.tags=g$(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,WX,{value:vQ}),Object.defineProperty(this,KX,{value:SQ}),Object.defineProperty(this,qX,{value:xQ}),this.sortMapEntries=typeof a==`function`?a:a===!0?_$:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function y$(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=XZ(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(NZ(t,``))}let o=!1,s=null;if(e.contents){if(nZ(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(NZ(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=$Z(e.contents,i,()=>s=null,t);s&&(c+=PZ(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push($Z(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
234
+ `)?(n.push(`...`),n.push(NZ(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(NZ(a(t),``)))}return n.join(`
235
+ `)+`
236
+ `}var b$=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,JX,{value:UX});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 mZ({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[JX]:{value:UX}});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=nZ(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){x$(this.contents)&&this.contents.add(e)}addIn(e,t){x$(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=gZ(this);e.anchor=!t||n.has(t)?_Z(t||`a`,n):t}return new SZ(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}=vZ(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=OZ(e,l,p);return o&&tZ(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new dQ(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return x$(this.contents)?this.contents.delete(e):!1}deleteIn(e){return AZ(e)?this.contents!=null&&(this.contents=null,!0):x$(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return tZ(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return AZ(e)?!t&&$X(this.contents)?this.contents.value:this.contents:tZ(this.contents)?this.contents.getIn(e,t):void 0}has(e){return tZ(this.contents)?this.contents.has(e):!1}hasIn(e){return AZ(e)?this.contents!==void 0:tZ(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=kZ(this.schema,[e],t):x$(this.contents)&&this.contents.set(e,t)}setIn(e,t){AZ(e)?this.contents=t:this.contents==null?this.contents=kZ(this.schema,Array.from(e),t):x$(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 mZ({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 mZ({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 v$(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=bZ(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`?yZ(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 y$(this,e)}};function x$(e){if(tZ(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var S$=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},C$=class extends S${constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},w$=class extends S${constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},T$=(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)+`…
237
+ `),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 E$(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 D$(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
238
+ `))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(D$(t.key)||D$(t.value))return!0}return!1;default:return!0}}function O$(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&D$(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function k$(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||$X(e)&&$X(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var A$=`All mapping items must start at the same column`;function j$({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??_Q)(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=E$(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`,A$)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
239
+ `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||D$(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`,A$);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&O$(r.indent,u,i),n.atKey=!1,k$(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=E$(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&&O$(r.indent,f,i),s=c.range[2];let l=new dQ(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+=`
240
+ `+_.comment:g.comment=_.comment);let e=new dQ(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 M$({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??yQ)(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=E$(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&&O$(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function N$(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 P$=`Block collections are not allowed within flow collections`,F$=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function I$({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?_Q:yQ))(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=E$(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+=`
241
+ `+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&D$(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];QX(t)&&(t=t.value??t.key),t.comment?t.comment+=`
242
+ `+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],F$(m)&&i(r.range,`BLOCK_IN_FLOW`,P$)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);F$(f)&&i(g.range,`BLOCK_IN_FLOW`,P$),n.atKey=!1;let _=E$(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?F$(m)&&i(v.range,`BLOCK_IN_FLOW`,P$):_.comment&&(g.comment?g.comment+=`
243
+ `+_.comment:g.comment=_.comment);let ee=new dQ(g,v);if(n.options.keepSourceTokens&&(ee.srcToken=l),o){let e=c;k$(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(ee)}else{let e=new _Q(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=N$(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
244
+ `+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function L$(e,t,n,r,i,a){let o=n.type===`block-map`?j$(e,t,n,r,a):n.type===`block-seq`?M$(e,t,n,r,a):I$(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function R$(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===_Q.tagName&&s===`map`||o===yQ.tagName&&s===`seq`)return L$(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),L$(e,t,n,i,o)}let l=L$(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=nZ(u)?u:new TZ(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function z$(e,t,n){let r=t.offset,i=B$(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?TZ.BLOCK_FOLDED:TZ.BLOCK_LITERAL,o=t.source?V$(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?`
245
+ `.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)+`
246
+ `;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===TZ.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
247
+ `):t.length>c||r[0]===` `?(f===` `?f=`
248
+ `:!p&&f===`
249
+ `&&(f=`
250
+
251
+ `),d+=f+t.slice(c)+r,f=`
252
+ `,p=!0):r===``?f===`
253
+ `?d+=`
254
+ `:f=`
255
+ `:(d+=f+r,f=` `,p=!1)}switch(i.chomp){case`-`:break;case`+`:for(let e=s;e<o.length;++e)d+=`
256
+ `+o[e][0].slice(c);d[d.length-1]!==`
257
+ `&&(d+=`
258
+ `);break;default:d+=`
259
+ `}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function B$({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 V$(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 H$(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=TZ.PLAIN,c=U$(a,l);break;case`single-quoted-scalar`:s=TZ.QUOTE_SINGLE,c=W$(a,l);break;case`double-quoted-scalar`:s=TZ.QUOTE_DOUBLE,c=K$(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=N$(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function U$(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}`),G$(e)}function W$(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),G$(e.slice(1,-1)).replace(/''/g,`'`)}function G$(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===`
260
+ `?a+=o:o=`
261
+ `:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function K$(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
262
+ `){if(i===`
263
+ `){let{fold:t,offset:i}=q$(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=J$[i];if(a)n+=a;else if(i===`
264
+ `)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
265
+ `)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+=Y$(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!==`
266
+ `&&(a!==`\r`||e[r+2]!==`
267
+ `)&&(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 q$(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
268
+ `||r===`\r`)&&(r!==`\r`||e[t+2]===`
269
+ `);)r===`
270
+ `&&(n+=`
271
+ `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var J$={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
272
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function Y$(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 X$(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?z$(e,t,r):H$(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[KX]:c?Z$(e.schema,i,c,n,r):t.type===`scalar`?Q$(e,i,t,r):e.schema[KX];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=$X(a)?a:new TZ(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new TZ(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 Z$(e,t,n,r,i){if(n===`!`)return e[KX];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[KX])}function Q$({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[KX];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[KX];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 $$(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 e1={composeNode:t1,composeEmptyNode:n1};function t1(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=r1(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=X$(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=R$(e1,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??=n1(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&&(!$X(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 n1(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=X$(e,{type:`scalar`,offset:$$(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 r1({options:e},{offset:t,source:n,end:r},i){let a=new SZ(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=N$(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function i1(e,t,{offset:n,start:r,value:i,end:a},o){let s=new b$(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=E$(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?t1(c,i,l,o):n1(c,l.end,r,null,l,o);let u=s.contents.range[2],d=N$(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function a1(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 o1(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?`
273
+
274
+ `:`
275
+ `)+(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 s1=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=a1(e);r?this.warnings.push(new w$(i,t,n)):this.errors.push(new C$(i,t,n))},this.directives=new mZ({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=o1(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(tZ(i)&&!i.flow&&i.items.length>0){let e=i.items[0];QX(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:o1(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=a1(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=i1(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 C$(a1(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 C$(a1(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=N$(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 C$(a1(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 b$(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}}},c1=Symbol(`break visit`),l1=Symbol(`skip children`),u1=Symbol(`remove item`);function d1(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),f1(Object.freeze([]),e,t)}d1.BREAK=c1,d1.SKIP=l1,d1.REMOVE=u1,d1.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},d1.parentCollection=(e,t)=>{let n=d1.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 f1(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=f1(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===c1)return c1;else r===u1&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function p1(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`
276
+ `:case`\r
277
+ `: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 m1(e){switch(e){case void 0:case` `:case`
278
+ `:case`\r`:case` `:return!0;default:return!1}}var h1=new Set(`0123456789ABCDEFabcdef`),g1=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),_1=new Set(`,[]{}`),v1=new Set(` ,[]{}
279
+ \r `),y1=e=>!e||v1.has(e),b1=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===`
280
+ `||t===`\r`&&this.buffer[e+1]===`
281
+ `}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===`
282
+ `||!t&&!this.atEnd)return e+n+1}return t===`
283
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&m1(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(`
284
+ `,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===`...`)&&m1(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&&!m1(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===`:`)&&m1(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(y1),`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(`...`))&&m1(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(y1),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||m1(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(`
285
+ `,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
286
+ `,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=>m1(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`
287
+ `:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
288
+ `)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(`
289
+ `,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===`
290
+ `;)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===`
291
+ `&&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(m1(r)||e&&_1.has(r))break;t=n}else if(m1(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
292
+ `?(n+=1,r=`
293
+ `,i=this.buffer[n+1]):t=n),i===`#`||e&&_1.has(i))break;if(r===`
294
+ `){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&_1.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(y1),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(m1(n)||t&&_1.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(;!m1(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(g1.has(t))t=this.buffer[++e];else if(t===`%`&&h1.has(this.buffer[e+1])&&h1.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===`
295
+ `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
296
+ `?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)}},x1=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 S1(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function C1(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 w1(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 T1(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 E1(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 D1(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 O1(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!S1(t.start,`explicit-key-ind`)&&!S1(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,w1(t.value)?t.value.end?D1(t.value.end,t.sep):t.value.end=t.sep:D1(t.start,t.sep),delete t.sep)}var k1=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 b1,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=p1(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`&&O1(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&&C1(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`:C1(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=E1(T1(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(`
297
+ `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
298
+ `,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)){D1(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(S1(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=E1(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(S1(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(w1(t.key)&&!S1(t.sep,`newline`)){let e=E1(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]}):S1(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&&!S1(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)){D1(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||S1(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=E1(T1(t));O1(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(`
299
+ `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
300
+ `,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=E1(T1(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=E1(T1(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 A1(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new x1||null,prettyErrors:t}}function j1(e,t={}){let{lineCounter:n,prettyErrors:r}=A1(t),i=new k1(n?.addNewLine),a=new s1(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 C$(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(T$(e,n)),o.warnings.forEach(T$(e,n))),o}function M1(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return XX(e)&&!r?e.toString(n):new b$(e,r,n).toString(n)}var N1=e=>pr($w(M({message:R}))(e),{onNone:()=>`The YAML parser failed without an error message`,onSome:({message:e})=>e}),P1=(e,t)=>T(function*(){let n=yield*gh({try:()=>j1(t,{keepSourceTokens:!0,prettyErrors:!0,strict:!0,uniqueKeys:!0}),catch:t=>new DJ({file:e,stage:`yaml`,expression:y(),message:N1(t)})}),r=n.errors[0]??n.warnings[0];return r===void 0?n:yield*new DJ({file:e,stage:`yaml`,expression:y(),message:r.message})}),F1=e=>M1(e);B(`@usine/config/YamlEdit`)({path:N(R).check(iE()),value:JE});var I1=(e,t)=>{let n=e.replaceAll(`\r
301
+ `,`
302
+ `);return t===`\r
303
+ `?n.replaceAll(`
304
+ `,`\r
305
+ `):n},L1=O(`YamlWriter.updateYaml`)((e,t,n)=>T(function*(){let r=yield*P1(e,t);return r.setIn(n.path,n.value),I1(r.toString(),t.includes(`\r
306
+ `)?`\r
307
+ `:`
308
+ `)}));O(`YamlWriter.updateFrontmatter`)((e,t,n)=>T(function*(){let r=yield*VX(e,t),i=I1(yield*L1(e,r.yaml,n),r.newline),a=i.endsWith(r.newline)?i.slice(0,-r.newline.length):i;return`---${r.newline}${a}${r.newline}---${r.newline}${r.body}`}));var R1=Cy(),z1=P([j,yT]).annotate({message:`Expected a CEL expression. Quote the value so that YAML reads it as a string.`}).pipe(NT(vJ,{decode:Fy(e=>String(e)),encode:Fy(e=>e)})),B1=P([cX.mapFields(Pw({if:z1})).pipe(NT(cX)),lX.mapFields(Pw({if:z1})).pipe(NT(lX)),uX.mapFields(Pw({if:z1})).pipe(NT(uX))]),V1=class extends B(`@usine/config/LoopFrontmatter`)({trigger:B1,selector:ME(iX),approval:kA.pipe(RT(w(`none`))),step:GN.pipe(RT(w(`run`))),agent:SA,maxCycles:vX.fields.maxCycles,permissions:vX.fields.permissions,priority:ME(_X)}){},H1=V1.pipe(wT({maxCycles:`max_cycles`})),U1=class extends B(`@usine/config/AgentFrontmatter`)({harness:yA,model:vA,effort:bA,parentModel:ME(vA),parentEffort:ME(bA)}){},W1=U1.pipe(wT({parentModel:`parent_model`,parentEffort:`parent_effort`})),G1=e=>`---\n${F1(oT(W1)(new U1(e)))}---\n${e.persona}`,K1=e=>`---\n${F1(oT(H1)(new V1(e)))}---\n${e.body}`,q1=(e,t)=>DJ.fromSchema(e,t),J1=Zw(JE),Y1=(e,t)=>T(function*(){return yield*J1((yield*P1(e,t)).toJS()).pipe(Ph(t=>new DJ({file:e,stage:`yaml`,expression:y(),message:R1(t.issue)})))}),X1=(e,t,n)=>{let r={path:n,message:t.message,expression:t.source},i=t._tag===`ExpressionCheckError`&&S(t.position)?{...r,position:t.position.value}:r;return new DJ({file:e,stage:`expression`,expression:b(t.source),message:t.message,details:[i]})},Z1=e=>{let t=e.slice(e.lastIndexOf(`/`)+1);return t.endsWith(`.md`)?w(t.slice(0,-3)):new DJ({file:e,stage:`schema`,expression:y(),message:`Expected a .md filename`})},Q1=e=>Z1(e).pipe(E(t=>Zw(vX.fields.name)(e.startsWith(`projects/`)?`${e.split(`/`)[1]}/${t}`:e.startsWith(`loops/`)?e.slice(6,-3):t).pipe(Ph(t=>q1(e,t))))),$1=e=>Z1(e).pipe(E(t=>Zw(SA)(t).pipe(Ph(t=>q1(e,t))))),e0=(e,t)=>{let n=[],r=[],i=0;for(;i<t.length;){let a=t.indexOf(`{{`,i);if(a<0)break;let o=t.indexOf(`}}`,a+2);if(o<0){let t=`The prompt has an unclosed {{ at character ${a}. Close it with }}.`;r.push(new DJ({file:e,stage:`expression`,expression:y(),message:t,details:[{path:[`body`],message:t}]}));break}let s=tT(vJ)(t.slice(a+2,o).trim());if(yi(s))n.push({source:s.success,start:a,end:o+2});else{let t=`The prompt has an empty expression at character ${a}. Add an expression between {{ and }}.`;r.push(new DJ({file:e,stage:`expression`,expression:y(),message:t,details:[{path:[`body`],message:t}]}))}i=o+2}return{expressions:n,problems:r}},t0=(e,t)=>new DJ({file:e,stage:`expression`,expression:t[0].expression,message:t.map(({message:e})=>e).join(`
309
+ `),details:t.flatMap(e=>e.details??[{path:[`body`],message:e.message}])}),n0=(e,t,n)=>{let r=bX(t.name),i=nX(t.trigger.on);return T(function*(){let{expressions:a,problems:o}=e0(r,t.body);if(zi(o))return yield*t0(r,o);let s=yield*rh(a,t=>e.evaluateScalar(t.source,i,n).pipe(Ph(e=>X1(r,e,[`body`])),Th(e=>({expression:t,value:e})))),c=``,l=0;for(let{expression:e,value:n}of s)c+=t.body.slice(l,e.start),c+=String(n),l=e.end;return c+t.body.slice(l)})},r0=O(`ConfigParser.parseUsineYaml`)((e,t)=>T(function*(){let n=yield*Y1(e,t);return yield*Zw(_Y)(n,{onExcessProperty:`error`,errors:`all`}).pipe(Ph(t=>q1(e,t)))})),i0=O(`ConfigParser.parseAgentFile`)((e,t)=>T(function*(){let n=yield*$1(e),r=yield*VX(e,t),i=yield*Y1(e,r.yaml),a=yield*Zw(W1)(i,{onExcessProperty:`error`,errors:`all`}).pipe(Ph(t=>q1(e,t))),o=yield*Zw(CA)(r.body).pipe(Ph(t=>q1(e,t)));return new xX({name:n,harness:a.harness,model:a.model,effort:a.effort,parentModel:a.parentModel,parentEffort:a.parentEffort,persona:o})})),a0=(e,t)=>T(function*(){let n=yield*Q1(e),r=yield*VX(e,t),i=yield*Y1(e,r.yaml),a=yield*Zw(H1)(i,{onExcessProperty:`error`,errors:`all`}).pipe(Ph(t=>q1(e,t))),o=yield*Zw(hX)(r.body).pipe(Ph(t=>{let n=q1(e,t);return new DJ({...n,message:n.message,details:[{path:[`body`],message:n.message}]})}));return new vX({name:n,...a,body:o})}),o0=(e,t,n,r,i,a)=>T(function*(){let o=[],s=x(i)?{expressions:[],problems:[]}:e0(t,i.value);if(o.push(...s.problems),x(n))return o;let c=nX(n.value);if(S(r)){let n=yield*e.checkBoolean(r.value,c).pipe(Sh);vi(n)&&o.push(X1(t,n.failure,[`trigger`,`if`]))}if(S(a)&&ee(a.value)){let n=yield*e.checkInteger(a.value,c).pipe(Sh);vi(n)&&o.push(X1(t,n.failure,[`priority`]))}for(let{source:n}of s.expressions){let r=yield*e.checkScalar(n,c).pipe(Sh);vi(r)&&o.push(X1(t,r.failure,[`body`]))}return o}),s0=KE(vX),c0=M({frontmatter:H1,name:vX.fields.name,body:hX}),l0=e=>O(`ConfigParser.checkLoopDraft`)(function*(t,n,r){yield*D({file:t});let i=`text`in n,{value:a,parsed:o}=yield*i?T(function*(){let e=yield*VX(t,n.text),r=yield*Y1(t,e.yaml),i=yield*Zw(YE)(r).pipe(Ph(e=>q1(t,e))),a=tT(c0)({frontmatter:i,name:yield*Q1(t),body:e.body},{errors:`all`,onExcessProperty:`error`}).pipe(xi(({frontmatter:e,...t})=>new vX({...e,...t})),bi(e=>{let n=q1(t,e);return new DJ({...n,message:n.message,details:(n.details??[]).map(e=>({...e,path:e.path[0]===`frontmatter`?e.path.slice(1):e.path}))})}));return{value:{...i,body:e.body},parsed:a}}):w({value:n.value,parsed:tT(s0)(n.value,{errors:`all`,onExcessProperty:`error`}).pipe(bi(e=>q1(t,e)))}),s=vi(o)?[o.failure]:[];if(!i){let e=$w(M({name:vX.fields.name}))(a);if(S(e)&&e.value.name!==(yield*Q1(t))){let e=`Entity identifier does not match its name`;s.push(new DJ({file:t,stage:`schema`,expression:y(),message:e,details:[{path:[`name`],message:e}]}))}}let c=$w(M({trigger:M({on:fX})}))(a),l=$w(M({trigger:M({if:i?z1:vJ})}))(a),u=$w(M({body:hX}))(a),d=$w(M({priority:i?V1.fields.priority:KE(vX.fields.priority)}))(a);s.push(...yield*o0(e,t,Sr(c,({trigger:e})=>e.on),Sr(l,({trigger:e})=>e.if),Sr(u,({body:e})=>e),Cr(d,({priority:e})=>e)));let f=$w(M({agent:SA}))(a),p=$w(M({selector:i?V1.fields.selector:KE(vX.fields.selector)}))(a),m=Cr(r,e=>OX(t,{agent:br(Sr(f,({agent:e})=>e)),selector:Cr(p,({selector:e})=>e)},e));return S(m)&&s.push(m.value),yield*A(`Checked independent loop fields`,{file:t,problems:s.length}),{loop:yi(o)?b(o.success):y(),problems:s}}),u0=e=>O(`ConfigParser.parseLoopFile`)((t,n)=>T(function*(){let r=yield*a0(t,n),i=yield*o0(e,t,b(r.trigger.on),b(r.trigger.if),b(r.body),r.priority);return zi(i)?yield*t0(t,i):r})),d0=$w(MA),f0=e=>O(`ConfigParser.configWarnings`)(function*(t,n){let r=new Set(t.labels.map(({name:e})=>NA(e))),i=[];for(let e of RX(t))for(let t of e.lanes)for(let n of t.sources)`label`in n&&!r.has(NA(n.label))&&i.push(new CX({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=d0(e);S(n)&&!r.has(NA(n.value))&&i.push(new wX({loop:t.name,label:n.value}))}}return i}),p0=class e extends kr()(`@usine/config/ConfigParser`){static layer=Df(e,T(function*(){return m0(yield*CJ)}))},m0=e=>({configWarnings:f0(e),checkLoopDraft:l0(e),parseUsineYaml:r0,parseAgentFile:i0,parseLoopFile:u0(e),renderPrompt:O(`ConfigParser.renderPrompt`)((t,n)=>n0(e,t,n))}),h0=R.pipe(I(`CursorKey`)),g0=Zw(N(M({value:JE}))),_0=e=>t=>Ph(t,t=>new Ez({operation:e,cause:t})),v0=class e extends kr()(`@usine/engine/CursorStore`){static layer=Df(e,T(function*(){let e=yield*jz;return{read:O(`CursorStore.read`)(function*(t,n){let r=_r((yield*T(function*(){return yield*g0(yield*e.select({value:_z.valueJson}).from(_z).where(Y(_z.cursorKey,t)).limit(1).execute())}).pipe(_0(`read runtime cursor`)))[0]);return x(r)?y():yield*Zw(n)(r.value.value,{onExcessProperty:`error`}).pipe(Th(b),kh(e=>Cg(`Stored cursor no longer decodes; treating it as absent`,{key:t,detail:e.message}).pipe(Eh(y()))))}),write:O(`CursorStore.write`)(function*(t,n,r){let i=yield*iT(n)(r).pipe(_0(`encode runtime cursor`));yield*e.insert(_z).values({cursorKey:t,valueJson:i}).onConflictDoUpdate({target:_z.cursorKey,set:{valueJson:i}}).execute().pipe(Oh,_0(`write runtime cursor`))})}}))},y0=e=>e.pipe(Ph(e=>e instanceof _R?e:new Ez({operation:`update cycle budget`,cause:e}))),b0=class e extends kr()(`@usine/engine/CycleBudgets`){static layer=Df(e,T(function*(){let e=yield*jz,t=cq(e);return{generation:O(`CycleBudgets.generation`)(function*(e){return yield*D({itemKey:e}),pr(yield*t.get(e).pipe(Ph(e=>new Ez({operation:`read cycle generation`,cause:e}))),{onNone:()=>wI.make(0),onSome:e=>e.generation})}),asks:O(`CycleBudgets.asks`)(()=>t.asks().pipe(Ph(e=>new Ez({operation:`read cycle asks`,cause:e})))),reset:O(`CycleBudgets.reset`)(function*(t,n){yield*D({askId:t,eventId:n.id}),yield*e.transaction(e=>T(function*(){if((yield*e.select().from(uz).where(Y(uz.askId,t)).execute())[0]?.eventId===n.id){yield*k(`Cycle budget reset answer already recorded`,{askId:t,eventId:n.id});return}let r=(yield*cq(e).asks()).find(({id:e})=>e===t);if(r===void 0)return yield*new _R({askId:t});let i=yield*cq(e).get(r.itemKey);if(x(i))return yield*hh(Error(`Open cycle ask has no budget`));let a=i.value.generation+1;yield*e.insert(oz).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:AK(n.payload),receivedAt:jK(n.receivedAt)}).execute(),yield*e.insert(uz).values({askId:t,eventId:n.id,itemKey:r.itemKey}).execute(),yield*e.update(cz).set({generation:a,askJson:null,resetPending:!0}).where(Y(cz.itemKey,r.itemKey)).execute(),yield*e.update(lz).set({generation:a}).where(tM(Y(lz.itemKey,r.itemKey),cM(lz.runId,e.select({runId:Q.runId}).from(Q).where(cM(J`json_extract(${Q.stateJson}, '$._tag')`,[...DN]))))).execute(),yield*k(`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(y0)}),close:O(`CycleBudgets.close`)(function*(t,n){yield*D({askId:t,reason:n});let r=jK(yield*l_);return yield*e.transaction(e=>T(function*(){let i=(yield*cq(e).asks()).find(({id:e})=>e===t);if(i===void 0)return yield*k(`Cycle-budget Ask is no longer open; nothing to close`,{askId:t,reason:n}),!1;let a=oT(kI)(i);return yield*e.insert(dz).values({askId:t,itemKey:i.itemKey,reason:n,askJson:a,closedAt:r}).onConflictDoUpdate({target:dz.askId,set:{reason:n,askJson:a,closedAt:r}}).execute(),yield*e.update(cz).set({askJson:null}).where(Y(cz.itemKey,i.itemKey)).execute(),yield*k(`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(Ph(e=>new Ez({operation:`close cycle ask`,cause:e})))}),pendingResets:O(`CycleBudgets.pendingResets`)(()=>t.pendingResets().pipe(Th(e=>e.map(e=>new gR(e))),Ph(e=>new Ez({operation:`read pending cycle resets`,cause:e})))),acknowledgeReset:O(`CycleBudgets.acknowledgeReset`)(function*(t){yield*D({itemKey:t.itemKey,generation:t.generation}),yield*e.update(cz).set({resetPending:!1}).where(tM(Y(cz.itemKey,t.itemKey),Y(cz.generation,t.generation))).execute().pipe(Ph(e=>new Ez({operation:`acknowledge cycle reset`,cause:e}))),yield*k(`Cycle reset trigger refresh recorded`,{itemKey:t.itemKey,generation:t.generation})})}}))},x0=new class extends B(`@usine/engine/RetryRequest`)({requestedBy:z(ZM),amendment:z(IF)}){}({requestedBy:y(),amendment:y()});B(`@usine/engine/RunAgainRequest`)({step:GN,approval:kA,cycleLimit:z(CI),permissions:jA,context:IF,requestedBy:z(ZM)});var S0=P([QR,iz]),C0=(e,t,n)=>{let r=rN.make(JSON.stringify([`operator-run-again`,n.reopening,n.trigger]));return new JR({event:new iN({id:nN.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})},w0=class extends B(`@usine/engine/StepExecution`)({attempt:HF,event:iN,run:RN,step:KN,repository:H,revision:cA,task:PF,agent:wA,parentModel:z(vA),permissions:jA,resume:z(xF),reattach:yT.pipe(IT(w(!1)))}){},T0=class extends kr()(`@usine/engine/StepExecutor`){},E0=e=>({attemptWindows:O(`RunStoreQueries.attemptWindows`)(function*(t){yield*D({attemptId:t});let[n]=yield*e.select(yq).from($).where(Y($.attemptId,t)).execute().pipe(E(TK));if(n===void 0)return yield*hh(Error(`No attempt ${t} recorded`));let r=WF(eq(n));if(x(r))return yield*A(`The Attempt ended before end times were recorded, so it has no window and none overlaps it`,{attemptId:t}),new qF({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 qF({own:r,overlapping:(yield*e.select(yq).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(tM(cM(Z.itemKey,i),Y($.agent,n.agent),$j($.attemptId,t))).orderBy($.startedAt).execute().pipe(E(TK))).flatMap(e=>wr(WF(eq(e)))).filter(e=>Bee(r.value,e))})})}),D0=e=>_r(e.attempts.at(-1)).pipe(Tr(e=>x(e.outcome))),O0=e=>Cr(e.salvage,e=>e._tag===`Retained`?e.pushFailure:y()),k0=(e,t,n)=>{let r=new gF({failure:n});return Vee({failure:n,number:t.number,maxAutoAttempts:NF})?{_tag:`RetryAttempt`,attempt:t,outcome:r}:{_tag:`RunFailed`,attempt:t,outcome:r,state:MN(e)}},A0=(e,t,n)=>{if(e.run.state._tag!==`Running`)return{_tag:`Unchanged`,reason:`RunNotRunning`};let r=D0(e);if(x(r))return{_tag:`Unchanged`,reason:`NoOpenAttempt`};if(r.value.id!==t)return{_tag:`Unchanged`,reason:`AttemptReplaced`};let i=pr(O0(r.value),{onNone:()=>n,onSome:e=>mi(e)});return vi(i)?k0(e.run.state,r.value,i.failure):{_tag:`RunSucceeded`,attempt:r.value,outcome:new hF,state:jN(e.run.state),result:i.success}},j0=e=>Vk(e,{Pushed:e=>b(e),PartlyPushed:({ref:e,commit:t})=>b(new xF({ref:e,commit:t})),Retained:()=>y(),Rejected:()=>y()}),M0=e=>Wi(e,e=>Cr(e.salvage,j0)),N0=(e,t,n,r)=>{let i=e.run.state;if(!SN(i)&&i._tag!==`Running`)return{_tag:`RunClosed`,state:i};let a=y(),o=D0(e);if(i._tag===`Running`&&S(o)){if(Er(n,o.value.id))return{_tag:`ReattachAttempt`,state:i,attempt:o.value,resume:M0(e.attempts)};let r=k0(i,o.value,mr(O0(o.value),()=>t));if(r._tag===`RunFailed`)return r;a=b(r)}let s=S(a)?new OF:mr(r,()=>e.attempts.length===0?new CF:S(YF(i,e.attempts))?new DF:new EF);return{_tag:`StartAttempt`,state:i._tag===`Running`?i:AN(i),number:MF.make((e.attempts.at(-1)?.number??0)+1),start:s,interrupted:a,resume:M0(e.attempts)}},P0=(e,t=y())=>e.run.state._tag===`Canceled`?{_tag:`AlreadyClosed`}:bN(e.run.state)?{_tag:`Canceled`,state:PN(e.run.state,t),attempt:e.run.state._tag===`Running`?Sr(D0(e),e=>({id:e.id,worker:e.worker,outcome:new _F})):y()}:{_tag:`CancelRejected`},F0=e=>{let t=e.run.state;return t._tag===`Failed`?{_tag:`Resume`,state:NN(t)}:t._tag===`Running`&&x(D0(e))?{_tag:`ResumePending`}:{_tag:`RetryRejected`}},I0=(e,t)=>pr(e,{onNone:()=>!1,onSome:e=>!Er(e,t)}),L0=(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},R0=(e,t)=>{if(e._tag!==`RunFailed`||yi(t))return y();switch(t.failure._tag){case`QuestionFailure`:return b(`question`);case`BlockedFailure`:return b(`blocker`);default:return y()}},z0=(e,t)=>pr(e.suppressedEventId,{onNone:()=>({_tag:`SuppressFrom`}),onSome:e=>e===t?{_tag:`Suppress`}:{_tag:`Lift`}}),B0=(e,t)=>{if(x(e))return{_tag:`OpenRun`};let n=e.value;return n.state._tag===`Running`?{_tag:`QueueEvent`}:xN(n.state)?{_tag:`SupersedeRun`,runId:n.id,state:FN(n.state,t)}:{_tag:`OpenRun`}},V0=z(LN).pipe(IT(w(y()))),H0=class extends B(`@usine/engine/internal/Claim`)({result:az,openedRun:V0,supersededRun:V0}){},U0=class extends V(`@usine/engine/internal/AttemptStarted`)(`AttemptStarted`,{execution:w0}){},W0=class extends V(`@usine/engine/internal/AttemptRecoveryFailed`)(`AttemptRecoveryFailed`,{}){},G0=class extends V(`@usine/engine/internal/RunClosed`)(`RunClosed`,{}){},K0=T(function*(){let e=yield*jz,t=yield*sk,n=wq(e),r=O(`RunStore.admitRun`)(function*(e,t,n){let r=yield*e.cycles.admit(t);return S(r)?new iz({eventId:t.event.id,ask:r.value}):(yield*e.createRun(t,t.event.id,n),yield*e.cycles.reserve(t,n),new QR({eventId:t.event.id,runId:n}))}),i=O(`RunStore.openRun`)(function*(e,t,n,i=y()){let a=yield*r(e,t,n);return new H0({result:a,openedRun:a._tag===`Claimed`?b(n):y(),supersededRun:i})}),a=e=>XR(e).pipe(Qh(sk,t)),o=O(`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=O(`RunStore.claimEvent`)(function*(e,t,n){if(!(yield*e.cycles.isCurrentEvent(t)))return new H0({result:new nz({eventId:t.event.id,reason:`superseded`})});let r=yield*e.loopItems.suppression(t.loop,t.itemKey);if(S(r)){let n=z0(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*k(`First Item state after the Agent stopped for the operator; it waits for the operator`,i),new H0({result:new rz({eventId:t.event.id,runId:r.value.runId})});case`Suppress`:return yield*k(`Item unchanged since the Agent stopped for the operator; no Run opens`,i),new H0({result:new rz({eventId:t.event.id,runId:r.value.runId})});case`Lift`:yield*e.loopItems.lift(t.loop,t.itemKey),yield*k(`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=B0(a===void 0?y():b((yield*e.snapshot(a.runId)).run),t.event.id);switch(yield*k(`Event claim decided`,{eventId:t.event.id,decision:o._tag}),o._tag){case`QueueEvent`:return new H0({result:new $R({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=O(`RunStore.recordAndClaim`)(function*(t,n){return yield*D({eventId:t.event.id,runId:n,loop:t.loop,itemKey:t.itemKey}),yield*e.transaction(e=>T(function*(){let r=wq(e),i=yield*r.recordTriggerEvent(t),c=yield*r.loopItems.sighted(i.loop,i.itemKey,i.event.id),l=mr(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=L0(d.value,I0(c,i.event.id));switch(f._tag){case`JoinRun`:return yield*k(`Event joined its existing Run`,{eventId:u,runId:f.run.id,state:f.run.state._tag}),new H0({result:new QR({eventId:u,runId:f.run.id})});case`StayIgnored`:return yield*k(`Event remains ignored`,{eventId:u,reason:f.reason}),new H0({result:new nz({eventId:u,reason:f.reason})});case`ReopenEvent`:{let e=l.reopening+1,n=yield*r.recordTriggerEvent(ZR(t,i.event.dedupKey,e),b({eventId:i.event.id,reopening:e}));return yield*k(`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))}}}))},KK(`submit event`)),l=O(`RunStore.parkForApproval`)(function*(t){return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=wq(e),r=yield*n.snapshot(t);if(r.run.state._tag!==`Pending`)return r.run.state;let i=ON(r.run.state);return yield*n.updateState(t,i),i}))},KK(`park run for approval`)),u=O(`RunStore.applyFinish`)(function*(e,t,n){if(yield*D({runId:t}),n._tag===`Unchanged`){yield*k(`Attempt completion ignored`,{runId:t,reason:n.reason});return}let{attempt:r,outcome:i}=n;yield*D({attemptId:r.id});let a={runId:t,attemptId:r.id,number:r.number,decision:n._tag};yield*k(`Attempt completion decided`,Vk(i,{Failed:({failure:e})=>({...a,failure:e._tag}),Succeeded:()=>a}));let o=yield*l_;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=O(`RunStore.suppressForOperator`)(function*(e,t,n){let r=t.run.id,i=Sr(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*k(`Agent stopped for the operator; its Loop suppresses the Item`,{...a,suppressedEventId:mr(i,()=>`none yet`)}):yield*k(`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 w0({attempt:t,event:e.event,run:new RN({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=O(`RunStore.beginAttempt`)(function*(t,n,r){return yield*D({runId:t,worker:n}),yield*e.transaction(e=>T(function*(){let i=wq(e),a=yield*i.snapshot(t),o=new oF({message:`The orchestrator stopped during the attempt`,cause:Error(`attempt interrupted by orchestrator restart`)}),s=yield*i.nextStart(t),c=N0(a,o,r,s);if(c._tag===`RunClosed`)return yield*k(`Attempt start skipped`,{runId:t,state:c.state._tag}),new G0;if(c._tag===`RunFailed`)return yield*u(i,t,c),new W0;if(c._tag===`ReattachAttempt`){let e=yield*l_,r=new HF({...c.attempt,reattachedAt:b(e)});return yield*i.recordReattach(r.id,e),yield*D({attemptId:r.id}),yield*k(`Attempt reattached after an orchestrator restart`,{runId:t,attemptId:r.id,number:r.number,worker:r.worker}),r.worker!==n&&(yield*wg(`Reattached Attempt keeps its own Worker, not the reserved one`,{runId:t,attemptId:r.id,worker:r.worker,reservedWorker:n})),new U0({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=jF.make(`${t}/${a.step.name}/${c.number}`),d=yield*l_,p=new HF({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*k(`Attempt started`,{runId:t,attemptId:l,number:c.number,worker:n,start:c.start._tag,resumesFrom:Sr(c.resume,({ref:e})=>e)}),new U0({execution:f(a,{attempt:p,state:c.state,resume:c.resume,reattach:!1})})}))},KK(`begin attempt`)),m=O(`RunStore.recordSalvage`)(function*(t,n){yield*D({attemptId:t,salvage:n._tag}),yield*e.transaction(e=>wq(e).recordSalvage(t,n)),yield*k(`Attempt salvage recorded`,Vk(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,pushFailure:r})=>({attemptId:t,path:e,commit:n,pushFailure:Sr(r,({message:e})=>e)}),Rejected:({path:e,commit:n})=>({attemptId:t,path:e,commit:n})}))},KK(`record attempt salvage`)),h=O(`RunStore.recordComments`)(function*(t,n){yield*D({attemptId:t,comments:n.length}),yield*e.transaction(e=>wq(e).recordComments(t,n)),yield*k(`Recorded the comments an Attempt posted before it ended without success`,{attemptId:t,comments:n.map(({kind:e,url:t})=>`${e} ${t.href}`)})},KK(`record attempt comments`)),g=O(`RunStore.recordOutOfMemory`)(function*(t,n){yield*D({attemptId:t,container:n.container,kills:n.kills});let r=yield*e.transaction(e=>wq(e).recordOutOfMemory(t,n));yield*k(`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})},KK(`record attempt out-of-memory kills`)),_=O(`RunStore.attemptWindows`)(function*(t){yield*D({attemptId:t});let n=yield*E0(e).attemptWindows(t);return yield*A(`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:Dr(n.own,({endedAt:e})=>S(e)),overlapping:n.overlapping.map(e=>e.attemptId)}),n},KK(`read attempt windows`)),v=O(`RunStore.discardLeftovers`)(function*(t){yield*D({worker:t});let n=yield*l_;return yield*e.transaction(e=>aq(e).discardLeftovers(t,n))},KK(`discard attempt leftovers`)),ee=O(`RunStore.openAttempts`)(function*(t){return yield*D({worker:t}),yield*aq(e).openAttempts(t)},KK(`count open attempts`)),te=O(`RunStore.finishAttempt`)(function*(t,n){return yield*D({runId:t.runId,attemptId:t.id}),yield*e.transaction(e=>T(function*(){let r=wq(e),i=yield*r.snapshot(t.runId),a=A0(i,t.id,n);yield*u(r,t.runId,a);let o=R0(a,n);return S(o)&&(yield*d(r,i,o.value)),a}))},KK(`finish attempt`)),ne=O(`RunStore.resolveFailure`)(function*(t,n,r){return yield*D({runId:t,attemptId:n}),yield*e.transaction(e=>T(function*(){let i=wq(e),a=yield*i.snapshot(t),o=a.attempts.at(-1);if(!CN(a.run.state).canResolveFailure||o?.id!==n)return yield*k(`Failure resolution rejected; Run or Attempt changed`,{runId:t,attemptId:n,state:a.run.state._tag,latestAttemptId:o?.id}),yield*new wz({runId:t,operation:`resolveFailure`,state:a.run.state._tag});if(Er(a.resolvedFailureAttemptId,n))return yield*k(`Run failure already resolved`,{runId:t,attemptId:n}),!1;let s=new LF({resolvedAt:yield*l_,operator:r});yield*i.resolveFailure(t,n,s);let c=yield*i.loopItems.liftRun(t);return yield*k(`Run failure resolved`,{runId:t,attemptId:n,liftedSuppression:c,resolvedAt:v_(s.resolvedAt),operator:C(r)}),c}))},KK(`resolve run failure`)),re=O(`RunStore.approve`)(function*(t,n,r){return yield*D({runId:t,eventId:n.id,channel:r.channel}),yield*e.transaction(e=>T(function*(){let i=wq(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,kN(a.run.state)),!0):yield*new wz({runId:t,operation:`approve`,state:a.run.state._tag})}))},KK(`approve run`)),ie=O(`RunStore.retry`)(function*(t,n=x0){let{amendment:r,requestedBy:i}=n;return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=wq(e),a=yield*n.snapshot(t),o=F0(a);if(yield*k(`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*k(`Run effective task and Agent amended`,{runId:t,agent:r.value.agent.name})),(yield*n.loopItems.liftRun(t))&&(yield*k(`Operator retry lifts the suppression of the Item`,{runId:t})),yield*n.setNextStart(t,b(S(r)?new TF({operator:i}):new wF({operator:i}))),yield*n.updateState(t,o.state),!0):(yield*k(`Operator retry rejected; another Run is open on the Item`,{runId:t,openRunId:e.runId,loop:a.run.loop,itemKey:a.itemKey}),yield*new Tz({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 wz({runId:t,operation:`retry`,state:a.run.state._tag})}))},KK(`retry run`)),ae=O(`RunStore.runAgain`)(function*(t,n){yield*D({runId:t,agent:n.context.agent.name});let i=yield*l_;return yield*e.transaction(e=>T(function*(){let o=wq(e),s=yield*o.snapshot(t),{loop:c}=s.run,{itemKey:l}=s;if(!CN(s.run.state).canRunAgain)return yield*k(`Run again rejected; only a succeeded or canceled Run runs again`,{runId:t,state:s.run.state._tag}),yield*new wz({runId:t,operation:`runAgain`,state:s.run.state._tag});let u=(yield*o.blockingRun(c,l))[0];if(u!==void 0)return yield*k(`Run again rejected; another Run is open on the Item`,{runId:t,openRunId:u.runId,loop:c,itemKey:l}),yield*new Tz({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=mr(yield*o.reopenedEvent(s.event.id),()=>({eventId:s.event.id,dedupKey:s.event.dedupKey})),f=pr(yield*o.newestReopening(d.eventId),{onNone:()=>1,onSome:e=>e.reopening+1}),p=pr(yield*o.cycles.get(l),{onNone:()=>wI.make(0),onSome:e=>e.generation}),m=C0(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 HW({from:t,requestedBy:n.requestedBy}));let g=yield*r(o,h,yield*a(h));return yield*k(`Run again decided`,Vk(g,{Claimed:({runId:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`OpenRun`,openedRunId:e,requestedBy:mr(n.requestedBy,()=>`none`)}),CycleBlocked:({ask:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`CycleBlocked`,askId:e.id,requestedBy:mr(n.requestedBy,()=>`none`)})})),g}))},KK(`run again`)),oe=O(`RunStore.cancel`)(function*(t){return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=wq(e),r=yield*n.snapshot(t),i=P0(r,yield*QM);if(yield*k(`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 wz({runId:t,operation:`cancel`,state:r.run.state._tag});let a=yield*l_;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:Sr(i.attempt,({id:e,worker:t})=>({id:e,worker:t})),loop:r.run.loop,itemKey:r.itemKey}}))},KK(`cancel run`)),se=O(`RunStore.revoke`)(function*(t,n){return yield*e.transaction(e=>T(function*(){let r=wq(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);xN(t.run.state)&&(yield*r.updateState(e.runId,IN(t.run.state)))}return i.map(e=>e.runId)}))},KK(`revoke run`)),ce=O(`RunStore.revokeQueued`)(function*(e){let{loop:t,itemKey:r,event:i}=e.submission;return yield*D({loop:t,itemKey:r,eventId:i.id}),yield*n.revokeQueued(t,r,e.eventIds)},KK(`revoke queued events`)),le=O(`RunStore.claimQueued`)(function*(t,n){return yield*e.transaction(e=>T(function*(){let r=wq(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*k(`Queued Event already opened its Run`,{eventId:t.event.id,runId:a[0].runId}),y())}))},KK(`claim queued event`)),ue=O(`RunStore.appendTranscript`)(function*(t,n){let r=yield*l_;yield*e.transaction(e=>T(function*(){let i=wq(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*A(`Transcript envelope already recorded; keeping the first copy`,{attemptId:n.attemptId,direction:t,sequence:n.sequence}))}))},KK(`append attempt transcript`)),de=O(`RunStore.transcript`)(function*(e){return yield*n.transcript(e)},KK(`read attempt transcript`));return{approve:re,appendTranscript:ue,beginAttempt:p,cancel:oe,claimQueued:le,finishAttempt:te,nextQueued:e=>n.nextQueued(e).pipe(KK(`find queued event`)),parkForApproval:l,pendingContinuations:n.pendingContinuations().pipe(KK(`list pending continuations`)),runIdsToDrive:n.runIdsToDrive().pipe(KK(`list the runs to drive`)),recordAndClaim:c,salvageCandidates:n.salvageCandidates().pipe(KK(`list salvage candidates`)),salvageCandidate:e=>n.salvageCandidate(e).pipe(KK(`read a salvage candidate`)),recordSalvage:m,recordComments:h,recordOutOfMemory:g,attemptWindows:_,discardLeftovers:v,openAttempts:ee,submission:e=>n.eventRouteByRun(e).pipe(E(t=>t[0]===void 0?fh(new Cz({runId:e})):w(YK(t[0]))),KK(`read run submission`)),resolveFailure:ne,retry:ie,revoke:se,revokeQueued:ce,runAgain:ae,snapshot:e=>n.snapshot(e).pipe(KK(`read run`)),transcript:de}}),q0=class e extends kr()(`@usine/engine/internal/RunStore`){static layer=Df(e,K0)},J0=R.pipe(I(`ItemProjectionSource`)),Y0=R.pipe(I(`ItemContentHash`)),X0=class extends B(`@usine/engine/ItemProjection`)({itemKey:xI,repository:H,source:J0,number:SI,contentHash:Y0,payload:YE,goneAt:AE(kE).pipe(RT(w(null)),IT(w(y())))}){},Z0=M({itemKey:X0.fields.itemKey,repository:H,source:J0,number:SI,contentHash:Y0,payload:YE,goneAt:X0.fields.goneAt}),Q0=Zw(N(Z0)),$0=Zw(N(SI)),e2=oT(YE),t2=oT(Z0.fields.goneAt),n2=e=>t=>Ph(t,t=>new Ez({operation:e,cause:t})),r2={itemKey:vz.itemKey,repository:vz.repository,source:vz.source,number:vz.itemNumber,contentHash:vz.contentHash,payload:vz.payloadJson,goneAt:vz.goneAt},i2=T(function*(){let e=yield*jz;return{get:O(`ItemProjectionReader.get`)(function*(t){yield*D({itemKey:t});let[n]=yield*Q0(yield*e.select(r2).from(vz).where(Y(vz.itemKey,t)).execute(),{onExcessProperty:`error`});return Sr(_r(n),e=>new X0(e))},n2(`read item projection`)),list:O(`ItemProjectionReader.list`)(function*(t,n){return yield*D({repository:t,limit:n.limit}),(yield*Q0(yield*e.select(r2).from(vz).where(Y(vz.repository,t)).orderBy(wM(vz.itemNumber)).limit(n.limit).execute(),{onExcessProperty:`error`})).map(e=>new X0(e))},n2(`list item projections`)),openIssues:O(`ItemProjectionReader.openIssues`)(function*(t){return yield*D({repository:t}),yield*$0((yield*e.select({number:vz.itemNumber}).from(vz).where(tM(Y(vz.repository,t),Y(vz.source,`issue`),uM(vz.goneAt),J`json_extract(${vz.payloadJson}, '$.state') = 'OPEN'`)).orderBy(CM(vz.itemNumber)).execute()).map(({number:e})=>e))},n2(`list open issue projections`))}}),a2=T(function*(){let e=yield*jz;return{upsert:O(`ItemProjectionWriter.upsert`)(function*(t){yield*D({repository:t.repository,item:t.number,itemKey:t.itemKey});let n=t2(t.goneAt);return(yield*e.insert(vz).values({itemKey:t.itemKey,repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:e2(t.payload),goneAt:n}).onConflictDoUpdate({target:vz.itemKey,set:{repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:e2(t.payload),goneAt:n},setWhere:J`${vz.contentHash} != ${t.contentHash} OR ${vz.goneAt} IS NOT ${n}`}).returning({itemKey:vz.itemKey}).execute()).length===0?(yield*A(`Item projection already matched the observed snapshot`,{repository:t.repository,item:t.number,contentHash:t.contentHash}),!1):(yield*A(`Item projection updated from trigger polling`,{repository:t.repository,item:t.number,source:t.source,contentHash:t.contentHash}),!0)},n2(`write item projection`)),markGone:O(`ItemProjectionWriter.markGone`)(function*(t,n){return yield*D({itemKey:t}),(yield*e.update(vz).set({goneAt:t2(b(n))}).where(tM(Y(vz.itemKey,t),uM(vz.goneAt))).returning({itemKey:vz.itemKey}).execute()).length===0?(yield*A(`Item projection already gone or never stored`,{itemKey:t}),!1):(yield*k(`Item projection marked gone from GitHub`,{itemKey:t,goneAt:v_(n)}),!0)},n2(`mark item projection gone`))}}),o2=class e extends kr()(`@usine/engine/ItemProjectionReader`){static layer=Df(e,i2)},s2=class e extends kr()(`@usine/engine/ItemProjectionWriter`){static layer=Df(e,a2)},c2=class extends kr()(`@usine/engine/TriggerCondition`){},l2=class extends B(`@usine/engine/LoopRuntimeState`)({loop:DA,paused:yT}){},u2=e=>t=>t.pipe(Ph(t=>new Ez({operation:e,cause:t}))),d2=T(function*(){let e=yield*jz,t=O(`LoopControl.stateFor`)(function*(t){yield*D({loop:t});let n=(yield*e.select({loop:xz.loopName,paused:xz.paused}).from(xz).where(Y(xz.loopName,t)).limit(1).execute())[0];return n===void 0?new l2({loop:t,paused:!1}):new l2(n)},u2(`read loop runtime state`)),n=O(`LoopControl.states`)(function*(){return(yield*e.select({loop:xz.loopName,paused:xz.paused}).from(xz).orderBy(CM(xz.loopName)).execute()).map(e=>new l2(e))},u2(`list loop runtime states`)),r=O(`LoopControl.write`)(function*(n){yield*D({loop:n.loop});let r=yield*t(n.loop);return r.paused===n.paused?(yield*A(`Loop runtime state was already set`,{loop:n.loop,paused:n.paused}),r):(yield*e.insert(xz).values({loopName:n.loop,paused:n.paused}).onConflictDoUpdate({target:xz.loopName,set:{paused:n.paused}}).execute().pipe(u2(`write loop runtime state`)),yield*k(n.paused?`Loop paused`:`Loop unpaused`,{loop:n.loop,paused:n.paused}),n)});return{isPaused:O(`LoopControl.isPaused`)(function*(e){return(yield*t(e)).paused}),pause:O(`LoopControl.pause`)(e=>r(new l2({loop:e,paused:!0}))),states:n(),unpause:O(`LoopControl.unpause`)(e=>r(new l2({loop:e,paused:!1})))}}),f2=class e extends kr()(`@usine/engine/LoopControl`){static layer=Df(e,d2)},p2=N(R),m2=class extends B(`@usine/engine/BoardMoveRecord`)({repository:H,itemKey:xI,at:OE,fromLane:R,toLane:R,added:p2.check(iE()),removed:p2}){},h2=Zw(N(M({repository:m2.fields.repository,itemKey:m2.fields.itemKey,at:kE,fromLane:m2.fields.fromLane,toLane:m2.fields.toLane,added:m2.fields.added,removed:m2.fields.removed}))),g2=oT(m2.fields.added),_2=oT(m2.fields.removed),v2=e=>t=>Ph(t,t=>new Ez({operation:e,cause:t})),y2=T(function*(){let e=yield*jz;return{record:O(`BoardMoves.record`)(function*(t){yield*D({repository:t.repository,itemKey:t.itemKey}),yield*e.insert(bz).values({repository:t.repository,itemKey:t.itemKey,movedAt:jK(t.at),fromLane:t.fromLane,toLane:t.toLane,addedJson:g2(t.added),removedJson:_2(t.removed)}).execute(),yield*A(`Recorded a Board move before writing its labels`,{repository:t.repository,itemKey:t.itemKey,at:jK(t.at),fromLane:t.fromLane,toLane:t.toLane})},v2(`record board move`)),onItem:O(`BoardMoves.onItem`)(function*(t,n){return yield*D({itemKey:t}),(yield*h2(yield*e.select({repository:bz.repository,itemKey:bz.itemKey,at:bz.movedAt,fromLane:bz.fromLane,toLane:bz.toLane,added:bz.addedJson,removed:bz.removedJson}).from(bz).where(tM(Y(bz.itemKey,t),aM(bz.movedAt,jK(n)))).orderBy(CM(bz.movedAt),CM(bz.moveId)).execute(),{onExcessProperty:`error`})).map(e=>new m2(e))},v2(`read board moves`))}}),b2=class e extends kr()(`@usine/engine/BoardMoves`){static layer=Df(e,y2)},x2=class extends kr()(`@usine/engine/RunEngineShutdown`){},S2=class e extends kr()(`@usine/engine/AttemptAdmission`){static layer=Df(e,T(function*(){let e=yield*Xh(x2),t=S(e)?e.value:yield*Zd(),n=yield*Yk(new Set),r=yield*Zd(),i=O(`AttemptAdmission.enter`)(function*(e){yield*D({runId:e});let r=yield*Qk(n,n=>tf(t)?[!1,n]:[!0,new Set([...n,e])]);return r||(yield*k(`Attempt deferred until restart; the engine is draining`,{runId:e})),r}),a=O(`AttemptAdmission.leave`)(function*(e){yield*D({runId:e});let i=yield*eA(n,t=>new Set([...t].filter(t=>t!==e)));(yield*ef(t))&&(yield*k(`Attempt settled during drain`,{runId:e,remainingRunIds:[...i]}),i.size===0&&(yield*nf(r,void 0)))});return{withAttempt:O(`AttemptAdmission.withAttempt`)(function*(e,t){return yield*D({runId:e}),yield*eg(i(e),e=>e?t:dh,t=>t?a(e):lh)}),drain:O(`AttemptAdmission.drain`)(function*(){yield*nf(t,void 0);let e=yield*Xk(n);yield*k(`Engine drain started; no further Attempts will be admitted`,{activeRunIds:[...e]}),e.size===0&&(yield*nf(r,void 0)),yield*Qd(r),yield*k(`Engine drain completed; all admitted Attempts settled`)})}}))},C2=class extends WE(`@usine/engine/internal/ParentStopUnconfirmedError`)(`ParentStopUnconfirmedError`,{attemptId:jF,worker:qN,cause:dE()}){},w2=(e,t)=>{let n=new Map(e);return n.delete(t),n},T2=O(`CheckoutRecovery.for`)(function*(e,t){let n=yield*Yk(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(Ih(e=>wg(`Attempt salvage reconciliation failed; work retained`,{attemptId:n.attemptId,worker:n.worker,message:String(e)})),zh),i=O(`CheckoutRecovery.keep`)(function*(e){yield*t.occupy(e.worker,e.attemptId).pipe(E(e=>ag(e.release).pipe(Th(t=>({worker:e.worker,release:t,checkoutKept:!0})))),E(t=>$k(n,n=>new Map(n).set(e.attemptId,t))),cg)}),a=O(`CheckoutRecovery.recoverOpen`)(function*(e){let n={attemptId:e.attemptId,worker:e.worker};yield*D(n);let a=yield*t.isLive(e.attemptId).pipe(Sh);if(yi(a)&&!a.success)return yield*r(e);vi(a)?yield*Cg(`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*k(`Leaving the checkout of an open Attempt whose parent task is live for its Run to reattach`,n),yield*i(e),yield*k(`Occupied a slot on the Worker of an open Attempt kept for its Run to reattach`,n)}),o=O(`CheckoutRecovery.recoverClosed`)(function*(e){let n={attemptId:e.attemptId,runId:e.runId,worker:e.worker};yield*D(n);let a=yield*t.interrupt(e.attemptId,`startup`).pipe(Sh);return yi(a)?(yield*r(e),y()):(yield*Cg(`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 Item, until a reconcile confirms the stop`,{...n,errorTag:a.failure._tag,message:a.failure.message}),yield*i(e),b(e))}),s=O(`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*Cg(`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(`,`)})),ea(yield*rh(i,e=>e.open?a(e).pipe(Eh(y())):o(e)))}),c=O(`CheckoutRecovery.reattachSlot`)(function*(e){return Sr(Tr(vr((yield*Xk(n)).get(e)),({checkoutKept:e})=>e),t=>({worker:t.worker,release:Xk(n).pipe(E(n=>n.get(e)===t?k(`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=O(`CheckoutRecovery.acquired`)(function*(e){(yield*Qk(n,t=>t.get(e)?.checkoutKept===!0?[!0,w2(t,e)]:[!1,t]))&&(yield*k(`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=O(`CheckoutRecovery.hold`)(function*(e,t){let r={attemptId:e,worker:t.worker};yield*D(r);let i=yield*ag(t.release);(yield*Qk(n,n=>n.has(e)?[!1,n]:[!0,new Map(n).set(e,{worker:t.worker,release:i,checkoutKept:!1})]))?yield*k(`The Attempt keeps its Run's slot until its parent task is confirmed stopped`,r):(yield*A(`The Attempt already has a slot kept until its parent task is confirmed stopped; releasing its Run's lease`,r),yield*i)},cg),d=O(`CheckoutRecovery.confirmStop`)(function*(e,n,r){let i={attemptId:e,worker:n.worker,checkoutKept:n.checkoutKept,reason:r};yield*D(i);let a=yield*t.interrupt(e,r).pipe(Sh);if(yi(a))return;let o={...i,errorTag:a.failure._tag,message:a.failure.message};return yield*n.checkoutKept?Cg(`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):Cg(`Could not confirm that the parent task of a closed Attempt stopped; its Worker's slot stays taken, and no Attempt starts on its Item, until a reconcile confirms the stop`,o),yield*new C2({attemptId:e,worker:n.worker,cause:a.failure})}),f=O(`CheckoutRecovery.recoverKept`)(function*(n){let i=yield*e.salvageCandidate(n).pipe(Sh);if(vi(i)){yield*wg(`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*Cg(`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*D(o),(yield*t.workers).includes(a.worker)?(yield*k(`Reconciling the checkout startup kept for an Attempt that was not reattached`,o),yield*r(a)):yield*Cg(`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:O(`CheckoutRecovery.reconcile`)(function*(e,t){yield*D({attemptId:e,reason:t});let r=(yield*Xk(n)).get(e);r===void 0?yield*A(`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*$k(n,t=>w2(t,e)).pipe(bh(r.release),cg),yield*k(`Released the slot kept for an Attempt whose parent task is confirmed stopped`,{attemptId:e,worker:r.worker,checkoutKept:r.checkoutKept}))})}}),E2=class extends B(`@usine/engine/UnconfirmedStop`)({attemptId:jF,runId:LN,loop:DA,itemKey:xI,worker:qN,reason:FF}){},D2=class e extends kr()(`@usine/engine/UnconfirmedStops`){static empty=Tf(e)({list:w([])})},O2=e=>jh(e,{EnginePersistenceError:e=>new oF({message:`Runtime store error: could not ${e.operation}`,cause:e}),RunNotFoundError:e=>hh(e),RunOperationRejectedError:e=>hh(e),RunRetryBlockedError:e=>hh(e)}),k2=4,A2=`100 millis`,j2=(e,t)=>n=>n.pipe(Ih(n=>n._tag===`EnginePersistenceError`?Cg(`A Run store operation failed to persist`,{runId:e,operation:t,cause:n.cause}):lh),Rh({schedule:Pm(A2),times:k2,while:e=>e._tag===`EnginePersistenceError`})),M2=e=>Cr(e,e=>e._tag===`Live`?b(e.attempt):y()),N2=class e extends kr()(`@usine/engine/internal/RunDriver`){static layer=Df(e,T(function*(){let e=yield*q0,t=yield*T0,n=yield*S2,r=yield*c2,i=yield*s2,a=yield*sk,o=yield*fk(),s=yield*T2(e,t),c=yield*Yk(new Map),l=yield*Yk(new Map),u=(e,t)=>Qk(l,n=>n.get(e)===t?[!0,w2(n,e)]:[!1,n]).pipe(E(n=>n?t.release:A(`The Run's slot stays with its Attempt until the parent task is confirmed stopped`,{runId:e,worker:t.worker}))),d=O(`RunDriver.launch`)(function*(e){if(yield*D({runId:e}),yield*yk(o,e)){yield*A(`The Run's fiber already runs in this process`,{runId:e});return}yield*A(`Starting the Run's fiber`,{runId:e});let t=yield*Ch(dg);yield*Sk(o,e,te(e).pipe(Lh(t=>Md(t)?lh:wg(`The Run's fiber stopped on an engine failure; the next reconcile or a restart resumes it`,{runId:e,cause:t})),pg(`RunDriver.drive`,{root:!0,links:wr(Sr(t,e=>({span:e,attributes:{}})))}),Mh(e=>Md(e)?ph(e):lh)),{onlyIfMissing:!0})}),f=O(`RunDriver.resume`)(function*(e){yield*D({runId:e});let t=yield*_k(o,e);S(t)&&(yield*A(`Waiting for the Run's previous fiber to end`,{runId:e}),yield*XE(t.value)),yield*d(e)}),p=O(`RunDriver.stop`)(function*(e){yield*D({runId:e}),(yield*yk(o,e))?(yield*bk(o,e),yield*k(`The closed Run's fiber stopped`,{runId:e})):yield*A(`The closed Run has no fiber in this process`,{runId:e})}),m=O(`RunDriver.markItemGone`)(function*(e,t){return yield*D({runId:e,itemKey:t.itemKey}),yield*i.markGone(t.itemKey,yield*l_).pipe(j2(e,`mark the item's projection gone`),kh(n=>Cg(`Could not mark the gone Item's projection; its Board card stays in place`,{completedRunId:e,itemKey:t.itemKey,errorTag:n._tag}).pipe(Eh(!1))))}),h=O(`RunDriver.continueWithNewest`)(function*(t){yield*D({runId:t});let n=yield*e.nextQueued(t).pipe(j2(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(j2(t,`revoke the queued events`));if(s===`no-longer-matches`){yield*k(`Queued Event no longer matches its trigger; revoked`,{...o,revokedEvents:r});return}let a=yield*m(t,i);yield*k(`Queued Event's Item is gone from its source; revoked its queued Events`,{...o,revokedEvents:r,projectionMarkedGone:a});return}let c=yield*XR(i).pipe(Qh(sk,a)),l=yield*e.claimQueued(i,c).pipe(j2(t,`claim the queued event`));x(l)?yield*k(`Queued Event still matches its trigger but could no longer be claimed; no Run opened`,o):(yield*k(`Queued Event still matches its trigger; opening its Run`,{...o,runId:l.value}),yield*d(l.value))}),g=O(`RunDriver.openAttempt`)(function*(n){yield*D({runId:n});let r=yield*e.snapshot(n).pipe(j2(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*D({attemptId:i.id,worker:i.worker});let o=yield*t.isLive(i.id).pipe(Sh);if(vi(o))return yield*Cg(`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*k(`The open Attempt's parent task is live; reattaching it`,a),b({_tag:`Live`,attempt:i});let s=yield*t.outcome(i.id).pipe(Sh);if(vi(s))return yield*Cg(`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*k(`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*k(`The open Attempt's parent task finished before this process recorded it; finishing the Attempt with its stored result`,{...a,outcome:Si(c,{onSuccess:()=>`Succeeded`,onFailure:({_tag:e})=>e})}),b({_tag:`Finished`,attempt:i,result:c})}),_=O(`RunDriver.slot`)(function*(e,n,r,i){yield*D({runId:e});let a=w(r),o=M2(r);if(S(o)){let t=yield*s.reattachSlot(o.value.id);if(S(t))return yield*k(`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,Sr(o,({worker:e})=>e))),open:S(o)?g(e):a}}),v=O(`RunDriver.attempt`)(function*(n,r,i,a){yield*D({runId:n,worker:i});let o=yield*a;if(x(M2(o))&&S(yield*ae(r)))return yield*k(`Run waits for an unconfirmed stop after reserving a worker slot`,{runId:n,worker:i,itemKey:r.itemKey}),`WaitingForStop`;if(S(o)&&o.value._tag===`Finished`)return(yield*e.finishAttempt(o.value.attempt,o.value.result).pipe(j2(n,`finish the attempt`)))._tag;let c=yield*e.beginAttempt(n,i,Sr(M2(o),({id:e})=>e)).pipe(j2(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(O2),salvage:t=>e.recordSalvage(c.execution.attempt.id,t).pipe(O2),comments:t=>e.recordComments(c.execution.attempt.id,t).pipe(O2),outOfMemory:t=>e.recordOutOfMemory(c.execution.attempt.id,t).pipe(O2),windows:e.attemptWindows(c.execution.attempt.id).pipe(j2(n,`read the attempt windows`),O2),transcript:e.transcript(new VG({attemptId:c.execution.attempt.id})).pipe(j2(n,`read the attempt transcript`),O2,Th(e=>e.flatMap(({envelope:e})=>e.version===7?[e]:[]))),checkoutAcquired:s.acquired(c.execution.attempt.id)}).pipe(Nh(e=>wg(`Step executor defect; operator intervention required`,{runId:n,attemptId:c.execution.attempt.id,defect:e instanceof Error?e.message:String(e)}).pipe(bh(new sF({message:`The step executor crashed with an unexpected error`,cause:e})))),Sh);return c.execution.reattach&&vi(l)&&(yield*oe(new E2({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,worker:i,reason:`failed`}))),vi(l)&&(yield*ie({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,reason:`failed`,worker:i})),(yield*e.finishAttempt(c.execution.attempt,l).pipe(j2(n,`finish the attempt`)))._tag}),ee=O(`RunDriver.awaitProviderRetry`)(function*(t){yield*D({runId:t});let n=yield*e.snapshot(t).pipe(j2(t,`read the retry delay`)),r=YF(n.run.state,n.attempts);if(x(r))return;let{retryAt:i,nextAttempt:a,message:o}=r.value,s=h_(i)-h_(yield*l_);yield*k(`Run waits before retrying provider capacity`,{runId:t,nextAttempt:a,message:o,retryAt:v_(i),delayMillis:Math.max(0,s)}),s>0&&(yield*Bh(s))}),te=Sg(function*(t){let r=yield*e.submission(t).pipe(j2(t,`read the run's submission`));if(yield*D({runId:t,loop:r.loop,itemKey:r.itemKey}),r.approval===`required`&&(yield*e.parkForApproval(t).pipe(j2(t,`park the run for approval`)))._tag===`Waiting`){yield*k(`Run waits for its approval`,{runId:t});return}let i;do{yield*ee(t);let e=yield*g(t);if(S(e)&&e.value._tag!==`Live`&&(yield*oe(new E2({attemptId:e.value.attempt.id,runId:t,loop:r.loop,itemKey:r.itemKey,worker:e.value.attempt.worker,reason:`startup`}))),x(M2(e))){let e=yield*ae(r);if(S(e)){yield*k(`The Run starts no Attempt while the parent task of an earlier Attempt on its 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*lg(i=>_(t,r,e,i).pipe(xh(({lease:e})=>$k(l,n=>new Map(n).set(t,e))),E(({lease:e,open:a})=>i(n.withAttempt(t,v(t,r,e.worker,a))).pipe(tg(u(t,e))))))}while(i===`RetryAttempt`);i!==`WaitingForStop`&&(i===`Unchanged`?yield*k(`Run closed by another operation; its fiber ends`,{runId:t}):yield*h(t))}),ne=O(`RunDriver.holdSlot`)(function*(e){let{runId:t,attemptId:n}=e;yield*D({runId:t,attemptId:n}),yield*re(new E2(e));let r=yield*Qk(l,e=>[vr(e.get(t)),w2(e,t)]);x(r)?yield*A(`The Run's fiber holds no slot in this process; no slot moves to its Attempt`,{runId:t,attemptId:n}):yield*s.hold(n,r.value)},cg),re=e=>$k(c,t=>t.has(e.attemptId)?t:new Map(t).set(e.attemptId,e)),ie=O(`RunDriver.confirmStopAfterFailure`)(function*(e){let{attemptId:n,runId:r,worker:i}=e,a={runId:r,attemptId:n,worker:i,reason:e.reason};yield*D(a),yield*re(new E2(e));let o=yield*t.interrupt(n,e.reason).pipe(Sh);yi(o)?(yield*$k(c,e=>w2(e,n)),yield*A(`The parent task of the failed Attempt is confirmed stopped; the Run's slot is freed`,a)):(yield*Cg(`Could not confirm that the parent task of the failed Attempt stopped; the Attempt keeps its Run's slot, no Attempt starts on its Item, and each reconcile tries the stop again`,{...a,errorTag:o.failure._tag,message:o.failure.message}),yield*ne(e))}),ae=e=>Xk(c).pipe(Th(t=>vr([...t.values()].find(({itemKey:t})=>t===e.itemKey)))),oe=O(`RunDriver.reconcileKept`)(function*(e){yield*D({...e}),yield*re(e),yield*s.reconcile(e.attemptId,e.reason),yield*$k(c,t=>w2(t,e.attemptId)),yield*k(`Parent stop confirmed; runs on the item can start attempts again`,{...e})}),se=O(`RunDriver.releaseKept`)(function*(e){yield*D({...e}),yield*oe(e).pipe(Ah(`ParentStopUnconfirmedError`,t=>Cg(`Parent stop unconfirmed; the worker slot and checkout stay reserved until reconciliation succeeds`,{...e,errorTag:t._tag})))}),ce=O(`RunDriver.recoverWorkspaces`)(function*(){yield*rh(yield*s.atStartup(),({attemptId:e,runId:t,loop:n,itemKey:r,worker:i})=>re(new E2({attemptId:e,runId:t,loop:n,itemKey:r,worker:i,reason:`startup`})),{discard:!0})});return{launch:d,resume:f,stop:p,continueWithNewest:h,reconcile:O(`RunDriver.reconcile`)(function*(){let n=[...(yield*Xk(c)).values()];yield*rh(n,e=>yk(o,e.runId).pipe(E(t=>t?lh:se(e))),{discard:!0});let r=yield*e.pendingContinuations;yield*rh(r,e=>h(e).pipe(Ih(t=>wg(`Could not continue the queued Events behind a closed Run`,{runId:e,errorTag:t._tag})),zh),{discard:!0});let i=yield*e.runIdsToDrive,a=yield*Uh(i,e=>Th(yk(o,e),e=>!e));yield*rh(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*A(`Every Run to drive already has its fiber`,s):yield*k(`Runs recovered from the run tables`,s)}),recoverWorkspaces:ce,holdSlot:ne,releaseKept:se,unconfirmedStops:Xk(c).pipe(Th(e=>[...e.values()]))}}))},P2=li(`@usine/engine/ReconcileInterval`,{defaultValue:()=>`3 minutes`});T(function*(){let e=yield*q0,t=yield*N2,n=yield*S2,r=yield*T0,i=yield*sk,a=O(`RunEngine.submit`)(function*(n){let r=yield*XR(n).pipe(Qh(sk,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},cg),o=O(`RunEngine.approve`)(function*(n,r,i){(yield*e.approve(n,r,i))?(yield*k(`Run approved`,{runId:n,eventId:r.id,channel:i.channel,approver:mr(i.approver,()=>`none`)}),yield*t.resume(n)):yield*A(`Approval was already recorded; the Run is unchanged`,{runId:n,eventId:r.id})},cg),s=O(`RunEngine.retry`)(function*(n,r=x0){(yield*e.retry(n,r))?yield*t.resume(n):yield*A(`Retry changed nothing; the Run already waits for its next Attempt`,{runId:n})},cg),c=O(`RunEngine.runAgain`)(function*(n,r){let i=yield*e.runAgain(n,r);return i._tag===`Claimed`&&(yield*t.launch(i.runId)),i},cg),l=O(`RunEngine.cancel`)(function*(n){let i=yield*e.cancel(n);if(i._tag===`AlreadyClosed`){yield*A(`Cancel was a no-op; the run was already closed`,{runId:n});return}yield*k(`Run canceled`,{runId:n,openAttempt:pr(i.openAttempt,{onNone:()=>`none`,onSome:({id:e})=>e})}),S(i.openAttempt)&&(yield*t.holdSlot({attemptId:i.openAttempt.value.id,worker:i.openAttempt.value.worker,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`}));let a=S(i.openAttempt)?yield*r.interrupt(i.openAttempt.value.id,`cancel`).pipe(Sh):pi(void 0);if(yield*t.stop(n),S(i.openAttempt)&&(yield*t.releaseKept({attemptId:i.openAttempt.value.id,worker:i.openAttempt.value.worker,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`})),yield*t.continueWithNewest(n),S(i.openAttempt)&&vi(a))return yield*new Dz({attemptId:i.openAttempt.value.id,cause:a.failure})},cg),u=O(`RunEngine.intervene`)(function*(t,n,i){yield*D({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*k(`Operator input rejected for an inactive Attempt`,{runId:t,attemptId:n}),yield*new kz({runId:t,attemptId:n,message:`This attempt is no longer running`});yield*r.intervene(n,i).pipe(Ph(e=>new kz({runId:t,attemptId:n,message:Vk(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,GitHubPushFailure:({message:e})=>e,InfraFailure:({message:e})=>e,ProviderCapacityFailure:({message:e})=>e,DefectFailure:({message:e})=>e,AgentFailure:({message:e})=>e})})),Ih(e=>Cg(`Operator input delivery failed`,{runId:t,attemptId:n,message:e.message})))}),d=O(`RunEngine.resolveFailure`)(function*(n,r,i){yield*D({runId:n,attemptId:r}),(yield*e.resolveFailure(n,r,i))&&(yield*k(`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))},cg),f=O(`RunEngine.revoke`)(function*(n,r){let i=yield*e.revoke(n,r);return yield*rh(i,t.stop,{concurrency:`unbounded`,discard:!0}),i},cg),p=O(`RunEngine.inspect`)(function*(t){return yield*e.snapshot(t)}),m=O(`RunEngine.transcript`)(function*(t){return yield*e.transcript(t)}),h=O(`RunEngine.discardLeftovers`)(function*(t){if(yield*D({worker:t}),(yield*r.workers).includes(t)){let n=yield*e.openAttempts(t);return yield*k(`Leftovers kept; the Worker is configured or still runs Attempts, so its Attempts stay tracked`,{worker:t,running:n}),yield*new Az({worker:t,running:n})}let n=yield*e.discardLeftovers(t);return yield*k(`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*Bh(yield*P2).pipe(bh(t.reconcile()),Ih(e=>wg(`Periodic Run reconcile failed; the next one tries again`,{errorTag:e._tag})),zh,ug,gg),{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 F2=class extends kr()(`@usine/engine/RunEngine`){},I2=(e,t)=>e.changes.pipe(XO(e=>e!==t),ik,E(pr({onNone:()=>dh,onSome:e=>w(e)}))),L2=cA.make(`HEAD`),R2=class extends WE(`@usine/orchestrator/LoopAgentResolutionError`)(`LoopAgentResolutionError`,{loop:DA,agent:SA,message:R}){},z2=O(`TriggerRouting.resolveLoop`)(function*(e,t){yield*D({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 R2({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:TA(r,e.config.settings.parentModel)}}),B2=O(`TriggerRouting.resolveLoops`)(function*(e){let t=[];for(let n of e.loops){let r=yield*Sh(z2(e,n));yi(r)?t.push(r.success):yield*wg(`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}),V2=e=>e.trigger.on===`schedule`?y():b(e.maxCycles),H2=e=>new JR({event:new iN({id:nN.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:V2(e.loop),repository:e.repository.name,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel}),U2=e=>Vk(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`})}),W2=e=>pr(e.expression,{onNone:()=>({configFile:e.file,configStage:e.stage}),onSome:t=>({configFile:e.file,configStage:e.stage,expression:t})}),G2=class extends B(`@usine/orchestrator/RepositoryPollFailure`)({repository:H,errorTag:R,message:j}){},K2=class extends B(`@usine/orchestrator/RepositoryPoll`)({repository:H,completedAt:OE}){},q2=class extends B(`@usine/orchestrator/PollCycle`)({repositoryPolls:N(K2).pipe(IT(w([]))),repositories:L.check($T(0)),changedItems:L.check($T(0)),submissions:N(az),revokedRuns:L.check($T(0)),failures:N(G2),preflightFindings:N(OW),nextPollAt:z(OE)}){},J2=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...W2(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},Y2=e=>{let t=e.flatMap(e=>pr(e,{onNone:()=>[],onSome:e=>[h_(e)]}));return t.length===0?y():c_(Math.max(...t))},X2=class extends B(`@usine/orchestrator/LoopEvaluationFailure`)({loop:DA,stage:jT([`if`,`prompt`]),expression:AE(vJ),errorTag:R,message:j}){},Z2=class extends B(`@usine/orchestrator/FailingItem`)({stream:jT([`issue`,`pr`]),number:SI,updatedAt:kE,contentHash:Y0,failures:kT(X2)}){},Q2=e=>e.stream===`issue`?new cU({number:e.number,updatedAt:e.updatedAt}):new lU({number:e.number,updatedAt:e.updatedAt}),$2=(e,t,n)=>{let[r,...i]=n;return r===void 0?y():b(new Z2({stream:e._tag===`ChangedIssue`?`issue`:`pr`,number:SI.make(e.number),updatedAt:e.updatedAt,contentHash:t,failures:[r,...i]}))},e4=e=>e.stage===`if`?`if:`:pr(e.expression,{onNone:()=>`prompt`,onSome:e=>`prompt {{ ${e} }}`}),t4=(e,t)=>t.failures.map(n=>new G2({repository:e,errorTag:n.errorTag,message:`Loop "${n.loop}": ${e4(n)} failed on ${t.stream===`issue`?`issue`:`pull request`} #${t.number}: ${n.message}`})),n4=e=>pr(e,{onNone:()=>[],onSome:({failures:e})=>e}),r4=(e,t)=>e.loop===t.loop&&e.stage===t.stage,i4=O(`PollingTriggers.logItemEvaluation`)(function*(e,t,n,r){yield*D({repository:e,item:t});for(let i of wr(r)){let r=pr(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:C(n.expression),errorTag:n.errorTag,message:n.message};r.some(e=>r4(e,n))?yield*A(`Loop evaluation still fails on unchanged Item content`,a):yield*wg(`Loop evaluation failed on an Item; its other Loops and the repository's other Items continue`,a)}}let i=n4(r);for(let r of n4(n))i.some(e=>r4(e,r))||(yield*k(`Loop evaluation no longer fails on the Item`,{repository:e,item:t,loop:r.loop,stage:r.stage}))}),a4=Zw(N(MA)),o4=M({labels:LU.fields.labels}),s4=M({labels:VU.fields.labels}),c4=(e,t)=>Zw(e===`issue`?o4:s4)(t).pipe(E(({labels:e})=>a4(e.nodes.map(({name:e})=>e)))),l4=(e,t)=>new aJ({repository:e.repository,itemKey:e.itemKey,message:t}),u4=e=>T(function*(){let t=S(e.goneAt);if(e.source===`issue`){let n=yield*Zw(LU)(e.payload).pipe(Ph(t=>l4(e,t.message)));return{itemKey:e.itemKey,kind:`issue`,number:SI.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*a4(n.labels.nodes.map(({name:e})=>e)).pipe(Ph(t=>l4(e,t.message))),conflicting:!1}}if(e.source===`pr`){let n=yield*Zw(VU)(e.payload).pipe(Ph(t=>l4(e,t.message))),r=n.merged?`pr-merged`:n.state===`OPEN`&&!t?`pr-open`:`pr-closed`;return{itemKey:e.itemKey,kind:`pr`,number:SI.make(e.number),title:n.title,url:n.url,state:r,linkedPullRequests:[],labels:yield*a4(n.labels.nodes.map(({name:e})=>e)).pipe(Ph(t=>l4(e,t.message))),conflicting:r===`pr-open`&&n.mergeable===`CONFLICTING`}}return yield*l4(e,`Unsupported item projection source: ${e.source}`)}),d4=O(`settledItemState`)(function*(e){yield*D({itemKey:e});let t=yield*(yield*o2).get(e);if(x(t))return y();let n=yield*Sh(u4(t.value));if(vi(n))return yield*A(`Stored Item payload doesn't decode; treating the Item as open`,{itemKey:e,message:n.failure.message}),y();let{state:r}=n.success;return RW(r)?b(r):y()}),f4=(e,t)=>e.canApprove||e.canResolveFailure&&!t,p4=O(`PollingTriggers.closeAsksOfClosedItems`)(function*(e){yield*D({repository:e});let t=yield*b0,n=(yield*t.asks()).filter(t=>fA(t.repository)===fA(e));for(let e of n){let n={askId:e.id,itemKey:e.itemKey,repository:e.repository},r=yield*d4(e.itemKey);x(r)?yield*A(`Cycle-budget Ask stays open; its Item is open or not stored`,n):(yield*t.close(e.id,`ItemClosed`))&&(yield*k(`Item is closed; its cycle-budget Ask leaves Needs attention`,{...n,itemState:r.value}))}}),m4=dT(xI).pipe(NT(gE(OT([pT(`github`),H,SI])))),h4=oT(m4),g4=(e,t)=>h4([`github`,H.make(fA(e)),SI.make(t)]),_4={labels:[],findings:[],catalogChanged:!1,nextPollAt:y()},v4=O(`PollingTriggers.applyLabelCatalog`)(function*(e,t,n){yield*D({repository:e});let r=yield*qz,i=yield*Jz,a={labelEntityTag:t,entityTagChanged:!1,confirmedLabels:y(),failures:[],nextPollAt:y()};if(vi(n)){let t=n.failure;return t._tag===`GitHubRateLimitError`?(yield*Cg(`Label catalog rate-limited; kept the stored catalog and deferred label provisioning`,{repository:e,operation:t.operation,retryAt:v_(t.retryAt)}),{...a,nextPollAt:b(t.retryAt)}):(yield*wg(`Label catalog request failed; kept the stored catalog, deferred label provisioning, and evaluated items anyway`,{repository:e,...J2(t)}),{...a,failures:[new G2({repository:e,errorTag:t._tag,message:t.message})]})}let o=n.success;if(!(o instanceof _U)){let t=yield*r.get(e);return x(t)?(yield*Cg(`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*A(`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 Pz({name:e,color:b(t),description:n}));return yield*i.replace(new Lz({repository:e,labels:s})),{...a,labelEntityTag:o.entityTag,entityTagChanged:!0,confirmedLabels:b(s)}}),y4=O(`PollingTriggers.synchronizeLabels`)(function*(e,t,n){yield*D({repository:e});let r=yield*EW,i=yield*jW,a=yield*Jz,o=yield*v4(e,n,yield*Sh(r.labels(e,n))),s=yield*pr(o.confirmedLabels,{onNone:()=>w(_4),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:Y2([o.nextPollAt,s.nextPollAt])};return s.catalogChanged&&(yield*a.replace(new Lz({repository:e,labels:s.labels})).pipe(Ph(e=>({_tag:`InterruptedRepositoryCycle`,error:e,failures:c.failures,preflightFindings:c.preflightFindings,nextPollAt:c.nextPollAt})))),c}),b4=O(`PollingTriggers.observeItem`)(function*(e,t){yield*D({repository:e,item:t.number});let n=yield*EW,r=yield*s2,i=yield*b0,a=g4(e,t.number),o=yield*i.generation(a),s=yield*n.snapshot(e,t),c=new X0({itemKey:a,repository:e,source:J0.make(t._tag===`ChangedIssue`?`issue`:`pr`),number:SI.make(t.number),contentHash:Y0.make(s.contentHash),payload:s.payload});return yield*r.upsert(c),yield*A(`Fetched changed-item snapshot`,{repository:e,item:c.number,stream:c.source,contentHash:c.contentHash}),{snapshot:s,projection:c,cycleGeneration:o}}),x4=O(`PollingTriggers.markItemGone`)(function*(e,t){return yield*D({repository:e,item:t}),yield*(yield*s2).markGone(g4(e,t),yield*l_)}),S4=(e,t,{projection:n,cycleGeneration:r})=>rN.make(JSON.stringify([e.name,fA(t.name),n.number,n.contentHash,...r===0?[]:[r]])),C4=(e,t,n)=>T(function*(){return yield*(yield*CJ).evaluateBoolean(e.trigger.if,nX(e.trigger.on),{repo:rX(t),item:n})}),w4=(e,t,n)=>T(function*(){let r=yield*CJ,i=rX(t);return yield*r.evaluateBooleanEach(e.trigger.if,nX(e.trigger.on),n.map(e=>({repo:i,item:e})))}),T4=O(`PollingTriggers.evaluateItem`)(function*(e,t,n){let{projection:r,cycleGeneration:i}=n;yield*D({repository:e.name,item:r.number});let a=yield*p0,o=yield*F2,s=t.filter(({loop:e})=>e.trigger.on===r.source),c=r.payload,l={repo:rX(e),item:c};if(s.length===0)return yield*A(`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`?cA.make(yield*Zw(lA)(c.headRefOid).pipe(Ph(()=>new AH({operation:`fetch-pull-request-snapshot`,message:`The pull request payload has no valid head commit`,detail:`pull request #${r.number} has no full headRefOid`})))):L2,f=[],p=0;for(let{agent:t,loop:m,parentModel:h}of s){yield*D({loop:m.name,agent:t.name});let s=yield*Sh(C4(m,e,c));if(vi(s)){f.push(new X2({loop:m.name,stage:`if`,expression:b(s.failure.source),errorTag:s.failure._tag,message:s.failure.message}));continue}if(!s.success){yield*A(`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*k(`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=S4(m,e,n),_=yield*l_,v=yield*Sh(a.renderPrompt(m,l));if(vi(v)){f.push(new X2({loop:m.name,stage:`prompt`,expression:v.failure.expression,errorTag:v.failure._tag,message:v.failure.message}));continue}let ee=yield*o.submit(H2({dedupKey:g,cycleGeneration:i,itemKey:r.itemKey,loop:m,payload:c,receivedAt:_,repository:e,revision:d,task:PF.make(v.success),agent:t,parentModel:h}));yield*k(`Submitted matching item state`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,contentHash:r.contentHash,revision:d,result:ee._tag,...U2(ee)}),u.push(ee)}return{submissions:u,revokedRuns:p,failures:f}}),E4=O(`PollingTriggers.revokeMissingItem`)(function*(e,t,n,r){yield*D({repository:e.name,item:r});let i=yield*F2,a=g4(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*k(`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}),D4=T(function*(){let e=new Set,t=yield*yD({capacity:128,strategy:`dropping`}),n=yield*Yk(y()),r=yield*Yk(0),i=({repository:e,item:t})=>`${fA(e)}:${pr(t,{onNone:()=>`*`,onSome:e=>String(e.number)})}`,a=e=>pr(e,{onNone:()=>lh,onSome:e=>$k(r,t=>Math.max(t,h_(e)))});return{offer:O(`PollingTriggers.hint`)(function*(r,o,s=y()){yield*D({repository:r,item:o?.number}),yield*Zk(n,b(yield*l_)),yield*a(s);let c={repository:r,item:vr(o)},l=i(c);e.has(l)?yield*A(`Hint coalesced with a pending fetch`,{repository:r,item:o?.number}):(e.add(l),(yield*xD(t,c))?yield*A(`Hint queued`,{repository:r,item:o?.number}):(e.delete(l),yield*Cg(`Hint queue full; the normal poll will refresh the repository`,{repository:r,item:o?.number})))},cg),take:lg(n=>n(DD(t)).pipe(xh(t=>ch(()=>e.delete(i(t)))))),defer:a,awaitBackoff:T(function*(){for(;;){let e=yield*Xk(r),t=yield*Nf;if(e<=t)return;yield*k(`GitHub request backoff delays polling and self-write Hints`,{sleepMs:e-t}),yield*Bh(Ra(e-t))}}),lastHint:Xk(n)}}),O4=class e extends kr()(`@usine/orchestrator/ItemHints`){static layer=Df(e,D4)},k4=Ba(10),A4={revokedRuns:0,failures:[],nextPollAt:y()},j4=O(`PollingTriggers.checkOpenIssues`)(function*(e,t){yield*D({repository:e.name});let n=yield*o2,r=yield*EW,i=yield*n.openIssues(e.name);if(i.length===0)return yield*A(`No open issues to check against GitHub`,{repository:e.name}),A4;let a=yield*Sh(r.missingIssues(e.name,i));if(vi(a)){let t=a.failure;return t._tag===`GitHubRateLimitError`?(yield*Cg(`Open-issue check rate-limited; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,operation:t.operation,retryAt:v_(t.retryAt)}),{...A4,nextPollAt:b(t.retryAt)}):(yield*wg(`Open-issue check failed; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,...J2(t)}),{...A4,failures:[new G2({repository:e.name,errorTag:t._tag,message:t.message})]})}let o=0;for(let n of a.success){let r=yield*E4(e,t,`issue`,n),i=yield*x4(e.name,n);o+=r,yield*k(`GitHub no longer has an open issue; it leaves the open lanes`,{repository:e.name,item:n,revokedRuns:r,projectionMarkedGone:i})}return yield*A(`Checked open issues against GitHub`,{repository:e.name,openIssues:i.length,missingIssues:a.success.length}),{...A4,revokedRuns:o}}),M4=4,N4=class extends B(`@usine/orchestrator/OpenPullRequest`)({number:lU.fields.number,updatedAt:kE,baseRefName:ME(aU),mergeable:j.pipe(RT(w(`UNKNOWN`))),checksUnsettled:yT.pipe(RT(w(!0)))}){},P4=(e,t)=>t._tag===`PullRequestSnapshot`&&t.payload.state===`OPEN`?b(new N4({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(),F4=O(`PollingTriggers.readBaseRef`)(function*(e,t,n,r){yield*D({repository:e,baseRefName:t});let i=yield*Sh((yield*EW).baseRefHead(e,t,n));if(vi(i)){let a=i.failure;return a._tag===`GitHubRateLimitError`?yield*a:(yield*Cg(`Could not read the base branch head; refreshing its open pull requests in this poll`,{repository:e,baseRefName:t,pullRequests:r.join(`, `),...J2(a)}),{_tag:`Unreadable`,recorded:n})}let a=i.success;return x(n)?(yield*k(`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*k(`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})}),I4=(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()},L4=O(`PollingTriggers.openPullRequestRefresh`)(function*(e,t,n,r){if(yield*D({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*rh(i,([t,r])=>F4(e,t,_r(n.find(e=>e.baseRefName===t)),r).pipe(Th(e=>[t,e])),{concurrency:M4})),o=t.filter(({number:e})=>!r.has(e)),s=o.flatMap(e=>wr(Sr(I4(e,a),t=>({pullRequest:e,reason:t}))));if(s.length===0)yield*A(`No open pull request needs a refresh`,{repository:e,openPullRequests:t.length,baseRefReads:a.size});else{let t=Yi(s,({reason:e})=>e);yield*k(`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`?wr(e.recorded):[e.head]).sort((e,t)=>e.baseRefName.localeCompare(t.baseRefName))}}),R4=4,z4=4,B4=R.pipe(I(`GitHubPollWatchKey`)),V4=class extends B(`@usine/orchestrator/StoredPollCursor`)({boardVersion:pT(5),openPullRequests:N(N4),baseRefHeads:N(oU).pipe(RT(w([]))),cursor:sU,labelEntityTag:AE(iU),watches:N(B4).check(sE()),failingItems:N(Z2).pipe(RT(w([])))}){},H4=e=>h0.make(`github-poll:${fA(e.name)}`),U4=({loop:e})=>B4.make(JSON.stringify([e.name,e.trigger.on,e.trigger.if])),W4=(e,t)=>e.config.repos.map(n=>{let r=t.filter(({loop:t})=>t.trigger.on!==`schedule`&&LX(e.config,t,n));return{repository:n,declaredLabels:zX(e.config,n.name),loops:r,watches:r.map(U4).sort()}}),G4=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),K4=class e extends kr()(`@usine/orchestrator/PollingTriggers`){static layer=Df(e,T(function*(){let e=yield*v0,t=yield*b0,n=yield*EW,r=yield*f2,i=yield*Yk(y()),a=yield*Yk(new Map),o=yield*O4,s=yield*JD(1),c=yield*Yk({instance:y(),repositories:new Set}),l=yield*Yk(new Map),u=e=>new V4({boardVersion:5,openPullRequests:[],baseRefHeads:[],cursor:sU.empty,labelEntityTag:y(),watches:e,failingItems:[]}),d=O(`PollingTriggers.readCursor`)(function*(t){yield*D({repository:t.repository.name});let n=yield*e.read(H4(t.repository),V4);return x(n)?u(t.watches):G4(n.value.watches,t.watches)?n.value:(yield*k(`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=O(`PollingTriggers.writeCursor`)(function*(t,n){yield*D({repository:t.repository.name}),yield*e.write(H4(t.repository),V4,n)}),p=O(`PollingTriggers.checkOpenIssuesWhenDue`)(function*(e){yield*D({repository:e.repository.name});let t=H4(e.repository),n=yield*Nf,r=(yield*Xk(l)).get(t);return r!==void 0&&n-r<Va(k4)?(yield*A(`Open issues were checked less than 10 minutes ago; skipped`,{repository:e.repository.name,lastCheckedAt:v_(s_(r))}),A4):(yield*$k(l,e=>new Map(e).set(t,n)),yield*j4(e.repository,e.loops))}),m=O(`PollingTriggers.pollRepository`)(function*(e){yield*D({repository:e.repository.name});let r=(yield*t.pendingResets()).filter(({repository:t})=>fA(t)===fA(e.repository.name)),i=r.length>0?u(e.watches):yield*d(e);r.length>0&&(yield*k(`Cycle budget reset requests fresh repository polling`,{repository:e.repository.name,items:r.map(({itemKey:e})=>e)}));let a=yield*y4(e.repository.name,e.declaredLabels,i.labelEntityTag);return yield*o.defer(a.nextPollAt),yield*T(function*(){let s=yield*n.changes(e.repository.name,i.cursor);yield*o.defer(s.backoffUntil);let l=(yield*Xk(c)).repositories.has(H4(e.repository))?[]:i.failingItems,u=s._tag===`RepositoryChanges`?s.items:[],d=new Set(u.map(({number:e})=>e)),m=yield*L4(e.repository.name,i.openPullRequests,i.baseRefHeads,new Set([...d,...l.map(({number:e})=>e)])),h=new Map([...l.map(e=>[e.number,Q2(e)]),...m.refreshed.map(({number:e,updatedAt:t})=>[e,new lU({number:e,updatedAt:t})])]);for(let e of u)h.set(e.number,e);s._tag===`RepositoryChanges`&&(yield*k(`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*k(`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 _=Y2([s.nextPollAt,a.nextPollAt]);yield*A(`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*rh(h.values(),t=>T(function*(){let n=yield*b4(e.repository.name,t),r=yield*T4(e.repository,e.loops,n),i=$2(t,n.projection.contentHash,r.failures);return yield*i4(e.repository.name,t.number,_r(v.get(t.number)),i),{_tag:`Evaluated`,item:t,observation:n,cycle:r,failing:i}}).pipe(Ah(`GitHubItemNotFoundError`,n=>T(function*(){if(!g.has(t.number))return yield*n;let r=yield*E4(e.repository,e.loops,t._tag===`ChangedIssue`?`issue`:`pr`,t.number),a=yield*x4(e.repository.name,t.number);return yield*Cg(`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:z4}),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*p4(e.repository.name);let ae=[...i.failingItems.filter(({number:e})=>!h.has(e)),...te.flatMap(({failing:e})=>wr(e))].sort((e,t)=>e.number-t.number),oe=[...i.openPullRequests.filter(({number:e})=>!h.has(e)),...te.flatMap(({item:e,observation:t})=>wr(P4(e,t.snapshot)))],se=m.baseRefHeads.filter(({baseRefName:e})=>oe.some(t=>Er(t.baseRefName,e))),ce=new V4({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*$k(c,t=>({...t,repositories:new Set([...t.repositories,H4(e.repository)])})),yield*rh(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=>t4(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:Y2([_,ie.nextPollAt])}}).pipe(Ph(t=>({_tag:`InterruptedRepositoryCycle`,error:t,failures:[...a.failures,...i.failingItems.flatMap(t=>t4(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:a.nextPollAt})))}),h=(yield*Kh()).pipe(ci(p0,b0,CJ,EW,o2,s2,jW,qz,Jz,F2)),g=O(`PollingTriggers.poll`)(function*(e){yield*o.awaitBackoff,yield*$k(c,t=>Er(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*A(`Paused Loop skipped during repository polling`,{loop:n.name}));let n=W4(e,(yield*B2(e)).filter(({loop:e})=>!t.has(e.name))),s=yield*rh(n,e=>Sh(m(e)).pipe(Th(t=>({repository:e,result:t}))),{concurrency:R4}),l=[],u=[],d=[],f=[],p=yield*l_;for(let{repository:e,result:t}of s){if(yi(t)){l.push(t.success),f.push(...t.success.preflightFindings),yield*$k(a,t=>new Map(t).set(fA(e.repository.name),new K2({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*Cg(`GitHub rate limit reached; delaying the next cycle`,{repository:e.repository.name,operation:r.operation,retryAt:v_(r.retryAt)}),d.push(b(r.retryAt)),yield*o.defer(b(r.retryAt))):(yield*wg(`Repository poll cycle failed; siblings were unaffected`,{repository:e.repository.name,...J2(r)}),u.push(new G2({repository:e.repository.name,errorTag:r._tag,message:r.message})))}let h=yield*Xk(a),g=new q2({repositoryPolls:n.flatMap(({repository:e})=>wr(_r(h.get(fA(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:Y2([...l.map(({nextPollAt:e})=>e),...d])});return yield*Zk(i,b(g)),g},Yh(h),s.withPermits(1)),_=O(`PollingTriggers.refreshHint`)(function*(e,t){yield*D({repository:t.repository,item:br(Sr(t.item,e=>e.number))}),yield*o.awaitBackoff;let n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop)),i=W4(e,(yield*B2(e)).filter(({loop:e})=>!n.has(e.name))).find(({repository:e})=>fA(e.name)===fA(t.repository));if(i===void 0){yield*k(`Hint ignored for an unmanaged repository`,{repository:t.repository,item:br(Sr(t.item,e=>e.number))});return}if(x(t.item)){let e=yield*m(i).pipe(kh(e=>e._tag===`InterruptedRepositoryCycle`?o.defer(e.nextPollAt).pipe(bh(fh(e.error))):fh(e)));yield*k(`Hint refreshed the repository`,{repository:t.repository,changedItems:e.changedItems,submissions:e.submissions.length,failures:e.failures});return}let a=t.item.value,s=yield*b4(i.repository.name,a),c=yield*T4(i.repository,i.loops,s);for(let e of c.failures)yield*Cg(`Hint could not evaluate a Loop on the Item`,{repository:t.repository,item:a.number,loop:e.loop,stage:e.stage,errorTag:e.errorTag,message:e.message});yield*k(`Hint refreshed the Item`,{repository:t.repository,item:a.number,submissions:c.submissions.length,revokedRuns:c.revokedRuns,failures:c.failures.length})},Yh(h),(e,t,n)=>e.pipe(kh(e=>T(function*(){e._tag===`GitHubRateLimitError`&&(yield*o.defer(b(e.retryAt))),yield*Cg(`Hint refresh failed; the normal poll will retry`,{repository:n.repository,item:br(Sr(n.item,e=>e.number)),...J2(e)})})),s.withPermits(1))),v=(e,t,n,r)=>T(function*(){let i=Math.max(n,r),a=t;for(;;){let t=i-(yield*Nf);if(t<=0)return;let n=yield*Vh([Bh(Ra(t)).pipe(Th(()=>({_tag:`Due`}))),o.take.pipe(Th(e=>({_tag:`Hint`,hint:e}))),I2(e,a).pipe(Th(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*Nf);s>0?yield*k(`Instance reloaded; the next poll waits for the time GitHub asked for`,{sleepMs:s}):yield*k(`Instance reloaded; polling now instead of after poll_interval`)}});return{latest:Xk(i),poll:g,run:e=>T(function*(){let t=yield*e.get,n=yield*Nf,r=yield*Sh(g(t));if(vi(r)){let e=t.config.settings.pollInterval*1e3;yield*wg(`Poll cycle could not read Loop runtime state; retrying`,{errorTag:r.failure._tag,message:r.failure.message,operation:r.failure.operation,sleepMs:e}),yield*Bh(Ra(e));return}let i=r.success,a=n+t.config.settings.pollInterval*1e3,o=pr(i.nextPollAt,{onNone:()=>0,onSome:h_}),s=yield*Nf,c=Math.max(0,Math.max(a,o)-s);yield*k(`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(ug),hint:o.offer,lastHint:o.lastHint}})).pipe(Mf(O4.layer))},q4=4,J4=6e4,Y4=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...W2(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},X4=class extends V(`@usine/orchestrator/ScheduleAgentFailure`)(`ScheduleAgentFailure`,{loop:DA,agent:SA,message:j}){},Z4=class extends V(`@usine/orchestrator/ScheduleTickFailure`)(`ScheduleTickFailure`,{loop:DA,repository:H,scheduledAt:OE,errorTag:R,message:j}){},Q4=class extends V(`@usine/orchestrator/ScheduleCronFailure`)(`ScheduleCronFailure`,{loop:DA,cron:j,tz:j,message:j}){},$4=P([X4,Q4,Z4]),e3=class extends B(`@usine/orchestrator/ScheduleCycle`)({loops:L.check($T(0)),fanout:L.check($T(0)),submissions:N(az),skipped:L.check($T(0)),alreadyFired:L.check($T(0)),failures:N($4),nextTickAt:z(OE)}){},t3=e=>e.loops.flatMap(t=>{let n=t.trigger;return n.on===`schedule`?[{loop:t,repositories:e.config.repos.filter(n=>LX(e.config,t,n)),trigger:n}]:[]}),n3=(e,t)=>{let n=p_(t);return n.setUTCSeconds(0,0),o_(Qp(e,n)?n:tm(e,n))},r3=(e,t)=>o_(em(e,p_(t))),i3=(e,t)=>pr(f_(e,t),{onNone:()=>v_(e),onSome:Mee}),a3=e=>e.length===0?y():c_(Math.min(...e.map(h_))),o3=e=>xI.make(JSON.stringify([`github`,fA(e.name)])),s3=(e,t,n)=>rN.make(JSON.stringify([e.name,fA(t.name),v_(n)])),c3=e=>({tick:{scheduledAt:v_(e.scheduledAt),scheduledAtLocal:e.scheduledAtLocal,cron:e.trigger.cron,tz:e.trigger.tz}});(class e extends kr()(`@usine/orchestrator/ScheduleTriggers`){static layer=Df(e,T(function*(){let e=yield*p0,t=yield*CJ,n=yield*F2,r=yield*f2,i=yield*Yk(y()),a=yield*Yk({instance:y(),ticks:new Map}),o=new WeakMap,s=e=>{let t=o.get(e);if(t!==void 0)return t;let n=Zp(e.cron,e.tz);return o.set(e,n),n},c=O(`ScheduleTriggers.submitTick`)(function*(r,i){yield*D({loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:v_(r.scheduledAt)});let a=c3(r),o={repo:rX(r.repository),item:a};if(!(yield*t.evaluateBoolean(r.trigger.if,nX(`schedule`),o)))return yield*A(`Scheduled Tick did not match its expression`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:v_(r.scheduledAt)}),y();let s=s3(r.loop,r.repository,r.scheduledAt),c=yield*e.renderPrompt(r.loop,o),l=yield*n.submit(H2({cycleGeneration:wI.make(0),agent:r.agent,dedupKey:s,itemKey:o3(r.repository),loop:r.loop,payload:a,receivedAt:i,repository:r.repository,revision:L2,task:PF.make(c),parentModel:r.parentModel}));return yield*k(`Submitted scheduled Tick`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:v_(r.scheduledAt),scheduledAtLocal:r.scheduledAtLocal,result:l._tag,...U2(l)}),b(l)}),l=O(`ScheduleTriggers.tick`)(function*(e){let t=yield*l_,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*A(`Paused Loop skipped during schedule evaluation`,{loop:t.name}));let o=t3(e).filter(({loop:e})=>!n.has(e.name)),l=yield*Qk(a,t=>{let n=Er(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*Cg(`Schedule loop selected no repositories`,{loop:n.loop.name}));let r=yield*gh({try:()=>{let e=s(n.trigger),r=n3(e,t);return{latest:r,latestLocal:i3(r,n.trigger.tz),next:r3(e,t)}},catch:e=>e}).pipe(Sh);if(vi(r)){yield*wg(`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 Q4({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=h_(i.latest),o=l.get(n.loop.name);if(o!==void 0&&o>=a){h+=1,yield*A(`Tick already fired`,{loop:n.loop.name,scheduledAt:v_(i.latest)});continue}let c=yield*Sh(z2(e,n.loop));if(vi(c)){let e=c.failure;yield*wg(`Schedule loop could not resolve its Agent`,{loop:e.loop,agent:e.agent,errorTag:e._tag,message:e.message}),d.push(new X4({loop:e.loop,agent:e.agent,message:e.message}))}else if(n.repositories.length!==0){p.set(n.loop.name,a),yield*k(`Schedule tick due`,{loop:n.loop.name,agent:c.success.agent.name,cron:n.trigger.cron,tz:n.trigger.tz,scheduledAt:v_(i.latest),scheduledAtLocal:i.latestLocal,repositories:n.repositories.length,nextTickAt:v_(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*D({schedules:o.length,fanout:u.length});let g=yield*rh(u,e=>Sh(c(e,t)).pipe(Th(t=>({candidate:e,result:t}))),{concurrency:q4}),_=[],v=[],ee=new Set,te=new Set,ne=0;for(let{candidate:e,result:t}of g){if(yi(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*wg(`Scheduled Tick failed; sibling fanout was unaffected`,{loop:e.loop.name,repository:e.repository.name,agent:e.agent.name,scheduledAt:v_(e.scheduledAt),...Y4(n)}),v.push(new Z4({loop:e.loop.name,repository:e.repository.name,scheduledAt:e.scheduledAt,errorTag:n._tag,message:n.message}))}yield*$k(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 e3({loops:o.length,fanout:u.length,submissions:_,skipped:ne,alreadyFired:h,failures:[...d,...f,...v],nextTickAt:a3(m)});return yield*Zk(i,b(re)),re}),u=(e,t,n)=>Hh(Bh(Ra(n)),I2(e,t).pipe(bh(k(`Instance reloaded; evaluating schedules now instead of after the sleep`))));return{latest:Xk(i),run:e=>T(function*(){let t=yield*e.get,n=yield*Sh(l(t));if(vi(n)){yield*wg(`Schedule cycle could not read Loop runtime state; retrying`,{errorTag:n.failure._tag,message:n.failure.message,operation:n.failure.operation,sleepMs:J4}),yield*u(e,t,J4);return}let r=n.success,i=yield*Nf,a=pr(r.nextTickAt,{onNone:()=>i+J4,onSome:h_}),o=Math.min(J4,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:pr(r.nextTickAt,{onNone:()=>`none`,onSome:v_}),sleepMs:o};r.fanout===0&&r.failures.length===0?yield*A(`Schedule cycle complete`,s):yield*k(`Schedule cycle complete`,s),yield*u(e,t,o)}).pipe(ug),tick:l}}))});var l3=class extends V(`@usine/orchestrator/ApprovalNeed`)(`ApprovalNeed`,{id:j,repository:H,runId:LN,loop:DA,item:F(Qq)}){},u3=class extends V(`@usine/orchestrator/RunFailureNeed`)(`RunFailureNeed`,{id:j,repository:H,runId:LN,loop:DA,failure:QW}){},d3=class extends V(`@usine/orchestrator/PollFailureNeed`)(`PollFailureNeed`,{id:j,failure:G2}){},f3=class extends V(`@usine/orchestrator/PreflightFindingNeed`)(`PreflightFindingNeed`,{id:j,finding:OW}){},p3=class extends V(`@usine/orchestrator/BoardProjectionNeed`)(`BoardProjectionNeed`,{id:j,failure:aJ}){},m3=class extends V(`@usine/orchestrator/ScheduleFailureNeed`)(`ScheduleFailureNeed`,{id:j,failure:$4}){},h3=class extends V(`@usine/orchestrator/ConfigFileNeed`)(`ConfigFileNeed`,{id:j,kind:jT([`loop`,`agent`]),error:DJ}){},g3=class extends V(`@usine/orchestrator/UnconfiguredWorkerNeed`)(`UnconfiguredWorkerNeed`,M({id:j,worker:qN,attempts:L.check($T(1)),running:L.check($T(0))}).check(WT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},_3=class extends V(`@usine/orchestrator/UnconfirmedStopNeed`)(`UnconfirmedStopNeed`,{id:j,repository:H,runId:LN,loop:DA,attemptNumber:MF,worker:qN}){},v3=class extends V(`@usine/orchestrator/UnresponsiveWorkerNeed`)(`UnresponsiveWorkerNeed`,{id:j,worker:qN,lastAnsweredAt:j,attempts:N(M({attemptId:jF,attemptNumber:MF,runId:LN,repository:H,loop:DA})).check(nE(1))}){},y3=class extends V(`CycleBudgetNeed`)(`CycleBudgetNeed`,{id:j,ask:kI,itemLabel:j,itemUrl:F(j)}){},b3=class extends V(`@usine/orchestrator/WorkerPreflightNeed`)(`WorkerPreflightNeed`,{id:j,worker:qN,message:j}){},x3=class extends V(`@usine/orchestrator/WorkerQuotaNeed`)(`WorkerQuotaNeed`,{id:j,worker:qN,message:j}){},S3=class extends V(`@usine/orchestrator/PoolLimitNeed`)(`PoolLimitNeed`,{id:j,pool:XP,login:AE(tF),window:jT([`primary`,`secondary`]),usedPercent:vT.check($T(80)),resetsAt:kE}){},C3=P([class extends V(`@usine/orchestrator/WebhookSilenceNeed`)(`WebhookSilenceNeed`,{id:j,startedAt:j,publicUrl:j}){},y3,l3,p3,u3,d3,f3,m3,h3,g3,_3,v3,b3,x3,S3]),w3=jT([`clear`,`active`,`needs-you`]),T3=class extends B(`@usine/orchestrator/ProjectView`)({id:lT(pA),name:lT(j),repositories:N(H).pipe(RT(w([])),IT(w([]))),repository:H,status:w3,runs:N(Wq),board:oJ,labels:N(sJ),preflightFindings:N(OW)}){},E3=class extends B(`@usine/orchestrator/LoopView`)({name:DA,trigger:j,agent:SA,paused:yT}){},D3=class extends V(`@usine/orchestrator/ReadyOverview`)(`Ready`,{projects:N(T3),loops:N(E3),needsYou:N(C3),dismissedNeeds:N(C3).pipe(IT(w([])))}){},O3=class extends V(`@usine/orchestrator/NeedsSetupOverview`)(`NeedsSetup`,{errorTag:R,projects:N(T3),loops:N(E3),needsYou:N(C3),dismissedNeeds:N(C3).pipe(IT(w([])))}){},k3=P([D3,O3]),A3=P([M({name:vX.fields.name,value:JE,text:lT(mT)}),M({name:vX.fields.name,text:j,value:lT(mT)})]),j3=class extends B(`LoopCheck`)({problems:N(EJ)}){},M3=class extends B(`LoopPreviewRequest`)({name:vX.fields.name,value:JE,itemKey:lT(xI)}){},N3=class extends B(`LoopPreviewItem`)({itemKey:xI,repository:H,kind:jT([`issue`,`pr`]),number:SI,title:j,url:j,state:FW,priority:gX}){},P3=class extends B(`LoopPreview`)({stream:fX,items:N(N3),total:L.check($T(0)),prompt:F(M({itemKey:xI,text:j})),repositoriesWithoutItems:N(H),failures:N(M({itemKey:xI,message:j}))}){},F3=class extends B(`ConfigurationEntityRequest`)({kind:j,identifier:MX}){},I3=class extends B(`ConfigurationRevisionQuery`)({kind:lT(j),identifier:lT(MX),before:lT(AX),limit:L.check(eE({minimum:1,maximum:100}))}){},L3=class extends B(`ConfigurationWrite`)({expected:AX,message:lT(j)}){},R3=P([M({...L3.fields,value:JE,text:lT(mT),position:lT(L.check($T(0)))}),M({...L3.fields,text:j,value:lT(mT),position:lT(L.check($T(0)))})]),z3=class extends B(`ConfigurationEntityView`)({key:NX,value:JE,text:j,number:AX}){},B3=class extends B(`ConfigurationRevisionSummary`)({number:AX,actor:F(ZM),time:OE,message:F(j),entities:N(NX)}){},V3=class extends B(`ConfigurationRevisionPage`)({revisions:N(B3),nextBefore:F(AX)}){};WE(`ConfigurationNotFound`)(`ConfigurationNotFound`,{message:j});var H3=class e extends B(`ConfigurationRevisionView`)({...B3.fields,changes:N(M({key:NX,before:F(JE),after:F(JE),position:lT(L)}))}){static fromRevision(t){return new e({...t,actor:C(t.actor),message:C(t.message),entities:t.changes.map(({key:e})=>e),changes:t.changes.map(e=>({...e,before:C(e.before),after:C(e.after)}))})}},U3=class extends B(`@usine/orchestrator/UpgradeRequest`)({timing:jJ,version:ME(AJ)}){},W3=class extends B(`@usine/orchestrator/UpgradeView`)({running:j,channel:OJ,mode:kJ,supported:yT,available:F(AJ),phase:jT([`idle`,`waiting`,`installing`,`failed`]),message:F(j),outcome:F(NJ)}){},G3=`~effect/http-api/HttpApiSchema/Stream`;function K3(e){let t=typeof e==`string`?KV(e):e;return e=>e.ast.checks!==void 0||f6(e.ast)?e.annotate({httpApiStatus:t}):e.annotateKey({httpApiStatus:t})}var q3=(e=>xT.pipe(K3(e)))(204),J3=e=>cT(e)&&pe(e,G3),Y3=e=>J3(e)&&e._tag===`StreamSse`,X3=e=>J3(e)&&e._tag===`StreamUint8Array`,Z3=e=>J3(e)&&e._tag===`StreamNdjson`,Q3=`~effect/http-api/HttpApiSchema/Upgrade`,$3=e=>cT(e)&&pe(e,Q3),e6=`~effect/http-api/HttpApiSchema/WithHeaders`,t6=`~effect/http-api/HttpApiSchema/WithHeadersValue`,n6=e=>({[t6]:t6,body:e.body,headers:e.headers}),r6=e=>cT(e)&&pe(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function i6(e,t,n){return sT(e.ast,{[e6]:e6,schema:t,headers:n})}function a6(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??o6(t._tag)}})}function o6(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 s6(e){return t=>a6(t,{_tag:`FormUrlEncoded`,...e})}var c6=e=>{if(xb(e)||xb(mS(e)))return!0;let t=e.encoding?.[0].to;return t!==void 0&&xb(t)},l6=FS(`~httpApiEncoding`),u6=FS(`~httpApiWithHeaders`),d6=FS(`httpApiStatus`);function f6(e){let t=PS(e);return t!==void 0&&`httpApiStatus`in t}function p6(e){return f6(e)?d6(e):e.checks===void 0?e.context?.annotations?.httpApiStatus:void 0}var m6={_tag:`Json`,contentType:`application/json`},h6={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function g6(e){return l6(e)??m6}function _6(e,t){return l6(e)||(xB(t)?m6:h6)}function v6(e){let t=g6(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function y6(e){return p6(e)??200}function b6(e){return r6(e)?p6(e.ast)??y6(e.schema.ast):y6(e.ast)}function x6(e){return r6(e)&&l6(e.ast)===void 0?v6(e.schema.ast):v6(e.ast)}function S6(e){return p6(e)??500}function C6(e){return r6(e)?p6(e.ast)??S6(e.schema.ast):S6(e.ast)}function w6(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}var T6=`~effect/http-api/HttpApiEndpoint`;function E6(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function D6(e){let t=Array.from(e.success);return zi(t)?t:[q3]}function O6(e){let t=new Set(e.error),n=e.disableCodecs?i:L6;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}var k6={[T6]:T6,pipe(){return e(this,arguments)},prefix(e){return j6({...A6(this),path:IV(this.path,e)})},middleware(e){return j6({...A6(this),middlewares:new Set([...this.middlewares,e])})},annotate(e,t){return j6({...A6(this),annotations:Xr(this.annotations,e,t)})},annotateMerge(e){return j6({...A6(this),annotations:oi(this.annotations,e)})}},A6=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 j6(e){function t(){}return Object.setPrototypeOf(t,k6),Object.assign(t,e)}var M6=e=>(t,n,r)=>{let a=r?.disableCodecs??!1,o=a?i:qE;return j6({identifier:t,path:n,method:e,params:N6(r?.params,o),query:N6(r?.query,o),headers:N6(r?.headers,o),payload:P6(r?.payload,e,a),success:I6(r?.success,e,r?.payload!==void 0,a),error:R6(r?.error,a),annotations:qr(),middlewares:new Set,disableCodecs:a})};function N6(e,t){if(e!==void 0)return cT(e)?t(e):t(M(e))}function P6(e,t,n){let r=new Map;if(e===void 0)return r;let a=Array.isArray(e)?e:cT(e)?[e]:[M(e).pipe(s6())],o=n?i:J6,s=!1;for(let e of a){if(J3(e)){if(Y3(e))throw Error(`StreamSse is response-only and cannot be used as a payload`);if(!xB(t))throw Error(`${t} endpoints cannot declare a streaming payload`);if(s)throw Error(`Multiple streaming payloads are not supported`);s=!0;let n=w6(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=_6(e.ast,t),i=w6(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 F6=`effect/http-api/stream/failure`;function I6(e,t,n,r){if(e===void 0)return new Set;let i=Li(e);return z6(i,t,n),new Set(r?i:i.map(L6))}var L6=f(e=>J3(e)||$3(e)?e:r6(e)?i6(e,J3(e.schema)?e.schema:q6(e.schema,x6(e)),qE(e.headers)):K6(e));function R6(e,t){if(e===void 0)return new Set;let n=Li(e);for(let e of n){let t=r6(e)?e.schema:e;if(J3(t))throw Error(`Streaming schemas are not supported in error responses`);if($3(t))throw Error(`Upgrade schemas are not supported in error responses`)}return V6(n,C6),new Set(t?n:n.map(L6))}function z6(e,t,n){if(e.some($3)){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=r6(n)?n.schema:n,a=b6(n);if(J3(e)){if(H6(e,t),r)throw Error(`Multiple streaming success responses are not supported`);r=!0;let n=B6(i,a);if(n.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(n.bufferedContentTypes.has(w6(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=B6(i,a),r=c6(e.ast);if(t.stream!==void 0){if(r)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=x6(n);if(w6(e.contentType)===w6(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}r||t.bufferedContentTypes.add(w6(x6(n).contentType)),t.noContent=t.noContent||r}}V6(e,b6)}function B6(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:new Set,noContent:!1},e.set(t,n)),n}function V6(e,t){let n=new Map;for(let r of e){let e=t(r),i=u6(r.ast),a=r6(r)?r.schema:i?.body??r,o=c6(a.ast)?``:w6(J3(a)?a.contentType:x6(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(r6(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 H6(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(Y3(e)&&U6(e.events.ast))throw Error(`SSE event name is reserved: ${F6}`)}function U6(e){return W6(mS(e),new Set)}function W6(e,t){if(t.has(e))return!1;if(t.add(e),Db(e))return e.types.some(e=>W6(e,t));if(Ob(e))return W6(e.thunk(),t);if(!Eb(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&G6(n.type,t)}function G6(e,t){if(t.has(e))return!1;t.add(e);let n=mS(e);return n===e?Cb(e)?e.literal===F6:Db(e)?e.types.some(e=>G6(e,t)):Ob(e)?G6(e.thunk(),t):!1:G6(n,t)}function K6(e){let t=v6(e.ast),n=u6(e.ast);return n===void 0?q6(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:q6(n.body,t),headersCodec:qE(n.headers)}})}function q6(e,t){switch(t._tag){case`Json`:return KE(e);case`FormUrlEncoded`:return qE(e);case`Text`:case`Uint8Array`:return e}}function J6(e,t){switch(_6(e.ast,t)._tag){case`Json`:return KE(e);case`FormUrlEncoded`:return qE(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}var Y6=M6(`GET`),X6=M6(`POST`),Z6=M6(`PUT`),Q6=M6(`DELETE`),$6=`~effect/http-api/HttpApi`,e8={[$6]:$6,pipe(){return e(this,arguments)},add(...e){let t={...this.groups};for(let n of e)Et(t,n.identifier,n);return n8({...t8(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(oi(e.annotations,r.annotations)))}return n8({...t8(this),groups:t})},prefix(e){return n8({...t8(this),groups:ji(this.groups,t=>t.prefix(e))})},middleware(e){return n8({...t8(this),groups:ji(this.groups,t=>t.middleware(e))})},annotate(e,t){return n8({...t8(this),annotations:Xr(this.annotations,e,t)})},annotateMerge(e){return n8({...t8(this),annotations:oi(this.annotations,e)})}},t8=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),n8=e=>{function t(){}return Object.setPrototypeOf(t,e8),Object.assign(t,e)},r8=e=>n8({identifier:e,groups:{},annotations:qr()}),i8=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=oi(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:oi(n,e.annotations),successes:a8(D6(e),b6),errors:a8(O6(e),C6)})}},a8=(e,t)=>{let n=new Map;return e.forEach(r),n;function r(e){let r=r6(e)?e.schema:e;if(J3(r)||$3(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}},o8=class extends kr()(`effect/http-api/HttpApi/ParseOptions`){},s8=class extends kr()(`effect/http-api/HttpApi/ParamsParseOptions`){},c8=class extends kr()(`effect/http-api/HttpApi/QueryParseOptions`){},l8=class extends kr()(`effect/http-api/HttpApi/HeadersParseOptions`){},u8=class extends kr()(`effect/http-api/HttpApi/PayloadParseOptions`){},d8=class extends kr()(`effect/http-api/HttpApi/SuccessParseOptions`){},f8=class extends kr()(`effect/http-api/HttpApi/ErrorParseOptions`){},p8=e=>{let t=Qr(e,o8);return{params:Qr(e,s8)??t,query:Qr(e,c8)??t,headers:Qr(e,l8)??t,payload:Qr(e,u8)??t,success:Qr(e,d8)??t,error:Qr(e,f8)??t}},m8=`~effect/http-api/HttpApiMiddleware`,h8=`~effect/http-api/HttpApiMiddleware/Security`,g8=()=>(e,t)=>{let n=St(),r;n!==0&&(Ct(2),r=new globalThis.Error,Ct(n));class i extends kr()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[m8]=m8,a.error=_8(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[h8]=h8,a.security=t.security}return a};function _8(e){return e===void 0?new Set:new Set(Array.isArray(e)?e:[e])}var v8=new Set;function y8(e){if(e===void 0)return v8;let t=Ux(e.ast);return Eb(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function b8(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=jV(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 x8=class extends kr()(`effect/http-api/OpenApi/Title`){},S8=class extends kr()(`effect/http-api/OpenApi/Version`){},C8=class extends kr()(`effect/http-api/OpenApi/Description`){},w8=class extends kr()(`effect/http-api/OpenApi/Summary`){},T8=class extends kr()(`effect/http-api/OpenApi/Transform`){},E8=(e,t)=>T(function*(){let n=yield*Kh(),r=t.httpClient.pipe(t?.baseUrl===void 0?i:vV(UB(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)}})}i8(e,{predicate:t?.predicate,onGroup(e){t.onGroup?.(e)},onEndpoint(e){let{group:n,endpoint:r,errors:i,successes:o,mergedAnnotations:s}=e,c=p8(s),l=k8(r.path,r.params),u={orElse:$8},d=new Map;for(let[e,t]of i.entries()){let n=F8(t);for(let[t,r]of n.entries())N8(d,e,t,A8(r,c.error,c.headers))}for(let[e,t]of d.entries()){let n=P8(t);u[e]=e=>E(Mh(n(e),t=>ph(Pd(Dd(new fB({reason:new vB({request:e.request,response:e})})),t))),fh)}let f=new Map;for(let[e,t]of o.entries()){let n=F8(t);for(let[t,r]of n.entries())N8(f,e,t,A8(r,c.success,c.headers))}for(let e of B8(r)){let t=R8(e)?e.schema:e;N8(f,b6(e),t.contentType,V8(e,c.success,c.headers))}for(let[e,t]of f.entries())u[e]=P8(t);let p=z8(r);p!==void 0&&(u[101]=e=>Th(e.upgrade,t=>({headers:e.headers,socket:t})));let m=tA(r.params,e=>rT(e,c.params)),h=[],g;for(let e of E6(r))X3(e)||Z3(e)?g=e:h.push(e);let _=tA(g,e=>({contentType:e.contentType,encode:t5(e,c.payload)})),v=zi(h)?rT(xB(r.method)?n5(h,r.method):P(h),c.payload):void 0,ee=tA(r.headers,e=>rT(e,c.headers)),te=tA(r.query,e=>rT(e,c.query)),ne=Array.from(e.middleware,e=>`${e.key}/Client`),re=Sg(function*(e){let i=jB(r.method)(r.path);if(e!==void 0){if(m!==void 0){let t=yield*m(e.params);i=HB(i,l(t))}if(_!==void 0&&RO(e.payload)){let t=yield*Kh();i=JB(i,uB(rk(_.encode(e.payload),t),_.contentType))}else if(v!==void 0){if(xB(r.method)){if(e.payload instanceof FormData)i=XB(i,e.payload);else{let t=yield*v(e.payload);i=JB(i,t)}}else{let t=yield*v(e.payload);i=KB(i,t)}}else if(_!==void 0)return yield*new Uw(new oy({message:`Expected a Stream payload`},e.payload));if(ee!==void 0){let t=yield*ee(e.headers);i=RB(i,t)}if(te!==void 0){let t=yield*te(e.query);i=KB(i,t)}}p!==void 0&&(i=VB(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})}})}),D8=(e,t)=>E(fV,n=>O8(e,{...t,httpClient:t?.transformClient?t.transformClient(n):n})),O8=(e,t)=>{let n={};return E8(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(Eh(n))},k8=(e,t)=>{if(t===void 0||!e.includes(`:`))return t=>e;let n=y8(t);return t=>b8(e,n,(e,n)=>{let r=t[e];if(r!==void 0)return encodeURIComponent(r);if(!n)throw Error(`Missing path parameter: ${e}`)})};function A8(e,t,n){let r=e.some(e=>r6(e)||u6(e.ast)!==void 0),i=Zw(r?P(e.map(e=>M8(e,t,n))):Z8(e),t);return e=>E(e.arrayBuffer,r?t=>i({body:t,headers:e.headers}):i)}var j8=M({body:hT,headers:hT});function M8(e,t,n){let r=u6(e.ast),i=r===void 0?r6(e)?{body:e.schema,headers:e.headers,toValue:n6}:{body:e,headers:hT,toValue:e=>e.body}:{body:r.bodyCodec,headers:r.headersCodec,toValue:r.transformation.decode},a=Zw(Q8(i.body).pipe(NT(i.body)),t),o=Zw(i.headers,n);return j8.pipe(NT(r6(e)?e:dT(e),$y({decode:e=>nh({body:a(e.body),headers:o(e.headers)}).pipe(Th(i.toValue),Ph(e=>e.issue)),encode:(e,t)=>fh(new cy({message:`Decode only schema`},e,t))})))}function N8(e,t,n,r){let i=w6(n),a=e.get(t);a===void 0?e.set(t,[{contentType:i,decode:r}]):a.push({contentType:i,decode:r})}function P8(e){let t=e[0];return e.length===1&&t!==void 0?t.decode:(t,n)=>{let r=w6(t.headers[`content-type`]??``),i=e.find(e=>e.contentType===r);return i===void 0?I8(t,r,e):i.decode(t,n)}}function F8(e){let t=new Map;for(let n of e){let e=c6((r6(n)?n.schema:n).ast)?``:w6(x6(n).contentType),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return t}function I8(e,t,n){let r=Array.from(new Set(n.map(e=>e.contentType))).join(`, `);return fh(new fB({reason:new yB({request:e.request,response:e,description:`Unsupported response content-type for status ${e.status}: ${t||`<missing>`}. Expected one of: ${r}`})}))}var L8=`effect/http-api/stream/failure`,R8=e=>r6(e);function z8(e){for(let t of e.success)if($3(t))return t}function B8(e){let t=[];for(let n of e.success)J3(r6(n)?n.schema:n)&&t.push(n);return t}function V8(e,t,n){let r=R8(e),i=H8(r?e.schema:e,t),a=(e,t)=>Th(Kh(),n=>rk(i(e,t),n));if(!r)return a;let o=Zw(e.headers,n);return(e,t)=>E(o(e.headers),n=>Th(a(e,t),e=>n6({body:e,headers:n})))}function H8(e,t){if(X3(e))return e=>e.stream;if(Z3(e)){let n=Zw(KE(e.schema),t),r=r_(e.maxElementBytes);return e=>e.stream.pipe($O(MR({ignoreEmptyLines:!0,maxLineBytes:r})),QO(t=>wR(t)?t.reason===`LineTooLarge`?new fB({reason:new yB({request:e.request,response:e,description:`NDJSON line exceeds maxElementBytes of ${r} bytes`})}):W8(t):t),JO(e=>n(e)))}let n=G8(e,t);return(t,r)=>K8(t.stream,e,n(r))}var U8=e=>wR(e)&&e.kind===`Pack`,W8=e=>new Uw(new oy({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 G8(e,t){let n=P([M({id:uT(j),event:pT(L8),data:gE(KE(SE(e.error,dE())))}),e.events]),r=RR(n,void 0,t);return e=>e===void 0?r:RR(n,e,t)}function K8(e,t,n){let r=BO(e.pipe(ek,$O(n)),e=>ch(()=>{let t;return sh(()=>t===void 0?E(e,e=>{for(let n=0;n<e.length;n++){let r=e[n];if(r.event===L8&&Cd(r.data)){if(n===0)return ph(r.data);t=r.data,e=e.slice(0,n);break}}return w(e)}):ph(t))}));return t.sseMode===`data`?qO(r,e=>e.data):r}var q8=HT(globalThis.ArrayBuffer,{expected:`ArrayBuffer`}),J8=q8.pipe(NT(bE,eb({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)}}))),Y8=q8.pipe(NT(j,eb({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)}}))),X8=Y8.pipe(NT(P([pT(``).pipe(NT(_T,eb({decode:()=>void 0,encode:()=>``}))),_E])));function Z8(e){return P(e.map(t));function t(e){return Q8(e).pipe(NT(e))}}function Q8(e){switch(v6(e.ast)._tag){case`Json`:return bb(mS(e.ast))?X8.pipe(NT(hT,eb({decode:e=>e===void 0?null:e,encode:e=>e===null?void 0:e}))):X8;case`FormUrlEncoded`:return Y8.pipe(NT(jE,eb({decode:e=>uv(new URLSearchParams(e)),encode:yv})));case`Uint8Array`:return J8;case`Text`:return Y8}}var $8=e=>fh(new fB({reason:new yB({request:e.request,response:e})})),e5=Hw(Xz);function t5(e,t){if(X3(e))return e=>e;let n=rT(kT(KE(e.schema)),t);return e=>e.pipe(YO(e=>n(e)),$O(ER()),ZO(U8,GO))}function n5(e,t){return P(e.map(e=>i5(e,t)))}var r5=new WeakMap;function i5(e,t){let n=e.ast,r=r5.get(n);if(r!==void 0)return r;let i=_6(n,t),a=e5.pipe(NT(e,$y({decode(e,t){return fh(new cy({message:`Encode only schema`},e,t))},encode(e,t){switch(i._tag){case`Multipart`:return fh(new cy({message:`Payload must be a FormData`},e,t));case`Json`:try{return w(iB(JSON.stringify(e),i.contentType))}catch{return fh(new oy({expected:`a JSON-serializable request body`},e,t))}case`Text`:return typeof e==`string`?w(iB(e,i.contentType)):fh(new oy({message:`Expected a string`},e,t));case`FormUrlEncoded`:return de(e)?w(oB(uv(e),i.contentType)):fh(new oy({message:`Expected a record`},e,t));case`Uint8Array`:return e instanceof Uint8Array?w(eB(e,i.contentType)):fh(new oy({message:`Expected a Uint8Array`},e,t))}}})));return r5.set(n,a),a}var a5=`~effect/http-api/HttpApiGroup`,o5={[a5]:a5,add(...e){let t={...this.endpoints};for(let n of e)Et(t,n.identifier,n);return c5({...s5(this),endpoints:t})},prefix(e){return c5({...s5(this),endpoints:ji(this.endpoints,t=>t.prefix(e))})},middleware(e){return c5({...s5(this),endpoints:ji(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return c5({...s5(this),annotations:oi(this.annotations,e)})},annotate(e,t){return c5({...s5(this),annotations:Xr(this.annotations,e,t)})},annotateEndpointsMerge(e){return c5({...s5(this),endpoints:ji(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return c5({...s5(this),endpoints:ji(this.endpoints,n=>n.annotate(e,t))})},pipe(){return e(this,arguments)}},s5=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),c5=e=>{function t(){}return Object.setPrototypeOf(t,o5),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},l5=(e,t)=>c5({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:qr()}),u5=jT([`workers`,`webhooks`,`tracing`]),d5=e=>M({added:N(e),removed:N(e),changed:N(e)});B(`@usine/orchestrator/InstanceReload`)({loops:d5(DA),agents:d5(SA),labels:d5(MA),repos:d5(H),projects:d5(pA),workers:d5(qN),settingsChanged:yT,operatorChanged:yT,quarantinedLoops:N(yX),invalidAgents:N(SX)});var f5=10,p5=class extends V(`@usine/github/LabelAdded`)(`LabelAdded`,{at:OE,label:hU}){},m5=class extends V(`@usine/github/LabelRemoved`)(`LabelRemoved`,{at:OE,label:hU}){},h5=class extends V(`@usine/github/Commented`)(`Commented`,{at:OE,url:R}){},g5=jT([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`DISMISSED`]),_5=class extends V(`@usine/github/Reviewed`)(`Reviewed`,{at:OE,url:R,state:g5}){};P([p5,m5,h5,_5]);var v5=`
310
+ __typename
311
+ ... on LabeledEvent { createdAt actor { __typename login } label { name color description } }
312
+ ... on UnlabeledEvent { createdAt actor { __typename login } label { name color description } }
313
+ ... on IssueComment { createdAt url author { __typename login } }`,y5=`
314
+ query UsineItemTimeline($owner: String!, $name: String!, $number: Int!, $since: DateTime!, $after: String) {
315
+ repository(owner: $owner, name: $name) {
316
+ issueOrPullRequest(number: $number) {
317
+ ... on Issue {
318
+ timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT]) {
319
+ pageInfo { hasNextPage endCursor }
320
+ nodes {${v5}
321
+ }
322
+ }
323
+ }
324
+ ... on PullRequest {
325
+ timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT, PULL_REQUEST_REVIEW]) {
326
+ pageInfo { hasNextPage endCursor }
327
+ nodes {${v5}
328
+ ... on PullRequestReview { createdAt submittedAt url state author { __typename login } }
329
+ }
330
+ }
331
+ }
332
+ }
333
+ }
334
+ }
335
+ `,b5=F(M({__typename:j,login:j})),x5=M({name:pU,color:mU,description:F(j)}),S5=e=>M({__typename:pT(e),createdAt:kE,actor:b5,label:x5}),C5=P([S5(`LabeledEvent`),S5(`UnlabeledEvent`),M({__typename:pT(`IssueComment`),createdAt:kE,url:R,author:b5}),M({__typename:pT(`PullRequestReview`),createdAt:kE,submittedAt:F(kE),url:R,state:jT([...g5.literals,`PENDING`]),author:b5})]),w5=M({repository:AE(M({issueOrPullRequest:AE(M({timelineItems:M({pageInfo:M({hasNextPage:yT,endCursor:F(j)}),nodes:N(F(C5))})}))}))}),T5=(e,t)=>{let n=t=>t!==null&&t.__typename===`Bot`&&t.login===e.slice(0,-5),r=e=>new hU({name:e.name,color:e.color,description:_r(e.description)});switch(t.__typename){case`LabeledEvent`:return n(t.actor)?[new p5({at:t.createdAt,label:r(t.label)})]:[];case`UnlabeledEvent`:return n(t.actor)?[new m5({at:t.createdAt,label:r(t.label)})]:[];case`IssueComment`:return n(t.author)?[new h5({at:t.createdAt,url:t.url})]:[];case`PullRequestReview`:{let e=t.state;return!n(t.author)||e===`PENDING`?[]:[new _5({at:t.submittedAt??t.createdAt,url:t.url,state:e})]}}},E5=class e extends kr()(`@usine/github/GitHubItemHistory`){static layer=Df(e,T(function*(){let e=yield*rU,t=yield*fV,n=O(`GitHubItemHistory.timelinePage`)(function*(n,r,i,a){yield*D({repository:n,item:r});let o=yield*e.installationToken(),{name:s,owner:c}=dA(n),l=yield*TU(t,o,`fetch-item-timeline`,y5,{owner:c,name:s,number:r,since:i,after:a},w5);if(x(l.repository))return yield*RH(`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 jH({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*RH(`fetch-item-timeline`,`GitHub returned hasNextPage for the timeline without an endCursor`):{nodes:f,next:b(d.endCursor)}:{nodes:f,next:y()}});return{appChanges:O(`GitHubItemHistory.appChanges`)(function*(e,t,r,i){yield*D({repository:e,item:t,actor:i});let a=v_(r),o=[],s=y(),c=0;do{let r=yield*n(e,t,a,C(s));o.push(...r.nodes),s=r.next,c+=1}while(S(s)&&c<f5);if(S(s))return yield*RH(`fetch-item-timeline`,`the timeline of ${e}#${t} since ${a} has more than ${f5} pages`);let l=o.flatMap(e=>e===null?[]:T5(i,e));return yield*A(`Read the bot's changes from an Item timeline`,{repository:e,item:t,actor:i,since:a,pages:c,timelineItems:o.length,appChanges:l.length}),l})}}))},D5=class extends V(`@usine/orchestrator/LabelAddedView`)(`LabelAdded`,{at:j,label:sJ}){},O5=class extends V(`@usine/orchestrator/LabelRemovedView`)(`LabelRemoved`,{at:j,label:sJ}){},k5=class extends V(`@usine/orchestrator/CommentedView`)(`Commented`,{at:j,url:j}){},A5=class extends V(`@usine/orchestrator/ReviewedView`)(`Reviewed`,{at:j,url:j,state:g5}){},j5=class extends V(`@usine/orchestrator/BoardMovedView`)(`BoardMoved`,{at:j,fromLane:PW,toLane:PW}){},M5=P([D5,O5,k5,A5,j5]),N5=class extends B(`@usine/orchestrator/AttemptGitHubChangesView`)({attemptId:jF,changes:N(M5)}){},P5=class extends B(`@usine/orchestrator/RunGitHubChangesView`)({attempts:N(N5)}){},F5=1e3,I5=6e4,L5=1e3,R5=1e4,z5=(e,t)=>{let n=new Map,r=[];for(let i of t){let[t,...a]=e.filter(e=>zee(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}},B5=e=>t=>{let n=h_(t.at),r=n-L5,i=h_(e.at),a=NA(e.label.name);return r-r%1e3<=i&&i<=n+R5&&(e._tag===`LabelAdded`?t.added:t.removed).some(e=>NA(e)===a)},V5=(e,t)=>{let n=new Set,r=[];for(let i of t){let t=i._tag===`LabelAdded`||i._tag===`LabelRemoved`?e.find(B5(i)):void 0;t===void 0?r.push(i):n.add(t)}return{moves:e.filter(e=>n.has(e)),rest:r}},H5=e=>new sJ({name:MA.make(e.name),color:e.color,description:C(e.description)}),U5=e=>Vk(e,{LabelAdded:({at:e,label:t})=>new D5({at:v_(e),label:H5(t)}),LabelRemoved:({at:e,label:t})=>new O5({at:v_(e),label:H5(t)}),Commented:({at:e,url:t})=>new k5({at:v_(e),url:t}),Reviewed:({at:e,url:t,state:n})=>new A5({at:v_(e),url:t,state:n})}),W5=e=>new j5({at:v_(e.at),fromLane:PW.make(e.fromLane),toLane:PW.make(e.toLane)}),G5=T(function*(){let e=yield*Eq,t=yield*E5,n=yield*rU,r=yield*b2,i=yield*Yk(new Map),a=O(`RunGitHubChanges.windowFor`)(function*(t){yield*D({attemptId:t.id,worker:t.worker});let n=WF(t);if(S(n))return n;let[r]=yield*e.transcript(new KG({attemptId:t.id,before:y(),limit:1}));return r===void 0?(yield*k(`An ended Attempt has neither an end time nor a transcript; no GitHub change is placed in it`,{attemptId:t.id}),y()):b(new UF({attemptId:t.id,startedAt:t.startedAt,endedAt:b(r.receivedAt)}))});return{read:O(`RunGitHubChanges.read`)(function*(o,s){yield*D({runId:s});let c=yield*e.inspect(s),l=eT(m4)(c.itemKey);if(x(l))return yield*A(`The Run has no GitHub Item, so it has no GitHub changes`,{runId:s}),new P5({attempts:[]});let[,,u]=l.value,d=c.repository;yield*D({repository:d,item:u});let f=e=>new P5({attempts:c.attempts.map(({id:t})=>new N5({attemptId:t,changes:e.get(t)??[]}))});if(c.attempts.length===0)return f(new Map);let{appSlug:p}=yield*n.installation(),m=YN.make(`${p}[bot]`),h=new Map(o.map(({name:e,kind:t})=>[e,dG(t,m)])),g=JSON.stringify([m,[...h].sort(([e],[t])=>e.localeCompare(t))]),_=e=>Sr(vr(h.get(e.worker)),t=>JSON.stringify([e.id,t,g])),v=yield*Xk(i),ee=new Map(c.attempts.flatMap(e=>wr(Cr(_(e),t=>Sr(vr(v.get(t)),t=>[e.id,t]))))),te=c.attempts.filter(({id:e})=>!ee.has(e));if(te.length===0)return yield*A(`Served the Run's GitHub changes from the Attempt cache`,{runId:s,attempts:c.attempts.length}),f(ee);let ne=yield*e.forItems([c.itemKey]),re=new Map([...ne.flatMap(({attempts:e})=>e),...c.attempts].map(e=>[e.id,e])),ie=new Map;for(let e of re.values()){let t=h.get(e.worker);t===void 0?yield*Cg(`Attempt worker is no longer configured; its GitHub writer is unknown`,{runId:s,attemptId:e.id,worker:e.worker}):ie.set(e.id,t)}let ae=(yield*rh([...re.values()],a)).flatMap(wr),oe=yield*Nf,se=new Map,ce=[],le=te.flatMap(e=>{let t=ae.find(({attemptId:t})=>t===e.id);return t===void 0?(se.set(e.id,[]),ce.push(e.id),[]):[t]});if(le.length>0){let e=Math.min(...le.map(({startedAt:e})=>h_(e))),n=s_(e-e%1e3),[i,a]=yield*nh([rh([...new Set([m,...le.flatMap(({attemptId:e})=>wr(vr(ie.get(e))))])],e=>t.appChanges(d,u,n,e).pipe(Th(t=>[e,t])),{concurrency:`unbounded`}),r.onItem(c.itemKey,__(n,{milliseconds:R5}))],{concurrency:`unbounded`}),o=new Map(i),l=o.get(m)??[],{moves:f,rest:p}=V5(a,l);o.set(m,p);let h=new Map;for(let[e,t]of o){let n=z5(ae.filter(({attemptId:t})=>!ie.has(t)||ie.get(t)===e),t);for(let[t,r]of n.attributed)ie.get(t)===e&&h.set(t,r);n.ambiguous.length>0&&(yield*k(`Left out GitHub changes that overlapping attempts with the same writer could each have made`,{runId:s,repository:d,item:u,actor:e,changes:n.ambiguous.length,at:n.ambiguous.map(({at:e})=>v_(e)).join(`, `)}))}for(let e of le){let t=[...(h.get(e.attemptId)??[]).map(e=>({at:h_(e.at),view:U5(e)})),...f.flatMap(t=>{let n=h_(t.at);return h_(e.startedAt)<=n&&pr(e.endedAt,{onNone:()=>!0,onSome:e=>n<=h_(e)})?[{at:n,view:W5(t)}]:[]})];se.set(e.attemptId,t.sort((e,t)=>e.at-t.at).map(({view:e})=>e)),S(e.endedAt)&&oe-h_(e.endedAt.value)>=I5&&ce.push(e.attemptId)}yield*k(`Read worker GitHub changes on a run item`,{runId:s,repository:d,item:u,since:v_(n),appChanges:i.reduce((e,[,t])=>e+t.length,0),boardMoves:a.length,boardMoveChanges:l.length-p.length,placed:le.reduce((e,{attemptId:t})=>e+(h.get(t)?.length??0),0),cachedAttempts:ce.length})}return yield*$k(i,e=>{let t=new Map(e);for(let e of te)if(ce.includes(e.id))for(let n of wr(_(e)))t.set(n,se.get(e.id)??[]);for(let e of[...t.keys()].slice(0,Math.max(0,t.size-F5)))t.delete(e);return t}),f(new Map([...ee,...se]))})}});(class e extends kr()(`@usine/orchestrator/RunGitHubChanges`){static layer=Df(e,G5)});var K5=jT([`binary`,`version`,`login`]),q5=class extends WE(`HarnessUnavailableError`)(`HarnessUnavailableError`,{harness:yA,capability:K5,message:R}){};P([class extends V(`HarnessReady`)(`HarnessReady`,{harness:yA}){},q5]),Xw(q5),sr(rr,({harness:e})=>e);var J5=class e extends kr()(`@usine/orchestrator/WorkerStatus`){static idle=Tf(e)({slots:w([]),queue:w([]),preflights:w([]),unavailable:w([]),machines:w([]),provisioning:w([])})},Y5=500,X5=O(`Board.readItems`)(function*(e,t,n){yield*D({repository:t});let r=yield*e.list(t,{limit:Y5}),i=new Set(r.map(({itemKey:e})=>e)),a=new Set(n.flatMap(({itemKey:e,repository:n,run:r})=>fA(n)===fA(t)&&bN(r.state)&&!i.has(e)?[e]:[])),o=ea(yield*rh(a,n=>e.get(n).pipe(xh(e=>x(e)?k(`Open run has no stored board item`,{repository:t,itemKey:n}):lh)),{concurrency:4}));return yield*A(`Selected board items`,{repository:t,history:r.length,additional:o.length,missing:a.size-o.length}),[...r,...o].sort((e,t)=>t.number-e.number)}),Z5=$w(mE),Q5=e=>new Qq({itemKey:e.itemKey,kind:e.kind,number:e.number,title:e.title,url:e.url,state:e.state}),$5=(e,t,n,r,i,a)=>{let o=Yi(n,({itemKey:e})=>e),s=t.map(e=>({item:e,runs:o[e.itemKey]??[],related:new Set})),c=`/${fA(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=Z5(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 t of s){if(d.has(t))continue;d.add(t);let n=[t];for(let e of n)for(let t of e.related)d.has(t)||(d.add(t),n.push(t));let r=Gi(n,({item:e},{item:t})=>(e.kind===t.kind?0:e.kind===`issue`?-1:1)||ir(e.number,t.number)),o=r[0],s=n.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)),c=s.find(({run:e})=>e.canCancel),l=n.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),p=c?.item??l[0]?.item??o.item,[m=null]=l.flatMap(({item:{number:e,url:t,state:n}})=>n===`pr-open`||n===`pr-merged`?[new $q({number:e,url:t,state:n})]:[]),h=s.find(({item:e,run:t})=>f4(t,RW(e.state)))??c??s[0],g=s.map(({run:e})=>e).reverse(),_=new eJ({...Q5(p),repository:e,title:o.item.title,labels:p.labels,items:r.map(({item:e})=>Q5(e)),pullRequest:m,runs:g,run:h?.run??null,needsYou:s.some(({item:e,run:t})=>f4(t,RW(e.state)))||n.some(({item:e})=>u.has(e.itemKey)),conflicting:p.conflicting,loops:[...new Set(r.flatMap(({item:e})=>i.get(e.itemKey)??[]))],usage:Lq(g,a)});f.push({view:_,running:c?.run.state===`Running`?c.run:void 0})}return f},e7=e=>e.flatMap(e=>`label`in e?[e.label]:[]),t7=e=>e.flatMap(e=>`state`in e?[e.state]:[]),n7=e=>[...e].sort((e,t)=>e.localeCompare(t)).map(e=>MA.make(e)).map(e=>({lane:new VW({name:PW.make(e),sources:[new zW({label:e})]}),origin:`proposed`})),r7=(e,t)=>e.lanes.length>0?e.lanes.map(e=>({lane:e,origin:`authored`})):n7(t),i7=e=>Xq.make(`${e.origin}:${e.lane.name}`),a7=(e,t)=>{let n=new Set(e.labels.map(NA));return t.find(({lane:e})=>e7(e.sources).some(e=>n.has(NA(e))))},o7=(e,t)=>t.find(({lane:t})=>t7(t.sources).includes(e.state)),s7=(e,t)=>RW(e.state)?o7(e,t):a7(e,t)??o7(e,t),c7=O(`Board.runningLane`)(function*(e,t,n,r,i){let a={repository:e.name,itemKey:t.itemKey,runId:n.id,loop:n.loop};if(yield*D(a),RW(t.state))return;let o=a7(t,r);if(o!==void 0)return yield*A(`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*A(`No Event read for the card's running Run; placing it by its Item's state`,a);return}let c=yield*c4(t.kind,s.payload).pipe(Th(b),kh(e=>Cg(`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(Eh(y()))));if(x(c))return;let l=a7({labels:c.value},r);return yield*A(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}),l7=O(`Board.project`)((e,t,n,r,i=[],a=new Map,o=new Map,s=new Map)=>T(function*(){yield*D({repository:e.name});let c=yield*rh(n,e=>u4(e).pipe(Sh)),l=[],u=[];for(let e of c)yi(e)?l.push(e.success):(u.push(e.failure),yield*wg(`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=r7(e,t),f=$5(e.name,l,r,i,a,o);yield*A(`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(i7(e),[]);let m=[];for(let{view:t,running:n}of f){let r=(n===void 0?void 0:yield*c7(e,t,n,d,s))??s7(t,d);r===void 0?m.push(t):p.get(i7(r))?.push(t)}let h=e=>e.sort((e,t)=>t.number-e.number);return new oJ({failures:u,lanes:[...d.map(e=>{let t=e7(e.lane.sources),n={id:i7(e),name:e.lane.name,sources:e.lane.sources,origin:e.origin,items:h(p.get(i7(e))??[])};return e.origin===`authored`&&t.length>0?new nJ({...n,origin:e.origin,labels:t}):new rJ(n)}),new rJ({id:Xq.make(`fallback:unmapped`),name:PW.make(`Unmapped`),sources:[],origin:`fallback`,items:h(m)})]})})),u7=500,d7=500,f7=e=>Vk(e,{GitHubPushFailure:({message:e})=>new UW({message:e}),InfraFailure:({message:e})=>new WW({message:e}),ProviderCapacityFailure:({message:e})=>new GW({message:e}),DefectFailure:({message:e})=>new KW({message:e}),AgentFailure:({message:e})=>new qW({message:e}),BlockedFailure:({message:e})=>new JW({message:e}),QuestionFailure:({question:e})=>new YW({question:e}),RunawayFailure:({ceiling:e})=>new XW({ceiling:e}),ChildSessionBudgetFailure:({attemptedChildren:e,maxChildren:t})=>new ZW({attemptedChildren:e,maxChildren:t})}),p7=e=>Vk(e,{Succeeded:()=>new $W,Failed:({failure:e})=>new eG({failure:f7(e)}),Canceled:()=>new tG}),m7=e=>{switch(e.kind){case`local`:return new rG;case`ssh`:return pr(e.provisioner,{onSome:({provider:e})=>new aG({provider:e}),onNone:()=>new iG({destination:mr(e.destination,()=>QN.make(e.name)),port:C(e.port)})});case`exe.dev`:return new iG({destination:QN.make(`${e.name}.exe.xyz`),port:null});case`cloudflare`:return new oG}},h7=e=>new Map(e.map(e=>[e.name,m7(e)])),g7=(e,t)=>new cG({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:v_(e.startedAt),outcome:pr(e.outcome,{onNone:()=>null,onSome:p7}),endedAt:pr(e.endedAt,{onNone:()=>null,onSome:v_}),salvage:C(e.salvage),start:C(e.start),reattachedAt:pr(e.reattachedAt,{onNone:()=>null,onSome:v_}),outOfMemory:C(e.outOfMemory)});O(`Operator.readUnrecordedEnds`)(function*(e,t){let n=yield*rh(t.attempts.filter(e=>S(e.outcome)&&x(e.endedAt)),t=>e.transcript(new KG({attemptId:t.id,before:y(),limit:1})).pipe(Th(e=>[t.id,e.at(-1)?.receivedAt])),{concurrency:4});return new Map(n.flatMap(([e,t])=>t===void 0?[]:[[e,t]]))});var _7=O(`Operator.readRunningEvents`)(function*(e,t){let n=t.flatMap(({run:e})=>e.state._tag===`Running`?[e.id]:[]),r=yield*e.events(n);return yield*A(`Read the Events of the running Runs`,{running:n.length,events:r.length}),new Map(r.map(({runId:e,event:t})=>[e,t]))}),v7=(e,t,n,r=new Map)=>{let i=CN(e.run.state),a=C(e.step.result),o=a?.facts.find(e=>e._tag===`PullRequest`);return new Wq({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,providerRetry:C(YF(e.run.state,e.attempts)),loopPaused:t.has(e.run.loop),machineWait:i.canCancel?r.get(e.run.id)??null:null,openedAt:v_(e.run.openedAt),closedAt:pr(e.closedAt,{onNone:()=>null,onSome:v_}),task:e.task,attempts:e.attempts.map(e=>g7(e,n)),approval:pr(e.approval,{onNone:()=>null,onSome:({approvedAt:e,source:t})=>new Uq({approvedAt:v_(e),source:C(t)})}),runAgain:C(e.runAgain),resultMessage:a?.message??null,pullRequestUrl:o?.url.toString()??null,...i,canResolveFailure:i.canResolveFailure&&!Er(e.resolvedFailureAttemptId,e.attempts.at(-1)?.id)})},y7=e=>Vk(e,{Started:e=>e,SessionEvent:e=>e,Final:e=>e,Failed:({failure:e})=>new qG({failure:f7(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}),b7=e=>{let t={sequence:e.sequence,attemptId:e.attemptId,receivedAt:v_(e.receivedAt),direction:e.direction,payload:y7(e.envelope.payload)};return e.envelope._tag===`InboundEnvelope`&&`target`in e.envelope?new YG({...t,target:e.envelope.target,operator:e.envelope.operator}):new YG(t)},x7=e=>[...e].sort((e,t)=>e.sequence-t.sequence).map(b7),S7=O(`Operator.readTranscriptPage`)(function*(e,t,n){yield*D({attemptId:t,before:C(n)});let r=yield*e.transcript(new KG({attemptId:t,before:n,limit:501})),i=r.length>u7,a=i?r.slice(1):r,o=a[0];return yield*A(`Read operator transcript page`,{attemptId:t,before:C(n),returned:a.length,hasEarlier:i}),{events:x7(a),earlier:i&&o!==void 0?[new XG({attemptId:t,before:o.sequence})]:[]}});O(`Operator.readTranscript`)(function*(e,t,n){yield*D({runId:t.run.id,request:n._tag});let r=yield*Vk(n,{ColdTranscriptRequest:()=>rh(t.attempts,t=>S7(e,t.id,y()),{concurrency:4}).pipe(Th(e=>({events:e.flatMap(({events:e})=>e).sort((e,t)=>e.sequence-t.sequence),earlier:e.flatMap(({earlier:e})=>e)}))),TailTranscriptRequest:({after:n})=>rh(t.attempts,t=>e.transcript(new GG({attemptId:t.id,after:n,limit:d7})),{concurrency:4}).pipe(Th(e=>({events:x7(e.flat()).slice(0,d7),earlier:[]}))),EarlierTranscriptRequest:({attemptId:n,before:r})=>t.attempts.some(e=>e.id===n)?S7(e,n,b(r)):new eK({runId:t.run.id,attemptId:n})});return yield*A(`Read operator transcript`,{runId:t.run.id,request:n._tag,events:r.events.length,earlier:r.earlier.length}),r});var C7=class extends B(`@usine/orchestrator/TaskItemView`)({...Qq.fields,labels:N(MA),conflicting:yT}){},w7=class extends B(`@usine/orchestrator/TaskLaneView`)({id:Xq,name:PW}){},T7=class extends B(`@usine/orchestrator/TaskCommentView`)({runId:LN,kind:VN,url:j,postedAt:F(j),attemptEndedAt:F(j)}){},E7=class extends B(`@usine/orchestrator/TaskView`)({repository:H,number:SI,title:j,current:xI,lane:w7,needsYou:yT,items:kT(C7),runs:N(Wq),comments:N(T7)}){},D7=pr({onNone:()=>null,onSome:v_}),O7=e=>{let t=(t,n)=>new T7({runId:e.run.id,kind:t.kind,url:t.url.toString(),postedAt:D7(t.at),attemptEndedAt:D7(n)}),n=Wi(e.attempts,e=>Dr(e.outcome,({_tag:e})=>e===`Succeeded`)).pipe(Cr(({endedAt:e})=>e)),r=pr(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 na([...r,...i].sort((e,t)=>a(t).localeCompare(a(e))),(e,t)=>e.url===t.url)},k7=T(function*(){let e=yield*Eq,t=yield*J5,n=yield*f2,r=yield*o2,i=yield*qz,a=yield*b0;return{read:O(`TaskReader.read`)(function*(o,s,c){yield*D({repository:s,item:c});let l=RX(o.config).find(({name:e})=>fA(e)===fA(s));if(l===void 0)return yield*k(`Task read refused; the repository is not a registered Project`,{repository:s,item:c}),yield*new cJ({repository:s});let[u,d,f,p,m]=yield*nh([e.list({closedLimit:0}).pipe(E(e=>X5(r,l.name,e))),i.get(l.name),n.states,a.asks(),t.provisioning],{concurrency:`unbounded`}),h=yield*e.forItems(u.map(({itemKey:e})=>e)),g=yield*_7(e,h),_=new Set(f.filter(e=>e.paused).map(e=>e.loop)),v=h7(o.config.workers),ee=TG(m),te=(yield*l7(l,pr(d,{onNone:()=>[],onSome:({labels:e})=>e.map(({name:e})=>e)}),u,h.map(e=>v7(e,_,v,ee)),p.map(({itemKey:e})=>e),new Map,new Map,g)).lanes.flatMap(e=>e.items.map(t=>({lane:e,task:t}))).find(({task:e})=>e.items.some(e=>e.number===c));if(te===void 0)return yield*k(`Task read found no task in the selected board items`,{repository:l.name,item:c,selectedItems:u.length}),yield*new lJ({repository:l.name,item:c});let{lane:ne,task:re}=te,ie=new Set(re.items.map(({itemKey:e})=>e)),ae=yield*rh(u.filter(({itemKey:e})=>ie.has(e)),e=>u4(e).pipe(Sh)),oe=new Map;for(let e of ae){if(vi(e)){yield*wg(`Task Item could not be projected; the other Items are shown`,{repository:l.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:c}=e.success;oe.set(t,new C7({itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:c}))}let[se,...ce]=re.items.flatMap(({itemKey:e})=>{let t=oe.get(e);return t===void 0?[]:[t]});if(se===void 0)return yield*new lJ({repository:l.name,item:c});let le=new Set(re.runs.map(({id:e})=>e)),ue=h.filter(({run:e})=>le.has(e.id)).sort((e,t)=>h_(t.run.openedAt)-h_(e.run.openedAt)||t.run.id.localeCompare(e.run.id)).flatMap(O7),de=new E7({repository:l.name,number:se.number,title:re.title,current:re.itemKey,lane:new w7({id:ne.id,name:ne.name}),needsYou:re.needsYou,items:[se,...ce],runs:[...re.runs].reverse(),comments:ue});return yield*A(`Read a Task`,{repository:l.name,item:c,origin:de.number,lane:ne.name,items:de.items.length,runs:de.runs.length,comments:ue.length}),de})}});(class e extends kr()(`@usine/orchestrator/TaskReader`){static layer=Df(e,k7)});var A7=class extends B(`@usine/orchestrator/LoopSelectorView`)({repos:F(N(H)),tags:F(N(RJ))}){},j7=class extends B(`@usine/orchestrator/LoopFileView`)({name:DA,file:wJ,stream:fX,condition:vJ,cron:F(oX),timeZone:F(sX),selector:F(A7),repositories:N(H),approval:kA,maxCycles:CI,permissions:jA,priority:F(_X),step:GN,agent:SA,prompt:hX,paused:yT,undeclaredLabels:N(MA)}){},M7=class extends B(`@usine/orchestrator/QuarantinedLoopView`)({name:R,file:wJ,error:DJ}){},N7=class extends B(`@usine/orchestrator/AgentFileView`)({name:SA,file:wJ,harness:yA,model:vA,effort:bA,parentModel:F(vA),parentEffort:F(bA),resolvedParentModel:F(vA),resolvedParentEffort:bA,persona:CA,loops:N(DA)}){},P7=class extends B(`@usine/orchestrator/InvalidAgentView`)({name:R,file:wJ,error:DJ}){},F7=class extends B(`@usine/orchestrator/GatewayView`)({domain:nP,destination:QN,adminPort:rP,adminTokenEnv:R,llmProviders:N(iP)}){},I7=class extends B(`@usine/orchestrator/WorkerSlotsView`)({capacity:L,leased:L}){},L7=class extends V(`@usine/orchestrator/PassedCheckView`)(`Passed`,{checkedAt:j}){},R7=class extends V(`@usine/orchestrator/DegradedCheckView`)(`Degraded`,{checkedAt:j,message:j}){},z7=class extends V(`@usine/orchestrator/DeferredCheckView`)(`Deferred`,{checkedAt:j,message:j}){},B7=class extends V(`@usine/orchestrator/FailedCheckView`)(`Failed`,{checkedAt:j,capability:F(pG),message:j}){},V7=P([L7,R7,z7,B7]),H7=class extends B(`@usine/orchestrator/HarnessPreflightView`)({harness:yA,check:V7}){},U7=class extends B(`@usine/orchestrator/ContainerView`)({image:F(oP),cpus:F(cP),memoryMib:F(lP),pids:F(uP)}){},W7=class extends B(`@usine/orchestrator/WorkerConfigurationView`)({name:qN,kind:JN,maxConcurrentAttempts:L,destination:F(QN),port:F($N),identityFile:F(eP),root:F(tP),gateway:F(F7),container:F(U7),containerLimits:F(dP).pipe(IT(w(null))),provisioner:F(AG).pipe(IT(w(null))),machines:N(EG).pipe(IT(w([]))),provisioning:F(DG).pipe(IT(w(null))),slots:F(I7),prerequisites:F(V7),harnesses:N(H7)}){},G7=class extends B(`@usine/orchestrator/RemovedWorkerView`)({name:qN,running:L}){},K7=class extends B(`@usine/orchestrator/LabelStateView`)({name:MA,onGitHub:F(yT),color:F(j),description:F(j),declared:yT,failure:F(OW)}){},q7=class extends V(`@usine/orchestrator/LabelLaneSourceView`)(`Label`,{label:K7}){},J7=class extends V(`@usine/orchestrator/StateLaneSourceView`)(`State`,{state:FW}){},Y7=P([q7,J7]),X7=class extends B(`@usine/orchestrator/LaneConfigurationView`)({name:PW,sources:N(Y7)}){},Z7=class extends B(`@usine/orchestrator/RepositoryConfigurationView`)({name:H,tags:N(RJ),lanes:N(X7),declaredLabels:N(K7),loops:N(DA)}){},Q7=class extends B(`@usine/orchestrator/SettingsView`)({pollInterval:L,maxChildren:L,maxAttemptMinutes:F(L),maxAttemptTokens:F(L),parentModel:F(vA),parentEffort:F(bA),operator:F(ZM),webhooks:jT([`off`,`deliveries`,`endpoint`]),webhooksPublicUrl:F(j),lastHintAt:F(j),tracing:F(M({otlpUrl:j,serviceName:j}))}){},$7=class extends B(`@usine/orchestrator/ConfigurationView`)({projects:N(LJ).pipe(RT(w([])),IT(w([]))),labels:N(IA),loops:N(j7),quarantinedLoops:N(M7),agents:N(N7),invalidAgents:N(P7),workers:N(W7),removedWorkers:N(G7),repositories:N(Z7),settings:Q7}){},e9=e=>{let t=e.slice(e.lastIndexOf(`/`)+1).replace(/\.md$/u,``);return t===``?e:t},t9=e=>Vk(e,{Passed:({checkedAt:e})=>new L7({checkedAt:v_(e)}),Degraded:({checkedAt:e,message:t})=>new R7({checkedAt:v_(e),message:t}),Deferred:({checkedAt:e,message:t})=>new z7({checkedAt:v_(e),message:t}),Failed:({checkedAt:e,capability:t,message:n})=>new B7({checkedAt:v_(e),capability:C(t),message:n})}),n9=e=>e.kind===`ssh`?{destination:C(e.destination),provisioner:NG(e),port:C(e.port),identityFile:C(e.identityFile),root:e.root,gateway:pr(e.gateway,{onNone:()=>null,onSome:e=>new F7({domain:e.domain,destination:e.destination,adminPort:e.adminPort,adminTokenEnv:e.adminTokenEnv,llmProviders:e.llmProviders})}),container:new U7({image:C(e.container.image),cpus:C(e.container.cpus),memoryMib:C(e.container.memoryMib),pids:C(e.container.pids)})}:{destination:null,provisioner:null,port:null,identityFile:null,root:null,gateway:null,container:null},r9=T(function*(){let e=yield*f2,t=yield*qz,n=yield*K4,r=yield*J5,i=O(`OperatorConfiguration.repository`)(function*(e,n,r){let i=Sr(yield*t.get(n.name),({labels:e})=>new Map(e.map(e=>[NA(e.name),e]))),a=new Map(e.config.labels.map(e=>[NA(e.name),e])),o=e=>{let t=NA(e),o=Cr(i,e=>_r(e.get(t))),s=a.get(t);return new K7({name:e,onGitHub:pr(i,{onNone:()=>null,onSome:()=>S(o)}),color:C(hr(Cr(o,({color:e})=>e),()=>Cr(_r(s),({color:e})=>e))),description:C(hr(Cr(o,({description:e})=>e),()=>Cr(_r(s),({description:e})=>e))),declared:s!==void 0,failure:r.find(e=>e.repository===n.name&&NA(e.label)===t)??null})};return new Z7({name:n.name,tags:n.tags,lanes:(RX(e.config).find(({name:e})=>e===n.name)?.lanes??[]).map(e=>new X7({name:e.name,sources:e.sources.map(e=>`label`in e?new q7({label:o(e.label)}):new J7({state:e.state}))})),declaredLabels:e.config.labels.map(({name:e})=>o(e)),loops:e.loops.filter(t=>LX(e.config,t,n)).map(({name:e})=>e)})});return{view:O(`OperatorConfiguration.view`)(function*(t){let{config:a}=t,[o,s,c,l,u,d]=yield*nh([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=pr(s,{onNone:()=>[],onSome:({preflightFindings:e})=>e}),m=yield*rh(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 j7({name:e.name,file:bX(e.name),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:pr(e.selector,{onNone:()=>null,onSome:({repos:e,tags:t})=>new A7({repos:C(e),tags:C(t)})}),repositories:a.repos.filter(n=>LX(t.config,e,n)).map(({name:e})=>e),approval:e.approval,maxCycles:e.maxCycles,permissions:e.permissions,priority:C(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 N7({name:e.name,file:wJ.make(`agents/${e.name}.md`),harness:e.harness,model:e.model,effort:e.effort,parentModel:C(e.parentModel),parentEffort:C(e.parentEffort),resolvedParentModel:C(TA(e.agent,a.settings.parentModel)),resolvedParentEffort:EA(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 W7({name:e.name,kind:e.kind,maxConcurrentAttempts:e.maxConcurrentAttempts,...n9(e),slots:t===void 0?null:new I7({capacity:t.capacity,leased:t.leased}),prerequisites:n===void 0?null:C(Sr(n.prerequisites,t9)),harnesses:(n?.harnesses??[]).map(({harness:e,check:t})=>new H7({harness:e,check:t9(t)})),containerLimits:n===void 0?null:C(n.containerLimits),machines:u.filter(t=>t.worker===e.name).map(jG),provisioning:C(Sr(_r(d.find(t=>t.worker===e.name)),MG))})}),{settings:re,webhooks:ie,tracing:ae}=a,oe=new $7({projects:a.projects,labels:t.config.labels,loops:g,quarantinedLoops:t.quarantinedLoops.map(({file:e,error:t})=>new M7({name:e9(e),file:e,error:t})),agents:_,invalidAgents:t.invalidAgents.map(({file:e,error:t})=>new P7({name:e9(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 G7({name:e,running:t})),repositories:m,settings:new Q7({pollInterval:re.pollInterval,maxChildren:re.maxChildren,maxAttemptMinutes:C(re.maxAttemptMinutes),maxAttemptTokens:C(re.maxAttemptTokens),parentModel:C(re.parentModel),parentEffort:C(re.parentEffort),operator:C(a.operator),webhooks:ie.mode,lastHintAt:C(Sr(yield*n.lastHint,v_)),webhooksPublicUrl:ie.mode===`endpoint`?ie.publicUrl.href:null,tracing:pr(ae,{onNone:()=>null,onSome:({otlpUrl:e,serviceName:t})=>({otlpUrl:e.href,serviceName:t})})})});return yield*A(`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 kr()(`@usine/orchestrator/OperatorConfiguration`){static layer=Df(e,r9)});var i9=class e extends kr()(`@usine/orchestrator/LoopMatches`){static layer=Df(e,T(function*(){let e=yield*CJ;return{matching:O(`LoopMatches.matching`)(function*(e,t,n){yield*D({repository:t.name,items:n.length});let r=e.loops.filter(n=>n.trigger.on!==`schedule`&&LX(e.config,n,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*Sh(w4(e,t,n.map(({payload:e})=>e)));if(vi(r)){o+=n.length,yield*A(`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 mee(n,r.success))yi(a)?a.success&&s.add(i):(o+=1,yield*A(`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*A(`Matched Loop triggers against stored Items`,{repository:t.name,loops:r.length,items:n.length,matches:s.length,failures:o}),s},Qh(CJ,e))}}))},a9=200,o9=10,s9=100,qee=500,c9=class extends V(`@usine/orchestrator/WorkerSilentView`)(`WorkerSilent`,{worker:qN,lastAnsweredAt:j}){},l9=class extends V(`@usine/orchestrator/ProviderRetryingView`)(`ProviderRetrying`,{agent:SA,message:R,retries:rF,since:j}){},Jee=P([c9,l9]),u9=class extends B(`@usine/orchestrator/RunningAttemptView`)({run:Wq,attempt:cG,item:F(Qq),lastActivityAt:F(j),warnings:N(Jee)}){},d9=class extends V(`@usine/orchestrator/SuppressedForOperatorView`)(`SuppressedForOperator`,{run:Wq}){},f9=class extends V(`@usine/orchestrator/ClosedUnchangedView`)(`ClosedUnchanged`,{run:Wq}){},p9=class extends V(`@usine/orchestrator/RunFailedView`)(`RunFailed`,{run:Wq}){},m9=class extends V(`@usine/orchestrator/LoopPausedView`)(`LoopPaused`,{}){},h9=class extends V(`@usine/orchestrator/CycleBudgetUsedUpView`)(`CycleBudgetUsedUp`,{ask:kI}){},g9=class extends V(`@usine/orchestrator/AwaitingApprovalView`)(`AwaitingApproval`,{run:Wq}){},_9=class extends V(`@usine/orchestrator/QueuedForWorkerView`)(`QueuedForWorker`,{run:Wq,ahead:F(L.check($T(0))),priority:F(gX).pipe(IT(w(null))),creating:F(EG).pipe(IT(w(null)))}){},v9=class extends V(`@usine/orchestrator/WaitingForStopView`)(`WaitingForStop`,{run:Wq,stop:Jq}){},y9=class extends V(`@usine/orchestrator/AwaitingPollView`)(`AwaitingPoll`,{}){},Yee=P([g9,d9,h9,p9,f9,m9,v9,_9,y9]),b9=class extends B(`@usine/orchestrator/StalledItemView`)({repository:H,loop:DA,item:Qq,reason:Yee}){},x9=class extends B(`@usine/orchestrator/ClosedRunView`)({run:Wq,item:F(Qq),closedAt:j}){},S9=class extends B(`@usine/orchestrator/WorkerView`)({name:qN,slots:I7,preflight:F(V7),machines:N(EG).pipe(IT(w([]))),provisioning:F(DG).pipe(IT(w(null)))}){},C9=class extends B(`@usine/orchestrator/RepositoryPollView`)({repository:H,polledAt:F(j)}){},w9=class extends B(`@usine/orchestrator/DeskView`)({running:N(u9),notMoving:N(b9),lastOutcomes:N(x9),workers:N(S9),polls:N(C9)}){},Xee=({runs:e,sighting:t,paused:n,ask:r,queue:i,creating:a,stop:o})=>{let s=e.find(({state:e})=>TN.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 v9({run:s,stop:o.value}));switch(s.state){case`Running`:return y();case`Waiting`:return b(new g9({run:s}));default:return b(new _9({run:s,ahead:i.get(s.id)?.ahead??null,priority:i.get(s.id)?.position.priority??null,creating:a.get(s.id)??null}))}}if(n)return b(new m9);let c=t=>_r(e.find(({id:e})=>e===t)),l=Cr(Cr(t,({suppressedBy:e})=>e),c);if(S(l))return b(new d9({run:l.value}));if(S(r))return b(new h9({ask:r.value}));let u=Cr(Cr(t,({run:e})=>e),c);return S(u)?b(u.value.state===`Failed`?new p9({run:u.value}):new f9({run:u.value})):b(new y9)},Zee=[`AwaitingApproval`,`SuppressedForOperator`,`CycleBudgetUsedUp`,`RunFailed`,`ClosedUnchanged`,`LoopPaused`,`WaitingForStop`,`QueuedForWorker`,`AwaitingPoll`],Qee=or([sr(ir,({reason:e})=>Zee.indexOf(e._tag)),sr(rr,({repository:e})=>e),sr(ar(ir),({item:e})=>e.number),sr(rr,({loop:e})=>e)]),$ee=({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`)},ete=e=>{let t=null,n=new Map,r=null;for(let i of e){$ee(i)&&(r=i);let e=i.envelope.payload;if(e._tag===`WorkerUnresponsive`)t=new c9({worker:e.worker,lastAnsweredAt:v_(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 l9({agent:t.session.agent,message:t.message,retries:t.retries,since:n.get(t.session.id)?.since??v_(i.receivedAt)})):(t._tag===`ProviderRecovered`||t._tag===`SessionIdle`||t._tag===`SessionFinished`)&&n.delete(t.session.id)}}return{lastActivityAt:r===null?null:v_(r.receivedAt),warnings:[...t===null?[]:[t],...n.values()]}},T9=e=>h_(e.checkedAt),tte=e=>{let t=[...wr(e.prerequisites),...e.harnesses.map(({check:e})=>e)],n=t.filter(({_tag:e})=>e===`Failed`),r=t.filter(({_tag:e})=>e===`Degraded`);return _r((n.length>0?n:r.length>0?r:t).reduce((e,t)=>e===void 0||T9(t)>T9(e)?t:e,void 0))},nte=e=>{let t=e.attempts.at(-1);return e.closedAt??t?.endedAt??t?.startedAt??e.openedAt},rte=({run:e,attempts:t})=>t.length===0&&e.state._tag===`Canceled`&&e.state.reason._tag!==`OperatorCanceled`,ite=T(function*(){let e=yield*Eq,t=yield*f2,n=yield*b0,r=yield*o2,i=yield*K4,a=yield*i9,o=yield*J5,s=yield*D2,c=O(`Operator.desk.recentActivity`)(function*(t){yield*D({attemptId:t.id});let[n,r]=yield*nh([e.transcript(new KG({attemptId:t.id,before:y(),limit:a9})),e.transcript(new UG({attemptId:t.id}))],{concurrency:`unbounded`});return ete([...n,...r])});return{desk:O(`Operator.desk`)(function*(l){let[u,d,f,p,m,h,g,_,v,ee,te]=yield*nh([e.list({closedLimit:0}),e.closed({limit:s9}),t.states,n.asks(),o.slots,o.queue,o.preflights,i.latest,s.list,o.machines,o.provisioning],{concurrency:`unbounded`}),ne=TG(te),re=ee.map(jG),ie=new Map(re.flatMap(e=>e.state===`creating`&&e.runId!==null?[[e.runId,e]]:[])),ae=new Map(h.map(e=>[e.runId,e])),oe=new Set(f.filter(e=>e.paused).map(e=>e.loop)),se=h7(l.config.workers),ce=yield*rh(l.config.repos,e=>T(function*(){let t=yield*r.list(e.name,{limit:qee});return{repository:e,items:t,matches:yield*a.matching(l,e,t)}}),{concurrency:4}),le=new Map;for(let{items:e}of ce)for(let t of e){let e=yield*Sh(u4(t));if(vi(e))continue;let{itemKey:n,kind:r,number:i,title:a,url:o,state:s}=e.success;le.set(n,new Qq({itemKey:n,kind:r,number:i,title:a,url:o,state:s}))}let ue=ce.flatMap(({matches:e})=>e),de=[...new Set(ue.map(({item:e})=>e.itemKey))],[fe,pe]=yield*nh([e.forItems(de),e.sightings(de)],{concurrency:`unbounded`}),me=new Map([...u,...fe].map(e=>[e.run.id,v7(e,oe,se,ne)])),he=[...me.values()].sort((e,t)=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),ge=e=>Cr(_r(v.find(t=>t.itemKey===e)),e=>Sr(_r(me.get(e.runId)?.attempts.find(({id:t})=>t===e.attemptId)),({number:t})=>new Jq({runId:e.runId,attemptNumber:t,worker:e.worker}))),_e=[];for(let{loop:e,item:t}of ue){let n=le.get(t.itemKey);if(n===void 0)continue;let r=Xee({runs:he.filter(n=>n.loop===e.name&&n.itemKey===t.itemKey),sighting:_r(pe.find(n=>n.loop===e.name&&n.itemKey===t.itemKey)),paused:oe.has(e.name),ask:_r(p.find(({itemKey:e})=>e===t.itemKey)),queue:ae,creating:ie,stop:ge(t.itemKey)});x(r)||(yield*A(`Matched Item is not moving`,{repository:t.repository,loop:e.name,item:t.number,reason:r.value._tag,...Vk(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:()=>({})})}),_e.push(new b9({repository:t.repository,loop:e.name,item:n,reason:r.value})))}let ve=yield*rh(he.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})=>Th(c(t),n=>new u9({run:e,attempt:t,item:le.get(e.itemKey)??null,...n})),{concurrency:4}),ye=d.filter(e=>!rte(e)).map(e=>{let t=v7(e,oe,se,ne);return new x9({run:t,item:le.get(t.itemKey)??null,closedAt:nte(t)})}).sort((e,t)=>t.closedAt.localeCompare(e.closedAt)).slice(0,o9),be=new Map(m.map(e=>[e.worker,e])),xe=new Map(g.map(e=>[e.worker,e])),Se=new Set(l.config.workers.map(({name:e})=>e)),Ce=[...l.config.workers.map(({name:e})=>e),...m.map(({worker:e})=>e).filter(e=>!Se.has(e))].map(e=>{let t=be.get(e),n=xe.get(e);return new S9({name:e,slots:new I7({capacity:t?.capacity??l.config.workers.find(t=>t.name===e)?.maxConcurrentAttempts??0,leased:t?.leased??0}),preflight:C(Sr(Cr(_r(n),tte),t9)),machines:re.filter(t=>t.worker===e),provisioning:C(Sr(_r(te.find(t=>t.worker===e)),MG))})}),we=pr(_,{onNone:()=>[],onSome:({repositoryPolls:e})=>e}),Te=l.config.repos.map(({name:e})=>{let t=we.find(({repository:t})=>fA(t)===fA(e));return new C9({repository:e,polledAt:t===void 0?null:v_(t.completedAt)})});return yield*A(`Built the operator desk`,{running:ve.length,matches:ue.length,notMoving:_e.length,lastOutcomes:ye.length,workers:Ce.length}),new w9({running:ve,notMoving:[..._e].sort(Qee),lastOutcomes:ye,workers:Ce,polls:Te})})}});(class e extends kr()(`@usine/orchestrator/OperatorDesk`){static layer=Df(e,ite).pipe(Mf(i9.layer))});var E9=L.check($T(0)),D9=L.check($T(1)),O9=L.check($T(0)),k9=KT.check(eE({minimum:0,maximum:1})),A9=j.check(GT(/^\d{4}-\d{2}-\d{2}$/u,{message:`Expected a UTC day as YYYY-MM-DD`})),j9=jT([`7d`,`30d`,`all`]),M9=jT([`day`,`week`]),ate=class extends B(`@usine/orchestrator/TaskDoneView`)({repository:H,number:SI,mergedAt:j,durationMillis:O9}){},ote=class extends B(`@usine/orchestrator/TaskPeriodView`)({start:A9,tasks:E9,medianMillis:F(O9),firstTimeRight:E9,operatorActions:E9}){},N9=class extends B(`@usine/orchestrator/LoopShareView`)({loop:DA,share:k9}){},ste=class extends B(`@usine/orchestrator/LoopRunTimeView`)({loop:DA,runs:D9,medianMillis:O9}){},cte=class extends B(`@usine/orchestrator/TaskTimeView`)({tasks:D9,loops:N(N9),waiting:k9,runs:N(ste)}){},lte=class extends B(`@usine/orchestrator/TaskCostView`)({tasks:D9,medianUsd:KP,estimate:yT}){},ute=class extends B(`@usine/orchestrator/TaskTokensView`)({tasks:D9,medianTokens:MP,loops:N(N9),cost:F(lte)}){},dte=class extends B(`@usine/orchestrator/UntimedTasksView`)({tasks:D9,before:A9}){},fte=class extends B(`@usine/orchestrator/StatisticsView`)({window:j9,from:j,to:j,bucket:M9,loops:N(DA),tasks:N(ate),medianMillis:F(O9),periods:N(ote),firstTimeRight:E9,operatorActions:E9,time:F(cte),tokens:F(ute),untimed:F(dte),unmetered:E9}){},P9=class extends B(`@usine/orchestrator/DurationSummaryView`)({count:D9,medianMillis:O9}){},F9=class extends B(`@usine/orchestrator/OutcomeCountsView`)({succeeded:E9,failed:E9,canceled:E9}){},pte=class extends B(`@usine/orchestrator/PoolTokensView`)({pool:XP,tokens:MP}){},mte=class extends B(`@usine/orchestrator/CostSummaryView`)({usd:KP,meanUsd:KP,estimate:yT,priced:D9}){},hte=class extends B(`@usine/orchestrator/UsageSummaryView`)({measured:E9,tokens:MP,meanTokens:F(MP),pools:N(pte),cost:F(mte)}){},I9={outcomes:F9,time:F(P9),usage:hte},gte=class extends B(`@usine/orchestrator/LoopStatisticsView`)({loop:DA,...I9}){},_te=class extends B(`@usine/orchestrator/AgentStatisticsView`)({agent:SA,...I9}){},vte=class extends B(`@usine/orchestrator/BrainStatisticsView`)({brain:xA,...I9}){},L9=class extends B(`@usine/orchestrator/ThroughputPeriodView`)({start:A9,...F9.fields}){},yte=class extends B(`@usine/orchestrator/WorkerQueueWaitView`)({worker:qN,wait:P9}){},bte=class extends B(`@usine/orchestrator/AttemptCountView`)({attempts:D9,runs:E9}){},xte=class extends B(`@usine/orchestrator/WorkerUtilizationView`)({worker:qN,slots:D9,occupiedMillis:O9,share:k9}){},Ste=class extends B(`@usine/orchestrator/NeedsAttentionPeriodView`)({start:A9,approvals:E9,failures:E9}){},Cte=class extends B(`@usine/orchestrator/NeedsAttentionView`)({approvals:E9,failures:E9,periods:N(Ste),approvalWait:F(P9),retryWait:F(P9),resolutionWait:F(P9),failureWait:F(P9)}){},wte=class extends B(`@usine/orchestrator/RunStatisticsView`)({window:j9,from:j,to:j,bucket:M9,runs:F9,runTime:F(P9),attemptTime:F(P9),unmeasuredAttempts:E9,throughput:N(L9),loops:N(gte),agents:N(_te),brains:N(vte),queueWait:N(yte),attemptsPerRun:N(bte),utilization:N(xte),needsAttention:Cte}){},R9={UpgradeError:409,ConfigurationNotFound:404,ConfigurationStoreError:500,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},z9=class extends UE(`@usine/orchestrator/OperatorHttpError`)({error:jT(Mi(R9)).annotate({description:`Domain failure tag that selects the HTTP status.`}),message:j.annotate({description:`Diagnostic text safe to show to the operator.`})}){get status(){return R9[this.error]}},Tte=[...new Set(Object.values(R9))].map(e=>z9.check(WT(t=>t.status===e)).annotate({httpApiStatus:e})),Ete=class extends g8()(`@usine/orchestrator/OperatorHttpPolicy`,{error:Tte}){},Dte=P([VT(`WorkerCapabilityError`,{worker:qN,capability:pG,message:j}),VT(`ExecutorOperationError`,{operation:fG,message:j}),VT(`CredentialUnavailableError`,{repository:H,message:j})]),Ote=class extends UE(`@usine/orchestrator/RestartRequiredRefusal`)({error:pT(`RestartRequiredError`),message:j,blocks:kT(u5),fields:kT(R)},{httpApiStatus:409}){},kte=class extends UE(`@usine/orchestrator/ReloadPreflightRefusal`)({error:pT(`ReloadPreflightError`),message:j,agents:N(SA),workers:N(qN),cause:Dte},{httpApiStatus:409}){},Ate=class extends UE(`@usine/orchestrator/FactoryConfigRefusal`)({error:pT(`FactoryConfigError`),message:j,file:wJ,stage:TJ},{httpApiStatus:422}){},B9=class extends UE(`StaleRevisionRefusal`)({error:pT(`StaleRevision`),message:j,expected:AX,current:AX},{httpApiStatus:409}){},V9=class extends UE(`ConfigurationInvalidRefusal`)({error:pT(`ConfigurationInvalid`),message:j,problems:kT(M({entity:NX,...EJ.fields}))},{httpApiStatus:422}){},H9=class extends UE(`ConfigurationRevertRefusal`)({error:pT(`ConfigurationRevertBlocked`),message:j,entities:kT(NX)},{httpApiStatus:409}){},U9=[B9,V9,H9,Ote,kte,Ate],W9={number:vE.pipe(NT(AX))},G9=F3.fields,K9=lT(mT),q9=P([j,kT(j).pipe(NT(j,eb({decode:e=>e[0],encode:e=>[e]})))]),J9=q9.pipe(NT(vE),NT(PG)),jte=P([M({after:K9,before:K9,attempt:K9}).pipe(NT(dT(ZG),eb({decode:()=>new ZG,encode:()=>({})}))),M({after:J9,before:K9,attempt:K9}).pipe(NT(dT(QG),eb({decode:({after:e})=>new QG({after:e}),encode:({after:e})=>({after:e})}))),M({after:K9,before:J9,attempt:q9.pipe(NT(jF))}).pipe(NT(dT($G),eb({decode:({before:e,attempt:t})=>new $G({before:e,attemptId:t}),encode:({before:e,attemptId:t})=>({before:e,attempt:t})})))]),Y9=j.check(GT(/^[A-Za-z0-9_.-]+$/u,{message:`Expected a repository path segment`})),X9=M({ok:pT(!0)}).annotate({title:`Acknowledgement`,description:`The request was accepted. An asynchronous action may still be running.`}),Z9={runId:LN},Q9={loop:DA},$9=M({window:q9.pipe(NT(j9),RT(w(`30d`)))}),Mte=r8(`OperatorApi`).annotate(x8,`usine operator API`).annotate(S8,`unversioned`).annotate(C8,`Read instance state, manage configuration, and operate runs. Requests use instance bearer tokens or browser sessions. API paths remain under /api.`).add(l5(`operator`).annotate(x8,`Operator`).annotate(C8,`Instance reads, configuration revisions, and run actions.`).add(Y6(`upgradeStatus`,`/api/upgrade`,{success:W3}).annotate(w8,`Read upgrade status`).annotate(C8,`Returns the running release, available release, and upgrade progress.`),Y6(`serverVersion`,`/api/version`,{success:j}).annotate(w8,`Read the running release`).annotate(C8,`Public health check that returns the running release string.`),X6(`requestUpgrade`,`/api/upgrade`,{payload:U3,success:X9}).annotate(w8,`Request an upgrade`).annotate(C8,`Accepts an upgrade when idle or an immediate restart. Poll upgrade status for the outcome.`),Y6(`overview`,`/api/overview`,{success:k3}).annotate(w8,`Read the instance overview`).annotate(C8,`Returns project boards, loops, workers, and instance readiness.`),X6(`dismissNeed`,`/api/attention/dismiss`,{payload:eN,success:X9}).annotate(w8,`Dismiss an attention item`).annotate(C8,`Acknowledges the current attention item until its state changes.`),X6(`undoDismissNeed`,`/api/attention/undo`,{payload:eN,success:X9}).annotate(w8,`Undo an attention dismissal`).annotate(C8,`Removes the acknowledgement for the supplied attention item.`),Y6(`agents`,`/api/agents`,{success:N(SA)}).annotate(w8,`List agents`).annotate(C8,`Returns the names of saved agent definitions available for runs.`),X6(`editAndRetry`,`/api/runs/:runId/edit-and-retry`,{params:Z9,payload:Vq,success:X9}).annotate(w8,`Edit and retry a run`).annotate(C8,`Retries a failed run with the supplied task or agent changes.`),X6(`runAgain`,`/api/runs/:runId/run-again`,{params:Z9,payload:Vq,success:S0}).annotate(w8,`Run an item again`).annotate(C8,`Opens a new run for a succeeded or canceled run and returns the admission result.`),X6(`intervene`,`/api/runs/:runId/intervene`,{params:Z9,payload:Hq,success:X9}).annotate(w8,`Send an operator message`).annotate(C8,`Sends a message to the selected session of a running attempt.`),X6(`resetCycleBudget`,`/api/cycle-budgets/reset`,{payload:M({askId:OI}),success:X9}).annotate(w8,`Reset an item cycle budget`).annotate(C8,`Answers an open cycle budget ask and allows the item to run again.`),Y6(`detail`,`/api/runs/:runId`,{params:Z9,query:jte,success:Yq}).annotate(w8,`Read a run and its transcript`).annotate(C8,`Without cursors, returns the latest transcript page. Use after for updates, or before and attempt together for earlier messages.`).annotate(T8,e=>({...e,parameters:[...e.parameters,...[{name:`after`,schema:PG,description:`Return messages after this sequence. Cannot be combined with before or attempt.`},{name:`before`,schema:PG,description:`Return messages before this sequence. Requires attempt; cannot be combined with after.`},{name:`attempt`,schema:jF,description:`Attempt to read earlier messages from. Requires before; cannot be combined with after.`}].map(({name:e,schema:t,description:n})=>({name:e,in:`query`,required:!1,description:n,schema:GE(t).schema}))]})),Y6(`githubChanges`,`/api/runs/:runId/github-changes`,{params:Z9,success:P5}).annotate(w8,`Read GitHub changes for a run`).annotate(C8,`Returns GitHub writes grouped by attempt window.`),X6(`approve`,`/api/runs/:runId/approve`,{params:Z9,success:X9}).annotate(w8,`Approve a waiting run`).annotate(C8,`Records the signed-in member approval for a run waiting at a gate.`),X6(`resolveFailure`,`/api/runs/:runId/resolve-failure`,{params:Z9,payload:M({attemptId:jF}),success:X9}).annotate(w8,`Resolve a run failure`).annotate(C8,`Acknowledges the supplied failed attempt only while it remains the current failure.`),X6(`retry`,`/api/runs/:runId/retry`,{params:Z9,success:X9}).annotate(w8,`Retry a failed run`).annotate(C8,`Starts another attempt of a failed run with its saved definitions.`),X6(`cancel`,`/api/runs/:runId/cancel`,{params:Z9,success:X9}).annotate(w8,`Cancel a run`).annotate(C8,`Cancels an open run and requests that any active attempt stop.`),Y6(`project`,`/api/projects/:project`,{params:{project:pA},success:T3}).annotate(w8,`Read a project board`).annotate(C8,`Returns the project and its board across member repositories.`),Y6(`projectTask`,`/api/projects/:project/tasks/:item`,{params:{project:pA,item:vE.pipe(NT(SI))},query:M({repository:H}),success:E7}).annotate(w8,`Read a project task`).annotate(C8,`Returns linked issues, pull requests, and runs for an item in a project repository.`),X6(`moveProjectItem`,`/api/projects/:project/items/:item/lane`,{params:{project:pA,item:vE.pipe(NT(SI))},payload:M({repository:H,toLane:Xq}),success:X9}).annotate(w8,`Move a project item`).annotate(C8,`Changes the GitHub labels of the task current item to match the destination lane.`),X6(`pauseProjectLoop`,`/api/loops/:project/:loop/pause`,{params:{project:pA,loop:DA},success:X9}).annotate(w8,`Pause a project loop`).annotate(C8,`Stops the loop from opening new runs without canceling existing runs.`),X6(`unpauseProjectLoop`,`/api/loops/:project/:loop/unpause`,{params:{project:pA,loop:DA},success:X9}).annotate(w8,`Resume a project loop`).annotate(C8,`Allows the loop to open runs for matching items.`),X6(`moveBoardItem`,`/api/projects/:owner/:repository/items/:item/lane`,{params:{owner:Y9,repository:Y9,item:vE.pipe(NT(SI))},payload:M({toLane:Xq}),success:X9}).annotate(w8,`Move a repository item`).annotate(C8,`Moves the item using the lanes of the project that contains its repository.`),X6(`discardLeftovers`,`/api/workers/:worker/discard-leftovers`,{params:{worker:qN},success:X9}).annotate(w8,`Discard worker leftovers`).annotate(C8,`Discards a removed worker only after its running attempts have ended.`),X6(`pause`,`/api/loops/:loop/pause`,{params:Q9,success:X9}).annotate(w8,`Pause a loop`).annotate(C8,`Accepts a qualified project/loop name, or a short name while it is unique. Encode slashes in the path segment.`),X6(`unpause`,`/api/loops/:loop/unpause`,{params:Q9,success:X9}).annotate(w8,`Resume a loop`).annotate(C8,`Accepts a qualified project/loop name, or a short name while it is unique. Encode slashes in the path segment.`)).add(Y6(`task`,`/api/projects/:owner/:repository/tasks/:item`,{params:{owner:Y9,repository:Y9,item:vE.pipe(NT(SI))},success:E7}).annotate(w8,`Read a repository task`).annotate(C8,`Returns linked items and runs for the repository item.`)).add(X6(`checkLoop`,`/api/configuration/loops/check`,{payload:A3,success:j3,error:U9}).annotate(w8,`Check a loop definition`).annotate(C8,`Checks the proposed loop, CEL expressions, and prompt without saving a revision.`),X6(`previewLoop`,`/api/configuration/loops/preview`,{payload:M3,success:P3,error:U9}).annotate(w8,`Preview a loop`).annotate(C8,`Evaluates the proposed loop against stored GitHub items without making GitHub requests or saving a revision.`),Y6(`configurationCapabilities`,`/api/configuration/capabilities`,{success:M({harnesses:N(yA),efforts:N(bA)})}).annotate(w8,`List configuration capabilities`).annotate(C8,`Returns supported harnesses and reasoning efforts.`),Y6(`configurationRepositories`,`/api/configuration/repositories`,{success:N(H)}).annotate(w8,`List installation repositories`).annotate(C8,`Returns repositories available to the instance GitHub App installation.`),Y6(`configurationLabels`,`/api/configuration/labels/:repository`,{params:{repository:H},success:N(hU)}).annotate(w8,`List repository labels`).annotate(C8,`Reads live GitHub labels. Encode the repository slash in the path segment.`),Y6(`configurationRevisions`,`/api/configuration/revisions`,{query:M({kind:lT(q9),identifier:lT(q9.pipe(NT(MX))),before:lT(q9.pipe(NT(vE),NT(AX))),limit:q9.pipe(NT(vE),NT(I3.fields.limit),RT(w(`50`)))}),success:V3,error:U9}).annotate(w8,`List configuration revisions`).annotate(C8,`Returns a page of revisions, newest first. Pass nextBefore as before for the next page; the default limit is 50.`),Y6(`configurationRevision`,`/api/configuration/revisions/:number`,{params:W9,success:H3,error:U9}).annotate(w8,`Read a configuration revision`).annotate(C8,`Returns each changed entity with its values before and after the revision.`),Y6(`configurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:G9,success:z3,error:U9}).annotate(w8,`Read a configuration entity`).annotate(C8,`Returns the current JSON value, export-format text, and revision number.`),Z6(`replaceConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:G9,payload:R3,success:H3,error:U9}).annotate(w8,`Replace a configuration entity`).annotate(C8,`Creates or replaces an entity from value or text. The expected revision rejects stale writes.`),Q6(`deleteConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:G9,payload:L3,success:H3,error:U9}).annotate(w8,`Delete a configuration entity`).annotate(C8,`Deletes the entity if the expected revision is current.`),X6(`revertConfigurationRevision`,`/api/configuration/revisions/:number/revert`,{params:W9,payload:L3,success:H3,error:U9}).annotate(w8,`Revert a configuration revision`).annotate(C8,`Creates a revision restoring earlier values unless later edits conflict.`)).add(Y6(`configuration`,`/api/configuration`,{success:$7}).annotate(w8,`Read instance configuration`).annotate(C8,`Returns stored configuration for the configuration editor.`)).add(Y6(`desk`,`/api/desk`,{success:w9}).annotate(w8,`Read overview attention and activity`).annotate(C8,`Returns attention items, active attempts, recent runs, and worker slots.`)).add(Y6(`statistics`,`/api/statistics`,{query:$9,success:fte}).annotate(w8,`Read task statistics`).annotate(C8,`Aggregates task outcomes and worker utilization for the requested window, defaulting to 30d.`),Y6(`runStatistics`,`/api/statistics/runs`,{query:$9,success:wte}).annotate(w8,`Read run statistics`).annotate(C8,`Aggregates runs, attempts, retries, and durations for the requested window, defaulting to 30d.`)).annotate(u8,{onExcessProperty:`error`}).middleware(Ete)),Nte=()=>D8(Mte,{baseUrl:globalThis.location.origin,transformClient:e=>e.pipe(vV(e=>LB(e,`x-usine-csrf`,hA())),yV(e=>ch(()=>{e.status===401&&window.location.replace(`/sign-in`)})))}),Pte=e=>yg(E(Nte(),t=>e(t.operator)).pipe(Qh(SV,!1),Jh(AV))),Fte=e=>e instanceof Error?e.message:String(e);export{iI as $,Yw as $t,_Y as A,br as An,jT as At,rJ as B,$w as Bt,NX as C,see as Cn,N as Ct,fX as D,_r as Dn,JE as Dt,vX as E,Cr as En,L as Et,kJ as F,y as Fn,M as Ft,ZG as G,eE as Gt,Vq as H,oT as Ht,DJ as I,hr as In,P as It,PG as J,aE as Jt,$G as K,qT as Kt,wJ as L,b as Ln,eT as Lt,mY as M,S as Mn,vT as Mt,LJ as N,Sr as Nn,TT as Nt,nX as O,mr as On,YE as Ot,OJ as P,pr as Pn,j as Pt,uI as Q,KE as Qt,eJ as R,wr as Rn,NT as Rt,MX as S,yi as Sn,Vk as St,xX as T,Tr as Tn,vE as Tt,Yq as U,gE as Ut,nJ as V,nT as Vt,Hq as W,Xw as Wt,RW as X,uT as Xt,FW as Y,nE as Yt,SI as Z,lT as Zt,i0 as _,pg as _n,gA as _t,z9 as a,Ah as an,pP as at,P1 as b,Mi as bn,fA as bt,L3 as c,E as cn,TN as ct,T3 as d,Ph as dn,MA as dt,v_ as en,oI as et,D3 as f,Sh as fn,AA as ft,K1 as g,gh as gn,_A as gt,G1 as h,w as hn,bA as ht,H9 as i,Eh as in,fP as it,cY as j,x as jn,F as jt,UJ as k,C as kn,pT as kt,M3 as l,Cg as ln,eN as lt,m4 as m,bg as mn,SA as mt,Fte as n,p_ as nn,sI as nt,B9 as o,kh as on,hP as ot,C3 as p,yg as pn,DA as pt,QG as q,$T as qt,V9 as r,h_ as rn,PF as rt,U3 as s,fh as sn,LN as st,Pte as t,m_ as tn,lI as tt,O3 as u,Th as un,$M as ut,a0 as v,ea as vn,pA as vt,IX as w,Dr as wn,yT as wt,PX as x,vi as xn,dA as xt,F1 as y,Bi as yn,H as yt,oJ as z,oe as zn,Zw as zt};