@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.
- package/README.md +7 -1
- package/dist/auth/api.d.ts +108 -0
- package/dist/auth/api.d.ts.map +1 -0
- package/dist/auth/api.js +109 -0
- package/dist/auth/api.js.map +1 -0
- package/dist/auth/http.d.ts.map +1 -1
- package/dist/auth/http.js +26 -33
- package/dist/auth/http.js.map +1 -1
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +2 -1
- package/dist/http.js.map +1 -1
- package/dist/openapi.d.ts +6 -0
- package/dist/openapi.d.ts.map +1 -0
- package/dist/openapi.js +68 -0
- package/dist/openapi.js.map +1 -0
- package/dist/web/assets/_agent-DduvwaVK.js +1 -0
- package/dist/web/assets/_label-CeJTfdyr.js +1 -0
- package/dist/web/assets/{_loop-CI8wT73I.js → _loop-xu3sbDMH.js} +1 -1
- package/dist/web/assets/{_name-BIiHdJIM.js → _name-DHJA0DfK.js} +1 -1
- package/dist/web/assets/{_number-DOftkarN.js → _number-CxL2Fcpl.js} +1 -1
- package/dist/web/assets/_number-DAq4EEnO.js +1 -0
- package/dist/web/assets/{_number-zDnuidOW.js → _number-DlcNbQyC.js} +1 -1
- package/dist/web/assets/_project-DAq4EEnO.js +1 -0
- package/dist/web/assets/{_project-DwYWqZaq.js → _project-DwpEglrZ.js} +1 -1
- package/dist/web/assets/{_project-CVPqKw8_.js → _project-GK2-urBn.js} +1 -1
- package/dist/web/assets/_run-DAq4EEnO.js +1 -0
- package/dist/web/assets/{_run-B4-87ibA.js → _run-jX-octY4.js} +1 -1
- package/dist/web/assets/{_worker-BBfkUdTZ.js → _worker-C_Nw6Vto.js} +1 -1
- package/dist/web/assets/{action-CAwzK5mk.js → action-CniC234z.js} +1 -1
- package/dist/web/assets/{actions-BXWVnBF3.js → actions-BJ8FViiC.js} +1 -1
- package/dist/web/assets/{agents-BStm1azV.js → agents-BD_MpjbH.js} +1 -1
- package/dist/web/assets/agents-Csj7pU8B.js +1 -0
- package/dist/web/assets/api-D3RWLycx.js +335 -0
- package/dist/web/assets/{code-block-CgYM2MuQ.js → code-block-d5zwBZo-.js} +1 -1
- package/dist/web/assets/{drawer-BB7jwe-O.js → drawer-D6KxeZBZ.js} +1 -1
- package/dist/web/assets/{edit-and-retry-B0OIPvbt.js → edit-and-retry-BKxt-FIG.js} +1 -1
- package/dist/web/assets/{file-error-DeQv_cj8.js → file-error-LMdCcTon.js} +1 -1
- package/dist/web/assets/{history-Dg2dL6yf.js → history-34nvr9sY.js} +1 -1
- package/dist/web/assets/{index-BGr-Cg-z.js → index-B_6qmKij.js} +3 -3
- package/dist/web/assets/{label-badge-C3PtxhEk.js → label-badge-cRUT7_pk.js} +1 -1
- package/dist/web/assets/{labels-DFfLQe0K.js → labels-BGCA9v1C.js} +1 -1
- package/dist/web/assets/{list-CHD0VbJL.js → list-qM2KUYvo.js} +1 -1
- package/dist/web/assets/loops-BXqvj3ko.js +1 -0
- package/dist/web/assets/{members-Cl_WCHwt.js → members-B14AFaH7.js} +1 -1
- package/dist/web/assets/{model-D9QKZ_Hk.js → model-C6gErpq3.js} +1 -1
- package/dist/web/assets/{moves-BQl144Rz.js → moves-BYTLKqNE.js} +1 -1
- package/dist/web/assets/{not-found-C8JhxsFV.js → not-found-CCicx33l.js} +1 -1
- package/dist/web/assets/{outcome-Bmu_N2Ni.js → outcome-D5IWnu4P.js} +1 -1
- package/dist/web/assets/{overview-CUn9OtUH.js → overview-DLYaCoiG.js} +1 -1
- package/dist/web/assets/{page-CmRQu9F2.js → page-BEpkTOW0.js} +1 -1
- package/dist/web/assets/{projects-D7j8WXJK.js → projects-B6PO2z2B.js} +1 -1
- package/dist/web/assets/{queries-Cvt0xQVN.js → queries-Bhp4FeLT.js} +1 -1
- package/dist/web/assets/{queries-CKjxlPEk.js → queries-CU77zJnf.js} +1 -1
- package/dist/web/assets/{queries-D5TGw8Nr.js → queries-C_qC_nGu.js} +1 -1
- package/dist/web/assets/{queries-Cdfj6CtB.js → queries-ESTqS3FK.js} +1 -1
- package/dist/web/assets/{repositories-B_mXysRY.js → repositories-Db6PsyxS.js} +1 -1
- package/dist/web/assets/{repository-link-B7-4fVcX.js → repository-link-OOfhq6c8.js} +1 -1
- package/dist/web/assets/route-D8Nd9ZwI.js +1 -0
- package/dist/web/assets/route-DjjbuG-J.js +1 -0
- package/dist/web/assets/{route-status-tny9_oCm.js → route-status-Cxocu6W_.js} +1 -1
- package/dist/web/assets/routes-DAq4EEnO.js +1 -0
- package/dist/web/assets/{routes-DRogv1gQ.js → routes-Dq3R4rSX.js} +1 -1
- package/dist/web/assets/{run-again-DVg9Ncn3.js → run-again-DHlW6Dcb.js} +1 -1
- package/dist/web/assets/{section-CjCP4gvu.js → section-C75aUrac.js} +1 -1
- package/dist/web/assets/{section-Du_ZZiFG.js → section-Db-f1liW.js} +1 -1
- package/dist/web/assets/{section-BjpSGYua.js → section-Wflvjspx.js} +1 -1
- package/dist/web/assets/{settings-DlN91oPk.js → settings-CpA5zhaC.js} +1 -1
- package/dist/web/assets/{sign-in-i_b9opnw.js → sign-in-D5kDf9C5.js} +1 -1
- package/dist/web/assets/{strings-DhGEKt5X.js → strings-DmAVtEUC.js} +1 -1
- package/dist/web/assets/tasks-DAq4EEnO.js +1 -0
- package/dist/web/assets/{tasks-DG6D0ByG.js → tasks-Dmzf4nUy.js} +1 -1
- package/dist/web/assets/{tokens-Dfsm5C2T.js → tokens-BHREcyDp.js} +1 -1
- package/dist/web/assets/{usage-cNWB4RMb.js → usage-ZTnmWdRP.js} +1 -1
- package/dist/web/assets/{use-project-links-C3F9c85T.js → use-project-links-CdgpfpoU.js} +1 -1
- package/dist/web/assets/{useTriggerFocusGuards-BEdypEdV.js → useTriggerFocusGuards-u-Jz4hr2.js} +1 -1
- package/dist/web/assets/{workers-DkgWKjiI.js → workers-D8lcf3zo.js} +1 -1
- package/dist/web/index.html +12 -12
- package/package.json +11 -10
- package/dist/web/assets/_agent-DIZrJ2oZ.js +0 -1
- package/dist/web/assets/_label-DMFWLPtF.js +0 -1
- package/dist/web/assets/_number-Bn_57si9.js +0 -1
- package/dist/web/assets/_project-Bn_57si9.js +0 -1
- package/dist/web/assets/_run-Bn_57si9.js +0 -1
- package/dist/web/assets/agents-BZV7-W7e.js +0 -1
- package/dist/web/assets/api-CoJQoiOc.js +0 -335
- package/dist/web/assets/loops-CRPsfOzn.js +0 -1
- package/dist/web/assets/route-Di3rgfZ0.js +0 -1
- package/dist/web/assets/route-DjL-s2L0.js +0 -1
- package/dist/web/assets/routes-Bn_57si9.js +0 -1
- package/dist/web/assets/tasks-Bn_57si9.js +0 -1
|
@@ -1,335 +0,0 @@
|
|
|
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,ee=()=>{_++};function te(e){return typeof e==`string`}function ne(e){return typeof e==`number`}function re(e){return typeof e==`boolean`}function ie(e){return typeof e==`bigint`}function ae(e){return typeof e==`symbol`}function oe(e){return te(e)||ne(e)||ae(e)}function se(e){return typeof e==`function`}function ce(e){return e!==void 0}function le(e){return e!=null}function ue(e){return!1}function de(e){return!0}function fe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pe(e){return typeof e==`object`&&!!e||se(e)}var me=r(2,(e,t)=>pe(e)&&t in e),he=r(2,(e,t)=>me(e,`_tag`)&&e._tag===t);function ge(e){return e instanceof Error}function _e(e){return me(e,Symbol.iterator)||te(e)}var ve=`~effect/Hash`,ye=e=>{switch(typeof e){case`number`:return Te(e);case`bigint`:return Ee(e.toString(10));case`string`:return Ee(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?Ee(`Invalid Date`):Ee(e.toISOString());if(e instanceof RegExp)return Ee(e.toString());{if(h.has(e))return be(e);let t=Fe.get(e);if(t!==void 0)return t;if(Ie.has(e))return ee(),Ee(`[Circular]`);Ie.add(e);let n=_,r;try{r=`~effect/Hash`in e?e[ve]():typeof e==`function`?be(e):e instanceof DataView?Ae(g(e)):Array.isArray(e)||ArrayBuffer.isView(e)?Ae(e):e instanceof Map?je(e):e instanceof Set?Ne(e):Oe(e)}finally{Ie.delete(e)}return n===_&&Fe.set(e,r),r}}return Ce(xe(Ee(String(e))))},be=e=>(Pe.has(e)||Pe.set(e,Ce(Math.random()*4294967296|0)),Pe.get(e)),xe=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),Se=r(2,(e,t)=>xe(Math.imul(e,2654435761)+Math.imul(t,2246822507))),Ce=e=>e&3221225471|e>>>1&1073741824,we=new DataView(new ArrayBuffer(8)),Te=e=>{let t=e|0;return t===e?Ce(t):(we.setFloat64(0,e===e?e:NaN),Ce(Se(we.getInt32(0),we.getInt32(4))))},Ee=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return Ce(t)},De=(e,t)=>{let n=12289;for(let r of t)n^=Se(ye(r),ye(e[r]));return Ce(n)},Oe=e=>De(e,m(e)),ke=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return Ce(r)},Ae=e=>{let t=6151;for(let n of e)t=Se(t,ye(n));return Ce(t)},je=ke(Ee(`Map`),([e,t])=>Se(ye(e),ye(t))),Me=Ee(`Set`),Ne=ke(Me,e=>Se(Me,ye(e))),Pe=new WeakMap,Fe=new WeakMap,Ie=new WeakSet,Le=`~effect/Equal`;function Re(){return arguments.length===1?e=>ze(e,arguments[0]):ze(arguments[0],arguments[1])}function ze(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:Be(e,t):!1}function Be(e,t){let n=He.length;for(let r=n;r-->0;)if(He[r]===e&&Ue[r]===t)return!0;if(n)return Ve(e,t);let r=We.get(e);r||We.set(e,r=new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=Ve(e,t)),i}function Ve(e,t){He.push(e),Ue.push(t);try{return eee(e,t)}finally{He.pop(),Ue.pop()}}var He=[],Ue=[],We=new WeakMap;function eee(e,t){if(ye(e)!==ye(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[Le](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,ye,ze):qe(e,t)}function Ge(e,t){for(let n=0;n<e.length;n++)if(!ze(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)||!ze(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=>ye(e[0]),Xe=(e,t)=>ze(e[0],t[0])&&ze(e[1],t[1]),Ze=e=>me(e,Le),Qe=()=>Re,$e=Symbol.for(`~effect/Redactable`),et=e=>me(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&&me(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=me(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&&!me(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),me(e,`toJSON`)&&se(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map(_t):e}catch{return`[toJSON threw]`}},vt=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?pt(e,{space:t}):ot(e,{space:t})}catch{return String(e)}},yt={toJSON(){return _t(this)},[gt](){return this.toJSON()},toString(){return ot(this.toJSON())}},bt=class{[gt](){return this.toJSON()}toString(){return ot(this.toJSON())}},xt=(()=>{let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.hasOwn(e,`writable`)?e.writable===!0:e.set!==void 0})(),St=()=>Error.stackTraceLimit,Ct=e=>{xt&&(Error.stackTraceLimit=e)},wt=class{constructor(e){this.value=e,this.done=!1}next(e){return this.done?(this.value=e,this):(this.done=!0,{value:this.value,done:!1})}},Tt=(()=>{let e=`~effect/Utils/internal`,t={[e]:e=>e()},n={[e]:e=>{try{return e()}finally{}}},r=St();if(r===0)return n[e];Ct(2);let i=t[e](()=>Error());return Ct(r),i.stack?.includes(e)===!0?t[e]:n[e]})();function Et(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function Dt(e,t){if(!Object.hasOwn(t,`__proto__`))Object.assign(e,t);else for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&Et(e,n,t[n])}var Ot=`~effect/Effect`,kt=`~effect/Exit`,At={_A:i,_E:i,_R:i},jt=`${Ot}/identifier`,Mt=`${Ot}/args`,Nt=`${Ot}/evaluate`,Pt=`${Ot}/successCont`,Ft=`${Ot}/failureCont`,It=`${Ot}/ensureCont`,Lt=Symbol.for(`effect/Effect/Yield`),Rt={pipe(){return e(this,arguments)},toJSON(){return{...this}},toString(){return ot(this.toJSON(),{ignoreToString:!0,space:2})},[gt](){return this.toJSON()}},zt={[Ot]:At,...Rt,[Symbol.iterator](){return new wt(this)},toJSON(){return{_id:`Effect`,op:this[jt],...`~effect/Effect/args`in this?{args:this[Mt]}:void 0}}},Bt=e=>me(e,Ot),Vt=e=>me(e,kt),Ht=`~effect/Cause`,Ut=`~effect/Cause/Reason`,Wt=e=>me(e,Ht),Gt=e=>me(e,Ut),Kt=class{constructor(e){this[Ht]=Ht,this.reasons=e}pipe(){return e(this,arguments)}toJSON(){return{_id:`Cause`,reasons:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${ot(this.reasons)})`}[gt](){return this.toJSON()}[Le](e){return Wt(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>Re(t,e.reasons[n]))}[ve](){return Ae(this.reasons)}},qt=new WeakMap,Jt=class{[Ut];annotations;_tag;constructor(e,t,n){if(this[Ut]=Ut,this._tag=e,t!==Yt&&typeof n==`object`&&n&&t.size>0){let e=qt.get(n);e&&(t=new Map([...e,...t])),qt.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((e,r)=>{t?.overwrite!==!0&&n.has(r)||n.set(r,e)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return e(this,arguments)}toString(){return ot(this)}[gt](){return this.toString()}},Yt=new Map,Xt=class extends Jt{constructor(e,t=Yt){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${ot(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[Le](e){return on(e)&&Re(this.error,e.error)&&Re(this.annotations,e.annotations)}[ve](){return Se(Ee(this._tag))(Se(ye(this.error))(ye(this.annotations)))}},Zt=e=>new Kt(e),tee=(e,t)=>{let n=new Map,r=[];for(let i of e.concat(t)){let e=ye(i),t=n.get(e);if(t===void 0)n.set(e,[i]);else if(t.some(e=>Re(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 Kt(tee(e.reasons,t.reasons));return Re(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 Kt(n)},en=new Kt([]),tn=e=>new Kt([new Xt(e)]),nn=class extends Jt{constructor(e,t=Yt){super(`Die`,t,e),this.defect=e}toString(){return`Die(${ot(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[Le](e){return sn(e)&&Re(this.defect,e.defect)&&Re(this.annotations,e.annotations)}[ve](){return Se(Ee(this._tag))(Se(ye(this.defect))(ye(this.annotations)))}},rn=e=>new Kt([new nn(e)]),an=r(e=>Wt(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new Kt(e.reasons.map(e=>e.annotate(t,n)))),on=e=>e._tag===`Fail`,sn=e=>e._tag===`Die`,cn=e=>e._tag===`Interrupt`;function ln(e){return vn(`Effect.evaluate: Not implemented`)}var un=e=>({...zt,[jt]:e.op,[Nt]:e[`~effect/Effect/evaluate`]??ln,[Pt]:e[Pt],[Ft]:e[Ft],[It]:e[It]}),dn=e=>{let t=un(e),n=function(e){this[Mt]=e};return n.prototype=t,function(e){return new n(e)}},fn=e=>{let t={[kt]:kt,_tag:e.op,get[e.prop](){return this[Mt]},...un(e),toString(){return`${e.op}(${ot(this[Mt])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[Mt]}},[Le](e){return Vt(e)&&e._tag===this._tag&&Re(this[`~effect/Effect/args`],e[`~effect/Effect/args`])},[ve](){return Se(Ee(e.op),ye(this[Mt]))}},n=function(e){this[Mt]=e};return n.prototype=t,function(e){return new n(e)}},pn=fn({op:`Success`,prop:`value`,[Nt](e){let t=e.getCont(Pt);return t?t[Pt](this[Mt],e,this):e.yieldWith(this)}}),mn={key:`effect/Cause/StackTrace`},hn={key:`effect/Cause/InterruptorStackTrace`},gn=fn({op:`Failure`,prop:`cause`,[Nt](e){let t=this[Mt],n=!1;e.cache.stackFrame&&(t=an(t,{mapUnsafe:new Map([[mn.key,e.cache.stackFrame]])}),n=!0);let r=e.getCont(Ft),i=e._interruptedCause;if(i&&e.interruptible){let a=!1;for(;r&&e.interruptible;)a||=jt in r,r=e.getCont(Ft);a&&(t=Zt(t.reasons.filter(e=>e._tag!==`Fail`))),t=$t(t,i),n=!0}return r?r[Ft](t,e,n?void 0:this):e.yieldWith(n?gn(t):this)}}),_n=e=>gn(tn(e)),vn=e=>gn(rn(e)),yn=dn({op:`WithFiber`,[Nt](e){return this[Mt](e)}}),bn=function(){class e extends globalThis.Error{}let t=un({op:`YieldableError`,[Nt](){return _n(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),xn=function(){let e=Symbol.for(`effect/Data/Error/plainArgs`);return class extends bn{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}}}}(),Sn=e=>{class t extends xn{_tag=e}return t.prototype.name=e,t},Cn=`~effect/Cause/NoSuchElementError`,wn=class extends Sn(`NoSuchElementError`){[Cn]=Cn;constructor(e){super({message:e})}},Tn=`~effect/Cause/Done`,En=e=>me(e,Tn),Dn={[Tn]:Tn,_tag:`Done`,value:void 0},On=e=>e===void 0?Dn:{[Tn]:Tn,_tag:`Done`,value:e},kn=_n(Dn),An=e=>e===void 0?kn:_n(On(e)),jn=e=>un({op:e.label,[Nt]:e.evaluate}),Mn=e=>(t,n)=>t===n||e(t,n),Nn=(e,t)=>e===t,Pn=()=>Nn;function Fn(e){return Mn((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 In(e){return Mn((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 Ln=`~effect/Option`,Rn={[Ln]:{_A:e=>e},...Rt,[Symbol.iterator](){return new wt(this)}},zn=Object.defineProperty(Object.assign(Object.create(Rn),{_tag:`Some`,_op:`Some`,[Le](e){return Hn(e)&&Wn(e)&&Re(this.value,e.value)},[ve](){return Se(ye(this._tag))(ye(this.value))},toString(){return`some(${ot(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:_t(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),Bn=ye(`None`),Vn=Object.assign(Object.create(Rn),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[Le](e){return Hn(e)&&Un(e)},[ve](){return Bn},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),Hn=e=>me(e,Ln),Un=e=>e._tag===`None`,Wn=e=>e._tag===`Some`,Gn=Object.create(Vn),Kn=function(e){this.value=e};Kn.prototype=zn;var qn=e=>new Kn(e),Jn=`~effect/Result`,Yn={[Jn]:{_A:e=>e,_E:e=>e},...Rt,[Symbol.iterator](){return new wt(this)}},Xn=Object.assign(Object.create(Yn),{_tag:`Success`,_op:`Success`,[Le](e){return Qn(e)&&er(e)&&Re(this.success,e.success)},[ve](){return Se(ye(this._tag))(ye(this.success))},toString(){return`success(${ot(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:_t(this.success)}}}),Zn=Object.assign(Object.create(Yn),{_tag:`Failure`,_op:`Failure`,[Le](e){return Qn(e)&&$n(e)&&Re(this.failure,e.failure)},[ve](){return Se(ye(this._tag))(ye(this.failure))},toString(){return`failure(${ot(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:_t(this.failure)}}}),Qn=e=>me(e,Jn),$n=e=>e._tag===`Failure`,er=e=>e._tag===`Success`,tr=function(e){this.failure=e};tr.prototype=Zn;var nr=e=>new tr(e),rr=function(e){this.success=e};rr.prototype=Xn;var ir=e=>new rr(e),ar=r(2,(e,t)=>Un(e)?nr(t()):ir(e.value));function or(e){return(t,n)=>t===n?0:e(t,n)}var sr=or((e,t)=>e<t?-1:1),cr=or((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 lr(e){return or((t,n)=>e(n,t))}function ur(e){let t=Array.from(e);return or((e,n)=>{let r=0;for(let i of t)if(r=i(e,n),r!==0)return r;return r})}var dr=r(2,(e,t)=>or((n,r)=>e(t(n),t(r)))),fr=e=>r(2,(t,n)=>e(t,n)===-1),pr=e=>r(2,(t,n)=>e(t,n)===1),mr=e=>r(2,(t,n)=>e(t,n)!==1),hr=e=>r(2,(t,n)=>e(t,n)!==-1),v=()=>Gn,y=qn,gr=Hn,b=Un,x=Wn,_r=r(2,(e,{onNone:t,onSome:n})=>b(e)?t():n(e.value)),vr=r(2,(e,t)=>b(e)?t():e.value),yr=r(2,(e,t)=>b(e)?t():e),br=e=>{let t=v();for(t of e)if(x(t))return t;return t},xr=e=>e==null?v():y(e),Sr=e=>e===void 0?v():y(e),Cr=e=>e===null?v():y(e),S=vr(c),wr=vr(l),Tr=e=>(...t)=>{try{return y(e(...t))}catch{return v()}},Er=r(2,(e,t)=>{if(x(e))return e.value;throw t()}),Dr=r(2,(e,t)=>b(e)?v():y(t(e.value))),Or=r(2,(e,t)=>b(e)?v():t(e.value)),kr=Or(i),Ar=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(b(n))return v();t.push(n.value)}return y(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(b(r))return v();Et(t,n,r.value)}return y(t)},jr=e=>b(e)?[]:[e.value],Mr=r(2,(e,t)=>b(e)?v():t(e.value)?y(e.value):v()),Nr=r(2,(e,t)=>t(e)?y(e):v()),Pr=(e=>r(2,(t,n)=>!b(t)&&e(t.value,n)))(Qe()),Fr=r(2,(e,t)=>!b(e)&&t(e.value)),Ir=`~effect/Context/Service`,Lr=function(){function e(){}let t=e;Object.setPrototypeOf(t,Rr);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[Br]=Br,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&zr.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},Rr={[Ir]:Ir,...jn({label:`Service`,evaluate(e){return pn(li(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return ri(this,e)},use(e){return yn(t=>e(li(t.context,this)))},useSync(e){return yn(t=>pn(e(li(t.context,this))))}},zr=new Set,Br=`~effect/Context/Reference`,Vr=`~effect/Context`,Hr=8,Ur=8,Wr=(e,t,n,r)=>{let i=Object.create(Zr);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Gr=(e,t)=>{t&&(Gr(e,t.parent),e.set(t.key,t.value))},Kr=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Gr(t,e.overlay),e._flat=t},qr=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),Xr(n)},Jr=Symbol(),Yr=(e,t)=>{let n=e;for(let e=n.overlay;e;e=e.parent)if(e.key===t)return e.value;let r=n.base.get(t);return r===void 0&&!n.base.has(t)?Jr:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=Ur&&(n.base=Kr(n),n.overlay=void 0,n.depth=0),r)},Xr=e=>Wr(void 0,e,void 0,0),Zr={get mapUnsafe(){return Kr(this)},...Rt,[Vr]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[Le](e){if(!$r(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[e,r]of t)if(!n.has(e)||!Re(r,n.get(e)))return!1;return!0},[ve](){return Te(this.mapUnsafe.size)}},Qr=(e,t)=>e.cacheRoot===t.cacheRoot,$r=e=>me(e,Vr),ei=e=>!!e[Br],ti=()=>ni,ni=Xr(new Map),ri=(e,t)=>Xr(new Map([[e.key,t]])),ii=r(3,(e,t,n)=>ai(e,t.key,n)),ai=(e,t,n)=>{let r=e,i=zr.has(t)?void 0:r.cacheRoot;if(r.depth>=Hr){let e=new Map(r._flat??r.base);return r._flat||Gr(e,r.overlay),e.set(t,n),Wr(i,e,void 0,0)}return Wr(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},oi=r(2,(e,t)=>si(e,t.key)),si=(e,t)=>{let n=Yr(e,t);return n===Jr?void 0:n},ci=r(2,(e,t)=>{let n=Yr(e,t.key);if(n===Jr){if(ei(t))return di(t);throw fi(t)}return n}),li=ci,ui=`~effect/Context/defaultValue`,di=e=>ui in e?e[ui]:e[ui]=e.defaultValue(),fi=e=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:``}`);if(t.stack){let e=t.stack.split(`
|
|
4
|
-
`);e.splice(1,3),t.stack=e.join(`
|
|
5
|
-
`)}return t},pi=r(2,(e,t)=>{let n=Yr(e,t.key);return n===Jr?ei(t)?y(di(t)):v():y(n)}),mi=r(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:qr(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),hi=(...e)=>{let t=new Map;for(let n=0;n<e.length;n++)e[n].mapUnsafe.forEach((e,n)=>{t.set(n,e)});return Xr(t)},gi=(...e)=>t=>{if(e.length<=1){let n=new Map;if(e.length===1){let r=e[0].key,i=Yr(t,r);i!==Jr&&n.set(r,i)}return Xr(n)}let n=new Set(e.map(e=>e.key));return qr(t,e=>e.forEach((t,r)=>{n.has(r)||e.delete(r)}))},_i=Lr,vi=e=>e.length>0,yi=e=>e>0?Math.floor(e):0,bi=e=>Math.max(1,yi(e)),xi=ir,Si=nr,Ci=ar,wi=e=>{if(se(e))try{return xi(e())}catch(e){return Si(e)}try{return xi(e.try())}catch(t){return Si(e.catch(t))}},Ti=Qn,Ei=$n,Di=er,Oi=r(2,(e,t)=>Ei(e)?Si(t(e.failure)):e),ki=r(2,(e,t)=>Di(e)?xi(t(e.success)):e),Ai=r(2,(e,{onFailure:t,onSuccess:n})=>Ei(e)?t(e.failure):n(e.success)),ji=r(2,(e,t)=>{if(Di(e))return e.success;throw t(e.failure)})(i),Mi=e=>{if(Symbol.iterator in e){let t=[];for(let n of e){if(Ei(n))return n;t.push(n.success)}return xi(t)}let t={};for(let n of Object.keys(e)){let r=e[n];if(Ei(r))return r;Et(t,n,r.success)}return xi(t)},Ni=(...e)=>e,Pi=Fn,Fi={[Symbol.iterator](){return Ii}},Ii={next(){return{done:!0,value:void 0}}},Li=()=>Fi,Ri=r(2,(e,t)=>Object.hasOwn(e,t)),zi=r(2,(e,t)=>{let n={...e};for(let r of Bi(e))Et(n,r,t(e[r],r));return n}),Bi=e=>Object.keys(e),Vi=e=>r(2,(t,n)=>{for(let r of Bi(t))if(!Ri(n,r)||!e(t[r],n[r]))return!1;return!0}),Hi=e=>{let t=Vi(e);return(e,n)=>t(e,n)&&t(n,e)},Ui=globalThis.Array,Wi=e=>Ui.isArray(e)?e:Ui.from(e),Gi=e=>Ui.isArray(e)?e:[e],Ki=r(2,(e,t)=>[t,...e]),qi=r(2,(e,t)=>[...e,t]),Ji=r(2,(e,t)=>Wi(e).concat(Wi(t)));Ui.isArray;var Yi=vi,Xi=vi;function Zi(e,t){return!Number.isFinite(e)||e<0||e>=t.length}var Qi=r(2,(e,t)=>{let n=Math.floor(t);return Zi(n,e)?v():y(e[n])}),$i=r(2,(e,t)=>{let n=Math.floor(t);if(Zi(n,e))throw Error(`Index out of bounds: ${n}`);return e[n]}),ea=Qi(0),ta=$i(0),na=e=>e[e.length-1],ra=r(2,(e,t)=>{let n=Wi(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 y(r)}else if(x(i))return i}return v()}),ia=r(2,(e,t)=>{let n=Ui.from(e);return n.sort(t),n}),aa=r(2,(e,t)=>oa(e,t,Ni)),oa=r(3,(e,t,n)=>{let r=Wi(e),i=Wi(t);if(Xi(r)&&Xi(i)){let e=[n(ta(r),ta(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[]}),sa=r(2,(e,t)=>{let n=Wi(e);if(Xi(n)){let[e,r]=t(n),i=[e],a=r;for(;vi(a);){let[e,n]=t(a);i.push(e),a=n}return i}return[]}),ca=r(2,(e,t)=>{let n=bi(t);return n>=e.length?[nee(e),[]]:[Ki(e.slice(1,n),ta(e)),e.slice(n)]}),nee=e=>e.slice(),la=r(2,(e,t)=>{let n=Wi(e);return Xi(n)?sa(n,ca(t)):[]}),ua=r(2,(e,t)=>{let n={};for(let r of e){let e=t(r);Object.hasOwn(n,e)?n[e].push(r):Et(n,e,[r])}return n}),da=(e,t)=>{let n=ye(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(Re(e,t))return!1;return r.push(t),!0},fa=()=>[],pa=e=>[e],ma=r(2,(e,t)=>e.map(t)),ha=e=>{let t=[];for(let n of e)x(n)&&t.push(n.value);return t},ga=In,_a=r(2,(e,t)=>{let n=[];next:for(let r of Wi(e)){for(let e=0;e<n.length;e++)if(t(r,n[e]))continue next;n.push(r)}return n}),va=e=>{let t=Wi(e);if(t.length<2)return[...t];let n=new Map,r=[];for(let e of t)da(n,e)&&r.push(e);return r},ya=`~effect/Duration`,ba=BigInt(0),xa=BigInt(1),Sa=BigInt(2),Ca=BigInt(10),wa=BigInt(1e3),Ta=BigInt(1e6),Ea=BigInt(1e9),Da=BigInt(6e10),Oa=BigInt(36e11),ka=BigInt(864e11),Aa=BigInt(6048e11),ja=e=>BigInt(Math.sign(e)*Math.round(Math.abs(e))),Ma=e=>Number.isInteger(e)?BigInt(e)*Ta:ja(e*1e6),Na=e=>qa(Number.isFinite(e)?ja(e):e),Pa=(e,t)=>{let n=Number(e);if(Number.isFinite(n))return n/t;let r=BigInt(t);return Number(e/r)+Number(e%r)/t},Fa=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=Ca**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t;return Ia(r?-o:o,a)},Ia=(e,t)=>{let n=e<ba?-e:e,r=n/t+(n%t*Sa>=t?xa:ba);return e<ba?-r:r},La=(e,t)=>{let n=Number(e)*t;if(!Number.isFinite(n))return qa(n);let r=Fa(e,BigInt(t)*Ta);return qa(Number.isInteger(n)&&BigInt(n)*Ta===r?n:r)},Ra=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,za=e=>{switch(typeof e){case`number`:return $a(e);case`bigint`:return Qa(e);case`string`:{if(e===`Infinity`)return Xa;if(e===`-Infinity`)return Za;let t=Ra.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return Qa(Fa(r,xa));if(i===`micro`||i===`micros`)return Qa(Fa(r,wa));switch(i){case`milli`:case`millis`:return La(r,1);case`second`:case`seconds`:return La(r,1e3);case`minute`:case`minutes`:return La(r,6e4);case`hour`:case`hours`:return La(r,36e5);case`day`:case`days`:return La(r,864e5);case`week`:case`weeks`:return La(r,6048e5)}break}case`object`:{if(e===null)break;if(ya in e)return e;if(Array.isArray(e)){if(e.length!==2||!e.every(ne))return Ha(e);if(Number.isNaN(e[0])||Number.isNaN(e[1]))return Ya;if(e[0]===-1/0||e[1]===-1/0)return Za;if(e[0]===1/0||e[1]===1/0)return Xa;let t=e[0]*1e9+e[1];return Number.isFinite(t)&&Number.isInteger(e[0])&&Number.isInteger(e[1])?qa(BigInt(e[0])*Ea+BigInt(e[1])):Na(t)}let t=e,n=0;if(t.weeks&&(n+=t.weeks*6048e5),t.days&&(n+=t.days*864e5),t.hours&&(n+=t.hours*36e5),t.minutes&&(n+=t.minutes*6e4),t.seconds&&(n+=t.seconds*1e3),t.milliseconds&&(n+=t.milliseconds),!t.microseconds&&!t.nanoseconds){if(!Number.isFinite(n))return qa(n);let e=Va(t);return e===void 0||BigInt(n)*Ta===e?qa(n):qa(e)}let r=n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0),i=Number.isFinite(r)?Va(t):void 0;return i===void 0?Na(r):qa(i)}}return Ha(e)},Ba=e=>!e||Number.isInteger(e),Va=e=>{if(!Ba(e.weeks)||!Ba(e.days)||!Ba(e.hours)||!Ba(e.minutes)||!Ba(e.seconds)||!Ba(e.milliseconds)||!Ba(e.microseconds)||!Ba(e.nanoseconds))return;let t=ba;return e.weeks&&(t+=BigInt(e.weeks)*Aa),e.days&&(t+=BigInt(e.days)*ka),e.hours&&(t+=BigInt(e.hours)*Oa),e.minutes&&(t+=BigInt(e.minutes)*Da),e.seconds&&(t+=BigInt(e.seconds)*Ea),e.milliseconds&&(t+=BigInt(e.milliseconds)*Ta),e.microseconds&&(t+=BigInt(e.microseconds)*wa),e.nanoseconds&&(t+=BigInt(e.nanoseconds)),t},Ha=e=>{throw Error(`Invalid Input: ${e}`)},Ua={_tag:`Millis`,millis:0},Wa={_tag:`Infinity`},Ga={_tag:`NegativeInfinity`},Ka={[ya]:ya,[ve](){switch(this.value._tag){case`Millis`:return ye(Ma(this.value.millis));case`Nanos`:return ye(this.value.nanos);default:return Oe(this.value)}},[Le](e){return Ja(e)&&so(this,e)},toString(){switch(this.value._tag){case`Infinity`:return`Infinity`;case`NegativeInfinity`:return`-Infinity`;case`Nanos`:return`${this.value.nanos} nanos`;case`Millis`:return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case`Millis`:return{_id:`Duration`,_tag:`Millis`,millis:this.value.millis};case`Nanos`:return{_id:`Duration`,_tag:`Nanos`,nanos:String(this.value.nanos)};case`Infinity`:return{_id:`Duration`,_tag:`Infinity`};case`NegativeInfinity`:return{_id:`Duration`,_tag:`NegativeInfinity`}}},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},qa=e=>{let t=Object.create(Ka);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?Ua:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:Ma(e)}:e>0?Wa:Ga:e===ba?Ua:{_tag:`Nanos`,nanos:e},t},Ja=e=>me(e,ya),Ya=qa(0),Xa=qa(1/0),Za=qa(-1/0),Qa=e=>qa(e),$a=e=>qa(e),eo=e=>qa(e*1e3),to=e=>qa(e*6e4),no=e=>io(za(e),{onMillis:i,onNanos:e=>Pa(e,1e6),onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),ro=e=>{let t=za(e);switch(t.value._tag){case`Infinity`:case`NegativeInfinity`:throw Error(`Cannot convert infinite duration to nanos`);case`Nanos`:return t.value.nanos;case`Millis`:return Ma(t.value.millis)}},io=r(2,(e,t)=>{switch(e.value._tag){case`Millis`:return t.onMillis(e.value.millis);case`Nanos`:return t.onNanos(e.value.nanos);case`Infinity`:return t.onInfinity();case`NegativeInfinity`:return(t.onNegativeInfinity??t.onInfinity)()}}),ao=r(3,(e,t,n)=>e.value._tag===`Infinity`||e.value._tag===`NegativeInfinity`||t.value._tag===`Infinity`||t.value._tag===`NegativeInfinity`?n.onInfinity(e,t):e.value._tag===`Millis`?t.value._tag===`Millis`?n.onMillis(e.value.millis,t.value.millis):n.onNanos(ro(e),t.value.nanos):n.onNanos(e.value.nanos,ro(t))),oo=(e,t)=>ao(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),so=r(2,(e,t)=>oo(e,t)),co=e=>t=>!Ei(e(t)),lo=e=>t=>t.has(e)?xi(t):Si(t),uo=r(2,(e,t)=>n=>{let r=e(n);return Ei(r)?r:t(r.success)}),fo=_i(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new _o}),po=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},mo=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},ho=e=>{try{return mo(e)}catch{return po(e)}},go=class{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,a=0;for(;a<r&&!(n[a][0]>t);a++)i=n[a];i&&i[0]===t?i[1].push(e):a===r?n.push([t,[e]]):n.splice(a,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}},_o=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?po:ho)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new vo(this.setImmediate)}},vo=class{tasks=new go;running=void 0;setImmediate;constructor(e=ho){this.setImmediate=e}scheduleTask(e,t){this.tasks.scheduleTask(e,t),this.running===void 0&&(this.running=this.setImmediate(this.afterScheduled))}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let e=this.tasks.drain();for(let t=0;t<e.length;t++){let n=e[t][1];for(let e=0;e<n.length;e++)n[e]()}}flush(){for(;this.tasks.buckets.length>0;)this.running!==void 0&&(this.running(),this.running=void 0),this.runTasks()}},yo=_i(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),bo=_i(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),xo=class extends n{constructor(e){super(),e&&Dt(this,e)}},So=e=>class extends xo{_tag=e},Co=Sn,wo=`~effect/encoding/EncodingError`,To=class extends Co(`EncodingError`){[wo]=wo},Eo=e=>Fo(typeof e==`string`?No.encode(e):e),Do=e=>{switch(e){case 16:return jo();case 32:return Mo();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=Ao();return t}}},Oo=Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),ko=()=>Math.random()*4294967296>>>0,Ao=()=>{let e=ko();return String.fromCharCode(Oo[e>>>28],Oo[e>>>24&15],Oo[e>>>20&15],Oo[e>>>16&15],Oo[e>>>12&15],Oo[e>>>8&15],Oo[e>>>4&15],Oo[e&15])},jo=()=>{let e=ko(),t=ko();return String.fromCharCode(Oo[e>>>28],Oo[e>>>24&15],Oo[e>>>20&15],Oo[e>>>16&15],Oo[e>>>12&15],Oo[e>>>8&15],Oo[e>>>4&15],Oo[e&15],Oo[t>>>28],Oo[t>>>24&15],Oo[t>>>20&15],Oo[t>>>16&15],Oo[t>>>12&15],Oo[t>>>8&15],Oo[t>>>4&15],Oo[t&15])},Mo=()=>{let e=ko(),t=ko(),n=ko(),r=ko();return String.fromCharCode(Oo[e>>>28],Oo[e>>>24&15],Oo[e>>>20&15],Oo[e>>>16&15],Oo[e>>>12&15],Oo[e>>>8&15],Oo[e>>>4&15],Oo[e&15],Oo[t>>>28],Oo[t>>>24&15],Oo[t>>>20&15],Oo[t>>>16&15],Oo[t>>>12&15],Oo[t>>>8&15],Oo[t>>>4&15],Oo[t&15],Oo[n>>>28],Oo[n>>>24&15],Oo[n>>>20&15],Oo[n>>>16&15],Oo[n>>>12&15],Oo[n>>>8&15],Oo[n>>>4&15],Oo[n&15],Oo[r>>>28],Oo[r>>>24&15],Oo[r>>>20&15],Oo[r>>>16&15],Oo[r>>>12&15],Oo[r>>>8&15],Oo[r>>>4&15],Oo[r&15])},No=new TextEncoder,Po=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),Fo=e=>{let t=``;for(let n=0;n<e.length;n++)t+=Po[e[n]];return t},Io=`effect/Tracer/ParentSpan`,Lo=class extends Lr()(Io,{fiberCached:!0}){},Ro=e=>e,zo=_i(`effect/Tracer/DisablePropagation`,{defaultValue:s}),Bo=_i(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),Vo=_i(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),Ho=`effect/Tracer`,Uo=Ro({span:e=>new Wo(e)}),Wo=class{_tag=`Span`;sampled;name;parent;annotations;links;startTime;kind;status;_traceId=void 0;_spanId=void 0;_attributes=void 0;_events=void 0;constructor(e){this.name=e.name,this.parent=e.parent,this.annotations=e.annotations,this.links=e.links,this.startTime=e.startTime,this.kind=e.kind,this.sampled=e.sampled,this.status={_tag:`Started`,startTime:e.startTime}}get traceId(){return this._traceId??=wr(this.parent)?.traceId??Do(32)}get spanId(){return this._spanId??=Do(16)}get attributes(){return this._attributes??=new Map}get events(){return this._events??=[]}end(e,t){this.status={_tag:`Ended`,endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}},Go=`effect/Metric/FiberRuntimeMetrics`,Ko=_i(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:l}),qo=_i(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:o}),Jo=_i(`effect/References/TracerTimingEnabled`,{defaultValue:o}),Yo=_i(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),Xo=_i(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),Zo=_i(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),Qo=_i(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),$o=_i(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),es=_i(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),ts=e=>{if(e?.captureStackTrace===!1||e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!=`boolean`)return e;let t=St();if(t===0&&e?.captureStackTrace!==!0)return{...e,captureStackTrace:!1};Ct(3);let n=Error();return Ct(t),{...e,captureStackTrace:rs(()=>n.stack)}},ns=e=>t=>{let n;return()=>{if(n!==void 0)return n;let r=t();if(!r)return;let i=r.split(`
|
|
6
|
-
`);if(i[e]!==void 0)return n=i[e].trim(),n}},rs=ns(3),is=class extends Jt{constructor(e,t=Yt){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[Le](e){return cn(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[ve](){return Ee(`${this._tag}:${this.fiberId}`)}},as=e=>new is(e),os=e=>new Kt([new is(e)]),ss=e=>e.reasons.some(on),cs=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return xi(n.error)}return Si(e)},ls=e=>e.reasons.some(sn),us=e=>ls(e)&&ss(e)?Zt(e.reasons.map(e=>e._tag===`Fail`&&!En(e.error)?new nn(e.error,e.annotations):e)):e,ds=e=>ls(e)?Si(us(e)):cs(e),fs=e=>{let t=e.reasons.find(sn);return t?xi(t.defect):Si(e)},ps=e=>e.reasons.some(cn),ms=e=>{let t;for(let n=0;n<e.reasons.length;n++){let r=e.reasons[n];r._tag===`Interrupt`&&(t??=new Set,r.fiberId!==void 0&&t.add(r.fiberId))}return t?xi(t):Si(e)},hs=e=>e.reasons.length>0&&e.reasons.every(cn),gs=r(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>on(e)?(n=!0,new Xt(t(e.error),e.annotations)):e);return n?Zt(r):e}),_s=e=>{let t;for(let n of e.reasons){if(n._tag===`Fail`)return n.error;n._tag===`Die`&&(t??=n)}return t===void 0?e.reasons.length>0?new globalThis.Error(`All fibers interrupted without error`):new globalThis.Error(`Empty cause`):t.defect},vs=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=St();i!==0&&Ct(1);try{for(let i of e.reasons)i._tag===`Interrupt`?r.push(i):n.push(ys(i._tag===`Die`?i.defect:i.error,i.annotations,t));if(n.length===0){let e=Error(`The fiber was interrupted by:`);e.name=`InterruptCause`,e.stack=ws(e,r);let i=new globalThis.Error(`All fibers interrupted without error`,{cause:e});i.name=`InterruptError`,i.stack=`${i.name}: ${i.message}`,n.push(ys(i,r[0].annotations,t))}}finally{i!==0&&Ct(i)}return n},ys=(e,t,n,r=new Set)=>{let i=typeof e,a;if(e&&i===`object`){r.add(e);let i=e.cause;if(a=new globalThis.Error(bs(e),{cause:i!==void 0&&!r.has(i)?ys(i,void 0,void 0,r):void 0}),typeof e.name==`string`&&(a.name=e.name),typeof e.stack==`string`)a.stack=Ss(e.stack,a,t);else{let e=`${a.name}: ${a.message}`;a.stack=t?Cs(e,t):e}n?.includeCauseInStack&&(a.stack=Ds(a));for(let t of Object.keys(e))t in a||(a[t]=e[t])}else{a=new globalThis.Error(e?i===`string`?e:pt(e):`Unknown error: ${e}`);let n=`${a.name}: ${a.message}`;a.stack=t?Cs(n,t):n}return a},bs=e=>{if(typeof e.message==`string`)return e.message;if(typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return pt(e)},xs=/\((.*)\)/g,Ss=(e,t,n)=>{let r=`${t.name}: ${t.message}`,i=(e.startsWith(r)?e.slice(r.length):e).split(`
|
|
7
|
-
`),a=[r];for(let e=1;e<i.length&&!/Generator\.next|~effect\/(?:Effect|Utils)/.test(i[e]);e++)a.push(i[e]);return n?Cs(a.join(`
|
|
8
|
-
`),n):a.join(`
|
|
9
|
-
`)},Cs=(e,t)=>{let n=t?.get(mn.key);return n&&(e=`${e}\n${Ts(n)}`),e},ws=(e,t)=>{let n=[`${e.name}: ${e.message}`];for(let e of t){let t=e.fiberId===void 0?`unknown`:`#${e.fiberId}`,r=e.annotations.get(hn.key);n.push(` at fiber (${t})`),r&&n.push(Ts(r))}return n.join(`
|
|
10
|
-
`)},Ts=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(xs),i=!1;for(let[,e]of r)i=!0,t.push(` at ${n.name} (${e})`);i||t.push(` at ${n.name} (${e.replace(/^at /,``)})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(`
|
|
11
|
-
`)},Es=e=>vs(e).map(Ds).join(`
|
|
12
|
-
`),Ds=e=>e.cause?`${e.stack} {\n${Os(e.cause,` `)}\n}`:e.stack,Os=(e,t)=>{let n=e.stack.split(`
|
|
13
|
-
`),r=`${t}[cause]: ${n[0]}`;for(let e=1,i=n.length;e<i;e++)r+=`\n${t}${n[e]}`;return e.cause&&(r+=` {\n${Os(e.cause,`${t} `)}\n${t}}`),r},ks=`~effect/Fiber`,As={_A:i,_E:i},js={id:0},Ms=(()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),Ns=()=>Ms===void 0?void 0:new Ms(`effect/Fiber`),Ps=()=>globalThis[rt],Fs=class{constructor(e,t=!0){this.setContext(e),this.id=++js.id,this.currentOpCount=0,this.interruptible=t,this._stack=[],this._observers=void 0,this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0,this._running=!1,this._deferredInterrupt=!1,this._parent=void 0,this._asyncContext=void 0,this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[ks](){return As}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return li(this.context,e)}addObserver(e){return this._exit?(e(this._exit),u):(this._observers===void 0?this._observers=[e]:this._observers.push(e),()=>this.removeObserver(e))}removeObserver(e){if(this._exit||this._observers===void 0)return;let t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)}interruptUnsafe(e,t){if(this._exit)return;let n=os(e);this.cache.stackFrame&&(n=an(n,ri(mn,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(Js(this._interruptedCause)))}pollUnsafe(){return this._exit}evaluate(e){if(this._exit)return;if(this._asyncContext!==void 0){let t=this._asyncContext;this._asyncContext=void 0;try{return t.runInAsyncScope(this.evaluate,this,e)}finally{t.emitDestroy()}}else if(this._yielded!==void 0){let e=this._yielded;this._yielded=void 0,e()}let t=this.runLoop(e);if(t===Lt){this._asyncContext=Ns();return}let n=zs.interruptChildren&&zs.interruptChildren(this);if(n!==void 0)return this.evaluate(Ic(n,()=>t));if(this._exit=t,this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit),this._parent&&=(this._parent._children?.delete(this),void 0),this._observers!==void 0){let e=this._observers;this._observers=void 0;for(let n=0;n<e.length;n++)e[n](t)}this._stack.length=0,this._children=void 0,this.context=ti()}runLoop(e){let t=globalThis[rt];globalThis[rt]=this;let n=this._running;this._running=!0;let r=!1,i=e;this.currentOpCount=0;try{for(;;)try{this._deferredInterrupt&&(this._deferredInterrupt=!1,i=Js(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=Ic($s,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[Nt](this),i===Lt){let e=this._yielded;if(`~effect/Exit`in e)return this._deferredInterrupt=!1,this._yielded=void 0,e;if(this._deferredInterrupt){this._yielded=void 0,e();continue}return Lt}}catch(e){if(!me(i,`~effect/Effect/evaluate`))return vn(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=vn(e)}}finally{this._running=n,globalThis[rt]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Ls;for(;;){let t=this._stack.pop();if(!t)return;let n=t[It];if(n!==void 0){let r=n.call(t,this);if(r)return r[e]=r,r}if(t[e])return t}}succeedWith(e){if(!(++this.currentOpCount&Rs-1))return pn(e);let t=this.getCont(Pt);return t?t[Pt](e,this):this.yieldWith(pn(e))}yieldWith(e){return this._yielded=e,Lt}children(){return this._children??=new Set}pipe(){return e(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&Qr(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Is(e);this.cache?.scheduler!==r.scheduler&&(this._dispatcher=void 0),this.cache=r}get currentSpanLocal(){let e=this.cache.span;return e?._tag===`Span`?e:void 0}},Is=e=>{let t=si(e,Ho);return{scheduler:li(e,fo),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:li(e,qo),span:si(e,Io),logLevel:li(e,Qo),minimumLogLevel:li(e,$o),stackFrame:li(e,Ko),runtimeMetrics:si(e,Go),maxOpsBeforeYield:li(e,yo),preventYield:li(e,bo)}},Ls={[Pt](e,t){return Js(t._interruptedCause)},[Ft](e,t){return Js(t._interruptedCause)}},Rs=32,zs={interruptChildren:void 0},Bs=e=>{if(!e.cache.stackFrame)return;let t=new Map;return t.set(hn.key,e.cache.stackFrame),Xr(t)},Vs=e=>{let t=e;return t._exit?qs(t._exit):lc(n=>t._exit?n(qs(t._exit)):Xs(e.addObserver(e=>n(qs(e)))))},Hs=e=>lc(t=>{let n=e[Symbol.iterator](),r=[],i;function a(){let e=n.next();for(;!e.done;)if(e.value._exit)r.push(e.value._exit),e=n.next();else{i=e.value.addObserver(e=>{r.push(e),a()});return}t(qs(r))}return a(),Xs(()=>i?.())}),Us=e=>{let t=e;return t._exit?t._exit:lc(n=>t._exit?n(t._exit):Xs(e.addObserver(n)))},Ws=e=>yn(t=>Gs(e,t.id)),Gs=r(e=>me(e[0],ks),(e,t,n)=>yn(r=>{let i=Bs(r);return i=i&&n?mi(i,n):i??n,e.interruptUnsafe(t,i),Nc(Vs(e))})),Ks=e=>yn(t=>{let n=Bs(t),r=fa();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return Nc(Hs(r))}),qs=pn,Js=gn,Ys=_n,Xs=dn({op:`Sync`,[Nt](e){let t=this[Mt](),n=e.getCont(Pt);return n?n[Pt](t,e):e.yieldWith(pn(t))}}),Zs=dn({op:`Suspend`,[Nt](e){return this[Mt]()}}),Qs=Ai({onFailure:Ys,onSuccess:qs}),$s=dn({op:`Yield`,[Nt](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(Yc)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}})(0),ec=qs(v()),tc=e=>Zs(()=>Js(e())),nc=e=>vn(e),rc=qs(void 0),ic=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new Ed(e,`An error occurred in Effect.try`):e.catch;return Zs(()=>{try{return qs(t())}catch(e){return Ys(n(e))}})},ac=e=>sc(function(t,n){e(n).then(e=>t(qs(e)),e=>t(nc(e)))},e.length!==0),oc=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new Ed(e,`An error occurred in Effect.tryPromise`):e.catch;return sc(function(e,r){let i=e=>Zs(()=>{try{return Ys(Tt(()=>n(e)))}catch(e){return nc(e)}});try{t(r).then(t=>e(qs(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},sc=function(){let e=un({op:`Async`,[Nt](e){let t=!1,n=!1,r=this.withSignal?new AbortController:void 0,i=this.register.call(e.cache.scheduler,r=>{t||(t=!0,n?e.evaluate(r):n=r)},r?.signal);return n===!1?(n=!0,e.yieldWith(()=>{t=!0}),r===void 0&&i===void 0||e._stack.push(cc(()=>(t=!0,r?.abort(),i??Yc))),Lt):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),cc=dn({op:`AsyncFinalizer`,[It](e){e.interruptible&&(e.interruptible=!1,e._stack.push(xu))},[Ft](e,t){return ps(e)?Ic(Gl(gn(e),this[Mt]()),()=>Js(e)):Js(e)}}),lc=e=>sc(e,e.length>=2),uc=lc(u),dc=(...e)=>{if(e.length===1){let t=e[0];return Zs(()=>vc(t()))}let[t,n]=e;return Zs(()=>vc(n.call(t.self)))},fc=(e,...t)=>{let n=t.length===0?function(){return Zs(()=>vc(e.apply(this,arguments)))}:function(){let n=Zs(()=>vc(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return pc(e.length,n)},pc=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),mc=ns(2),hc=function(){let e=typeof arguments[0]==`string`,t=e?arguments[0]:`Effect.fn`,n=e?arguments[1]:void 0,r=St(),i;return r!==0&&(Ct(2),i=new globalThis.Error,Ct(r)),e?(r,...a)=>gc(t,r,i,a,e,n):gc(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},gc=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?mc(()=>n.stack):l;return pc(o.length,function(...t){let n=Zs(()=>{let e=o.apply(this,arguments);return Bt(e)?e:vc(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!Bt(n))return n;let u=St(),d;return u!==0&&(Ct(2),d=new globalThis.Error,Ct(u)),nl(i?od(e,a,e=>sd(n,e)):n,Ko,t=>({name:e,stack:d?mc(()=>d.stack):l,parent:{name:s,stack:c,parent:t}}))})},ree=(e,...t)=>pc(e.length,t.length===0?function(){return _c(()=>e.apply(this,arguments))}:function(){let n=_c(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),_c=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return qs(r.value);let i=r.value;if(i&&i._tag===`Success`)n=i.value;else{if(i&&i._tag===`Failure`)return r.value;{let n=!0;return Zs(()=>n?(n=!1,Ic(r.value,e=>vc(t,e))):Zs(()=>vc(e())))}}}}catch(e){return nc(e)}},vc=function(){let e=un({op:`Iterator`,[Pt](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return qs(r.value);if(!Lc(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)}}(),yc=r(2,(e,t)=>new Sc(e,Cc,qs(t))),bc=function(e){return e._stack.push(this),this[Mt]},xc=un({op:`OnSuccess`,[Nt]:bc}),Sc=function(e,t,n){this[Mt]=e,this[Pt]=t,this.payload=n};Sc.prototype=xc;var Cc=function(){return this.payload},wc=function(e,t){return t.succeedWith(this.payload)},Tc=(()=>{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})(),Ec=function(e,t){let n=this.payload;return t.succeedWith(Tc?n(e):Tt(()=>n(e)))},Dc=function(e){let t=this.payload;return t(e)},Oc=function(e){let t=this.payload;return new Sc(t(e),wc,e)},kc=function(e){return new Sc(this.payload,wc,e)},Ac=e=>Bc(e,y),jc=r(2,(e,t)=>new Sc(e,Bt(t)?Cc:Dc,t)),Mc=r(2,(e,t)=>new Sc(e,Bt(t)?kc:Oc,t)),Nc=e=>new Sc(e,Cc,Yc),Pc=(e,t)=>yn(n=>{let r=new Set;return su(n,()=>r.size===0?void 0:Ks(r)),lc(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=Lu(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})})}})}),Fc=r(e=>Bt(e[1]),(e,t,n)=>Pc([e,t],n)),Ic=r(2,(e,t)=>new Sc(e,Dc,t)),Lc=e=>e[kt]!==void 0,Rc=r(2,(e,t)=>Lc(e)?e._tag===`Success`?t(e.value):e:Ic(e,t)),zc=e=>Ic(e,i),Bc=r(2,(e,t)=>new Sc(e,Ec,t)),Vc=r(2,(e,t)=>Lc(e)?Xc(e,t):Bc(e,t)),Hc=r(2,(e,t)=>Lc(e)?Zc(e,t):Cl(e,t)),Uc=r(2,(e,t)=>Lc(e)?Qc(e,t):wl(e,t)),Wc=e=>gn(os(e)),Gc=e=>e._tag===`Success`,Kc=e=>e._tag===`Failure`,qc=e=>e._tag===`Failure`?xi(e.cause):Si(e),Jc=e=>e._tag===`Failure`&&ps(e.cause),Yc=pn(void 0),Xc=r(2,(e,t)=>e._tag===`Success`?pn(t(e.value)):e),Zc=r(2,(e,t)=>e._tag===`Success`?e:gn(gs(e.cause,t))),Qc=r(2,(e,t)=>e._tag===`Success`?pn(t.onSuccess(e.value)):gn(gs(e.cause,t.onFailure))),iee=r(2,(e,t)=>Gc(e)?t:e),$c=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?Yc:gn(Zt(t))},el=e=>yn(t=>qs(pi(t.context,e))),tl=r(2,(e,t)=>yn(n=>{let r=n.context,i=t(r);return r===i||(n.setContext(i),su(n,()=>{n.setContext(r)})),e})),nl=r(3,(e,t,n)=>tl(e,e=>{let r=ci(e,t),i=n(r);return r===i?e:ii(e,t,i)})),rl=()=>il,il=yn(e=>qs(e.context)),al=e=>yn(t=>e(t.context)),ol=r(2,(e,t)=>Lc(e)?e:tl(e,mi(t))),sl=function(){return arguments.length===1?r(2,(e,t)=>cl(e,arguments[0],t)):r(3,(e,t,n)=>cl(e,t,n)).apply(this,arguments)},cl=(e,t,n)=>tl(e,ii(t,n)),ll=r(e=>Bt(e[0]),(e,t)=>Ou({while:o,body:a(t?.disableYield?e:Ic(e,e=>$s)),step:u})),ul=r(2,(e,t)=>new fl(e,t.length===1?t:e=>t(e))),dl=un({op:`OnFailure`,[Nt]:bc}),fl=function(e,t){this[Mt]=e,this[Ft]=t};fl.prototype=dl;var pl=r(3,(e,t,n)=>ul(e,e=>{let r=t(e);return Ei(r)?Js(r.failure):n(r.success,e)})),ml=r(2,(e,t)=>pl(e,ds,e=>t(e))),hl=r(2,(e,t)=>pl(e,fs,t)),gl=r(2,(e,t)=>ul(e,e=>jc(t(e),Js(e)))),_l=r(3,(e,t,n)=>ul(e,e=>{let r=t(e);return Ei(r)?Js(e):jc(n(r.success,e),Js(e))})),vl=r(2,(e,t)=>_l(e,cs,e=>t(e))),yl=r(e=>Bt(e[0]),(e,t,n,r)=>ul(e,e=>{let i=ds(e);return Ei(i)?Js(i.failure):t(i.success)?n(i.success):r?r(i.success):Js(e)})),bl=r(e=>Bt(e[0]),(e,t,n,r)=>ul(e,e=>{let i=ds(e);if(Ei(i))return Js(i.failure);let a=t(i.success);return Ei(a)?r?r(a.failure):Js(e):n(a.success)})),xl=r(e=>Bt(e[0]),(e,t,n,r)=>yl(e,Array.isArray(t)?e=>me(e,`_tag`)&&t.includes(e._tag):he(t),n,r)),Sl=r(e=>Bt(e[0]),(e,t,n)=>{let r;return bl(e,e=>(r??=Object.keys(t),me(e,`_tag`)&&te(e._tag)&&r.includes(e._tag)?xi(e):Si(e)),e=>t[e._tag](e),n)}),Cl=r(2,(e,t)=>ul(e,e=>Js(gs(e,t)))),wl=r(2,(e,t)=>kl(e,{onFailure:e=>Js(gs(e,t.onFailure)),onSuccess:e=>Xs(()=>t.onSuccess(e))})),Tl=e=>ml(e,nc),El=r(e=>Bt(e[0]),(e,t)=>{if(!t?.log)return Pl(e,{onFailure:e=>rc,onSuccess:e=>rc});let n=Fd(t.log===!0?void 0:t.log);return kl(e,{onFailure(e){let r=ds(e);return Ei(r)?Js(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>rc})}),Dl=e=>Fl(e,{onFailure:v,onSuccess:y}),Ol=e=>Il(e,{onFailure:Si,onSuccess:xi}),kl=r(2,(e,t)=>new jl(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),Al=un({op:`OnSuccessAndFailure`,[Nt]:bc}),jl=function(e,t,n){this[Mt]=e,this[Pt]=t,this[Ft]=n};jl.prototype=Al;var Ml=function(e,t){let n=this.payload;return t.succeedWith(Tc?n.onSuccess(e):Tt(()=>n.onSuccess(e)))},Nl=((e,t)=>{let n=un({op:e,[Nt]:bc,[Pt]:Ml,[Ft]:t}),r=function(e,t){this[Mt]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=ds(e);if(Ei(n))return Js(n.failure);let r=this.payload;return t.succeedWith(Tc?r.onFailure(n.success):Tt(()=>r.onFailure(n.success)))}),Pl=r(2,(e,t)=>kl(e,{onFailure:e=>{let n=ds(e);return Ei(n)?Js(n.failure):t.onFailure(n.success)},onSuccess:t.onSuccess})),Fl=r(2,(e,t)=>new Nl(e,t)),Il=r(2,(e,t)=>{if(Lc(e)){if(e._tag===`Success`)return pn(t.onSuccess(e.value));let n=ds(e.cause);return Ei(n)?gn(n.failure):pn(t.onFailure(n.success))}return Fl(e,t)}),Ll=e=>Lc(e)?pn(e):Rl(e),Rl=dn({op:`Exit`,[Nt](e){return e._stack.push(this),this[Mt]},[Pt](e,t,n){return t.succeedWith(n??pn(e))},[Ft](e,t,n){return t.succeedWith(n??gn(e))}}),zl=`~effect/Scope`,Bl=`~effect/Scope/Closeable`,Vl=Lr(`effect/Scope`),Hl=(e,t)=>yn(n=>(wu(n),Ul(e,t)??rc)),Ul=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&Zl(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return Wl(n.finalizer,t);let r=n.finalizers;return r.size===1?Wl(r.values().next().value,t):Kl(e,r,t)},Wl=(e,t)=>{try{return e(t)}catch(e){return vn(e)}},Gl=(e,t)=>Gc(e)?t:ul(t,t=>Js(us(Qt(e.cause,t)))),Kl=fc(function*(e,t,n){let r=[],i=[],a=Array.from(t),o=Ps();for(let t=a.length-1;t>=0;t--){let[s,c]=a[t];e.strategy===`sequential`?r.push(yield*Ll(Wl(c,n))):s!==o&&i.push(Lu(o,Wl(c,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*Hs(i)),yield*$c(r)}),ql=(e,t)=>{let n=$l(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(Xl(e,n,e=>Hl(n,e)),n)},Jl=(e,t)=>Zs(()=>e.state._tag===`Closed`?t(e.state.exit):(Xl(e,{},t),rc)),Yl=(e,t)=>Jl(e,a(t)),Xl=(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)}},Zl=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=eu:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=eu))},Ql=e=>$l(e,void 0),$l=(e=`sequential`,t)=>({[Bl]:Bl,[zl]:zl,strategy:e,parent:t,state:eu}),eu={_tag:`Empty`},tu=Vl,nu=sl(Vl),ru=e=>Zs(()=>{let t=Ql();return cu(e(t),e=>Zs(()=>Ul(t,e)??rc))}),iu=(e,t,n)=>al(r=>Eu(i=>Ic(tu,a=>Mc(n?.interruptible?i(e):e,e=>Jl(a,n=>ol(t(e,n),r)))))),au=function(){let e=un({op:`OnExit`,[Nt](e){return e._stack.push(this),this.effect},[It](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(xu),e.interruptible=!1)},[Pt](e,t,n){n??=pn(e);let r;try{r=this.onExit(n)}catch(e){r=vn(e)}return r?Ic(r,e=>n):n},[Ft](e,t,n){n??=gn(e);let r;try{r=this.onExit(n)}catch(e){r=vn(e)}return r?Ic(Gl(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),ou=(e,t,n)=>new au(e,t,n),su=(e,t)=>{e._stack.push(new au(void 0,t,void 0))},cu=r(2,ou),lu=r(2,(e,t)=>cu(e,e=>t)),uu=r(3,(e,t,n)=>cu(e,e=>{let r=t(e);return Ei(r)?rc:n(r.success,e)})),du=r(2,(e,t)=>uu(e,qc,t)),fu=r(3,(e,t,n)=>cu(e,e=>{if(e._tag!==`Failure`)return rc;let r=t(e.cause);return Ei(r)?rc:n(r.success,e.cause)})),pu=r(2,(e,t)=>fu(ms,t)(e)),mu=(e,t,n)=>Eu(r=>Ic(e,e=>ou(Zs(()=>r(t(e))),t=>n(e,t),!0))),hu=a(1/0),gu=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,su(e,()=>{if(!(--t.awaiters>0||t.done))return i===t&&(i=void 0),Ws(t.fiber)}),Us(t.fiber));return[yn(o=>{if(i!==void 0)return o===i.fiber?Us(i.fiber):a(o,i);if(r!==void 0&&(n===1/0||o.getRef(fd).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(fd),c={fiber:new Fs(o.context),awaiters:0,done:!1};i=c;let l=a(o,c);return c.fiber.evaluate(ou(e,e=>{if(c.done=!0,i!==c||(i=void 0,Jc(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e})),c.fiber._exit??l}),Xs(()=>{i=void 0,r=void 0})]},_u=e=>Xs(()=>gu(e,hu)[0]),vu=yn(e=>Js(os(e.id))),yu=e=>yn(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(xu)),e)),bu=dn({op:`SetInterruptible`,[It](e){if(e.interruptible=this[Mt],e._interruptedCause&&e.interruptible)return()=>Js(e._interruptedCause)}}),xu=bu(!0),Su=bu(!1),Cu=e=>{if(e.interruptible=!0,e._stack.push(Su),e._interruptedCause)return Js(e._interruptedCause)},wu=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(xu))},Tu=e=>yn(t=>t.interruptible?e:Cu(t)??e),Eu=e=>yn(t=>t.interruptible?(t.interruptible=!1,t._stack.push(xu),e(Tu)):e(i)),Du=(e,t)=>_e(e)?t?.mode===`result`?ku(e,Ol,t):ku(e,i,t):t?.discard?t.mode===`result`?ku(Object.values(e),Ol,t):ku(Object.values(e),i,t):Zs(()=>Bc(ku(Object.entries(e),([e,n])=>Bc(t?.mode===`result`?Ol(n):n,t=>[e,t]),{concurrency:t?.concurrency}),Object.fromEntries)),Ou=dn({op:`While`,[Pt](e,t){return this[Mt].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[Mt].body()):Yc},[Nt](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[Mt].body()):Yc}}),ku=r(e=>typeof e[1]==`function`,(e,t,n)=>Zs(()=>{let r=ju(n?.concurrency);if(r===1)return Au(e,t,n);let i=Wi(e),a=i.length;if(a===0)return n?.discard?rc:qs([]);let o=n?.discard?void 0:Array(a),s=Fu({f:t,out:o},i,{concurrency:r});return s?yc(s,o):qs(o)})),Au=(e,t,n)=>Zs(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return yc(Ou({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),ju=e=>e===`unbounded`?1/0:Math.max(1,e??1),Mu=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>Ic(Ll(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??rc),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!Lc(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},Nu=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=vn(e);return f=t,c=!0,u&&u.size>0?Ic(yu(Ks(Array.from(u))),()=>f??t):t},h=()=>{let i=!1;for(;!f&&a<o;a++){let o=r[a],g=p??t(e,o,a);if(Lc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=Lu(l,g,!0,!0,`inherit`);if(t._exit){if(f=n(e,o,t._exit,a),f)break;continue}u.add(t);let r=a;if(t.addObserver(a=>{u.delete(t);try{if(f){if(a._tag===`Failure`){let e=a.cause.reasons.filter(e=>e._tag!==`Interrupt`);if(e.length>0){let t=Zt(e);f=gn(f._tag===`Failure`?us(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??rc)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return lc(e=>{l=Ps(),u=new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):Zs(()=>(f??=Yc,Ic(u?Ks(u):rc,()=>f?._tag===`Failure`?f:rc)))})}if(c=!0,f){if(u&&u.size>0){let e=Bs(l);u.forEach(t=>t.interruptUnsafe(l.id,e));return}if(d||f._tag===`Failure`)return f}else if(d){if(u)u.size===0&&d(rc);else return Yc}};return h()}},Pu=()=>e=>Nu(e),Fu=Nu({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)}}),Iu=r(e=>_e(e[0])&&!Bt(e[0]),(e,t,n)=>Bc(ku(e,(e,n)=>{let r=t(e,n);return typeof r==`boolean`?qs(r?y(e):v()):Bc(r,t=>t?y(e):v())},n),ha)),Lu=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new Fs(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=Ns(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},Ru=e=>()=>yn(t=>t===e?rc:Ws(e)),zu=r(e=>Bt(e[0]),(e,t,n)=>yn(r=>{let i=t.state._tag===`Closed`?new Fs(r.context):Lu(r,e,n?.startImmediately,!0,n?.uninterruptible);return i._exit||(t.state._tag===`Closed`?i.interruptUnsafe(r.id,Bs(r)):(Xl(t,i,Ru(i)),i.addObserver(()=>Zl(t,i)))),qs(i)})),Bu=r(e=>Bt(e[0]),(e,t)=>Ic(tu,n=>zu(e,n,t))),Vu=e=>(t,n)=>{let r=new Fs(n?.scheduler?ii(e,fo,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal){if(n.signal.aborted)r.interruptUnsafe();else{let e=()=>r.interruptUnsafe();n.signal.addEventListener(`abort`,e,{once:!0}),r.addObserver(()=>n.signal.removeEventListener(`abort`,e))}}return n?.onFiberStart&&n.onFiberStart(r),r},Hu=r(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):(Zl(t,e),Xl(t,e,Ru(e)),e.addObserver(()=>Zl(t,e)),e)),Uu=Vu(ti()),Wu=e=>{let t=Vu(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},Gu=(e=>{let t=Wu(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw _s(e.cause);return e.value})})(ti()),Ku=e=>{let t=Vu(e);return e=>{if(Lc(e))return e;let n=new _o(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??vn(new wd(r))}},qu=Ku(ti()),Ju=(e=>{let t=Ku(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw _s(n.cause);return n.value}})(ti()),Yu=qs(!0),Xu=qs(!1),Zu=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return Yu;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=[],Yu}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](Yc)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](Yc)}open=yn(e=>this._isOpen?Xu:(this._isOpen=!0,this.scheduleUnsafe(e)));release=yn(e=>this._isOpen?Xu:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=lc(e=>this._isOpen?e(rc):(this.waiters.push(e),Xs(()=>{let t=this.waiters.indexOf(e);t===-1?this.scheduled!==void 0&&(t=this.scheduled.indexOf(e),t!==-1&&this.scheduled.splice(t,1)):this.waiters.splice(t,1)})));closeUnsafe(){return this._isOpen?(this._isOpen=!1,!0):!1}close=Xs(()=>this.closeUnsafe());whenOpen=e=>Ic(this.await,()=>e);isOpen(){return this._isOpen}},Qu=e=>new Zu(e??!1),$u=BigInt(0),ed={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:$u,endTime:$u,exit:Yc},attributes:new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},td=e=>Object.assign(Object.create(ed),e),nd=e=>e?li(e.annotations,zo)?e._tag===`Span`?nd(wr(e.parent)):v():y(e):v(),rd=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&li(n.annotations,zo),i=n?.parent===void 0?n?.root?v():nd(e.cache.span):y(n.parent),a;if(r)a=td({name:t,parent:i,annotations:ii(n?.annotations??ti(),zo,!0)});else{let r=e.cache.tracer??Uo,o=e.getRef(fd),s=e.getRef(Jo),c=e.getRef(Yo),l=e.getRef(Xo),u=n?.level??e.getRef(Bo),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??ti(),links:d,startTime:s?o.currentTimeNanosUnsafe():$u,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(x(i)&&i.value.sampled===!1?!1:!Od(e.getRef(Vo),u))});for(let e in c)a.attribute(e,c[e]);if(n?.attributes!==void 0)for(let e in n.attributes)a.attribute(e,n.attributes[e])}return a},id=(e,t)=>(t=typeof t==`function`?t:l,nl(Ko,n=>({name:e,stack:t,parent:n}))),ad=(e,t,n,r)=>Xs(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():$u,t)}),od=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return yn(t=>{let i=rd(t,e,n),a=t.getRef(fd),o=t.getRef(Jo);return su(t,e=>ad(i,e,a,o)),r(i)})},sd=sl(Lo),cd=function(){let e=Bt(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=i;return t._tag===`Span`&&(n=ts(n),r=id(t.name,n?.captureStackTrace)),e?sd(r(arguments[0]),t):e=>sd(r(e),t)},ld=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=ts(arguments[2]);if(e){let e=arguments[0];return od(t,arguments[2],t=>cd(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>od(t,r?r(...a):i,t=>cd(e,t,n))},ud=(...e)=>yn(t=>{let n=t.currentSpanLocal;if(n){if(e.length===1)for(let[t,r]of Object.entries(e[0]))n.attribute(t,r);else n.attribute(e[0],e[1])}return rc}),dd=yn(e=>{let t=e.currentSpanLocal;return t?qs(t):Ys(new wn)}),fd=_i(`effect/Clock`,{defaultValue:()=>new md}),pd=2**31-1,md=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=Xs(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return _d()}currentTimeNanos=Xs(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return gd()}monotonicTimeNanos=Xs(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(no(e))}sleepMillis(e){return e<=0?$s:Number.isFinite(e)?lc(t=>{let n=e>pd?this.sleepMillis(e-pd):rc,r=setTimeout(()=>t(n),Math.min(e,pd));return Xs(()=>clearTimeout(r))}):uc}},hd=BigInt(1e6),gd=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())*hd;return e>t&&(t=e),t}}(),_d=function(){let e=BigInt(1e9),t;return()=>{let n=gd(),r=BigInt(Date.now())*hd;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}}(),vd=e=>yn(t=>e(t.getRef(fd))),yd=e=>vd(t=>t.sleep(za(e))),bd=vd(e=>e.currentTimeMillis),xd=`~effect/Cause/IllegalArgumentError`,Sd=class extends Sn(`IllegalArgumentError`){[xd]=xd;constructor(e){super({message:e})}},Cd=`~effect/Cause/AsyncFiberError`,wd=class extends Sn(`AsyncFiberError`){[Cd]=Cd;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}},Td=`~effect/Cause/UnknownError`,Ed=class extends Sn(`UnknownError`){[Td]=Td;constructor(e,t){super({message:t,cause:e})}},Dd=_i(`effect/Console`,{defaultValue:()=>globalThis.console}),Od=pr(dr(cr,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}})),kd=_i(`effect/Logger/CurrentLoggers`,{defaultValue:()=>new Set([Rd,zd])}),Ad=_i(`effect/Logger/LogToStderr`,{defaultValue:s}),jd={"~effect/Logger":{_Message:i,_Output:i},pipe(){return e(this,arguments)}},Md=e=>{let t=Object.create(jd);return t.log=e,t},Nd=e=>e.replace(/[\s="]/g,`_`),Pd=(e,t)=>`${Nd(e[0])}=${t-e[1]}ms`,Fd=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];Wt(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?Zt(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=en),yn(r=>{let i=e??r.cache.logLevel;if(Od(r.cache.minimumLogLevel,i))return rc;let a=r.getRef(fd),o=r.getRef(kd);if(o.size>0){let e=new Date(a.currentTimeMillisUnsafe());for(let a of o)a.log({cause:n,fiber:r,date:e,logLevel:i,message:t})}return rc})},Id={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};Id.gray,Id.blue,Id.green,Id.yellow,Id.red,Id.bgBrightRed,Id.black;var Ld=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`)}`,Rd=Md(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Es(e));let o=t.getTime(),s=n.getRef(es),c=``;for(let e of s)c+=` ${Pd(e,o)}`;let l=n.getRef(Zo);Object.keys(l).length>0&&a.push(l);let u=n.getRef(Dd);(n.getRef(Ad)?u.error:u.log)(`[${Ld(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),zd=Md(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(fd),a=t.getRef(Zo),o=t.cache.span;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))Et(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=Es(e)),o.event(vt(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)}),Bd=Wt,Vd=Gt,Hd=on,Ud=Zt,Wd=tn,Gd=rn,Kd=e=>new Xt(e),qd=e=>new nn(e),Jd=as,Yd=hs,Xd=gs,Zd=Qt,Qd=_s,$d=ps,ef=ms,tf=Es,nf=En,rf=An,af=Sd,of=pn,sf=gn,cf=_n,lf=Yc,uf=Gc,df=Kc,ff={"~effect/Deferred":{_A:i,_E:i},pipe(){return e(this,arguments)}},pf=function(){this.resumes=void 0,this.effect=void 0};pf.prototype=ff;var mf=()=>new pf,hf=()=>Xs(()=>mf()),gf=e=>lc(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),Xs(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),_f=r(2,(e,t)=>Xs(()=>xf(e,t))),vf=e=>Xs(()=>yf(e)),yf=e=>e.effect!==void 0,bf=r(2,(e,t)=>_f(e,pn(t))),xf=(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},Sf=r(2,(e,t)=>Eu(n=>Ic(Ll(n(e)),e=>_f(t,e)))),Cf=Jo,wf=Vl,Tf=Ql,Ef=nu,Df=Jl,Of=Yl,kf=ql,Af=Hl,jf=`~effect/Layer`,Mf=`~effect/Layer/MemoMap`,Nf=(e,t)=>{let n={observers:0,deferred:mf(),scope:Tf(),finalizer:r=>Zs(()=>--n.observers>0?rc:(e.map.delete(t),Af(n.scope,r)))};return n},Pf=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,Xl(t,{},e.finalizer),!0),Ff={[jf]:{_ROut:i,_E:i,_RIn:i},pipe(){return e(this,arguments)}},If=e=>{let t=Object.create(Ff);return t.build=e,t},Lf=e=>If((t,n)=>{let r=kf(n);return cu(e(t,r),e=>e._tag===`Failure`?Af(r,e):rc)}),Rf=e=>{let t=Lf((n,r)=>n.getOrElseMemoize(t,r,e));return t},zf=class{get[Mf](){return Mf}parent;constructor(e){this.parent=e}map=new Map;get(e,t){let n=this.map.get(e);return n?(Pf(n,t),n.deferred.effect??gf(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return Zs(()=>{let r;return ou(Zs(()=>{let i=this.get(e,t);if(i)return i;let a=Nf(this,e);return Pf(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&xf(r,e)})})}},Bf=()=>new zf,Vf=e=>new zf(e),Hf=class e extends Lr()(`effect/Layer/CurrentMemoMap`){static forkOrCreate(t){let n=oi(t,e);return n?Vf(n):Bf()}},Uf=r(3,(e,t,n)=>sl(Bc(Zs(()=>e.build(t,n)),ii(Hf,t)),Hf,t)),Wf=r(2,(e,t)=>yn(n=>Uf(e,Hf.forkOrCreate(n.context),t))),Gf=function(){return arguments.length===1?e=>Kf(ri(arguments[0],e)):Kf(ri(arguments[0],arguments[1]))},Kf=e=>If(a(qs(e))),qf=function(){return arguments.length===1?e=>Jf(arguments[0],e):Jf(arguments[0],arguments[1])},Jf=(e,t)=>Yf(Bc(t,t=>ri(e,t))),Yf=e=>Rf((t,n)=>Ef(e,n)),Xf=e=>Yf(yc(e,ti())),Zf=(e,t,n)=>{let r=kf(n,`parallel`);return ku(e,e=>e.build(t,kf(r,`sequential`)),{concurrency:e.length}).pipe(Bc(e=>hi(...e)))},Qf=(...e)=>Rf((t,n)=>Zf(e,t,n)),$f=(e,t,n)=>Rf((r,i)=>Ic(Array.isArray(t)?Zf(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(ol(t),Bc(e=>n(e,t))))),ep=r(2,(e,t)=>$f(e,t,i)),tp=r(2,(e,t)=>$f(e,t,(e,t)=>mi(t,e))),np=fd,rp=bd,ip=`~effect/DateTime`,ap=`~effect/DateTime/TimeZone`,op={[ip]:ip,pipe(){return e(this,arguments)},[gt](){return this.toString()},toJSON(){return zp(this).toJSON()}},sp={...op,_tag:`Utc`,[ve](){return Te(this.epochMilliseconds)},[Le](e){return pp(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${zp(this).toJSON()})`}},cp={...op,_tag:`Zoned`,[ve](){return Se(Te(this.epochMilliseconds))(ye(this.zone))},[Le](e){return pp(e)&&e._tag===`Zoned`&&this.epochMilliseconds===e.epochMilliseconds&&Re(this.zone,e.zone)},toString(){return`DateTime.Zoned(${lm(this)})`}},lp={[ap]:ap,[gt](){return this.toString()}},up={...lp,_tag:`Named`,[ve](){return Ee(`Named:${this.id}`)},[Le](e){return hp(e)&&e._tag===`Named`&&this.id===e.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:`TimeZone`,_tag:`Named`,id:this.id}}},dp={...lp,_tag:`Offset`,[ve](){return Ee(`Offset:${this.offset}`)},[Le](e){return hp(e)&&e._tag===`Offset`&&this.offset===e.offset},toString(){return`TimeZone.Offset(${Hp(this.offset)})`},toJSON(){return{_id:`TimeZone`,_tag:`Offset`,offset:this.offset}}},fp=(e,t,n)=>{let r=Object.create(cp);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},pp=e=>me(e,ip),mp=e=>pp(e[0]),hp=e=>me(e,ap),gp=e=>hp(e)&&e._tag===`Named`,_p=e=>e._tag===`Utc`,vp=e=>e._tag===`Zoned`,yp=e=>{let t=Object.create(sp);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},bp=e=>{let t=e.getTime();if(Number.isNaN(t))throw new af(`Invalid date`);return yp(t)},xp=e=>{if(pp(e))return e;if(e instanceof Date)return bp(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return bp(new Date(e.epochMilliseconds));let t=new Date(0);return Jp(t,e),bp(t)}return typeof e==`string`&&!Sp(e)?bp(new Date(e+`Z`)):bp(new Date(e))},Sp=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e)||/z$|gmt$/i.test(e),Cp=-864e13+432e5,wp=864e13-504e5,Tp=(e,t)=>{let n=t?.timeZone;if(n===void 0&&pp(e)&&vp(e))return e;let r=xp(e);if(r.epochMilliseconds<Cp||r.epochMilliseconds>wp)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=Pp(new Date(r.epochMilliseconds).getTimezoneOffset()*-60*1e3);else if(hp(n))i=n;else if(typeof n==`number`)i=Pp(n);else{let e=Lp(n);if(b(e))throw new af(`Invalid time zone: ${n}`);i=e.value}return t?.adjustForTimeZone===!0?Xp(r.epochMilliseconds,i,t?.disambiguation??`compatible`):fp(r.epochMilliseconds,i,r.partsUtc)},Ep=Tr(xp),Dp=Bc(rp,yp),Op=e=>yp(e.epochMilliseconds),kp=r(mp,(e,t,n)=>n?.adjustForTimeZone===!0?Xp(e.epochMilliseconds,t,n?.disambiguation??`compatible`):fp(e.epochMilliseconds,t,e.partsUtc)),Ap=new Map,jp={day:`numeric`,month:`numeric`,year:`numeric`,era:`short`,hour:`numeric`,minute:`numeric`,second:`numeric`,timeZoneName:`longOffset`,fractionalSecondDigits:3,hourCycle:`h23`},Mp=e=>{let t=e.resolvedOptions().timeZone,n=Ap.get(t);if(n!==void 0)return n;let r=Object.create(up);return r.id=t,r.format=e,Ap.set(t,r),r},Np=e=>{let t=Ap.get(e);if(t!==void 0)return t;try{let t=Mp(new Intl.DateTimeFormat(`en-US`,{...jp,timeZone:e}));return Ap.set(e,t),t}catch{throw new af(`Invalid time zone: ${e}`)}},Pp=e=>{let t=Object.create(dp);return t.offset=e,t},Fp=Tr(Np),Ip=/^(?:GMT)?[+-]/,Lp=e=>{if(Ip.test(e)){let t=Qp(e);return t===null?v():y(Pp(t))}return Fp(e)},Rp=r(mp,(e,t,n)=>Dr(Fp(t),t=>kp(e,t,n))),zp=e=>new Date(e.epochMilliseconds),Bp=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},Vp=e=>Bp(e).getTime()-Wp(e),Hp=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`)}`},Up=e=>Hp(Vp(e)),Wp=e=>e.epochMilliseconds,Gp=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()}),Kp=e=>e._tag===`Utc`?qp(e):(e.partsAdjusted===void 0&&(e.partsAdjusted=rm(e,Gp)),e.partsAdjusted),qp=e=>(e.partsUtc===void 0&&(e.partsUtc=im(e,Gp)),e.partsUtc),Jp=(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)},Yp=864e5,Xp=(e,t,n)=>{if(t._tag===`Offset`)return fp(e-t.offset,t);let r=$p(e-Yp,e,t),i=$p(e+Yp,e,t);if(r===i)return fp(e-r,t);let a=r<i,o=r-i;if(a){if($p(e-i,e,t)===i)return fp(e-i,t);let a=fp(e-r,t);if(e!==Bp(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 fp(e-i,t);case`compatible`:case`later`:return a}return a}if($p(e-r,e,t)===r){if(n===`earlier`||n===`compatible`||$p(e-r+o,e+o,t)===r)return fp(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 fp(e-i,t)},Zp=/([+-])(\d{2}):?(\d{2})$/,Qp=e=>{let t=Zp.exec(e);if(t===null)return null;let[,n,r,i]=t;return(n===`+`?1:-1)*(Number(r)*60+Number(i))*60*1e3},$p=(e,t,n)=>{let r=n.format.formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??``;if(r===`GMT`)return 0;let i=Qp(r);return i===null?Vp(fp(t,n)):i},em=r(mp,(e,t,n)=>{if(e._tag===`Utc`){let n=zp(e);return t(n),yp(n.getTime())}let r=Bp(e),i=new Date(r.getTime());return t(i),Xp(i.getTime(),e.zone,n?.disambiguation??`compatible`)}),tm=r(2,(e,t)=>nm(e,e=>{let n=new Date(e);return t(n),n.getTime()})),nm=r(2,(e,t)=>{let n=t(Wp(e));return e._tag===`Utc`?yp(n):fp(n,e.zone)}),rm=r(2,(e,t)=>t(Bp(e))),im=r(2,(e,t)=>t(zp(e))),am=r(2,(e,t)=>{let n=tm(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:em(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)}})}),om=r(2,(e,t)=>{let n={};for(let e in t)n[e]=-1*t[e];return am(e,n)}),sm=e=>zp(e).toISOString(),cm=e=>{let t=Bp(e);return e._tag===`Utc`?t.toISOString():`${t.toISOString().slice(0,-1)}${Up(e)}`},lm=e=>e.zone._tag===`Offset`?cm(e):`${cm(e)}[${e.zone.id}]`;globalThis.Number;var um=cr;globalThis.String;var dm=e=>e.toLowerCase(),aee=e=>e.length>0,fm=`~effect/Cron`;function pm(e){return{tz:e.tz,and:e.and,seconds:Wi(e.seconds),minutes:Wi(e.minutes),hours:Wi(e.hours),days:Wi(e.days),months:Wi(e.months),weekdays:Wi(e.weekdays)}}var mm={[fm]:fm,[Le](e){return hm(e)&&Nm(this,e)},[ve](){return d(ye(this.tz),Se(ye(this.and)),Se(Ae(Wi(this.seconds))),Se(Ae(Wi(this.minutes))),Se(Ae(Wi(this.hours))),Se(Ae(Wi(this.days))),Se(Ae(Wi(this.months))),Se(Ae(Wi(this.weekdays))))},toObject(){return pm(this)},toString(){return`Cron(${ot(pm(this))})`},toJSON(){let e=pm(this);return e._id=`Cron`,e},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},hm=e=>me(e,fm),gm=e=>{let t=Object.create(mm);t.seconds=vm.seconds(e.seconds??[0]),t.minutes=vm.minutes(e.minutes),t.hours=vm.hours(e.hours),t.days=vm.days(e.days),t.months=vm.months(e.months),t.weekdays=vm.weekdays(e.weekdays),t.and=e.and===!0,t.tz=Sr(e.tz);let n=Array.from(t.seconds),r=Array.from(t.minutes),i=Array.from(t.hours),a=Array.from(t.days),o=Array.from(t.months),s=Array.from(t.weekdays);return t.first={second:n[0]??0,minute:r[0]??0,hour:i[0]??0,day:a[0]??1,month:(o[0]??1)-1,weekday:s[0]??0},t.last={second:n[n.length-1]??59,minute:r[r.length-1]??59,hour:i[i.length-1]??23,day:a[a.length-1]??31,month:(o[o.length-1]??12)-1,weekday:s[s.length-1]??6},t.next={second:bm.next.second(n),minute:bm.next.minute(r),hour:bm.next.hour(i),day:bm.next.day(a),month:bm.next.month(o),weekday:bm.next.weekday(s)},t.prev={second:bm.prev.second(n),minute:bm.prev.minute(r),hour:bm.prev.hour(i),day:bm.prev.day(a),month:bm.prev.month(o),weekday:bm.prev.weekday(s)},t},_m=(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(ia(a,um))},vm={seconds:_m(`seconds`,0,59),minutes:_m(`minutes`,0,59),hours:_m(`hours`,0,23),days:_m(`days`,1,31),months:_m(`months`,1,12),weekdays:_m(`weekdays`,0,7,e=>e===7?0:e)},ym=(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},bm={prev:{second:ym(60,`prev`),minute:ym(60,`prev`),hour:ym(24,`prev`),day:ym(32,`prev`),month:ym(13,`prev`),weekday:ym(7,`prev`)},next:{second:ym(60,`next`),minute:ym(60,`next`),hour:ym(24,`next`),day:ym(32,`next`),month:ym(13,`next`),weekday:ym(7,`next`)}},xm=`~effect/Cron/CronParseError`,Sm=class extends Co(`CronParseError`){[xm]=xm},Cm=(e,t)=>{let n=e.trim().split(/\s+/).filter(aee);if(n.length!==5&&n.length!==6)return Si(new Sm({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 Mi({tz:t===void 0||hp(t)?xi(t):Ci(Lp(t),()=>new Sm({message:`Invalid time zone in cron expression`,input:t})),seconds:Bm(r,Pm),minutes:Bm(i,Fm),hours:Bm(a,Im),days:Bm(o,Lm),months:Bm(s,Rm),weekdays:Bm(c,zm)}).pipe(ki(({tz:e,seconds:t,minutes:n,hours:r,days:i,months:a,weekdays:o})=>gm({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})))},wm=(e,t)=>ji(Cm(e,t)),Tm=(e,t)=>{let n=Tp(t,{timeZone:wr(e.tz)}).pipe(Kp);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)},Em=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+1,0)).getUTCDate(),Dm=(e,t)=>km(e,t,`next`),Om=(e,t)=>km(e,t,`prev`),km=(e,t,n)=>{let r=wr(e.tz),i=Tp(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&&gp(r)&&r.id===`UTC`,p=f?u:e=>{let t=Tp(e,{timeZone:i.zone,adjustForTimeZone:!0,disambiguation:a?`later`:void 0}).pipe(Bp),n=e.getTime()-t.getTime();(a?n!==0:n>0)&&e.setTime(a?t.getTime():e.getTime()+n)},m=a||f?s:e=>Tp(e,{timeZone:i.zone,adjustForTimeZone:!0}).epochMilliseconds<=i.epochMilliseconds;return zp(em(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=Em(t)-e+l.day}else r=!a&&n>Em(t)?Em(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=Em(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`)}))},Am=Mn((e,t)=>Re(e.tz,t.tz)&&e.and===t.and&&Mm(e.seconds,t.seconds)&&Mm(e.minutes,t.minutes)&&Mm(e.hours,t.hours)&&Mm(e.days,t.days)&&Mm(e.months,t.months)&&Mm(e.weekdays,t.weekdays)),jm=In(Pn()),Mm=(e,t)=>jm(Wi(e),Wi(t)),Nm=r(2,(e,t)=>Am(e,t)),Pm={min:0,max:59},Fm={min:0,max:59},Im={min:0,max:23},Lm={min:1,max:31},Rm={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}},zm={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}},Bm=(e,t)=>{let n=new Set,r=e.split(`,`),i=Vm(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:Vm(a);if(c!==void 0){if(!Number.isInteger(c))return Si(new Sm({message:`Expected step value to be a positive integer`,input:e}));if(c<1)return Si(new Sm({message:`Expected step value to be greater than 0`,input:e}));if(c>t.max)return Si(new Sm({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 Si(new Sm({message:`Expected a positive integer`,input:e}));if(n<t.min||n>t.max)return Si(new Sm({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(r===void 0)for(let e=n;e<=(c===void 0?n:t.max);e+=c??1)s(e);else{if(!Number.isInteger(r))return Si(new Sm({message:`Expected a positive integer`,input:e}));if(r<t.min||r>t.max)return Si(new Sm({message:`Expected a value between ${t.min} and ${t.max}`,input:e}));if(n>r)return Si(new Sm({message:`Invalid value range`,input:e}));for(let e=n;e<=r;e+=c??1)s(e)}}}return xi({values:n,wildcard:a})},Vm=e=>{let t=e.indexOf(`/`);if(t!==-1){let n=e.slice(t+1);return[e.slice(0,t),Wm.test(n)?Number(n):NaN]}return[e,void 0]},Hm=(e,t)=>{let n=e.indexOf(`-`);return n===-1?[Um(e,t),void 0]:[Um(e.slice(0,n),t),Um(e.slice(n+1),t)]};function Um(e,t){return t?.[dm(e)]??(Wm.test(e)?Number(e):NaN)}var Wm=/^\d+$/,Gm=r(2,(e,t)=>pl(e,Ym,e=>t(e))),Km=e=>e.reasons.some(qm),qm=e=>e._tag===`Fail`&&nf(e.error),Jm=e=>{let t,n=!1;for(let r of e.reasons)qm(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?Si(e):n?Si(Ud(e.reasons.filter(e=>!qm(e)))):xi(t)},Ym=e=>{let t=Jm(e);return Ei(t)?t:xi(t.success.value)},Xm=e=>{let t=Jm(e);return Ei(t)?sf(t.failure):of(t.success.value)},Zm=r(2,(e,t)=>kl(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=Jm(e);return Ei(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),Qm=`~effect/Schedule`,$m=_i(`effect/Schedule/CurrentMetadata`,{defaultValue:a({input:void 0,output:void 0,duration:Ya,attempt:0,start:0,now:0,elapsed:0,elapsedSincePrevious:0})}),eh={[Qm]:{_Out:i,_In:i,_Env:i},pipe(){return e(this,arguments)}},th=e=>me(e,Qm),nh=e=>{let t=Object.create(eh);return t.step=e,t},rh=()=>{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}}},ih=e=>nh(Bc(e,e=>{let t=rh();return(n,r)=>e(t(n,r))})),ah=e=>ul(e.step,e=>qs(()=>Js(e))),oh=e=>vd(t=>Bc(ah(e),e=>{let n=rh();return r=>Zs(()=>{let i=t.currentTimeMillisUnsafe();return Ic(e(i,r),([e,t])=>{let a=n(i,r);return a.output=e,a.duration=t,yc(yd(t),a)})})})),sh=(e,t=2)=>{let n=no(za(e));return ih(qs(e=>{let r=$a(n*t**(e.attempt-1));return qs([r,r])}))},ch=e=>nh(Bc(ah(e),e=>(t,n)=>Zm(e(t,n),{onSuccess:e=>qs([n,e[1]]),onFailure:Js,onDone:()=>rf(n)}))),lh=e=>{let t=za(e);return ih(qs(e=>qs([e.attempt-1,t])))},uh=r(2,(e,t)=>nh(Bc(ah(e),e=>{let n=rh();return(r,i)=>Ic(e(r,i),e=>{let[a,o]=e,s=t({...n(r,i),output:a,duration:o});return Ic(Bt(s)?s:qs(s),t=>t?qs(e):rf(a))})}))),dh=lh(Ya),fh=(e,t,n)=>ru(r=>Ic(n?.local?Uf(t,Bf(),r):Wf(t,r),t=>ol(e,t))),ph=r(e=>Bt(e[0]),(e,t,n)=>$r(t)?ol(e,t):fh(e,Array.isArray(t)?Qf(...t):t,n)),mh=r(3,(e,t,n)=>Ic(oh(t),t=>{let r=$m.defaultValue(),i,a=pl(Zs(()=>sl(e,$m,r)),ds,e=>(i=e,Ic(t(e),e=>(r=e,a))));return Gm(a,e=>Tt(()=>n(i,e)))})),hh=r(2,(e,t)=>mh(e,typeof t==`function`?t(i):th(t)?t:_h(t),Ys)),gh=ch(dh),_h=e=>{let t=e.schedule?ch(e.schedule):gh;return e.while&&(t=uh(t,({input:t})=>{let n=e.while(t);return Bt(n)?n:qs(n)})),e.until&&(t=uh(t,({input:t})=>{let n=e.until(t);return Bt(n)?Bc(n,e=>!e):qs(!n)})),e.times!==void 0&&(t=uh(t,({attempt:t})=>qs(t<=e.times))),t},vh=`~effect/MutableHashMap`,yh={[vh]:vh,[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)}},bh=()=>{let e=Object.create(yh);return e.backing=new Map,e.buckets=new Map,e},xh=r(2,(e,t)=>{if(e.backing.has(t))return y(e.backing.get(t));if(Sh(t))return v();let n=ye(t),r=e.buckets.get(n);return r===void 0?v():Ch(e,r,t)}),Sh=e=>typeof e!=`object`&&typeof e!=`function`,Ch=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(Re(n,t[r])){let n=t[r];return y(e.backing.get(n))}return v()},wh=r(2,(e,t)=>x(xh(e,t))),Th=r(3,(e,t,n)=>{if(e.backing.has(t)||Sh(t))return e.backing.set(t,n),e;let r=ye(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=Eh(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),Eh=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(Re(t,e[n]))return e[n]},Dh=r(2,(e,t)=>{if(Sh(t))return e.backing.delete(t),e;let n=ye(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||Re(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),Oh=Bt,kh=Du,Ah=ku,jh=ac,Mh=oc,C=qs,Nh=ec,Ph=Zs,Fh=Xs,Ih=rc,Lh=lc,Rh=uc,w=dc,zh=Ys,Bh=Js,Vh=tc,Hh=nc,Uh=ic,Wh=yn,Gh=Qs,T=Ic,Kh=zc,qh=jc,Jh=Mc,Yh=Ol,Xh=Dl,Zh=Ll,Qh=Bc,$h=yc,eg=Ac,tg=Nc,ng=ml,rg=xl,ig=Sl,ag=ul,og=hl,sg=Cl,cg=Tl,lg=vl,ug=gl,dg=hh,fg=El,pg=yd,mg=Pc,hg=Fc,gg=Iu,_g=Fl,vg=kl,yg=rl,bg=al,xg=ph,Sg=ol,Cg=el,wg=tl,Tg=sl,Eg=iu,Dg=mu,Og=lu,kg=du,Ag=ou,jg=cu,Mg=_u,Ng=vu,Pg=pu,Fg=yu,Ig=Eu,Lg=ll,E=ud,Rg=dd,zg=od,Bg=ld,Vg=cd,Hg=zu,Ug=Bu,Wg=Uu,Gg=Vu,Kg=Gu,qg=Ju,Jg=qu,Yg=fc,D=hc,Xg=Fd(`Warn`),Zg=Fd(`Error`),O=Fd(`Info`),k=Fd(`Debug`),Qg=Vc,$g=Hc,e_=Uc,t_=Rc,n_=ree,r_=`~effect/BigDecimal`,i_={[r_]:r_,[ve](){let e=f_(this);return Se(Ee(String(e.value)),Te(e.scale))},[Le](e){return a_(e)&&__(this,e)===0},toString(){return`BigDecimal(${y_(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[gt](){return this.toJSON()},pipe(){return e(this,arguments)}},a_=e=>me(e,r_),o_=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(i_);return n.value=e,n.scale=t,n},s_=(e,t)=>{let n=o_(e,t);return n.normalized=n,n},c_=BigInt(0),l_=BigInt(1),u_=BigInt(10),d_=s_(c_,0),f_=e=>{if(e.normalized===void 0){if(e.value===c_)e.normalized=d_;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=s_(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},p_=100,m_=[l_],h_=(e,t)=>e===t?0:e<t?-1:1,g_=(e,t)=>{let n=`${e.value<c_?-e.value:e.value}`,r=`${t.value<c_?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==c_)return i<c_?-1:1;let a=Math.max(n.length,r.length);return sr(n.padEnd(a,`0`),r.padEnd(a,`0`))},__=(e,t)=>{if(e.scale===t.scale)return h_(e.value,t.value);let n=v_(e),r=v_(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>p_)return n===-1?g_(t,e):g_(e,t);let o=m_[a]??=u_**BigInt(a);return i>0?h_(e.value,t.value*o):h_(e.value*o,t.value)},v_=e=>e.value===c_?0:e.value<c_?-1:1,y_=e=>{let t=f_(e);if(Math.abs(t.scale)>=16)return b_(t);let n=t.value<c_,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},b_=e=>{if(x_(e))return`0e+0`;let t=f_(e),n=`${t.value}`,r=t.value<c_?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},x_=e=>e.value===c_,S_=globalThis.BigInt,C_=e=>e>S_(2**53-1)||e<S_(-(2**53-1))?v():y(Number(e)),w_=BigInt(1),T_=BigInt(1e3),E_=BigInt(1024),D_=[{symbol:`B`,factor:w_,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:T_,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:T_**BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:T_**BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:T_**BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:T_**BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:T_**BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:T_**BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:T_**BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:T_**BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:T_**BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],O_=[D_[0],{symbol:`KiB`,factor:E_,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:E_**BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:E_**BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:E_**BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:E_**BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:E_**BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:E_**BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:E_**BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}];[...D_,...O_.slice(1)];var k_=C_,A_=e=>Er(k_(e),()=>Error(`ByteSize exceeds Number.MAX_SAFE_INTEGER: ${e}`)),j_=pp,M_=_p,N_=bp,P_=xp,F_=Ep,I_=Dp,L_=Op,R_=Fp,z_=Rp,B_=zp,V_=Bp,H_=Wp,U_=am,W_=om,G_=sm,K_=lm,q_=e=>Y_(typeof e==`string`?X_.encode(e):e),J_=e=>{let t=Z_(e),n=t.length;if(n%4!=0)return Si(new To({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${n}`}));let r=t.indexOf(`=`);if(r!==-1&&(r<n-2||r===n-2&&t[n-1]!==`=`))return Si(new To({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),r=new Uint8Array(n/4*3-e);for(let e=0,i=0;e<n;e+=4,i+=3){let n=ev(t.charCodeAt(e))<<18|ev(t.charCodeAt(e+1))<<12|ev(t.charCodeAt(e+2))<<6|ev(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return xi(r)}catch(e){return Si(new To({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},Y_=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=Q_[e[r-2]>>2],n+=Q_[(e[r-2]&3)<<4|e[r-1]>>4],n+=Q_[(e[r-1]&15)<<2|e[r]>>6],n+=Q_[e[r]&63];return r===t+1&&(n+=Q_[e[r-2]>>2],n+=Q_[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=Q_[e[r-2]>>2],n+=Q_[(e[r-2]&3)<<4|e[r-1]>>4],n+=Q_[(e[r-1]&15)<<2],n+=`=`),n},X_=new TextEncoder,Z_=e=>e.replace(/[\n\r]/g,``),Q_=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,$_=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)$_[Q_.charCodeAt(e)]=e;$_[61]=0;var ev=e=>{if(e>=$_.length||$_[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return $_[e]},tv=`~effect/http/Cookies`,nv=`~effect/http/Cookies/Cookie`,rv={[tv]:tv,...yt,toJSON(){return{_id:`effect/Cookies`,cookies:zi(this.cookies,e=>e.toJSON())}},pipe(){return e(this,arguments)}},iv=e=>{let t=Object.create(rv);return t.cookies=e,t},av=e=>{let t={};for(let n of e)Et(t,n.name,n);return iv(t)},ov=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=sv(e.trim());t&&n.push(t)}return av(n)};function sv(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(!cv.test(r))return;let i=t[0].slice(n+1),a=uv(i);if(t.length===1)return Object.assign(Object.create(lv),{name:r,value:a,valueEncoded:i});let o={};for(let e=1;e<t.length;e++){let n=t[e],r=n.indexOf(`=`),i=r===-1?n:n.slice(0,r).trim(),a=r===-1?void 0:n.slice(r+1).trim();switch(i.toLowerCase()){case`domain`:{if(a===void 0)break;let e=a.trim().replace(/^\./,``);e&&(o.domain=e);break}case`expires`:{if(a===void 0)break;let e=new Date(a);isNaN(e.getTime())||(o.expires=e);break}case`max-age`:{if(a===void 0)break;let e=parseInt(a,10);isNaN(e)||(o.maxAge=eo(e));break}case`path`:if(a===void 0)break;a[0]===`/`&&(o.path=a);break;case`priority`:if(a===void 0)break;switch(a.toLowerCase()){case`low`:o.priority=`low`;break;case`medium`:o.priority=`medium`;break;case`high`:o.priority=`high`}break;case`httponly`:o.httpOnly=!0;break;case`secure`:o.secure=!0;break;case`partitioned`:o.partitioned=!0;break;case`samesite`:if(a===void 0)break;switch(a.toLowerCase()){case`lax`:o.sameSite=`lax`;break;case`strict`:o.sameSite=`strict`;break;case`none`:o.sameSite=`none`}}}return Object.assign(Object.create(lv),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}var cv=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,lv={[nv]:nv,...yt,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}},uv=e=>{try{return decodeURIComponent(e)}catch{return e}},dv=new WeakMap,fv=e=>{if(dv.has(e))return dv.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},pv=`~effect/Redacted`,mv=e=>me(e,pv),hv=(e,t)=>{let n=Object.create(gv);return t?.label&&(n.label=t.label),dv.set(n,e),n},gv={[pv]:{_A:e=>e},label:void 0,...Rt,toJSON(){return this.toString()},toString(){return`<redacted${te(this.label)?`:`+this.label:``}>`},[ve](){return ye(dv.get(this))},[Le](e){return mv(e)&&Re(dv.get(this),dv.get(e))}},_v=fv,vv=e=>Mn((t,n)=>e(_v(t),_v(n))),yv=Symbol.for(`~effect/http/Headers`),bv=Object.defineProperties(Object.create(null),{[yv]:{value:yv},[$e]:{value(e){return Av(this,li(e,Mv))}},toJSON:{value(){return tt(this)}},[Le]:{value(e){return Sv(this,e)}},[ve]:{value(){return Oe(this)}},toString:{value:yt.toString},[gt]:{value:yt[gt]}}),xv=e=>Object.assign(Object.create(bv),e),Sv=Hi(Pn()),Cv=Object.create(bv),wv=e=>{if(e===void 0)return Cv;if(Symbol.iterator in e){let t=Object.create(bv);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(bv);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},Tv=e=>Object.setPrototypeOf(e,bv),Ev=r(3,(e,t,n)=>{let r=xv(e);return r[t.toLowerCase()]=n,r}),Dv=r(2,(e,t)=>xv({...e,...wv(t)})),Ov=r(2,(e,t)=>{let n=xv(e);return Object.assign(n,t),n}),kv=r(2,(e,t)=>{let n=xv(e);return delete n[t.toLowerCase()],n}),Av=r(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=hv(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=hv(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),jv=(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},Mv=_i(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),Nv=e=>typeof e==`string`?e:_v(e),Pv=`~effect/http/UrlParams`,Fv=e=>me(e,Pv),Iv={...Rt,[Pv]:Pv,[Symbol.iterator](){return this.params[Symbol.iterator]()},[$e](e){return{_id:`UrlParams`,params:Object.fromEntries(Yv(this,li(e,ay)))}},toJSON(){return tt(this)},[Le](e){return Vv(this,e)},[ve](){return Ae(this.params.flat())}},Lv=e=>{let t=Object.create(Iv);return t.params=e,t},Rv=e=>{if(Fv(e))return e;let t=zv(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)},zv=e=>{let t=typeof e[Symbol.iterator]==`function`?Wi(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,Bv(r[t])]);else if(typeof r==`object`&&r&&!mv(r)){let t=zv(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,Bv(r)]);return n},Bv=e=>mv(e)?e:String(e),Vv=Mn((e,t)=>Hv(e.params,t.params)),Hv=ga(Pi([Pn(),Qe()])),Uv=Lv([]),Wv=r(2,(e,t)=>Lv(t(e.params))),Gv=r(2,(e,t)=>{let n=Rv(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)}),Kv=r(2,(e,t)=>Wv(e,Ji(Rv(t).params))),qv=e=>new URLSearchParams(Rv(e).params.map(([e,t])=>[e,Nv(t)])).toString(),Jv=e=>{let t={};for(let[n,r]of e.params){let e=Nv(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},Yv=r(2,(e,t)=>{let n=Array.isArray(t)?t:[t];return e.params.map(([e,t])=>[e,typeof t==`string`&&Xv(e,n)?hv(t):t])}),Xv=jv,Zv=(e,t=iy())=>{e.includes(`@`)&&(e=ty(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)+ny(e.slice(n+1,i),t)+e.slice(i)},Qv=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i,$v=/[/\\?#]/,ey=/[/?#]/,ty=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=Qv.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?$v:ey),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])},ny=(e,t)=>e.split(`&`).map(e=>{let n=e.indexOf(`=`);return n!==-1&&Xv(ry(e.slice(0,n)),t)?e.slice(0,n+1)+`REDACTED`:e}).join(`&`),ry=e=>{if(!e.includes(`%`)&&!e.includes(`+`))return e;try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return e}},iy=()=>li(globalThis[`~effect/Fiber/currentFiber`]?.context??ti(),ay),ay=_i(`effect/http/UrlParams/CurrentRedactedNames`,{defaultValue:()=>[`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]});function oy(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function sy(e){return t=>oy(t)?.[e]}var cy=`~structural`,ly=`~sentinels`,uy=`~constructor`,dy=f(e=>{let t=oy(e)?.identifier;return typeof t==`string`?t:e.getExpected(dy)}),fy=Symbol(),py=of,my=py(fy),hy=py(fy),gy=e=>e===fy?v():y(e),_y=e=>e._tag===`None`?my:py(e.value),vy=`~effect/SchemaIssue/Issue`;function yy(e){return me(e,vy)&&e[vy]===vy}function by(e){return Object.hasOwn(e,`input`)}var xy=class{[vy]=vy;constructor(e,t){t?.reportInput===!0&&e!==fy&&(this.input=e)}},Sy=class extends xy{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},Cy=class extends xy{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},wy=class extends xy{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},Ty=class extends xy{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},Ey=class extends xy{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},Dy=class extends xy{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},Oy=class extends xy{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},ky=class extends xy{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function Ay(e,t,n,r,i){return new Dy(e,[new wy([t],n)],r,i)}var jy=class extends xy{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},My=class extends xy{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},Ny=class extends xy{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function Py(e,t,n){if(yy(e))return e;if(typeof e==`string`)return new ky({message:e},t,n);let r=typeof e.issue==`string`?new ky({message:e.issue},t,n):e.issue;return new wy(e.path,r)}function Fy(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new ky(void 0,t,n):Py(e,t,n)}function Iy(e,t,n,r){return Array.isArray(t)?Xi(t)?t.length===1?Py(t[0],n,r):new Dy(e,ma(t,e=>Py(e,n,r)),n,r):void 0:Fy(t,n,r)}var Ly=e=>{let t=Yy(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return Hy(dy(e.ast),e);case`InvalidValue`:{let t=Vy(e);if(t!==void 0)return Hy(t,e);let n=By(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=By(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=By(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},Ry=e=>Yy(e)??Yy(e.issue);function zy(e){return t=>({issues:Wy(t,[],e?.leafHook??Ly,e?.checkHook??Ry)})}function By(e){return by(e)?ot(e.input):void 0}function Vy(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function Hy(e,t){let n=By(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function Uy(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?Hy(Gy(e.filter),e):Hy(r,e.issue)}function Wy(e,t,n,r,i){switch(e._tag){case`Filter`:return Wy(e.issue,t,n,r,i??Uy(e,r));case`Encoding`:return Wy(e.issue,t,n,r,i);case`Pointer`:return Wy(e.issue,[...t,...e.path],n,r,i);case`Composite`:case`AnyOf`:return e._tag===`Composite`||e.issues.length>0?e.issues.flatMap(e=>Wy(e,t,n,r,i)):[{path:t,message:i??Yy(e)??Hy(dy(e.ast),e)}];default:return[{path:t,message:i??n(e)}]}}function Gy(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=>Gy(e)).join(` & `)}}function Ky(){return e=>Jy(e,``)}var qy=Ky();function Jy(e,t,n){let r;switch(e._tag){case`Filter`:return Jy(e.issue,t,n??Uy(e,Ry));case`Encoding`:return Jy(e.issue,t,n);case`Pointer`:return Jy(e.issue,t+lt(e.path),n);case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>Jy(e,t,n)).join(`
|
|
14
|
-
`);r=n??Yy(e)??Hy(dy(e.ast),e);break;default:r=n??Ly(e)}return t?`${r}\n at ${t}`:r}function Yy(e){if(e._tag===`Pointer`||e._tag===`Composite`)return;if(e._tag===`Encoding`)return Yy(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 Xy(e){let t;for(let n of e.reasons){if(!Hd(n)||!yy(n.error))return;t??=n.error}return t}function Zy(e,t){let n=Xy(e);if(n===void 0)throw Error(t,{cause:e});return n}var Qy=e=>Object.assign(Object.create(t),e);function $y(e){return sb((t,n)=>zh(e(t,n)))}function eb(e){return $y((t,n)=>{let r={message:e(t)};return x(t)?new jy(r,t.value,n):new jy(r)})}var tb=eb(()=>`Encoding is not supported`),nb=Qy({_tag:`Passthrough`});function rb(){return nb}function ib(e){return Qy({_tag:`Transform`,transform:e})}function ab(e){return Qy({_tag:`TransformEffect`,transform:e})}function ob(e){return Qy({_tag:`TransformOptional`,transform:e})}function sb(e){return Qy({_tag:`TransformOptionalEffect`,transform:e})}function cb(){return ob(()=>v())}function lb(e){return sb(t=>{let n=Mr(t,ce);return x(n)?C(n):Qg(e,y)})}function ub(){return ib(globalThis.String)}function db(){return ib(globalThis.Number)}function fb(){return ab((e,t)=>{try{return C(globalThis.BigInt(e))}catch{return zh(new ky({expected:`a value that can be converted to a bigint`},e,t))}})}function pb(e){return ab((t,n)=>Uh({try:()=>JSON.parse(t,e?.reviver),catch:()=>new ky({expected:`a valid JSON string`},t,n)}))}function mb(e){return ab((t,n)=>Uh({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 ky({expected:`a JSON-serializable value`},t,n)}))}function hb(){return ib(q_)}function gb(){return ab((e,t)=>$g(Gh(J_(e)),()=>new ky({expected:`a valid Base64 string`},e,t)))}var _b=class extends n{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new _b(this.encode,this.decode)}},vb=`~effect/SchemaTransformation/Transformation`,yb=class extends n{[vb]=vb;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new yb(this.encode,this.decode)}};function bb(e){return me(e,vb)&&e[vb]===vb}var xb=e=>bb(e)?e:new yb(e.decode,e.encode);function Sb(e){return new yb(ab(e.decode),ab(e.encode))}function Cb(e){return new yb(ib(e.decode),ib(e.encode))}function wb(e){return new yb(ob(e.decode),ob(e.encode))}var Tb=new yb(rb(),rb());function Eb(){return Tb}var Db=new yb(db(),ub()),Ob=new yb(fb(),ub()),kb=e=>fe(e)&&typeof e.message==`string`,Ab=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:Pb(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},jb=e=>{try{let t=pt(e);return t===void 0?ot(e):JSON.parse(t)}catch{return ot(e)}},Mb=(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},Nb=e=>{let t=new WeakSet,n=r=>{if(ge(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=Mb(r,e,n);return t.delete(r),i}return jb(r)};return n},Pb=e=>kb(e)?Ab(e):e,Fb=e=>Cb({decode:Pb,encode:Nb(e)});function Ib(){return Cb({decode:Cr,encode:S})}function Lb(){return wb({decode:y,encode:kr})}var Rb=Sb({decode:(e,t)=>URL.canParse(e)?C(new URL(e)):zh(new ky({expected:`a valid URL string`},e,t)),encode:e=>C(e.href)}),zb=new yb(gb(),hb());function Bb(e){return new yb(pb(e??{}),mb(e))}function Vb(e){return t=>t._tag===e}var Hb=Vb(`Declaration`),Ub=Vb(`Null`),Wb=Vb(`Void`),Gb=Vb(`Never`),Kb=Vb(`Literal`),qb=Vb(`UniqueSymbol`),Jb=Vb(`Arrays`),Yb=Vb(`Objects`),Xb=Vb(`Union`),Zb=Vb(`Suspend`),Qb=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},$b={},ex=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}},tx=`~effect/Schema`,nx=class{[tx]=tx;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}>`}},rx=class extends nx{_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===fy)return my;e??=this.run(this.typeParameters);try{return e(t,this,n)}catch(e){return Hh(e)}}}_rebuild(e,t,n,r,i){let a=DS(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new rx(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>`}},ix=new class extends nx{_tag=`Null`;getParser(){return GS(this,null)}getExpected(){return`null`}},ax=class extends nx{_tag=`Undefined`;getParser(){return GS(this,void 0)}toCodecJson(){return hS(this,[ox])}getExpected(){return`undefined`}},ox=new Qb(ix,new yb(ib(()=>void 0),ib(()=>null))),sx=new ax,cx=new class extends nx{_tag=`Void`;getParser(){let e=py(void 0);return t=>t===fy?my:e}toCodecJson(){return hS(this,[ox])}getExpected(){return`void`}},lx=new class extends nx{_tag=`Never`;getParser(){return KS(this,ue)}getExpected(){return`never`}},ux=new class extends nx{_tag=`Unknown`;getParser(){return KS(this,de)}getExpected(){return`unknown`}},dx=class extends nx{_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 GS(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?fx(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:fx(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function fx(e){let t=globalThis.String(e.literal);return hS(e,[new Qb(new dx(t),new yb(ib(()=>e.literal),ib(()=>t)))])}var px=new class extends nx{_tag=`String`;getParser(){return KS(this,te)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&iC(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},mx=class extends nx{_tag=`Number`;getParser(){return KS(this,ne)}matchKey(e,t){return this._match(XS,e,t)}matchPart(e,t){return this._match(YS,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:iC(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(hx(this.checks,`effect/schema/isFinite`)||hx(this.checks,`effect/schema/isInt`))?this:hS(this,[uS])}toCodecStringTree(){return this.toCodecJson()===this?hS(this,[$S]):hS(this,[eC])}getExpected(){return`number`}};function hx(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&hx(e.checks,t))}var gx=new mx,_x=new class extends nx{_tag=`Boolean`;getParser(){return KS(this,re)}getExpected(){return`boolean`}},vx=new class extends nx{_tag=`BigInt`;getParser(){return KS(this,ie)}matchPart(e,t){if(!tC.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:iC(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return hS(this,[rC])}getExpected(){return`bigint`}},yx=class extends nx{_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(IS(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(IS(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 Ey(n,t[o],i),a=new wy([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return zh(new Dy(n,[a],t,i))}return e.issues?zh(new Dy(n,e.issues,t,i)):py(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:ju(t.concurrency),f=d===1?Sx(i,e,0,u):Cx(i,e,{concurrency:d,end:u});if(!f)return c(i);if(Lc(f))return t_(f,()=>c(i));let p=!0;return Ph(()=>p?(p=!1,T(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===fy)return my;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)):zh(new Oy(n,e,a))}catch(e){return Hh(e)}}}_rebuild(e,t,n){let r=DS(this.elements,e),i=DS(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new yx(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 bx(e,t,n,r){if(n._tag===`Failure`)return wx(e,e.ast,r,n);let i=n===hy?t:n[Mt];if(i!==fy)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(IS(t.ast))return;let n=new wy([r],new Ty(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return cf(new Dy(e.ast,[n],e.input,e.options))}}var xx={onItem(e,t,n){let r=n<e.len?t:fy;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:bx},Sx=Mu()(xx),Cx=Pu()(xx),wx=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Xy(r.cause);if(i===void 0)return sf(Xd(r.cause,r=>new Dy(t,[new wy([n],r)],e.input,e.options)));let a=new wy([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return cf(new Dy(t,[a],e.input,e.options))},Tx=`[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?`;function Ex(e,t,n=$b){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(qS(VS(t)))}var Dx=class{name;type;constructor(e,t){this.name=e,this.type=t}};function Ox(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(Ox);default:return!1}}function kx(e){let t=_S(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(kx);default:return!1}}function Ax(e){return Ox(e)&&kx(e)}var jx=class{parameter;type;constructor(e,t){if(!Ax(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,IS(t)&&!WS(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},Mx=class extends nx{_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 KS(n,le);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(qS(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 wx(t,n,i,s)??lf;let c=s===hy?o:s[Mt];if(a!==fy&&c!==fy){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return lf;Et(t.out,a,c)}return lf},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!Lc(t))return T(Zh(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return wx(e,n,r,a)??lf;let o=a===hy?r:a[Mt],s=e.input[r],l=i.parserValue(s,e.options);return Lc(l)?t(e,r,o,s,l):T(Zh(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return Lc(a)?t(e,n,n,i,a):T(Zh(a),r=>t(e,n,n,i,r))},u=i?Pu()({onItem:(e,[t,n])=>n.is.parameter===px?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return n_(function*(t,d){if(t===fy)return fy;if(typeof t!=`object`||!t||Array.isArray(t))return yield*zh(new Oy(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:ju(d.concurrency),ee=i&&g?n.indexSignatures.map(e=>Ex(f,e.parameter,d)):void 0;if(g){let r=ee?new Set(e):e;if(ee)for(let e of ee)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 Ey(n,f[a],d),r=new wy([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*zh(new Dy(n,[r],t,d))}}}if(r){let e=_===1?Fx(m,a):Ix(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===px?l:c,r=ee?.[e]??(t.is.parameter===px?Object.keys(f):Ex(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!Lc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=fa();for(let t=0;t<i;t++){let n=o[t],r=ee?.[t]??(n.is.parameter===px?Object.keys(f):Ex(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*zh(new Dy(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return T(Zh(n),n=>{let i={...e,out:{...e.out}},o=Nx(i,r,n);if(o)return o;let s=()=>py(i.out),c=Fx(i,a.slice(t+1));return c?t_(c,s):s()})};return(e,t)=>{if(e===fy)return my;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&ju(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return zh(new Oy(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=Yx(i,s),l=c?i[s]:fy,d=n.parser(l,t);if(!Lc(d))return u(o,e,d);if(d===hy){c&&Et(a,s,l);continue}let f=Nx(o,n,d);if(f)return f}}catch(e){return Hh(e)}return py(a)}}_rebuild(e,t,n,r){let i=DS(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new Dx(t.name,n)}),a=DS(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new jx(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new Mx(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 Nx(e,t,n){if(n._tag===`Failure`)return wx(e,e.ast,t.name,n);if(n===hy)return;let r=n[Mt];if(r!==fy)Et(e.out,t.name,r);else if(delete e.out[t.name],!IS(t.type)){let n=new wy([t.name],new Ty(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return cf(new Dy(e.ast,[n],e.input,e.options))}}var Px={onItem(e,t){if(!Yx(e.input,t.name))return t.parser(fy,e.options);let n=e.input[t.name];return Et(e.out,t.name,n),t.parser(n,e.options)},step:Nx},Fx=Mu()(Px),Ix=Pu()(Px);function Lx(e,t){return e?t?[...e,...t]:e:t}function Rx(e,t,n){return new Mx(Reflect.ownKeys(e).map(t=>new Dx(t,e[t].ast)),[],n,t)}function zx(e){return e.ast}function Bx(e,t=void 0){return new yx(!1,e.map(e=>e.ast),[],void 0,t)}function Vx(e,t,n){return new Xx(e.map(zx),t,void 0,n)}function Hx(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=Lx(i,e.checks)}return new Mx(n,r,void 0,i)}var Ux=p(e=>{for(;;){if(Zb(e))return ux;let t=e.encoding;if(!t)return e.recur?.(Ux,i)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==i))return ux;e=t[t.length-1].to}});function Wx(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(Wx)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function Gx(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[ly];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!IS(t)){if(Kb(t))return[{key:e.name,literal:t.literal}];if(qb(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!IS(e)){if(Kb(e))return[{key:t,literal:e.literal}];if(qb(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>Gx(Ux(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return Gx(e.thunk())}}var Kx=new WeakMap,qx=Object.freeze([]),Jx=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Yx=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function oee(e){let t=Kx.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=Ux(c);if(Gb(l))continue;if(Kb(l)||qb(l)){a??=new Map;let e=Kb(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=Gx(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=Wx(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??qx);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??qx;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(pe(e)){let n=Yx(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??qx;if(t)return o}return qx}}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=Jx(t);if(!pe(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Yx(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=Yx(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=Yx(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(Jx(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Kx.set(e,t),t}var Xx=class extends nx{_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===fy)return my;let i=(o??=oee(n.types))(e,r);if(i.length===0)return zh(new My(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:Lc(r)?Zx(n,r.cause,e,t):Qx(n,r,e,t)}return $x(n,a,i,e,t)}}_rebuild(e,t,n){let r=DS(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new Xx(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=VS(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Kb);if(t.length>0)return`${rS(n.isMutable)}[ ${t.map(t=>e(t)+iS(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Kb(e.type));if(t.length>0)return`{ ${t.map(t=>`${rS(t.type.context?.isMutable)}${ct(t.name)}${iS(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Zx(e,t,n,r){let i=Xy(t);return i?cf(new My(e,[i],n,r)):sf(t)}function Qx(e,t,n,r){return ag(t,t=>Zx(e,t,n,r))}function $x(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=tS(a,n);if(!o)return a.out?a.out:zh(new My(e,a.issues??[],r,i));if(Lc(o))return eS(o,a);let s=!0;return Ph(()=>s?(s=!1,eS(o,a)):$x(e,t,n,r,i))}function eS(e,t){return t_(e,e=>t.out===hy?C(t.input):t.out?t.out:zh(new My(t.ast,t.issues??[],t.input,t.options)))}var tS=Mu()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=Xy(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]),cf(new Ny(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return lf}}}),nS=new Xx([new dx(`Infinity`),new dx(`-Infinity`),new dx(`NaN`)]);function rS(e){return e?``:`readonly `}function iS(e){return e?`?`:``}var aS=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 aS(this.run,{...this.annotations,...e},this.aborted)}abort(){return new aS(this.run,this.annotations,!0)}and(e,t){return new oS([this,e],t)}},oS=class extends n{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new oS(this.checks,{...this.annotations,...e})}and(e,t){return new oS([this,e],t)}};function sS(e,t,n=!1){return new aS((t,n,r)=>Iy(n,e(t,n,r),t,r),t,n)}function cS(e){return sS(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 lS=bS(gx,[cS()]),uS=new Qb(new Xx([lS,nS]),new yb(db(),ib(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function dS(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return sS(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 fS=new WeakMap;function pS(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&fS.set(n,mS(e)),n}function mS(e){let t=fS.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 fS.set(e,n),n}function hS(e,t){return e.encoding===t?e:pS(e,{encoding:t})}function gS(e,t){if(e.context===t)return e;let n=mS(e);return n.context===t&&n.encoding===e.encoding?n:pS(e,{context:t})}function _S(e){return e.encoding?_S(e.encoding[e.encoding.length-1].to):e}function vS(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return yS(e,qi(e.checks.slice(0,-1),n.annotate(t)))}return pS(e,{annotations:{...e.annotations,...t}})}function yS(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:pS(e,{checks:t})}function bS(e,t){return yS(e,Lx(e.checks,t))}function xS(e,t){let n=t(e.to);return n===e.to?e:new Qb(n,e.transformation)}function SS(e,t){let n=e,r=n[n.length-1],i=xS(r,t);return i===r?e:qi(e.slice(0,e.length-1),i)}function CS(e){return t=>t.encoding?hS(t,SS(t.encoding,e)):t}function wS(e,t){return CS(e=>gS(e,t))(e)}function TS(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:hS(r,SS(r.encoding,n))}return e(r)}return p(n)}function ES(e,t,n){let r=new Qb(e,t);return hS(n,n.encoding?[...n.encoding,r]:[r])}function DS(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 OS(e,t){return gS(e,e.context?new ex(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new ex(!1,!1,void 0,t))}var kS=p(e=>AS(gS(e,e.context?e.context.isOptional===!1?new ex(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new ex(!0,!1)))),AS=CS(kS),jS=f(e=>kS(new Xx([e,sx])));function MS(e,t){return gS(e,e.context?new ex(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new ex(!1,!1,t))}function NS(e,t,n){return ES(e,n,t)}function PS(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:oe(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 FS(e,t){let{literals:n,parameters:r}=PS(e);return new Mx(n.map(e=>new Dx(e,t)),r.map(e=>new jx(e,t)))}function IS(e){return e.context?.isOptional??!1}function LS(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(LS)}function RS(e){function t(e){return LS(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Yi(n)?n:void 0}function zS(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Zb(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var BS=p(e=>{let t=mS(e);if(t!==e){let n=BS(t);return n===t&&e.encoding===void 0?e:gS(n,e.context)}let n=`recur`in e?e.recur(BS):e;if(`encodingChecks`in n&&n.encodingChecks){let t=zS(e)?n.encodingChecks:Jb(n)||Yb(n)||Hb(n)&&n.typeParameters.length>0?RS(n.encodingChecks):void 0;return pS(n,{encodingChecks:void 0,checks:Lx(n.checks,t)})}return n}),VS=p(e=>BS(US(e)));function HS(e,t){let n=t,r=n.length,i=n[r-1],a=[new Qb(US(hS(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Qb(US(n[e-1].to),n[e].transformation.flip()));let o=US(i.to);return o.encoding?hS(o,[...o.encoding,...a]):hS(o,a)}var US=f(e=>{if(e.encoding)return HS(e,e.encoding);let t=mS(e);if(t!==e){let n=US(t);return n===t?e:gS(n,e.context)}return`flip`in e?e.flip(US):`recur`in e?e.recur(US):e});function WS(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(WS);default:return!1}}function GS(e,t){let n=t===0?hy:py(t);return(r,i)=>r===fy?my:r===t?n:zh(new Oy(e,r,i))}function KS(e,t){return(n,r)=>n===fy?my:t(n)?hy:zh(new Oy(e,n,r))}var qS=TS(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(qS)}}),JS=TS(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(JS)}}),YS=new globalThis.RegExp(`^${Tx}$`),XS=new globalThis.RegExp(`^(?:${Tx}|Infinity|-Infinity|NaN)$`);function ZS(e){return dS(YS,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:YS.source}),...e})}var QS=bS(px,[ZS()]),$S=new Qb(QS,Db),eC=new Qb(new Xx([QS,nS]),Db),tC=new globalThis.RegExp(`^-?\\d+$`);function nC(e){return dS(tC,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:tC.source}),...e})}var rC=new Qb(bS(px,[nC({expected:`a string representing a bigint`})]),Ob);function iC(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=iC(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 Sy(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function aC(e){if(!Hb(e))return;let t=e.annotations?.[uy];return se(t)?t(e.typeParameters):void 0}var oC=oy,sC=sy;function cC(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function lC(e){return e===void 0||typeof e==`string`}function uC(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 dC(e){return uC(e,cC)}var fC=new rx([],()=>(e,t,n)=>dC(e)?hy:zh(new Oy(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>gC}),pC=new Qb(fC,Eb()),mC=new Qb(new Xx([new yx(!1,[],[fC]),new Mx([],[new jx(px,fC)])]),Eb());function hC(e){return uC(e,lC)}var gC=new Qb(new rx([],()=>(e,t,n)=>hC(e)?hy:zh(new Oy(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),Eb()),_C=(e,t,n)=>e===hy?n(t):t_(e,n);function vC(e){let t=yC(e);return(e,n,r)=>{try{return t(e,n,r)}catch(e){return Hh(e)}}}function yC(e){if(e._tag===`Middleware`)return(t,n,r)=>bC(t===hy?e.decode(py(gy(n)),r):e.decode(Qg(t,gy),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===hy?py(t):e;case`Transform`:{let e=e=>e===fy?my:py(t.transform(e));return(t,n)=>_C(t,n,e)}case`TransformOptional`:{let e=e=>_y(t.transform(gy(e)));return(t,n)=>_C(t,n,e)}case`TransformEffect`:return(e,n,r)=>_C(e,n,e=>e===fy?my:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>_C(e,n,e=>bC(t.transform(gy(e),r)))}}var bC=e=>t_(e,_y),xC=(e,t,n,r)=>ag(r,r=>Vh(()=>Xd(r,r=>new Cy(e,r,t,n))));function SC(e,t){let n=vC(e.link.transformation),r;return(i,a)=>{if(i===fy)return my;if(e.isConstructed(i))return hy;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function CC(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==fy&&r!==void 0)return t(r,i);let a=n;if(Lc(a)&&a._tag===`Success`){let e=t(a[Mt],i);return e===hy?a:e}return t_(xC(e,r,i,a),e=>{let n=t(e,i);return n===hy?py(e):n})}}function wC(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:CC(e,n)}function TC(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?aC(e):void 0,o=a?SC(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>vC(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(Lc(r)){if(r._tag===`Success`){let i=r===hy?t:r[Mt];if(t!==fy&&i!==fy){let i=iC(u,t,void 0,e,n);i&&(r=zh(new Dy(e,i,t,n)))}}}else r=T(r,r=>{if(t!==fy&&r!==fy){let r=iC(u,t,void 0,e,n);if(r)return zh(new Dy(e,r,t,n))}return C(r)})}if(s&&!n.disableChecks){if(Lc(r)){if(r._tag===`Success`){let i=r===hy?t:r[Mt];if(i===fy)return r;let a=iC(s,i,void 0,e,n);a&&(r=zh(new Dy(e,a,i,n)))}}else r=T(r,t=>{if(t!==fy){let r=iC(s,t,void 0,e,n);if(r)return zh(new Dy(e,r,t,n))}return C(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=t_(o,e=>{let n=t(e,r);return n===hy?py(e):n})}if(o._tag===`Success`){let e=o[Mt],t=p(e,r);return t===hy?o:t}return o=xC(e,n,r,o),t_(o,e=>{let t=p(e,r);return t===hy?py(e):t})}:p}var EC=Symbol(),DC=new WeakMap,OC=e=>MC(e).parser,kC=e=>MC(e).makeEffect,AC=e=>wC(e,kC),jC=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=TC(this.ast,OC)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=TC(this.ast,kC,AC)}};function MC(e){let t=DC.get(e);if(t!==void 0)return t;let n=new jC(e);return DC.set(e,n),n}function NC(e){let t=e.ast,n;return(e,r)=>(n??=qC(ew,BS(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function PC(e){let t=NC(e);return(e,n)=>{let r=Jg(t(e,n));return uf(r)?y(r.value):(Zy(r.cause,`Option adapter can only return none for schema issues`),v())}}function FC(e){return QC(BS(e.ast))}function IC(e){return RC(e.ast)}function LC(e){{let t=JC(KC(e));return e=>{let n=t(e,$b);return uf(n)?!0:(Zy(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function RC(e){let t=BS(e),n=e=>(n=LC(t),n(e));return e=>n(e)}function zC(e,t){let n=KC(e.ast);return t===void 0?n:(e,r)=>n(e,WC(t,r))}function BC(e,t){return YC(zC(e,t))}var VC=BC;function HC(e,t){return XC(zC(e,t))}function UC(e,t){let n=KC(US(e.ast));return t===void 0?n:(e,r)=>n(e,WC(t,r))}var WC=(e,t)=>t?{...e,...t}:e,GC=e=>e===fy?zh(new ky):C(e);function KC(e){return qC($C,e)}function see(e,t){return e===hy?C(t):Lc(e)?e[`~effect/Effect/args`]===fy?GC(fy):e:t_(e,GC)}function qC(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??$b);return a===hy?C(r):Lc(a)?a[`~effect/Effect/args`]===fy?GC(fy):a:t_(a,GC)}}function JC(e){return(t,n)=>Jg(e(t,n))}function YC(e){let t=JC(e);return(e,n)=>{let r=t(e,n);return uf(r)?y(r.value):(Zy(r.cause,`Option adapter can only return none for schema issues`),v())}}function XC(e){let t=JC(e);return(e,n)=>{let r=t(e,n);return uf(r)?xi(r.value):Si(Zy(r.cause,`Result adapter can only return schema issues`))}}function ZC(e,t){let n=Jg(e);if(uf(n))return n.value;let r=Zy(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function QC(e){let t,n;return(r,i)=>{t??=MC(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??$b,o=t.make;if(o!==void 0&&r!==fy){let e;try{e=o(r,a)}catch(e){throw Zy(Gd(e),`Constructor adapter can only throw schema issues`),e}if(e!==EC&&e!==fy)return e}return ZC(see((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var $C=e=>MC(e).parser,ew=e=>MC(e).makeEffect,tw=`~effect/Schema/Schema`,nw=Symbol(),rw={[tw]:tw,get make(){let e=FC(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=NC(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=PC(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return e(this,arguments)},annotate(e){return this.rebuild(vS(this.ast,e))},annotateKey(e){return this.rebuild(OS(this.ast,e))},check(...e){return this.rebuild(bS(this.ast,e))},rebuild(e){return iw(e,this[nw])}};function iw(e,t){function n(){}let r=Object.setPrototypeOf(n,rw);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[nw]=t,r.ast=e,r}function aw(e){return iw(ow(e.ast),{schema:e})}var ow=TS(e=>{let t=mS(e);if(t!==e){let n=ow(t);if(n===t)return e;if(n.encoding===void 0)return gS(n,e.context)}let n=dw(e,ow),r=e.context;return n===e||r===void 0?n:wS(n,sw(r))});function sw(e){return e.constructorDefault===void 0?e:new ex(e.isOptional,e.isMutable,void 0,e.annotations)}function cw(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function lw(e){return t=>{let n=[...t].sort((t,n)=>e(VS(t))-e(VS(n)));return n.some((e,n)=>e!==t[n])?n:t}}var uw=lw(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function dw(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!se(n))return hS(e,[pC]);let r=n(e.typeParameters.map(e=>iw(VS(e))));return r===void 0?e:hS(e,[xS(r,t)])}case`Unknown`:return hS(e,[pC]);case`ObjectKeyword`:return hS(e,[mC]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return cw(e),e.recur(t,JS);case`Union`:{let n=uw(e.types);return n===e.types?e.recur(t):new Xx(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 fw(e){return iw(vw(e.ast),{schema:e})}var pw=lw(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function mw(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>iw(t(VS(e)))),i=e.annotations?.toCodecStringTree;if(se(i)){let n=i(r);return n===void 0?e:hS(e,[xS(n,t)])}let a=e.annotations?.toCodecJson,o=se(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??(se(s)?s(r):void 0);return c===void 0?n(e):hS(e,[xS(c,t)])}case`Null`:return hS(e,[hw]);case`Boolean`:return hS(e,[gw]);case`Unknown`:case`ObjectKeyword`:return hS(e,[gC]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return cw(e),e.recur(t,JS);case`Union`:{let n=pw(e.types);return n===e.types?e.recur(t):new Xx(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 hw=new Qb(new dx(`null`),new yb(ib(()=>null),ib(()=>`null`))),gw=new Qb(new Xx([new dx(`true`),new dx(`false`)]),new yb(ib(e=>e===`true`),ub())),_w=new yb(ib(e=>typeof e==`string`?[e]:e),rb()),vw=TS(e=>{let t=mw(e,vw,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?wS(t,sw(e.context)):t},{stopAt:e=>e.transformation===_w});function yw(e){return uf(e)?e.value:{issues:[{message:tf(e.cause)}]}}function bw(e,t){let n=zC(e),r={errors:`all`,...t?.parseOptions},i=zy(t);return xw(e,{validate:e=>{let t=new _o(`sync`),a=Wg(_g(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?yw(o):new Promise(e=>{a.addObserver(t=>{e(yw(t))})})}})}function xw(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 Sw=r(2,(e,t)=>({...e,...t})),Cw=r(2,(e,t)=>Tw(e,(e,n)=>[Object.hasOwn(t,e)?t[e]:e,n])),ww=e=>e;function Tw(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 Ew=`~effect/Schema/SchemaError`;function Dw(e){return me(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}({...yt}),{...yt},{...yt},{...yt},{...yt},{...yt},{...yt},{...yt};var Ow=tw;function kw(){return(e,t,n)=>Yw(new rx(e.map(zx),e=>t(e.map(e=>Yw(e))),n))}function Aw(e,t){return kw()([],()=>(t,n,r)=>e(t)?C(t):zh(new Oy(n,t,r)),t)}var jw=class extends Co(`SchemaError`){[Ew]=Ew;constructor(e){let t=St();Ct(0);try{super({issue:e})}finally{Ct(t)}}get message(){return qy(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[gt](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}};function Mw(e){return Dw(e)}function Nw(e){return Lc(e)?Pw(e):ag(e,e=>Vh(()=>Xd(e,e=>new jw(e))))}function Pw(e){return uf(e)?e:sf(Xd(e.cause,e=>new jw(e)))}function Fw(e,t){let n;for(let r of e.reasons){if(!Hd(r)||!Mw(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 Iw(e){let t=Jg(e);if(uf(t))return t.value;throw Fw(t.cause,`Sync adapter can only throw schema errors`)}function Lw(e,t){return bw(e,t)}var Rw=IC;function zw(e,t){let n=zC(e,t);return(e,t)=>Nw(n(e,t))}var Bw=zw,Vw=BC,Hw=VC;function Uw(e,t){let n=HC(e,t);return(e,t)=>Oi(n(e,t),e=>new jw(e))}function Ww(e,t){let n=zw(e,t);return(e,t)=>Iw(n(e,t))}function Gw(e,t){let n=UC(e,t);return(e,t)=>Nw(n(e,t))}var Kw=Gw;function qw(e,t){let n=Gw(e,t);return(e,t)=>Iw(n(e,t))}var Jw=qw,Yw=iw;function Xw(e){return me(e,Ow)&&e[Ow]===Ow}var Zw=ww(e=>Yw(kS(e.ast),{schema:e})),Qw=ww(e=>{let t=yT(e);return Yw(jS(e.ast),{schema:t})}),$w=ww(e=>Yw(BS(e.ast),{schema:e})),eT=ww(e=>Yw(VS(e.ast),{schema:e}));function tT(e){let t=Yw(new dx(e),{literal:e,transform(n){return t.pipe(bT(tT(n),{decode:ib(()=>n),encode:ib(()=>e)}))}});return t}var nT=Yw(lx),rT=Yw(ux),iT=Yw(ix),aT=Yw(sx),A=Yw(px),oT=Yw(gx),sT=Yw(_x),cT=Yw(vx),lT=Yw(cx);function uT(e,t){return Yw(e,{fields:t,mapFields(e,t){let n=e(this.fields);return uT(Rx(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function j(e){return uT(Rx(e,void 0),e)}var dT=e=>typeof e==`symbol`?e:globalThis.String(e);function fT(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=eT(t.fields[o]),c=Object.hasOwn(e,o),l=c?e[o]:o,u=dT(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 j(n).pipe(bT(t,Cb({decode:Cw(i),encode:Cw(r)})))}}function pT(e,t){return Yw(FS(e.ast,t.ast),{key:e,value:t})}function mT(e,t){return Yw(Hx(e.ast,t.map(zx)),{schema:e,records:t})}function hT(e,t){return Yw(e,{elements:t,mapElements(e,t){let n=e(this.elements);return hT(Bx(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function gT(e){return hT(Bx(e),e)}var M=ww(e=>Yw(new yx(!1,[],[e.ast]),{value:e})),_T=ww(e=>Yw(new yx(!1,[e.ast],[e.ast]),{value:e}));function vT(e,t){return Yw(e,{members:t,mapMembers(e,t){let n=e(this.members);return vT(Vx(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function N(e,t){return vT(Vx(e,t,void 0),e)}function P(e){let t=e.map(tT);return Yw(Vx(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return N(e(this.members))},pick(e){return P(e)},transform(e){return N(t.map((t,n)=>t.transform(e[n])))}})}var F=ww(e=>N([e,iT])),yT=ww(e=>N([e,aT]));function I(e){return t=>Yw(t.ast,{schema:t,identifier:e})}function bT(e,t){return n=>Yw(NS(n.ast,e.ast,t?xb(t):Eb()),{from:n,to:e})}function xT(){return(e,t)=>AT()(e,{decode:t,encode:tb})}function ST(e,t){return n=>t?bT(n,t)(e):bT(n)(e)}function CT(e){return t=>Yw(MS(t.ast,e),{schema:t})}function wT(e){return Lc(e)&&e._tag===`Success`?e:ag(e,e=>Vh(()=>Xd(e,e=>e.issue)))}function TT(e,t){let n=t?.encodingStrategy===`omit`?cb():rb();return t=>Zw(eT(t)).pipe(bT(t,{decode:lb(wT(e)),encode:n}))}function ET(e,t){return n=>$w(n).pipe(TT(e,t),ST(Zw(n)))}function DT(e){return tT(e).pipe(CT(C(e)))}function OT(e,t){return j({_tag:DT(e),...t})}function kT(e,t){return Aw(t=>t instanceof e,t)}function AT(){return(e,t)=>new Qb(e.ast,xb(t))}var jT=sS;function MT(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 dS(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var NT=Yw(lS),PT=cS;function FT(e){let t=pr(e.order),n=e.formatter??ot;return(r,i)=>jT(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function IT(e){let t=hr(e.order),n=e.formatter??ot;return(r,i)=>jT(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 LT(e){let t=hr(e.order),n=pr(e.order),r=mr(e.order),i=fr(e.order),a=e.formatter??ot;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return jT(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 RT(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${ot(e)}`);return e}var zT=FT({order:cr,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:RT(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${ot(e)})`})})}),BT=IT({order:cr,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:RT(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${ot(e)})`})})}),VT=LT({order:cr,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:RT(e.minimum),maximum:RT(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 HT(e){return jT(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=oT.check(HT());function UT(e,t){return e=qT(e),WT(e,Math.ceil(e/2),t)}function WT(e,t,n){return jT(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})`}),[cy]:!0,arbitraryConstraint:{minLength:e},...n})}function GT(e){return WT(1,1,e)}function KT(e,t){return e=qT(e),jT(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})`}),[cy]:!0,arbitraryConstraint:{maxLength:e},...t})}function qT(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function JT(e){return jT(e=>va(e).length===e.length,{expected:`an array with unique items`,representation:{id:`effect/schema/isUnique`,payload:null},toJsonSchema:()=>({uniqueItems:!0}),toCode:()=>({runtime:`Schema.isUnique()`}),arbitraryConstraint:{uniqueBy:i},...e})}var R=A.check(GT()),YT=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),XT=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},ZT=[];function QT(e){let t=YT(e),n=ZT[t];if(n!==void 0)return n;let r=PE.pipe(bT(rT,Fb(XT(t))));return ZT[t]=r,r}globalThis.RegExp;var $T=A.annotate({expected:`a string that will be decoded as a URL`}),eE=kT(globalThis.URL,{representation:{id:`effect/schema/URL`,payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:`URL`,toCodecJson:()=>AT()($T,Rb)}),tE=$T.pipe(bT(eE,Rb)),nE=A.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function rE(e,t){return nE.pipe(bT(e,Bb(t)))}var iE=rE(rT);globalThis.File,globalThis.URLSearchParams;var aE=A.annotate({expected:`a string that will be decoded as a finite number`}).pipe(bT(NT,Db)),oE=A.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),sE=kT(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>AT()(oE,zb)});function cE(e,t){return Yw(kw()([e,t],([e,t])=>(n,r,i)=>{if(!Vd(n))return zh(new Oy(r,n,i));switch(n._tag){case`Fail`:return e_(zC(e)(n.error,i),{onSuccess:Kd,onFailure:e=>Ay(r,`error`,e,n,i)});case`Die`:return e_(zC(t)(n.defect,i),{onSuccess:qd,onFailure:e=>Ay(r,`defect`,e,n,i)});case`Interrupt`:return C(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])=>AT()(N([j({_tag:tT(`Fail`),error:e}),j({_tag:tT(`Die`),defect:t}),j({_tag:tT(`Interrupt`),fiberId:yT(NT)})]),Cb({decode:e=>{switch(e._tag){case`Fail`:return Kd(e.error);case`Die`:return qd(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 lE(e,t){return Yw(kw()([e,t],([e,t])=>{let n=M(cE(e,t));return(e,t,r)=>Bd(e)?e_(zC(n)(e.reasons,r),{onSuccess:Ud,onFailure:n=>Ay(t,`reasons`,n,e,r)}):zh(new Oy(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])=>AT()(M(cE(e,t)),Cb({decode:Ud,encode:({reasons:e})=>e}))}).ast,{error:e,defect:t})}var uE=Sb({decode:(e,t)=>_r(F_(e),{onNone:()=>zh(new ky({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>C(L_(e))}),encode:e=>C(G_(e))}),dE=-864e13,fE=864e13;function pE(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 mE(e,t){return L.check(VT({minimum:e,maximum:t}))}var hE=Aw(e=>j_(e)&&M_(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]=pE(e,dE,fE);return xT()(mE(t,n),ib(P_))},toCodecJson:()=>AT()(A,uE),toFormatter:()=>e=>e.toString()}),gE=A.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(bT(hE,uE));function z(e){return Yw(kw()([e],([e])=>(t,n,r)=>gr(t)?b(t)?Nh:e_(zC(e)(t.value,r),{onSuccess:y,onFailure:e=>Ay(n,`value`,e,t,r)}):zh(new Oy(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])=>AT()(N([j({_tag:tT(`Some`),value:e}),j({_tag:tT(`None`)})]),Cb({decode:e=>e._tag===`None`?v():y(e.value),encode:e=>x(e)?{_tag:`Some`,value:e.value}:{_tag:`None`}}))}).ast,{value:e})}function _E(e){return F(e).pipe(bT(z($w(e)),Ib()))}var vE=Aw(Fv,{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:()=>Vv,toCodec:()=>AT()(M(gT([A,A])),Cb({decode:Lv,encode:e=>e.params.map(([e,t])=>[e,Nv(t)])}))}).pipe(bT(pT(A,N([A,_T(A)])),Cb({decode:Jv,encode:Rv})));function yE(e){return Zw(e).pipe(bT(z($w(e)),Lb()))}function bE(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:zC(tT(n));return Yw(kw()([e],([e])=>(t,n,r)=>mv(t)?t_(a===void 0?Ih:$g(a(t.label,r),e=>new wy([`label`],e)),()=>e_(zC(e)(_v(t),r),{onSuccess:e=>hv(e,{label:t.label}),onFailure:()=>new Dy(n,[new wy([`value`],new ky(void 0,t,r))],t,r)})):zh(new Oy(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])=>AT()(e,{decode:ib(e=>hv(e,{label:n})),encode:r?eb(e=>`Cannot serialize Redacted`+(x(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):ib(_v)}),toEquivalence:([e])=>vv(e)}).ast,{value:e})}function xE(e,t){return bT(bE($w(e),{label:t?.label,disallowJsonEncode:t?.disallowEncode}),{decode:ib(e=>hv(e,{label:t?.label})),encode:t?.disallowEncode?eb(e=>`Cannot encode Redacted`+(x(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):ib(_v)})(e)}var SE=globalThis.Symbol.for(`immer-draftable`),CE={};function wE(t,n,r,i,a){let o=OE(r,n,i),s=DE(n),c=class extends t{constructor(...[e,t]){let n=t?.[`~payload`],i=n?.token===CE?n.value:r.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:CE,value:i}})}static[Ow]=Ow;get[s](){return s}static[SE]=!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 FC(o(this))(e??{},t)}static makeOption(e,t){return PC(o(this))(e??{},t)}static makeEffect(e,t){return o(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(vS(this.ast,e))}static annotateKey(e){return this.rebuild(OS(this.ast,e))}static check(...e){return this.rebuild(bS(this.ast,e))}static extend(e){return(t,n)=>{let i=kE(t)?t:j(t),o={...r.fields,...i.fields},s=Rx(o,r.ast.checks,{identifier:e});return wE(this,e,uT(bS(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 TE(e,t){return new e(t,{"~payload":{token:CE,value:t}})}function EE(e){return new yb(ib(t=>TE(e,t)),rb())}function DE(e){return`~effect/Schema/Class/${e}`}function OE(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=DE(t),o=e=>e instanceof i||me(e,a),s=EE(i);return r=bT(Yw(new rx([e.ast],()=>(e,t,n)=>o(e)?C(e):zh(new Oy(t,e,n)),{identifier:t,[uy]:([e])=>({isConstructed:o,link:new Qb(e,s)}),toCodec:([e])=>new Qb(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[ly]:Gx(e.ast),...n})),s)(e)}}function kE(e){return Xw(e)}var B=e=>(t,n)=>wE(xo,e,kE(t)?t:j(t),n,e=>({toString(){return`${e}(${ot({...this})})`}})),V=e=>(t,n,r)=>{let i=kE(n)?n.mapFields(e=>({_tag:DT(t),...e}),{unsafePreserveChecks:!0}):OT(t,n);return B(e??t)(i,r)},AE=e=>(t,n)=>wE(xn,e,kE(t)?t:j(t),n,e=>({name:e})),jE=e=>(t,n,r)=>{let i=kE(n)?n.mapFields(e=>({_tag:DT(t),...e}),{unsafePreserveChecks:!0}):OT(t,n);return AE(e??t)(i,r)},ME=aw,NE=fw,PE=Yw(vS(fC,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),FE=pT(A,PE),IE=Vs,LE=Us,RE=Ws,zE=Gs,BE=Ks,VE=Hu,HE=Qu,UE=`~effect/MutableRef`,WE={[UE]:UE,...Rt,toJSON(){return{_id:`MutableRef`,current:_t(this.current)}}},GE=e=>{let t=Object.create(WE);return t.current=e,t},KE=r(2,(e,t)=>(e.current=t,e)),qE=Symbol.for(`effect/MutableList/Empty`),JE=()=>({head:void 0,tail:void 0,length:0}),YE=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})},XE=()=>({array:[],mutable:!0,offset:0,next:void 0}),ZE=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=XE(),e.tail=e.tail.next):e.head=e.tail=XE(),e.tail.array.push(t),e.length++},QE=e=>{e.head=e.tail=void 0,e.length=0},$E=e=>{if(!e.head)return qE;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:QE(e):YE(e),t},eD=`~effect/Queue`,tD=`~effect/Queue/Enqueue`,nD=`~effect/Queue/Dequeue`,rD={_A:i,_E:i},iD={[eD]:rD,[tD]:rD,[nD]:rD,...Rt,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:uee(this)}}},aD=e=>yn(t=>{let n=Object.create(iD);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=JE(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},qs(n)}),oD=e=>aD({capacity:e}),sD=r(2,(e,t)=>Zs(()=>cD(e,t)?mD:e.state._tag===`Open`&&e.strategy===`suspend`?SD(e,t):pD)),cD=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?($E(e.messages),ZE(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(ZE(e.messages,t),_D(e),!0):(ZE(e.messages,t),vD(e),!0):!1,lD=r(2,(e,t)=>Xs(()=>uD(e,t))),uD=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=iee(gn(t),hD);return e.state.offers.size===0&&e.messages.length===0?(DD(e,n),!0):(e.state={...e.state,_tag:`Closing`,exit:n},vD(e),!0)},dD=e=>Xs(()=>cee(e)),cee=e=>{if(e.state._tag===`Done`)return!1;QE(e.messages);let t=e.state.offers;DD(e,e.state._tag===`Open`?gD:e.state.exit);for(let e of t)wD(e);return!0},fD=e=>yD(()=>lee(e)??jc(xD(e,()=>bD(e,1)),fD(e))),lee=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=$E(e.messages);return ED(e),pn(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=TD(e.state.offers);return ED(e),pn(t)}},uee=e=>e.state._tag===`Done`?0:e.messages.length,pD=pn(!1),mD=pn(!0),hD=_n(On()),gD=Wc(),_D=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(Yc),e.messages.length===0))break}},vD=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,_D(e)},0))},yD=dn({op:`QueueTake`,[Nt](e){let t=this[Mt]();return Vt(t)?t[Nt](e):t}}),bD=(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,xD=(e,t)=>lc(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(Yc);let r={ready:t,resume:n};return e.state.takers.add(r),Xs(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),SD=(e,t)=>lc(n=>cD(e,t)?n(mD):CD(e,{_tag:`Single`,message:t,resume:n})),CD=(e,t)=>{if(e.state._tag!==`Open`)return wD(t);let n=e.state.offers;return n.add(t),Xs(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&DD(e,e.state.exit))})},wD=e=>e._tag===`Single`?e.resume(pD):e.resume(pn(e.remaining.slice(e.offset))),TD=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(mD),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(pn([]))),n},ED=e=>{if(e.state._tag===`Done`)return Km(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(DD(e,e.state.exit),Km(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`)ZE(e.messages,t.message),e.state.offers.delete(t),t.resume(mD);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;ZE(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(pn([]))}let r=e.state;if(r._tag===`Done`)return Km(r.exit.cause)}return!1},DD=(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()},OD=e=>new AD(e),kD=(e,t,n)=>lc(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),Xs(()=>{e.waiters.delete(i)})}),AD=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=Zs(()=>this.free<e?kD(this,e,t):(this.taken+=e,qs(e)));return t}takeIfAvailable(e){return Zs(()=>this.free<e?qs(!1):(this.taken+=e,qs(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return yn(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),rc))}release(e){return yn(t=>qs(this.releaseUnsafe(t,e)))}get releaseAll(){return yn(e=>qs(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>Eu(n=>{let r=Zs(()=>this.free<e?Ic(n(kD(this,e,rc)),()=>r):(this.taken+=e,ou(n(t),()=>{this.releaseUnsafe(Ps(),e)},!0)));return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>Eu(n=>this.free<e?ec:(this.taken+=e,ou(n(Ac(t)),()=>{this.releaseUnsafe(Ps(),e)},!0)))}},jD=e=>Xs(()=>new AD(e)),MD=`~effect/Channel`,ND=e=>me(e,MD),PD={[MD]:{_Env:i,_InErr:i,_InElem:i,_OutErr:i,_OutElem:i},pipe(){return e(this,arguments)}},FD=e=>{let t=Object.create(PD);return t.transform=(t,n)=>ag(e(t,n),e=>C(Bh(e))),t},ID=(e,t)=>FD((n,r)=>T(zD(e)(n,r),e=>t(e,r))),LD=e=>FD((t,n)=>e),RD=e=>FD(Yg(function*(t,n){let r=kf(n),i=e=>Af(r,Xm(e));return kg(yield*kg(e(t,n,r),i),i)})),zD=e=>e.transform,BD=e=>FD((t,n)=>Ph(()=>zD(e())(t,n))),VD=e=>LD(C(zh(e))),HD=e=>LD(Bh(e)),UD=e=>HD(Gd(e)),WD=e=>FD((t,n)=>GD({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),GD=e=>{let t=e.readable.getReader(),n=e.exit??GE(void 0),r=Ph(()=>n.current?n.current:vg(Mh({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??Bh(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?rf():C(pa(t))}));return $h(Of(e.scope,e.releaseLockOnEnd?Fh(()=>t.releaseLock()):jh(()=>t.cancel().catch(e=>t.closed.then(()=>Promise.reject(e),u))).pipe(Og(Fh(()=>t.releaseLock())))),r)},KD=r(2,(e,t)=>ID(e,e=>Fh(()=>{let n=0;return Qh(e,e=>t(e,n++))}))),qD=e=>e===void 0||e!==`unbounded`&&e<=1,JD=r(e=>ND(e[0]),(e,t,n)=>qD(n?.concurrency)?YD(e,t):XD(e,t,n)),YD=(e,t)=>FD((n,r)=>{let i=0;return Qh(zD(e)(n,r),T(e=>t(e,i++)))}),XD=(e,t,n)=>RD(Yg(function*(r,i,o){let s=0,c=yield*zD(e)(r,i),l=n.concurrency===`unbounded`?2**53-1:Math.min(n.concurrency,2**53-1),u=yield*oD(0);yield*Of(o,dD(u));let d=Gg(yield*yg()),f=VE(o);if(n.unordered){let e=OD(l),n=a(e.release(1)),r=vg({onFailure:e=>T(lD(u,e),n),onSuccess:e=>T(sD(u,e),n)});yield*e.take(1).pipe(T(()=>c),T(e=>{let n=s++;return f(d(r(Ph(()=>t(e,n))))),Ih}),Lg({disableYield:!0}),ag(t=>e.withPermits(l-1)(lD(u,t))),Hg(o))}else{let e=yield*oD(l-2);yield*Of(o,dD(e)),yield*fD(e).pipe(Kh,T(e=>sD(u,e)),Lg({disableYield:!0}),ag(e=>lD(u,e)),Hg(o));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,uD(u,e.cause))};yield*c.pipe(T(i=>{if(n)return Bh(n);let a=s++,o=d(Ph(()=>t(i,a)));return f(o),o.addObserver(r),sD(e,LE(o))}),Lg({disableYield:!0}),ag(t=>sD(e,sf(t)).pipe(qh(lD(e,t)))),Hg(o))}return fD(u)})),ZD=e=>ID(e,e=>{let t,n=0;return C(Ph(function r(){if(t===void 0)return T(e,e=>{switch(e.length){case 0:return r();case 1:return C(e[0]);default:return t=e,C(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),C(i)}))}),QD=r(2,(e,t)=>ID(e,e=>C(T(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return Xi(i)?C(i):T(e,n)})))),$D=r(2,(e,t)=>FD((n,r)=>{let i=kf(r);return Qh(zD(e)(n,i),e=>{let a=e.pipe(ag(e=>{if(Km(e))return Bh(e);let o=i;return i=kf(r),Af(o,sf(e)).pipe(qh(zD(t(e))(n,i)),T(e=>(a=e,e)))}));return Ph(()=>a)})})),eO=r(3,(e,t,n)=>$D(e,e=>{let r=t(e);return Ei(r)?HD(r.failure):n(r.success,e)})),tO=r(2,(e,t)=>eO(e,ds,e=>t(e))),nO=r(e=>ND(e[0]),(e,t,n,r)=>tO(e,e=>t(e)?n(e):r?r(e):VD(e))),rO=r(2,(e,t)=>ID(e,e=>C(sg(e,e=>nf(e)?e:t(e))))),iO=r(e=>ND(e[0])&&ND(e[1]),(e,t,n)=>RD(Yg(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*oD(0);yield*Of(a,dD(s));let c=0;function l(e,t){if(c++,!Km(t))return lD(s,t);switch(o){case`both`:return c===2?lD(s,t):Ih;case`left`:case`right`:return e===o?lD(s,t):Ih;case`either`:return lD(s,t)}}let u=(e,t,n)=>zD(t)(r,n).pipe(T(e=>e.pipe(T(e=>sD(s,e)),Lg)),kg(t=>Ag(Xm(t),e=>Af(n,e)).pipe(vg({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Hg(a));return yield*u(`left`,e,kf(a)),yield*u(`right`,t,kf(a)),fD(s)}))),aO=(e,t)=>FD((n,r)=>Fh(()=>{let r=new TextDecoder(e,t),i={stream:!0},a=n.pipe(Qh(ma(e=>r.decode(e,i))),Gm(e=>{a=rf(e);let t=r.decode();return t.length>0?C(pa(t)):a}));return Ph(()=>a)})),oO=r(2,(e,t)=>FD((n,r)=>T(zD(e)(n,r),e=>zD(t)(e,r)))),sO=r(2,(e,t)=>iO(e,LD(C(T(t,rf))),{haltStrategy:`either`})),cO=r(2,(e,t)=>RD((n,r,i)=>Df(i,t).pipe(qh(zD(e)(n,r))))),lO=r(2,(e,t)=>cO(e,e=>t)),uO=(e,t,n)=>Ph(()=>{let r=Tf();return Gm(T(zD(e)(rf(),r),t),n||C).pipe(jg(e=>Af(r,e)))}),dO=r(2,(e,t)=>FD((n,r)=>Qh(Sg(zD(e)(n,r),t),Sg(t)))),fO=r(2,(e,t)=>uO(e,e=>Lg(T(e,t),{disableYield:!0}))),pO=e=>Ph(()=>{let t=v();return uO(e,e=>e.pipe(eg,T(e=>(t=e,rf()))),()=>C(t))}),mO=(e,t)=>zD(e)(rf(),t),hO=(e,t)=>()=>{let n=Bw(_T(e),t);return FD((e,t)=>C(T(e,e=>n(e))))},gO=`~effect/Stream`,_O={_R:i,_E:i,_A:i},vO=function(e){this.channel=e};vO.prototype={[gO]:_O,pipe(){return e(this,arguments)}};var yO=e=>new vO(e),bO=`~effect/Stream`,xO=e=>me(e,bO),SO=yO,CO=(e,t)=>SO(FD((n,r)=>T(mO(e.channel,r),e=>t(e,r)))),wO=e=>e.channel,TO=e=>{let t=SO(BD(()=>e().channel));return EO.set(t,e),t},EO=new WeakMap,DO=e=>SO(VD(e)),OO=e=>SO(UD(e)),kO=e=>SO(WD(e)),AO=r(2,(e,t)=>TO(()=>{let n=0;return SO(KD(e.channel,ma(e=>t(e,n++))))})),jO=r(e=>xO(e[0]),(e,t,n)=>e.channel.pipe(ZD,JD(t,n),KD(pa),SO)),MO=r(2,(e,t)=>SO(JD(e.channel,t))),NO=r(2,(e,t)=>SO(QD(wO(e),t))),PO=r(e=>xO(e[0]),(e,t,n,r)=>SO(nO(wO(e),t,e=>n(e).channel,r&&(e=>r(e).channel)))),FO=r(2,(e,t)=>SO(rO(e.channel,t))),IO=r(2,(e,t)=>SO(oO(e.channel,t))),LO=r(e=>xO(e[0]),(e,t)=>e.channel.pipe(oO(aO(t?.encoding)),SO)),RO=r(2,(e,t)=>SO(sO(e.channel,t))),zO=r(2,(e,t)=>SO(lO(e.channel,t))),BO=r(2,(e,t)=>SO(dO(e.channel,t))),VO=e=>Qh(pO(e.channel),Dr($i(0))),HO=r(e=>xO(e[0]),(e,t,n)=>{let r,i,a=!1,o=HE(!1),s=n?.signal,c=()=>i.interruptUnsafe();return new ReadableStream({start(n){i=Wg(Sg(fO(ID(e.channel,e=>C(o.whenOpen(e))),e=>Fh(()=>{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(Qd(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,Kg(tg(RE(i)))}},n?.strategy)}),UO=r(e=>xO(e[0]),(e,t)=>Qh(yg(),n=>HO(e,n,t))),WO=Lr(`effect/Crypto`),GO=`~effect/FiberMap`,KO=e=>me(e,GO),qO={[GO]:GO,[Symbol.iterator](){return this.state._tag===`Closed`?Li():this.state.backing[Symbol.iterator]()},...Rt,toJSON(){return{_id:`FiberMap`,state:this.state}}},JO=(e,t)=>{let n=Object.create(qO);return n.state={_tag:`Open`,backing:e,fibers:new Set},n.deferred=t,n},YO=()=>Eg(Fh(()=>JO(bh(),mf())),e=>Ph(()=>{let t=e.state;return t._tag===`Closed`?Ih:(e.state={_tag:`Closed`},BE(t.fibers).pipe(Sf(e.deferred)))})),XO=-1,ZO=co(uo(ef,lo(XO))),QO=r(e=>KO(e[0]),(e,t,n,r)=>{if(e.state._tag===`Closed`){n.interruptUnsafe(XO);return}let i=xh(e.state.backing,t);if(i._tag===`Some`){if(i.value===n)return;if(r?.onlyIfMissing===!0){n.interruptUnsafe(XO);return}}Th(e.state.backing,t,n),e.state.fibers.add(n),i._tag===`Some`&&i.value.interruptUnsafe(XO),n.addObserver(i=>{if(e.state._tag===`Closed`)return;e.state.fibers.delete(n);let a=xh(e.state.backing,t);x(a)&&n===a.value&&Dh(e.state.backing,t),df(i)&&(r?.propagateInterruption===!0?!ZO(i.cause):!Yd(i.cause))&&xf(e.deferred,i)})}),$O=r(2,(e,t)=>e.state._tag===`Closed`?v():xh(e.state.backing,t)),ek=r(2,(e,t)=>Ph(()=>C($O(e,t)))),tk=r(2,(e,t)=>e.state._tag!==`Closed`&&wh(e.state.backing,t)),nk=r(2,(e,t)=>Fh(()=>tk(e,t))),rk=r(2,(e,t)=>Ph(()=>{if(e.state._tag===`Closed`)return Ih;let n=xh(e.state.backing,t);return n._tag===`None`?Ih:zE(n.value,XO)})),ik=function(){let e;return()=>(e===void 0&&(e=Wg(Ng)),e)}(),ak=function(){let e=arguments[0];if(Oh(arguments[2]))return ok(e,arguments[1],arguments[2],arguments[3]);let t=arguments[1],n=arguments[2];return r=>ok(e,t,r,n)},ok=(e,t,n,r)=>Wh(i=>{if(e.state._tag===`Closed`)return Ng;if(r?.onlyIfMissing===!0&&tk(e,t))return Fh(ik);let a=Lu(i,n,r?.startImmediately??!0,!0);return QO(e,t,a,r),C(a)}),sk=`~effect/Match/Matcher`,ck={[sk]:{_input:i,_filters:i,_remaining:i,_result:i,_return:i,_args:i},_tag:`TypeMatcher`,add(e){return lk(this.select,[...this.cases,e])},pipe(){return e(this,arguments)}};function lk(e,t){let n=Object.create(ck);return n.select=e,n.cases=t,n}var uk={[sk]:{_input:i,_filters:i,_result:i,_return:i,_flavor:i},_tag:`ValueMatcher`,add(e){return Di(this.value)?this:e._tag===`When`&&e.guard(this.provided)===!0||e._tag===`Not`&&e.guard(this.provided)===!1?dk(this.provided,xi(e.evaluate(this.provided))):this},pipe(){return e(this,arguments)}};function dk(e,t){let n=Object.create(uk);return n.provided=e,n.value=t,n}var fk=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),pk=e=>{if(typeof e==`function`)return e;if(Array.isArray(e)){let t=e.map(pk),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,pk(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},mk=e=>dk(e,Si(e)),hk=r(2,(e,t)=>vk(t)(lk(i,[]))(e)),gk=(e,t)=>n=>n.add(fk(pk(e),t)),_k=e=>t=>{let n=fk(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},vk=(e=>t=>{let n=_k(e)(t);return e=>Sk(n(e))})(`_tag`),yk=e=>t=>{let n=bk(t);return Ti(n)?n._tag===`Success`?n.success:e(n.failure):(...t)=>{let r=n(...t);return Di(r)?r.success:e(r.failure,...t)}},bk=e=>{if(e._tag===`ValueMatcher`)return e.value;let t=e.cases.length;if(t===1){let t=e.cases[0];return(...n)=>{let r=e.select(...n);return t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1?xi(t.evaluate(r,...n)):Si(r)}}return(...n)=>{let r=e.select(...n);for(let i=0;i<t;i++){let t=e.cases[i];if(t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1)return xi(t.evaluate(r,...n))}return Si(r)}},xk=`effect/match/Match/exhaustive: absurd`,Sk=e=>{let t=bk(e);if(Ti(t)){if(Di(t))return t.success;throw Error(xk)}return(...e)=>{let n=t(...e);if(Di(n))return n.success;throw Error(xk)}},Ck=mk,wk=hk,Tk=gk,Ek=te,Dk=ne,Ok=ae,kk=yk,Ak={"~effect/Ref":{_A:i},...Rt,toJSON(){return{_id:`Ref`,ref:this.ref}}},jk=e=>{let t=Object.create(Ak);return t.ref=GE(e),t},Mk=e=>Fh(()=>jk(e)),Nk=e=>Fh(()=>e.ref.current),Pk=r(2,(e,t)=>Fh(()=>KE(e.ref,t))),Fk=r(2,(e,t)=>Fh(()=>{let[n,r]=t(e.ref.current);return e.ref.current=r,n})),Ik=r(2,(e,t)=>Fh(()=>{e.ref.current=t(e.ref.current)})),Lk=r(2,(e,t)=>Fh(()=>e.ref.current=t(e.ref.current))),Rk=r(2,(e,t)=>e===void 0?void 0:t(e)),zk=`~effect/SynchronizedRef`,Bk={...Rt,[zk]:zk,toJSON(){return{_id:`SynchronizedRef`,value:this.backing.ref.current}}},Vk=e=>{let t=Object.create(Bk);return t.semaphore=OD(1),t.backing=jk(e),t},Hk=e=>Fh(()=>Vk(e)),Uk=e=>e.backing.ref.current,Wk=r(2,(e,t)=>e.semaphore.withPermit(Ph(()=>Qh(t(Uk(e)),([t,n])=>(e.backing.ref.current=n,t))))),H=A.check(MT(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u,{message:`Expected a full GitHub repo name (owner/name)`})).pipe(I(`RepositoryName`)),Gk=A.check(MT(/^[^\s-]\S*$/u,{message:`Expected a Git revision without whitespace or a leading dash`})).pipe(I(`RepositoryRevision`)),Kk=A.check(MT(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u,{message:`Expected a 40- or 64-character lowercase Git object ID`})).pipe(I(`CommitSha`)),qk=e=>e.replaceAll(/[^A-Za-z0-9_.-]/gu,`_`),Jk=e=>{let t=e.indexOf(`/`);return{owner:e.slice(0,t),name:e.slice(t+1)}},Yk=e=>e.toLowerCase(),Xk=A.check(MT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a project slug`})).pipe(I(`ProjectId`)),Zk=j({message:A}),Qk=()=>document.cookie.split(`; `).find(e=>e.startsWith(`usine_csrf=`))?.slice(11)??``,$k=async(e,t,n={})=>{let r={method:n.method??`GET`,credentials:`same-origin`,headers:{"content-type":`application/json`,"x-usine-csrf":Qk()}};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(Ww(Zk)(a).message);return Ww(t)(a)},eA=j({ok:sT}),tA=A.check(MT(/\S/u,{message:`Expected a non-blank model ID`})).pipe(I(`ModelId`)),nA=P([`claude`,`codex`,`pi`]),rA=P([`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),iA=class extends B(`Agent/BrainSpec`)({harness:nA,model:tA,effort:rA}){},aA=A.check(MT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case agent name`})).pipe(I(`AgentName`)),oA=A.check(MT(/\S/u,{message:`Expected a non-blank agent persona`})).pipe(I(`AgentPersona`)),sA=class extends B(`Agent`)({name:aA,brain:iA,parentModel:_E(tA),parentEffort:yE(rA),persona:oA}){},cA=(e,t)=>br([e.parentModel,t]),lA=(e,t)=>vr(br([e.parentEffort,t]),()=>e.brain.effort),uA=R.pipe(I(`LoopName`)),dA=[`none`,`required`],fA=P(dA),pA=[`write`,`read`],mA=P(pA),hA=A.check(MT(/^\S(?:.*\S)?$/u,{message:`Expected a GitHub label name without surrounding whitespace`}),KT(50,{message:`Expected a GitHub label name of at most 50 characters`})).pipe(I(`GitHubLabelName`)),gA=e=>e.toLowerCase(),_A=A.check(MT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex GitHub label color without #`})).pipe(I(`GitHubLabelColor`)),vA=A.check(KT(100,{message:`Expected a GitHub label description of at most 100 characters`})),yA=class extends B(`@usine/config/DeclaredLabel`)({name:hA,color:yE(_A),description:yE(vA)}){},U=Symbol.for(`drizzle:entityKind`),bA=new WeakMap;function xA(e){let t=new Set;for(let n=e;n;n=Object.getPrototypeOf(n))U in n&&t.add(n[U]);return bA.set(e,t),t}var SA=Function.prototype[Symbol.hasInstance];function W(e,t){if(SA.call(t,e))return!0;if(typeof e!=`object`||!e)return!1;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`&&(bA.get(n)??xA(n)).has(t[U])}function CA(e){if(typeof e!=`object`||!e)return;let t=Object.getPrototypeOf(e)?.constructor;if(typeof t==`function`)return bA.get(t)??xA(t)}var wA=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}},TA=Symbol.for(`drizzle:Name`),EA=Symbol.for(`drizzle:Schema`),DA=Symbol.for(`drizzle:Columns`),OA=Symbol.for(`drizzle:ExtraConfigColumns`),kA=Symbol.for(`drizzle:OriginalName`),AA=Symbol.for(`drizzle:BaseName`),jA=Symbol.for(`drizzle:CacheKey`),MA=Symbol.for(`drizzle:IsAlias`),NA=Symbol.for(`drizzle:Qualifier`),PA=Symbol.for(`drizzle:ExtraConfigBuilder`),FA=Symbol.for(`drizzle:IsDrizzleTable`),IA=class{static[U]=`Table`;static[Symbol.hasInstance](e){return W(e,this)}static Symbol={Name:TA,Schema:EA,OriginalName:kA,Columns:DA,ExtraConfigColumns:OA,BaseName:AA,IsAlias:MA,ExtraConfigBuilder:PA,CacheKey:jA};[TA];[kA];[EA];[DA];[OA];[AA];[jA];[MA]=!1;[FA]=!0;[PA]=void 0;constructor(e,t,n){this[TA]=this[kA]=e,this[EA]=t,this[AA]=n,this[jA]=t?`${t}.${e}`:e}};function LA(e){return e[TA]}var RA=Symbol.for(`drizzle:OriginalColumn`),zA=e=>e;zA.isNoop=!0;var BA=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=zA;mapToDriverValue=zA;postBuild(){return this}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}[RA](){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(`)},VA=Symbol.for(`drizzle:ViewBaseConfig`),HA=Symbol.for(`drizzle:IsDrizzleView`),UA=class{static[U]=`View`;static[Symbol.hasInstance](e){return W(e,this)}[VA];[HA]=!0;get[TA](){return this[VA].name}get[EA](){return this[VA].schema}get[MA](){return this[VA].isAlias}get[kA](){return this[VA].originalName}get[DA](){return this[VA].selectedFields}constructor({name:e,schema:t,selectedFields:n,query:r}){this[VA]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}},WA=class{static[U]=`Subquery`;static[Symbol.hasInstance](e){return W(e,this)}get[TA](){return this._.alias}get[EA](){}get[kA](){return this._.alias}get[MA](){return!1}get[DA](){return this._.selectedFields}constructor(e,t,n,r=!1){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r}}},GA=class extends WA{static[U]=`WithSubquery`};function KA(e){return e!=null&&typeof e.getSQL==`function`}var qA=class e{queryChunks;static[U]=`SQL`;static[Symbol.hasInstance](e){return W(e,this)}decoder=tj;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=ZA(f);if(QA(f,p,q.string))i.sql+=f.value??``;else if(QA(f,p,q.sql))this.collectSQL(f.queryChunks,t,n,r||f.shouldInlineParams,i,a,void 0);else if(QA(f,p,q.name))i.sql+=s(f.value);else if(f!==void 0){if(QA(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[IA.Symbol.Schema];i.sql+=f.isAlias?s(f.name):f.table[MA]||t===void 0?s(f.table[IA.Symbol.Name])+`.`+s(e):s(t)+`.`+s(f.table[IA.Symbol.Name])+`.`+s(e)}else if(QA(f,p,q.param)){let e=f.value,o=ZA(e);if(QA(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&&ZA(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(QA(f,p,q.placeholder))i.sql+=c(n.value++,f),a.push(f);else if(QA(f,p,q.table)){let e=f[IA.Symbol.Schema],t=f[IA.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[MA]?s(t):s(e)+`.`+s(t)}else if(QA(f,p,q.view)){let e=f[VA].schema,t=f[VA].name;i.sql+=e===void 0||f[VA].isAlias?s(t):s(e)+`.`+s(t)}else if(QA(f,p,q.aliased)&&f.fieldAlias!==void 0)i.sql+=(f.origin===void 0?``:s(f.origin)+`.`)+s(f.fieldAlias);else if(QA(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&&ZA(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=ZA(d);f===q.other?this.collectBoundValue(d,o[u],c[u],t,n,r,i,a):QA(d,f,q.string)?i.sql+=d.value??``:this.collectSQL([f===q.sql?d:new rj(d,o[u])],t,n,r,i,a,void 0)}i.sql+=`)`}else if(QA(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(KA(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)),ZA(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},JA=new WeakMap,YA=Symbol(`drizzle:chunkKind`);function XA(e,t){let n=t.has(G[U])?q.string:t.has(qA[U])?q.sql:t.has($A[U])?q.name:t.has(BA[U])?q.column:t.has(rj[U])?q.param:t.has(oj[U])?q.placeholder:t.has(IA[U])?q.table:t.has(UA[U])?q.view:t.has(qA.Aliased[U])?q.aliased:t.has(WA[U])?q.subquery:t.has(ij[U])?q.valueRows:q.other;return JA.set(e,n),n!==q.other&&Object.defineProperty(e.prototype,YA,{value:n}),n}function ZA(e){if(typeof e!=`object`||!e)return q.other;let t=e[YA];if(t!==void 0)return t;let n=Object.getPrototypeOf(e)?.constructor;return typeof n==`function`?JA.get(n)??XA(n,CA(e)):q.other}function QA(e,t,n){return t===n}var $A=class{value;static[U]=`Name`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e){this.value=e}getSQL(){return new qA([this])}};function ej(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}var tj={mapFromDriverValue:e=>e};tj.mapFromDriverValue.isNoop=!0;var nj={mapToDriverValue:e=>e};nj.mapToDriverValue.isNoop=!0,{...tj,...nj};var rj=class{value;encoder;codec;static[U]=`Param`;static[Symbol.hasInstance](e){return W(e,this)}brand;constructor(e,t=nj,n){this.value=e,this.encoder=t,this.codec=n}getSQL(){return new qA([this])}},ij=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=ZA(o);r.push(s===q.sql||s===q.string?o:new rj(o,t[a]))}return r.push(K[`)`]),new qA(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 qA(n)}(function(e){function t(){return new qA([])}e.empty=t;function n(e){return new qA(e)}e.fromList=n;function r(e){return new qA([new G(e)])}e.raw=r;function i(e,t){let{length:n}=e;if(t===void 0||n===0)return new qA(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 qA(r)}e.join=i;function a(e){return new $A(e)}e.identifier=a;function o(e){return new oj(e)}e.placeholder=o;function s(e,t){return new rj(e,t)}e.param=s;function c(e){let t=aj(e);if(t.length)return J.raw(t)}e.comment=c})(J||={});function aj(e){let t=aj.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})(aj||={}),(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})(qA||={});var oj=class{name;static[U]=`Placeholder`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}getSQL(){return new qA([this])}};function sj(e){let t=e.queryChunks,n;for(let e=0;e<t.length;++e){let r=t[e];W(r,BA)&&((n??=[...t])[e]=J.identifier(r.name))}if(!n)return e;let r=new qA(n);return r.decoder=e.decoder,r.shouldInlineParams=e.shouldInlineParams,r}function cj(e,t){for(let n=0;n<e.length;++n){let r=e[n];switch(ZA(r)){case q.table:t.add(r[jA]);break;case q.sql:cj(r.queryChunks,t);break;case q.param:{let e=r.value;ZA(e)===q.sql&&cj(e.queryChunks,t);break}case q.subquery:cj(r._.sql.queryChunks,t);break;case q.valueRows:cj(r.cells,t);break;case q.other:case q.aliased:Array.isArray(r)?cj(r,t):KA(r)&&cj(r.getSQL().queryChunks,t)}}}BA.prototype.getSQL=function(){return new qA([this])},G.prototype.getSQL=function(){return new qA([this])},WA.prototype.getSQL=function(){return new qA([this])};function lj(e,t){Object.defineProperty(e,NA,{get(){let e=t(this);return Object.defineProperty(this,NA,{value:e,enumerable:!1,configurable:!0,writable:!0}),e},configurable:!0})}function uj(e,t){return new qA(e===void 0?[new $A(t)]:[new $A(e),K[`.`],new $A(t)])}lj(IA.prototype,e=>uj(e[EA],e[TA])),lj(UA.prototype,e=>uj(e[VA].schema,e[VA].name)),lj(WA.prototype,e=>new $A(e._.alias));function dj(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 fj=Object.getPrototypeOf(()=>null).constructor;function pj(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 mj(e,t){let n=`\t"use strict";
|
|
19
|
-
const { columns } = this;
|
|
20
|
-
const { length } = rows;
|
|
21
|
-
const mapped = new Array(length);
|
|
22
|
-
${pj(e,t)}
|
|
23
|
-
return mapped;
|
|
24
|
-
//# sourceURL=drizzle:jit-query-mapper`;return Object.assign(new fj(`rows`,n).bind({columns:e}),{body:`function jitQueryMapper (rows) {\n${n}\n}`})}function hj(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?dj(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 gj(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,BA))r.push({path:s,field:o,fieldType:`Column`,codec:n?.get(o,`normalize`),arrayDimensions:o.dimensions,column:o});else if(W(o,qA)){let e=_j(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,qA.Aliased)){let e=_j(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,WA)){let e,t=Object.values(o._.selectedFields)[0],i;W(t,BA)?(e=t,i=t):W(t,qA)?(e=_j(t),i=t.decoder):(e=_j(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,IA)?gj(o[IA.Symbol.Columns],s,n,r):gj(o,s,n,r)}return r}function _j(e){let{decoder:t}=e.getSQL();return QA(t,ZA(t),q.column)?t:void 0}function vj(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 yj(e){return e[IA.Symbol.Columns]}function bj(e){let t=ZA(e);return QA(e,t,q.subquery)?e._.alias:QA(e,t,q.view)?e[VA].name:QA(e,t,q.sql)?void 0:e[IA.Symbol.IsAlias]?e[IA.Symbol.Name]:e[IA.Symbol.BaseName]}function xj(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}typeof TextDecoder>`u`||new TextDecoder;function Sj(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 Cj=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===RA&&!this.ignoreColumnAlias?()=>e:e[t]}},wj=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=QA(n,ZA(n),q.column)?new Proxy(n,this.columnHandler??=new Cj(this.view,this.ignoreColumnAlias)):KA(n)?n:new Proxy(n,this),r.set(n,i)),i}},Tj=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===NA)return this.qualifier??=J.identifier(this.alias);if(t===IA.Symbol.IsAlias)return!0;if(t===IA.Symbol.Name||this.replaceOriginalName&&t===IA.Symbol.OriginalName)return this.alias;if(t===IA.Symbol.Columns){let t=e[IA.Symbol.Columns];return t&&(QA(e,ZA(e),q.view)?this.aliasSelection(t,n):this.getProxiedColumns(t,n))}if(t===VA){let t=e[VA],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(QA(r,ZA(r),q.column)){let i=e[IA.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 Cj(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 wj(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}},Ej=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=ZA(n);return QA(n,a,q.column)?i=new Proxy(n,this.columnHandler??=new Cj(this.subquery,!0)):QA(n,a,q.aliased)?(i=n.clone(),i.isSelectionField=!0,i.origin=this.alias):i=n,r.set(n,i),i}},Dj=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===NA)return this.qualifier??=J.identifier(this.alias);if(t===IA.Symbol.IsAlias)return!0;if(t===IA.Symbol.Name)return this.alias;if(t===IA.Symbol.OriginalName)return e._.alias;if(t!==IA.Symbol.Schema)return t===`_`?this.config??={...e._,alias:this.alias,isWith:!0,selectedFields:this.aliasSelection(e,n)}:t===IA.Symbol.Columns?this.aliasSelection(e,n):e[t]}aliasSelection(e,t){return this.selection??=new Proxy(e._.selectedFields,new Ej(t,this.alias))}},Oj=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===RA?()=>e:e[t]}};function kj(e,t){return QA(e,ZA(e),q.subquery)?new Proxy(e,new Dj(t)):new Proxy(e,new Tj(t,!1,!1))}function Aj(e){let t=e[IA.Symbol.Schema],n=J.identifier(e[IA.Symbol.OriginalName]);return t?J`${J.identifier(t)}.${n} ${e}`:J`${n} ${e}`}function jj(e,t){return new Proxy(e,new Oj(t))}BA.prototype.as=function(e){return jj(this,e)};function Mj(e){return e[RA]()}var Nj=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 Pj(e,t){if(ej(t)&&!KA(e)){let n=ZA(e);if(n!==q.param&&n!==q.placeholder&&n!==q.column&&n!==q.table&&n!==q.view)return new rj(e,t)}return e}var Fj=(e,t,n)=>new qA([e,t,Pj(n,e)]),Y=(e,t)=>Fj(e,K[` = `],t),Ij=(e,t)=>Fj(e,K[` <> `],t),Lj=(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 qA(n)};function Rj(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new qA(t):Lj(t,K[`) and (`])}function zj(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new qA(t):Lj(t,K[`) or (`])}function Bj(e){if(e)return W(e,qA)?J`not (${e})`:J`not ${e}`}var Vj=(e,t)=>Fj(e,K[` > `],t),Hj=(e,t)=>Fj(e,K[` >= `],t),Uj=(e,t)=>Fj(e,K[` < `],t),Wj=(e,t)=>Fj(e,K[` <= `],t);function Gj(e,t){return Array.isArray(t)?t.length===0?new qA([K[`1 = 0`]]):new qA([e,K[` in `],t.map(t=>Pj(t,e))]):Fj(e,K[` in `],t)}function Kj(e,t){return Array.isArray(t)?t.length===0?new qA([K[`1 = 1`]]):new qA([e,K[` not in `],t.map(t=>Pj(t,e))]):Fj(e,K[` not in `],t)}function qj(e){return J`(${e} is null)`}function Jj(e){return J`(${e} is not null)`}function Yj(e){return J`exists ${e}`}function Xj(e){return J`not exists ${e}`}function Zj(e,t,n){return J`${e} between ${Pj(t,e)} and ${Pj(n,e)}`}function Qj(e,t,n){return J`${e} not between ${Pj(t,e)} and ${Pj(n,e)}`}function $j(e,t){return J`${e} like ${t}`}function eM(e,t){return J`${e} not like ${t}`}function tM(e,t){return J`${e} ilike ${t}`}function nM(e,t){return J`${e} not ilike ${t}`}function rM(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContains requires at least one value`);let n=Pj(t,e),r=J`${Array.isArray(n)?new rj(n):n}`;return J`${e} @> ${r}`}return J`${e} @> ${Pj(t,e)}`}function dee(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContained requires at least one value`);let n=Pj(t,e),r=J`${Array.isArray(n)?new rj(n):n}`;return J`${e} <@ ${r}`}return J`${e} <@ ${Pj(t,e)}`}function iM(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayOverlaps requires at least one value`);let n=Pj(t,e),r=J`${Array.isArray(n)?new rj(n):n}`;return J`${e} && ${r}`}return J`${e} && ${Pj(t,e)}`}function aM(e){return J`${e} asc`}function oM(e){return J`${e} desc`}var sM={and:Rj,between:Zj,eq:Y,exists:Yj,gt:Vj,gte:Hj,ilike:tM,inArray:Gj,arrayContains:rM,arrayContained:dee,arrayOverlaps:iM,isNull:qj,isNotNull:Jj,like:$j,lt:Uj,lte:Wj,ne:Ij,not:Bj,notBetween:Qj,notExists:Xj,notLike:eM,notIlike:nM,notInArray:Kj,or:zj,sql:J},cM={sql:J,asc:aM,desc:oM};function lM(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??tj;break;case`Nested`:o=tj;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){lM(o[t.key],!1,t.selection,!1,i);continue}lM(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 uM(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??tj;break;case`Nested`:a=tj;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?lM(s,!1,t.selection,!1,i):lM(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 dM({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){return(o=>t&&!o[0]?o[0]:a?uM(t?o[0]:o,t,e,n,r):lM(t?o[0]:o,t,e,n,r,i))}function fM(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:ee,subqueryDecoder:te}]of e.entries()){let e=`${n}[${t}]`,ne=JSON.stringify(m),re=f[t];if(_){r?(l.push(`if (${re} !== null) ${re} = JSON.parse(${re});`),d=!0):i&&(l.push(`if (typeof ${re} === 'string') ${re} = JSON.parse(${re});`),d=!0);let t=`s${s.n++}`,n=o.length;if(o.push(`const { selection: ${t} } = ${e};`),g){let e=`j${s.n++}`,r=fM(_,`${re}[${e}]`,t,!1,i,!0,o,s,!1);if(r.hasWork){d=!0,l.push(`if (${re} !== null) {`),l.push(`\tfor (let ${e} = 0; ${e} < ${re}.length; ++${e}) {`);for(let e of r.bodyStmts)l.push(`\t\t${e}`);l.push(`\t\t${re}[${e}] = ${r.literal};`),l.push(` }`),l.push(`}`)}else o.splice(n,1)}else{let e=fM(_,re,t,!1,i,!0,o,s,!1);if(e.hasWork){d=!0,l.push(`if (${re} !== null) {`);for(let t of e.bodyStmts)l.push(`\t${t}`);l.push(`\t${re} = ${e.literal};`),l.push(`}`)}else o.splice(n,1)}u.push(`${ne}: ${re}`);continue}let ie=``,ae=``,oe=!1;switch(p){case`Column`:if(a&&c.mapFromJsonValue){oe=!0;let e=s.n++;ae=`field: dec${e}`,ie=`dec${e}.mapFromJsonValue`}else if(!c.mapFromDriverValue.isNoop){let e=s.n++;ae=`field: dec${e}`,ie=`dec${e}.mapFromDriverValue`}break;case`SQL`:if(a&&c.decoder.mapFromJsonValue){oe=!0;let e=s.n++;ae=`field: { decoder: dec${e} }`,ie=`dec${e}.mapFromJsonValue`}else if(!c.decoder.mapFromDriverValue.isNoop){let e=s.n++;ae=`field: { decoder: dec${e} }`,ie=`dec${e}.mapFromDriverValue`}break;case`SQL.Aliased`:if(a&&c.sql.decoder.mapFromJsonValue){oe=!0;let e=s.n++;ae=`field: { sql: { decoder: dec${e} } }`,ie=`dec${e}.mapFromJsonValue`}else if(!c.sql.decoder.mapFromDriverValue.isNoop){let e=s.n++;ae=`field: { sql: { decoder: dec${e} } }`,ie=`dec${e}.mapFromDriverValue`}break;case`Subquery`:if(a&&te?.mapFromJsonValue){oe=!0;let e=s.n++;ae=`subqueryDecoder: dec${e}`,ie=`dec${e}.mapFromJsonValue`}else if(te&&!te.mapFromDriverValue.isNoop){let e=s.n++;ae=`subqueryDecoder: dec${e}`,ie=`dec${e}.mapFromDriverValue`}break;case`Nested`:break;default:{let t=c.getSQL();if(a&&t.decoder.mapFromJsonValue){oe=!0;let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),ie=`dec${t}.mapFromJsonValue`}else if(!t.decoder.mapFromDriverValue.isNoop){let t=s.n++;o.push(`const dec${t} = ${e}.field.getSQL().decoder;`),ie=`dec${t}.mapFromDriverValue`}}}let se=``;if(!oe&&h&&(se=`codec${s.n++}`),ae||se){let t=[];ae&&t.push(ae),se&&t.push(`codec: ${se}`),o.push(`const { ${t.join(`, `)} } = ${e};`)}if(ie||se){d=!0;let e=re;se&&(e=`${se}(${e}, ${ee})`),ie&&(e=`${ie}(${e})`),u.push(`${ne}: ${re} === null ? null : ${e}`)}else u.push(`${ne}: ${re}`)}return{bodyStmts:l,literal:`{ ${u.join(`, `)} }`,hasWork:d}}function pM({selection:e,isFirst:t,parseJson:n,parseJsonIfString:r,rootJsonMappers:i,arrayModeRoot:a}){let o=[],s=fM(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 fj(`rows`,l).bind({selection:e}),{body:`function jitRqbMapper (rows) {\n${l}\n}`})}function mM(e,t){let n=e[DA][t],r=ZA(n);return QA(n,r,q.column)?n:new qA([e,K[`.`],J.identifier(QA(n,r,q.aliased)?n.fieldAlias:t)])}var hM=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 gM(e,t,n=[]){if(t===MM)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,oj))return n.push(Y(e,t)),n;let r=Object.entries(t);if(!r.length)return;let i=new hM(n,K[`) and (`]);for(let[t,a]of r)if(a!==MM){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 (`]),gM(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 hM(n,t===`OR`?K[`) or (`]:K[`) and (`]);for(let t of r)o.open(),gM(e,t,n),o.close();o.finish(),i.close();continue}case`isNotNull`:case`isNull`:if(!a)continue;i.push(sM[t](e));continue;case`in`:i.push(sM.inArray(e,a));continue;case`notIn`:i.push(sM.notInArray(e,a));continue;default:i.push(sM[t](e,a));continue}}return i.finish()?n:void 0}function _M(e,t,n={},r={},i,a=0,o=[]){if(t===MM)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 hM(o,K[`) and (`]),l=!1,u=t=>{_M(e,t,n,r,i,a,o).hasRelationFilters&&(l=!0)};for(let[t,d]of s)if(d!==MM){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,sM):d.getSQL();if(t===MM)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 hM(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[DA],t)&&e[DA][t]){c.open(),gM(mM(e,t),d,o),c.close();continue}let s=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0;if(!s)throw new wA({message:`Unknown relational filter field: "${t}"`});i&&(AM(i,s.targetTable),AM(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 `]),jM(u,o),f&&(o.push(K[` inner join `]),jM(f,o),o.push(K[` on `]));let{filter:g}=TM(s,e,u,f,[],o);o.push(K[` where `]);let _=new hM(o,K[`) and (`]);if(_.pushChunks(g),!m){_.open();let e=_M(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 vM=new Set([`min`,`max`,`count`,`avg`,`first`]);function yM(e,t){if(typeof e!=`string`)throw new wA({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 wA({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 wA({message:`Invalid order "${t}": malformed value "${e}", expected "${r}" or "${r}(<aggregate>)"`});let i=n[1].slice(0,-1);if(!vM.has(i))throw new wA({message:`Invalid order "${t}": unknown aggregate "${i}" in "${e}", expected one of: ${[...vM].join(`, `)}`});return{direction:r,aggregate:i}}function bM(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[DA],l)&&e[DA][l]){let{direction:n,aggregate:r}=yM(u,t);if(!!r!=!!o?.isAggregated)throw new wA({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 hM(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 wA({message:`Unknown relational order field: "${t}"`});let f=d.relationType===`many`&&typeof u==`string`?yM(u,t):void 0,p=f?.aggregate===`count`?f.direction:void 0;if(typeof u!=`object`&&!p)throw new wA({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&&(AM(i,d.targetTable),AM(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 `]]:[];jM(h,_),g&&(_.push(K[` inner join `]),jM(g,_),_.push(K[` on `]));let{filter:ee}=TM(d,e,h,g,[],_),te=o?[...o.filters,ee]:[ee];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 hM(s,K[`) and (`]);for(let e=0;e<te.length;++e)t.pushChunks(te[e]);t.finish()||(s.length=e),s.push(K[`)`],p===`asc`?K[` asc`]:K[` desc`])}else bM(h,u,r[d.targetTableName]?.relations??{},r,i,a,{from:_,filters:te,isAggregated:!!o?.isAggregated||d.relationType===`many`,depth:m+1,path:t},s,c)}return s}function xM(e,t,n={},r={},i,a=`limit`,o=[]){let s=o.length;if(typeof t==`function`){let n=t(e,cM);if(!n)return;let r=ZA(n);if(QA(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),ZA(t)!==q.sql&&o.push(K[` asc`])}else QA(n,r,q.column)&&o.push(n,K[` asc`]);return o.length>s?o:void 0}return bM(e,t,n,r,i,a,void 0,o,s),o.length>s?o:void 0}function SM(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:sM.sql}):c;if(!t)continue;let l=t.getSQL(),u=n?_j(l):void 0,d=u&&(!r||!u.jsonSelectIdentifier)?new qA([n.apply(u,r?`castInJson`:`cast`,new qA([K[`(`],l,K[`)`]])),K[` as `],J.identifier(s)]):new qA([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 CM({_:{column:e,key:t}}){let n=ZA(e);return J.identifier(QA(e,n,q.column)?e.name:QA(e,n,q.aliased)?e.fieldAlias:t)}function wM(e,t,n,r,i,a){e.open(),t.push(n,K[`.`],CM(r),K[` = `],i,K[`.`],CM(a)),e.close()}function TM(e,t,n,r,i=[],a=[]){let o=e.isFilterReversed?t:n,s=t[NA],c=n[NA],l=r?.[NA],u=new hM(i,K[`) and (`]);if(e.through){let{sourceColumns:t,targetColumns:n,through:{source:r,target:d}}=e;u.open(),_M(o,e.where,{},{},void 0,0,i),u.close();for(let e=0;e<t.length;++e)wM(u,i,s,t[e],l,r[e]);u.finish();let f=new hM(a,K[`) and (`]);for(let e=0;e<n.length;++e)wM(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)wM(u,i,s,d[e],c,f[e]);return u.open(),_M(o,e.where,{},{},void 0,0,i),u.close(),u.finish(),{filter:i}}function EM(e,t,n,r,i,a,o=[]){let s=new hM(o,K[`) and (`]),c=!1;return t&&`where`in t&&(s.open(),c=_M(e,t.where,n,r,i,0,o).hasRelationFilters,s.close()),s.pushChunks(a),{sql:s.finish()?o:void 0,hasRelationFilters:c}}function DM(e,t,n,r,i,a,o){a?e.push(i.apply(a,o?`castInJson`:`cast`,new qA([t,K[`.`],J.identifier(n)]))):e.push(t,K[`.`],J.identifier(n)),e.push(K[` as `],J.identifier(r))}function OM(e,t,n,r,i,a,o,s){let c,l,u,d=ZA(t);if(QA(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 qA([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(QA(t,d,q.sql))c=_j(t),u=`SQL`,DM(s,e,n,n,o,c,r);else if(QA(t,d,q.aliased))c=_j(t),u=`SQL.Aliased`,DM(s,e,t.fieldAlias,n,o,c,r);else if(QA(t,d,q.subquery)){let i=Object.values(t._.selectedFields)[0],a=ZA(i);QA(i,a,q.column)?(c=i,l=i):QA(i,a,q.aliased)?(c=_j(i),l=i.sql.decoder):QA(i,a,q.sql)&&(c=_j(i),l=i.decoder),u=`Subquery`,DM(s,e,t._.alias,n,o,c,r)}else if(KA(t))c=_j(t),u=`SQLWrapper`,DM(s,e,n,n,o,c,r);else throw new wA({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 kM(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[`, `]),OM(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[`, `]),OM(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[`, `]),OM(e,t[l],l,r,n,i,a,o));return o.length>c}function AM(e,t){let n=ZA(t);if(e.usedTables!==void 0&&QA(t,n,q.table)){e.usedTables.add(t[jA]);return}if(!QA(t,n,q.subquery))return;let r=t._.alias,i=e.subqueries.get(r);if(i&&i._.sql!==t._.sql)throw new wA({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 jM(e,t=[]){if(!e[MA])return t.push(e),t;let n=e[EA];return n&&t.push(J.identifier(n),K[`.`]),t.push(J.identifier(e[kA]),K[` as `],e[NA]),t}var MM=Symbol.for(`drizzle:EmptyFilter`),NM=A.check(MT(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u,{message:`Expected a GitHub login`})).pipe(I(`OperatorLogin`)),PM=_i(`@usine/core/ActingMember`,{defaultValue:v}),FM=R.pipe(I(`AttentionRevision`)),IM=class extends B(`@usine/engine/AttentionKey`)({id:R,revision:FM}){};B(`@usine/engine/AttentionAcknowledgement`)({...IM.fields,dismissedBy:_E(NM),dismissedAt:gE});var LM=e=>{let t=j(e),n=new Set(Object.keys(e)),r=pT(A.check(jT(e=>!n.has(e))),nT.annotate({message:`Unexpected key`}));return t.rebuild(mT(t,[r]).ast)},RM=R.pipe(I(`EventId`)),zM=R.pipe(I(`DedupKey`)),BM=class extends B(`Event`)({id:RM,dedupKey:zM,payload:PE,receivedAt:hE}){},VM=class extends V(`CancelReason/OperatorCanceled`)(`OperatorCanceled`,{by:_E(NM).pipe(TT(C(null)),CT(C(v())))}){},HM=class extends V(`CancelReason/Superseded`)(`Superseded`,{by:RM}){},UM=class extends V(`CancelReason/Revoked`)(`Revoked`,{}){},WM=N([VM,HM,UM]),GM=class extends V(`RunState/Pending`)(`Pending`,{}){},KM=class extends V(`RunState/Waiting`)(`Waiting`,{}){},qM=class extends V(`RunState/Queued`)(`Queued`,{}){},JM=class extends V(`RunState/Running`)(`Running`,{}){},YM=class extends V(`RunState/Succeeded`)(`Succeeded`,{}){},XM=class extends V(`RunState/Failed`)(`Failed`,{}){},ZM=class extends V(`RunState/Canceled`)(`Canceled`,{reason:WM}){},QM=N([GM,KM,qM,JM]),$M=N([...QM.members,YM,XM,ZM]),eN=N([GM,KM,qM]),tN=N([GM,qM]),nN=Rw(QM),rN=Rw(eN),iN=Rw(tN),aN=e=>({canApprove:e._tag===`Waiting`,canRetry:e._tag===`Failed`,canResolveFailure:e._tag===`Failed`,canCancel:nN(e),canRunAgain:e._tag===`Succeeded`||e._tag===`Canceled`}),oN=()=>(...e)=>e,sN=oN()(`Pending`,`Waiting`,`Queued`,`Running`),cN=oN()(`Pending`,`Waiting`,`Queued`,`Running`,`Succeeded`,`Failed`,`Canceled`),lN=oN()(`Pending`,`Waiting`,`Queued`),uN=e=>new KM,dN=e=>new qM,fN=e=>new JM,pN=e=>new YM,mN=e=>new XM,hN=e=>new JM,gN=(e,t=v())=>new ZM({reason:new VM({by:t})}),_N=(e,t)=>new ZM({reason:new HM({by:t})}),vN=e=>new ZM({reason:new UM}),yN=R.pipe(I(`RunId`)),bN=class extends B(`Run`)({id:yN,eventId:RM,loop:uA,state:$M,openedAt:hE}){},xN=class extends V(`StepResult/Commit`)(`Commit`,{sha:Kk,summary:R}){},SN=class extends V(`StepResult/PullRequest`)(`PullRequest`,{number:L.check(BT(1)),url:tE}){},CN=P([`issue-comment`,`review`,`review-comment`]),wN=class extends V(`StepResult/Comment`)(`Comment`,{url:tE,kind:CN,at:yE(gE)}){},TN=N([xN,SN,wN]),EN=class extends B(`StepResult`)({message:R,facts:M(TN)}){},DN=R.pipe(I(`StepName`)),ON=class extends B(`Step`)({runId:yN,name:DN,result:z(EN)}){},kN=A.check(MT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case worker name`})).pipe(I(`WorkerName`)),AN=P([`local`,`exe.dev`,`ssh`,`cloudflare`]),jN=A.check(MT(/^[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`)),MN=L.check(BT(1)).pipe(I(`BotUserId`)),NN=class extends B(`BotAccount`)({login:jN,id:MN}){get noreplyEmail(){return`${String(this.id)}+${this.login}@users.noreply.github.com`}},PN=A.check(MT(/^(?:[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`)),FN=L.check(VT({minimum:1,maximum:65535})).pipe(I(`SshPort`)),IN=A.check(MT(/^(?:\/|~\/)[!-~]+$/u,{message:`Expected an absolute or ~/ key path without spaces or control characters`})).pipe(I(`SshIdentityFile`)),LN=A.check(MT(/^(?:\/[!-.0-~]+)+$/u,{message:`Expected an absolute directory without spaces, control characters, or a trailing /`})).pipe(I(`WorkerRoot`)),RN=A.check(MT(/^(?:[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`)),zN=L.check(VT({minimum:1,maximum:65535})).pipe(I(`GatewayAdminPort`)),BN=P([`anthropic`,`openai`]),VN=P([`api-key`,`subscription`]),HN=A.check(MT(/^[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`)),UN=A.check(MT(/^[0-9a-f]{64}$/u,{message:`Expected a container ID of 64 lowercase hex digits`})).pipe(I(`ContainerId`)),WN=NT.check(zT(0)).pipe(I(`ContainerCpus`)),GN=L.check(BT(256)).pipe(I(`ContainerMemoryMib`)),KN=L.check(BT(64)).pipe(I(`ContainerPids`)),qN=class extends B(`ContainerLimits`)({cpus:WN,memoryMib:GN,pids:KN}){},JN=[`cpus`,`memoryMib`,`pids`],YN=P([`lite`,`basic`,`standard-1`,`standard-2`,`standard-3`,`standard-4`]),XN=A.check(MT(/^[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`)),ZN=P([`anthropic`,`openai`]),QN=P([`hetzner`,`boat`]),$N=A.check(MT(/^[A-Za-z0-9_-]{1,64}$/u,{message:`Expected a provider machine ID`})).pipe(I(`MachineId`)),eP=A.check(MT(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner server type, such as cx33`})).pipe(I(`HetznerServerType`)),tP=A.check(MT(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/u,{message:`Expected a Hetzner location, such as nbg1`})).pipe(I(`HetznerLocation`)),nP=A.check(MT(/^[!-~](?:[ -~]{0,253}[!-~])?$/u,{message:`Expected a Hetzner image ID, snapshot description, or image name`})).pipe(I(`HetznerImage`)),rP=A.check(MT(/^[!-~](?:[ -~]{0,126}[!-~])?$/u,{message:`Expected a Hetzner resource name without control characters`})).pipe(I(`HetznerResourceName`)),iP=/^(?:[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,aP=pT(A,A.check(MT(/^(?:[a-z0-9A-Z](?:[-_.a-z0-9A-Z]{0,61}[a-z0-9A-Z])?)?$/u,{message:`Expected a Hetzner label value`}))).check(jT(e=>{let t=Object.keys(e),n=t.find(e=>!iP.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}"`})),oP=A.check(MT(/^[a-z_][a-z0-9_-]{0,31}$/u,{message:`Expected a Unix user name`})).pipe(I(`SshUser`)),sP=P([`small`,`default`,`large`,`xlarge`]),cP=A.check(MT(/^[a-z0-9][a-z0-9-]{0,62}$/u),jT(e=>![`latest`,`tree`,`pull`,`rm`,`save`,`current`,`self`,`new`].includes(e),{message:`Expected a non-reserved Boat snapshot name`})).pipe(I(`BoatSnapshotName`)),lP=A.check(MT(/^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`)),uP=L.check(VT({minimum:1,maximum:2147483})).pipe(I(`ProvisionerSeconds`)),dP=e=>uP.pipe(TT(C(e)),CT(C(uP.make(e)))),fP=class extends B(`ProvisionerTimings`)(j({sshWait:dP(600),creationBackoffMin:dP(30),creationBackoffMax:dP(600),machineCheckInterval:dP(86400)}).check(jT(e=>e.creationBackoffMin<=e.creationBackoffMax||`Creation backoff minimum must not exceed its maximum`))){},pP=R.pipe(I(`AgentSessionId`)),mP=L.check(BT(0)).pipe(I(`TokenCount`)),hP=L.check(BT(1)),gP=hP.pipe(I(`ChildSessionBudget`)),_P=hP.pipe(I(`ChildSessionCount`)),vP=N([class extends V(`Agent/ParentSession`)(`ParentSession`,{id:pP,agent:aA,brain:iA}){},class extends V(`Agent/ChildSession`)(`ChildSession`,{id:pP,parentId:pP,agent:aA,brain:iA,gatewayCredential:yE(VN).pipe(CT(C(v())))}){}]),yP=R.pipe(I(`HarnessSessionId`)),bP=class extends B(`Agent/HarnessSession`)({id:yP,cwd:R,home:yE(R).pipe(CT(C(v())))}){},xP=class extends V(`Agent/SessionStarted`)(`SessionStarted`,{session:vP,harnessSession:yE(bP).pipe(CT(C(v())))}){},SP=class extends V(`Agent/TextOutput`)(`TextOutput`,{session:vP,text:R}){},CP=class extends V(`Agent/ToolStarted`)(`ToolStarted`,{session:vP,callId:R,tool:R,input:PE}){},wP=class extends V(`Agent/ToolFinished`)(`ToolFinished`,{session:vP,callId:R,tool:R,output:PE,isError:sT}){},TP=class extends V(`Agent/SessionFinished`)(`SessionFinished`,{session:vP}){},EP=class extends V(`Agent/SessionIdle`)(`SessionIdle`,{session:vP}){},DP=class extends V(`Agent/SessionResumed`)(`SessionResumed`,{session:vP}){},OP=NT.check(BT(0)).pipe(I(`UsdAmount`)),kP=L.check(BT(0)),AP=class extends B(`Agent/TokenBreakdown`)({input:kP,cachedInput:kP,cacheWrite:kP,output:kP}){},jP=class extends V(`Agent/SessionTokensUpdated`)(`SessionTokensUpdated`,{session:vP,totalTokens:mP,costUsd:yE(OP).pipe(CT(C(v()))),breakdown:yE(AP).pipe(CT(C(v())))}){},MP=P([`apiKeys`,`claudePlan`,`chatgptPlan`]),NP=(e,t)=>{switch(e.harness){case`claude`:return Pr(t,`api-key`)?`apiKeys`:`claudePlan`;case`codex`:return Pr(t,`api-key`)?`apiKeys`:`chatgptPlan`;case`pi`:return e.model.startsWith(`openai-codex/`)?`chatgptPlan`:`apiKeys`}},PP=e=>wk(e,{ParentSession:({brain:e})=>NP(e,v()),ChildSession:({brain:e,gatewayCredential:t})=>NP(e,t)}),FP=class extends B(`Agent/RateLimitWindow`)({usedPercent:oT,windowDurationMinutes:_E(oT),resetsAt:_E(gE)}){},IP=class extends B(`Agent/RateLimitsSnapshot`)({limitId:_E(A),limitName:_E(A),primary:_E(FP),secondary:_E(FP)}){},LP=R.pipe(I(`PoolLogin`)),RP=class extends V(`Agent/PoolRateLimitsUpdated`)(`PoolRateLimitsUpdated`,{session:vP,pool:MP,login:yE(LP).pipe(CT(C(v()))),rateLimits:IP}){},zP=hP.pipe(I(`ProviderRetries`)),BP=N([xP,SP,CP,wP,RP,TP,EP,DP,jP,class extends V(`Agent/ProviderRetrying`)(`ProviderRetrying`,{session:vP,message:R,retries:zP}){},class extends V(`Agent/ProviderRecovered`)(`ProviderRecovered`,{session:vP,retries:zP}){}]),VP=class extends jE(`AttemptFailure/GitHubPushFailure`)(`GitHubPushFailure`,{repository:H,ref:R,message:A}){},HP=class extends jE(`AttemptFailure/InfraFailure`)(`InfraFailure`,{message:A,cause:QT()}){},UP=class extends jE(`AttemptFailure/DefectFailure`)(`DefectFailure`,{message:A,cause:QT()}){},WP=class extends jE(`AttemptFailure/ProviderCapacityFailure`)(`ProviderCapacityFailure`,{message:R}){},GP=class extends jE(`AttemptFailure/AgentFailure`)(`AgentFailure`,{message:A}){},KP=class extends jE(`AttemptFailure/BlockedFailure`)(`BlockedFailure`,{message:R}){},qP=class extends jE(`AttemptFailure/QuestionFailure`)(`QuestionFailure`,{question:R}){},JP=P([`wall-clock`,`tokens`]),YP=N([VP,HP,WP,UP,GP,KP,qP,class extends jE(`AttemptFailure/RunawayFailure`)(`RunawayFailure`,{ceiling:JP}){},class extends jE(`AttemptFailure/ChildSessionBudgetFailure`)(`ChildSessionBudgetFailure`,{maxChildren:gP,attemptedChildren:_P}){}]),XP=Rw(N([HP,WP])),ZP=class extends V(`AttemptOutcome/Succeeded`)(`Succeeded`,{}){},QP=class extends V(`AttemptOutcome/Failed`)(`Failed`,{failure:YP}){},$P=class extends V(`AttemptOutcome/Canceled`)(`Canceled`,{}){},eF=N([ZP,QP,$P]),tF=R.pipe(I(`SalvageRef`)),nF=(e,t)=>tF.make(`usine/salvage/${qk(e)}/${t}`),rF=class extends V(`AttemptSalvage/Pushed`)(`Pushed`,{ref:tF,commit:Kk}){},iF=N([rF,class extends V(`AttemptSalvage/PartlyPushed`)(`PartlyPushed`,{ref:tF,commit:Kk,path:R,message:A}){},class extends V(`AttemptSalvage/Retained`)(`Retained`,{path:R,commit:_E(Kk),message:A,pushFailure:_E(VP).pipe(TT(C(null)),CT(C(v())))}){},class extends V(`AttemptSalvage/Rejected`)(`Rejected`,{path:R,commit:Kk,message:A}){}]),aF=class extends V(`AttemptStart/Event`)(`Event`,{}){},oF=class extends V(`AttemptStart/Retry`)(`OperatorRetry`,{operator:_E(NM)}){},sF=class extends V(`AttemptStart/EditAndRetry`)(`EditAndRetry`,{operator:_E(NM)}){},cF=class extends V(`AttemptStart/InfraRetry`)(`InfraRetry`,{}){},lF=class extends V(`AttemptStart/ProviderRetry`)(`ProviderRetry`,{}){},uF=class extends V(`AttemptStart/AfterRestart`)(`AfterRestart`,{}){},dF=N([oF,sF]),fF=N([aF,oF,sF,cF,lF,uF]),pF=R.pipe(I(`AttemptId`)),mF=L.check(BT(1)).pipe(I(`AttemptNumber`)),hF=mF.make(3),gF=A.check(MT(/\S/u,{message:`Expected non-blank task text`})).pipe(I(`AttemptTask`)),_F=P([`cancel`,`failed`,`startup`]),vF=class extends B(`AttemptContext`)({task:gF,agent:sA,parentModel:_E(tA)}){},yF=class extends B(`FailureResolution`)(LM({resolvedAt:gE,operator:_E(NM)})){},bF=L.check(BT(1)),xF=class extends B(`OutOfMemoryKills`)({kills:bF,memoryMib:GN}){},SF=class extends B(`ContainerOutOfMemoryKills`)({container:UN,kills:bF,memoryMib:GN}){},CF=e=>new xF({kills:e.reduce((e,{kills:t})=>e+t,0),memoryMib:na(e).memoryMib}),wF=class extends B(`Attempt`)({id:pF,runId:yN,stepName:DN,worker:kN,number:mF,brain:iA,task:gF,agent:aA,operatorIntervened:sT,parentModel:_E(tA),startedAt:hE,outcome:z(eF),endedAt:z(hE),salvage:z(iF),failureResolution:z(yF).pipe(CT(C(v()))),start:z(fF).pipe(CT(C(v()))),reattachedAt:z(hE).pipe(CT(C(v()))),comments:M(wN).pipe(CT(C([]))),outOfMemory:z(xF).pipe(CT(C(v())))}){},TF=class extends B(`AttemptWindow`)({attemptId:pF,startedAt:hE,endedAt:z(hE)}){},EF=e=>x(e.outcome)&&b(e.endedAt)?v():y(new TF({attemptId:e.id,startedAt:e.startedAt,endedAt:e.endedAt})),DF=e=>{let t=H_(e.startedAt);return t-t%1e3},OF=(e,t)=>_r(e.endedAt,{onNone:()=>!0,onSome:e=>t<=H_(e)}),kF=(e,t)=>{let n=H_(t);return DF(e)<=n&&OF(e,n)},AF=(e,t)=>OF(e,DF(t))&&OF(t,DF(e)),jF=class extends B(`AttemptWindows`)({own:z(TF),overlapping:M(TF)}){},MF=e=>XP(e.failure)&&e.number<e.maxAutoAttempts,NF=class extends B(`ProviderRetry`)(LM({nextAttempt:mF.check(BT(2)),retryAt:gE,message:R})){},PF=(e,t)=>{if(e._tag!==`Running`)return v();let n=t.at(-1);if(n===void 0||n.number>=hF||b(n.outcome)||b(n.endedAt))return v();let r=n.outcome.value;return r._tag!==`Failed`||r.failure._tag!==`ProviderCapacityFailure`?v():y(new NF({nextAttempt:mF.make(n.number+1),retryAt:U_(n.endedAt.value,{minutes:n.number===1?2:5}),message:r.failure.message}))},FF=L.check(BT(1)).pipe(I(`AttemptChannelSequence`)),IF=[`inbound`,`outbound`],LF=P(IF),RF=class extends B(`AttemptChannel/RunSpec`)({attemptId:pF,repository:H,revision:Gk,baseCommit:Kk,payload:PE,task:gF,agent:sA,parentModel:_E(tA),maxChildren:gP,parentEffort:rA,resume:_E(rF),conflictingSalvage:_E(rF).pipe(TT(C(null)),CT(C(v()))),preparedAt:_E(gE).pipe(TT(C(null))),botLogin:_E(jN).pipe(TT(C(null)))}){},zF=class extends V(`AttemptChannel/Started`)(`Started`,{parentModel:tA,conflictingSalvage:_E(rF).pipe(TT(C(null)),CT(C(v())))}){},BF=class extends V(`AttemptChannel/SessionEvent`)(`SessionEvent`,{event:BP}){},VF=class extends V(`AttemptChannel/Final`)(`Final`,{result:EN}){},HF=class extends V(`AttemptChannel/Failed`)(`Failed`,{failure:YP}){},UF=class extends V(`AttemptChannel/Interrupted`)(`Interrupted`,{}){},WF=class extends V(`AttemptChannel/Steer`)(`Steer`,{message:R}){},GF=class extends V(`AttemptChannel/Interrupt`)(`Interrupt`,{}){},KF=class extends V(`AttemptChannel/Cancel`)(`Cancel`,{}){},qF=class extends V(`AttemptChannel/OperatorMessage`)(`OperatorMessage`,{message:R}){},JF=class extends V(`AttemptChannel/Release`)(`Release`,{}){},YF=N([WF,GF,qF,JF]),XF=N([YF,KF]),ZF=class extends V(`AttemptChannel/ParentTarget`)(`Parent`,{}){},QF=class extends V(`AttemptChannel/ChildTarget`)(`Child`,{sessionId:pP}){},$F=N([ZF,QF]),eI=class extends B(`AttemptChannel/Intervention`)({operator:R,target:$F,action:YF}){},tI=class extends B(`AttemptChannel/InterventionState`)({held:sT,paused:sT,queued:sT.pipe(TT(C(!1)),CT(C(!1)))}){},nI=class extends V(`AttemptChannel/InterventionApplied`)(`InterventionApplied`,{inputSequence:FF,intervention:eI,state:tI}){},rI=class extends V(`AttemptChannel/InterventionRejected`)(`InterventionRejected`,{inputSequence:FF,intervention:eI,message:R}){},iI=class extends V(`AttemptChannel/WorkerUnresponsive`)(`WorkerUnresponsive`,{worker:kN,lastAnsweredAt:gE,reason:R,unansweredProbes:L.check(BT(1)).pipe(TT(C(1)),CT(C(1)))}){},aI=class extends V(`AttemptChannel/WorkerResponsive`)(`WorkerResponsive`,{worker:kN,lastAnsweredAt:gE,recovered:sT.pipe(TT(C(!0)),CT(C(!0)))}){};N([iI,aI]);var oI=N([zF,BF,VF,HF,UF,nI,rI,iI,aI]),sI={version:tT(7),attemptId:pF,sequence:FF,sentAt:gE},cI=class extends V(`AttemptChannel/OutboundEnvelope`)(`OutboundEnvelope`,{...sI,payload:oI}){},lI=class extends V(`AttemptChannel/InboundEnvelope`)(`InboundEnvelope`,{...sI,target:$F.pipe(TT(C({_tag:`Parent`}))),operator:R,payload:XF}){},uI=N([cI,lI]),dI=R.pipe(I(`ItemKey`)),fI=L.check(BT(1)).pipe(I(`ItemNumber`)),pI=L.check(BT(1)).pipe(I(`CycleLimit`)),mI=L.check(BT(0)).pipe(I(`CycleGeneration`)),hI=pI.make(3),gI=L.check(BT(0)).pipe(I(`CycleCount`)),_I=class extends B(`LoopCycleCount`)(LM({loop:uA,admitted:gI,completed:gI}).check(jT(({admitted:e,completed:t})=>t<=e,{message:`Completed runs can't exceed admitted runs`}))){},vI=RM.pipe(I(`CycleBudgetAskId`)),yI=class extends B(`CycleBudgetAsk`)(LM({id:vI,itemKey:dI,repository:H,loop:uA,limit:pI,counts:_T(_I)}).check(jT(({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 gI.make(Math.max(...this.counts.map(({completed:e})=>e)))}},bI=[`ui`],xI=P(bI),SI=class extends B(`ApprovalSource`)(LM({channel:xI,approver:_E(NM)})){},CI=class extends B(`RunApproval`)({approvedAt:hE,source:z(SI)}){},wI=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 fee(e,this)}},fee=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[TA],...r,n[0].table[TA],...i];return e??`${a.join(`_`)}_fk`}isNameExplicit(){return!!this.reference().name}};function pee(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 wI(t)}var TI=class extends Nj{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 wI(()=>{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))}},EI=class extends BA{static[U]=`SQLiteColumn`;table;constructor(e,t){super(e,t),this.table=e}},mee={},DI={cast:void 0,castInJson:void 0,castParam:void 0,normalize:void 0,normalizeInJson:void 0,normalizeParam:void 0},OI={cast:`cast`,castArray:`cast`,castInJson:`castInJson`,castArrayInJson:`castInJson`,castParam:`castParam`,castArrayParam:`castParam`,normalize:`normalize`,normalizeArray:`normalize`,normalizeInJson:`normalizeInJson`,normalizeArrayInJson:`normalizeInJson`,normalizeParam:`normalizeParam`,normalizeParamArray:`normalizeParam`},hee=class{resolveTypes;codecs;static[U]=`CodecsCollection`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e,t=mee){this.resolveTypes=e,this.codecs=t}itemCodecsCache=new Map;arrayCodecsCache=new Map;codecsOf(e,t){let n=t??e.codec;if(!n)return DI;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}:DI,i.set(n,a)}return a}get(e,t,n){return this.codecsOf(e,n)[OI[t]]}apply(e,t,n,r){let i=OI[t],a=this.codecsOf(e,r)[i];return a?i===`castParam`?a(n,e,e.dimensions):a(n,e.dimensions):n}},gee={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 kI(e){return gee[e]??e}var AI=typeof Buffer>`u`?new TextEncoder:void 0,jI=AI?e=>AI.encode(e):e=>Buffer.from(e),_ee={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 MI(e,t){return _ee[e]?.[t]}var NI=class extends TI{static[U]=`SQLiteBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteBigInt`)}build(e){return new PI(e,this.config)}},PI=class extends EI{static[U]=`SQLiteBigInt`;codec=`blob:bigint`;getSQLType(){return`blob`}mapToDriverValue=e=>jI(e.toString())},FI=class extends TI{static[U]=`SQLiteBlobJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteBlobJson`)}build(e){return new II(e,this.config)}},II=class extends EI{static[U]=`SQLiteBlobJson`;codec=`blob:json`;getSQLType(){return`blob`}mapToDriverValue=e=>jI(JSON.stringify(e))},LI=class extends TI{static[U]=`SQLiteBlobBufferBuilder`;constructor(e){super(e,`object buffer`,`SQLiteBlobBuffer`)}build(e){return new RI(e,this.config)}},RI=class extends EI{static[U]=`SQLiteBlobBuffer`;codec=`blob`;getSQLType(){return`blob`}};function zI(e,t){let{name:n,config:r}=xj(e,t);return r?.mode===`bigint`?new NI(n):r?.mode===`buffer`?new LI(n):new FI(n)}var BI=class extends TI{static[U]=`SQLiteCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`SQLiteCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new VI(e,this.config)}},VI=class extends EI{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`?kI(n):void 0}getSQLType(){return this.sqlName}};function HI(e){return(t,n)=>{let{name:r,config:i}=xj(t,n);return new BI(r,i,e)}}var UI=class extends TI{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()}},WI=class extends EI{static[U]=`SQLiteBaseInteger`;autoIncrement=this.config.autoIncrement;getSQLType(){return`integer`}},GI=class extends UI{static[U]=`SQLiteIntegerBuilder`;constructor(e){super(e,`number int53`,`SQLiteInteger`)}build(e){return new KI(e,this.config)}},KI=class extends WI{static[U]=`SQLiteInteger`;codec=`integer`},qI=class extends UI{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 JI(e,this.config)}},JI=class extends WI{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}},YI=class extends UI{static[U]=`SQLiteBooleanBuilder`;constructor(e,t){super(e,`boolean`,`SQLiteBoolean`),this.config.mode=t}build(e){return new XI(e,this.config)}},XI=class extends WI{static[U]=`SQLiteBoolean`;codec=`integer:boolean`;mode=this.config.mode;mapToDriverValue=e=>+!!e};function ZI(e,t){let{name:n,config:r}=xj(e,t);return r?.mode===`timestamp`||r?.mode===`timestamp_ms`?new qI(n,r.mode):r?.mode===`boolean`?new YI(n,r.mode):new GI(n)}var QI=class extends TI{static[U]=`SQLiteNumericBuilder`;constructor(e){super(e,`string numeric`,`SQLiteNumeric`)}build(e){return new $I(e,this.config)}},$I=class extends EI{static[U]=`SQLiteNumeric`;codec=`numeric`;getSQLType(){return`numeric`}},eL=class extends TI{static[U]=`SQLiteNumericNumberBuilder`;constructor(e){super(e,`number`,`SQLiteNumericNumber`)}build(e){return new tL(e,this.config)}},tL=class extends EI{static[U]=`SQLiteNumericNumber`;codec=`numeric:number`;mapToDriverValue=String;getSQLType(){return`numeric`}},nL=class extends TI{static[U]=`SQLiteNumericBigIntBuilder`;constructor(e){super(e,`bigint int64`,`SQLiteNumericBigInt`)}build(e){return new rL(e,this.config)}},rL=class extends EI{static[U]=`SQLiteNumericBigInt`;codec=`numeric:bigint`;mapToDriverValue=String;getSQLType(){return`numeric`}};function iL(e,t){let{name:n,config:r}=xj(e,t),i=r?.mode;return i===`number`?new eL(n):i===`bigint`?new nL(n):new QI(n)}var aL=class extends TI{static[U]=`SQLiteRealBuilder`;constructor(e){super(e,`number double`,`SQLiteReal`)}build(e){return new oL(e,this.config)}},oL=class extends EI{static[U]=`SQLiteReal`;codec=`real`;getSQLType(){return`real`}};function sL(e){return new aL(e??``)}var cL=class extends TI{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 lL(e,this.config)}},lL=class extends EI{static[U]=`SQLiteText`;codec=`text`;enumValues=this.config.enumValues;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:``}`}},uL=class extends TI{static[U]=`SQLiteTextJsonBuilder`;constructor(e){super(e,`object json`,`SQLiteTextJson`)}build(e){return new dL(e,this.config)}},dL=class extends EI{static[U]=`SQLiteTextJson`;codec=`text:json`;getSQLType(){return`text`}mapToDriverValue=e=>JSON.stringify(e)};function X(e,t={}){let{name:n,config:r}=xj(e,t);return r.mode===`json`?new uL(n):new cL(n,r)}function fL(){return{blob:zI,customType:HI,integer:ZI,numeric:iL,real:sL,text:X}}function pL(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 mL(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 hL(e){return e===`snake_case`?pL:e===`camelCase`?mL:e=>e}var gL=Symbol.for(`drizzle:SQLiteInlineForeignKeys`),_L=class extends IA{static[U]=`SQLiteTable`;static Symbol=Object.assign({},IA.Symbol,{InlineForeignKeys:gL});[IA.Symbol.Columns];[gL]=[];[IA.Symbol.ExtraConfigBuilder]=void 0};function vL(e,t,n,r,i,a=e){let o=hL(i),s=new _L(e,r,a),c=typeof t==`function`?t(fL()):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[gL].push(...n.buildForeignKeys(r,s)),[e,r]})),u=Object.assign(s,l);return u[IA.Symbol.Columns]=l,u[IA.Symbol.ExtraConfigColumns]=l,n&&(u[_L.Symbol.ExtraConfigBuilder]=n),u}function yL(e){return(t,n,r)=>vL(t,n,r,void 0,e)}var bL=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 xL(e,this)}},xL=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 SL(e,t){return new bL(e,t)}var CL=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 wL(this.name,e,this.unique)}},wL=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 TL(this.config,e)}},TL=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 EL(e){return new CL(e,!1)}function DL(e){return new CL(e,!0)}function OL(...e){return e[0].columns?new kL(e[0].columns,e[0].name):new kL(e)}var kL=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 AL(e,this.columns,this.name)}},AL=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[_L.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}},jL=Sj(e=>`"${e.replace(/"/g,`""`)}"`),ML={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 `)},NL=class{static[U]=`SQLiteDialect`;static[Symbol.hasInstance](e){return W(e,this)}codecs;mapperGenerators;constructor(e){this.codecs=new hee(kI,e?.codecs),this.mapperGenerators=e?.useJitMappers?{rows:mj,relationalRows:pM}:{rows:hj,relationalRows:dM}}escapeName(e){return jL(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 qA(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[IA.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,qA)?e:J.param(e,s)}a[e]=e<i-1?J`${J.identifier(s.name)} = ${c}, `:J`${J.identifier(s.name)} = ${c}`}return new qA(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 qA([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=ZA(r),s=r?QA(r,o,q.sql)||QA(r,o,q.subquery)?void 0:r[IA.Symbol.IsAlias]||r[IA.Symbol.Schema]===void 0?r[IA.Symbol.Name]:`${r[IA.Symbol.Schema]}.${r[IA.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(Mj(o).name):J.identifier(o.name):o.isAlias?Mj(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,BA)){let{table:e}=i;if((e[IA.Symbol.IsAlias]||e[IA.Symbol.Schema]===void 0?e[IA.Symbol.Name]:`${e[IA.Symbol.Schema]}.${e[IA.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 qA(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,BA)){let{table:e}=i;if((e[IA.Symbol.IsAlias]||e[IA.Symbol.Schema]===void 0?e[IA.Symbol.Name]:`${e[IA.Symbol.Schema]}.${e[IA.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 qA(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 qA(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,_L)?t.push(J`${new G(r.joinType)} join ${i[IA.Symbol.IsAlias]?Aj(i):i}${a}`):t.push(J`${new G(r.joinType)} join ${i}${a}`),n<e.length-1&&t.push(K[` `])}return new qA(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,IA)&&e[IA.Symbol.IsAlias])return Aj(e);if(W(e,UA)&&e[VA].isAlias){let t=J`${J.identifier(e[VA].originalName)}`;return e[VA].schema&&(t=J`${J.identifier(e[VA].schema)}.${t}`),J`${t} ${J.identifier(e[VA].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??gj(t,void 0,this.codecs),h=ZA(a),g=QA(a,h,q.subquery)?a._.alias:QA(a,h,q.view)?a[VA].name:QA(a,h,q.sql)?void 0:LA(a);for(let e of m)if(W(e.field,BA)&&LA(e.field.table)!==g&&!(e=>o?.some(({alias:t})=>t===(e[IA.Symbol.IsAlias]?LA(e):e[IA.Symbol.BaseName])))(e.field.table)){let t=LA(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,ee=this.buildWithCTE(e),te=d?J` distinct`:void 0,ne=this.buildSelection(m,{isSingleTable:_,table:a,ignoreCastCodecs:!p||f.length>0}),re=this.buildFromTable(a),ie=this.buildJoins(o),ae=r?J` where ${r}`:void 0,oe=i?J` having ${i}`:void 0,se=[];if(c)for(let[e,t]of c.entries())se.push(t),e<c.length-1&&se.push(K[`, `]);let ce=se.length>0?J` group by ${J.join(se)}`:void 0,le=this.buildOrderBy(s),ue=this.buildLimit(l),de=u?J` offset ${u}`:void 0,fe=J`${ee}select${te} ${ne} from ${re}${ie}${ae}${ce}${oe}${le}${ue}${de}`;return f.length>0?this.buildSetOperations(fe,m,p,f):fe}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=gj(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?MI(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 qA.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 qA.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,EI)?e.push(J.identifier(t.name)):W(t,qA)?e.push(J`${sj(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[IA.Symbol.Columns],l=o?o.map(e=>[e,c[e]]):Object.entries(c),u=a&&!W(t,qA)?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 qA(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 ij(n,u.map(([,e])=>e))]}let h=this.buildWithCTE(i),g=new qA(m),_=r?J` returning ${this.buildSelection(r,{isSingleTable:!0,ignoreCastCodecs:!s,table:e})}`:void 0,ee=n?.length?J.join(n):void 0;return J`${h}insert into ${e} ${p} ${g}${ee}${_}`}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 qA(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??``,ee=c??0,te=d??{subqueries:new Map,usedTables:f};ee||(AM(te,t),t=kj(t,`d${ee}`));let ne=t[NA],re=h?1:g?.limit,ie=g?.offset,{sql:ae}=EM(t,g,n.relations,e,te,i),oe=g?.orderBy?xM(t,g.orderBy,n.relations,e,te):void 0,se=g?g.with:void 0,ce=[];if(se)for(let e of Object.keys(se))se[e]&&ce.push(e);let le=ee?-1:p.length;ee||p.push(void 0),p.push(K[`select `]);let ue=+!!kM(ne,n.table[DA],m,!!o,n.name,this.codecs,p,g?.columns);if(g?.extras){let e=p.length;ue&&p.push(K[`, `]);let n=SM(t,g.extras,this.codecs,!!o,p);m.push(...n.selection),n.sql?++ue:p.length=e}if(!ue&&!ce.length)throw new wA({message:`No fields selected for table "${n.name}"${_?` ("${_}")`:``}`});for(let r of ce){let i=se[r],a=n.relations[r];if(!a)throw new wA({message:`Unknown relation "${n.name}" -> "${r}"`});let s=a.relationType===`one`;AM(te,a.targetTable),AM(te,a.throughTable);let c=kj(a.targetTable,`d${ee+1}`),l=a.throughTable?kj(a.throughTable,`tr${ee}`):void 0,{filter:d,joinCondition:f}=TM(a,t,c,l);ue++&&p.push(K[`, `]);let h=p.length;p.push(void 0,ML.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:ee+1,withSubqueries:te,through:l?{table:l,condition:f}:void 0,jsonb:u},p);p.push(ML.relationClose,J.identifier(r));let ne=[K[`(select `],o?u:ML.json,s?ML.object:ML.groupArray];for(let e=0;e<g.length;++e){let t=g[e];e&&ne.push(K[`, `]),ne.push(new G(this.escapeString(t.key)),K[`, `]),t.selection?ne.push(u,K[`(`],J.identifier(t.key),K[`)`]):ne.push(J.identifier(t.key))}ne.push(s?K[`)`]:ML.groupArrayClose),p[h]=new qA(ne),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 `]),jM(t,p),l&&(p.push(K[` inner join `]),jM(l.table,p),p.push(K[` on `],...l.condition)),ae&&p.push(K[` where `],...ae),oe&&p.push(K[` order by `],...oe),re!==void 0&&p.push(K[` limit `],re),ie!==void 0&&p.push(K[` offset `],ie),le!==-1&&(p[le]=this.buildWithCTE([...te.subqueries.values()])),m}},PL=class extends UA{static[U]=`SQLiteViewBase`},FL=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===VA)return{...t[VA],selectedFields:new Proxy(t[VA].selectedFields,this)};if(typeof n==`symbol`)return t[n];let i=ZA(t),a=(QA(t,i,q.subquery)?t._.selectedFields:QA(t,i,q.view)?t[VA].selectedFields:t)[n];if(a===void 0&&n===`getSQL`){let e=t[n];return typeof e==`function`?e.bind(r??t):e}let o=ZA(a);if(QA(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(QA(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 QA(a,o,q.column)?this.config.alias?new Proxy(a,new Cj(new Proxy(a.table,new Tj(this.config.alias,this.config.replaceOriginalName??!1,!0)),!0)):a:typeof a!=`object`||!a?a:new Proxy(a,new e(this.config))}};function IL(e){if(W(e,IA))return[e[jA]];let t=new Set;return cj(e.queryChunks,t),[...t]}var LL=class{static[U]=`TypedQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}getSelectedFields(){return this._.selectedFields}},RL=class{builder;static[U]=`SQLiteSelectBuilder`;static[Symbol.hasInstance](e){return W(e,this)}fields;session;dialect;withList;distinct;constructor(e,t=zL){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,WA)?Object.fromEntries(Object.keys(e._.selectedFields).map(t=>[t,e[t]])):W(e,PL)?e[VA].selectedFields:W(e,qA)?{}:yj(e),new this.builder({table:e,fields:n,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList??[],distinct:this.distinct})}},zL=class extends LL{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=bj(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}getUsedTables(e=this.getSQL()){return IL(e)}createJoin(e){return(t,n)=>{let r=this.tableName,i=bj(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,qA))){let e=W(t,WA)?t._.selectedFields:W(t,UA)?t[VA].selectedFields:t[IA.Symbol.Columns];this.config.fields[i]=e}if(typeof n==`function`&&(n=n(new Proxy(this.config.fields,new FL({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(VL()):n;if(!vj(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 FL({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new FL({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 FL({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 FL({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??=gj(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 WA(this.getSQL(),this.config.fields,e),new FL({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new FL({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}};function BL(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!vj(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 VL=()=>({union:HL,unionAll:UL,intersect:WL,except:GL}),HL=BL(`union`,!1),UL=BL(`union`,!0),WL=BL(`intersect`,!1),GL=BL(`except`,!1),KL=class{static[U]=`SQLiteQueryBuilder`;static[Symbol.hasInstance](e){return W(e,this)}dialect;dialectConfig;constructor(e){this.dialect=W(e,NL)?e:void 0,this.dialectConfig=W(e,NL)?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 GA(i,t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new FL({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}}};with(...e){let t=this;function n(n){return new RL({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(n){return new RL({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:r}}select(e){return new RL({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new RL({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||=new NL(this.dialectConfig),this.dialect}},qL=class{name;static[U]=`SQLiteViewBuilderCore`;static[Symbol.hasInstance](e){return W(e,this)}constructor(e){this.name=e}config={}},JL=class extends qL{static[U]=`SQLiteViewBuilder`;as(e){typeof e==`function`&&(e=e(new KL));let t=new FL({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=e.getSelectedFields();return new Proxy(new XL({config:{name:this.name,schema:void 0,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},YL=class extends qL{static[U]=`SQLiteManualViewBuilder`;columns;constructor(e,t,n){super(e),this.columns=yj(vL(e,t,void 0,void 0,n))}existing(){return new Proxy(new XL({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new FL({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new XL({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new FL({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},XL=class extends PL{static[U]=`SQLiteView`;constructor({config:e}){super(e)}};function ZL(e){return((t,n)=>n?new YL(t,n,e):new JL(t))}function QL(e,t){return new Proxy(e,new Tj(t,!1))}var $L={table:yL(`snake_case`),view:ZL(`snake_case`)},eR=class extends B(`CycleBudgetReset`)({itemKey:dI,repository:H,generation:mI}){},tR=class extends jE(`CycleBudgetResetRejectedError`)(`CycleBudgetResetRejectedError`,{askId:vI}){},nR=[`ItemClosed`];P(nR);var rR=j({...eR.fields,ask:_E(yI),resetPending:sT}),iR=`~effect/encoding/Ndjson/NdjsonError`,aR=new TextEncoder,oR=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),sR=class extends Co(`NdjsonError`){[iR]=iR;get message(){return this.kind}},cR=e=>me(e,iR),lR=()=>FD((e,t)=>C(T(e,e=>{try{return C(pa(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 zh(new sR({kind:`Pack`,cause:e}))}}))),uR=()=>KD(lR(),ma(e=>aR.encode(e))),dR=(e,t,n)=>{let r,i,a=(e,t)=>(r=t,Yi(e)?C(e):t===void 0?void 0:zh(t)),o=Ph(()=>r===void 0?i===void 0?Zm(e,{onSuccess:e=>{let n=[];return a(n,t(e,n))??o},onFailure:Bh,onDone:e=>{i={leftover:e};let t=[];return a(t,n(t))??rf(e)}}):rf(i.leftover):zh(r));return o},fR=(e,t,n,r)=>{if(!(n&&e.length===0))try{t.push(JSON.parse(e))}catch(e){return new sR({kind:`Unpack`,reason:`InvalidJson`,unterminated:r,cause:e})}},pR=10,mR=13,hR=new Uint8Array,gR=e=>FD((t,n)=>Fh(()=>{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 sR({kind:`Unpack`,reason:`InvalidUtf8`,unterminated:r,cause:e})}let o=i!==oR;if(i=oR,!(o&&r&&a.length===0))return fR(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===pR||a===mR){if(a===pR&&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===mR}else if(s=!1,o+i+1-e>r)return new sR({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(hR,0,0),e,!0))})),_R=`~effect/encoding/Sse/SseError`,vR=class extends Co(`EventTooLarge`){get message(){return`Pending SSE event exceeded the maximum size of ${this.maxEventSize}`}},yR=class extends Co(`SseError`){[_R]=_R;get message(){return this.reason.message}},bR=10485760,xR=e=>FD((t,n)=>Fh(()=>{let n=[],r,i=CR(e=>{e._tag===`Retry`?r=e:n.push(e)},e),a=T(t,e=>{for(let t=0;t<e.length;t++){let n=i.feed(e[t]);if(n!==void 0)return zh(n)}return Ih});return Ph(function e(){if(Yi(n)){let e=n;return n=[],C(e)}return r?zh(r):T(a,e)})})),SR=(e,t,n)=>oO(xR(t),hO(OR.pipe(bT(e,kR)),n)());function CR(e,t){let n=t?.maxEventSize??bR,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(wR)&&(e=e.slice(wR.length)),i=!1;let t=e.length,r=c,l=0;for(;l<t;){if(s&&(s=!1,e.charCodeAt(l)===TR)){++l;continue}let n=l;for(;n<t;){let t=e.charCodeAt(n);if(t===ER||t===TR)break;++n}if(n===t){a.push(e.slice(l)),o+=t-l;break}s=e.charCodeAt(n)===ER;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 yR({reason:new vR({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)===DR?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 jR({duration:$a(parseInt(a,10)),lastEventId:l}))}}var wR=``,TR=10,ER=13,DR=32,OR=j({_tag:DT(`Event`),id:yT(A),event:A,data:A}),kR=Cb({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})}),AR=`~effect/encoding/Sse/Retry`,jR=class e extends So(`Retry`){[AR]=AR;static is(e){return me(e,AR)}static filter(t){return e.is(t)?xi(t):Si(t)}},MR=class extends B(`@usine/engine/Submission`)({event:BM,itemKey:dI,loop:uA,step:DN,approval:fA,permissions:mA.pipe(TT(C(`write`)),CT(C(`write`))),cycleLimit:z(pI).pipe(ET(C(y(hI))),CT(C(y(hI)))),cycleGeneration:mI.pipe(TT(C(mI.make(0))),CT(C(mI.make(0)))),repository:H,revision:Gk,task:gF,agent:sA,parentModel:z(tA)}){},NR=`@usine/engine/DurableRun`,PR=D(`Submission.runIdFor`)(function*(e){let t=yield*(yield*WO).digest(`SHA-256`,new TextEncoder().encode(`${NR}-${e.event.dedupKey}`)).pipe(cg);return yN.make(Eo(t.subarray(0,16)))}),FR=(e,t,n)=>{let r=zM.make(JSON.stringify([`reopened`,n,t]));return new MR({...e,event:new BM({...e.event,id:RM.make(r),dedupKey:r})})},IR=class extends V(`@usine/engine/Claimed`)(`Claimed`,{eventId:RM,runId:yN}){},LR=class extends V(`@usine/engine/Queued`)(`Queued`,{eventId:RM}){},RR=[`superseded`,`revoked`],zR=P(RR),BR=class extends V(`@usine/engine/Ignored`)(`Ignored`,{eventId:RM,reason:zR}){},VR=class extends V(`@usine/engine/Suppressed`)(`Suppressed`,{eventId:RM,runId:yN}){},HR=class extends V(`@usine/engine/CycleBlocked`)(`CycleBlocked`,{eventId:RM,ask:yI}){},UR=N([IR,LR,VR,BR,HR]),WR=$L.table(`usine_events`,{eventId:X().$type().primaryKey(),dedupKey:X().$type().notNull().unique(),payloadJson:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[SL(`usine_events_payload_json_valid`,J`json_valid(${e.payloadJson})`)]),Z=$L.table(`usine_trigger_events`,{eventId:X().$type().primaryKey().references(()=>WR.eventId),itemKey:X().$type().notNull(),loopName:X().$type().notNull(),stepName:X().$type().notNull(),approval:X({enum:dA}).$type().notNull(),permissions:X({enum:pA}).$type().notNull().default(`write`),cycleLimit:ZI().$type(),cycleGeneration:ZI().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(()=>WR.eventId),reopening:ZI().notNull().default(0)},e=>[SL(`usine_trigger_events_approval`,J`${e.approval} in ('none', 'required')`),SL(`usine_trigger_events_cycle_limit`,J`${e.cycleLimit} is null or ${e.cycleLimit} >= 1`),SL(`usine_trigger_events_agent_json_valid`,J`json_valid(${e.agentJson})`),EL(`usine_trigger_events_item`).on(e.loopName,e.itemKey),EL(`usine_trigger_events_item_history`).on(e.itemKey),DL(`usine_trigger_event_reopening`).on(e.reopensEventId,e.reopening)]),GR=$L.table(`usine_loop_items`,{loopName:X().$type().notNull(),itemKey:X().$type().notNull(),observedEventId:X().$type().references(()=>WR.eventId),suppressedByRunId:X().$type().references(()=>Q.runId),suppressedEventId:X().$type().references(()=>WR.eventId)},e=>[OL({columns:[e.loopName,e.itemKey]})]),KR=$L.table(`usine_item_cycle_budgets`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),generation:ZI().notNull().default(0),askJson:X({mode:`json`}).$type(),resetPending:ZI({mode:`boolean`}).notNull().default(!1)},e=>[SL(`usine_item_cycle_generation`,J`${e.generation} >= 0`),SL(`usine_item_cycle_ask_json`,J`${e.askJson} is null or json_valid(${e.askJson})`)]),qR=$L.table(`usine_cycle_reservations`,{runId:X().$type().primaryKey().references(()=>Q.runId),itemKey:X().$type().notNull().references(()=>KR.itemKey),generation:ZI().notNull(),loop:X().$type().notNull()},e=>[EL(`usine_cycle_reservations_item`).on(e.itemKey,e.generation,e.loop),SL(`usine_cycle_reservations_generation`,J`${e.generation} >= 0`)]),JR=$L.table(`usine_cycle_resets`,{askId:X().$type().primaryKey(),eventId:X().$type().notNull().unique().references(()=>WR.eventId),itemKey:X().$type().notNull().references(()=>KR.itemKey)}),YR=$L.table(`usine_cycle_ask_closures`,{askId:X().$type().primaryKey(),itemKey:X().$type().notNull().references(()=>KR.itemKey),reason:X({enum:nR}).$type().notNull(),askJson:X({mode:`json`}).$type().notNull(),closedAt:X().notNull()},e=>[SL(`usine_cycle_ask_closures_reason`,J`${e.reason} in ('ItemClosed')`),SL(`usine_cycle_ask_closures_ask_json`,J`json_valid(${e.askJson})`)]),Q=$L.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=>[SL(`usine_runs_state_json_valid`,J`json_valid(${e.stateJson})`),SL(`usine_runs_agent_json_valid`,J`json_valid(${e.agentJson})`)]),XR=$L.table(`usine_steps`,{runId:X().$type().notNull().references(()=>Q.runId),stepName:X().$type().notNull(),result:X({mode:`json`}).$type()},e=>[OL({columns:[e.runId,e.stepName]}),SL(`usine_steps_result_json_valid`,J`${e.result} is null or json_valid(${e.result})`)]),$=$L.table(`usine_attempts`,{attemptId:X().$type().primaryKey(),runId:X().$type().notNull(),stepName:X().$type().notNull(),workerName:X().$type().notNull(),attemptNumber:ZI({mode:`number`}).$type().notNull(),brainJson:X({mode:`json`}).$type().notNull(),task:X().$type().notNull(),agent:X().$type().notNull(),operatorIntervened:ZI({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=>[SL(`usine_attempts_number`,J`${e.attemptNumber} >= 1`),SL(`usine_attempts_brain_json_valid`,J`json_valid(${e.brainJson})`),SL(`usine_attempts_outcome_json_valid`,J`${e.outcomeJson} is null or json_valid(${e.outcomeJson})`),SL(`usine_attempts_salvage_json_valid`,J`${e.salvageJson} is null or json_valid(${e.salvageJson})`),DL(`usine_attempt_number`).on(e.runId,e.stepName,e.attemptNumber),DL(`usine_one_in_flight_attempt`).on(e.runId).where(J`${e.outcomeJson} is null`),pee({columns:[e.runId,e.stepName],foreignColumns:[XR.runId,XR.stepName]})]),ZR=$L.table(`usine_attempt_transcripts`,{sequence:ZI({mode:`number`}).primaryKey({autoIncrement:!0}),attemptId:X().$type().notNull().references(()=>$.attemptId),direction:X({enum:IF}).notNull(),channelSequence:ZI({mode:`number`}).$type().notNull(),envelope:X({mode:`json`}).$type().notNull(),receivedAt:X().notNull()},e=>[SL(`usine_attempt_transcripts_direction`,J`${e.direction} in ('inbound', 'outbound')`),SL(`usine_attempt_transcripts_sequence`,J`${e.channelSequence} >= 1`),SL(`usine_attempt_transcripts_envelope_json_valid`,J`json_valid(${e.envelope})`),DL(`usine_attempt_transcript_envelope`).on(e.attemptId,e.direction,e.channelSequence),EL(`usine_attempt_transcript_tail`).on(e.attemptId,e.sequence),EL(`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'`)]),QR=$L.table(`usine_approvals`,{runId:X().$type().primaryKey().references(()=>Q.runId),eventId:X().$type().notNull().unique().references(()=>WR.eventId),channel:X({enum:bI}).$type(),approver:X().$type()},e=>[SL(`usine_approvals_source`,J`(${e.channel} is null and ${e.approver} is null) or ${e.channel} = 'ui'`)]),$R=$L.table(`usine_run_again_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),fromRunId:X().$type().notNull().references(()=>Q.runId),requestedBy:X().$type()}),ez=$L.table(`usine_ignored_events`,{eventId:X().$type().primaryKey().references(()=>Z.eventId),reason:X({enum:RR}).$type().notNull()},e=>[SL(`usine_ignored_events_reason`,J`${e.reason} in ('superseded', 'revoked')`)]),tz=$L.table(`usine_cursors`,{cursorKey:X().primaryKey(),valueJson:X({mode:`json`}).$type().notNull()},e=>[SL(`usine_cursors_value_json_valid`,J`json_valid(${e.valueJson})`)]),nz=$L.table(`usine_item_projections`,{itemKey:X().$type().primaryKey(),repository:X().$type().notNull(),source:X().notNull(),itemNumber:ZI({mode:`number`}).notNull(),contentHash:X().notNull(),payloadJson:X({mode:`json`}).$type().notNull(),goneAt:X()},e=>[SL(`usine_item_projections_number`,J`${e.itemNumber} >= 1`),SL(`usine_item_projections_payload_json_valid`,J`json_valid(${e.payloadJson})`),DL(`usine_item_projection_number`).on(e.repository,e.itemNumber)]),rz=$L.table(`usine_repository_label_projections`,{repository:X().$type().primaryKey(),labelsJson:X({mode:`json`}).$type().notNull()},e=>[SL(`usine_repository_label_projections_labels_json_valid`,J`json_valid(${e.labelsJson})`)]),iz=$L.table(`usine_board_moves`,{moveId:ZI({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=>[SL(`usine_board_moves_added_json_valid`,J`json_valid(${e.addedJson})`),SL(`usine_board_moves_removed_json_valid`,J`json_valid(${e.removedJson})`),EL(`usine_board_moves_item`).on(e.itemKey,e.movedAt)]),az=$L.table(`usine_loop_runtime`,{loopName:X().$type().primaryKey(),paused:ZI({mode:`boolean`}).notNull()}),oz=$L.table(`usine_projection_revision`,{singleton:ZI({mode:`number`}).primaryKey().default(1),revision:ZI({mode:`number`}).notNull().default(0)},e=>[SL(`usine_projection_revision_singleton`,J`${e.singleton} = 1`)]);$L.table(`usine_attention_acknowledgements`,{id:X().notNull(),revision:X().$type().notNull(),dismissedBy:X().$type(),dismissedAt:X().notNull()},e=>[OL({columns:[e.id,e.revision]})]);var sz=class extends jE(`@usine/engine/RunNotFoundError`)(`RunNotFoundError`,{runId:yN}){},cz=class extends jE(`@usine/engine/RunOperationRejectedError`)(`RunOperationRejectedError`,{runId:yN,operation:P([`approve`,`retry`,`resolveFailure`,`runAgain`,`cancel`]),state:A}){},lz=class extends jE(`@usine/engine/RunRetryBlockedError`)(`RunRetryBlockedError`,{runId:yN,openRunId:yN,message:R}){},uz=class extends jE(`@usine/engine/EnginePersistenceError`)(`EnginePersistenceError`,{operation:A,cause:QT()}){},dz=class extends jE(`@usine/engine/AttemptCancellationError`)(`AttemptCancellationError`,{attemptId:pF,cause:QT()}){},fz=N([sz,cz,lz,uz]),pz=class extends jE(`@usine/engine/RunInterventionRejectedError`)(`RunInterventionRejectedError`,{runId:yN,attemptId:pF,message:R}){},mz=class extends jE(`@usine/engine/LeftoversDiscardRejectedError`)(`LeftoversDiscardRejectedError`,{worker:kN,running:L.check(BT(0))}){};N([sz,cz,lz,uz,dz,pz]);var hz=class e extends Lr()(`@usine/engine/internal/RunDatabase`){static layer=t=>Gf(e)(t)},gz=A.check(MT(/\S/u,{message:`Expected a non-blank repository label`})),_z=A.check(MT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})),vz=class extends B(`@usine/engine/RepositoryLabel`)({name:gz,color:_E(_z),description:_E(A)}){},yz=jT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),bz=M(vz).check(yz),xz=class extends B(`@usine/engine/RepositoryLabelProjection`)({repository:H,labels:bz}){},Sz=M(A),Cz=Rw(Sz),wz=j({repository:H,labels:N([xz.fields.labels,Sz])}),Tz=e=>Cz(e)?e.map(e=>new vz({name:e,color:v(),description:v()})):e,Ez=zw(M(wz)),Dz=Jw(xz.fields.labels),Oz=e=>t=>sg(t,t=>new uz({operation:e,cause:t})),kz=w(function*(){let e=yield*hz;return{get:D(`RepositoryLabelProjectionReader.get`)(function*(t){let n=(yield*Ez(yield*e.select({repository:rz.repository,labels:rz.labelsJson}).from(rz).where(Y(rz.repository,t)).limit(1).execute(),{onExcessProperty:`error`}))[0];return n===void 0?v():y(new xz({repository:n.repository,labels:Tz(n.labels)}))},Oz(`read repository label projection`))}}),Az=w(function*(){let e=yield*hz;return{replace:D(`RepositoryLabelProjectionWriter.replace`)(function*(t){yield*E({repository:t.repository});let n=Dz(t.labels);return(yield*e.insert(rz).values({repository:t.repository,labelsJson:n}).onConflictDoUpdate({target:rz.repository,set:{labelsJson:n},setWhere:Ij(rz.labelsJson,n)}).returning({repository:rz.repository}).execute()).length===0?(yield*k(`Repository label projection already matched GitHub`,{repository:t.repository,labels:t.labels.length}),!1):(yield*k(`Repository label projection updated from trigger polling`,{repository:t.repository,labels:t.labels.length}),!0)},Oz(`write repository label projection`))}}),jz=class e extends Lr()(`@usine/engine/RepositoryLabelProjectionReader`){static layer=qf(e,kz)},Mz=class e extends Lr()(`@usine/engine/RepositoryLabelProjectionWriter`){static layer=qf(e,Az)},Nz=`~effect/http/HttpBody`,Pz=e=>me(e,Nz),Fz=class{[Nz];constructor(){this[Nz]=Nz}[gt](){return this.toJSON()}toString(){return ot(this,{ignoreToString:!0})}},Iz=new class extends Fz{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}},Lz=class extends Fz{_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??=Vz(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}}},Rz=(e,t)=>new Lz(e,t??`application/octet-stream`,e.length),zz=new TextEncoder,Bz=globalThis.Buffer,Vz=Bz===void 0?e=>zz.encode(e):e=>Bz.from(e,`utf8`),Hz=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),Bz!==void 0)return new Lz(void 0,t??`text/plain`,Bz.byteLength(e,`utf8`),e);let n=zz.encode(e);return new Lz(n,t??`text/plain`,n.length,e)},Uz=(e,t)=>Hz(JSON.stringify(e),t??`application/json`),Wz=(e,t)=>Hz(qv(Rv(e)),t??`application/x-www-form-urlencoded`),Gz=class extends Fz{_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}}},Kz=e=>new Gz(e),qz=class extends Fz{_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}}},Jz=(e,t,n)=>new qz(e,t??`application/octet-stream`,n),Yz=`~effect/http/HttpClientError`,Xz=class extends Co(`HttpClientError`){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[Yz]=Yz;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}},Zz=e=>e.endsWith(`Error`)?e.slice(0,-5):e,Qz=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,$z=e=>`${e.method} ${Zv(e.url)}`,eB=class extends Co(`TransportError`){get methodAndUrl(){return $z(this.request)}get message(){return Qz(Zz(this._tag),this.description,this.methodAndUrl)}},tB=class extends Co(`InvalidUrlError`){get methodAndUrl(){return $z(this.request)}get message(){return Qz(Zz(this._tag),this.description,this.methodAndUrl)}},nB=class extends Co(`StatusCodeError`){get methodAndUrl(){return $z(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return Qz(Zz(this._tag),this.description,e)}},rB=class extends Co(`DecodeError`){get methodAndUrl(){return $z(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return Qz(Zz(this._tag),this.description,e)}},iB=class extends Co(`EmptyBodyError`){get methodAndUrl(){return $z(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return Qz(Zz(this._tag),this.description,e)}},aB=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,oB=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],sB=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?kv(kv(e,`content-type`),`content-length`):(e=t.contentType===void 0?kv(e,`content-type`):Ev(e,`content-type`,t.contentType),t.contentLength===void 0?kv(e,`content-length`):Ev(e,`content-length`,t.contentLength.toString())),cB=class extends Co(`UrlError`){},lB=(e,t,n)=>wi({try:()=>{let r=new URL(e,uB());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,Nv(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new cB({cause:e})}),uB=()=>{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`,fB={[dB]:dB,...yt,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:Zv(this.url),urlParams:this.urlParams,hash:this.hash,headers:tt(this.headers),body:this.body.toJSON()}},pipe(){return e(this,arguments)}};function pB(e,t,n,r,i,a){let o=Object.create(fB);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var mB=pB(`GET`,``,Uv,v(),Cv,Iz),hB=e=>(t,n)=>yB(mB,{method:e,url:t,...n??void 0}),gB=hB(`GET`),_B=hB(`POST`),vB=hB(`PATCH`),yB=r(2,(e,t)=>{let n=e;return t.method&&(n=bB(n,t.method)),t.url&&(n=EB(n,t.url)),t.headers&&(n=SB(n,t.headers)),t.urlParams&&(n=kB(n,t.urlParams)),t.hash&&(n=jB(n,t.hash)),t.body&&(n=MB(n,t.body)),t.accept&&(n=CB(n,t.accept)),t.acceptJson&&(n=wB(n)),n}),bB=r(2,(e,t)=>pB(t,e.url,e.urlParams,e.hash,e.headers,e.body)),xB=r(3,(e,t,n)=>pB(e.method,e.url,e.urlParams,e.hash,Ev(e.headers,t,n),e.body)),SB=r(2,(e,t)=>pB(e.method,e.url,e.urlParams,e.hash,Dv(e.headers,t),e.body)),CB=r(2,(e,t)=>xB(e,`Accept`,t)),wB=CB(`application/json`),TB=r(2,(e,t)=>pB(e.method,e.url,e.urlParams,e.hash,Ev(Ev(e.headers,`connection`,`Upgrade`),`upgrade`,t),e.body)),EB=r(2,(e,t)=>{if(typeof t==`string`)return pB(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Rv(n.searchParams),i=xr(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,pB(e.method,n.toString(),r,i,e.headers,e.body)}),DB=r(2,(e,t)=>t===``?e:pB(e.method,OB(t,e.url),e.urlParams,e.hash,e.headers,e.body)),OB=(e,t)=>{let n=e.endsWith(`/`),r=t.startsWith(`/`);return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t},kB=r(2,(e,t)=>pB(e.method,e.url,Gv(e.urlParams,t),e.hash,e.headers,e.body)),AB=r(2,(e,t)=>pB(e.method,e.url,Kv(e.urlParams,t),e.hash,e.headers,e.body)),jB=r(2,(e,t)=>pB(e.method,e.url,e.urlParams,y(t),e.headers,e.body)),MB=r(2,(e,t)=>pB(e.method,e.url,e.urlParams,e.hash,sB(e.headers,t),t)),NB=r(2,(e,t)=>MB(e,Uz(t))),PB=r(2,(e,t)=>MB(e,Kz(t)));function FB(e){let t=lB(e.url,e.urlParams,wr(e.hash));return Di(t)?y(t.success):v()}var IB=`~effect/http/HttpIncomingMessage`,LB=(e,t)=>{let n=Bw(ME(e)),r=t?.reviver===void 0?void 0:Bw(rE(ME(e),t));return e=>r===void 0?T(e.json,e=>n(e,t)):T(e.text,i=>i===``?T(e.json,e=>n(e,t)):r(i,t))},RB=(e,t)=>({...t,headers:tt(e.headers),remoteAddress:e.remoteAddress}),zB=`~effect/http/HttpClientResponse/WebSource`,BB=e=>e[zB]?.(),VB=`~effect/http/HttpClientResponse`,HB=(e,t)=>new UB(e,t),UB=class extends bt{[IB];[VB];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[IB]=IB,this[VB]=VB}toJSON(){return RB(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=FB(this.request);return b(e)?``:(e.value.hash=``,e.value.href)}get headers(){return wv(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=ov(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return v()}[zB](){return this.source}get stream(){return this.source.body?kO({evaluate:()=>this.source.body,onError:e=>new Xz({reason:new rB({request:this.request,response:this,cause:e})})}):DO(new Xz({reason:new iB({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return T(this.text,e=>Uh({try:()=>e===``?null:JSON.parse(e),catch:e=>new Xz({reason:new rB({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=Qh(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return T(this.text,e=>Uh({try:()=>Rv(new URLSearchParams(e)),catch:e=>new Xz({reason:new rB({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=Mh({try:()=>this.source.formData(),catch:e=>new Xz({reason:new rB({request:this.request,response:this,cause:e})})}).pipe(Mg,qg)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=Mh({try:()=>this.source.arrayBuffer(),catch:e=>new Xz({reason:new rB({request:this.request,response:this,cause:e})})}).pipe(Mg,qg),this.arrayBufferBody}get upgrade(){return zh(new Xz({reason:new nB({request:this.request,response:this,description:`fetch cannot hand over the connection of an HTTP upgrade`})}))}pipe(){return e(this,arguments)}},WB=e=>Tv({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${_r(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),GB={"http:":80,"https:":443,"ws:":80,"wss:":443},KB=(e,t,n)=>{let r=Zv(t.search,n).slice(1);if(e.attribute(`url.full`,Zv(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===``?GB[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},qB=(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()]},JB=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,jv(a,i)?`<redacted>`:n[a])},YB=`~effect/http/HttpClient`,XB=Lr(`effect/HttpClient`),ZB=r(2,(e,t)=>QB(n=>t(e.postprocess(n)),e.preprocess)),QB=(e,t)=>{let n=Object.create($B);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},$B={[YB]:YB,pipe(){return e(this,arguments)},...yt,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(oB.map(([e,t])=>[t,function(t,n){return this.execute(hB(e)(t,n))}]))},eV=e=>QB(t=>T(t,t=>Wh(n=>{let r=uV.get(t),i=r??new AbortController,a=lB(t.url,t.urlParams,wr(t.hash));if(Ei(a))return zh(new Xz({reason:new tB({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(zo)||n.getRef(iV)(t)){let a=e(t,o,i.signal,n);return r?a:Ig(e=>vg(e(a),{onSuccess(e){return lV.register(e,i),C(new dV(e,i))},onFailure(e){return $d(e)&&i.abort(),Bh(e)}}))}return zg(n.getRef(sV)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(Mv);KB(a,o,qB(t.urlParams,n.getRef(ay)));let c=n.getRef(aV);return JB(a,`request`,t.headers,c,s),t=n.getRef(oV)?SB(t,WB(a)):t,Ig(l=>l(e(t,o,i.signal,n)).pipe(Vg(a,{captureStackTrace:!1}),vg({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),JB(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),tV(n,a,t,e)),r?C(e):(lV.register(e,i),C(new dV(e,i)))),onFailure(e){return!r&&$d(e)&&i.abort(),Bh(e)}})))})})),C),tV=(e,t,n,r)=>{let i=St();Ct(0);let a;try{a=cf(new Xz({reason:new nB({request:n,response:r})}))}finally{Ct(i)}t.end(e.getRef(Cf)?e.getRef(np).currentTimeNanosUnsafe():BigInt(0),a)},nV=r(2,(e,t)=>QB(e.postprocess,n=>Qh(e.preprocess(n),t))),rV=r(2,(e,t)=>ZB(e,Jh(t))),iV=_i(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>s}),aV=_i(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>s}),oV=_i(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:o}),sV=_i(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),cV=e=>qf(XB)(bg(t=>Qh(e,e=>ZB(e,wg(e=>mi(t,e)))))),lV=(()=>{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))}}})(),uV=new WeakMap,dV=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[VB]=VB;[IB]=IB;applyInterrupt(e){return Ph(()=>(lV.unregister(this.original),Pg(e,()=>Fh(()=>{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)}[zB](){let e=BB(this.original);return e!==void 0&&lV.unregister(this.original),e}get stream(){return TO(()=>(lV.unregister(this.original),zO(this.original.stream,Fh(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[gt](){return this.original[gt]()}pipe(){return e(this,arguments)}},fV=_i(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),pV=class extends Lr()(`effect/http/FetchHttpClient/RequestInit`){},mV=cV(C(eV((e,t,n,r)=>{if(e.headers.upgrade!==void 0)return zh(new Xz({reason:new eB({request:e,description:`fetch cannot send an HTTP upgrade request`})}));let i=r.getRef(fV),a=oi(r.context,pV)??{},o=a.headers?Ov(wv(a.headers),e.headers):e.headers;o[`content-length`]&&(o=kv(o,`content-length`));let s,c=Fh(()=>s?.abort()),l=r=>Qh(Mh({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 Xz({reason:new eB({request:e,cause:t})})}),t=>{let n=HB(e,t);return s?(t.body===null&&s.abort(),Object.create(n,{...Object.fromEntries([`arrayBuffer`,`text`,`json`,`formData`,`urlParamsBody`].map(e=>[e,{get:()=>Og(n[e],c)}])),stream:{get:()=>zO(n.stream,c)}})):n}).pipe(kg(()=>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=Lh(e=>{let n=()=>e(Ng);if(t.aborted)n();else return t.addEventListener(`abort`,n,{once:!0}),Fh(()=>t.removeEventListener(`abort`,n))});return T(UO(RO(e.body.stream,r)),l)}}return l(void 0)})));function hV(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 gV=Lr(`effect/http/HttpEffect/CurrentRequestState`),_V=e=>Wh(t=>{let n=oi(t.context,gV);return n!==void 0&&(n.loggerDisabled=!0),e}),vV=Lr(`effect/http/HttpRouter`),yV=e=>e.endsWith(`/`)?e.slice(0,-1):e,bV=r(2,(e,t)=>(t=yV(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),xV=`~effect/http/HttpRouter/Middleware`,SV=function(){return arguments.length===0?CV:CV(arguments[0],arguments[1])},CV=(e,t)=>t?.global?Xf(w(function*(){let t=yield*vV,n=Oh(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new EV(Oh(e)?Yf(Qh(e,e=>Xr(new Map([[TV,e]])))):Kf(Xr(new Map([[TV,e]])))),wV=0,TV=`effect/http/HttpRouter/MiddlewareFn`,EV=class e{[xV]={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++wV}`;this.layer=Yf(w({self:this},function*(){let e=yield*yg(),t=[si(e,TV)];if(this.dependencies){let n=yield*Hf,r=li(e,wf),i=yield*Uf(this.dependencies,n,r);t.push(...OV(i))}return Xr(new Map([[n,t]]))})).pipe(ep(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?tp(this.dependencies,t.layer):t.layer)}},DV=new WeakMap,OV=e=>{let t=DV.get(e);if(t)return t;let n=fa(),r=0;for(let[t,i]of e.mapUnsafe)t.startsWith(`effect/http/HttpRouter/Middleware-`)&&(n.push(i),i.length>r&&(r=i.length));if(n.length===0)t=[];else{let e=new Set;for(let t=r-1;t>=0;t--)for(let r of n)t<r.length&&e.add(r[t]);t=Wi(e).reverse()}return DV.set(e,t),t};SV(_V).layer;var kV={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},AV=e=>kV[e],jV=L.check(BT(1)).pipe(I(`GitHubAppId`)),MV=xE(R.check(MT(/^-----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:jV,privateKey:MV});var NV=class extends Lr()(`@usine/github/GitHubCredentials`){},PV=class extends jE(`@usine/github/AppAuthenticationError`)(`AppAuthenticationError`,{message:R}){},FV=new TextEncoder,IV=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),LV=(...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},RV=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])},zV=(e,t)=>LV(new Uint8Array([e]),RV(t.length),t),BV=e=>zV(48,LV(new Uint8Array([2,1,0]),IV,zV(4,e))),VV=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?BV(i):i},HV=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/=/gu,``).replace(/\+/gu,`-`).replace(/\//gu,`_`)},UV=e=>HV(FV.encode(JSON.stringify(e))),WV=e=>{let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},GV=D(`AppJwt.import`)(function*(e){let t=yield*Mh({try:async()=>crypto.subtle.importKey(`pkcs8`,WV(VV(_v(e.privateKey))),{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},!1,[`sign`]),catch:()=>new PV({message:`Could not import the GitHub App private key as an RSA private key`})});return D(`AppJwt.sign`)(function*(){let n=Math.floor((yield*rp)/1e3),r=`${UV({alg:`RS256`,typ:`JWT`})}.${UV({iat:n-60,exp:n+540,iss:e.appId})}`,i=yield*jh(()=>crypto.subtle.sign(`RSASSA-PKCS1-v1_5`,t,WV(FV.encode(r))));return hv(`${r}.${HV(new Uint8Array(i))}`)})}),KV=L.check(BT(1)),qV=KV.pipe(I(`GitHubInstallationId`)),JV=KV.pipe(I(`GitHubRepositoryId`)),YV=R.pipe(I(`GitHubAppSlug`)),XV=class extends B(`@usine/github/Installation`)({id:qV,accountLogin:R,appSlug:YV}){},ZV=class extends V(`@usine/github/TokenScope/InstallationWide`)(`InstallationWide`,{}){},QV=class extends V(`@usine/github/TokenScope/SingleRepository`)(`SingleRepository`,{repository:H,repositoryId:JV,permissions:mA}){},$V=N([ZV,QV]),eH=class extends B(`@usine/github/InstallationToken`)({value:bE(R,{disallowJsonEncode:!0}),expiresAt:hE,scope:$V}){},tH=P([`missing`,`multiple`,`suspended`]),nH=class extends jE(`@usine/github/InstallationDiscoveryError`)(`InstallationDiscoveryError`,{reason:tH,message:R}){},rH={checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},iH={write:{checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},read:{checks:`read`,contents:`read`,issues:`write`,metadata:`read`,pull_requests:`write`}},aH=(e,t)=>e===t||t===`read`&&e===`write`,oH=e=>Object.entries(rH).flatMap(([t,n])=>aH(e[t],n)?[]:[`${t}:${n}`]),sH=class extends V(`@usine/github/ProjectAccess/CoveredProject`)(`CoveredProject`,{installationId:qV,repository:H,repositoryId:JV}){},cH=class extends jE(`@usine/github/ProjectNotInstalledError`)(`ProjectNotInstalledError`,{repository:H,message:R}){};N([sH,cH]);var lH=(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 cH({repository:t,message:`The GitHub App installation has no access to "${t}"`}):new sH({installationId:e.id,repository:t,repositoryId:n.id})})},uH=class extends jE(`@usine/github/AppPermissionError`)(`AppPermissionError`,{missing:M(R).check(GT()),message:R}){},dH=P([`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`]),fH=class extends jE(`@usine/github/GitHubApiError`)(`GitHubApiError`,{operation:dH,status:z(L),message:R}){},pH=class extends jE(`@usine/github/GitHubRateLimitError`)(`GitHubRateLimitError`,{operation:dH,retryAt:hE,message:R}){},mH=class extends jE(`@usine/github/InvalidGitHubResponseError`)(`InvalidGitHubResponseError`,{operation:dH,message:R,detail:R}){},hH=class extends jE(`@usine/github/GitHubItemNotFoundError`)(`GitHubItemNotFoundError`,{operation:dH,item:L.check(BT(1)),message:R}){};N([nH,uH,fH,pH,mH]);var gH=`https://api.github.com`,_H=`2026-03-10`,vH=e=>SB({accept:`application/vnd.github+json`,authorization:`Bearer ${_v(e)}`,"user-agent":`usine`,"x-github-api-version":_H}),yH=(e,t)=>new fH({operation:e,status:t.response===void 0?v():y(t.response.status),message:t.response===void 0?`Could not send the request to GitHub`:`GitHub returned HTTP status ${t.response.status}`}),bH=Vw(j({message:R})),xH=(e,t)=>t.json.pipe(Qh(t=>_r(bH(t),{onNone:()=>e,onSome:({message:t})=>new fH({operation:e.operation,status:e.status,message:`${e.message}: ${t}`})})),ng(t=>k(`GitHub's error response has no JSON body to read a reason from`,{operation:e.operation,message:t.message}).pipe($h(e)))),SH=(e,t)=>new mH({operation:e,message:`GitHub returned a response in an unexpected format`,detail:t}),CH=e=>{if(e===void 0||!/^\d+$/u.test(e))return v();let t=Number(e);return Number.isSafeInteger(t)?y(t):v()},wH=(e,t)=>{let n=CH(e);if(x(n))return y(t+n.value*1e3);if(e===void 0)return v();let r=Date.parse(e);return Number.isFinite(r)?y(r):v()},TH=(e,t)=>{let n=CH(e[`x-ratelimit-remaining`]),r=CH(e[`x-ratelimit-reset`]);return x(n)&&n.value<=t&&x(r)?y(r.value*1e3):v()},EH=(e,t)=>Dr(CH(e[`x-poll-interval`]),e=>t+e*1e3),DH=e=>{let t=e.flatMap(e=>_r(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?v():y(Math.max(...t))},OH=(e,t)=>DH([wH(e[`retry-after`],t),TH(e,0)]),kH=(e,t,n)=>{let r=Or(OH(t.headers,n),F_);return(t.status===403||t.status===429)&&x(r)?new pH({operation:e,retryAt:r.value,message:`GitHub API rate limit exceeded`}):new fH({operation:e,status:y(t.status),message:`GitHub returned HTTP status ${t.status}`})},AH=e=>e===void 0?v():xr(/<(?<url>[^>]+)>;\s*rel="next"/u.exec(e)?.groups?.url),jH=A.check(MT(/^[1-9][0-9]*$/u)).pipe(I(`WebhookDeliveryId`)),MH=rE(M(class extends B(`@usine/github/WebhookDelivery`)({id:jH,event:R,repositoryId:_E(JV)}){}.pipe(fT({repositoryId:`repository_id`}))),{reviver:(e,t,n)=>e===`id`?n?.source:t}),NH=36e5,PH=3e5,FH=M(j({id:qV,appSlug:YV,account:j({login:R}),permissions:pT(A,A),suspendedAt:F(A)}).pipe(fT({appSlug:`app_slug`,suspendedAt:`suspended_at`}))),IH=j({login:jN,id:MN}),LH=j({id:JV,name:H}).pipe(fT({name:`full_name`})),RH=j({totalCount:L.check(BT(0)),repositories:M(LH)}).pipe(fT({totalCount:`total_count`})),zH=j({token:R,expiresAt:gE,repositories:yE(M(LH))}).pipe(fT({expiresAt:`expires_at`})),BH=e=>e._tag===`InstallationWide`?{operation:`mint-installation-token`,body:{permissions:rH}}:{operation:`mint-worker-token`,body:{permissions:iH[e.permissions],repository_ids:[e.repositoryId]}},VH=class e extends Lr()(`@usine/github/GitHubApp`){static layer=qf(e,w(function*(){let e=yield*NV,t=yield*GV(e),n=yield*XB,r=D(`GitHubApp.fetch`)(function*(t,r){yield*E({appId:e.appId,operation:t});let i=yield*n.execute(r).pipe(sg(e=>yH(t,e)));if(i.status<200||i.status>=300){let e=kH(t,i,yield*rp);return e._tag===`GitHubRateLimitError`?yield*e:yield*yield*xH(e,i)}return i}),i=(e,t,n)=>r(e,t).pipe(T(t=>LB(n)(t).pipe(sg(t=>SH(e,t.message))))),a=D(`GitHubApp.deliveries`)(function*(n){yield*E({appId:e.appId,after:S(n)});let i=yield*t(),a=y(`${gH}/app/hook/deliveries?per_page=100`),o=[];for(let e=0;e<10&&x(a);e+=1){let e=yield*r(`poll-webhook-deliveries`,gB(a.value).pipe(vH(i))),t=yield*e.text.pipe(T(zw(MH)),sg(e=>SH(`poll-webhook-deliveries`,e.message))),s=t.filter(e=>b(n)||BigInt(e.id)>BigInt(n.value));if(o.push(...s),s.length<t.length)return o;a=AH(e.headers.link)}return x(a)&&(yield*Xg(`Webhook delivery page limit reached; older hints dropped`,{appId:e.appId,deliveries:o.length})),o}),o=D(`GitHubApp.discoverInstallation`)(function*(){let e=yield*t(),[n,...r]=yield*i(`discover-installation`,gB(`${gH}/app/installations?per_page=2`).pipe(vH(e)),FH);if(n===void 0)return yield*new nH({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 nH({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 nH({reason:`suspended`,message:`The GitHub App installation is suspended. Unsuspend it in the installation settings on GitHub.`});let a=oH(n.permissions);return a.length>0?yield*new uH({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 XV({id:n.id,accountLogin:n.account.login,appSlug:n.appSlug})}),s=D(`GitHubApp.mintToken`)(function*(e,n){let{operation:r,body:a}=BH(n);yield*E({installationId:e,operation:r,scope:n._tag,permissions:n._tag===`SingleRepository`?n.permissions:`installation`});let o=yield*t(),s=yield*i(r,_B(`${gH}/app/installations/${e}/access_tokens`).pipe(NB(a),vH(o)),zH),c=yield*rp,l=H_(s.expiresAt)-c;if(l<=0||l>378e4)return yield*new mH({operation:r,message:`GitHub returned an installation token that is expired or exceeds the one-hour lifetime limit`,detail:`expires_at ${G_(s.expiresAt)} is ${l}ms from now`});l>NH&&(yield*O(`Accepted GitHub token clock skew; capped the local lease`,{installationId:e,operation:r,skewMillis:l-NH}));let u=vr(s.repositories,()=>[]);return n._tag===`SingleRepository`&&!(u.length===1&&u.every(e=>e.id===n.repositoryId))?yield*new mH({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 eH({value:hv(s.token),expiresAt:P_(c+Math.min(l,NH)),scope:n})}),c=D(`GitHubApp.installedRepositories`)(function*(e){let t=[];for(let n=1;;n+=1){let r=yield*i(`list-installation-repositories`,gB(`${gH}/installation/repositories?per_page=100&page=${n}`).pipe(vH(e.value)),RH);if(t.push(...r.repositories),t.length>=r.totalCount)return t;if(r.repositories.length===0)return yield*new mH({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*Hk(v()),u=D(`GitHubApp.lease`)(()=>Wk(l,e=>w(function*(){let t=yield*rp;if(x(e)&&H_(e.value.token.expiresAt)-t>PH)return[e.value,e];let n=yield*o(),r={installation:n,token:yield*s(n.id,new ZV)};return[r,y(r)]}))),d=yield*Hk(v()),f=D(`GitHubApp.botAccount`)(()=>Wk(d,e=>w(function*(){let{installation:t,token:n}=yield*u(),{appSlug:r}=t;if(yield*E({appSlug:r}),x(e)&&e.value.appSlug===r)return[e.value.account,e];let a=new NN(yield*i(`read-bot-account`,gB(`${gH}/users/${encodeURIComponent(`${r}[bot]`)}`).pipe(vH(n.value)),IH));return yield*O(`Read the App's bot account`,{appSlug:r,login:a.login,id:a.id}),[a,y({appSlug:r,account:a})]})));return{configureWebhook:D(`GitHubApp.configureWebhook`)(function*(n){yield*E({appId:e.appId});let i=yield*t();yield*r(`configure-webhook`,vB(`${gH}/app/hook/config`).pipe(NB({url:n.href,content_type:`json`}),vH(i))),yield*O(`Configured the App webhook endpoint`,{appId:e.appId})}),deliveries:a,repositories:D(`GitHubApp.repositories`)(function*(){let{token:e,installation:t}=yield*u();yield*E({installationId:t.id});let n=yield*c(e);return yield*k(`Listed installation repositories`,{count:n.length}),n.map(({name:e})=>e)}),installation:D(`GitHubApp.installation`)(()=>Qh(u(),e=>e.installation)),botAccount:f,installationToken:D(`GitHubApp.installationToken`)(()=>Qh(u(),e=>e.token)),projectAccess:D(`GitHubApp.projectAccess`)(function*(e){let{installation:t,token:n}=yield*u();return lH(t,e,yield*c(n))}),workerToken:D(`GitHubApp.workerToken`)((e,t)=>s(e.installationId,new QV({repository:e.repository,repositoryId:e.repositoryId,permissions:t})))}}))},HH=R.pipe(I(`GitHubEntityTag`)),UH=R.pipe(I(`GitHubBaseRefName`)),WH=class extends B(`@usine/github/BaseRefHead`)({baseRefName:UH,sha:Kk,entityTag:_E(HH)}){},GH=class e extends B(`@usine/github/PollCursor`)({entityTag:_E(HH),watermark:_E(gE)}){static empty=new e({entityTag:v(),watermark:v()})},KH=class extends V(`@usine/github/ChangedIssue`)(`ChangedIssue`,{number:L.check(BT(1)),updatedAt:hE}){},qH=class extends V(`@usine/github/ChangedPullRequest`)(`ChangedPullRequest`,{number:L.check(BT(1)),updatedAt:hE}){},JH=N([KH,qH]),YH=class extends V(`@usine/github/RepositoryNotModified`)(`RepositoryNotModified`,{cursor:GH,nextPollAt:z(hE),backoffUntil:z(hE).pipe(CT(C(v())))}){},XH=class extends V(`@usine/github/RepositoryChanges`)(`RepositoryChanges`,{cursor:GH,items:M(JH),backlog:sT,nextPollAt:z(hE),backoffUntil:z(hE).pipe(CT(C(v())))}){};N([YH,XH]);var ZH=R.pipe(I(`GitHubRepositoryLabelName`)),QH=A.check(MT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})).pipe(I(`GitHubRepositoryLabelColor`)),$H=class extends B(`@usine/github/RepositoryLabel`)({name:ZH,color:QH,description:_E(A)}){},eU=jT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),tU=class extends B(`@usine/github/RepositoryLabelCatalog`)({entityTag:_E(HH),labels:M($H).check(eU)}){},nU=class extends V(`@usine/github/RepositoryLabelsNotModified`)(`RepositoryLabelsNotModified`,{}){};N([tU,nU]);var rU=class extends B(`@usine/github/NewRepositoryLabel`)({name:ZH,color:z(QH),description:z(A)}){},iU=j({name:ZH,color:QH,description:F(A)}),aU=e=>{let{name:t,owner:n}=Jk(e);return`${gH}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`},oU=class e extends Lr()(`@usine/github/GitHubLabelWriter`){static layer=qf(e,w(function*(){let e=yield*VH,t=yield*XB;return{create:D(`GitHubLabelWriter.create`)(function*(n,r){yield*E({repository:n,label:r.name});let i=yield*e.installationToken(),a={name:r.name};x(r.color)&&(a.color=r.color.value),x(r.description)&&(a.description=r.description.value);let o=_B(aU(n)).pipe(NB(a),vH(i.value)),s=yield*t.execute(o).pipe(sg(e=>yH(`create-repository-label`,e)));if(s.status<200||s.status>=300)return yield*kH(`create-repository-label`,s,yield*rp);let c=yield*LB(iU)(s).pipe(sg(e=>SH(`create-repository-label`,e.message)));return new $H({name:c.name,color:c.color,description:xr(c.description)})})}}))},sU=6e4,cU=j({data:Zw(rT),errors:Zw(M(j({message:A,type:Zw(A)})))}),lU=D(`GitHub.queryGraphql`)(function*(e,t,n,r,i,a){let o=_B(`${gH}/graphql`).pipe(NB({query:r,variables:i}),vH(t.value)),s=yield*e.execute(o).pipe(sg(e=>yH(n,e))),c=yield*rp;if(s.status!==200)return yield*kH(n,s,c);let l=yield*LB(cU)(s).pipe(sg(e=>SH(n,e.message)));if(l.errors!==void 0&&l.errors.length>0){if(l.errors.some(e=>e.type===`RATE_LIMITED`))return yield*new pH({operation:n,retryAt:P_(vr(OH(s.headers,c),()=>c+sU)),message:`GitHub GraphQL API rate limit exceeded`});if(!l.errors.every(e=>e.type===`NOT_FOUND`))return yield*SH(n,`GraphQL errors: ${l.errors.map(e=>e.message).join(`; `)}`)}return yield*zw(a)(l.data).pipe(sg(e=>SH(n,e.message)))}),uU=L.check(BT(1)),dU=L.check(BT(0)),fU=A.check(MT(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u,{message:`Expected a GitHub UTC timestamp`})),pU=(e,t)=>F(e).pipe(bT(e,{decode:ib(e=>e??t),encode:ib(e=>e)})),mU={totalCount:0,nodes:[]},hU=j({login:R}),gU=F(hU),_U=j({totalCount:dU,nodes:M(j({name:R}))}),vU=j({actor:F(j({login:R,type:R})),createdAt:fU}),yU=pT(A,vU).pipe(TT(C({}))),bU=j({totalCount:dU,nodes:M(j({author:gU,body:A,createdAt:fU}))}),xU=j({number:uU,title:A,body:A,url:R,state:A,stateReason:F(A),createdAt:fU,updatedAt:fU,closedAt:F(fU),author:gU,issueType:F(j({name:A})),milestone:F(j({title:A})),labels:pU(_U,mU),labelEvents:yU,assignees:j({totalCount:dU,nodes:M(hU)}),comments:bU,closedByPullRequestsReferences:pU(j({totalCount:dU,nodes:M(j({number:uU,state:A,isDraft:sT,url:R}))}),mU)}),SU=F(j({login:Zw(R)})),CU=j({author:gU,state:A,body:A,submittedAt:F(fU),commit:F(j({oid:R}))}),wU=j({author:gU,body:A}),TU=j({number:uU,title:A,body:A,url:R,state:A,isDraft:sT,merged:sT,createdAt:fU,updatedAt:fU,mergedAt:F(fU),author:gU,baseRefName:UH,headRefName:A,headRefOid:R,additions:dU,deletions:dU,changedFiles:dU,reviewDecision:F(A),mergeable:A.pipe(TT(C(`UNKNOWN`))),mergeStateStatus:A.pipe(TT(C(`UNKNOWN`))),statusCheckRollup:F(j({state:A})),labels:pU(_U,mU),labelEvents:yU,reviewRequests:pU(j({totalCount:dU,nodes:M(j({requestedReviewer:SU}))}),mU),reviews:pU(j({totalCount:dU,nodes:M(CU)}),mU),reviewThreads:j({totalCount:dU,nodes:M(j({isResolved:sT,isOutdated:sT,path:A,comments:j({totalCount:dU,nodes:M(wU)})}))}),comments:bU,closingIssuesReferences:pU(j({totalCount:dU,nodes:M(j({number:uU,state:A}))}),mU)}),EU=A.check(MT(/^[a-f0-9]{64}$/u,{message:`Expected a SHA-256 content hash`})).pipe(I(`GitHubContentHash`)),DU=class extends V(`@usine/github/IssueSnapshot`)(`IssueSnapshot`,{payload:xU,contentHash:EU}){},OU=class extends V(`@usine/github/PullRequestSnapshot`)(`PullRequestSnapshot`,{payload:TU,contentHash:EU}){};N([DU,OU]);var kU=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
|
-
`,AU=`
|
|
43
|
-
query UsineLabelEvents($owner: String!, $name: String!, $number: Int!, $before: String!) {
|
|
44
|
-
repository(owner: $owner, name: $name) {
|
|
45
|
-
issueOrPullRequest(number: $number) {
|
|
46
|
-
... on Issue { ${kU(`$before`)} }
|
|
47
|
-
... on PullRequest { ${kU(`$before`)} }
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
`,jU=`
|
|
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
|
-
${kU(`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
|
-
`,MU=`
|
|
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
|
-
${kU(`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
|
-
`,NU=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
|
-
`},PU=10,FU=j({pageInfo:j({hasPreviousPage:sT,startCursor:F(R)}),nodes:M(F(j({...vU.fields,label:j({name:R})})))}),IU=j({repository:_E(j({issueOrPullRequest:_E(j({timelineItems:FU}))}))}),LU=D(`GitHubPolling.labelEvents`)(function*(e,t,n,r,i){yield*E({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>=PU||s.pageInfo.startCursor===null){if(yield*Xg(`Cannot complete current label provenance`,{repository:t,item:n,pages:c,missingLabels:[...a]}),s.pageInfo.startCursor===null)return yield*SH(`fetch-item-timeline`,`GitHub returned hasPreviousPage for label events without a startCursor`);break}yield*k(`Reading older events for current labels`,{repository:t,item:n,pages:c,missingLabels:[...a]});let r=yield*e.app.installationToken(),{owner:i,name:l}=Jk(t),u=yield*lU(e.http,r,`fetch-item-timeline`,AU,{owner:i,name:l,number:n,before:s.pageInfo.startCursor},IU);if(b(u.repository))return yield*SH(`fetch-item-timeline`,`repository "${t}" is null`);let d=u.repository.value.issueOrPullRequest;if(b(d))return yield*new hH({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*Xg(`GitHub has no label event for some current labels`,{repository:t,item:n,missingLabels:[...a]})),yield*k(`Read current label provenance`,{repository:t,item:n,pages:c,labels:o.size}),Object.fromEntries(o)}),RU=new Set([`closedAt`,`createdAt`,`mergedAt`,`submittedAt`,`updatedAt`]),zU=e=>Array.isArray(e)?e.map(zU):Rw(FE)(e)?Object.fromEntries(Object.entries(e).filter(([e,t])=>!RU.has(e)||!te(t)&&t!==null).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,zU(t)])):e,BU=5e3,VU=100,HU=10,UU=100,WU=50,GU=M(j({number:L.check(BT(1)),updatedAt:gE,pullRequest:Zw(rT)}).pipe(fT({updatedAt:`updated_at`,pullRequest:`pull_request`}))),KU=j({object:j({sha:Kk})}),qU=M(j({name:ZH,color:QH,description:F(A)})),JU=({name:e,color:t,description:n})=>new $H({name:e,color:t,description:xr(n)}),YU=j({repository:_E(j({issue:_E(j({...xU.fields,timelineItems:FU}))}))}),XU=j({repository:_E(j({pullRequest:_E(j({...TU.fields,timelineItems:FU}))}))}),ZU=F(j({number:L})),QU=e=>j({repository:_E(j(Object.fromEntries(Array.from({length:e},(e,t)=>[`i${t}`,ZU]))))}),$U=e=>F_(e),eW=e=>e.map(e=>e.pullRequest===void 0?new KH({number:e.number,updatedAt:e.updatedAt}):new qH({number:e.number,updatedAt:e.updatedAt})),tW=e=>{let t=e.flatMap(e=>_r(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?v():$U(Math.max(...t))},nW=(e,t)=>tW([wH(e[`retry-after`],t),TH(e,VU)]),rW=(e,t)=>tW([EH(e,t),wH(e[`retry-after`],t),TH(e,VU)]),iW=e=>{let t=H_(e)-BU;return`${new Date(t-t%1e3).toISOString().slice(0,19)}Z`},aW=(e,t)=>{let{name:n,owner:r}=Jk(e),i=new URL(`${gH}/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`),x(t.watermark)&&i.searchParams.set(`since`,iW(t.watermark.value)),i.toString()},oW=e=>{let{name:t,owner:n}=Jk(e),r=new URL(`${gH}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`);return r.searchParams.set(`per_page`,`100`),r.toString()},sW=(e,t)=>{let{name:n,owner:r}=Jk(e),i=t.split(`/`).map(encodeURIComponent).join(`/`);return`${gH}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/git/ref/heads/${i}`},cW=(e,t)=>{let{name:n,owner:r}=Jk(e),i=new URL(`${gH}/repos/${encodeURIComponent(r)}/${encodeURIComponent(n)}/issues/${t}/labels`);return i.searchParams.set(`per_page`,`100`),i.toString()},lW=(e,t)=>{let n=t.map(({updatedAt:e})=>H_(e));return x(e.watermark)&&n.push(H_(e.watermark.value)),n.length===0?v():$U(Math.max(...n))},uW=class e extends Lr()(`@usine/github/GitHubPolling`){static layer=qf(e,w(function*(){let e=yield*VH,t=yield*WO,n=yield*XB,r=dW(t),i=D(`GitHubPolling.execute`)(function*(e,t){return yield*n.execute(t).pipe(sg(t=>yH(e,t)))}),a=D(`GitHubPolling.changesPage`)(function*(t){let n=yield*e.installationToken(),r=gB(t).pipe(vH(n.value)),a=yield*i(`poll-repository-changes`,r),o=yield*rp;return a.status===200?{items:eW(yield*LB(GU)(a).pipe(sg(e=>SH(`poll-repository-changes`,e.message)))),next:AH(a.headers.link)}:yield*kH(`poll-repository-changes`,a,o)}),o=D(`GitHubPolling.labelsPage`)(function*(t,n){let r=yield*e.installationToken(),a=gB(n).pipe(vH(r.value)),o=yield*i(t,a),s=yield*rp;return o.status===200?{labels:(yield*LB(qU)(o).pipe(sg(e=>SH(t,e.message)))).map(JU),next:AH(o.headers.link)}:yield*kH(t,o,s)}),s=D(`GitHubPolling.remainingLabelPages`)(function*(e,t){let n=[...t.labels],r=t.next,i=1;for(;x(r)&&i<UU;){let t=yield*o(e,r.value);n.push(...t.labels),r=t.next,i+=1}return x(r)?yield*SH(e,`the GitHub label list has more than ${UU} pages`):n.sort((e,t)=>e.name.localeCompare(t.name))}),c=D(`GitHubPolling.allLabels`)(function*(e,t){return yield*s(e,yield*o(e,t))}),l=D(`GitHubPolling.labels`)(function*(t,n){yield*E({repository:t});let r=yield*e.installationToken(),a=gB(oW(t)).pipe(vH(r.value));x(n)&&(a=xB(a,`if-none-match`,n.value));let o=yield*i(`list-repository-labels`,a),c=yield*rp;if(o.status===304)return new nU;if(o.status!==200)return yield*kH(`list-repository-labels`,o,c);let l=yield*LB(qU)(o).pipe(sg(e=>SH(`list-repository-labels`,e.message))),u=yield*s(`list-repository-labels`,{labels:l.map(JU),next:AH(o.headers.link)}),d=Vw(HH)(o.headers.etag);return b(d)&&(yield*Xg(`GitHub omitted the label catalog ETag; next poll is unconditional`,{repository:t})),new tU({entityTag:d,labels:u})}),u=D(`GitHubPolling.changes`)(function*(t,n){let r=yield*e.installationToken(),o=gB(aW(t,n)).pipe(vH(r.value));x(n.entityTag)&&(o=xB(o,`if-none-match`,n.entityTag.value));let s=yield*i(`poll-repository-changes`,o),c=yield*rp,l=rW(s.headers,c);if(s.status===304)return new YH({cursor:n,nextPollAt:l,backoffUntil:nW(s.headers,c)});if(s.status!==200)return yield*kH(`poll-repository-changes`,s,c);let u=eW(yield*LB(GU)(s).pipe(sg(e=>SH(`poll-repository-changes`,e.message)))),d=Vw(HH)(s.headers.etag);b(d)&&(yield*Xg(`GitHub omitted the changes ETag; next poll is unconditional`,{repository:t}));let f=[...u],p=AH(s.headers.link),m=1;for(;x(p)&&m<HU;){let e=yield*a(p.value);f.push(...e.items),p=e.next,m+=1}let h=x(p);return h&&(yield*O(`GitHub changes walk hit the page cap; backlog remains`,{repository:t,pages:m,items:f.length})),new XH({cursor:new GH({entityTag:d,watermark:lW(n,f)}),items:f,backlog:h,nextPollAt:l,backoffUntil:nW(s.headers,c)})}),d=D(`GitHubPolling.baseRefHead`)(function*(t,n,r){yield*E({repository:t,baseRefName:n});let a=yield*e.installationToken(),o=gB(sW(t,n)).pipe(vH(a.value)),s=Or(r,({entityTag:e})=>e);x(s)&&(o=xB(o,`if-none-match`,s.value));let c=yield*i(`fetch-base-ref-head`,o),l=yield*rp;if(c.status===304&&x(r))return r.value;if(c.status!==200)return yield*kH(`fetch-base-ref-head`,c,l);let u=yield*LB(KU)(c).pipe(sg(e=>SH(`fetch-base-ref-head`,e.message))),d=Vw(HH)(c.headers.etag);return b(d)&&(yield*Xg(`GitHub omitted the base branch ETag; next read is unconditional`,{repository:t,baseRefName:n})),new WH({baseRefName:n,sha:u.object.sha,entityTag:d})}),f=D(`GitHubPolling.graphql`)(function*(t,r,i,a,o){let s=yield*e.installationToken(),{name:c,owner:l}=Jk(r);return yield*lU(n,s,t,a,{owner:l,name:c,number:i},o)});return{changes:u,labels:l,baseRefHead:d,snapshot:D(`GitHubPolling.snapshot`)((t,i)=>w(function*(){let a=e=>SH(e,`repository "${t}" is null: deleted, renamed, or no longer accessible`),o=(e,n)=>new hH({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=D(`GitHubPolling.completeItemLabels`)(function*(e){if(e.labels.nodes.length>=e.labels.totalCount)return e.labels;yield*k(`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`,cW(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,jU,YU);if(b(c.repository))return yield*a(`fetch-issue-snapshot`);let l=c.repository.value.issue;if(b(l))return yield*o(`fetch-issue-snapshot`,`issue`);let{timelineItems:u,...d}=l.value,p=yield*s(d),m={...d,labels:p,labelEvents:yield*LU({http:n,app:e},t,i.number,p.nodes,u)};return new DU({payload:m,contentHash:yield*r(m)})}let l=yield*f(`fetch-pull-request-snapshot`,t,i.number,MU,XU);if(b(l.repository))return yield*a(`fetch-pull-request-snapshot`);let u=l.repository.value.pullRequest;if(b(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*LU({http:n,app:e},t,i.number,m.nodes,d)};return new OU({payload:h,contentHash:yield*r(h)})})),missingIssues:D(`GitHubPolling.missingIssues`)(function*(t,r){yield*E({repository:t,issues:r.length});let{name:i,owner:a}=Jk(t);return(yield*Ah(la(r,WU),r=>w(function*(){let o=yield*e.installationToken(),s=yield*lU(n,o,`find-missing-issues`,NU(r.length),{owner:a,name:i,...Object.fromEntries(r.map((e,t)=>[`n${t}`,e]))},QU(r.length));if(b(s.repository))return yield*SH(`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=>D(`GitHubPolling.contentHash`)(function*(t){let n=new TextEncoder().encode(JSON.stringify(zU(t))),r=yield*e.digest(`SHA-256`,n).pipe(cg);return EU.make(Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``))}),fW=class extends B(`@usine/orchestrator/LabelPreflightFinding`)({repository:H,label:hA,errorTag:R,message:R}){},pW=(e,t)=>{let n=[];if(x(e.color)){let r=e.color.value.toLowerCase();_r(t.color,{onNone:()=>!0,onSome:e=>e.toLowerCase()!==r})&&n.push(`color`)}if(x(e.description)){let r=e.description.value;_r(t.description,{onNone:()=>!0,onSome:e=>e!==r})&&n.push(`description`)}return n},mW=e=>new rU({name:ZH.make(e.name),color:Dr(e.color,QH.make),description:e.description}),hW=class e extends Lr()(`@usine/orchestrator/LabelReconciler`){static layer=qf(e,w(function*(){let e=yield*oU;return{reconcile:D(`LabelReconciler.reconcile`)(function*(t,n,r){yield*E({repository:t});let i=[...r],a=new Map(r.map(e=>[gA(e.name),e])),o=[],s=!1,c=v();for(let r of n){let n=a.get(gA(r.name));if(n!==void 0){let e=pW(r,n);e.length>0?yield*Xg(`Declared GitHub label differs from the existing repository label; left unchanged`,{repository:t,label:r.name,drift:e.join(`, `)}):yield*k(`Declared GitHub label already exists`,{repository:t,label:r.name});continue}let l=yield*Yh(e.create(t,mW(r)));if(Ei(l)){let e=l.failure;if(o.push(new fW({repository:t,label:r.name,errorTag:e._tag,message:e.message})),e._tag===`GitHubRateLimitError`){c=y(e.retryAt),yield*Xg(`Label creation rate-limited; remaining declarations deferred and trigger evaluation continues`,{repository:t,label:r.name,errorTag:e._tag,message:e.message,retryAt:G_(e.retryAt)});break}yield*Zg(`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 vz({name:l.success.name,color:y(l.success.color),description:l.success.description});i.push(u),a.set(gA(u.name),u),s=!0,yield*O(`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}})}}))},gW=e=>A.check(MT(/\S/u,{message:e})),_W=e=>jT(t=>new Set(t.map(t=>Yk(e(t)))).size===t.length,{message:`Expected unique repository names, ignoring case`}),vW=gW(`Expected a non-blank lane name`).pipe(I(`LaneName`)),yW=P([`issue-open`,`issue-closed`,`pr-open`,`pr-closed`,`pr-merged`]),bW=P([`issue-closed`,`pr-closed`,`pr-merged`]),xW=Rw(bW),SW=e=>xW(e),CW=class extends B(`@usine/config/LabelLaneSource`)({label:hA}){},wW=N([CW,class extends B(`@usine/config/StateLaneSource`)({state:yW}){}]),TW=class extends B(`@usine/config/Lane`)({name:vW,sources:M(wW).check(GT())}){},EW=class extends B(`RunAgain`)(LM({from:yN,requestedBy:_E(NM)})){},DW=class extends V(`@usine/orchestrator/GitHubPushFailureView`)(`GitHubPushFailure`,{message:A}){},OW=class extends V(`@usine/orchestrator/InfraFailureView`)(`InfraFailure`,{message:A}){},kW=class extends V(`@usine/orchestrator/ProviderCapacityFailureView`)(`ProviderCapacityFailure`,{message:A}){},AW=class extends V(`@usine/orchestrator/DefectFailureView`)(`DefectFailure`,{message:A}){},jW=class extends V(`@usine/orchestrator/AgentFailureView`)(`AgentFailure`,{message:A}){},MW=class extends V(`@usine/orchestrator/BlockedFailureView`)(`BlockedFailure`,{message:A}){},NW=class extends V(`@usine/orchestrator/QuestionFailureView`)(`QuestionFailure`,{question:A}){},PW=class extends V(`@usine/orchestrator/RunawayFailureView`)(`RunawayFailure`,{ceiling:JP}){},FW=class extends V(`@usine/orchestrator/ChildSessionBudgetFailureView`)(`ChildSessionBudgetFailure`,{maxChildren:gP,attemptedChildren:_P}){},IW=N([DW,OW,kW,AW,jW,MW,NW,PW,FW]),LW=class extends V(`@usine/orchestrator/SucceededAttemptView`)(`Succeeded`,{}){},RW=class extends V(`@usine/orchestrator/FailedAttemptView`)(`Failed`,{failure:IW}){},zW=class extends V(`@usine/orchestrator/CanceledAttemptView`)(`Canceled`,{}){},BW=N([LW,RW,zW]),VW=class extends V(`@usine/orchestrator/LocalWorkerAccess`)(`Local`,{}){},HW=class extends V(`@usine/orchestrator/SshWorkerAccess`)(`Ssh`,{destination:PN,port:F(FN)}){},UW=class extends V(`@usine/orchestrator/ProvisionedWorkerAccess`)(`Provisioned`,{provider:QN}){},WW=class extends V(`@usine/orchestrator/SandboxWorkerAccess`)(`Sandbox`,{}){},GW=N([VW,HW,UW,WW]),KW=class extends B(`@usine/orchestrator/AttemptView`)({id:pF,number:mF,worker:kN,workerAccess:F(GW),brain:iA,task:gF,agent:aA,operatorIntervened:sT,startedAt:A,outcome:F(BW),endedAt:F(A),salvage:F(iF),start:F(fF).pipe(CT(C(null))),reattachedAt:F(A).pipe(CT(C(null))),outOfMemory:F(xF).pipe(CT(C(null)))}){},qW=jN.make(`exe-dev-github-integration[bot]`),JW=A.check(MT(/^[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`));A.check(MT(/^\/[^\0\r\n]*$/u,{message:`Expected an absolute remote home directory without control bytes`})).pipe(I(`ExeDevHomePath`)),B(`@usine/executor/ExeDevGitHubIntegration`)({repository:H,name:JW}),L.check(BT(1)).pipe(I(`ExeDevCredentialGrantMinutes`));var YW=(e,t)=>{switch(e){case`local`:case`ssh`:case`cloudflare`:return t;case`exe.dev`:return qW}},XW=P([`preflight`,`prepare`,`launch`,`cancel`,`cleanup`]),ZW=P([`machine`,`toolchain`,`memory`,`harness-login`,`credentials`,`gateway`,`container`,`provider`]),QW=class extends jE(`@usine/executor/ExecutorOperationError`)(`ExecutorOperationError`,{operation:XW,message:R,cause:QT()}){},$W=P([`refused`,`unreachable`]),eG=class extends jE(`@usine/executor/CredentialUnavailableError`)(`CredentialUnavailableError`,{repository:H,reason:$W,message:R,cause:QT()}){},tG=class extends jE(`@usine/executor/WorkerCapabilityError`)(`WorkerCapabilityError`,{worker:kN,capability:ZW,message:R,cause:QT()}){},nG=P([`capacity`,`quota`,`refused`,`provider`,`unreachable`,`timeout`]);jE(`@usine/executor/MachineUnavailableError`)(`MachineUnavailableError`,{worker:kN,provider:QN,reason:nG,message:R}),N([QW,eG,tG]),B(`@usine/executor/CheckoutRequest`)({attemptId:pF,worker:kN,repository:H,loop:uA,permissions:mA,revision:Gk,payload:PE,task:gF,agent:sA,parentModel:z(tA),maxChildren:gP,maxAttemptMinutes:z(L.check(zT(0))),maxAttemptTokens:z(L.check(zT(0))),parentEffort:rA,salvageRef:tF,resume:z(rF),reattach:sT.pipe(CT(C(!1))),botLogin:z(jN).pipe(CT(C(v()))),commitAuthor:NN});var rG=R.pipe(I(`WorktreePath`));B(`@usine/executor/AttemptWorkspace`)({worker:kN,spec:RF,worktree:rG});var iG=Aw(e=>mv(e)&&te(_v(e)),{expected:`Redacted<string>`});B(`@usine/executor/WorkerCredential`)({value:iG,expiresAt:hE}),Lr()(`@usine/executor/CredentialProvider`),Lr()(`@usine/executor/Executor`);var aG=R.pipe(I(`MachineHold`)),oG=class extends B(`@usine/executor/MachineCheck`)({brains:M(iA),containerLimits:z(qN)}){};B(`@usine/executor/MachineGrant`)({hold:aG,id:$N,worker:kN,provider:QN,checked:z(oG)});var sG=P([`creating`,`ready`,`deleting`]);B(`@usine/executor/MachineStatus`)({worker:kN,provider:QN,state:sG,id:z($N),runId:z(yN),attemptId:z(pF),since:hE}),Lr()(`@usine/executor/WorkerMachines`);var cG=class extends B(`@usine/orchestrator/MachineQuotaWait`)({worker:kN,message:A}){},lG=e=>new Map(e.flatMap(e=>_r(e.quota,{onNone:()=>[],onSome:t=>e.waitingRuns.map(n=>[n,new cG({worker:e.worker,message:t})])}))),uG=class extends B(`@usine/orchestrator/MachineView`)({worker:kN,provider:QN,state:sG,id:F($N),runId:F(yN),attemptId:F(pF),since:A}){},dG=class extends B(`@usine/orchestrator/ProvisioningPauseView`)({reason:N([nG,tT(`check`)]),message:A,failures:L,failedAt:A,retryAt:A,blocked:sT}){},fG=class extends V(`@usine/orchestrator/HetznerProvisionerView`)(`hetzner`,{tokenEnv:A,serverType:eP,location:tP,image:nP,network:F(rP),firewall:F(rP).pipe(CT(C(null))),sshKey:rP,sshUser:oP,labels:pT(A,A),anthropicKeyEnv:F(A),openaiKeyEnv:F(A)}){},pG=class extends V(`@usine/orchestrator/BoatProvisionerView`)(`boat`,{tokenEnv:A,size:sP,anthropicKeyEnv:F(A),openaiKeyEnv:F(A)}){},mG=N([fG,pG]),hG=e=>new uG({worker:e.worker,provider:e.provider,state:e.state,id:S(e.id),runId:S(e.runId),attemptId:S(e.attemptId),since:G_(e.since)}),gG=e=>new dG({reason:e.reason,message:e.message,failures:e.failures,failedAt:G_(e.failedAt),retryAt:G_(e.retryAt),blocked:e.blocked}),_G=e=>_r(e.provisioner,{onNone:()=>null,onSome:e=>e.provider===`hetzner`?new fG({tokenEnv:e.tokenEnv,serverType:e.serverType,location:e.location,image:e.image,network:S(e.network),firewall:S(e.firewall),sshKey:e.sshKey,sshUser:e.sshUser,labels:e.labels,anthropicKeyEnv:S(e.apiKeys.anthropic),openaiKeyEnv:S(e.apiKeys.openai)}):new pG({tokenEnv:e.tokenEnv,size:e.size,anthropicKeyEnv:S(e.apiKeys.anthropic),openaiKeyEnv:S(e.apiKeys.openai)})}),vG=L.check(BT(1)).pipe(I(`TranscriptSequence`)),yG=P([3,4]),bG=j({...cI.fields,version:yG}),xG=j({_tag:tT(`InboundEnvelope`),version:yG,attemptId:pF,sequence:FF,sentAt:gE,payload:N([WF,GF])}),SG=P([5,6]),CG=N([uI,j({...cI.fields,version:SG}),j({...lI.fields,version:SG}),bG,xG]),wG=class extends B(`@usine/engine/TranscriptEntry`)({sequence:vG,attemptId:pF,direction:LF,envelope:CG,receivedAt:hE}){},TG=class extends V(`@usine/engine/TranscriptAllQuery`)(`TranscriptAllQuery`,{attemptId:pF}){},EG=class extends V(`@usine/engine/TranscriptSessionsQuery`)(`TranscriptSessionsQuery`,{attemptId:pF}){},DG=class extends V(`@usine/engine/TranscriptWorkerQuery`)(`TranscriptWorkerQuery`,{attemptId:pF}){},OG=class extends V(`@usine/engine/TranscriptUsageQuery`)(`TranscriptUsageQuery`,{attemptId:pF}){},kG=class extends V(`@usine/engine/TranscriptTailQuery`)(`TranscriptTailQuery`,{attemptId:pF,after:vG,limit:L.check(BT(1))}){},AG=class extends V(`@usine/engine/TranscriptPageQuery`)(`TranscriptPageQuery`,{attemptId:pF,before:z(vG),limit:L.check(BT(1))}){};N([TG,EG,DG,OG,kG,AG]);var jG=class extends V(`@usine/orchestrator/FailedTranscriptView`)(`Failed`,{failure:IW}){},MG=N([zF,BF,VF,jG,UF,WF,GF,qF,JF,KF,nI,rI,iI,aI]),NG=class extends B(`@usine/orchestrator/TranscriptEventView`)({sequence:vG,attemptId:pF,receivedAt:A,direction:LF,target:Zw($F),operator:Zw(R),payload:MG}){},PG=class extends B(`@usine/orchestrator/TranscriptPageCursor`)({attemptId:pF,before:vG}){},FG=class extends V(`@usine/orchestrator/ColdTranscriptRequest`)(`ColdTranscriptRequest`,{}){},IG=class extends V(`@usine/orchestrator/TailTranscriptRequest`)(`TailTranscriptRequest`,{after:vG}){},LG=class extends V(`@usine/orchestrator/EarlierTranscriptRequest`)(`EarlierTranscriptRequest`,{attemptId:pF,before:vG}){};N([FG,IG,LG]);var RG=class extends jE(`@usine/orchestrator/TranscriptAttemptNotFoundError`)(`TranscriptAttemptNotFoundError`,{runId:yN,attemptId:pF}){},zG=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}]]),BG=(e,t)=>Dr(xr(zG.get(e)),e=>OP.make((t.input*e.input+t.cachedInput*e.cachedInput+t.cacheWrite*(e.cacheWrite??e.input)+t.output*e.output)/1e6)),VG=class extends B(`@usine/engine/RunSnapshot`)({event:BM,itemKey:dI,run:bN,step:ON,attempts:M(wF),resolvedFailureAttemptId:z(pF),closedAt:z(hE),approval:z(CI),runAgain:z(EW),repository:H,revision:Gk,task:gF,agent:sA,parentModel:z(tA),permissions:mA}){},HG=class extends B(`@usine/engine/RunEvent`)({runId:yN,event:BM}){},UG=class extends B(`@usine/engine/RunEvidence`)({snapshot:VG,transcript:M(wG)}){},WG=class extends B(`@usine/engine/RunSummary`)({itemKey:dI,run:bN,step:ON,attempts:M(wF),resolvedFailureAttemptId:z(pF),closedAt:z(hE),approval:z(CI),runAgain:z(EW),repository:H,task:gF,agent:sA}){},GG=class extends B(`@usine/engine/WorkerAttempts`)(j({worker:kN,attempts:L.check(BT(1)),running:L.check(BT(0))}).check(jT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},KG=class extends B(`@usine/engine/LoopSighting`)({loop:uA,itemKey:dI,event:z(RM),run:z(yN),suppressedBy:z(yN)}){},qG=L.check(BT(0)).pipe(I(`ProjectionRevision`)),JG=j({eventId:RM,dedupKey:zM,payload:PE,receivedAt:gE,itemKey:dI,loop:uA,step:DN,approval:fA,permissions:mA,cycleLimit:F(pI),cycleGeneration:mI,repository:H,revision:Gk,task:gF,agent:sA,parentModel:F(tA)}),YG=j({itemKey:dI,repository:H,revision:Gk,task:gF,agent:sA,parentModel:F(tA),runId:yN,eventId:RM,loop:uA,state:$M,resolvedFailureAttemptId:F(pF),openedAt:gE,closedAt:F(gE),stepName:DN,result:F(EN),approvedAt:F(gE),approvalChannel:F(xI),approver:F(NM),againFrom:F(yN),againRequestedBy:F(NM)}),XG=j({attemptId:pF,runId:yN,stepName:DN,worker:kN,number:mF,brain:iA,task:gF,agent:aA,operatorIntervened:sT,parentModel:F(tA),startedAt:gE,outcome:F(eF),endedAt:F(gE),salvage:F(iF),start:F(fF),failureResolution:F(yF),reattachedAt:F(gE),comments:F(M(wN)),outOfMemory:F(M(SF))}),ZG=j({sequence:vG,attemptId:pF,direction:LF,envelope:wG.fields.envelope,receivedAt:gE}),QG=j({runId:yN}),$G=j({reason:zR}),eK=j({revision:qG}),tK=j({runId:yN,eventId:RM,dedupKey:zM,payload:PE,receivedAt:gE}),nK=j({...JG.fields,reopening:L}),rK=j({eventId:RM,dedupKey:zM}),iK=zw(M(JG)),aK=zw(M(nK)),oK=zw(M(rK)),sK=zw(M(YG)),cK=zw(M(tK)),lK=zw(M(XG)),uK=zw(M(QG)),dK=zw(M($G)),fK=zw(M(eK)),pK=zw(M(ZG)),mK=Jw(PE),hK=Jw(gE),gK=Jw($M),_K=Jw(eF),vK=Jw(iF),yK=Jw(M(wN)),bK=Jw(M(SF)),xK=zw(M(j({outOfMemory:F(M(SF))}))),SK=Jw(yF),CK=Jw(fF),wK=zw(M(j({nextStart:F(dF)}))),TK=Jw(EN),EK=Jw(uI),DK=Jw(sA),OK=Jw(iA),kK=Rw(fz),AK=e=>t=>sg(t,t=>kK(t)?t:new uz({operation:e,cause:t})),jK=e=>new BM({id:e.eventId,dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),MK=e=>new HG({runId:e.runId,event:jK(e)}),NK=e=>new MR({event:jK(e),itemKey:e.itemKey,loop:e.loop,step:e.step,approval:e.approval,permissions:e.permissions,cycleLimit:xr(e.cycleLimit),cycleGeneration:e.cycleGeneration,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:xr(e.parentModel)}),PK=e=>new bN({id:e.runId,eventId:e.eventId,loop:e.loop,state:e.state,openedAt:e.openedAt}),FK=e=>Dr(xr(e.approvedAt),t=>new CI({approvedAt:t,source:Dr(xr(e.approvalChannel),t=>new SI({channel:t,approver:xr(e.approver)}))})),IK=e=>Dr(xr(e.againFrom),t=>new EW({from:t,requestedBy:xr(e.againRequestedBy)})),LK=e=>new ON({runId:e.runId,name:e.stepName,result:xr(e.result)}),RK=e=>new wF({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:xr(e.parentModel),startedAt:e.startedAt,outcome:xr(e.outcome),endedAt:xr(e.endedAt),salvage:xr(e.salvage),start:xr(e.start),failureResolution:xr(e.failureResolution),reattachedAt:xr(e.reattachedAt),comments:e.comments??[],outOfMemory:Nr(e.outOfMemory??[],Xi).pipe(Dr(CF))}),zK=(e,t)=>new WG({itemKey:e.itemKey,run:PK(e),step:LK(e),attempts:t.map(RK),resolvedFailureAttemptId:xr(e.resolvedFailureAttemptId),closedAt:xr(e.closedAt),approval:FK(e),runAgain:IK(e),repository:e.repository,task:e.task,agent:e.agent}),BK=e=>new wG({sequence:e.sequence,attemptId:e.attemptId,direction:e.direction,envelope:e.envelope,receivedAt:e.receivedAt}),VK=qj($.leftoversDiscardedAt),HK=qj($.outcomeJson),UK=e=>{let t=D(`RunStoreQueries.attemptCountsByWorker`)(function*(){let t=yield*e.select({worker:$.workerName,attempts:J`count(*)`,running:J`sum(case when ${HK} then 1 else 0 end)`}).from($).where(VK).groupBy($.workerName).orderBy(aM($.workerName)).execute();return yield*zw(M(GG))(t)});return{attemptCountsByWorker:t,openAttempts:D(`RunStoreQueries.openAttempts`)(function*(e){return(yield*t()).find(t=>t.worker===e)?.running??0}),discardLeftovers:D(`RunStoreQueries.discardLeftovers`)(function*(t,n){return(yield*e.update($).set({leftoversDiscardedAt:hK(n)}).where(Rj(Y($.workerName,t),VK)).returning({attemptId:$.attemptId}).execute()).map(({attemptId:e})=>e)})}},WK={itemKey:KR.itemKey,repository:KR.repository,generation:KR.generation,ask:KR.askJson,resetPending:KR.resetPending},GK=zw(M(rR),{onExcessProperty:`error`}),KK=e=>{let t=Y(Z.cycleGeneration,J`coalesce((
|
|
185
|
-
select ${KR.generation} from ${KR}
|
|
186
|
-
where ${KR.itemKey} = ${Z.itemKey}
|
|
187
|
-
), 0)`),n=D(`CycleBudget.get`)(function*(t){return yield*E({itemKey:t}),xr((yield*e.select(WK).from(KR).where(Y(KR.itemKey,t)).execute().pipe(T(GK)))[0])}),r=D(`CycleBudget.counts`)(function*(t){yield*E({itemKey:t.itemKey,generation:t.generation});let n=Yj(e.select({id:$.attemptId}).from($).where(Y($.runId,Q.runId))),r=J`json_extract(${Q.stateJson}, '$._tag')`,i=yield*e.select({loop:qR.loop,admitted:J`count(*)`,completed:J`sum(case when ${Kj(r,[...sN])} and ${n} then 1 else 0 end)`}).from(qR).innerJoin(Q,Y(Q.runId,qR.runId)).where(Rj(Y(qR.itemKey,t.itemKey),Y(qR.generation,t.generation),zj(Ij(r,`Canceled`),n))).groupBy(qR.loop).orderBy(aM(qR.loop)).execute();return yield*zw(M(_I))(i,{onExcessProperty:`error`})});return{admit:D(`CycleBudget.admit`)(function*(t){yield*E({itemKey:t.itemKey,loop:t.loop});let i=yield*n(t.itemKey);if(x(i)&&x(i.value.ask))return yield*O(`Item cycle budget remains exhausted`,{itemKey:t.itemKey,askId:i.value.ask.value.id,loop:t.loop}),i.value.ask;if(b(t.cycleLimit))return v();yield*e.insert(KR).values({itemKey:t.itemKey,repository:t.repository}).onConflictDoNothing().execute();let a=yield*n(t.itemKey);if(b(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 v();let c=new yI({id:vI.make(RM.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(KR).set({askJson:Jw(yI)(c)}).where(Y(KR.itemKey,t.itemKey)).execute(),yield*Xg(`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}),y(c)}),reserve:D(`CycleBudget.reserve`)(function*(t,i){if(b(t.cycleLimit))return;yield*E({runId:i,itemKey:t.itemKey,loop:t.loop});let a=yield*n(t.itemKey);if(b(a))return yield*Hh(Error(`Run admitted without its cycle budget`));yield*e.insert(qR).values({runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation}).onConflictDoNothing().execute(),yield*O(`Item cycle reserved`,{runId:i,itemKey:t.itemKey,loop:t.loop,generation:a.value.generation,counts:yield*r(a.value)})}),get:n,asks:D(`CycleBudget.asks`)(function*(){return(yield*e.select(WK).from(KR).where(Jj(KR.askJson)).execute().pipe(T(GK))).flatMap(({ask:e})=>jr(e))}),pendingResets:D(`CycleBudget.pendingResets`)(function*(){return yield*e.select(WK).from(KR).where(Y(KR.resetPending,!0)).execute().pipe(T(GK))}),isCurrentEvent:D(`CycleBudget.isCurrentEvent`)(function*(e){yield*E({eventId:e.event.id,itemKey:e.itemKey});let t=_r(yield*n(e.itemKey),{onNone:()=>0,onSome:e=>e.generation}),r=e.cycleGeneration===t;return r||(yield*O(`Event observation was superseded by a cycle reset`,{eventId:e.event.id,itemKey:e.itemKey,observedGeneration:e.cycleGeneration,generation:t})),r}),currentEvent:t}},qK=zw(M(j({observedEventId:F(RM),suppressedByRunId:F(yN),suppressedEventId:F(RM)}))),JK=zw(M(j({loop:uA,itemKey:dI,observedEventId:F(RM),suppressedByRunId:F(yN)}))),YK=zw(M(j({eventId:RM,reopensEventId:RM}))),XK=zw(M(j({eventId:RM,runId:yN}))),ZK=e=>{let t=(e,t)=>Rj(Y(GR.loopName,e),Y(GR.itemKey,t)),n=D(`LoopItems.row`)(function*(n,r){return xr((yield*qK(yield*e.select({observedEventId:GR.observedEventId,suppressedByRunId:GR.suppressedByRunId,suppressedEventId:GR.suppressedEventId}).from(GR).where(t(n,r)).execute()))[0])});return{sighted:D(`LoopItems.sighted`)(function*(t,r,i){let a=Dr(yield*n(t,r),({observedEventId:e})=>xr(e));return yield*e.insert(GR).values({loopName:t,itemKey:r,observedEventId:i}).onConflictDoUpdate({target:[GR.loopName,GR.itemKey],set:{observedEventId:i}}).execute(),a}),unmatched:D(`LoopItems.unmatched`)(function*(n,r){yield*e.update(GR).set({observedEventId:null,suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),suppression:D(`LoopItems.suppression`)(function*(e,t){return Or(yield*n(e,t),({suppressedByRunId:e,suppressedEventId:t})=>e===null?v():y({runId:e,suppressedEventId:xr(t)}))}),startSuppression:D(`LoopItems.startSuppression`)(function*(t,r,i,a,o){if(Fr(yield*n(t,r),({observedEventId:e})=>e===null))return!1;let s=S(o);return yield*e.insert(GR).values({loopName:t,itemKey:r,observedEventId:a,suppressedByRunId:i,suppressedEventId:s}).onConflictDoUpdate({target:[GR.loopName,GR.itemKey],set:{suppressedByRunId:i,suppressedEventId:s}}).execute(),!0}),suppressFrom:D(`LoopItems.suppressFrom`)(function*(n,r,i){yield*e.update(GR).set({suppressedEventId:i}).where(Rj(t(n,r),Jj(GR.suppressedByRunId))).execute()}),lift:D(`LoopItems.lift`)(function*(n,r){yield*e.update(GR).set({suppressedByRunId:null,suppressedEventId:null}).where(t(n,r)).execute()}),liftRun:D(`LoopItems.liftRun`)(function*(t){return(yield*e.update(GR).set({suppressedByRunId:null,suppressedEventId:null}).where(Y(GR.suppressedByRunId,t)).returning({loopName:GR.loopName}).execute()).length>0}),sightings:D(`LoopItems.sightings`)(function*(t){let n=[...new Set(t)];if(n.length===0)return[];let r=(yield*Ah(la(n,100),t=>e.select({loop:GR.loopName,itemKey:GR.itemKey,observedEventId:GR.observedEventId,suppressedByRunId:GR.suppressedByRunId}).from(GR).where(Gj(GR.itemKey,t)).execute().pipe(T(JK)))).flat(),i=[...new Set(r.flatMap(({observedEventId:e})=>e===null?[]:[e]))],a=(yield*Ah(la(i,100),t=>e.select({eventId:Z.eventId,reopensEventId:Z.reopensEventId}).from(Z).where(Gj(Z.reopensEventId,t)).orderBy(oM(Z.reopening)).execute().pipe(T(YK)))).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*Ah(la(i.map(s),100),t=>e.select({eventId:Q.eventId,runId:Q.runId}).from(Q).where(Gj(Q.eventId,t)).execute().pipe(T(XK)))).flat().map(({eventId:e,runId:t})=>[e,t]));return r.map(({loop:e,itemKey:t,observedEventId:n,suppressedByRunId:r})=>{let i=Dr(xr(n),s);return new KG({loop:e,itemKey:t,event:i,run:Or(i,e=>xr(c.get(e))),suppressedBy:xr(r)})})})}},QK=e=>({appendTranscript:D(`RunStoreQueries.appendTranscript`)(function*(t,n,r){return(yield*e.insert(ZR).values({attemptId:n.attemptId,direction:t,channelSequence:n.sequence,envelope:EK(n),receivedAt:hK(r)}).onConflictDoNothing().returning({sequence:ZR.sequence}).execute()).length>0}),transcript:D(`RunStoreQueries.transcript`)(function*(t){yield*E({attemptId:t.attemptId,query:t._tag});let n=wk(t,{TranscriptWorkerQuery:({attemptId:e})=>Rj(Y(ZR.attemptId,e),Y(ZR.direction,`outbound`),J`json_extract(${ZR.envelope}, '$.payload._tag') IN ('WorkerUnresponsive', 'WorkerResponsive')`),TranscriptSessionsQuery:({attemptId:t})=>Gj(ZR.sequence,e.select({sequence:J`max(${ZR.sequence})`}).from(ZR).where(Rj(Y(ZR.attemptId,t),J`(
|
|
188
|
-
json_extract(${ZR.envelope}, '$.payload._tag') = 'InterventionApplied'
|
|
189
|
-
OR (json_extract(${ZR.envelope}, '$.payload._tag') = 'SessionEvent'
|
|
190
|
-
AND json_extract(${ZR.envelope}, '$.payload.event._tag') IN ('SessionStarted', 'SessionIdle', 'SessionResumed', 'SessionFinished'))
|
|
191
|
-
)`)).groupBy(J`coalesce(json_extract(${ZR.envelope}, '$.payload.event.session.id'), json_extract(${ZR.envelope}, '$.payload.intervention.target.sessionId'), '@parent')`,J`json_extract(${ZR.envelope}, '$.payload._tag')`,J`json_extract(${ZR.envelope}, '$.payload.event._tag') = 'SessionStarted'`)),TranscriptUsageQuery:({attemptId:t})=>{let n=e.select({sequence:ZR.sequence,tokens:J`max(json_extract(${ZR.envelope}, '$.payload.event.totalTokens'))`.as(`tokens`)}).from(ZR).where(Rj(Y(ZR.attemptId,t),J`json_extract(${ZR.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${ZR.envelope}, '$.payload.event._tag') = 'SessionTokensUpdated'`)).groupBy(J`json_extract(${ZR.envelope}, '$.payload.event.session.id')`).as(`highest`);return Gj(ZR.sequence,e.select({sequence:n.sequence}).from(n))},TranscriptAllQuery:({attemptId:e})=>Y(ZR.attemptId,e),TranscriptTailQuery:({attemptId:e,after:t})=>Rj(Y(ZR.attemptId,e),Vj(ZR.sequence,t)),TranscriptPageQuery:({attemptId:e,before:t})=>_r(t,{onNone:()=>Y(ZR.attemptId,e),onSome:t=>Rj(Y(ZR.attemptId,e),Uj(ZR.sequence,t))})}),r=e.select({sequence:ZR.sequence,attemptId:ZR.attemptId,direction:ZR.direction,envelope:ZR.envelope,receivedAt:ZR.receivedAt}).from(ZR).where(n);return(yield*pK(yield*wk(t,{TranscriptWorkerQuery:()=>r.orderBy(oM(ZR.sequence)).limit(1).execute(),TranscriptSessionsQuery:()=>r.orderBy(aM(ZR.sequence)).execute(),TranscriptUsageQuery:()=>r.orderBy(aM(ZR.sequence)).execute(),TranscriptAllQuery:()=>r.orderBy(aM(ZR.sequence)).execute(),TranscriptTailQuery:({limit:e})=>r.orderBy(aM(ZR.sequence)).limit(e).execute(),TranscriptPageQuery:({limit:e})=>r.orderBy(oM(ZR.sequence)).limit(e).execute()}),{onExcessProperty:`error`})).map(BK).sort((e,t)=>e.sequence-t.sequence)})}),$K=(e,t)=>H_(t.openedAt)-H_(e.openedAt)||t.runId.localeCompare(e.runId),eq={eventId:WR.eventId,dedupKey:WR.dedupKey,payload:WR.payloadJson,receivedAt:WR.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},tq=QL(WR,`approval_event`),nq={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:XR.stepName,result:XR.result,approvedAt:tq.receivedAt,approvalChannel:QR.channel,approver:QR.approver,againFrom:$R.fromRunId,againRequestedBy:$R.requestedBy},rq={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},iq=J`json_extract(${Q.stateJson}, '$._tag')`,aq=Gj(iq,[...sN]),oq=Gj(iq,[...lN]),sq=e=>Ww(PE)(DK(e)),cq=e=>{let t=D(`RunStoreQueries.eventRouteByDedup`)(function*(t){return yield*iK(yield*e.select(eq).from(WR).innerJoin(Z,Y(Z.eventId,WR.eventId)).where(Y(WR.dedupKey,t)).execute())}),n=D(`RunStoreQueries.eventRouteByRun`)(function*(t){return yield*iK(yield*e.select(eq).from(Q).innerJoin(WR,Y(WR.eventId,Q.eventId)).innerJoin(Z,Y(Z.eventId,WR.eventId)).where(Y(Q.runId,t)).execute())}),r=()=>e.select(nq).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).innerJoin(XR,Y(XR.runId,Q.runId)).leftJoin(QR,Y(QR.runId,Q.runId)).leftJoin(tq,Y(tq.eventId,QR.eventId)).leftJoin($R,Y($R.eventId,Q.eventId)),i=D(`RunStoreQueries.runRows`)(function*(e){return yield*sK(yield*r().where(Y(Q.runId,e)).execute())}),a=(...t)=>w(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(Rj(qj($.leftoversDiscardedAt),...t)).execute();return(yield*zw(M(j({attemptId:pF,worker:kN,repository:H,runId:yN,loop:uA,itemKey:dI,number:mF,permissions:mA,outcome:A,salvage:F(iF)})))(n)).map(({number:e,outcome:t,salvage:n,...r})=>({...r,ref:nF(r.runId,e),succeeded:t===`Succeeded`,open:t===``,rejected:n?._tag===`Rejected`?y(n):v()}))}),o=D(`RunStoreQueries.salvageCandidates`)(function*(){return yield*a()}),s=D(`RunStoreQueries.salvageCandidate`)(function*(e){return yield*E({attemptId:e}),ea(yield*a(Y($.attemptId,e)))}),c=D(`RunStoreQueries.attemptRows`)(function*(t){return yield*lK(yield*e.select(rq).from($).where(Y($.runId,t)).orderBy($.attemptNumber).execute())}),l=D(`RunStoreQueries.snapshot`)(function*(e){let[t,r,a]=yield*kh([i(e),c(e),n(e)]),o=t[0],s=a[0];return o===void 0||s===void 0?yield*new sz({runId:e}):new VG({event:jK(s),itemKey:s.itemKey,run:PK(o),step:LK(o),attempts:r.map(RK),resolvedFailureAttemptId:xr(o.resolvedFailureAttemptId),closedAt:xr(o.closedAt),approval:FK(o),runAgain:IK(o),repository:o.repository,revision:o.revision,task:o.task,agent:o.agent,parentModel:xr(o.parentModel),permissions:s.permissions})}),u=D(`RunStoreQueries.summariesWithAttempts`)(function*(t){let n=ua((yield*Ah(la(t.map(({runId:e})=>e),100),t=>e.select(rq).from($).where(Gj($.runId,t)).orderBy(aM($.runId),aM($.attemptNumber)).execute().pipe(T(lK)))).flat(),({runId:e})=>e);return t.map(e=>zK(e,n[e.runId]??[]))}),d=D(`RunStoreQueries.itemRunSummaries`)(function*(e){if(e.length===0)return[];let t=(yield*Ah(la([...new Set(e)],100),e=>r().where(Gj(Z.itemKey,e)).execute().pipe(T(sK)))).flat().sort($K);return yield*u(t)}),f=D(`RunStoreQueries.runSummaries`)(function*(e){let[t,n]=yield*kh([r().where(aq).orderBy(oM(Q.openedAt),oM(Q.runId)).execute().pipe(T(sK)),r().where(Kj(iq,[...sN])).orderBy(oM(Q.openedAt),oM(Q.runId)).limit(e).execute().pipe(T(sK))]),i=[...t,...n].sort($K);return yield*u(i)}),p=D(`RunStoreQueries.runEvents`)(function*(t){return(yield*Ah(la([...new Set(t)],100),t=>e.select({runId:Q.runId,eventId:WR.eventId,dedupKey:WR.dedupKey,payload:WR.payloadJson,receivedAt:WR.receivedAt}).from(Q).innerJoin(WR,Y(WR.eventId,Q.eventId)).where(Gj(Q.runId,t)).execute().pipe(T(cK)))).flat().map(MK)}),m=D(`RunStoreQueries.closedRunSummaries`)(function*(e){let t=yield*r().where(Kj(iq,[...sN])).orderBy(oM(Q.closedAt),oM(Q.runId)).limit(e).execute().pipe(T(sK));return yield*u(t)}),h=D(`RunStoreQueries.closedRunSummariesSince`)(function*(e){let t=Kj(iq,[...sN]),n=yield*r().where(_r(e,{onNone:()=>t,onSome:e=>Rj(t,Hj(Q.closedAt,hK(e)))})).orderBy(oM(Q.closedAt),oM(Q.runId)).execute().pipe(T(sK));return yield*u(n)}),g=D(`RunStoreQueries.projectionRevision`)(function*(){return xr((yield*fK(yield*e.select({revision:oz.revision}).from(oz).where(Y(oz.singleton,1)).limit(1).execute()))[0]?.revision)}),_=D(`RunStoreQueries.updateState`)(function*(t,n,r){let i=nN(n)?null:hK(r??(yield*I_));if((yield*e.update(Q).set({stateJson:gK(n),closedAt:i}).where(Y(Q.runId,t)).returning({runId:Q.runId}).execute()).length===0)return yield*new sz({runId:t})}),ee=D(`RunStoreQueries.resolveFailure`)(function*(t,n,r){yield*E({runId:t,attemptId:n}),yield*e.update($).set({failureResolutionJson:SK(r)}).where(Y($.attemptId,n)).execute(),yield*e.update(Q).set({resolvedFailureAttemptId:n}).where(Y(Q.runId,t)).execute()}),te=D(`RunStoreQueries.addAttempt`)(function*(t){yield*e.insert($).values({attemptId:t.id,runId:t.runId,stepName:t.stepName,workerName:t.worker,attemptNumber:t.number,brainJson:OK(t.brain),task:t.task,agent:t.agent,operatorIntervened:t.operatorIntervened,parentModel:S(t.parentModel),startedAt:hK(t.startedAt),outcomeJson:null,endedAt:null,salvageJson:null,startJson:_r(t.start,{onNone:()=>null,onSome:CK})}).execute()}),ne=D(`RunStoreQueries.recordReattach`)(function*(t,n){yield*E({attemptId:t}),yield*e.update($).set({reattachedAt:hK(n)}).where(Y($.attemptId,t)).execute()}),re=D(`RunStoreQueries.nextStart`)(function*(t){return xr((yield*wK(yield*e.select({nextStart:Q.nextStartJson}).from(Q).where(Y(Q.runId,t)).execute()))[0]?.nextStart)}),ie=D(`RunStoreQueries.setNextStart`)(function*(t,n){yield*e.update(Q).set({nextStartJson:_r(n,{onNone:()=>null,onSome:CK})}).where(Y(Q.runId,t)).execute()}),ae=D(`RunStoreQueries.recordSalvage`)(function*(t,n){yield*E({attemptId:t,salvage:n._tag}),yield*e.update($).set({salvageJson:vK(n)}).where(Y($.attemptId,t)).execute(),n._tag===`Retained`&&x(n.pushFailure)&&(yield*e.update($).set({outcomeJson:_K(new QP({failure:n.pushFailure.value}))}).where(Rj(Y($.attemptId,t),J`json_extract(${$.outcomeJson}, '$._tag') = 'Failed'`,J`json_extract(${$.outcomeJson}, '$.failure._tag') != 'GitHubPushFailure'`)).execute())}),oe=D(`RunStoreQueries.recordComments`)(function*(t,n){yield*E({attemptId:t,comments:n.length}),yield*e.update($).set({commentsJson:yK(n)}).where(Y($.attemptId,t)).execute()}),se=D(`RunStoreQueries.recordOutOfMemory`)(function*(t,n){yield*E({attemptId:t,container:n.container,kills:n.kills});let r=qi(((yield*xK(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:bK(r)}).where(Y($.attemptId,t)).execute(),CF(r)}),ce=D(`RunStoreQueries.closeAttempt`)(function*(t,n,r){yield*e.update($).set({outcomeJson:_K(n),endedAt:hK(r)}).where(Rj(Y($.attemptId,t),qj($.outcomeJson))).execute()}),le=D(`RunStoreQueries.amend`)(function*(t,n){yield*E({runId:t,agent:n.agent.name}),yield*e.update(Q).set({task:n.task,agentJson:sq(n.agent),parentModel:S(n.parentModel)}).where(Y(Q.runId,t)).execute()}),ue=D(`RunStoreQueries.markIntervened`)(function*(t){yield*E({attemptId:t}),yield*e.update($).set({operatorIntervened:!0}).where(Y($.attemptId,t)).execute()}),de=D(`RunStoreQueries.updateAttemptParentModel`)(function*(t,n){yield*e.update($).set({parentModel:n}).where(Y($.attemptId,t)).execute()}),fe=D(`RunStoreQueries.updateStepResult`)(function*(t,n,r){yield*e.update(XR).set({result:TK(r)}).where(Rj(Y(XR.runId,t),Y(XR.stepName,n))).execute()}),pe=D(`RunStoreQueries.approvalExists`)(function*(t){return(yield*e.$count(QR,Y(QR.runId,t)).execute())>0}),me=D(`RunStoreQueries.recordApproval`)(function*(t,n,r){yield*e.insert(WR).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:mK(n.payload),receivedAt:hK(n.receivedAt)}).onConflictDoNothing().execute(),yield*e.insert(QR).values({runId:t,eventId:n.id,channel:r.channel,approver:S(r.approver)}).execute()}),he=D(`RunStoreQueries.createRun`)(function*(t,n,r){let i=QL(Z,`candidate`),a=QL(Q,`candidate_run`),o=QL(ez,`ignored`);yield*e.insert(ez).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(Rj(Y(i.loopName,t.loop),Y(i.itemKey,t.itemKey),Ij(i.eventId,n),qj(a.runId),qj(o.eventId)))).onConflictDoNothing().execute(),yield*e.insert(Q).values({runId:r,eventId:n,loopName:t.loop,stateJson:gK(new GM),openedAt:hK(t.event.receivedAt),repository:t.repository,revision:t.revision,task:t.task,agentJson:sq(t.agent),parentModel:S(t.parentModel)}).onConflictDoNothing().execute(),yield*e.insert(XR).values({runId:r,stepName:t.step,result:null}).onConflictDoNothing().execute()}),ge=D(`RunStoreQueries.runForEvent`)(function*(t){return yield*uK(yield*e.select({runId:Q.runId}).from(Q).where(Y(Q.eventId,t)).execute())}),_e=D(`RunStoreQueries.ignoredEvent`)(function*(t){return yield*dK(yield*e.select({reason:ez.reason}).from(ez).where(Y(ez.eventId,t)).execute())}),ve=D(`RunStoreQueries.blockingRun`)(function*(t,n){return yield*uK(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(Rj(Y(Z.loopName,t),Y(Z.itemKey,n),aq)).orderBy(oM(Q.openedAt)).limit(1).execute())}),ye=D(`RunStoreQueries.newestReopening`)(function*(t){return Dr(xr((yield*aK(yield*e.select({...eq,reopening:Z.reopening}).from(WR).innerJoin(Z,Y(Z.eventId,WR.eventId)).where(Y(Z.reopensEventId,t)).orderBy(oM(Z.reopening)).limit(1).execute()))[0]),e=>({submission:NK(e),reopening:e.reopening}))}),be=D(`RunStoreQueries.reopenedEvent`)(function*(t){let n=QL(WR,`reopened_event`);return xr((yield*oK(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])}),xe=D(`RunStoreQueries.recordRunAgain`)(function*(t,n){yield*e.insert($R).values({eventId:t,fromRunId:n.from,requestedBy:S(n.requestedBy)}).execute()}),Se=D(`RunStoreQueries.recordTriggerEvent`)(function*(n,r=v()){yield*e.insert(WR).values({eventId:n.event.id,dedupKey:n.event.dedupKey,payloadJson:mK(n.event.payload),receivedAt:hK(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:S(n.cycleLimit),cycleGeneration:n.cycleGeneration,repository:n.repository,revision:n.revision,task:n.task,agentJson:sq(n.agent),parentModel:S(n.parentModel),reopensEventId:S(Dr(r,({eventId:e})=>e)),reopening:_r(r,{onNone:()=>0,onSome:({reopening:e})=>e})}).execute(),n):NK(i)}),Ce=D(`RunStoreQueries.nextQueued`)(function*(t){let r=(yield*n(t))[0];if(r===void 0)return v();let i=yield*ZK(e).suppression(r.loop,r.itemKey);if(x(i))return yield*O(`Queued Events wait while a suppression keeps the Item`,{runId:t,suppressedBy:i.value.runId,loop:r.loop,itemKey:r.itemKey}),v();let a=yield*iK(yield*e.select(eq).from(WR).innerJoin(Z,Y(Z.eventId,WR.eventId)).leftJoin(Q,Y(Q.eventId,WR.eventId)).leftJoin(ez,Y(ez.eventId,WR.eventId)).where(Rj(Y(Z.loopName,r.loop),Y(Z.itemKey,r.itemKey),KK(e).currentEvent,qj(Q.runId),qj(ez.eventId))).orderBy(oM(WR.receivedAt)).execute());return xr(a[0]).pipe(Dr(e=>({submission:NK(e),eventIds:a.map(e=>e.eventId)})))}),we=D(`RunStoreQueries.runIdsToDrive`)(function*(){return(yield*uK(yield*e.select({runId:Q.runId}).from(Q).where(Rj(aq,Ij(iq,`Waiting`))).execute())).map(({runId:e})=>e)}),Te=D(`RunStoreQueries.pendingContinuations`)(function*(){let t=yield*e.selectDistinct({loop:Z.loopName,itemKey:Z.itemKey}).from(Z).leftJoin(Q,Y(Q.eventId,Z.eventId)).leftJoin(ez,Y(ez.eventId,Z.eventId)).leftJoin(KR,Y(KR.itemKey,Z.itemKey)).leftJoin(GR,Rj(Y(GR.loopName,Z.loopName),Y(GR.itemKey,Z.itemKey))).where(Rj(qj(Q.runId),qj(ez.eventId),qj(KR.askJson),qj(GR.suppressedByRunId),KK(e).currentEvent)).execute();return(yield*Ah(yield*zw(M(j({loop:uA,itemKey:dI})))(t),({loop:t,itemKey:n})=>w(function*(){return(yield*ve(t,n)).length>0?[]:yield*uK(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(Rj(Y(Z.loopName,t),Y(Z.itemKey,n))).orderBy(oM(Q.openedAt),oM(Q.runId)).limit(1).execute())}))).flat().map(({runId:e})=>e)}),Ee=D(`RunStoreQueries.revokeQueued`)(function*(t,n,r){let i=QL(Z,`candidate`),a=QL(Q,`candidate_run`);return(yield*e.insert(ez).select(e.select({eventId:i.eventId,reason:J`'revoked'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).where(Rj(Y(i.loopName,t),Y(i.itemKey,n),Gj(i.eventId,r),qj(a.runId)))).onConflictDoNothing().returning({eventId:ez.eventId}).execute()).length}),De=D(`RunStoreQueries.revokeUnstarted`)(function*(t,n){let r=yield*uK(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(Rj(Y(Z.loopName,t),Y(Z.itemKey,n),oq)).execute()),i=e.select({eventId:Z.eventId}).from(Z).where(Rj(Y(Z.loopName,t),Y(Z.itemKey,n)));return yield*Ee(t,n,i),r});return{salvageCandidates:o,salvageCandidate:s,cycles:KK(e),loopItems:ZK(e),...QK(e),addAttempt:te,recordReattach:ne,nextStart:re,setNextStart:ie,recordSalvage:ae,recordComments:oe,recordOutOfMemory:se,amend:le,markIntervened:ue,approvalExists:pe,blockingRun:ve,closeAttempt:ce,createRun:he,eventRouteByRun:n,ignoredEvent:_e,newestReopening:ye,nextQueued:Ce,reopenedEvent:be,recordRunAgain:xe,pendingContinuations:Te,recordTriggerEvent:Se,runIdsToDrive:we,recordApproval:me,revision:g,revokeQueued:Ee,revokeUnstarted:De,runSummaries:f,closedRunSummaries:m,closedRunSummariesSince:h,itemRunSummaries:d,runEvents:p,runForEvent:ge,snapshot:l,updateStepResult:fe,updateAttemptParentModel:de,updateState:_,resolveFailure:ee}},lq=w(function*(){let e=yield*hz,t=cq(e),n=D(`RunReader.inspect`)(e=>t.snapshot(e).pipe(AK(`read run`))),r=D(`RunReader.evidence`)(function*(t){yield*E({runId:t});let n=yield*e.transaction(e=>w(function*(){let n=cq(e),r=yield*n.snapshot(t);return new UG({snapshot:r,transcript:(yield*Ah(r.attempts,({id:e})=>n.transcript(new TG({attemptId:e})))).flat().sort((e,t)=>e.sequence-t.sequence)})})).pipe(AK(`read run evidence`));return yield*k(`Run evidence read`,{runId:t,attempts:n.snapshot.attempts.length,transcriptRows:n.transcript.length}),n}),i=D(`RunReader.list`)(e=>t.runSummaries(e.closedLimit).pipe(AK(`list runs`))),a=D(`RunReader.closed`)(e=>t.closedRunSummaries(e.limit).pipe(AK(`list closed runs`))),o=D(`RunReader.closedSince`)(e=>t.closedRunSummariesSince(e).pipe(AK(`list runs closed since a time`))),s=D(`RunReader.revision`)(()=>t.revision().pipe(AK(`read projection revision`)));return{inspect:n,evidence:r,list:i,closed:a,closedSince:o,forItems:D(`RunReader.forItems`)(e=>t.itemRunSummaries(e).pipe(AK(`read item run histories`))),events:D(`RunReader.events`)(e=>t.runEvents(e).pipe(AK(`read the events of runs`))),revision:s,transcript:D(`RunReader.transcript`)(e=>t.transcript(e).pipe(AK(`read attempt transcript`))),latestPoolRateLimits:D(`RunReader.latestPoolRateLimits`)(function*(){let t=yield*e.select({event:J`json_extract(${ZR.envelope}, '$.payload.event')`}).from(ZR).where(Gj(ZR.sequence,e.select({sequence:J`max(${ZR.sequence})`}).from(ZR).where(Rj(Y(ZR.direction,`outbound`),J`json_extract(${ZR.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${ZR.envelope}, '$.payload.event._tag') = 'PoolRateLimitsUpdated'`)).groupBy(J`json_extract(${ZR.envelope}, '$.payload.event.pool')`))).execute(),n=yield*zw(M(j({event:rE(RP)})))(t,{onExcessProperty:`error`});return yield*E({pools:n.map(({event:e})=>e.pool)}),yield*k(`Read latest pool rate limits`,{pools:n.map(({event:e})=>e.pool)}),n.map(({event:e})=>e)},AK(`read latest pool rate limits`)),attemptsByWorker:D(`RunReader.attemptsByWorker`)(()=>UK(e).attemptCountsByWorker().pipe(AK(`count attempts by worker`))),sightings:D(`RunReader.sightings`)(e=>t.loopItems.sightings(e).pipe(AK(`read loop sightings`)))}}),uq=class e extends Lr()(`@usine/engine/RunReader`){static layer=qf(e,lq)},dq=class extends B(`@usine/orchestrator/UsageCostView`)({usd:OP,estimate:sT}){},fq=class extends B(`@usine/orchestrator/SessionUsageView`)({attemptId:pF,session:vP,pool:MP,tokens:mP,cost:F(dq)}){},pq=class extends B(`@usine/orchestrator/PoolUsageView`)({pool:MP,tokens:mP,cost:F(dq)}){},mq=class extends B(`@usine/orchestrator/RunUsageView`)({tokens:mP,pools:M(pq),sessions:M(fq)}){},hq=class extends B(`@usine/orchestrator/TaskPoolUsageView`)({pool:MP,tokens:mP,cost:F(dq),unpriced:sT}){},gq=class extends B(`@usine/orchestrator/TaskUsageView`)({durationMillis:L.check(BT(0)),runningSince:M(A),unmeasured:L.check(BT(0)),tokens:mP,pools:M(hq),cost:F(dq)}){},_q=[`apiKeys`,`claudePlan`,`chatgptPlan`],vq=(e,t)=>_r(t,{onNone:()=>null,onSome:t=>new dq({usd:t,estimate:e!==`apiKeys`})}),yq=({session:e,costUsd:t,breakdown:n})=>x(t)||e.brain.harness!==`codex`?t:Or(n,t=>BG(e.brain.model,t)),bq=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:yq(e.report)})),r=n.map(({attemptId:e,report:t,price:n})=>{let r=PP(t.session);return new fq({attemptId:e,session:t.session,pool:r,tokens:t.totalTokens,cost:vq(r,n)})}),i=new Set(n.flatMap(({report:e,price:t})=>b(t)&&e.session.brain.harness===`codex`&&x(e.breakdown)?[e.session.brain.model]:[])),a=_q.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 pq({pool:e,tokens:mP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:vq(e,n.length===t.length?y(OP.make(n.reduce((e,t)=>e+t,0))):v())})]});return{view:new mq({tokens:mP.make(r.reduce((e,{tokens:t})=>e+t,0)),pools:a,sessions:r}),unknownModels:i}},xq=(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=_q.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 hq({pool:e,tokens:mP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:vq(e,n.length===0?v():y(OP.make(n.reduce((e,t)=>e+t,0)))),unpriced:n.length<t.length})]}),s=o.flatMap(({cost:e})=>e===null?[]:[e]);return new gq({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:OP.make(s.reduce((e,{usd:t})=>e+t,0)),estimate:s.some(({estimate:e})=>e)})})},Sq=w(function*(){let e=yield*uq,t=yield*Fh(()=>new Map),n=yield*Fh(()=>new Set),r=D(`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 OG({attemptId:n.id}));return x(n.outcome)&&t.set(n.id,i),{reports:i,read:!0}});return{read:D(`RunUsageReader.read`)(function*(e){yield*E({runId:e.run.id});let t=yield*Ah(e.attempts,r,{concurrency:4}),{view:i,unknownModels:a}=bq(t.flatMap(({reports:e})=>e));for(let t of a)n.has(t)||(n.add(t),yield*Xg(`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*k(`Read Run usage`,{runId:e.run.id,sessions:i.sessions.length,tokens:i.tokens,attemptsRead:t.filter(({read:e})=>e).length,attemptsCached:t.filter(({read:e})=>!e).length}),i})}});(class e extends Lr()(`@usine/orchestrator/RunUsageReader`){static layer=qf(e,Sq)});var Cq=P(cN),wq=F(A),Tq=class extends B(`@usine/orchestrator/EditAndRetry`)({task:gF,agent:aA}){},Eq=class extends B(`@usine/orchestrator/SessionIntervention`)({attemptId:pF,target:$F.pipe(TT(C({_tag:`Parent`}))),action:YF}){};jE(`@usine/orchestrator/RosterAgentNotFoundError`)(`RosterAgentNotFoundError`,{agent:aA,message:A}),jE(`@usine/orchestrator/LoopNotFoundError`)(`LoopNotFoundError`,{loop:uA,message:A});var Dq=class extends B(`@usine/orchestrator/ApprovalView`)({approvedAt:A,source:F(SI)}){},Oq=class extends B(`@usine/orchestrator/RunView`)({id:yN,itemKey:dI,loop:uA,repository:H,agent:aA,agentBrain:iA,state:Cq,providerRetry:F(NF).pipe(TT(C(null)),CT(C(null))),machineWait:F(cG).pipe(TT(C(null)),CT(C(null))),loopPaused:sT,openedAt:A,closedAt:F(A),task:A,attempts:M(KW),approval:F(Dq),runAgain:F(EW),resultMessage:wq,pullRequestUrl:wq,canApprove:sT,canRetry:sT,canResolveFailure:sT,canCancel:sT,canRunAgain:sT}){},kq=L.check(BT(0)),Aq=L.check(BT(0)),jq=class extends B(`@usine/orchestrator/RunDurationView`)({endedMillis:kq,runningSince:F(A),unmeasured:Aq}){},Mq=class extends B(`@usine/orchestrator/UnconfirmedStopView`)({runId:yN,attemptNumber:mF,worker:kN}){},Nq=class extends B(`@usine/orchestrator/RunDetailView`)({run:Oq,agentDefinitionChanged:sT,eventDedupKey:A,eventPayload:PE,transcript:M(NG),sessionState:M(NG),earlierTranscript:M(PG),worker:F(kN).pipe(CT(C(null))),settledItemState:F(bW).pipe(CT(C(null))),duration:jq.pipe(CT(C(new jq({endedMillis:0,runningSince:null,unmeasured:0})))),usage:mq.pipe(CT(C(new mq({tokens:mP.make(0),pools:[],sessions:[]})))),unconfirmedStop:F(Mq).pipe(CT(C(null))),machine:F(uG).pipe(CT(C(null)))}){},Pq=R.pipe(I(`BoardLaneId`)),Fq=P([`authored`,`proposed`,`fallback`]),Iq=class extends B(`@usine/orchestrator/BoardItemLink`)({itemKey:dI,kind:P([`issue`,`pr`]),number:fI,title:A,url:R,state:yW}){},Lq=class extends B(`@usine/orchestrator/BoardPullRequestView`)({number:fI,url:R,state:P([`pr-open`,`pr-merged`])}){},Rq=class extends B(`@usine/orchestrator/BoardTaskView`)({...Iq.fields,repository:H,labels:M(hA),items:M(Iq).check(GT()),pullRequest:F(Lq),runs:M(Oq),run:F(Oq),needsYou:sT,conflicting:sT,loops:M(uA),usage:gq}){},zq={id:Pq,name:vW,sources:M(wW),origin:Fq,items:M(Rq)},Bq=class extends V(`@usine/orchestrator/WritableBoardLaneView`)(`WritableBoardLane`,{...zq,origin:tT(`authored`),labels:M(hA).check(GT())}){},Vq=class extends V(`@usine/orchestrator/ReadOnlyBoardLaneView`)(`ReadOnlyBoardLane`,zq){},Hq=N([Bq,Vq]),Uq=class extends jE(`@usine/orchestrator/BoardProjectionError`)(`BoardProjectionError`,{repository:H,itemKey:dI,message:R}){},Wq=class extends B(`@usine/orchestrator/BoardView`)({lanes:M(Hq),failures:M(Uq)}){},Gq=class extends B(`@usine/orchestrator/LabelView`)({name:hA,color:F(A),description:F(A)}){};B(`@usine/orchestrator/BoardMove`)({repository:H,item:fI,toLane:Pq});var Kq=class extends jE(`@usine/orchestrator/BoardProjectNotFoundError`)(`BoardProjectNotFoundError`,{repository:H}){get message(){return`Project "${this.repository}" was not found.`}},qq=class extends jE(`@usine/orchestrator/BoardItemNotFoundError`)(`BoardItemNotFoundError`,{repository:H,item:fI}){get message(){return`Item ${this.repository}#${this.item} was not found on the board.`}};jE(`@usine/orchestrator/BoardLaneNotFoundError`)(`BoardLaneNotFoundError`,{repository:H,lane:Pq}),jE(`@usine/orchestrator/BoardLaneReadOnlyError`)(`BoardLaneReadOnlyError`,{repository:H,lane:Pq});var Jq=A.check(MT(/^(?:[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`)),Yq=A.check(MT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected a CEL identifier`})),Xq=A.check(MT(/^[A-Za-z_][A-Za-z0-9_.]*$/u,{message:`Expected a CEL object-type name`})),Zq=e=>jT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:e}),Qq=class extends B(`@usine/expression/ObjectField`)({name:Yq,type:Jq,nullable:sT.pipe(CT(C(!1)))}){},$q=class extends B(`@usine/expression/ObjectType`)({name:Xq,fields:M(Qq).check(Zq(`Expected unique CEL object-field names`))}){},eJ=class extends B(`@usine/expression/Variable`)({name:Yq,type:Jq}){},tJ=class extends B(`@usine/expression/Environment`)({types:M($q).check(Zq(`Expected unique CEL object-type names`)),variables:M(eJ).check(Zq(`Expected unique CEL variable names`))}){},nJ=A.check(MT(/\S/u,{message:`Expected a non-blank CEL expression`})).pipe(I(`ExpressionSource`)),rJ=L.check(BT(0)),iJ=P([`check_failed`,`parse_error`,`type_error`,`unexpected_result_type`]),aJ=class extends jE(`@usine/expression/ExpressionCheckError`)(`ExpressionCheckError`,{source:nJ,code:iJ,message:R,position:z(rJ)}){},oJ=class extends jE(`@usine/expression/ExpressionEvaluationError`)(`ExpressionEvaluationError`,{source:nJ,message:R}){};N([aJ,oJ]),N([A,oT,cT,sT,iT]);var sJ=class extends Lr()(`@usine/expression/ExpressionEngine`){},cJ=R.pipe(I(`InstancePath`)),lJ=P([`expression`,`frontmatter`,`read`,`reference`,`schema`,`yaml`]),uJ=j({path:M(N([A,oT])),message:A,expression:Zw(nJ),position:Zw(L.check(BT(0)))}),dJ=class e extends jE(`@usine/config/ConfigFileError`)(`ConfigFileError`,{file:cJ,stage:lJ,expression:yE(nJ),message:R,details:Zw(M(uJ))}){static fromSchema(t,n){let r=zy()(n.issue).issues.map(({path:e,message:t})=>({path:(e??[]).map(e=>Ck(e).pipe(Tk(Ek,e=>e),Tk(Dk,e=>e),Tk(Ok,String),kk(({key:e})=>String(e)))),message:t}));return new e({file:t,stage:`schema`,expression:v(),message:Ky()(n.issue),details:r})}};N([dJ,class extends jE(`@usine/config/FactoryConfigError`)(`FactoryConfigError`,{file:cJ,stage:lJ,message:R}){}]);var fJ=P([`latest`,`next`]),pJ=P([`off`,`propose`,`automatic`]),mJ=A.check(MT(/^(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`)),hJ=P([`idle`,`now`]),gJ={previous:mJ,target:mJ},_J=N([class extends B(`@usine/core/UpgradeInstalling`)({...gJ,status:tT(`installing`)}){},class extends B(`@usine/core/UpgradeGood`)({...gJ,status:tT(`good`)}){},class extends B(`@usine/core/UpgradeRolledBack`)({...gJ,status:tT(`rolled-back`),reason:R,failureStage:P([`install`,`health-check`,`unknown`]).pipe(TT(C(`unknown`)))}){},class extends B(`@usine/core/UpgradeFailed`)({...gJ,status:tT(`failed`),reason:R}){}]),vJ=e=>`label`in e?`label:${gA(e.label)}`:`state:${e.state}`,yJ=jT(e=>{let t=e.flatMap(({sources:e})=>e.map(vJ));return new Set(t).size===t.length},{message:`Expected each lane source in only one lane`}),bJ=M(TW).check(jT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique lane names`}),yJ),xJ=class extends B(`@usine/config/Project`)({id:Xk,name:gW(`Expected a project display name`),repositories:_T(H).check(_W(e=>e)),lanes:bJ.pipe(TT(C([])),CT(C([])))}){includes(e){return this.repositories.some(t=>Yk(t)===Yk(e))}},SJ=gW(`Expected a non-blank registry tag`).pipe(I(`RegistryTag`)),CJ=L.check(BT(1)),wJ=jT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique names`}),TJ=jT(e=>new Set(e.map(({name:e})=>gA(e))).size===e.length,{message:`Expected unique GitHub label names`}),EJ=M(yA).check(TJ),DJ=class extends B(`@usine/config/ManagedRepo`)({name:H,tags:M(SJ).check(JT()).pipe(TT(C([]))),lanes:bJ.pipe(TT(C([])))}){},OJ=CJ.pipe(TT(C(1))),kJ=class extends B(`@usine/config/LocalWorker`)({name:kN,kind:tT(`local`),maxConcurrentAttempts:OJ}){},AJ=class extends B(`@usine/config/ExeDevWorker`)({name:kN,kind:tT(`exe.dev`),maxConcurrentAttempts:OJ}){},jJ=A.check(MT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected an environment variable name`})).pipe(I(`EnvironmentVariableName`)),MJ=class extends B(`@usine/config/WorkerGateway`)({domain:RN,destination:PN,adminPort:zN.pipe(TT(C(7070))),adminTokenEnv:jJ,llmProviders:M(BN).check(JT()).pipe(TT(C([])))}){},NJ=class extends B(`@usine/config/WorkerContainer`)({image:yE(HN),cpus:yE(WN),memoryMib:yE(GN),pids:yE(KN)}){},PJ=class extends B(`@usine/config/ProviderApiKeys`)({anthropic:yE(jJ),openai:yE(jJ)}){}.pipe(TT(C({}))),FJ=fP.pipe(fT({sshWait:`ssh_wait`,creationBackoffMin:`creation_backoff_min`,creationBackoffMax:`creation_backoff_max`,machineCheckInterval:`machine_check_interval`}),TT(C({}))),IJ=class extends B(`@usine/config/HetznerProvisioner`)({provider:tT(`hetzner`),tokenEnv:jJ,serverType:eP,location:tP,image:nP,network:yE(rP),firewall:yE(rP),sshKey:rP,sshUser:oP.pipe(TT(C(`usine`))),labels:aP.pipe(TT(C({}))),apiKeys:PJ,timings:FJ}){},LJ=class extends B(`@usine/config/BoatTailnet`)({gatewayAddress:lP,clientIdEnv:jJ,clientSecretEnv:jJ}){},RJ=class extends B(`@usine/config/BoatProvisioner`)({provider:tT(`boat`),tokenEnv:jJ,size:sP.pipe(TT(C(`default`))),snapshot:yE(cP),tailnet:yE(LJ.pipe(fT({gatewayAddress:`gateway_address`,clientIdEnv:`client_id_env`,clientSecretEnv:`client_secret_env`}))),apiKeys:PJ,timings:FJ}){};N([IJ,RJ]);var zJ=N([IJ.pipe(fT({tokenEnv:`token_env`,serverType:`server_type`,sshKey:`ssh_key`,sshUser:`ssh_user`,apiKeys:`api_keys`})),RJ.pipe(fT({tokenEnv:`token_env`,apiKeys:`api_keys`}))]),BJ=class extends B(`@usine/config/SshWorker`)({name:kN,kind:tT(`ssh`),maxConcurrentAttempts:OJ,destination:yE(PN),provisioner:yE(zJ),identityFile:yE(IN),port:yE(FN),root:LN,gateway:yE(MJ.pipe(fT({adminPort:`admin_port`,adminTokenEnv:`admin_token_env`,llmProviders:`llm_providers`}))),container:NJ.pipe(fT({memoryMib:`memory_mib`}),TT(C({})))}){},VJ=e=>{let t=wr(e.provisioner);if(t===void 0)return b(e.destination)?`SSH worker "${e.name}" needs a destination or a provisioner`:void 0;if(x(e.destination))return`SSH worker "${e.name}" sets both destination and provisioner; a provisioned worker creates its machines, so remove destination`;if(x(e.port))return`SSH worker "${e.name}" sets port, which a provisioned worker takes from its provider`;switch(t.provider){case`hetzner`:return x(e.gateway)&&b(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 x(e.gateway)&&(b(t.tailnet)||b(t.snapshot))?`SSH worker "${e.name}" needs provisioner.tailnet and provisioner.snapshot to use a Boat gateway`:x(t.tailnet)&&b(e.gateway)?`SSH worker "${e.name}" sets provisioner.tailnet without a gateway`:b(e.identityFile)?`SSH worker "${e.name}" has a Boat provisioner and needs identity_file, whose .pub file usine adds to each sandbox`:void 0}},HJ=tE.check(jT(e=>e.protocol===`https:`,{message:`Expected an https URL`}),jT(e=>e.username===``&&e.password===``&&e.search===``&&e.hash===``&&e.pathname===`/`,{message:`Expected the Worker's origin, without a path, credentials, or query string`})),UJ=class extends B(`@usine/config/CloudflareLlmProviderKey`)({provider:ZN,apiKeyEnv:jJ}){},WJ=jT(e=>new Set(e.map(({provider:e})=>e)).size===e.length,{message:`Expected each provider once`}),GJ=class extends B(`@usine/config/CloudflareWorker`)({name:kN,kind:tT(`cloudflare`),maxConcurrentAttempts:OJ,workerUrl:HJ,accessClientIdEnv:jJ,accessClientSecretEnv:jJ,image:XN,instanceType:YN.pipe(TT(C(`standard-4`))),llmProviders:M(UJ.pipe(fT({apiKeyEnv:`api_key_env`}))).check(WJ).pipe(TT(C([])))}){},KJ=N([kJ,AJ,BJ,GJ]),qJ=class extends B(`@usine/config/Settings`)({upgradeChannel:fJ.pipe(TT(C(`latest`))),upgradeMode:pJ.pipe(TT(C(`propose`))),pollInterval:CJ.pipe(TT(C(60))),maxChildren:gP.pipe(TT(C(4))),maxAttemptMinutes:yE(CJ),maxAttemptTokens:yE(CJ),parentModel:yE(tA),parentEffort:yE(rA)}){},JJ=N([j({mode:tT(`off`)}),j({mode:tT(`deliveries`)}),j({mode:tT(`endpoint`),publicUrl:tE}).pipe(fT({publicUrl:`public_url`}))]),YJ=tE.check(jT(e=>e.protocol===`http:`||e.protocol===`https:`,{message:`Expected an http or https URL`}),jT(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`})),XJ=class extends B(`@usine/config/Tracing`)({otlpUrl:YJ,serviceName:gW(`Expected a non-blank service name`).pipe(TT(C(`usine`)))}){},ZJ=qJ.pipe(fT({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`})),QJ=N([kJ.pipe(fT({maxConcurrentAttempts:`max_concurrent_attempts`})),AJ.pipe(fT({maxConcurrentAttempts:`max_concurrent_attempts`})),BJ.pipe(fT({maxConcurrentAttempts:`max_concurrent_attempts`,identityFile:`identity_file`})).check(jT(e=>VJ(e)??!0)),GJ.pipe(fT({maxConcurrentAttempts:`max_concurrent_attempts`,workerUrl:`worker_url`,accessClientIdEnv:`access_client_id_env`,accessClientSecretEnv:`access_client_secret_env`,instanceType:`instance_type`,llmProviders:`llm_providers`}))]),$J=M(DJ).check(_W(e=>e.name)),eY=M(QJ).check(GT(),wJ),tY=class extends B(`@usine/config/UsineConfig`)(j({version:P([1,2]),projects:M(xJ).pipe(TT(C([])),CT(C([]))),labels:EJ.pipe(TT(C([]))),repos:$J,settings:ZJ.pipe(TT(C({}))),workers:eY.pipe(TT(C([{name:`local`,kind:`local`}]))),webhooks:JJ.pipe(TT(C({mode:`off`}))),operator:yE(NM),tracing:yE(XJ.pipe(fT({otlpUrl:`otlp_url`,serviceName:`service_name`})))}).check(jT(({version:e,projects:t,repos:n})=>{if(e===1)return t.length===0;let r=t.flatMap(({repositories:e})=>e.map(Yk)),i=new Set(n.map(({name:e})=>Yk(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`}))){},nY=Ww(Jq),rY=(e,t)=>new $q({name:e,fields:t.map(([e,t,n])=>new Qq({name:e,type:nY(t),nullable:n===`nullable`}))}),iY=rY(`Actor`,[[`login`,`string`]]),aY=rY(`LabelActor`,[[`login`,`string`],[`type`,`string`]]),oY=rY(`LabelEvent`,[[`actor`,`LabelActor`,`nullable`],[`createdAt`,`string`]]),sY=rY(`Label`,[[`name`,`string`]]),cY=rY(`Milestone`,[[`title`,`string`]]),lY=rY(`IssueType`,[[`name`,`string`]]),uY=rY(`Commit`,[[`oid`,`string`]]),dY=rY(`RepoContext`,[[`name`,`string`],[`owner`,`string`],[`url`,`string`]]),fY=rY(`Labels`,[[`totalCount`,`int`],[`nodes`,`list<Label>`]]),pY=rY(`Assignees`,[[`totalCount`,`int`],[`nodes`,`list<Actor>`]]),mY=rY(`IssueComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),hY=rY(`IssueComments`,[[`totalCount`,`int`],[`nodes`,`list<IssueComment>`]]),gY=rY(`PullRequestReference`,[[`number`,`int`],[`state`,`string`],[`isDraft`,`bool`],[`url`,`string`]]),_Y=rY(`PullRequestReferences`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestReference>`]]),vY=rY(`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`]]),yY=rY(`RequestedReviewer`,[[`login`,`string`,`nullable`]]),bY=rY(`ReviewRequest`,[[`requestedReviewer`,`RequestedReviewer`,`nullable`]]),xY=rY(`ReviewRequests`,[[`totalCount`,`int`],[`nodes`,`list<ReviewRequest>`]]),SY=rY(`Review`,[[`author`,`Actor`,`nullable`],[`state`,`string`],[`body`,`string`],[`submittedAt`,`string`,`nullable`],[`commit`,`Commit`,`nullable`]]),CY=rY(`Reviews`,[[`totalCount`,`int`],[`nodes`,`list<Review>`]]),wY=rY(`ReviewThreadComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`]]),TY=rY(`ReviewThreadComments`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThreadComment>`]]),EY=rY(`ReviewThread`,[[`isResolved`,`bool`],[`isOutdated`,`bool`],[`path`,`string`],[`comments`,`ReviewThreadComments`]]),DY=rY(`ReviewThreads`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThread>`]]),OY=rY(`PullRequestComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),kY=rY(`PullRequestComments`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestComment>`]]),AY=rY(`ClosingIssueReference`,[[`number`,`int`],[`state`,`string`]]),jY=rY(`ClosingIssueReferences`,[[`totalCount`,`int`],[`nodes`,`list<ClosingIssueReference>`]]),MY=rY(`StatusCheckRollup`,[[`state`,`string`]]),NY=rY(`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`]]),PY=rY(`Tick`,[[`scheduledAt`,`string`],[`scheduledAtLocal`,`string`],[`cron`,`string`],[`tz`,`string`]]),FY=rY(`SchedulePayload`,[[`tick`,`Tick`]]),IY=(e,t)=>new tJ({types:[dY,...e],variables:[new eJ({name:`repo`,type:nY(`RepoContext`)}),new eJ({name:`item`,type:nY(t)})]}),LY=IY([iY,aY,oY,sY,cY,lY,fY,pY,mY,hY,gY,_Y,vY],`IssuePayload`),RY=IY([iY,aY,oY,sY,uY,fY,yY,bY,xY,SY,CY,wY,TY,EY,DY,OY,kY,AY,jY,MY,NY],`PullRequestPayload`),zY=IY([PY,FY],`SchedulePayload`),BY=e=>{switch(e){case`issue`:return LY;case`pr`:return RY;case`schedule`:return zY}},VY=e=>{let{owner:t}=Jk(e.name);return{name:e.name,owner:t,url:`https://github.com/${e.name}`}},HY=class extends B(`@usine/config/Selector`)({repos:yE(M(H).check(GT(),_W(e=>e))),tags:yE(M(SJ).check(GT(),JT()))}){}.check(jT(e=>x(e.repos)||x(e.tags),{message:`Expected selector.repos, selector.tags, or both`})),UY=(e,t)=>_r(e,{onNone:()=>!0,onSome:e=>{let n=_r(e.repos,{onNone:()=>!0,onSome:e=>e.some(e=>Yk(e)===Yk(t.name))}),r=_r(e.tags,{onNone:()=>!0,onSome:e=>e.some(e=>t.tags.includes(e))});return n&&r}}),WY=A.check(jT(e=>e.trim().split(/\s+/u).length===5&&Di(Cm(e)),{message:`Expected a valid five-field cron expression`})).pipe(I(`Cron`)),GY=A.check(jT(e=>x(R_(e)),{message:`Expected an IANA time-zone name`})).pipe(I(`TimeZone`)),KY=class extends B(`@usine/config/IssueTrigger`)({on:tT(`issue`),if:nJ}){},qY=class extends B(`@usine/config/PullRequestTrigger`)({on:tT(`pr`),if:nJ}){},JY=class extends B(`@usine/config/ScheduleTrigger`)({on:tT(`schedule`),if:nJ,cron:WY,tz:GY.pipe(TT(C(`UTC`)))}){},YY=N([KY,qY,JY]),XY=P([`issue`,`pr`,`schedule`]),ZY=MT(/^(?:[a-z0-9]+(?:-[a-z0-9]+)*\/)?[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a loop name or project/loop identifier`}),QY=uA.check(ZY),$Y=gW(`Expected a non-blank Markdown prompt`).pipe(I(`PromptTemplate`)),eX=L.pipe(I(`PriorityValue`)),tX=N([eX,nJ]),nX=class extends B(`@usine/config/LoopFile`)({name:QY,trigger:YY,selector:z(HY),approval:fA,maxCycles:pI.pipe(TT(C(hI)),CT(C(hI))),permissions:mA.pipe(TT(C(`write`)),CT(C(`write`))),priority:z(tX).pipe(CT(C(v()))),step:DN,agent:aA,body:$Y}){},rX=class extends B(`@usine/config/QuarantinedLoop`)({file:cJ,error:dJ}){},iX=e=>{let[t,n]=e.split(`/`);return cJ.make(n===void 0?`loops/${e}.md`:`projects/${t}/loops/${n}.md`)};D(`Loop.evaluatePriority`)(function*(e,t,n){if(yield*E({loop:t.name}),b(t.priority))return eX.make(0);let r=t.priority.value;if(ne(r))return r;let i=yield*e.evaluateInteger(r,BY(t.trigger.on),n);return yield*zw(eX)(Number(i)).pipe(sg(()=>new oJ({source:r,message:`Priority must be a safe integer between -9007199254740991 and 9007199254740991`})))});var aX=class extends B(`@usine/config/AgentFile`)({name:aA,harness:nA,model:tA,effort:rA,parentModel:z(tA),parentEffort:z(rA),persona:oA}){get agent(){return new sA({name:this.name,persona:this.persona,brain:new iA({harness:this.harness,model:this.model,effort:this.effort}),parentModel:this.parentModel,parentEffort:this.parentEffort})}},oX=class extends B(`@usine/config/InvalidAgent`)({file:cJ,error:dJ}){},sX=class extends V(`@usine/config/UndeclaredLaneLabelWarning`)(`UndeclaredLaneLabelWarning`,{repository:H,lane:vW,label:hA}){},cX=class extends V(`@usine/config/UndeclaredTriggerLabelWarning`)(`UndeclaredTriggerLabelWarning`,{loop:nX.fields.name,label:hA}){},lX=N([sX,cX]),uX=(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})=>Yk(e)))}),dX=e=>e.map(e=>`"${e}"`).join(`, `),fX=(e,t,n)=>{let r=[],i=()=>r.length===0?v():y(new dJ({file:e,stage:`reference`,expression:v(),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.`}),b(t.selector))return i();if(x(t.selector.value.repos)){let e=t.selector.value.repos.value.filter(e=>!n.repoNames.has(Yk(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(x(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()},pX=class extends B(`@usine/config/LoadedInstance`)(j({config:tY,agents:M(aX),invalidAgents:M(oX),loops:M(nX),quarantinedLoops:M(rX),warnings:M(lX)}).check(jT(({agents:e,config:t,loops:n})=>{let r=uX(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=>b(fX(iX(e.name),e,r)))},{message:`Expected every loop to reference only loaded agents and registry entries`}))){},mX=L.check(BT(0)).pipe(I(`ConfigurationRevisionNumber`)),hX=P([`settings`,`worker`,`repository`,`project`,`label`,`loop`,`agent`]),gX=R.pipe(I(`ConfigurationEntityId`)),_X=class extends B(`@usine/config/ConfigurationEntityKey`)({kind:hX,identifier:gX}){get key(){return`${this.kind}:${this.identifier}`}},vX=class extends B(`@usine/config/ConfigurationEntity`)({key:_X,value:PE}){},yX=class extends B(`@usine/config/ConfigurationChange`)({key:_X,before:z(PE),after:z(PE),position:Zw(L.check(BT(0)))}){};(class e extends B(`@usine/config/Configuration`)(j({number:mX,instance:z(pX)}).check(jT(({number:e,instance:t})=>e===0===b(t),{message:`Only an uninitialized configuration has revision zero`}))){get actor(){return Or(this.instance,({config:e})=>e.operator)}static empty=new e({number:mX.make(0),instance:v()})}),B(`@usine/config/ConfigurationRevision`)({number:mX.check(zT(0)),actor:z(NM),time:hE,message:z(A),changes:M(yX)}),jE(`@usine/config/StaleRevision`)(`StaleRevision`,{expected:mX,actual:mX});var bX=class extends jE(`@usine/config/ConfigurationInvalid`)(`ConfigurationInvalid`,{problems:_T(dJ)}){};jE(`@usine/config/ConfigurationStoreError`)(`ConfigurationStoreError`,{operation:A,cause:QT()}),jE(`@usine/config/ConfigurationRevertBlocked`)(`ConfigurationRevertBlocked`,{entities:_T(_X)});var xX=(e,t,n)=>UY(t.selector,n)&&(e.version===1||e.projects.some(e=>t.name.startsWith(`${e.id}/`)&&e.includes(n.name))),SX=e=>e.version===1?e.repos:e.projects.flatMap(t=>t.repositories.flatMap(n=>e.repos.filter(e=>Yk(e.name)===Yk(n)).map(e=>new DJ({...e,lanes:t.lanes})))),CX=(e,t)=>{let n=new Map(e.labels.map(e=>[gA(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(gA(e.label))&&n.set(gA(e.label),new yA({name:e.label,color:v(),description:v()}));return[...n.values()]},wX=(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},TX=(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:v(),message:`Expected the file to start with a YAML frontmatter delimiter (---)`});let r=3+n.length,i=`${n}---`,a=wX(t,n,r);if(a<0)return new dJ({file:e,stage:`frontmatter`,expression:v(),message:`Expected a closing YAML frontmatter delimiter (---)`});let o=a+i.length,s=t.startsWith(n,o)?o+n.length:o;return C({yaml:t.slice(r,a),body:t.slice(s),newline:n})},EX=Symbol.for(`yaml.alias`),DX=Symbol.for(`yaml.document`),OX=Symbol.for(`yaml.map`),kX=Symbol.for(`yaml.pair`),AX=Symbol.for(`yaml.scalar`),jX=Symbol.for(`yaml.seq`),MX=Symbol.for(`yaml.node.type`),NX=e=>!!e&&typeof e==`object`&&e[MX]===EX,PX=e=>!!e&&typeof e==`object`&&e[MX]===DX,FX=e=>!!e&&typeof e==`object`&&e[MX]===OX,IX=e=>!!e&&typeof e==`object`&&e[MX]===kX,LX=e=>!!e&&typeof e==`object`&&e[MX]===AX,RX=e=>!!e&&typeof e==`object`&&e[MX]===jX;function zX(e){if(e&&typeof e==`object`)switch(e[MX]){case OX:case jX:return!0}return!1}function BX(e){if(e&&typeof e==`object`)switch(e[MX]){case EX:case OX:case AX:case jX:return!0}return!1}var VX=e=>(LX(e)||zX(e))&&!!e.anchor,HX=Symbol(`break visit`),UX=Symbol(`skip children`),WX=Symbol(`remove node`);function GX(e,t){let n=qX(t);PX(e)?KX(null,e.contents,n,Object.freeze([e]))===WX&&(e.contents=null):KX(null,e,n,Object.freeze([]))}GX.BREAK=HX,GX.SKIP=UX,GX.REMOVE=WX;function KX(e,t,n,r){let i=JX(e,t,n,r);if(BX(i)||IX(i))return YX(e,r,i),KX(e,i,n,r);if(typeof i!=`symbol`){if(zX(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=KX(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===HX)return HX;else i===WX&&(t.items.splice(e,1),--e)}}else if(IX(t)){r=Object.freeze(r.concat(t));let e=KX(`key`,t.key,n,r);if(e===HX)return HX;e===WX&&(t.key=null);let i=KX(`value`,t.value,n,r);if(i===HX)return HX;i===WX&&(t.value=null)}}return i}function qX(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 JX(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(FX(t))return n.Map?.(e,t,r);if(RX(t))return n.Seq?.(e,t,r);if(IX(t))return n.Pair?.(e,t,r);if(LX(t))return n.Scalar?.(e,t,r);if(NX(t))return n.Alias?.(e,t,r)}function YX(e,t,n){let r=t[t.length-1];if(zX(r))r.items[e]=n;else if(IX(r))e===`key`?r.key=n:r.value=n;else if(PX(r))r.contents=n;else{let e=NX(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var XX={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},ZX=e=>e.replace(/[!,[\]{}]/g,e=>XX[e]),QX=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+ZX(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&&BX(e.contents)){let t={};GX(e.contents,(e,n)=>{BX(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
|
-
`)}};QX.defaultYaml={explicit:!1,version:`1.2`},QX.defaultTags={"!!":`tag:yaml.org,2002:`};function $X(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 eZ(e){let t=new Set;return GX(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function tZ(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function nZ(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=eZ(e);let a=tZ(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(LX(t.node)||zX(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 rZ(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=rZ(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=rZ(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=rZ(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=rZ(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function iZ(e,t,n){if(Array.isArray(e))return e.map((e,t)=>iZ(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!VX(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 aZ=class{constructor(e){Object.defineProperty(this,MX,{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(!PX(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=iZ(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?rZ(i,{"":o},``,o):o}},oZ=class extends aZ{constructor(e){super(EX),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=[],GX(e,{Node:(e,t)=>{(NX(t)||VX(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||=(iZ(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=sZ(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($X(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 sZ(e,t,n){if(NX(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(zX(t)){let r=0;for(let i of t.items){let t=sZ(e,i,n);t>r&&(r=t)}return r}if(IX(t)){let r=sZ(e,t.key,n),i=sZ(e,t.value,n);return Math.max(r,i)}return 1}var cZ=e=>!e||typeof e!=`function`&&typeof e!=`object`,lZ=class extends aZ{constructor(e){super(AX),this.value=e}toJSON(e,t){return t?.keep?this.value:iZ(this.value,e,t)}toString(){return String(this.value)}};lZ.BLOCK_FOLDED=`BLOCK_FOLDED`,lZ.BLOCK_LITERAL=`BLOCK_LITERAL`,lZ.PLAIN=`PLAIN`,lZ.QUOTE_DOUBLE=`QUOTE_DOUBLE`,lZ.QUOTE_SINGLE=`QUOTE_SINGLE`;var uZ=`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 fZ(e,t,n){if(PX(e)&&(e=e.contents),BX(e))return e;if(IX(e)){let t=n.schema[OX].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 oZ(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=uZ+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 lZ(e);return c&&(c.node=t),t}l=e instanceof Map?o[OX]:Symbol.iterator in Object(e)?o[jX]:o[OX]}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 lZ(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function pZ(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 fZ(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var mZ=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,hZ=class extends aZ{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=>BX(t)||IX(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(mZ(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(zX(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,pZ(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(zX(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&&LX(i)?i.value:i:zX(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!IX(t))return!1;let n=t.value;return n==null||e&&LX(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 zX(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(zX(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,pZ(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},gZ=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function _Z(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var vZ=(e,t,n)=>e.endsWith(`
|
|
198
|
-
`)?_Z(n,t):n.includes(`
|
|
199
|
-
`)?`
|
|
200
|
-
`+_Z(n,t):(e.endsWith(` `)?``:` `)+n,yZ=`flow`,bZ=`block`,xZ=`quoted`;function SZ(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=CZ(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=CZ(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 ee=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?ee=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(ee+=`${e[i]}\\`),ee+=`\n${t}${e.slice(i+1,a)}`)}return ee}function CZ(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 wZ=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),TZ=e=>/^(%|---|\.\.\.)/m.test(e);function EZ(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 DZ(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(TZ(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:SZ(o,a,xZ,wZ(t,!1))}function OZ(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
209
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return DZ(e,t);let n=t.indent||(TZ(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:SZ(r,n,yZ,wZ(t,!1))}function kZ(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=DZ;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?OZ:i&&!t?DZ:n?OZ:DZ}return r(e,t)}var AZ;try{AZ=RegExp(`(^|(?<!
|
|
210
|
-
))
|
|
211
|
-
+(?!
|
|
212
|
-
|$)`,`g`)}catch{AZ=/\n+(?!\n|$)/g}function jZ({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 kZ(n,r);let l=r.indent||(r.forceBlockIndent||TZ(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===lZ.BLOCK_FOLDED?!1:t===lZ.BLOCK_LITERAL||!EZ(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(AZ,`$&${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 ee=n.substring(0,_<g?_+1:g);ee&&=(n=n.substring(ee.length),ee.replace(/\n+/g,`$&${l}`));let te=(h?l?`2`:`1`:``)+d;if(e&&(te+=` `+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=wZ(r,!0);o!==`folded`&&t!==lZ.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=SZ(`${ee}${e}${p}`,l,bZ,a);if(!i)return`>${te}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${te}\n${l}${ee}${n}${p}`}function MZ(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 kZ(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
221
|
-
`)?kZ(a,t):jZ(e,t,n,r);if(!s&&!u&&i!==lZ.PLAIN&&a.includes(`
|
|
222
|
-
`))return jZ(e,t,n,r);if(TZ(a)){if(c===``)return t.forceBlockIndent=!0,jZ(e,t,n,r);if(s&&c===l)return kZ(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 kZ(a,t)}return s?d:SZ(d,c,yZ,wZ(t,!1))}function NZ(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!==lZ.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=lZ.QUOTE_DOUBLE);let c=e=>{switch(e){case lZ.BLOCK_FOLDED:case lZ.BLOCK_LITERAL:return i||a?kZ(o.value,t):jZ(o,t,n,r);case lZ.QUOTE_DOUBLE:return DZ(o.value,t);case lZ.QUOTE_SINGLE:return OZ(o.value,t);case lZ.PLAIN:return MZ(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 PZ(e,t){let n=Object.assign({blockQuote:!0,commentString:gZ,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function FZ(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(LX(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 IZ(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(LX(e)||zX(e))&&e.anchor;a&&$X(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 LZ(e,t,n,r){if(IX(e))return e.toString(t,n,r);if(NX(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=BX(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=FZ(t.doc.schema.tags,a);let o=IZ(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):LX(a)?NZ(a,t,n,r):a.toString(t,n,r);return o?LX(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function RZ({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=BX(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(zX(e)||!BX(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||zX(e)||(LX(e)?e.type===lZ.BLOCK_FOLDED||e.type===lZ.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=LZ(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+=vZ(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=vZ(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=vZ(g,n.indent,l(f))));let _,ee,te;BX(t)?(_=!!t.spaceBefore,ee=t.commentBefore,te=t.comment):(_=!1,ee=null,te=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&LX(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&RX(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let ne=!1,re=LZ(t,n,()=>ne=!0,()=>h=!0),ie=` `;if(f||_||ee){if(ie=_?`
|
|
223
|
-
`:``,ee){let e=l(ee);ie+=`\n${_Z(e,n.indent)}`}re===``&&!n.inFlow?ie===`
|
|
224
|
-
`&&te&&(ie=`
|
|
225
|
-
|
|
226
|
-
`):ie+=`\n${n.indent}`}else if(!p&&zX(t)){let e=re[0],r=re.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=re.indexOf(` `);e===`&`&&n!==-1&&n<r&&re[n+1]===`!`&&(n=re.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(ie=`\n${n.indent}`)}}else(re===``||re[0]===`
|
|
228
|
-
`)&&(ie=``);return g+=ie+re,n.inFlow?ne&&r&&r():te&&!ne?g+=vZ(g,n.indent,l(te)):h&&i&&i(),g}function zZ(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var BZ=`<<`,VZ={identify:e=>e===BZ||typeof e==`symbol`&&e.description===BZ,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new lZ(Symbol(BZ)),{addToJSMap:UZ}),stringify:()=>BZ},HZ=(e,t)=>(VZ.identify(t)||LX(t)&&(!t.type||t.type===lZ.PLAIN)&&VZ.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===VZ.tag&&e.default);function UZ(e,t,n){let r=GZ(e,n);if(RX(r))for(let n of r.items)WZ(e,t,n);else if(Array.isArray(r))for(let n of r)WZ(e,t,n);else WZ(e,t,r)}function WZ(e,t,n){let r=GZ(e,n);if(!FX(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 GZ(e,t){return e&&NX(t)?t.resolve(e.doc,e):t}function KZ(e,t,{key:n,value:r}){if(BX(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(HZ(e,n))UZ(e,t,r);else{let i=iZ(n,``,e);if(t instanceof Map)t.set(i,iZ(r,i,e));else if(t instanceof Set)t.add(i);else{let a=qZ(n,i,e),o=iZ(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function qZ(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(BX(e)&&n?.doc){let t=PZ(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)+`..."`),zZ(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 JZ(e,t,n){return new YZ(fZ(e,void 0,n),fZ(t,void 0,n))}var YZ=class e{constructor(e,t=null){Object.defineProperty(this,MX,{value:kX}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return BX(n)&&(n=n.clone(t)),BX(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return KZ(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?RZ(this,e,t,n):JSON.stringify(this)}};function XZ(e,t,n){return(t.inFlow??e.flow?QZ:ZZ)(e,t,n)}function ZZ({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(BX(i))!d&&i.spaceBefore&&f.push(``),$Z(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(IX(i)){let e=BX(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),$Z(n,f,e.commentBefore,d))}d=!1;let s=LZ(i,u,()=>o=null,()=>d=!0);o&&(s+=vZ(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
|
-
`+_Z(l(e),c),s&&s()):d&&o&&o(),p}function QZ({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(BX(i))i.spaceBefore&&d.push(``),$Z(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(IX(i)){let e=BX(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),$Z(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=BX(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=LZ(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+=vZ(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 $Z({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=_Z(t(r),e);n.push(i.trimStart())}}function eQ(e,t){let n=LX(t)?t.value:t;for(let r of e)if(IX(r)&&(r.key===t||r.key===n||LX(r.key)&&r.key.value===n))return r}var tQ=class extends hZ{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(OX,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(JZ(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=IX(e)?e:!e||typeof e!=`object`||!(`key`in e)?new YZ(e,e?.value):new YZ(e.key,e.value);let r=eQ(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);LX(r.value)&&cZ(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=eQ(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=eQ(this.items,e)?.value;return(!t&&LX(n)?n.value:n)??void 0}has(e){return!!eQ(this.items,e)}set(e,t){this.add(new YZ(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)KZ(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!IX(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})),XZ(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},nQ={collection:`map`,default:!0,nodeClass:tQ,tag:`tag:yaml.org,2002:map`,resolve(e,t){return FX(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>tQ.from(e,t,n)},rQ=class extends hZ{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(jX,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=iQ(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=iQ(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&LX(r)?r.value:r}has(e){let t=iQ(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=iQ(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];LX(r)&&cZ(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(iZ(e,String(r++),t));return n}toString(e,t,n){return e?XZ(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(fZ(a,void 0,n))}}return i}};function iQ(e){let t=LX(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var aQ={collection:`seq`,default:!0,nodeClass:rQ,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return RX(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>rQ.from(e,t,n)},oQ={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),NZ(e,t,n,r)}},sQ={identify:e=>e==null,createNode:()=>new lZ(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new lZ(null),stringify:({source:e},t)=>typeof e==`string`&&sQ.test.test(e)?e:t.options.nullStr},cQ={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new lZ(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&cQ.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function lQ({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 uQ={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:lQ},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():lQ(e)}},fQ={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 lZ(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:lQ},pQ=e=>typeof e==`bigint`||Number.isInteger(e),mQ=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function hQ(e,t,n){let{value:r}=e;return pQ(r)&&r>=0?n+r.toString(t):lQ(e)}var gQ={identify:e=>pQ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>mQ(e,2,8,n),stringify:e=>hQ(e,8,`0o`)},_Q={identify:pQ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>mQ(e,0,10,n),stringify:lQ},vQ={identify:e=>pQ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>mQ(e,2,16,n),stringify:e=>hQ(e,16,`0x`)},yQ=[nQ,aQ,oQ,sQ,cQ,gQ,_Q,vQ,uQ,dQ,fQ];function bQ(e){return typeof e==`bigint`||Number.isInteger(e)}var xQ=({value:e})=>JSON.stringify(e),SQ=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:xQ},{identify:e=>e==null,createNode:()=>new lZ(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:xQ},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:xQ},{identify:bQ,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})=>bQ(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:xQ}],CQ=[nQ,aQ].concat(SQ,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}}),wQ={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??=lZ.BLOCK_LITERAL,t!==lZ.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===lZ.BLOCK_LITERAL?`
|
|
233
|
-
`:` `)}return NZ({comment:e,type:t,value:s},r,i,a)}};function TQ(e,t){if(RX(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!IX(r)){if(FX(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new YZ(new lZ(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]=IX(r)?r:new YZ(r)}}else t(`Expected a sequence for this tag`);return e}function EQ(e,t,n){let{replacer:r}=n,i=new rQ(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(JZ(o,s,n))}return i}var DQ={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:TQ,createNode:EQ},OQ=class e extends rQ{constructor(){super(),this.add=tQ.prototype.add.bind(this),this.delete=tQ.prototype.delete.bind(this),this.get=tQ.prototype.get.bind(this),this.has=tQ.prototype.has.bind(this),this.set=tQ.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(IX(e)?(r=iZ(e.key,``,t),i=iZ(e.value,r,t)):r=iZ(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=EQ(e,t,n),i=new this;return i.items=r.items,i}};OQ.tag=`tag:yaml.org,2002:omap`;var kQ={collection:`seq`,identify:e=>e instanceof Map,nodeClass:OQ,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=TQ(e,t),r=[];for(let{key:e}of n.items)LX(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new OQ,n)},createNode:(e,t,n)=>OQ.from(e,t,n)};function AQ({value:e,source:t},n){return t&&(e?jQ:MQ).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var jQ={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 lZ(!0),stringify:AQ},MQ={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 lZ(!1),stringify:AQ},NQ={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:lQ},PQ={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():lQ(e)}},FQ={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 lZ(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:lQ},IQ=e=>typeof e==`bigint`||Number.isInteger(e);function LQ(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 RQ(e,t,n){let{value:r}=e;if(IQ(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return lQ(e)}var zQ={identify:IQ,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>LQ(e,2,2,n),stringify:e=>RQ(e,2,`0b`)},BQ={identify:IQ,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>LQ(e,1,8,n),stringify:e=>RQ(e,8,`0`)},VQ={identify:IQ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>LQ(e,0,10,n),stringify:lQ},HQ={identify:IQ,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>LQ(e,2,16,n),stringify:e=>RQ(e,16,`0x`)},UQ=class e extends tQ{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=IX(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new YZ(e.key,null):new YZ(e,null),eQ(this.items,t.key)||this.items.push(t)}get(e,t){let n=eQ(this.items,e);return!t&&IX(n)?LX(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=eQ(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new YZ(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(JZ(e,null,n));return i}};UQ.tag=`tag:yaml.org,2002:set`;var WQ={collection:`map`,identify:e=>e instanceof Set,nodeClass:UQ,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>UQ.from(e,t,n),resolve(e,t){if(FX(e)){if(e.hasAllNullValues(!0))return Object.assign(new UQ,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}};function GQ(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 KQ(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return lQ(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 qQ={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})=>GQ(e,n),stringify:KQ},JQ={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=>GQ(e,!1),stringify:KQ},YQ={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(YQ.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=GQ(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$/,``)??``},XQ=[nQ,aQ,oQ,sQ,jQ,MQ,zQ,BQ,VQ,HQ,NQ,PQ,FQ,wQ,VZ,kQ,DQ,WQ,qQ,JQ,YQ],ZQ=new Map([[`core`,yQ],[`failsafe`,[nQ,aQ,oQ]],[`json`,CQ],[`yaml11`,XQ],[`yaml-1.1`,XQ]]),QQ={binary:wQ,bool:cQ,float:fQ,floatExp:dQ,floatNaN:uQ,floatTime:JQ,int:_Q,intHex:vQ,intOct:gQ,intTime:qQ,map:nQ,merge:VZ,null:sQ,omap:kQ,pairs:DQ,seq:aQ,set:WQ,timestamp:YQ},$Q={"tag:yaml.org,2002:binary":wQ,"tag:yaml.org,2002:merge":VZ,"tag:yaml.org,2002:omap":kQ,"tag:yaml.org,2002:pairs":DQ,"tag:yaml.org,2002:set":WQ,"tag:yaml.org,2002:timestamp":YQ};function e$(e,t,n){let r=ZQ.get(t);if(r&&!e)return n&&!r.includes(VZ)?r.concat(VZ):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(ZQ.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(VZ)),i.reduce((e,t)=>{let n=typeof t==`string`?QQ[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(QQ).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 t$=(e,t)=>e.key<t.key?-1:+(e.key>t.key),n$=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?e$(e,`compat`):e?e$(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?$Q:{},this.tags=e$(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,OX,{value:nQ}),Object.defineProperty(this,AX,{value:oQ}),Object.defineProperty(this,jX,{value:aQ}),this.sortMapEntries=typeof a==`function`?a:a===!0?t$:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function r$(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=PZ(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(_Z(t,``))}let o=!1,s=null;if(e.contents){if(BX(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(_Z(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=LZ(e.contents,i,()=>s=null,t);s&&(c+=vZ(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(LZ(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
|
|
234
|
-
`)?(n.push(`...`),n.push(_Z(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(_Z(a(t),``)))}return n.join(`
|
|
235
|
-
`)+`
|
|
236
|
-
`}var i$=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,MX,{value:DX});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 QX({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[MX]:{value:DX}});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=BX(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){a$(this.contents)&&this.contents.add(e)}addIn(e,t){a$(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=eZ(this);e.anchor=!t||n.has(t)?tZ(t||`a`,n):t}return new oZ(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}=nZ(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=fZ(e,l,p);return o&&zX(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new YZ(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return a$(this.contents)?this.contents.delete(e):!1}deleteIn(e){return mZ(e)?this.contents!=null&&(this.contents=null,!0):a$(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return zX(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return mZ(e)?!t&&LX(this.contents)?this.contents.value:this.contents:zX(this.contents)?this.contents.getIn(e,t):void 0}has(e){return zX(this.contents)?this.contents.has(e):!1}hasIn(e){return mZ(e)?this.contents!==void 0:zX(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=pZ(this.schema,[e],t):a$(this.contents)&&this.contents.set(e,t)}setIn(e,t){mZ(e)?this.contents=t:this.contents==null?this.contents=pZ(this.schema,Array.from(e),t):a$(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 QX({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 QX({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 n$(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=iZ(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`?rZ(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 r$(this,e)}};function a$(e){if(zX(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var o$=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},s$=class extends o${constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},c$=class extends o${constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},l$=(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 u$(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,ee=null,te=null,ne=null,re=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:ne&&n===`seq-item-ind`||(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(ee=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,re??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,re??=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`),ne&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),ne=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){te&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),te=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let ie=e[e.length-1],ae=ie?ie.offset+ie.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:te,found:ne,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:ee,end:ae,start:re??ae}}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 f$(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 p$(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||LX(e)&&LX(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var m$=`All mapping items must start at the same column`;function h$({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??tQ)(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=u$(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`,m$)),!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`,m$);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&f$(r.indent,u,i),n.atKey=!1,p$(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=u$(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&&f$(r.indent,f,i),s=c.range[2];let l=new YZ(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 YZ(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function g$({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??rQ)(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=u$(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&&f$(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function _$(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 v$=`Block collections are not allowed within flow collections`,y$=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function b$({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?tQ:rQ))(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=u$(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];IX(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],y$(m)&&i(r.range,`BLOCK_IN_FLOW`,v$)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);y$(f)&&i(g.range,`BLOCK_IN_FLOW`,v$),n.atKey=!1;let _=u$(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 ee=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;ee?y$(m)&&i(ee.range,`BLOCK_IN_FLOW`,v$):_.comment&&(g.comment?g.comment+=`
|
|
243
|
-
`+_.comment:g.comment=_.comment);let te=new YZ(g,ee);if(n.options.keepSourceTokens&&(te.srcToken=l),o){let e=c;p$(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(te)}else{let e=new tQ(n.schema);e.flow=!0,e.items.push(te);let t=(ee??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=ee?ee.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=_$(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 x$(e,t,n,r,i,a){let o=n.type===`block-map`?h$(e,t,n,r,a):n.type===`block-seq`?g$(e,t,n,r,a):b$(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function S$(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===tQ.tagName&&s===`map`||o===rQ.tagName&&s===`seq`)return x$(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),x$(e,t,n,i,o)}let l=x$(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=BX(u)?u:new lZ(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function C$(e,t,n){let r=t.offset,i=w$(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?lZ.BLOCK_FOLDED:lZ.BLOCK_LITERAL,o=t.source?T$(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===lZ.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 w$({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 T$(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 E$(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=lZ.PLAIN,c=D$(a,l);break;case`single-quoted-scalar`:s=lZ.QUOTE_SINGLE,c=O$(a,l);break;case`double-quoted-scalar`:s=lZ.QUOTE_DOUBLE,c=A$(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=_$(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function D$(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}`),k$(e)}function O$(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),k$(e.slice(1,-1)).replace(/''/g,`'`)}function k$(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 A$(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}=j$(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=M$[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+=N$(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 j$(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 M$={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
|
|
272
|
-
`,r:`\r`,t:` `,v:`\v`,N:`
`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function N$(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 P$(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?C$(e,t,r):E$(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[AX]:c?F$(e.schema,i,c,n,r):t.type===`scalar`?I$(e,i,t,r):e.schema[AX];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=LX(a)?a:new lZ(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new lZ(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 F$(e,t,n,r,i){if(n===`!`)return e[AX];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[AX])}function I$({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[AX];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[AX];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 L$(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 R$={composeNode:z$,composeEmptyNode:B$};function z$(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=V$(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=P$(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=S$(R$,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??=B$(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&&(!LX(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 B$(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=P$(e,{type:`scalar`,offset:L$(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 V$({options:e},{offset:t,source:n,end:r},i){let a=new oZ(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=_$(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function H$(e,t,{offset:n,start:r,value:i,end:a},o){let s=new i$(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=u$(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?z$(c,i,l,o):B$(c,l.end,r,null,l,o);let u=s.contents.range[2],d=_$(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function U$(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 W$(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 G$=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=U$(e);r?this.warnings.push(new c$(i,t,n)):this.errors.push(new s$(i,t,n))},this.directives=new QX({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=W$(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(zX(i)&&!i.flow&&i.items.length>0){let e=i.items[0];IX(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:W$(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=U$(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=H$(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 s$(U$(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 s$(U$(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=_$(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 s$(U$(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 i$(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}}},K$=Symbol(`break visit`),q$=Symbol(`skip children`),J$=Symbol(`remove item`);function Y$(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),X$(Object.freeze([]),e,t)}Y$.BREAK=K$,Y$.SKIP=q$,Y$.REMOVE=J$,Y$.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},Y$.parentCollection=(e,t)=>{let n=Y$.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 X$(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=X$(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===K$)return K$;else r===J$&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function Z$(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 Q$(e){switch(e){case void 0:case` `:case`
|
|
278
|
-
`:case`\r`:case` `:return!0;default:return!1}}var $$=new Set(`0123456789ABCDEFabcdef`),e1=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),t1=new Set(`,[]{}`),n1=new Set(` ,[]{}
|
|
279
|
-
\r `),r1=e=>!e||n1.has(e),i1=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===`...`)&&Q$(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===`...`)&&Q$(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&&!Q$(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===`:`)&&Q$(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(r1),`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(`...`))&&Q$(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(r1),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||Q$(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=>Q$(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(Q$(r)||e&&t1.has(r))break;t=n}else if(Q$(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&&t1.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&&t1.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(r1),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(Q$(n)||t&&t1.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(;!Q$(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(e1.has(t))t=this.buffer[++e];else if(t===`%`&&$$.has(this.buffer[e+1])&&$$.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)}},a1=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 o1(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function s1(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 c1(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 l1(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 u1(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 f1(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!o1(t.start,`explicit-key-ind`)&&!o1(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,c1(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 p1=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 i1,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=Z$(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`&&f1(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&&s1(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`:s1(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=u1(l1(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(o1(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=u1(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(o1(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(c1(t.key)&&!o1(t.sep,`newline`)){let e=u1(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]}):o1(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&&!o1(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||o1(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=u1(l1(t));f1(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=u1(l1(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=u1(l1(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 m1(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new a1||null,prettyErrors:t}}function h1(e,t={}){let{lineCounter:n,prettyErrors:r}=m1(t),i=new p1(n?.addNewLine),a=new G$(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 s$(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(l$(e,n)),o.warnings.forEach(l$(e,n))),o}function g1(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 PX(e)&&!r?e.toString(n):new i$(e,r,n).toString(n)}var _1=e=>_r(Vw(j({message:R}))(e),{onNone:()=>`The YAML parser failed without an error message`,onSome:({message:e})=>e}),v1=(e,t)=>w(function*(){let n=yield*Uh({try:()=>h1(t,{keepSourceTokens:!0,prettyErrors:!0,strict:!0,uniqueKeys:!0}),catch:t=>new dJ({file:e,stage:`yaml`,expression:v(),message:_1(t)})}),r=n.errors[0]??n.warnings[0];return r===void 0?n:yield*new dJ({file:e,stage:`yaml`,expression:v(),message:r.message})}),y1=e=>g1(e);B(`@usine/config/YamlEdit`)({path:M(R).check(GT()),value:PE});var b1=(e,t)=>{let n=e.replaceAll(`\r
|
|
301
|
-
`,`
|
|
302
|
-
`);return t===`\r
|
|
303
|
-
`?n.replaceAll(`
|
|
304
|
-
`,`\r
|
|
305
|
-
`):n},x1=D(`YamlWriter.updateYaml`)((e,t,n)=>w(function*(){let r=yield*v1(e,t);return r.setIn(n.path,n.value),b1(r.toString(),t.includes(`\r
|
|
306
|
-
`)?`\r
|
|
307
|
-
`:`
|
|
308
|
-
`)}));D(`YamlWriter.updateFrontmatter`)((e,t,n)=>w(function*(){let r=yield*TX(e,t),i=b1(yield*x1(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 S1=Ky(),C1=N([A,sT]).annotate({message:`Expected a CEL expression. Quote the value so that YAML reads it as a string.`}).pipe(bT(nJ,{decode:ib(e=>String(e)),encode:ib(e=>e)})),w1=N([KY.mapFields(Sw({if:C1})).pipe(bT(KY)),qY.mapFields(Sw({if:C1})).pipe(bT(qY)),JY.mapFields(Sw({if:C1})).pipe(bT(JY))]),T1=class extends B(`@usine/config/LoopFrontmatter`)({trigger:w1,selector:yE(HY),approval:fA.pipe(TT(C(`none`))),step:DN.pipe(TT(C(`run`))),agent:aA,maxCycles:nX.fields.maxCycles,permissions:nX.fields.permissions,priority:yE(tX)}){},E1=T1.pipe(fT({maxCycles:`max_cycles`})),D1=class extends B(`@usine/config/AgentFrontmatter`)({harness:nA,model:tA,effort:rA,parentModel:yE(tA),parentEffort:yE(rA)}){},O1=D1.pipe(fT({parentModel:`parent_model`,parentEffort:`parent_effort`})),k1=e=>`---\n${y1(Jw(O1)(new D1(e)))}---\n${e.persona}`,A1=e=>`---\n${y1(Jw(E1)(new T1(e)))}---\n${e.body}`,j1=(e,t)=>dJ.fromSchema(e,t),M1=zw(PE),N1=(e,t)=>w(function*(){return yield*M1((yield*v1(e,t)).toJS()).pipe(sg(t=>new dJ({file:e,stage:`yaml`,expression:v(),message:S1(t.issue)})))}),P1=(e,t,n)=>{let r={path:n,message:t.message,expression:t.source},i=t._tag===`ExpressionCheckError`&&x(t.position)?{...r,position:t.position.value}:r;return new dJ({file:e,stage:`expression`,expression:y(t.source),message:t.message,details:[i]})},F1=e=>{let t=e.slice(e.lastIndexOf(`/`)+1);return t.endsWith(`.md`)?C(t.slice(0,-3)):new dJ({file:e,stage:`schema`,expression:v(),message:`Expected a .md filename`})},I1=e=>F1(e).pipe(T(t=>zw(nX.fields.name)(e.startsWith(`projects/`)?`${e.split(`/`)[1]}/${t}`:e.startsWith(`loops/`)?e.slice(6,-3):t).pipe(sg(t=>j1(e,t))))),L1=e=>F1(e).pipe(T(t=>zw(aA)(t).pipe(sg(t=>j1(e,t))))),R1=(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:v(),message:t,details:[{path:[`body`],message:t}]}));break}let s=Uw(nJ)(t.slice(a+2,o).trim());if(Di(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:v(),message:t,details:[{path:[`body`],message:t}]}))}i=o+2}return{expressions:n,problems:r}},z1=(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}])}),B1=(e,t,n)=>{let r=iX(t.name),i=BY(t.trigger.on);return w(function*(){let{expressions:a,problems:o}=R1(r,t.body);if(Yi(o))return yield*z1(r,o);let s=yield*Ah(a,t=>e.evaluateScalar(t.source,i,n).pipe(sg(e=>P1(r,e,[`body`])),Qh(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)})},V1=D(`ConfigParser.parseUsineYaml`)((e,t)=>w(function*(){let n=yield*N1(e,t);return yield*zw(tY)(n,{onExcessProperty:`error`,errors:`all`}).pipe(sg(t=>j1(e,t)))})),H1=D(`ConfigParser.parseAgentFile`)((e,t)=>w(function*(){let n=yield*L1(e),r=yield*TX(e,t),i=yield*N1(e,r.yaml),a=yield*zw(O1)(i,{onExcessProperty:`error`,errors:`all`}).pipe(sg(t=>j1(e,t))),o=yield*zw(oA)(r.body).pipe(sg(t=>j1(e,t)));return new aX({name:n,harness:a.harness,model:a.model,effort:a.effort,parentModel:a.parentModel,parentEffort:a.parentEffort,persona:o})})),U1=(e,t)=>w(function*(){let n=yield*I1(e),r=yield*TX(e,t),i=yield*N1(e,r.yaml),a=yield*zw(E1)(i,{onExcessProperty:`error`,errors:`all`}).pipe(sg(t=>j1(e,t))),o=yield*zw($Y)(r.body).pipe(sg(t=>{let n=j1(e,t);return new dJ({...n,message:n.message,details:[{path:[`body`],message:n.message}]})}));return new nX({name:n,...a,body:o})}),W1=(e,t,n,r,i,a)=>w(function*(){let o=[],s=b(i)?{expressions:[],problems:[]}:R1(t,i.value);if(o.push(...s.problems),b(n))return o;let c=BY(n.value);if(x(r)){let n=yield*e.checkBoolean(r.value,c).pipe(Yh);Ei(n)&&o.push(P1(t,n.failure,[`trigger`,`if`]))}if(x(a)&&te(a.value)){let n=yield*e.checkInteger(a.value,c).pipe(Yh);Ei(n)&&o.push(P1(t,n.failure,[`priority`]))}for(let{source:n}of s.expressions){let r=yield*e.checkScalar(n,c).pipe(Yh);Ei(r)&&o.push(P1(t,r.failure,[`body`]))}return o}),G1=ME(nX),K1=j({frontmatter:E1,name:nX.fields.name,body:$Y}),q1=e=>D(`ConfigParser.checkLoopDraft`)(function*(t,n,r){yield*E({file:t});let i=`text`in n,{value:a,parsed:o}=yield*i?w(function*(){let e=yield*TX(t,n.text),r=yield*N1(t,e.yaml),i=yield*zw(FE)(r).pipe(sg(e=>j1(t,e))),a=Uw(K1)({frontmatter:i,name:yield*I1(t),body:e.body},{errors:`all`,onExcessProperty:`error`}).pipe(ki(({frontmatter:e,...t})=>new nX({...e,...t})),Oi(e=>{let n=j1(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}}):C({value:n.value,parsed:Uw(G1)(n.value,{errors:`all`,onExcessProperty:`error`}).pipe(Oi(e=>j1(t,e)))}),s=Ei(o)?[o.failure]:[];if(!i){let e=Vw(j({name:nX.fields.name}))(a);if(x(e)&&e.value.name!==(yield*I1(t))){let e=`Entity identifier does not match its name`;s.push(new dJ({file:t,stage:`schema`,expression:v(),message:e,details:[{path:[`name`],message:e}]}))}}let c=Vw(j({trigger:j({on:XY})}))(a),l=Vw(j({trigger:j({if:i?C1:nJ})}))(a),u=Vw(j({body:$Y}))(a),d=Vw(j({priority:i?T1.fields.priority:ME(nX.fields.priority)}))(a);s.push(...yield*W1(e,t,Dr(c,({trigger:e})=>e.on),Dr(l,({trigger:e})=>e.if),Dr(u,({body:e})=>e),Or(d,({priority:e})=>e)));let f=Vw(j({agent:aA}))(a),p=Vw(j({selector:i?T1.fields.selector:ME(nX.fields.selector)}))(a),m=Or(r,e=>fX(t,{agent:wr(Dr(f,({agent:e})=>e)),selector:Or(p,({selector:e})=>e)},e));return x(m)&&s.push(m.value),yield*k(`Checked independent loop fields`,{file:t,problems:s.length}),{loop:Di(o)?y(o.success):v(),problems:s}}),J1=e=>D(`ConfigParser.parseLoopFile`)((t,n)=>w(function*(){let r=yield*U1(t,n),i=yield*W1(e,t,y(r.trigger.on),y(r.trigger.if),y(r.body),r.priority);return Yi(i)?yield*z1(t,i):r})),Y1=Vw(hA),X1=e=>D(`ConfigParser.configWarnings`)(function*(t,n){let r=new Set(t.labels.map(({name:e})=>gA(e))),i=[];for(let e of SX(t))for(let t of e.lanes)for(let n of t.sources)`label`in n&&!r.has(gA(n.label))&&i.push(new sX({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=Y1(e);x(n)&&!r.has(gA(n.value))&&i.push(new cX({loop:t.name,label:n.value}))}}return i}),Z1=class e extends Lr()(`@usine/config/ConfigParser`){static layer=qf(e,w(function*(){return Q1(yield*sJ)}))},Q1=e=>({configWarnings:X1(e),checkLoopDraft:q1(e),parseUsineYaml:V1,parseAgentFile:H1,parseLoopFile:J1(e),renderPrompt:D(`ConfigParser.renderPrompt`)((t,n)=>B1(e,t,n))}),$1=R.pipe(I(`CursorKey`)),e0=zw(M(j({value:PE}))),t0=e=>t=>sg(t,t=>new uz({operation:e,cause:t})),n0=class e extends Lr()(`@usine/engine/CursorStore`){static layer=qf(e,w(function*(){let e=yield*hz;return{read:D(`CursorStore.read`)(function*(t,n){let r=xr((yield*w(function*(){return yield*e0(yield*e.select({value:tz.valueJson}).from(tz).where(Y(tz.cursorKey,t)).limit(1).execute())}).pipe(t0(`read runtime cursor`)))[0]);return b(r)?v():yield*zw(n)(r.value.value,{onExcessProperty:`error`}).pipe(Qh(y),ng(e=>Xg(`Stored cursor no longer decodes; treating it as absent`,{key:t,detail:e.message}).pipe($h(v()))))}),write:D(`CursorStore.write`)(function*(t,n,r){let i=yield*Kw(n)(r).pipe(t0(`encode runtime cursor`));yield*e.insert(tz).values({cursorKey:t,valueJson:i}).onConflictDoUpdate({target:tz.cursorKey,set:{valueJson:i}}).execute().pipe(tg,t0(`write runtime cursor`))})}}))},r0=e=>e.pipe(sg(e=>e instanceof tR?e:new uz({operation:`update cycle budget`,cause:e}))),i0=class e extends Lr()(`@usine/engine/CycleBudgets`){static layer=qf(e,w(function*(){let e=yield*hz,t=KK(e);return{generation:D(`CycleBudgets.generation`)(function*(e){return yield*E({itemKey:e}),_r(yield*t.get(e).pipe(sg(e=>new uz({operation:`read cycle generation`,cause:e}))),{onNone:()=>mI.make(0),onSome:e=>e.generation})}),asks:D(`CycleBudgets.asks`)(()=>t.asks().pipe(sg(e=>new uz({operation:`read cycle asks`,cause:e})))),reset:D(`CycleBudgets.reset`)(function*(t,n){yield*E({askId:t,eventId:n.id}),yield*e.transaction(e=>w(function*(){if((yield*e.select().from(JR).where(Y(JR.askId,t)).execute())[0]?.eventId===n.id){yield*O(`Cycle budget reset answer already recorded`,{askId:t,eventId:n.id});return}let r=(yield*KK(e).asks()).find(({id:e})=>e===t);if(r===void 0)return yield*new tR({askId:t});let i=yield*KK(e).get(r.itemKey);if(b(i))return yield*Hh(Error(`Open cycle ask has no budget`));let a=i.value.generation+1;yield*e.insert(WR).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:mK(n.payload),receivedAt:hK(n.receivedAt)}).execute(),yield*e.insert(JR).values({askId:t,eventId:n.id,itemKey:r.itemKey}).execute(),yield*e.update(KR).set({generation:a,askJson:null,resetPending:!0}).where(Y(KR.itemKey,r.itemKey)).execute(),yield*e.update(qR).set({generation:a}).where(Rj(Y(qR.itemKey,r.itemKey),Gj(qR.runId,e.select({runId:Q.runId}).from(Q).where(Gj(J`json_extract(${Q.stateJson}, '$._tag')`,[...lN]))))).execute(),yield*O(`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(r0)}),close:D(`CycleBudgets.close`)(function*(t,n){yield*E({askId:t,reason:n});let r=hK(yield*I_);return yield*e.transaction(e=>w(function*(){let i=(yield*KK(e).asks()).find(({id:e})=>e===t);if(i===void 0)return yield*O(`Cycle-budget Ask is no longer open; nothing to close`,{askId:t,reason:n}),!1;let a=Jw(yI)(i);return yield*e.insert(YR).values({askId:t,itemKey:i.itemKey,reason:n,askJson:a,closedAt:r}).onConflictDoUpdate({target:YR.askId,set:{reason:n,askJson:a,closedAt:r}}).execute(),yield*e.update(KR).set({askJson:null}).where(Y(KR.itemKey,i.itemKey)).execute(),yield*O(`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(sg(e=>new uz({operation:`close cycle ask`,cause:e})))}),pendingResets:D(`CycleBudgets.pendingResets`)(()=>t.pendingResets().pipe(Qh(e=>e.map(e=>new eR(e))),sg(e=>new uz({operation:`read pending cycle resets`,cause:e})))),acknowledgeReset:D(`CycleBudgets.acknowledgeReset`)(function*(t){yield*E({itemKey:t.itemKey,generation:t.generation}),yield*e.update(KR).set({resetPending:!1}).where(Rj(Y(KR.itemKey,t.itemKey),Y(KR.generation,t.generation))).execute().pipe(sg(e=>new uz({operation:`acknowledge cycle reset`,cause:e}))),yield*O(`Cycle reset trigger refresh recorded`,{itemKey:t.itemKey,generation:t.generation})})}}))},a0=new class extends B(`@usine/engine/RetryRequest`)({requestedBy:z(NM),amendment:z(vF)}){}({requestedBy:v(),amendment:v()});B(`@usine/engine/RunAgainRequest`)({step:DN,approval:fA,cycleLimit:z(pI),permissions:mA,context:vF,requestedBy:z(NM)});var o0=N([IR,HR]),s0=(e,t,n)=>{let r=zM.make(JSON.stringify([`operator-run-again`,n.reopening,n.trigger]));return new MR({event:new BM({id:RM.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})},c0=class extends B(`@usine/engine/StepExecution`)({attempt:wF,event:BM,run:bN,step:ON,repository:H,revision:Gk,task:gF,agent:sA,parentModel:z(tA),permissions:mA,resume:z(rF),reattach:sT.pipe(CT(C(!1)))}){},l0=class extends Lr()(`@usine/engine/StepExecutor`){},u0=e=>({attemptWindows:D(`RunStoreQueries.attemptWindows`)(function*(t){yield*E({attemptId:t});let[n]=yield*e.select(rq).from($).where(Y($.attemptId,t)).execute().pipe(T(lK));if(n===void 0)return yield*Hh(Error(`No attempt ${t} recorded`));let r=EF(RK(n));if(b(r))return yield*k(`The Attempt ended before end times were recorded, so it has no window and none overlaps it`,{attemptId:t}),new jF({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 jF({own:r,overlapping:(yield*e.select(rq).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(Rj(Gj(Z.itemKey,i),Y($.agent,n.agent),Ij($.attemptId,t))).orderBy($.startedAt).execute().pipe(T(lK))).flatMap(e=>jr(EF(RK(e)))).filter(e=>AF(r.value,e))})})}),d0=e=>xr(e.attempts.at(-1)).pipe(Mr(e=>b(e.outcome))),f0=e=>Or(e.salvage,e=>e._tag===`Retained`?e.pushFailure:v()),p0=(e,t,n)=>{let r=new QP({failure:n});return MF({failure:n,number:t.number,maxAutoAttempts:hF})?{_tag:`RetryAttempt`,attempt:t,outcome:r}:{_tag:`RunFailed`,attempt:t,outcome:r,state:mN(e)}},m0=(e,t,n)=>{if(e.run.state._tag!==`Running`)return{_tag:`Unchanged`,reason:`RunNotRunning`};let r=d0(e);if(b(r))return{_tag:`Unchanged`,reason:`NoOpenAttempt`};if(r.value.id!==t)return{_tag:`Unchanged`,reason:`AttemptReplaced`};let i=_r(f0(r.value),{onNone:()=>n,onSome:e=>Si(e)});return Ei(i)?p0(e.run.state,r.value,i.failure):{_tag:`RunSucceeded`,attempt:r.value,outcome:new ZP,state:pN(e.run.state),result:i.success}},h0=e=>wk(e,{Pushed:e=>y(e),PartlyPushed:({ref:e,commit:t})=>y(new rF({ref:e,commit:t})),Retained:()=>v(),Rejected:()=>v()}),g0=e=>ra(e,e=>Or(e.salvage,h0)),_0=(e,t,n,r)=>{let i=e.run.state;if(!iN(i)&&i._tag!==`Running`)return{_tag:`RunClosed`,state:i};let a=v(),o=d0(e);if(i._tag===`Running`&&x(o)){if(Pr(n,o.value.id))return{_tag:`ReattachAttempt`,state:i,attempt:o.value,resume:g0(e.attempts)};let r=p0(i,o.value,vr(f0(o.value),()=>t));if(r._tag===`RunFailed`)return r;a=y(r)}let s=x(a)?new uF:vr(r,()=>e.attempts.length===0?new aF:x(PF(i,e.attempts))?new lF:new cF);return{_tag:`StartAttempt`,state:i._tag===`Running`?i:fN(i),number:mF.make((e.attempts.at(-1)?.number??0)+1),start:s,interrupted:a,resume:g0(e.attempts)}},v0=(e,t=v())=>e.run.state._tag===`Canceled`?{_tag:`AlreadyClosed`}:nN(e.run.state)?{_tag:`Canceled`,state:gN(e.run.state,t),attempt:e.run.state._tag===`Running`?Dr(d0(e),e=>({id:e.id,worker:e.worker,outcome:new $P})):v()}:{_tag:`CancelRejected`},y0=e=>{let t=e.run.state;return t._tag===`Failed`?{_tag:`Resume`,state:hN(t)}:t._tag===`Running`&&b(d0(e))?{_tag:`ResumePending`}:{_tag:`RetryRejected`}},b0=(e,t)=>_r(e,{onNone:()=>!1,onSome:e=>!Pr(e,t)}),x0=(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},S0=(e,t)=>{if(e._tag!==`RunFailed`||Di(t))return v();switch(t.failure._tag){case`QuestionFailure`:return y(`question`);case`BlockedFailure`:return y(`blocker`);default:return v()}},C0=(e,t)=>_r(e.suppressedEventId,{onNone:()=>({_tag:`SuppressFrom`}),onSome:e=>e===t?{_tag:`Suppress`}:{_tag:`Lift`}}),w0=(e,t)=>{if(b(e))return{_tag:`OpenRun`};let n=e.value;return n.state._tag===`Running`?{_tag:`QueueEvent`}:rN(n.state)?{_tag:`SupersedeRun`,runId:n.id,state:_N(n.state,t)}:{_tag:`OpenRun`}},T0=z(yN).pipe(CT(C(v()))),E0=class extends B(`@usine/engine/internal/Claim`)({result:UR,openedRun:T0,supersededRun:T0}){},D0=class extends V(`@usine/engine/internal/AttemptStarted`)(`AttemptStarted`,{execution:c0}){},O0=class extends V(`@usine/engine/internal/AttemptRecoveryFailed`)(`AttemptRecoveryFailed`,{}){},k0=class extends V(`@usine/engine/internal/RunClosed`)(`RunClosed`,{}){},A0=w(function*(){let e=yield*hz,t=yield*WO,n=cq(e),r=D(`RunStore.admitRun`)(function*(e,t,n){let r=yield*e.cycles.admit(t);return x(r)?new HR({eventId:t.event.id,ask:r.value}):(yield*e.createRun(t,t.event.id,n),yield*e.cycles.reserve(t,n),new IR({eventId:t.event.id,runId:n}))}),i=D(`RunStore.openRun`)(function*(e,t,n,i=v()){let a=yield*r(e,t,n);return new E0({result:a,openedRun:a._tag===`Claimed`?y(n):v(),supersededRun:i})}),a=e=>PR(e).pipe(Tg(WO,t)),o=D(`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 y({_tag:`Owned`,run:t})}let r=(yield*e.ignoredEvent(t))[0];return r===void 0?v():y({_tag:`Ignored`,reason:r.reason})}),s=D(`RunStore.claimEvent`)(function*(e,t,n){if(!(yield*e.cycles.isCurrentEvent(t)))return new E0({result:new BR({eventId:t.event.id,reason:`superseded`})});let r=yield*e.loopItems.suppression(t.loop,t.itemKey);if(x(r)){let n=C0(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*O(`First Item state after the Agent stopped for the operator; it waits for the operator`,i),new E0({result:new VR({eventId:t.event.id,runId:r.value.runId})});case`Suppress`:return yield*O(`Item unchanged since the Agent stopped for the operator; no Run opens`,i),new E0({result:new VR({eventId:t.event.id,runId:r.value.runId})});case`Lift`:yield*e.loopItems.lift(t.loop,t.itemKey),yield*O(`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=w0(a===void 0?v():y((yield*e.snapshot(a.runId)).run),t.event.id);switch(yield*O(`Event claim decided`,{eventId:t.event.id,decision:o._tag}),o._tag){case`QueueEvent`:return new E0({result:new LR({eventId:t.event.id})});case`SupersedeRun`:return yield*e.updateState(o.runId,o.state),yield*i(e,t,n,y(o.runId));case`OpenRun`:return yield*i(e,t,n)}}),c=D(`RunStore.recordAndClaim`)(function*(t,n){return yield*E({eventId:t.event.id,runId:n,loop:t.loop,itemKey:t.itemKey}),yield*e.transaction(e=>w(function*(){let r=cq(e),i=yield*r.recordTriggerEvent(t),c=yield*r.loopItems.sighted(i.loop,i.itemKey,i.event.id),l=vr(yield*r.newestReopening(i.event.id),()=>({submission:i,reopening:0})),u=l.submission.event.id,d=yield*o(r,u);if(b(d))return yield*s(r,l.submission,l.reopening===0?n:yield*a(l.submission));let f=x0(d.value,b0(c,i.event.id));switch(f._tag){case`JoinRun`:return yield*O(`Event joined its existing Run`,{eventId:u,runId:f.run.id,state:f.run.state._tag}),new E0({result:new IR({eventId:u,runId:f.run.id})});case`StayIgnored`:return yield*O(`Event remains ignored`,{eventId:u,reason:f.reason}),new E0({result:new BR({eventId:u,reason:f.reason})});case`ReopenEvent`:{let e=l.reopening+1,n=yield*r.recordTriggerEvent(FR(t,i.event.dedupKey,e),y({eventId:i.event.id,reopening:e}));return yield*O(`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))}}}))},AK(`submit event`)),l=D(`RunStore.parkForApproval`)(function*(t){return yield*E({runId:t}),yield*e.transaction(e=>w(function*(){let n=cq(e),r=yield*n.snapshot(t);if(r.run.state._tag!==`Pending`)return r.run.state;let i=uN(r.run.state);return yield*n.updateState(t,i),i}))},AK(`park run for approval`)),u=D(`RunStore.applyFinish`)(function*(e,t,n){if(yield*E({runId:t}),n._tag===`Unchanged`){yield*O(`Attempt completion ignored`,{runId:t,reason:n.reason});return}let{attempt:r,outcome:i}=n;yield*E({attemptId:r.id});let a={runId:t,attemptId:r.id,number:r.number,decision:n._tag};yield*O(`Attempt completion decided`,wk(i,{Failed:({failure:e})=>({...a,failure:e._tag}),Succeeded:()=>a}));let o=yield*I_;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=D(`RunStore.suppressForOperator`)(function*(e,t,n){let r=t.run.id,i=Dr(yield*e.nextQueued(r),({submission:e})=>e.event.id),a={runId:r,loop:t.run.loop,itemKey:t.itemKey,stop:n};(yield*e.loopItems.startSuppression(t.run.loop,t.itemKey,r,t.event.id,i))?yield*O(`Agent stopped for the operator; its Loop suppresses the Item`,{...a,suppressedEventId:vr(i,()=>`none yet`)}):yield*O(`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 c0({attempt:t,event:e.event,run:new bN({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=D(`RunStore.beginAttempt`)(function*(t,n,r){return yield*E({runId:t,worker:n}),yield*e.transaction(e=>w(function*(){let i=cq(e),a=yield*i.snapshot(t),o=new HP({message:`The orchestrator stopped during the attempt`,cause:Error(`attempt interrupted by orchestrator restart`)}),s=yield*i.nextStart(t),c=_0(a,o,r,s);if(c._tag===`RunClosed`)return yield*O(`Attempt start skipped`,{runId:t,state:c.state._tag}),new k0;if(c._tag===`RunFailed`)return yield*u(i,t,c),new O0;if(c._tag===`ReattachAttempt`){let e=yield*I_,r=new wF({...c.attempt,reattachedAt:y(e)});return yield*i.recordReattach(r.id,e),yield*E({attemptId:r.id}),yield*O(`Attempt reattached after an orchestrator restart`,{runId:t,attemptId:r.id,number:r.number,worker:r.worker}),r.worker!==n&&(yield*Zg(`Reattached Attempt keeps its own Worker, not the reserved one`,{runId:t,attemptId:r.id,worker:r.worker,reservedWorker:n})),new D0({execution:f(a,{attempt:r,state:c.state,resume:c.resume,reattach:!0})})}x(c.interrupted)&&(yield*u(i,t,c.interrupted.value)),a.run.state._tag!==c.state._tag&&(yield*i.updateState(t,c.state));let l=pF.make(`${t}/${a.step.name}/${c.number}`),d=yield*I_,p=new wF({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:v(),endedAt:v(),salvage:v(),start:y(c.start),reattachedAt:v()});return yield*i.addAttempt(p),x(s)&&(yield*i.setNextStart(t,v())),yield*O(`Attempt started`,{runId:t,attemptId:l,number:c.number,worker:n,start:c.start._tag,resumesFrom:Dr(c.resume,({ref:e})=>e)}),new D0({execution:f(a,{attempt:p,state:c.state,resume:c.resume,reattach:!1})})}))},AK(`begin attempt`)),m=D(`RunStore.recordSalvage`)(function*(t,n){yield*E({attemptId:t,salvage:n._tag}),yield*e.transaction(e=>cq(e).recordSalvage(t,n)),yield*O(`Attempt salvage recorded`,wk(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:Dr(r,({message:e})=>e)}),Rejected:({path:e,commit:n})=>({attemptId:t,path:e,commit:n})}))},AK(`record attempt salvage`)),h=D(`RunStore.recordComments`)(function*(t,n){yield*E({attemptId:t,comments:n.length}),yield*e.transaction(e=>cq(e).recordComments(t,n)),yield*O(`Recorded the comments an Attempt posted before it ended without success`,{attemptId:t,comments:n.map(({kind:e,url:t})=>`${e} ${t.href}`)})},AK(`record attempt comments`)),g=D(`RunStore.recordOutOfMemory`)(function*(t,n){yield*E({attemptId:t,container:n.container,kills:n.kills});let r=yield*e.transaction(e=>cq(e).recordOutOfMemory(t,n));yield*O(`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})},AK(`record attempt out-of-memory kills`)),_=D(`RunStore.attemptWindows`)(function*(t){yield*E({attemptId:t});let n=yield*u0(e).attemptWindows(t);return yield*k(`Read the Attempt's window and the Attempts of the same Agent that overlap it on its Item`,{attemptId:t,recorded:x(n.own),ended:Fr(n.own,({endedAt:e})=>x(e)),overlapping:n.overlapping.map(e=>e.attemptId)}),n},AK(`read attempt windows`)),ee=D(`RunStore.discardLeftovers`)(function*(t){yield*E({worker:t});let n=yield*I_;return yield*e.transaction(e=>UK(e).discardLeftovers(t,n))},AK(`discard attempt leftovers`)),te=D(`RunStore.openAttempts`)(function*(t){return yield*E({worker:t}),yield*UK(e).openAttempts(t)},AK(`count open attempts`)),ne=D(`RunStore.finishAttempt`)(function*(t,n){return yield*E({runId:t.runId,attemptId:t.id}),yield*e.transaction(e=>w(function*(){let r=cq(e),i=yield*r.snapshot(t.runId),a=m0(i,t.id,n);yield*u(r,t.runId,a);let o=S0(a,n);return x(o)&&(yield*d(r,i,o.value)),a}))},AK(`finish attempt`)),re=D(`RunStore.resolveFailure`)(function*(t,n,r){return yield*E({runId:t,attemptId:n}),yield*e.transaction(e=>w(function*(){let i=cq(e),a=yield*i.snapshot(t),o=a.attempts.at(-1);if(!aN(a.run.state).canResolveFailure||o?.id!==n)return yield*O(`Failure resolution rejected; Run or Attempt changed`,{runId:t,attemptId:n,state:a.run.state._tag,latestAttemptId:o?.id}),yield*new cz({runId:t,operation:`resolveFailure`,state:a.run.state._tag});if(Pr(a.resolvedFailureAttemptId,n))return yield*O(`Run failure already resolved`,{runId:t,attemptId:n}),!1;let s=new yF({resolvedAt:yield*I_,operator:r});yield*i.resolveFailure(t,n,s);let c=yield*i.loopItems.liftRun(t);return yield*O(`Run failure resolved`,{runId:t,attemptId:n,liftedSuppression:c,resolvedAt:G_(s.resolvedAt),operator:S(r)}),c}))},AK(`resolve run failure`)),ie=D(`RunStore.approve`)(function*(t,n,r){return yield*E({runId:t,eventId:n.id,channel:r.channel}),yield*e.transaction(e=>w(function*(){let i=cq(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,dN(a.run.state)),!0):yield*new cz({runId:t,operation:`approve`,state:a.run.state._tag})}))},AK(`approve run`)),ae=D(`RunStore.retry`)(function*(t,n=a0){let{amendment:r,requestedBy:i}=n;return yield*E({runId:t}),yield*e.transaction(e=>w(function*(){let n=cq(e),a=yield*n.snapshot(t),o=y0(a);if(yield*O(`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?(x(r)&&(yield*n.amend(t,r.value),yield*O(`Run effective task and Agent amended`,{runId:t,agent:r.value.agent.name})),(yield*n.loopItems.liftRun(t))&&(yield*O(`Operator retry lifts the suppression of the Item`,{runId:t})),yield*n.setNextStart(t,y(x(r)?new sF({operator:i}):new oF({operator:i}))),yield*n.updateState(t,o.state),!0):(yield*O(`Operator retry rejected; another Run is open on the Item`,{runId:t,openRunId:e.runId,loop:a.run.loop,itemKey:a.itemKey}),yield*new lz({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`&&b(r)?!1:yield*new cz({runId:t,operation:`retry`,state:a.run.state._tag})}))},AK(`retry run`)),oe=D(`RunStore.runAgain`)(function*(t,n){yield*E({runId:t,agent:n.context.agent.name});let i=yield*I_;return yield*e.transaction(e=>w(function*(){let o=cq(e),s=yield*o.snapshot(t),{loop:c}=s.run,{itemKey:l}=s;if(!aN(s.run.state).canRunAgain)return yield*O(`Run again rejected; only a succeeded or canceled Run runs again`,{runId:t,state:s.run.state._tag}),yield*new cz({runId:t,operation:`runAgain`,state:s.run.state._tag});let u=(yield*o.blockingRun(c,l))[0];if(u!==void 0)return yield*O(`Run again rejected; another Run is open on the Item`,{runId:t,openRunId:u.runId,loop:c,itemKey:l}),yield*new lz({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=vr(yield*o.reopenedEvent(s.event.id),()=>({eventId:s.event.id,dedupKey:s.event.dedupKey})),f=_r(yield*o.newestReopening(d.eventId),{onNone:()=>1,onSome:e=>e.reopening+1}),p=_r(yield*o.cycles.get(l),{onNone:()=>mI.make(0),onSome:e=>e.generation}),m=s0(s,n,{trigger:d.dedupKey,reopening:f,generation:p,receivedAt:i}),h=yield*o.recordTriggerEvent(m,y({eventId:d.eventId,reopening:f}));yield*o.recordRunAgain(h.event.id,new EW({from:t,requestedBy:n.requestedBy}));let g=yield*r(o,h,yield*a(h));return yield*O(`Run again decided`,wk(g,{Claimed:({runId:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`OpenRun`,openedRunId:e,requestedBy:vr(n.requestedBy,()=>`none`)}),CycleBlocked:({ask:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`CycleBlocked`,askId:e.id,requestedBy:vr(n.requestedBy,()=>`none`)})})),g}))},AK(`run again`)),se=D(`RunStore.cancel`)(function*(t){return yield*E({runId:t}),yield*e.transaction(e=>w(function*(){let n=cq(e),r=yield*n.snapshot(t),i=v0(r,yield*PM);if(yield*O(`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 cz({runId:t,operation:`cancel`,state:r.run.state._tag});let a=yield*I_;if(x(i.attempt)){let{id:e,outcome:t}=i.attempt.value;yield*n.closeAttempt(e,t,a)}return yield*n.updateState(t,i.state,a),{_tag:`Canceled`,openAttempt:Dr(i.attempt,({id:e,worker:t})=>({id:e,worker:t})),loop:r.run.loop,itemKey:r.itemKey}}))},AK(`cancel run`)),ce=D(`RunStore.revoke`)(function*(t,n){return yield*e.transaction(e=>w(function*(){let r=cq(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);rN(t.run.state)&&(yield*r.updateState(e.runId,vN(t.run.state)))}return i.map(e=>e.runId)}))},AK(`revoke run`)),le=D(`RunStore.revokeQueued`)(function*(e){let{loop:t,itemKey:r,event:i}=e.submission;return yield*E({loop:t,itemKey:r,eventId:i.id}),yield*n.revokeQueued(t,r,e.eventIds)},AK(`revoke queued events`)),ue=D(`RunStore.claimQueued`)(function*(t,n){return yield*e.transaction(e=>w(function*(){let r=cq(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||x(yield*r.loopItems.suppression(t.loop,t.itemKey))||!(yield*r.cycles.isCurrentEvent(t))?v():(yield*i(r,t,n)).openedRun:(yield*O(`Queued Event already opened its Run`,{eventId:t.event.id,runId:a[0].runId}),v())}))},AK(`claim queued event`)),de=D(`RunStore.appendTranscript`)(function*(t,n){let r=yield*I_;yield*e.transaction(e=>w(function*(){let i=cq(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*k(`Transcript envelope already recorded; keeping the first copy`,{attemptId:n.attemptId,direction:t,sequence:n.sequence}))}))},AK(`append attempt transcript`)),fe=D(`RunStore.transcript`)(function*(e){return yield*n.transcript(e)},AK(`read attempt transcript`));return{approve:ie,appendTranscript:de,beginAttempt:p,cancel:se,claimQueued:ue,finishAttempt:ne,nextQueued:e=>n.nextQueued(e).pipe(AK(`find queued event`)),parkForApproval:l,pendingContinuations:n.pendingContinuations().pipe(AK(`list pending continuations`)),runIdsToDrive:n.runIdsToDrive().pipe(AK(`list the runs to drive`)),recordAndClaim:c,salvageCandidates:n.salvageCandidates().pipe(AK(`list salvage candidates`)),salvageCandidate:e=>n.salvageCandidate(e).pipe(AK(`read a salvage candidate`)),recordSalvage:m,recordComments:h,recordOutOfMemory:g,attemptWindows:_,discardLeftovers:ee,openAttempts:te,submission:e=>n.eventRouteByRun(e).pipe(T(t=>t[0]===void 0?zh(new sz({runId:e})):C(NK(t[0]))),AK(`read run submission`)),resolveFailure:re,retry:ae,revoke:ce,revokeQueued:le,runAgain:oe,snapshot:e=>n.snapshot(e).pipe(AK(`read run`)),transcript:fe}}),j0=class e extends Lr()(`@usine/engine/internal/RunStore`){static layer=qf(e,A0)},M0=R.pipe(I(`ItemProjectionSource`)),N0=R.pipe(I(`ItemContentHash`)),P0=class extends B(`@usine/engine/ItemProjection`)({itemKey:dI,repository:H,source:M0,number:fI,contentHash:N0,payload:FE,goneAt:_E(gE).pipe(TT(C(null)),CT(C(v())))}){},F0=j({itemKey:P0.fields.itemKey,repository:H,source:M0,number:fI,contentHash:N0,payload:FE,goneAt:P0.fields.goneAt}),I0=zw(M(F0)),L0=zw(M(fI)),R0=Jw(FE),z0=Jw(F0.fields.goneAt),B0=e=>t=>sg(t,t=>new uz({operation:e,cause:t})),V0={itemKey:nz.itemKey,repository:nz.repository,source:nz.source,number:nz.itemNumber,contentHash:nz.contentHash,payload:nz.payloadJson,goneAt:nz.goneAt},H0=w(function*(){let e=yield*hz;return{get:D(`ItemProjectionReader.get`)(function*(t){yield*E({itemKey:t});let[n]=yield*I0(yield*e.select(V0).from(nz).where(Y(nz.itemKey,t)).execute(),{onExcessProperty:`error`});return Dr(xr(n),e=>new P0(e))},B0(`read item projection`)),list:D(`ItemProjectionReader.list`)(function*(t,n){return yield*E({repository:t,limit:n.limit}),(yield*I0(yield*e.select(V0).from(nz).where(Y(nz.repository,t)).orderBy(oM(nz.itemNumber)).limit(n.limit).execute(),{onExcessProperty:`error`})).map(e=>new P0(e))},B0(`list item projections`)),openIssues:D(`ItemProjectionReader.openIssues`)(function*(t){return yield*E({repository:t}),yield*L0((yield*e.select({number:nz.itemNumber}).from(nz).where(Rj(Y(nz.repository,t),Y(nz.source,`issue`),qj(nz.goneAt),J`json_extract(${nz.payloadJson}, '$.state') = 'OPEN'`)).orderBy(aM(nz.itemNumber)).execute()).map(({number:e})=>e))},B0(`list open issue projections`))}}),U0=w(function*(){let e=yield*hz;return{upsert:D(`ItemProjectionWriter.upsert`)(function*(t){yield*E({repository:t.repository,item:t.number,itemKey:t.itemKey});let n=z0(t.goneAt);return(yield*e.insert(nz).values({itemKey:t.itemKey,repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:R0(t.payload),goneAt:n}).onConflictDoUpdate({target:nz.itemKey,set:{repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:R0(t.payload),goneAt:n},setWhere:J`${nz.contentHash} != ${t.contentHash} OR ${nz.goneAt} IS NOT ${n}`}).returning({itemKey:nz.itemKey}).execute()).length===0?(yield*k(`Item projection already matched the observed snapshot`,{repository:t.repository,item:t.number,contentHash:t.contentHash}),!1):(yield*k(`Item projection updated from trigger polling`,{repository:t.repository,item:t.number,source:t.source,contentHash:t.contentHash}),!0)},B0(`write item projection`)),markGone:D(`ItemProjectionWriter.markGone`)(function*(t,n){return yield*E({itemKey:t}),(yield*e.update(nz).set({goneAt:z0(y(n))}).where(Rj(Y(nz.itemKey,t),qj(nz.goneAt))).returning({itemKey:nz.itemKey}).execute()).length===0?(yield*k(`Item projection already gone or never stored`,{itemKey:t}),!1):(yield*O(`Item projection marked gone from GitHub`,{itemKey:t,goneAt:G_(n)}),!0)},B0(`mark item projection gone`))}}),W0=class e extends Lr()(`@usine/engine/ItemProjectionReader`){static layer=qf(e,H0)},G0=class e extends Lr()(`@usine/engine/ItemProjectionWriter`){static layer=qf(e,U0)},K0=class extends Lr()(`@usine/engine/TriggerCondition`){},q0=class extends B(`@usine/engine/LoopRuntimeState`)({loop:uA,paused:sT}){},J0=e=>t=>t.pipe(sg(t=>new uz({operation:e,cause:t}))),Y0=w(function*(){let e=yield*hz,t=D(`LoopControl.stateFor`)(function*(t){yield*E({loop:t});let n=(yield*e.select({loop:az.loopName,paused:az.paused}).from(az).where(Y(az.loopName,t)).limit(1).execute())[0];return n===void 0?new q0({loop:t,paused:!1}):new q0(n)},J0(`read loop runtime state`)),n=D(`LoopControl.states`)(function*(){return(yield*e.select({loop:az.loopName,paused:az.paused}).from(az).orderBy(aM(az.loopName)).execute()).map(e=>new q0(e))},J0(`list loop runtime states`)),r=D(`LoopControl.write`)(function*(n){yield*E({loop:n.loop});let r=yield*t(n.loop);return r.paused===n.paused?(yield*k(`Loop runtime state was already set`,{loop:n.loop,paused:n.paused}),r):(yield*e.insert(az).values({loopName:n.loop,paused:n.paused}).onConflictDoUpdate({target:az.loopName,set:{paused:n.paused}}).execute().pipe(J0(`write loop runtime state`)),yield*O(n.paused?`Loop paused`:`Loop unpaused`,{loop:n.loop,paused:n.paused}),n)});return{isPaused:D(`LoopControl.isPaused`)(function*(e){return(yield*t(e)).paused}),pause:D(`LoopControl.pause`)(e=>r(new q0({loop:e,paused:!0}))),states:n(),unpause:D(`LoopControl.unpause`)(e=>r(new q0({loop:e,paused:!1})))}}),X0=class e extends Lr()(`@usine/engine/LoopControl`){static layer=qf(e,Y0)},Z0=M(R),Q0=class extends B(`@usine/engine/BoardMoveRecord`)({repository:H,itemKey:dI,at:hE,fromLane:R,toLane:R,added:Z0.check(GT()),removed:Z0}){},$0=zw(M(j({repository:Q0.fields.repository,itemKey:Q0.fields.itemKey,at:gE,fromLane:Q0.fields.fromLane,toLane:Q0.fields.toLane,added:Q0.fields.added,removed:Q0.fields.removed}))),e2=Jw(Q0.fields.added),t2=Jw(Q0.fields.removed),n2=e=>t=>sg(t,t=>new uz({operation:e,cause:t})),r2=w(function*(){let e=yield*hz;return{record:D(`BoardMoves.record`)(function*(t){yield*E({repository:t.repository,itemKey:t.itemKey}),yield*e.insert(iz).values({repository:t.repository,itemKey:t.itemKey,movedAt:hK(t.at),fromLane:t.fromLane,toLane:t.toLane,addedJson:e2(t.added),removedJson:t2(t.removed)}).execute(),yield*k(`Recorded a Board move before writing its labels`,{repository:t.repository,itemKey:t.itemKey,at:hK(t.at),fromLane:t.fromLane,toLane:t.toLane})},n2(`record board move`)),onItem:D(`BoardMoves.onItem`)(function*(t,n){return yield*E({itemKey:t}),(yield*$0(yield*e.select({repository:iz.repository,itemKey:iz.itemKey,at:iz.movedAt,fromLane:iz.fromLane,toLane:iz.toLane,added:iz.addedJson,removed:iz.removedJson}).from(iz).where(Rj(Y(iz.itemKey,t),Hj(iz.movedAt,hK(n)))).orderBy(aM(iz.movedAt),aM(iz.moveId)).execute(),{onExcessProperty:`error`})).map(e=>new Q0(e))},n2(`read board moves`))}}),i2=class e extends Lr()(`@usine/engine/BoardMoves`){static layer=qf(e,r2)},a2=class extends Lr()(`@usine/engine/RunEngineShutdown`){},o2=class e extends Lr()(`@usine/engine/AttemptAdmission`){static layer=qf(e,w(function*(){let e=yield*Cg(a2),t=x(e)?e.value:yield*hf(),n=yield*Mk(new Set),r=yield*hf(),i=D(`AttemptAdmission.enter`)(function*(e){yield*E({runId:e});let r=yield*Fk(n,n=>yf(t)?[!1,n]:[!0,new Set([...n,e])]);return r||(yield*O(`Attempt deferred until restart; the engine is draining`,{runId:e})),r}),a=D(`AttemptAdmission.leave`)(function*(e){yield*E({runId:e});let i=yield*Lk(n,t=>new Set([...t].filter(t=>t!==e)));(yield*vf(t))&&(yield*O(`Attempt settled during drain`,{runId:e,remainingRunIds:[...i]}),i.size===0&&(yield*bf(r,void 0)))});return{withAttempt:D(`AttemptAdmission.withAttempt`)(function*(e,t){return yield*E({runId:e}),yield*Dg(i(e),e=>e?t:Rh,t=>t?a(e):Ih)}),drain:D(`AttemptAdmission.drain`)(function*(){yield*bf(t,void 0);let e=yield*Nk(n);yield*O(`Engine drain started; no further Attempts will be admitted`,{activeRunIds:[...e]}),e.size===0&&(yield*bf(r,void 0)),yield*gf(r),yield*O(`Engine drain completed; all admitted Attempts settled`)})}}))},s2=class extends jE(`@usine/engine/internal/ParentStopUnconfirmedError`)(`ParentStopUnconfirmedError`,{attemptId:pF,worker:kN,cause:QT()}){},c2=(e,t)=>{let n=new Map(e);return n.delete(t),n},l2=D(`CheckoutRecovery.for`)(function*(e,t){let n=yield*Mk(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(lg(e=>Zg(`Attempt salvage reconciliation failed; work retained`,{attemptId:n.attemptId,worker:n.worker,message:String(e)})),fg),i=D(`CheckoutRecovery.keep`)(function*(e){yield*t.occupy(e.worker,e.attemptId).pipe(T(e=>Mg(e.release).pipe(Qh(t=>({worker:e.worker,release:t,checkoutKept:!0})))),T(t=>Ik(n,n=>new Map(n).set(e.attemptId,t))),Fg)}),a=D(`CheckoutRecovery.recoverOpen`)(function*(e){let n={attemptId:e.attemptId,worker:e.worker};yield*E(n);let a=yield*t.isLive(e.attemptId).pipe(Yh);if(Di(a)&&!a.success)return yield*r(e);Ei(a)?yield*Xg(`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*O(`Leaving the checkout of an open Attempt whose parent task is live for its Run to reattach`,n),yield*i(e),yield*O(`Occupied a slot on the Worker of an open Attempt kept for its Run to reattach`,n)}),o=D(`CheckoutRecovery.recoverClosed`)(function*(e){let n={attemptId:e.attemptId,runId:e.runId,worker:e.worker};yield*E(n);let a=yield*t.interrupt(e.attemptId,`startup`).pipe(Yh);return Di(a)?(yield*r(e),v()):(yield*Xg(`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),y(e))}),s=D(`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*Xg(`Attempts recorded on Workers that are not configured were not reconciled; their checkouts stay until those Workers are configured again or their leftovers are discarded`,{attempts:s.length,workers:[...new Set(s.map(({worker:e})=>e))].sort().join(`,`)})),ha(yield*Ah(i,e=>e.open?a(e).pipe($h(v())):o(e)))}),c=D(`CheckoutRecovery.reattachSlot`)(function*(e){return Dr(Mr(Sr((yield*Nk(n)).get(e)),({checkoutKept:e})=>e),t=>({worker:t.worker,release:Nk(n).pipe(T(n=>n.get(e)===t?O(`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=D(`CheckoutRecovery.acquired`)(function*(e){(yield*Fk(n,t=>t.get(e)?.checkoutKept===!0?[!0,c2(t,e)]:[!1,t]))&&(yield*O(`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=D(`CheckoutRecovery.hold`)(function*(e,t){let r={attemptId:e,worker:t.worker};yield*E(r);let i=yield*Mg(t.release);(yield*Fk(n,n=>n.has(e)?[!1,n]:[!0,new Map(n).set(e,{worker:t.worker,release:i,checkoutKept:!1})]))?yield*O(`The Attempt keeps its Run's slot until its parent task is confirmed stopped`,r):(yield*k(`The Attempt already has a slot kept until its parent task is confirmed stopped; releasing its Run's lease`,r),yield*i)},Fg),d=D(`CheckoutRecovery.confirmStop`)(function*(e,n,r){let i={attemptId:e,worker:n.worker,checkoutKept:n.checkoutKept,reason:r};yield*E(i);let a=yield*t.interrupt(e,r).pipe(Yh);if(Di(a))return;let o={...i,errorTag:a.failure._tag,message:a.failure.message};return yield*n.checkoutKept?Xg(`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):Xg(`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 s2({attemptId:e,worker:n.worker,cause:a.failure})}),f=D(`CheckoutRecovery.recoverKept`)(function*(n){let i=yield*e.salvageCandidate(n).pipe(Yh);if(Ei(i)){yield*Zg(`Could not read the Attempt whose checkout startup kept; the checkout stays until the next startup`,{attemptId:n,errorTag:i.failure._tag});return}if(b(i.success)){yield*Xg(`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*E(o),(yield*t.workers).includes(a.worker)?(yield*O(`Reconciling the checkout startup kept for an Attempt that was not reattached`,o),yield*r(a)):yield*Xg(`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:D(`CheckoutRecovery.reconcile`)(function*(e,t){yield*E({attemptId:e,reason:t});let r=(yield*Nk(n)).get(e);r===void 0?yield*k(`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*Ik(n,t=>c2(t,e)).pipe(qh(r.release),Fg),yield*O(`Released the slot kept for an Attempt whose parent task is confirmed stopped`,{attemptId:e,worker:r.worker,checkoutKept:r.checkoutKept}))})}}),u2=class extends B(`@usine/engine/UnconfirmedStop`)({attemptId:pF,runId:yN,loop:uA,itemKey:dI,worker:kN,reason:_F}){},d2=class e extends Lr()(`@usine/engine/UnconfirmedStops`){static empty=Gf(e)({list:C([])})},f2=e=>ig(e,{EnginePersistenceError:e=>new HP({message:`Runtime store error: could not ${e.operation}`,cause:e}),RunNotFoundError:e=>Hh(e),RunOperationRejectedError:e=>Hh(e),RunRetryBlockedError:e=>Hh(e)}),p2=4,m2=`100 millis`,h2=(e,t)=>n=>n.pipe(lg(n=>n._tag===`EnginePersistenceError`?Xg(`A Run store operation failed to persist`,{runId:e,operation:t,cause:n.cause}):Ih),dg({schedule:sh(m2),times:p2,while:e=>e._tag===`EnginePersistenceError`})),g2=e=>Or(e,e=>e._tag===`Live`?y(e.attempt):v()),_2=class e extends Lr()(`@usine/engine/internal/RunDriver`){static layer=qf(e,w(function*(){let e=yield*j0,t=yield*l0,n=yield*o2,r=yield*K0,i=yield*G0,a=yield*WO,o=yield*YO(),s=yield*l2(e,t),c=yield*Mk(new Map),l=yield*Mk(new Map),u=(e,t)=>Fk(l,n=>n.get(e)===t?[!0,c2(n,e)]:[!1,n]).pipe(T(n=>n?t.release:k(`The Run's slot stays with its Attempt until the parent task is confirmed stopped`,{runId:e,worker:t.worker}))),d=D(`RunDriver.launch`)(function*(e){if(yield*E({runId:e}),yield*nk(o,e)){yield*k(`The Run's fiber already runs in this process`,{runId:e});return}yield*k(`Starting the Run's fiber`,{runId:e});let t=yield*Xh(Rg);yield*ak(o,e,ne(e).pipe(ug(t=>Yd(t)?Ih:Zg(`The Run's fiber stopped on an engine failure; the next reconcile or a restart resumes it`,{runId:e,cause:t})),Bg(`RunDriver.drive`,{root:!0,links:jr(Dr(t,e=>({span:e,attributes:{}})))}),ag(e=>Yd(e)?Bh(e):Ih)),{onlyIfMissing:!0})}),f=D(`RunDriver.resume`)(function*(e){yield*E({runId:e});let t=yield*ek(o,e);x(t)&&(yield*k(`Waiting for the Run's previous fiber to end`,{runId:e}),yield*IE(t.value)),yield*d(e)}),p=D(`RunDriver.stop`)(function*(e){yield*E({runId:e}),(yield*nk(o,e))?(yield*rk(o,e),yield*O(`The closed Run's fiber stopped`,{runId:e})):yield*k(`The closed Run has no fiber in this process`,{runId:e})}),m=D(`RunDriver.markItemGone`)(function*(e,t){return yield*E({runId:e,itemKey:t.itemKey}),yield*i.markGone(t.itemKey,yield*I_).pipe(h2(e,`mark the item's projection gone`),ng(n=>Xg(`Could not mark the gone Item's projection; its Board card stays in place`,{completedRunId:e,itemKey:t.itemKey,errorTag:n._tag}).pipe($h(!1))))}),h=D(`RunDriver.continueWithNewest`)(function*(t){yield*E({runId:t});let n=yield*e.nextQueued(t).pipe(h2(t,`read the queued events`));if(b(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(h2(t,`revoke the queued events`));if(s===`no-longer-matches`){yield*O(`Queued Event no longer matches its trigger; revoked`,{...o,revokedEvents:r});return}let a=yield*m(t,i);yield*O(`Queued Event's Item is gone from its source; revoked its queued Events`,{...o,revokedEvents:r,projectionMarkedGone:a});return}let c=yield*PR(i).pipe(Tg(WO,a)),l=yield*e.claimQueued(i,c).pipe(h2(t,`claim the queued event`));b(l)?yield*O(`Queued Event still matches its trigger but could no longer be claimed; no Run opened`,o):(yield*O(`Queued Event still matches its trigger; opening its Run`,{...o,runId:l.value}),yield*d(l.value))}),g=D(`RunDriver.openAttempt`)(function*(n){yield*E({runId:n});let r=yield*e.snapshot(n).pipe(h2(n,`read the run`)),i=r.attempts.at(-1);if(r.run.state._tag!==`Running`||i===void 0||x(i.outcome))return v();let a={runId:n,attemptId:i.id,worker:i.worker};yield*E({attemptId:i.id,worker:i.worker});let o=yield*t.isLive(i.id).pipe(Yh);if(Ei(o))return yield*Xg(`Could not read whether the open Attempt is live; the Run does not reattach it`,{...a,errorTag:o.failure._tag,message:o.failure.message}),y({_tag:`Interrupted`,attempt:i});if(o.success)return yield*O(`The open Attempt's parent task is live; reattaching it`,a),y({_tag:`Live`,attempt:i});let s=yield*t.outcome(i.id).pipe(Yh);if(Ei(s))return yield*Xg(`Could not read the open Attempt's stored outcome; the Run does not reattach it`,{...a,errorTag:s.failure._tag,message:s.failure.message}),y({_tag:`Interrupted`,attempt:i});if(b(s.success))return yield*O(`The open Attempt's parent task is gone; the Run does not reattach it`,a),y({_tag:`Interrupted`,attempt:i});let c=s.success.value;return yield*O(`The open Attempt's parent task finished before this process recorded it; finishing the Attempt with its stored result`,{...a,outcome:Ai(c,{onSuccess:()=>`Succeeded`,onFailure:({_tag:e})=>e})}),y({_tag:`Finished`,attempt:i,result:c})}),_=D(`RunDriver.slot`)(function*(e,n,r,i){yield*E({runId:e});let a=C(r),o=g2(r);if(x(o)){let t=yield*s.reattachSlot(o.value.id);if(x(t))return yield*O(`The Run reattaches its open Attempt in the slot startup occupied on its Worker`,{runId:e,attemptId:o.value.id,worker:t.value.worker}),{lease:t.value,open:a}}return{lease:yield*i(t.reserve(e,n,Dr(o,({worker:e})=>e))),open:x(o)?g(e):a}}),ee=D(`RunDriver.attempt`)(function*(n,r,i,a){yield*E({runId:n,worker:i});let o=yield*a;if(b(g2(o))&&x(yield*oe(r)))return yield*O(`Run waits for an unconfirmed stop after reserving a worker slot`,{runId:n,worker:i,itemKey:r.itemKey}),`WaitingForStop`;if(x(o)&&o.value._tag===`Finished`)return(yield*e.finishAttempt(o.value.attempt,o.value.result).pipe(h2(n,`finish the attempt`)))._tag;let c=yield*e.beginAttempt(n,i,Dr(g2(o),({id:e})=>e)).pipe(h2(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(f2),salvage:t=>e.recordSalvage(c.execution.attempt.id,t).pipe(f2),comments:t=>e.recordComments(c.execution.attempt.id,t).pipe(f2),outOfMemory:t=>e.recordOutOfMemory(c.execution.attempt.id,t).pipe(f2),windows:e.attemptWindows(c.execution.attempt.id).pipe(h2(n,`read the attempt windows`),f2),transcript:e.transcript(new TG({attemptId:c.execution.attempt.id})).pipe(h2(n,`read the attempt transcript`),f2,Qh(e=>e.flatMap(({envelope:e})=>e.version===7?[e]:[]))),checkoutAcquired:s.acquired(c.execution.attempt.id)}).pipe(og(e=>Zg(`Step executor defect; operator intervention required`,{runId:n,attemptId:c.execution.attempt.id,defect:e instanceof Error?e.message:String(e)}).pipe(qh(new UP({message:`The step executor crashed with an unexpected error`,cause:e})))),Yh);return c.execution.reattach&&Ei(l)&&(yield*se(new u2({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,worker:i,reason:`failed`}))),Ei(l)&&(yield*ae({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(h2(n,`finish the attempt`)))._tag}),te=D(`RunDriver.awaitProviderRetry`)(function*(t){yield*E({runId:t});let n=yield*e.snapshot(t).pipe(h2(t,`read the retry delay`)),r=PF(n.run.state,n.attempts);if(b(r))return;let{retryAt:i,nextAttempt:a,message:o}=r.value,s=H_(i)-H_(yield*I_);yield*O(`Run waits before retrying provider capacity`,{runId:t,nextAttempt:a,message:o,retryAt:G_(i),delayMillis:Math.max(0,s)}),s>0&&(yield*pg(s))}),ne=Yg(function*(t){let r=yield*e.submission(t).pipe(h2(t,`read the run's submission`));if(yield*E({runId:t,loop:r.loop,itemKey:r.itemKey}),r.approval===`required`&&(yield*e.parkForApproval(t).pipe(h2(t,`park the run for approval`)))._tag===`Waiting`){yield*O(`Run waits for its approval`,{runId:t});return}let i;do{yield*te(t);let e=yield*g(t);if(x(e)&&e.value._tag!==`Live`&&(yield*se(new u2({attemptId:e.value.attempt.id,runId:t,loop:r.loop,itemKey:r.itemKey,worker:e.value.attempt.worker,reason:`startup`}))),b(g2(e))){let e=yield*oe(r);if(x(e)){yield*O(`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*Ig(i=>_(t,r,e,i).pipe(Jh(({lease:e})=>Ik(l,n=>new Map(n).set(t,e))),T(({lease:e,open:a})=>i(n.withAttempt(t,ee(t,r,e.worker,a))).pipe(Og(u(t,e))))))}while(i===`RetryAttempt`);i!==`WaitingForStop`&&(i===`Unchanged`?yield*O(`Run closed by another operation; its fiber ends`,{runId:t}):yield*h(t))}),re=D(`RunDriver.holdSlot`)(function*(e){let{runId:t,attemptId:n}=e;yield*E({runId:t,attemptId:n}),yield*ie(new u2(e));let r=yield*Fk(l,e=>[Sr(e.get(t)),c2(e,t)]);b(r)?yield*k(`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)},Fg),ie=e=>Ik(c,t=>t.has(e.attemptId)?t:new Map(t).set(e.attemptId,e)),ae=D(`RunDriver.confirmStopAfterFailure`)(function*(e){let{attemptId:n,runId:r,worker:i}=e,a={runId:r,attemptId:n,worker:i,reason:e.reason};yield*E(a),yield*ie(new u2(e));let o=yield*t.interrupt(n,e.reason).pipe(Yh);Di(o)?(yield*Ik(c,e=>c2(e,n)),yield*k(`The parent task of the failed Attempt is confirmed stopped; the Run's slot is freed`,a)):(yield*Xg(`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*re(e))}),oe=e=>Nk(c).pipe(Qh(t=>Sr([...t.values()].find(({itemKey:t})=>t===e.itemKey)))),se=D(`RunDriver.reconcileKept`)(function*(e){yield*E({...e}),yield*ie(e),yield*s.reconcile(e.attemptId,e.reason),yield*Ik(c,t=>c2(t,e.attemptId)),yield*O(`Parent stop confirmed; runs on the item can start attempts again`,{...e})}),ce=D(`RunDriver.releaseKept`)(function*(e){yield*E({...e}),yield*se(e).pipe(rg(`ParentStopUnconfirmedError`,t=>Xg(`Parent stop unconfirmed; the worker slot and checkout stay reserved until reconciliation succeeds`,{...e,errorTag:t._tag})))}),le=D(`RunDriver.recoverWorkspaces`)(function*(){yield*Ah(yield*s.atStartup(),({attemptId:e,runId:t,loop:n,itemKey:r,worker:i})=>ie(new u2({attemptId:e,runId:t,loop:n,itemKey:r,worker:i,reason:`startup`})),{discard:!0})});return{launch:d,resume:f,stop:p,continueWithNewest:h,reconcile:D(`RunDriver.reconcile`)(function*(){let n=[...(yield*Nk(c)).values()];yield*Ah(n,e=>nk(o,e.runId).pipe(T(t=>t?Ih:ce(e))),{discard:!0});let r=yield*e.pendingContinuations;yield*Ah(r,e=>h(e).pipe(lg(t=>Zg(`Could not continue the queued Events behind a closed Run`,{runId:e,errorTag:t._tag})),fg),{discard:!0});let i=yield*e.runIdsToDrive,a=yield*gg(i,e=>Qh(nk(o,e),e=>!e));yield*Ah(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*k(`Every Run to drive already has its fiber`,s):yield*O(`Runs recovered from the run tables`,s)}),recoverWorkspaces:le,holdSlot:re,releaseKept:ce,unconfirmedStops:Nk(c).pipe(Qh(e=>[...e.values()]))}}))},v2=_i(`@usine/engine/ReconcileInterval`,{defaultValue:()=>`3 minutes`});w(function*(){let e=yield*j0,t=yield*_2,n=yield*o2,r=yield*l0,i=yield*WO,a=D(`RunEngine.submit`)(function*(n){let r=yield*PR(n).pipe(Tg(WO,i)),a=yield*e.recordAndClaim(n,r);return x(a.supersededRun)&&(yield*t.stop(a.supersededRun.value)),x(a.openedRun)&&(yield*t.launch(a.openedRun.value)),a.result},Fg),o=D(`RunEngine.approve`)(function*(n,r,i){(yield*e.approve(n,r,i))?(yield*O(`Run approved`,{runId:n,eventId:r.id,channel:i.channel,approver:vr(i.approver,()=>`none`)}),yield*t.resume(n)):yield*k(`Approval was already recorded; the Run is unchanged`,{runId:n,eventId:r.id})},Fg),s=D(`RunEngine.retry`)(function*(n,r=a0){(yield*e.retry(n,r))?yield*t.resume(n):yield*k(`Retry changed nothing; the Run already waits for its next Attempt`,{runId:n})},Fg),c=D(`RunEngine.runAgain`)(function*(n,r){let i=yield*e.runAgain(n,r);return i._tag===`Claimed`&&(yield*t.launch(i.runId)),i},Fg),l=D(`RunEngine.cancel`)(function*(n){let i=yield*e.cancel(n);if(i._tag===`AlreadyClosed`){yield*k(`Cancel was a no-op; the run was already closed`,{runId:n});return}yield*O(`Run canceled`,{runId:n,openAttempt:_r(i.openAttempt,{onNone:()=>`none`,onSome:({id:e})=>e})}),x(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=x(i.openAttempt)?yield*r.interrupt(i.openAttempt.value.id,`cancel`).pipe(Yh):xi(void 0);if(yield*t.stop(n),x(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),x(i.openAttempt)&&Ei(a))return yield*new dz({attemptId:i.openAttempt.value.id,cause:a.failure})},Fg),u=D(`RunEngine.intervene`)(function*(t,n,i){yield*E({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||x(o.outcome))return yield*O(`Operator input rejected for an inactive Attempt`,{runId:t,attemptId:n}),yield*new pz({runId:t,attemptId:n,message:`This attempt is no longer running`});yield*r.intervene(n,i).pipe(sg(e=>new pz({runId:t,attemptId:n,message:wk(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})})),lg(e=>Xg(`Operator input delivery failed`,{runId:t,attemptId:n,message:e.message})))}),d=D(`RunEngine.resolveFailure`)(function*(n,r,i){yield*E({runId:n,attemptId:r}),(yield*e.resolveFailure(n,r,i))&&(yield*O(`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))},Fg),f=D(`RunEngine.revoke`)(function*(n,r){let i=yield*e.revoke(n,r);return yield*Ah(i,t.stop,{concurrency:`unbounded`,discard:!0}),i},Fg),p=D(`RunEngine.inspect`)(function*(t){return yield*e.snapshot(t)}),m=D(`RunEngine.transcript`)(function*(t){return yield*e.transcript(t)}),h=D(`RunEngine.discardLeftovers`)(function*(t){if(yield*E({worker:t}),(yield*r.workers).includes(t)){let n=yield*e.openAttempts(t);return yield*O(`Leftovers kept; the Worker is configured or still runs Attempts, so its Attempts stay tracked`,{worker:t,running:n}),yield*new mz({worker:t,running:n})}let n=yield*e.discardLeftovers(t);return yield*O(`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*pg(yield*v2).pipe(qh(t.reconcile()),lg(e=>Zg(`Periodic Run reconcile failed; the next one tries again`,{errorTag:e._tag})),fg,Lg,Ug),{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 y2=class extends Lr()(`@usine/engine/RunEngine`){},b2=(e,t)=>e.changes.pipe(NO(e=>e!==t),VO,T(_r({onNone:()=>Rh,onSome:e=>C(e)}))),x2=Gk.make(`HEAD`),S2=class extends jE(`@usine/orchestrator/LoopAgentResolutionError`)(`LoopAgentResolutionError`,{loop:uA,agent:aA,message:R}){},C2=D(`TriggerRouting.resolveLoop`)(function*(e,t){yield*E({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 S2({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:cA(r,e.config.settings.parentModel)}}),w2=D(`TriggerRouting.resolveLoops`)(function*(e){let t=[];for(let n of e.loops){let r=yield*Yh(C2(e,n));Di(r)?t.push(r.success):yield*Zg(`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}),T2=e=>e.trigger.on===`schedule`?v():y(e.maxCycles),E2=e=>new MR({event:new BM({id:RM.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:T2(e.loop),repository:e.repository.name,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel}),D2=e=>wk(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`})}),O2=e=>_r(e.expression,{onNone:()=>({configFile:e.file,configStage:e.stage}),onSome:t=>({configFile:e.file,configStage:e.stage,expression:t})}),k2=class extends B(`@usine/orchestrator/RepositoryPollFailure`)({repository:H,errorTag:R,message:A}){},A2=class extends B(`@usine/orchestrator/RepositoryPoll`)({repository:H,completedAt:hE}){},j2=class extends B(`@usine/orchestrator/PollCycle`)({repositoryPolls:M(A2).pipe(CT(C([]))),repositories:L.check(BT(0)),changedItems:L.check(BT(0)),submissions:M(UR),revokedRuns:L.check(BT(0)),failures:M(k2),preflightFindings:M(fW),nextPollAt:z(hE)}){},M2=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...O2(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},N2=e=>{let t=e.flatMap(e=>_r(e,{onNone:()=>[],onSome:e=>[H_(e)]}));return t.length===0?v():F_(Math.max(...t))},P2=class extends B(`@usine/orchestrator/LoopEvaluationFailure`)({loop:uA,stage:P([`if`,`prompt`]),expression:_E(nJ),errorTag:R,message:A}){},F2=class extends B(`@usine/orchestrator/FailingItem`)({stream:P([`issue`,`pr`]),number:fI,updatedAt:gE,contentHash:N0,failures:_T(P2)}){},I2=e=>e.stream===`issue`?new KH({number:e.number,updatedAt:e.updatedAt}):new qH({number:e.number,updatedAt:e.updatedAt}),L2=(e,t,n)=>{let[r,...i]=n;return r===void 0?v():y(new F2({stream:e._tag===`ChangedIssue`?`issue`:`pr`,number:fI.make(e.number),updatedAt:e.updatedAt,contentHash:t,failures:[r,...i]}))},R2=e=>e.stage===`if`?`if:`:_r(e.expression,{onNone:()=>`prompt`,onSome:e=>`prompt {{ ${e} }}`}),z2=(e,t)=>t.failures.map(n=>new k2({repository:e,errorTag:n.errorTag,message:`Loop "${n.loop}": ${R2(n)} failed on ${t.stream===`issue`?`issue`:`pull request`} #${t.number}: ${n.message}`})),B2=e=>_r(e,{onNone:()=>[],onSome:({failures:e})=>e}),V2=(e,t)=>e.loop===t.loop&&e.stage===t.stage,H2=D(`PollingTriggers.logItemEvaluation`)(function*(e,t,n,r){yield*E({repository:e,item:t});for(let i of jr(r)){let r=_r(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:S(n.expression),errorTag:n.errorTag,message:n.message};r.some(e=>V2(e,n))?yield*k(`Loop evaluation still fails on unchanged Item content`,a):yield*Zg(`Loop evaluation failed on an Item; its other Loops and the repository's other Items continue`,a)}}let i=B2(r);for(let r of B2(n))i.some(e=>V2(e,r))||(yield*O(`Loop evaluation no longer fails on the Item`,{repository:e,item:t,loop:r.loop,stage:r.stage}))}),U2=zw(M(hA)),W2=j({labels:xU.fields.labels}),G2=j({labels:TU.fields.labels}),K2=(e,t)=>zw(e===`issue`?W2:G2)(t).pipe(T(({labels:e})=>U2(e.nodes.map(({name:e})=>e)))),q2=(e,t)=>new Uq({repository:e.repository,itemKey:e.itemKey,message:t}),J2=e=>w(function*(){let t=x(e.goneAt);if(e.source===`issue`){let n=yield*zw(xU)(e.payload).pipe(sg(t=>q2(e,t.message)));return{itemKey:e.itemKey,kind:`issue`,number:fI.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*U2(n.labels.nodes.map(({name:e})=>e)).pipe(sg(t=>q2(e,t.message))),conflicting:!1}}if(e.source===`pr`){let n=yield*zw(TU)(e.payload).pipe(sg(t=>q2(e,t.message))),r=n.merged?`pr-merged`:n.state===`OPEN`&&!t?`pr-open`:`pr-closed`;return{itemKey:e.itemKey,kind:`pr`,number:fI.make(e.number),title:n.title,url:n.url,state:r,linkedPullRequests:[],labels:yield*U2(n.labels.nodes.map(({name:e})=>e)).pipe(sg(t=>q2(e,t.message))),conflicting:r===`pr-open`&&n.mergeable===`CONFLICTING`}}return yield*q2(e,`Unsupported item projection source: ${e.source}`)}),Y2=D(`settledItemState`)(function*(e){yield*E({itemKey:e});let t=yield*(yield*W0).get(e);if(b(t))return v();let n=yield*Yh(J2(t.value));if(Ei(n))return yield*k(`Stored Item payload doesn't decode; treating the Item as open`,{itemKey:e,message:n.failure.message}),v();let{state:r}=n.success;return SW(r)?y(r):v()}),X2=(e,t)=>e.canApprove||e.canResolveFailure&&!t,Z2=D(`PollingTriggers.closeAsksOfClosedItems`)(function*(e){yield*E({repository:e});let t=yield*i0,n=(yield*t.asks()).filter(t=>Yk(t.repository)===Yk(e));for(let e of n){let n={askId:e.id,itemKey:e.itemKey,repository:e.repository},r=yield*Y2(e.itemKey);b(r)?yield*k(`Cycle-budget Ask stays open; its Item is open or not stored`,n):(yield*t.close(e.id,`ItemClosed`))&&(yield*O(`Item is closed; its cycle-budget Ask leaves Needs attention`,{...n,itemState:r.value}))}}),Q2=$w(dI).pipe(bT(rE(gT([tT(`github`),H,fI])))),$2=Jw(Q2),e4=(e,t)=>$2([`github`,H.make(Yk(e)),fI.make(t)]),t4={labels:[],findings:[],catalogChanged:!1,nextPollAt:v()},n4=D(`PollingTriggers.applyLabelCatalog`)(function*(e,t,n){yield*E({repository:e});let r=yield*jz,i=yield*Mz,a={labelEntityTag:t,entityTagChanged:!1,confirmedLabels:v(),failures:[],nextPollAt:v()};if(Ei(n)){let t=n.failure;return t._tag===`GitHubRateLimitError`?(yield*Xg(`Label catalog rate-limited; kept the stored catalog and deferred label provisioning`,{repository:e,operation:t.operation,retryAt:G_(t.retryAt)}),{...a,nextPollAt:y(t.retryAt)}):(yield*Zg(`Label catalog request failed; kept the stored catalog, deferred label provisioning, and evaluated items anyway`,{repository:e,...M2(t)}),{...a,failures:[new k2({repository:e,errorTag:t._tag,message:t.message})]})}let o=n.success;if(!(o instanceof tU)){let t=yield*r.get(e);return b(t)?(yield*Xg(`Repository label catalog unchanged (304) but its projection is missing; refetching next cycle and deferring label provisioning`,{repository:e}),{...a,labelEntityTag:v(),entityTagChanged:!0}):(yield*k(`Repository label catalog unchanged (304)`,{repository:e}),{...a,confirmedLabels:y(t.value.labels)})}let s=o.labels.map(({name:e,color:t,description:n})=>new vz({name:e,color:y(t),description:n}));return yield*i.replace(new xz({repository:e,labels:s})),{...a,labelEntityTag:o.entityTag,entityTagChanged:!0,confirmedLabels:y(s)}}),r4=D(`PollingTriggers.synchronizeLabels`)(function*(e,t,n){yield*E({repository:e});let r=yield*uW,i=yield*hW,a=yield*Mz,o=yield*n4(e,n,yield*Yh(r.labels(e,n))),s=yield*_r(o.confirmedLabels,{onNone:()=>C(t4),onSome:n=>i.reconcile(e,t,n)}),c={labelEntityTag:s.catalogChanged?v():o.labelEntityTag,entityTagChanged:o.entityTagChanged||s.catalogChanged,failures:o.failures,preflightFindings:s.findings,nextPollAt:N2([o.nextPollAt,s.nextPollAt])};return s.catalogChanged&&(yield*a.replace(new xz({repository:e,labels:s.labels})).pipe(sg(e=>({_tag:`InterruptedRepositoryCycle`,error:e,failures:c.failures,preflightFindings:c.preflightFindings,nextPollAt:c.nextPollAt})))),c}),i4=D(`PollingTriggers.observeItem`)(function*(e,t){yield*E({repository:e,item:t.number});let n=yield*uW,r=yield*G0,i=yield*i0,a=e4(e,t.number),o=yield*i.generation(a),s=yield*n.snapshot(e,t),c=new P0({itemKey:a,repository:e,source:M0.make(t._tag===`ChangedIssue`?`issue`:`pr`),number:fI.make(t.number),contentHash:N0.make(s.contentHash),payload:s.payload});return yield*r.upsert(c),yield*k(`Fetched changed-item snapshot`,{repository:e,item:c.number,stream:c.source,contentHash:c.contentHash}),{snapshot:s,projection:c,cycleGeneration:o}}),a4=D(`PollingTriggers.markItemGone`)(function*(e,t){return yield*E({repository:e,item:t}),yield*(yield*G0).markGone(e4(e,t),yield*I_)}),o4=(e,t,{projection:n,cycleGeneration:r})=>zM.make(JSON.stringify([e.name,Yk(t.name),n.number,n.contentHash,...r===0?[]:[r]])),s4=(e,t,n)=>w(function*(){return yield*(yield*sJ).evaluateBoolean(e.trigger.if,BY(e.trigger.on),{repo:VY(t),item:n})}),c4=(e,t,n)=>w(function*(){let r=yield*sJ,i=VY(t);return yield*r.evaluateBooleanEach(e.trigger.if,BY(e.trigger.on),n.map(e=>({repo:i,item:e})))}),l4=D(`PollingTriggers.evaluateItem`)(function*(e,t,n){let{projection:r,cycleGeneration:i}=n;yield*E({repository:e.name,item:r.number});let a=yield*Z1,o=yield*y2,s=t.filter(({loop:e})=>e.trigger.on===r.source),c=r.payload,l={repo:VY(e),item:c};if(s.length===0)return yield*k(`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`?Gk.make(yield*zw(Kk)(c.headRefOid).pipe(sg(()=>new mH({operation:`fetch-pull-request-snapshot`,message:`The pull request payload has no valid head commit`,detail:`pull request #${r.number} has no full headRefOid`})))):x2,f=[],p=0;for(let{agent:t,loop:m,parentModel:h}of s){yield*E({loop:m.name,agent:t.name});let s=yield*Yh(s4(m,e,c));if(Ei(s)){f.push(new P2({loop:m.name,stage:`if`,expression:y(s.failure.source),errorTag:s.failure._tag,message:s.failure.message}));continue}if(!s.success){yield*k(`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*O(`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=o4(m,e,n),_=yield*I_,ee=yield*Yh(a.renderPrompt(m,l));if(Ei(ee)){f.push(new P2({loop:m.name,stage:`prompt`,expression:ee.failure.expression,errorTag:ee.failure._tag,message:ee.failure.message}));continue}let te=yield*o.submit(E2({dedupKey:g,cycleGeneration:i,itemKey:r.itemKey,loop:m,payload:c,receivedAt:_,repository:e,revision:d,task:gF.make(ee.success),agent:t,parentModel:h}));yield*O(`Submitted matching item state`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,contentHash:r.contentHash,revision:d,result:te._tag,...D2(te)}),u.push(te)}return{submissions:u,revokedRuns:p,failures:f}}),u4=D(`PollingTriggers.revokeMissingItem`)(function*(e,t,n,r){yield*E({repository:e.name,item:r});let i=yield*y2,a=e4(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*O(`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=w(function*(){let e=new Set,t=yield*aD({capacity:128,strategy:`dropping`}),n=yield*Mk(v()),r=yield*Mk(0),i=({repository:e,item:t})=>`${Yk(e)}:${_r(t,{onNone:()=>`*`,onSome:e=>String(e.number)})}`,a=e=>_r(e,{onNone:()=>Ih,onSome:e=>Ik(r,t=>Math.max(t,H_(e)))});return{offer:D(`PollingTriggers.hint`)(function*(r,o,s=v()){yield*E({repository:r,item:o?.number}),yield*Pk(n,y(yield*I_)),yield*a(s);let c={repository:r,item:Sr(o)},l=i(c);e.has(l)?yield*k(`Hint coalesced with a pending fetch`,{repository:r,item:o?.number}):(e.add(l),(yield*sD(t,c))?yield*k(`Hint queued`,{repository:r,item:o?.number}):(e.delete(l),yield*Xg(`Hint queue full; the normal poll will refresh the repository`,{repository:r,item:o?.number})))},Fg),take:Ig(n=>n(fD(t)).pipe(Jh(t=>Fh(()=>e.delete(i(t)))))),defer:a,awaitBackoff:w(function*(){for(;;){let e=yield*Nk(r),t=yield*rp;if(e<=t)return;yield*O(`GitHub request backoff delays polling and self-write Hints`,{sleepMs:e-t}),yield*pg($a(e-t))}}),lastHint:Nk(n)}}),f4=class e extends Lr()(`@usine/orchestrator/ItemHints`){static layer=qf(e,d4)},p4=to(10),m4={revokedRuns:0,failures:[],nextPollAt:v()},h4=D(`PollingTriggers.checkOpenIssues`)(function*(e,t){yield*E({repository:e.name});let n=yield*W0,r=yield*uW,i=yield*n.openIssues(e.name);if(i.length===0)return yield*k(`No open issues to check against GitHub`,{repository:e.name}),m4;let a=yield*Yh(r.missingIssues(e.name,i));if(Ei(a)){let t=a.failure;return t._tag===`GitHubRateLimitError`?(yield*Xg(`Open-issue check rate-limited; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,operation:t.operation,retryAt:G_(t.retryAt)}),{...m4,nextPollAt:y(t.retryAt)}):(yield*Zg(`Open-issue check failed; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,...M2(t)}),{...m4,failures:[new k2({repository:e.name,errorTag:t._tag,message:t.message})]})}let o=0;for(let n of a.success){let r=yield*u4(e,t,`issue`,n),i=yield*a4(e.name,n);o+=r,yield*O(`GitHub no longer has an open issue; it leaves the open lanes`,{repository:e.name,item:n,revokedRuns:r,projectionMarkedGone:i})}return yield*k(`Checked open issues against GitHub`,{repository:e.name,openIssues:i.length,missingIssues:a.success.length}),{...m4,revokedRuns:o}}),g4=4,_4=class extends B(`@usine/orchestrator/OpenPullRequest`)({number:qH.fields.number,updatedAt:gE,baseRefName:yE(UH),mergeable:A.pipe(TT(C(`UNKNOWN`))),checksUnsettled:sT.pipe(TT(C(!0)))}){},v4=(e,t)=>t._tag===`PullRequestSnapshot`&&t.payload.state===`OPEN`?y(new _4({number:e.number,updatedAt:e.updatedAt,baseRefName:y(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`})):v(),y4=D(`PollingTriggers.readBaseRef`)(function*(e,t,n,r){yield*E({repository:e,baseRefName:t});let i=yield*Yh((yield*uW).baseRefHead(e,t,n));if(Ei(i)){let a=i.failure;return a._tag===`GitHubRateLimitError`?yield*a:(yield*Xg(`Could not read the base branch head; refreshing its open pull requests in this poll`,{repository:e,baseRefName:t,pullRequests:r.join(`, `),...M2(a)}),{_tag:`Unreadable`,recorded:n})}let a=i.success;return b(n)?(yield*O(`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*O(`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})}),b4=(e,t)=>{if(b(e.baseRefName))return y(`baseUnrecorded`);let n=t.get(e.baseRefName.value);return n?._tag===`Moved`?y(`baseMoved`):n?._tag===`Unreadable`?y(`baseUnreadable`):e.mergeable===`UNKNOWN`?y(`mergeableUnknown`):e.checksUnsettled?y(`checksUnsettled`):v()},x4=D(`PollingTriggers.openPullRequestRefresh`)(function*(e,t,n,r){if(yield*E({repository:e}),t.length===0)return{refreshed:[],baseRefHeads:[]};let i=new Map;for(let{number:e,baseRefName:n}of t){if(b(n))continue;let t=i.get(n.value)??[];t.push(e),i.set(n.value,t)}let a=new Map(yield*Ah(i,([t,r])=>y4(e,t,xr(n.find(e=>e.baseRefName===t)),r).pipe(Qh(e=>[t,e])),{concurrency:g4})),o=t.filter(({number:e})=>!r.has(e)),s=o.flatMap(e=>jr(Dr(b4(e,a),t=>({pullRequest:e,reason:t}))));if(s.length===0)yield*k(`No open pull request needs a refresh`,{repository:e,openPullRequests:t.length,baseRefReads:a.size});else{let t=ua(s,({reason:e})=>e);yield*O(`Refreshing open pull requests`,{repository:e,baseRefReads:a.size,refreshed:s.length,skipped:o.length-s.length,...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.map(({pullRequest:e})=>e.number).join(`, `)]))})}return{refreshed:s.map(({pullRequest:e})=>e),baseRefHeads:[...a.values()].flatMap(e=>e._tag===`Unreadable`?jr(e.recorded):[e.head]).sort((e,t)=>e.baseRefName.localeCompare(t.baseRefName))}}),S4=4,C4=4,w4=R.pipe(I(`GitHubPollWatchKey`)),T4=class extends B(`@usine/orchestrator/StoredPollCursor`)({boardVersion:tT(5),openPullRequests:M(_4),baseRefHeads:M(WH).pipe(TT(C([]))),cursor:GH,labelEntityTag:_E(HH),watches:M(w4).check(JT()),failingItems:M(F2).pipe(TT(C([])))}){},E4=e=>$1.make(`github-poll:${Yk(e.name)}`),D4=({loop:e})=>w4.make(JSON.stringify([e.name,e.trigger.on,e.trigger.if])),O4=(e,t)=>e.config.repos.map(n=>{let r=t.filter(({loop:t})=>t.trigger.on!==`schedule`&&xX(e.config,t,n));return{repository:n,declaredLabels:CX(e.config,n.name),loops:r,watches:r.map(D4).sort()}}),k4=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),A4=class e extends Lr()(`@usine/orchestrator/PollingTriggers`){static layer=qf(e,w(function*(){let e=yield*n0,t=yield*i0,n=yield*uW,r=yield*X0,i=yield*Mk(v()),a=yield*Mk(new Map),o=yield*f4,s=yield*jD(1),c=yield*Mk({instance:v(),repositories:new Set}),l=yield*Mk(new Map),u=e=>new T4({boardVersion:5,openPullRequests:[],baseRefHeads:[],cursor:GH.empty,labelEntityTag:v(),watches:e,failingItems:[]}),d=D(`PollingTriggers.readCursor`)(function*(t){yield*E({repository:t.repository.name});let n=yield*e.read(E4(t.repository),T4);return b(n)?u(t.watches):k4(n.value.watches,t.watches)?n.value:(yield*O(`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=D(`PollingTriggers.writeCursor`)(function*(t,n){yield*E({repository:t.repository.name}),yield*e.write(E4(t.repository),T4,n)}),p=D(`PollingTriggers.checkOpenIssuesWhenDue`)(function*(e){yield*E({repository:e.repository.name});let t=E4(e.repository),n=yield*rp,r=(yield*Nk(l)).get(t);return r!==void 0&&n-r<no(p4)?(yield*k(`Open issues were checked less than 10 minutes ago; skipped`,{repository:e.repository.name,lastCheckedAt:G_(P_(r))}),m4):(yield*Ik(l,e=>new Map(e).set(t,n)),yield*h4(e.repository,e.loops))}),m=D(`PollingTriggers.pollRepository`)(function*(e){yield*E({repository:e.repository.name});let r=(yield*t.pendingResets()).filter(({repository:t})=>Yk(t)===Yk(e.repository.name)),i=r.length>0?u(e.watches):yield*d(e);r.length>0&&(yield*O(`Cycle budget reset requests fresh repository polling`,{repository:e.repository.name,items:r.map(({itemKey:e})=>e)}));let a=yield*r4(e.repository.name,e.declaredLabels,i.labelEntityTag);return yield*o.defer(a.nextPollAt),yield*w(function*(){let s=yield*n.changes(e.repository.name,i.cursor);yield*o.defer(s.backoffUntil);let l=(yield*Nk(c)).repositories.has(E4(e.repository))?[]:i.failingItems,u=s._tag===`RepositoryChanges`?s.items:[],d=new Set(u.map(({number:e})=>e)),m=yield*x4(e.repository.name,i.openPullRequests,i.baseRefHeads,new Set([...d,...l.map(({number:e})=>e)])),h=new Map([...l.map(e=>[e.number,I2(e)]),...m.refreshed.map(({number:e,updatedAt:t})=>[e,new qH({number:e,updatedAt:t})])]);for(let e of u)h.set(e.number,e);s._tag===`RepositoryChanges`&&(yield*O(`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*O(`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 _=N2([s.nextPollAt,a.nextPollAt]);yield*k(`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 ee=new Map(i.failingItems.map(e=>[e.number,e])),te=yield*Ah(h.values(),t=>w(function*(){let n=yield*i4(e.repository.name,t),r=yield*l4(e.repository,e.loops,n),i=L2(t,n.projection.contentHash,r.failures);return yield*H2(e.repository.name,t.number,xr(ee.get(t.number)),i),{_tag:`Evaluated`,item:t,observation:n,cycle:r,failing:i}}).pipe(rg(`GitHubItemNotFoundError`,n=>w(function*(){if(!g.has(t.number))return yield*n;let r=yield*u4(e.repository,e.loops,t._tag===`ChangedIssue`?`issue`:`pr`,t.number),a=yield*a4(e.repository.name,t.number);return yield*Xg(`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:C4}),ne=te.flatMap(e=>e._tag===`Evaluated`?[e]:[]),re=te.reduce((e,t)=>e+(t._tag===`Missing`?t.revokedRuns:0),0),ie=ne.map(({cycle:e})=>e),ae=yield*p(e);yield*o.defer(ae.nextPollAt),yield*Z2(e.repository.name);let oe=[...i.failingItems.filter(({number:e})=>!h.has(e)),...ne.flatMap(({failing:e})=>jr(e))].sort((e,t)=>e.number-t.number),se=[...i.openPullRequests.filter(({number:e})=>!h.has(e)),...ne.flatMap(({item:e,observation:t})=>jr(v4(e,t.snapshot)))],ce=m.baseRefHeads.filter(({baseRefName:e})=>se.some(t=>Pr(t.baseRefName,e))),le=new T4({boardVersion:5,cursor:s.cursor,labelEntityTag:a.labelEntityTag,watches:e.watches,openPullRequests:se,baseRefHeads:ce,failingItems:oe});return(s._tag===`RepositoryChanges`||h.size>0||a.entityTagChanged||!Re(ce,i.baseRefHeads))&&(yield*f(e,le)),yield*Ik(c,t=>({...t,repositories:new Set([...t.repositories,E4(e.repository)])})),yield*Ah(r,t.acknowledgeReset,{discard:!0}),{changedItems:s._tag===`RepositoryChanges`?s.items.length:0,submissions:ie.flatMap(({submissions:e})=>e),revokedRuns:ie.reduce((e,t)=>e+t.revokedRuns,re+ae.revokedRuns),failures:[...a.failures,...ae.failures,...oe.flatMap(t=>z2(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:N2([_,ae.nextPollAt])}}).pipe(sg(t=>({_tag:`InterruptedRepositoryCycle`,error:t,failures:[...a.failures,...i.failingItems.flatMap(t=>z2(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:a.nextPollAt})))}),h=(yield*yg()).pipe(gi(Z1,i0,sJ,uW,W0,G0,hW,jz,Mz,y2)),g=D(`PollingTriggers.poll`)(function*(e){yield*o.awaitBackoff,yield*Ik(c,t=>Pr(t.instance,e)?t:{instance:y(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*k(`Paused Loop skipped during repository polling`,{loop:n.name}));let n=O4(e,(yield*w2(e)).filter(({loop:e})=>!t.has(e.name))),s=yield*Ah(n,e=>Yh(m(e)).pipe(Qh(t=>({repository:e,result:t}))),{concurrency:S4}),l=[],u=[],d=[],f=[],p=yield*I_;for(let{repository:e,result:t}of s){if(Di(t)){l.push(t.success),f.push(...t.success.preflightFindings),yield*Ik(a,t=>new Map(t).set(Yk(e.repository.name),new A2({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*Xg(`GitHub rate limit reached; delaying the next cycle`,{repository:e.repository.name,operation:r.operation,retryAt:G_(r.retryAt)}),d.push(y(r.retryAt)),yield*o.defer(y(r.retryAt))):(yield*Zg(`Repository poll cycle failed; siblings were unaffected`,{repository:e.repository.name,...M2(r)}),u.push(new k2({repository:e.repository.name,errorTag:r._tag,message:r.message})))}let h=yield*Nk(a),g=new j2({repositoryPolls:n.flatMap(({repository:e})=>jr(xr(h.get(Yk(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:N2([...l.map(({nextPollAt:e})=>e),...d])});return yield*Pk(i,y(g)),g},Sg(h),s.withPermits(1)),_=D(`PollingTriggers.refreshHint`)(function*(e,t){yield*E({repository:t.repository,item:wr(Dr(t.item,e=>e.number))}),yield*o.awaitBackoff;let n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop)),i=O4(e,(yield*w2(e)).filter(({loop:e})=>!n.has(e.name))).find(({repository:e})=>Yk(e.name)===Yk(t.repository));if(i===void 0){yield*O(`Hint ignored for an unmanaged repository`,{repository:t.repository,item:wr(Dr(t.item,e=>e.number))});return}if(b(t.item)){let e=yield*m(i).pipe(ng(e=>e._tag===`InterruptedRepositoryCycle`?o.defer(e.nextPollAt).pipe(qh(zh(e.error))):zh(e)));yield*O(`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*i4(i.repository.name,a),c=yield*l4(i.repository,i.loops,s);for(let e of c.failures)yield*Xg(`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*O(`Hint refreshed the Item`,{repository:t.repository,item:a.number,submissions:c.submissions.length,revokedRuns:c.revokedRuns,failures:c.failures.length})},Sg(h),(e,t,n)=>e.pipe(ng(e=>w(function*(){e._tag===`GitHubRateLimitError`&&(yield*o.defer(y(e.retryAt))),yield*Xg(`Hint refresh failed; the normal poll will retry`,{repository:n.repository,item:wr(Dr(n.item,e=>e.number)),...M2(e)})})),s.withPermits(1))),ee=(e,t,n,r)=>w(function*(){let i=Math.max(n,r),a=t;for(;;){let t=i-(yield*rp);if(t<=0)return;let n=yield*mg([pg($a(t)).pipe(Qh(()=>({_tag:`Due`}))),o.take.pipe(Qh(e=>({_tag:`Hint`,hint:e}))),b2(e,a).pipe(Qh(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*rp);s>0?yield*O(`Instance reloaded; the next poll waits for the time GitHub asked for`,{sleepMs:s}):yield*O(`Instance reloaded; polling now instead of after poll_interval`)}});return{latest:Nk(i),poll:g,run:e=>w(function*(){let t=yield*e.get,n=yield*rp,r=yield*Yh(g(t));if(Ei(r)){let e=t.config.settings.pollInterval*1e3;yield*Zg(`Poll cycle could not read Loop runtime state; retrying`,{errorTag:r.failure._tag,message:r.failure.message,operation:r.failure.operation,sleepMs:e}),yield*pg($a(e));return}let i=r.success,a=n+t.config.settings.pollInterval*1e3,o=_r(i.nextPollAt,{onNone:()=>0,onSome:H_}),s=yield*rp,c=Math.max(0,Math.max(a,o)-s);yield*O(`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*ee(e,t,a,o)}).pipe(Lg),hint:o.offer,lastHint:o.lastHint}})).pipe(ep(f4.layer))},j4=4,M4=6e4,N4=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...O2(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},P4=class extends V(`@usine/orchestrator/ScheduleAgentFailure`)(`ScheduleAgentFailure`,{loop:uA,agent:aA,message:A}){},F4=class extends V(`@usine/orchestrator/ScheduleTickFailure`)(`ScheduleTickFailure`,{loop:uA,repository:H,scheduledAt:hE,errorTag:R,message:A}){},I4=class extends V(`@usine/orchestrator/ScheduleCronFailure`)(`ScheduleCronFailure`,{loop:uA,cron:A,tz:A,message:A}){},L4=N([P4,I4,F4]),R4=class extends B(`@usine/orchestrator/ScheduleCycle`)({loops:L.check(BT(0)),fanout:L.check(BT(0)),submissions:M(UR),skipped:L.check(BT(0)),alreadyFired:L.check(BT(0)),failures:M(L4),nextTickAt:z(hE)}){},z4=e=>e.loops.flatMap(t=>{let n=t.trigger;return n.on===`schedule`?[{loop:t,repositories:e.config.repos.filter(n=>xX(e.config,t,n)),trigger:n}]:[]}),B4=(e,t)=>{let n=B_(t);return n.setUTCSeconds(0,0),N_(Tm(e,n)?n:Om(e,n))},V4=(e,t)=>N_(Dm(e,B_(t))),H4=(e,t)=>_r(z_(e,t),{onNone:()=>G_(e),onSome:K_}),U4=e=>e.length===0?v():F_(Math.min(...e.map(H_))),W4=e=>dI.make(JSON.stringify([`github`,Yk(e.name)])),G4=(e,t,n)=>zM.make(JSON.stringify([e.name,Yk(t.name),G_(n)])),K4=e=>({tick:{scheduledAt:G_(e.scheduledAt),scheduledAtLocal:e.scheduledAtLocal,cron:e.trigger.cron,tz:e.trigger.tz}});(class e extends Lr()(`@usine/orchestrator/ScheduleTriggers`){static layer=qf(e,w(function*(){let e=yield*Z1,t=yield*sJ,n=yield*y2,r=yield*X0,i=yield*Mk(v()),a=yield*Mk({instance:v(),ticks:new Map}),o=new WeakMap,s=e=>{let t=o.get(e);if(t!==void 0)return t;let n=wm(e.cron,e.tz);return o.set(e,n),n},c=D(`ScheduleTriggers.submitTick`)(function*(r,i){yield*E({loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:G_(r.scheduledAt)});let a=K4(r),o={repo:VY(r.repository),item:a};if(!(yield*t.evaluateBoolean(r.trigger.if,BY(`schedule`),o)))return yield*k(`Scheduled Tick did not match its expression`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:G_(r.scheduledAt)}),v();let s=G4(r.loop,r.repository,r.scheduledAt),c=yield*e.renderPrompt(r.loop,o),l=yield*n.submit(E2({cycleGeneration:mI.make(0),agent:r.agent,dedupKey:s,itemKey:W4(r.repository),loop:r.loop,payload:a,receivedAt:i,repository:r.repository,revision:x2,task:gF.make(c),parentModel:r.parentModel}));return yield*O(`Submitted scheduled Tick`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:G_(r.scheduledAt),scheduledAtLocal:r.scheduledAtLocal,result:l._tag,...D2(l)}),y(l)}),l=D(`ScheduleTriggers.tick`)(function*(e){let t=yield*I_,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*k(`Paused Loop skipped during schedule evaluation`,{loop:t.name}));let o=z4(e).filter(({loop:e})=>!n.has(e.name)),l=yield*Fk(a,t=>{let n=Pr(t.instance,e)?t:{instance:y(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*Xg(`Schedule loop selected no repositories`,{loop:n.loop.name}));let r=yield*Uh({try:()=>{let e=s(n.trigger),r=B4(e,t);return{latest:r,latestLocal:H4(r,n.trigger.tz),next:V4(e,t)}},catch:e=>e}).pipe(Yh);if(Ei(r)){yield*Zg(`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 I4({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*k(`Tick already fired`,{loop:n.loop.name,scheduledAt:G_(i.latest)});continue}let c=yield*Yh(C2(e,n.loop));if(Ei(c)){let e=c.failure;yield*Zg(`Schedule loop could not resolve its Agent`,{loop:e.loop,agent:e.agent,errorTag:e._tag,message:e.message}),d.push(new P4({loop:e.loop,agent:e.agent,message:e.message}))}else if(n.repositories.length!==0){p.set(n.loop.name,a),yield*O(`Schedule tick due`,{loop:n.loop.name,agent:c.success.agent.name,cron:n.trigger.cron,tz:n.trigger.tz,scheduledAt:G_(i.latest),scheduledAtLocal:i.latestLocal,repositories:n.repositories.length,nextTickAt:G_(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*E({schedules:o.length,fanout:u.length});let g=yield*Ah(u,e=>Yh(c(e,t)).pipe(Qh(t=>({candidate:e,result:t}))),{concurrency:j4}),_=[],ee=[],te=new Set,ne=new Set,re=0;for(let{candidate:e,result:t}of g){if(Di(t)){x(t.success)?(_.push(t.success.value),te.add(e.loop.name)):re+=1;continue}let n=t.failure;ne.add(e.loop.name),yield*Zg(`Scheduled Tick failed; sibling fanout was unaffected`,{loop:e.loop.name,repository:e.repository.name,agent:e.agent.name,scheduledAt:G_(e.scheduledAt),...N4(n)}),ee.push(new F4({loop:e.loop.name,repository:e.repository.name,scheduledAt:e.scheduledAt,errorTag:n._tag,message:n.message}))}yield*Ik(a,e=>{let t=new Map(e.ticks);for(let[e,n]of p)te.has(e)&&!ne.has(e)&&t.set(e,n);return{...e,ticks:t}});let ie=new R4({loops:o.length,fanout:u.length,submissions:_,skipped:re,alreadyFired:h,failures:[...d,...f,...ee],nextTickAt:U4(m)});return yield*Pk(i,y(ie)),ie}),u=(e,t,n)=>hg(pg($a(n)),b2(e,t).pipe(qh(O(`Instance reloaded; evaluating schedules now instead of after the sleep`))));return{latest:Nk(i),run:e=>w(function*(){let t=yield*e.get,n=yield*Yh(l(t));if(Ei(n)){yield*Zg(`Schedule cycle could not read Loop runtime state; retrying`,{errorTag:n.failure._tag,message:n.failure.message,operation:n.failure.operation,sleepMs:M4}),yield*u(e,t,M4);return}let r=n.success,i=yield*rp,a=_r(r.nextTickAt,{onNone:()=>i+M4,onSome:H_}),o=Math.min(M4,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:_r(r.nextTickAt,{onNone:()=>`none`,onSome:G_}),sleepMs:o};r.fanout===0&&r.failures.length===0?yield*k(`Schedule cycle complete`,s):yield*O(`Schedule cycle complete`,s),yield*u(e,t,o)}).pipe(Lg),tick:l}}))});var q4=class extends V(`@usine/orchestrator/ApprovalNeed`)(`ApprovalNeed`,{id:A,repository:H,runId:yN,loop:uA,item:F(Iq)}){},J4=class extends V(`@usine/orchestrator/RunFailureNeed`)(`RunFailureNeed`,{id:A,repository:H,runId:yN,loop:uA,failure:IW}){},Y4=class extends V(`@usine/orchestrator/PollFailureNeed`)(`PollFailureNeed`,{id:A,failure:k2}){},X4=class extends V(`@usine/orchestrator/PreflightFindingNeed`)(`PreflightFindingNeed`,{id:A,finding:fW}){},Z4=class extends V(`@usine/orchestrator/BoardProjectionNeed`)(`BoardProjectionNeed`,{id:A,failure:Uq}){},Q4=class extends V(`@usine/orchestrator/ScheduleFailureNeed`)(`ScheduleFailureNeed`,{id:A,failure:L4}){},$4=class extends V(`@usine/orchestrator/ConfigFileNeed`)(`ConfigFileNeed`,{id:A,kind:P([`loop`,`agent`]),error:dJ}){},e3=class extends V(`@usine/orchestrator/UnconfiguredWorkerNeed`)(`UnconfiguredWorkerNeed`,j({id:A,worker:kN,attempts:L.check(BT(1)),running:L.check(BT(0))}).check(jT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},t3=class extends V(`@usine/orchestrator/UnconfirmedStopNeed`)(`UnconfirmedStopNeed`,{id:A,repository:H,runId:yN,loop:uA,attemptNumber:mF,worker:kN}){},n3=class extends V(`@usine/orchestrator/UnresponsiveWorkerNeed`)(`UnresponsiveWorkerNeed`,{id:A,worker:kN,lastAnsweredAt:A,attempts:M(j({attemptId:pF,attemptNumber:mF,runId:yN,repository:H,loop:uA})).check(UT(1))}){},r3=class extends V(`CycleBudgetNeed`)(`CycleBudgetNeed`,{id:A,ask:yI,itemLabel:A,itemUrl:F(A)}){},i3=class extends V(`@usine/orchestrator/WorkerPreflightNeed`)(`WorkerPreflightNeed`,{id:A,worker:kN,message:A}){},a3=class extends V(`@usine/orchestrator/WorkerQuotaNeed`)(`WorkerQuotaNeed`,{id:A,worker:kN,message:A}){},o3=class extends V(`@usine/orchestrator/PoolLimitNeed`)(`PoolLimitNeed`,{id:A,pool:MP,login:_E(LP),window:P([`primary`,`secondary`]),usedPercent:oT.check(BT(80)),resetsAt:gE}){},s3=N([class extends V(`@usine/orchestrator/WebhookSilenceNeed`)(`WebhookSilenceNeed`,{id:A,startedAt:A,publicUrl:A}){},r3,q4,Z4,J4,Y4,X4,Q4,$4,e3,t3,n3,i3,a3,o3]),c3=P([`clear`,`active`,`needs-you`]),l3=class extends B(`@usine/orchestrator/ProjectView`)({id:Zw(Xk),name:Zw(A),repositories:M(H).pipe(TT(C([])),CT(C([]))),repository:H,status:c3,runs:M(Oq),board:Wq,labels:M(Gq),preflightFindings:M(fW)}){},u3=class extends B(`@usine/orchestrator/LoopView`)({name:uA,trigger:A,agent:aA,paused:sT}){},d3=class extends V(`@usine/orchestrator/ReadyOverview`)(`Ready`,{projects:M(l3),loops:M(u3),needsYou:M(s3),dismissedNeeds:M(s3).pipe(CT(C([])))}){},f3=class extends V(`@usine/orchestrator/NeedsSetupOverview`)(`NeedsSetup`,{errorTag:R,projects:M(l3),loops:M(u3),needsYou:M(s3),dismissedNeeds:M(s3).pipe(CT(C([])))}){},p3=N([d3,f3]),m3=N([j({name:nX.fields.name,value:PE,text:Zw(nT)}),j({name:nX.fields.name,text:A,value:Zw(nT)})]),h3=class extends B(`LoopCheck`)({problems:M(uJ)}){},g3=class extends B(`LoopPreviewRequest`)({name:nX.fields.name,value:PE,itemKey:Zw(dI)}){},_3=class extends B(`LoopPreviewItem`)({itemKey:dI,repository:H,kind:P([`issue`,`pr`]),number:fI,title:A,url:A,state:yW,priority:eX}){},v3=class extends B(`LoopPreview`)({stream:XY,items:M(_3),total:L.check(BT(0)),prompt:F(j({itemKey:dI,text:A})),repositoriesWithoutItems:M(H),failures:M(j({itemKey:dI,message:A}))}){},y3=class extends B(`ConfigurationEntityRequest`)({kind:A,identifier:gX}){},b3=class extends B(`ConfigurationRevisionQuery`)({kind:Zw(A),identifier:Zw(gX),before:Zw(mX),limit:L.check(VT({minimum:1,maximum:100}))}){},x3=class extends B(`ConfigurationWrite`)({expected:mX,message:Zw(A)}){},S3=N([j({...x3.fields,value:PE,text:Zw(nT),position:Zw(L.check(BT(0)))}),j({...x3.fields,text:A,value:Zw(nT),position:Zw(L.check(BT(0)))})]),C3=class extends B(`ConfigurationEntityView`)({key:_X,value:PE,text:A,number:mX}){},w3=class extends B(`ConfigurationRevisionSummary`)({number:mX,actor:F(NM),time:hE,message:F(A),entities:M(_X)}){},T3=class extends B(`ConfigurationRevisionPage`)({revisions:M(w3),nextBefore:F(mX)}){};jE(`ConfigurationNotFound`)(`ConfigurationNotFound`,{message:A});var E3=class e extends B(`ConfigurationRevisionView`)({...w3.fields,changes:M(j({key:_X,before:F(PE),after:F(PE),position:Zw(L)}))}){static fromRevision(t){return new e({...t,actor:S(t.actor),message:S(t.message),entities:t.changes.map(({key:e})=>e),changes:t.changes.map(e=>({...e,before:S(e.before),after:S(e.after)}))})}},D3=class extends B(`@usine/orchestrator/UpgradeRequest`)({timing:hJ,version:yE(mJ)}){},O3=class extends B(`@usine/orchestrator/UpgradeView`)({running:A,channel:fJ,mode:pJ,supported:sT,available:F(mJ),phase:P([`idle`,`waiting`,`installing`,`failed`]),message:F(A),outcome:F(_J)}){},k3=`~effect/http-api/HttpApiSchema/Stream`;function A3(e){let t=typeof e==`string`?AV(e):e;return e=>e.ast.checks!==void 0||X3(e.ast)?e.annotate({httpApiStatus:t}):e.annotateKey({httpApiStatus:t})}var j3=(e=>lT.pipe(A3(e)))(204),M3=e=>Xw(e)&&me(e,k3),N3=e=>M3(e)&&e._tag===`StreamSse`,P3=e=>M3(e)&&e._tag===`StreamUint8Array`,F3=e=>M3(e)&&e._tag===`StreamNdjson`,I3=`~effect/http-api/HttpApiSchema/Upgrade`,L3=e=>Xw(e)&&me(e,I3),R3=`~effect/http-api/HttpApiSchema/WithHeaders`,z3=`~effect/http-api/HttpApiSchema/WithHeadersValue`,B3=e=>({[z3]:z3,body:e.body,headers:e.headers}),V3=e=>Xw(e)&&me(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function H3(e,t,n){return Yw(e.ast,{[R3]:R3,schema:t,headers:n})}function U3(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??W3(t._tag)}})}function W3(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 G3(e){return t=>U3(t,{_tag:`FormUrlEncoded`,...e})}var K3=e=>{if(Wb(e)||Wb(VS(e)))return!0;let t=e.encoding?.[0].to;return t!==void 0&&Wb(t)},q3=sC(`~httpApiEncoding`),J3=sC(`~httpApiWithHeaders`),Y3=sC(`httpApiStatus`);function X3(e){let t=oC(e);return t!==void 0&&`httpApiStatus`in t}function Z3(e){return X3(e)?Y3(e):e.checks===void 0?e.context?.annotations?.httpApiStatus:void 0}var Q3={_tag:`Json`,contentType:`application/json`},$3={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function e6(e){return q3(e)??Q3}function t6(e,t){return q3(e)||(aB(t)?Q3:$3)}function n6(e){let t=e6(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function r6(e){return Z3(e)??200}function i6(e){return V3(e)?Z3(e.ast)??r6(e.schema.ast):r6(e.ast)}function a6(e){return V3(e)&&q3(e.ast)===void 0?n6(e.schema.ast):n6(e.ast)}function o6(e){return Z3(e)??500}function s6(e){return V3(e)?Z3(e.ast)??o6(e.schema.ast):o6(e.ast)}function c6(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}var l6=`~effect/http-api/HttpApiEndpoint`;function u6(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 Yi(t)?t:[j3]}function f6(e){let t=new Set(e.error),n=e.disableCodecs?i:x6;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}var p6={[l6]:l6,pipe(){return e(this,arguments)},prefix(e){return h6({...m6(this),path:bV(this.path,e)})},middleware(e){return h6({...m6(this),middlewares:new Set([...this.middlewares,e])})},annotate(e,t){return h6({...m6(this),annotations:ii(this.annotations,e,t)})},annotateMerge(e){return h6({...m6(this),annotations:mi(this.annotations,e)})}},m6=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 h6(e){function t(){}return Object.setPrototypeOf(t,p6),Object.assign(t,e)}var g6=e=>(t,n,r)=>{let a=r?.disableCodecs??!1,o=a?i:NE;return h6({identifier:t,path:n,method:e,params:_6(r?.params,o),query:_6(r?.query,o),headers:_6(r?.headers,o),payload:v6(r?.payload,e,a),success:b6(r?.success,e,r?.payload!==void 0,a),error:S6(r?.error,a),annotations:ti(),middlewares:new Set,disableCodecs:a})};function _6(e,t){if(e!==void 0)return Xw(e)?t(e):t(j(e))}function v6(e,t,n){let r=new Map;if(e===void 0)return r;let a=Array.isArray(e)?e:Xw(e)?[e]:[j(e).pipe(G3())],o=n?i:M6,s=!1;for(let e of a){if(M3(e)){if(N3(e))throw Error(`StreamSse is response-only and cannot be used as a payload`);if(!aB(t))throw Error(`${t} endpoints cannot declare a streaming payload`);if(s)throw Error(`Multiple streaming payloads are not supported`);s=!0;let n=c6(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=t6(e.ast,t),i=c6(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 y6=`effect/http-api/stream/failure`;function b6(e,t,n,r){if(e===void 0)return new Set;let i=Gi(e);return C6(i,t,n),new Set(r?i:i.map(x6))}var x6=f(e=>M3(e)||L3(e)?e:V3(e)?H3(e,M3(e.schema)?e.schema:j6(e.schema,a6(e)),NE(e.headers)):A6(e));function S6(e,t){if(e===void 0)return new Set;let n=Gi(e);for(let e of n){let t=V3(e)?e.schema:e;if(M3(t))throw Error(`Streaming schemas are not supported in error responses`);if(L3(t))throw Error(`Upgrade schemas are not supported in error responses`)}return T6(n,s6),new Set(t?n:n.map(x6))}function C6(e,t,n){if(e.some(L3)){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=V3(n)?n.schema:n,a=i6(n);if(M3(e)){if(E6(e,t),r)throw Error(`Multiple streaming success responses are not supported`);r=!0;let n=w6(i,a);if(n.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(n.bufferedContentTypes.has(c6(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=w6(i,a),r=K3(e.ast);if(t.stream!==void 0){if(r)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=a6(n);if(c6(e.contentType)===c6(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}r||t.bufferedContentTypes.add(c6(a6(n).contentType)),t.noContent=t.noContent||r}}T6(e,i6)}function w6(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:new Set,noContent:!1},e.set(t,n)),n}function T6(e,t){let n=new Map;for(let r of e){let e=t(r),i=J3(r.ast),a=V3(r)?r.schema:i?.body??r,o=K3(a.ast)?``:c6(M3(a)?a.contentType:a6(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(V3(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 E6(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(N3(e)&&D6(e.events.ast))throw Error(`SSE event name is reserved: ${y6}`)}function D6(e){return O6(VS(e),new Set)}function O6(e,t){if(t.has(e))return!1;if(t.add(e),Xb(e))return e.types.some(e=>O6(e,t));if(Zb(e))return O6(e.thunk(),t);if(!Yb(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&k6(n.type,t)}function k6(e,t){if(t.has(e))return!1;t.add(e);let n=VS(e);return n===e?Kb(e)?e.literal===y6:Xb(e)?e.types.some(e=>k6(e,t)):Zb(e)?k6(e.thunk(),t):!1:k6(n,t)}function A6(e){let t=n6(e.ast),n=J3(e.ast);return n===void 0?j6(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:j6(n.body,t),headersCodec:NE(n.headers)}})}function j6(e,t){switch(t._tag){case`Json`:return ME(e);case`FormUrlEncoded`:return NE(e);case`Text`:case`Uint8Array`:return e}}function M6(e,t){switch(t6(e.ast,t)._tag){case`Json`:return ME(e);case`FormUrlEncoded`:return NE(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}var N6=g6(`GET`),P6=g6(`POST`),F6=g6(`PUT`),I6=g6(`DELETE`),L6=`~effect/http-api/HttpApi`,R6={[L6]:L6,pipe(){return e(this,arguments)},add(...e){let t={...this.groups};for(let n of e)Et(t,n.identifier,n);return B6({...z6(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];Et(t,n,r.annotateMerge(mi(e.annotations,r.annotations)))}return B6({...z6(this),groups:t})},prefix(e){return B6({...z6(this),groups:zi(this.groups,t=>t.prefix(e))})},middleware(e){return B6({...z6(this),groups:zi(this.groups,t=>t.middleware(e))})},annotate(e,t){return B6({...z6(this),annotations:ii(this.annotations,e,t)})},annotateMerge(e){return B6({...z6(this),annotations:mi(this.annotations,e)})}},z6=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),B6=e=>{function t(){}return Object.setPrototypeOf(t,R6),Object.assign(t,e)},V6=e=>B6({identifier:e,groups:{},annotations:ti()}),H6=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=mi(e.annotations,r.annotations);t.onGroup({group:r,mergedAnnotations:n});let i=Object.values(r.endpoints);for(let e of i)(!t.predicate||t.predicate({endpoint:e,group:r}))&&t.onEndpoint({group:r,endpoint:e,middleware:e.middlewares,mergedAnnotations:mi(n,e.annotations),successes:U6(d6(e),i6),errors:U6(f6(e),s6)})}},U6=(e,t)=>{let n=new Map;return e.forEach(r),n;function r(e){let r=V3(e)?e.schema:e;if(M3(r)||L3(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}},W6=class extends Lr()(`effect/http-api/HttpApi/ParseOptions`){},G6=class extends Lr()(`effect/http-api/HttpApi/ParamsParseOptions`){},K6=class extends Lr()(`effect/http-api/HttpApi/QueryParseOptions`){},q6=class extends Lr()(`effect/http-api/HttpApi/HeadersParseOptions`){},J6=class extends Lr()(`effect/http-api/HttpApi/PayloadParseOptions`){},Y6=class extends Lr()(`effect/http-api/HttpApi/SuccessParseOptions`){},X6=class extends Lr()(`effect/http-api/HttpApi/ErrorParseOptions`){},Z6=e=>{let t=oi(e,W6);return{params:oi(e,G6)??t,query:oi(e,K6)??t,headers:oi(e,q6)??t,payload:oi(e,J6)??t,success:oi(e,Y6)??t,error:oi(e,X6)??t}},Q6=`~effect/http-api/HttpApiMiddleware`,$6=`~effect/http-api/HttpApiMiddleware/Security`,e8=()=>(e,t)=>{let n=St(),r;n!==0&&(Ct(2),r=new globalThis.Error,Ct(n));class i extends Lr()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[Q6]=Q6,a.error=t8(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[$6]=$6,a.security=t.security}return a};function t8(e){return e===void 0?new Set:new Set(Array.isArray(e)?e:[e])}var n8=new Set;function r8(e){if(e===void 0)return n8;let t=_S(e.ast);return Yb(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function i8(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=hV(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 a8=(e,t)=>w(function*(){let n=yield*yg(),r=t.httpClient.pipe(t?.baseUrl===void 0?i:nV(DB(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)}})}H6(e,{predicate:t?.predicate,onGroup(e){t.onGroup?.(e)},onEndpoint(e){let{group:n,endpoint:r,errors:i,successes:o,mergedAnnotations:s}=e,c=Z6(s),l=c8(r.path,r.params),u={orElse:M8},d=new Map;for(let[e,t]of i.entries()){let n=m8(t);for(let[t,r]of n.entries())f8(d,e,t,l8(r,c.error,c.headers))}for(let[e,t]of d.entries()){let n=p8(t);u[e]=e=>T(ag(n(e),t=>Bh(Zd(Wd(new Xz({reason:new nB({request:e.request,response:e})})),t))),zh)}let f=new Map;for(let[e,t]of o.entries()){let n=m8(t);for(let[t,r]of n.entries())f8(f,e,t,l8(r,c.success,c.headers))}for(let e of y8(r)){let t=_8(e)?e.schema:e;f8(f,i6(e),t.contentType,b8(e,c.success,c.headers))}for(let[e,t]of f.entries())u[e]=p8(t);let p=v8(r);p!==void 0&&(u[101]=e=>Qh(e.upgrade,t=>({headers:e.headers,socket:t})));let m=Rk(r.params,e=>Gw(e,c.params)),h=[],g;for(let e of u6(r))P3(e)||F3(e)?g=e:h.push(e);let _=Rk(g,e=>({contentType:e.contentType,encode:P8(e,c.payload)})),ee=Yi(h)?Gw(aB(r.method)?F8(h,r.method):N(h),c.payload):void 0,te=Rk(r.headers,e=>Gw(e,c.headers)),ne=Rk(r.query,e=>Gw(e,c.query)),re=Array.from(e.middleware,e=>`${e.key}/Client`),ie=Yg(function*(e){let i=hB(r.method)(r.path);if(e!==void 0){if(m!==void 0){let t=yield*m(e.params);i=EB(i,l(t))}if(_!==void 0&&xO(e.payload)){let t=yield*yg();i=MB(i,Jz(BO(_.encode(e.payload),t),_.contentType))}else if(ee!==void 0){if(aB(r.method)){if(e.payload instanceof FormData)i=PB(i,e.payload);else{let t=yield*ee(e.payload);i=MB(i,t)}}else{let t=yield*ee(e.payload);i=AB(i,t)}}else if(_!==void 0)return yield*new jw(new ky({message:`Expected a Stream payload`},e.payload));if(te!==void 0){let t=yield*te(e.headers);i=SB(i,t)}if(ne!==void 0){let t=yield*ne(e.query);i=AB(i,t)}}p!==void 0&&(i=TB(i,p.protocol));let o=yield*a(n,r,i,re,re.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:ie})}})}),o8=(e,t)=>T(XB,n=>s8(e,{...t,httpClient:t?.transformClient?t.transformClient(n):n})),s8=(e,t)=>{let n={};return a8(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($h(n))},c8=(e,t)=>{if(t===void 0||!e.includes(`:`))return t=>e;let n=r8(t);return t=>i8(e,n,(e,n)=>{let r=t[e];if(r!==void 0)return encodeURIComponent(r);if(!n)throw Error(`Missing path parameter: ${e}`)})};function l8(e,t,n){let r=e.some(e=>V3(e)||J3(e.ast)!==void 0),i=zw(r?N(e.map(e=>d8(e,t,n))):A8(e),t);return e=>T(e.arrayBuffer,r?t=>i({body:t,headers:e.headers}):i)}var u8=j({body:rT,headers:rT});function d8(e,t,n){let r=J3(e.ast),i=r===void 0?V3(e)?{body:e.schema,headers:e.headers,toValue:B3}:{body:e,headers:rT,toValue:e=>e.body}:{body:r.bodyCodec,headers:r.headersCodec,toValue:r.transformation.decode},a=zw(j8(i.body).pipe(bT(i.body)),t),o=zw(i.headers,n);return u8.pipe(bT(V3(e)?e:$w(e),Sb({decode:e=>kh({body:a(e.body),headers:o(e.headers)}).pipe(Qh(i.toValue),sg(e=>e.issue)),encode:(e,t)=>zh(new jy({message:`Decode only schema`},e,t))})))}function f8(e,t,n,r){let i=c6(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=c6(t.headers[`content-type`]??``),i=e.find(e=>e.contentType===r);return i===void 0?h8(t,r,e):i.decode(t,n)}}function m8(e){let t=new Map;for(let n of e){let e=K3((V3(n)?n.schema:n).ast)?``:c6(a6(n).contentType),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return t}function h8(e,t,n){let r=Array.from(new Set(n.map(e=>e.contentType))).join(`, `);return zh(new Xz({reason:new rB({request:e.request,response:e,description:`Unsupported response content-type for status ${e.status}: ${t||`<missing>`}. Expected one of: ${r}`})}))}var g8=`effect/http-api/stream/failure`,_8=e=>V3(e);function v8(e){for(let t of e.success)if(L3(t))return t}function y8(e){let t=[];for(let n of e.success)M3(V3(n)?n.schema:n)&&t.push(n);return t}function b8(e,t,n){let r=_8(e),i=x8(r?e.schema:e,t),a=(e,t)=>Qh(yg(),n=>BO(i(e,t),n));if(!r)return a;let o=zw(e.headers,n);return(e,t)=>T(o(e.headers),n=>Qh(a(e,t),e=>B3({body:e,headers:n})))}function x8(e,t){if(P3(e))return e=>e.stream;if(F3(e)){let n=zw(ME(e.schema),t),r=A_(e.maxElementBytes);return e=>e.stream.pipe(IO(gR({ignoreEmptyLines:!0,maxLineBytes:r})),FO(t=>cR(t)?t.reason===`LineTooLarge`?new Xz({reason:new rB({request:e.request,response:e,description:`NDJSON line exceeds maxElementBytes of ${r} bytes`})}):C8(t):t),jO(e=>n(e)))}let n=w8(e,t);return(t,r)=>T8(t.stream,e,n(r))}var S8=e=>cR(e)&&e.kind===`Pack`,C8=e=>new jw(new ky({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 w8(e,t){let n=N([j({id:Qw(A),event:tT(g8),data:rE(ME(lE(e.error,QT())))}),e.events]),r=SR(n,void 0,t);return e=>e===void 0?r:SR(n,e,t)}function T8(e,t,n){let r=CO(e.pipe(LO,IO(n)),e=>Fh(()=>{let t;return Ph(()=>t===void 0?T(e,e=>{for(let n=0;n<e.length;n++){let r=e[n];if(r.event===g8&&Bd(r.data)){if(n===0)return Bh(r.data);t=r.data,e=e.slice(0,n);break}}return C(e)}):Bh(t))}));return t.sseMode===`data`?AO(r,e=>e.data):r}var E8=kT(globalThis.ArrayBuffer,{expected:`ArrayBuffer`}),D8=E8.pipe(bT(sE,Cb({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)}}))),O8=E8.pipe(bT(A,Cb({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)}}))),k8=O8.pipe(bT(N([tT(``).pipe(bT(aT,Cb({decode:()=>void 0,encode:()=>``}))),iE])));function A8(e){return N(e.map(t));function t(e){return j8(e).pipe(bT(e))}}function j8(e){switch(n6(e.ast)._tag){case`Json`:return Ub(VS(e.ast))?k8.pipe(bT(rT,Cb({decode:e=>e===void 0?null:e,encode:e=>e===null?void 0:e}))):k8;case`FormUrlEncoded`:return O8.pipe(bT(vE,Cb({decode:e=>Rv(new URLSearchParams(e)),encode:qv})));case`Uint8Array`:return D8;case`Text`:return O8}}var M8=e=>zh(new Xz({reason:new rB({request:e.request,response:e})})),N8=Aw(Pz);function P8(e,t){if(P3(e))return e=>e;let n=Gw(_T(ME(e.schema)),t);return e=>e.pipe(MO(e=>n(e)),IO(uR()),PO(S8,OO))}function F8(e,t){return N(e.map(e=>L8(e,t)))}var I8=new WeakMap;function L8(e,t){let n=e.ast,r=I8.get(n);if(r!==void 0)return r;let i=t6(n,t),a=N8.pipe(bT(e,Sb({decode(e,t){return zh(new jy({message:`Encode only schema`},e,t))},encode(e,t){switch(i._tag){case`Multipart`:return zh(new jy({message:`Payload must be a FormData`},e,t));case`Json`:try{return C(Hz(JSON.stringify(e),i.contentType))}catch{return zh(new ky({expected:`a JSON-serializable request body`},e,t))}case`Text`:return typeof e==`string`?C(Hz(e,i.contentType)):zh(new ky({message:`Expected a string`},e,t));case`FormUrlEncoded`:return fe(e)?C(Wz(Rv(e),i.contentType)):zh(new ky({message:`Expected a record`},e,t));case`Uint8Array`:return e instanceof Uint8Array?C(Rz(e,i.contentType)):zh(new ky({message:`Expected a Uint8Array`},e,t))}}})));return I8.set(n,a),a}var R8=`~effect/http-api/HttpApiGroup`,z8={[R8]:R8,add(...e){let t={...this.endpoints};for(let n of e)Et(t,n.identifier,n);return V8({...B8(this),endpoints:t})},prefix(e){return V8({...B8(this),endpoints:zi(this.endpoints,t=>t.prefix(e))})},middleware(e){return V8({...B8(this),endpoints:zi(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return V8({...B8(this),annotations:mi(this.annotations,e)})},annotate(e,t){return V8({...B8(this),annotations:ii(this.annotations,e,t)})},annotateEndpointsMerge(e){return V8({...B8(this),endpoints:zi(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return V8({...B8(this),endpoints:zi(this.endpoints,n=>n.annotate(e,t))})},pipe(){return e(this,arguments)}},B8=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),V8=e=>{function t(){}return Object.setPrototypeOf(t,z8),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},H8=(e,t)=>V8({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:ti()}),U8=P([`workers`,`webhooks`,`tracing`]),W8=e=>j({added:M(e),removed:M(e),changed:M(e)});B(`@usine/orchestrator/InstanceReload`)({loops:W8(uA),agents:W8(aA),labels:W8(hA),repos:W8(H),projects:W8(Xk),workers:W8(kN),settingsChanged:sT,operatorChanged:sT,quarantinedLoops:M(rX),invalidAgents:M(oX)});var G8=10,K8=class extends V(`@usine/github/LabelAdded`)(`LabelAdded`,{at:hE,label:$H}){},q8=class extends V(`@usine/github/LabelRemoved`)(`LabelRemoved`,{at:hE,label:$H}){},J8=class extends V(`@usine/github/Commented`)(`Commented`,{at:hE,url:R}){},Y8=P([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`DISMISSED`]),X8=class extends V(`@usine/github/Reviewed`)(`Reviewed`,{at:hE,url:R,state:Y8}){};N([K8,q8,J8,X8]);var Z8=`
|
|
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 } }`,Q8=`
|
|
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 {${Z8}
|
|
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 {${Z8}
|
|
328
|
-
... on PullRequestReview { createdAt submittedAt url state author { __typename login } }
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
`,$8=F(j({__typename:A,login:A})),e5=j({name:ZH,color:QH,description:F(A)}),t5=e=>j({__typename:tT(e),createdAt:gE,actor:$8,label:e5}),n5=N([t5(`LabeledEvent`),t5(`UnlabeledEvent`),j({__typename:tT(`IssueComment`),createdAt:gE,url:R,author:$8}),j({__typename:tT(`PullRequestReview`),createdAt:gE,submittedAt:F(gE),url:R,state:P([...Y8.literals,`PENDING`]),author:$8})]),r5=j({repository:_E(j({issueOrPullRequest:_E(j({timelineItems:j({pageInfo:j({hasNextPage:sT,endCursor:F(A)}),nodes:M(F(n5))})}))}))}),i5=(e,t)=>{let n=t=>t!==null&&t.__typename===`Bot`&&t.login===e.slice(0,-5),r=e=>new $H({name:e.name,color:e.color,description:xr(e.description)});switch(t.__typename){case`LabeledEvent`:return n(t.actor)?[new K8({at:t.createdAt,label:r(t.label)})]:[];case`UnlabeledEvent`:return n(t.actor)?[new q8({at:t.createdAt,label:r(t.label)})]:[];case`IssueComment`:return n(t.author)?[new J8({at:t.createdAt,url:t.url})]:[];case`PullRequestReview`:{let e=t.state;return!n(t.author)||e===`PENDING`?[]:[new X8({at:t.submittedAt??t.createdAt,url:t.url,state:e})]}}},a5=class e extends Lr()(`@usine/github/GitHubItemHistory`){static layer=qf(e,w(function*(){let e=yield*VH,t=yield*XB,n=D(`GitHubItemHistory.timelinePage`)(function*(n,r,i,a){yield*E({repository:n,item:r});let o=yield*e.installationToken(),{name:s,owner:c}=Jk(n),l=yield*lU(t,o,`fetch-item-timeline`,Q8,{owner:c,name:s,number:r,since:i,after:a},r5);if(b(l.repository))return yield*SH(`fetch-item-timeline`,`repository "${n}" is null: deleted, renamed, or no longer accessible`);let u=l.repository.value.issueOrPullRequest;if(b(u))return yield*new hH({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*SH(`fetch-item-timeline`,`GitHub returned hasNextPage for the timeline without an endCursor`):{nodes:f,next:y(d.endCursor)}:{nodes:f,next:v()}});return{appChanges:D(`GitHubItemHistory.appChanges`)(function*(e,t,r,i){yield*E({repository:e,item:t,actor:i});let a=G_(r),o=[],s=v(),c=0;do{let r=yield*n(e,t,a,S(s));o.push(...r.nodes),s=r.next,c+=1}while(x(s)&&c<G8);if(x(s))return yield*SH(`fetch-item-timeline`,`the timeline of ${e}#${t} since ${a} has more than ${G8} pages`);let l=o.flatMap(e=>e===null?[]:i5(i,e));return yield*k(`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})}}))},o5=class extends V(`@usine/orchestrator/LabelAddedView`)(`LabelAdded`,{at:A,label:Gq}){},s5=class extends V(`@usine/orchestrator/LabelRemovedView`)(`LabelRemoved`,{at:A,label:Gq}){},c5=class extends V(`@usine/orchestrator/CommentedView`)(`Commented`,{at:A,url:A}){},l5=class extends V(`@usine/orchestrator/ReviewedView`)(`Reviewed`,{at:A,url:A,state:Y8}){},u5=class extends V(`@usine/orchestrator/BoardMovedView`)(`BoardMoved`,{at:A,fromLane:vW,toLane:vW}){},d5=N([o5,s5,c5,l5,u5]),f5=class extends B(`@usine/orchestrator/AttemptGitHubChangesView`)({attemptId:pF,changes:M(d5)}){},p5=class extends B(`@usine/orchestrator/RunGitHubChangesView`)({attempts:M(f5)}){},m5=1e3,h5=6e4,g5=1e3,_5=1e4,v5=(e,t)=>{let n=new Map,r=[];for(let i of t){let[t,...a]=e.filter(e=>kF(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}},y5=e=>t=>{let n=H_(t.at),r=n-g5,i=H_(e.at),a=gA(e.label.name);return r-r%1e3<=i&&i<=n+_5&&(e._tag===`LabelAdded`?t.added:t.removed).some(e=>gA(e)===a)},b5=(e,t)=>{let n=new Set,r=[];for(let i of t){let t=i._tag===`LabelAdded`||i._tag===`LabelRemoved`?e.find(y5(i)):void 0;t===void 0?r.push(i):n.add(t)}return{moves:e.filter(e=>n.has(e)),rest:r}},x5=e=>new Gq({name:hA.make(e.name),color:e.color,description:S(e.description)}),S5=e=>wk(e,{LabelAdded:({at:e,label:t})=>new o5({at:G_(e),label:x5(t)}),LabelRemoved:({at:e,label:t})=>new s5({at:G_(e),label:x5(t)}),Commented:({at:e,url:t})=>new c5({at:G_(e),url:t}),Reviewed:({at:e,url:t,state:n})=>new l5({at:G_(e),url:t,state:n})}),C5=e=>new u5({at:G_(e.at),fromLane:vW.make(e.fromLane),toLane:vW.make(e.toLane)}),w5=w(function*(){let e=yield*uq,t=yield*a5,n=yield*VH,r=yield*i2,i=yield*Mk(new Map),a=D(`RunGitHubChanges.windowFor`)(function*(t){yield*E({attemptId:t.id,worker:t.worker});let n=EF(t);if(x(n))return n;let[r]=yield*e.transcript(new AG({attemptId:t.id,before:v(),limit:1}));return r===void 0?(yield*O(`An ended Attempt has neither an end time nor a transcript; no GitHub change is placed in it`,{attemptId:t.id}),v()):y(new TF({attemptId:t.id,startedAt:t.startedAt,endedAt:y(r.receivedAt)}))});return{read:D(`RunGitHubChanges.read`)(function*(o,s){yield*E({runId:s});let c=yield*e.inspect(s),l=Hw(Q2)(c.itemKey);if(b(l))return yield*k(`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*E({repository:d,item:u});let f=e=>new p5({attempts:c.attempts.map(({id:t})=>new f5({attemptId:t,changes:e.get(t)??[]}))});if(c.attempts.length===0)return f(new Map);let{appSlug:p}=yield*n.installation(),m=jN.make(`${p}[bot]`),h=new Map(o.map(({name:e,kind:t})=>[e,YW(t,m)])),g=JSON.stringify([m,[...h].sort(([e],[t])=>e.localeCompare(t))]),_=e=>Dr(Sr(h.get(e.worker)),t=>JSON.stringify([e.id,t,g])),ee=yield*Nk(i),te=new Map(c.attempts.flatMap(e=>jr(Or(_(e),t=>Dr(Sr(ee.get(t)),t=>[e.id,t]))))),ne=c.attempts.filter(({id:e})=>!te.has(e));if(ne.length===0)return yield*k(`Served the Run's GitHub changes from the Attempt cache`,{runId:s,attempts:c.attempts.length}),f(te);let re=yield*e.forItems([c.itemKey]),ie=new Map([...re.flatMap(({attempts:e})=>e),...c.attempts].map(e=>[e.id,e])),ae=new Map;for(let e of ie.values()){let t=h.get(e.worker);t===void 0?yield*Xg(`Attempt worker is no longer configured; its GitHub writer is unknown`,{runId:s,attemptId:e.id,worker:e.worker}):ae.set(e.id,t)}let oe=(yield*Ah([...ie.values()],a)).flatMap(jr),se=yield*rp,ce=new Map,le=[],ue=ne.flatMap(e=>{let t=oe.find(({attemptId:t})=>t===e.id);return t===void 0?(ce.set(e.id,[]),le.push(e.id),[]):[t]});if(ue.length>0){let e=Math.min(...ue.map(({startedAt:e})=>H_(e))),n=P_(e-e%1e3),[i,a]=yield*kh([Ah([...new Set([m,...ue.flatMap(({attemptId:e})=>jr(Sr(ae.get(e))))])],e=>t.appChanges(d,u,n,e).pipe(Qh(t=>[e,t])),{concurrency:`unbounded`}),r.onItem(c.itemKey,W_(n,{milliseconds:_5}))],{concurrency:`unbounded`}),o=new Map(i),l=o.get(m)??[],{moves:f,rest:p}=b5(a,l);o.set(m,p);let h=new Map;for(let[e,t]of o){let n=v5(oe.filter(({attemptId:t})=>!ae.has(t)||ae.get(t)===e),t);for(let[t,r]of n.attributed)ae.get(t)===e&&h.set(t,r);n.ambiguous.length>0&&(yield*O(`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})=>G_(e)).join(`, `)}))}for(let e of ue){let t=[...(h.get(e.attemptId)??[]).map(e=>({at:H_(e.at),view:S5(e)})),...f.flatMap(t=>{let n=H_(t.at);return H_(e.startedAt)<=n&&_r(e.endedAt,{onNone:()=>!0,onSome:e=>n<=H_(e)})?[{at:n,view:C5(t)}]:[]})];ce.set(e.attemptId,t.sort((e,t)=>e.at-t.at).map(({view:e})=>e)),x(e.endedAt)&&se-H_(e.endedAt.value)>=h5&&le.push(e.attemptId)}yield*O(`Read worker GitHub changes on a run item`,{runId:s,repository:d,item:u,since:G_(n),appChanges:i.reduce((e,[,t])=>e+t.length,0),boardMoves:a.length,boardMoveChanges:l.length-p.length,placed:ue.reduce((e,{attemptId:t})=>e+(h.get(t)?.length??0),0),cachedAttempts:le.length})}return yield*Ik(i,e=>{let t=new Map(e);for(let e of ne)if(le.includes(e.id))for(let n of jr(_(e)))t.set(n,ce.get(e.id)??[]);for(let e of[...t.keys()].slice(0,Math.max(0,t.size-m5)))t.delete(e);return t}),f(new Map([...te,...ce]))})}});(class e extends Lr()(`@usine/orchestrator/RunGitHubChanges`){static layer=qf(e,w5)});var T5=P([`binary`,`version`,`login`]),E5=class extends jE(`HarnessUnavailableError`)(`HarnessUnavailableError`,{harness:nA,capability:T5,message:R}){};N([class extends V(`HarnessReady`)(`HarnessReady`,{harness:nA}){},E5]),Rw(E5),dr(sr,({harness:e})=>e);var D5=class e extends Lr()(`@usine/orchestrator/WorkerStatus`){static idle=Gf(e)({slots:C([]),queue:C([]),preflights:C([]),unavailable:C([]),machines:C([]),provisioning:C([])})},O5=500,k5=D(`Board.readItems`)(function*(e,t,n){yield*E({repository:t});let r=yield*e.list(t,{limit:O5}),i=new Set(r.map(({itemKey:e})=>e)),a=new Set(n.flatMap(({itemKey:e,repository:n,run:r})=>Yk(n)===Yk(t)&&nN(r.state)&&!i.has(e)?[e]:[])),o=ha(yield*Ah(a,n=>e.get(n).pipe(Jh(e=>b(e)?O(`Open run has no stored board item`,{repository:t,itemKey:n}):Ih)),{concurrency:4}));return yield*k(`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)}),A5=Vw(tE),j5=e=>new Iq({itemKey:e.itemKey,kind:e.kind,number:e.number,title:e.title,url:e.url,state:e.state}),M5=(e,t,n,r,i,a)=>{let o=ua(n,({itemKey:e})=>e),s=t.map(e=>({item:e,runs:o[e.itemKey]??[],related:new Set})),c=`/${Yk(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=A5(n);if(b(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=ia(n,({item:e},{item:t})=>(e.kind===t.kind?0:e.kind===`issue`?-1:1)||cr(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 Lq({number:e,url:t,state:n})]:[]),h=s.find(({item:e,run:t})=>X2(t,SW(e.state)))??c??s[0],g=s.map(({run:e})=>e).reverse(),_=new Rq({...j5(p),repository:e,title:o.item.title,labels:p.labels,items:r.map(({item:e})=>j5(e)),pullRequest:m,runs:g,run:h?.run??null,needsYou:s.some(({item:e,run:t})=>X2(t,SW(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:xq(g,a)});f.push({view:_,running:c?.run.state===`Running`?c.run:void 0})}return f},N5=e=>e.flatMap(e=>`label`in e?[e.label]:[]),P5=e=>e.flatMap(e=>`state`in e?[e.state]:[]),F5=e=>[...e].sort((e,t)=>e.localeCompare(t)).map(e=>hA.make(e)).map(e=>({lane:new TW({name:vW.make(e),sources:[new CW({label:e})]}),origin:`proposed`})),I5=(e,t)=>e.lanes.length>0?e.lanes.map(e=>({lane:e,origin:`authored`})):F5(t),L5=e=>Pq.make(`${e.origin}:${e.lane.name}`),R5=(e,t)=>{let n=new Set(e.labels.map(gA));return t.find(({lane:e})=>N5(e.sources).some(e=>n.has(gA(e))))},z5=(e,t)=>t.find(({lane:t})=>P5(t.sources).includes(e.state)),B5=(e,t)=>SW(e.state)?z5(e,t):R5(e,t)??z5(e,t),V5=D(`Board.runningLane`)(function*(e,t,n,r,i){let a={repository:e.name,itemKey:t.itemKey,runId:n.id,loop:n.loop};if(yield*E(a),SW(t.state))return;let o=R5(t,r);if(o!==void 0)return yield*k(`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*k(`No Event read for the card's running Run; placing it by its Item's state`,a);return}let c=yield*K2(t.kind,s.payload).pipe(Qh(y),ng(e=>Xg(`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($h(v()))));if(b(c))return;let l=R5({labels:c.value},r);return yield*k(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}),H5=D(`Board.project`)((e,t,n,r,i=[],a=new Map,o=new Map,s=new Map)=>w(function*(){yield*E({repository:e.name});let c=yield*Ah(n,e=>J2(e).pipe(Yh)),l=[],u=[];for(let e of c)Di(e)?l.push(e.success):(u.push(e.failure),yield*Zg(`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=I5(e,t),f=M5(e.name,l,r,i,a,o);yield*k(`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(L5(e),[]);let m=[];for(let{view:t,running:n}of f){let r=(n===void 0?void 0:yield*V5(e,t,n,d,s))??B5(t,d);r===void 0?m.push(t):p.get(L5(r))?.push(t)}let h=e=>e.sort((e,t)=>t.number-e.number);return new Wq({failures:u,lanes:[...d.map(e=>{let t=N5(e.lane.sources),n={id:L5(e),name:e.lane.name,sources:e.lane.sources,origin:e.origin,items:h(p.get(L5(e))??[])};return e.origin===`authored`&&t.length>0?new Bq({...n,origin:e.origin,labels:t}):new Vq(n)}),new Vq({id:Pq.make(`fallback:unmapped`),name:vW.make(`Unmapped`),sources:[],origin:`fallback`,items:h(m)})]})})),U5=500,W5=500,G5=e=>wk(e,{GitHubPushFailure:({message:e})=>new DW({message:e}),InfraFailure:({message:e})=>new OW({message:e}),ProviderCapacityFailure:({message:e})=>new kW({message:e}),DefectFailure:({message:e})=>new AW({message:e}),AgentFailure:({message:e})=>new jW({message:e}),BlockedFailure:({message:e})=>new MW({message:e}),QuestionFailure:({question:e})=>new NW({question:e}),RunawayFailure:({ceiling:e})=>new PW({ceiling:e}),ChildSessionBudgetFailure:({attemptedChildren:e,maxChildren:t})=>new FW({attemptedChildren:e,maxChildren:t})}),K5=e=>wk(e,{Succeeded:()=>new LW,Failed:({failure:e})=>new RW({failure:G5(e)}),Canceled:()=>new zW}),q5=e=>{switch(e.kind){case`local`:return new VW;case`ssh`:return _r(e.provisioner,{onSome:({provider:e})=>new UW({provider:e}),onNone:()=>new HW({destination:vr(e.destination,()=>PN.make(e.name)),port:S(e.port)})});case`exe.dev`:return new HW({destination:PN.make(`${e.name}.exe.xyz`),port:null});case`cloudflare`:return new WW}},J5=e=>new Map(e.map(e=>[e.name,q5(e)])),Y5=(e,t)=>new KW({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:G_(e.startedAt),outcome:_r(e.outcome,{onNone:()=>null,onSome:K5}),endedAt:_r(e.endedAt,{onNone:()=>null,onSome:G_}),salvage:S(e.salvage),start:S(e.start),reattachedAt:_r(e.reattachedAt,{onNone:()=>null,onSome:G_}),outOfMemory:S(e.outOfMemory)});D(`Operator.readUnrecordedEnds`)(function*(e,t){let n=yield*Ah(t.attempts.filter(e=>x(e.outcome)&&b(e.endedAt)),t=>e.transcript(new AG({attemptId:t.id,before:v(),limit:1})).pipe(Qh(e=>[t.id,e.at(-1)?.receivedAt])),{concurrency:4});return new Map(n.flatMap(([e,t])=>t===void 0?[]:[[e,t]]))});var X5=D(`Operator.readRunningEvents`)(function*(e,t){let n=t.flatMap(({run:e})=>e.state._tag===`Running`?[e.id]:[]),r=yield*e.events(n);return yield*k(`Read the Events of the running Runs`,{running:n.length,events:r.length}),new Map(r.map(({runId:e,event:t})=>[e,t]))}),Z5=(e,t,n,r=new Map)=>{let i=aN(e.run.state),a=S(e.step.result),o=a?.facts.find(e=>e._tag===`PullRequest`);return new Oq({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:S(PF(e.run.state,e.attempts)),loopPaused:t.has(e.run.loop),machineWait:i.canCancel?r.get(e.run.id)??null:null,openedAt:G_(e.run.openedAt),closedAt:_r(e.closedAt,{onNone:()=>null,onSome:G_}),task:e.task,attempts:e.attempts.map(e=>Y5(e,n)),approval:_r(e.approval,{onNone:()=>null,onSome:({approvedAt:e,source:t})=>new Dq({approvedAt:G_(e),source:S(t)})}),runAgain:S(e.runAgain),resultMessage:a?.message??null,pullRequestUrl:o?.url.toString()??null,...i,canResolveFailure:i.canResolveFailure&&!Pr(e.resolvedFailureAttemptId,e.attempts.at(-1)?.id)})},Q5=e=>wk(e,{Started:e=>e,SessionEvent:e=>e,Final:e=>e,Failed:({failure:e})=>new jG({failure:G5(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}),$5=e=>{let t={sequence:e.sequence,attemptId:e.attemptId,receivedAt:G_(e.receivedAt),direction:e.direction,payload:Q5(e.envelope.payload)};return e.envelope._tag===`InboundEnvelope`&&`target`in e.envelope?new NG({...t,target:e.envelope.target,operator:e.envelope.operator}):new NG(t)},e7=e=>[...e].sort((e,t)=>e.sequence-t.sequence).map($5),t7=D(`Operator.readTranscriptPage`)(function*(e,t,n){yield*E({attemptId:t,before:S(n)});let r=yield*e.transcript(new AG({attemptId:t,before:n,limit:501})),i=r.length>U5,a=i?r.slice(1):r,o=a[0];return yield*k(`Read operator transcript page`,{attemptId:t,before:S(n),returned:a.length,hasEarlier:i}),{events:e7(a),earlier:i&&o!==void 0?[new PG({attemptId:t,before:o.sequence})]:[]}});D(`Operator.readTranscript`)(function*(e,t,n){yield*E({runId:t.run.id,request:n._tag});let r=yield*wk(n,{ColdTranscriptRequest:()=>Ah(t.attempts,t=>t7(e,t.id,v()),{concurrency:4}).pipe(Qh(e=>({events:e.flatMap(({events:e})=>e).sort((e,t)=>e.sequence-t.sequence),earlier:e.flatMap(({earlier:e})=>e)}))),TailTranscriptRequest:({after:n})=>Ah(t.attempts,t=>e.transcript(new kG({attemptId:t.id,after:n,limit:W5})),{concurrency:4}).pipe(Qh(e=>({events:e7(e.flat()).slice(0,W5),earlier:[]}))),EarlierTranscriptRequest:({attemptId:n,before:r})=>t.attempts.some(e=>e.id===n)?t7(e,n,y(r)):new RG({runId:t.run.id,attemptId:n})});return yield*k(`Read operator transcript`,{runId:t.run.id,request:n._tag,events:r.events.length,earlier:r.earlier.length}),r});var n7=class extends B(`@usine/orchestrator/TaskItemView`)({...Iq.fields,labels:M(hA),conflicting:sT}){},r7=class extends B(`@usine/orchestrator/TaskLaneView`)({id:Pq,name:vW}){},i7=class extends B(`@usine/orchestrator/TaskCommentView`)({runId:yN,kind:CN,url:A,postedAt:F(A),attemptEndedAt:F(A)}){},a7=class extends B(`@usine/orchestrator/TaskView`)({repository:H,number:fI,title:A,current:dI,lane:r7,needsYou:sT,items:_T(n7),runs:M(Oq),comments:M(i7)}){},o7=_r({onNone:()=>null,onSome:G_}),s7=e=>{let t=(t,n)=>new i7({runId:e.run.id,kind:t.kind,url:t.url.toString(),postedAt:o7(t.at),attemptEndedAt:o7(n)}),n=ra(e.attempts,e=>Fr(e.outcome,({_tag:e})=>e===`Succeeded`)).pipe(Or(({endedAt:e})=>e)),r=_r(e.step.result,{onNone:()=>[],onSome:({facts:e})=>e.flatMap(e=>e._tag===`Comment`?[t(e,n)]:[])}),i=e.attempts.flatMap(e=>e.comments.map(n=>t(n,e.endedAt))),a=({postedAt:e,attemptEndedAt:t})=>e??t??``;return _a([...r,...i].sort((e,t)=>a(t).localeCompare(a(e))),(e,t)=>e.url===t.url)},c7=w(function*(){let e=yield*uq,t=yield*D5,n=yield*X0,r=yield*W0,i=yield*jz,a=yield*i0;return{read:D(`TaskReader.read`)(function*(o,s,c){yield*E({repository:s,item:c});let l=SX(o.config).find(({name:e})=>Yk(e)===Yk(s));if(l===void 0)return yield*O(`Task read refused; the repository is not a registered Project`,{repository:s,item:c}),yield*new Kq({repository:s});let[u,d,f,p,m]=yield*kh([e.list({closedLimit:0}).pipe(T(e=>k5(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*X5(e,h),_=new Set(f.filter(e=>e.paused).map(e=>e.loop)),ee=J5(o.config.workers),te=lG(m),ne=(yield*H5(l,_r(d,{onNone:()=>[],onSome:({labels:e})=>e.map(({name:e})=>e)}),u,h.map(e=>Z5(e,_,ee,te)),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(ne===void 0)return yield*O(`Task read found no task in the selected board items`,{repository:l.name,item:c,selectedItems:u.length}),yield*new qq({repository:l.name,item:c});let{lane:re,task:ie}=ne,ae=new Set(ie.items.map(({itemKey:e})=>e)),oe=yield*Ah(u.filter(({itemKey:e})=>ae.has(e)),e=>J2(e).pipe(Yh)),se=new Map;for(let e of oe){if(Ei(e)){yield*Zg(`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;se.set(t,new n7({itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:c}))}let[ce,...le]=ie.items.flatMap(({itemKey:e})=>{let t=se.get(e);return t===void 0?[]:[t]});if(ce===void 0)return yield*new qq({repository:l.name,item:c});let ue=new Set(ie.runs.map(({id:e})=>e)),de=h.filter(({run:e})=>ue.has(e.id)).sort((e,t)=>H_(t.run.openedAt)-H_(e.run.openedAt)||t.run.id.localeCompare(e.run.id)).flatMap(s7),fe=new a7({repository:l.name,number:ce.number,title:ie.title,current:ie.itemKey,lane:new r7({id:re.id,name:re.name}),needsYou:ie.needsYou,items:[ce,...le],runs:[...ie.runs].reverse(),comments:de});return yield*k(`Read a Task`,{repository:l.name,item:c,origin:fe.number,lane:re.name,items:fe.items.length,runs:fe.runs.length,comments:de.length}),fe})}});(class e extends Lr()(`@usine/orchestrator/TaskReader`){static layer=qf(e,c7)});var l7=class extends B(`@usine/orchestrator/LoopSelectorView`)({repos:F(M(H)),tags:F(M(SJ))}){},u7=class extends B(`@usine/orchestrator/LoopFileView`)({name:uA,file:cJ,stream:XY,condition:nJ,cron:F(WY),timeZone:F(GY),selector:F(l7),repositories:M(H),approval:fA,maxCycles:pI,permissions:mA,priority:F(tX),step:DN,agent:aA,prompt:$Y,paused:sT,undeclaredLabels:M(hA)}){},d7=class extends B(`@usine/orchestrator/QuarantinedLoopView`)({name:R,file:cJ,error:dJ}){},f7=class extends B(`@usine/orchestrator/AgentFileView`)({name:aA,file:cJ,harness:nA,model:tA,effort:rA,parentModel:F(tA),parentEffort:F(rA),resolvedParentModel:F(tA),resolvedParentEffort:rA,persona:oA,loops:M(uA)}){},p7=class extends B(`@usine/orchestrator/InvalidAgentView`)({name:R,file:cJ,error:dJ}){},m7=class extends B(`@usine/orchestrator/GatewayView`)({domain:RN,destination:PN,adminPort:zN,adminTokenEnv:R,llmProviders:M(BN)}){},h7=class extends B(`@usine/orchestrator/WorkerSlotsView`)({capacity:L,leased:L}){},g7=class extends V(`@usine/orchestrator/PassedCheckView`)(`Passed`,{checkedAt:A}){},_7=class extends V(`@usine/orchestrator/DegradedCheckView`)(`Degraded`,{checkedAt:A,message:A}){},v7=class extends V(`@usine/orchestrator/DeferredCheckView`)(`Deferred`,{checkedAt:A,message:A}){},y7=class extends V(`@usine/orchestrator/FailedCheckView`)(`Failed`,{checkedAt:A,capability:F(ZW),message:A}){},b7=N([g7,_7,v7,y7]),x7=class extends B(`@usine/orchestrator/HarnessPreflightView`)({harness:nA,check:b7}){},S7=class extends B(`@usine/orchestrator/ContainerView`)({image:F(HN),cpus:F(WN),memoryMib:F(GN),pids:F(KN)}){},C7=class extends B(`@usine/orchestrator/WorkerConfigurationView`)({name:kN,kind:AN,maxConcurrentAttempts:L,destination:F(PN),port:F(FN),identityFile:F(IN),root:F(LN),gateway:F(m7),container:F(S7),containerLimits:F(qN).pipe(CT(C(null))),provisioner:F(mG).pipe(CT(C(null))),machines:M(uG).pipe(CT(C([]))),provisioning:F(dG).pipe(CT(C(null))),slots:F(h7),prerequisites:F(b7),harnesses:M(x7)}){},w7=class extends B(`@usine/orchestrator/RemovedWorkerView`)({name:kN,running:L}){},T7=class extends B(`@usine/orchestrator/LabelStateView`)({name:hA,onGitHub:F(sT),color:F(A),description:F(A),declared:sT,failure:F(fW)}){},E7=class extends V(`@usine/orchestrator/LabelLaneSourceView`)(`Label`,{label:T7}){},D7=class extends V(`@usine/orchestrator/StateLaneSourceView`)(`State`,{state:yW}){},O7=N([E7,D7]),k7=class extends B(`@usine/orchestrator/LaneConfigurationView`)({name:vW,sources:M(O7)}){},A7=class extends B(`@usine/orchestrator/RepositoryConfigurationView`)({name:H,tags:M(SJ),lanes:M(k7),declaredLabels:M(T7),loops:M(uA)}){},j7=class extends B(`@usine/orchestrator/SettingsView`)({pollInterval:L,maxChildren:L,maxAttemptMinutes:F(L),maxAttemptTokens:F(L),parentModel:F(tA),parentEffort:F(rA),operator:F(NM),webhooks:P([`off`,`deliveries`,`endpoint`]),webhooksPublicUrl:F(A),lastHintAt:F(A),tracing:F(j({otlpUrl:A,serviceName:A}))}){},M7=class extends B(`@usine/orchestrator/ConfigurationView`)({projects:M(xJ).pipe(TT(C([])),CT(C([]))),labels:M(yA),loops:M(u7),quarantinedLoops:M(d7),agents:M(f7),invalidAgents:M(p7),workers:M(C7),removedWorkers:M(w7),repositories:M(A7),settings:j7}){},N7=e=>{let t=e.slice(e.lastIndexOf(`/`)+1).replace(/\.md$/u,``);return t===``?e:t},P7=e=>wk(e,{Passed:({checkedAt:e})=>new g7({checkedAt:G_(e)}),Degraded:({checkedAt:e,message:t})=>new _7({checkedAt:G_(e),message:t}),Deferred:({checkedAt:e,message:t})=>new v7({checkedAt:G_(e),message:t}),Failed:({checkedAt:e,capability:t,message:n})=>new y7({checkedAt:G_(e),capability:S(t),message:n})}),F7=e=>e.kind===`ssh`?{destination:S(e.destination),provisioner:_G(e),port:S(e.port),identityFile:S(e.identityFile),root:e.root,gateway:_r(e.gateway,{onNone:()=>null,onSome:e=>new m7({domain:e.domain,destination:e.destination,adminPort:e.adminPort,adminTokenEnv:e.adminTokenEnv,llmProviders:e.llmProviders})}),container:new S7({image:S(e.container.image),cpus:S(e.container.cpus),memoryMib:S(e.container.memoryMib),pids:S(e.container.pids)})}:{destination:null,provisioner:null,port:null,identityFile:null,root:null,gateway:null,container:null},I7=w(function*(){let e=yield*X0,t=yield*jz,n=yield*A4,r=yield*D5,i=D(`OperatorConfiguration.repository`)(function*(e,n,r){let i=Dr(yield*t.get(n.name),({labels:e})=>new Map(e.map(e=>[gA(e.name),e]))),a=new Map(e.config.labels.map(e=>[gA(e.name),e])),o=e=>{let t=gA(e),o=Or(i,e=>xr(e.get(t))),s=a.get(t);return new T7({name:e,onGitHub:_r(i,{onNone:()=>null,onSome:()=>x(o)}),color:S(yr(Or(o,({color:e})=>e),()=>Or(xr(s),({color:e})=>e))),description:S(yr(Or(o,({description:e})=>e),()=>Or(xr(s),({description:e})=>e))),declared:s!==void 0,failure:r.find(e=>e.repository===n.name&&gA(e.label)===t)??null})};return new A7({name:n.name,tags:n.tags,lanes:(SX(e.config).find(({name:e})=>e===n.name)?.lanes??[]).map(e=>new k7({name:e.name,sources:e.sources.map(e=>`label`in e?new E7({label:o(e.label)}):new D7({state:e.state}))})),declaredLabels:e.config.labels.map(({name:e})=>o(e)),loops:e.loops.filter(t=>xX(e.config,t,n)).map(({name:e})=>e)})});return{view:D(`OperatorConfiguration.view`)(function*(t){let{config:a}=t,[o,s,c,l,u,d]=yield*kh([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=_r(s,{onNone:()=>[],onSome:({preflightFindings:e})=>e}),m=yield*Ah(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 u7({name:e.name,file:iX(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:_r(e.selector,{onNone:()=>null,onSome:({repos:e,tags:t})=>new l7({repos:S(e),tags:S(t)})}),repositories:a.repos.filter(n=>xX(t.config,e,n)).map(({name:e})=>e),approval:e.approval,maxCycles:e.maxCycles,permissions:e.permissions,priority:S(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 f7({name:e.name,file:cJ.make(`agents/${e.name}.md`),harness:e.harness,model:e.model,effort:e.effort,parentModel:S(e.parentModel),parentEffort:S(e.parentEffort),resolvedParentModel:S(cA(e.agent,a.settings.parentModel)),resolvedParentEffort:lA(e.agent,a.settings.parentEffort),persona:e.persona,loops:t.loops.filter(({agent:t})=>t===e.name).map(({name:e})=>e)})),ee=new Map(c.map(e=>[e.worker,e])),te=new Map(l.map(e=>[e.worker,e])),ne=new Set(a.workers.map(({name:e})=>e)),re=a.workers.map(e=>{let t=ee.get(e.name),n=te.get(e.name);return new C7({name:e.name,kind:e.kind,maxConcurrentAttempts:e.maxConcurrentAttempts,...F7(e),slots:t===void 0?null:new h7({capacity:t.capacity,leased:t.leased}),prerequisites:n===void 0?null:S(Dr(n.prerequisites,P7)),harnesses:(n?.harnesses??[]).map(({harness:e,check:t})=>new x7({harness:e,check:P7(t)})),containerLimits:n===void 0?null:S(n.containerLimits),machines:u.filter(t=>t.worker===e.name).map(hG),provisioning:S(Dr(xr(d.find(t=>t.worker===e.name)),gG))})}),{settings:ie,webhooks:ae,tracing:oe}=a,se=new M7({projects:a.projects,labels:t.config.labels,loops:g,quarantinedLoops:t.quarantinedLoops.map(({file:e,error:t})=>new d7({name:N7(e),file:e,error:t})),agents:_,invalidAgents:t.invalidAgents.map(({file:e,error:t})=>new p7({name:N7(e),file:e,error:t})),workers:re,removedWorkers:c.filter(({worker:e,leased:t})=>!ne.has(e)&&t>0).map(({worker:e,leased:t})=>new w7({name:e,running:t})),repositories:m,settings:new j7({pollInterval:ie.pollInterval,maxChildren:ie.maxChildren,maxAttemptMinutes:S(ie.maxAttemptMinutes),maxAttemptTokens:S(ie.maxAttemptTokens),parentModel:S(ie.parentModel),parentEffort:S(ie.parentEffort),operator:S(a.operator),webhooks:ae.mode,lastHintAt:S(Dr(yield*n.lastHint,G_)),webhooksPublicUrl:ae.mode===`endpoint`?ae.publicUrl.href:null,tracing:_r(oe,{onNone:()=>null,onSome:({otlpUrl:e,serviceName:t})=>({otlpUrl:e.href,serviceName:t})})})});return yield*k(`Read the configuration view`,{loops:g.length,quarantinedLoops:se.quarantinedLoops.length,agents:_.length,invalidAgents:se.invalidAgents.length,workers:re.length,runningWorkers:c.length,repositories:m.length}),se})}});(class e extends Lr()(`@usine/orchestrator/OperatorConfiguration`){static layer=qf(e,I7)});var L7=class e extends Lr()(`@usine/orchestrator/LoopMatches`){static layer=qf(e,w(function*(){let e=yield*sJ;return{matching:D(`LoopMatches.matching`)(function*(e,t,n){yield*E({repository:t.name,items:n.length});let r=e.loops.filter(n=>n.trigger.on!==`schedule`&&xX(e.config,n,t)),i=n.filter(({goneAt:e})=>b(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*Yh(c4(e,t,n.map(({payload:e})=>e)));if(Ei(r)){o+=n.length,yield*k(`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 aa(n,r.success))Di(a)?a.success&&s.add(i):(o+=1,yield*k(`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*k(`Matched Loop triggers against stored Items`,{repository:t.name,loops:r.length,items:n.length,matches:s.length,failures:o}),s},Tg(sJ,e))}}))},R7=200,z7=10,B7=100,V7=500,H7=class extends V(`@usine/orchestrator/WorkerSilentView`)(`WorkerSilent`,{worker:kN,lastAnsweredAt:A}){},U7=class extends V(`@usine/orchestrator/ProviderRetryingView`)(`ProviderRetrying`,{agent:aA,message:R,retries:zP,since:A}){},W7=N([H7,U7]),G7=class extends B(`@usine/orchestrator/RunningAttemptView`)({run:Oq,attempt:KW,item:F(Iq),lastActivityAt:F(A),warnings:M(W7)}){},K7=class extends V(`@usine/orchestrator/SuppressedForOperatorView`)(`SuppressedForOperator`,{run:Oq}){},q7=class extends V(`@usine/orchestrator/ClosedUnchangedView`)(`ClosedUnchanged`,{run:Oq}){},J7=class extends V(`@usine/orchestrator/RunFailedView`)(`RunFailed`,{run:Oq}){},Y7=class extends V(`@usine/orchestrator/LoopPausedView`)(`LoopPaused`,{}){},X7=class extends V(`@usine/orchestrator/CycleBudgetUsedUpView`)(`CycleBudgetUsedUp`,{ask:yI}){},Z7=class extends V(`@usine/orchestrator/AwaitingApprovalView`)(`AwaitingApproval`,{run:Oq}){},Q7=class extends V(`@usine/orchestrator/QueuedForWorkerView`)(`QueuedForWorker`,{run:Oq,ahead:F(L.check(BT(0))),priority:F(eX).pipe(CT(C(null))),creating:F(uG).pipe(CT(C(null)))}){},$7=class extends V(`@usine/orchestrator/WaitingForStopView`)(`WaitingForStop`,{run:Oq,stop:Mq}){},e9=class extends V(`@usine/orchestrator/AwaitingPollView`)(`AwaitingPoll`,{}){},t9=N([Z7,K7,X7,J7,q7,Y7,$7,Q7,e9]),n9=class extends B(`@usine/orchestrator/StalledItemView`)({repository:H,loop:uA,item:Iq,reason:t9}){},r9=class extends B(`@usine/orchestrator/ClosedRunView`)({run:Oq,item:F(Iq),closedAt:A}){},i9=class extends B(`@usine/orchestrator/WorkerView`)({name:kN,slots:h7,preflight:F(b7),machines:M(uG).pipe(CT(C([]))),provisioning:F(dG).pipe(CT(C(null)))}){},a9=class extends B(`@usine/orchestrator/RepositoryPollView`)({repository:H,polledAt:F(A)}){},o9=class extends B(`@usine/orchestrator/DeskView`)({running:M(G7),notMoving:M(n9),lastOutcomes:M(r9),workers:M(i9),polls:M(a9)}){},s9=({runs:e,sighting:t,paused:n,ask:r,queue:i,creating:a,stop:o})=>{let s=e.find(({state:e})=>sN.some(t=>t===e));if(s!==void 0){let e=s.attempts.at(-1)?.outcome===null;if(x(o)&&s.state!==`Waiting`&&!e)return y(new $7({run:s,stop:o.value}));switch(s.state){case`Running`:return v();case`Waiting`:return y(new Z7({run:s}));default:return y(new Q7({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 y(new Y7);let c=t=>xr(e.find(({id:e})=>e===t)),l=Or(Or(t,({suppressedBy:e})=>e),c);if(x(l))return y(new K7({run:l.value}));if(x(r))return y(new X7({ask:r.value}));let u=Or(Or(t,({run:e})=>e),c);return x(u)?y(u.value.state===`Failed`?new J7({run:u.value}):new q7({run:u.value})):y(new e9)},c9=[`AwaitingApproval`,`SuppressedForOperator`,`CycleBudgetUsedUp`,`RunFailed`,`ClosedUnchanged`,`LoopPaused`,`WaitingForStop`,`QueuedForWorker`,`AwaitingPoll`],l9=ur([dr(cr,({reason:e})=>c9.indexOf(e._tag)),dr(sr,({repository:e})=>e),dr(lr(cr),({item:e})=>e.number),dr(sr,({loop:e})=>e)]),u9=({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`)},d9=e=>{let t=null,n=new Map,r=null;for(let i of e){u9(i)&&(r=i);let e=i.envelope.payload;if(e._tag===`WorkerUnresponsive`)t=new H7({worker:e.worker,lastAnsweredAt:G_(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 U7({agent:t.session.agent,message:t.message,retries:t.retries,since:n.get(t.session.id)?.since??G_(i.receivedAt)})):(t._tag===`ProviderRecovered`||t._tag===`SessionIdle`||t._tag===`SessionFinished`)&&n.delete(t.session.id)}}return{lastActivityAt:r===null?null:G_(r.receivedAt),warnings:[...t===null?[]:[t],...n.values()]}},f9=e=>H_(e.checkedAt),p9=e=>{let t=[...jr(e.prerequisites),...e.harnesses.map(({check:e})=>e)],n=t.filter(({_tag:e})=>e===`Failed`),r=t.filter(({_tag:e})=>e===`Degraded`);return xr((n.length>0?n:r.length>0?r:t).reduce((e,t)=>e===void 0||f9(t)>f9(e)?t:e,void 0))},m9=e=>{let t=e.attempts.at(-1);return e.closedAt??t?.endedAt??t?.startedAt??e.openedAt},h9=({run:e,attempts:t})=>t.length===0&&e.state._tag===`Canceled`&&e.state.reason._tag!==`OperatorCanceled`,g9=w(function*(){let e=yield*uq,t=yield*X0,n=yield*i0,r=yield*W0,i=yield*A4,a=yield*L7,o=yield*D5,s=yield*d2,c=D(`Operator.desk.recentActivity`)(function*(t){yield*E({attemptId:t.id});let[n,r]=yield*kh([e.transcript(new AG({attemptId:t.id,before:v(),limit:R7})),e.transcript(new DG({attemptId:t.id}))],{concurrency:`unbounded`});return d9([...n,...r])});return{desk:D(`Operator.desk`)(function*(l){let[u,d,f,p,m,h,g,_,ee,te,ne]=yield*kh([e.list({closedLimit:0}),e.closed({limit:B7}),t.states,n.asks(),o.slots,o.queue,o.preflights,i.latest,s.list,o.machines,o.provisioning],{concurrency:`unbounded`}),re=lG(ne),ie=te.map(hG),ae=new Map(ie.flatMap(e=>e.state===`creating`&&e.runId!==null?[[e.runId,e]]:[])),oe=new Map(h.map(e=>[e.runId,e])),se=new Set(f.filter(e=>e.paused).map(e=>e.loop)),ce=J5(l.config.workers),le=yield*Ah(l.config.repos,e=>w(function*(){let t=yield*r.list(e.name,{limit:V7});return{repository:e,items:t,matches:yield*a.matching(l,e,t)}}),{concurrency:4}),ue=new Map;for(let{items:e}of le)for(let t of e){let e=yield*Yh(J2(t));if(Ei(e))continue;let{itemKey:n,kind:r,number:i,title:a,url:o,state:s}=e.success;ue.set(n,new Iq({itemKey:n,kind:r,number:i,title:a,url:o,state:s}))}let de=le.flatMap(({matches:e})=>e),fe=[...new Set(de.map(({item:e})=>e.itemKey))],[pe,me]=yield*kh([e.forItems(fe),e.sightings(fe)],{concurrency:`unbounded`}),he=new Map([...u,...pe].map(e=>[e.run.id,Z5(e,se,ce,re)])),ge=[...he.values()].sort((e,t)=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),_e=e=>Or(xr(ee.find(t=>t.itemKey===e)),e=>Dr(xr(he.get(e.runId)?.attempts.find(({id:t})=>t===e.attemptId)),({number:t})=>new Mq({runId:e.runId,attemptNumber:t,worker:e.worker}))),ve=[];for(let{loop:e,item:t}of de){let n=ue.get(t.itemKey);if(n===void 0)continue;let r=s9({runs:ge.filter(n=>n.loop===e.name&&n.itemKey===t.itemKey),sighting:xr(me.find(n=>n.loop===e.name&&n.itemKey===t.itemKey)),paused:se.has(e.name),ask:xr(p.find(({itemKey:e})=>e===t.itemKey)),queue:oe,creating:ae,stop:_e(t.itemKey)});b(r)||(yield*k(`Matched Item is not moving`,{repository:t.repository,loop:e.name,item:t.number,reason:r.value._tag,...wk(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:()=>({})})}),ve.push(new n9({repository:t.repository,loop:e.name,item:n,reason:r.value})))}let ye=yield*Ah(ge.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})=>Qh(c(t),n=>new G7({run:e,attempt:t,item:ue.get(e.itemKey)??null,...n})),{concurrency:4}),be=d.filter(e=>!h9(e)).map(e=>{let t=Z5(e,se,ce,re);return new r9({run:t,item:ue.get(t.itemKey)??null,closedAt:m9(t)})}).sort((e,t)=>t.closedAt.localeCompare(e.closedAt)).slice(0,z7),xe=new Map(m.map(e=>[e.worker,e])),Se=new Map(g.map(e=>[e.worker,e])),Ce=new Set(l.config.workers.map(({name:e})=>e)),we=[...l.config.workers.map(({name:e})=>e),...m.map(({worker:e})=>e).filter(e=>!Ce.has(e))].map(e=>{let t=xe.get(e),n=Se.get(e);return new i9({name:e,slots:new h7({capacity:t?.capacity??l.config.workers.find(t=>t.name===e)?.maxConcurrentAttempts??0,leased:t?.leased??0}),preflight:S(Dr(Or(xr(n),p9),P7)),machines:ie.filter(t=>t.worker===e),provisioning:S(Dr(xr(ne.find(t=>t.worker===e)),gG))})}),Te=_r(_,{onNone:()=>[],onSome:({repositoryPolls:e})=>e}),Ee=l.config.repos.map(({name:e})=>{let t=Te.find(({repository:t})=>Yk(t)===Yk(e));return new a9({repository:e,polledAt:t===void 0?null:G_(t.completedAt)})});return yield*k(`Built the operator desk`,{running:ye.length,matches:de.length,notMoving:ve.length,lastOutcomes:be.length,workers:we.length}),new o9({running:ye,notMoving:[...ve].sort(l9),lastOutcomes:be,workers:we,polls:Ee})})}});(class e extends Lr()(`@usine/orchestrator/OperatorDesk`){static layer=qf(e,g9).pipe(ep(L7.layer))});var _9=L.check(BT(0)),v9=L.check(BT(1)),y9=L.check(BT(0)),b9=NT.check(VT({minimum:0,maximum:1})),x9=A.check(MT(/^\d{4}-\d{2}-\d{2}$/u,{message:`Expected a UTC day as YYYY-MM-DD`})),S9=P([`7d`,`30d`,`all`]),C9=P([`day`,`week`]),w9=class extends B(`@usine/orchestrator/TaskDoneView`)({repository:H,number:fI,mergedAt:A,durationMillis:y9}){},T9=class extends B(`@usine/orchestrator/TaskPeriodView`)({start:x9,tasks:_9,medianMillis:F(y9),firstTimeRight:_9,operatorActions:_9}){},E9=class extends B(`@usine/orchestrator/LoopShareView`)({loop:uA,share:b9}){},D9=class extends B(`@usine/orchestrator/LoopRunTimeView`)({loop:uA,runs:v9,medianMillis:y9}){},O9=class extends B(`@usine/orchestrator/TaskTimeView`)({tasks:v9,loops:M(E9),waiting:b9,runs:M(D9)}){},k9=class extends B(`@usine/orchestrator/TaskCostView`)({tasks:v9,medianUsd:OP,estimate:sT}){},A9=class extends B(`@usine/orchestrator/TaskTokensView`)({tasks:v9,medianTokens:mP,loops:M(E9),cost:F(k9)}){},j9=class extends B(`@usine/orchestrator/UntimedTasksView`)({tasks:v9,before:x9}){},M9=class extends B(`@usine/orchestrator/StatisticsView`)({window:S9,from:A,to:A,bucket:C9,loops:M(uA),tasks:M(w9),medianMillis:F(y9),periods:M(T9),firstTimeRight:_9,operatorActions:_9,time:F(O9),tokens:F(A9),untimed:F(j9),unmetered:_9}){},N9=class extends B(`@usine/orchestrator/DurationSummaryView`)({count:v9,medianMillis:y9}){},P9=class extends B(`@usine/orchestrator/OutcomeCountsView`)({succeeded:_9,failed:_9,canceled:_9}){},F9=class extends B(`@usine/orchestrator/PoolTokensView`)({pool:MP,tokens:mP}){},I9=class extends B(`@usine/orchestrator/CostSummaryView`)({usd:OP,meanUsd:OP,estimate:sT,priced:v9}){},vee=class extends B(`@usine/orchestrator/UsageSummaryView`)({measured:_9,tokens:mP,meanTokens:F(mP),pools:M(F9),cost:F(I9)}){},L9={outcomes:P9,time:F(N9),usage:vee},yee=class extends B(`@usine/orchestrator/LoopStatisticsView`)({loop:uA,...L9}){},bee=class extends B(`@usine/orchestrator/AgentStatisticsView`)({agent:aA,...L9}){},xee=class extends B(`@usine/orchestrator/BrainStatisticsView`)({brain:iA,...L9}){},See=class extends B(`@usine/orchestrator/ThroughputPeriodView`)({start:x9,...P9.fields}){},Cee=class extends B(`@usine/orchestrator/WorkerQueueWaitView`)({worker:kN,wait:N9}){},wee=class extends B(`@usine/orchestrator/AttemptCountView`)({attempts:v9,runs:_9}){},Tee=class extends B(`@usine/orchestrator/WorkerUtilizationView`)({worker:kN,slots:v9,occupiedMillis:y9,share:b9}){},Eee=class extends B(`@usine/orchestrator/NeedsAttentionPeriodView`)({start:x9,approvals:_9,failures:_9}){},Dee=class extends B(`@usine/orchestrator/NeedsAttentionView`)({approvals:_9,failures:_9,periods:M(Eee),approvalWait:F(N9),retryWait:F(N9),resolutionWait:F(N9),failureWait:F(N9)}){},Oee=class extends B(`@usine/orchestrator/RunStatisticsView`)({window:S9,from:A,to:A,bucket:C9,runs:P9,runTime:F(N9),attemptTime:F(N9),unmeasuredAttempts:_9,throughput:M(See),loops:M(yee),agents:M(bee),brains:M(xee),queueWait:M(Cee),attemptsPerRun:M(wee),utilization:M(Tee),needsAttention:Dee}){},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 AE(`@usine/orchestrator/OperatorHttpError`)({error:P(Bi(R9)),message:A}){get status(){return R9[this.error]}},kee=[...new Set(Object.values(R9))].map(e=>z9.check(jT(t=>t.status===e)).annotate({httpApiStatus:e})),Aee=class extends e8()(`@usine/orchestrator/OperatorHttpPolicy`,{error:kee}){},jee=N([OT(`WorkerCapabilityError`,{worker:kN,capability:ZW,message:A}),OT(`ExecutorOperationError`,{operation:XW,message:A}),OT(`CredentialUnavailableError`,{repository:H,message:A})]),Mee=class extends AE(`@usine/orchestrator/RestartRequiredRefusal`)({error:tT(`RestartRequiredError`),message:A,blocks:_T(U8),fields:_T(R)},{httpApiStatus:409}){},Nee=class extends AE(`@usine/orchestrator/ReloadPreflightRefusal`)({error:tT(`ReloadPreflightError`),message:A,agents:M(aA),workers:M(kN),cause:jee},{httpApiStatus:409}){},Pee=class extends AE(`@usine/orchestrator/FactoryConfigRefusal`)({error:tT(`FactoryConfigError`),message:A,file:cJ,stage:lJ},{httpApiStatus:422}){},B9=class extends AE(`StaleRevisionRefusal`)({error:tT(`StaleRevision`),message:A,expected:mX,current:mX},{httpApiStatus:409}){},V9=class extends AE(`ConfigurationInvalidRefusal`)({error:tT(`ConfigurationInvalid`),message:A,problems:_T(j({entity:_X,...uJ.fields}))},{httpApiStatus:422}){},H9=class extends AE(`ConfigurationRevertRefusal`)({error:tT(`ConfigurationRevertBlocked`),message:A,entities:_T(_X)},{httpApiStatus:409}){},U9=[B9,V9,H9,Mee,Nee,Pee],W9={number:aE.pipe(bT(mX))},G9=y3.fields,K9=Zw(nT),q9=N([A,_T(A).pipe(bT(A,Cb({decode:e=>e[0],encode:e=>[e]})))]),J9=q9.pipe(bT(aE),bT(vG)),Fee=N([j({after:K9,before:K9,attempt:K9}).pipe(bT($w(FG),Cb({decode:()=>new FG,encode:()=>({})}))),j({after:J9,before:K9,attempt:K9}).pipe(bT($w(IG),Cb({decode:({after:e})=>new IG({after:e}),encode:({after:e})=>({after:e})}))),j({after:K9,before:J9,attempt:q9.pipe(bT(pF))}).pipe(bT($w(LG),Cb({decode:({before:e,attempt:t})=>new LG({before:e,attemptId:t}),encode:({before:e,attemptId:t})=>({before:e,attempt:t})})))]),Y9=A.check(MT(/^[A-Za-z0-9_.-]+$/u,{message:`Expected a repository path segment`})),X9=j({ok:tT(!0)}),Z9={runId:yN},Q9={loop:uA},$9=j({window:q9.pipe(bT(S9),TT(C(`30d`)))}),Iee=V6(`OperatorApi`).add(H8(`operator`).add(N6(`upgradeStatus`,`/api/upgrade`,{success:O3}),N6(`serverVersion`,`/api/version`,{success:A}),P6(`requestUpgrade`,`/api/upgrade`,{payload:D3,success:X9}),N6(`overview`,`/api/overview`,{success:p3}),P6(`dismissNeed`,`/api/attention/dismiss`,{payload:IM,success:X9}),P6(`undoDismissNeed`,`/api/attention/undo`,{payload:IM,success:X9}),N6(`agents`,`/api/agents`,{success:M(aA)}),P6(`editAndRetry`,`/api/runs/:runId/edit-and-retry`,{params:Z9,payload:Tq,success:X9}),P6(`runAgain`,`/api/runs/:runId/run-again`,{params:Z9,payload:Tq,success:o0}),P6(`intervene`,`/api/runs/:runId/intervene`,{params:Z9,payload:Eq,success:X9}),P6(`resetCycleBudget`,`/api/cycle-budgets/reset`,{payload:j({askId:vI}),success:X9}),N6(`detail`,`/api/runs/:runId`,{params:Z9,query:Fee,success:Nq}),N6(`githubChanges`,`/api/runs/:runId/github-changes`,{params:Z9,success:p5}),P6(`approve`,`/api/runs/:runId/approve`,{params:Z9,success:X9}),P6(`resolveFailure`,`/api/runs/:runId/resolve-failure`,{params:Z9,payload:j({attemptId:pF}),success:X9}),P6(`retry`,`/api/runs/:runId/retry`,{params:Z9,success:X9}),P6(`cancel`,`/api/runs/:runId/cancel`,{params:Z9,success:X9}),N6(`project`,`/api/projects/:project`,{params:{project:Xk},success:l3}),N6(`projectTask`,`/api/projects/:project/tasks/:item`,{params:{project:Xk,item:aE.pipe(bT(fI))},query:j({repository:H}),success:a7}),P6(`moveProjectItem`,`/api/projects/:project/items/:item/lane`,{params:{project:Xk,item:aE.pipe(bT(fI))},payload:j({repository:H,toLane:Pq}),success:X9}),P6(`pauseProjectLoop`,`/api/loops/:project/:loop/pause`,{params:{project:Xk,loop:uA},success:X9}),P6(`unpauseProjectLoop`,`/api/loops/:project/:loop/unpause`,{params:{project:Xk,loop:uA},success:X9}),P6(`moveBoardItem`,`/api/projects/:owner/:repository/items/:item/lane`,{params:{owner:Y9,repository:Y9,item:aE.pipe(bT(fI))},payload:j({toLane:Pq}),success:X9}),P6(`discardLeftovers`,`/api/workers/:worker/discard-leftovers`,{params:{worker:kN},success:X9}),P6(`pause`,`/api/loops/:loop/pause`,{params:Q9,success:X9}),P6(`unpause`,`/api/loops/:loop/unpause`,{params:Q9,success:X9})).add(N6(`task`,`/api/projects/:owner/:repository/tasks/:item`,{params:{owner:Y9,repository:Y9,item:aE.pipe(bT(fI))},success:a7})).add(P6(`checkLoop`,`/api/configuration/loops/check`,{payload:m3,success:h3,error:U9}),P6(`previewLoop`,`/api/configuration/loops/preview`,{payload:g3,success:v3,error:U9}),N6(`configurationCapabilities`,`/api/configuration/capabilities`,{success:j({harnesses:M(nA),efforts:M(rA)})}),N6(`configurationRepositories`,`/api/configuration/repositories`,{success:M(H)}),N6(`configurationLabels`,`/api/configuration/labels/:repository`,{params:{repository:H},success:M($H)}),N6(`configurationRevisions`,`/api/configuration/revisions`,{query:j({kind:Zw(q9),identifier:Zw(q9.pipe(bT(gX))),before:Zw(q9.pipe(bT(aE),bT(mX))),limit:q9.pipe(bT(aE),bT(b3.fields.limit),TT(C(`50`)))}),success:T3,error:U9}),N6(`configurationRevision`,`/api/configuration/revisions/:number`,{params:W9,success:E3,error:U9}),N6(`configurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:G9,success:C3,error:U9}),F6(`replaceConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:G9,payload:S3,success:E3,error:U9}),I6(`deleteConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:G9,payload:x3,success:E3,error:U9}),P6(`revertConfigurationRevision`,`/api/configuration/revisions/:number/revert`,{params:W9,payload:x3,success:E3,error:U9})).add(N6(`configuration`,`/api/configuration`,{success:M7})).add(N6(`desk`,`/api/desk`,{success:o9})).add(N6(`statistics`,`/api/statistics`,{query:$9,success:M9}),N6(`runStatistics`,`/api/statistics/runs`,{query:$9,success:Oee})).annotate(J6,{onExcessProperty:`error`}).middleware(Aee)),Lee=()=>o8(Iee,{baseUrl:globalThis.location.origin,transformClient:e=>e.pipe(nV(e=>xB(e,`x-usine-csrf`,Qk())),rV(e=>Fh(()=>{e.status===401&&window.location.replace(`/sign-in`)})))}),Ree=e=>Kg(T(Lee(),t=>e(t.operator)).pipe(Tg(oV,!1),xg(mV))),zee=e=>e instanceof Error?e.message:String(e);export{GF as $,Lw as $t,tY as A,wr as An,P as At,Vq as B,Vw as Bt,_X as C,Ar as Cn,M as Ct,XY as D,xr as Dn,PE as Dt,nX as E,Or as En,L as Et,pJ as F,v as Fn,j as Ft,FG as G,VT as Gt,Tq as H,Jw as Ht,dJ as I,yr as In,N as It,vG as J,KT as Jt,LG as K,PT as Kt,cJ as L,y as Ln,Hw as Lt,QJ as M,x as Mn,oT as Mt,xJ as N,Dr as Nn,pT as Nt,BY as O,vr as On,FE as Ot,fJ as P,_r as Pn,A as Pt,QF as Q,ME as Qt,Rq as R,jr as Rn,bT as Rt,gX as S,Di as Sn,wk as St,aX as T,Mr as Tn,aE as Tt,Nq as U,rE as Ut,Bq as V,Ww as Vt,Eq as W,Rw as Wt,SW as X,Qw as Xt,yW as Y,UT as Yt,fI as Z,Zw as Zt,H1 as _,Bg as _n,$k as _t,z9 as a,rg as an,YN as at,v1 as b,Bi as bn,Yk as bt,x3 as c,T as cn,sN as ct,l3 as d,sg as dn,hA as dt,G_ as en,qF as et,d3 as f,Yh as fn,pA as ft,A1 as g,Uh as gn,eA as gt,k1 as h,C as hn,rA as ht,H9 as i,$h as in,JN as it,KJ as j,b as jn,F as jt,DJ as k,S as kn,tT as kt,g3 as l,Xg as ln,IM as lt,Q2 as m,qg as mn,aA as mt,zee as n,B_ as nn,JF as nt,B9 as o,ng as on,ZN as ot,s3 as p,Kg as pn,uA as pt,IG as q,BT as qt,V9 as r,H_ as rn,gF as rt,D3 as s,zh as sn,yN as st,Ree as t,V_ as tn,ZF as tt,f3 as u,Qh as un,FM as ut,U1 as v,ha as vn,Xk as vt,bX as w,Fr as wn,sT as wt,vX as x,Ei as xn,Jk as xt,y1 as y,Xi as yn,H as yt,Wq as z,se as zn,zw as zt};
|